{"version":3,"sources":["mod::vue/node_modules/@vue/shared/dist/shared.cjs.prod.js","mod::vue/node_modules/@vue/shared/index.js","/opt/whdata/generated/platform/ap/btw.btwcoach/build/https:/raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/generated/decode-data-html.ts","/opt/whdata/generated/platform/ap/btw.btwcoach/build/https:/raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/generated/decode-data-xml.ts","/opt/whdata/generated/platform/ap/btw.btwcoach/build/https:/raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/decode_codepoint.ts","/opt/whdata/generated/platform/ap/btw.btwcoach/build/https:/raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/decode.ts","mod::vue/node_modules/@babel/parser/src/util/location.ts","mod::vue/node_modules/@babel/parser/src/parse-error/module-errors.ts","mod::vue/node_modules/@babel/parser/src/parse-error/to-node-description.ts","mod::vue/node_modules/@babel/parser/src/parse-error/standard-errors.ts","mod::vue/node_modules/@babel/parser/src/parse-error/strict-mode-errors.ts","mod::vue/node_modules/@babel/parser/src/parse-error/parse-expression-errors.ts","mod::vue/node_modules/@babel/parser/src/parse-error/pipeline-operator-errors.ts","mod::vue/node_modules/@babel/parser/src/parse-error.ts","mod::vue/node_modules/@babel/parser/src/options.ts","mod::vue/node_modules/@babel/parser/src/plugins/estree.ts","mod::vue/node_modules/@babel/parser/src/tokenizer/context.ts","mod::vue/node_modules/@babel/parser/src/tokenizer/types.ts","mod::vue/node_modules/@babel/babel-helper-validator-identifier/src/identifier.ts","mod::vue/node_modules/@babel/babel-helper-validator-identifier/src/keyword.ts","mod::vue/node_modules/@babel/parser/src/util/identifier.ts","mod::vue/node_modules/@babel/parser/src/util/scope.ts","mod::vue/node_modules/@babel/parser/src/plugins/flow/scope.ts","mod::vue/node_modules/@babel/parser/src/plugins/flow/index.ts","mod::vue/node_modules/@babel/parser/src/plugins/jsx/xhtml.ts","mod::vue/node_modules/@babel/parser/src/util/whitespace.ts","mod::vue/node_modules/@babel/parser/src/plugins/jsx/index.ts","mod::vue/node_modules/@babel/parser/src/plugins/typescript/scope.ts","mod::vue/node_modules/@babel/parser/src/util/production-parameter.ts","mod::vue/node_modules/@babel/parser/src/parser/base.ts","mod::vue/node_modules/@babel/parser/src/parser/comments.ts","mod::vue/node_modules/@babel/parser/src/tokenizer/state.ts","mod::vue/node_modules/@babel/babel-helper-string-parser/src/index.ts","mod::vue/node_modules/@babel/parser/src/tokenizer/index.ts","mod::vue/node_modules/@babel/parser/src/util/class-scope.ts","mod::vue/node_modules/@babel/parser/src/util/expression-scope.ts","mod::vue/node_modules/@babel/parser/src/parser/util.ts","mod::vue/node_modules/@babel/parser/src/parser/node.ts","mod::vue/node_modules/@babel/parser/src/parser/lval.ts","mod::vue/node_modules/@babel/parser/src/plugins/typescript/index.ts","mod::vue/node_modules/@babel/parser/src/plugins/placeholders.ts","mod::vue/node_modules/@babel/parser/src/plugins/v8intrinsic.ts","mod::vue/node_modules/@babel/parser/src/plugin-utils.ts","mod::vue/node_modules/@babel/parser/src/parser/expression.ts","mod::vue/node_modules/@babel/parser/src/parser/statement.ts","mod::vue/node_modules/@babel/parser/src/parser/index.ts","mod::vue/node_modules/@babel/parser/src/index.ts","mod::vue/node_modules/estree-walker/dist/umd/estree-walker.js","mod::vue/node_modules/source-map-js/lib/base64.js","mod::vue/node_modules/source-map-js/lib/base64-vlq.js","mod::vue/node_modules/source-map-js/lib/util.js","mod::vue/node_modules/source-map-js/lib/array-set.js","mod::vue/node_modules/source-map-js/lib/mapping-list.js","mod::vue/node_modules/source-map-js/lib/source-map-generator.js","mod::vue/node_modules/source-map-js/lib/binary-search.js","mod::vue/node_modules/source-map-js/lib/quick-sort.js","mod::vue/node_modules/source-map-js/lib/source-map-consumer.js","mod::vue/node_modules/source-map-js/lib/source-node.js","mod::vue/node_modules/source-map-js/source-map.js","mod::vue/node_modules/@vue/compiler-core/dist/compiler-core.cjs.prod.js","mod::vue/node_modules/@vue/compiler-core/index.js","mod::vue/node_modules/@vue/compiler-dom/dist/compiler-dom.cjs.prod.js","mod::vue/node_modules/@vue/compiler-dom/index.js","mod::vue/node_modules/@vue/reactivity/dist/reactivity.cjs.prod.js","mod::vue/node_modules/@vue/reactivity/index.js","mod::vue/node_modules/@vue/runtime-core/dist/runtime-core.cjs.prod.js","mod::vue/node_modules/@vue/runtime-core/index.js","mod::vue/node_modules/@vue/runtime-dom/dist/runtime-dom.cjs.prod.js","mod::vue/node_modules/@vue/runtime-dom/index.js","mod::vue/node_modules/vue/dist/vue.cjs.prod.js","mod::vue/node_modules/vue/index.js","mod::btw/node_modules/extend/index.js","mod::vue/node_modules/reka-ui/dist/rolldown-runtime.cjs","mod::vue/node_modules/ohash/dist/shared/ohash.D__AXeF1.mjs","mod::vue/node_modules/ohash/dist/crypto/js/index.mjs","mod::vue/node_modules/ohash/dist/index.mjs","mod::vue/node_modules/reka-ui/src/shared/arrays.ts","mod::vue/node_modules/reka-ui/src/shared/browser.ts","mod::vue/node_modules/reka-ui/src/shared/clamp.ts","mod::vue/node_modules/reka-ui/src/shared/createContext.ts","mod::vue/node_modules/reka-ui/src/shared/getActiveElement.ts","mod::vue/node_modules/reka-ui/src/shared/handleAndDispatchCustomEvent.ts","mod::vue/node_modules/reka-ui/src/shared/isValidVNodeElement.ts","mod::vue/node_modules/reka-ui/src/shared/nullish.ts","mod::vue/node_modules/reka-ui/src/shared/isValueEqualOrExist.ts","mod::vue/node_modules/reka-ui/src/shared/object.ts","mod::vue/node_modules/@vueuse/shared/dist/index.js","mod::vue/node_modules/@vueuse/core/dist/index.js","mod::vue/node_modules/reka-ui/src/shared/onFocusOutside.ts","mod::vue/node_modules/reka-ui/src/shared/renderSlotFragments.ts","mod::vue/node_modules/reka-ui/src/shared/trap-focus.ts","mod::vue/node_modules/reka-ui/src/shared/useArrowNavigation.ts","mod::vue/node_modules/reka-ui/src/ConfigProvider/ConfigProvider.vue","mod::vue/node_modules/reka-ui/src/ConfigProvider/ConfigProvider.vue","mod::vue/node_modules/defu/dist/defu.cjs","mod::vue/node_modules/defu/lib/defu.cjs","mod::vue/node_modules/reka-ui/src/shared/useBodyScrollLock.ts","mod::vue/node_modules/reka-ui/src/shared/useComposing.ts","mod::vue/node_modules/@internationalized/date/dist/private/packages/@internationalized/date/src/utils.ts","mod::vue/node_modules/@internationalized/date/dist/private/calendars/packages/@internationalized/date/src/calendars/GregorianCalendar.ts","mod::vue/node_modules/@internationalized/date/dist/private/packages/@internationalized/date/src/weekStartData.ts","mod::vue/node_modules/@internationalized/date/dist/private/packages/@internationalized/date/src/queries.ts","mod::vue/node_modules/@internationalized/date/dist/private/packages/@internationalized/date/src/conversion.ts","mod::vue/node_modules/@internationalized/date/dist/private/packages/@internationalized/date/src/manipulation.ts","mod::vue/node_modules/@internationalized/date/dist/private/packages/@internationalized/date/src/string.ts","mod::vue/node_modules/@internationalized/date/dist/private/packages/@internationalized/date/src/CalendarDate.ts","mod::vue/node_modules/@internationalized/date/dist/private/calendars/packages/@internationalized/date/src/calendars/JapaneseCalendar.ts","mod::vue/node_modules/@internationalized/date/dist/private/calendars/packages/@internationalized/date/src/calendars/BuddhistCalendar.ts","mod::vue/node_modules/@internationalized/date/dist/private/calendars/packages/@internationalized/date/src/calendars/TaiwanCalendar.ts","mod::vue/node_modules/@internationalized/date/dist/private/calendars/packages/@internationalized/date/src/calendars/PersianCalendar.ts","mod::vue/node_modules/@internationalized/date/dist/private/calendars/packages/@internationalized/date/src/calendars/IndianCalendar.ts","mod::vue/node_modules/@internationalized/date/dist/private/calendars/packages/@internationalized/date/src/calendars/IslamicCalendar.ts","mod::vue/node_modules/@internationalized/date/dist/private/calendars/packages/@internationalized/date/src/calendars/HebrewCalendar.ts","mod::vue/node_modules/@internationalized/date/dist/private/calendars/packages/@internationalized/date/src/calendars/EthiopicCalendar.ts","mod::vue/node_modules/@internationalized/date/dist/private/packages/@internationalized/date/src/createCalendar.ts","mod::vue/node_modules/@internationalized/date/dist/private/packages/@internationalized/date/src/DateFormatter.ts","mod::vue/node_modules/reka-ui/src/date/comparators.ts","mod::vue/node_modules/reka-ui/src/shared/date/comparators.ts","mod::vue/node_modules/reka-ui/src/date/utils.ts","mod::vue/node_modules/reka-ui/src/shared/date/utils.ts","mod::vue/node_modules/reka-ui/src/date/calendar.ts","mod::vue/node_modules/reka-ui/dist/date/index.cjs","mod::vue/node_modules/reka-ui/src/shared/useDateFormatter.ts","mod::vue/node_modules/reka-ui/src/shared/useDirection.ts","mod::vue/node_modules/reka-ui/src/shared/useEmitAsProps.ts","mod::vue/node_modules/reka-ui/src/shared/useFilter.ts","mod::vue/node_modules/reka-ui/src/shared/useFocusGuards.ts","mod::vue/node_modules/reka-ui/src/shared/useFormControl.ts","mod::vue/node_modules/reka-ui/src/shared/useForwardExpose.ts","mod::vue/node_modules/reka-ui/src/shared/useForwardProps.ts","mod::vue/node_modules/reka-ui/src/shared/useForwardPropsEmits.ts","mod::vue/node_modules/reka-ui/src/shared/useForwardRef.ts","mod::vue/node_modules/reka-ui/src/shared/useGraceArea.ts","mod::vue/node_modules/aria-hidden/dist/es5/index.js","mod::vue/node_modules/reka-ui/src/shared/useHideOthers.ts","mod::vue/node_modules/reka-ui/src/shared/useId.ts","mod::vue/node_modules/reka-ui/src/shared/useKbd.ts","mod::vue/node_modules/reka-ui/src/shared/useLocale.ts","mod::vue/node_modules/reka-ui/src/shared/useSelectionBehavior.ts","mod::vue/node_modules/reka-ui/src/shared/useSize.ts","mod::vue/node_modules/reka-ui/src/shared/useStateMachine.ts","mod::vue/node_modules/reka-ui/src/shared/useTypeahead.ts","mod::vue/node_modules/reka-ui/src/shared/withDefault.ts","mod::vue/node_modules/reka-ui/dist/shared/index.cjs","mod::vue/node_modules/reka-ui/src/Presence/usePresence.ts","mod::vue/node_modules/reka-ui/src/Presence/Presence.ts","mod::vue/node_modules/reka-ui/src/Primitive/Slot.ts","mod::vue/node_modules/reka-ui/src/Primitive/Primitive.ts","mod::vue/node_modules/reka-ui/src/Primitive/usePrimitiveElement.ts","mod::vue/node_modules/reka-ui/src/Collapsible/CollapsibleRoot.vue","mod::vue/node_modules/reka-ui/src/Collapsible/CollapsibleRoot.vue","mod::vue/node_modules/reka-ui/src/Collapsible/CollapsibleContent.vue","mod::vue/node_modules/reka-ui/src/Collapsible/CollapsibleContent.vue","mod::vue/node_modules/reka-ui/src/Collapsible/CollapsibleTrigger.vue","mod::vue/node_modules/reka-ui/src/Collapsible/CollapsibleTrigger.vue","mod::vue/node_modules/reka-ui/src/shared/useSingleOrMultipleValue.ts","mod::vue/node_modules/reka-ui/src/Accordion/AccordionRoot.vue","mod::vue/node_modules/reka-ui/src/Accordion/AccordionRoot.vue","mod::vue/node_modules/reka-ui/src/Accordion/AccordionItem.vue","mod::vue/node_modules/reka-ui/src/Accordion/AccordionItem.vue","mod::vue/node_modules/reka-ui/src/Accordion/AccordionContent.vue","mod::vue/node_modules/reka-ui/src/Accordion/AccordionContent.vue","mod::vue/node_modules/reka-ui/src/Accordion/AccordionHeader.vue","mod::vue/node_modules/reka-ui/src/Accordion/AccordionHeader.vue","mod::vue/node_modules/reka-ui/src/Accordion/AccordionTrigger.vue","mod::vue/node_modules/reka-ui/src/Accordion/AccordionTrigger.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogRoot.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogRoot.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogClose.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogClose.vue","mod::vue/node_modules/reka-ui/src/DismissableLayer/utils.ts","mod::vue/node_modules/reka-ui/src/DismissableLayer/DismissableLayer.vue","mod::vue/node_modules/reka-ui/src/DismissableLayer/DismissableLayer.vue","mod::vue/node_modules/reka-ui/src/DismissableLayer/DismissableLayerBranch.vue","mod::vue/node_modules/reka-ui/src/DismissableLayer/DismissableLayerBranch.vue","mod::vue/node_modules/reka-ui/src/FocusScope/stack.ts","mod::vue/node_modules/reka-ui/src/FocusScope/utils.ts","mod::vue/node_modules/reka-ui/src/FocusScope/FocusScope.vue","mod::vue/node_modules/reka-ui/src/FocusScope/FocusScope.vue","mod::vue/node_modules/reka-ui/src/Menu/utils.ts","mod::vue/node_modules/reka-ui/src/Dialog/utils.ts","mod::vue/node_modules/reka-ui/src/Dialog/DialogContentImpl.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogContentImpl.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogContentModal.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogContentModal.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogContentNonModal.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogContentNonModal.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogContent.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogContent.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogDescription.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogDescription.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogOverlayImpl.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogOverlayImpl.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogOverlay.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogOverlay.vue","mod::vue/node_modules/reka-ui/src/Teleport/Teleport.vue","mod::vue/node_modules/reka-ui/src/Teleport/Teleport.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogPortal.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogPortal.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogTitle.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogTitle.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogTrigger.vue","mod::vue/node_modules/reka-ui/src/Dialog/DialogTrigger.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogAction.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogAction.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogContent.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogContent.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogCancel.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogCancel.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogDescription.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogDescription.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogOverlay.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogOverlay.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogPortal.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogPortal.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogRoot.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogRoot.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogTitle.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogTitle.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogTrigger.vue","mod::vue/node_modules/reka-ui/src/AlertDialog/AlertDialogTrigger.vue","mod::vue/node_modules/reka-ui/src/AspectRatio/AspectRatio.vue","mod::vue/node_modules/reka-ui/src/AspectRatio/AspectRatio.vue","mod::vue/node_modules/reka-ui/src/Collection/Collection.ts","mod::vue/node_modules/reka-ui/src/VisuallyHidden/VisuallyHidden.vue","mod::vue/node_modules/reka-ui/src/VisuallyHidden/VisuallyHidden.vue","mod::vue/node_modules/reka-ui/src/VisuallyHidden/VisuallyHiddenInputBubble.vue","mod::vue/node_modules/reka-ui/src/VisuallyHidden/VisuallyHiddenInputBubble.vue","mod::vue/node_modules/reka-ui/src/VisuallyHidden/VisuallyHiddenInput.vue","mod::vue/node_modules/reka-ui/src/VisuallyHidden/VisuallyHiddenInput.vue","mod::vue/node_modules/reka-ui/src/Listbox/utils.ts","mod::vue/node_modules/reka-ui/src/RovingFocus/utils.ts","mod::vue/node_modules/reka-ui/src/Listbox/ListboxRoot.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxRoot.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxContent.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxContent.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxFilter.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxFilter.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxGroup.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxGroup.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxGroupLabel.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxGroupLabel.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxItem.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxItem.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxItemIndicator.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxItemIndicator.vue","mod::vue/node_modules/@tanstack/virtual-core/src/lazy-measurements.ts","mod::vue/node_modules/@tanstack/virtual-core/src/utils.ts","mod::vue/node_modules/@tanstack/virtual-core/src/index.ts","mod::vue/node_modules/@tanstack/vue-virtual/src/index.ts","mod::vue/node_modules/reka-ui/src/Listbox/ListboxVirtualizer.vue","mod::vue/node_modules/reka-ui/src/Listbox/ListboxVirtualizer.vue","mod::vue/node_modules/reka-ui/src/Popper/PopperRoot.vue","mod::vue/node_modules/reka-ui/src/Popper/PopperRoot.vue","mod::vue/node_modules/reka-ui/src/Popper/PopperAnchor.vue","mod::vue/node_modules/reka-ui/src/Popper/PopperAnchor.vue","mod::vue/node_modules/reka-ui/src/shared/component/Arrow.vue","mod::vue/node_modules/reka-ui/src/shared/component/Arrow.vue","mod::vue/node_modules/reka-ui/src/Popper/utils.ts","mod::vue/node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs","mod::vue/node_modules/@floating-ui/core/dist/floating-ui.core.mjs","mod::vue/node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs","mod::vue/node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs","mod::vue/node_modules/vue-demi/lib/index.cjs","mod::vue/node_modules/@floating-ui/vue/dist/floating-ui.vue.esm.js","mod::vue/node_modules/reka-ui/src/Popper/PopperContent.vue","mod::vue/node_modules/reka-ui/src/Popper/PopperContent.vue","mod::vue/node_modules/reka-ui/src/Popper/PopperArrow.vue","mod::vue/node_modules/reka-ui/src/Popper/PopperArrow.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxRoot.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxRoot.vue","mod::vue/node_modules/reka-ui/src/Autocomplete/AutocompleteRoot.vue","mod::vue/node_modules/reka-ui/src/Autocomplete/AutocompleteRoot.vue","mod::vue/node_modules/reka-ui/src/Autocomplete/AutocompleteInput.vue","mod::vue/node_modules/reka-ui/src/Autocomplete/AutocompleteInput.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxAnchor.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxAnchor.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxContentImpl.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxContentImpl.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxArrow.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxArrow.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxCancel.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxCancel.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxContent.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxContent.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxEmpty.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxEmpty.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxGroup.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxGroup.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxInput.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxInput.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxItem.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxItem.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxItemIndicator.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxItemIndicator.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxLabel.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxLabel.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxPortal.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxPortal.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxSeparator.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxSeparator.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxTrigger.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxTrigger.vue","mod::vue/node_modules/reka-ui/src/shared/useNonce.ts","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxViewport.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxViewport.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxVirtualizer.vue","mod::vue/node_modules/reka-ui/src/Combobox/ComboboxVirtualizer.vue","mod::vue/node_modules/reka-ui/src/Avatar/AvatarRoot.vue","mod::vue/node_modules/reka-ui/src/Avatar/AvatarRoot.vue","mod::vue/node_modules/reka-ui/src/Avatar/AvatarFallback.vue","mod::vue/node_modules/reka-ui/src/Avatar/AvatarFallback.vue","mod::vue/node_modules/reka-ui/src/Avatar/utils.ts","mod::vue/node_modules/reka-ui/src/Avatar/AvatarImage.vue","mod::vue/node_modules/reka-ui/src/Avatar/AvatarImage.vue","mod::vue/node_modules/reka-ui/src/shared/date/parts.ts","mod::vue/node_modules/reka-ui/src/shared/date/placeholders.ts","mod::vue/node_modules/reka-ui/src/shared/date/parser.ts","mod::vue/node_modules/reka-ui/src/shared/date/segment.ts","mod::vue/node_modules/reka-ui/src/shared/date/useDateField.ts","mod::vue/node_modules/reka-ui/src/Calendar/useCalendar.ts","mod::vue/node_modules/reka-ui/src/Calendar/CalendarRoot.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarRoot.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarCell.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarCell.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarCellTrigger.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarCellTrigger.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarGrid.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarGrid.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarGridBody.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarGridBody.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarGridHead.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarGridHead.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarGridRow.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarGridRow.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarHeadCell.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarHeadCell.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarHeader.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarHeader.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarHeading.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarHeading.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarNext.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarNext.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarPrev.vue","mod::vue/node_modules/reka-ui/src/Calendar/CalendarPrev.vue","mod::vue/node_modules/reka-ui/src/RovingFocus/RovingFocusGroup.vue","mod::vue/node_modules/reka-ui/src/RovingFocus/RovingFocusGroup.vue","mod::vue/node_modules/reka-ui/src/RovingFocus/RovingFocusItem.vue","mod::vue/node_modules/reka-ui/src/RovingFocus/RovingFocusItem.vue","mod::vue/node_modules/reka-ui/src/Checkbox/CheckboxGroupRoot.vue","mod::vue/node_modules/reka-ui/src/Checkbox/CheckboxGroupRoot.vue","mod::vue/node_modules/reka-ui/src/Checkbox/utils.ts","mod::vue/node_modules/reka-ui/src/Checkbox/CheckboxRoot.vue","mod::vue/node_modules/reka-ui/src/Checkbox/CheckboxRoot.vue","mod::vue/node_modules/reka-ui/src/Checkbox/CheckboxIndicator.vue","mod::vue/node_modules/reka-ui/src/Checkbox/CheckboxIndicator.vue","mod::vue/node_modules/reka-ui/src/shared/color/convert.ts","mod::vue/node_modules/reka-ui/src/shared/color/channel.ts","mod::vue/node_modules/reka-ui/src/shared/color/gradient.ts","mod::vue/node_modules/reka-ui/src/shared/color/parse.ts","mod::vue/node_modules/reka-ui/src/shared/color/utils.ts","mod::vue/node_modules/reka-ui/src/ColorArea/ColorAreaRoot.vue","mod::vue/node_modules/reka-ui/src/ColorArea/ColorAreaRoot.vue","mod::vue/node_modules/reka-ui/src/ColorArea/utils.ts","mod::vue/node_modules/reka-ui/src/ColorArea/ColorAreaArea.vue","mod::vue/node_modules/reka-ui/src/ColorArea/ColorAreaArea.vue","mod::vue/node_modules/reka-ui/src/ColorArea/ColorAreaThumb.vue","mod::vue/node_modules/reka-ui/src/ColorArea/ColorAreaThumb.vue","mod::vue/node_modules/reka-ui/src/ColorField/ColorFieldRoot.vue","mod::vue/node_modules/reka-ui/src/ColorField/ColorFieldRoot.vue","mod::vue/node_modules/reka-ui/src/ColorField/ColorFieldInput.vue","mod::vue/node_modules/reka-ui/src/ColorField/ColorFieldInput.vue","mod::vue/node_modules/reka-ui/src/Slider/utils.ts","mod::vue/node_modules/reka-ui/src/Slider/SliderHorizontal.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderHorizontal.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderVertical.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderVertical.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderRoot.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderRoot.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderImpl.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderImpl.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderRange.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderRange.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderThumbImpl.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderThumbImpl.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderThumb.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderThumb.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderTrack.vue","mod::vue/node_modules/reka-ui/src/Slider/SliderTrack.vue","mod::vue/node_modules/reka-ui/src/ColorSlider/ColorSliderRoot.vue","mod::vue/node_modules/reka-ui/src/ColorSlider/ColorSliderRoot.vue","mod::vue/node_modules/reka-ui/src/ColorSlider/ColorSliderThumb.vue","mod::vue/node_modules/reka-ui/src/ColorSlider/ColorSliderThumb.vue","mod::vue/node_modules/reka-ui/src/ColorSlider/ColorSliderTrack.vue","mod::vue/node_modules/reka-ui/src/ColorSlider/ColorSliderTrack.vue","mod::vue/node_modules/reka-ui/src/ColorSwatch/ColorSwatch.vue","mod::vue/node_modules/reka-ui/src/ColorSwatch/ColorSwatch.vue","mod::vue/node_modules/reka-ui/src/ColorSwatchPicker/ColorSwatchPickerItem.vue","mod::vue/node_modules/reka-ui/src/ColorSwatchPicker/ColorSwatchPickerItem.vue","mod::vue/node_modules/reka-ui/src/ColorSwatchPicker/ColorSwatchPickerItemIndicator.vue","mod::vue/node_modules/reka-ui/src/ColorSwatchPicker/ColorSwatchPickerItemIndicator.vue","mod::vue/node_modules/reka-ui/src/ColorSwatchPicker/ColorSwatchPickerItemSwatch.vue","mod::vue/node_modules/reka-ui/src/ColorSwatchPicker/ColorSwatchPickerItemSwatch.vue","mod::vue/node_modules/reka-ui/src/ColorSwatchPicker/ColorSwatchPickerRoot.vue","mod::vue/node_modules/reka-ui/src/ColorSwatchPicker/ColorSwatchPickerRoot.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuAnchor.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuAnchor.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuArrow.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuArrow.vue","mod::vue/node_modules/reka-ui/src/shared/useIsUsingKeyboard.ts","mod::vue/node_modules/reka-ui/src/Menu/MenuRoot.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuRoot.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuContentImpl.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuContentImpl.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuItemImpl.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuItemImpl.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuItem.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuItem.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuItemIndicator.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuItemIndicator.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuCheckboxItem.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuCheckboxItem.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuRootContentModal.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuRootContentModal.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuRootContentNonModal.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuRootContentNonModal.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuContent.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuContent.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuGroup.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuGroup.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuLabel.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuLabel.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuPortal.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuPortal.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuRadioGroup.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuRadioGroup.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuRadioItem.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuRadioItem.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuSeparator.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuSeparator.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuSub.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuSub.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuSubContent.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuSubContent.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuSubTrigger.vue","mod::vue/node_modules/reka-ui/src/Menu/MenuSubTrigger.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuArrow.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuArrow.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuCheckboxItem.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuCheckboxItem.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuRoot.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuRoot.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuContent.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuContent.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuGroup.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuGroup.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuItem.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuItem.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuItemIndicator.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuItemIndicator.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuLabel.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuLabel.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuPortal.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuPortal.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuRadioGroup.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuRadioGroup.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuRadioItem.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuRadioItem.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuSeparator.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuSeparator.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuSub.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuSub.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuSubContent.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuSubContent.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuSubTrigger.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuSubTrigger.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/utils.ts","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuTrigger.vue","mod::vue/node_modules/reka-ui/src/ContextMenu/ContextMenuTrigger.vue","mod::vue/node_modules/reka-ui/src/DateField/DateFieldRoot.vue","mod::vue/node_modules/reka-ui/src/DateField/DateFieldRoot.vue","mod::vue/node_modules/reka-ui/src/DateField/DateFieldInput.vue","mod::vue/node_modules/reka-ui/src/DateField/DateFieldInput.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverRoot.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverRoot.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverAnchor.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverAnchor.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerAnchor.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerAnchor.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverArrow.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverArrow.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerArrow.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerArrow.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerRoot.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerRoot.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerCalendar.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerCalendar.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerCell.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerCell.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerCellTrigger.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerCellTrigger.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverClose.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverClose.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerClose.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerClose.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverContentImpl.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverContentImpl.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverContentModal.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverContentModal.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverContentNonModal.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverContentNonModal.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverContent.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverContent.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverPortal.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverPortal.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerContent.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerContent.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerField.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerField.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerGrid.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerGrid.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerGridBody.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerGridBody.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerGridHead.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerGridHead.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerGridRow.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerGridRow.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerHeadCell.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerHeadCell.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerHeader.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerHeader.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerHeading.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerHeading.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerInput.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerInput.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerNext.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerNext.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerPrev.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerPrev.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverTrigger.vue","mod::vue/node_modules/reka-ui/src/Popover/PopoverTrigger.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerTrigger.vue","mod::vue/node_modules/reka-ui/src/DatePicker/DatePickerTrigger.vue","mod::vue/node_modules/reka-ui/src/DateRangeField/DateRangeFieldRoot.vue","mod::vue/node_modules/reka-ui/src/DateRangeField/DateRangeFieldRoot.vue","mod::vue/node_modules/reka-ui/src/DateRangeField/DateRangeFieldInput.vue","mod::vue/node_modules/reka-ui/src/DateRangeField/DateRangeFieldInput.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerAnchor.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerAnchor.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerArrow.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerArrow.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerRoot.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerRoot.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/useRangeCalendar.ts","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarRoot.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarRoot.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerCalendar.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerCalendar.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarCell.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarCell.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerCell.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerCell.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarCellTrigger.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarCellTrigger.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerCellTrigger.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerCellTrigger.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerClose.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerClose.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerContent.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerContent.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerField.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerField.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarGrid.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarGrid.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerGrid.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerGrid.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarGridBody.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarGridBody.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerGridBody.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerGridBody.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarGridHead.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarGridHead.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerGridHead.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerGridHead.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarGridRow.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarGridRow.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerGridRow.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerGridRow.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarHeadCell.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarHeadCell.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerHeadCell.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerHeadCell.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarHeader.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarHeader.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerHeader.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerHeader.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarHeading.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarHeading.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerHeading.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerHeading.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerInput.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerInput.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarNext.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarNext.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerNext.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerNext.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarPrev.vue","mod::vue/node_modules/reka-ui/src/RangeCalendar/RangeCalendarPrev.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerPrev.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerPrev.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerTrigger.vue","mod::vue/node_modules/reka-ui/src/DateRangePicker/DateRangePickerTrigger.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuArrow.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuArrow.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuCheckboxItem.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuCheckboxItem.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuRoot.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuRoot.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuContent.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuContent.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuFilter.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuFilter.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuGroup.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuGroup.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuItem.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuItem.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuItemIndicator.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuItemIndicator.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuLabel.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuLabel.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuPortal.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuPortal.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuRadioGroup.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuRadioGroup.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuRadioItem.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuRadioItem.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuSeparator.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuSeparator.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuSub.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuSub.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuSubContent.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuSubContent.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuSubTrigger.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuSubTrigger.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuTrigger.vue","mod::vue/node_modules/reka-ui/src/DropdownMenu/DropdownMenuTrigger.vue","mod::vue/node_modules/reka-ui/src/Editable/EditableRoot.vue","mod::vue/node_modules/reka-ui/src/Editable/EditableRoot.vue","mod::vue/node_modules/reka-ui/src/Editable/EditableArea.vue","mod::vue/node_modules/reka-ui/src/Editable/EditableArea.vue","mod::vue/node_modules/reka-ui/src/Editable/EditableCancelTrigger.vue","mod::vue/node_modules/reka-ui/src/Editable/EditableCancelTrigger.vue","mod::vue/node_modules/reka-ui/src/Editable/EditableEditTrigger.vue","mod::vue/node_modules/reka-ui/src/Editable/EditableEditTrigger.vue","mod::vue/node_modules/reka-ui/src/Editable/EditableInput.vue","mod::vue/node_modules/reka-ui/src/Editable/EditableInput.vue","mod::vue/node_modules/reka-ui/src/Editable/EditablePreview.vue","mod::vue/node_modules/reka-ui/src/Editable/EditablePreview.vue","mod::vue/node_modules/reka-ui/src/Editable/EditableSubmitTrigger.vue","mod::vue/node_modules/reka-ui/src/Editable/EditableSubmitTrigger.vue","mod::vue/node_modules/reka-ui/src/HoverCard/HoverCardArrow.vue","mod::vue/node_modules/reka-ui/src/HoverCard/HoverCardArrow.vue","mod::vue/node_modules/reka-ui/src/HoverCard/HoverCardRoot.vue","mod::vue/node_modules/reka-ui/src/HoverCard/HoverCardRoot.vue","mod::vue/node_modules/reka-ui/src/HoverCard/utils.ts","mod::vue/node_modules/reka-ui/src/HoverCard/HoverCardContentImpl.vue","mod::vue/node_modules/reka-ui/src/HoverCard/HoverCardContentImpl.vue","mod::vue/node_modules/reka-ui/src/HoverCard/HoverCardContent.vue","mod::vue/node_modules/reka-ui/src/HoverCard/HoverCardContent.vue","mod::vue/node_modules/reka-ui/src/HoverCard/HoverCardPortal.vue","mod::vue/node_modules/reka-ui/src/HoverCard/HoverCardPortal.vue","mod::vue/node_modules/reka-ui/src/HoverCard/HoverCardTrigger.vue","mod::vue/node_modules/reka-ui/src/HoverCard/HoverCardTrigger.vue","mod::vue/node_modules/reka-ui/src/Label/Label.vue","mod::vue/node_modules/reka-ui/src/Label/Label.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarArrow.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarArrow.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarCheckboxItem.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarCheckboxItem.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarRoot.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarRoot.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarMenu.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarMenu.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarContent.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarContent.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarGroup.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarGroup.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarItem.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarItem.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarItemIndicator.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarItemIndicator.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarLabel.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarLabel.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarPortal.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarPortal.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarRadioGroup.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarRadioGroup.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarRadioItem.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarRadioItem.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarSeparator.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarSeparator.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarSub.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarSub.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarSubContent.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarSubContent.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarSubTrigger.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarSubTrigger.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarTrigger.vue","mod::vue/node_modules/reka-ui/src/Menubar/MenubarTrigger.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/useMonthPicker.ts","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerRoot.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerRoot.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerCell.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerCell.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerCellTrigger.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerCellTrigger.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerGrid.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerGrid.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerGridBody.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerGridBody.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerGridRow.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerGridRow.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerHeader.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerHeader.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerHeading.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerHeading.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerNext.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerNext.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerPrev.vue","mod::vue/node_modules/reka-ui/src/MonthPicker/MonthPickerPrev.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/useRangeMonthPicker.ts","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerRoot.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerRoot.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerCell.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerCell.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerCellTrigger.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerCellTrigger.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerGrid.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerGrid.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerGridBody.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerGridBody.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerGridRow.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerGridRow.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerHeader.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerHeader.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerHeading.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerHeading.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerNext.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerNext.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerPrev.vue","mod::vue/node_modules/reka-ui/src/MonthRangePicker/MonthRangePickerPrev.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/utils.ts","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuRoot.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuRoot.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuItem.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuItem.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuContentImpl.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuContentImpl.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuContent.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuContent.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuIndicator.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuIndicator.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuLink.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuLink.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuList.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuList.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuSub.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuSub.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuTrigger.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuTrigger.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuViewport.vue","mod::vue/node_modules/reka-ui/src/NavigationMenu/NavigationMenuViewport.vue","mod::vue/node_modules/@internationalized/number/dist/private/packages/@internationalized/number/src/NumberFormatter.ts","mod::vue/node_modules/@internationalized/number/dist/private/packages/@internationalized/number/src/NumberParser.ts","mod::vue/node_modules/reka-ui/src/NumberField/utils.ts","mod::vue/node_modules/reka-ui/src/NumberField/NumberFieldRoot.vue","mod::vue/node_modules/reka-ui/src/NumberField/NumberFieldRoot.vue","mod::vue/node_modules/reka-ui/src/NumberField/NumberFieldDecrement.vue","mod::vue/node_modules/reka-ui/src/NumberField/NumberFieldDecrement.vue","mod::vue/node_modules/reka-ui/src/NumberField/NumberFieldIncrement.vue","mod::vue/node_modules/reka-ui/src/NumberField/NumberFieldIncrement.vue","mod::vue/node_modules/reka-ui/src/NumberField/NumberFieldInput.vue","mod::vue/node_modules/reka-ui/src/NumberField/NumberFieldInput.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationEllipsis.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationEllipsis.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationRoot.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationRoot.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationFirst.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationFirst.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationLast.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationLast.vue","mod::vue/node_modules/reka-ui/src/Pagination/utils.ts","mod::vue/node_modules/reka-ui/src/Pagination/PaginationList.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationList.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationListItem.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationListItem.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationNext.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationNext.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationPrev.vue","mod::vue/node_modules/reka-ui/src/Pagination/PaginationPrev.vue","mod::vue/node_modules/reka-ui/src/PinInput/PinInputRoot.vue","mod::vue/node_modules/reka-ui/src/PinInput/PinInputRoot.vue","mod::vue/node_modules/reka-ui/src/PinInput/PinInputInput.vue","mod::vue/node_modules/reka-ui/src/PinInput/PinInputInput.vue","mod::vue/node_modules/reka-ui/src/Progress/ProgressRoot.vue","mod::vue/node_modules/reka-ui/src/Progress/ProgressRoot.vue","mod::vue/node_modules/reka-ui/src/Progress/ProgressIndicator.vue","mod::vue/node_modules/reka-ui/src/Progress/ProgressIndicator.vue","mod::vue/node_modules/reka-ui/src/RadioGroup/utils.ts","mod::vue/node_modules/reka-ui/src/RadioGroup/Radio.vue","mod::vue/node_modules/reka-ui/src/RadioGroup/Radio.vue","mod::vue/node_modules/reka-ui/src/RadioGroup/RadioGroupRoot.vue","mod::vue/node_modules/reka-ui/src/RadioGroup/RadioGroupRoot.vue","mod::vue/node_modules/reka-ui/src/RadioGroup/RadioGroupItem.vue","mod::vue/node_modules/reka-ui/src/RadioGroup/RadioGroupItem.vue","mod::vue/node_modules/reka-ui/src/RadioGroup/RadioGroupIndicator.vue","mod::vue/node_modules/reka-ui/src/RadioGroup/RadioGroupIndicator.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaRoot.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaRoot.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaCornerImpl.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaCornerImpl.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaCorner.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaCorner.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/utils.ts","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarX.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarX.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarY.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarY.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarAuto.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarAuto.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarGlimpse.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarGlimpse.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarHover.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarHover.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarScroll.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarScroll.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbar.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbar.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarVisible.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarVisible.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarImpl.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaScrollbarImpl.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaThumb.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaThumb.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaViewport.vue","mod::vue/node_modules/reka-ui/src/ScrollArea/ScrollAreaViewport.vue","mod::vue/node_modules/reka-ui/src/Select/utils.ts","mod::vue/node_modules/reka-ui/src/Select/SelectRoot.vue","mod::vue/node_modules/reka-ui/src/Select/SelectRoot.vue","mod::vue/node_modules/reka-ui/src/Select/BubbleSelect.vue","mod::vue/node_modules/reka-ui/src/Select/BubbleSelect.vue","mod::vue/node_modules/reka-ui/src/Select/SelectPopperPosition.vue","mod::vue/node_modules/reka-ui/src/Select/SelectPopperPosition.vue","mod::vue/node_modules/reka-ui/src/Select/SelectContentImpl.vue","mod::vue/node_modules/reka-ui/src/Select/SelectContentImpl.vue","mod::vue/node_modules/reka-ui/src/Select/SelectItemAlignedPosition.vue","mod::vue/node_modules/reka-ui/src/Select/SelectItemAlignedPosition.vue","mod::vue/node_modules/reka-ui/src/Select/SelectArrow.vue","mod::vue/node_modules/reka-ui/src/Select/SelectArrow.vue","mod::vue/node_modules/reka-ui/src/Select/SelectProvider.vue","mod::vue/node_modules/reka-ui/src/Select/SelectProvider.vue","mod::vue/node_modules/reka-ui/src/Select/SelectContent.vue","mod::vue/node_modules/reka-ui/src/Select/SelectContent.vue","mod::vue/node_modules/reka-ui/src/Select/SelectGroup.vue","mod::vue/node_modules/reka-ui/src/Select/SelectGroup.vue","mod::vue/node_modules/reka-ui/src/Select/SelectIcon.vue","mod::vue/node_modules/reka-ui/src/Select/SelectIcon.vue","mod::vue/node_modules/reka-ui/src/Select/SelectItem.vue","mod::vue/node_modules/reka-ui/src/Select/SelectItem.vue","mod::vue/node_modules/reka-ui/src/Select/SelectItemIndicator.vue","mod::vue/node_modules/reka-ui/src/Select/SelectItemIndicator.vue","mod::vue/node_modules/reka-ui/src/Select/SelectItemText.vue","mod::vue/node_modules/reka-ui/src/Select/SelectItemText.vue","mod::vue/node_modules/reka-ui/src/Select/SelectLabel.vue","mod::vue/node_modules/reka-ui/src/Select/SelectLabel.vue","mod::vue/node_modules/reka-ui/src/Select/SelectPortal.vue","mod::vue/node_modules/reka-ui/src/Select/SelectPortal.vue","mod::vue/node_modules/reka-ui/src/Select/SelectScrollButtonImpl.vue","mod::vue/node_modules/reka-ui/src/Select/SelectScrollButtonImpl.vue","mod::vue/node_modules/reka-ui/src/Select/SelectScrollDownButton.vue","mod::vue/node_modules/reka-ui/src/Select/SelectScrollDownButton.vue","mod::vue/node_modules/reka-ui/src/Select/SelectScrollUpButton.vue","mod::vue/node_modules/reka-ui/src/Select/SelectScrollUpButton.vue","mod::vue/node_modules/reka-ui/src/Select/SelectSeparator.vue","mod::vue/node_modules/reka-ui/src/Select/SelectSeparator.vue","mod::vue/node_modules/reka-ui/src/Select/SelectTrigger.vue","mod::vue/node_modules/reka-ui/src/Select/SelectTrigger.vue","mod::vue/node_modules/reka-ui/src/Select/SelectValue.vue","mod::vue/node_modules/reka-ui/src/Select/SelectValue.vue","mod::vue/node_modules/reka-ui/src/Select/SelectViewport.vue","mod::vue/node_modules/reka-ui/src/Select/SelectViewport.vue","mod::vue/node_modules/reka-ui/src/shared/component/BaseSeparator.vue","mod::vue/node_modules/reka-ui/src/shared/component/BaseSeparator.vue","mod::vue/node_modules/reka-ui/src/Separator/Separator.vue","mod::vue/node_modules/reka-ui/src/Separator/Separator.vue","mod::vue/node_modules/reka-ui/src/Splitter/utils/assert.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/dom.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/events.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/calculate.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/compare.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/callPanelCallbacks.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/debounce.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/resizePanel.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/layout.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/pivot.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/rects.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/stackingOrder.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/registry.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/style.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/units.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/validation.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/composables/useWindowSplitterPanelGroupBehavior.ts","mod::vue/node_modules/reka-ui/src/Splitter/utils/storage.ts","mod::vue/node_modules/reka-ui/src/Splitter/SplitterGroup.vue","mod::vue/node_modules/reka-ui/src/Splitter/SplitterGroup.vue","mod::vue/node_modules/reka-ui/src/Splitter/SplitterPanel.vue","mod::vue/node_modules/reka-ui/src/Splitter/SplitterPanel.vue","mod::vue/node_modules/reka-ui/src/Splitter/utils/composables/useWindowSplitterBehavior.ts","mod::vue/node_modules/reka-ui/src/Splitter/SplitterResizeHandle.vue","mod::vue/node_modules/reka-ui/src/Splitter/SplitterResizeHandle.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperRoot.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperRoot.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperItem.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperItem.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperDescription.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperDescription.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperIndicator.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperIndicator.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperSeparator.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperSeparator.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperTitle.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperTitle.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperTrigger.vue","mod::vue/node_modules/reka-ui/src/Stepper/StepperTrigger.vue","mod::vue/node_modules/reka-ui/src/Switch/SwitchRoot.vue","mod::vue/node_modules/reka-ui/src/Switch/SwitchRoot.vue","mod::vue/node_modules/reka-ui/src/Switch/SwitchThumb.vue","mod::vue/node_modules/reka-ui/src/Switch/SwitchThumb.vue","mod::vue/node_modules/reka-ui/src/Tabs/TabsRoot.vue","mod::vue/node_modules/reka-ui/src/Tabs/TabsRoot.vue","mod::vue/node_modules/reka-ui/src/Tabs/utils.ts","mod::vue/node_modules/reka-ui/src/Tabs/TabsContent.vue","mod::vue/node_modules/reka-ui/src/Tabs/TabsContent.vue","mod::vue/node_modules/reka-ui/src/Tabs/TabsIndicator.vue","mod::vue/node_modules/reka-ui/src/Tabs/TabsIndicator.vue","mod::vue/node_modules/reka-ui/src/Tabs/TabsList.vue","mod::vue/node_modules/reka-ui/src/Tabs/TabsList.vue","mod::vue/node_modules/reka-ui/src/Tabs/TabsTrigger.vue","mod::vue/node_modules/reka-ui/src/Tabs/TabsTrigger.vue","mod::vue/node_modules/reka-ui/src/TagsInput/TagsInputRoot.vue","mod::vue/node_modules/reka-ui/src/TagsInput/TagsInputRoot.vue","mod::vue/node_modules/reka-ui/src/TagsInput/TagsInputClear.vue","mod::vue/node_modules/reka-ui/src/TagsInput/TagsInputClear.vue","mod::vue/node_modules/reka-ui/src/TagsInput/TagsInputInput.vue","mod::vue/node_modules/reka-ui/src/TagsInput/TagsInputInput.vue","mod::vue/node_modules/reka-ui/src/TagsInput/TagsInputItem.vue","mod::vue/node_modules/reka-ui/src/TagsInput/TagsInputItem.vue","mod::vue/node_modules/reka-ui/src/TagsInput/TagsInputItemDelete.vue","mod::vue/node_modules/reka-ui/src/TagsInput/TagsInputItemDelete.vue","mod::vue/node_modules/reka-ui/src/TagsInput/TagsInputItemText.vue","mod::vue/node_modules/reka-ui/src/TagsInput/TagsInputItemText.vue","mod::vue/node_modules/reka-ui/src/TimeField/TimeFieldRoot.vue","mod::vue/node_modules/reka-ui/src/TimeField/TimeFieldRoot.vue","mod::vue/node_modules/reka-ui/src/TimeField/TimeFieldInput.vue","mod::vue/node_modules/reka-ui/src/TimeField/TimeFieldInput.vue","mod::vue/node_modules/reka-ui/src/TimeRangeField/TimeRangeFieldRoot.vue","mod::vue/node_modules/reka-ui/src/TimeRangeField/TimeRangeFieldRoot.vue","mod::vue/node_modules/reka-ui/src/TimeRangeField/TimeRangeFieldInput.vue","mod::vue/node_modules/reka-ui/src/TimeRangeField/TimeRangeFieldInput.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastAnnounceExclude.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastAnnounceExclude.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastProvider.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastProvider.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastAnnounce.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastAnnounce.vue","mod::vue/node_modules/reka-ui/src/Toast/utils.ts","mod::vue/node_modules/reka-ui/src/Toast/ToastRootImpl.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastRootImpl.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastClose.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastClose.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastAction.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastAction.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastDescription.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastDescription.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastPortal.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastPortal.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastRoot.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastRoot.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastTitle.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastTitle.vue","mod::vue/node_modules/reka-ui/src/Toast/FocusProxy.vue","mod::vue/node_modules/reka-ui/src/Toast/FocusProxy.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastViewport.vue","mod::vue/node_modules/reka-ui/src/Toast/ToastViewport.vue","mod::vue/node_modules/reka-ui/src/ToggleGroup/ToggleGroupRoot.vue","mod::vue/node_modules/reka-ui/src/ToggleGroup/ToggleGroupRoot.vue","mod::vue/node_modules/reka-ui/src/Toggle/Toggle.vue","mod::vue/node_modules/reka-ui/src/Toggle/Toggle.vue","mod::vue/node_modules/reka-ui/src/ToggleGroup/ToggleGroupItem.vue","mod::vue/node_modules/reka-ui/src/ToggleGroup/ToggleGroupItem.vue","mod::vue/node_modules/reka-ui/src/Toolbar/ToolbarButton.vue","mod::vue/node_modules/reka-ui/src/Toolbar/ToolbarButton.vue","mod::vue/node_modules/reka-ui/src/Toolbar/ToolbarLink.vue","mod::vue/node_modules/reka-ui/src/Toolbar/ToolbarLink.vue","mod::vue/node_modules/reka-ui/src/Toolbar/ToolbarRoot.vue","mod::vue/node_modules/reka-ui/src/Toolbar/ToolbarRoot.vue","mod::vue/node_modules/reka-ui/src/Toolbar/ToolbarSeparator.vue","mod::vue/node_modules/reka-ui/src/Toolbar/ToolbarSeparator.vue","mod::vue/node_modules/reka-ui/src/Toolbar/ToolbarToggleGroup.vue","mod::vue/node_modules/reka-ui/src/Toolbar/ToolbarToggleGroup.vue","mod::vue/node_modules/reka-ui/src/Toolbar/ToolbarToggleItem.vue","mod::vue/node_modules/reka-ui/src/Toolbar/ToolbarToggleItem.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipArrow.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipArrow.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipProvider.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipProvider.vue","mod::vue/node_modules/reka-ui/src/Tooltip/utils.ts","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipRoot.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipRoot.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipContentImpl.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipContentImpl.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipContentHoverable.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipContentHoverable.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipContent.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipContent.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipPortal.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipPortal.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipTrigger.vue","mod::vue/node_modules/reka-ui/src/Tooltip/TooltipTrigger.vue","mod::vue/node_modules/reka-ui/src/Tree/utils.ts","mod::vue/node_modules/reka-ui/src/Tree/TreeRoot.vue","mod::vue/node_modules/reka-ui/src/Tree/TreeRoot.vue","mod::vue/node_modules/reka-ui/src/Tree/TreeItem.vue","mod::vue/node_modules/reka-ui/src/Tree/TreeItem.vue","mod::vue/node_modules/reka-ui/src/Tree/TreeVirtualizer.vue","mod::vue/node_modules/reka-ui/src/Tree/TreeVirtualizer.vue","mod::vue/node_modules/reka-ui/src/Viewport/Viewport.vue","mod::vue/node_modules/reka-ui/src/Viewport/Viewport.vue","mod::vue/node_modules/reka-ui/src/YearPicker/useYearPicker.ts","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerRoot.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerRoot.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerCell.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerCell.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerCellTrigger.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerCellTrigger.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerGrid.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerGrid.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerGridBody.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerGridBody.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerGridRow.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerGridRow.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerHeader.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerHeader.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerHeading.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerHeading.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerNext.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerNext.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerPrev.vue","mod::vue/node_modules/reka-ui/src/YearPicker/YearPickerPrev.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/useRangeYearPicker.ts","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerRoot.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerRoot.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerCell.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerCell.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerCellTrigger.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerCellTrigger.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerGrid.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerGrid.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerGridBody.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerGridBody.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerGridRow.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerGridRow.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerHeader.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerHeader.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerHeading.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerHeading.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerNext.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerNext.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerPrev.vue","mod::vue/node_modules/reka-ui/src/YearRangePicker/YearRangePickerPrev.vue","mod::vue/node_modules/reka-ui/dist/index2.cjs","mod::vue/node_modules/reka-ui/dist/index.cjs","@webhare/env/src/envbackend.ts","@webhare/env/src/init-browser.ts","@webhare/dompack/src/tree.ts","@webhare/std/src/quacks.ts","@webhare/std/src/finmath.ts","@webhare/std/src/money.ts","@webhare/std/src/strings.ts","@webhare/std/src/collections.ts","@webhare/std/src/localmutex.ts","@webhare/frontend/src/init.ts","@webhare/tsrun/src/polyfills.ts","mod::publisher/js/internal/polyfills/iterator-helpers.ts","@webhare/env/src/navigation.ts","@webhare/env/src/whglobal.ts","mod::system/js/dompack/src/events.ts","@webhare/dompack/src/busy.ts","mod::system/js/dompack/src/tree.ts","mod::system/js/dompack/src/components.ts","@webhare/dompack/src/storage.ts","@webhare/dompack/src/browser.ts","mod::publisher/js/internal/polyfills/publisher-integration.ts","mod::btw/webdesigns/btwcoach/frontend/frontend.ts","node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js","@webhare/js-api-tools/src/stacktracing.ts","@webhare/rpc/src/rpc.ts","@webhare/auth/src/shared.ts","@webhare/frontend/src/auth.ts","@webhare/frontend/src/gtm.ts","@webhare/frontend/src/frontend.ts","mod::btw/webdesigns/btwcoach/frontend/lib/useWrdAuthState.ts","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChatWorkspace.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChatView.vue","mod::btw/node_modules/shared/src/utils/hasA11yProp.ts","mod::btw/node_modules/shared/src/utils/isEmptyString.ts","mod::btw/node_modules/shared/src/utils/mergeClasses.ts","mod::btw/node_modules/shared/src/utils/toKebabCase.ts","mod::btw/node_modules/shared/src/utils/toCamelCase.ts","mod::btw/node_modules/shared/src/utils/toPascalCase.ts","mod::btw/node_modules/lucide-vue-next/src/defaultAttributes.ts","mod::btw/node_modules/lucide-vue-next/src/Icon.ts","mod::btw/node_modules/lucide-vue-next/src/createLucideIcon.ts","mod::btw/node_modules/lucide-vue-next/src/icons/arrow-down.ts","mod::btw/node_modules/lucide-vue-next/src/icons/brain.ts","mod::btw/node_modules/lucide-vue-next/src/icons/check.ts","mod::btw/node_modules/lucide-vue-next/src/icons/chevron-down.ts","mod::btw/node_modules/lucide-vue-next/src/icons/circle-alert.ts","mod::btw/node_modules/lucide-vue-next/src/icons/copy.ts","mod::btw/node_modules/lucide-vue-next/src/icons/corner-down-left.ts","mod::btw/node_modules/lucide-vue-next/src/icons/download.ts","mod::btw/node_modules/lucide-vue-next/src/icons/file-text.ts","mod::btw/node_modules/lucide-vue-next/src/icons/flask-conical.ts","mod::btw/node_modules/lucide-vue-next/src/icons/loader-circle.ts","mod::btw/node_modules/lucide-vue-next/src/icons/log-out.ts","mod::btw/node_modules/lucide-vue-next/src/icons/menu.ts","mod::btw/node_modules/lucide-vue-next/src/icons/message-square.ts","mod::btw/node_modules/lucide-vue-next/src/icons/moon.ts","mod::btw/node_modules/lucide-vue-next/src/icons/search.ts","mod::btw/node_modules/lucide-vue-next/src/icons/square-pen.ts","mod::btw/node_modules/lucide-vue-next/src/icons/square.ts","mod::btw/node_modules/lucide-vue-next/src/icons/sun.ts","mod::btw/node_modules/lucide-vue-next/src/icons/thumbs-up.ts","mod::btw/node_modules/lucide-vue-next/src/icons/thumbs-down.ts","mod::btw/node_modules/lucide-vue-next/src/icons/triangle-alert.ts","mod::btw/node_modules/lucide-vue-next/src/icons/x.ts","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/Sidebar.vue","mod::btw/node_modules/streamdown-vue/dist/StreamMarkdown-BUAEdLZw.js","mod::btw/node_modules/bail/index.js","mod::btw/node_modules/unified/lib/index.js","mod::btw/node_modules/is-plain-obj/index.js","mod::btw/node_modules/trough/lib/index.js","mod::btw/node_modules/unist-util-stringify-position/lib/index.js","mod::btw/node_modules/vfile-message/lib/index.js","mod::btw/node_modules/vfile/lib/minpath.browser.js","mod::btw/node_modules/vfile/lib/minproc.browser.js","mod::btw/node_modules/vfile/lib/minurl.shared.js","mod::btw/node_modules/vfile/lib/minurl.browser.js","mod::btw/node_modules/vfile/lib/index.js","mod::btw/node_modules/unified/lib/callable-instance.js","mod::btw/node_modules/mdast-util-to-string/lib/index.js","mod::btw/node_modules/decode-named-character-reference/index.dom.js","mod::btw/node_modules/micromark-util-chunked/index.js","mod::btw/node_modules/micromark-util-combine-extensions/index.js","mod::btw/node_modules/micromark-util-decode-numeric-character-reference/index.js","mod::btw/node_modules/micromark-util-normalize-identifier/index.js","mod::btw/node_modules/micromark-util-character/index.js","mod::btw/node_modules/micromark-util-sanitize-uri/index.js","mod::btw/node_modules/micromark-factory-space/index.js","mod::btw/node_modules/micromark/lib/initialize/content.js","mod::btw/node_modules/micromark/lib/initialize/document.js","mod::btw/node_modules/micromark-util-classify-character/index.js","mod::btw/node_modules/micromark-util-resolve-all/index.js","mod::btw/node_modules/micromark-core-commonmark/lib/attention.js","mod::btw/node_modules/micromark-core-commonmark/lib/autolink.js","mod::btw/node_modules/micromark-core-commonmark/lib/blank-line.js","mod::btw/node_modules/micromark-core-commonmark/lib/block-quote.js","mod::btw/node_modules/micromark-core-commonmark/lib/character-escape.js","mod::btw/node_modules/micromark-core-commonmark/lib/character-reference.js","mod::btw/node_modules/micromark-core-commonmark/lib/code-fenced.js","mod::btw/node_modules/micromark-core-commonmark/lib/code-indented.js","mod::btw/node_modules/micromark-core-commonmark/lib/code-text.js","mod::btw/node_modules/micromark-util-subtokenize/lib/splice-buffer.js","mod::btw/node_modules/micromark-util-subtokenize/index.js","mod::btw/node_modules/micromark-core-commonmark/lib/content.js","mod::btw/node_modules/micromark-factory-destination/index.js","mod::btw/node_modules/micromark-factory-label/index.js","mod::btw/node_modules/micromark-factory-title/index.js","mod::btw/node_modules/micromark-factory-whitespace/index.js","mod::btw/node_modules/micromark-core-commonmark/lib/definition.js","mod::btw/node_modules/micromark-core-commonmark/lib/hard-break-escape.js","mod::btw/node_modules/micromark-core-commonmark/lib/heading-atx.js","mod::btw/node_modules/micromark-util-html-tag-name/index.js","mod::btw/node_modules/micromark-core-commonmark/lib/html-flow.js","mod::btw/node_modules/micromark-core-commonmark/lib/html-text.js","mod::btw/node_modules/micromark-core-commonmark/lib/label-end.js","mod::btw/node_modules/micromark-core-commonmark/lib/label-start-image.js","mod::btw/node_modules/micromark-core-commonmark/lib/label-start-link.js","mod::btw/node_modules/micromark-core-commonmark/lib/line-ending.js","mod::btw/node_modules/micromark-core-commonmark/lib/thematic-break.js","mod::btw/node_modules/micromark-core-commonmark/lib/list.js","mod::btw/node_modules/micromark-core-commonmark/lib/setext-underline.js","mod::btw/node_modules/micromark/lib/initialize/flow.js","mod::btw/node_modules/micromark/lib/initialize/text.js","mod::btw/node_modules/micromark/lib/constructs.js","mod::btw/node_modules/micromark/lib/create-tokenizer.js","mod::btw/node_modules/micromark/lib/parse.js","mod::btw/node_modules/micromark/lib/postprocess.js","mod::btw/node_modules/micromark/lib/preprocess.js","mod::btw/node_modules/micromark-util-decode-string/index.js","mod::btw/node_modules/mdast-util-from-markdown/lib/index.js","mod::btw/node_modules/remark-parse/lib/index.js","mod::btw/node_modules/ccount/index.js","mod::btw/node_modules/escape-string-regexp/index.js","mod::btw/node_modules/unist-util-is/lib/index.js","mod::btw/node_modules/unist-util-visit-parents/lib/index.js","mod::btw/node_modules/mdast-util-find-and-replace/lib/index.js","mod::btw/node_modules/mdast-util-gfm-autolink-literal/lib/index.js","mod::btw/node_modules/mdast-util-gfm-footnote/lib/index.js","mod::btw/node_modules/mdast-util-gfm-strikethrough/lib/index.js","mod::btw/node_modules/markdown-table/index.js","mod::btw/node_modules/zwitch/index.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/blockquote.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/pattern-in-scope.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/break.js","mod::btw/node_modules/longest-streak/index.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/format-code-as-indented.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/check-fence.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/code.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/check-quote.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/definition.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/check-emphasis.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/encode-character-reference.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/encode-info.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/emphasis.js","mod::btw/node_modules/unist-util-visit/lib/index.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/heading.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/html.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/image.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/image-reference.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/inline-code.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/format-link-as-autolink.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/link.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/link-reference.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/check-bullet.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/check-bullet-other.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/check-bullet-ordered.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/check-rule.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/list.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/check-list-item-indent.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/list-item.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/paragraph.js","mod::btw/node_modules/mdast-util-phrasing/lib/index.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/root.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/check-strong.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/strong.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/text.js","mod::btw/node_modules/mdast-util-to-markdown/lib/util/check-rule-repetition.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/thematic-break.js","mod::btw/node_modules/mdast-util-to-markdown/lib/handle/index.js","mod::btw/node_modules/mdast-util-gfm-table/lib/index.js","mod::btw/node_modules/mdast-util-gfm-task-list-item/lib/index.js","mod::btw/node_modules/mdast-util-gfm/lib/index.js","mod::btw/node_modules/micromark-extension-gfm-autolink-literal/lib/syntax.js","mod::btw/node_modules/micromark-extension-gfm-footnote/lib/syntax.js","mod::btw/node_modules/micromark-extension-gfm-strikethrough/lib/syntax.js","mod::btw/node_modules/micromark-extension-gfm-table/lib/edit-map.js","mod::btw/node_modules/micromark-extension-gfm-table/lib/infer.js","mod::btw/node_modules/micromark-extension-gfm-table/lib/syntax.js","mod::btw/node_modules/micromark-extension-gfm-task-list-item/lib/syntax.js","mod::btw/node_modules/micromark-extension-gfm/index.js","mod::btw/node_modules/remark-gfm/lib/index.js","mod::btw/node_modules/mdast-util-math/lib/index.js","mod::btw/node_modules/micromark-extension-math/lib/math-flow.js","mod::btw/node_modules/micromark-extension-math/lib/math-text.js","mod::btw/node_modules/micromark-extension-math/lib/syntax.js","mod::btw/node_modules/remark-math/lib/index.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/blockquote.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/break.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/code.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/delete.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/emphasis.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/footnote-reference.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/heading.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/html.js","mod::btw/node_modules/mdast-util-to-hast/lib/revert.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/image-reference.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/image.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/inline-code.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/link-reference.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/link.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/list-item.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/list.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/paragraph.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/root.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/strong.js","mod::btw/node_modules/unist-util-position/lib/index.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/table.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/table-row.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/table-cell.js","mod::btw/node_modules/trim-lines/index.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/text.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/thematic-break.js","mod::btw/node_modules/mdast-util-to-hast/lib/handlers/index.js","mod::btw/node_modules/@ungap/structured-clone/esm/deserialize.js","mod::btw/node_modules/@ungap/structured-clone/esm/serialize.js","mod::btw/node_modules/@ungap/structured-clone/esm/index.js","mod::btw/node_modules/mdast-util-to-hast/lib/footer.js","mod::btw/node_modules/mdast-util-to-hast/lib/state.js","mod::btw/node_modules/mdast-util-to-hast/lib/index.js","mod::btw/node_modules/remark-rehype/lib/index.js","mod::btw/node_modules/property-information/lib/util/schema.js","mod::btw/node_modules/property-information/lib/util/merge.js","mod::btw/node_modules/property-information/lib/normalize.js","mod::btw/node_modules/property-information/lib/util/info.js","mod::btw/node_modules/property-information/lib/util/types.js","mod::btw/node_modules/property-information/lib/util/defined-info.js","mod::btw/node_modules/property-information/lib/util/create.js","mod::btw/node_modules/property-information/lib/aria.js","mod::btw/node_modules/property-information/lib/util/case-sensitive-transform.js","mod::btw/node_modules/property-information/lib/util/case-insensitive-transform.js","mod::btw/node_modules/property-information/lib/html.js","mod::btw/node_modules/property-information/lib/svg.js","mod::btw/node_modules/property-information/lib/xlink.js","mod::btw/node_modules/property-information/lib/xmlns.js","mod::btw/node_modules/property-information/lib/xml.js","mod::btw/node_modules/property-information/lib/find.js","mod::btw/node_modules/property-information/index.js","mod::btw/node_modules/comma-separated-tokens/index.js","mod::btw/node_modules/hast-util-parse-selector/lib/index.js","mod::btw/node_modules/space-separated-tokens/index.js","mod::btw/node_modules/hastscript/lib/create-h.js","mod::btw/node_modules/hastscript/lib/svg-case-sensitive-tag-names.js","mod::btw/node_modules/hastscript/lib/index.js","mod::btw/node_modules/web-namespaces/index.js","mod::btw/node_modules/hast-util-from-dom/lib/index.js","mod::btw/node_modules/hast-util-from-html-isomorphic/lib/browser.js","mod::btw/node_modules/unist-util-find-after/lib/index.js","mod::btw/node_modules/hast-util-is-element/lib/index.js","mod::btw/node_modules/hast-util-to-text/lib/index.js","mod::btw/node_modules/rehype-katex/lib/index.js","mod::btw/node_modules/@shikijs/types/dist/index.mjs","mod::btw/node_modules/@shikijs/vscode-textmate/dist/index.js","mod::btw/node_modules/html-void-elements/index.js","mod::btw/node_modules/stringify-entities/lib/core.js","mod::btw/node_modules/stringify-entities/lib/util/to-hexadecimal.js","mod::btw/node_modules/stringify-entities/lib/util/to-decimal.js","mod::btw/node_modules/character-entities-legacy/index.js","mod::btw/node_modules/character-entities-html4/index.js","mod::btw/node_modules/stringify-entities/lib/constant/dangerous.js","mod::btw/node_modules/stringify-entities/lib/util/to-named.js","mod::btw/node_modules/stringify-entities/lib/util/format-smart.js","mod::btw/node_modules/stringify-entities/lib/index.js","mod::btw/node_modules/hast-util-to-html/lib/handle/comment.js","mod::btw/node_modules/hast-util-to-html/lib/handle/doctype.js","mod::btw/node_modules/hast-util-whitespace/lib/index.js","mod::btw/node_modules/hast-util-to-html/lib/omission/util/siblings.js","mod::btw/node_modules/hast-util-to-html/lib/omission/omission.js","mod::btw/node_modules/hast-util-to-html/lib/omission/closing.js","mod::btw/node_modules/hast-util-to-html/lib/omission/opening.js","mod::btw/node_modules/hast-util-to-html/lib/handle/element.js","mod::btw/node_modules/hast-util-to-html/lib/handle/text.js","mod::btw/node_modules/hast-util-to-html/lib/handle/raw.js","mod::btw/node_modules/hast-util-to-html/lib/handle/root.js","mod::btw/node_modules/hast-util-to-html/lib/handle/index.js","mod::btw/node_modules/hast-util-to-html/lib/index.js","mod::btw/node_modules/@shikijs/core/dist/index.mjs","mod::btw/node_modules/oniguruma-parser/src/utils.ts","mod::btw/node_modules/oniguruma-parser/src/tokenizer/tokenize.ts","mod::btw/node_modules/oniguruma-parser/src/parser/node-utils.ts","mod::btw/node_modules/oniguruma-parser/src/parser/parse.ts","mod::btw/node_modules/oniguruma-parser/src/traverser/traverse.ts","mod::btw/node_modules/regex/src/utils-internals.js","mod::btw/node_modules/regex-utilities/src/index.js","mod::btw/node_modules/regex/src/atomic.js","mod::btw/node_modules/regex-recursion/src/index.js","mod::btw/node_modules/oniguruma-to-es/src/utils.js","mod::btw/node_modules/oniguruma-to-es/src/options.js","mod::btw/node_modules/oniguruma-to-es/src/unicode.js","mod::btw/node_modules/oniguruma-to-es/src/transform.js","mod::btw/node_modules/oniguruma-to-es/src/generate.js","mod::btw/node_modules/oniguruma-to-es/src/subclass.js","mod::btw/node_modules/oniguruma-to-es/src/index.js","mod::btw/node_modules/@shikijs/engine-javascript/dist/shared/engine-javascript.hzpS1_41.mjs","mod::btw/node_modules/@shikijs/engine-javascript/dist/engine-compile.mjs","mod::btw/node_modules/@shikijs/themes/dist/github-light.mjs","mod::btw/node_modules/@shikijs/themes/dist/github-dark.mjs","mod::btw/node_modules/streamdown-vue/dist/index.es.js","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/SidebarNavigation.vue","mod::btw/webdesigns/btwcoach/frontend/lib/useTheme.ts","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ThemeToggle.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ThemeToggle.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/ThemeToggle.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/FieldError.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/FieldError.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/SidebarNavigation.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/SidebarNavigation.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ResizableDialog.vue","mod::btw/webdesigns/btwcoach/frontend/lib/usePersistedSize.ts","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ResizableDialog.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/ResizableDialog.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/Sidebar.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/Sidebar.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/PromptInput.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/PromptInput.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/PromptInput.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/MessageItem.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/Reasoning.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/Reasoning.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/Reasoning.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChainOfThought.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/SourceBadge.vue","mod::btw/webdesigns/btwcoach/frontend/lib/citations.ts","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/SourceBadge.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/SourceBadge.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChainOfThought.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/ChainOfThought.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/CitationLink.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/CitationLink.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/CitationLink.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/MessageActions.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/MessageActions.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/MessageActions.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/MessageItem.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/MessageItem.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/TestModePicker.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/TestModePicker.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/FeedbackDialog.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/FeedbackDialog.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/FeedbackDialog.vue","mod::btw/webdesigns/btwcoach/frontend/lib/chat.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/ai-sdk-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/api-call-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/empty-response-body-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/evaluation-unsupported-question-type-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/get-error-message.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/invalid-argument-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/invalid-prompt-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/invalid-response-data-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/json-parse-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/load-api-key-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/load-setting-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/no-content-generated-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/no-such-model-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/no-such-provider-reference-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/too-many-embedding-values-for-call-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/type-validation-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/errors/unsupported-functionality-error.ts","mod::btw/node_modules/@ai-sdk/provider/src/json-value/is-json.ts","mod::btw/node_modules/zod/v4/core/core.js","mod::btw/node_modules/zod/v4/core/util.js","mod::btw/node_modules/zod/v4/core/errors.js","mod::btw/node_modules/zod/v4/core/parse.js","mod::btw/node_modules/zod/v4/core/regexes.js","mod::btw/node_modules/zod/v4/core/checks.js","mod::btw/node_modules/zod/v4/core/doc.js","mod::btw/node_modules/zod/v4/core/versions.js","mod::btw/node_modules/zod/v4/core/schemas.js","mod::btw/node_modules/zod/v4/core/registries.js","mod::btw/node_modules/zod/v4/core/api.js","mod::btw/node_modules/zod/v4/core/to-json-schema.js","mod::btw/node_modules/zod/v4/core/json-schema-processors.js","mod::btw/node_modules/zod/v4/classic/iso.js","mod::btw/node_modules/zod/v4/classic/errors.js","mod::btw/node_modules/zod/v4/classic/parse.js","mod::btw/node_modules/zod/v4/classic/schemas.js","mod::btw/node_modules/eventsource-parser/src/errors.ts","mod::btw/node_modules/eventsource-parser/src/parse.ts","mod::btw/node_modules/eventsource-parser/src/stream.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/as-array.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/combine-headers.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/remove-undefined-entries.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/delay.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/websocket.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/connect-to-websocket.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/convert-async-iterator-to-readable-stream.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/convert-inline-file-data-to-uint8-array.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/uint8-utils.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/convert-image-model-file-to-data-uri.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/convert-to-form-data.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/create-language-model-response-metadata.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/create-null-language-model-usage.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/create-tool-name-mapping.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/create-provider-stream-error.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/delayed-promise.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/delete-from-api.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/extract-response-headers.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/get-runtime-environment-user-agent.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/handle-fetch-error.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/is-abort-error.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/version.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/normalize-headers.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/with-user-agent-suffix.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/detect-media-type.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/cancel-response-body.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/download-error.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/is-browser-runtime.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/is-same-origin.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/validate-download-url.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/safe-node-fetch.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/sanitize-request-headers.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/fetch-with-validated-redirects.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/read-response-with-size-limit.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/download-blob.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/embedding-model-capabilities.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/extract-lines.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/filter-nullable.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/generate-id.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/get-error-message.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/get-from-api.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/inject-json-instruction.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/is-buffer.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/is-non-nullable.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/is-provider-reference.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/is-record.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/is-url-supported.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/load-api-key.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/load-optional-setting.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/load-setting.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/map-reasoning-to-provider.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/media-type-to-extension.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/normalize-batch-request-counts.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/parse-json.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/secure-json-parse.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/validate-types.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/schema.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/add-additional-properties-to-json-schema.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/options.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/any.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/array.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/branded.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/catch.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/date.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/default.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/effects.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/enum.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/literal.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/string.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/record.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/map.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/never.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/null.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/union.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/number.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/object.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/optional.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/promise.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/set.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/select-parser.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/get-relative-path.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/parse-def.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/refs.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/parse-json-event-stream.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/parse-provider-options.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/post-multipart-stream-to-api.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/post-to-api.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/types/tool.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/provider-defined-tool-factory.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/provider-executed-tool-factory.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/resolve.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/resolve-full-media-type.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/resolve-provider-reference.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/retry-with-exponential-backoff.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/response-handler.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/is-json-serializable.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/serialization-error.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/serialize-model-options.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/streaming-tool-call-tracker.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/strip-file-extension.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/transcription-stream-envelope.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/validate-base-url.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/without-trailing-slash.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/types/executable-tool.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/is-async-iterable.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/types/execute-tool.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/types/tool-caller.ts","mod::btw/node_modules/@ai-sdk/provider-utils/src/index.ts","mod::btw/node_modules/ai/src/index.ts","mod::btw/node_modules/ai/src/agent/tool-loop-agent.ts","mod::btw/node_modules/ai/src/generate-text/generate-text.ts","mod::btw/node_modules/ai/src/error/index.ts","mod::btw/node_modules/ai/src/error/invalid-argument-error.ts","mod::btw/node_modules/ai/src/error/invalid-stream-part-error.ts","mod::btw/node_modules/ai/src/error/invalid-tool-approval-error.ts","mod::btw/node_modules/ai/src/error/invalid-tool-approval-signature-error.ts","mod::btw/node_modules/ai/src/error/invalid-tool-input-error.ts","mod::btw/node_modules/ai/src/error/tool-call-not-found-for-approval-error.ts","mod::btw/node_modules/ai/src/error/missing-tool-result-error.ts","mod::btw/node_modules/ai/src/error/no-image-generated-error.ts","mod::btw/node_modules/ai/src/error/no-object-generated-error.ts","mod::btw/node_modules/ai/src/error/no-output-generated-error.ts","mod::btw/node_modules/ai/src/error/no-speech-generated-error.ts","mod::btw/node_modules/ai/src/error/no-transcript-generated-error.ts","mod::btw/node_modules/ai/src/error/no-translation-generated-error.ts","mod::btw/node_modules/ai/src/error/no-video-generated-error.ts","mod::btw/node_modules/ai/src/error/no-such-tool-error.ts","mod::btw/node_modules/ai/src/error/stream-provider-error.ts","mod::btw/node_modules/ai/src/error/tool-call-repair-error.ts","mod::btw/node_modules/ai/src/error/tool-choice-violation-error.ts","mod::btw/node_modules/ai/src/error/unsupported-model-version-error.ts","mod::btw/node_modules/ai/src/error/ui-message-stream-error.ts","mod::btw/node_modules/ai/src/prompt/invalid-data-content-error.ts","mod::btw/node_modules/ai/src/prompt/invalid-message-role-error.ts","mod::btw/node_modules/ai/src/prompt/message-conversion-error.ts","mod::btw/node_modules/ai/src/util/retry-error.ts","mod::btw/node_modules/ai/src/logger/log-warnings.ts","mod::btw/node_modules/ai/src/model/resolve-model.ts","mod::btw/node_modules/ai/src/util/log-v2-compatibility-warning.ts","mod::btw/node_modules/ai/src/model/as-embedding-model-v3.ts","mod::btw/node_modules/ai/src/model/as-embedding-model-v4.ts","mod::btw/node_modules/ai/src/model/as-image-model-v3.ts","mod::btw/node_modules/ai/src/model/as-image-model-v4.ts","mod::btw/node_modules/ai/src/model/as-language-model-v3.ts","mod::btw/node_modules/ai/src/model/as-language-model-v4.ts","mod::btw/node_modules/ai/src/model/as-reranking-model-v4.ts","mod::btw/node_modules/ai/src/model/as-speech-model-v3.ts","mod::btw/node_modules/ai/src/model/as-speech-model-v4.ts","mod::btw/node_modules/ai/src/model/as-transcription-model-v3.ts","mod::btw/node_modules/ai/src/model/as-transcription-model-v4.ts","mod::btw/node_modules/ai/src/model/as-video-model-v4.ts","mod::btw/node_modules/ai/src/model/as-provider-v3.ts","mod::btw/node_modules/ai/src/model/as-provider-v4.ts","mod::btw/node_modules/ai/src/prompt/clone-model-message.ts","mod::btw/node_modules/ai/src/prompt/convert-to-language-model-prompt.ts","mod::btw/node_modules/ai/src/util/download/download.ts","mod::btw/node_modules/ai/src/version.ts","mod::btw/node_modules/ai/src/util/download/download-function.ts","mod::btw/node_modules/ai/src/util/merge-objects.ts","mod::btw/node_modules/ai/src/prompt/file-part-data.ts","mod::btw/node_modules/ai/src/prompt/split-data-url.ts","mod::btw/node_modules/ai/src/prompt/create-tool-model-output.ts","mod::btw/node_modules/ai/src/prompt/prepare-language-model-call-options.ts","mod::btw/node_modules/ai/src/prompt/prepare-tool-choice.ts","mod::btw/node_modules/ai/src/prompt/prepare-tools.ts","mod::btw/node_modules/ai/src/util/is-non-empty-object.ts","mod::btw/node_modules/ai/src/prompt/request-options.ts","mod::btw/node_modules/ai/src/prompt/standardize-prompt.ts","mod::btw/node_modules/ai/src/util/zod.ts","mod::btw/node_modules/ai/src/types/json-value.ts","mod::btw/node_modules/ai/src/types/provider-metadata.ts","mod::btw/node_modules/ai/src/prompt/content-part.ts","mod::btw/node_modules/ai/src/prompt/message.ts","mod::btw/node_modules/ai/src/prompt/wrap-gateway-error.ts","mod::btw/node_modules/ai/src/types/usage.ts","mod::btw/node_modules/ai/src/util/get-own.ts","mod::btw/node_modules/ai/src/util/merge-abort-signals.ts","mod::btw/node_modules/ai/src/util/now.ts","mod::btw/node_modules/ai/src/util/notify.ts","mod::btw/node_modules/ai/src/util/retry-with-exponential-backoff.ts","mod::btw/node_modules/ai/src/util/prepare-retries.ts","mod::btw/node_modules/ai/src/util/set-abort-timeout.ts","mod::btw/node_modules/ai/src/generate-text/calculate-tokens-per-second.ts","mod::btw/node_modules/ai/src/generate-text/collect-tool-approvals.ts","mod::btw/node_modules/ai/src/generate-text/generated-file.ts","mod::btw/node_modules/ai/src/generate-text/convert-language-model-content.ts","mod::btw/node_modules/ai/src/tool-search/prepare-tool-search.ts","mod::btw/node_modules/ai/src/generate-text/tool-caller-configuration.ts","mod::btw/node_modules/ai/src/tool-search/tool-search.ts","mod::btw/node_modules/ai/src/generate-text/execute-tool-call.ts","mod::btw/node_modules/ai/src/generate-text/validate-tool-context.ts","mod::btw/node_modules/ai/src/generate-text/filter-active-tools.ts","mod::btw/node_modules/ai/src/generate-text/is-tool-execution-allowed-finish-reason.ts","mod::btw/node_modules/ai/src/generate-text/output.ts","mod::btw/node_modules/ai/src/util/parse-partial-json.ts","mod::btw/node_modules/ai/src/util/fix-json.ts","mod::btw/node_modules/ai/src/generate-text/parse-tool-call.ts","mod::btw/node_modules/ai/src/generate-text/prepare-step-call-settings.ts","mod::btw/node_modules/ai/src/generate-text/reasoning-output.ts","mod::btw/node_modules/ai/src/generate-text/resolve-tool-approval.ts","mod::btw/node_modules/ai/src/telemetry/filter-included-context.ts","mod::btw/node_modules/ai/src/telemetry/create-telemetry-dispatcher.ts","mod::btw/node_modules/ai/src/util/merge-callbacks.ts","mod::btw/node_modules/ai/src/telemetry/tracing-channel.ts","mod::btw/node_modules/ai/src/util/is-node-runtime.ts","mod::btw/node_modules/ai/src/telemetry/tracing-channel-publisher.ts","mod::btw/node_modules/ai/src/telemetry/telemetry-registry.ts","mod::btw/node_modules/ai/src/generate-text/reasoning.ts","mod::btw/node_modules/ai/src/generate-text/step-result.ts","mod::btw/node_modules/ai/src/generate-text/restricted-telemetry-dispatcher.ts","mod::btw/node_modules/ai/src/generate-text/stop-condition.ts","mod::btw/node_modules/ai/src/generate-text/sum-token-counts.ts","mod::btw/node_modules/ai/src/generate-text/to-response-messages.ts","mod::btw/node_modules/ai/src/generate-text/tool-approval-signature.ts","mod::btw/node_modules/ai/src/util/canonical-hash.ts","mod::btw/node_modules/ai/src/generate-text/validate-tool-approvals.ts","mod::btw/node_modules/ai/src/generate-text/stream-text.ts","mod::btw/node_modules/ai/src/util/prepare-headers.ts","mod::btw/node_modules/ai/src/text-stream/create-text-stream-response.ts","mod::btw/node_modules/ai/src/util/write-to-server-response.ts","mod::btw/node_modules/ai/src/text-stream/pipe-text-stream-to-response.ts","mod::btw/node_modules/ai/src/text-stream/to-text-stream.ts","mod::btw/node_modules/ai/src/ui-message-stream/json-to-sse-transform-stream.ts","mod::btw/node_modules/ai/src/ui-message-stream/ui-message-stream-headers.ts","mod::btw/node_modules/ai/src/ui-message-stream/create-ui-message-stream-response.ts","mod::btw/node_modules/ai/src/ui-message-stream/pipe-ui-message-stream-to-response.ts","mod::btw/node_modules/ai/src/ui-message-stream/get-response-ui-message-id.ts","mod::btw/node_modules/ai/src/ui/process-ui-message-stream.ts","mod::btw/node_modules/ai/src/ui-message-stream/ui-message-chunks.ts","mod::btw/node_modules/ai/src/util/create-id-map.ts","mod::btw/node_modules/ai/src/ui/ui-messages.ts","mod::btw/node_modules/ai/src/ui/warn-if-ui-message-has-deprecated-raw-input.ts","mod::btw/node_modules/ai/src/ui-message-stream/handle-ui-message-stream-finish.ts","mod::btw/node_modules/ai/src/ui-message-stream/to-ui-message-chunk.ts","mod::btw/node_modules/ai/src/ui-message-stream/to-ui-message-stream.ts","mod::btw/node_modules/ai/src/util/async-iterable-stream.ts","mod::btw/node_modules/ai/src/util/consume-stream.ts","mod::btw/node_modules/ai/src/util/create-resolvable-promise.ts","mod::btw/node_modules/ai/src/util/create-stitchable-stream.ts","mod::btw/node_modules/ai/src/generate-text/stream-retry-attempt-boundary.ts","mod::btw/node_modules/ai/src/generate-text/execute-tools-from-stream.ts","mod::btw/node_modules/ai/src/generate-text/invoke-tool-callbacks-from-stream.ts","mod::btw/node_modules/ai/src/generate-text/stream-language-model-call.ts","mod::btw/node_modules/ai/src/prompt/normalize-stream-provider-error.ts","mod::btw/node_modules/ai/src/ui-message-stream/create-ui-message-stream.ts","mod::btw/node_modules/ai/src/ui-message-stream/read-ui-message-stream.ts","mod::btw/node_modules/ai/src/ui/convert-to-model-messages.ts","mod::btw/node_modules/ai/src/ui/validate-ui-messages.ts","mod::btw/node_modules/ai/src/agent/create-agent-ui-stream.ts","mod::btw/node_modules/ai/src/agent/create-agent-ui-stream-response.ts","mod::btw/node_modules/ai/src/agent/pipe-agent-ui-stream-to-response.ts","mod::btw/node_modules/ai/src/batch/batch.ts","mod::btw/node_modules/ai/src/generate-image/generate-image.ts","mod::btw/node_modules/ai/src/prompt/data-content.ts","mod::btw/node_modules/ai/src/util/is-deep-equal-data.ts","mod::btw/node_modules/ai/src/embed/embed.ts","mod::btw/node_modules/ai/src/embed/restricted-telemetry-dispatcher.ts","mod::btw/node_modules/ai/src/embed/embed-many.ts","mod::btw/node_modules/ai/src/model/get-embedding-model-max-input-bytes-per-call.ts","mod::btw/node_modules/ai/src/util/split-array.ts","mod::btw/node_modules/ai/src/evaluate/evaluate.ts","mod::btw/node_modules/ai/src/evaluate/validate-evaluation.ts","mod::btw/node_modules/ai/src/generate-object/generate-object.ts","mod::btw/node_modules/ai/src/generate-text/extract-reasoning-content.ts","mod::btw/node_modules/ai/src/generate-text/extract-text-content.ts","mod::btw/node_modules/ai/src/generate-object/output-strategy.ts","mod::btw/node_modules/ai/src/generate-object/parse-and-validate-object-result.ts","mod::btw/node_modules/ai/src/generate-object/validate-object-generation-input.ts","mod::btw/node_modules/ai/src/generate-object/stream-object.ts","mod::btw/node_modules/ai/src/util/cosine-similarity.ts","mod::btw/node_modules/ai/src/util/download/create-download.ts","mod::btw/node_modules/ai/src/util/data-url.ts","mod::btw/node_modules/ai/src/util/serial-job-executor.ts","mod::btw/node_modules/ai/src/util/simulate-readable-stream.ts","mod::btw/node_modules/ai/src/generate-speech/generate-speech.ts","mod::btw/node_modules/ai/src/generate-speech/generated-audio-file.ts","mod::btw/node_modules/ai/src/generate-speech/index.ts","mod::btw/node_modules/ai/src/generate-text/prune-messages.ts","mod::btw/node_modules/ai/src/generate-text/smooth-stream.ts","mod::btw/node_modules/ai/src/generate-text/tool-fingerprint.ts","mod::btw/node_modules/ai/src/generate-video/generate-video.ts","mod::btw/node_modules/ai/src/generate-video/start-video.ts","mod::btw/node_modules/ai/src/generate-video/get-video-status.ts","mod::btw/node_modules/ai/src/middleware/default-embedding-settings-middleware.ts","mod::btw/node_modules/ai/src/middleware/default-instructions-middleware.ts","mod::btw/node_modules/ai/src/middleware/default-settings-middleware.ts","mod::btw/node_modules/ai/src/middleware/extract-json-middleware.ts","mod::btw/node_modules/ai/src/util/get-potential-start-index.ts","mod::btw/node_modules/ai/src/middleware/extract-reasoning-middleware.ts","mod::btw/node_modules/ai/src/middleware/simulate-streaming-middleware.ts","mod::btw/node_modules/ai/src/middleware/add-tool-input-examples-middleware.ts","mod::btw/node_modules/ai/src/middleware/wrap-language-model.ts","mod::btw/node_modules/ai/src/middleware/wrap-embedding-model.ts","mod::btw/node_modules/ai/src/middleware/wrap-image-model.ts","mod::btw/node_modules/ai/src/middleware/wrap-provider.ts","mod::btw/node_modules/ai/src/realtime/audio-utils.ts","mod::btw/node_modules/ai/src/realtime/get-realtime-tool-definitions.ts","mod::btw/node_modules/ai/src/realtime/realtime-session.ts","mod::btw/node_modules/ai/src/realtime/browser-realtime-audio.ts","mod::btw/node_modules/ai/src/realtime/realtime-event-channel.ts","mod::btw/node_modules/ai/src/realtime/encode-realtime-frame.ts","mod::btw/node_modules/ai/src/realtime/browser-realtime-transport.ts","mod::btw/node_modules/ai/src/realtime/browser-realtime-live-websocket.ts","mod::btw/node_modules/ai/src/realtime/browser-realtime-webrtc.ts","mod::btw/node_modules/ai/src/realtime/realtime-attempt.ts","mod::btw/node_modules/ai/src/realtime/realtime-command-tracker.ts","mod::btw/node_modules/ai/src/realtime/validate-realtime-setup.ts","mod::btw/node_modules/ai/src/realtime/realtime-session-state.ts","mod::btw/node_modules/ai/src/realtime/realtime-event-reducer.ts","mod::btw/node_modules/ai/src/registry/custom-provider.ts","mod::btw/node_modules/ai/src/registry/no-such-provider-error.ts","mod::btw/node_modules/ai/src/registry/provider-registry.ts","mod::btw/node_modules/ai/src/rerank/rerank.ts","mod::btw/node_modules/ai/src/rerank/restricted-telemetry-dispatcher.ts","mod::btw/node_modules/ai/src/transcribe/transcribe.ts","mod::btw/node_modules/ai/src/transcribe/stream-transcribe.ts","mod::btw/node_modules/ai/src/transcribe/index.ts","mod::btw/node_modules/ai/src/translate/stream-translate.ts","mod::btw/node_modules/ai/src/ui/call-completion-api.ts","mod::btw/node_modules/ai/src/ui/create-ui-api-call-error.ts","mod::btw/node_modules/ai/src/ui/process-text-stream.ts","mod::btw/node_modules/ai/src/ui/chat.ts","mod::btw/node_modules/ai/src/ui/convert-file-list-to-file-ui-parts.ts","mod::btw/node_modules/ai/src/ui/default-chat-transport.ts","mod::btw/node_modules/ai/src/ui/http-chat-transport.ts","mod::btw/node_modules/ai/src/ui/direct-chat-transport.ts","mod::btw/node_modules/ai/src/ui/last-assistant-message-is-complete-with-approval-responses.ts","mod::btw/node_modules/ai/src/ui/last-assistant-message-is-complete-with-tool-calls.ts","mod::btw/node_modules/ai/src/ui/transform-text-to-ui-message-stream.ts","mod::btw/node_modules/ai/src/ui/text-stream-chat-transport.ts","mod::btw/node_modules/ai/src/upload-file/upload-file.ts","mod::btw/node_modules/ai/src/upload-skill/upload-skill.ts","mod::btw/node_modules/swrv/src/lib/hash.ts","mod::btw/node_modules/swrv/src/cache/index.ts","mod::btw/node_modules/swrv/src/use-swrv.ts","mod::btw/node_modules/swrv/src/lib/web-preset.ts","mod::btw/node_modules/swrv/src/index.ts","mod::btw/node_modules/@ai-sdk/vue/src/use-object.ts","mod::btw/node_modules/@ai-sdk/vue/src/use-completion.ts","mod::btw/node_modules/@ai-sdk/vue/src/chat.vue.ts","mod::btw/node_modules/@ai-sdk/vue/src/use-chat.ts","mod::btw/node_modules/@ai-sdk/vue/src/index.ts","mod::btw/webdesigns/btwcoach/frontend/lib/api.ts","mod::btw/webdesigns/btwcoach/frontend/lib/chatAuth.ts","mod::btw/webdesigns/btwcoach/frontend/lib/chatGateway.ts","mod::btw/webdesigns/btwcoach/frontend/lib/chatHistory.ts","mod::btw/webdesigns/btwcoach/frontend/lib/meta.ts","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChatView.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/ChatView.vue","mod::btw/webdesigns/btwcoach/frontend/lib/useConversationHistory.ts","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChatWorkspace.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/ChatWorkspace.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/LoginForm.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/CodeInput.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/CodeInput.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/CodeInput.vue","mod::btw/webdesigns/btwcoach/frontend/lib/useLoginCode.ts","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/LoginForm.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/components/LoginForm.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/App.vue","/opt/whdata/generated/platform/ap/btw.btwcoach/build/sfc-template:/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/App.vue?type=template","mod::btw/webdesigns/btwcoach/frontend/App.vue","/entrypoint.js"],"sourcesContent":["/**\n* @vue/shared v3.5.18\n* (c) 2018-present Yuxi (Evan) You and Vue contributors\n* @license MIT\n**/\n'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n/*! #__NO_SIDE_EFFECTS__ */\n// @__NO_SIDE_EFFECTS__\nfunction makeMap(str) {\n  const map = /* @__PURE__ */ Object.create(null);\n  for (const key of str.split(\",\")) map[key] = 1;\n  return (val) => val in map;\n}\n\nconst EMPTY_OBJ = {};\nconst EMPTY_ARR = [];\nconst NOOP = () => {\n};\nconst NO = () => false;\nconst isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter\n(key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97);\nconst isModelListener = (key) => key.startsWith(\"onUpdate:\");\nconst extend = Object.assign;\nconst remove = (arr, el) => {\n  const i = arr.indexOf(el);\n  if (i > -1) {\n    arr.splice(i, 1);\n  }\n};\nconst hasOwnProperty = Object.prototype.hasOwnProperty;\nconst hasOwn = (val, key) => hasOwnProperty.call(val, key);\nconst isArray = Array.isArray;\nconst isMap = (val) => toTypeString(val) === \"[object Map]\";\nconst isSet = (val) => toTypeString(val) === \"[object Set]\";\nconst isDate = (val) => toTypeString(val) === \"[object Date]\";\nconst isRegExp = (val) => toTypeString(val) === \"[object RegExp]\";\nconst isFunction = (val) => typeof val === \"function\";\nconst isString = (val) => typeof val === \"string\";\nconst isSymbol = (val) => typeof val === \"symbol\";\nconst isObject = (val) => val !== null && typeof val === \"object\";\nconst isPromise = (val) => {\n  return (isObject(val) || isFunction(val)) && isFunction(val.then) && isFunction(val.catch);\n};\nconst objectToString = Object.prototype.toString;\nconst toTypeString = (value) => objectToString.call(value);\nconst toRawType = (value) => {\n  return toTypeString(value).slice(8, -1);\n};\nconst isPlainObject = (val) => toTypeString(val) === \"[object Object]\";\nconst isIntegerKey = (key) => isString(key) && key !== \"NaN\" && key[0] !== \"-\" && \"\" + parseInt(key, 10) === key;\nconst isReservedProp = /* @__PURE__ */ makeMap(\n  // the leading comma is intentional so empty string \"\" is also included\n  \",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted\"\n);\nconst isBuiltInDirective = /* @__PURE__ */ makeMap(\n  \"bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo\"\n);\nconst cacheStringFunction = (fn) => {\n  const cache = /* @__PURE__ */ Object.create(null);\n  return (str) => {\n    const hit = cache[str];\n    return hit || (cache[str] = fn(str));\n  };\n};\nconst camelizeRE = /-(\\w)/g;\nconst camelize = cacheStringFunction(\n  (str) => {\n    return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : \"\");\n  }\n);\nconst hyphenateRE = /\\B([A-Z])/g;\nconst hyphenate = cacheStringFunction(\n  (str) => str.replace(hyphenateRE, \"-$1\").toLowerCase()\n);\nconst capitalize = cacheStringFunction((str) => {\n  return str.charAt(0).toUpperCase() + str.slice(1);\n});\nconst toHandlerKey = cacheStringFunction(\n  (str) => {\n    const s = str ? `on${capitalize(str)}` : ``;\n    return s;\n  }\n);\nconst hasChanged = (value, oldValue) => !Object.is(value, oldValue);\nconst invokeArrayFns = (fns, ...arg) => {\n  for (let i = 0; i < fns.length; i++) {\n    fns[i](...arg);\n  }\n};\nconst def = (obj, key, value, writable = false) => {\n  Object.defineProperty(obj, key, {\n    configurable: true,\n    enumerable: false,\n    writable,\n    value\n  });\n};\nconst looseToNumber = (val) => {\n  const n = parseFloat(val);\n  return isNaN(n) ? val : n;\n};\nconst toNumber = (val) => {\n  const n = isString(val) ? Number(val) : NaN;\n  return isNaN(n) ? val : n;\n};\nlet _globalThis;\nconst getGlobalThis = () => {\n  return _globalThis || (_globalThis = typeof globalThis !== \"undefined\" ? globalThis : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : typeof global !== \"undefined\" ? global : {});\n};\nconst identRE = /^[_$a-zA-Z\\xA0-\\uFFFF][_$a-zA-Z0-9\\xA0-\\uFFFF]*$/;\nfunction genPropsAccessExp(name) {\n  return identRE.test(name) ? `__props.${name}` : `__props[${JSON.stringify(name)}]`;\n}\nfunction genCacheKey(source, options) {\n  return source + JSON.stringify(\n    options,\n    (_, val) => typeof val === \"function\" ? val.toString() : val\n  );\n}\n\nconst PatchFlags = {\n  \"TEXT\": 1,\n  \"1\": \"TEXT\",\n  \"CLASS\": 2,\n  \"2\": \"CLASS\",\n  \"STYLE\": 4,\n  \"4\": \"STYLE\",\n  \"PROPS\": 8,\n  \"8\": \"PROPS\",\n  \"FULL_PROPS\": 16,\n  \"16\": \"FULL_PROPS\",\n  \"NEED_HYDRATION\": 32,\n  \"32\": \"NEED_HYDRATION\",\n  \"STABLE_FRAGMENT\": 64,\n  \"64\": \"STABLE_FRAGMENT\",\n  \"KEYED_FRAGMENT\": 128,\n  \"128\": \"KEYED_FRAGMENT\",\n  \"UNKEYED_FRAGMENT\": 256,\n  \"256\": \"UNKEYED_FRAGMENT\",\n  \"NEED_PATCH\": 512,\n  \"512\": \"NEED_PATCH\",\n  \"DYNAMIC_SLOTS\": 1024,\n  \"1024\": \"DYNAMIC_SLOTS\",\n  \"DEV_ROOT_FRAGMENT\": 2048,\n  \"2048\": \"DEV_ROOT_FRAGMENT\",\n  \"CACHED\": -1,\n  \"-1\": \"CACHED\",\n  \"BAIL\": -2,\n  \"-2\": \"BAIL\"\n};\nconst PatchFlagNames = {\n  [1]: `TEXT`,\n  [2]: `CLASS`,\n  [4]: `STYLE`,\n  [8]: `PROPS`,\n  [16]: `FULL_PROPS`,\n  [32]: `NEED_HYDRATION`,\n  [64]: `STABLE_FRAGMENT`,\n  [128]: `KEYED_FRAGMENT`,\n  [256]: `UNKEYED_FRAGMENT`,\n  [512]: `NEED_PATCH`,\n  [1024]: `DYNAMIC_SLOTS`,\n  [2048]: `DEV_ROOT_FRAGMENT`,\n  [-1]: `CACHED`,\n  [-2]: `BAIL`\n};\n\nconst ShapeFlags = {\n  \"ELEMENT\": 1,\n  \"1\": \"ELEMENT\",\n  \"FUNCTIONAL_COMPONENT\": 2,\n  \"2\": \"FUNCTIONAL_COMPONENT\",\n  \"STATEFUL_COMPONENT\": 4,\n  \"4\": \"STATEFUL_COMPONENT\",\n  \"TEXT_CHILDREN\": 8,\n  \"8\": \"TEXT_CHILDREN\",\n  \"ARRAY_CHILDREN\": 16,\n  \"16\": \"ARRAY_CHILDREN\",\n  \"SLOTS_CHILDREN\": 32,\n  \"32\": \"SLOTS_CHILDREN\",\n  \"TELEPORT\": 64,\n  \"64\": \"TELEPORT\",\n  \"SUSPENSE\": 128,\n  \"128\": \"SUSPENSE\",\n  \"COMPONENT_SHOULD_KEEP_ALIVE\": 256,\n  \"256\": \"COMPONENT_SHOULD_KEEP_ALIVE\",\n  \"COMPONENT_KEPT_ALIVE\": 512,\n  \"512\": \"COMPONENT_KEPT_ALIVE\",\n  \"COMPONENT\": 6,\n  \"6\": \"COMPONENT\"\n};\n\nconst SlotFlags = {\n  \"STABLE\": 1,\n  \"1\": \"STABLE\",\n  \"DYNAMIC\": 2,\n  \"2\": \"DYNAMIC\",\n  \"FORWARDED\": 3,\n  \"3\": \"FORWARDED\"\n};\nconst slotFlagsText = {\n  [1]: \"STABLE\",\n  [2]: \"DYNAMIC\",\n  [3]: \"FORWARDED\"\n};\n\nconst GLOBALS_ALLOWED = \"Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol\";\nconst isGloballyAllowed = /* @__PURE__ */ makeMap(GLOBALS_ALLOWED);\nconst isGloballyWhitelisted = isGloballyAllowed;\n\nconst range = 2;\nfunction generateCodeFrame(source, start = 0, end = source.length) {\n  start = Math.max(0, Math.min(start, source.length));\n  end = Math.max(0, Math.min(end, source.length));\n  if (start > end) return \"\";\n  let lines = source.split(/(\\r?\\n)/);\n  const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);\n  lines = lines.filter((_, idx) => idx % 2 === 0);\n  let count = 0;\n  const res = [];\n  for (let i = 0; i < lines.length; i++) {\n    count += lines[i].length + (newlineSequences[i] && newlineSequences[i].length || 0);\n    if (count >= start) {\n      for (let j = i - range; j <= i + range || end > count; j++) {\n        if (j < 0 || j >= lines.length) continue;\n        const line = j + 1;\n        res.push(\n          `${line}${\" \".repeat(Math.max(3 - String(line).length, 0))}|  ${lines[j]}`\n        );\n        const lineLength = lines[j].length;\n        const newLineSeqLength = newlineSequences[j] && newlineSequences[j].length || 0;\n        if (j === i) {\n          const pad = start - (count - (lineLength + newLineSeqLength));\n          const length = Math.max(\n            1,\n            end > count ? lineLength - pad : end - start\n          );\n          res.push(`   |  ` + \" \".repeat(pad) + \"^\".repeat(length));\n        } else if (j > i) {\n          if (end > count) {\n            const length = Math.max(Math.min(end - count, lineLength), 1);\n            res.push(`   |  ` + \"^\".repeat(length));\n          }\n          count += lineLength + newLineSeqLength;\n        }\n      }\n      break;\n    }\n  }\n  return res.join(\"\\n\");\n}\n\nfunction normalizeStyle(value) {\n  if (isArray(value)) {\n    const res = {};\n    for (let i = 0; i < value.length; i++) {\n      const item = value[i];\n      const normalized = isString(item) ? parseStringStyle(item) : normalizeStyle(item);\n      if (normalized) {\n        for (const key in normalized) {\n          res[key] = normalized[key];\n        }\n      }\n    }\n    return res;\n  } else if (isString(value) || isObject(value)) {\n    return value;\n  }\n}\nconst listDelimiterRE = /;(?![^(]*\\))/g;\nconst propertyDelimiterRE = /:([^]+)/;\nconst styleCommentRE = /\\/\\*[^]*?\\*\\//g;\nfunction parseStringStyle(cssText) {\n  const ret = {};\n  cssText.replace(styleCommentRE, \"\").split(listDelimiterRE).forEach((item) => {\n    if (item) {\n      const tmp = item.split(propertyDelimiterRE);\n      tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());\n    }\n  });\n  return ret;\n}\nfunction stringifyStyle(styles) {\n  if (!styles) return \"\";\n  if (isString(styles)) return styles;\n  let ret = \"\";\n  for (const key in styles) {\n    const value = styles[key];\n    if (isString(value) || typeof value === \"number\") {\n      const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key);\n      ret += `${normalizedKey}:${value};`;\n    }\n  }\n  return ret;\n}\nfunction normalizeClass(value) {\n  let res = \"\";\n  if (isString(value)) {\n    res = value;\n  } else if (isArray(value)) {\n    for (let i = 0; i < value.length; i++) {\n      const normalized = normalizeClass(value[i]);\n      if (normalized) {\n        res += normalized + \" \";\n      }\n    }\n  } else if (isObject(value)) {\n    for (const name in value) {\n      if (value[name]) {\n        res += name + \" \";\n      }\n    }\n  }\n  return res.trim();\n}\nfunction normalizeProps(props) {\n  if (!props) return null;\n  let { class: klass, style } = props;\n  if (klass && !isString(klass)) {\n    props.class = normalizeClass(klass);\n  }\n  if (style) {\n    props.style = normalizeStyle(style);\n  }\n  return props;\n}\n\nconst HTML_TAGS = \"html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot\";\nconst SVG_TAGS = \"svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view\";\nconst MATH_TAGS = \"annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics\";\nconst VOID_TAGS = \"area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr\";\nconst isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS);\nconst isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS);\nconst isMathMLTag = /* @__PURE__ */ makeMap(MATH_TAGS);\nconst isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS);\n\nconst specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;\nconst isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs);\nconst isBooleanAttr = /* @__PURE__ */ makeMap(\n  specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`\n);\nfunction includeBooleanAttr(value) {\n  return !!value || value === \"\";\n}\nconst unsafeAttrCharRE = /[>/=\"'\\u0009\\u000a\\u000c\\u0020]/;\nconst attrValidationCache = {};\nfunction isSSRSafeAttrName(name) {\n  if (attrValidationCache.hasOwnProperty(name)) {\n    return attrValidationCache[name];\n  }\n  const isUnsafe = unsafeAttrCharRE.test(name);\n  if (isUnsafe) {\n    console.error(`unsafe attribute name: ${name}`);\n  }\n  return attrValidationCache[name] = !isUnsafe;\n}\nconst propsToAttrMap = {\n  acceptCharset: \"accept-charset\",\n  className: \"class\",\n  htmlFor: \"for\",\n  httpEquiv: \"http-equiv\"\n};\nconst isKnownHtmlAttr = /* @__PURE__ */ makeMap(\n  `accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap`\n);\nconst isKnownSvgAttr = /* @__PURE__ */ makeMap(\n  `xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,color-interpolation-filters,color-profile,color-rendering,contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,overflow,overline-position,overline-thickness,panose-1,paint-order,path,pathLength,patternContentUnits,patternTransform,patternUnits,ping,pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,specularConstant,specularExponent,speed,spreadMethod,startOffset,stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,string,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,text-decoration,text-rendering,textLength,to,transform,transform-origin,type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan`\n);\nconst isKnownMathMLAttr = /* @__PURE__ */ makeMap(\n  `accent,accentunder,actiontype,align,alignmentscope,altimg,altimg-height,altimg-valign,altimg-width,alttext,bevelled,close,columnsalign,columnlines,columnspan,denomalign,depth,dir,display,displaystyle,encoding,equalcolumns,equalrows,fence,fontstyle,fontweight,form,frame,framespacing,groupalign,height,href,id,indentalign,indentalignfirst,indentalignlast,indentshift,indentshiftfirst,indentshiftlast,indextype,justify,largetop,largeop,lquote,lspace,mathbackground,mathcolor,mathsize,mathvariant,maxsize,minlabelspacing,mode,other,overflow,position,rowalign,rowlines,rowspan,rquote,rspace,scriptlevel,scriptminsize,scriptsizemultiplier,selection,separator,separators,shift,side,src,stackalign,stretchy,subscriptshift,superscriptshift,symmetric,voffset,width,widths,xlink:href,xlink:show,xlink:type,xmlns`\n);\nfunction isRenderableAttrValue(value) {\n  if (value == null) {\n    return false;\n  }\n  const type = typeof value;\n  return type === \"string\" || type === \"number\" || type === \"boolean\";\n}\n\nconst escapeRE = /[\"'&<>]/;\nfunction escapeHtml(string) {\n  const str = \"\" + string;\n  const match = escapeRE.exec(str);\n  if (!match) {\n    return str;\n  }\n  let html = \"\";\n  let escaped;\n  let index;\n  let lastIndex = 0;\n  for (index = match.index; index < str.length; index++) {\n    switch (str.charCodeAt(index)) {\n      case 34:\n        escaped = \"&quot;\";\n        break;\n      case 38:\n        escaped = \"&amp;\";\n        break;\n      case 39:\n        escaped = \"&#39;\";\n        break;\n      case 60:\n        escaped = \"&lt;\";\n        break;\n      case 62:\n        escaped = \"&gt;\";\n        break;\n      default:\n        continue;\n    }\n    if (lastIndex !== index) {\n      html += str.slice(lastIndex, index);\n    }\n    lastIndex = index + 1;\n    html += escaped;\n  }\n  return lastIndex !== index ? html + str.slice(lastIndex, index) : html;\n}\nconst commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g;\nfunction escapeHtmlComment(src) {\n  return src.replace(commentStripRE, \"\");\n}\nconst cssVarNameEscapeSymbolsRE = /[ !\"#$%&'()*+,./:;<=>?@[\\\\\\]^`{|}~]/g;\nfunction getEscapedCssVarName(key, doubleEscape) {\n  return key.replace(\n    cssVarNameEscapeSymbolsRE,\n    (s) => doubleEscape ? s === '\"' ? '\\\\\\\\\\\\\"' : `\\\\\\\\${s}` : `\\\\${s}`\n  );\n}\n\nfunction looseCompareArrays(a, b) {\n  if (a.length !== b.length) return false;\n  let equal = true;\n  for (let i = 0; equal && i < a.length; i++) {\n    equal = looseEqual(a[i], b[i]);\n  }\n  return equal;\n}\nfunction looseEqual(a, b) {\n  if (a === b) return true;\n  let aValidType = isDate(a);\n  let bValidType = isDate(b);\n  if (aValidType || bValidType) {\n    return aValidType && bValidType ? a.getTime() === b.getTime() : false;\n  }\n  aValidType = isSymbol(a);\n  bValidType = isSymbol(b);\n  if (aValidType || bValidType) {\n    return a === b;\n  }\n  aValidType = isArray(a);\n  bValidType = isArray(b);\n  if (aValidType || bValidType) {\n    return aValidType && bValidType ? looseCompareArrays(a, b) : false;\n  }\n  aValidType = isObject(a);\n  bValidType = isObject(b);\n  if (aValidType || bValidType) {\n    if (!aValidType || !bValidType) {\n      return false;\n    }\n    const aKeysCount = Object.keys(a).length;\n    const bKeysCount = Object.keys(b).length;\n    if (aKeysCount !== bKeysCount) {\n      return false;\n    }\n    for (const key in a) {\n      const aHasKey = a.hasOwnProperty(key);\n      const bHasKey = b.hasOwnProperty(key);\n      if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key])) {\n        return false;\n      }\n    }\n  }\n  return String(a) === String(b);\n}\nfunction looseIndexOf(arr, val) {\n  return arr.findIndex((item) => looseEqual(item, val));\n}\n\nconst isRef = (val) => {\n  return !!(val && val[\"__v_isRef\"] === true);\n};\nconst toDisplayString = (val) => {\n  return isString(val) ? val : val == null ? \"\" : isArray(val) || isObject(val) && (val.toString === objectToString || !isFunction(val.toString)) ? isRef(val) ? toDisplayString(val.value) : JSON.stringify(val, replacer, 2) : String(val);\n};\nconst replacer = (_key, val) => {\n  if (isRef(val)) {\n    return replacer(_key, val.value);\n  } else if (isMap(val)) {\n    return {\n      [`Map(${val.size})`]: [...val.entries()].reduce(\n        (entries, [key, val2], i) => {\n          entries[stringifySymbol(key, i) + \" =>\"] = val2;\n          return entries;\n        },\n        {}\n      )\n    };\n  } else if (isSet(val)) {\n    return {\n      [`Set(${val.size})`]: [...val.values()].map((v) => stringifySymbol(v))\n    };\n  } else if (isSymbol(val)) {\n    return stringifySymbol(val);\n  } else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {\n    return String(val);\n  }\n  return val;\n};\nconst stringifySymbol = (v, i = \"\") => {\n  var _a;\n  return (\n    // Symbol.description in es2019+ so we need to cast here to pass\n    // the lib: es2016 check\n    isSymbol(v) ? `Symbol(${(_a = v.description) != null ? _a : i})` : v\n  );\n};\n\nfunction normalizeCssVarValue(value) {\n  if (value == null) {\n    return \"initial\";\n  }\n  if (typeof value === \"string\") {\n    return value === \"\" ? \" \" : value;\n  }\n  return String(value);\n}\n\nexports.EMPTY_ARR = EMPTY_ARR;\nexports.EMPTY_OBJ = EMPTY_OBJ;\nexports.NO = NO;\nexports.NOOP = NOOP;\nexports.PatchFlagNames = PatchFlagNames;\nexports.PatchFlags = PatchFlags;\nexports.ShapeFlags = ShapeFlags;\nexports.SlotFlags = SlotFlags;\nexports.camelize = camelize;\nexports.capitalize = capitalize;\nexports.cssVarNameEscapeSymbolsRE = cssVarNameEscapeSymbolsRE;\nexports.def = def;\nexports.escapeHtml = escapeHtml;\nexports.escapeHtmlComment = escapeHtmlComment;\nexports.extend = extend;\nexports.genCacheKey = genCacheKey;\nexports.genPropsAccessExp = genPropsAccessExp;\nexports.generateCodeFrame = generateCodeFrame;\nexports.getEscapedCssVarName = getEscapedCssVarName;\nexports.getGlobalThis = getGlobalThis;\nexports.hasChanged = hasChanged;\nexports.hasOwn = hasOwn;\nexports.hyphenate = hyphenate;\nexports.includeBooleanAttr = includeBooleanAttr;\nexports.invokeArrayFns = invokeArrayFns;\nexports.isArray = isArray;\nexports.isBooleanAttr = isBooleanAttr;\nexports.isBuiltInDirective = isBuiltInDirective;\nexports.isDate = isDate;\nexports.isFunction = isFunction;\nexports.isGloballyAllowed = isGloballyAllowed;\nexports.isGloballyWhitelisted = isGloballyWhitelisted;\nexports.isHTMLTag = isHTMLTag;\nexports.isIntegerKey = isIntegerKey;\nexports.isKnownHtmlAttr = isKnownHtmlAttr;\nexports.isKnownMathMLAttr = isKnownMathMLAttr;\nexports.isKnownSvgAttr = isKnownSvgAttr;\nexports.isMap = isMap;\nexports.isMathMLTag = isMathMLTag;\nexports.isModelListener = isModelListener;\nexports.isObject = isObject;\nexports.isOn = isOn;\nexports.isPlainObject = isPlainObject;\nexports.isPromise = isPromise;\nexports.isRegExp = isRegExp;\nexports.isRenderableAttrValue = isRenderableAttrValue;\nexports.isReservedProp = isReservedProp;\nexports.isSSRSafeAttrName = isSSRSafeAttrName;\nexports.isSVGTag = isSVGTag;\nexports.isSet = isSet;\nexports.isSpecialBooleanAttr = isSpecialBooleanAttr;\nexports.isString = isString;\nexports.isSymbol = isSymbol;\nexports.isVoidTag = isVoidTag;\nexports.looseEqual = looseEqual;\nexports.looseIndexOf = looseIndexOf;\nexports.looseToNumber = looseToNumber;\nexports.makeMap = makeMap;\nexports.normalizeClass = normalizeClass;\nexports.normalizeCssVarValue = normalizeCssVarValue;\nexports.normalizeProps = normalizeProps;\nexports.normalizeStyle = normalizeStyle;\nexports.objectToString = objectToString;\nexports.parseStringStyle = parseStringStyle;\nexports.propsToAttrMap = propsToAttrMap;\nexports.remove = remove;\nexports.slotFlagsText = slotFlagsText;\nexports.stringifyStyle = stringifyStyle;\nexports.toDisplayString = toDisplayString;\nexports.toHandlerKey = toHandlerKey;\nexports.toNumber = toNumber;\nexports.toRawType = toRawType;\nexports.toTypeString = toTypeString;\n","'use strict'\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./dist/shared.cjs.prod.js')\n} else {\n  module.exports = require('./dist/shared.cjs.js')\n}\n",null,null,null,null,"export type Pos = {\n  start: number;\n};\n\n// These are used when `options.locations` is on, for the\n// `startLoc` and `endLoc` properties.\n\nexport class Position {\n  line: number;\n  column: number;\n  index: number;\n\n  constructor(line: number, col: number, index: number) {\n    this.line = line;\n    this.column = col;\n    this.index = index;\n  }\n}\n\nexport class SourceLocation {\n  start: Position;\n  end: Position;\n  filename: string;\n  identifierName: string | undefined | null;\n\n  constructor(start: Position, end?: Position) {\n    this.start = start;\n    // (may start as null, but initialized later)\n    this.end = end;\n  }\n}\n\n/**\n * creates a new position with a non-zero column offset from the given position.\n * This function should be only be used when we create AST node out of the token\n * boundaries, such as TemplateElement ends before tt.templateNonTail. This\n * function does not skip whitespaces.\n */\nexport function createPositionWithColumnOffset(\n  position: Position,\n  columnOffset: number,\n) {\n  const { line, column, index } = position;\n  return new Position(line, column + columnOffset, index + columnOffset);\n}\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\n\nconst code = \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\";\n\nexport default {\n  ImportMetaOutsideModule: {\n    message: `import.meta may appear only with 'sourceType: \"module\"'`,\n    code,\n  },\n  ImportOutsideModule: {\n    message: `'import' and 'export' may appear only with 'sourceType: \"module\"'`,\n    code,\n  },\n} satisfies ParseErrorTemplates;\n","const NodeDescriptions = {\n  ArrayPattern: \"array destructuring pattern\",\n  AssignmentExpression: \"assignment expression\",\n  AssignmentPattern: \"assignment expression\",\n  ArrowFunctionExpression: \"arrow function expression\",\n  ConditionalExpression: \"conditional expression\",\n  CatchClause: \"catch clause\",\n  ForOfStatement: \"for-of statement\",\n  ForInStatement: \"for-in statement\",\n  ForStatement: \"for-loop\",\n  FormalParameters: \"function parameter list\",\n  Identifier: \"identifier\",\n  ImportSpecifier: \"import specifier\",\n  ImportDefaultSpecifier: \"import default specifier\",\n  ImportNamespaceSpecifier: \"import namespace specifier\",\n  ObjectPattern: \"object destructuring pattern\",\n  ParenthesizedExpression: \"parenthesized expression\",\n  RestElement: \"rest element\",\n  UpdateExpression: {\n    true: \"prefix operation\",\n    false: \"postfix operation\",\n  },\n  VariableDeclarator: \"variable declaration\",\n  YieldExpression: \"yield expression\",\n};\n\ntype NodeTypesWithDescriptions = keyof Omit<\n  typeof NodeDescriptions,\n  \"UpdateExpression\"\n>;\n\ntype NodeWithDescription =\n  | {\n      type: \"UpdateExpression\";\n      prefix: boolean;\n    }\n  | {\n      type: NodeTypesWithDescriptions;\n    };\n\nconst toNodeDescription = (node: NodeWithDescription) =>\n  node.type === \"UpdateExpression\"\n    ? NodeDescriptions.UpdateExpression[`${node.prefix}`]\n    : NodeDescriptions[node.type];\n\nexport default toNodeDescription;\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\nimport toNodeDescription from \"./to-node-description.ts\";\n\nexport type LValAncestor =\n  | { type: \"UpdateExpression\"; prefix: boolean }\n  | {\n      type:\n        | \"ArrayPattern\"\n        | \"AssignmentExpression\"\n        | \"CatchClause\"\n        | \"ForOfStatement\"\n        | \"FormalParameters\"\n        | \"ForInStatement\"\n        | \"ForStatement\"\n        | \"ImportSpecifier\"\n        | \"ImportNamespaceSpecifier\"\n        | \"ImportDefaultSpecifier\"\n        | \"ParenthesizedExpression\"\n        | \"ObjectPattern\"\n        | \"RestElement\"\n        | \"VariableDeclarator\";\n    };\n\nexport default {\n  AccessorIsGenerator: ({ kind }: { kind: \"get\" | \"set\" }) =>\n    `A ${kind}ter cannot be a generator.`,\n  ArgumentsInClass:\n    \"'arguments' is only allowed in functions and class methods.\",\n  AsyncFunctionInSingleStatementContext:\n    \"Async functions can only be declared at the top level or inside a block.\",\n  AwaitBindingIdentifier:\n    \"Can not use 'await' as identifier inside an async function.\",\n  AwaitBindingIdentifierInStaticBlock:\n    \"Can not use 'await' as identifier inside a static block.\",\n  AwaitExpressionFormalParameter:\n    \"'await' is not allowed in async function parameters.\",\n  AwaitUsingNotInAsyncContext:\n    \"'await using' is only allowed within async functions and at the top levels of modules.\",\n  AwaitNotInAsyncContext:\n    \"'await' is only allowed within async functions and at the top levels of modules.\",\n  BadGetterArity: \"A 'get' accessor must not have any formal parameters.\",\n  BadSetterArity: \"A 'set' accessor must have exactly one formal parameter.\",\n  BadSetterRestParameter:\n    \"A 'set' accessor function argument must not be a rest parameter.\",\n  ConstructorClassField: \"Classes may not have a field named 'constructor'.\",\n  ConstructorClassPrivateField:\n    \"Classes may not have a private field named '#constructor'.\",\n  ConstructorIsAccessor: \"Class constructor may not be an accessor.\",\n  ConstructorIsAsync: \"Constructor can't be an async function.\",\n  ConstructorIsGenerator: \"Constructor can't be a generator.\",\n  DeclarationMissingInitializer: ({\n    kind,\n  }: {\n    kind: \"await using\" | \"const\" | \"destructuring\" | \"using\";\n  }) => `Missing initializer in ${kind} declaration.`,\n  DecoratorArgumentsOutsideParentheses:\n    \"Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.\",\n  DecoratorBeforeExport:\n    \"Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.\",\n  DecoratorsBeforeAfterExport:\n    \"Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.\",\n  DecoratorConstructor:\n    \"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?\",\n  DecoratorExportClass:\n    \"Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.\",\n  DecoratorSemicolon: \"Decorators must not be followed by a semicolon.\",\n  DecoratorStaticBlock: \"Decorators can't be used with a static block.\",\n  DeferImportRequiresNamespace:\n    'Only `import defer * as x from \"./module\"` is valid.',\n  DeletePrivateField: \"Deleting a private field is not allowed.\",\n  DestructureNamedImport:\n    \"ES2015 named imports do not destructure. Use another statement for destructuring after the import.\",\n  DuplicateConstructor: \"Duplicate constructor in the same class.\",\n  DuplicateDefaultExport: \"Only one default export allowed per module.\",\n  DuplicateExport: ({ exportName }: { exportName: string }) =>\n    `\\`${exportName}\\` has already been exported. Exported identifiers must be unique.`,\n  DuplicateProto: \"Redefinition of __proto__ property.\",\n  DuplicateRegExpFlags: \"Duplicate regular expression flag.\",\n  ElementAfterRest: \"Rest element must be last element.\",\n  EscapedCharNotAnIdentifier: \"Invalid Unicode escape.\",\n  ExportBindingIsString: ({\n    localName,\n    exportName,\n  }: {\n    localName: string;\n    exportName: string;\n  }) =>\n    `A string literal cannot be used as an exported binding without \\`from\\`.\\n- Did you mean \\`export { '${localName}' as '${exportName}' } from 'some-module'\\`?`,\n  ExportDefaultFromAsIdentifier:\n    \"'from' is not allowed as an identifier after 'export default'.\",\n\n  ForInOfLoopInitializer: ({\n    type,\n  }: {\n    type: \"ForInStatement\" | \"ForOfStatement\";\n  }) =>\n    `'${\n      type === \"ForInStatement\" ? \"for-in\" : \"for-of\"\n    }' loop variable declaration may not have an initializer.`,\n  ForInUsing: \"For-in loop may not start with 'using' declaration.\",\n\n  ForOfAsync: \"The left-hand side of a for-of loop may not be 'async'.\",\n  ForOfLet: \"The left-hand side of a for-of loop may not start with 'let'.\",\n  GeneratorInSingleStatementContext:\n    \"Generators can only be declared at the top level or inside a block.\",\n\n  IllegalBreakContinue: ({\n    type,\n  }: {\n    type: \"BreakStatement\" | \"ContinueStatement\";\n  }) => `Unsyntactic ${type === \"BreakStatement\" ? \"break\" : \"continue\"}.`,\n\n  IllegalLanguageModeDirective:\n    \"Illegal 'use strict' directive in function with non-simple parameter list.\",\n  IllegalReturn: \"'return' outside of function.\",\n  ImportAttributesUseAssert:\n    \"The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedImportAssert` parser plugin to suppress this error.\",\n  ImportBindingIsString: ({ importName }: { importName: string }) =>\n    `A string literal cannot be used as an imported binding.\\n- Did you mean \\`import { \"${importName}\" as foo }\\`?`,\n  ImportCallArity: `\\`import()\\` requires exactly one or two arguments.`,\n  ImportCallNotNewExpression: \"Cannot use new with import(...).\",\n  ImportCallSpreadArgument: \"`...` is not allowed in `import()`.\",\n  ImportJSONBindingNotDefault:\n    \"A JSON module can only be imported with `default`.\",\n  ImportReflectionHasAssertion: \"`import module x` cannot have assertions.\",\n  ImportReflectionNotBinding:\n    'Only `import module x from \"./module\"` is valid.',\n  IncompatibleRegExpUVFlags:\n    \"The 'u' and 'v' regular expression flags cannot be enabled at the same time.\",\n  InvalidBigIntLiteral: \"Invalid BigIntLiteral.\",\n  InvalidCodePoint: \"Code point out of bounds.\",\n  InvalidCoverDiscardElement:\n    \"'void' must be followed by an expression when not used in a binding position.\",\n  InvalidCoverInitializedName: \"Invalid shorthand property initializer.\",\n  InvalidDecimal: \"Invalid decimal.\",\n  InvalidDigit: ({ radix }: { radix: number }) =>\n    `Expected number in radix ${radix}.`,\n  InvalidEscapeSequence: \"Bad character escape sequence.\",\n  InvalidEscapeSequenceTemplate: \"Invalid escape sequence in template.\",\n  InvalidEscapedReservedWord: ({ reservedWord }: { reservedWord: string }) =>\n    `Escape sequence in keyword ${reservedWord}.`,\n  InvalidIdentifier: ({ identifierName }: { identifierName: string }) =>\n    `Invalid identifier ${identifierName}.`,\n  InvalidLhs: ({ ancestor }: { ancestor: LValAncestor }) =>\n    `Invalid left-hand side in ${toNodeDescription(ancestor)}.`,\n  InvalidLhsBinding: ({ ancestor }: { ancestor: LValAncestor }) =>\n    `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,\n  InvalidLhsOptionalChaining: ({ ancestor }: { ancestor: LValAncestor }) =>\n    `Invalid optional chaining in the left-hand side of ${toNodeDescription(\n      ancestor,\n    )}.`,\n  InvalidNumber: \"Invalid number.\",\n  InvalidOrMissingExponent:\n    \"Floating-point numbers require a valid exponent after the 'e'.\",\n  InvalidOrUnexpectedToken: ({ unexpected }: { unexpected: string }) =>\n    `Unexpected character '${unexpected}'.`,\n  InvalidParenthesizedAssignment: \"Invalid parenthesized assignment pattern.\",\n  InvalidPrivateFieldResolution: ({\n    identifierName,\n  }: {\n    identifierName: string;\n  }) => `Private name #${identifierName} is not defined.`,\n  InvalidPropertyBindingPattern: \"Binding member expression.\",\n  InvalidRecordProperty:\n    \"Only properties and spread elements are allowed in record definitions.\",\n  InvalidRestAssignmentPattern: \"Invalid rest operator's argument.\",\n  LabelRedeclaration: ({ labelName }: { labelName: string }) =>\n    `Label '${labelName}' is already declared.`,\n  LetInLexicalBinding: \"'let' is disallowed as a lexically bound name.\",\n  LineTerminatorBeforeArrow: \"No line break is allowed before '=>'.\",\n  MalformedRegExpFlags: \"Invalid regular expression flag.\",\n  MissingClassName: \"A class name is required.\",\n  MissingEqInAssignment:\n    \"Only '=' operator can be used for specifying default value.\",\n  MissingSemicolon: \"Missing semicolon.\",\n  MissingPlugin: ({ missingPlugin }: { missingPlugin: [string] }) =>\n    `This experimental syntax requires enabling the parser plugin: ${missingPlugin\n      .map(name => JSON.stringify(name))\n      .join(\", \")}.`,\n  // FIXME: Would be nice to make this \"missingPlugins\" instead.\n  // Also, seems like we can drop the \"(s)\" from the message and just make it \"s\".\n  MissingOneOfPlugins: ({ missingPlugin }: { missingPlugin: string[] }) =>\n    `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin\n      .map(name => JSON.stringify(name))\n      .join(\", \")}.`,\n  MissingUnicodeEscape: \"Expecting Unicode escape sequence \\\\uXXXX.\",\n  MixingCoalesceWithLogical:\n    \"Nullish coalescing operator(??) requires parens when mixing with logical operators.\",\n  ModuleAttributeDifferentFromType:\n    \"The only accepted module attribute is `type`.\",\n  ModuleAttributeInvalidValue:\n    \"Only string literals are allowed as module attribute values.\",\n  ModuleAttributesWithDuplicateKeys: ({ key }: { key: string }) =>\n    `Duplicate key \"${key}\" is not allowed in module attributes.`,\n  ModuleExportNameHasLoneSurrogate: ({\n    surrogateCharCode,\n  }: {\n    surrogateCharCode: number;\n  }) =>\n    `An export name cannot include a lone surrogate, found '\\\\u${surrogateCharCode.toString(\n      16,\n    )}'.`,\n  ModuleExportUndefined: ({ localName }: { localName: string }) =>\n    `Export '${localName}' is not defined.`,\n  MultipleDefaultsInSwitch: \"Multiple default clauses.\",\n  NewlineAfterThrow: \"Illegal newline after throw.\",\n  NoCatchOrFinally: \"Missing catch or finally clause.\",\n  NumberIdentifier: \"Identifier directly after number.\",\n  NumericSeparatorInEscapeSequence:\n    \"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.\",\n  ObsoleteAwaitStar:\n    \"'await*' has been removed from the async functions proposal. Use Promise.all() instead.\",\n  OptionalChainingNoNew:\n    \"Constructors in/after an Optional Chain are not allowed.\",\n  OptionalChainingNoTemplate:\n    \"Tagged Template Literals are not allowed in optionalChain.\",\n  OverrideOnConstructor:\n    \"'override' modifier cannot appear on a constructor declaration.\",\n  ParamDupe: \"Argument name clash.\",\n  PatternHasAccessor: \"Object pattern can't contain getter or setter.\",\n  PatternHasMethod: \"Object pattern can't contain methods.\",\n  PrivateInExpectedIn: ({ identifierName }: { identifierName: string }) =>\n    `Private names are only allowed in property accesses (\\`obj.#${identifierName}\\`) or in \\`in\\` expressions (\\`#${identifierName} in obj\\`).`,\n  PrivateNameRedeclaration: ({ identifierName }: { identifierName: string }) =>\n    `Duplicate private name #${identifierName}.`,\n  RecordExpressionBarIncorrectEndSyntaxType:\n    \"Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n  RecordExpressionBarIncorrectStartSyntaxType:\n    \"Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n  RecordExpressionHashIncorrectStartSyntaxType:\n    \"Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.\",\n  RecordNoProto: \"'__proto__' is not allowed in Record expressions.\",\n  RestTrailingComma: \"Unexpected trailing comma after rest element.\",\n  SloppyFunction:\n    \"In non-strict mode code, functions can only be declared at top level or inside a block.\",\n  SloppyFunctionAnnexB:\n    \"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.\",\n  SourcePhaseImportRequiresDefault:\n    'Only `import source x from \"./module\"` is valid.',\n  StaticPrototype: \"Classes may not have static property named prototype.\",\n  SuperNotAllowed:\n    \"`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?\",\n  SuperPrivateField: \"Private fields can't be accessed on super.\",\n  TrailingDecorator: \"Decorators must be attached to a class element.\",\n  TupleExpressionBarIncorrectEndSyntaxType:\n    \"Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n  TupleExpressionBarIncorrectStartSyntaxType:\n    \"Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.\",\n  TupleExpressionHashIncorrectStartSyntaxType:\n    \"Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.\",\n  UnexpectedArgumentPlaceholder: \"Unexpected argument placeholder.\",\n  UnexpectedAwaitAfterPipelineBody:\n    'Unexpected \"await\" after pipeline body; await must have parentheses in minimal proposal.',\n  UnexpectedDigitAfterHash: \"Unexpected digit after hash token.\",\n  UnexpectedImportExport:\n    \"'import' and 'export' may only appear at the top level.\",\n  UnexpectedKeyword: ({ keyword }: { keyword: string }) =>\n    `Unexpected keyword '${keyword}'.`,\n  UnexpectedLeadingDecorator:\n    \"Leading decorators must be attached to a class declaration.\",\n  UnexpectedLexicalDeclaration:\n    \"Lexical declaration cannot appear in a single-statement context.\",\n  UnexpectedNewTarget:\n    \"`new.target` can only be used in functions or class properties.\",\n  UnexpectedNumericSeparator:\n    \"A numeric separator is only allowed between two digits.\",\n  UnexpectedPrivateField: \"Unexpected private name.\",\n  UnexpectedReservedWord: ({ reservedWord }: { reservedWord: string }) =>\n    `Unexpected reserved word '${reservedWord}'.`,\n  UnexpectedSuper: \"'super' is only allowed in object methods and classes.\",\n  UnexpectedToken: ({\n    expected,\n    unexpected,\n  }: {\n    expected?: string | null;\n    unexpected?: string | null;\n  }) =>\n    `Unexpected token${unexpected ? ` '${unexpected}'.` : \"\"}${\n      expected ? `, expected \"${expected}\"` : \"\"\n    }`,\n  UnexpectedTokenUnaryExponentiation:\n    \"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.\",\n  UnexpectedUsingDeclaration:\n    \"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.\",\n  UnexpectedVoidPattern: \"Unexpected void binding.\",\n  UnsupportedBind: \"Binding should be performed on object property.\",\n  UnsupportedDecoratorExport:\n    \"A decorated export must export a class declaration.\",\n  UnsupportedDefaultExport:\n    \"Only expressions, functions or classes are allowed as the `default` export.\",\n  UnsupportedImport:\n    \"`import` can only be used in `import()` or `import.meta`.\",\n  UnsupportedMetaProperty: ({\n    target,\n    onlyValidPropertyName,\n  }: {\n    target: string;\n    onlyValidPropertyName: string;\n  }) =>\n    `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`,\n  UnsupportedParameterDecorator:\n    \"Decorators cannot be used to decorate parameters.\",\n  UnsupportedPropertyDecorator:\n    \"Decorators cannot be used to decorate object literal properties.\",\n  UnsupportedSuper:\n    \"'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).\",\n  UnterminatedComment: \"Unterminated comment.\",\n  UnterminatedRegExp: \"Unterminated regular expression.\",\n  UnterminatedString: \"Unterminated string constant.\",\n  UnterminatedTemplate: \"Unterminated template.\",\n  UsingDeclarationExport: \"Using declaration cannot be exported.\",\n  UsingDeclarationHasBindingPattern:\n    \"Using declaration cannot have destructuring patterns.\",\n  VarRedeclaration: ({ identifierName }: { identifierName: string }) =>\n    `Identifier '${identifierName}' has already been declared.`,\n  VoidPatternCatchClauseParam:\n    \"A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.\",\n  VoidPatternInitializer: \"A void binding may not have an initializer.\",\n  YieldBindingIdentifier:\n    \"Can not use 'yield' as identifier inside a generator.\",\n  YieldInParameter: \"Yield expression is not allowed in formal parameters.\",\n  YieldNotInGeneratorFunction:\n    \"'yield' is only allowed within generator functions.\",\n  ZeroDigitNumericSeparator:\n    \"Numeric separator can not be used after leading 0.\",\n} satisfies ParseErrorTemplates;\n","import type { ParseErrorTemplates } from \"../parse-error\";\n\nexport default {\n  StrictDelete: \"Deleting local variable in strict mode.\",\n\n  // `referenceName` is the StringValue[1] of an IdentifierReference[2], which\n  // is represented as just an `Identifier`[3] in the Babel AST.\n  // 1. https://tc39.es/ecma262/#sec-static-semantics-stringvalue\n  // 2. https://tc39.es/ecma262/#prod-IdentifierReference\n  // 3. https://github.com/babel/babel/blob/main/packages/babel-parser/ast/spec.md#identifier\n  StrictEvalArguments: ({ referenceName }: { referenceName: string }) =>\n    `Assigning to '${referenceName}' in strict mode.`,\n\n  // `bindingName` is the StringValue[1] of a BindingIdentifier[2], which is\n  // represented as just an `Identifier`[3] in the Babel AST.\n  // 1. https://tc39.es/ecma262/#sec-static-semantics-stringvalue\n  // 2. https://tc39.es/ecma262/#prod-BindingIdentifier\n  // 3. https://github.com/babel/babel/blob/main/packages/babel-parser/ast/spec.md#identifier\n  StrictEvalArgumentsBinding: ({ bindingName }: { bindingName: string }) =>\n    `Binding '${bindingName}' in strict mode.`,\n\n  StrictFunction:\n    \"In strict mode code, functions can only be declared at top level or inside a block.\",\n\n  StrictNumericEscape: \"The only valid numeric escape in strict mode is '\\\\0'.\",\n\n  StrictOctalLiteral: \"Legacy octal literals are not allowed in strict mode.\",\n\n  StrictWith: \"'with' in strict mode.\",\n} satisfies ParseErrorTemplates;\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\n\nexport default {\n  ParseExpressionEmptyInput:\n    \"Unexpected parseExpression() input: The input is empty or contains only comments.\",\n  ParseExpressionExpectsEOF: ({ unexpected }: { unexpected: number }) =>\n    `Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \\`${String.fromCodePoint(unexpected)}\\`.`,\n} satisfies ParseErrorTemplates;\n","import type { ParseErrorTemplates } from \"../parse-error.ts\";\nimport toNodeDescription from \"./to-node-description.ts\";\n\nexport const UnparenthesizedPipeBodyDescriptions = new Set([\n  \"ArrowFunctionExpression\",\n  \"AssignmentExpression\",\n  \"ConditionalExpression\",\n  \"YieldExpression\",\n] as const);\n\ntype GetSetMemberType<T extends Set<any>> =\n  T extends Set<infer M> ? M : unknown;\n\nexport type UnparenthesizedPipeBodyTypes = GetSetMemberType<\n  typeof UnparenthesizedPipeBodyDescriptions\n>;\n\nexport default {\n  // This error is only used by the smart-mix proposal\n  PipeBodyIsTighter:\n    \"Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.\",\n  PipeTopicRequiresHackPipes: process.env.BABEL_8_BREAKING\n    ? 'Topic references are only supported when using the `\"proposal\": \"hack\"` version of the pipeline proposal.'\n    : 'Topic reference is used, but the pipelineOperator plugin was not passed a \"proposal\": \"hack\" or \"smart\" option.',\n  PipeTopicUnbound:\n    \"Topic reference is unbound; it must be inside a pipe body.\",\n  PipeTopicUnconfiguredToken: ({ token }: { token: string }) =>\n    `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { \"proposal\": \"hack\", \"topicToken\": \"${token}\" }.`,\n  PipeTopicUnused:\n    \"Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.\",\n  PipeUnparenthesizedBody: ({ type }: { type: UnparenthesizedPipeBodyTypes }) =>\n    `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({\n      type,\n    })}; please wrap it in parentheses.`,\n\n  ...(process.env.BABEL_8_BREAKING\n    ? {}\n    : {\n        // Messages whose codes start with “Pipeline” or “PrimaryTopic”\n        // are retained for backwards compatibility\n        // with the deprecated smart-mix pipe operator proposal plugin.\n        // They are subject to removal in a future major version.\n        PipelineBodyNoArrow:\n          'Unexpected arrow \"=>\" after pipeline body; arrow function in pipeline body must be parenthesized.',\n        PipelineBodySequenceExpression:\n          \"Pipeline body may not be a comma-separated sequence expression.\",\n        PipelineHeadSequenceExpression:\n          \"Pipeline head should not be a comma-separated sequence expression.\",\n        PipelineTopicUnused:\n          \"Pipeline is in topic style but does not use topic reference.\",\n        PrimaryTopicNotAllowed:\n          \"Topic reference was used in a lexical context without topic binding.\",\n        PrimaryTopicRequiresSmartPipeline:\n          'Topic reference is used, but the pipelineOperator plugin was not passed a \"proposal\": \"hack\" or \"smart\" option.',\n      }),\n} satisfies ParseErrorTemplates;\n","import { Position } from \"./util/location.ts\";\n\ntype SyntaxPlugin =\n  | \"flow\"\n  | \"typescript\"\n  | \"jsx\"\n  | \"pipelineOperator\"\n  | \"placeholders\";\n\ntype ParseErrorCode =\n  | \"BABEL_PARSER_SYNTAX_ERROR\"\n  | \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\";\n\n// Babel uses \"normal\" SyntaxErrors for it's errors, but adds some extra\n// functionality. This functionality is defined in the\n// `ParseErrorSpecification` interface below. We may choose to change to someday\n// give our errors their own full-blown class, but until then this allow us to\n// keep all the desirable properties of SyntaxErrors (like their name in stack\n// traces, etc.), and also allows us to punt on any publicly facing\n// class-hierarchy decisions until Babel 8.\ninterface ParseErrorSpecification<ErrorDetails> {\n  // Look, these *could* be readonly, but then Flow complains when we initially\n  // set them. We could do a whole dance and make a special interface that's not\n  // readonly for when we create the error, then cast it to the readonly\n  // interface for public use, but the previous implementation didn't have them\n  // as readonly, so let's just not worry about it for now.\n  code: ParseErrorCode;\n  reasonCode: string;\n  syntaxPlugin?: SyntaxPlugin;\n  missingPlugin?: string | string[];\n  loc: Position;\n  details: ErrorDetails;\n\n  // We should consider removing this as it now just contains the same\n  // information as `loc.index`.\n  pos: number;\n}\n\nexport type ParseError<ErrorDetails> = SyntaxError &\n  ParseErrorSpecification<ErrorDetails>;\n\n// By `ParseErrorConstructor`, we mean something like the new-less style\n// `ErrorConstructor`[1], since `ParseError`'s are not themselves actually\n// separate classes from `SyntaxError`'s.\n//\n// 1. https://github.com/microsoft/TypeScript/blob/v4.5.5/lib/lib.es5.d.ts#L1027\nexport type ParseErrorConstructor<ErrorDetails> = (\n  loc: Position,\n  details: ErrorDetails,\n) => ParseError<ErrorDetails>;\n\ntype ToMessage<ErrorDetails> = (self: ErrorDetails) => string;\n\ntype ParseErrorCredentials<ErrorDetails> = {\n  code: string;\n  reasonCode: string;\n  syntaxPlugin?: SyntaxPlugin;\n  toMessage: ToMessage<ErrorDetails>;\n};\n\nfunction defineHidden(obj: object, key: string, value: unknown) {\n  Object.defineProperty(obj, key, {\n    enumerable: false,\n    configurable: true,\n    value,\n  });\n}\n\nfunction toParseErrorConstructor<ErrorDetails extends object>({\n  toMessage,\n  code,\n  reasonCode,\n  syntaxPlugin,\n}: ParseErrorCredentials<ErrorDetails>): ParseErrorConstructor<ErrorDetails> {\n  const hasMissingPlugin =\n    reasonCode === \"MissingPlugin\" || reasonCode === \"MissingOneOfPlugins\";\n\n  if (!process.env.BABEL_8_BREAKING) {\n    const oldReasonCodes: Record<string, string> = {\n      AccessorCannotDeclareThisParameter: \"AccesorCannotDeclareThisParameter\",\n      AccessorCannotHaveTypeParameters: \"AccesorCannotHaveTypeParameters\",\n      ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:\n        \"ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference\",\n      SetAccessorCannotHaveOptionalParameter:\n        \"SetAccesorCannotHaveOptionalParameter\",\n      SetAccessorCannotHaveRestParameter: \"SetAccesorCannotHaveRestParameter\",\n      SetAccessorCannotHaveReturnType: \"SetAccesorCannotHaveReturnType\",\n    };\n    if (oldReasonCodes[reasonCode]) {\n      reasonCode = oldReasonCodes[reasonCode];\n    }\n  }\n\n  return function constructor(loc: Position, details: ErrorDetails) {\n    const error: ParseError<ErrorDetails> = new SyntaxError() as any;\n\n    error.code = code as ParseErrorCode;\n    error.reasonCode = reasonCode;\n    error.loc = loc;\n    error.pos = loc.index;\n\n    error.syntaxPlugin = syntaxPlugin;\n    if (hasMissingPlugin) {\n      error.missingPlugin = (details as any).missingPlugin;\n    }\n\n    type Overrides = {\n      loc?: Position;\n      details?: ErrorDetails;\n    };\n    defineHidden(error, \"clone\", function clone(overrides: Overrides = {}) {\n      const { line, column, index } = overrides.loc ?? loc;\n      return constructor(new Position(line, column, index), {\n        ...details,\n        ...overrides.details,\n      });\n    });\n\n    defineHidden(error, \"details\", details);\n\n    Object.defineProperty(error, \"message\", {\n      configurable: true,\n      get(this: ParseError<ErrorDetails>): string {\n        const message = `${toMessage(details)} (${loc.line}:${loc.column})`;\n        this.message = message;\n        return message;\n      },\n      set(value: string) {\n        Object.defineProperty(this, \"message\", { value, writable: true });\n      },\n    });\n\n    return error;\n  };\n}\n\ntype ParseErrorTemplate =\n  | string\n  | ToMessage<any>\n  | { message: string | ToMessage<any>; code?: ParseErrorCode };\n\nexport type ParseErrorTemplates = { [reasonCode: string]: ParseErrorTemplate };\n\n// This is the templated form of `ParseErrorEnum`.\n//\n// Note: We could factor out the return type calculation into something like\n// `ParseErrorConstructor<T extends ParseErrorTemplates>`, and then we could\n// reuse it in the non-templated form of `ParseErrorEnum`, but TypeScript\n// doesn't seem to drill down that far when showing you the computed type of\n// an object in an editor, so we'll leave it inlined for now.\nexport function ParseErrorEnum(a: TemplateStringsArray): <\n  T extends ParseErrorTemplates,\n>(\n  parseErrorTemplates: T,\n) => {\n  [K in keyof T]: ParseErrorConstructor<\n    T[K] extends { message: string | ToMessage<any> }\n      ? T[K][\"message\"] extends ToMessage<any>\n        ? Parameters<T[K][\"message\"]>[0]\n        : object\n      : T[K] extends ToMessage<any>\n        ? Parameters<T[K]>[0]\n        : object\n  >;\n};\n\nexport function ParseErrorEnum<T extends ParseErrorTemplates>(\n  parseErrorTemplates: T,\n  syntaxPlugin?: SyntaxPlugin,\n): {\n  [K in keyof T]: ParseErrorConstructor<\n    T[K] extends { message: string | ToMessage<any> }\n      ? T[K][\"message\"] extends ToMessage<any>\n        ? Parameters<T[K][\"message\"]>[0]\n        : object\n      : T[K] extends ToMessage<any>\n        ? Parameters<T[K]>[0]\n        : object\n  >;\n};\n\n// You call `ParseErrorEnum` with a mapping from `ReasonCode`'s to either:\n//\n// 1. a static error message,\n// 2. `toMessage` functions that define additional necessary `details` needed by\n//    the `ParseError`, or\n// 3. Objects that contain a `message` of one of the above and overridden `code`\n//    and/or `reasonCode`:\n//\n// ParseErrorEnum `optionalSyntaxPlugin` ({\n//   ErrorWithStaticMessage: \"message\",\n//   ErrorWithDynamicMessage: ({ type } : { type: string }) => `${type}`),\n//   ErrorWithOverriddenCodeAndOrReasonCode: {\n//     message: ({ type }: { type: string }) => `${type}`),\n//     code: \"AN_ERROR_CODE\",\n//     ...(BABEL_8_BREAKING ? { } : { reasonCode: \"CustomErrorReasonCode\" })\n//   }\n// });\n//\nexport function ParseErrorEnum(\n  argument: TemplateStringsArray | ParseErrorTemplates,\n  syntaxPlugin?: SyntaxPlugin,\n) {\n  // If the first parameter is an array, that means we were called with a tagged\n  // template literal. Extract the syntaxPlugin from this, and call again in\n  // the \"normalized\" form.\n  if (Array.isArray(argument)) {\n    return (parseErrorTemplates: ParseErrorTemplates) =>\n      ParseErrorEnum(parseErrorTemplates, argument[0]);\n  }\n\n  const ParseErrorConstructors = {} as Record<\n    string,\n    ParseErrorConstructor<unknown>\n  >;\n\n  for (const reasonCode of Object.keys(argument)) {\n    const template = (argument as ParseErrorTemplates)[reasonCode];\n    const { message, ...rest } =\n      typeof template === \"string\"\n        ? { message: () => template }\n        : typeof template === \"function\"\n          ? { message: template }\n          : template;\n    const toMessage = typeof message === \"string\" ? () => message : message;\n\n    ParseErrorConstructors[reasonCode] = toParseErrorConstructor({\n      code: \"BABEL_PARSER_SYNTAX_ERROR\",\n      reasonCode,\n      toMessage,\n      ...(syntaxPlugin ? { syntaxPlugin } : {}),\n      ...rest,\n    });\n  }\n\n  return ParseErrorConstructors;\n}\n\nimport ModuleErrors from \"./parse-error/module-errors.ts\";\nimport StandardErrors from \"./parse-error/standard-errors.ts\";\nimport StrictModeErrors from \"./parse-error/strict-mode-errors.ts\";\nimport ParseExpressionErrors from \"./parse-error/parse-expression-errors.ts\";\nimport PipelineOperatorErrors from \"./parse-error/pipeline-operator-errors.ts\";\n\nexport const Errors = {\n  ...ParseErrorEnum(ModuleErrors),\n  ...ParseErrorEnum(StandardErrors),\n  ...ParseErrorEnum(StrictModeErrors),\n  ...ParseErrorEnum(ParseExpressionErrors),\n  ...ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors),\n};\n\nexport type { LValAncestor } from \"./parse-error/standard-errors.ts\";\n","import type { Plugin } from \"./plugin-utils.ts\";\n\n// A second optional argument can be given to further configure\n// the parser process. These options are recognized:\n\nexport type SourceType = \"script\" | \"commonjs\" | \"module\" | \"unambiguous\";\n\nexport interface Options {\n  /**\n   * By default, import and export declarations can only appear at a program's top level.\n   * Setting this option to true allows them anywhere where a statement is allowed.\n   */\n  allowImportExportEverywhere?: boolean;\n\n  /**\n   * By default, await use is not allowed outside of an async function.\n   * Set this to true to accept such code.\n   */\n  allowAwaitOutsideFunction?: boolean;\n\n  /**\n   * By default, a return statement at the top level raises an error.\n   * Set this to true to accept such code.\n   */\n  allowReturnOutsideFunction?: boolean;\n\n  /**\n   * By default, new.target use is not allowed outside of a function or class.\n   * Set this to true to accept such code.\n   */\n  allowNewTargetOutsideFunction?: boolean;\n\n  allowSuperOutsideMethod?: boolean;\n\n  /**\n   * By default, exported identifiers must refer to a declared variable.\n   * Set this to true to allow export statements to reference undeclared variables.\n   */\n  allowUndeclaredExports?: boolean;\n\n  /**\n   * By default, yield use is not allowed outside of a generator function.\n   * Set this to true to accept such code.\n   */\n\n  allowYieldOutsideFunction?: boolean;\n\n  /**\n   * By default, Babel parser JavaScript code according to Annex B syntax.\n   * Set this to `false` to disable such behavior.\n   */\n  annexB?: boolean;\n\n  /**\n   * By default, Babel attaches comments to adjacent AST nodes.\n   * When this option is set to false, comments are not attached.\n   * It can provide up to 30% performance improvement when the input code has many comments.\n   * @babel/eslint-parser will set it for you.\n   * It is not recommended to use attachComment: false with Babel transform,\n   * as doing so removes all the comments in output code, and renders annotations such as\n   * /* istanbul ignore next *\\/ nonfunctional.\n   */\n  attachComment?: boolean;\n\n  /**\n   * By default, Babel always throws an error when it finds some invalid code.\n   * When this option is set to true, it will store the parsing error and\n   * try to continue parsing the invalid input file.\n   */\n  errorRecovery?: boolean;\n\n  /**\n   * Indicate the mode the code should be parsed in.\n   * Can be one of \"script\", \"commonjs\", \"module\", or \"unambiguous\". Defaults to \"script\".\n   * \"unambiguous\" will make @babel/parser attempt to guess, based on the presence\n   * of ES6 import or export statements.\n   * Files with ES6 imports and exports are considered \"module\" and are otherwise \"script\".\n   *\n   * Use \"commonjs\" to parse code that is intended to be run in a CommonJS environment such as Node.js.\n   */\n  sourceType?: SourceType;\n\n  /**\n   * Correlate output AST nodes with their source filename.\n   * Useful when generating code and source maps from the ASTs of multiple input files.\n   */\n  sourceFilename?: string;\n\n  /**\n   * By default, all source indexes start from 0.\n   * You can provide a start index to alternatively start with.\n   * Useful for integration with other source tools.\n   */\n  startIndex?: number;\n\n  /**\n   * By default, the first line of code parsed is treated as line 1.\n   * You can provide a line number to alternatively start with.\n   * Useful for integration with other source tools.\n   */\n  startLine?: number;\n\n  /**\n   * By default, the parsed code is treated as if it starts from line 1, column 0.\n   * You can provide a column number to alternatively start with.\n   * Useful for integration with other source tools.\n   */\n  startColumn?: number;\n\n  /**\n   * Array containing the plugins that you want to enable.\n   */\n  plugins?: Plugin[];\n\n  /**\n   * Should the parser work in strict mode.\n   * Defaults to true if sourceType === 'module'. Otherwise, false.\n   */\n  strictMode?: boolean;\n\n  /**\n   * Adds a ranges property to each node: [node.start, node.end]\n   */\n  ranges?: boolean;\n\n  /**\n   * Adds all parsed tokens to a tokens property on the File node.\n   */\n  tokens?: boolean;\n\n  /**\n   * By default, the parser adds information about parentheses by setting\n   * `extra.parenthesized` to `true` as needed.\n   * When this option is `true` the parser creates `ParenthesizedExpression`\n   * AST nodes instead of using the `extra` property.\n   */\n  createParenthesizedExpressions?: boolean;\n\n  /**\n   * The default is false in Babel 7 and true in Babel 8\n   * Set this to true to parse it as an `ImportExpression` node.\n   * Otherwise `import(foo)` is parsed as `CallExpression(Import, [Identifier(foo)])`.\n   */\n  createImportExpressions?: boolean;\n}\n\nexport const enum OptionFlags {\n  AllowAwaitOutsideFunction = 1 << 0,\n  AllowReturnOutsideFunction = 1 << 1,\n  AllowNewTargetOutsideFunction = 1 << 2,\n  AllowImportExportEverywhere = 1 << 3,\n  AllowSuperOutsideMethod = 1 << 4,\n  AllowYieldOutsideFunction = 1 << 5,\n  AllowUndeclaredExports = 1 << 6,\n  Ranges = 1 << 7,\n  Tokens = 1 << 8,\n  CreateImportExpressions = 1 << 9,\n  CreateParenthesizedExpressions = 1 << 10,\n  ErrorRecovery = 1 << 11,\n  AttachComment = 1 << 12,\n  AnnexB = 1 << 13,\n}\n\ntype OptionsWithDefaults = Required<Options>;\n\nfunction createDefaultOptions(): OptionsWithDefaults {\n  return {\n    // Source type (\"script\" or \"module\") for different semantics\n    sourceType: \"script\",\n    // Source filename.\n    sourceFilename: undefined,\n    // Index (0-based) from which to start counting source. Useful for\n    // integration with other tools.\n    startIndex: 0,\n    // Column (0-based) from which to start counting source. Useful for\n    // integration with other tools.\n    startColumn: 0,\n    // Line (1-based) from which to start counting source. Useful for\n    // integration with other tools.\n    startLine: 1,\n    // When enabled, await at the top level is not considered an\n    // error.\n    allowAwaitOutsideFunction: false,\n    // When enabled, a return at the top level is not considered an\n    // error.\n    allowReturnOutsideFunction: false,\n    // When enabled, new.target outside a function or class is not\n    // considered an error.\n    allowNewTargetOutsideFunction: false,\n    // When enabled, import/export statements are not constrained to\n    // appearing at the top of the program.\n    allowImportExportEverywhere: false,\n    // TODO\n    allowSuperOutsideMethod: false,\n    // When enabled, export statements can reference undeclared variables.\n    allowUndeclaredExports: false,\n    allowYieldOutsideFunction: false,\n    // An array of plugins to enable\n    plugins: [],\n    // TODO\n    strictMode: null,\n    // Nodes have their start and end characters offsets recorded in\n    // `start` and `end` properties (directly on the node, rather than\n    // the `loc` object, which holds line/column data. To also add a\n    // [semi-standardized][range] `range` property holding a `[start,\n    // end]` array with the same numbers, set the `ranges` option to\n    // `true`.\n    //\n    // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678\n    ranges: false,\n    // Adds all parsed tokens to a `tokens` property on the `File` node\n    tokens: false,\n    // Whether to create ImportExpression AST nodes (if false\n    // `import(foo)` will be parsed as CallExpression(Import, [Identifier(foo)])\n    createImportExpressions: process.env.BABEL_8_BREAKING ? true : false,\n    // Whether to create ParenthesizedExpression AST nodes (if false\n    // the parser sets extra.parenthesized on the expression nodes instead).\n    createParenthesizedExpressions: false,\n    // When enabled, errors are attached to the AST instead of being directly thrown.\n    // Some errors will still throw, because @babel/parser can't always recover.\n    errorRecovery: false,\n    // When enabled, comments will be attached to adjacent AST nodes as one of\n    // `leadingComments`, `trailingComments` and `innerComments`. The comment attachment\n    // is vital to preserve comments after transform. If you don't print AST back,\n    // consider set this option to `false` for performance\n    attachComment: true,\n    // When enabled, the parser will support Annex B syntax.\n    // https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers\n    annexB: true,\n  };\n}\n\n// Interpret and default an options object\n\nexport function getOptions(opts?: Options | null): OptionsWithDefaults {\n  // https://github.com/babel/babel/pull/16918\n  // `options` is accessed frequently, please make sure it is a fast object.\n  // `%ToFastProperties` can make it a fast object, but the performance is the same as the slow object.\n  const options: any = createDefaultOptions();\n\n  if (opts == null) {\n    return options;\n  }\n  if (opts.annexB != null && opts.annexB !== false) {\n    throw new Error(\"The `annexB` option can only be set to `false`.\");\n  }\n\n  for (const key of Object.keys(options) as (keyof Options)[]) {\n    if (opts[key] != null) options[key] = opts[key];\n  }\n\n  if (options.startLine === 1) {\n    if (opts.startIndex == null && options.startColumn > 0) {\n      options.startIndex = options.startColumn;\n    } else if (opts.startColumn == null && options.startIndex > 0) {\n      options.startColumn = options.startIndex;\n    }\n  } else if (opts.startColumn == null || opts.startIndex == null) {\n    if (opts.startIndex != null || process.env.BABEL_8_BREAKING) {\n      throw new Error(\n        \"With a `startLine > 1` you must also specify `startIndex` and `startColumn`.\",\n      );\n    }\n  }\n\n  if (options.sourceType === \"commonjs\") {\n    if (opts.allowAwaitOutsideFunction != null) {\n      throw new Error(\n        \"The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.\",\n      );\n    }\n    if (opts.allowReturnOutsideFunction != null) {\n      throw new Error(\n        \"`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.\",\n      );\n    }\n    if (opts.allowNewTargetOutsideFunction != null) {\n      throw new Error(\n        \"`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.\",\n      );\n    }\n  }\n\n  return options;\n}\n","import type { TokenType } from \"../tokenizer/types.ts\";\nimport type Parser from \"../parser/index.ts\";\nimport type * as N from \"../types.ts\";\nimport type { Node as NodeType, NodeBase, File } from \"../types.ts\";\nimport type { Position } from \"../util/location.ts\";\nimport { Errors } from \"../parse-error.ts\";\nimport type { Undone } from \"../parser/node.ts\";\nimport type { BindingFlag } from \"../util/scopeflags.ts\";\nimport { OptionFlags } from \"../options.ts\";\nimport type { ExpressionErrors } from \"../parser/util.ts\";\n\nconst { defineProperty } = Object;\nconst toUnenumerable = (object: any, key: string) => {\n  if (object) {\n    defineProperty(object, key, { enumerable: false, value: object[key] });\n  }\n};\n\nfunction toESTreeLocation(node: any) {\n  toUnenumerable(node.loc.start, \"index\");\n  toUnenumerable(node.loc.end, \"index\");\n\n  return node;\n}\n\nexport default (superClass: typeof Parser) =>\n  class ESTreeParserMixin extends superClass implements Parser {\n    parse(): File {\n      const file = toESTreeLocation(super.parse());\n\n      if (this.optionFlags & OptionFlags.Tokens) {\n        file.tokens = file.tokens.map(toESTreeLocation);\n      }\n\n      return file;\n    }\n\n    // @ts-expect-error ESTree plugin changes node types\n    parseRegExpLiteral({ pattern, flags }): N.EstreeRegExpLiteral {\n      let regex: RegExp | null = null;\n      try {\n        regex = new RegExp(pattern, flags);\n      } catch (_) {\n        // In environments that don't support these flags value will\n        // be null as the regex can't be represented natively.\n      }\n      const node = this.estreeParseLiteral<N.EstreeRegExpLiteral>(regex);\n      node.regex = { pattern, flags };\n\n      return node;\n    }\n\n    // @ts-expect-error ESTree plugin changes node types\n    parseBigIntLiteral(value: any): N.Node {\n      // https://github.com/estree/estree/blob/master/es2020.md#bigintliteral\n      let bigInt: bigint | null;\n      try {\n        bigInt = BigInt(value);\n      } catch {\n        bigInt = null;\n      }\n      const node = this.estreeParseLiteral<N.EstreeBigIntLiteral>(bigInt);\n      node.bigint = String(node.value || value);\n\n      return node;\n    }\n\n    // @ts-expect-error ESTree plugin changes node types\n    parseDecimalLiteral(value: any): N.Node {\n      // https://github.com/estree/estree/blob/master/experimental/decimal.md\n      // todo: use BigDecimal when node supports it.\n      const decimal: null = null;\n      const node = this.estreeParseLiteral(decimal);\n      node.decimal = String(node.value || value);\n\n      return node;\n    }\n\n    estreeParseLiteral<T extends N.EstreeLiteral>(value: any) {\n      // @ts-expect-error ESTree plugin changes node types\n      return this.parseLiteral<T>(value, \"Literal\");\n    }\n\n    // @ts-expect-error ESTree plugin changes node types\n    parseStringLiteral(value: any): N.Node {\n      return this.estreeParseLiteral(value);\n    }\n\n    parseNumericLiteral(value: any): any {\n      return this.estreeParseLiteral(value);\n    }\n\n    // @ts-expect-error ESTree plugin changes node types\n    parseNullLiteral(): N.Node {\n      return this.estreeParseLiteral(null);\n    }\n\n    parseBooleanLiteral(value: boolean): N.BooleanLiteral {\n      // @ts-expect-error ESTree plugin changes node types\n      return this.estreeParseLiteral(value);\n    }\n\n    // https://github.com/estree/estree/blob/master/es2020.md#chainexpression\n    estreeParseChainExpression(\n      node: N.Expression,\n      endLoc: Position,\n    ): N.EstreeChainExpression {\n      const chain = this.startNodeAtNode<N.EstreeChainExpression>(node);\n      chain.expression = node;\n      return this.finishNodeAt(chain, \"ChainExpression\", endLoc);\n    }\n\n    // Cast a Directive to an ExpressionStatement. Mutates the input Directive.\n    directiveToStmt(directive: N.Directive): N.ExpressionStatement {\n      const expression = directive.value as any as N.EstreeLiteral;\n      delete directive.value;\n\n      this.castNodeTo(expression, \"Literal\");\n      expression.raw = expression.extra.raw;\n      expression.value = expression.extra.expressionValue;\n\n      const stmt = this.castNodeTo(directive, \"ExpressionStatement\");\n      stmt.expression = expression;\n      stmt.directive = expression.extra.rawValue;\n\n      delete expression.extra;\n\n      return stmt;\n    }\n\n    /**\n     * The TS-ESLint always define optional AST properties, here we provide the\n     * default value for such properties immediately after `finishNode` was invoked.\n     * This hook will be implemented by the typescript plugin.\n     *\n     * Note: This hook should be manually invoked when we change the `type` of a given AST\n     * node, to ensure that the optional properties are correctly filled.\n     * @param node The AST node finished by finishNode\n     */\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    fillOptionalPropertiesForTSESLint(node: NodeType) {}\n\n    cloneEstreeStringLiteral(node: N.EstreeLiteral): N.EstreeLiteral {\n      const { start, end, loc, range, raw, value } = node;\n      const cloned = Object.create(node.constructor.prototype);\n      cloned.type = \"Literal\";\n      cloned.start = start;\n      cloned.end = end;\n      cloned.loc = loc;\n      cloned.range = range;\n      cloned.raw = raw;\n      cloned.value = value;\n      return cloned;\n    }\n\n    // ==================================\n    // Overrides\n    // ==================================\n\n    initFunction(node: N.BodilessFunctionOrMethodBase, isAsync: boolean): void {\n      super.initFunction(node, isAsync);\n      node.expression = false;\n    }\n\n    checkDeclaration(node: N.Pattern | N.ObjectProperty): void {\n      if (node != null && this.isObjectProperty(node)) {\n        // @ts-expect-error plugin typings\n        this.checkDeclaration((node as unknown as N.EstreeProperty).value);\n      } else {\n        super.checkDeclaration(node);\n      }\n    }\n\n    getObjectOrClassMethodParams(method: N.ObjectMethod | N.ClassMethod) {\n      return (method as unknown as N.EstreeMethodDefinition).value.params;\n    }\n\n    isValidDirective(stmt: N.Statement): stmt is N.ExpressionStatement {\n      return (\n        stmt.type === \"ExpressionStatement\" &&\n        stmt.expression.type === \"Literal\" &&\n        typeof stmt.expression.value === \"string\" &&\n        !stmt.expression.extra?.parenthesized\n      );\n    }\n\n    parseBlockBody(\n      node: N.BlockStatementLike,\n      allowDirectives: boolean | undefined | null,\n      topLevel: boolean,\n      end: TokenType,\n      afterBlockParse?: (hasStrictModeDirective: boolean) => void,\n    ): void {\n      super.parseBlockBody(\n        node,\n        allowDirectives,\n        topLevel,\n        end,\n        afterBlockParse,\n      );\n\n      const directiveStatements = node.directives.map(d =>\n        this.directiveToStmt(d),\n      );\n      // @ts-expect-error estree plugin typings\n      node.body = directiveStatements.concat(node.body);\n      delete node.directives;\n    }\n\n    parsePrivateName(): any {\n      const node = super.parsePrivateName();\n      if (!process.env.BABEL_8_BREAKING) {\n        if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n          return node;\n        }\n      }\n      return this.convertPrivateNameToPrivateIdentifier(node);\n    }\n\n    convertPrivateNameToPrivateIdentifier(\n      node: N.PrivateName,\n    ): N.EstreePrivateIdentifier {\n      const name = super.getPrivateNameSV(node);\n      node = node as any;\n      delete node.id;\n      // @ts-expect-error mutate AST types\n      node.name = name;\n      return this.castNodeTo(node, \"PrivateIdentifier\");\n    }\n\n    // @ts-expect-error ESTree plugin changes node types\n    isPrivateName(node: N.Node): node is N.EstreePrivateIdentifier {\n      if (!process.env.BABEL_8_BREAKING) {\n        if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n          return super.isPrivateName(node);\n        }\n      }\n      return node.type === \"PrivateIdentifier\";\n    }\n\n    // @ts-expect-error ESTree plugin changes node types\n    getPrivateNameSV(node: N.EstreePrivateIdentifier): string {\n      if (!process.env.BABEL_8_BREAKING) {\n        if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n          return super.getPrivateNameSV(node as unknown as N.PrivateName);\n        }\n      }\n      return node.name;\n    }\n\n    // @ts-expect-error plugin may override interfaces\n    parseLiteral<T extends N.Literal>(value: any, type: T[\"type\"]): T {\n      const node = super.parseLiteral<T>(value, type);\n      // @ts-expect-error mutating AST types\n      node.raw = node.extra.raw;\n      delete node.extra;\n\n      return node;\n    }\n\n    parseFunctionBody(\n      node: N.Function,\n      allowExpression?: boolean | null,\n      isMethod: boolean = false,\n    ): void {\n      super.parseFunctionBody(node, allowExpression, isMethod);\n      node.expression = node.body.type !== \"BlockStatement\";\n    }\n\n    // @ts-expect-error plugin may override interfaces\n    parseMethod<\n      T extends N.ClassPrivateMethod | N.ObjectMethod | N.ClassMethod,\n    >(\n      node: Undone<T>,\n      isGenerator: boolean,\n      isAsync: boolean,\n      isConstructor: boolean,\n      allowDirectSuper: boolean,\n      type: T[\"type\"],\n      inClassScope: boolean = false,\n    ):\n      | N.EstreeProperty\n      | N.EstreeMethodDefinition\n      | N.EstreeTSAbstractMethodDefinition {\n      let funcNode = this.startNode<N.MethodLike>();\n      funcNode.kind = node.kind; // provide kind, so super method correctly sets state\n      funcNode = super.parseMethod(\n        funcNode,\n        isGenerator,\n        isAsync,\n        isConstructor,\n        allowDirectSuper,\n        type,\n        inClassScope,\n      );\n      delete funcNode.kind;\n      const { typeParameters } = node;\n      if (typeParameters) {\n        delete node.typeParameters;\n        funcNode.typeParameters = typeParameters;\n        this.resetStartLocationFromNode(funcNode, typeParameters);\n      }\n      const valueNode = this.castNodeTo(\n        funcNode as N.MethodLike,\n        process.env.BABEL_8_BREAKING &&\n          this.hasPlugin(\"typescript\") &&\n          !funcNode.body\n          ? \"TSEmptyBodyFunctionExpression\"\n          : \"FunctionExpression\",\n      );\n      (\n        node as unknown as Undone<\n          | N.EstreeProperty\n          | N.EstreeMethodDefinition\n          | N.EstreeTSAbstractMethodDefinition\n        >\n      ).value = valueNode;\n      if (type === \"ClassPrivateMethod\") {\n        node.computed = false;\n      }\n      if (process.env.BABEL_8_BREAKING && this.hasPlugin(\"typescript\")) {\n        // @ts-expect-error todo(flow->ts) property not defined for all types in union\n        if (node.abstract) {\n          // @ts-expect-error remove abstract from TSAbstractMethodDefinition\n          delete node.abstract;\n          return this.finishNode(\n            // @ts-expect-error cast methods to estree types\n            node as Undone<N.EstreeTSAbstractMethodDefinition>,\n            \"TSAbstractMethodDefinition\",\n          );\n        }\n      }\n      if (type === \"ObjectMethod\") {\n        if ((node as any as N.ObjectMethod).kind === \"method\") {\n          (node as any as N.EstreeProperty).kind = \"init\";\n        }\n        (node as any as N.EstreeProperty).shorthand = false;\n        return this.finishNode(\n          // @ts-expect-error cast methods to estree types\n          node as Undone<N.EstreeProperty>,\n          \"Property\",\n        );\n      } else {\n        return this.finishNode(\n          // @ts-expect-error cast methods to estree types\n          node as Undone<N.EstreeMethodDefinition>,\n          \"MethodDefinition\",\n        );\n      }\n    }\n\n    nameIsConstructor(key: N.Expression | N.PrivateName): boolean {\n      if (key.type === \"Literal\") return key.value === \"constructor\";\n      return super.nameIsConstructor(key);\n    }\n\n    parseClassProperty(...args: [N.ClassProperty]): any {\n      const propertyNode = super.parseClassProperty(...args);\n      if (!process.env.BABEL_8_BREAKING) {\n        if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n          return propertyNode as unknown as N.EstreePropertyDefinition;\n        }\n      }\n      if (\n        process.env.BABEL_8_BREAKING &&\n        propertyNode.abstract &&\n        this.hasPlugin(\"typescript\")\n      ) {\n        delete propertyNode.abstract;\n        this.castNodeTo(propertyNode, \"TSAbstractPropertyDefinition\");\n      } else {\n        this.castNodeTo(propertyNode, \"PropertyDefinition\");\n      }\n      return propertyNode;\n    }\n\n    parseClassPrivateProperty(...args: [N.ClassPrivateProperty]): any {\n      const propertyNode = super.parseClassPrivateProperty(...args);\n      if (!process.env.BABEL_8_BREAKING) {\n        if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n          return propertyNode as unknown as N.EstreePropertyDefinition;\n        }\n      }\n      if (\n        process.env.BABEL_8_BREAKING &&\n        propertyNode.abstract &&\n        this.hasPlugin(\"typescript\")\n      ) {\n        this.castNodeTo(propertyNode, \"TSAbstractPropertyDefinition\");\n      } else {\n        this.castNodeTo(propertyNode, \"PropertyDefinition\");\n      }\n      propertyNode.computed = false;\n      return propertyNode;\n    }\n\n    parseClassAccessorProperty(\n      this: Parser,\n      node: N.ClassAccessorProperty,\n    ): any {\n      const accessorPropertyNode = super.parseClassAccessorProperty(node);\n      if (!process.env.BABEL_8_BREAKING) {\n        if (!this.getPluginOption(\"estree\", \"classFeatures\")) {\n          return accessorPropertyNode;\n        }\n      }\n      if (accessorPropertyNode.abstract && this.hasPlugin(\"typescript\")) {\n        delete accessorPropertyNode.abstract;\n        this.castNodeTo(accessorPropertyNode, \"TSAbstractAccessorProperty\");\n      } else {\n        this.castNodeTo(accessorPropertyNode, \"AccessorProperty\");\n      }\n      return accessorPropertyNode;\n    }\n\n    parseObjectProperty(\n      prop: N.ObjectProperty,\n      startLoc: Position | undefined | null,\n      isPattern: boolean,\n      refExpressionErrors?: ExpressionErrors | null,\n    ): N.ObjectProperty | undefined | null {\n      const node: N.EstreeProperty = super.parseObjectProperty(\n        prop,\n        startLoc,\n        isPattern,\n        refExpressionErrors,\n      ) as any;\n\n      if (node) {\n        node.kind = \"init\";\n        this.castNodeTo(node, \"Property\");\n      }\n\n      return node as any;\n    }\n\n    finishObjectProperty(node: Undone<N.ObjectProperty>): N.ObjectProperty {\n      (node as unknown as Undone<N.EstreeProperty>).kind = \"init\";\n      return this.finishNode(\n        node as unknown as Undone<N.EstreeProperty>,\n        \"Property\",\n      ) as any;\n    }\n\n    isValidLVal(\n      type: string,\n      isUnparenthesizedInAssign: boolean,\n      binding: BindingFlag,\n    ) {\n      return type === \"Property\"\n        ? \"value\"\n        : super.isValidLVal(type, isUnparenthesizedInAssign, binding);\n    }\n\n    isAssignable(node: N.Node, isBinding?: boolean): boolean {\n      if (node != null && this.isObjectProperty(node)) {\n        return this.isAssignable(node.value, isBinding);\n      }\n      return super.isAssignable(node, isBinding);\n    }\n\n    toAssignable(node: N.Node, isLHS: boolean = false): void {\n      if (node != null && this.isObjectProperty(node)) {\n        const { key, value } = node;\n        if (this.isPrivateName(key)) {\n          this.classScope.usePrivateName(\n            this.getPrivateNameSV(key),\n            key.loc.start,\n          );\n        }\n        this.toAssignable(value, isLHS);\n      } else {\n        super.toAssignable(node, isLHS);\n      }\n    }\n\n    toAssignableObjectExpressionProp(\n      prop: N.Node,\n      isLast: boolean,\n      isLHS: boolean,\n    ) {\n      if (\n        prop.type === \"Property\" &&\n        (prop.kind === \"get\" || prop.kind === \"set\")\n      ) {\n        this.raise(Errors.PatternHasAccessor, prop.key);\n      } else if (prop.type === \"Property\" && prop.method) {\n        this.raise(Errors.PatternHasMethod, prop.key);\n      } else {\n        super.toAssignableObjectExpressionProp(prop, isLast, isLHS);\n      }\n    }\n\n    finishCallExpression<T extends N.CallExpression | N.OptionalCallExpression>(\n      unfinished: Undone<T>,\n      optional: boolean,\n    ): T {\n      const node = super.finishCallExpression(unfinished, optional);\n\n      if (node.callee.type === \"Import\") {\n        this.castNodeTo(node, \"ImportExpression\");\n        (node as N.Node as N.EstreeImportExpression).source = node\n          .arguments[0] as N.Expression;\n        (node as N.Node as N.EstreeImportExpression).options =\n          (node.arguments[1] as N.Expression) ?? null;\n        if (!process.env.BABEL_8_BREAKING) {\n          // compatibility with previous ESTree AST\n          (node as N.Node as N.EstreeImportExpression).attributes =\n            (node.arguments[1] as N.Expression) ?? null;\n        }\n        // arguments isn't optional in the type definition\n        delete node.arguments;\n        // callee isn't optional in the type definition\n        delete node.callee;\n      } else if (node.type === \"OptionalCallExpression\") {\n        this.castNodeTo(node, \"CallExpression\");\n      } else {\n        node.optional = false;\n      }\n\n      return node;\n    }\n\n    toReferencedArguments(\n      node:\n        | N.CallExpression\n        | N.OptionalCallExpression\n        | N.EstreeImportExpression,\n      /* isParenthesizedExpr?: boolean, */\n    ) {\n      // ImportExpressions do not have an arguments array.\n      if (node.type === \"ImportExpression\") {\n        return;\n      }\n\n      super.toReferencedArguments(node);\n    }\n\n    parseExport(\n      unfinished: Undone<N.AnyExport>,\n      decorators: N.Decorator[] | null,\n    ) {\n      const exportStartLoc = this.state.lastTokStartLoc;\n      const node = super.parseExport(unfinished, decorators);\n\n      switch (node.type) {\n        case \"ExportAllDeclaration\":\n          // @ts-expect-error mutating AST types\n          node.exported = null;\n          break;\n\n        case \"ExportNamedDeclaration\":\n          if (\n            node.specifiers.length === 1 &&\n            node.specifiers[0].type === \"ExportNamespaceSpecifier\"\n          ) {\n            this.castNodeTo(node, \"ExportAllDeclaration\");\n            // @ts-expect-error mutating AST types\n            node.exported = node.specifiers[0].exported;\n            delete node.specifiers;\n          }\n\n        // fallthrough\n        case \"ExportDefaultDeclaration\":\n          {\n            const { declaration } = node;\n            if (\n              declaration?.type === \"ClassDeclaration\" &&\n              declaration.decorators?.length > 0 &&\n              // decorator comes before export\n              declaration.start === node.start\n            ) {\n              this.resetStartLocation(\n                node,\n                // For compatibility with ESLint's keyword-spacing rule, which assumes that an\n                // export declaration must start with export.\n                // https://github.com/babel/babel/issues/15085\n                // Here we reset export declaration's start to be the start of the export token\n                exportStartLoc,\n              );\n            }\n          }\n\n          break;\n      }\n\n      return node;\n    }\n\n    stopParseSubscript(base: N.Expression, state: N.ParseSubscriptState) {\n      const node = super.stopParseSubscript(base, state);\n      if (state.optionalChainMember) {\n        return this.estreeParseChainExpression(node, base.loc.end);\n      }\n      return node;\n    }\n\n    parseMember(\n      base: N.Expression,\n      startLoc: Position,\n      state: N.ParseSubscriptState,\n      computed: boolean,\n      optional: boolean,\n    ) {\n      const node = super.parseMember(base, startLoc, state, computed, optional);\n      if (node.type === \"OptionalMemberExpression\") {\n        this.castNodeTo(node, \"MemberExpression\");\n      } else {\n        node.optional = false;\n      }\n      return node;\n    }\n\n    isOptionalMemberExpression(node: N.Node) {\n      if (node.type === \"ChainExpression\") {\n        return node.expression.type === \"MemberExpression\";\n      }\n      return super.isOptionalMemberExpression(node);\n    }\n\n    hasPropertyAsPrivateName(node: N.Node): boolean {\n      if (node.type === \"ChainExpression\") {\n        node = node.expression;\n      }\n      return super.hasPropertyAsPrivateName(node);\n    }\n\n    // @ts-expect-error ESTree plugin changes node types\n    isObjectProperty(node: N.Node): node is N.EstreeProperty {\n      return node.type === \"Property\" && node.kind === \"init\" && !node.method;\n    }\n\n    // @ts-expect-error ESTree plugin changes node types\n    isObjectMethod(node: N.Node): node is N.EstreeProperty {\n      return (\n        node.type === \"Property\" &&\n        (node.method || node.kind === \"get\" || node.kind === \"set\")\n      );\n    }\n\n    /* ============================================================ *\n     * parser/node.ts                                               *\n     * ============================================================ */\n\n    castNodeTo<T extends N.Node[\"type\"]>(\n      node: N.Node,\n      type: T,\n    ): Extract<N.Node, { type: T }> {\n      const result = super.castNodeTo(node, type);\n      this.fillOptionalPropertiesForTSESLint(result);\n      return result;\n    }\n\n    cloneIdentifier<T extends N.Identifier | N.Placeholder>(node: T): T {\n      const cloned = super.cloneIdentifier(node);\n      this.fillOptionalPropertiesForTSESLint(cloned);\n      return cloned;\n    }\n\n    cloneStringLiteral<\n      T extends N.EstreeLiteral | N.StringLiteral | N.Placeholder,\n    >(node: T): T {\n      if (node.type === \"Literal\") {\n        return this.cloneEstreeStringLiteral(node) as T;\n      }\n      return super.cloneStringLiteral(node);\n    }\n\n    finishNodeAt<T extends NodeType>(\n      node: Undone<T>,\n      type: T[\"type\"],\n      endLoc: Position,\n    ): T {\n      return toESTreeLocation(super.finishNodeAt(node, type, endLoc));\n    }\n\n    // Override for TS-ESLint that does not allow optional AST properties\n    finishNode<T extends NodeType>(node: Undone<T>, type: T[\"type\"]): T {\n      const result = super.finishNode(node, type);\n      this.fillOptionalPropertiesForTSESLint(result);\n      return result;\n    }\n\n    resetStartLocation(node: N.Node, startLoc: Position) {\n      super.resetStartLocation(node, startLoc);\n      toESTreeLocation(node);\n    }\n\n    resetEndLocation(\n      node: NodeBase,\n      endLoc: Position = this.state.lastTokEndLoc,\n    ): void {\n      super.resetEndLocation(node, endLoc);\n      toESTreeLocation(node);\n    }\n  };\n","// The token context is used in JSX plugin to track\n// jsx tag / jsx text / normal JavaScript expression\n\nexport class TokContext {\n  constructor(token: string, preserveSpace?: boolean) {\n    this.token = token;\n    this.preserveSpace = !!preserveSpace;\n  }\n\n  token: string;\n  preserveSpace: boolean;\n}\n\nconst types: {\n  [key: string]: TokContext;\n} = {\n  brace: new TokContext(\"{\"), // normal JavaScript expression\n  j_oTag: new TokContext(\"<tag\"), // JSX opening tag\n  j_cTag: new TokContext(\"</tag\"), // JSX closing tag\n  j_expr: new TokContext(\"<tag>...</tag>\", true), // JSX expressions\n};\n\nif (!process.env.BABEL_8_BREAKING) {\n  types.template = new TokContext(\"`\", true);\n}\n\nexport { types };\n","import { types as tc, type TokContext } from \"./context.ts\";\n// ## Token types\n\n// The assignment of fine-grained, information-carrying type objects\n// allows the tokenizer to store the information it has about a\n// token in a way that is very cheap for the parser to look up.\n\n// All token type variables start with an underscore, to make them\n// easy to recognize.\n\n// The `beforeExpr` property is used to disambiguate between 1) binary\n// expression (<) and JSX Tag start (<name>); 2) object literal and JSX\n// texts. It is set on the `updateContext` function in the JSX plugin.\n\n// The `startsExpr` property is used to determine whether an expression\n// may be the “argument” subexpression of a `yield` expression or\n// `yield` statement. It is set on all token types that may be at the\n// start of a subexpression.\n\n// `isLoop` marks a keyword as starting a loop, which is important\n// to know when parsing a label, in order to allow or disallow\n// continue jumps to that label.\n\nconst beforeExpr = true;\nconst startsExpr = true;\nconst isLoop = true;\nconst isAssign = true;\nconst prefix = true;\nconst postfix = true;\n\ntype TokenOptions = {\n  keyword?: string;\n  beforeExpr?: boolean;\n  startsExpr?: boolean;\n  rightAssociative?: boolean;\n  isLoop?: boolean;\n  isAssign?: boolean;\n  prefix?: boolean;\n  postfix?: boolean;\n  binop?: number | null;\n};\n\n// Internally the tokenizer stores token as a number\nexport type TokenType = number;\n\n// The `ExportedTokenType` is exported via `tokTypes` and accessible\n// when `tokens: true` is enabled. Unlike internal token type, it provides\n// metadata of the tokens.\nexport class ExportedTokenType {\n  label: string;\n  keyword: string | undefined | null;\n  beforeExpr: boolean;\n  startsExpr: boolean;\n  rightAssociative: boolean;\n  isLoop: boolean;\n  isAssign: boolean;\n  prefix: boolean;\n  postfix: boolean;\n  binop: number | undefined | null;\n  // todo(Babel 8): remove updateContext from exposed token layout\n  declare updateContext:\n    | ((context: Array<TokContext>) => void)\n    | undefined\n    | null;\n\n  constructor(label: string, conf: TokenOptions = {}) {\n    this.label = label;\n    this.keyword = conf.keyword;\n    this.beforeExpr = !!conf.beforeExpr;\n    this.startsExpr = !!conf.startsExpr;\n    this.rightAssociative = !!conf.rightAssociative;\n    this.isLoop = !!conf.isLoop;\n    this.isAssign = !!conf.isAssign;\n    this.prefix = !!conf.prefix;\n    this.postfix = !!conf.postfix;\n    this.binop = conf.binop != null ? conf.binop : null;\n    if (!process.env.BABEL_8_BREAKING) {\n      this.updateContext = null;\n    }\n  }\n}\n\n// A map from keyword/keyword-like string value to the token type\nexport const keywords = new Map<string, TokenType>();\n\nfunction createKeyword(name: string, options: TokenOptions = {}): TokenType {\n  options.keyword = name;\n  const token = createToken(name, options);\n  keywords.set(name, token);\n  return token;\n}\n\nfunction createBinop(name: string, binop: number) {\n  return createToken(name, { beforeExpr, binop });\n}\n\nlet tokenTypeCounter = -1;\nexport const tokenTypes: ExportedTokenType[] = [];\nconst tokenLabels: string[] = [];\nconst tokenBinops: number[] = [];\nconst tokenBeforeExprs: boolean[] = [];\nconst tokenStartsExprs: boolean[] = [];\nconst tokenPrefixes: boolean[] = [];\n\nfunction createToken(name: string, options: TokenOptions = {}): TokenType {\n  ++tokenTypeCounter;\n  tokenLabels.push(name);\n  tokenBinops.push(options.binop ?? -1);\n  tokenBeforeExprs.push(options.beforeExpr ?? false);\n  tokenStartsExprs.push(options.startsExpr ?? false);\n  tokenPrefixes.push(options.prefix ?? false);\n  tokenTypes.push(new ExportedTokenType(name, options));\n\n  return tokenTypeCounter;\n}\n\nfunction createKeywordLike(\n  name: string,\n  options: TokenOptions = {},\n): TokenType {\n  ++tokenTypeCounter;\n  keywords.set(name, tokenTypeCounter);\n  tokenLabels.push(name);\n  tokenBinops.push(options.binop ?? -1);\n  tokenBeforeExprs.push(options.beforeExpr ?? false);\n  tokenStartsExprs.push(options.startsExpr ?? false);\n  tokenPrefixes.push(options.prefix ?? false);\n  // In the exported token type, we set the label as \"name\" for backward compatibility with Babel 7\n  tokenTypes.push(new ExportedTokenType(\"name\", options));\n\n  return tokenTypeCounter;\n}\n\n// For performance the token type helpers depend on the following declarations order.\n// When adding new token types, please also check if the token helpers need update.\n\nexport type InternalTokenTypes = typeof tt;\n\nexport const tt = {\n  // Punctuation token types.\n  bracketL: createToken(\"[\", { beforeExpr, startsExpr }),\n  // TODO: Remove this in Babel 8\n  bracketHashL: createToken(\"#[\", { beforeExpr, startsExpr }),\n  // TODO: Remove this in Babel 8\n  bracketBarL: createToken(\"[|\", { beforeExpr, startsExpr }),\n  bracketR: createToken(\"]\"),\n  // TODO: Remove this in Babel 8\n  bracketBarR: createToken(\"|]\"),\n  braceL: createToken(\"{\", { beforeExpr, startsExpr }),\n  // TODO: Remove this in Babel 8\n  braceBarL: createToken(\"{|\", { beforeExpr, startsExpr }),\n  // TODO: Remove this in Babel 8\n  braceHashL: createToken(\"#{\", { beforeExpr, startsExpr }),\n  braceR: createToken(\"}\"),\n  braceBarR: createToken(\"|}\"),\n  parenL: createToken(\"(\", { beforeExpr, startsExpr }),\n  parenR: createToken(\")\"),\n  comma: createToken(\",\", { beforeExpr }),\n  semi: createToken(\";\", { beforeExpr }),\n  colon: createToken(\":\", { beforeExpr }),\n  doubleColon: createToken(\"::\", { beforeExpr }),\n  dot: createToken(\".\"),\n  question: createToken(\"?\", { beforeExpr }),\n  questionDot: createToken(\"?.\"),\n  arrow: createToken(\"=>\", { beforeExpr }),\n  template: createToken(\"template\"),\n  ellipsis: createToken(\"...\", { beforeExpr }),\n  backQuote: createToken(\"`\", { startsExpr }),\n  dollarBraceL: createToken(\"${\", { beforeExpr, startsExpr }),\n  // start: isTemplate\n  templateTail: createToken(\"...`\", { startsExpr }),\n  templateNonTail: createToken(\"...${\", { beforeExpr, startsExpr }),\n  // end: isTemplate\n  at: createToken(\"@\"),\n  hash: createToken(\"#\", { startsExpr }),\n\n  // Special hashbang token.\n  interpreterDirective: createToken(\"#!...\"),\n\n  // Operators. These carry several kinds of properties to help the\n  // parser use them properly (the presence of these properties is\n  // what categorizes them as operators).\n  //\n  // `binop`, when present, specifies that this operator is a binary\n  // operator, and will refer to its precedence.\n  //\n  // `prefix` and `postfix` mark the operator as a prefix or postfix\n  // unary operator.\n  //\n  // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as\n  // binary operators with a very low precedence, that should result\n  // in AssignmentExpression nodes.\n\n  // start: isAssign\n  eq: createToken(\"=\", { beforeExpr, isAssign }),\n  assign: createToken(\"_=\", { beforeExpr, isAssign }),\n  slashAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n  // These are only needed to support % and ^ as a Hack-pipe topic token.\n  // When the proposal settles on a token, the others can be merged with\n  // tt.assign.\n  xorAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n  moduloAssign: createToken(\"_=\", { beforeExpr, isAssign }),\n  // end: isAssign\n\n  incDec: createToken(\"++/--\", { prefix, postfix, startsExpr }),\n  bang: createToken(\"!\", { beforeExpr, prefix, startsExpr }),\n  tilde: createToken(\"~\", { beforeExpr, prefix, startsExpr }),\n\n  // More possible topic tokens.\n  // When the proposal settles on a token, at least one of these may be removed.\n  doubleCaret: createToken(\"^^\", { startsExpr }),\n  doubleAt: createToken(\"@@\", { startsExpr }),\n\n  // start: isBinop\n  pipeline: createBinop(\"|>\", 0),\n  nullishCoalescing: createBinop(\"??\", 1),\n  logicalOR: createBinop(\"||\", 1),\n  logicalAND: createBinop(\"&&\", 2),\n  bitwiseOR: createBinop(\"|\", 3),\n  bitwiseXOR: createBinop(\"^\", 4),\n  bitwiseAND: createBinop(\"&\", 5),\n  equality: createBinop(\"==/!=/===/!==\", 6),\n  lt: createBinop(\"</>/<=/>=\", 7),\n  gt: createBinop(\"</>/<=/>=\", 7),\n  relational: createBinop(\"</>/<=/>=\", 7),\n  bitShift: createBinop(\"<</>>/>>>\", 8),\n  bitShiftL: createBinop(\"<</>>/>>>\", 8),\n  bitShiftR: createBinop(\"<</>>/>>>\", 8),\n  plusMin: createToken(\"+/-\", { beforeExpr, binop: 9, prefix, startsExpr }),\n  // startsExpr: required by v8intrinsic plugin\n  modulo: createToken(\"%\", { binop: 10, startsExpr }),\n  // unset `beforeExpr` as it can be `function *`\n  star: createToken(\"*\", { binop: 10 }),\n  slash: createBinop(\"/\", 10),\n  exponent: createToken(\"**\", {\n    beforeExpr,\n    binop: 11,\n    rightAssociative: true,\n  }),\n\n  // Keywords\n  // Don't forget to update packages/babel-helper-validator-identifier/src/keyword.js\n  // when new keywords are added\n  // start: isLiteralPropertyName\n  // start: isKeyword\n  _in: createKeyword(\"in\", { beforeExpr, binop: 7 }),\n  _instanceof: createKeyword(\"instanceof\", { beforeExpr, binop: 7 }),\n  // end: isBinop\n  _break: createKeyword(\"break\"),\n  _case: createKeyword(\"case\", { beforeExpr }),\n  _catch: createKeyword(\"catch\"),\n  _continue: createKeyword(\"continue\"),\n  _debugger: createKeyword(\"debugger\"),\n  _default: createKeyword(\"default\", { beforeExpr }),\n  _else: createKeyword(\"else\", { beforeExpr }),\n  _finally: createKeyword(\"finally\"),\n  _function: createKeyword(\"function\", { startsExpr }),\n  _if: createKeyword(\"if\"),\n  _return: createKeyword(\"return\", { beforeExpr }),\n  _switch: createKeyword(\"switch\"),\n  _throw: createKeyword(\"throw\", { beforeExpr, prefix, startsExpr }),\n  _try: createKeyword(\"try\"),\n  _var: createKeyword(\"var\"),\n  _const: createKeyword(\"const\"),\n  _with: createKeyword(\"with\"),\n  _new: createKeyword(\"new\", { beforeExpr, startsExpr }),\n  _this: createKeyword(\"this\", { startsExpr }),\n  _super: createKeyword(\"super\", { startsExpr }),\n  _class: createKeyword(\"class\", { startsExpr }),\n  _extends: createKeyword(\"extends\", { beforeExpr }),\n  _export: createKeyword(\"export\"),\n  _import: createKeyword(\"import\", { startsExpr }),\n  _null: createKeyword(\"null\", { startsExpr }),\n  _true: createKeyword(\"true\", { startsExpr }),\n  _false: createKeyword(\"false\", { startsExpr }),\n  _typeof: createKeyword(\"typeof\", { beforeExpr, prefix, startsExpr }),\n  _void: createKeyword(\"void\", { beforeExpr, prefix, startsExpr }),\n  _delete: createKeyword(\"delete\", { beforeExpr, prefix, startsExpr }),\n  // start: isLoop\n  _do: createKeyword(\"do\", { isLoop, beforeExpr }),\n  _for: createKeyword(\"for\", { isLoop }),\n  _while: createKeyword(\"while\", { isLoop }),\n  // end: isLoop\n  // end: isKeyword\n\n  // Primary literals\n  // start: isIdentifier\n  _as: createKeywordLike(\"as\", { startsExpr }),\n  _assert: createKeywordLike(\"assert\", { startsExpr }),\n  _async: createKeywordLike(\"async\", { startsExpr }),\n  _await: createKeywordLike(\"await\", { startsExpr }),\n  _defer: createKeywordLike(\"defer\", { startsExpr }),\n  _from: createKeywordLike(\"from\", { startsExpr }),\n  _get: createKeywordLike(\"get\", { startsExpr }),\n  _let: createKeywordLike(\"let\", { startsExpr }),\n  _meta: createKeywordLike(\"meta\", { startsExpr }),\n  _of: createKeywordLike(\"of\", { startsExpr }),\n  _sent: createKeywordLike(\"sent\", { startsExpr }),\n  _set: createKeywordLike(\"set\", { startsExpr }),\n  _source: createKeywordLike(\"source\", { startsExpr }),\n  _static: createKeywordLike(\"static\", { startsExpr }),\n  _using: createKeywordLike(\"using\", { startsExpr }),\n  _yield: createKeywordLike(\"yield\", { startsExpr }),\n\n  // Flow and TypeScript Keywordlike\n  _asserts: createKeywordLike(\"asserts\", { startsExpr }),\n  _checks: createKeywordLike(\"checks\", { startsExpr }),\n  _exports: createKeywordLike(\"exports\", { startsExpr }),\n  _global: createKeywordLike(\"global\", { startsExpr }),\n  _implements: createKeywordLike(\"implements\", { startsExpr }),\n  _intrinsic: createKeywordLike(\"intrinsic\", { startsExpr }),\n  _infer: createKeywordLike(\"infer\", { startsExpr }),\n  _is: createKeywordLike(\"is\", { startsExpr }),\n  _mixins: createKeywordLike(\"mixins\", { startsExpr }),\n  _proto: createKeywordLike(\"proto\", { startsExpr }),\n  _require: createKeywordLike(\"require\", { startsExpr }),\n  _satisfies: createKeywordLike(\"satisfies\", { startsExpr }),\n  // start: isTSTypeOperator\n  _keyof: createKeywordLike(\"keyof\", { startsExpr }),\n  _readonly: createKeywordLike(\"readonly\", { startsExpr }),\n  _unique: createKeywordLike(\"unique\", { startsExpr }),\n  // end: isTSTypeOperator\n  // start: isTSDeclarationStart\n  _abstract: createKeywordLike(\"abstract\", { startsExpr }),\n  _declare: createKeywordLike(\"declare\", { startsExpr }),\n  _enum: createKeywordLike(\"enum\", { startsExpr }),\n  _module: createKeywordLike(\"module\", { startsExpr }),\n  _namespace: createKeywordLike(\"namespace\", { startsExpr }),\n  // start: isFlowInterfaceOrTypeOrOpaque\n  _interface: createKeywordLike(\"interface\", { startsExpr }),\n  _type: createKeywordLike(\"type\", { startsExpr }),\n  // end: isTSDeclarationStart\n  _opaque: createKeywordLike(\"opaque\", { startsExpr }),\n  // end: isFlowInterfaceOrTypeOrOpaque\n  name: createToken(\"name\", { startsExpr }),\n\n  // placeholder plugin\n  placeholder: createToken(\"%%\", { startsExpr }),\n  // end: isIdentifier\n\n  string: createToken(\"string\", { startsExpr }),\n  num: createToken(\"num\", { startsExpr }),\n  bigint: createToken(\"bigint\", { startsExpr }),\n  // TODO: Remove this in Babel 8\n  decimal: createToken(\"decimal\", { startsExpr }),\n  // end: isLiteralPropertyName\n  regexp: createToken(\"regexp\", { startsExpr }),\n  privateName: createToken(\"#name\", { startsExpr }),\n  eof: createToken(\"eof\"),\n\n  // jsx plugin\n  jsxName: createToken(\"jsxName\"),\n  jsxText: createToken(\"jsxText\", { beforeExpr }),\n  jsxTagStart: createToken(\"jsxTagStart\", { startsExpr }),\n  jsxTagEnd: createToken(\"jsxTagEnd\"),\n} as const;\n\nexport function tokenIsIdentifier(token: TokenType): boolean {\n  return token >= tt._as && token <= tt.placeholder;\n}\n\nexport function tokenKeywordOrIdentifierIsKeyword(token: TokenType): boolean {\n  // we can remove the token >= tt._in check when we\n  // know a token is either keyword or identifier\n  return token <= tt._while;\n}\n\nexport function tokenIsKeywordOrIdentifier(token: TokenType): boolean {\n  return token >= tt._in && token <= tt.placeholder;\n}\n\nexport function tokenIsLiteralPropertyName(token: TokenType): boolean {\n  return token >= tt._in && token <= tt.decimal;\n}\n\nexport function tokenComesBeforeExpression(token: TokenType): boolean {\n  return tokenBeforeExprs[token];\n}\n\nexport function tokenCanStartExpression(token: TokenType): boolean {\n  return tokenStartsExprs[token];\n}\n\nexport function tokenIsAssignment(token: TokenType): boolean {\n  return token >= tt.eq && token <= tt.moduloAssign;\n}\n\nexport function tokenIsFlowInterfaceOrTypeOrOpaque(token: TokenType): boolean {\n  return token >= tt._interface && token <= tt._opaque;\n}\n\nexport function tokenIsLoop(token: TokenType): boolean {\n  return token >= tt._do && token <= tt._while;\n}\n\nexport function tokenIsKeyword(token: TokenType): boolean {\n  return token >= tt._in && token <= tt._while;\n}\n\nexport function tokenIsOperator(token: TokenType): boolean {\n  return token >= tt.pipeline && token <= tt._instanceof;\n}\n\nexport function tokenIsPostfix(token: TokenType): boolean {\n  return token === tt.incDec;\n}\n\nexport function tokenIsPrefix(token: TokenType): boolean {\n  return tokenPrefixes[token];\n}\n\nexport function tokenIsTSTypeOperator(token: TokenType): boolean {\n  return token >= tt._keyof && token <= tt._unique;\n}\n\nexport function tokenIsTSDeclarationStart(token: TokenType): boolean {\n  return token >= tt._abstract && token <= tt._type;\n}\n\nexport function tokenLabelName(token: TokenType): string {\n  return tokenLabels[token];\n}\n\nexport function tokenOperatorPrecedence(token: TokenType): number {\n  return tokenBinops[token];\n}\n\nexport function tokenIsBinaryOperator(token: TokenType): boolean {\n  return tokenBinops[token] !== -1;\n}\n\nexport function tokenIsRightAssociative(token: TokenType): boolean {\n  return token === tt.exponent;\n}\n\nexport function tokenIsTemplate(token: TokenType): boolean {\n  return token >= tt.templateTail && token <= tt.templateNonTail;\n}\n\nexport function getExportedToken(token: TokenType): ExportedTokenType {\n  return tokenTypes[token];\n}\n\nexport function isTokenType(obj: any): boolean {\n  return typeof obj === \"number\";\n}\n\nif (!process.env.BABEL_8_BREAKING) {\n  tokenTypes[tt.braceR].updateContext = context => {\n    context.pop();\n  };\n\n  tokenTypes[tt.braceL].updateContext =\n    tokenTypes[tt.braceHashL].updateContext =\n    tokenTypes[tt.dollarBraceL].updateContext =\n      context => {\n        context.push(tc.brace);\n      };\n\n  tokenTypes[tt.backQuote].updateContext = context => {\n    if (context[context.length - 1] === tc.template) {\n      context.pop();\n    } else {\n      context.push(tc.template);\n    }\n  };\n\n  tokenTypes[tt.jsxTagStart].updateContext = context => {\n    context.push(tc.j_expr, tc.j_oTag);\n  };\n}\n","// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// ## Character categories\n\n// Big ugly regular expressions that match characters in the\n// whitespace, identifier, and identifier-start categories. These\n// are only applied when a character is found to actually have a\n// code point between 0x80 and 0xffff.\n// Generated by `scripts/generate-identifier-regex.cjs`.\n\n/* prettier-ignore */\nlet nonASCIIidentifierStartChars = \"\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086a\\u0870-\\u0887\\u0889-\\u088e\\u08a0-\\u08c9\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u09fc\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13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\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u1711\\u171f-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1878\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4c\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1c80-\\u1c8a\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1ce9-\\u1cec\\u1cee-\\u1cf3\\u1cf5\\u1cf6\\u1cfa\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309b-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31bf\\u31f0-\\u31ff\\u3400-\\u4dbf\\u4e00-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua69d\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7cd\\ua7d0\\ua7d1\\ua7d3\\ua7d5-\\ua7dc\\ua7f2-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\ua9e0-\\ua9e4\\ua9e6-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab69\\uab70-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\";\n/* prettier-ignore */\nlet nonASCIIidentifierChars = \"\\xb7\\u0300-\\u036f\\u0387\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u0669\\u0670\\u06d6-\\u06dc\\u06df-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u06f0-\\u06f9\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07c0-\\u07c9\\u07eb-\\u07f3\\u07fd\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0859-\\u085b\\u0897-\\u089f\\u08ca-\\u08e1\\u08e3-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09cb-\\u09cd\\u09d7\\u09e2\\u09e3\\u09e6-\\u09ef\\u09fe\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2\\u0ae3\\u0ae6-\\u0aef\\u0afa-\\u0aff\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b55-\\u0b57\\u0b62\\u0b63\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c00-\\u0c04\\u0c3c\\u0c3e-\\u0c44\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0c66-\\u0c6f\\u0c81-\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0ce6-\\u0cef\\u0cf3\\u0d00-\\u0d03\\u0d3b\\u0d3c\\u0d3e-\\u0d44\\u0d46-\\u0d48\\u0d4a-\\u0d4d\\u0d57\\u0d62\\u0d63\\u0d66-\\u0d6f\\u0d81-\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0de6-\\u0def\\u0df2\\u0df3\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0e50-\\u0e59\\u0eb1\\u0eb4-\\u0ebc\\u0ec8-\\u0ece\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f3e\\u0f3f\\u0f71-\\u0f84\\u0f86\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102b-\\u103e\\u1040-\\u1049\\u1056-\\u1059\\u105e-\\u1060\\u1062-\\u1064\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u1369-\\u1371\\u1712-\\u1715\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b4-\\u17d3\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u180f-\\u1819\\u18a9\\u1920-\\u192b\\u1930-\\u193b\\u1946-\\u194f\\u19d0-\\u19da\\u1a17-\\u1a1b\\u1a55-\\u1a5e\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1ab0-\\u1abd\\u1abf-\\u1ace\\u1b00-\\u1b04\\u1b34-\\u1b44\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1b80-\\u1b82\\u1ba1-\\u1bad\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c24-\\u1c37\\u1c40-\\u1c49\\u1c50-\\u1c59\\u1cd0-\\u1cd2\\u1cd4-\\u1ce8\\u1ced\\u1cf4\\u1cf7-\\u1cf9\\u1dc0-\\u1dff\\u200c\\u200d\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\u30fb\\ua620-\\ua629\\ua66f\\ua674-\\ua67d\\ua69e\\ua69f\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua823-\\ua827\\ua82c\\ua880\\ua881\\ua8b4-\\ua8c5\\ua8d0-\\ua8d9\\ua8e0-\\ua8f1\\ua8ff-\\ua909\\ua926-\\ua92d\\ua947-\\ua953\\ua980-\\ua983\\ua9b3-\\ua9c0\\ua9d0-\\ua9d9\\ua9e5\\ua9f0-\\ua9f9\\uaa29-\\uaa36\\uaa43\\uaa4c\\uaa4d\\uaa50-\\uaa59\\uaa7b-\\uaa7d\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uaaeb-\\uaaef\\uaaf5\\uaaf6\\uabe3-\\uabea\\uabec\\uabed\\uabf0-\\uabf9\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f\\uff65\";\n\nconst nonASCIIidentifierStart = new RegExp(\n  \"[\" + nonASCIIidentifierStartChars + \"]\",\n);\nconst nonASCIIidentifier = new RegExp(\n  \"[\" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"]\",\n);\n\nnonASCIIidentifierStartChars = nonASCIIidentifierChars = null;\n\n// These are a run-length and offset-encoded representation of the\n// >0xffff code points that are a valid part of identifiers. The\n// offset starts at 0x10000, and each pair of numbers represents an\n// offset to the next range, and then a size of the range. They were\n// generated by `scripts/generate-identifier-regex.cjs`.\n/* prettier-ignore */\nconst astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191];\n/* prettier-ignore */\nconst astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239];\n\n// This has a complexity linear to the value of the code. The\n// assumption is that looking up astral identifier characters is\n// rare.\nfunction isInAstralSet(code: number, set: readonly number[]): boolean {\n  let pos = 0x10000;\n  for (let i = 0, length = set.length; i < length; i += 2) {\n    pos += set[i];\n    if (pos > code) return false;\n\n    pos += set[i + 1];\n    if (pos >= code) return true;\n  }\n  return false;\n}\n\n// Test whether a given character code starts an identifier.\n\nexport function isIdentifierStart(code: number): boolean {\n  if (code < charCodes.uppercaseA) return code === charCodes.dollarSign;\n  if (code <= charCodes.uppercaseZ) return true;\n  if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n  if (code <= charCodes.lowercaseZ) return true;\n  if (code <= 0xffff) {\n    return (\n      code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))\n    );\n  }\n  return isInAstralSet(code, astralIdentifierStartCodes);\n}\n\n// Test whether a given character is part of an identifier.\n\nexport function isIdentifierChar(code: number): boolean {\n  if (code < charCodes.digit0) return code === charCodes.dollarSign;\n  if (code < charCodes.colon) return true;\n  if (code < charCodes.uppercaseA) return false;\n  if (code <= charCodes.uppercaseZ) return true;\n  if (code < charCodes.lowercaseA) return code === charCodes.underscore;\n  if (code <= charCodes.lowercaseZ) return true;\n  if (code <= 0xffff) {\n    return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));\n  }\n  return (\n    isInAstralSet(code, astralIdentifierStartCodes) ||\n    isInAstralSet(code, astralIdentifierCodes)\n  );\n}\n\n// Test whether a given string is a valid identifier name\n\nexport function isIdentifierName(name: string): boolean {\n  let isFirst = true;\n  for (let i = 0; i < name.length; i++) {\n    // The implementation is based on\n    // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n    // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n    // since `name` is mostly ASCII, an inlined `charCodeAt` wins here\n    let cp = name.charCodeAt(i);\n    if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {\n      const trail = name.charCodeAt(++i);\n      if ((trail & 0xfc00) === 0xdc00) {\n        cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n      }\n    }\n    if (isFirst) {\n      isFirst = false;\n      if (!isIdentifierStart(cp)) {\n        return false;\n      }\n    } else if (!isIdentifierChar(cp)) {\n      return false;\n    }\n  }\n  return !isFirst;\n}\n","const reservedWords = {\n  keyword: [\n    \"break\",\n    \"case\",\n    \"catch\",\n    \"continue\",\n    \"debugger\",\n    \"default\",\n    \"do\",\n    \"else\",\n    \"finally\",\n    \"for\",\n    \"function\",\n    \"if\",\n    \"return\",\n    \"switch\",\n    \"throw\",\n    \"try\",\n    \"var\",\n    \"const\",\n    \"while\",\n    \"with\",\n    \"new\",\n    \"this\",\n    \"super\",\n    \"class\",\n    \"extends\",\n    \"export\",\n    \"import\",\n    \"null\",\n    \"true\",\n    \"false\",\n    \"in\",\n    \"instanceof\",\n    \"typeof\",\n    \"void\",\n    \"delete\",\n  ],\n  strict: [\n    \"implements\",\n    \"interface\",\n    \"let\",\n    \"package\",\n    \"private\",\n    \"protected\",\n    \"public\",\n    \"static\",\n    \"yield\",\n  ],\n  strictBind: [\"eval\", \"arguments\"],\n};\nconst keywords = new Set(reservedWords.keyword);\nconst reservedWordsStrictSet = new Set(reservedWords.strict);\nconst reservedWordsStrictBindSet = new Set(reservedWords.strictBind);\n\n/**\n * Checks if word is a reserved word in non-strict mode\n */\nexport function isReservedWord(word: string, inModule: boolean): boolean {\n  return (inModule && word === \"await\") || word === \"enum\";\n}\n\n/**\n * Checks if word is a reserved word in non-binding strict mode\n *\n * Includes non-strict reserved words\n */\nexport function isStrictReservedWord(word: string, inModule: boolean): boolean {\n  return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode, but it is allowed as\n * a normal identifier.\n */\nexport function isStrictBindOnlyReservedWord(word: string): boolean {\n  return reservedWordsStrictBindSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode\n *\n * Includes non-strict reserved words and non-binding strict reserved words\n */\nexport function isStrictBindReservedWord(\n  word: string,\n  inModule: boolean,\n): boolean {\n  return (\n    isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word)\n  );\n}\n\nexport function isKeyword(word: string): boolean {\n  return keywords.has(word);\n}\n","import * as charCodes from \"charcodes\";\nimport { isIdentifierStart } from \"@babel/helper-validator-identifier\";\n\nexport {\n  isIdentifierStart,\n  isIdentifierChar,\n  isReservedWord,\n  isStrictBindOnlyReservedWord,\n  isStrictBindReservedWord,\n  isStrictReservedWord,\n  isKeyword,\n} from \"@babel/helper-validator-identifier\";\n\nexport const keywordRelationalOperator = /^in(stanceof)?$/;\n\n// Test whether a current state character code and next character code is @\n\nexport function isIteratorStart(\n  current: number,\n  next: number,\n  next2: number,\n): boolean {\n  return (\n    current === charCodes.atSign &&\n    next === charCodes.atSign &&\n    isIdentifierStart(next2)\n  );\n}\n\n// This is the comprehensive set of JavaScript reserved words\n// If a word is in this set, it could be a reserved word,\n// depending on sourceType/strictMode/binding info. In other words\n// if a word is not in this set, it is not a reserved word under\n// any circumstance.\nconst reservedWordLikeSet = new Set([\n  \"break\",\n  \"case\",\n  \"catch\",\n  \"continue\",\n  \"debugger\",\n  \"default\",\n  \"do\",\n  \"else\",\n  \"finally\",\n  \"for\",\n  \"function\",\n  \"if\",\n  \"return\",\n  \"switch\",\n  \"throw\",\n  \"try\",\n  \"var\",\n  \"const\",\n  \"while\",\n  \"with\",\n  \"new\",\n  \"this\",\n  \"super\",\n  \"class\",\n  \"extends\",\n  \"export\",\n  \"import\",\n  \"null\",\n  \"true\",\n  \"false\",\n  \"in\",\n  \"instanceof\",\n  \"typeof\",\n  \"void\",\n  \"delete\",\n  // strict\n  \"implements\",\n  \"interface\",\n  \"let\",\n  \"package\",\n  \"private\",\n  \"protected\",\n  \"public\",\n  \"static\",\n  \"yield\",\n  // strictBind\n  \"eval\",\n  \"arguments\",\n  // reservedWorkLike\n  \"enum\",\n  \"await\",\n]);\n\nexport function canBeReservedWord(word: string): boolean {\n  return reservedWordLikeSet.has(word);\n}\n","import { ScopeFlag, BindingFlag } from \"./scopeflags.ts\";\nimport type { Position } from \"./location.ts\";\nimport type * as N from \"../types.ts\";\nimport { Errors } from \"../parse-error.ts\";\nimport type Tokenizer from \"../tokenizer/index.ts\";\n\nexport const enum NameType {\n  // var-declared names in the current lexical scope\n  Var = 1 << 0,\n  // lexically-declared names in the current lexical scope\n  Lexical = 1 << 1,\n  // lexically-declared FunctionDeclaration names in the current lexical scope\n  Function = 1 << 2,\n}\n\n// Start an AST node, attaching a start offset.\nexport class Scope {\n  flags: ScopeFlag = 0;\n  names: Map<string, NameType> = new Map();\n  firstLexicalName = \"\";\n\n  constructor(flags: ScopeFlag) {\n    this.flags = flags;\n  }\n}\n\n// The functions in this module keep track of declared variables in the\n// current scope in order to detect duplicate variable names.\nexport default class ScopeHandler<IScope extends Scope = Scope> {\n  parser: Tokenizer;\n  scopeStack: Array<IScope> = [];\n  inModule: boolean;\n  undefinedExports: Map<string, Position> = new Map();\n\n  constructor(parser: Tokenizer, inModule: boolean) {\n    this.parser = parser;\n    this.inModule = inModule;\n  }\n\n  get inTopLevel() {\n    return (this.currentScope().flags & ScopeFlag.PROGRAM) > 0;\n  }\n  get inFunction() {\n    return (this.currentVarScopeFlags() & ScopeFlag.FUNCTION_BASE) > 0;\n  }\n  get allowSuper() {\n    return (this.currentThisScopeFlags() & ScopeFlag.SUPER) > 0;\n  }\n  get allowDirectSuper() {\n    return (this.currentThisScopeFlags() & ScopeFlag.DIRECT_SUPER) > 0;\n  }\n  get allowNewTarget() {\n    return (this.currentThisScopeFlags() & ScopeFlag.NEW_TARGET) > 0;\n  }\n  get inClass() {\n    return (this.currentThisScopeFlags() & ScopeFlag.CLASS_BASE) > 0;\n  }\n  get inClassAndNotInNonArrowFunction() {\n    const flags = this.currentThisScopeFlags();\n    return (\n      (flags & ScopeFlag.CLASS_BASE) > 0 &&\n      (flags & ScopeFlag.FUNCTION_BASE) === 0\n    );\n  }\n  get inStaticBlock() {\n    for (let i = this.scopeStack.length - 1; ; i--) {\n      const { flags } = this.scopeStack[i];\n      if (flags & ScopeFlag.STATIC_BLOCK) {\n        return true;\n      }\n      if (flags & (ScopeFlag.VAR | ScopeFlag.CLASS_BASE)) {\n        // function body, module body, class property initializers\n        return false;\n      }\n    }\n  }\n  get inNonArrowFunction() {\n    return (this.currentThisScopeFlags() & ScopeFlag.FUNCTION_BASE) > 0;\n  }\n  get inBareCaseStatement() {\n    return (this.currentScope().flags & ScopeFlag.SWITCH) > 0;\n  }\n  get treatFunctionsAsVar() {\n    return this.treatFunctionsAsVarInScope(this.currentScope());\n  }\n\n  createScope(flags: ScopeFlag): Scope {\n    return new Scope(flags);\n  }\n\n  enter(flags: ScopeFlag) {\n    /*:: +createScope: (flags:ScopeFlag) => IScope; */\n    // @ts-expect-error This method will be overwritten by subclasses\n    this.scopeStack.push(this.createScope(flags));\n  }\n\n  exit(): ScopeFlag {\n    const scope = this.scopeStack.pop();\n    return scope.flags;\n  }\n\n  // The spec says:\n  // > At the top level of a function, or script, function declarations are\n  // > treated like var declarations rather than like lexical declarations.\n  treatFunctionsAsVarInScope(scope: IScope): boolean {\n    return !!(\n      scope.flags & (ScopeFlag.FUNCTION_BASE | ScopeFlag.STATIC_BLOCK) ||\n      (!this.parser.inModule && scope.flags & ScopeFlag.PROGRAM)\n    );\n  }\n\n  declareName(name: string, bindingType: BindingFlag, loc: Position) {\n    let scope = this.currentScope();\n    if (\n      bindingType & BindingFlag.SCOPE_LEXICAL ||\n      bindingType & BindingFlag.SCOPE_FUNCTION\n    ) {\n      this.checkRedeclarationInScope(scope, name, bindingType, loc);\n\n      let type = scope.names.get(name) || 0;\n\n      if (bindingType & BindingFlag.SCOPE_FUNCTION) {\n        type = type | NameType.Function;\n      } else {\n        if (!scope.firstLexicalName) {\n          scope.firstLexicalName = name;\n        }\n        type = type | NameType.Lexical;\n      }\n\n      scope.names.set(name, type);\n\n      if (bindingType & BindingFlag.SCOPE_LEXICAL) {\n        this.maybeExportDefined(scope, name);\n      }\n    } else if (bindingType & BindingFlag.SCOPE_VAR) {\n      for (let i = this.scopeStack.length - 1; i >= 0; --i) {\n        scope = this.scopeStack[i];\n        this.checkRedeclarationInScope(scope, name, bindingType, loc);\n        scope.names.set(name, (scope.names.get(name) || 0) | NameType.Var);\n        this.maybeExportDefined(scope, name);\n\n        if (scope.flags & ScopeFlag.VAR) break;\n      }\n    }\n    if (this.parser.inModule && scope.flags & ScopeFlag.PROGRAM) {\n      this.undefinedExports.delete(name);\n    }\n  }\n\n  maybeExportDefined(scope: IScope, name: string) {\n    if (this.parser.inModule && scope.flags & ScopeFlag.PROGRAM) {\n      this.undefinedExports.delete(name);\n    }\n  }\n\n  checkRedeclarationInScope(\n    scope: IScope,\n    name: string,\n    bindingType: BindingFlag,\n    loc: Position,\n  ) {\n    if (this.isRedeclaredInScope(scope, name, bindingType)) {\n      this.parser.raise(Errors.VarRedeclaration, loc, {\n        identifierName: name,\n      });\n    }\n  }\n\n  isRedeclaredInScope(\n    scope: IScope,\n    name: string,\n    bindingType: BindingFlag,\n  ): boolean {\n    if (!(bindingType & BindingFlag.KIND_VALUE)) return false;\n\n    if (bindingType & BindingFlag.SCOPE_LEXICAL) {\n      return scope.names.has(name);\n    }\n\n    const type = scope.names.get(name);\n\n    if (bindingType & BindingFlag.SCOPE_FUNCTION) {\n      return (\n        (type & NameType.Lexical) > 0 ||\n        (!this.treatFunctionsAsVarInScope(scope) && (type & NameType.Var) > 0)\n      );\n    }\n\n    return (\n      ((type & NameType.Lexical) > 0 &&\n        // Annex B.3.4\n        // https://tc39.es/ecma262/#sec-variablestatements-in-catch-blocks\n        !(\n          scope.flags & ScopeFlag.SIMPLE_CATCH &&\n          scope.firstLexicalName === name\n        )) ||\n      (!this.treatFunctionsAsVarInScope(scope) &&\n        (type & NameType.Function) > 0)\n    );\n  }\n\n  checkLocalExport(id: N.Identifier) {\n    const { name } = id;\n    const topLevelScope = this.scopeStack[0];\n    if (!topLevelScope.names.has(name)) {\n      this.undefinedExports.set(name, id.loc.start);\n    }\n  }\n\n  currentScope(): IScope {\n    return this.scopeStack[this.scopeStack.length - 1];\n  }\n\n  currentVarScopeFlags(): ScopeFlag {\n    for (let i = this.scopeStack.length - 1; ; i--) {\n      const { flags } = this.scopeStack[i];\n      if (flags & ScopeFlag.VAR) {\n        return flags;\n      }\n    }\n  }\n\n  // Could be useful for `arguments`, `this`, `new.target`, `super()`, `super.property`, and `super[property]`.\n  currentThisScopeFlags(): ScopeFlag {\n    for (let i = this.scopeStack.length - 1; ; i--) {\n      const { flags } = this.scopeStack[i];\n      if (\n        flags & (ScopeFlag.VAR | ScopeFlag.CLASS_BASE) &&\n        !(flags & ScopeFlag.ARROW)\n      ) {\n        return flags;\n      }\n    }\n  }\n}\n","import type { Position } from \"../../util/location.ts\";\nimport ScopeHandler, { NameType, Scope } from \"../../util/scope.ts\";\nimport { BindingFlag, type ScopeFlag } from \"../../util/scopeflags.ts\";\nimport type * as N from \"../../types.ts\";\n\n// Reference implementation: https://github.com/facebook/flow/blob/23aeb2a2ef6eb4241ce178fde5d8f17c5f747fb5/src/typing/env.ml#L536-L584\nclass FlowScope extends Scope {\n  // declare function foo(): type;\n  declareFunctions: Set<string> = new Set();\n}\n\nexport default class FlowScopeHandler extends ScopeHandler<FlowScope> {\n  createScope(flags: ScopeFlag): FlowScope {\n    return new FlowScope(flags);\n  }\n\n  declareName(name: string, bindingType: BindingFlag, loc: Position) {\n    const scope = this.currentScope();\n    if (bindingType & BindingFlag.FLAG_FLOW_DECLARE_FN) {\n      this.checkRedeclarationInScope(scope, name, bindingType, loc);\n      this.maybeExportDefined(scope, name);\n      scope.declareFunctions.add(name);\n      return;\n    }\n\n    super.declareName(name, bindingType, loc);\n  }\n\n  isRedeclaredInScope(\n    scope: FlowScope,\n    name: string,\n    bindingType: BindingFlag,\n  ): boolean {\n    if (super.isRedeclaredInScope(scope, name, bindingType)) return true;\n\n    if (\n      bindingType & BindingFlag.FLAG_FLOW_DECLARE_FN &&\n      !scope.declareFunctions.has(name)\n    ) {\n      const type = scope.names.get(name);\n      return (type & NameType.Function) > 0 || (type & NameType.Lexical) > 0;\n    }\n\n    return false;\n  }\n\n  checkLocalExport(id: N.Identifier) {\n    if (!this.scopeStack[0].declareFunctions.has(id.name)) {\n      super.checkLocalExport(id);\n    }\n  }\n}\n","/*:: declare var invariant; */\n\nimport type Parser from \"../../parser/index.ts\";\nimport {\n  tokenIsIdentifier,\n  tokenIsKeyword,\n  tokenIsKeywordOrIdentifier,\n  tokenIsLiteralPropertyName,\n  tokenLabelName,\n  tt,\n  type TokenType,\n  tokenIsFlowInterfaceOrTypeOrOpaque,\n} from \"../../tokenizer/types.ts\";\nimport type * as N from \"../../types.ts\";\nimport type { Position } from \"../../util/location.ts\";\nimport { types as tc } from \"../../tokenizer/context.ts\";\nimport * as charCodes from \"charcodes\";\nimport { isIteratorStart } from \"../../util/identifier.ts\";\nimport FlowScopeHandler from \"./scope.ts\";\nimport { BindingFlag, ScopeFlag } from \"../../util/scopeflags.ts\";\nimport type { ExpressionErrors } from \"../../parser/util.ts\";\nimport type { ParseStatementFlag } from \"../../parser/statement.ts\";\nimport { Errors, ParseErrorEnum } from \"../../parse-error.ts\";\nimport type { Undone } from \"../../parser/node.ts\";\nimport type { ClassWithMixin, IJSXParserMixin } from \"../jsx/index.ts\";\n\nconst reservedTypes = new Set([\n  \"_\",\n  \"any\",\n  \"bool\",\n  \"boolean\",\n  \"empty\",\n  \"extends\",\n  \"false\",\n  \"interface\",\n  \"mixed\",\n  \"null\",\n  \"number\",\n  \"static\",\n  \"string\",\n  \"true\",\n  \"typeof\",\n  \"void\",\n]);\n\n/* eslint sort-keys: \"error\" */\n// The Errors key follows https://github.com/facebook/flow/blob/master/src/parser/parse_error.ml unless it does not exist\nconst FlowErrors = ParseErrorEnum`flow`({\n  AmbiguousConditionalArrow:\n    \"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.\",\n  AmbiguousDeclareModuleKind:\n    \"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.\",\n  // TODO: When we get proper string enums in typescript make this ReservedType.\n  // Not really worth it to do the whole $Values dance with reservedTypes set.\n  AssignReservedType: ({ reservedType }: { reservedType: string }) =>\n    `Cannot overwrite reserved type ${reservedType}.`,\n  DeclareClassElement:\n    \"The `declare` modifier can only appear on class fields.\",\n  DeclareClassFieldInitializer:\n    \"Initializers are not allowed in fields with the `declare` modifier.\",\n  DuplicateDeclareModuleExports:\n    \"Duplicate `declare module.exports` statement.\",\n  EnumBooleanMemberNotInitialized: ({\n    memberName,\n    enumName,\n  }: {\n    memberName: string;\n    enumName: string;\n  }) =>\n    `Boolean enum members need to be initialized. Use either \\`${memberName} = true,\\` or \\`${memberName} = false,\\` in enum \\`${enumName}\\`.`,\n  EnumDuplicateMemberName: ({\n    memberName,\n    enumName,\n  }: {\n    memberName: string;\n    enumName: string;\n  }) =>\n    `Enum member names need to be unique, but the name \\`${memberName}\\` has already been used before in enum \\`${enumName}\\`.`,\n  EnumInconsistentMemberValues: ({ enumName }: { enumName: string }) =>\n    `Enum \\`${enumName}\\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,\n  EnumInvalidExplicitType: ({\n    invalidEnumType,\n    enumName,\n  }: {\n    invalidEnumType: string;\n    enumName: string;\n  }) =>\n    `Enum type \\`${invalidEnumType}\\` is not valid. Use one of \\`boolean\\`, \\`number\\`, \\`string\\`, or \\`symbol\\` in enum \\`${enumName}\\`.`,\n  EnumInvalidExplicitTypeUnknownSupplied: ({\n    enumName,\n  }: {\n    enumName: string;\n  }) =>\n    `Supplied enum type is not valid. Use one of \\`boolean\\`, \\`number\\`, \\`string\\`, or \\`symbol\\` in enum \\`${enumName}\\`.`,\n\n  // TODO: When moving to typescript, we should either have each of the\n  // following errors only accept the specific strings they want:\n  //\n  // ...PrimaryType: explicitType: \"string\" | \"number\" | \"boolean\"\n  // ...SymbolType: explicitType: \"symbol\"\n  // ...UnknownType: explicitType: null\n  //\n  // Or, alternatively, merge these three errors together into one\n  // `EnumInvalidMemberInitializer` error that can accept `EnumExplicitType`\n  // without alteration, and then just have its message change based on the\n  // explicitType.\n  EnumInvalidMemberInitializerPrimaryType: ({\n    enumName,\n    memberName,\n    explicitType,\n  }: {\n    enumName: string;\n    memberName: string;\n    explicitType: EnumExplicitType;\n  }) =>\n    `Enum \\`${enumName}\\` has type \\`${explicitType}\\`, so the initializer of \\`${memberName}\\` needs to be a ${explicitType} literal.`,\n  EnumInvalidMemberInitializerSymbolType: ({\n    enumName,\n    memberName,\n  }: {\n    enumName: string;\n    memberName: string;\n    explicitType: EnumExplicitType;\n  }) =>\n    `Symbol enum members cannot be initialized. Use \\`${memberName},\\` in enum \\`${enumName}\\`.`,\n  EnumInvalidMemberInitializerUnknownType: ({\n    enumName,\n    memberName,\n  }: {\n    enumName: string;\n    memberName: string;\n    explicitType: EnumExplicitType;\n  }) =>\n    `The enum member initializer for \\`${memberName}\\` needs to be a literal (either a boolean, number, or string) in enum \\`${enumName}\\`.`,\n  EnumInvalidMemberName: ({\n    enumName,\n    memberName,\n    suggestion,\n  }: {\n    enumName: string;\n    memberName: string;\n    suggestion: string;\n  }) =>\n    `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \\`${memberName}\\`, consider using \\`${suggestion}\\`, in enum \\`${enumName}\\`.`,\n  EnumNumberMemberNotInitialized: ({\n    enumName,\n    memberName,\n  }: {\n    enumName: string;\n    memberName: string;\n  }) =>\n    `Number enum members need to be initialized, e.g. \\`${memberName} = 1\\` in enum \\`${enumName}\\`.`,\n  EnumStringMemberInconsistentlyInitialized: ({\n    enumName,\n  }: {\n    enumName: string;\n  }) =>\n    `String enum members need to consistently either all use initializers, or use no initializers, in enum \\`${enumName}\\`.`,\n  GetterMayNotHaveThisParam: \"A getter cannot have a `this` parameter.\",\n  ImportReflectionHasImportType:\n    \"An `import module` declaration can not use `type` or `typeof` keyword.\",\n  ImportTypeShorthandOnlyInPureImport:\n    \"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.\",\n  InexactInsideExact:\n    \"Explicit inexact syntax cannot appear inside an explicit exact object type.\",\n  InexactInsideNonObject:\n    \"Explicit inexact syntax cannot appear in class or interface definitions.\",\n  InexactVariance: \"Explicit inexact syntax cannot have variance.\",\n  InvalidNonTypeImportInDeclareModule:\n    \"Imports within a `declare module` body must always be `import type` or `import typeof`.\",\n  MissingTypeParamDefault:\n    \"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.\",\n  NestedDeclareModule:\n    \"`declare module` cannot be used inside another `declare module`.\",\n  NestedFlowComment: \"Cannot have a flow comment inside another flow comment.\",\n  PatternIsOptional: {\n    message:\n      \"A binding pattern parameter cannot be optional in an implementation signature.\",\n    // For consistency in TypeScript and Flow error codes\n    ...(!process.env.BABEL_8_BREAKING\n      ? { reasonCode: \"OptionalBindingPattern\" }\n      : {}),\n  },\n  SetterMayNotHaveThisParam: \"A setter cannot have a `this` parameter.\",\n  SpreadVariance: \"Spread properties cannot have variance.\",\n  ThisParamAnnotationRequired:\n    \"A type annotation is required for the `this` parameter.\",\n  ThisParamBannedInConstructor:\n    \"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.\",\n  ThisParamMayNotBeOptional: \"The `this` parameter cannot be optional.\",\n  ThisParamMustBeFirst:\n    \"The `this` parameter must be the first function parameter.\",\n  ThisParamNoDefault: \"The `this` parameter may not have a default value.\",\n  TypeBeforeInitializer:\n    \"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.\",\n  TypeCastInPattern:\n    \"The type cast expression is expected to be wrapped with parenthesis.\",\n  UnexpectedExplicitInexactInObject:\n    \"Explicit inexact syntax must appear at the end of an inexact object.\",\n  UnexpectedReservedType: ({ reservedType }: { reservedType: string }) =>\n    `Unexpected reserved type ${reservedType}.`,\n  UnexpectedReservedUnderscore:\n    \"`_` is only allowed as a type argument to call or new.\",\n  UnexpectedSpaceBetweenModuloChecks:\n    \"Spaces between `%` and `checks` are not allowed here.\",\n  UnexpectedSpreadType:\n    \"Spread operator cannot appear in class or interface definitions.\",\n  UnexpectedSubtractionOperand:\n    'Unexpected token, expected \"number\" or \"bigint\".',\n  UnexpectedTokenAfterTypeParameter:\n    \"Expected an arrow function after this type parameter declaration.\",\n  UnexpectedTypeParameterBeforeAsyncArrowFunction:\n    \"Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.\",\n  UnsupportedDeclareExportKind: ({\n    unsupportedExportKind,\n    suggestion,\n  }: {\n    unsupportedExportKind: string;\n    suggestion: string;\n  }) =>\n    `\\`declare export ${unsupportedExportKind}\\` is not supported. Use \\`${suggestion}\\` instead.`,\n  UnsupportedStatementInDeclareModule:\n    \"Only declares and type imports are allowed inside declare module.\",\n  UnterminatedFlowComment: \"Unterminated flow-comment.\",\n});\n/* eslint-disable sort-keys */\n\nfunction isEsModuleType(bodyElement: N.Node): boolean {\n  return (\n    bodyElement.type === \"DeclareExportAllDeclaration\" ||\n    (bodyElement.type === \"DeclareExportDeclaration\" &&\n      (!bodyElement.declaration ||\n        (bodyElement.declaration.type !== \"TypeAlias\" &&\n          bodyElement.declaration.type !== \"InterfaceDeclaration\")))\n  );\n}\n\nfunction hasTypeImportKind(\n  node: Undone<N.ImportSpecifier | N.ImportDeclaration>,\n): boolean {\n  return node.importKind === \"type\" || node.importKind === \"typeof\";\n}\n\nconst exportSuggestions = {\n  const: \"declare export var\",\n  let: \"declare export var\",\n  type: \"export type\",\n  interface: \"export interface\",\n};\n\n// Like Array#filter, but returns a tuple [ acceptedElements, discardedElements ]\nfunction partition<T>(\n  list: T[],\n  test: (c: T, b: number, a: T[]) => boolean | undefined | null,\n): [T[], T[]] {\n  const list1: T[] = [];\n  const list2: T[] = [];\n  for (let i = 0; i < list.length; i++) {\n    (test(list[i], i, list) ? list1 : list2).push(list[i]);\n  }\n  return [list1, list2];\n}\n\nconst FLOW_PRAGMA_REGEX = /\\*?\\s*@((?:no)?flow)\\b/;\n\n// Flow enums types\ntype EnumExplicitType = null | \"boolean\" | \"number\" | \"string\" | \"symbol\";\n\ntype EnumContext = {\n  enumName: string;\n  explicitType: EnumExplicitType;\n  memberName: string;\n};\n\ntype EnumMemberInit =\n  | {\n      type: \"number\";\n      loc: Position;\n      value: N.Node;\n    }\n  | {\n      type: \"string\";\n      loc: Position;\n      value: N.Node;\n    }\n  | {\n      type: \"boolean\";\n      loc: Position;\n      value: N.Node;\n    }\n  | {\n      type: \"invalid\";\n      loc: Position;\n    }\n  | {\n      type: \"none\";\n      loc: Position;\n    };\n\nexport default (superClass: ClassWithMixin<typeof Parser, IJSXParserMixin>) =>\n  class FlowParserMixin extends superClass implements Parser {\n    // The value of the @flow/@noflow pragma. Initially undefined, transitions\n    // to \"@flow\" or \"@noflow\" if we see a pragma. Transitions to null if we are\n    // past the initial comment.\n    flowPragma: void | null | \"flow\" | \"noflow\" = undefined;\n\n    getScopeHandler(): new (...args: any) => FlowScopeHandler {\n      return FlowScopeHandler;\n    }\n\n    shouldParseTypes(): boolean {\n      return this.getPluginOption(\"flow\", \"all\") || this.flowPragma === \"flow\";\n    }\n\n    finishToken(type: TokenType, val: any): void {\n      if (\n        type !== tt.string &&\n        type !== tt.semi &&\n        type !== tt.interpreterDirective\n      ) {\n        if (this.flowPragma === undefined) {\n          this.flowPragma = null;\n        }\n      }\n      super.finishToken(type, val);\n    }\n\n    addComment(comment: N.Comment): void {\n      if (this.flowPragma === undefined) {\n        // Try to parse a flow pragma.\n        const matches = FLOW_PRAGMA_REGEX.exec(comment.value);\n        if (!matches) {\n          // do nothing\n        } else if (matches[1] === \"flow\") {\n          this.flowPragma = \"flow\";\n        } else if (matches[1] === \"noflow\") {\n          this.flowPragma = \"noflow\";\n        } else {\n          throw new Error(\"Unexpected flow pragma\");\n        }\n      }\n      super.addComment(comment);\n    }\n\n    flowParseTypeInitialiser(tok?: TokenType): N.FlowType {\n      const oldInType = this.state.inType;\n      this.state.inType = true;\n      this.expect(tok || tt.colon);\n\n      const type = this.flowParseType();\n      this.state.inType = oldInType;\n      return type;\n    }\n\n    flowParsePredicate(): N.FlowPredicate {\n      const node = this.startNode<N.FlowPredicate>();\n      const moduloLoc = this.state.startLoc;\n      this.next(); // eat `%`\n      this.expectContextual(tt._checks);\n      // Force '%' and 'checks' to be adjacent\n      if (this.state.lastTokStartLoc.index > moduloLoc.index + 1) {\n        this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc);\n      }\n      if (this.eat(tt.parenL)) {\n        node.value = super.parseExpression();\n        this.expect(tt.parenR);\n        return this.finishNode(node, \"DeclaredPredicate\");\n      } else {\n        return this.finishNode(node, \"InferredPredicate\");\n      }\n    }\n\n    flowParseTypeAndPredicateInitialiser(): [\n      N.FlowType | undefined | null,\n      N.FlowPredicate | undefined | null,\n    ] {\n      const oldInType = this.state.inType;\n      this.state.inType = true;\n      this.expect(tt.colon);\n      let type = null;\n      let predicate = null;\n      if (this.match(tt.modulo)) {\n        this.state.inType = oldInType;\n        predicate = this.flowParsePredicate();\n      } else {\n        type = this.flowParseType();\n        this.state.inType = oldInType;\n        if (this.match(tt.modulo)) {\n          predicate = this.flowParsePredicate();\n        }\n      }\n      return [type, predicate];\n    }\n\n    flowParseDeclareClass(\n      node: Undone<N.FlowDeclareClass>,\n    ): N.FlowDeclareClass {\n      this.next();\n      this.flowParseInterfaceish(node, /*isClass*/ true);\n      return this.finishNode(node, \"DeclareClass\");\n    }\n\n    flowParseDeclareFunction(\n      node: Undone<N.FlowDeclareFunction>,\n    ): N.FlowDeclareFunction {\n      this.next();\n\n      const id = (node.id = this.parseIdentifier());\n\n      const typeNode = this.startNode<N.FlowFunctionTypeAnnotation>();\n      const typeContainer = this.startNode<N.TypeAnnotation>();\n\n      if (this.match(tt.lt)) {\n        typeNode.typeParameters = this.flowParseTypeParameterDeclaration();\n      } else {\n        typeNode.typeParameters = null;\n      }\n\n      this.expect(tt.parenL);\n      const tmp = this.flowParseFunctionTypeParams();\n      typeNode.params = tmp.params;\n      typeNode.rest = tmp.rest;\n      typeNode.this = tmp._this;\n      this.expect(tt.parenR);\n\n      [typeNode.returnType, node.predicate] =\n        this.flowParseTypeAndPredicateInitialiser();\n\n      typeContainer.typeAnnotation = this.finishNode(\n        typeNode,\n        \"FunctionTypeAnnotation\",\n      );\n\n      id.typeAnnotation = this.finishNode(typeContainer, \"TypeAnnotation\");\n\n      this.resetEndLocation(id);\n      this.semicolon();\n\n      this.scope.declareName(\n        node.id.name,\n        BindingFlag.TYPE_FLOW_DECLARE_FN,\n        node.id.loc.start,\n      );\n\n      return this.finishNode(node, \"DeclareFunction\");\n    }\n\n    flowParseDeclare(\n      node: Undone<N.FlowDeclare>,\n      insideModule?: boolean,\n    ): N.FlowDeclare {\n      if (this.match(tt._class)) {\n        return this.flowParseDeclareClass(node);\n      } else if (this.match(tt._function)) {\n        return this.flowParseDeclareFunction(node);\n      } else if (this.match(tt._var)) {\n        return this.flowParseDeclareVariable(node);\n      } else if (this.eatContextual(tt._module)) {\n        if (this.match(tt.dot)) {\n          return this.flowParseDeclareModuleExports(node);\n        } else {\n          if (insideModule) {\n            this.raise(\n              FlowErrors.NestedDeclareModule,\n              this.state.lastTokStartLoc,\n            );\n          }\n          return this.flowParseDeclareModule(node);\n        }\n      } else if (this.isContextual(tt._type)) {\n        return this.flowParseDeclareTypeAlias(node);\n      } else if (this.isContextual(tt._opaque)) {\n        return this.flowParseDeclareOpaqueType(node);\n      } else if (this.isContextual(tt._interface)) {\n        return this.flowParseDeclareInterface(node);\n      } else if (this.match(tt._export)) {\n        return this.flowParseDeclareExportDeclaration(node, insideModule);\n      } else {\n        this.unexpected();\n      }\n    }\n\n    flowParseDeclareVariable(\n      node: Undone<N.FlowDeclareVariable>,\n    ): N.FlowDeclareVariable {\n      this.next();\n      node.id = this.flowParseTypeAnnotatableIdentifier(\n        /*allowPrimitiveOverride*/ true,\n      );\n      this.scope.declareName(\n        node.id.name,\n        BindingFlag.TYPE_VAR,\n        node.id.loc.start,\n      );\n      this.semicolon();\n      return this.finishNode(node, \"DeclareVariable\");\n    }\n\n    flowParseDeclareModule(\n      node: Undone<N.FlowDeclareModule>,\n    ): N.FlowDeclareModule {\n      this.scope.enter(ScopeFlag.OTHER);\n\n      if (this.match(tt.string)) {\n        node.id = super.parseExprAtom();\n      } else {\n        node.id = this.parseIdentifier();\n      }\n\n      const bodyNode = (node.body = this.startNode<N.BlockStatement>());\n      // @ts-expect-error refine typings\n      const body = (bodyNode.body = []);\n      this.expect(tt.braceL);\n      while (!this.match(tt.braceR)) {\n        let bodyNode = this.startNode<N.ImportDeclaration>();\n\n        if (this.match(tt._import)) {\n          this.next();\n          if (!this.isContextual(tt._type) && !this.match(tt._typeof)) {\n            this.raise(\n              FlowErrors.InvalidNonTypeImportInDeclareModule,\n              this.state.lastTokStartLoc,\n            );\n          }\n          super.parseImport(bodyNode);\n        } else {\n          this.expectContextual(\n            tt._declare,\n            FlowErrors.UnsupportedStatementInDeclareModule,\n          );\n          // @ts-expect-error refine typings\n          bodyNode = this.flowParseDeclare(bodyNode, true);\n        }\n\n        body.push(bodyNode);\n      }\n\n      this.scope.exit();\n\n      this.expect(tt.braceR);\n\n      this.finishNode(bodyNode, \"BlockStatement\");\n\n      let kind: \"CommonJS\" | \"ES\" | null = null;\n      let hasModuleExport = false;\n      body.forEach(bodyElement => {\n        if (isEsModuleType(bodyElement)) {\n          if (kind === \"CommonJS\") {\n            this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);\n          }\n          kind = \"ES\";\n        } else if (bodyElement.type === \"DeclareModuleExports\") {\n          if (hasModuleExport) {\n            this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement);\n          }\n          if (kind === \"ES\") {\n            this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);\n          }\n          kind = \"CommonJS\";\n          hasModuleExport = true;\n        }\n      });\n\n      node.kind = kind || \"CommonJS\";\n      return this.finishNode(node, \"DeclareModule\");\n    }\n\n    flowParseDeclareExportDeclaration(\n      node: Undone<N.FlowDeclareExportDeclaration>,\n      insideModule?: boolean | null,\n    ): N.FlowDeclareExportDeclaration {\n      this.expect(tt._export);\n\n      if (this.eat(tt._default)) {\n        if (this.match(tt._function) || this.match(tt._class)) {\n          // declare export default class ...\n          // declare export default function ...\n          node.declaration = this.flowParseDeclare(this.startNode());\n        } else {\n          // declare export default [type];\n          node.declaration = this.flowParseType();\n          this.semicolon();\n        }\n        node.default = true;\n\n        return this.finishNode(node, \"DeclareExportDeclaration\");\n      } else {\n        if (\n          this.match(tt._const) ||\n          this.isLet() ||\n          ((this.isContextual(tt._type) || this.isContextual(tt._interface)) &&\n            !insideModule)\n        ) {\n          const label = this.state.value as\n            | \"const\"\n            | \"let\"\n            | \"type\"\n            | \"interface\";\n          throw this.raise(\n            FlowErrors.UnsupportedDeclareExportKind,\n            this.state.startLoc,\n            {\n              unsupportedExportKind: label,\n              suggestion: exportSuggestions[label],\n            },\n          );\n        }\n\n        if (\n          this.match(tt._var) || // declare export var ...\n          this.match(tt._function) || // declare export function ...\n          this.match(tt._class) || // declare export class ...\n          this.isContextual(tt._opaque) // declare export opaque ..\n        ) {\n          node.declaration = this.flowParseDeclare(this.startNode());\n          node.default = false;\n\n          return this.finishNode(node, \"DeclareExportDeclaration\");\n        } else if (\n          this.match(tt.star) || // declare export * from ''\n          this.match(tt.braceL) || // declare export {} ...\n          this.isContextual(tt._interface) || // declare export interface ...\n          this.isContextual(tt._type) || // declare export type ...\n          this.isContextual(tt._opaque) // declare export opaque type ...\n        ) {\n          node = this.parseExport(\n            node as Undone<N.ExportNamedDeclaration | N.ExportAllDeclaration>,\n            /* decorators */ null,\n          );\n          if (node.type === \"ExportNamedDeclaration\") {\n            node.default = false;\n            delete node.exportKind;\n            return this.castNodeTo(\n              node as N.ExportNamedDeclaration,\n              \"DeclareExportDeclaration\",\n            );\n          } else {\n            return this.castNodeTo(\n              node as N.ExportAllDeclaration,\n              \"DeclareExportAllDeclaration\",\n            );\n          }\n        }\n      }\n\n      this.unexpected();\n    }\n\n    flowParseDeclareModuleExports(\n      node: Undone<N.FlowDeclareModuleExports>,\n    ): N.FlowDeclareModuleExports {\n      this.next();\n      this.expectContextual(tt._exports);\n      node.typeAnnotation = this.flowParseTypeAnnotation();\n      this.semicolon();\n\n      return this.finishNode(node, \"DeclareModuleExports\");\n    }\n\n    flowParseDeclareTypeAlias(\n      node: Undone<N.FlowDeclareTypeAlias>,\n    ): N.FlowDeclareTypeAlias {\n      this.next();\n      const finished = this.flowParseTypeAlias(\n        node,\n      ) as unknown as N.FlowDeclareTypeAlias;\n      // Don't do finishNode as we don't want to process comments twice\n      this.castNodeTo(finished, \"DeclareTypeAlias\");\n      return finished;\n    }\n\n    flowParseDeclareOpaqueType(\n      node: Undone<N.FlowDeclareOpaqueType>,\n    ): N.FlowDeclareOpaqueType {\n      this.next();\n      const finished = this.flowParseOpaqueType(\n        node,\n        true,\n      ) as unknown as N.FlowDeclareOpaqueType;\n      // Don't do finishNode as we don't want to process comments twice\n      this.castNodeTo(finished, \"DeclareOpaqueType\");\n      return finished;\n    }\n\n    flowParseDeclareInterface(\n      node: Undone<N.FlowDeclareInterface>,\n    ): N.FlowDeclareInterface {\n      this.next();\n      this.flowParseInterfaceish(node, /* isClass */ false);\n      return this.finishNode(node, \"DeclareInterface\");\n    }\n\n    // Interfaces\n\n    flowParseInterfaceish(node: Undone<N.FlowDeclare>, isClass: boolean): void {\n      node.id = this.flowParseRestrictedIdentifier(\n        /* liberal */ !isClass,\n        /* declaration */ true,\n      );\n\n      this.scope.declareName(\n        node.id.name,\n        isClass ? BindingFlag.TYPE_FUNCTION : BindingFlag.TYPE_LEXICAL,\n        node.id.loc.start,\n      );\n\n      if (this.match(tt.lt)) {\n        node.typeParameters = this.flowParseTypeParameterDeclaration();\n      } else {\n        node.typeParameters = null;\n      }\n\n      node.extends = [];\n\n      if (this.eat(tt._extends)) {\n        do {\n          node.extends.push(this.flowParseInterfaceExtends());\n        } while (!isClass && this.eat(tt.comma));\n      }\n\n      if (isClass) {\n        node.implements = [];\n        node.mixins = [];\n\n        if (this.eatContextual(tt._mixins)) {\n          do {\n            node.mixins.push(this.flowParseInterfaceExtends());\n          } while (this.eat(tt.comma));\n        }\n\n        if (this.eatContextual(tt._implements)) {\n          do {\n            node.implements.push(this.flowParseInterfaceExtends());\n          } while (this.eat(tt.comma));\n        }\n      }\n\n      node.body = this.flowParseObjectType({\n        allowStatic: isClass,\n        allowExact: false,\n        allowSpread: false,\n        allowProto: isClass,\n        allowInexact: false,\n      });\n    }\n\n    flowParseInterfaceExtends(): N.FlowInterfaceExtends {\n      const node = this.startNode<N.FlowInterfaceExtends>();\n\n      node.id = this.flowParseQualifiedTypeIdentifier();\n      if (this.match(tt.lt)) {\n        node.typeParameters = this.flowParseTypeParameterInstantiation();\n      } else {\n        node.typeParameters = null;\n      }\n\n      return this.finishNode(node, \"InterfaceExtends\");\n    }\n\n    flowParseInterface(node: Undone<N.FlowInterface>): N.FlowInterface {\n      this.flowParseInterfaceish(node, /* isClass */ false);\n      return this.finishNode(node, \"InterfaceDeclaration\");\n    }\n\n    checkNotUnderscore(word: string) {\n      if (word === \"_\") {\n        this.raise(\n          FlowErrors.UnexpectedReservedUnderscore,\n          this.state.startLoc,\n        );\n      }\n    }\n\n    checkReservedType(word: string, startLoc: Position, declaration?: boolean) {\n      if (!reservedTypes.has(word)) return;\n\n      this.raise(\n        declaration\n          ? FlowErrors.AssignReservedType\n          : FlowErrors.UnexpectedReservedType,\n        startLoc,\n        {\n          reservedType: word,\n        },\n      );\n    }\n\n    flowParseRestrictedIdentifier(\n      liberal?: boolean,\n      declaration?: boolean,\n    ): N.Identifier {\n      this.checkReservedType(\n        this.state.value,\n        this.state.startLoc,\n        declaration,\n      );\n      return this.parseIdentifier(liberal);\n    }\n\n    // Type aliases\n\n    flowParseTypeAlias(node: Undone<N.FlowTypeAlias>): N.FlowTypeAlias {\n      node.id = this.flowParseRestrictedIdentifier(\n        /* liberal */ false,\n        /* declaration */ true,\n      );\n      this.scope.declareName(\n        node.id.name,\n        BindingFlag.TYPE_LEXICAL,\n        node.id.loc.start,\n      );\n\n      if (this.match(tt.lt)) {\n        node.typeParameters = this.flowParseTypeParameterDeclaration();\n      } else {\n        node.typeParameters = null;\n      }\n\n      node.right = this.flowParseTypeInitialiser(tt.eq);\n      this.semicolon();\n\n      return this.finishNode(node, \"TypeAlias\");\n    }\n\n    flowParseOpaqueType(\n      node: Undone<N.FlowOpaqueType>,\n      declare: boolean,\n    ): N.FlowOpaqueType {\n      this.expectContextual(tt._type);\n      node.id = this.flowParseRestrictedIdentifier(\n        /* liberal */ true,\n        /* declaration */ true,\n      );\n      this.scope.declareName(\n        node.id.name,\n        BindingFlag.TYPE_LEXICAL,\n        node.id.loc.start,\n      );\n\n      if (this.match(tt.lt)) {\n        node.typeParameters = this.flowParseTypeParameterDeclaration();\n      } else {\n        node.typeParameters = null;\n      }\n\n      // Parse the supertype\n      node.supertype = null;\n      if (this.match(tt.colon)) {\n        node.supertype = this.flowParseTypeInitialiser(tt.colon);\n      }\n\n      node.impltype = null;\n      if (!declare) {\n        node.impltype = this.flowParseTypeInitialiser(tt.eq);\n      }\n      this.semicolon();\n\n      return this.finishNode(node, \"OpaqueType\");\n    }\n\n    // Type annotations\n\n    flowParseTypeParameter(requireDefault: boolean = false): N.TypeParameter {\n      const nodeStartLoc = this.state.startLoc;\n\n      const node = this.startNode<N.TypeParameter>();\n\n      const variance = this.flowParseVariance();\n\n      const ident = this.flowParseTypeAnnotatableIdentifier();\n      node.name = ident.name;\n      // @ts-expect-error migrate to Babel types\n      node.variance = variance;\n      // @ts-expect-error migrate to Babel types\n      node.bound = ident.typeAnnotation;\n\n      if (this.match(tt.eq)) {\n        this.eat(tt.eq);\n        // @ts-expect-error migrate to Babel types\n        node.default = this.flowParseType();\n      } else {\n        if (requireDefault) {\n          this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc);\n        }\n      }\n\n      return this.finishNode(node, \"TypeParameter\");\n    }\n\n    flowParseTypeParameterDeclaration(): N.TypeParameterDeclaration {\n      const oldInType = this.state.inType;\n      const node = this.startNode<N.TypeParameterDeclaration>();\n      node.params = [];\n\n      this.state.inType = true;\n\n      // istanbul ignore else: this condition is already checked at all call sites\n      if (this.match(tt.lt) || this.match(tt.jsxTagStart)) {\n        this.next();\n      } else {\n        this.unexpected();\n      }\n\n      let defaultRequired = false;\n\n      do {\n        const typeParameter = this.flowParseTypeParameter(defaultRequired);\n\n        node.params.push(typeParameter);\n\n        if (typeParameter.default) {\n          defaultRequired = true;\n        }\n\n        if (!this.match(tt.gt)) {\n          this.expect(tt.comma);\n        }\n      } while (!this.match(tt.gt));\n      this.expect(tt.gt);\n\n      this.state.inType = oldInType;\n\n      return this.finishNode(node, \"TypeParameterDeclaration\");\n    }\n\n    // Parse in top level normal context if we are in a JSX context\n    flowInTopLevelContext<T>(cb: () => T): T {\n      if (this.curContext() !== tc.brace) {\n        const oldContext = this.state.context;\n        this.state.context = [oldContext[0]];\n        try {\n          return cb();\n        } finally {\n          this.state.context = oldContext;\n        }\n      } else {\n        return cb();\n      }\n    }\n\n    // Used when parsing type arguments from ES or JSX productions, where the first token\n    // has been created without state.inType. Thus we need to re-scan the lt token.\n    flowParseTypeParameterInstantiationInExpression():\n      | N.TypeParameterInstantiation\n      | undefined {\n      if (this.reScan_lt() !== tt.lt) return;\n      return this.flowParseTypeParameterInstantiation();\n    }\n\n    flowParseTypeParameterInstantiation(): N.TypeParameterInstantiation {\n      const node = this.startNode<N.TypeParameterInstantiation>();\n      const oldInType = this.state.inType;\n\n      this.state.inType = true;\n      node.params = [];\n      this.flowInTopLevelContext(() => {\n        this.expect(tt.lt);\n        const oldNoAnonFunctionType = this.state.noAnonFunctionType;\n        this.state.noAnonFunctionType = false;\n        while (!this.match(tt.gt)) {\n          node.params.push(this.flowParseType());\n          if (!this.match(tt.gt)) {\n            this.expect(tt.comma);\n          }\n        }\n        this.state.noAnonFunctionType = oldNoAnonFunctionType;\n      });\n\n      this.state.inType = oldInType;\n      if (!this.state.inType && this.curContext() === tc.brace) {\n        // rescan `>` when we are no longer in type context and JSX parsing context\n        // since it was tokenized when `inType` is `true`.\n        this.reScan_lt_gt();\n      }\n      this.expect(tt.gt);\n\n      return this.finishNode(node, \"TypeParameterInstantiation\");\n    }\n\n    flowParseTypeParameterInstantiationCallOrNew(): N.TypeParameterInstantiation {\n      if (this.reScan_lt() !== tt.lt) return;\n      const node = this.startNode<N.TypeParameterInstantiation>();\n      const oldInType = this.state.inType;\n      node.params = [];\n\n      this.state.inType = true;\n\n      this.expect(tt.lt);\n      while (!this.match(tt.gt)) {\n        node.params.push(this.flowParseTypeOrImplicitInstantiation());\n        if (!this.match(tt.gt)) {\n          this.expect(tt.comma);\n        }\n      }\n      this.expect(tt.gt);\n\n      this.state.inType = oldInType;\n\n      return this.finishNode(node, \"TypeParameterInstantiation\");\n    }\n\n    flowParseInterfaceType(): N.FlowInterfaceType {\n      const node = this.startNode<N.FlowInterfaceType>();\n      this.expectContextual(tt._interface);\n\n      node.extends = [];\n      if (this.eat(tt._extends)) {\n        do {\n          node.extends.push(this.flowParseInterfaceExtends());\n        } while (this.eat(tt.comma));\n      }\n\n      node.body = this.flowParseObjectType({\n        allowStatic: false,\n        allowExact: false,\n        allowSpread: false,\n        allowProto: false,\n        allowInexact: false,\n      });\n\n      return this.finishNode(node, \"InterfaceTypeAnnotation\");\n    }\n\n    flowParseObjectPropertyKey(): N.Expression {\n      return this.match(tt.num) || this.match(tt.string)\n        ? super.parseExprAtom()\n        : this.parseIdentifier(true);\n    }\n\n    flowParseObjectTypeIndexer(\n      node: Undone<N.FlowObjectTypeIndexer>,\n      isStatic: boolean,\n      variance?: N.FlowVariance | null,\n    ): N.FlowObjectTypeIndexer {\n      node.static = isStatic;\n\n      // Note: bracketL has already been consumed\n      if (this.lookahead().type === tt.colon) {\n        node.id = this.flowParseObjectPropertyKey();\n        node.key = this.flowParseTypeInitialiser();\n      } else {\n        node.id = null;\n        node.key = this.flowParseType();\n      }\n      this.expect(tt.bracketR);\n      node.value = this.flowParseTypeInitialiser();\n      node.variance = variance;\n\n      return this.finishNode(node, \"ObjectTypeIndexer\");\n    }\n\n    flowParseObjectTypeInternalSlot(\n      node: Undone<N.FlowObjectTypeInternalSlot>,\n      isStatic: boolean,\n    ): N.FlowObjectTypeInternalSlot {\n      node.static = isStatic;\n      // Note: both bracketL have already been consumed\n      node.id = this.flowParseObjectPropertyKey();\n      this.expect(tt.bracketR);\n      this.expect(tt.bracketR);\n      if (this.match(tt.lt) || this.match(tt.parenL)) {\n        node.method = true;\n        node.optional = false;\n        node.value = this.flowParseObjectTypeMethodish(\n          this.startNodeAt(node.loc.start),\n        );\n      } else {\n        node.method = false;\n        if (this.eat(tt.question)) {\n          node.optional = true;\n        }\n        node.value = this.flowParseTypeInitialiser();\n      }\n      return this.finishNode(node, \"ObjectTypeInternalSlot\");\n    }\n\n    flowParseObjectTypeMethodish(\n      node: Undone<N.FlowFunctionTypeAnnotation>,\n    ): N.FlowFunctionTypeAnnotation {\n      node.params = [];\n      node.rest = null;\n      node.typeParameters = null;\n      node.this = null;\n\n      if (this.match(tt.lt)) {\n        node.typeParameters = this.flowParseTypeParameterDeclaration();\n      }\n\n      this.expect(tt.parenL);\n      if (this.match(tt._this)) {\n        node.this = this.flowParseFunctionTypeParam(/* first */ true);\n        // match Flow parser behavior\n        node.this.name = null;\n        if (!this.match(tt.parenR)) {\n          this.expect(tt.comma);\n        }\n      }\n      while (!this.match(tt.parenR) && !this.match(tt.ellipsis)) {\n        node.params.push(this.flowParseFunctionTypeParam(false));\n        if (!this.match(tt.parenR)) {\n          this.expect(tt.comma);\n        }\n      }\n\n      if (this.eat(tt.ellipsis)) {\n        node.rest = this.flowParseFunctionTypeParam(false);\n      }\n      this.expect(tt.parenR);\n      node.returnType = this.flowParseTypeInitialiser();\n\n      return this.finishNode(node, \"FunctionTypeAnnotation\");\n    }\n\n    flowParseObjectTypeCallProperty(\n      node: Undone<N.FlowObjectTypeCallProperty>,\n      isStatic: boolean,\n    ): N.FlowObjectTypeCallProperty {\n      const valueNode = this.startNode();\n      node.static = isStatic;\n      node.value = this.flowParseObjectTypeMethodish(valueNode);\n      return this.finishNode(node, \"ObjectTypeCallProperty\");\n    }\n\n    flowParseObjectType({\n      allowStatic,\n      allowExact,\n      allowSpread,\n      allowProto,\n      allowInexact,\n    }: {\n      allowStatic: boolean;\n      allowExact: boolean;\n      allowSpread: boolean;\n      allowProto: boolean;\n      allowInexact: boolean;\n    }): N.FlowObjectTypeAnnotation {\n      const oldInType = this.state.inType;\n      this.state.inType = true;\n\n      const nodeStart = this.startNode<N.FlowObjectTypeAnnotation>();\n\n      nodeStart.callProperties = [];\n      nodeStart.properties = [];\n      nodeStart.indexers = [];\n      nodeStart.internalSlots = [];\n\n      let endDelim;\n      let exact;\n      let inexact = false;\n      if (allowExact && this.match(tt.braceBarL)) {\n        this.expect(tt.braceBarL);\n        endDelim = tt.braceBarR;\n        exact = true;\n      } else {\n        this.expect(tt.braceL);\n        endDelim = tt.braceR;\n        exact = false;\n      }\n\n      nodeStart.exact = exact;\n\n      while (!this.match(endDelim)) {\n        let isStatic = false;\n        let protoStartLoc: Position | undefined | null = null;\n        let inexactStartLoc: Position | undefined | null = null;\n        const node = this.startNode();\n\n        if (allowProto && this.isContextual(tt._proto)) {\n          const lookahead = this.lookahead();\n\n          if (lookahead.type !== tt.colon && lookahead.type !== tt.question) {\n            this.next();\n            protoStartLoc = this.state.startLoc;\n            allowStatic = false;\n          }\n        }\n\n        if (allowStatic && this.isContextual(tt._static)) {\n          const lookahead = this.lookahead();\n\n          // static is a valid identifier name\n          if (lookahead.type !== tt.colon && lookahead.type !== tt.question) {\n            this.next();\n            isStatic = true;\n          }\n        }\n\n        const variance = this.flowParseVariance();\n\n        if (this.eat(tt.bracketL)) {\n          if (protoStartLoc != null) {\n            this.unexpected(protoStartLoc);\n          }\n          if (this.eat(tt.bracketL)) {\n            if (variance) {\n              this.unexpected(variance.loc.start);\n            }\n            nodeStart.internalSlots.push(\n              this.flowParseObjectTypeInternalSlot(node, isStatic),\n            );\n          } else {\n            nodeStart.indexers.push(\n              this.flowParseObjectTypeIndexer(node, isStatic, variance),\n            );\n          }\n        } else if (this.match(tt.parenL) || this.match(tt.lt)) {\n          if (protoStartLoc != null) {\n            this.unexpected(protoStartLoc);\n          }\n          if (variance) {\n            this.unexpected(variance.loc.start);\n          }\n          nodeStart.callProperties.push(\n            this.flowParseObjectTypeCallProperty(node, isStatic),\n          );\n        } else {\n          let kind = \"init\";\n\n          if (this.isContextual(tt._get) || this.isContextual(tt._set)) {\n            const lookahead = this.lookahead();\n            if (tokenIsLiteralPropertyName(lookahead.type)) {\n              kind = this.state.value;\n              this.next();\n            }\n          }\n\n          const propOrInexact = this.flowParseObjectTypeProperty(\n            node,\n            isStatic,\n            protoStartLoc,\n            variance,\n            kind,\n            allowSpread,\n            allowInexact ?? !exact,\n          );\n\n          if (propOrInexact === null) {\n            inexact = true;\n            inexactStartLoc = this.state.lastTokStartLoc;\n          } else {\n            nodeStart.properties.push(propOrInexact);\n          }\n        }\n\n        this.flowObjectTypeSemicolon();\n\n        if (\n          inexactStartLoc &&\n          !this.match(tt.braceR) &&\n          !this.match(tt.braceBarR)\n        ) {\n          this.raise(\n            FlowErrors.UnexpectedExplicitInexactInObject,\n            inexactStartLoc,\n          );\n        }\n      }\n\n      this.expect(endDelim);\n\n      /* The inexact flag should only be added on ObjectTypeAnnotations that\n       * are not the body of an interface, declare interface, or declare class.\n       * Since spreads are only allowed in object types, checking that is\n       * sufficient here.\n       */\n      if (allowSpread) {\n        nodeStart.inexact = inexact;\n      }\n\n      const out = this.finishNode(nodeStart, \"ObjectTypeAnnotation\");\n\n      this.state.inType = oldInType;\n\n      return out;\n    }\n\n    flowParseObjectTypeProperty(\n      node: Undone<N.FlowObjectTypeProperty | N.FlowObjectTypeSpreadProperty>,\n      isStatic: boolean,\n      protoStartLoc: Position | undefined | null,\n      variance: N.FlowVariance | undefined | null,\n      kind: string,\n      allowSpread: boolean,\n      allowInexact: boolean,\n    ): N.FlowObjectTypeProperty | N.FlowObjectTypeSpreadProperty | null {\n      if (this.eat(tt.ellipsis)) {\n        const isInexactToken =\n          this.match(tt.comma) ||\n          this.match(tt.semi) ||\n          this.match(tt.braceR) ||\n          this.match(tt.braceBarR);\n\n        if (isInexactToken) {\n          if (!allowSpread) {\n            this.raise(\n              FlowErrors.InexactInsideNonObject,\n              this.state.lastTokStartLoc,\n            );\n          } else if (!allowInexact) {\n            this.raise(\n              FlowErrors.InexactInsideExact,\n              this.state.lastTokStartLoc,\n            );\n          }\n          if (variance) {\n            this.raise(FlowErrors.InexactVariance, variance);\n          }\n\n          return null;\n        }\n\n        if (!allowSpread) {\n          this.raise(\n            FlowErrors.UnexpectedSpreadType,\n            this.state.lastTokStartLoc,\n          );\n        }\n        if (protoStartLoc != null) {\n          this.unexpected(protoStartLoc);\n        }\n        if (variance) {\n          this.raise(FlowErrors.SpreadVariance, variance);\n        }\n\n        node.argument = this.flowParseType();\n        return this.finishNode(node, \"ObjectTypeSpreadProperty\");\n      } else {\n        node.key = this.flowParseObjectPropertyKey();\n        node.static = isStatic;\n        node.proto = protoStartLoc != null;\n        node.kind = kind;\n\n        let optional = false;\n        if (this.match(tt.lt) || this.match(tt.parenL)) {\n          // This is a method property\n          node.method = true;\n\n          if (protoStartLoc != null) {\n            this.unexpected(protoStartLoc);\n          }\n          if (variance) {\n            this.unexpected(variance.loc.start);\n          }\n\n          node.value = this.flowParseObjectTypeMethodish(\n            this.startNodeAt(node.loc.start),\n          );\n          if (kind === \"get\" || kind === \"set\") {\n            this.flowCheckGetterSetterParams(node);\n          }\n          /** Declared classes/interfaces do not allow spread */\n          if (\n            !allowSpread &&\n            node.key.name === \"constructor\" &&\n            node.value.this\n          ) {\n            this.raise(\n              FlowErrors.ThisParamBannedInConstructor,\n              node.value.this,\n            );\n          }\n        } else {\n          if (kind !== \"init\") this.unexpected();\n\n          node.method = false;\n\n          if (this.eat(tt.question)) {\n            optional = true;\n          }\n          node.value = this.flowParseTypeInitialiser();\n          node.variance = variance;\n        }\n\n        node.optional = optional;\n\n        return this.finishNode(node, \"ObjectTypeProperty\");\n      }\n    }\n\n    // This is similar to checkGetterSetterParams, but as\n    // @babel/parser uses non estree properties we cannot reuse it here\n    flowCheckGetterSetterParams(\n      property: Undone<\n        N.FlowObjectTypeProperty | N.FlowObjectTypeSpreadProperty\n      >,\n    ): void {\n      const paramCount = property.kind === \"get\" ? 0 : 1;\n      const length =\n        property.value.params.length + (property.value.rest ? 1 : 0);\n\n      if (property.value.this) {\n        this.raise(\n          property.kind === \"get\"\n            ? FlowErrors.GetterMayNotHaveThisParam\n            : FlowErrors.SetterMayNotHaveThisParam,\n          property.value.this,\n        );\n      }\n\n      if (length !== paramCount) {\n        this.raise(\n          property.kind === \"get\"\n            ? Errors.BadGetterArity\n            : Errors.BadSetterArity,\n          property,\n        );\n      }\n\n      if (property.kind === \"set\" && property.value.rest) {\n        this.raise(Errors.BadSetterRestParameter, property);\n      }\n    }\n\n    flowObjectTypeSemicolon(): void {\n      if (\n        !this.eat(tt.semi) &&\n        !this.eat(tt.comma) &&\n        !this.match(tt.braceR) &&\n        !this.match(tt.braceBarR)\n      ) {\n        this.unexpected();\n      }\n    }\n\n    flowParseQualifiedTypeIdentifier(\n      startLoc?: Position,\n      id?: N.Identifier,\n    ): N.FlowQualifiedTypeIdentifier | N.Identifier {\n      startLoc ??= this.state.startLoc;\n      let node: N.Identifier | N.FlowQualifiedTypeIdentifier =\n        id || this.flowParseRestrictedIdentifier(true);\n\n      while (this.eat(tt.dot)) {\n        const node2 = this.startNodeAt<N.FlowQualifiedTypeIdentifier>(startLoc);\n        node2.qualification = node;\n        node2.id = this.flowParseRestrictedIdentifier(true);\n        node = this.finishNode(node2, \"QualifiedTypeIdentifier\");\n      }\n\n      return node;\n    }\n\n    flowParseGenericType(\n      startLoc: Position,\n      id: N.Identifier,\n    ): N.FlowGenericTypeAnnotation {\n      const node = this.startNodeAt<N.FlowGenericTypeAnnotation>(startLoc);\n\n      node.typeParameters = null;\n      node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id);\n\n      if (this.match(tt.lt)) {\n        node.typeParameters = this.flowParseTypeParameterInstantiation();\n      }\n\n      return this.finishNode(node, \"GenericTypeAnnotation\");\n    }\n\n    flowParseTypeofType(): N.FlowTypeofTypeAnnotation {\n      const node = this.startNode<N.FlowTypeofTypeAnnotation>();\n      this.expect(tt._typeof);\n      node.argument = this.flowParsePrimaryType();\n      return this.finishNode(node, \"TypeofTypeAnnotation\");\n    }\n\n    flowParseTupleType(): N.FlowTupleTypeAnnotation {\n      const node = this.startNode<N.FlowTupleTypeAnnotation>();\n      node.types = [];\n      this.expect(tt.bracketL);\n      // We allow trailing commas\n      while (this.state.pos < this.length && !this.match(tt.bracketR)) {\n        node.types.push(this.flowParseType());\n        if (this.match(tt.bracketR)) break;\n        this.expect(tt.comma);\n      }\n      this.expect(tt.bracketR);\n      return this.finishNode(node, \"TupleTypeAnnotation\");\n    }\n\n    flowParseFunctionTypeParam(first: boolean): N.FlowFunctionTypeParam {\n      let name = null;\n      let optional = false;\n      let typeAnnotation = null;\n      const node = this.startNode<N.FlowFunctionTypeParam>();\n      const lh = this.lookahead();\n      const isThis = this.state.type === tt._this;\n\n      if (lh.type === tt.colon || lh.type === tt.question) {\n        if (isThis && !first) {\n          this.raise(FlowErrors.ThisParamMustBeFirst, node);\n        }\n        name = this.parseIdentifier(isThis);\n        if (this.eat(tt.question)) {\n          optional = true;\n          if (isThis) {\n            this.raise(FlowErrors.ThisParamMayNotBeOptional, node);\n          }\n        }\n        typeAnnotation = this.flowParseTypeInitialiser();\n      } else {\n        typeAnnotation = this.flowParseType();\n      }\n      node.name = name;\n      node.optional = optional;\n      node.typeAnnotation = typeAnnotation;\n      return this.finishNode(node, \"FunctionTypeParam\");\n    }\n\n    reinterpretTypeAsFunctionTypeParam(\n      type: N.FlowType,\n    ): N.FlowFunctionTypeParam {\n      const node = this.startNodeAt<N.FlowFunctionTypeParam>(type.loc.start);\n      node.name = null;\n      node.optional = false;\n      node.typeAnnotation = type;\n      return this.finishNode(node, \"FunctionTypeParam\");\n    }\n\n    flowParseFunctionTypeParams(params: N.FlowFunctionTypeParam[] = []): {\n      params: N.FlowFunctionTypeParam[];\n      rest: N.FlowFunctionTypeParam | undefined | null;\n      _this: N.FlowFunctionTypeParam | undefined | null;\n    } {\n      let rest: N.FlowFunctionTypeParam | undefined | null = null;\n      let _this: N.FlowFunctionTypeParam | undefined | null = null;\n      if (this.match(tt._this)) {\n        _this = this.flowParseFunctionTypeParam(/* first */ true);\n        // match Flow parser behavior\n        _this.name = null;\n        if (!this.match(tt.parenR)) {\n          this.expect(tt.comma);\n        }\n      }\n      while (!this.match(tt.parenR) && !this.match(tt.ellipsis)) {\n        params.push(this.flowParseFunctionTypeParam(false));\n        if (!this.match(tt.parenR)) {\n          this.expect(tt.comma);\n        }\n      }\n      if (this.eat(tt.ellipsis)) {\n        rest = this.flowParseFunctionTypeParam(false);\n      }\n      return { params, rest, _this };\n    }\n\n    flowIdentToTypeAnnotation(\n      startLoc: Position,\n      node: Undone<N.FlowType>,\n      id: N.Identifier,\n    ): N.FlowType {\n      switch (id.name) {\n        case \"any\":\n          return this.finishNode(node, \"AnyTypeAnnotation\");\n\n        case \"bool\":\n        case \"boolean\":\n          return this.finishNode(node, \"BooleanTypeAnnotation\");\n\n        case \"mixed\":\n          return this.finishNode(node, \"MixedTypeAnnotation\");\n\n        case \"empty\":\n          return this.finishNode(node, \"EmptyTypeAnnotation\");\n\n        case \"number\":\n          return this.finishNode(node, \"NumberTypeAnnotation\");\n\n        case \"string\":\n          return this.finishNode(node, \"StringTypeAnnotation\");\n\n        case \"symbol\":\n          return this.finishNode(node, \"SymbolTypeAnnotation\");\n\n        default:\n          this.checkNotUnderscore(id.name);\n          return this.flowParseGenericType(startLoc, id);\n      }\n    }\n\n    // The parsing of types roughly parallels the parsing of expressions, and\n    // primary types are kind of like primary expressions...they're the\n    // primitives with which other types are constructed.\n    flowParsePrimaryType(): N.FlowType {\n      const startLoc = this.state.startLoc;\n      const node = this.startNode<N.FlowOtherTypeAnnotation>();\n      let tmp;\n      let type;\n      let isGroupedType = false;\n      const oldNoAnonFunctionType = this.state.noAnonFunctionType;\n\n      switch (this.state.type) {\n        case tt.braceL:\n          return this.flowParseObjectType({\n            allowStatic: false,\n            allowExact: false,\n            allowSpread: true,\n            allowProto: false,\n            allowInexact: true,\n          });\n\n        case tt.braceBarL:\n          return this.flowParseObjectType({\n            allowStatic: false,\n            allowExact: true,\n            allowSpread: true,\n            allowProto: false,\n            allowInexact: false,\n          });\n\n        case tt.bracketL:\n          this.state.noAnonFunctionType = false;\n          type = this.flowParseTupleType();\n          this.state.noAnonFunctionType = oldNoAnonFunctionType;\n          return type;\n\n        case tt.lt: {\n          const node = this.startNode<N.FlowFunctionTypeAnnotation>();\n          node.typeParameters = this.flowParseTypeParameterDeclaration();\n          this.expect(tt.parenL);\n          tmp = this.flowParseFunctionTypeParams();\n          node.params = tmp.params;\n          node.rest = tmp.rest;\n          node.this = tmp._this;\n          this.expect(tt.parenR);\n\n          this.expect(tt.arrow);\n\n          node.returnType = this.flowParseType();\n\n          return this.finishNode(node, \"FunctionTypeAnnotation\");\n        }\n\n        case tt.parenL: {\n          const node = this.startNode<N.FlowFunctionTypeAnnotation>();\n          this.next();\n\n          // Check to see if this is actually a grouped type\n          if (!this.match(tt.parenR) && !this.match(tt.ellipsis)) {\n            if (tokenIsIdentifier(this.state.type) || this.match(tt._this)) {\n              const token = this.lookahead().type;\n              isGroupedType = token !== tt.question && token !== tt.colon;\n            } else {\n              isGroupedType = true;\n            }\n          }\n\n          if (isGroupedType) {\n            this.state.noAnonFunctionType = false;\n            type = this.flowParseType();\n            this.state.noAnonFunctionType = oldNoAnonFunctionType;\n\n            // A `,` or a `) =>` means this is an anonymous function type\n            if (\n              this.state.noAnonFunctionType ||\n              !(\n                this.match(tt.comma) ||\n                (this.match(tt.parenR) && this.lookahead().type === tt.arrow)\n              )\n            ) {\n              this.expect(tt.parenR);\n              return type;\n            } else {\n              // Eat a comma if there is one\n              this.eat(tt.comma);\n            }\n          }\n\n          if (type) {\n            tmp = this.flowParseFunctionTypeParams([\n              this.reinterpretTypeAsFunctionTypeParam(type),\n            ]);\n          } else {\n            tmp = this.flowParseFunctionTypeParams();\n          }\n\n          node.params = tmp.params;\n          node.rest = tmp.rest;\n          node.this = tmp._this;\n\n          this.expect(tt.parenR);\n\n          this.expect(tt.arrow);\n\n          node.returnType = this.flowParseType();\n\n          node.typeParameters = null;\n\n          return this.finishNode(node, \"FunctionTypeAnnotation\");\n        }\n\n        case tt.string:\n          return this.parseLiteral<N.StringLiteralTypeAnnotation>(\n            this.state.value,\n            \"StringLiteralTypeAnnotation\",\n          );\n\n        case tt._true:\n        case tt._false:\n          node.value = this.match(tt._true);\n          this.next();\n          return this.finishNode(\n            node as Undone<N.BooleanLiteralTypeAnnotation>,\n            \"BooleanLiteralTypeAnnotation\",\n          );\n\n        case tt.plusMin:\n          if (this.state.value === \"-\") {\n            this.next();\n            if (this.match(tt.num)) {\n              return this.parseLiteralAtNode<N.NumberLiteralTypeAnnotation>(\n                -this.state.value,\n                \"NumberLiteralTypeAnnotation\",\n                node,\n              );\n            }\n\n            if (this.match(tt.bigint)) {\n              return this.parseLiteralAtNode<N.BigIntLiteralTypeAnnotation>(\n                -this.state.value,\n                \"BigIntLiteralTypeAnnotation\",\n                node,\n              );\n            }\n\n            throw this.raise(\n              FlowErrors.UnexpectedSubtractionOperand,\n              this.state.startLoc,\n            );\n          }\n          this.unexpected();\n          return;\n        case tt.num:\n          return this.parseLiteral(\n            this.state.value,\n            \"NumberLiteralTypeAnnotation\",\n          );\n\n        case tt.bigint:\n          return this.parseLiteral(\n            this.state.value,\n            \"BigIntLiteralTypeAnnotation\",\n          );\n\n        case tt._void:\n          this.next();\n          return this.finishNode(node, \"VoidTypeAnnotation\");\n\n        case tt._null:\n          this.next();\n          return this.finishNode(node, \"NullLiteralTypeAnnotation\");\n\n        case tt._this:\n          this.next();\n          return this.finishNode(node, \"ThisTypeAnnotation\");\n\n        case tt.star:\n          this.next();\n          return this.finishNode(node, \"ExistsTypeAnnotation\");\n\n        case tt._typeof:\n          return this.flowParseTypeofType();\n\n        default:\n          if (tokenIsKeyword(this.state.type)) {\n            const label = tokenLabelName(this.state.type);\n            this.next();\n            return super.createIdentifier(node as Undone<N.Identifier>, label);\n          } else if (tokenIsIdentifier(this.state.type)) {\n            if (this.isContextual(tt._interface)) {\n              return this.flowParseInterfaceType();\n            }\n\n            return this.flowIdentToTypeAnnotation(\n              startLoc,\n              node,\n              this.parseIdentifier(),\n            );\n          }\n      }\n\n      this.unexpected();\n    }\n\n    flowParsePostfixType(): N.FlowType {\n      const startLoc = this.state.startLoc;\n      let type = this.flowParsePrimaryType();\n      let seenOptionalIndexedAccess = false;\n      while (\n        (this.match(tt.bracketL) || this.match(tt.questionDot)) &&\n        !this.canInsertSemicolon()\n      ) {\n        const node = this.startNodeAt<N.FlowOtherTypeAnnotation>(startLoc);\n        const optional = this.eat(tt.questionDot);\n        seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;\n        this.expect(tt.bracketL);\n        if (!optional && this.match(tt.bracketR)) {\n          node.elementType = type;\n          this.next(); // eat `]`\n          type = this.finishNode(node, \"ArrayTypeAnnotation\");\n        } else {\n          node.objectType = type;\n          node.indexType = this.flowParseType();\n          this.expect(tt.bracketR);\n          if (seenOptionalIndexedAccess) {\n            node.optional = optional;\n            type = this.finishNode<N.FlowOptionalIndexedAccessType>(\n              // @ts-expect-error todo(flow->ts)\n              node,\n              \"OptionalIndexedAccessType\",\n            );\n          } else {\n            type = this.finishNode<N.FlowIndexedAccessType>(\n              // @ts-expect-error todo(flow->ts)\n              node,\n              \"IndexedAccessType\",\n            );\n          }\n        }\n      }\n      return type;\n    }\n\n    flowParsePrefixType(): N.FlowType {\n      const node = this.startNode<N.FlowOtherTypeAnnotation>();\n      if (this.eat(tt.question)) {\n        node.typeAnnotation = this.flowParsePrefixType();\n        return this.finishNode(node, \"NullableTypeAnnotation\");\n      } else {\n        return this.flowParsePostfixType();\n      }\n    }\n\n    flowParseAnonFunctionWithoutParens(): N.FlowType {\n      const param = this.flowParsePrefixType();\n      if (!this.state.noAnonFunctionType && this.eat(tt.arrow)) {\n        // TODO: This should be a type error. Passing in a SourceLocation, and it expects a Position.\n        const node = this.startNodeAt<N.FlowFunctionTypeAnnotation>(\n          param.loc.start,\n        );\n        node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];\n        node.rest = null;\n        node.this = null;\n        node.returnType = this.flowParseType();\n        node.typeParameters = null;\n        return this.finishNode(node, \"FunctionTypeAnnotation\");\n      }\n      return param;\n    }\n\n    flowParseIntersectionType(): N.FlowType {\n      const node = this.startNode<N.FlowOtherTypeAnnotation>();\n      this.eat(tt.bitwiseAND);\n      const type = this.flowParseAnonFunctionWithoutParens();\n      node.types = [type];\n      while (this.eat(tt.bitwiseAND)) {\n        node.types.push(this.flowParseAnonFunctionWithoutParens());\n      }\n      return node.types.length === 1\n        ? type\n        : this.finishNode(node, \"IntersectionTypeAnnotation\");\n    }\n\n    flowParseUnionType(): N.FlowType {\n      const node = this.startNode<N.FlowOtherTypeAnnotation>();\n      this.eat(tt.bitwiseOR);\n      const type = this.flowParseIntersectionType();\n      node.types = [type];\n      while (this.eat(tt.bitwiseOR)) {\n        node.types.push(this.flowParseIntersectionType());\n      }\n      return node.types.length === 1\n        ? type\n        : this.finishNode(node, \"UnionTypeAnnotation\");\n    }\n\n    flowParseType(): N.FlowType {\n      const oldInType = this.state.inType;\n      this.state.inType = true;\n      const type = this.flowParseUnionType();\n      this.state.inType = oldInType;\n      return type;\n    }\n\n    flowParseTypeOrImplicitInstantiation(): N.FlowType {\n      if (this.state.type === tt.name && this.state.value === \"_\") {\n        const startLoc = this.state.startLoc;\n        const node = this.parseIdentifier();\n        return this.flowParseGenericType(startLoc, node);\n      } else {\n        return this.flowParseType();\n      }\n    }\n\n    flowParseTypeAnnotation(): N.TypeAnnotation {\n      const node = this.startNode<N.TypeAnnotation>();\n      node.typeAnnotation = this.flowParseTypeInitialiser();\n      return this.finishNode(node, \"TypeAnnotation\");\n    }\n\n    flowParseTypeAnnotatableIdentifier(\n      allowPrimitiveOverride?: boolean,\n    ): N.Identifier {\n      const ident = allowPrimitiveOverride\n        ? this.parseIdentifier()\n        : this.flowParseRestrictedIdentifier();\n      if (this.match(tt.colon)) {\n        ident.typeAnnotation = this.flowParseTypeAnnotation();\n        this.resetEndLocation(ident);\n      }\n      return ident;\n    }\n\n    typeCastToParameter(node: N.TypeCastExpression): N.Expression {\n      (node.expression as N.Identifier).typeAnnotation = node.typeAnnotation;\n\n      this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);\n\n      return node.expression;\n    }\n\n    flowParseVariance(): N.FlowVariance | undefined | null {\n      let variance = null;\n      if (this.match(tt.plusMin)) {\n        variance = this.startNode<N.FlowVariance>();\n        if (this.state.value === \"+\") {\n          variance.kind = \"plus\";\n        } else {\n          variance.kind = \"minus\";\n        }\n        this.next();\n        return this.finishNode(variance, \"Variance\");\n      }\n      return variance;\n    }\n\n    // ==================================\n    // Overrides\n    // ==================================\n\n    parseFunctionBody(\n      node: N.Function,\n      allowExpressionBody?: boolean | null,\n      isMethod: boolean = false,\n    ): void {\n      if (allowExpressionBody) {\n        this.forwardNoArrowParamsConversionAt(node, () =>\n          super.parseFunctionBody(node, true, isMethod),\n        );\n        return;\n      }\n\n      super.parseFunctionBody(node, false, isMethod);\n    }\n\n    parseFunctionBodyAndFinish<\n      T extends\n        | N.Function\n        | N.TSDeclareMethod\n        | N.TSDeclareFunction\n        | N.ClassPrivateMethod,\n    >(node: Undone<T>, type: T[\"type\"], isMethod: boolean = false): T {\n      if (this.match(tt.colon)) {\n        const typeNode = this.startNode<N.TypeAnnotation>();\n\n        [\n          typeNode.typeAnnotation,\n          // @ts-expect-error predicate may not exist\n          node.predicate,\n        ] = this.flowParseTypeAndPredicateInitialiser();\n\n        node.returnType = typeNode.typeAnnotation\n          ? this.finishNode(typeNode, \"TypeAnnotation\")\n          : null;\n      }\n\n      return super.parseFunctionBodyAndFinish(node, type, isMethod);\n    }\n\n    // interfaces and enums\n    parseStatementLike(flags: ParseStatementFlag): N.Statement {\n      // strict mode handling of `interface` since it's a reserved word\n      if (this.state.strict && this.isContextual(tt._interface)) {\n        const lookahead = this.lookahead();\n        if (tokenIsKeywordOrIdentifier(lookahead.type)) {\n          const node = this.startNode<N.FlowInterface>();\n          this.next();\n          return this.flowParseInterface(node);\n        }\n      } else if (this.isContextual(tt._enum)) {\n        const node = this.startNode();\n        this.next();\n        return this.flowParseEnumDeclaration(node);\n      }\n      const stmt = super.parseStatementLike(flags);\n      // We will parse a flow pragma in any comment before the first statement.\n      if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {\n        this.flowPragma = null;\n      }\n      return stmt;\n    }\n\n    // declares, interfaces and type aliases\n    parseExpressionStatement(\n      node: N.ExpressionStatement,\n      expr: N.Expression,\n      decorators: N.Decorator[] | null,\n    ): N.ExpressionStatement {\n      if (expr.type === \"Identifier\") {\n        if (expr.name === \"declare\") {\n          if (\n            this.match(tt._class) ||\n            tokenIsIdentifier(this.state.type) ||\n            this.match(tt._function) ||\n            this.match(tt._var) ||\n            this.match(tt._export)\n          ) {\n            // @ts-expect-error: refine typings\n            return this.flowParseDeclare(node);\n          }\n        } else if (tokenIsIdentifier(this.state.type)) {\n          if (expr.name === \"interface\") {\n            // @ts-expect-error: refine typings\n            return this.flowParseInterface(node);\n          } else if (expr.name === \"type\") {\n            // @ts-expect-error: refine typings\n            return this.flowParseTypeAlias(node);\n          } else if (expr.name === \"opaque\") {\n            // @ts-expect-error: refine typings\n            return this.flowParseOpaqueType(node, false);\n          }\n        }\n      }\n\n      return super.parseExpressionStatement(node, expr, decorators);\n    }\n\n    // export type\n    shouldParseExportDeclaration(): boolean {\n      const { type } = this.state;\n      if (type === tt._enum || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {\n        return !this.state.containsEsc;\n      }\n      return super.shouldParseExportDeclaration();\n    }\n\n    isExportDefaultSpecifier(): boolean {\n      const { type } = this.state;\n      if (type === tt._enum || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {\n        return this.state.containsEsc;\n      }\n\n      return super.isExportDefaultSpecifier();\n    }\n\n    parseExportDefaultExpression() {\n      if (this.isContextual(tt._enum)) {\n        const node = this.startNode();\n        this.next();\n        return this.flowParseEnumDeclaration(node);\n      }\n      return super.parseExportDefaultExpression();\n    }\n\n    parseConditional(\n      expr: N.Expression,\n\n      startLoc: Position,\n      refExpressionErrors?: ExpressionErrors | null,\n    ): N.Expression {\n      if (!this.match(tt.question)) return expr;\n\n      if (this.state.maybeInArrowParameters) {\n        const nextCh = this.lookaheadCharCode();\n        // These tokens cannot start an expression, so if one of them follows\n        // ? then we are probably in an arrow function parameters list and we\n        // don't parse the conditional expression.\n        if (\n          nextCh === charCodes.comma || // (a?, b) => c\n          nextCh === charCodes.equalsTo || // (a? = b) => c\n          nextCh === charCodes.colon || // (a?: b) => c\n          nextCh === charCodes.rightParenthesis // (a?) => c\n        ) {\n          /*:: invariant(refExpressionErrors != null) */\n          this.setOptionalParametersError(refExpressionErrors);\n          return expr;\n        }\n      }\n\n      this.expect(tt.question);\n      const state = this.state.clone();\n      const originalNoArrowAt = this.state.noArrowAt;\n      const node = this.startNodeAt<N.ConditionalExpression>(startLoc);\n      let { consequent, failed } = this.tryParseConditionalConsequent();\n      let [valid, invalid] = this.getArrowLikeExpressions(consequent);\n\n      if (failed || invalid.length > 0) {\n        const noArrowAt = [...originalNoArrowAt];\n\n        if (invalid.length > 0) {\n          this.state = state;\n          this.state.noArrowAt = noArrowAt;\n\n          for (let i = 0; i < invalid.length; i++) {\n            noArrowAt.push(invalid[i].start);\n          }\n\n          ({ consequent, failed } = this.tryParseConditionalConsequent());\n          [valid, invalid] = this.getArrowLikeExpressions(consequent);\n        }\n\n        if (failed && valid.length > 1) {\n          // if there are two or more possible correct ways of parsing, throw an\n          // error.\n          // e.g.   Source: a ? (b): c => (d): e => f\n          //      Result 1: a ? b : (c => ((d): e => f))\n          //      Result 2: a ? ((b): c => d) : (e => f)\n          this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc);\n        }\n\n        if (failed && valid.length === 1) {\n          this.state = state;\n          noArrowAt.push(valid[0].start);\n          this.state.noArrowAt = noArrowAt;\n          ({ consequent, failed } = this.tryParseConditionalConsequent());\n        }\n      }\n\n      this.getArrowLikeExpressions(consequent, true);\n\n      this.state.noArrowAt = originalNoArrowAt;\n      this.expect(tt.colon);\n\n      node.test = expr;\n      node.consequent = consequent;\n      node.alternate = this.forwardNoArrowParamsConversionAt(node, () =>\n        this.parseMaybeAssign(undefined, undefined),\n      );\n\n      return this.finishNode(node, \"ConditionalExpression\");\n    }\n\n    tryParseConditionalConsequent(): {\n      consequent: N.Expression;\n      failed: boolean;\n    } {\n      this.state.noArrowParamsConversionAt.push(this.state.start);\n\n      const consequent = this.parseMaybeAssignAllowIn();\n      const failed = !this.match(tt.colon);\n\n      this.state.noArrowParamsConversionAt.pop();\n\n      return { consequent, failed };\n    }\n\n    // Given an expression, walks through out its arrow functions whose body is\n    // an expression and through out conditional expressions. It returns every\n    // function which has been parsed with a return type but could have been\n    // parenthesized expressions.\n    // These functions are separated into two arrays: one containing the ones\n    // whose parameters can be converted to assignable lists, one containing the\n    // others.\n    getArrowLikeExpressions(\n      node: N.Expression,\n      disallowInvalid?: boolean,\n    ): [N.ArrowFunctionExpression[], N.ArrowFunctionExpression[]] {\n      const stack = [node];\n      const arrows: N.ArrowFunctionExpression[] = [];\n\n      while (stack.length !== 0) {\n        const node = stack.pop();\n        if (\n          node.type === \"ArrowFunctionExpression\" &&\n          node.body.type !== \"BlockStatement\"\n        ) {\n          if (node.typeParameters || !node.returnType) {\n            // This is an arrow expression without ambiguity, so check its parameters\n            this.finishArrowValidation(node);\n          } else {\n            arrows.push(node);\n          }\n          stack.push(node.body);\n        } else if (node.type === \"ConditionalExpression\") {\n          stack.push(node.consequent);\n          stack.push(node.alternate);\n        }\n      }\n\n      if (disallowInvalid) {\n        arrows.forEach(node => this.finishArrowValidation(node));\n        return [arrows, []];\n      }\n\n      return partition(arrows, node =>\n        node.params.every(param => this.isAssignable(param, true)),\n      );\n    }\n\n    finishArrowValidation(node: N.ArrowFunctionExpression) {\n      this.toAssignableList(\n        // node.params is Expression[] instead of $ReadOnlyArray<Pattern> because it\n        // has not been converted yet.\n        node.params as any as N.Expression[],\n        node.extra?.trailingCommaLoc,\n        /* isLHS */ false,\n      );\n      // Enter scope, as checkParams defines bindings\n      this.scope.enter(ScopeFlag.FUNCTION | ScopeFlag.ARROW);\n      // Use super's method to force the parameters to be checked\n      super.checkParams(node, false, true);\n      this.scope.exit();\n    }\n\n    forwardNoArrowParamsConversionAt<T>(\n      node: Undone<N.Node>,\n      parse: () => T,\n    ): T {\n      let result: T;\n      if (\n        this.state.noArrowParamsConversionAt.includes(\n          this.offsetToSourcePos(node.start),\n        )\n      ) {\n        this.state.noArrowParamsConversionAt.push(this.state.start);\n        result = parse();\n        this.state.noArrowParamsConversionAt.pop();\n      } else {\n        result = parse();\n      }\n\n      return result;\n    }\n\n    parseParenItem<T extends N.Expression | N.RestElement | N.SpreadElement>(\n      node: T,\n      startLoc: Position,\n    ): T | N.TypeCastExpression | N.TsTypeCastExpression {\n      const newNode = super.parseParenItem(node, startLoc);\n      if (this.eat(tt.question)) {\n        (newNode as N.Identifier).optional = true;\n        // Include questionmark in location of node\n        // Don't use this.finishNode() as otherwise we might process comments twice and\n        // include already consumed parens\n        this.resetEndLocation(node);\n      }\n\n      if (this.match(tt.colon)) {\n        const typeCastNode = this.startNodeAt<N.TypeCastExpression>(startLoc);\n        typeCastNode.expression = newNode as N.Expression;\n        typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();\n\n        return this.finishNode(typeCastNode, \"TypeCastExpression\");\n      }\n\n      return newNode;\n    }\n\n    assertModuleNodeAllowed(node: N.Node) {\n      if (\n        (node.type === \"ImportDeclaration\" &&\n          (node.importKind === \"type\" || node.importKind === \"typeof\")) ||\n        (node.type === \"ExportNamedDeclaration\" &&\n          node.exportKind === \"type\") ||\n        (node.type === \"ExportAllDeclaration\" && node.exportKind === \"type\")\n      ) {\n        // Allow Flowtype imports and exports in all conditions because\n        // Flow itself does not care about 'sourceType'.\n        return;\n      }\n\n      super.assertModuleNodeAllowed(node);\n    }\n\n    parseExportDeclaration(\n      node: N.ExportNamedDeclaration,\n    ): N.Declaration | undefined | null {\n      if (this.isContextual(tt._type)) {\n        node.exportKind = \"type\";\n\n        const declarationNode = this.startNode();\n        this.next();\n\n        if (this.match(tt.braceL)) {\n          // export type { foo, bar };\n          node.specifiers = this.parseExportSpecifiers(\n            /* isInTypeExport */ true,\n          );\n          super.parseExportFrom(node);\n          return null;\n        } else {\n          // export type Foo = Bar;\n          // @ts-expect-error: refine typings\n          return this.flowParseTypeAlias(declarationNode);\n        }\n      } else if (this.isContextual(tt._opaque)) {\n        node.exportKind = \"type\";\n\n        const declarationNode = this.startNode();\n        this.next();\n        // export opaque type Foo = Bar;\n        // @ts-expect-error: refine typings\n        return this.flowParseOpaqueType(declarationNode, false);\n      } else if (this.isContextual(tt._interface)) {\n        node.exportKind = \"type\";\n        const declarationNode = this.startNode();\n        this.next();\n        // @ts-expect-error: refine typings\n        return this.flowParseInterface(declarationNode);\n      } else if (this.isContextual(tt._enum)) {\n        node.exportKind = \"value\";\n        const declarationNode = this.startNode();\n        this.next();\n        // @ts-expect-error: refine typings\n        return this.flowParseEnumDeclaration(declarationNode);\n      } else {\n        return super.parseExportDeclaration(node);\n      }\n    }\n\n    eatExportStar(\n      node: Undone<N.Node>,\n    ): node is Undone<N.ExportNamedDeclaration | N.ExportAllDeclaration> {\n      if (super.eatExportStar(node)) return true;\n\n      if (this.isContextual(tt._type) && this.lookahead().type === tt.star) {\n        (\n          node as Undone<N.ExportNamedDeclaration | N.ExportAllDeclaration>\n        ).exportKind = \"type\";\n        this.next();\n        this.next();\n        return true;\n      }\n\n      return false;\n    }\n\n    maybeParseExportNamespaceSpecifier(\n      node: Undone<N.ExportNamedDeclaration | N.ExportAllDeclaration>,\n    ): node is Undone<N.ExportNamedDeclaration> {\n      const { startLoc } = this.state;\n      const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);\n      if (hasNamespace && node.exportKind === \"type\") {\n        this.unexpected(startLoc);\n      }\n      return hasNamespace;\n    }\n\n    parseClassId(\n      node: N.Class,\n      isStatement: boolean,\n      optionalId?: boolean | null,\n    ) {\n      super.parseClassId(node, isStatement, optionalId);\n      if (this.match(tt.lt)) {\n        node.typeParameters = this.flowParseTypeParameterDeclaration();\n      }\n    }\n\n    parseClassMember(\n      classBody: N.ClassBody,\n      member: any,\n      state: N.ParseClassMemberState,\n    ): void {\n      const { startLoc } = this.state;\n      if (this.isContextual(tt._declare)) {\n        if (super.parseClassMemberFromModifier(classBody, member)) {\n          // 'declare' is a class element name\n          return;\n        }\n\n        member.declare = true;\n      }\n\n      super.parseClassMember(classBody, member, state);\n\n      if (member.declare) {\n        if (\n          member.type !== \"ClassProperty\" &&\n          member.type !== \"ClassPrivateProperty\" &&\n          member.type !== \"PropertyDefinition\" // Used by estree plugin\n        ) {\n          this.raise(FlowErrors.DeclareClassElement, startLoc);\n        } else if (member.value) {\n          this.raise(FlowErrors.DeclareClassFieldInitializer, member.value);\n        }\n      }\n    }\n\n    isIterator(word: string): boolean {\n      return word === \"iterator\" || word === \"asyncIterator\";\n    }\n\n    readIterator(): void {\n      const word = super.readWord1();\n      const fullWord = \"@@\" + word;\n\n      // Allow @@iterator and @@asyncIterator as a identifier only inside type\n      if (!this.isIterator(word) || !this.state.inType) {\n        this.raise(Errors.InvalidIdentifier, this.state.curPosition(), {\n          identifierName: fullWord,\n        });\n      }\n\n      this.finishToken(tt.name, fullWord);\n    }\n\n    // ensure that inside flow types, we bypass the jsx parser plugin\n    getTokenFromCode(code: number): void {\n      const next = this.input.charCodeAt(this.state.pos + 1);\n      if (code === charCodes.leftCurlyBrace && next === charCodes.verticalBar) {\n        this.finishOp(tt.braceBarL, 2);\n      } else if (\n        this.state.inType &&\n        (code === charCodes.greaterThan || code === charCodes.lessThan)\n      ) {\n        this.finishOp(code === charCodes.greaterThan ? tt.gt : tt.lt, 1);\n      } else if (this.state.inType && code === charCodes.questionMark) {\n        if (next === charCodes.dot) {\n          this.finishOp(tt.questionDot, 2);\n        } else {\n          // allow double nullable types in Flow: ??string\n          this.finishOp(tt.question, 1);\n        }\n      } else if (\n        isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))\n      ) {\n        this.state.pos += 2; // eat \"@@\"\n        this.readIterator();\n      } else {\n        super.getTokenFromCode(code);\n      }\n    }\n\n    isAssignable(node: N.Node, isBinding?: boolean): boolean {\n      if (node.type === \"TypeCastExpression\") {\n        return this.isAssignable(node.expression, isBinding);\n      } else {\n        return super.isAssignable(node, isBinding);\n      }\n    }\n\n    toAssignable(node: N.Node, isLHS: boolean = false): void {\n      if (\n        !isLHS &&\n        node.type === \"AssignmentExpression\" &&\n        node.left.type === \"TypeCastExpression\"\n      ) {\n        node.left = this.typeCastToParameter(node.left) as N.Assignable;\n      }\n      super.toAssignable(node, isLHS);\n    }\n\n    // turn type casts that we found in function parameter head into type annotated params\n    toAssignableList(\n      exprList: N.Expression[],\n      trailingCommaLoc: Position | undefined | null,\n      isLHS: boolean,\n    ): void {\n      for (let i = 0; i < exprList.length; i++) {\n        const expr = exprList[i];\n        if (expr?.type === \"TypeCastExpression\") {\n          exprList[i] = this.typeCastToParameter(expr);\n        }\n      }\n      super.toAssignableList(exprList, trailingCommaLoc, isLHS);\n    }\n\n    // this is a list of nodes, from something like a call expression, we need to filter the\n    // type casts that we've found that are illegal in this context\n    toReferencedList(\n      exprList:\n        | ReadonlyArray<N.Expression | N.SpreadElement>\n        | ReadonlyArray<N.Expression | N.RestElement>,\n      isParenthesizedExpr?: boolean,\n    ):\n      | ReadonlyArray<N.Expression | N.SpreadElement>\n      | ReadonlyArray<N.Expression | N.RestElement> {\n      for (let i = 0; i < exprList.length; i++) {\n        const expr = exprList[i];\n        if (\n          expr &&\n          expr.type === \"TypeCastExpression\" &&\n          !expr.extra?.parenthesized &&\n          (exprList.length > 1 || !isParenthesizedExpr)\n        ) {\n          this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation);\n        }\n      }\n\n      return exprList;\n    }\n\n    parseArrayLike(\n      close: TokenType,\n      canBePattern: boolean,\n      isTuple: boolean,\n      refExpressionErrors?: ExpressionErrors | null,\n    ): N.ArrayExpression | N.TupleExpression {\n      const node = super.parseArrayLike(\n        close,\n        canBePattern,\n        isTuple,\n        refExpressionErrors,\n      );\n\n      // This could be an array pattern:\n      //   ([a: string, b: string]) => {}\n      // In this case, we don't have to call toReferencedList. We will\n      // call it, if needed, when we are sure that it is a parenthesized\n      // expression by calling toReferencedListDeep.\n      if (canBePattern && !this.state.maybeInArrowParameters) {\n        this.toReferencedList(node.elements);\n      }\n\n      return node;\n    }\n\n    isValidLVal(type: string, isParenthesized: boolean, binding: BindingFlag) {\n      return (\n        type === \"TypeCastExpression\" ||\n        super.isValidLVal(type, isParenthesized, binding)\n      );\n    }\n\n    // parse class property type annotations\n    parseClassProperty(node: N.ClassProperty): N.ClassProperty {\n      if (this.match(tt.colon)) {\n        node.typeAnnotation = this.flowParseTypeAnnotation();\n      }\n      return super.parseClassProperty(node);\n    }\n\n    parseClassPrivateProperty(\n      node: N.ClassPrivateProperty,\n    ): N.ClassPrivateProperty {\n      if (this.match(tt.colon)) {\n        node.typeAnnotation = this.flowParseTypeAnnotation();\n      }\n      return super.parseClassPrivateProperty(node);\n    }\n\n    // determine whether or not we're currently in the position where a class method would appear\n    isClassMethod(): boolean {\n      return this.match(tt.lt) || super.isClassMethod();\n    }\n\n    // determine whether or not we're currently in the position where a class property would appear\n    isClassProperty(): boolean {\n      return this.match(tt.colon) || super.isClassProperty();\n    }\n\n    isNonstaticConstructor(method: N.ClassMethod | N.ClassProperty): boolean {\n      return !this.match(tt.colon) && super.isNonstaticConstructor(method);\n    }\n\n    // parse type parameters for class methods\n    pushClassMethod(\n      classBody: N.ClassBody,\n      method: N.ClassMethod,\n      isGenerator: boolean,\n      isAsync: boolean,\n      isConstructor: boolean,\n      allowsDirectSuper: boolean,\n    ): void {\n      if ((method as any).variance) {\n        this.unexpected((method as any).variance.loc.start);\n      }\n      delete (method as any).variance;\n      if (this.match(tt.lt)) {\n        method.typeParameters = this.flowParseTypeParameterDeclaration();\n      }\n\n      super.pushClassMethod(\n        classBody,\n        method,\n        isGenerator,\n        isAsync,\n        isConstructor,\n        allowsDirectSuper,\n      );\n\n      if (method.params && isConstructor) {\n        const params = method.params;\n        if (params.length > 0 && this.isThisParam(params[0])) {\n          this.raise(FlowErrors.ThisParamBannedInConstructor, method);\n        }\n        // estree support\n      } else if (\n        // @ts-expect-error TS does not know about the fact that estree can replace ClassMethod with MethodDefinition\n        method.type === \"MethodDefinition\" &&\n        isConstructor &&\n        // @ts-expect-error estree\n        method.value.params\n      ) {\n        // @ts-expect-error estree\n        const params = method.value.params;\n        if (params.length > 0 && this.isThisParam(params[0])) {\n          this.raise(FlowErrors.ThisParamBannedInConstructor, method);\n        }\n      }\n    }\n\n    pushClassPrivateMethod(\n      classBody: N.ClassBody,\n      method: N.ClassPrivateMethod,\n      isGenerator: boolean,\n      isAsync: boolean,\n    ): void {\n      if ((method as any).variance) {\n        this.unexpected((method as any).variance.loc.start);\n      }\n      delete (method as any).variance;\n      if (this.match(tt.lt)) {\n        method.typeParameters = this.flowParseTypeParameterDeclaration();\n      }\n\n      super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);\n    }\n\n    // parse a the super class type parameters and implements\n    parseClassSuper(node: N.Class): void {\n      super.parseClassSuper(node);\n      if (\n        node.superClass &&\n        (this.match(tt.lt) ||\n          // handles `class extends C<<T>`\n          this.match(tt.bitShiftL))\n      ) {\n        if (process.env.BABEL_8_BREAKING) {\n          node.superTypeArguments =\n            this.flowParseTypeParameterInstantiationInExpression();\n        } else {\n          node.superTypeParameters =\n            this.flowParseTypeParameterInstantiationInExpression();\n        }\n      }\n      if (this.isContextual(tt._implements)) {\n        this.next();\n        const implemented: N.FlowClassImplements[] = (node.implements = []);\n        do {\n          const node = this.startNode<N.FlowClassImplements>();\n          node.id = this.flowParseRestrictedIdentifier(/*liberal*/ true);\n          if (this.match(tt.lt)) {\n            node.typeParameters = this.flowParseTypeParameterInstantiation();\n          } else {\n            node.typeParameters = null;\n          }\n          implemented.push(this.finishNode(node, \"ClassImplements\"));\n        } while (this.eat(tt.comma));\n      }\n    }\n\n    checkGetterSetterParams(method: N.ObjectMethod | N.ClassMethod): void {\n      super.checkGetterSetterParams(method);\n      const params = this.getObjectOrClassMethodParams(method);\n      if (params.length > 0) {\n        const param = params[0];\n        if (this.isThisParam(param) && method.kind === \"get\") {\n          this.raise(FlowErrors.GetterMayNotHaveThisParam, param);\n        } else if (this.isThisParam(param)) {\n          this.raise(FlowErrors.SetterMayNotHaveThisParam, param);\n        }\n      }\n    }\n\n    parsePropertyNamePrefixOperator(\n      node: N.ObjectOrClassMember | N.ClassMember,\n    ): void {\n      node.variance = this.flowParseVariance();\n    }\n\n    // parse type parameters for object method shorthand\n    parseObjPropValue<T extends N.ObjectMember>(\n      prop: Undone<T>,\n      startLoc: Position | undefined | null,\n      isGenerator: boolean,\n      isAsync: boolean,\n      isPattern: boolean,\n      isAccessor: boolean,\n      refExpressionErrors?: ExpressionErrors | null,\n    ): T {\n      if ((prop as any).variance) {\n        this.unexpected((prop as any).variance.loc.start);\n      }\n      delete (prop as any).variance;\n\n      let typeParameters;\n\n      // method shorthand\n      if (this.match(tt.lt) && !isAccessor) {\n        typeParameters = this.flowParseTypeParameterDeclaration();\n        if (!this.match(tt.parenL)) this.unexpected();\n      }\n\n      const result = super.parseObjPropValue(\n        prop,\n        startLoc,\n        isGenerator,\n        isAsync,\n        isPattern,\n        isAccessor,\n        refExpressionErrors,\n      );\n\n      // add typeParameters if we found them\n      if (typeParameters) {\n        // @ts-expect-error: refine typings\n        (result.value || result).typeParameters = typeParameters;\n      }\n      return result;\n    }\n\n    parseFunctionParamType(param: N.Pattern): N.Pattern {\n      if (this.eat(tt.question)) {\n        if (param.type !== \"Identifier\") {\n          this.raise(FlowErrors.PatternIsOptional, param);\n        }\n        if (this.isThisParam(param)) {\n          this.raise(FlowErrors.ThisParamMayNotBeOptional, param);\n        }\n\n        (param as any as N.Identifier).optional = true;\n      }\n      if (this.match(tt.colon)) {\n        param.typeAnnotation = this.flowParseTypeAnnotation();\n      } else if (this.isThisParam(param)) {\n        this.raise(FlowErrors.ThisParamAnnotationRequired, param);\n      }\n\n      if (this.match(tt.eq) && this.isThisParam(param)) {\n        this.raise(FlowErrors.ThisParamNoDefault, param);\n      }\n\n      this.resetEndLocation(param);\n      return param;\n    }\n\n    parseMaybeDefault<P extends N.Pattern>(\n      startLoc?: Position | null,\n      left?: P | null,\n    ): P | N.AssignmentPattern {\n      const node = super.parseMaybeDefault(startLoc, left);\n\n      if (\n        node.type === \"AssignmentPattern\" &&\n        node.typeAnnotation &&\n        node.right.start < node.typeAnnotation.start\n      ) {\n        this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation);\n      }\n\n      return node;\n    }\n\n    checkImportReflection(node: Undone<N.ImportDeclaration>) {\n      super.checkImportReflection(node);\n      if (node.module && node.importKind !== \"value\") {\n        this.raise(\n          FlowErrors.ImportReflectionHasImportType,\n          node.specifiers[0].loc.start,\n        );\n      }\n    }\n\n    parseImportSpecifierLocal<\n      T extends\n        | N.ImportSpecifier\n        | N.ImportDefaultSpecifier\n        | N.ImportNamespaceSpecifier,\n    >(node: N.ImportDeclaration, specifier: Undone<T>, type: T[\"type\"]): void {\n      specifier.local = hasTypeImportKind(node)\n        ? this.flowParseRestrictedIdentifier(\n            /* liberal */ true,\n            /* declaration */ true,\n          )\n        : this.parseIdentifier();\n\n      node.specifiers.push(this.finishImportSpecifier(specifier, type));\n    }\n\n    isPotentialImportPhase(isExport: boolean): boolean {\n      if (super.isPotentialImportPhase(isExport)) return true;\n      if (this.isContextual(tt._type)) {\n        if (!isExport) return true;\n        const ch = this.lookaheadCharCode();\n        return ch === charCodes.leftCurlyBrace || ch === charCodes.asterisk;\n      }\n      return !isExport && this.isContextual(tt._typeof);\n    }\n\n    applyImportPhase(\n      node: Undone<N.ImportDeclaration | N.ExportNamedDeclaration>,\n      isExport: boolean,\n      phase: string | null,\n      loc?: Position,\n    ): void {\n      super.applyImportPhase(node, isExport, phase, loc);\n      if (isExport) {\n        if (!phase && this.match(tt._default)) {\n          // TODO: Align with our TS AST and always add .exportKind\n          return;\n        }\n        (node as N.ExportNamedDeclaration).exportKind =\n          phase === \"type\" ? phase : \"value\";\n      } else {\n        if (phase === \"type\" && this.match(tt.star)) this.unexpected();\n        (node as N.ImportDeclaration).importKind =\n          phase === \"type\" || phase === \"typeof\" ? phase : \"value\";\n      }\n    }\n\n    // parse import-type/typeof shorthand\n    parseImportSpecifier(\n      specifier: any,\n      importedIsString: boolean,\n      isInTypeOnlyImport: boolean,\n      // eslint-disable-next-line @typescript-eslint/no-unused-vars\n      isMaybeTypeOnly: boolean,\n      // eslint-disable-next-line @typescript-eslint/no-unused-vars\n      bindingType: BindingFlag | undefined,\n    ): N.ImportSpecifier {\n      const firstIdent = specifier.imported;\n\n      let specifierTypeKind = null;\n      if (firstIdent.type === \"Identifier\") {\n        if (firstIdent.name === \"type\") {\n          specifierTypeKind = \"type\";\n        } else if (firstIdent.name === \"typeof\") {\n          specifierTypeKind = \"typeof\";\n        }\n      }\n\n      let isBinding = false;\n      if (this.isContextual(tt._as) && !this.isLookaheadContextual(\"as\")) {\n        const as_ident = this.parseIdentifier(true);\n        if (\n          specifierTypeKind !== null &&\n          !tokenIsKeywordOrIdentifier(this.state.type)\n        ) {\n          // `import {type as ,` or `import {type as }`\n          specifier.imported = as_ident;\n          specifier.importKind = specifierTypeKind;\n          specifier.local = this.cloneIdentifier(as_ident);\n        } else {\n          // `import {type as foo`\n          specifier.imported = firstIdent;\n          specifier.importKind = null;\n          specifier.local = this.parseIdentifier();\n        }\n      } else {\n        if (\n          specifierTypeKind !== null &&\n          tokenIsKeywordOrIdentifier(this.state.type)\n        ) {\n          // `import {type foo`\n          specifier.imported = this.parseIdentifier(true);\n          specifier.importKind = specifierTypeKind;\n        } else {\n          if (importedIsString) {\n            /*:: invariant(firstIdent instanceof N.StringLiteral) */\n            throw this.raise(Errors.ImportBindingIsString, specifier, {\n              importName: firstIdent.value,\n            });\n          }\n          /*:: invariant(firstIdent instanceof N.Node) */\n          specifier.imported = firstIdent;\n          specifier.importKind = null;\n        }\n\n        if (this.eatContextual(tt._as)) {\n          specifier.local = this.parseIdentifier();\n        } else {\n          isBinding = true;\n          specifier.local = this.cloneIdentifier(specifier.imported);\n        }\n      }\n\n      const specifierIsTypeImport = hasTypeImportKind(specifier);\n\n      if (isInTypeOnlyImport && specifierIsTypeImport) {\n        this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier);\n      }\n\n      if (isInTypeOnlyImport || specifierIsTypeImport) {\n        this.checkReservedType(\n          specifier.local.name,\n          specifier.local.loc.start,\n          /* declaration */ true,\n        );\n      }\n\n      if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {\n        this.checkReservedWord(\n          specifier.local.name,\n          specifier.loc.start,\n          true,\n          true,\n        );\n      }\n\n      return this.finishImportSpecifier(specifier, \"ImportSpecifier\");\n    }\n\n    parseBindingAtom(): N.Pattern {\n      switch (this.state.type) {\n        case tt._this:\n          // \"this\" may be the name of a parameter, so allow it.\n          return this.parseIdentifier(/* liberal */ true);\n        default:\n          return super.parseBindingAtom();\n      }\n    }\n\n    // parse function type parameters - function foo<T>() {}\n    parseFunctionParams(\n      node: Undone<N.Function>,\n      isConstructor: boolean,\n    ): void {\n      // @ts-expect-error kind may not index node\n      const kind = node.kind;\n      if (kind !== \"get\" && kind !== \"set\" && this.match(tt.lt)) {\n        node.typeParameters = this.flowParseTypeParameterDeclaration();\n      }\n      super.parseFunctionParams(node, isConstructor);\n    }\n\n    // parse flow type annotations on variable declarator heads - let foo: string = bar\n    parseVarId(\n      decl: N.VariableDeclarator,\n      kind: \"var\" | \"let\" | \"const\" | \"using\" | \"await using\",\n    ): void {\n      super.parseVarId(decl, kind);\n      if (this.match(tt.colon)) {\n        decl.id.typeAnnotation = this.flowParseTypeAnnotation();\n        this.resetEndLocation(decl.id); // set end position to end of type\n      }\n    }\n\n    // parse the return type of an async arrow function - let foo = (async (): number => {});\n    parseAsyncArrowFromCallExpression(\n      node: N.ArrowFunctionExpression,\n      call: N.CallExpression,\n    ): N.ArrowFunctionExpression {\n      if (this.match(tt.colon)) {\n        const oldNoAnonFunctionType = this.state.noAnonFunctionType;\n        this.state.noAnonFunctionType = true;\n        node.returnType = this.flowParseTypeAnnotation();\n        this.state.noAnonFunctionType = oldNoAnonFunctionType;\n      }\n\n      return super.parseAsyncArrowFromCallExpression(node, call);\n    }\n\n    // todo description\n    shouldParseAsyncArrow(): boolean {\n      return this.match(tt.colon) || super.shouldParseAsyncArrow();\n    }\n\n    // We need to support type parameter declarations for arrow functions. This\n    // is tricky. There are three situations we need to handle\n    //\n    // 1. This is either JSX or an arrow function. We'll try JSX first. If that\n    //    fails, we'll try an arrow function. If that fails, we'll throw the JSX\n    //    error.\n    // 2. This is an arrow function. We'll parse the type parameter declaration,\n    //    parse the rest, make sure the rest is an arrow function, and go from\n    //    there\n    // 3. This is neither. Just call the super method\n    parseMaybeAssign(\n      refExpressionErrors?: ExpressionErrors | null,\n      afterLeftParse?: Function,\n    ): N.Expression {\n      let state = null;\n\n      let jsx;\n\n      if (\n        this.hasPlugin(\"jsx\") &&\n        (this.match(tt.jsxTagStart) || this.match(tt.lt))\n      ) {\n        state = this.state.clone();\n\n        jsx = this.tryParse(\n          () => super.parseMaybeAssign(refExpressionErrors, afterLeftParse),\n          state,\n        );\n\n        /*:: invariant(!jsx.aborted) */\n        /*:: invariant(jsx.node != null) */\n        if (!jsx.error) return jsx.node;\n\n        // Remove `tc.j_expr` and `tc.j_oTag` from context added\n        // by parsing `jsxTagStart` to stop the JSX plugin from\n        // messing with the tokens\n        const { context } = this.state;\n        const currentContext = context[context.length - 1];\n        if (currentContext === tc.j_oTag || currentContext === tc.j_expr) {\n          context.pop();\n        }\n      }\n\n      if (jsx?.error || this.match(tt.lt)) {\n        state = state || this.state.clone();\n\n        let typeParameters: N.TypeParameterDeclaration;\n\n        const arrow = this.tryParse((abort: () => never) => {\n          typeParameters = this.flowParseTypeParameterDeclaration();\n\n          const arrowExpression = this.forwardNoArrowParamsConversionAt(\n            typeParameters,\n            () => {\n              const result = super.parseMaybeAssign(\n                refExpressionErrors,\n                afterLeftParse,\n              );\n\n              this.resetStartLocationFromNode(result, typeParameters);\n\n              return result;\n            },\n          );\n\n          // <T>(() => {});\n          // <T>(() => {}: any);\n          if (arrowExpression.extra?.parenthesized) abort();\n\n          // The above can return a TypeCastExpression when the arrow\n          // expression is not wrapped in parens. See also `this.parseParenItem`.\n          // (<T>() => {}: any);\n          const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);\n\n          if (expr.type !== \"ArrowFunctionExpression\") abort();\n\n          expr.typeParameters = typeParameters;\n          this.resetStartLocationFromNode(expr, typeParameters);\n\n          return arrowExpression;\n        }, state);\n\n        let arrowExpression:\n          | N.ArrowFunctionExpression\n          | N.TypeCastExpression\n          | undefined\n          | null = null;\n\n        if (\n          arrow.node &&\n          this.maybeUnwrapTypeCastExpression(arrow.node).type ===\n            \"ArrowFunctionExpression\"\n        ) {\n          if (!arrow.error && !arrow.aborted) {\n            // <T> async () => {}\n            // @ts-expect-error: refine tryParse typings\n            if (arrow.node.async) {\n              /*:: invariant(typeParameters) */\n              this.raise(\n                FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction,\n                typeParameters,\n              );\n            }\n            return arrow.node;\n          }\n\n          // @ts-expect-error: refine typings\n          arrowExpression = arrow.node;\n        }\n\n        // If we are here, both JSX and Flow parsing attempts failed.\n        // Give the precedence to the JSX error, except if JSX had an\n        // unrecoverable error while Flow didn't.\n        // If the error is recoverable, we can only re-report it if there is\n        // a node we can return.\n\n        if (jsx?.node) {\n          /*:: invariant(jsx.failState) */\n          this.state = jsx.failState;\n          return jsx.node;\n        }\n\n        if (arrowExpression) {\n          /*:: invariant(arrow.failState) */\n          this.state = arrow.failState;\n          return arrowExpression;\n        }\n\n        if (jsx?.thrown) throw jsx.error;\n        if (arrow.thrown) throw arrow.error;\n\n        /*:: invariant(typeParameters) */\n        throw this.raise(\n          FlowErrors.UnexpectedTokenAfterTypeParameter,\n          typeParameters,\n        );\n      }\n\n      return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);\n    }\n\n    // handle return types for arrow functions\n    parseArrow(\n      node: Undone<N.ArrowFunctionExpression>,\n    ): Undone<N.ArrowFunctionExpression> | undefined | null {\n      if (this.match(tt.colon)) {\n        // @ts-expect-error todo(flow->ts)\n        const result = this.tryParse<N.TypeAnnotation>(() => {\n          const oldNoAnonFunctionType = this.state.noAnonFunctionType;\n          this.state.noAnonFunctionType = true;\n\n          const typeNode = this.startNode<N.TypeAnnotation>();\n\n          [\n            typeNode.typeAnnotation,\n            // @ts-expect-error (destructuring not supported yet)\n            node.predicate,\n          ] = this.flowParseTypeAndPredicateInitialiser();\n\n          this.state.noAnonFunctionType = oldNoAnonFunctionType;\n\n          if (this.canInsertSemicolon()) this.unexpected();\n          if (!this.match(tt.arrow)) this.unexpected();\n\n          return typeNode;\n        });\n\n        if (result.thrown) return null;\n        /*:: invariant(result.node) */\n\n        if (result.error) this.state = result.failState;\n\n        // assign after it is clear it is an arrow\n        // @ts-expect-error todo(flow->ts)\n        node.returnType = result.node.typeAnnotation\n          ? this.finishNode(result.node, \"TypeAnnotation\")\n          : null;\n      }\n\n      return super.parseArrow(node);\n    }\n\n    shouldParseArrow(params: Array<N.Node>): boolean {\n      return this.match(tt.colon) || super.shouldParseArrow(params);\n    }\n\n    setArrowFunctionParameters(\n      node: Undone<N.ArrowFunctionExpression>,\n      params:\n        | Array<N.Expression | N.SpreadElement>\n        | Array<N.Expression | N.RestElement>,\n    ): void {\n      if (\n        this.state.noArrowParamsConversionAt.includes(\n          this.offsetToSourcePos(node.start),\n        )\n      ) {\n        node.params = params as N.ArrowFunctionExpression[\"params\"];\n      } else {\n        super.setArrowFunctionParameters(node, params);\n      }\n    }\n\n    checkParams(\n      node: N.Function,\n      allowDuplicates: boolean,\n      isArrowFunction?: boolean | null,\n      strictModeChanged: boolean = true,\n    ): void {\n      if (\n        isArrowFunction &&\n        this.state.noArrowParamsConversionAt.includes(\n          this.offsetToSourcePos(node.start),\n        )\n      ) {\n        return;\n      }\n\n      // ensure the `this` param is first, if it exists\n      for (let i = 0; i < node.params.length; i++) {\n        if (this.isThisParam(node.params[i]) && i > 0) {\n          this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]);\n        }\n      }\n\n      super.checkParams(\n        node,\n        allowDuplicates,\n        isArrowFunction,\n        strictModeChanged,\n      );\n    }\n\n    parseParenAndDistinguishExpression(canBeArrow: boolean): N.Expression {\n      return super.parseParenAndDistinguishExpression(\n        canBeArrow &&\n          !this.state.noArrowAt.includes(\n            this.sourceToOffsetPos(this.state.start),\n          ),\n      );\n    }\n\n    parseSubscripts(\n      base: N.Expression,\n      startLoc: Position,\n      noCalls?: boolean | null,\n    ): N.Expression {\n      if (\n        base.type === \"Identifier\" &&\n        base.name === \"async\" &&\n        this.state.noArrowAt.includes(startLoc.index)\n      ) {\n        this.next();\n\n        const node = this.startNodeAt<N.CallExpression>(startLoc);\n        node.callee = base;\n        node.arguments = super.parseCallExpressionArguments();\n        base = this.finishNode(node, \"CallExpression\");\n      } else if (\n        base.type === \"Identifier\" &&\n        base.name === \"async\" &&\n        this.match(tt.lt)\n      ) {\n        const state = this.state.clone();\n        const arrow = this.tryParse(\n          abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(),\n          state,\n        );\n\n        /*:: invariant(arrow.node != null) */\n        // @ts-expect-error: refine tryParse typings\n        if (!arrow.error && !arrow.aborted) return arrow.node;\n\n        const result = this.tryParse(\n          () => super.parseSubscripts(base, startLoc, noCalls),\n          state,\n        );\n\n        if (result.node && !result.error) return result.node;\n\n        if (arrow.node) {\n          this.state = arrow.failState;\n          // @ts-expect-error: refine tryParse typings\n          return arrow.node;\n        }\n\n        if (result.node) {\n          this.state = result.failState;\n          return result.node;\n        }\n\n        throw arrow.error || result.error;\n      }\n\n      return super.parseSubscripts(base, startLoc, noCalls);\n    }\n\n    parseSubscript(\n      base: N.Expression,\n\n      startLoc: Position,\n      noCalls: boolean | undefined | null,\n      subscriptState: N.ParseSubscriptState,\n    ): N.Expression {\n      if (this.match(tt.questionDot) && this.isLookaheadToken_lt()) {\n        subscriptState.optionalChainMember = true;\n        if (noCalls) {\n          subscriptState.stop = true;\n          return base;\n        }\n        this.next();\n        const node = this.startNodeAt<N.OptionalCallExpression>(startLoc);\n        node.callee = base;\n        node.typeArguments =\n          this.flowParseTypeParameterInstantiationInExpression();\n        this.expect(tt.parenL);\n        node.arguments = this.parseCallExpressionArguments();\n        node.optional = true;\n        return this.finishCallExpression(node, /* optional */ true);\n      } else if (\n        !noCalls &&\n        this.shouldParseTypes() &&\n        (this.match(tt.lt) ||\n          // also handles `new C<<T>`\n          this.match(tt.bitShiftL))\n      ) {\n        const node = this.startNodeAt<\n          N.OptionalCallExpression | N.CallExpression\n        >(startLoc);\n        node.callee = base;\n\n        const result = this.tryParse(() => {\n          node.typeArguments =\n            this.flowParseTypeParameterInstantiationCallOrNew();\n          this.expect(tt.parenL);\n          node.arguments = super.parseCallExpressionArguments();\n          if (subscriptState.optionalChainMember) {\n            (node as Undone<N.OptionalCallExpression>).optional = false;\n          }\n          return this.finishCallExpression(\n            node,\n            subscriptState.optionalChainMember,\n          );\n        });\n\n        if (result.node) {\n          if (result.error) this.state = result.failState;\n          return result.node;\n        }\n      }\n\n      return super.parseSubscript(\n        base,\n\n        startLoc,\n        noCalls,\n        subscriptState,\n      );\n    }\n\n    parseNewCallee(node: N.NewExpression): void {\n      super.parseNewCallee(node);\n\n      let targs = null;\n      if (this.shouldParseTypes() && this.match(tt.lt)) {\n        targs = this.tryParse(() =>\n          this.flowParseTypeParameterInstantiationCallOrNew(),\n        ).node;\n      }\n      node.typeArguments = targs;\n    }\n\n    parseAsyncArrowWithTypeParameters(\n      startLoc: Position,\n    ): N.ArrowFunctionExpression | undefined | null {\n      const node = this.startNodeAt<N.ArrowFunctionExpression>(startLoc);\n      this.parseFunctionParams(node, false);\n      if (!this.parseArrow(node)) return;\n      return super.parseArrowExpression(\n        node,\n        /* params */ undefined,\n        /* isAsync */ true,\n      );\n    }\n\n    readToken_mult_modulo(code: number): void {\n      const next = this.input.charCodeAt(this.state.pos + 1);\n      if (\n        code === charCodes.asterisk &&\n        next === charCodes.slash &&\n        this.state.hasFlowComment\n      ) {\n        this.state.hasFlowComment = false;\n        this.state.pos += 2;\n        this.nextToken();\n        return;\n      }\n\n      super.readToken_mult_modulo(code);\n    }\n\n    readToken_pipe_amp(code: number): void {\n      const next = this.input.charCodeAt(this.state.pos + 1);\n      if (\n        code === charCodes.verticalBar &&\n        next === charCodes.rightCurlyBrace\n      ) {\n        // '|}'\n        this.finishOp(tt.braceBarR, 2);\n        return;\n      }\n\n      super.readToken_pipe_amp(code);\n    }\n\n    parseTopLevel(file: N.File, program: N.Program): N.File {\n      const fileNode = super.parseTopLevel(file, program);\n      if (this.state.hasFlowComment) {\n        this.raise(\n          FlowErrors.UnterminatedFlowComment,\n          this.state.curPosition(),\n        );\n      }\n      return fileNode;\n    }\n\n    skipBlockComment(): N.CommentBlock | undefined {\n      if (this.hasPlugin(\"flowComments\") && this.skipFlowComment()) {\n        if (this.state.hasFlowComment) {\n          throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc);\n        }\n        this.hasFlowCommentCompletion();\n        const commentSkip = this.skipFlowComment();\n        if (commentSkip) {\n          this.state.pos += commentSkip;\n          this.state.hasFlowComment = true;\n        }\n        return;\n      }\n\n      return super.skipBlockComment(this.state.hasFlowComment ? \"*-/\" : \"*/\");\n    }\n\n    skipFlowComment(): number | false {\n      const { pos } = this.state;\n      let shiftToFirstNonWhiteSpace = 2;\n      while (\n        [charCodes.space, charCodes.tab].includes(\n          // @ts-expect-error testing whether a number is included\n          this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace),\n        )\n      ) {\n        shiftToFirstNonWhiteSpace++;\n      }\n\n      const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);\n      const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);\n\n      if (ch2 === charCodes.colon && ch3 === charCodes.colon) {\n        return shiftToFirstNonWhiteSpace + 2; // check for /*::\n      }\n      if (\n        this.input.slice(\n          shiftToFirstNonWhiteSpace + pos,\n          shiftToFirstNonWhiteSpace + pos + 12,\n        ) === \"flow-include\"\n      ) {\n        return shiftToFirstNonWhiteSpace + 12; // check for /*flow-include\n      }\n      if (ch2 === charCodes.colon && ch3 !== charCodes.colon) {\n        return shiftToFirstNonWhiteSpace; // check for /*:, advance up to :\n      }\n      return false;\n    }\n\n    hasFlowCommentCompletion(): void {\n      const end = this.input.indexOf(\"*/\", this.state.pos);\n      if (end === -1) {\n        throw this.raise(Errors.UnterminatedComment, this.state.curPosition());\n      }\n    }\n\n    // Flow enum parsing\n\n    flowEnumErrorBooleanMemberNotInitialized(\n      loc: Position,\n      {\n        enumName,\n        memberName,\n      }: {\n        enumName: string;\n        memberName: string;\n      },\n    ): void {\n      this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, {\n        memberName,\n        enumName,\n      });\n    }\n\n    flowEnumErrorInvalidMemberInitializer(\n      loc: Position,\n      enumContext: EnumContext,\n    ) {\n      return this.raise(\n        !enumContext.explicitType\n          ? FlowErrors.EnumInvalidMemberInitializerUnknownType\n          : enumContext.explicitType === \"symbol\"\n            ? FlowErrors.EnumInvalidMemberInitializerSymbolType\n            : FlowErrors.EnumInvalidMemberInitializerPrimaryType,\n        loc,\n        enumContext,\n      );\n    }\n\n    flowEnumErrorNumberMemberNotInitialized(\n      loc: Position,\n      details: {\n        enumName: string;\n        memberName: string;\n      },\n    ): void {\n      this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details);\n    }\n\n    flowEnumErrorStringMemberInconsistentlyInitialized(\n      node: N.Node,\n      details: {\n        enumName: string;\n      },\n    ): void {\n      this.raise(\n        FlowErrors.EnumStringMemberInconsistentlyInitialized,\n        node,\n        details,\n      );\n    }\n\n    flowEnumMemberInit(): EnumMemberInit {\n      const startLoc = this.state.startLoc;\n      const endOfInit = () => this.match(tt.comma) || this.match(tt.braceR);\n      switch (this.state.type) {\n        case tt.num: {\n          const literal = this.parseNumericLiteral(this.state.value);\n          if (endOfInit()) {\n            return { type: \"number\", loc: literal.loc.start, value: literal };\n          }\n          return { type: \"invalid\", loc: startLoc };\n        }\n        case tt.string: {\n          const literal = this.parseStringLiteral(this.state.value);\n          if (endOfInit()) {\n            return { type: \"string\", loc: literal.loc.start, value: literal };\n          }\n          return { type: \"invalid\", loc: startLoc };\n        }\n        case tt._true:\n        case tt._false: {\n          const literal = this.parseBooleanLiteral(this.match(tt._true));\n          if (endOfInit()) {\n            return {\n              type: \"boolean\",\n              loc: literal.loc.start,\n              value: literal,\n            };\n          }\n          return { type: \"invalid\", loc: startLoc };\n        }\n        default:\n          return { type: \"invalid\", loc: startLoc };\n      }\n    }\n\n    flowEnumMemberRaw(): {\n      id: N.Identifier;\n      init: EnumMemberInit;\n    } {\n      const loc = this.state.startLoc;\n      const id = this.parseIdentifier(true);\n      const init = this.eat(tt.eq)\n        ? this.flowEnumMemberInit()\n        : { type: \"none\" as const, loc };\n      return { id, init };\n    }\n\n    flowEnumCheckExplicitTypeMismatch(\n      loc: Position,\n      context: EnumContext,\n      expectedType: EnumExplicitType,\n    ): void {\n      const { explicitType } = context;\n      if (explicitType === null) {\n        return;\n      }\n      if (explicitType !== expectedType) {\n        this.flowEnumErrorInvalidMemberInitializer(loc, context);\n      }\n    }\n\n    flowEnumMembers({\n      enumName,\n      explicitType,\n    }: {\n      enumName: string;\n      explicitType: EnumExplicitType;\n    }): {\n      members: {\n        booleanMembers: Extract<\n          N.FlowEnumMember,\n          { type: \"EnumBooleanMember\" }\n        >[];\n        numberMembers: Extract<\n          N.FlowEnumMember,\n          { type: \"EnumNumberMember\" }\n        >[];\n        stringMembers: Extract<\n          N.FlowEnumMember,\n          { type: \"EnumStringMember\" }\n        >[];\n        defaultedMembers: Extract<\n          N.FlowEnumMember,\n          { type: \"EnumDefaultedMember\" }\n        >[];\n      };\n      hasUnknownMembers: boolean;\n    } {\n      const seenNames = new Set();\n      const members = {\n        // @ts-expect-error: migrate to Babel types\n        booleanMembers: [],\n        // @ts-expect-error: migrate to Babel types\n        numberMembers: [],\n        // @ts-expect-error: migrate to Babel types\n        stringMembers: [],\n        // @ts-expect-error: migrate to Babel types\n        defaultedMembers: [],\n      };\n      let hasUnknownMembers = false;\n      while (!this.match(tt.braceR)) {\n        if (this.eat(tt.ellipsis)) {\n          hasUnknownMembers = true;\n          break;\n        }\n        const memberNode = this.startNode<N.FlowEnumMember>();\n        const { id, init } = this.flowEnumMemberRaw();\n        const memberName = id.name;\n        if (memberName === \"\") {\n          continue;\n        }\n        if (/^[a-z]/.test(memberName)) {\n          this.raise(FlowErrors.EnumInvalidMemberName, id, {\n            memberName,\n            suggestion: memberName[0].toUpperCase() + memberName.slice(1),\n            enumName,\n          });\n        }\n        if (seenNames.has(memberName)) {\n          this.raise(FlowErrors.EnumDuplicateMemberName, id, {\n            memberName,\n            enumName,\n          });\n        }\n        seenNames.add(memberName);\n        const context = { enumName, explicitType, memberName };\n        memberNode.id = id;\n        switch (init.type) {\n          case \"boolean\": {\n            this.flowEnumCheckExplicitTypeMismatch(\n              init.loc,\n              context,\n              \"boolean\",\n            );\n            memberNode.init = init.value;\n            members.booleanMembers.push(\n              this.finishNode(memberNode, \"EnumBooleanMember\"),\n            );\n            break;\n          }\n          case \"number\": {\n            this.flowEnumCheckExplicitTypeMismatch(init.loc, context, \"number\");\n            memberNode.init = init.value;\n            members.numberMembers.push(\n              this.finishNode(memberNode, \"EnumNumberMember\"),\n            );\n            break;\n          }\n          case \"string\": {\n            this.flowEnumCheckExplicitTypeMismatch(init.loc, context, \"string\");\n            memberNode.init = init.value;\n            members.stringMembers.push(\n              this.finishNode(memberNode, \"EnumStringMember\"),\n            );\n            break;\n          }\n          case \"invalid\": {\n            throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context);\n          }\n          case \"none\": {\n            switch (explicitType) {\n              case \"boolean\":\n                this.flowEnumErrorBooleanMemberNotInitialized(\n                  init.loc,\n                  context,\n                );\n                break;\n              case \"number\":\n                this.flowEnumErrorNumberMemberNotInitialized(init.loc, context);\n                break;\n              default:\n                members.defaultedMembers.push(\n                  this.finishNode(memberNode, \"EnumDefaultedMember\"),\n                );\n            }\n          }\n        }\n\n        if (!this.match(tt.braceR)) {\n          this.expect(tt.comma);\n        }\n      }\n      return { members, hasUnknownMembers };\n    }\n\n    flowEnumStringMembers(\n      initializedMembers: Array<N.Node>,\n      defaultedMembers: Array<N.Node>,\n      {\n        enumName,\n      }: {\n        enumName: string;\n      },\n    ): Array<N.Node> {\n      if (initializedMembers.length === 0) {\n        return defaultedMembers;\n      } else if (defaultedMembers.length === 0) {\n        return initializedMembers;\n      } else if (defaultedMembers.length > initializedMembers.length) {\n        for (const member of initializedMembers) {\n          this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {\n            enumName,\n          });\n        }\n        return defaultedMembers;\n      } else {\n        for (const member of defaultedMembers) {\n          this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {\n            enumName,\n          });\n        }\n        return initializedMembers;\n      }\n    }\n\n    flowEnumParseExplicitType({\n      enumName,\n    }: {\n      enumName: string;\n    }): EnumExplicitType {\n      if (!this.eatContextual(tt._of)) return null;\n\n      if (!tokenIsIdentifier(this.state.type)) {\n        throw this.raise(\n          FlowErrors.EnumInvalidExplicitTypeUnknownSupplied,\n          this.state.startLoc,\n          {\n            enumName,\n          },\n        );\n      }\n\n      const { value } = this.state;\n      this.next();\n\n      if (\n        value !== \"boolean\" &&\n        value !== \"number\" &&\n        value !== \"string\" &&\n        value !== \"symbol\"\n      ) {\n        this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, {\n          enumName,\n          invalidEnumType: value,\n        });\n      }\n\n      return value;\n    }\n\n    flowEnumBody(node: Undone<N.FlowEnumBody>, id: N.Identifier): N.Node {\n      const enumName = id.name;\n      const nameLoc = id.loc.start;\n      const explicitType = this.flowEnumParseExplicitType({ enumName });\n      this.expect(tt.braceL);\n      const { members, hasUnknownMembers } = this.flowEnumMembers({\n        enumName,\n        explicitType,\n      });\n      node.hasUnknownMembers = hasUnknownMembers;\n\n      switch (explicitType) {\n        case \"boolean\":\n          node.explicitType = true;\n          node.members = members.booleanMembers;\n          this.expect(tt.braceR);\n          return this.finishNode(node, \"EnumBooleanBody\");\n        case \"number\":\n          node.explicitType = true;\n          node.members = members.numberMembers;\n          this.expect(tt.braceR);\n          return this.finishNode(node, \"EnumNumberBody\");\n        case \"string\":\n          node.explicitType = true;\n          node.members = this.flowEnumStringMembers(\n            members.stringMembers,\n            members.defaultedMembers,\n            { enumName },\n          );\n          this.expect(tt.braceR);\n          return this.finishNode(node, \"EnumStringBody\");\n        case \"symbol\":\n          node.members = members.defaultedMembers;\n          this.expect(tt.braceR);\n          return this.finishNode(node, \"EnumSymbolBody\");\n        default: {\n          // `explicitType` is `null`\n          const empty = () => {\n            node.members = [];\n            this.expect(tt.braceR);\n            return this.finishNode(node, \"EnumStringBody\");\n          };\n          node.explicitType = false;\n\n          const boolsLen = members.booleanMembers.length;\n          const numsLen = members.numberMembers.length;\n          const strsLen = members.stringMembers.length;\n          const defaultedLen = members.defaultedMembers.length;\n\n          if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {\n            return empty();\n          } else if (!boolsLen && !numsLen) {\n            node.members = this.flowEnumStringMembers(\n              members.stringMembers,\n              members.defaultedMembers,\n              { enumName },\n            );\n            this.expect(tt.braceR);\n            return this.finishNode(node, \"EnumStringBody\");\n          } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {\n            for (const member of members.defaultedMembers) {\n              this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, {\n                enumName,\n                memberName: member.id.name,\n              });\n            }\n            node.members = members.booleanMembers;\n            this.expect(tt.braceR);\n            return this.finishNode(node, \"EnumBooleanBody\");\n          } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {\n            for (const member of members.defaultedMembers) {\n              this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, {\n                enumName,\n                memberName: member.id.name,\n              });\n            }\n            node.members = members.numberMembers;\n            this.expect(tt.braceR);\n            return this.finishNode(node, \"EnumNumberBody\");\n          } else {\n            this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, {\n              enumName,\n            });\n            return empty();\n          }\n        }\n      }\n    }\n\n    flowParseEnumDeclaration(\n      node: Undone<N.FlowEnumDeclaration>,\n    ): N.FlowEnumDeclaration {\n      const id = this.parseIdentifier();\n      node.id = id;\n      node.body = this.flowEnumBody(this.startNode(), id);\n      return this.finishNode(node, \"EnumDeclaration\");\n    }\n\n    jsxParseOpeningElementAfterName(\n      node: N.JSXOpeningElement,\n    ): N.JSXOpeningElement {\n      if (this.shouldParseTypes()) {\n        if (this.match(tt.lt) || this.match(tt.bitShiftL)) {\n          node.typeArguments =\n            this.flowParseTypeParameterInstantiationInExpression();\n        }\n      }\n\n      return super.jsxParseOpeningElementAfterName(node);\n    }\n\n    // check if the next token is a tt.lt\n    isLookaheadToken_lt(): boolean {\n      const next = this.nextTokenStart();\n      if (this.input.charCodeAt(next) === charCodes.lessThan) {\n        const afterNext = this.input.charCodeAt(next + 1);\n        return (\n          afterNext !== charCodes.lessThan && afterNext !== charCodes.equalsTo\n        );\n      }\n      return false;\n    }\n\n    // used after we have finished parsing types\n    reScan_lt_gt() {\n      const { type } = this.state;\n      if (type === tt.lt) {\n        this.state.pos -= 1;\n        this.readToken_lt();\n      } else if (type === tt.gt) {\n        this.state.pos -= 1;\n        this.readToken_gt();\n      }\n    }\n\n    reScan_lt() {\n      const { type } = this.state;\n      if (type === tt.bitShiftL) {\n        this.state.pos -= 2;\n        this.finishOp(tt.lt, 1);\n        return tt.lt;\n      }\n      return type;\n    }\n\n    maybeUnwrapTypeCastExpression(node: N.Node) {\n      return node.type === \"TypeCastExpression\" ? node.expression : node;\n    }\n  };\n","const entities: { [name: string]: string } = {\n  __proto__: null,\n  quot: \"\\u0022\",\n  amp: \"&\",\n  apos: \"\\u0027\",\n  lt: \"<\",\n  gt: \">\",\n  nbsp: \"\\u00A0\",\n  iexcl: \"\\u00A1\",\n  cent: \"\\u00A2\",\n  pound: \"\\u00A3\",\n  curren: \"\\u00A4\",\n  yen: \"\\u00A5\",\n  brvbar: \"\\u00A6\",\n  sect: \"\\u00A7\",\n  uml: \"\\u00A8\",\n  copy: \"\\u00A9\",\n  ordf: \"\\u00AA\",\n  laquo: \"\\u00AB\",\n  not: \"\\u00AC\",\n  shy: \"\\u00AD\",\n  reg: \"\\u00AE\",\n  macr: \"\\u00AF\",\n  deg: \"\\u00B0\",\n  plusmn: \"\\u00B1\",\n  sup2: \"\\u00B2\",\n  sup3: \"\\u00B3\",\n  acute: \"\\u00B4\",\n  micro: \"\\u00B5\",\n  para: \"\\u00B6\",\n  middot: \"\\u00B7\",\n  cedil: \"\\u00B8\",\n  sup1: \"\\u00B9\",\n  ordm: \"\\u00BA\",\n  raquo: \"\\u00BB\",\n  frac14: \"\\u00BC\",\n  frac12: \"\\u00BD\",\n  frac34: \"\\u00BE\",\n  iquest: \"\\u00BF\",\n  Agrave: \"\\u00C0\",\n  Aacute: \"\\u00C1\",\n  Acirc: \"\\u00C2\",\n  Atilde: \"\\u00C3\",\n  Auml: \"\\u00C4\",\n  Aring: \"\\u00C5\",\n  AElig: \"\\u00C6\",\n  Ccedil: \"\\u00C7\",\n  Egrave: \"\\u00C8\",\n  Eacute: \"\\u00C9\",\n  Ecirc: \"\\u00CA\",\n  Euml: \"\\u00CB\",\n  Igrave: \"\\u00CC\",\n  Iacute: \"\\u00CD\",\n  Icirc: \"\\u00CE\",\n  Iuml: \"\\u00CF\",\n  ETH: \"\\u00D0\",\n  Ntilde: \"\\u00D1\",\n  Ograve: \"\\u00D2\",\n  Oacute: \"\\u00D3\",\n  Ocirc: \"\\u00D4\",\n  Otilde: \"\\u00D5\",\n  Ouml: \"\\u00D6\",\n  times: \"\\u00D7\",\n  Oslash: \"\\u00D8\",\n  Ugrave: \"\\u00D9\",\n  Uacute: \"\\u00DA\",\n  Ucirc: \"\\u00DB\",\n  Uuml: \"\\u00DC\",\n  Yacute: \"\\u00DD\",\n  THORN: \"\\u00DE\",\n  szlig: \"\\u00DF\",\n  agrave: \"\\u00E0\",\n  aacute: \"\\u00E1\",\n  acirc: \"\\u00E2\",\n  atilde: \"\\u00E3\",\n  auml: \"\\u00E4\",\n  aring: \"\\u00E5\",\n  aelig: \"\\u00E6\",\n  ccedil: \"\\u00E7\",\n  egrave: \"\\u00E8\",\n  eacute: \"\\u00E9\",\n  ecirc: \"\\u00EA\",\n  euml: \"\\u00EB\",\n  igrave: \"\\u00EC\",\n  iacute: \"\\u00ED\",\n  icirc: \"\\u00EE\",\n  iuml: \"\\u00EF\",\n  eth: \"\\u00F0\",\n  ntilde: \"\\u00F1\",\n  ograve: \"\\u00F2\",\n  oacute: \"\\u00F3\",\n  ocirc: \"\\u00F4\",\n  otilde: \"\\u00F5\",\n  ouml: \"\\u00F6\",\n  divide: \"\\u00F7\",\n  oslash: \"\\u00F8\",\n  ugrave: \"\\u00F9\",\n  uacute: \"\\u00FA\",\n  ucirc: \"\\u00FB\",\n  uuml: \"\\u00FC\",\n  yacute: \"\\u00FD\",\n  thorn: \"\\u00FE\",\n  yuml: \"\\u00FF\",\n  OElig: \"\\u0152\",\n  oelig: \"\\u0153\",\n  Scaron: \"\\u0160\",\n  scaron: \"\\u0161\",\n  Yuml: \"\\u0178\",\n  fnof: \"\\u0192\",\n  circ: \"\\u02C6\",\n  tilde: \"\\u02DC\",\n  Alpha: \"\\u0391\",\n  Beta: \"\\u0392\",\n  Gamma: \"\\u0393\",\n  Delta: \"\\u0394\",\n  Epsilon: \"\\u0395\",\n  Zeta: \"\\u0396\",\n  Eta: \"\\u0397\",\n  Theta: \"\\u0398\",\n  Iota: \"\\u0399\",\n  Kappa: \"\\u039A\",\n  Lambda: \"\\u039B\",\n  Mu: \"\\u039C\",\n  Nu: \"\\u039D\",\n  Xi: \"\\u039E\",\n  Omicron: \"\\u039F\",\n  Pi: \"\\u03A0\",\n  Rho: \"\\u03A1\",\n  Sigma: \"\\u03A3\",\n  Tau: \"\\u03A4\",\n  Upsilon: \"\\u03A5\",\n  Phi: \"\\u03A6\",\n  Chi: \"\\u03A7\",\n  Psi: \"\\u03A8\",\n  Omega: \"\\u03A9\",\n  alpha: \"\\u03B1\",\n  beta: \"\\u03B2\",\n  gamma: \"\\u03B3\",\n  delta: \"\\u03B4\",\n  epsilon: \"\\u03B5\",\n  zeta: \"\\u03B6\",\n  eta: \"\\u03B7\",\n  theta: \"\\u03B8\",\n  iota: \"\\u03B9\",\n  kappa: \"\\u03BA\",\n  lambda: \"\\u03BB\",\n  mu: \"\\u03BC\",\n  nu: \"\\u03BD\",\n  xi: \"\\u03BE\",\n  omicron: \"\\u03BF\",\n  pi: \"\\u03C0\",\n  rho: \"\\u03C1\",\n  sigmaf: \"\\u03C2\",\n  sigma: \"\\u03C3\",\n  tau: \"\\u03C4\",\n  upsilon: \"\\u03C5\",\n  phi: \"\\u03C6\",\n  chi: \"\\u03C7\",\n  psi: \"\\u03C8\",\n  omega: \"\\u03C9\",\n  thetasym: \"\\u03D1\",\n  upsih: \"\\u03D2\",\n  piv: \"\\u03D6\",\n  ensp: \"\\u2002\",\n  emsp: \"\\u2003\",\n  thinsp: \"\\u2009\",\n  zwnj: \"\\u200C\",\n  zwj: \"\\u200D\",\n  lrm: \"\\u200E\",\n  rlm: \"\\u200F\",\n  ndash: \"\\u2013\",\n  mdash: \"\\u2014\",\n  lsquo: \"\\u2018\",\n  rsquo: \"\\u2019\",\n  sbquo: \"\\u201A\",\n  ldquo: \"\\u201C\",\n  rdquo: \"\\u201D\",\n  bdquo: \"\\u201E\",\n  dagger: \"\\u2020\",\n  Dagger: \"\\u2021\",\n  bull: \"\\u2022\",\n  hellip: \"\\u2026\",\n  permil: \"\\u2030\",\n  prime: \"\\u2032\",\n  Prime: \"\\u2033\",\n  lsaquo: \"\\u2039\",\n  rsaquo: \"\\u203A\",\n  oline: \"\\u203E\",\n  frasl: \"\\u2044\",\n  euro: \"\\u20AC\",\n  image: \"\\u2111\",\n  weierp: \"\\u2118\",\n  real: \"\\u211C\",\n  trade: \"\\u2122\",\n  alefsym: \"\\u2135\",\n  larr: \"\\u2190\",\n  uarr: \"\\u2191\",\n  rarr: \"\\u2192\",\n  darr: \"\\u2193\",\n  harr: \"\\u2194\",\n  crarr: \"\\u21B5\",\n  lArr: \"\\u21D0\",\n  uArr: \"\\u21D1\",\n  rArr: \"\\u21D2\",\n  dArr: \"\\u21D3\",\n  hArr: \"\\u21D4\",\n  forall: \"\\u2200\",\n  part: \"\\u2202\",\n  exist: \"\\u2203\",\n  empty: \"\\u2205\",\n  nabla: \"\\u2207\",\n  isin: \"\\u2208\",\n  notin: \"\\u2209\",\n  ni: \"\\u220B\",\n  prod: \"\\u220F\",\n  sum: \"\\u2211\",\n  minus: \"\\u2212\",\n  lowast: \"\\u2217\",\n  radic: \"\\u221A\",\n  prop: \"\\u221D\",\n  infin: \"\\u221E\",\n  ang: \"\\u2220\",\n  and: \"\\u2227\",\n  or: \"\\u2228\",\n  cap: \"\\u2229\",\n  cup: \"\\u222A\",\n  int: \"\\u222B\",\n  there4: \"\\u2234\",\n  sim: \"\\u223C\",\n  cong: \"\\u2245\",\n  asymp: \"\\u2248\",\n  ne: \"\\u2260\",\n  equiv: \"\\u2261\",\n  le: \"\\u2264\",\n  ge: \"\\u2265\",\n  sub: \"\\u2282\",\n  sup: \"\\u2283\",\n  nsub: \"\\u2284\",\n  sube: \"\\u2286\",\n  supe: \"\\u2287\",\n  oplus: \"\\u2295\",\n  otimes: \"\\u2297\",\n  perp: \"\\u22A5\",\n  sdot: \"\\u22C5\",\n  lceil: \"\\u2308\",\n  rceil: \"\\u2309\",\n  lfloor: \"\\u230A\",\n  rfloor: \"\\u230B\",\n  lang: \"\\u2329\",\n  rang: \"\\u232A\",\n  loz: \"\\u25CA\",\n  spades: \"\\u2660\",\n  clubs: \"\\u2663\",\n  hearts: \"\\u2665\",\n  diams: \"\\u2666\",\n} as const;\nexport default entities;\n","import * as charCodes from \"charcodes\";\n\n// Matches a whole line break (where CRLF is considered a single\n// line break). Used to count lines.\nexport const lineBreak = /\\r\\n|[\\r\\n\\u2028\\u2029]/;\nexport const lineBreakG = new RegExp(lineBreak.source, \"g\");\n\n// https://tc39.github.io/ecma262/#sec-line-terminators\nexport function isNewLine(code: number): boolean {\n  switch (code) {\n    case charCodes.lineFeed:\n    case charCodes.carriageReturn:\n    case charCodes.lineSeparator:\n    case charCodes.paragraphSeparator:\n      return true;\n\n    default:\n      return false;\n  }\n}\n\nexport function hasNewLine(input: string, start: number, end: number): boolean {\n  for (let i = start; i < end; i++) {\n    if (isNewLine(input.charCodeAt(i))) {\n      return true;\n    }\n  }\n  return false;\n}\n\nexport const skipWhiteSpace = /(?:\\s|\\/\\/.*|\\/\\*[^]*?\\*\\/)*/g;\n\nexport const skipWhiteSpaceInLine =\n  /(?:[^\\S\\n\\r\\u2028\\u2029]|\\/\\/.*|\\/\\*.*?\\*\\/)*/g;\n\n// https://tc39.github.io/ecma262/#sec-white-space\nexport function isWhitespace(code: number): boolean {\n  switch (code) {\n    case 0x0009: // CHARACTER TABULATION\n    case 0x000b: // LINE TABULATION\n    case 0x000c: // FORM FEED\n    case charCodes.space:\n    case charCodes.nonBreakingSpace:\n    case charCodes.oghamSpaceMark:\n    case 0x2000: // EN QUAD\n    case 0x2001: // EM QUAD\n    case 0x2002: // EN SPACE\n    case 0x2003: // EM SPACE\n    case 0x2004: // THREE-PER-EM SPACE\n    case 0x2005: // FOUR-PER-EM SPACE\n    case 0x2006: // SIX-PER-EM SPACE\n    case 0x2007: // FIGURE SPACE\n    case 0x2008: // PUNCTUATION SPACE\n    case 0x2009: // THIN SPACE\n    case 0x200a: // HAIR SPACE\n    case 0x202f: // NARROW NO-BREAK SPACE\n    case 0x205f: // MEDIUM MATHEMATICAL SPACE\n    case 0x3000: // IDEOGRAPHIC SPACE\n    case 0xfeff: // ZERO WIDTH NO-BREAK SPACE\n      return true;\n\n    default:\n      return false;\n  }\n}\n","import * as charCodes from \"charcodes\";\n\nimport XHTMLEntities from \"./xhtml.ts\";\nimport type Parser from \"../../parser/index.ts\";\nimport type { ExpressionErrors } from \"../../parser/util.ts\";\nimport {\n  tokenComesBeforeExpression,\n  tokenIsKeyword,\n  tokenLabelName,\n  type TokenType,\n  tt,\n} from \"../../tokenizer/types.ts\";\nimport type { TokContext } from \"../../tokenizer/context.ts\";\nimport { types as tc } from \"../../tokenizer/context.ts\";\nimport type * as N from \"../../types.ts\";\nimport { isIdentifierChar, isIdentifierStart } from \"../../util/identifier.ts\";\nimport type { Position } from \"../../util/location.ts\";\nimport { isNewLine } from \"../../util/whitespace.ts\";\nimport { Errors, ParseErrorEnum } from \"../../parse-error.ts\";\nimport type { Undone } from \"../../parser/node.ts\";\n\n/* eslint sort-keys: \"error\" */\nconst JsxErrors = ParseErrorEnum`jsx`({\n  AttributeIsEmpty:\n    \"JSX attributes must only be assigned a non-empty expression.\",\n  MissingClosingTagElement: ({ openingTagName }: { openingTagName: string }) =>\n    `Expected corresponding JSX closing tag for <${openingTagName}>.`,\n  MissingClosingTagFragment: \"Expected corresponding JSX closing tag for <>.\",\n  UnexpectedSequenceExpression:\n    \"Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?\",\n  // FIXME: Unify with Errors.UnexpectedToken\n  UnexpectedToken: ({\n    unexpected,\n    HTMLEntity,\n  }: {\n    unexpected: string;\n    HTMLEntity: string;\n  }) =>\n    `Unexpected token \\`${unexpected}\\`. Did you mean \\`${HTMLEntity}\\` or \\`{'${unexpected}'}\\`?`,\n  UnsupportedJsxValue:\n    \"JSX value should be either an expression or a quoted JSX text.\",\n  UnterminatedJsxContent: \"Unterminated JSX contents.\",\n  UnwrappedAdjacentJSXElements:\n    \"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?\",\n});\n\n/* eslint-disable sort-keys */\n\nfunction isFragment(object?: N.JSXTag | null): object is N.JSXFragmentTag {\n  return object\n    ? object.type === \"JSXOpeningFragment\" ||\n        object.type === \"JSXClosingFragment\"\n    : false;\n}\n\n// Transforms JSX element name to string.\n\nfunction getQualifiedJSXName(\n  object: N.JSXIdentifier | N.JSXNamespacedName | N.JSXMemberExpression,\n): string {\n  if (object.type === \"JSXIdentifier\") {\n    return object.name;\n  }\n\n  if (object.type === \"JSXNamespacedName\") {\n    return object.namespace.name + \":\" + object.name.name;\n  }\n\n  if (object.type === \"JSXMemberExpression\") {\n    return (\n      getQualifiedJSXName(object.object) +\n      \".\" +\n      getQualifiedJSXName(object.property)\n    );\n  }\n\n  // istanbul ignore next\n  // @ts-expect-error - object is 'never'\n  throw new Error(\"Node had unexpected type: \" + object.type);\n}\n\nexport interface IJSXParserMixin {\n  jsxParseOpeningElementAfterName(\n    node: N.JSXOpeningElement,\n  ): N.JSXOpeningElement;\n}\n\nexport type ClassWithMixin<\n  T extends new (...args: any) => any,\n  M extends object,\n> = T extends new (...args: infer P) => infer I\n  ? new (...args: P) => I & M\n  : never;\n\nexport default (superClass: typeof Parser) =>\n  class JSXParserMixin extends superClass implements Parser, IJSXParserMixin {\n    // Reads inline JSX contents token.\n\n    jsxReadToken(): void {\n      let out = \"\";\n      let chunkStart = this.state.pos;\n      for (;;) {\n        if (this.state.pos >= this.length) {\n          throw this.raise(\n            JsxErrors.UnterminatedJsxContent,\n            this.state.startLoc,\n          );\n        }\n\n        const ch = this.input.charCodeAt(this.state.pos);\n\n        switch (ch) {\n          case charCodes.lessThan:\n          case charCodes.leftCurlyBrace:\n            if (this.state.pos === this.state.start) {\n              if (ch === charCodes.lessThan && this.state.canStartJSXElement) {\n                ++this.state.pos;\n                this.finishToken(tt.jsxTagStart);\n              } else {\n                super.getTokenFromCode(ch);\n              }\n              return;\n            }\n            out += this.input.slice(chunkStart, this.state.pos);\n            this.finishToken(tt.jsxText, out);\n            return;\n\n          case charCodes.ampersand:\n            out += this.input.slice(chunkStart, this.state.pos);\n            out += this.jsxReadEntity();\n            chunkStart = this.state.pos;\n            break;\n\n          case charCodes.greaterThan:\n          case charCodes.rightCurlyBrace:\n            if (process.env.BABEL_8_BREAKING) {\n              this.raise(JsxErrors.UnexpectedToken, this.state.curPosition(), {\n                unexpected: this.input[this.state.pos],\n                HTMLEntity:\n                  ch === charCodes.rightCurlyBrace ? \"&rbrace;\" : \"&gt;\",\n              });\n            }\n          /* falls through */\n\n          default:\n            if (isNewLine(ch)) {\n              out += this.input.slice(chunkStart, this.state.pos);\n              out += this.jsxReadNewLine(true);\n              chunkStart = this.state.pos;\n            } else {\n              ++this.state.pos;\n            }\n        }\n      }\n    }\n\n    jsxReadNewLine(normalizeCRLF: boolean): string {\n      const ch = this.input.charCodeAt(this.state.pos);\n      let out;\n      ++this.state.pos;\n      if (\n        ch === charCodes.carriageReturn &&\n        this.input.charCodeAt(this.state.pos) === charCodes.lineFeed\n      ) {\n        ++this.state.pos;\n        out = normalizeCRLF ? \"\\n\" : \"\\r\\n\";\n      } else {\n        out = String.fromCharCode(ch);\n      }\n      ++this.state.curLine;\n      this.state.lineStart = this.state.pos;\n\n      return out;\n    }\n\n    jsxReadString(quote: number): void {\n      let out = \"\";\n      let chunkStart = ++this.state.pos;\n      for (;;) {\n        if (this.state.pos >= this.length) {\n          throw this.raise(Errors.UnterminatedString, this.state.startLoc);\n        }\n\n        const ch = this.input.charCodeAt(this.state.pos);\n        if (ch === quote) break;\n        if (ch === charCodes.ampersand) {\n          out += this.input.slice(chunkStart, this.state.pos);\n          out += this.jsxReadEntity();\n          chunkStart = this.state.pos;\n        } else if (isNewLine(ch)) {\n          out += this.input.slice(chunkStart, this.state.pos);\n          out += this.jsxReadNewLine(false);\n          chunkStart = this.state.pos;\n        } else {\n          ++this.state.pos;\n        }\n      }\n      out += this.input.slice(chunkStart, this.state.pos++);\n      this.finishToken(tt.string, out);\n    }\n\n    jsxReadEntity(): string {\n      const startPos = ++this.state.pos;\n      if (this.codePointAtPos(this.state.pos) === charCodes.numberSign) {\n        ++this.state.pos;\n\n        let radix = 10;\n        if (this.codePointAtPos(this.state.pos) === charCodes.lowercaseX) {\n          radix = 16;\n          ++this.state.pos;\n        }\n\n        const codePoint = this.readInt(\n          radix,\n          /* len */ undefined,\n          /* forceLen */ false,\n          /* allowNumSeparator */ \"bail\",\n        );\n        if (\n          codePoint !== null &&\n          this.codePointAtPos(this.state.pos) === charCodes.semicolon\n        ) {\n          ++this.state.pos;\n          return String.fromCodePoint(codePoint);\n        }\n      } else {\n        let count = 0;\n        let semi = false;\n        while (\n          count++ < 10 &&\n          this.state.pos < this.length &&\n          !(semi = this.codePointAtPos(this.state.pos) === charCodes.semicolon)\n        ) {\n          ++this.state.pos;\n        }\n\n        if (semi) {\n          const desc = this.input.slice(startPos, this.state.pos);\n          const entity = XHTMLEntities[desc];\n          ++this.state.pos;\n\n          if (entity) {\n            return entity;\n          }\n        }\n      }\n\n      // Not a valid entity\n      this.state.pos = startPos;\n      return \"&\";\n    }\n\n    // Read a JSX identifier (valid tag or attribute name).\n    //\n    // Optimized version since JSX identifiers can\"t contain\n    // escape characters and so can be read as single slice.\n    // Also assumes that first character was already checked\n    // by isIdentifierStart in readToken.\n\n    jsxReadWord(): void {\n      let ch;\n      const start = this.state.pos;\n      do {\n        ch = this.input.charCodeAt(++this.state.pos);\n      } while (isIdentifierChar(ch) || ch === charCodes.dash);\n      this.finishToken(tt.jsxName, this.input.slice(start, this.state.pos));\n    }\n\n    // Parse next token as JSX identifier\n\n    jsxParseIdentifier(): N.JSXIdentifier {\n      const node = this.startNode<N.JSXIdentifier>();\n      if (this.match(tt.jsxName)) {\n        node.name = this.state.value;\n      } else if (tokenIsKeyword(this.state.type)) {\n        node.name = tokenLabelName(this.state.type);\n      } else {\n        this.unexpected();\n      }\n      this.next();\n      return this.finishNode(node, \"JSXIdentifier\");\n    }\n\n    // Parse namespaced identifier.\n\n    jsxParseNamespacedName(): N.JSXNamespacedName | N.JSXIdentifier {\n      const startLoc = this.state.startLoc;\n      const name = this.jsxParseIdentifier();\n      if (!this.eat(tt.colon)) return name;\n\n      const node = this.startNodeAt<N.JSXNamespacedName>(startLoc);\n      node.namespace = name;\n      node.name = this.jsxParseIdentifier();\n      return this.finishNode(node, \"JSXNamespacedName\");\n    }\n\n    // Parses element name in any form - namespaced, member\n    // or single identifier.\n\n    jsxParseElementName():\n      | N.JSXIdentifier\n      | N.JSXNamespacedName\n      | N.JSXMemberExpression {\n      const startLoc = this.state.startLoc;\n      let node: N.JSXIdentifier | N.JSXNamespacedName | N.JSXMemberExpression =\n        this.jsxParseNamespacedName();\n      if (node.type === \"JSXNamespacedName\") {\n        return node;\n      }\n      while (this.eat(tt.dot)) {\n        const newNode = this.startNodeAt<N.JSXMemberExpression>(startLoc);\n        newNode.object = node;\n        newNode.property = this.jsxParseIdentifier();\n        node = this.finishNode(newNode, \"JSXMemberExpression\");\n      }\n      return node;\n    }\n\n    // Parses any type of JSX attribute value.\n\n    jsxParseAttributeValue():\n      | N.JSXExpressionContainer\n      | N.JSXElement\n      | N.StringLiteral {\n      let node;\n      switch (this.state.type) {\n        case tt.braceL:\n          node = this.startNode();\n          this.setContext(tc.brace);\n          this.next();\n          node = this.jsxParseExpressionContainer(node, tc.j_oTag);\n          if (node.expression.type === \"JSXEmptyExpression\") {\n            this.raise(JsxErrors.AttributeIsEmpty, node);\n          }\n          return node;\n\n        case tt.jsxTagStart:\n        case tt.string:\n          return this.parseExprAtom() as N.JSXElement | N.StringLiteral;\n\n        default:\n          throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc);\n      }\n    }\n\n    // JSXEmptyExpression is unique type since it doesn't actually parse anything,\n    // and so it should start at the end of last read token (left brace) and finish\n    // at the beginning of the next one (right brace).\n\n    jsxParseEmptyExpression(): N.JSXEmptyExpression {\n      const node = this.startNodeAt(this.state.lastTokEndLoc);\n      return this.finishNodeAt(node, \"JSXEmptyExpression\", this.state.startLoc);\n    }\n\n    // Parse JSX spread child\n\n    jsxParseSpreadChild(node: Undone<N.JSXSpreadChild>): N.JSXSpreadChild {\n      this.next(); // ellipsis\n      node.expression = this.parseExpression();\n      this.setContext(tc.j_expr);\n      this.state.canStartJSXElement = true;\n      this.expect(tt.braceR);\n\n      return this.finishNode(node, \"JSXSpreadChild\");\n    }\n\n    // Parses JSX expression enclosed into curly brackets.\n\n    jsxParseExpressionContainer(\n      node: Undone<N.JSXExpressionContainer>,\n      previousContext: TokContext,\n    ): N.JSXExpressionContainer {\n      if (this.match(tt.braceR)) {\n        node.expression = this.jsxParseEmptyExpression();\n      } else {\n        const expression = this.parseExpression();\n\n        if (process.env.BABEL_8_BREAKING) {\n          if (\n            expression.type === \"SequenceExpression\" &&\n            !expression.extra?.parenthesized\n          ) {\n            this.raise(\n              JsxErrors.UnexpectedSequenceExpression,\n              expression.expressions[1],\n            );\n          }\n        }\n\n        node.expression = expression;\n      }\n      this.setContext(previousContext);\n      this.state.canStartJSXElement = true;\n      this.expect(tt.braceR);\n\n      return this.finishNode(node, \"JSXExpressionContainer\");\n    }\n\n    // Parses following JSX attribute name-value pair.\n\n    jsxParseAttribute(): N.JSXAttribute | N.JSXSpreadAttribute {\n      const node = this.startNode<N.JSXAttribute | N.JSXSpreadAttribute>();\n      if (this.match(tt.braceL)) {\n        this.setContext(tc.brace);\n        this.next();\n        this.expect(tt.ellipsis);\n        node.argument = this.parseMaybeAssignAllowIn();\n        this.setContext(tc.j_oTag);\n        this.state.canStartJSXElement = true;\n        this.expect(tt.braceR);\n        return this.finishNode(node, \"JSXSpreadAttribute\");\n      }\n      node.name = this.jsxParseNamespacedName();\n      node.value = this.eat(tt.eq) ? this.jsxParseAttributeValue() : null;\n      return this.finishNode(node, \"JSXAttribute\");\n    }\n\n    // Parses JSX opening tag starting after \"<\".\n\n    jsxParseOpeningElementAt(\n      startLoc: Position,\n    ): N.JSXOpeningElement | N.JSXOpeningFragment {\n      const node = this.startNodeAt<N.JSXOpeningElement | N.JSXOpeningFragment>(\n        startLoc,\n      );\n      if (this.eat(tt.jsxTagEnd)) {\n        return this.finishNode(node, \"JSXOpeningFragment\");\n      }\n      node.name = this.jsxParseElementName();\n      return this.jsxParseOpeningElementAfterName(\n        node as Undone<N.JSXOpeningElement>,\n      );\n    }\n\n    jsxParseOpeningElementAfterName(\n      node: Undone<N.JSXOpeningElement>,\n    ): N.JSXOpeningElement {\n      const attributes: (N.JSXAttribute | N.JSXSpreadAttribute)[] = [];\n      while (!this.match(tt.slash) && !this.match(tt.jsxTagEnd)) {\n        attributes.push(this.jsxParseAttribute());\n      }\n      node.attributes = attributes;\n      node.selfClosing = this.eat(tt.slash);\n      this.expect(tt.jsxTagEnd);\n      return this.finishNode(node, \"JSXOpeningElement\");\n    }\n\n    // Parses JSX closing tag starting after \"</\".\n\n    jsxParseClosingElementAt(\n      startLoc: Position,\n    ): N.JSXClosingElement | N.JSXClosingFragment {\n      const node = this.startNodeAt<N.JSXClosingFragment | N.JSXClosingElement>(\n        startLoc,\n      );\n      if (this.eat(tt.jsxTagEnd)) {\n        return this.finishNode(node, \"JSXClosingFragment\");\n      }\n      node.name = this.jsxParseElementName();\n      this.expect(tt.jsxTagEnd);\n      return this.finishNode(node, \"JSXClosingElement\");\n    }\n\n    // Parses entire JSX element, including it\"s opening tag\n    // (starting after \"<\"), attributes, contents and closing tag.\n\n    jsxParseElementAt(startLoc: Position): N.JSXElement | N.JSXFragment {\n      const node = this.startNodeAt<N.JSXElement | N.JSXFragment>(startLoc);\n      const children = [];\n      const openingElement = this.jsxParseOpeningElementAt(startLoc);\n      let closingElement = null;\n\n      if (!openingElement.selfClosing) {\n        contents: for (;;) {\n          switch (this.state.type) {\n            case tt.jsxTagStart:\n              startLoc = this.state.startLoc;\n              this.next();\n              if (this.eat(tt.slash)) {\n                closingElement = this.jsxParseClosingElementAt(startLoc);\n                break contents;\n              }\n              children.push(this.jsxParseElementAt(startLoc));\n              break;\n\n            case tt.jsxText:\n              children.push(this.parseLiteral(this.state.value, \"JSXText\"));\n              break;\n\n            case tt.braceL: {\n              const node = this.startNode<\n                N.JSXSpreadChild | N.JSXExpressionContainer\n              >();\n              this.setContext(tc.brace);\n              this.next();\n              if (this.match(tt.ellipsis)) {\n                children.push(this.jsxParseSpreadChild(node));\n              } else {\n                children.push(\n                  this.jsxParseExpressionContainer(node, tc.j_expr),\n                );\n              }\n\n              break;\n            }\n            // istanbul ignore next - should never happen\n            default:\n              this.unexpected();\n          }\n        }\n\n        if (\n          isFragment(openingElement) &&\n          !isFragment(closingElement) &&\n          closingElement !== null\n        ) {\n          this.raise(JsxErrors.MissingClosingTagFragment, closingElement);\n        } else if (!isFragment(openingElement) && isFragment(closingElement)) {\n          this.raise(JsxErrors.MissingClosingTagElement, closingElement, {\n            openingTagName: getQualifiedJSXName(openingElement.name),\n          });\n        } else if (!isFragment(openingElement) && !isFragment(closingElement)) {\n          if (\n            getQualifiedJSXName(closingElement.name) !==\n            getQualifiedJSXName(openingElement.name)\n          ) {\n            this.raise(JsxErrors.MissingClosingTagElement, closingElement, {\n              openingTagName: getQualifiedJSXName(openingElement.name),\n            });\n          }\n        }\n      }\n\n      if (isFragment(openingElement)) {\n        node.openingFragment = openingElement;\n        node.closingFragment = closingElement;\n      } else {\n        node.openingElement = openingElement;\n        node.closingElement = closingElement;\n      }\n      node.children = children;\n      if (this.match(tt.lt)) {\n        throw this.raise(\n          JsxErrors.UnwrappedAdjacentJSXElements,\n          this.state.startLoc,\n        );\n      }\n\n      return isFragment(openingElement)\n        ? this.finishNode(node, \"JSXFragment\")\n        : this.finishNode(node, \"JSXElement\");\n    }\n\n    // Parses entire JSX element from current position.\n\n    jsxParseElement(): N.JSXElement | N.JSXFragment {\n      const startLoc = this.state.startLoc;\n      this.next();\n      return this.jsxParseElementAt(startLoc);\n    }\n\n    setContext(newContext: TokContext) {\n      const { context } = this.state;\n      context[context.length - 1] = newContext;\n    }\n\n    // ==================================\n    // Overrides\n    // ==================================\n\n    parseExprAtom(refExpressionErrors?: ExpressionErrors | null): N.Expression {\n      if (this.match(tt.jsxTagStart)) {\n        return this.jsxParseElement();\n      } else if (\n        this.match(tt.lt) &&\n        this.input.charCodeAt(this.state.pos) !== charCodes.exclamationMark\n      ) {\n        // In case we encounter an lt token here it will always be the start of\n        // jsx as the lt sign is not allowed in places that expect an expression\n        this.replaceToken(tt.jsxTagStart);\n        return this.jsxParseElement();\n      } else {\n        return super.parseExprAtom(refExpressionErrors);\n      }\n    }\n\n    skipSpace() {\n      const curContext = this.curContext();\n      if (!curContext.preserveSpace) super.skipSpace();\n    }\n\n    getTokenFromCode(code: number): void {\n      const context = this.curContext();\n\n      if (context === tc.j_expr) {\n        this.jsxReadToken();\n        return;\n      }\n\n      if (context === tc.j_oTag || context === tc.j_cTag) {\n        if (isIdentifierStart(code)) {\n          this.jsxReadWord();\n          return;\n        }\n\n        if (code === charCodes.greaterThan) {\n          ++this.state.pos;\n          this.finishToken(tt.jsxTagEnd);\n          return;\n        }\n\n        if (\n          (code === charCodes.quotationMark || code === charCodes.apostrophe) &&\n          context === tc.j_oTag\n        ) {\n          this.jsxReadString(code);\n          return;\n        }\n      }\n\n      if (\n        code === charCodes.lessThan &&\n        this.state.canStartJSXElement &&\n        this.input.charCodeAt(this.state.pos + 1) !== charCodes.exclamationMark\n      ) {\n        ++this.state.pos;\n        this.finishToken(tt.jsxTagStart);\n        return;\n      }\n\n      super.getTokenFromCode(code);\n    }\n\n    updateContext(prevType: TokenType): void {\n      const { context, type } = this.state;\n      if (type === tt.slash && prevType === tt.jsxTagStart) {\n        // do not consider JSX expr -> JSX open tag -> ... anymore\n        // reconsider as closing tag context\n        context.splice(-2, 2, tc.j_cTag);\n        this.state.canStartJSXElement = false;\n      } else if (type === tt.jsxTagStart) {\n        // start opening tag context\n        context.push(tc.j_oTag);\n      } else if (type === tt.jsxTagEnd) {\n        const out = context[context.length - 1];\n        if ((out === tc.j_oTag && prevType === tt.slash) || out === tc.j_cTag) {\n          context.pop();\n          this.state.canStartJSXElement =\n            context[context.length - 1] === tc.j_expr;\n        } else {\n          this.setContext(tc.j_expr);\n          this.state.canStartJSXElement = true;\n        }\n      } else {\n        this.state.canStartJSXElement = tokenComesBeforeExpression(type);\n      }\n    }\n  };\n","import type { Position } from \"../../util/location.ts\";\nimport ScopeHandler, { NameType, Scope } from \"../../util/scope.ts\";\nimport { BindingFlag, ScopeFlag } from \"../../util/scopeflags.ts\";\nimport type * as N from \"../../types.ts\";\nimport { Errors } from \"../../parse-error.ts\";\n\nconst enum TsNameType {\n  Types = 1 << 0,\n  // enums (which are also in .types)\n  Enums = 1 << 1,\n  // const enums (which are also in .enums and .types)\n  ConstEnums = 1 << 2,\n  // classes (which are also in .lexical) and interface (which are also in .types)\n  Classes = 1 << 3,\n  // namespaces and ambient functions (or classes) are too difficult to track,\n  // especially without type analysis.\n  // We need to track them anyway, to avoid \"X is not defined\" errors\n  // when exporting them.\n  ExportOnlyBindings = 1 << 4,\n}\n\nclass TypeScriptScope extends Scope {\n  tsNames: Map<string, TsNameType> = new Map();\n}\n\n// See https://github.com/babel/babel/pull/9766#discussion_r268920730 for an\n// explanation of how typescript handles scope.\n\nexport default class TypeScriptScopeHandler extends ScopeHandler<TypeScriptScope> {\n  importsStack: Set<string>[] = [];\n\n  createScope(flags: ScopeFlag): TypeScriptScope {\n    this.importsStack.push(new Set()); // Always keep the top-level scope for export checks.\n\n    return new TypeScriptScope(flags);\n  }\n\n  enter(flags: ScopeFlag): void {\n    if (flags === ScopeFlag.TS_MODULE) {\n      this.importsStack.push(new Set());\n    }\n\n    super.enter(flags);\n  }\n\n  exit() {\n    const flags = super.exit();\n\n    if (flags === ScopeFlag.TS_MODULE) {\n      this.importsStack.pop();\n    }\n\n    return flags;\n  }\n\n  hasImport(name: string, allowShadow?: boolean) {\n    const len = this.importsStack.length;\n    if (this.importsStack[len - 1].has(name)) {\n      return true;\n    }\n    if (!allowShadow && len > 1) {\n      for (let i = 0; i < len - 1; i++) {\n        if (this.importsStack[i].has(name)) return true;\n      }\n    }\n    return false;\n  }\n\n  declareName(name: string, bindingType: BindingFlag, loc: Position) {\n    if (bindingType & BindingFlag.FLAG_TS_IMPORT) {\n      if (this.hasImport(name, true)) {\n        this.parser.raise(Errors.VarRedeclaration, loc, {\n          identifierName: name,\n        });\n      }\n      this.importsStack[this.importsStack.length - 1].add(name);\n      return;\n    }\n\n    const scope = this.currentScope();\n    let type = scope.tsNames.get(name) || 0;\n\n    if (bindingType & BindingFlag.FLAG_TS_EXPORT_ONLY) {\n      this.maybeExportDefined(scope, name);\n      scope.tsNames.set(name, type | TsNameType.ExportOnlyBindings);\n      return;\n    }\n\n    super.declareName(name, bindingType, loc);\n\n    if (bindingType & BindingFlag.KIND_TYPE) {\n      if (!(bindingType & BindingFlag.KIND_VALUE)) {\n        // \"Value\" bindings have already been registered by the superclass.\n        this.checkRedeclarationInScope(scope, name, bindingType, loc);\n        this.maybeExportDefined(scope, name);\n      }\n      type = type | TsNameType.Types;\n    }\n    if (bindingType & BindingFlag.FLAG_TS_ENUM) {\n      type = type | TsNameType.Enums;\n    }\n    if (bindingType & BindingFlag.FLAG_TS_CONST_ENUM) {\n      type = type | TsNameType.ConstEnums;\n    }\n    if (bindingType & BindingFlag.FLAG_CLASS) {\n      type = type | TsNameType.Classes;\n    }\n    if (type) scope.tsNames.set(name, type);\n  }\n\n  isRedeclaredInScope(\n    scope: TypeScriptScope,\n    name: string,\n    bindingType: BindingFlag,\n  ): boolean {\n    const type = scope.tsNames.get(name);\n    if ((type & TsNameType.Enums) > 0) {\n      if (bindingType & BindingFlag.FLAG_TS_ENUM) {\n        // Enums can be merged with other enums if they are both\n        //  const or both non-const.\n        const isConst = !!(bindingType & BindingFlag.FLAG_TS_CONST_ENUM);\n        const wasConst = (type & TsNameType.ConstEnums) > 0;\n        return isConst !== wasConst;\n      }\n      return true;\n    }\n    if (\n      bindingType & BindingFlag.FLAG_CLASS &&\n      (type & TsNameType.Classes) > 0\n    ) {\n      if (scope.names.get(name) & NameType.Lexical) {\n        // Classes can be merged with interfaces\n        return !!(bindingType & BindingFlag.KIND_VALUE);\n      } else {\n        // Interface can be merged with other classes or interfaces\n        return false;\n      }\n    }\n    if (bindingType & BindingFlag.KIND_TYPE && (type & TsNameType.Types) > 0) {\n      return true;\n    }\n\n    return super.isRedeclaredInScope(scope, name, bindingType);\n  }\n\n  checkLocalExport(id: N.Identifier) {\n    const { name } = id;\n\n    if (this.hasImport(name)) return;\n\n    const len = this.scopeStack.length;\n    for (let i = len - 1; i >= 0; i--) {\n      const scope = this.scopeStack[i];\n      const type = scope.tsNames.get(name);\n      if (\n        (type & TsNameType.Types) > 0 ||\n        (type & TsNameType.ExportOnlyBindings) > 0\n      ) {\n        return;\n      }\n    }\n\n    super.checkLocalExport(id);\n  }\n}\n","// ProductionParameterHandler is a stack fashioned production parameter tracker\n// https://tc39.es/ecma262/#sec-grammar-notation\n// The tracked parameters are defined above.\n//\n// Whenever [+Await]/[+Yield] appears in the right-hand sides of a production,\n// we must enter a new tracking stack. For example when parsing\n//\n// AsyncFunctionDeclaration [Yield, Await]:\n//   async [no LineTerminator here] function BindingIdentifier[?Yield, ?Await]\n//     ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody }\n//\n// we must follow such process:\n//\n// 1. parse async keyword\n// 2. parse function keyword\n// 3. parse bindingIdentifier <= inherit current parameters: [?Await]\n// 4. enter new stack with (PARAM_AWAIT)\n// 5. parse formal parameters <= must have [Await] parameter [+Await]\n// 6. parse function body\n// 7. exit current stack\n\nexport const enum ParamKind {\n  // Initial Parameter flags\n  PARAM = 0b0000,\n  // track [Yield] production parameter\n  PARAM_YIELD = 0b0001,\n  // track [Await] production parameter\n  PARAM_AWAIT = 0b0010,\n  // track [Return] production parameter\n  PARAM_RETURN = 0b0100,\n  // track [In] production parameter\n  PARAM_IN = 0b1000,\n}\n\n// todo(flow->ts) - check if more granular type can be used,\n//  type below is not good because things like PARAM_AWAIT|PARAM_YIELD are not included\n// export type ParamKind =\n//   | typeof PARAM\n//   | typeof PARAM_AWAIT\n//   | typeof PARAM_IN\n//   | typeof PARAM_RETURN\n//   | typeof PARAM_YIELD;\n\nexport default class ProductionParameterHandler {\n  stacks: Array<ParamKind> = [];\n  enter(flags: ParamKind) {\n    this.stacks.push(flags);\n  }\n\n  exit() {\n    this.stacks.pop();\n  }\n\n  currentFlags(): ParamKind {\n    return this.stacks[this.stacks.length - 1];\n  }\n\n  get hasAwait(): boolean {\n    return (this.currentFlags() & ParamKind.PARAM_AWAIT) > 0;\n  }\n\n  get hasYield(): boolean {\n    return (this.currentFlags() & ParamKind.PARAM_YIELD) > 0;\n  }\n\n  get hasReturn(): boolean {\n    return (this.currentFlags() & ParamKind.PARAM_RETURN) > 0;\n  }\n\n  get hasIn(): boolean {\n    return (this.currentFlags() & ParamKind.PARAM_IN) > 0;\n  }\n}\n\nexport function functionFlags(\n  isAsync: boolean,\n  isGenerator: boolean,\n): ParamKind {\n  return (\n    (isAsync ? ParamKind.PARAM_AWAIT : 0) |\n    (isGenerator ? ParamKind.PARAM_YIELD : 0)\n  );\n}\n","import type { OptionFlags, Options } from \"../options.ts\";\nimport type State from \"../tokenizer/state.ts\";\nimport type { PluginsMap } from \"./index.ts\";\nimport type ScopeHandler from \"../util/scope.ts\";\nimport type ExpressionScopeHandler from \"../util/expression-scope.ts\";\nimport type ClassScopeHandler from \"../util/class-scope.ts\";\nimport type ProductionParameterHandler from \"../util/production-parameter.ts\";\nimport type {\n  ParserPluginWithOptions,\n  PluginConfig,\n  PluginOptions,\n} from \"../typings.ts\";\nimport type * as N from \"../types.ts\";\n\nexport default class BaseParser {\n  // Properties set by constructor in index.js\n  declare options: Options;\n  declare optionFlags: OptionFlags;\n  declare inModule: boolean;\n  declare scope: ScopeHandler<any>;\n  declare classScope: ClassScopeHandler;\n  declare prodParam: ProductionParameterHandler;\n  declare expressionScope: ExpressionScopeHandler;\n  declare plugins: PluginsMap;\n  declare filename: string | undefined | null;\n  declare startIndex: number;\n  // Names of exports store. `default` is stored as a name for both\n  // `export default foo;` and `export { foo as default };`.\n  declare exportedIdentifiers: Set<string>;\n  sawUnambiguousESM: boolean = false;\n  ambiguousScriptDifferentAst: boolean = false;\n\n  // Initialized by Tokenizer\n  declare state: State;\n  // input and length are not in state as they are constant and we do\n  // not want to ever copy them, which happens if state gets cloned\n  declare input: string;\n  declare length: number;\n  // Comment store for Program.comments\n  declare comments: Array<N.Comment>;\n\n  sourceToOffsetPos(sourcePos: number) {\n    return sourcePos + this.startIndex;\n  }\n\n  offsetToSourcePos(offsetPos: number) {\n    return offsetPos - this.startIndex;\n  }\n\n  // This method accepts either a string (plugin name) or an array pair\n  // (plugin name and options object). If an options object is given,\n  // then each value is non-recursively checked for identity with that\n  // plugin’s actual option value.\n  hasPlugin(pluginConfig: PluginConfig): boolean {\n    if (typeof pluginConfig === \"string\") {\n      return this.plugins.has(pluginConfig);\n    } else {\n      const [pluginName, pluginOptions] = pluginConfig;\n      if (!this.hasPlugin(pluginName)) {\n        return false;\n      }\n      const actualOptions = this.plugins.get(pluginName);\n      for (const key of Object.keys(\n        pluginOptions,\n      ) as (keyof typeof pluginOptions)[]) {\n        if (actualOptions?.[key] !== pluginOptions[key]) {\n          return false;\n        }\n      }\n      return true;\n    }\n  }\n\n  getPluginOption<\n    PluginName extends ParserPluginWithOptions[0],\n    OptionName extends keyof PluginOptions<PluginName>,\n  >(plugin: PluginName, name: OptionName) {\n    return (this.plugins.get(plugin) as null | PluginOptions<PluginName>)?.[\n      name\n    ];\n  }\n}\n","/*:: declare var invariant; */\n\nimport BaseParser from \"./base.ts\";\nimport type { Comment, Node } from \"../types.ts\";\nimport * as charCodes from \"charcodes\";\nimport type { Undone } from \"./node.ts\";\n\n/**\n * A whitespace token containing comments\n */\nexport type CommentWhitespace = {\n  /**\n   * the start of the whitespace token.\n   */\n  start: number;\n  /**\n   * the end of the whitespace token.\n   */\n  end: number;\n  /**\n   * the containing comments\n   */\n  comments: Array<Comment>;\n  /**\n   * the immediately preceding AST node of the whitespace token\n   */\n  leadingNode: Node | null;\n  /**\n   * the immediately following AST node of the whitespace token\n   */\n  trailingNode: Node | null;\n  /**\n   * the innermost AST node containing the whitespace with minimal size (|end - start|)\n   */\n  containingNode: Node | null;\n};\n\n/**\n * Merge comments with node's trailingComments or assign comments to be\n * trailingComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n */\nfunction setTrailingComments(node: Undone<Node>, comments: Array<Comment>) {\n  if (node.trailingComments === undefined) {\n    node.trailingComments = comments;\n  } else {\n    node.trailingComments.unshift(...comments);\n  }\n}\n\n/**\n * Merge comments with node's leadingComments or assign comments to be\n * leadingComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n */\nfunction setLeadingComments(node: Undone<Node>, comments: Array<Comment>) {\n  if (node.leadingComments === undefined) {\n    node.leadingComments = comments;\n  } else {\n    node.leadingComments.unshift(...comments);\n  }\n}\n\n/**\n * Merge comments with node's innerComments or assign comments to be\n * innerComments. New comments will be placed before old comments\n * because the commentStack is enumerated reversely.\n */\nexport function setInnerComments(\n  node: Undone<Node>,\n  comments?: Array<Comment>,\n) {\n  if (node.innerComments === undefined) {\n    node.innerComments = comments;\n  } else {\n    node.innerComments.unshift(...comments);\n  }\n}\n\n/**\n * Given node and elements array, if elements has non-null element,\n * merge comments to its trailingComments, otherwise merge comments\n * to node's innerComments\n */\nfunction adjustInnerComments(\n  node: Undone<Node>,\n  elements: Array<Node>,\n  commentWS: CommentWhitespace,\n) {\n  let lastElement = null;\n  let i = elements.length;\n  while (lastElement === null && i > 0) {\n    lastElement = elements[--i];\n  }\n  if (lastElement === null || lastElement.start > commentWS.start) {\n    setInnerComments(node, commentWS.comments);\n  } else {\n    setTrailingComments(lastElement, commentWS.comments);\n  }\n}\n\nexport default class CommentsParser extends BaseParser {\n  addComment(comment: Comment): void {\n    if (this.filename) comment.loc.filename = this.filename;\n    const { commentsLen } = this.state;\n    if (this.comments.length !== commentsLen) {\n      this.comments.length = commentsLen;\n    }\n    this.comments.push(comment);\n    this.state.commentsLen++;\n  }\n\n  /**\n   * Given a newly created AST node _n_, attach _n_ to a comment whitespace _w_ if applicable\n   * {@see {@link CommentWhitespace}}\n   */\n  processComment(node: Node): void {\n    const { commentStack } = this.state;\n    const commentStackLength = commentStack.length;\n    if (commentStackLength === 0) return;\n    let i = commentStackLength - 1;\n    const lastCommentWS = commentStack[i];\n\n    if (lastCommentWS.start === node.end) {\n      lastCommentWS.leadingNode = node;\n      i--;\n    }\n\n    const { start: nodeStart } = node;\n    // invariant: for all 0 <= j <= i, let c = commentStack[j], c must satisfy c.end < node.end\n    for (; i >= 0; i--) {\n      const commentWS = commentStack[i];\n      const commentEnd = commentWS.end;\n      if (commentEnd > nodeStart) {\n        // by definition of commentWhiteSpace, this implies commentWS.start > nodeStart\n        // so node can be a containingNode candidate. At this time we can finalize the comment\n        // whitespace, because\n        // 1) its leadingNode or trailingNode, if exists, will not change\n        // 2) its containingNode have been assigned and will not change because it is the\n        //    innermost minimal-sized AST node\n        commentWS.containingNode = node;\n        this.finalizeComment(commentWS);\n        commentStack.splice(i, 1);\n      } else {\n        if (commentEnd === nodeStart) {\n          commentWS.trailingNode = node;\n        }\n        // stop the loop when commentEnd <= nodeStart\n        break;\n      }\n    }\n  }\n\n  /**\n   * Assign the comments of comment whitespaces to related AST nodes.\n   * Also adjust innerComments following trailing comma.\n   */\n  finalizeComment(commentWS: CommentWhitespace) {\n    const { comments } = commentWS;\n    if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {\n      if (commentWS.leadingNode !== null) {\n        setTrailingComments(commentWS.leadingNode, comments);\n      }\n      if (commentWS.trailingNode !== null) {\n        setLeadingComments(commentWS.trailingNode, comments);\n      }\n    } else {\n      /*:: invariant(commentWS.containingNode !== null) */\n      const { containingNode: node, start: commentStart } = commentWS;\n      if (\n        this.input.charCodeAt(this.offsetToSourcePos(commentStart) - 1) ===\n        charCodes.comma\n      ) {\n        // If a commentWhitespace follows a comma and the containingNode allows\n        // list structures with trailing comma, merge it to the trailingComment\n        // of the last non-null list element\n        switch (node.type) {\n          case \"ObjectExpression\":\n          case \"ObjectPattern\":\n          case \"RecordExpression\":\n            adjustInnerComments(node, node.properties, commentWS);\n            break;\n          case \"CallExpression\":\n          case \"OptionalCallExpression\":\n            adjustInnerComments(node, node.arguments, commentWS);\n            break;\n          case \"ImportExpression\":\n            adjustInnerComments(\n              node,\n              [node.source, node.options ?? null],\n              commentWS,\n            );\n            break;\n          case \"FunctionDeclaration\":\n          case \"FunctionExpression\":\n          case \"ArrowFunctionExpression\":\n          case \"ObjectMethod\":\n          case \"ClassMethod\":\n          case \"ClassPrivateMethod\":\n            adjustInnerComments(node, node.params, commentWS);\n            break;\n          case \"ArrayExpression\":\n          case \"ArrayPattern\":\n          case \"TupleExpression\":\n            adjustInnerComments(node, node.elements, commentWS);\n            break;\n          case \"ExportNamedDeclaration\":\n          case \"ImportDeclaration\":\n            adjustInnerComments(node, node.specifiers, commentWS);\n            break;\n          case \"TSEnumDeclaration\":\n            if (!process.env.BABEL_8_BREAKING) {\n              adjustInnerComments(node, node.members, commentWS);\n            } else {\n              setInnerComments(node, comments);\n            }\n            break;\n          case \"TSEnumBody\":\n            adjustInnerComments(node, node.members, commentWS);\n            break;\n          default: {\n            setInnerComments(node, comments);\n          }\n        }\n      } else {\n        setInnerComments(node, comments);\n      }\n    }\n  }\n\n  /**\n   * Drains remaining commentStack and applies finalizeComment\n   * to each comment whitespace. Used only in parseExpression\n   * where the top level AST node is _not_ Program\n   * {@see {@link CommentsParser#finalizeComment}}\n   */\n  finalizeRemainingComments() {\n    const { commentStack } = this.state;\n    for (let i = commentStack.length - 1; i >= 0; i--) {\n      this.finalizeComment(commentStack[i]);\n    }\n    this.state.commentStack = [];\n  }\n\n  /* eslint-disable no-irregular-whitespace */\n  /**\n   * Reset previous node trailing comments. Used in object / class\n   * property parsing. We parse `async`, `static`, `set` and `get`\n   * as an identifier but may reinterpret it into an async/static/accessor\n   * method later. In this case the identifier is not part of the AST and we\n   * should sync the knowledge to commentStacks\n   *\n   * For example, when parsing\n   * ```\n   * async /* 1 *​/ function f() {}\n   * ```\n   * the comment whitespace `/* 1 *​/` has leading node Identifier(async). When\n   * we see the function token, we create a Function node and mark `/* 1 *​/` as\n   * inner comments. So `/* 1 *​/` should be detached from the Identifier node.\n   *\n   * @param node the last finished AST node _before_ current token\n   */\n  /* eslint-enable no-irregular-whitespace */\n  resetPreviousNodeTrailingComments(node: Node) {\n    const { commentStack } = this.state;\n    const { length } = commentStack;\n    if (length === 0) return;\n    const commentWS = commentStack[length - 1];\n    if (commentWS.leadingNode === node) {\n      commentWS.leadingNode = null;\n    }\n  }\n\n  /**\n   * Attach a node to the comment whitespaces right before/after\n   * the given range.\n   *\n   * This is used to properly attach comments around parenthesized\n   * expressions as leading/trailing comments of the inner expression.\n   */\n  takeSurroundingComments(node: Node, start: number, end: number) {\n    const { commentStack } = this.state;\n    const commentStackLength = commentStack.length;\n    if (commentStackLength === 0) return;\n    let i = commentStackLength - 1;\n\n    for (; i >= 0; i--) {\n      const commentWS = commentStack[i];\n      const commentEnd = commentWS.end;\n      const commentStart = commentWS.start;\n\n      if (commentStart === end) {\n        commentWS.leadingNode = node;\n      } else if (commentEnd === start) {\n        commentWS.trailingNode = node;\n      } else if (commentEnd < start) {\n        break;\n      }\n    }\n  }\n}\n","import type { Options } from \"../options.ts\";\nimport type { CommentWhitespace } from \"../parser/comments\";\nimport { Position } from \"../util/location.ts\";\n\nimport { types as ct, type TokContext } from \"./context.ts\";\nimport { tt, type TokenType } from \"./types.ts\";\nimport type { Errors } from \"../parse-error.ts\";\nimport type { ParseError } from \"../parse-error.ts\";\n\nexport type DeferredStrictError =\n  | typeof Errors.StrictNumericEscape\n  | typeof Errors.StrictOctalLiteral;\n\ntype TopicContextState = {\n  // When a topic binding has been currently established,\n  // then this is 1. Otherwise, it is 0. This is forwards compatible\n  // with a future plugin for multiple lexical topics.\n  maxNumOfResolvableTopics: number;\n  // When a topic binding has been currently established, and if that binding\n  // has been used as a topic reference `#`, then this is 0. Otherwise, it is\n  // `null`. This is forwards compatible with a future plugin for multiple\n  // lexical topics.\n  maxTopicIndex: null | 0;\n};\n\nexport const enum LoopLabelKind {\n  Loop = 1,\n  Switch = 2,\n}\n\ndeclare const bit: import(\"../../../../scripts/babel-plugin-bit-decorator/types.d.ts\").BitDecorator<State>;\n\nexport default class State {\n  @bit.storage flags: number;\n\n  @bit accessor strict = false;\n\n  startIndex: number;\n  curLine: number;\n  lineStart: number;\n\n  // And, if locations are used, the {line, column} object\n  // corresponding to those offsets\n  startLoc: Position;\n  endLoc: Position;\n\n  init({\n    strictMode,\n    sourceType,\n    startIndex,\n    startLine,\n    startColumn,\n  }: Options): void {\n    this.strict =\n      strictMode === false\n        ? false\n        : strictMode === true\n          ? true\n          : sourceType === \"module\";\n\n    this.startIndex = startIndex;\n    this.curLine = startLine;\n    this.lineStart = -startColumn;\n    this.startLoc = this.endLoc = new Position(\n      startLine,\n      startColumn,\n      startIndex,\n    );\n  }\n\n  errors: ParseError<any>[] = [];\n\n  // Used to signify the start of a potential arrow function\n  potentialArrowAt: number = -1;\n\n  // Used to signify the start of an expression which looks like a\n  // typed arrow function, but it isn't\n  // e.g. a ? (b) : c => d\n  //          ^\n  noArrowAt: number[] = [];\n\n  // Used to signify the start of an expression whose params, if it looks like\n  // an arrow function, shouldn't be converted to assignable nodes.\n  // This is used to defer the validation of typed arrow functions inside\n  // conditional expressions.\n  // e.g. a ? (b) : c => d\n  //          ^\n  noArrowParamsConversionAt: number[] = [];\n\n  // Flags to track\n  @bit accessor maybeInArrowParameters = false;\n  @bit accessor inType = false;\n  @bit accessor noAnonFunctionType = false;\n  @bit accessor hasFlowComment = false;\n  @bit accessor isAmbientContext = false;\n  @bit accessor inAbstractClass = false;\n  @bit accessor inDisallowConditionalTypesContext = false;\n\n  // For the Hack-style pipelines plugin\n  topicContext: TopicContextState = {\n    maxNumOfResolvableTopics: 0,\n    maxTopicIndex: null,\n  };\n\n  // For the F#-style pipelines plugin\n  @bit accessor soloAwait = false;\n  @bit accessor inFSharpPipelineDirectBody = false;\n\n  // Labels in scope.\n  labels: Array<{\n    kind: LoopLabelKind;\n    name?: string | null;\n    statementStart?: number;\n  }> = [];\n\n  commentsLen = 0;\n  // Comment attachment store\n  commentStack: Array<CommentWhitespace> = [];\n\n  // The current position of the tokenizer in the input.\n  pos: number = 0;\n\n  // Properties of the current token:\n  // Its type\n  type: TokenType = tt.eof;\n\n  // For tokens that include more information than their type, the value\n  value: any = null;\n\n  // Its start and end offset\n  start: number = 0;\n  end: number = 0;\n\n  // Position information for the previous token\n  // this is initialized when generating the second token.\n  lastTokEndLoc: Position = null;\n  // this is initialized when generating the second token.\n  lastTokStartLoc: Position = null;\n\n  // The context stack is used to track whether the apostrophe \"`\" starts\n  // or ends a string template\n  context: Array<TokContext> = [ct.brace];\n\n  // Used to track whether a JSX element is allowed to form\n  @bit accessor canStartJSXElement = true;\n\n  // Used to signal to callers of `readWord1` whether the word\n  // contained any escape sequences. This is needed because words with\n  // escape sequences must not be interpreted as keywords.\n  @bit accessor containsEsc = false;\n\n  // Used to track invalid escape sequences in template literals,\n  // that must be reported if the template is not tagged.\n  firstInvalidTemplateEscapePos: null | Position = null;\n\n  @bit accessor hasTopLevelAwait = false;\n\n  // This property is used to track the following errors\n  // - StrictNumericEscape\n  // - StrictOctalLiteral\n  //\n  // in a literal that occurs prior to/immediately after a \"use strict\" directive.\n\n  // todo(JLHwung): set strictErrors to null and avoid recording string errors\n  // after a non-directive is parsed\n  strictErrors: Map<number, [DeferredStrictError, Position]> = new Map();\n\n  // Tokens length in token store\n  tokensLength: number = 0;\n\n  /**\n   * When we add a new property, we must manually update the `clone` method\n   * @see State#clone\n   */\n\n  curPosition(): Position {\n    return new Position(\n      this.curLine,\n      this.pos - this.lineStart,\n      this.pos + this.startIndex,\n    );\n  }\n\n  clone(): State {\n    const state = new State();\n    state.flags = this.flags;\n    state.startIndex = this.startIndex;\n    state.curLine = this.curLine;\n    state.lineStart = this.lineStart;\n    state.startLoc = this.startLoc;\n    state.endLoc = this.endLoc;\n    state.errors = this.errors.slice();\n    state.potentialArrowAt = this.potentialArrowAt;\n    state.noArrowAt = this.noArrowAt.slice();\n    state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice();\n    state.topicContext = this.topicContext;\n    state.labels = this.labels.slice();\n    state.commentsLen = this.commentsLen;\n    state.commentStack = this.commentStack.slice();\n    state.pos = this.pos;\n    state.type = this.type;\n    state.value = this.value;\n    state.start = this.start;\n    state.end = this.end;\n    state.lastTokEndLoc = this.lastTokEndLoc;\n    state.lastTokStartLoc = this.lastTokStartLoc;\n    state.context = this.context.slice();\n    state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos;\n    state.strictErrors = this.strictErrors;\n    state.tokensLength = this.tokensLength;\n\n    return state;\n  }\n}\n\nexport type LookaheadState = {\n  pos: number;\n  value: any;\n  type: TokenType;\n  start: number;\n  end: number;\n  context: TokContext[];\n  startLoc: Position;\n  lastTokEndLoc: Position;\n  curLine: number;\n  lineStart: number;\n  curPosition: State[\"curPosition\"];\n  /* Used only in readToken_mult_modulo */\n  inType: boolean;\n  // These boolean properties are not initialized in createLookaheadState()\n  // instead they will only be set by the tokenizer\n  containsEsc?: boolean;\n};\n","// We inline this package\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport * as charCodes from \"charcodes\";\n\n// The following character codes are forbidden from being\n// an immediate sibling of NumericLiteralSeparator _\nconst forbiddenNumericSeparatorSiblings = {\n  decBinOct: new Set<number>([\n    charCodes.dot,\n    charCodes.uppercaseB,\n    charCodes.uppercaseE,\n    charCodes.uppercaseO,\n    charCodes.underscore, // multiple separators are not allowed\n    charCodes.lowercaseB,\n    charCodes.lowercaseE,\n    charCodes.lowercaseO,\n  ]),\n  hex: new Set<number>([\n    charCodes.dot,\n    charCodes.uppercaseX,\n    charCodes.underscore, // multiple separators are not allowed\n    charCodes.lowercaseX,\n  ]),\n};\n\nconst isAllowedNumericSeparatorSibling = {\n  // 0 - 1\n  bin: (ch: number) => ch === charCodes.digit0 || ch === charCodes.digit1,\n\n  // 0 - 7\n  oct: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit7,\n\n  // 0 - 9\n  dec: (ch: number) => ch >= charCodes.digit0 && ch <= charCodes.digit9,\n\n  // 0 - 9, A - F, a - f,\n  hex: (ch: number) =>\n    (ch >= charCodes.digit0 && ch <= charCodes.digit9) ||\n    (ch >= charCodes.uppercaseA && ch <= charCodes.uppercaseF) ||\n    (ch >= charCodes.lowercaseA && ch <= charCodes.lowercaseF),\n};\n\nexport type StringContentsErrorHandlers = EscapedCharErrorHandlers & {\n  unterminated(\n    initialPos: number,\n    initialLineStart: number,\n    initialCurLine: number,\n  ): void;\n};\n\nexport function readStringContents(\n  type: \"single\" | \"double\" | \"template\",\n  input: string,\n  pos: number,\n  lineStart: number,\n  curLine: number,\n  errors: StringContentsErrorHandlers,\n) {\n  const initialPos = pos;\n  const initialLineStart = lineStart;\n  const initialCurLine = curLine;\n\n  let out = \"\";\n  let firstInvalidLoc = null;\n  let chunkStart = pos;\n  const { length } = input;\n  for (;;) {\n    if (pos >= length) {\n      errors.unterminated(initialPos, initialLineStart, initialCurLine);\n      out += input.slice(chunkStart, pos);\n      break;\n    }\n    const ch = input.charCodeAt(pos);\n    if (isStringEnd(type, ch, input, pos)) {\n      out += input.slice(chunkStart, pos);\n      break;\n    }\n    if (ch === charCodes.backslash) {\n      out += input.slice(chunkStart, pos);\n      const res = readEscapedChar(\n        input,\n        pos,\n        lineStart,\n        curLine,\n        type === \"template\",\n        errors,\n      );\n      if (res.ch === null && !firstInvalidLoc) {\n        firstInvalidLoc = { pos, lineStart, curLine };\n      } else {\n        out += res.ch;\n      }\n      ({ pos, lineStart, curLine } = res);\n      chunkStart = pos;\n    } else if (\n      ch === charCodes.lineSeparator ||\n      ch === charCodes.paragraphSeparator\n    ) {\n      ++pos;\n      ++curLine;\n      lineStart = pos;\n    } else if (ch === charCodes.lineFeed || ch === charCodes.carriageReturn) {\n      if (type === \"template\") {\n        out += input.slice(chunkStart, pos) + \"\\n\";\n        ++pos;\n        if (\n          ch === charCodes.carriageReturn &&\n          input.charCodeAt(pos) === charCodes.lineFeed\n        ) {\n          ++pos;\n        }\n        ++curLine;\n        chunkStart = lineStart = pos;\n      } else {\n        errors.unterminated(initialPos, initialLineStart, initialCurLine);\n      }\n    } else {\n      ++pos;\n    }\n  }\n  return process.env.BABEL_8_BREAKING\n    ? { pos, str: out, firstInvalidLoc, lineStart, curLine }\n    : {\n        pos,\n        str: out,\n        firstInvalidLoc,\n        lineStart,\n        curLine,\n        containsInvalid: !!firstInvalidLoc,\n      };\n}\n\nfunction isStringEnd(\n  type: \"single\" | \"double\" | \"template\",\n  ch: number,\n  input: string,\n  pos: number,\n) {\n  if (type === \"template\") {\n    return (\n      ch === charCodes.graveAccent ||\n      (ch === charCodes.dollarSign &&\n        input.charCodeAt(pos + 1) === charCodes.leftCurlyBrace)\n    );\n  }\n  return (\n    ch === (type === \"double\" ? charCodes.quotationMark : charCodes.apostrophe)\n  );\n}\n\ntype EscapedCharErrorHandlers = HexCharErrorHandlers &\n  CodePointErrorHandlers & {\n    strictNumericEscape(pos: number, lineStart: number, curLine: number): void;\n  };\n\nfunction readEscapedChar(\n  input: string,\n  pos: number,\n  lineStart: number,\n  curLine: number,\n  inTemplate: boolean,\n  errors: EscapedCharErrorHandlers,\n) {\n  const throwOnInvalid = !inTemplate;\n  pos++; // skip '\\'\n\n  const res = (ch: string | null) => ({ pos, ch, lineStart, curLine });\n\n  const ch = input.charCodeAt(pos++);\n  switch (ch) {\n    case charCodes.lowercaseN:\n      return res(\"\\n\");\n    case charCodes.lowercaseR:\n      return res(\"\\r\");\n    case charCodes.lowercaseX: {\n      let code;\n      ({ code, pos } = readHexChar(\n        input,\n        pos,\n        lineStart,\n        curLine,\n        2,\n        false,\n        throwOnInvalid,\n        errors,\n      ));\n      return res(code === null ? null : String.fromCharCode(code));\n    }\n    case charCodes.lowercaseU: {\n      let code;\n      ({ code, pos } = readCodePoint(\n        input,\n        pos,\n        lineStart,\n        curLine,\n        throwOnInvalid,\n        errors,\n      ));\n      return res(code === null ? null : String.fromCodePoint(code));\n    }\n    case charCodes.lowercaseT:\n      return res(\"\\t\");\n    case charCodes.lowercaseB:\n      return res(\"\\b\");\n    case charCodes.lowercaseV:\n      return res(\"\\u000b\");\n    case charCodes.lowercaseF:\n      return res(\"\\f\");\n    case charCodes.carriageReturn:\n      if (input.charCodeAt(pos) === charCodes.lineFeed) {\n        ++pos;\n      }\n    // fall through\n    case charCodes.lineFeed:\n      lineStart = pos;\n      ++curLine;\n    // fall through\n    case charCodes.lineSeparator:\n    case charCodes.paragraphSeparator:\n      return res(\"\");\n    case charCodes.digit8:\n    case charCodes.digit9:\n      if (inTemplate) {\n        return res(null);\n      } else {\n        errors.strictNumericEscape(pos - 1, lineStart, curLine);\n      }\n    // fall through\n    default:\n      if (ch >= charCodes.digit0 && ch <= charCodes.digit7) {\n        const startPos = pos - 1;\n        const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));\n\n        let octalStr = match[0];\n\n        let octal = parseInt(octalStr, 8);\n        if (octal > 255) {\n          octalStr = octalStr.slice(0, -1);\n          octal = parseInt(octalStr, 8);\n        }\n        pos += octalStr.length - 1;\n        const next = input.charCodeAt(pos);\n        if (\n          octalStr !== \"0\" ||\n          next === charCodes.digit8 ||\n          next === charCodes.digit9\n        ) {\n          if (inTemplate) {\n            return res(null);\n          } else {\n            errors.strictNumericEscape(startPos, lineStart, curLine);\n          }\n        }\n\n        return res(String.fromCharCode(octal));\n      }\n\n      return res(String.fromCharCode(ch));\n  }\n}\n\ntype HexCharErrorHandlers = IntErrorHandlers & {\n  invalidEscapeSequence(pos: number, lineStart: number, curLine: number): void;\n};\n\n// Used to read character escape sequences ('\\x', '\\u').\nfunction readHexChar(\n  input: string,\n  pos: number,\n  lineStart: number,\n  curLine: number,\n  len: number,\n  forceLen: boolean,\n  throwOnInvalid: boolean,\n  errors: HexCharErrorHandlers,\n) {\n  const initialPos = pos;\n  let n;\n  ({ n, pos } = readInt(\n    input,\n    pos,\n    lineStart,\n    curLine,\n    16,\n    len,\n    forceLen,\n    false,\n    errors,\n    /* bailOnError */ !throwOnInvalid,\n  ));\n  if (n === null) {\n    if (throwOnInvalid) {\n      errors.invalidEscapeSequence(initialPos, lineStart, curLine);\n    } else {\n      pos = initialPos - 1;\n    }\n  }\n  return { code: n, pos };\n}\n\nexport type IntErrorHandlers = {\n  numericSeparatorInEscapeSequence(\n    pos: number,\n    lineStart: number,\n    curLine: number,\n  ): void;\n  unexpectedNumericSeparator(\n    pos: number,\n    lineStart: number,\n    curLine: number,\n  ): void;\n  // It can return \"true\" to indicate that the error was handled\n  // and the int parsing should continue.\n  invalidDigit(\n    pos: number,\n    lineStart: number,\n    curLine: number,\n    radix: number,\n  ): boolean;\n};\n\nexport function readInt(\n  input: string,\n  pos: number,\n  lineStart: number,\n  curLine: number,\n  radix: number,\n  len: number | undefined,\n  forceLen: boolean,\n  allowNumSeparator: boolean | \"bail\",\n  errors: IntErrorHandlers,\n  bailOnError: boolean,\n) {\n  const start = pos;\n  const forbiddenSiblings =\n    radix === 16\n      ? forbiddenNumericSeparatorSiblings.hex\n      : forbiddenNumericSeparatorSiblings.decBinOct;\n  const isAllowedSibling =\n    radix === 16\n      ? isAllowedNumericSeparatorSibling.hex\n      : radix === 10\n        ? isAllowedNumericSeparatorSibling.dec\n        : radix === 8\n          ? isAllowedNumericSeparatorSibling.oct\n          : isAllowedNumericSeparatorSibling.bin;\n\n  let invalid = false;\n  let total = 0;\n\n  for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {\n    const code = input.charCodeAt(pos);\n    let val;\n\n    if (code === charCodes.underscore && allowNumSeparator !== \"bail\") {\n      const prev = input.charCodeAt(pos - 1);\n      const next = input.charCodeAt(pos + 1);\n\n      if (!allowNumSeparator) {\n        if (bailOnError) return { n: null, pos };\n        errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);\n      } else if (\n        Number.isNaN(next) ||\n        !isAllowedSibling(next) ||\n        forbiddenSiblings.has(prev) ||\n        forbiddenSiblings.has(next)\n      ) {\n        if (bailOnError) return { n: null, pos };\n        errors.unexpectedNumericSeparator(pos, lineStart, curLine);\n      }\n\n      // Ignore this _ character\n      ++pos;\n      continue;\n    }\n\n    if (code >= charCodes.lowercaseA) {\n      val = code - charCodes.lowercaseA + charCodes.lineFeed;\n    } else if (code >= charCodes.uppercaseA) {\n      val = code - charCodes.uppercaseA + charCodes.lineFeed;\n    } else if (charCodes.isDigit(code)) {\n      val = code - charCodes.digit0; // 0-9\n    } else {\n      val = Infinity;\n    }\n    if (val >= radix) {\n      // If we found a digit which is too big, errors.invalidDigit can return true to avoid\n      // breaking the loop (this is used for error recovery).\n      if (val <= 9 && bailOnError) {\n        return { n: null, pos };\n      } else if (\n        val <= 9 &&\n        errors.invalidDigit(pos, lineStart, curLine, radix)\n      ) {\n        val = 0;\n      } else if (forceLen) {\n        val = 0;\n        invalid = true;\n      } else {\n        break;\n      }\n    }\n    ++pos;\n    total = total * radix + val;\n  }\n  if (pos === start || (len != null && pos - start !== len) || invalid) {\n    return { n: null, pos };\n  }\n\n  return { n: total, pos };\n}\n\nexport type CodePointErrorHandlers = HexCharErrorHandlers & {\n  invalidCodePoint(pos: number, lineStart: number, curLine: number): void;\n};\n\nexport function readCodePoint(\n  input: string,\n  pos: number,\n  lineStart: number,\n  curLine: number,\n  throwOnInvalid: boolean,\n  errors: CodePointErrorHandlers,\n) {\n  const ch = input.charCodeAt(pos);\n  let code;\n\n  if (ch === charCodes.leftCurlyBrace) {\n    ++pos;\n    ({ code, pos } = readHexChar(\n      input,\n      pos,\n      lineStart,\n      curLine,\n      input.indexOf(\"}\", pos) - pos,\n      true,\n      throwOnInvalid,\n      errors,\n    ));\n    ++pos;\n    if (code !== null && code > 0x10ffff) {\n      if (throwOnInvalid) {\n        errors.invalidCodePoint(pos, lineStart, curLine);\n      } else {\n        return { code: null, pos };\n      }\n    }\n  } else {\n    ({ code, pos } = readHexChar(\n      input,\n      pos,\n      lineStart,\n      curLine,\n      4,\n      false,\n      throwOnInvalid,\n      errors,\n    ));\n  }\n  return { code, pos };\n}\n","/*:: declare var invariant; */\n\nimport { OptionFlags, type Options } from \"../options.ts\";\nimport {\n  Position,\n  SourceLocation,\n  createPositionWithColumnOffset,\n} from \"../util/location.ts\";\nimport CommentsParser, { type CommentWhitespace } from \"../parser/comments.ts\";\nimport type * as N from \"../types.ts\";\nimport * as charCodes from \"charcodes\";\nimport { isIdentifierStart, isIdentifierChar } from \"../util/identifier.ts\";\nimport {\n  tokenIsKeyword,\n  tokenLabelName,\n  tt,\n  keywords as keywordTypes,\n  type TokenType,\n} from \"./types.ts\";\nimport type { TokContext } from \"./context.ts\";\nimport {\n  Errors,\n  type ParseError,\n  type ParseErrorConstructor,\n} from \"../parse-error.ts\";\nimport {\n  lineBreakG,\n  isNewLine,\n  isWhitespace,\n  skipWhiteSpace,\n  skipWhiteSpaceInLine,\n} from \"../util/whitespace.ts\";\nimport State from \"./state.ts\";\nimport type { LookaheadState, DeferredStrictError } from \"./state.ts\";\nimport type { Undone } from \"../parser/node.ts\";\nimport type { Node } from \"../types.ts\";\n\nimport {\n  readInt,\n  readCodePoint,\n  readStringContents,\n  type IntErrorHandlers,\n  type CodePointErrorHandlers,\n  type StringContentsErrorHandlers,\n} from \"@babel/helper-string-parser\";\n\nimport type { Plugin } from \"../typings.ts\";\n\nfunction buildPosition(pos: number, lineStart: number, curLine: number) {\n  return new Position(curLine, pos - lineStart, pos);\n}\n\nconst VALID_REGEX_FLAGS = new Set([\n  charCodes.lowercaseG,\n  charCodes.lowercaseM,\n  charCodes.lowercaseS,\n  charCodes.lowercaseI,\n  charCodes.lowercaseY,\n  charCodes.lowercaseU,\n  charCodes.lowercaseD,\n  charCodes.lowercaseV,\n]);\n\n// Object type used to represent tokens. Note that normally, tokens\n// simply exist as properties on the parser object. This is only\n// used for the onToken callback and the external tokenizer.\n\nexport class Token {\n  constructor(state: State) {\n    const startIndex = state.startIndex || 0;\n    this.type = state.type;\n    this.value = state.value;\n    this.start = startIndex + state.start;\n    this.end = startIndex + state.end;\n    this.loc = new SourceLocation(state.startLoc, state.endLoc);\n  }\n\n  declare type: TokenType;\n  declare value: any;\n  declare start: number;\n  declare end: number;\n  declare loc: SourceLocation;\n}\n\n// ## Tokenizer\n\nexport default abstract class Tokenizer extends CommentsParser {\n  isLookahead: boolean;\n\n  // Token store.\n  tokens: Array<Token | N.Comment> = [];\n\n  constructor(options: Options, input: string) {\n    super();\n    this.state = new State();\n    this.state.init(options);\n    this.input = input;\n    this.length = input.length;\n    this.comments = [];\n    this.isLookahead = false;\n  }\n\n  pushToken(token: Token | N.Comment) {\n    // Pop out invalid tokens trapped by try-catch parsing.\n    // Those parsing branches are mainly created by typescript and flow plugins.\n    this.tokens.length = this.state.tokensLength;\n    this.tokens.push(token);\n    ++this.state.tokensLength;\n  }\n\n  // Move to the next token\n\n  next(): void {\n    this.checkKeywordEscapes();\n    if (this.optionFlags & OptionFlags.Tokens) {\n      this.pushToken(new Token(this.state));\n    }\n\n    this.state.lastTokEndLoc = this.state.endLoc;\n    this.state.lastTokStartLoc = this.state.startLoc;\n    this.nextToken();\n  }\n\n  eat(type: TokenType): boolean {\n    if (this.match(type)) {\n      this.next();\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  /**\n   * Whether current token matches given type\n   */\n  match(type: TokenType): boolean {\n    return this.state.type === type;\n  }\n\n  /**\n   * Create a LookaheadState from current parser state\n   */\n  createLookaheadState(state: State): LookaheadState {\n    return {\n      pos: state.pos,\n      value: null,\n      type: state.type,\n      start: state.start,\n      end: state.end,\n      context: [this.curContext()],\n      inType: state.inType,\n      startLoc: state.startLoc,\n      lastTokEndLoc: state.lastTokEndLoc,\n      curLine: state.curLine,\n      lineStart: state.lineStart,\n      curPosition: state.curPosition,\n    };\n  }\n\n  /**\n   * lookahead peeks the next token, skipping changes to token context and\n   * comment stack. For performance it returns a limited LookaheadState\n   * instead of full parser state.\n   *\n   * The { column, line } Loc info is not included in lookahead since such usage\n   * is rare. Although it may return other location properties e.g. `curLine` and\n   * `lineStart`, these properties are not listed in the LookaheadState interface\n   * and thus the returned value is _NOT_ reliable.\n   *\n   * The tokenizer should make best efforts to avoid using any parser state\n   * other than those defined in LookaheadState\n   */\n  lookahead(): LookaheadState {\n    const old = this.state;\n    // @ts-expect-error For performance we use a simplified tokenizer state structure\n    this.state = this.createLookaheadState(old);\n\n    this.isLookahead = true;\n    this.nextToken();\n    this.isLookahead = false;\n\n    const curr = this.state;\n    this.state = old;\n    return curr;\n  }\n\n  nextTokenStart(): number {\n    return this.nextTokenStartSince(this.state.pos);\n  }\n\n  nextTokenStartSince(pos: number): number {\n    skipWhiteSpace.lastIndex = pos;\n    return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;\n  }\n\n  lookaheadCharCode(): number {\n    return this.lookaheadCharCodeSince(this.state.pos);\n  }\n\n  lookaheadCharCodeSince(pos: number): number {\n    return this.input.charCodeAt(this.nextTokenStartSince(pos));\n  }\n\n  /**\n   * Similar to nextToken, but it will stop at line break when it is seen before the next token\n   *\n   * @returns {number} position of the next token start or line break, whichever is seen first.\n   * @memberof Tokenizer\n   */\n  nextTokenInLineStart(): number {\n    return this.nextTokenInLineStartSince(this.state.pos);\n  }\n\n  nextTokenInLineStartSince(pos: number): number {\n    skipWhiteSpaceInLine.lastIndex = pos;\n    return skipWhiteSpaceInLine.test(this.input)\n      ? skipWhiteSpaceInLine.lastIndex\n      : pos;\n  }\n\n  /**\n   * Similar to lookaheadCharCode, but it will return the char code of line break if it is\n   * seen before the next token\n   *\n   * @returns {number} char code of the next token start or line break, whichever is seen first.\n   * @memberof Tokenizer\n   */\n  lookaheadInLineCharCode(): number {\n    return this.input.charCodeAt(this.nextTokenInLineStart());\n  }\n\n  codePointAtPos(pos: number): number {\n    // The implementation is based on\n    // https://source.chromium.org/chromium/chromium/src/+/master:v8/src/builtins/builtins-string-gen.cc;l=1455;drc=221e331b49dfefadbc6fa40b0c68e6f97606d0b3;bpv=0;bpt=1\n    // We reimplement `codePointAt` because `codePointAt` is a V8 builtin which is not inlined by TurboFan (as of M91)\n    // since `input` is mostly ASCII, an inlined `charCodeAt` wins here\n    let cp = this.input.charCodeAt(pos);\n    if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {\n      const trail = this.input.charCodeAt(pos);\n      if ((trail & 0xfc00) === 0xdc00) {\n        cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);\n      }\n    }\n    return cp;\n  }\n\n  // Toggle strict mode. Re-reads the next number or string to please\n  // pedantic tests (`\"use strict\"; 010;` should fail).\n\n  setStrict(strict: boolean): void {\n    this.state.strict = strict;\n    if (strict) {\n      // Throw an error for any string decimal escape found before/immediately\n      // after a \"use strict\" directive. Strict mode will be set at parse\n      // time for any literals that occur after the next node of the strict\n      // directive.\n      this.state.strictErrors.forEach(([toParseError, at]) =>\n        this.raise(toParseError, at),\n      );\n      this.state.strictErrors.clear();\n    }\n  }\n\n  curContext(): TokContext {\n    return this.state.context[this.state.context.length - 1];\n  }\n\n  // Read a single token, updating the parser object's token-related properties.\n  nextToken(): void {\n    this.skipSpace();\n    this.state.start = this.state.pos;\n    if (!this.isLookahead) this.state.startLoc = this.state.curPosition();\n    if (this.state.pos >= this.length) {\n      this.finishToken(tt.eof);\n      return;\n    }\n\n    this.getTokenFromCode(this.codePointAtPos(this.state.pos));\n  }\n\n  // Skips a block comment, whose end is marked by commentEnd.\n  // *-/ is used by the Flow plugin, when parsing block comments nested\n  // inside Flow comments.\n  skipBlockComment(commentEnd: \"*/\" | \"*-/\"): N.CommentBlock | undefined {\n    let startLoc;\n    if (!this.isLookahead) startLoc = this.state.curPosition();\n    const start = this.state.pos;\n    const end = this.input.indexOf(commentEnd, start + 2);\n    if (end === -1) {\n      // We have to call this again here because startLoc may not be set...\n      // This seems to be for performance reasons:\n      // https://github.com/babel/babel/commit/acf2a10899f696a8aaf34df78bf9725b5ea7f2da\n      throw this.raise(Errors.UnterminatedComment, this.state.curPosition());\n    }\n\n    this.state.pos = end + commentEnd.length;\n    lineBreakG.lastIndex = start + 2;\n    while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {\n      ++this.state.curLine;\n      this.state.lineStart = lineBreakG.lastIndex;\n    }\n\n    // If we are doing a lookahead right now we need to advance the position (above code)\n    // but we do not want to push the comment to the state.\n    if (this.isLookahead) return;\n    /*:: invariant(startLoc) */\n\n    const comment: N.CommentBlock = {\n      type: \"CommentBlock\",\n      value: this.input.slice(start + 2, end),\n      start: this.sourceToOffsetPos(start),\n      end: this.sourceToOffsetPos(end + commentEnd.length),\n      loc: new SourceLocation(startLoc, this.state.curPosition()),\n    };\n    if (this.optionFlags & OptionFlags.Tokens) this.pushToken(comment);\n    return comment;\n  }\n\n  skipLineComment(startSkip: number): N.CommentLine | undefined {\n    const start = this.state.pos;\n    let startLoc;\n    if (!this.isLookahead) startLoc = this.state.curPosition();\n    let ch = this.input.charCodeAt((this.state.pos += startSkip));\n    if (this.state.pos < this.length) {\n      while (!isNewLine(ch) && ++this.state.pos < this.length) {\n        ch = this.input.charCodeAt(this.state.pos);\n      }\n    }\n\n    // If we are doing a lookahead right now we need to advance the position (above code)\n    // but we do not want to push the comment to the state.\n    if (this.isLookahead) return;\n\n    const end = this.state.pos;\n    const value = this.input.slice(start + startSkip, end);\n\n    const comment: N.CommentLine = {\n      type: \"CommentLine\",\n      value,\n      start: this.sourceToOffsetPos(start),\n      end: this.sourceToOffsetPos(end),\n      loc: new SourceLocation(startLoc, this.state.curPosition()),\n    };\n    if (this.optionFlags & OptionFlags.Tokens) this.pushToken(comment);\n    return comment;\n  }\n\n  // Called at the start of the parse and after every token. Skips\n  // whitespace and comments, and.\n\n  skipSpace(): void {\n    const spaceStart = this.state.pos;\n    const comments: N.Comment[] =\n      this.optionFlags & OptionFlags.AttachComment ? [] : null;\n    loop: while (this.state.pos < this.length) {\n      const ch = this.input.charCodeAt(this.state.pos);\n      switch (ch) {\n        case charCodes.space:\n        case charCodes.nonBreakingSpace:\n        case charCodes.tab:\n          ++this.state.pos;\n          break;\n        case charCodes.carriageReturn:\n          if (\n            this.input.charCodeAt(this.state.pos + 1) === charCodes.lineFeed\n          ) {\n            ++this.state.pos;\n          }\n        // fall through\n        case charCodes.lineFeed:\n        case charCodes.lineSeparator:\n        case charCodes.paragraphSeparator:\n          ++this.state.pos;\n          ++this.state.curLine;\n          this.state.lineStart = this.state.pos;\n          break;\n\n        case charCodes.slash:\n          switch (this.input.charCodeAt(this.state.pos + 1)) {\n            case charCodes.asterisk: {\n              const comment = this.skipBlockComment(\"*/\");\n              if (comment !== undefined) {\n                this.addComment(comment);\n                comments?.push(comment);\n              }\n              break;\n            }\n\n            case charCodes.slash: {\n              const comment = this.skipLineComment(2);\n              if (comment !== undefined) {\n                this.addComment(comment);\n                comments?.push(comment);\n              }\n              break;\n            }\n\n            default:\n              break loop;\n          }\n          break;\n\n        default:\n          if (isWhitespace(ch)) {\n            ++this.state.pos;\n          } else if (\n            ch === charCodes.dash &&\n            !this.inModule &&\n            this.optionFlags & OptionFlags.AnnexB\n          ) {\n            const pos = this.state.pos;\n            if (\n              this.input.charCodeAt(pos + 1) === charCodes.dash &&\n              this.input.charCodeAt(pos + 2) === charCodes.greaterThan &&\n              (spaceStart === 0 || this.state.lineStart > spaceStart)\n            ) {\n              // A `-->` line comment\n              const comment = this.skipLineComment(3);\n              if (comment !== undefined) {\n                this.addComment(comment);\n                comments?.push(comment);\n              }\n            } else {\n              break loop;\n            }\n          } else if (\n            ch === charCodes.lessThan &&\n            !this.inModule &&\n            this.optionFlags & OptionFlags.AnnexB\n          ) {\n            const pos = this.state.pos;\n            if (\n              this.input.charCodeAt(pos + 1) === charCodes.exclamationMark &&\n              this.input.charCodeAt(pos + 2) === charCodes.dash &&\n              this.input.charCodeAt(pos + 3) === charCodes.dash\n            ) {\n              // `<!--`, an XML-style comment that should be interpreted as a line comment\n              const comment = this.skipLineComment(4);\n              if (comment !== undefined) {\n                this.addComment(comment);\n                comments?.push(comment);\n              }\n            } else {\n              break loop;\n            }\n          } else {\n            break loop;\n          }\n      }\n    }\n\n    if (comments?.length > 0) {\n      const end = this.state.pos;\n      const commentWhitespace: CommentWhitespace = {\n        start: this.sourceToOffsetPos(spaceStart),\n        end: this.sourceToOffsetPos(end),\n        comments,\n        leadingNode: null,\n        trailingNode: null,\n        containingNode: null,\n      };\n      this.state.commentStack.push(commentWhitespace);\n    }\n  }\n\n  // Called at the end of every token. Sets `end`, `val`, and\n  // maintains `context` and `canStartJSXElement`, and skips the space after\n  // the token, so that the next one's `start` will point at the\n  // right position.\n\n  finishToken(type: TokenType, val?: any): void {\n    this.state.end = this.state.pos;\n    this.state.endLoc = this.state.curPosition();\n    const prevType = this.state.type;\n    this.state.type = type;\n    this.state.value = val;\n\n    if (!this.isLookahead) {\n      this.updateContext(prevType);\n    }\n  }\n\n  replaceToken(type: TokenType): void {\n    this.state.type = type;\n    // @ts-expect-error the prevType of updateContext is required\n    // only when the new type is tt.slash/tt.jsxTagEnd\n    this.updateContext();\n  }\n\n  // ### Token reading\n\n  // This is the function that is called to fetch the next token. It\n  // is somewhat obscure, because it works in character codes rather\n  // than characters, and because operator parsing has been inlined\n  // into it.\n  //\n  // All in the name of speed.\n\n  // number sign is \"#\"\n  readToken_numberSign(): void {\n    if (this.state.pos === 0 && this.readToken_interpreter()) {\n      return;\n    }\n\n    const nextPos = this.state.pos + 1;\n    const next = this.codePointAtPos(nextPos);\n    if (next >= charCodes.digit0 && next <= charCodes.digit9) {\n      throw this.raise(\n        Errors.UnexpectedDigitAfterHash,\n        this.state.curPosition(),\n      );\n    }\n\n    if (\n      !process.env.BABEL_8_BREAKING &&\n      (next === charCodes.leftCurlyBrace ||\n        (next === charCodes.leftSquareBracket &&\n          this.hasPlugin(\"recordAndTuple\")))\n    ) {\n      // When we see `#{`, it is likely to be a hash record.\n      // However we don't yell at `#[` since users may intend to use \"computed private fields\",\n      // which is not allowed in the spec. Throwing expecting recordAndTuple is\n      // misleading\n      this.expectPlugin(\"recordAndTuple\");\n      if (\n        !process.env.BABEL_8_BREAKING &&\n        this.getPluginOption(\"recordAndTuple\", \"syntaxType\") === \"bar\"\n      ) {\n        throw this.raise(\n          next === charCodes.leftCurlyBrace\n            ? Errors.RecordExpressionHashIncorrectStartSyntaxType\n            : Errors.TupleExpressionHashIncorrectStartSyntaxType,\n          this.state.curPosition(),\n        );\n      }\n\n      this.state.pos += 2;\n      if (next === charCodes.leftCurlyBrace) {\n        // #{\n        this.finishToken(tt.braceHashL);\n      } else {\n        // #[\n        this.finishToken(tt.bracketHashL);\n      }\n    } else if (isIdentifierStart(next)) {\n      ++this.state.pos;\n      this.finishToken(tt.privateName, this.readWord1(next));\n    } else if (next === charCodes.backslash) {\n      ++this.state.pos;\n      this.finishToken(tt.privateName, this.readWord1());\n    } else {\n      this.finishOp(tt.hash, 1);\n    }\n  }\n\n  readToken_dot(): void {\n    const next = this.input.charCodeAt(this.state.pos + 1);\n    if (next >= charCodes.digit0 && next <= charCodes.digit9) {\n      this.readNumber(true);\n      return;\n    }\n\n    if (\n      next === charCodes.dot &&\n      this.input.charCodeAt(this.state.pos + 2) === charCodes.dot\n    ) {\n      this.state.pos += 3;\n      this.finishToken(tt.ellipsis);\n    } else {\n      ++this.state.pos;\n      this.finishToken(tt.dot);\n    }\n  }\n\n  readToken_slash(): void {\n    const next = this.input.charCodeAt(this.state.pos + 1);\n    if (next === charCodes.equalsTo) {\n      this.finishOp(tt.slashAssign, 2);\n    } else {\n      this.finishOp(tt.slash, 1);\n    }\n  }\n\n  readToken_interpreter(): boolean {\n    if (this.state.pos !== 0 || this.length < 2) return false;\n\n    let ch = this.input.charCodeAt(this.state.pos + 1);\n    if (ch !== charCodes.exclamationMark) return false;\n\n    const start = this.state.pos;\n    this.state.pos += 1;\n\n    while (!isNewLine(ch) && ++this.state.pos < this.length) {\n      ch = this.input.charCodeAt(this.state.pos);\n    }\n\n    const value = this.input.slice(start + 2, this.state.pos);\n\n    this.finishToken(tt.interpreterDirective, value);\n\n    return true;\n  }\n\n  readToken_mult_modulo(code: number): void {\n    // '%' or '*'\n    let type = code === charCodes.asterisk ? tt.star : tt.modulo;\n    let width = 1;\n    let next = this.input.charCodeAt(this.state.pos + 1);\n\n    // Exponentiation operator '**'\n    if (code === charCodes.asterisk && next === charCodes.asterisk) {\n      width++;\n      next = this.input.charCodeAt(this.state.pos + 2);\n      type = tt.exponent;\n    }\n\n    // '%=' or '*='\n    if (next === charCodes.equalsTo && !this.state.inType) {\n      width++;\n      // `tt.moduloAssign` is only needed to support % as a Hack-pipe topic token.\n      // If the proposal ends up choosing a different token,\n      // it can be merged with tt.assign.\n      type = code === charCodes.percentSign ? tt.moduloAssign : tt.assign;\n    }\n\n    this.finishOp(type, width);\n  }\n\n  readToken_pipe_amp(code: number): void {\n    // '||' '&&' '||=' '&&='\n    const next = this.input.charCodeAt(this.state.pos + 1);\n\n    if (next === code) {\n      if (this.input.charCodeAt(this.state.pos + 2) === charCodes.equalsTo) {\n        this.finishOp(tt.assign, 3);\n      } else {\n        this.finishOp(\n          code === charCodes.verticalBar ? tt.logicalOR : tt.logicalAND,\n          2,\n        );\n      }\n      return;\n    }\n\n    if (code === charCodes.verticalBar) {\n      // '|>'\n      if (next === charCodes.greaterThan) {\n        this.finishOp(tt.pipeline, 2);\n        return;\n      }\n      // '|}'\n      if (\n        !process.env.BABEL_8_BREAKING &&\n        this.hasPlugin(\"recordAndTuple\") &&\n        next === charCodes.rightCurlyBrace\n      ) {\n        if (this.getPluginOption(\"recordAndTuple\", \"syntaxType\") !== \"bar\") {\n          throw this.raise(\n            Errors.RecordExpressionBarIncorrectEndSyntaxType,\n            this.state.curPosition(),\n          );\n        }\n        this.state.pos += 2;\n        this.finishToken(tt.braceBarR);\n        return;\n      }\n\n      // '|]'\n      if (\n        !process.env.BABEL_8_BREAKING &&\n        this.hasPlugin(\"recordAndTuple\") &&\n        next === charCodes.rightSquareBracket\n      ) {\n        if (this.getPluginOption(\"recordAndTuple\", \"syntaxType\") !== \"bar\") {\n          throw this.raise(\n            Errors.TupleExpressionBarIncorrectEndSyntaxType,\n            this.state.curPosition(),\n          );\n        }\n        this.state.pos += 2;\n        this.finishToken(tt.bracketBarR);\n        return;\n      }\n    }\n\n    if (next === charCodes.equalsTo) {\n      this.finishOp(tt.assign, 2);\n      return;\n    }\n\n    this.finishOp(\n      code === charCodes.verticalBar ? tt.bitwiseOR : tt.bitwiseAND,\n      1,\n    );\n  }\n\n  readToken_caret(): void {\n    const next = this.input.charCodeAt(this.state.pos + 1);\n\n    // '^='\n    if (next === charCodes.equalsTo && !this.state.inType) {\n      // `tt.xorAssign` is only needed to support ^ as a Hack-pipe topic token.\n      // If the proposal ends up choosing a different token,\n      // it can be merged with tt.assign.\n      this.finishOp(tt.xorAssign, 2);\n    }\n    // '^^'\n    else if (\n      next === charCodes.caret &&\n      // If the ^^ token is not enabled, we don't throw but parse two single ^s\n      // because it could be a ^ hack token followed by a ^ binary operator.\n      this.hasPlugin([\n        \"pipelineOperator\",\n        { proposal: \"hack\", topicToken: \"^^\" },\n      ])\n    ) {\n      this.finishOp(tt.doubleCaret, 2);\n\n      // `^^^` is forbidden and must be separated by a space.\n      const lookaheadCh = this.input.codePointAt(this.state.pos);\n      if (lookaheadCh === charCodes.caret) {\n        this.unexpected();\n      }\n    }\n    // '^'\n    else {\n      this.finishOp(tt.bitwiseXOR, 1);\n    }\n  }\n\n  readToken_atSign(): void {\n    const next = this.input.charCodeAt(this.state.pos + 1);\n\n    // '@@'\n    if (\n      next === charCodes.atSign &&\n      this.hasPlugin([\n        \"pipelineOperator\",\n        { proposal: \"hack\", topicToken: \"@@\" },\n      ])\n    ) {\n      this.finishOp(tt.doubleAt, 2);\n    }\n    // '@'\n    else {\n      this.finishOp(tt.at, 1);\n    }\n  }\n\n  readToken_plus_min(code: number): void {\n    // '+-'\n    const next = this.input.charCodeAt(this.state.pos + 1);\n\n    if (next === code) {\n      this.finishOp(tt.incDec, 2);\n      return;\n    }\n\n    if (next === charCodes.equalsTo) {\n      this.finishOp(tt.assign, 2);\n    } else {\n      this.finishOp(tt.plusMin, 1);\n    }\n  }\n\n  readToken_lt(): void {\n    // '<'\n    const { pos } = this.state;\n    const next = this.input.charCodeAt(pos + 1);\n\n    if (next === charCodes.lessThan) {\n      if (this.input.charCodeAt(pos + 2) === charCodes.equalsTo) {\n        this.finishOp(tt.assign, 3);\n        return;\n      }\n      this.finishOp(tt.bitShiftL, 2);\n      return;\n    }\n\n    if (next === charCodes.equalsTo) {\n      // <=\n      this.finishOp(tt.relational, 2);\n      return;\n    }\n\n    this.finishOp(tt.lt, 1);\n  }\n\n  readToken_gt(): void {\n    // '>'\n    const { pos } = this.state;\n    const next = this.input.charCodeAt(pos + 1);\n\n    if (next === charCodes.greaterThan) {\n      const size =\n        this.input.charCodeAt(pos + 2) === charCodes.greaterThan ? 3 : 2;\n      if (this.input.charCodeAt(pos + size) === charCodes.equalsTo) {\n        this.finishOp(tt.assign, size + 1);\n        return;\n      }\n      this.finishOp(tt.bitShiftR, size);\n      return;\n    }\n\n    if (next === charCodes.equalsTo) {\n      // <= | >=\n      this.finishOp(tt.relational, 2);\n      return;\n    }\n\n    this.finishOp(tt.gt, 1);\n  }\n\n  readToken_eq_excl(code: number): void {\n    // '=!'\n    const next = this.input.charCodeAt(this.state.pos + 1);\n    if (next === charCodes.equalsTo) {\n      this.finishOp(\n        tt.equality,\n        this.input.charCodeAt(this.state.pos + 2) === charCodes.equalsTo\n          ? 3\n          : 2,\n      );\n      return;\n    }\n    if (code === charCodes.equalsTo && next === charCodes.greaterThan) {\n      // '=>'\n      this.state.pos += 2;\n      this.finishToken(tt.arrow);\n      return;\n    }\n    this.finishOp(code === charCodes.equalsTo ? tt.eq : tt.bang, 1);\n  }\n\n  readToken_question(): void {\n    // '?'\n    const next = this.input.charCodeAt(this.state.pos + 1);\n    const next2 = this.input.charCodeAt(this.state.pos + 2);\n    if (next === charCodes.questionMark) {\n      if (next2 === charCodes.equalsTo) {\n        // '??='\n        this.finishOp(tt.assign, 3);\n      } else {\n        // '??'\n        this.finishOp(tt.nullishCoalescing, 2);\n      }\n    } else if (\n      next === charCodes.dot &&\n      !(next2 >= charCodes.digit0 && next2 <= charCodes.digit9)\n    ) {\n      // '.' not followed by a number\n      this.state.pos += 2;\n      this.finishToken(tt.questionDot);\n    } else {\n      ++this.state.pos;\n      this.finishToken(tt.question);\n    }\n  }\n\n  getTokenFromCode(code: number): void {\n    switch (code) {\n      // The interpretation of a dot depends on whether it is followed\n      // by a digit or another two dots.\n\n      case charCodes.dot:\n        this.readToken_dot();\n        return;\n      // Punctuation tokens.\n      case charCodes.leftParenthesis:\n        ++this.state.pos;\n        this.finishToken(tt.parenL);\n        return;\n      case charCodes.rightParenthesis:\n        ++this.state.pos;\n        this.finishToken(tt.parenR);\n        return;\n      case charCodes.semicolon:\n        ++this.state.pos;\n        this.finishToken(tt.semi);\n        return;\n      case charCodes.comma:\n        ++this.state.pos;\n        this.finishToken(tt.comma);\n        return;\n      case charCodes.leftSquareBracket:\n        if (\n          !process.env.BABEL_8_BREAKING &&\n          this.hasPlugin(\"recordAndTuple\") &&\n          this.input.charCodeAt(this.state.pos + 1) === charCodes.verticalBar\n        ) {\n          if (this.getPluginOption(\"recordAndTuple\", \"syntaxType\") !== \"bar\") {\n            throw this.raise(\n              Errors.TupleExpressionBarIncorrectStartSyntaxType,\n              this.state.curPosition(),\n            );\n          }\n\n          // [|\n          this.state.pos += 2;\n          this.finishToken(tt.bracketBarL);\n        } else {\n          ++this.state.pos;\n          this.finishToken(tt.bracketL);\n        }\n        return;\n      case charCodes.rightSquareBracket:\n        ++this.state.pos;\n        this.finishToken(tt.bracketR);\n        return;\n      case charCodes.leftCurlyBrace:\n        if (\n          !process.env.BABEL_8_BREAKING &&\n          this.hasPlugin(\"recordAndTuple\") &&\n          this.input.charCodeAt(this.state.pos + 1) === charCodes.verticalBar\n        ) {\n          if (this.getPluginOption(\"recordAndTuple\", \"syntaxType\") !== \"bar\") {\n            throw this.raise(\n              Errors.RecordExpressionBarIncorrectStartSyntaxType,\n              this.state.curPosition(),\n            );\n          }\n\n          // {|\n          this.state.pos += 2;\n          this.finishToken(tt.braceBarL);\n        } else {\n          ++this.state.pos;\n          this.finishToken(tt.braceL);\n        }\n        return;\n      case charCodes.rightCurlyBrace:\n        ++this.state.pos;\n        this.finishToken(tt.braceR);\n        return;\n\n      case charCodes.colon:\n        if (\n          this.hasPlugin(\"functionBind\") &&\n          this.input.charCodeAt(this.state.pos + 1) === charCodes.colon\n        ) {\n          this.finishOp(tt.doubleColon, 2);\n        } else {\n          ++this.state.pos;\n          this.finishToken(tt.colon);\n        }\n        return;\n\n      case charCodes.questionMark:\n        this.readToken_question();\n        return;\n\n      case charCodes.graveAccent:\n        this.readTemplateToken();\n        return;\n\n      case charCodes.digit0: {\n        const next = this.input.charCodeAt(this.state.pos + 1);\n        // '0x', '0X' - hex number\n        if (next === charCodes.lowercaseX || next === charCodes.uppercaseX) {\n          this.readRadixNumber(16);\n          return;\n        }\n        // '0o', '0O' - octal number\n        if (next === charCodes.lowercaseO || next === charCodes.uppercaseO) {\n          this.readRadixNumber(8);\n          return;\n        }\n        // '0b', '0B' - binary number\n        if (next === charCodes.lowercaseB || next === charCodes.uppercaseB) {\n          this.readRadixNumber(2);\n          return;\n        }\n      }\n      // Anything else beginning with a digit is an integer, octal\n      // number, or float. (fall through)\n      case charCodes.digit1:\n      case charCodes.digit2:\n      case charCodes.digit3:\n      case charCodes.digit4:\n      case charCodes.digit5:\n      case charCodes.digit6:\n      case charCodes.digit7:\n      case charCodes.digit8:\n      case charCodes.digit9:\n        this.readNumber(false);\n        return;\n\n      // Quotes produce strings.\n      case charCodes.quotationMark:\n      case charCodes.apostrophe:\n        this.readString(code);\n        return;\n\n      // Operators are parsed inline in tiny state machines. '=' (charCodes.equalsTo) is\n      // often referred to. `finishOp` simply skips the amount of\n      // characters it is given as second argument, and returns a token\n      // of the type given by its first argument.\n\n      case charCodes.slash:\n        this.readToken_slash();\n        return;\n\n      case charCodes.percentSign:\n      case charCodes.asterisk:\n        this.readToken_mult_modulo(code);\n        return;\n\n      case charCodes.verticalBar:\n      case charCodes.ampersand:\n        this.readToken_pipe_amp(code);\n        return;\n\n      case charCodes.caret:\n        this.readToken_caret();\n        return;\n\n      case charCodes.plusSign:\n      case charCodes.dash:\n        this.readToken_plus_min(code);\n        return;\n\n      case charCodes.lessThan:\n        this.readToken_lt();\n        return;\n\n      case charCodes.greaterThan:\n        this.readToken_gt();\n        return;\n\n      case charCodes.equalsTo:\n      case charCodes.exclamationMark:\n        this.readToken_eq_excl(code);\n        return;\n\n      case charCodes.tilde:\n        this.finishOp(tt.tilde, 1);\n        return;\n\n      case charCodes.atSign:\n        this.readToken_atSign();\n        return;\n\n      case charCodes.numberSign:\n        this.readToken_numberSign();\n        return;\n\n      case charCodes.backslash:\n        this.readWord();\n        return;\n\n      default:\n        if (isIdentifierStart(code)) {\n          this.readWord(code);\n          return;\n        }\n    }\n\n    throw this.raise(\n      Errors.InvalidOrUnexpectedToken,\n      this.state.curPosition(),\n      {\n        unexpected: String.fromCodePoint(code),\n      },\n    );\n  }\n\n  finishOp(type: TokenType, size: number): void {\n    const str = this.input.slice(this.state.pos, this.state.pos + size);\n    this.state.pos += size;\n    this.finishToken(type, str);\n  }\n\n  readRegexp(): void {\n    const startLoc = this.state.startLoc;\n    const start = this.state.start + 1;\n    let escaped, inClass;\n    let { pos } = this.state;\n    for (; ; ++pos) {\n      if (pos >= this.length) {\n        // FIXME: explain\n        throw this.raise(\n          Errors.UnterminatedRegExp,\n          createPositionWithColumnOffset(startLoc, 1),\n        );\n      }\n      const ch = this.input.charCodeAt(pos);\n      if (isNewLine(ch)) {\n        throw this.raise(\n          Errors.UnterminatedRegExp,\n          createPositionWithColumnOffset(startLoc, 1),\n        );\n      }\n      if (escaped) {\n        escaped = false;\n      } else {\n        if (ch === charCodes.leftSquareBracket) {\n          inClass = true;\n        } else if (ch === charCodes.rightSquareBracket && inClass) {\n          inClass = false;\n        } else if (ch === charCodes.slash && !inClass) {\n          break;\n        }\n        escaped = ch === charCodes.backslash;\n      }\n    }\n    const content = this.input.slice(start, pos);\n    ++pos;\n\n    let mods = \"\";\n\n    const nextPos = () =>\n      // (pos + 1) + 1 - start\n      createPositionWithColumnOffset(startLoc, pos + 2 - start);\n\n    while (pos < this.length) {\n      const cp = this.codePointAtPos(pos);\n      // It doesn't matter if cp > 0xffff, the loop will either throw or break because we check on cp\n      const char = String.fromCharCode(cp);\n\n      // @ts-expect-error VALID_REGEX_FLAGS.has should accept expanded type: number\n      if (VALID_REGEX_FLAGS.has(cp)) {\n        if (cp === charCodes.lowercaseV) {\n          if (mods.includes(\"u\")) {\n            this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());\n          }\n        } else if (cp === charCodes.lowercaseU) {\n          if (mods.includes(\"v\")) {\n            this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());\n          }\n        }\n        if (mods.includes(char)) {\n          this.raise(Errors.DuplicateRegExpFlags, nextPos());\n        }\n      } else if (isIdentifierChar(cp) || cp === charCodes.backslash) {\n        this.raise(Errors.MalformedRegExpFlags, nextPos());\n      } else {\n        break;\n      }\n\n      ++pos;\n      mods += char;\n    }\n    this.state.pos = pos;\n\n    this.finishToken(tt.regexp, {\n      pattern: content,\n      flags: mods,\n    });\n  }\n\n  // Read an integer in the given radix. Return null if zero digits\n  // were read, the integer value otherwise. When `len` is given, this\n  // will return `null` unless the integer has exactly `len` digits.\n  // When `forceLen` is `true`, it means that we already know that in case\n  // of a malformed number we have to skip `len` characters anyway, instead\n  // of bailing out early. For example, in \"\\u{123Z}\" we want to read up to }\n  // anyway, while in \"\\u00Z\" we will stop at Z instead of consuming four\n  // characters (and thus the closing quote).\n\n  readInt(\n    radix: number,\n    len?: number,\n    forceLen: boolean = false,\n    allowNumSeparator: boolean | \"bail\" = true,\n  ): number | null {\n    const { n, pos } = readInt(\n      this.input,\n      this.state.pos,\n      this.state.lineStart,\n      this.state.curLine,\n      radix,\n      len,\n      forceLen,\n      allowNumSeparator,\n      this.errorHandlers_readInt,\n      /* bailOnError */ false,\n    );\n    this.state.pos = pos;\n    return n;\n  }\n\n  readRadixNumber(radix: number): void {\n    const start = this.state.pos;\n    const startLoc = this.state.curPosition();\n    let isBigInt = false;\n\n    this.state.pos += 2; // 0x\n    const val = this.readInt(radix);\n    if (val == null) {\n      this.raise(\n        Errors.InvalidDigit,\n        // Numeric literals can't have newlines, so this is safe to do.\n        createPositionWithColumnOffset(startLoc, 2),\n        {\n          radix,\n        },\n      );\n    }\n    const next = this.input.charCodeAt(this.state.pos);\n\n    if (next === charCodes.lowercaseN) {\n      ++this.state.pos;\n      isBigInt = true;\n    } else if (next === charCodes.lowercaseM) {\n      throw this.raise(Errors.InvalidDecimal, startLoc);\n    }\n\n    if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {\n      throw this.raise(Errors.NumberIdentifier, this.state.curPosition());\n    }\n\n    if (isBigInt) {\n      const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, \"\");\n      this.finishToken(tt.bigint, str);\n      return;\n    }\n\n    this.finishToken(tt.num, val);\n  }\n\n  // Read an integer, octal integer, or floating-point number.\n\n  readNumber(startsWithDot: boolean): void {\n    const start = this.state.pos;\n    const startLoc = this.state.curPosition();\n    let isFloat = false;\n    let isBigInt = false;\n    let hasExponent = false;\n    let isOctal = false;\n\n    if (!startsWithDot && this.readInt(10) === null) {\n      this.raise(Errors.InvalidNumber, this.state.curPosition());\n    }\n    const hasLeadingZero =\n      this.state.pos - start >= 2 &&\n      this.input.charCodeAt(start) === charCodes.digit0;\n\n    if (hasLeadingZero) {\n      const integer = this.input.slice(start, this.state.pos);\n      this.recordStrictModeErrors(Errors.StrictOctalLiteral, startLoc);\n      if (!this.state.strict) {\n        // disallow numeric separators in non octal decimals and legacy octal likes\n        const underscorePos = integer.indexOf(\"_\");\n        if (underscorePos > 0) {\n          // Numeric literals can't have newlines, so this is safe to do.\n          this.raise(\n            Errors.ZeroDigitNumericSeparator,\n            createPositionWithColumnOffset(startLoc, underscorePos),\n          );\n        }\n      }\n      isOctal = hasLeadingZero && !/[89]/.test(integer);\n    }\n\n    let next = this.input.charCodeAt(this.state.pos);\n    if (next === charCodes.dot && !isOctal) {\n      ++this.state.pos;\n      this.readInt(10);\n      isFloat = true;\n      next = this.input.charCodeAt(this.state.pos);\n    }\n\n    if (\n      (next === charCodes.uppercaseE || next === charCodes.lowercaseE) &&\n      !isOctal\n    ) {\n      next = this.input.charCodeAt(++this.state.pos);\n      if (next === charCodes.plusSign || next === charCodes.dash) {\n        ++this.state.pos;\n      }\n      if (this.readInt(10) === null) {\n        this.raise(Errors.InvalidOrMissingExponent, startLoc);\n      }\n      isFloat = true;\n      hasExponent = true;\n      next = this.input.charCodeAt(this.state.pos);\n    }\n\n    if (next === charCodes.lowercaseN) {\n      // disallow floats, legacy octal syntax and non octal decimals\n      // new style octal (\"0o\") is handled in this.readRadixNumber\n      if (isFloat || hasLeadingZero) {\n        this.raise(Errors.InvalidBigIntLiteral, startLoc);\n      }\n      ++this.state.pos;\n      isBigInt = true;\n    }\n\n    if (!process.env.BABEL_8_BREAKING && next === charCodes.lowercaseM) {\n      this.expectPlugin(\"decimal\", this.state.curPosition());\n      if (hasExponent || hasLeadingZero) {\n        this.raise(Errors.InvalidDecimal, startLoc);\n      }\n      ++this.state.pos;\n      // eslint-disable-next-line no-var\n      var isDecimal = true;\n    }\n\n    if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {\n      throw this.raise(Errors.NumberIdentifier, this.state.curPosition());\n    }\n\n    // remove \"_\" for numeric literal separator, and trailing `m` or `n`\n    const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, \"\");\n\n    if (isBigInt) {\n      this.finishToken(tt.bigint, str);\n      return;\n    }\n\n    if (!process.env.BABEL_8_BREAKING && isDecimal) {\n      this.finishToken(tt.decimal, str);\n      return;\n    }\n\n    const val = isOctal ? parseInt(str, 8) : parseFloat(str);\n    this.finishToken(tt.num, val);\n  }\n\n  // Read a string value, interpreting backslash-escapes.\n\n  readCodePoint(throwOnInvalid: boolean): number | null {\n    const { code, pos } = readCodePoint(\n      this.input,\n      this.state.pos,\n      this.state.lineStart,\n      this.state.curLine,\n      throwOnInvalid,\n      this.errorHandlers_readCodePoint,\n    );\n    this.state.pos = pos;\n    return code;\n  }\n\n  readString(quote: number): void {\n    const { str, pos, curLine, lineStart } = readStringContents(\n      quote === charCodes.quotationMark ? \"double\" : \"single\",\n      this.input,\n      this.state.pos + 1, // skip the quote\n      this.state.lineStart,\n      this.state.curLine,\n      this.errorHandlers_readStringContents_string,\n    );\n    this.state.pos = pos + 1; // skip the quote\n    this.state.lineStart = lineStart;\n    this.state.curLine = curLine;\n    this.finishToken(tt.string, str);\n  }\n\n  // Reads template continuation `}...`\n  readTemplateContinuation(): void {\n    if (!this.match(tt.braceR)) {\n      this.unexpected(null, tt.braceR);\n    }\n    // rewind pos to `}`\n    this.state.pos--;\n    this.readTemplateToken();\n  }\n\n  // Reads template string tokens.\n  readTemplateToken(): void {\n    const opening = this.input[this.state.pos];\n    const { str, firstInvalidLoc, pos, curLine, lineStart } =\n      readStringContents(\n        \"template\",\n        this.input,\n        this.state.pos + 1, // skip '`' or `}`\n        this.state.lineStart,\n        this.state.curLine,\n        this.errorHandlers_readStringContents_template,\n      );\n    this.state.pos = pos + 1; // skip '`' or `$`\n    this.state.lineStart = lineStart;\n    this.state.curLine = curLine;\n\n    if (firstInvalidLoc) {\n      this.state.firstInvalidTemplateEscapePos = new Position(\n        firstInvalidLoc.curLine,\n        firstInvalidLoc.pos - firstInvalidLoc.lineStart,\n        this.sourceToOffsetPos(firstInvalidLoc.pos),\n      );\n    }\n\n    if (this.input.codePointAt(pos) === charCodes.graveAccent) {\n      this.finishToken(\n        tt.templateTail,\n        firstInvalidLoc ? null : opening + str + \"`\",\n      );\n    } else {\n      this.state.pos++; // skip '{'\n      this.finishToken(\n        tt.templateNonTail,\n        firstInvalidLoc ? null : opening + str + \"${\",\n      );\n    }\n  }\n\n  recordStrictModeErrors(toParseError: DeferredStrictError, at: Position) {\n    const index = at.index;\n\n    if (this.state.strict && !this.state.strictErrors.has(index)) {\n      this.raise(toParseError, at);\n    } else {\n      this.state.strictErrors.set(index, [toParseError, at]);\n    }\n  }\n\n  // Read an identifier, and return it as a string. Sets `this.state.containsEsc`\n  // to whether the word contained a '\\u' escape.\n  //\n  // Incrementally adds only escaped chars, adding other chunks as-is\n  // as a micro-optimization.\n  //\n  // When `firstCode` is given, it assumes it is always an identifier start and\n  // will skip reading start position again\n\n  readWord1(firstCode?: number): string {\n    this.state.containsEsc = false;\n    let word = \"\";\n    const start = this.state.pos;\n    let chunkStart = this.state.pos;\n    if (firstCode !== undefined) {\n      this.state.pos += firstCode <= 0xffff ? 1 : 2;\n    }\n\n    while (this.state.pos < this.length) {\n      const ch = this.codePointAtPos(this.state.pos);\n      if (isIdentifierChar(ch)) {\n        this.state.pos += ch <= 0xffff ? 1 : 2;\n      } else if (ch === charCodes.backslash) {\n        this.state.containsEsc = true;\n\n        word += this.input.slice(chunkStart, this.state.pos);\n        const escStart = this.state.curPosition();\n        const identifierCheck =\n          this.state.pos === start ? isIdentifierStart : isIdentifierChar;\n\n        if (this.input.charCodeAt(++this.state.pos) !== charCodes.lowercaseU) {\n          this.raise(Errors.MissingUnicodeEscape, this.state.curPosition());\n          chunkStart = this.state.pos - 1;\n          continue;\n        }\n\n        ++this.state.pos;\n        const esc = this.readCodePoint(true);\n        if (esc !== null) {\n          if (!identifierCheck(esc)) {\n            this.raise(Errors.EscapedCharNotAnIdentifier, escStart);\n          }\n\n          word += String.fromCodePoint(esc);\n        }\n        chunkStart = this.state.pos;\n      } else {\n        break;\n      }\n    }\n    return word + this.input.slice(chunkStart, this.state.pos);\n  }\n\n  // Read an identifier or keyword token. Will check for reserved\n  // words when necessary.\n\n  readWord(firstCode?: number): void {\n    const word = this.readWord1(firstCode);\n    const type = keywordTypes.get(word);\n    if (type !== undefined) {\n      // We don't use word as state.value here because word is a dynamic string\n      // while token label is a shared constant string\n      this.finishToken(type, tokenLabelName(type));\n    } else {\n      this.finishToken(tt.name, word);\n    }\n  }\n\n  checkKeywordEscapes(): void {\n    const { type } = this.state;\n    if (tokenIsKeyword(type) && this.state.containsEsc) {\n      this.raise(Errors.InvalidEscapedReservedWord, this.state.startLoc, {\n        reservedWord: tokenLabelName(type),\n      });\n    }\n  }\n\n  /**\n   * Raise a `ParseError` given the appropriate properties. If passed a\n   * `Position` for the `at` property, raises the `ParseError` at that location.\n   * Otherwise, if passed a `Node`, raises the `ParseError` at the start\n   * location of that `Node`.\n   *\n   * If `errorRecovery` is `true`, the error is pushed to the errors array and\n   * returned. If `errorRecovery` is `false`, the error is instead thrown.\n   *\n   * The return type is marked as `never` for simplicity, as error recovery\n   * will create types in an invalid AST shape.\n   */\n  raise<ErrorDetails = object>(\n    toParseError: ParseErrorConstructor<ErrorDetails>,\n    at: Position | Undone<Node>,\n    details: ErrorDetails = {} as ErrorDetails,\n  ): ParseError<ErrorDetails> {\n    const loc = at instanceof Position ? at : at.loc.start;\n    const error = toParseError(loc, details);\n\n    if (!(this.optionFlags & OptionFlags.ErrorRecovery)) throw error;\n    if (!this.isLookahead) this.state.errors.push(error);\n\n    return error;\n  }\n\n  /**\n   * If `errorRecovery` is `false`, this method behaves identically to `raise`.\n   * If `errorRecovery` is `true`, this method will first see if there is\n   * already an error stored at the same `Position`, and replaces it with the\n   * one generated here.\n   */\n  raiseOverwrite<ErrorDetails>(\n    toParseError: ParseErrorConstructor<ErrorDetails>,\n    at: Position | Undone<Node>,\n    details: ErrorDetails = {} as ErrorDetails,\n  ): ParseError<ErrorDetails> | never {\n    const loc = at instanceof Position ? at : at.loc.start;\n    const pos = loc.index;\n    const errors = this.state.errors;\n\n    for (let i = errors.length - 1; i >= 0; i--) {\n      const error = errors[i];\n      if (error.loc.index === pos) {\n        return (errors[i] = toParseError(loc, details));\n      }\n      if (error.loc.index < pos) break;\n    }\n\n    return this.raise(toParseError, at, details);\n  }\n\n  // updateContext is used by the jsx plugin\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  updateContext(prevType: TokenType): void {}\n\n  // Raise an unexpected token error. Can take the expected token type.\n  unexpected(loc?: Position | null, type?: TokenType): void {\n    throw this.raise(\n      Errors.UnexpectedToken,\n      loc != null ? loc : this.state.startLoc,\n      {\n        expected: type ? tokenLabelName(type) : null,\n      },\n    );\n  }\n\n  expectPlugin(pluginName: Plugin, loc?: Position): true {\n    if (this.hasPlugin(pluginName)) {\n      return true;\n    }\n\n    throw this.raise(\n      Errors.MissingPlugin,\n      loc != null ? loc : this.state.startLoc,\n      {\n        missingPlugin: [pluginName],\n      },\n    );\n  }\n\n  expectOnePlugin(pluginNames: Plugin[]): void {\n    if (!pluginNames.some(name => this.hasPlugin(name))) {\n      throw this.raise(Errors.MissingOneOfPlugins, this.state.startLoc, {\n        missingPlugin: pluginNames,\n      });\n    }\n  }\n\n  errorBuilder(error: ParseErrorConstructor<object>) {\n    return (pos: number, lineStart: number, curLine: number) => {\n      this.raise(error, buildPosition(pos, lineStart, curLine));\n    };\n  }\n\n  errorHandlers_readInt: IntErrorHandlers = {\n    invalidDigit: (pos, lineStart, curLine, radix) => {\n      if (!(this.optionFlags & OptionFlags.ErrorRecovery)) return false;\n\n      this.raise(Errors.InvalidDigit, buildPosition(pos, lineStart, curLine), {\n        radix,\n      });\n      // Continue parsing the number as if there was no invalid digit.\n      return true;\n    },\n    numericSeparatorInEscapeSequence: this.errorBuilder(\n      Errors.NumericSeparatorInEscapeSequence,\n    ),\n    unexpectedNumericSeparator: this.errorBuilder(\n      Errors.UnexpectedNumericSeparator,\n    ),\n  };\n\n  errorHandlers_readCodePoint: CodePointErrorHandlers = {\n    ...this.errorHandlers_readInt,\n    invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence),\n    invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint),\n  };\n\n  errorHandlers_readStringContents_string: StringContentsErrorHandlers = {\n    ...this.errorHandlers_readCodePoint,\n    strictNumericEscape: (pos, lineStart, curLine) => {\n      this.recordStrictModeErrors(\n        Errors.StrictNumericEscape,\n        buildPosition(pos, lineStart, curLine),\n      );\n    },\n    unterminated: (pos, lineStart, curLine) => {\n      throw this.raise(\n        Errors.UnterminatedString, // Report the error at the string quote\n        buildPosition(pos - 1, lineStart, curLine),\n      );\n    },\n  };\n\n  errorHandlers_readStringContents_template: StringContentsErrorHandlers = {\n    ...this.errorHandlers_readCodePoint,\n    strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape),\n    unterminated: (pos, lineStart, curLine) => {\n      throw this.raise(\n        Errors.UnterminatedTemplate,\n        buildPosition(pos, lineStart, curLine),\n      );\n    },\n  };\n}\n","import { ClassElementType } from \"./scopeflags.ts\";\nimport type { Position } from \"./location.ts\";\nimport { Errors } from \"../parse-error.ts\";\nimport type Tokenizer from \"../tokenizer/index.ts\";\n\nexport class ClassScope {\n  // A list of private named declared in the current class\n  privateNames: Set<string> = new Set();\n\n  // A list of private getters of setters without their counterpart\n  loneAccessors: Map<string, ClassElementType> = new Map();\n\n  // A list of private names used before being defined, mapping to\n  // their position.\n  undefinedPrivateNames: Map<string, Position> = new Map();\n}\n\nexport default class ClassScopeHandler {\n  parser: Tokenizer;\n  stack: Array<ClassScope> = [];\n  undefinedPrivateNames: Map<string, Position> = new Map();\n\n  constructor(parser: Tokenizer) {\n    this.parser = parser;\n  }\n\n  current(): ClassScope {\n    return this.stack[this.stack.length - 1];\n  }\n\n  enter() {\n    this.stack.push(new ClassScope());\n  }\n\n  exit() {\n    const oldClassScope = this.stack.pop();\n\n    // Migrate the usage of not yet defined private names to the outer\n    // class scope, or raise an error if we reached the top-level scope.\n\n    const current = this.current();\n\n    // Array.from is needed because this is compiled to an array-like for loop\n    for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) {\n      if (current) {\n        if (!current.undefinedPrivateNames.has(name)) {\n          current.undefinedPrivateNames.set(name, loc);\n        }\n      } else {\n        this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {\n          identifierName: name,\n        });\n      }\n    }\n  }\n\n  declarePrivateName(\n    name: string,\n    elementType: ClassElementType,\n    loc: Position,\n  ) {\n    const { privateNames, loneAccessors, undefinedPrivateNames } =\n      this.current();\n    let redefined = privateNames.has(name);\n\n    if (elementType & ClassElementType.KIND_ACCESSOR) {\n      const accessor = redefined && loneAccessors.get(name);\n      if (accessor) {\n        const oldStatic = accessor & ClassElementType.FLAG_STATIC;\n        const newStatic = elementType & ClassElementType.FLAG_STATIC;\n\n        const oldKind = accessor & ClassElementType.KIND_ACCESSOR;\n        const newKind = elementType & ClassElementType.KIND_ACCESSOR;\n\n        // The private name can be duplicated only if it is used by\n        // two accessors with different kind (get and set), and if\n        // they have the same placement (static or not).\n        redefined = oldKind === newKind || oldStatic !== newStatic;\n\n        if (!redefined) loneAccessors.delete(name);\n      } else if (!redefined) {\n        loneAccessors.set(name, elementType);\n      }\n    }\n\n    if (redefined) {\n      this.parser.raise(Errors.PrivateNameRedeclaration, loc, {\n        identifierName: name,\n      });\n    }\n\n    privateNames.add(name);\n    undefinedPrivateNames.delete(name);\n  }\n\n  usePrivateName(name: string, loc: Position) {\n    let classScope;\n    for (classScope of this.stack) {\n      if (classScope.privateNames.has(name)) return;\n    }\n\n    if (classScope) {\n      classScope.undefinedPrivateNames.set(name, loc);\n    } else {\n      // top-level\n      this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {\n        identifierName: name,\n      });\n    }\n  }\n}\n","import { Errors, type ParseErrorConstructor } from \"../parse-error.ts\";\nimport type { Position } from \"./location.ts\";\nimport type { Node } from \"../types.ts\";\nimport type Tokenizer from \"../tokenizer/index.ts\";\nimport type { Undone } from \"../parser/node.ts\";\n\n/**\n * @module util/expression-scope\n\nExpressionScope is used to track declaration errors in these ambiguous patterns:\n\n- CoverParenthesizedExpressionAndArrowParameterList\n  e.g. we don't know if `({ x })` is an parenthesized expression or an\n  arrow function parameters until we see an `=>` after `)`.\n\n- CoverCallExpressionAndAsyncArrowHead\n  e.g. we don't know if `async({ x })` is a call expression or an async arrow\n  function parameters until we see an `=>` after `)`\n\nThe following declaration errors (@see parser-errors/standard) will be recorded in\nsome expression scopes and thrown later when we know what the ambiguous pattern is\n\n- AwaitBindingIdentifier\n- AwaitExpressionFormalParameter\n- YieldInParameter\n- InvalidParenthesizedAssignment when parenthesized is an identifier\n\nThere are four different expression scope\n- Expression\n  A general scope that represents program / function body / static block. No errors\n  will be recorded nor thrown in this scope.\n\n- MaybeArrowParameterDeclaration\n  A scope that represents ambiguous arrow head e.g. `(x)`. Errors will be recorded\n  alongside parent scopes and thrown when `ExpressionScopeHandler#validateAsPattern`\n  is called.\n\n- MaybeAsyncArrowParameterDeclaration\n  A scope that represents ambiguous async arrow head e.g. `async(x)`. Errors will\n  be recorded alongside parent scopes and thrown when\n  `ExpressionScopeHandler#validateAsPattern` is called.\n\n- ParameterDeclaration\n  A scope that represents unambiguous function parameters `function(x)`. Errors\n  recorded in this scope will be thrown immediately. No errors will be recorded in\n  this scope.\n\n// @see {@link https://docs.google.com/document/d/1FAvEp9EUK-G8kHfDIEo_385Hs2SUBCYbJ5H-NnLvq8M | V8 Expression Scope design docs}\n */\n\nconst enum ExpressionScopeType {\n  kExpression = 0,\n  kMaybeArrowParameterDeclaration = 1,\n  kMaybeAsyncArrowParameterDeclaration = 2,\n  kParameterDeclaration = 3,\n}\n\nclass ExpressionScope {\n  declare type: ExpressionScopeType;\n\n  constructor(type: ExpressionScopeType = ExpressionScopeType.kExpression) {\n    this.type = type;\n  }\n\n  canBeArrowParameterDeclaration(): this is ArrowHeadParsingScope {\n    return (\n      this.type === ExpressionScopeType.kMaybeAsyncArrowParameterDeclaration ||\n      this.type === ExpressionScopeType.kMaybeArrowParameterDeclaration\n    );\n  }\n\n  isCertainlyParameterDeclaration() {\n    return this.type === ExpressionScopeType.kParameterDeclaration;\n  }\n}\n\ntype ArrowHeadParsingParameterInitializerError =\n  | typeof Errors.AwaitExpressionFormalParameter\n  | typeof Errors.YieldInParameter;\ntype ArrowHeadParsingDeclarationError =\n  | ArrowHeadParsingParameterInitializerError\n  | typeof Errors.InvalidParenthesizedAssignment\n  | typeof Errors.AwaitBindingIdentifier;\n\nclass ArrowHeadParsingScope extends ExpressionScope {\n  declarationErrors: Map<number, [ParseErrorConstructor<object>, Position]> =\n    new Map();\n  constructor(\n    type:\n      | ExpressionScopeType.kMaybeArrowParameterDeclaration\n      | ExpressionScopeType.kMaybeAsyncArrowParameterDeclaration,\n  ) {\n    super(type);\n  }\n  recordDeclarationError(\n    ParsingErrorClass: ParseErrorConstructor<object>,\n    at: Position,\n  ) {\n    const index = at.index;\n\n    this.declarationErrors.set(index, [ParsingErrorClass, at]);\n  }\n  clearDeclarationError(index: number) {\n    this.declarationErrors.delete(index);\n  }\n  iterateErrors(\n    iterator: (a: [ArrowHeadParsingDeclarationError, Position]) => void,\n  ) {\n    this.declarationErrors.forEach(iterator);\n  }\n}\n\nexport default class ExpressionScopeHandler {\n  parser: Tokenizer;\n  stack: Array<ExpressionScope> = [new ExpressionScope()];\n\n  constructor(parser: Tokenizer) {\n    this.parser = parser;\n  }\n  enter(scope: ExpressionScope) {\n    this.stack.push(scope);\n  }\n\n  exit() {\n    this.stack.pop();\n  }\n\n  /**\n   * Record likely parameter initializer errors\n   *\n   * When current scope is a ParameterDeclaration, the error will be thrown immediately,\n   * otherwise it will be recorded to any ancestry MaybeArrowParameterDeclaration and\n   * MaybeAsyncArrowParameterDeclaration scope until an Expression scope is seen.\n   */\n  recordParameterInitializerError(\n    toParseError: ArrowHeadParsingParameterInitializerError,\n    node: Undone<Node>,\n  ): void {\n    const origin = node.loc.start;\n    const { stack } = this;\n    let i = stack.length - 1;\n    let scope: ExpressionScope = stack[i];\n    while (!scope.isCertainlyParameterDeclaration()) {\n      if (scope.canBeArrowParameterDeclaration()) {\n        scope.recordDeclarationError(toParseError, origin);\n      } else {\n        /*:: invariant(scope.type == ExpressionScopeType.kExpression) */\n        // Type-Expression is the boundary where initializer error can populate to\n        return;\n      }\n      scope = stack[--i];\n    }\n    this.parser.raise(toParseError, origin);\n  }\n\n  /**\n   * Record errors that must be thrown if the current pattern ends up being an arrow\n   * function parameter. This is used to record parenthesized identifiers, and to record\n   * \"a as T\" and \"<T> a\" type assertions when parsing typescript.\n   *\n   * A parenthesized identifier (or type assertion) in LHS can be ambiguous because the assignment\n   * can be transformed to an assignable later, but not vice versa:\n   * For example, in `([(a) = []] = []) => {}`, we think `(a) = []` is an LHS in `[(a) = []]`,\n   * an LHS within `[(a) = []] = []`. However the LHS chain is then transformed by toAssignable,\n   * and we should throw assignment `(a)`, which is only valid in LHS. Hence we record the\n   * location of parenthesized `(a)` to current scope if it is one of MaybeArrowParameterDeclaration\n   * and MaybeAsyncArrowParameterDeclaration\n   *\n   * Unlike `recordParameterInitializerError`, we don't record to ancestry scope because we\n   * validate arrow head parsing scope before exit, and then the LHS will be unambiguous:\n   * For example, in `( x = ( [(a) = []] = [] ) ) => {}`, we should not record `(a)` in `( x = ... ) =>`\n   * arrow scope because when we finish parsing `( [(a) = []] = [] )`, it is an unambiguous assignment\n   * expression and can not be cast to pattern\n   */\n  recordArrowParameterBindingError(\n    error: ParseErrorConstructor<object>,\n    node: Node,\n  ): void {\n    const { stack } = this;\n    const scope: ExpressionScope = stack[stack.length - 1];\n    const origin = node.loc.start;\n    if (scope.isCertainlyParameterDeclaration()) {\n      this.parser.raise(error, origin);\n    } else if (scope.canBeArrowParameterDeclaration()) {\n      scope.recordDeclarationError(error, origin);\n    } else {\n      return;\n    }\n  }\n\n  /**\n   * Record likely async arrow parameter errors\n   *\n   * Errors will be recorded to any ancestry MaybeAsyncArrowParameterDeclaration\n   * scope until an Expression scope is seen.\n   */\n  recordAsyncArrowParametersError(at: Position): void {\n    const { stack } = this;\n    let i = stack.length - 1;\n    let scope: ExpressionScope = stack[i];\n    while (scope.canBeArrowParameterDeclaration()) {\n      if (\n        scope.type === ExpressionScopeType.kMaybeAsyncArrowParameterDeclaration\n      ) {\n        scope.recordDeclarationError(Errors.AwaitBindingIdentifier, at);\n      }\n      scope = stack[--i];\n    }\n  }\n\n  validateAsPattern(): void {\n    const { stack } = this;\n    const currentScope = stack[stack.length - 1];\n    if (!currentScope.canBeArrowParameterDeclaration()) return;\n    currentScope.iterateErrors(([toParseError, loc]) => {\n      this.parser.raise(toParseError, loc);\n      // iterate from parent scope\n      let i = stack.length - 2;\n      let scope = stack[i];\n      while (scope.canBeArrowParameterDeclaration()) {\n        scope.clearDeclarationError(loc.index);\n        scope = stack[--i];\n      }\n    });\n  }\n}\n\nexport function newParameterDeclarationScope() {\n  return new ExpressionScope(ExpressionScopeType.kParameterDeclaration);\n}\n\nexport function newArrowHeadScope() {\n  return new ArrowHeadParsingScope(\n    ExpressionScopeType.kMaybeArrowParameterDeclaration,\n  );\n}\n\nexport function newAsyncArrowScope() {\n  return new ArrowHeadParsingScope(\n    ExpressionScopeType.kMaybeAsyncArrowParameterDeclaration,\n  );\n}\n\nexport function newExpressionScope() {\n  return new ExpressionScope();\n}\n","import type { Position } from \"../util/location.ts\";\nimport {\n  tokenIsLiteralPropertyName,\n  tt,\n  type TokenType,\n} from \"../tokenizer/types.ts\";\nimport Tokenizer from \"../tokenizer/index.ts\";\nimport type State from \"../tokenizer/state.ts\";\nimport type {\n  EstreePropertyDefinition,\n  Node,\n  ObjectMethod,\n  ObjectProperty,\n  PrivateName,\n} from \"../types.d.ts\";\nimport { hasNewLine } from \"../util/whitespace.ts\";\nimport { isIdentifierChar } from \"../util/identifier.ts\";\nimport ClassScopeHandler from \"../util/class-scope.ts\";\nimport ExpressionScopeHandler from \"../util/expression-scope.ts\";\nimport { ScopeFlag } from \"../util/scopeflags.ts\";\nimport ProductionParameterHandler, {\n  ParamKind,\n} from \"../util/production-parameter.ts\";\nimport {\n  Errors,\n  type ParseError,\n  type ParseErrorConstructor,\n} from \"../parse-error.ts\";\nimport type Parser from \"./index.ts\";\n\nimport type ScopeHandler from \"../util/scope.ts\";\nimport { OptionFlags } from \"../options.ts\";\n\ntype TryParse<Node, Error, Thrown, Aborted, FailState> = {\n  node: Node;\n  error: Error;\n  thrown: Thrown;\n  aborted: Aborted;\n  failState: FailState;\n};\n\n// ## Parser utilities\n\nexport default abstract class UtilParser extends Tokenizer {\n  // Forward-declaration: defined in parser/index.js\n  abstract getScopeHandler(): new (...args: any) => ScopeHandler;\n\n  addExtra(\n    node: Partial<Node>,\n    key: string,\n    value: any,\n    enumerable: boolean = true,\n  ): void {\n    if (!node) return;\n\n    let { extra } = node;\n    if (extra == null) {\n      extra = {};\n      node.extra = extra;\n    }\n\n    if (enumerable) {\n      extra[key] = value;\n    } else {\n      Object.defineProperty(extra, key, { enumerable, value });\n    }\n  }\n\n  // Tests whether parsed token is a contextual keyword.\n\n  isContextual(token: TokenType): boolean {\n    return this.state.type === token && !this.state.containsEsc;\n  }\n\n  isUnparsedContextual(nameStart: number, name: string): boolean {\n    if (this.input.startsWith(name, nameStart)) {\n      const nextCh = this.input.charCodeAt(nameStart + name.length);\n      return !(\n        isIdentifierChar(nextCh) ||\n        // check if `nextCh is between 0xd800 - 0xdbff,\n        // if `nextCh` is NaN, `NaN & 0xfc00` is 0, the function\n        // returns true\n        (nextCh & 0xfc00) === 0xd800\n      );\n    }\n    return false;\n  }\n\n  isLookaheadContextual(name: string): boolean {\n    const next = this.nextTokenStart();\n    return this.isUnparsedContextual(next, name);\n  }\n\n  // Consumes contextual keyword if possible.\n\n  eatContextual(token: TokenType): boolean {\n    if (this.isContextual(token)) {\n      this.next();\n      return true;\n    }\n    return false;\n  }\n\n  // Asserts that following token is given contextual keyword.\n\n  expectContextual(\n    token: TokenType,\n    toParseError?: ParseErrorConstructor<any>,\n  ): void {\n    if (!this.eatContextual(token)) {\n      if (toParseError != null) {\n        throw this.raise(toParseError, this.state.startLoc);\n      }\n      this.unexpected(null, token);\n    }\n  }\n\n  // Test whether a semicolon can be inserted at the current position.\n\n  canInsertSemicolon(): boolean {\n    return (\n      this.match(tt.eof) ||\n      this.match(tt.braceR) ||\n      this.hasPrecedingLineBreak()\n    );\n  }\n\n  hasPrecedingLineBreak(): boolean {\n    return hasNewLine(\n      this.input,\n      this.offsetToSourcePos(this.state.lastTokEndLoc.index),\n      this.state.start,\n    );\n  }\n\n  hasFollowingLineBreak(): boolean {\n    return hasNewLine(this.input, this.state.end, this.nextTokenStart());\n  }\n\n  isLineTerminator(): boolean {\n    return this.eat(tt.semi) || this.canInsertSemicolon();\n  }\n\n  // Consume a semicolon, or, failing that, see if we are allowed to\n  // pretend that there is a semicolon at this position.\n\n  semicolon(allowAsi: boolean = true): void {\n    if (allowAsi ? this.isLineTerminator() : this.eat(tt.semi)) return;\n    this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc);\n  }\n\n  // Expect a token of a given type. If found, consume it, otherwise,\n  // raise an unexpected token error at given pos.\n\n  expect(type: TokenType, loc?: Position | null): void {\n    if (!this.eat(type)) {\n      this.unexpected(loc, type);\n    }\n  }\n\n  // tryParse will clone parser state.\n  // It is expensive and should be used with cautions\n  tryParse<T extends Node | ReadonlyArray<Node>>(\n    fn: (abort: (node?: T) => never) => T,\n    oldState: State = this.state.clone(),\n  ):\n    | TryParse<T, null, false, false, null>\n    | TryParse<T | null, ParseError<any>, boolean, false, State>\n    | TryParse<T | null, null, false, true, State> {\n    const abortSignal: {\n      node: T | null;\n    } = { node: null };\n    try {\n      const node = fn((node = null) => {\n        abortSignal.node = node;\n        // eslint-disable-next-line @typescript-eslint/only-throw-error\n        throw abortSignal;\n      });\n      if (this.state.errors.length > oldState.errors.length) {\n        const failState = this.state;\n        this.state = oldState;\n        // tokensLength should be preserved during error recovery mode\n        // since the parser does not halt and will instead parse the\n        // remaining tokens\n        this.state.tokensLength = failState.tokensLength;\n        return {\n          node,\n          error: failState.errors[oldState.errors.length],\n          thrown: false,\n          aborted: false,\n          failState,\n        };\n      }\n\n      return {\n        node,\n        error: null,\n        thrown: false,\n        aborted: false,\n        failState: null,\n      };\n    } catch (error) {\n      const failState = this.state;\n      this.state = oldState;\n      if (error instanceof SyntaxError) {\n        // @ts-expect-error casting general syntax error to parse error\n        return { node: null, error, thrown: true, aborted: false, failState };\n      }\n      if (error === abortSignal) {\n        return {\n          node: abortSignal.node,\n          error: null,\n          thrown: false,\n          aborted: true,\n          failState,\n        };\n      }\n\n      throw error;\n    }\n  }\n\n  checkExpressionErrors(\n    refExpressionErrors: ExpressionErrors | undefined | null,\n    andThrow: boolean,\n  ) {\n    if (!refExpressionErrors) return false;\n    const {\n      shorthandAssignLoc,\n      doubleProtoLoc,\n      privateKeyLoc,\n      optionalParametersLoc,\n      voidPatternLoc,\n    } = refExpressionErrors;\n\n    const hasErrors =\n      !!shorthandAssignLoc ||\n      !!doubleProtoLoc ||\n      !!optionalParametersLoc ||\n      !!privateKeyLoc ||\n      !!voidPatternLoc;\n\n    if (!andThrow) {\n      return hasErrors;\n    }\n\n    if (shorthandAssignLoc != null) {\n      this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);\n    }\n\n    if (doubleProtoLoc != null) {\n      this.raise(Errors.DuplicateProto, doubleProtoLoc);\n    }\n\n    if (privateKeyLoc != null) {\n      this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);\n    }\n\n    if (optionalParametersLoc != null) {\n      this.unexpected(optionalParametersLoc);\n    }\n\n    if (voidPatternLoc != null) {\n      this.raise(Errors.InvalidCoverDiscardElement, voidPatternLoc);\n    }\n  }\n\n  /**\n   * Test if current token is a literal property name\n   * https://tc39.es/ecma262/#prod-LiteralPropertyName\n   * LiteralPropertyName:\n   *   IdentifierName\n   *   StringLiteral\n   *   NumericLiteral\n   *   BigIntLiteral\n   */\n  isLiteralPropertyName(): boolean {\n    return tokenIsLiteralPropertyName(this.state.type);\n  }\n\n  /**\n   * Test if given node is a PrivateName\n   * will be overridden in ESTree plugin\n   */\n  isPrivateName(node: Node): node is PrivateName {\n    return node.type === \"PrivateName\";\n  }\n\n  /**\n   * Return the string value of a given private name\n   * WITHOUT `#`\n   * @see {@link https://tc39.es/ecma262/#sec-static-semantics-stringvalue}\n   */\n  getPrivateNameSV(node: PrivateName): string {\n    return node.id.name;\n  }\n\n  /**\n   * Return whether the given node is a member/optional chain that\n   * contains a private name as its property\n   * It is overridden in ESTree plugin\n   */\n  hasPropertyAsPrivateName(node: Node): boolean {\n    return (\n      (node.type === \"MemberExpression\" ||\n        node.type === \"OptionalMemberExpression\") &&\n      this.isPrivateName(node.property)\n    );\n  }\n\n  isObjectProperty(\n    node: Node,\n  ): node is ObjectProperty | EstreePropertyDefinition {\n    return node.type === \"ObjectProperty\";\n  }\n\n  isObjectMethod(node: Node): node is ObjectMethod {\n    return node.type === \"ObjectMethod\";\n  }\n\n  initializeScopes(\n    this: Parser,\n    inModule: boolean = this.options.sourceType === \"module\",\n  ): () => void {\n    // Initialize state\n    const oldLabels = this.state.labels;\n    this.state.labels = [];\n\n    const oldExportedIdentifiers = this.exportedIdentifiers;\n    this.exportedIdentifiers = new Set();\n\n    // initialize scopes\n    const oldInModule = this.inModule;\n    this.inModule = inModule;\n\n    const oldScope = this.scope;\n    const ScopeHandler = this.getScopeHandler();\n    this.scope = new ScopeHandler(this, inModule);\n\n    const oldProdParam = this.prodParam;\n    this.prodParam = new ProductionParameterHandler();\n\n    const oldClassScope = this.classScope;\n    this.classScope = new ClassScopeHandler(this);\n\n    const oldExpressionScope = this.expressionScope;\n    this.expressionScope = new ExpressionScopeHandler(this);\n\n    return () => {\n      // Revert state\n      this.state.labels = oldLabels;\n      this.exportedIdentifiers = oldExportedIdentifiers;\n\n      // Revert scopes\n      this.inModule = oldInModule;\n      this.scope = oldScope;\n      this.prodParam = oldProdParam;\n      this.classScope = oldClassScope;\n      this.expressionScope = oldExpressionScope;\n    };\n  }\n\n  enterInitialScopes() {\n    let paramFlags = ParamKind.PARAM;\n    if (\n      this.inModule ||\n      this.optionFlags & OptionFlags.AllowAwaitOutsideFunction\n    ) {\n      paramFlags |= ParamKind.PARAM_AWAIT;\n    }\n    if (this.optionFlags & OptionFlags.AllowYieldOutsideFunction) {\n      paramFlags |= ParamKind.PARAM_YIELD;\n    }\n    // The inModule flag ensures that the module block within a CommonJS source\n    // will be treated as an ES module.\n    const isCommonJS = !this.inModule && this.options.sourceType === \"commonjs\";\n    if (\n      isCommonJS ||\n      this.optionFlags & OptionFlags.AllowReturnOutsideFunction\n    ) {\n      paramFlags |= ParamKind.PARAM_RETURN;\n    }\n    this.prodParam.enter(paramFlags);\n    let scopeFlags = isCommonJS ? ScopeFlag.FUNCTION : ScopeFlag.PROGRAM;\n    if (this.optionFlags & OptionFlags.AllowNewTargetOutsideFunction) {\n      scopeFlags |= ScopeFlag.NEW_TARGET;\n    }\n    this.scope.enter(scopeFlags);\n  }\n\n  checkDestructuringPrivate(refExpressionErrors: ExpressionErrors) {\n    const { privateKeyLoc } = refExpressionErrors;\n    if (privateKeyLoc !== null) {\n      this.expectPlugin(\"destructuringPrivate\", privateKeyLoc);\n    }\n  }\n}\n\n/**\n * The ExpressionErrors is a context struct used to track ambiguous patterns\n * When we are sure the parsed pattern is a RHS, which means it is not a pattern,\n * we will throw on this position on invalid assign syntax, otherwise it will be reset to null\n *\n * Types of ExpressionErrors:\n *\n * - **shorthandAssignLoc**: track initializer `=` position\n * - **doubleProtoLoc**: track the duplicate `__proto__` key position\n * - **privateKeyLoc**: track private key `#p` position\n * - **optionalParametersLoc**: track the optional parameter (`?`).\n *   It's only used by typescript and flow plugins\n */\nexport class ExpressionErrors {\n  shorthandAssignLoc: Position | undefined | null = null;\n  doubleProtoLoc: Position | undefined | null = null;\n  privateKeyLoc: Position | undefined | null = null;\n  optionalParametersLoc: Position | undefined | null = null;\n  voidPatternLoc: Position | undefined | null = null;\n}\n","import UtilParser from \"./util.ts\";\nimport { SourceLocation, type Position } from \"../util/location.ts\";\nimport type {\n  Comment,\n  Node as NodeType,\n  NodeBase,\n  EstreeLiteral,\n  Identifier,\n  Placeholder,\n  StringLiteral,\n} from \"../types.ts\";\nimport { OptionFlags } from \"../options.ts\";\n\n// Start an AST node, attaching a start offset.\n\nclass Node implements NodeBase {\n  constructor(parser: UtilParser, pos: number, loc: Position) {\n    this.start = pos;\n    this.end = 0;\n    this.loc = new SourceLocation(loc);\n    if (parser?.optionFlags & OptionFlags.Ranges) this.range = [pos, 0];\n    if (parser?.filename) this.loc.filename = parser.filename;\n  }\n\n  type: string = \"\";\n  declare start: number;\n  declare end: number;\n  declare loc: SourceLocation;\n  declare range: [number, number];\n  declare leadingComments: Array<Comment>;\n  declare trailingComments: Array<Comment>;\n  declare innerComments: Array<Comment>;\n  declare extra: {\n    [key: string]: any;\n  };\n}\nconst NodePrototype = Node.prototype;\n\nif (!process.env.BABEL_8_BREAKING) {\n  // @ts-expect-error __clone is not defined in Node prototype\n  NodePrototype.__clone = function (): Node {\n    const newNode = new Node(undefined, this.start, this.loc.start);\n    const keys = Object.keys(this) as (keyof Node)[];\n    for (let i = 0, length = keys.length; i < length; i++) {\n      const key = keys[i];\n      // Do not clone comments that are already attached to the node\n      if (\n        key !== \"leadingComments\" &&\n        key !== \"trailingComments\" &&\n        key !== \"innerComments\"\n      ) {\n        // @ts-expect-error cloning this to newNode\n        newNode[key] = this[key];\n      }\n    }\n\n    return newNode;\n  };\n}\n\nexport type Undone<T extends NodeType> = Omit<T, \"type\">;\n\nexport abstract class NodeUtils extends UtilParser {\n  startNode<T extends NodeType = never>(): Undone<T> {\n    const loc = this.state.startLoc;\n    return new Node(this, loc.index, loc) as unknown as Undone<T>;\n  }\n\n  startNodeAt<T extends NodeType = never>(loc: Position): Undone<T> {\n    return new Node(this, loc.index, loc) as unknown as Undone<T>;\n  }\n\n  /** Start a new node with a previous node's location. */\n  startNodeAtNode<T extends NodeType = never>(\n    type: Undone<NodeType>,\n  ): Undone<T> {\n    return this.startNodeAt(type.loc.start);\n  }\n\n  // Finish an AST node, adding `type` and `end` properties.\n\n  finishNode<T extends NodeType>(node: Undone<T>, type: T[\"type\"]): T {\n    return this.finishNodeAt(node, type, this.state.lastTokEndLoc);\n  }\n\n  // Finish node at given position\n\n  finishNodeAt<T extends NodeType>(\n    node: Omit<T, \"type\">,\n    type: T[\"type\"],\n    endLoc: Position,\n  ): T {\n    if (process.env.NODE_ENV !== \"production\" && node.end > 0) {\n      throw new Error(\n        \"Do not call finishNode*() twice on the same node.\" +\n          \" Instead use resetEndLocation() or change type directly.\",\n      );\n    }\n    (node as T).type = type;\n    node.end = endLoc.index;\n    node.loc.end = endLoc;\n    if (this.optionFlags & OptionFlags.Ranges) node.range[1] = endLoc.index;\n    if (this.optionFlags & OptionFlags.AttachComment) {\n      this.processComment(node as T);\n    }\n    return node as T;\n  }\n\n  resetStartLocation(node: NodeBase, startLoc: Position): void {\n    node.start = startLoc.index;\n    node.loc.start = startLoc;\n    if (this.optionFlags & OptionFlags.Ranges) node.range[0] = startLoc.index;\n  }\n\n  resetEndLocation(\n    node: NodeBase,\n    endLoc: Position = this.state.lastTokEndLoc,\n  ): void {\n    node.end = endLoc.index;\n    node.loc.end = endLoc;\n    if (this.optionFlags & OptionFlags.Ranges) node.range[1] = endLoc.index;\n  }\n\n  /**\n   * Reset the start location of node to the start location of locationNode\n   */\n  resetStartLocationFromNode(node: NodeBase, locationNode: NodeBase): void {\n    this.resetStartLocation(node, locationNode.loc.start);\n  }\n\n  castNodeTo<T extends NodeType[\"type\"]>(\n    node: NodeType,\n    type: T,\n  ): Extract<NodeType, { type: T }> {\n    node.type = type;\n    return node as Extract<NodeType, { type: T }>;\n  }\n\n  cloneIdentifier<T extends Identifier | Placeholder>(node: T): T {\n    // We don't need to clone `typeAnnotations` and `optional`: because\n    // cloneIdentifier is only used in object shorthand and named import/export.\n    // Neither of them allow type annotations after the identifier or optional identifier\n    const { type, start, end, loc, range, name } = node;\n    const cloned = Object.create(NodePrototype);\n    cloned.type = type;\n    cloned.start = start;\n    cloned.end = end;\n    cloned.loc = loc;\n    cloned.range = range;\n    cloned.name = name;\n    if (node.extra) cloned.extra = node.extra;\n    return cloned;\n  }\n\n  cloneStringLiteral<T extends StringLiteral | EstreeLiteral | Placeholder>(\n    node: T,\n  ): T {\n    const { type, start, end, loc, range, extra } = node;\n    const cloned = Object.create(NodePrototype);\n    cloned.type = type;\n    cloned.start = start;\n    cloned.end = end;\n    cloned.loc = loc;\n    cloned.range = range;\n    cloned.extra = extra;\n    cloned.value = (node as StringLiteral).value;\n    return cloned;\n  }\n}\n","import * as charCodes from \"charcodes\";\nimport { tt, type TokenType } from \"../tokenizer/types.ts\";\nimport type {\n  AssignmentPattern,\n  TSParameterProperty,\n  Decorator,\n  Expression,\n  Identifier,\n  Node,\n  Pattern,\n  RestElement,\n  SpreadElement,\n  ObjectOrClassMember,\n  ClassMember,\n  ObjectMember,\n  TsNamedTypeElementBase,\n  PrivateName,\n  ObjectExpression,\n  ObjectPattern,\n  ArrayPattern,\n  AssignmentProperty,\n  Assignable,\n  VoidPattern,\n} from \"../types.ts\";\nimport type { Position } from \"../util/location.ts\";\nimport {\n  isStrictBindOnlyReservedWord,\n  isStrictBindReservedWord,\n} from \"../util/identifier.ts\";\nimport { NodeUtils, type Undone } from \"./node.ts\";\nimport { BindingFlag } from \"../util/scopeflags.ts\";\nimport type { ExpressionErrors } from \"./util.ts\";\nimport { Errors, type LValAncestor } from \"../parse-error.ts\";\nimport type Parser from \"./index.ts\";\n\nconst unwrapParenthesizedExpression = (node: Node): Node => {\n  return node.type === \"ParenthesizedExpression\"\n    ? unwrapParenthesizedExpression(node.expression)\n    : node;\n};\n\nexport const enum ParseBindingListFlags {\n  ALLOW_EMPTY = 1 << 0,\n  IS_FUNCTION_PARAMS = 1 << 1,\n  IS_CONSTRUCTOR_PARAMS = 1 << 2,\n}\n\nexport default abstract class LValParser extends NodeUtils {\n  // Forward-declaration: defined in expression.js\n  abstract parseIdentifier(liberal?: boolean): Identifier;\n  abstract parseMaybeAssign(\n    refExpressionErrors?: ExpressionErrors | null,\n    afterLeftParse?: Function,\n  ): Expression;\n\n  abstract parseMaybeAssignAllowIn(\n    refExpressionErrors?: ExpressionErrors | null,\n    afterLeftParse?: Function,\n  ): Expression;\n\n  abstract parseObjectLike<T extends ObjectPattern | ObjectExpression>(\n    close: TokenType,\n    isPattern: boolean,\n    isRecord?: boolean,\n    refExpressionErrors?: ExpressionErrors,\n  ): T;\n  abstract parseObjPropValue(\n    prop: any,\n    startLoc: Position | null,\n    isGenerator: boolean,\n    isAsync: boolean,\n    isPattern: boolean,\n    isAccessor: boolean,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): void;\n  abstract parsePropertyName(\n    prop: ObjectOrClassMember | ClassMember | TsNamedTypeElementBase,\n  ): void;\n  abstract parsePrivateName(): PrivateName;\n  // Forward-declaration: defined in statement.js\n  abstract parseDecorator(): Decorator;\n\n  /**\n   * Convert existing expression atom to assignable pattern\n   * if possible. Also checks invalid destructuring targets:\n   *\n   * - Parenthesized Destructuring patterns\n   * - RestElement is not the last element\n   * - Missing `=` in assignment pattern\n   *\n   * NOTE: There is a corresponding \"isAssignable\" method.\n   * When this one is updated, please check if also that one needs to be updated.\n   *\n   * @param node The expression atom\n   * @param isLHS Whether we are parsing a LeftHandSideExpression.\n   *              If isLHS is `true`, the following cases are allowed: `[(a)] = [0]`, `[(a.b)] = [0]`\n   *              If isLHS is `false`, we are in an arrow function parameters list.\n   */\n  toAssignable(node: Node, isLHS: boolean = false): asserts node is Assignable {\n    let parenthesized = undefined;\n    if (node.type === \"ParenthesizedExpression\" || node.extra?.parenthesized) {\n      parenthesized = unwrapParenthesizedExpression(node);\n      if (isLHS) {\n        // an LHS can be reinterpreted to a binding pattern but not vice versa.\n        // therefore a parenthesized identifier is ambiguous until we are sure it is an assignment expression\n        // i.e. `([(a) = []] = []) => {}`\n        // see also `recordArrowParameterBindingError` signature in packages/babel-parser/src/util/expression-scope.js\n        if (parenthesized.type === \"Identifier\") {\n          this.expressionScope.recordArrowParameterBindingError(\n            Errors.InvalidParenthesizedAssignment,\n            node,\n          );\n        } else if (\n          parenthesized.type !== \"MemberExpression\" &&\n          !this.isOptionalMemberExpression(parenthesized)\n        ) {\n          // A parenthesized member expression can be in LHS but not in pattern.\n          // If the LHS is later interpreted as a pattern, `checkLVal` will throw for member expression binding\n          // i.e. `([(a.b) = []] = []) => {}`\n          this.raise(Errors.InvalidParenthesizedAssignment, node);\n        }\n      } else {\n        this.raise(Errors.InvalidParenthesizedAssignment, node);\n      }\n    }\n\n    switch (node.type) {\n      case \"Identifier\":\n      case \"ObjectPattern\":\n      case \"ArrayPattern\":\n      case \"AssignmentPattern\":\n      case \"RestElement\":\n      case \"VoidPattern\":\n        break;\n\n      case \"ObjectExpression\":\n        this.castNodeTo(node, \"ObjectPattern\");\n        for (\n          let i = 0, length = node.properties.length, last = length - 1;\n          i < length;\n          i++\n        ) {\n          const prop = node.properties[i];\n          const isLast = i === last;\n          this.toAssignableObjectExpressionProp(prop, isLast, isLHS);\n\n          if (\n            isLast &&\n            (prop as Node).type === \"RestElement\" &&\n            node.extra?.trailingCommaLoc\n          ) {\n            this.raise(Errors.RestTrailingComma, node.extra.trailingCommaLoc);\n          }\n        }\n        break;\n\n      case \"ObjectProperty\": {\n        const { key, value } = node;\n        if (this.isPrivateName(key)) {\n          this.classScope.usePrivateName(\n            this.getPrivateNameSV(key),\n            key.loc.start,\n          );\n        }\n        this.toAssignable(value, isLHS);\n        break;\n      }\n\n      case \"SpreadElement\": {\n        throw new Error(\n          \"Internal @babel/parser error (this is a bug, please report it).\" +\n            \" SpreadElement should be converted by .toAssignable's caller.\",\n        );\n      }\n\n      case \"ArrayExpression\":\n        this.castNodeTo(node, \"ArrayPattern\");\n        this.toAssignableList(\n          node.elements,\n          node.extra?.trailingCommaLoc,\n          isLHS,\n        );\n        break;\n\n      case \"AssignmentExpression\":\n        if (node.operator !== \"=\") {\n          this.raise(Errors.MissingEqInAssignment, node.left.loc.end);\n        }\n\n        this.castNodeTo(node, \"AssignmentPattern\");\n        delete node.operator;\n        if (node.left.type === \"VoidPattern\") {\n          this.raise(Errors.VoidPatternInitializer, node.left);\n        }\n        this.toAssignable(node.left, isLHS);\n        break;\n\n      case \"ParenthesizedExpression\":\n        /*::invariant (parenthesized !== undefined) */\n        this.toAssignable(parenthesized, isLHS);\n        break;\n\n      default:\n      // We don't know how to deal with this node. It will\n      // be reported by a later call to checkLVal\n    }\n  }\n\n  toAssignableObjectExpressionProp(\n    prop: Node,\n    isLast: boolean,\n    isLHS: boolean,\n  ) {\n    if (prop.type === \"ObjectMethod\") {\n      this.raise(\n        prop.kind === \"get\" || prop.kind === \"set\"\n          ? Errors.PatternHasAccessor\n          : Errors.PatternHasMethod,\n        prop.key,\n      );\n    } else if (prop.type === \"SpreadElement\") {\n      this.castNodeTo(prop, \"RestElement\");\n      const arg = prop.argument;\n      this.checkToRestConversion(arg, /* allowPattern */ false);\n      this.toAssignable(arg, isLHS);\n\n      if (!isLast) {\n        this.raise(Errors.RestTrailingComma, prop);\n      }\n    } else {\n      this.toAssignable(prop, isLHS);\n    }\n  }\n\n  // Convert list of expression atoms to binding list.\n\n  toAssignableList(\n    exprList: (\n      | Expression\n      | SpreadElement\n      | RestElement\n      | VoidPattern\n      | AssignmentPattern\n      | null\n    )[],\n    trailingCommaLoc: Position | undefined | null,\n    isLHS: boolean,\n  ): void {\n    const end = exprList.length - 1;\n\n    for (let i = 0; i <= end; i++) {\n      const elt = exprList[i];\n      if (!elt) continue;\n\n      this.toAssignableListItem(exprList, i, isLHS);\n\n      if (elt.type === \"RestElement\") {\n        if (i < end) {\n          this.raise(Errors.RestTrailingComma, elt);\n        } else if (trailingCommaLoc) {\n          this.raise(Errors.RestTrailingComma, trailingCommaLoc);\n        }\n      }\n    }\n  }\n\n  toAssignableListItem(\n    exprList: (\n      | Expression\n      | SpreadElement\n      | RestElement\n      | VoidPattern\n      | AssignmentPattern\n    )[],\n    index: number,\n    isLHS: boolean,\n  ): void {\n    const node = exprList[index];\n    if (node.type === \"SpreadElement\") {\n      this.castNodeTo(node, \"RestElement\");\n      const arg = node.argument;\n      this.checkToRestConversion(arg, /* allowPattern */ true);\n      this.toAssignable(arg, isLHS);\n    } else {\n      this.toAssignable(node, isLHS);\n    }\n  }\n\n  isAssignable(node: Node, isBinding?: boolean): boolean {\n    switch (node.type) {\n      case \"Identifier\":\n      case \"ObjectPattern\":\n      case \"ArrayPattern\":\n      case \"AssignmentPattern\":\n      case \"RestElement\":\n      case \"VoidPattern\":\n        return true;\n\n      case \"ObjectExpression\": {\n        const last = node.properties.length - 1;\n        return node.properties.every((prop, i) => {\n          return (\n            prop.type !== \"ObjectMethod\" &&\n            (i === last || prop.type !== \"SpreadElement\") &&\n            this.isAssignable(prop)\n          );\n        });\n      }\n\n      case \"ObjectProperty\":\n        return this.isAssignable(node.value);\n\n      case \"SpreadElement\":\n        return this.isAssignable(node.argument);\n\n      case \"ArrayExpression\":\n        return node.elements.every(\n          element => element === null || this.isAssignable(element),\n        );\n\n      case \"AssignmentExpression\":\n        return node.operator === \"=\";\n\n      case \"ParenthesizedExpression\":\n        return this.isAssignable(node.expression);\n\n      case \"MemberExpression\":\n      case \"OptionalMemberExpression\":\n        return !isBinding;\n\n      default:\n        return false;\n    }\n  }\n\n  // Convert list of expression atoms to a list of\n\n  toReferencedList(\n    exprList:\n      | ReadonlyArray<\n          Expression | SpreadElement | VoidPattern | AssignmentPattern\n        >\n      | ReadonlyArray<\n          Expression | RestElement | VoidPattern | AssignmentPattern\n        >,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    isParenthesizedExpr?: boolean,\n  ):\n    | ReadonlyArray<\n        Expression | SpreadElement | VoidPattern | AssignmentPattern\n      >\n    | ReadonlyArray<\n        Expression | RestElement | VoidPattern | AssignmentPattern\n      > {\n    return exprList;\n  }\n\n  toReferencedListDeep(\n    exprList:\n      | ReadonlyArray<\n          Expression | SpreadElement | VoidPattern | AssignmentPattern\n        >\n      | ReadonlyArray<\n          Expression | RestElement | VoidPattern | AssignmentPattern\n        >,\n    isParenthesizedExpr?: boolean,\n  ): void {\n    this.toReferencedList(exprList, isParenthesizedExpr);\n\n    for (const expr of exprList) {\n      if (expr?.type === \"ArrayExpression\") {\n        this.toReferencedListDeep(expr.elements);\n      }\n    }\n  }\n\n  // Parses spread element.\n\n  parseSpread(\n    this: Parser,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): SpreadElement {\n    const node = this.startNode<SpreadElement>();\n    this.next();\n    node.argument = this.parseMaybeAssignAllowIn(\n      refExpressionErrors,\n      undefined,\n    );\n    return this.finishNode(node, \"SpreadElement\");\n  }\n\n  // https://tc39.es/ecma262/#prod-BindingRestElement\n  parseRestBinding(this: Parser): RestElement {\n    const node = this.startNode<RestElement>();\n    this.next(); // eat `...`\n    const argument = this.parseBindingAtom();\n    if (argument.type === \"VoidPattern\") {\n      this.raise(Errors.UnexpectedVoidPattern, argument);\n    }\n    node.argument = argument;\n    return this.finishNode(node, \"RestElement\");\n  }\n\n  // Parses lvalue (assignable) atom.\n  parseBindingAtom(this: Parser): Pattern {\n    // https://tc39.es/ecma262/#prod-BindingPattern\n    switch (this.state.type) {\n      case tt.bracketL: {\n        const node = this.startNode<ArrayPattern>();\n        this.next();\n        node.elements = this.parseBindingList(\n          tt.bracketR,\n          charCodes.rightSquareBracket,\n          ParseBindingListFlags.ALLOW_EMPTY,\n        );\n        return this.finishNode(node, \"ArrayPattern\");\n      }\n\n      case tt.braceL:\n        return this.parseObjectLike(tt.braceR, true);\n\n      case tt._void:\n        return this.parseVoidPattern(null);\n    }\n\n    // https://tc39.es/ecma262/#prod-BindingIdentifier\n    return this.parseIdentifier();\n  }\n\n  // https://tc39.es/ecma262/#prod-BindingElementList\n  parseBindingList(\n    this: Parser,\n    close: TokenType,\n    closeCharCode: (typeof charCodes)[keyof typeof charCodes],\n    flags: ParseBindingListFlags.ALLOW_EMPTY,\n  ): Array<Pattern>;\n  parseBindingList(\n    this: Parser,\n    close: TokenType,\n    closeCharCode: (typeof charCodes)[keyof typeof charCodes],\n    flags: ParseBindingListFlags.IS_FUNCTION_PARAMS,\n  ): Array<Pattern | TSParameterProperty>;\n  parseBindingList(\n    this: Parser,\n    close: TokenType,\n    closeCharCode: (typeof charCodes)[keyof typeof charCodes],\n    flags: ParseBindingListFlags,\n  ): Array<Pattern | TSParameterProperty> {\n    const allowEmpty = flags & ParseBindingListFlags.ALLOW_EMPTY;\n\n    const elts: Array<Pattern | TSParameterProperty> = [];\n    let first = true;\n    while (!this.eat(close)) {\n      if (first) {\n        first = false;\n      } else {\n        this.expect(tt.comma);\n      }\n      if (allowEmpty && this.match(tt.comma)) {\n        elts.push(null);\n      } else if (this.eat(close)) {\n        break;\n      } else if (this.match(tt.ellipsis)) {\n        let rest: Pattern = this.parseRestBinding();\n        if (\n          (!process.env.BABEL_8_BREAKING && this.hasPlugin(\"flow\")) ||\n          flags & ParseBindingListFlags.IS_FUNCTION_PARAMS\n        ) {\n          rest = this.parseFunctionParamType(rest);\n        }\n        elts.push(rest);\n        if (!this.checkCommaAfterRest(closeCharCode)) {\n          this.expect(close);\n          break;\n        }\n      } else {\n        const decorators = [];\n        if (flags & ParseBindingListFlags.IS_FUNCTION_PARAMS) {\n          if (this.match(tt.at) && this.hasPlugin(\"decorators\")) {\n            this.raise(\n              Errors.UnsupportedParameterDecorator,\n              this.state.startLoc,\n            );\n          }\n          // invariant: hasPlugin(\"decorators-legacy\")\n          while (this.match(tt.at)) {\n            decorators.push(this.parseDecorator());\n          }\n        }\n        elts.push(this.parseBindingElement(flags, decorators));\n      }\n    }\n    return elts;\n  }\n\n  // https://tc39.es/ecma262/#prod-BindingRestProperty\n  parseBindingRestProperty(\n    this: Parser,\n    prop: Undone<RestElement>,\n  ): RestElement {\n    this.next(); // eat '...'\n    if (this.hasPlugin(\"discardBinding\") && this.match(tt._void)) {\n      prop.argument = this.parseVoidPattern(null);\n      this.raise(Errors.UnexpectedVoidPattern, prop.argument);\n    } else {\n      // Don't use parseRestBinding() as we only allow Identifier here.\n      prop.argument = this.parseIdentifier();\n    }\n    this.checkCommaAfterRest(charCodes.rightCurlyBrace);\n    return this.finishNode(prop, \"RestElement\");\n  }\n\n  // https://tc39.es/ecma262/#prod-BindingProperty\n  parseBindingProperty(this: Parser): AssignmentProperty | RestElement {\n    const { type, startLoc } = this.state;\n    if (type === tt.ellipsis) {\n      return this.parseBindingRestProperty(this.startNode());\n    }\n\n    const prop = this.startNode<AssignmentProperty>();\n    if (type === tt.privateName) {\n      this.expectPlugin(\"destructuringPrivate\", startLoc);\n      this.classScope.usePrivateName(this.state.value, startLoc);\n      prop.key = this.parsePrivateName();\n    } else {\n      this.parsePropertyName(prop);\n    }\n    prop.method = false;\n    return this.parseObjPropValue(\n      prop,\n      startLoc,\n      false /* isGenerator */,\n      false /* isAsync */,\n      true /* isPattern */,\n      false /* isAccessor */,\n    );\n  }\n\n  // https://tc39.es/ecma262/#prod-BindingElement\n  parseBindingElement(\n    this: Parser,\n    flags: ParseBindingListFlags,\n    decorators: Decorator[],\n  ): Pattern | TSParameterProperty {\n    const left = this.parseMaybeDefault();\n    if (\n      (!process.env.BABEL_8_BREAKING && this.hasPlugin(\"flow\")) ||\n      flags & ParseBindingListFlags.IS_FUNCTION_PARAMS\n    ) {\n      this.parseFunctionParamType(left);\n    }\n    if (decorators.length) {\n      left.decorators = decorators;\n      this.resetStartLocationFromNode(left, decorators[0]);\n    }\n    const elt = this.parseMaybeDefault(left.loc.start, left);\n    return elt;\n  }\n\n  // Used by flow/typescript plugin to add type annotations to binding elements\n  parseFunctionParamType(param: Pattern): Pattern {\n    return param;\n  }\n\n  // Parses assignment pattern around given atom if possible.\n  // https://tc39.es/ecma262/#prod-BindingElement\n  parseMaybeDefault<P extends Pattern>(\n    this: Parser,\n    startLoc?: Position | null,\n    left?: P,\n  ): P | AssignmentPattern;\n  parseMaybeDefault(\n    this: Parser,\n    startLoc?: Position | null,\n    left?: Pattern | null,\n  ): Pattern {\n    startLoc ??= this.state.startLoc;\n    left = left ?? this.parseBindingAtom();\n    if (!this.eat(tt.eq)) return left;\n\n    const node = this.startNodeAt<AssignmentPattern>(startLoc);\n    if (left.type === \"VoidPattern\") {\n      this.raise(Errors.VoidPatternInitializer, left);\n    }\n    node.left = left;\n    node.right = this.parseMaybeAssignAllowIn();\n    return this.finishNode(node, \"AssignmentPattern\");\n  }\n  /**\n   * Return information use in determining whether a Node of a given type is an LVal,\n   * possibly given certain additional context information.\n   *\n   * Subclasser notes: This method has kind of a lot of mixed, but related,\n   * responsibilities. If we can definitively determine with the information\n   * provided that this either *is* or *isn't* a valid `LVal`, then the return\n   * value is easy: just return `true` or `false`. However, if it is a valid\n   * LVal *ancestor*, and thus its descendants must be subsequently visited to\n   * continue the \"investigation\", then this method should return the relevant\n   * child key as a `string`. In some special cases, you additionally want to\n   * convey that this node should be treated as if it were parenthesized. In\n   * that case, a tuple of [key: string, parenthesized: boolean] is returned.\n   * The `string`-only return option is actually just a shorthand for:\n   * `[key: string, parenthesized: false]`.\n   *\n   * @param type A Node `type` string\n   * @param isUnparenthesizedInAssign\n   *        Whether the node in question is unparenthesized and its parent\n   *        is either an assignment pattern or an assignment expression.\n   * @param binding\n   *        The binding operation that is being considered for this potential\n   *        LVal.\n   * @returns `true` or `false` if we can immediately determine whether the node\n   *          type in question can be treated as an `LVal`.\n   *          A `string` key to traverse if we must check this child.\n   *          A `[string, boolean]` tuple if we need to check this child and\n   *          treat is as parenthesized.\n   */\n  isValidLVal(\n    type: string,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    isUnparenthesizedInAssign: boolean,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    binding: BindingFlag,\n  ): string | boolean | [string, boolean] {\n    switch (type) {\n      case \"AssignmentPattern\":\n        return \"left\";\n      case \"RestElement\":\n        return \"argument\";\n      case \"ObjectProperty\":\n        return \"value\";\n      case \"ParenthesizedExpression\":\n        return \"expression\";\n      case \"ArrayPattern\":\n        return \"elements\";\n      case \"ObjectPattern\":\n        return \"properties\";\n      case \"VoidPattern\":\n        return true;\n    }\n    return false;\n  }\n\n  // Overridden by the estree plugin\n  isOptionalMemberExpression(expression: Node): boolean {\n    return expression.type === \"OptionalMemberExpression\";\n  }\n\n  /**\n   * Verify that a target expression is an lval (something that can be assigned to).\n   *\n   * @param expression The expression in question to check.\n   * @param ancestor\n   *        The relevant ancestor to provide context information for the error\n   *        if the check fails.\n   * @param binding\n   *        The desired binding type. If the given expression is an identifier\n   *        and `binding` is not `BindingFlag.TYPE_NONE`, `checkLVal` will register binding\n   *        to the parser scope See also `src/util/scopeflags.js`\n   * @param checkClashes\n   *        An optional string set to check if an identifier name is included.\n   *        `checkLVal` will add checked identifier name to `checkClashes` It is\n   *        used in tracking duplicates in function parameter lists. If it is\n   *        false, `checkLVal` will skip duplicate checks\n   * @param strictModeChanged\n   *        Whether an identifier has been parsed in a sloppy context but should\n   *        be reinterpreted as strict-mode. e.g. `(arguments) => { \"use strict \"}`\n   * @param hasParenthesizedAncestor\n   *        This is only used internally during recursive calls, and you should\n   *        not have to set it yourself.\n   */\n\n  checkLVal(\n    expression:\n      | Expression\n      | ObjectMember\n      | RestElement\n      | Pattern\n      | TSParameterProperty,\n    ancestor: LValAncestor,\n    binding: BindingFlag = BindingFlag.TYPE_NONE,\n    checkClashes: Set<string> | false = false,\n    strictModeChanged: boolean = false,\n    hasParenthesizedAncestor: boolean = false,\n  ): void {\n    const type = expression.type;\n\n    // If we find here an ObjectMethod, it's because this was originally\n    // an ObjectExpression which has then been converted.\n    // toAssignable already reported this error with a nicer message.\n    if (this.isObjectMethod(expression)) return;\n\n    const isOptionalMemberExpression =\n      this.isOptionalMemberExpression(expression);\n\n    if (isOptionalMemberExpression || type === \"MemberExpression\") {\n      if (isOptionalMemberExpression) {\n        this.expectPlugin(\"optionalChainingAssign\", expression.loc.start);\n        if (ancestor.type !== \"AssignmentExpression\") {\n          this.raise(Errors.InvalidLhsOptionalChaining, expression, {\n            ancestor,\n          });\n        }\n      }\n\n      if (binding !== BindingFlag.TYPE_NONE) {\n        this.raise(Errors.InvalidPropertyBindingPattern, expression);\n      }\n      return;\n    }\n\n    if (type === \"Identifier\") {\n      this.checkIdentifier(expression, binding, strictModeChanged);\n\n      const { name } = expression;\n\n      if (checkClashes) {\n        if (checkClashes.has(name)) {\n          this.raise(Errors.ParamDupe, expression);\n        } else {\n          checkClashes.add(name);\n        }\n      }\n\n      return;\n    } else if (type === \"VoidPattern\" && ancestor.type === \"CatchClause\") {\n      this.raise(Errors.VoidPatternCatchClauseParam, expression);\n    }\n\n    const validity = this.isValidLVal(\n      type,\n      !(hasParenthesizedAncestor || expression.extra?.parenthesized) &&\n        ancestor.type === \"AssignmentExpression\",\n      binding,\n    );\n\n    if (validity === true) return;\n    if (validity === false) {\n      const ParseErrorClass =\n        binding === BindingFlag.TYPE_NONE\n          ? Errors.InvalidLhs\n          : Errors.InvalidLhsBinding;\n\n      this.raise(ParseErrorClass, expression, { ancestor });\n      return;\n    }\n\n    let key: string, isParenthesizedExpression: boolean;\n    if (typeof validity === \"string\") {\n      key = validity;\n      isParenthesizedExpression = type === \"ParenthesizedExpression\";\n    } else {\n      [key, isParenthesizedExpression] = validity;\n    }\n\n    const nextAncestor =\n      type === \"ArrayPattern\" || type === \"ObjectPattern\"\n        ? ({ type } as const)\n        : ancestor;\n\n    // @ts-expect-error key may not index expression.\n    const val = expression[key];\n    if (Array.isArray(val)) {\n      for (const child of val) {\n        if (child) {\n          this.checkLVal(\n            child,\n            nextAncestor,\n            binding,\n            checkClashes,\n            strictModeChanged,\n            isParenthesizedExpression,\n          );\n        }\n      }\n    } else if (val) {\n      this.checkLVal(\n        val,\n        nextAncestor,\n        binding,\n        checkClashes,\n        strictModeChanged,\n        isParenthesizedExpression,\n      );\n    }\n  }\n\n  checkIdentifier(\n    at: Identifier,\n    bindingType: BindingFlag,\n    strictModeChanged: boolean = false,\n  ) {\n    if (\n      this.state.strict &&\n      (strictModeChanged\n        ? isStrictBindReservedWord(at.name, this.inModule)\n        : isStrictBindOnlyReservedWord(at.name))\n    ) {\n      if (bindingType === BindingFlag.TYPE_NONE) {\n        this.raise(Errors.StrictEvalArguments, at, { referenceName: at.name });\n      } else {\n        this.raise(Errors.StrictEvalArgumentsBinding, at, {\n          bindingName: at.name,\n        });\n      }\n    }\n\n    if (bindingType & BindingFlag.FLAG_NO_LET_IN_LEXICAL && at.name === \"let\") {\n      this.raise(Errors.LetInLexicalBinding, at);\n    }\n\n    if (!(bindingType & BindingFlag.TYPE_NONE)) {\n      this.declareNameFromIdentifier(at, bindingType);\n    }\n  }\n\n  declareNameFromIdentifier(identifier: Identifier, binding: BindingFlag) {\n    this.scope.declareName(identifier.name, binding, identifier.loc.start);\n  }\n\n  checkToRestConversion(node: Node, allowPattern: boolean): void {\n    switch (node.type) {\n      case \"ParenthesizedExpression\":\n        this.checkToRestConversion(node.expression, allowPattern);\n        break;\n      case \"Identifier\":\n      case \"MemberExpression\":\n        break;\n      case \"ArrayExpression\":\n      case \"ObjectExpression\":\n        if (allowPattern) break;\n      /* falls through */\n      default:\n        this.raise(Errors.InvalidRestAssignmentPattern, node);\n    }\n  }\n\n  checkCommaAfterRest(\n    close: (typeof charCodes)[keyof typeof charCodes],\n  ): boolean {\n    if (!this.match(tt.comma)) {\n      return false;\n    }\n\n    this.raise(\n      this.lookaheadCharCode() === close\n        ? Errors.RestTrailingComma\n        : Errors.ElementAfterRest,\n      this.state.startLoc,\n    );\n\n    return true;\n  }\n}\n","import type State from \"../../tokenizer/state.ts\";\nimport {\n  tokenIsIdentifier,\n  tokenIsTSDeclarationStart,\n  tokenIsTSTypeOperator,\n  tokenOperatorPrecedence,\n  tokenIsKeywordOrIdentifier,\n  tt,\n  type TokenType,\n  tokenIsTemplate,\n  tokenCanStartExpression,\n} from \"../../tokenizer/types.ts\";\nimport { types as tc } from \"../../tokenizer/context.ts\";\nimport type * as N from \"../../types.ts\";\nimport type { Position } from \"../../util/location.ts\";\nimport { createPositionWithColumnOffset } from \"../../util/location.ts\";\nimport type Parser from \"../../parser/index.ts\";\nimport { ScopeFlag, BindingFlag } from \"../../util/scopeflags.ts\";\nimport TypeScriptScopeHandler from \"./scope.ts\";\nimport * as charCodes from \"charcodes\";\nimport type { ExpressionErrors } from \"../../parser/util.ts\";\nimport type { ParseStatementFlag } from \"../../parser/statement.ts\";\nimport { ParamKind } from \"../../util/production-parameter.ts\";\nimport { Errors, ParseErrorEnum } from \"../../parse-error.ts\";\nimport type { Undone } from \"../../parser/node.ts\";\nimport type { ClassWithMixin, IJSXParserMixin } from \"../jsx/index.ts\";\nimport { ParseBindingListFlags } from \"../../parser/lval.ts\";\nimport { OptionFlags } from \"../../options.ts\";\n\ntype TsModifier =\n  | \"readonly\"\n  | \"abstract\"\n  | \"declare\"\n  | \"static\"\n  | \"override\"\n  | \"const\"\n  | N.Accessibility\n  | N.VarianceAnnotations;\n\nfunction nonNull<T>(x?: T | null): T {\n  if (x == null) {\n    throw new Error(`Unexpected ${x} value.`);\n  }\n  return x;\n}\n\nfunction assert(x: boolean): void {\n  if (!x) {\n    throw new Error(\"Assert fail\");\n  }\n}\n\ntype ParsingContext =\n  | \"EnumMembers\"\n  | \"HeritageClauseElement\"\n  | \"TupleElementTypes\"\n  | \"TypeMembers\"\n  | \"TypeParametersOrArguments\";\n\ntype ModifierBase = {\n  accessibility?: N.Accessibility;\n} & {\n  [key in TsModifier]?: boolean | undefined | null;\n};\n\n/* eslint sort-keys: \"error\" */\nconst TSErrors = ParseErrorEnum`typescript`({\n  AbstractMethodHasImplementation: ({ methodName }: { methodName: string }) =>\n    `Method '${methodName}' cannot have an implementation because it is marked abstract.`,\n  AbstractPropertyHasInitializer: ({\n    propertyName,\n  }: {\n    propertyName: string;\n  }) =>\n    `Property '${propertyName}' cannot have an initializer because it is marked abstract.`,\n  AccessorCannotBeOptional:\n    \"An 'accessor' property cannot be declared optional.\",\n  AccessorCannotDeclareThisParameter:\n    \"'get' and 'set' accessors cannot declare 'this' parameters.\",\n  AccessorCannotHaveTypeParameters: \"An accessor cannot have type parameters.\",\n  ClassMethodHasDeclare: \"Class methods cannot have the 'declare' modifier.\",\n  ClassMethodHasReadonly: \"Class methods cannot have the 'readonly' modifier.\",\n  ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference:\n    \"A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.\",\n  ConstructorHasTypeParameters:\n    \"Type parameters cannot appear on a constructor declaration.\",\n  DeclareAccessor: ({ kind }: { kind: \"get\" | \"set\" }) =>\n    `'declare' is not allowed in ${kind}ters.`,\n  DeclareClassFieldHasInitializer:\n    \"Initializers are not allowed in ambient contexts.\",\n  DeclareFunctionHasImplementation:\n    \"An implementation cannot be declared in ambient contexts.\",\n  DuplicateAccessibilityModifier: ({\n    modifier,\n  }: {\n    modifier: N.Accessibility;\n  }) => `Accessibility modifier already seen: '${modifier}'.`,\n  DuplicateModifier: ({ modifier }: { modifier: TsModifier }) =>\n    `Duplicate modifier: '${modifier}'.`,\n  // `token` matches the terminology used by typescript:\n  // https://github.com/microsoft/TypeScript/blob/main/src/compiler/types.ts#L2915\n  EmptyHeritageClauseType: ({ token }: { token: \"extends\" | \"implements\" }) =>\n    `'${token}' list cannot be empty.`,\n  EmptyTypeArguments: \"Type argument list cannot be empty.\",\n  EmptyTypeParameters: \"Type parameter list cannot be empty.\",\n  ExpectedAmbientAfterExportDeclare:\n    \"'export declare' must be followed by an ambient declaration.\",\n  ImportAliasHasImportType: \"An import alias can not use 'import type'.\",\n  ImportReflectionHasImportType:\n    \"An `import module` declaration can not use `type` modifier\",\n  IncompatibleModifiers: ({\n    modifiers,\n  }: {\n    modifiers: [TsModifier, TsModifier];\n  }) =>\n    `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`,\n  IndexSignatureHasAbstract:\n    \"Index signatures cannot have the 'abstract' modifier.\",\n  IndexSignatureHasAccessibility: ({\n    modifier,\n  }: {\n    modifier: N.Accessibility;\n  }) =>\n    `Index signatures cannot have an accessibility modifier ('${modifier}').`,\n  IndexSignatureHasDeclare:\n    \"Index signatures cannot have the 'declare' modifier.\",\n  IndexSignatureHasOverride:\n    \"'override' modifier cannot appear on an index signature.\",\n  IndexSignatureHasStatic:\n    \"Index signatures cannot have the 'static' modifier.\",\n  InitializerNotAllowedInAmbientContext:\n    \"Initializers are not allowed in ambient contexts.\",\n  InvalidHeritageClauseType: ({ token }: { token: \"extends\" | \"implements\" }) =>\n    `'${token}' list can only include identifiers or qualified-names with optional type arguments.`,\n  InvalidModifierOnAwaitUsingDeclaration: (modifier: TsModifier) =>\n    `'${modifier}' modifier cannot appear on an await using declaration.`,\n  InvalidModifierOnTypeMember: ({ modifier }: { modifier: TsModifier }) =>\n    `'${modifier}' modifier cannot appear on a type member.`,\n  InvalidModifierOnTypeParameter: ({ modifier }: { modifier: TsModifier }) =>\n    `'${modifier}' modifier cannot appear on a type parameter.`,\n  InvalidModifierOnTypeParameterPositions: ({\n    modifier,\n  }: {\n    modifier: TsModifier;\n  }) =>\n    `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`,\n\n  InvalidModifierOnUsingDeclaration: (modifier: TsModifier) =>\n    `'${modifier}' modifier cannot appear on a using declaration.`,\n  InvalidModifiersOrder: ({\n    orderedModifiers,\n  }: {\n    orderedModifiers: [TsModifier, TsModifier];\n  }) =>\n    `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`,\n  InvalidPropertyAccessAfterInstantiationExpression:\n    \"Invalid property access after an instantiation expression. \" +\n    \"You can either wrap the instantiation expression in parentheses, or delete the type arguments.\",\n  InvalidTupleMemberLabel:\n    \"Tuple members must be labeled with a simple identifier.\",\n  MissingInterfaceName:\n    \"'interface' declarations must be followed by an identifier.\",\n  NonAbstractClassHasAbstractMethod:\n    \"Abstract methods can only appear within an abstract class.\",\n  NonClassMethodPropertyHasAbstractModifier:\n    \"'abstract' modifier can only appear on a class, method, or property declaration.\",\n  OptionalTypeBeforeRequired:\n    \"A required element cannot follow an optional element.\",\n  OverrideNotInSubClass:\n    \"This member cannot have an 'override' modifier because its containing class does not extend another class.\",\n  PatternIsOptional:\n    \"A binding pattern parameter cannot be optional in an implementation signature.\",\n  PrivateElementHasAbstract:\n    \"Private elements cannot have the 'abstract' modifier.\",\n  PrivateElementHasAccessibility: ({\n    modifier,\n  }: {\n    modifier: N.Accessibility;\n  }) =>\n    `Private elements cannot have an accessibility modifier ('${modifier}').`,\n  ReadonlyForMethodSignature:\n    \"'readonly' modifier can only appear on a property declaration or index signature.\",\n  ReservedArrowTypeParam:\n    \"This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.\",\n  ReservedTypeAssertion:\n    \"This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.\",\n  SetAccessorCannotHaveOptionalParameter:\n    \"A 'set' accessor cannot have an optional parameter.\",\n  SetAccessorCannotHaveRestParameter:\n    \"A 'set' accessor cannot have rest parameter.\",\n  SetAccessorCannotHaveReturnType:\n    \"A 'set' accessor cannot have a return type annotation.\",\n  SingleTypeParameterWithoutTrailingComma: ({\n    typeParameterName,\n  }: {\n    typeParameterName: string;\n  }) =>\n    `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`,\n  StaticBlockCannotHaveModifier:\n    \"Static class blocks cannot have any modifier.\",\n  TupleOptionalAfterType:\n    \"A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).\",\n  TypeAnnotationAfterAssign:\n    \"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.\",\n  TypeImportCannotSpecifyDefaultAndNamed:\n    \"A type-only import can specify a default import or named bindings, but not both.\",\n  TypeModifierIsUsedInTypeExports:\n    \"The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.\",\n  TypeModifierIsUsedInTypeImports:\n    \"The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.\",\n  UnexpectedParameterModifier:\n    \"A parameter property is only allowed in a constructor implementation.\",\n  UnexpectedReadonly:\n    \"'readonly' type modifier is only permitted on array and tuple literal types.\",\n  UnexpectedTypeAnnotation: \"Did not expect a type annotation here.\",\n  UnexpectedTypeCastInParameter: \"Unexpected type cast in parameter position.\",\n  UnsupportedImportTypeArgument:\n    \"Argument in a type import must be a string literal.\",\n  UnsupportedParameterPropertyKind:\n    \"A parameter property may not be declared using a binding pattern.\",\n  UnsupportedSignatureParameterKind: ({ type }: { type: string }) =>\n    `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.`,\n  UsingDeclarationInAmbientContext: (kind: \"using\" | \"await using\") =>\n    `'${kind}' declarations are not allowed in ambient contexts.`,\n});\n\n/* eslint-disable sort-keys */\n\n// Doesn't handle \"void\" or \"null\" because those are keywords, not identifiers.\n// It also doesn't handle \"intrinsic\", since usually it's not a keyword.\nfunction keywordTypeFromName(value: string): N.TsKeywordTypeType | undefined {\n  switch (value) {\n    case \"any\":\n      return \"TSAnyKeyword\";\n    case \"boolean\":\n      return \"TSBooleanKeyword\";\n    case \"bigint\":\n      return \"TSBigIntKeyword\";\n    case \"never\":\n      return \"TSNeverKeyword\";\n    case \"number\":\n      return \"TSNumberKeyword\";\n    case \"object\":\n      return \"TSObjectKeyword\";\n    case \"string\":\n      return \"TSStringKeyword\";\n    case \"symbol\":\n      return \"TSSymbolKeyword\";\n    case \"undefined\":\n      return \"TSUndefinedKeyword\";\n    case \"unknown\":\n      return \"TSUnknownKeyword\";\n    default:\n      return undefined;\n  }\n}\n\nfunction tsIsAccessModifier(modifier: string): modifier is N.Accessibility {\n  return (\n    modifier === \"private\" || modifier === \"public\" || modifier === \"protected\"\n  );\n}\n\nfunction tsIsVarianceAnnotations(\n  modifier: string,\n): modifier is N.VarianceAnnotations {\n  return modifier === \"in\" || modifier === \"out\";\n}\n\nfunction tsIsEntityName(\n  node: N.Expression,\n): node is N.MemberExpression | N.Identifier | N.TsInstantiationExpression {\n  if (node.extra?.parenthesized) {\n    return false;\n  }\n  switch (node.type) {\n    case \"Identifier\":\n      return true;\n    case \"MemberExpression\":\n      return !node.computed && tsIsEntityName(node.object);\n    case \"TSInstantiationExpression\":\n      return tsIsEntityName(node.expression);\n    default:\n      return false;\n  }\n}\n\nexport const enum tsParseEntityNameFlags {\n  NONE = 0b00,\n  ALLOW_RESERVED_WORDS = 0b01,\n  LEADING_THIS_AS_IDENTIFIER = 0b10,\n}\n\nexport default (superClass: ClassWithMixin<typeof Parser, IJSXParserMixin>) =>\n  class TypeScriptParserMixin extends superClass implements Parser {\n    getScopeHandler(): new (...args: any) => TypeScriptScopeHandler {\n      return TypeScriptScopeHandler;\n    }\n\n    tsIsIdentifier(): boolean {\n      // TODO: actually a bit more complex in TypeScript, but shouldn't matter.\n      // See https://github.com/Microsoft/TypeScript/issues/15008\n      return tokenIsIdentifier(this.state.type);\n    }\n\n    tsTokenCanFollowModifier() {\n      return (\n        this.match(tt.bracketL) ||\n        this.match(tt.braceL) ||\n        this.match(tt.star) ||\n        this.match(tt.ellipsis) ||\n        this.match(tt.privateName) ||\n        this.isLiteralPropertyName()\n      );\n    }\n\n    tsNextTokenOnSameLineAndCanFollowModifier() {\n      this.next();\n      if (this.hasPrecedingLineBreak()) {\n        return false;\n      }\n      return this.tsTokenCanFollowModifier();\n    }\n\n    tsNextTokenCanFollowModifier() {\n      // Note: TypeScript's implementation is much more complicated because\n      // more things are considered modifiers there.\n      // This implementation only handles modifiers not handled by @babel/parser itself. And \"static\".\n      if (this.match(tt._static)) {\n        this.next();\n        return this.tsTokenCanFollowModifier();\n      }\n      return this.tsNextTokenOnSameLineAndCanFollowModifier();\n    }\n\n    /** Parses a modifier matching one the given modifier names. */\n    tsParseModifier<T extends TsModifier>(\n      allowedModifiers: T[],\n      stopOnStartOfClassStaticBlock?: boolean,\n      hasSeenStaticModifier?: boolean,\n    ): T | undefined | null {\n      if (\n        !tokenIsIdentifier(this.state.type) &&\n        this.state.type !== tt._in &&\n        this.state.type !== tt._const\n      ) {\n        return undefined;\n      }\n\n      const modifier = this.state.value;\n      if (allowedModifiers.includes(modifier)) {\n        if (hasSeenStaticModifier && this.match(tt._static)) {\n          return undefined;\n        }\n        if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {\n          return undefined;\n        }\n        if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {\n          return modifier;\n        }\n      }\n      return undefined;\n    }\n\n    /** Parses a list of modifiers, in any order.\n     *  If you need a specific order, you must call this function multiple times:\n     *    this.tsParseModifiers({ modified: node, allowedModifiers: [\"public\"] });\n     *    this.tsParseModifiers({ modified: node, allowedModifiers: [\"abstract\", \"readonly\"] });\n     */\n    tsParseModifiers<N extends ModifierBase>(\n      {\n        allowedModifiers,\n        disallowedModifiers,\n        stopOnStartOfClassStaticBlock,\n        errorTemplate = TSErrors.InvalidModifierOnTypeMember,\n      }: {\n        allowedModifiers: readonly TsModifier[];\n        disallowedModifiers?: TsModifier[];\n        stopOnStartOfClassStaticBlock?: boolean;\n        errorTemplate?: typeof TSErrors.InvalidModifierOnTypeMember;\n      },\n      modified: N,\n    ): void {\n      const enforceOrder = (\n        loc: Position,\n        modifier: TsModifier,\n        before: TsModifier,\n        after: TsModifier,\n      ) => {\n        if (modifier === before && modified[after]) {\n          this.raise(TSErrors.InvalidModifiersOrder, loc, {\n            orderedModifiers: [before, after],\n          });\n        }\n      };\n      const incompatible = (\n        loc: Position,\n        modifier: TsModifier,\n        mod1: TsModifier,\n        mod2: TsModifier,\n      ) => {\n        if (\n          (modified[mod1] && modifier === mod2) ||\n          (modified[mod2] && modifier === mod1)\n        ) {\n          this.raise(TSErrors.IncompatibleModifiers, loc, {\n            modifiers: [mod1, mod2],\n          });\n        }\n      };\n\n      for (;;) {\n        const { startLoc } = this.state;\n        const modifier: TsModifier | undefined | null = this.tsParseModifier(\n          allowedModifiers.concat(disallowedModifiers ?? []),\n          stopOnStartOfClassStaticBlock,\n          modified.static,\n        );\n\n        if (!modifier) break;\n\n        if (tsIsAccessModifier(modifier)) {\n          if (modified.accessibility) {\n            this.raise(TSErrors.DuplicateAccessibilityModifier, startLoc, {\n              modifier,\n            });\n          } else {\n            enforceOrder(startLoc, modifier, modifier, \"override\");\n            enforceOrder(startLoc, modifier, modifier, \"static\");\n            enforceOrder(startLoc, modifier, modifier, \"readonly\");\n\n            modified.accessibility = modifier;\n          }\n        } else if (tsIsVarianceAnnotations(modifier)) {\n          if (modified[modifier]) {\n            this.raise(TSErrors.DuplicateModifier, startLoc, { modifier });\n          }\n          modified[modifier] = true;\n\n          enforceOrder(startLoc, modifier, \"in\", \"out\");\n        } else {\n          if (Object.hasOwn(modified, modifier)) {\n            this.raise(TSErrors.DuplicateModifier, startLoc, { modifier });\n          } else {\n            enforceOrder(startLoc, modifier, \"static\", \"readonly\");\n            enforceOrder(startLoc, modifier, \"static\", \"override\");\n            enforceOrder(startLoc, modifier, \"override\", \"readonly\");\n            enforceOrder(startLoc, modifier, \"abstract\", \"override\");\n\n            incompatible(startLoc, modifier, \"declare\", \"override\");\n            incompatible(startLoc, modifier, \"static\", \"abstract\");\n          }\n          modified[modifier] = true;\n        }\n\n        if (disallowedModifiers?.includes(modifier)) {\n          this.raise(errorTemplate, startLoc, {\n            modifier,\n          });\n        }\n      }\n    }\n\n    tsIsListTerminator(kind: ParsingContext): boolean {\n      switch (kind) {\n        case \"EnumMembers\":\n        case \"TypeMembers\":\n          return this.match(tt.braceR);\n        case \"HeritageClauseElement\":\n          return this.match(tt.braceL);\n        case \"TupleElementTypes\":\n          return this.match(tt.bracketR);\n        case \"TypeParametersOrArguments\":\n          return this.match(tt.gt);\n      }\n    }\n\n    tsParseList<T extends N.Node>(\n      kind: ParsingContext,\n      parseElement: () => T,\n    ): T[] {\n      const result: T[] = [];\n      while (!this.tsIsListTerminator(kind)) {\n        // Skipping \"parseListElement\" from the TS source since that's just for error handling.\n        result.push(parseElement());\n      }\n      return result;\n    }\n\n    tsParseDelimitedList<T extends N.Node>(\n      kind: ParsingContext,\n      parseElement: () => T,\n      refTrailingCommaPos?: {\n        value: number;\n      },\n    ): T[] {\n      return nonNull(\n        this.tsParseDelimitedListWorker(\n          kind,\n          parseElement,\n          /* expectSuccess */ true,\n          refTrailingCommaPos,\n        ),\n      );\n    }\n\n    /**\n     * If !expectSuccess, returns undefined instead of failing to parse.\n     * If expectSuccess, parseElement should always return a defined value.\n     */\n    tsParseDelimitedListWorker<T extends N.Node>(\n      kind: ParsingContext,\n      parseElement: () => T | undefined,\n      expectSuccess: boolean,\n      refTrailingCommaPos?: {\n        value: number;\n      },\n    ): T[] | undefined {\n      const result: T[] = [];\n      let trailingCommaPos = -1;\n\n      for (;;) {\n        if (this.tsIsListTerminator(kind)) {\n          break;\n        }\n        trailingCommaPos = -1;\n\n        const element = parseElement();\n        if (element == null) {\n          return undefined;\n        }\n        result.push(element);\n\n        if (this.eat(tt.comma)) {\n          trailingCommaPos = this.state.lastTokStartLoc.index;\n          continue;\n        }\n\n        if (this.tsIsListTerminator(kind)) {\n          break;\n        }\n\n        if (expectSuccess) {\n          // This will fail with an error about a missing comma\n          this.expect(tt.comma);\n        }\n        return undefined;\n      }\n\n      if (refTrailingCommaPos) {\n        refTrailingCommaPos.value = trailingCommaPos;\n      }\n\n      return result;\n    }\n\n    tsParseBracketedList<T extends N.Node>(\n      kind: ParsingContext,\n      parseElement: () => T,\n      bracket: boolean,\n      skipFirstToken: boolean,\n      refTrailingCommaPos?: {\n        value: number;\n      },\n    ): T[] {\n      if (!skipFirstToken) {\n        if (bracket) {\n          this.expect(tt.bracketL);\n        } else {\n          this.expect(tt.lt);\n        }\n      }\n\n      const result = this.tsParseDelimitedList(\n        kind,\n        parseElement,\n        refTrailingCommaPos,\n      );\n\n      if (bracket) {\n        this.expect(tt.bracketR);\n      } else {\n        this.expect(tt.gt);\n      }\n\n      return result;\n    }\n\n    tsParseImportType(): N.TsImportType {\n      const node = this.startNode<N.TsImportType>();\n      this.expect(tt._import);\n      this.expect(tt.parenL);\n      if (!this.match(tt.string)) {\n        this.raise(TSErrors.UnsupportedImportTypeArgument, this.state.startLoc);\n        if (process.env.BABEL_8_BREAKING) {\n          // Consume as an non-conditional type so that we can recover from this error\n          node.argument = this.tsParseNonConditionalType() as any;\n        } else {\n          node.argument = super.parseExprAtom() as any;\n        }\n      } else {\n        if (process.env.BABEL_8_BREAKING) {\n          node.argument = this.tsParseLiteralTypeNode();\n        } else {\n          // @ts-ignore(Babel 7 vs Babel 8) Babel 7 AST\n          node.argument = this.parseStringLiteral(this.state.value);\n        }\n      }\n      if (this.eat(tt.comma)) {\n        node.options = this.tsParseImportTypeOptions();\n      } else {\n        node.options = null;\n      }\n      this.expect(tt.parenR);\n\n      if (this.eat(tt.dot)) {\n        // In this instance, the entity name will actually itself be a\n        // qualifier, so allow it to be a reserved word as well.\n        node.qualifier = this.tsParseEntityName(\n          tsParseEntityNameFlags.ALLOW_RESERVED_WORDS |\n            tsParseEntityNameFlags.LEADING_THIS_AS_IDENTIFIER,\n        );\n      }\n      if (this.match(tt.lt)) {\n        if (process.env.BABEL_8_BREAKING) {\n          node.typeArguments = this.tsParseTypeArguments();\n        } else {\n          node.typeParameters = this.tsParseTypeArguments();\n        }\n      }\n      return this.finishNode(node, \"TSImportType\");\n    }\n\n    tsParseImportTypeOptions(): N.ObjectExpression {\n      const node = this.startNode<N.ObjectExpression>();\n      this.expect(tt.braceL);\n      const withProperty = this.startNode<N.ObjectProperty>();\n      if (this.isContextual(tt._with)) {\n        withProperty.method = false;\n        withProperty.key = this.parseIdentifier(true);\n        withProperty.computed = false;\n        withProperty.shorthand = false;\n      } else {\n        this.unexpected(null, tt._with);\n      }\n      this.expect(tt.colon);\n      withProperty.value = this.tsParseImportTypeWithPropertyValue();\n      node.properties = [this.finishObjectProperty(withProperty)];\n      this.eat(tt.comma);\n      this.expect(tt.braceR);\n      return this.finishNode(node, \"ObjectExpression\");\n    }\n\n    tsParseImportTypeWithPropertyValue(): N.ObjectExpression {\n      const node = this.startNode<N.ObjectExpression>();\n      const properties = [];\n      this.expect(tt.braceL);\n      while (!this.match(tt.braceR)) {\n        const type = this.state.type;\n        if (tokenIsIdentifier(type) || type === tt.string) {\n          properties.push(super.parsePropertyDefinition(null));\n        } else {\n          this.unexpected();\n        }\n        this.eat(tt.comma);\n      }\n      node.properties = properties;\n      this.next(); // eat }\n      return this.finishNode(node, \"ObjectExpression\");\n    }\n\n    tsParseEntityName(flags: tsParseEntityNameFlags): N.TsEntityName {\n      let entity: N.TsEntityName;\n      if (\n        flags & tsParseEntityNameFlags.ALLOW_RESERVED_WORDS &&\n        this.match(tt._this)\n      ) {\n        if (flags & tsParseEntityNameFlags.LEADING_THIS_AS_IDENTIFIER) {\n          entity = this.parseIdentifier(true);\n        } else {\n          const node = this.startNode<N.ThisExpression>();\n          this.next();\n          entity = this.finishNode(node, \"ThisExpression\");\n        }\n      } else {\n        entity = this.parseIdentifier(\n          !!(flags & tsParseEntityNameFlags.ALLOW_RESERVED_WORDS),\n        );\n      }\n      while (this.eat(tt.dot)) {\n        const node: Undone<N.TsQualifiedName> =\n          this.startNodeAtNode<N.TsQualifiedName>(entity);\n        node.left = entity;\n        node.right = this.parseIdentifier(\n          !!(flags & tsParseEntityNameFlags.ALLOW_RESERVED_WORDS),\n        );\n        entity = this.finishNode(node, \"TSQualifiedName\");\n      }\n      return entity;\n    }\n\n    tsParseTypeReference(): N.TsTypeReference {\n      const node = this.startNode<N.TsTypeReference>();\n      node.typeName = this.tsParseEntityName(\n        tsParseEntityNameFlags.ALLOW_RESERVED_WORDS,\n      );\n      if (!this.hasPrecedingLineBreak() && this.match(tt.lt)) {\n        if (process.env.BABEL_8_BREAKING) {\n          node.typeArguments = this.tsParseTypeArguments();\n        } else {\n          node.typeParameters = this.tsParseTypeArguments();\n        }\n      }\n      return this.finishNode(node, \"TSTypeReference\");\n    }\n\n    tsParseThisTypePredicate(lhs: N.TsThisType): N.TsTypePredicate {\n      this.next();\n      const node = this.startNodeAtNode<N.TsTypePredicate>(lhs);\n      node.parameterName = lhs;\n      node.typeAnnotation = this.tsParseTypeAnnotation(/* eatColon */ false);\n      node.asserts = false;\n      return this.finishNode(node, \"TSTypePredicate\");\n    }\n\n    tsParseThisTypeNode(): N.TsThisType {\n      const node = this.startNode<N.TsThisType>();\n      this.next();\n      return this.finishNode(node, \"TSThisType\");\n    }\n\n    tsParseTypeQuery(): N.TsTypeQuery {\n      const node = this.startNode<N.TsTypeQuery>();\n      this.expect(tt._typeof);\n      if (this.match(tt._import)) {\n        node.exprName = this.tsParseImportType();\n      } else {\n        if (process.env.BABEL_8_BREAKING) {\n          node.exprName = this.tsParseEntityName(\n            tsParseEntityNameFlags.ALLOW_RESERVED_WORDS,\n          );\n        } else {\n          node.exprName = this.tsParseEntityName(\n            tsParseEntityNameFlags.ALLOW_RESERVED_WORDS |\n              tsParseEntityNameFlags.LEADING_THIS_AS_IDENTIFIER,\n          );\n        }\n      }\n      if (!this.hasPrecedingLineBreak() && this.match(tt.lt)) {\n        if (process.env.BABEL_8_BREAKING) {\n          node.typeArguments = this.tsParseTypeArguments();\n        } else {\n          node.typeParameters = this.tsParseTypeArguments();\n        }\n      }\n      return this.finishNode(node, \"TSTypeQuery\");\n    }\n\n    tsParseInOutModifiers = this.tsParseModifiers.bind(this, {\n      allowedModifiers: [\"in\", \"out\"],\n      disallowedModifiers: [\n        \"const\",\n        \"public\",\n        \"private\",\n        \"protected\",\n        \"readonly\",\n        \"declare\",\n        \"abstract\",\n        \"override\",\n      ],\n      errorTemplate: TSErrors.InvalidModifierOnTypeParameter,\n    });\n\n    tsParseConstModifier = this.tsParseModifiers.bind(this, {\n      allowedModifiers: [\"const\"],\n      // for better error recovery\n      disallowedModifiers: [\"in\", \"out\"],\n      errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions,\n    });\n\n    tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, {\n      allowedModifiers: [\"in\", \"out\", \"const\"],\n      disallowedModifiers: [\n        \"public\",\n        \"private\",\n        \"protected\",\n        \"readonly\",\n        \"declare\",\n        \"abstract\",\n        \"override\",\n      ],\n      errorTemplate: TSErrors.InvalidModifierOnTypeParameter,\n    });\n\n    tsParseTypeParameter(\n      parseModifiers: (node: Undone<N.TsTypeParameter>) => void,\n    ): N.TsTypeParameter {\n      const node = this.startNode<N.TsTypeParameter>();\n\n      parseModifiers(node);\n\n      node.name = this.tsParseTypeParameterName();\n      node.constraint = this.tsEatThenParseType(tt._extends);\n      node.default = this.tsEatThenParseType(tt.eq);\n      return this.finishNode(node, \"TSTypeParameter\");\n    }\n\n    tsTryParseTypeParameters(\n      parseModifiers: (node: N.TsTypeParameter) => void,\n    ): N.TsTypeParameterDeclaration | undefined | null {\n      if (this.match(tt.lt)) {\n        return this.tsParseTypeParameters(parseModifiers);\n      }\n    }\n\n    tsParseTypeParameters(parseModifiers: (node: N.TsTypeParameter) => void) {\n      const node = this.startNode<N.TsTypeParameterDeclaration>();\n\n      if (this.match(tt.lt) || this.match(tt.jsxTagStart)) {\n        this.next();\n      } else {\n        this.unexpected();\n      }\n\n      const refTrailingCommaPos = { value: -1 };\n\n      node.params = this.tsParseBracketedList(\n        \"TypeParametersOrArguments\",\n        this.tsParseTypeParameter.bind(this, parseModifiers),\n        /* bracket */ false,\n        /* skipFirstToken */ true,\n        refTrailingCommaPos,\n      );\n      if (node.params.length === 0) {\n        this.raise(TSErrors.EmptyTypeParameters, node);\n      }\n      if (refTrailingCommaPos.value !== -1) {\n        this.addExtra(node, \"trailingComma\", refTrailingCommaPos.value);\n      }\n      return this.finishNode(node, \"TSTypeParameterDeclaration\");\n    }\n\n    // Note: In TypeScript implementation we must provide `yieldContext` and `awaitContext`,\n    // but here it's always false, because this is only used for types.\n    tsFillSignature(\n      returnToken: TokenType,\n      signature: Undone<N.TsSignatureDeclaration>,\n    ): void {\n      // Arrow fns *must* have return token (`=>`). Normal functions can omit it.\n      const returnTokenRequired = returnToken === tt.arrow;\n\n      // https://github.com/babel/babel/issues/9231\n      const paramsKey = process.env.BABEL_8_BREAKING ? \"params\" : \"parameters\";\n      const returnTypeKey = process.env.BABEL_8_BREAKING\n        ? \"returnType\"\n        : \"typeAnnotation\";\n\n      signature.typeParameters = this.tsTryParseTypeParameters(\n        this.tsParseConstModifier,\n      );\n      this.expect(tt.parenL);\n      signature[paramsKey] = this.tsParseBindingListForSignature();\n      if (returnTokenRequired) {\n        signature[returnTypeKey] =\n          this.tsParseTypeOrTypePredicateAnnotation(returnToken);\n      } else if (this.match(returnToken)) {\n        signature[returnTypeKey] =\n          this.tsParseTypeOrTypePredicateAnnotation(returnToken);\n      }\n    }\n\n    tsParseBindingListForSignature(): Array<\n      | N.Identifier\n      | N.RestElement\n      | N.ObjectPattern\n      | N.ArrayPattern\n      | N.VoidPattern\n    > {\n      const list = super.parseBindingList(\n        tt.parenR,\n        charCodes.rightParenthesis,\n        ParseBindingListFlags.IS_FUNCTION_PARAMS,\n      );\n      for (const pattern of list) {\n        const { type } = pattern;\n        if (type === \"AssignmentPattern\" || type === \"TSParameterProperty\") {\n          this.raise(TSErrors.UnsupportedSignatureParameterKind, pattern, {\n            type,\n          });\n        }\n      }\n      return list as Exclude<\n        (typeof list)[0],\n        N.AssignmentPattern | N.TSParameterProperty\n      >[];\n    }\n\n    tsParseTypeMemberSemicolon(): void {\n      if (!this.eat(tt.comma) && !this.isLineTerminator()) {\n        this.expect(tt.semi);\n      }\n    }\n\n    tsParseSignatureMember(\n      kind: \"TSCallSignatureDeclaration\" | \"TSConstructSignatureDeclaration\",\n      node: Undone<\n        N.TsCallSignatureDeclaration | N.TsConstructSignatureDeclaration\n      >,\n    ): N.TsCallSignatureDeclaration | N.TsConstructSignatureDeclaration {\n      this.tsFillSignature(tt.colon, node);\n      this.tsParseTypeMemberSemicolon();\n      return this.finishNode(node, kind);\n    }\n\n    tsIsUnambiguouslyIndexSignature() {\n      this.next(); // Skip '{'\n      if (tokenIsIdentifier(this.state.type)) {\n        this.next();\n        return this.match(tt.colon);\n      }\n      return false;\n    }\n\n    tsTryParseIndexSignature(\n      node: Undone<N.TsIndexSignature>,\n    ): N.TsIndexSignature | undefined {\n      if (\n        !(\n          this.match(tt.bracketL) &&\n          this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this))\n        )\n      ) {\n        return;\n      }\n\n      this.expect(tt.bracketL);\n      const id = this.parseIdentifier();\n      id.typeAnnotation = this.tsParseTypeAnnotation();\n      this.resetEndLocation(id); // set end position to end of type\n\n      this.expect(tt.bracketR);\n      node.parameters = [id];\n\n      const type = this.tsTryParseTypeAnnotation();\n      if (type) node.typeAnnotation = type;\n      this.tsParseTypeMemberSemicolon();\n      return this.finishNode(node, \"TSIndexSignature\");\n    }\n\n    tsParsePropertyOrMethodSignature(\n      node: Undone<N.TsPropertySignature | N.TsMethodSignature>,\n      readonly: boolean,\n    ): N.TsPropertySignature | N.TsMethodSignature {\n      if (this.eat(tt.question)) node.optional = true;\n\n      if (this.match(tt.parenL) || this.match(tt.lt)) {\n        if (readonly) {\n          this.raise(TSErrors.ReadonlyForMethodSignature, node);\n        }\n        const method = node as Undone<N.TsMethodSignature>;\n        if (method.kind && this.match(tt.lt)) {\n          this.raise(\n            TSErrors.AccessorCannotHaveTypeParameters,\n            this.state.curPosition(),\n          );\n        }\n        this.tsFillSignature(tt.colon, method);\n        this.tsParseTypeMemberSemicolon();\n        const paramsKey = process.env.BABEL_8_BREAKING\n          ? \"params\"\n          : \"parameters\";\n        const returnTypeKey = process.env.BABEL_8_BREAKING\n          ? \"returnType\"\n          : \"typeAnnotation\";\n        if (method.kind === \"get\") {\n          if (method[paramsKey].length > 0) {\n            this.raise(Errors.BadGetterArity, this.state.curPosition());\n            if (this.isThisParam(method[paramsKey][0])) {\n              this.raise(\n                TSErrors.AccessorCannotDeclareThisParameter,\n                this.state.curPosition(),\n              );\n            }\n          }\n        } else if (method.kind === \"set\") {\n          if (method[paramsKey].length !== 1) {\n            this.raise(Errors.BadSetterArity, this.state.curPosition());\n          } else {\n            const firstParameter = method[paramsKey][0];\n            if (this.isThisParam(firstParameter)) {\n              this.raise(\n                TSErrors.AccessorCannotDeclareThisParameter,\n                this.state.curPosition(),\n              );\n            }\n            if (\n              firstParameter.type === \"Identifier\" &&\n              firstParameter.optional\n            ) {\n              this.raise(\n                TSErrors.SetAccessorCannotHaveOptionalParameter,\n                this.state.curPosition(),\n              );\n            }\n            if (firstParameter.type === \"RestElement\") {\n              this.raise(\n                TSErrors.SetAccessorCannotHaveRestParameter,\n                this.state.curPosition(),\n              );\n            }\n          }\n          if (method[returnTypeKey]) {\n            this.raise(\n              TSErrors.SetAccessorCannotHaveReturnType,\n              method[returnTypeKey],\n            );\n          }\n        } else {\n          method.kind = \"method\";\n        }\n        return this.finishNode(method, \"TSMethodSignature\");\n      } else {\n        const property = node as Undone<N.TsPropertySignature>;\n        if (readonly) property.readonly = true;\n        const type = this.tsTryParseTypeAnnotation();\n        if (type) property.typeAnnotation = type;\n        this.tsParseTypeMemberSemicolon();\n        return this.finishNode(property, \"TSPropertySignature\");\n      }\n    }\n\n    tsParseTypeMember(): N.TsTypeElement {\n      const node: any = this.startNode();\n\n      if (this.match(tt.parenL) || this.match(tt.lt)) {\n        return this.tsParseSignatureMember(\"TSCallSignatureDeclaration\", node);\n      }\n\n      if (this.match(tt._new)) {\n        const id = this.startNode<N.Identifier>();\n        this.next();\n        if (this.match(tt.parenL) || this.match(tt.lt)) {\n          return this.tsParseSignatureMember(\n            \"TSConstructSignatureDeclaration\",\n            node,\n          );\n        } else {\n          node.key = this.createIdentifier(id, \"new\");\n          return this.tsParsePropertyOrMethodSignature(node, false);\n        }\n      }\n\n      this.tsParseModifiers(\n        {\n          allowedModifiers: [\"readonly\"],\n          disallowedModifiers: [\n            \"declare\",\n            \"abstract\",\n            \"private\",\n            \"protected\",\n            \"public\",\n            \"static\",\n            \"override\",\n          ],\n        },\n        node,\n      );\n\n      const idx = this.tsTryParseIndexSignature(node);\n      if (idx) {\n        return idx;\n      }\n\n      super.parsePropertyName(node);\n      if (\n        !node.computed &&\n        node.key.type === \"Identifier\" &&\n        (node.key.name === \"get\" || node.key.name === \"set\") &&\n        this.tsTokenCanFollowModifier()\n      ) {\n        node.kind = node.key.name;\n        super.parsePropertyName(node);\n        // Allow < here so that we can recover from get key<T> later\n        if (!this.match(tt.parenL) && !this.match(tt.lt)) {\n          this.unexpected(null, tt.parenL);\n        }\n      }\n      return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);\n    }\n\n    tsParseTypeLiteral(): N.TsTypeLiteral {\n      const node = this.startNode<N.TsTypeLiteral>();\n      node.members = this.tsParseObjectTypeMembers();\n      return this.finishNode(node, \"TSTypeLiteral\");\n    }\n\n    tsParseObjectTypeMembers(): Array<N.TsTypeElement> {\n      this.expect(tt.braceL);\n      const members = this.tsParseList(\n        \"TypeMembers\",\n        this.tsParseTypeMember.bind(this),\n      );\n      this.expect(tt.braceR);\n      return members;\n    }\n\n    tsIsStartOfMappedType(): boolean {\n      this.next();\n      if (this.eat(tt.plusMin)) {\n        return this.isContextual(tt._readonly);\n      }\n      if (this.isContextual(tt._readonly)) {\n        this.next();\n      }\n      if (!this.match(tt.bracketL)) {\n        return false;\n      }\n      this.next();\n      if (!this.tsIsIdentifier()) {\n        return false;\n      }\n      this.next();\n      return this.match(tt._in);\n    }\n\n    tsParseMappedType(): N.TsMappedType {\n      const node = this.startNode<N.TsMappedType>();\n\n      this.expect(tt.braceL);\n\n      if (this.match(tt.plusMin)) {\n        node.readonly = this.state.value;\n        this.next();\n        this.expectContextual(tt._readonly);\n      } else if (this.eatContextual(tt._readonly)) {\n        node.readonly = true;\n      }\n\n      this.expect(tt.bracketL);\n      if (process.env.BABEL_8_BREAKING) {\n        node.key = this.tsParseTypeParameterName() as N.Identifier;\n        node.constraint = this.tsExpectThenParseType(tt._in);\n      } else {\n        const typeParameter = this.startNode<N.TsTypeParameter>();\n        typeParameter.name = this.tsParseTypeParameterName();\n        typeParameter.constraint = this.tsExpectThenParseType(tt._in);\n        // @ts-expect-error for Babel 7\n        node.typeParameter = this.finishNode(typeParameter, \"TSTypeParameter\");\n      }\n      node.nameType = this.eatContextual(tt._as) ? this.tsParseType() : null;\n\n      this.expect(tt.bracketR);\n\n      if (this.match(tt.plusMin)) {\n        node.optional = this.state.value;\n        this.next();\n        this.expect(tt.question);\n      } else if (this.eat(tt.question)) {\n        node.optional = true;\n      }\n\n      node.typeAnnotation = this.tsTryParseType();\n      this.semicolon();\n      this.expect(tt.braceR);\n\n      return this.finishNode(node, \"TSMappedType\");\n    }\n\n    tsParseTupleType(): N.TsTupleType {\n      const node = this.startNode<N.TsTupleType>();\n      node.elementTypes = this.tsParseBracketedList(\n        \"TupleElementTypes\",\n        this.tsParseTupleElementType.bind(this),\n        /* bracket */ true,\n        /* skipFirstToken */ false,\n      );\n\n      // Validate the elementTypes to ensure that no mandatory elements\n      // follow optional elements\n      let seenOptionalElement = false;\n      node.elementTypes.forEach(elementNode => {\n        const { type } = elementNode;\n\n        if (\n          seenOptionalElement &&\n          type !== \"TSRestType\" &&\n          type !== \"TSOptionalType\" &&\n          !(type === \"TSNamedTupleMember\" && elementNode.optional)\n        ) {\n          this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode);\n        }\n\n        seenOptionalElement ||=\n          (type === \"TSNamedTupleMember\" && elementNode.optional) ||\n          type === \"TSOptionalType\";\n      });\n\n      return this.finishNode(node, \"TSTupleType\");\n    }\n\n    tsParseTupleElementType(): N.TsNamedTupleMember | N.TsType {\n      // parses `...TsType[]`\n\n      const restStartLoc = this.state.startLoc;\n\n      const rest = this.eat(tt.ellipsis);\n      const { startLoc } = this.state;\n\n      let labeled: boolean;\n      let label: N.Identifier;\n      let optional: boolean;\n      let type: N.TsNamedTupleMember | N.TsType;\n\n      const isWord = tokenIsKeywordOrIdentifier(this.state.type);\n      const chAfterWord = isWord ? this.lookaheadCharCode() : null;\n      if (chAfterWord === charCodes.colon) {\n        labeled = true;\n        optional = false;\n        label = this.parseIdentifier(true);\n        this.expect(tt.colon);\n        type = this.tsParseType();\n      } else if (chAfterWord === charCodes.questionMark) {\n        optional = true;\n        const wordName = this.state.value;\n        const typeOrLabel = this.tsParseNonArrayType();\n\n        if (this.lookaheadCharCode() === charCodes.colon) {\n          labeled = true;\n          label = this.createIdentifier(\n            this.startNodeAt<N.Identifier>(startLoc),\n            wordName,\n          );\n          this.expect(tt.question);\n          this.expect(tt.colon);\n          type = this.tsParseType();\n        } else {\n          labeled = false;\n          type = typeOrLabel;\n          this.expect(tt.question);\n        }\n      } else {\n        type = this.tsParseType();\n        optional = this.eat(tt.question);\n        // In this case (labeled === true) could be only in invalid label.\n        // E.g. [x.y:type]\n        // An error is raised while processing node.\n        labeled = this.eat(tt.colon);\n      }\n\n      if (labeled) {\n        let labeledNode: Undone<N.TsNamedTupleMember>;\n        if (label) {\n          labeledNode = this.startNodeAt<N.TsNamedTupleMember>(startLoc);\n          labeledNode.optional = optional;\n          labeledNode.label = label;\n          labeledNode.elementType = type;\n\n          if (this.eat(tt.question)) {\n            labeledNode.optional = true;\n            this.raise(\n              TSErrors.TupleOptionalAfterType,\n              this.state.lastTokStartLoc,\n            );\n          }\n        } else {\n          labeledNode = this.startNodeAt<N.TsNamedTupleMember>(startLoc);\n          labeledNode.optional = optional;\n          this.raise(TSErrors.InvalidTupleMemberLabel, type);\n          // @ts-expect-error This produces an invalid AST, but at least we don't drop\n          // nodes representing the invalid source.\n          labeledNode.label = type;\n          labeledNode.elementType = this.tsParseType();\n        }\n        type = this.finishNode(labeledNode, \"TSNamedTupleMember\");\n      } else if (optional) {\n        const optionalTypeNode = this.startNodeAt<N.TsOptionalType>(startLoc);\n        optionalTypeNode.typeAnnotation = type;\n        type = this.finishNode(optionalTypeNode, \"TSOptionalType\");\n      }\n\n      if (rest) {\n        const restNode = this.startNodeAt<N.TsRestType>(restStartLoc);\n        restNode.typeAnnotation = type;\n        type = this.finishNode(restNode, \"TSRestType\");\n      }\n\n      return type;\n    }\n\n    tsParseParenthesizedType(): N.TsParenthesizedType {\n      const node = this.startNode<N.TsParenthesizedType>();\n      this.expect(tt.parenL);\n      node.typeAnnotation = this.tsParseType();\n      this.expect(tt.parenR);\n      return this.finishNode(node, \"TSParenthesizedType\");\n    }\n\n    tsParseFunctionOrConstructorType(\n      type: \"TSFunctionType\" | \"TSConstructorType\",\n      abstract?: boolean,\n    ): N.TsFunctionOrConstructorType {\n      const node = this.startNode<\n        N.TsFunctionOrConstructorType | N.TsConstructorType\n      >();\n      if (type === \"TSConstructorType\") {\n        (node as Undone<N.TsConstructorType>).abstract = !!abstract;\n        if (abstract) this.next();\n        this.next(); // eat `new`\n      }\n      this.tsInAllowConditionalTypesContext(() =>\n        this.tsFillSignature(tt.arrow, node),\n      );\n      return this.finishNode(node, type);\n    }\n\n    tsParseLiteralTypeNode(): N.TsLiteralType {\n      const node = this.startNode<N.TsLiteralType>();\n      switch (this.state.type) {\n        case tt.num:\n        case tt.bigint:\n        case tt.string:\n        case tt._true:\n        case tt._false:\n          // For compatibility to estree we cannot call parseLiteral directly here\n          // @ts-expect-error refine typings\n          node.literal = super.parseExprAtom();\n          break;\n        default:\n          this.unexpected();\n      }\n      return this.finishNode(node, \"TSLiteralType\");\n    }\n\n    tsParseTemplateLiteralType(): N.TsTemplateLiteralType | N.TsLiteralType {\n      if (process.env.BABEL_8_BREAKING) {\n        const startLoc = this.state.startLoc;\n        let curElt = this.parseTemplateElement(false);\n        const quasis = [curElt];\n        if (curElt.tail) {\n          const node = this.startNodeAt<N.TsLiteralType>(startLoc);\n          const literal = this.startNodeAt<N.TemplateLiteral>(startLoc);\n          literal.expressions = [];\n          literal.quasis = quasis;\n          node.literal = this.finishNode(literal, \"TemplateLiteral\");\n          return this.finishNode(node, \"TSLiteralType\");\n        } else {\n          const substitutions: N.TsType[] = [];\n          while (!curElt.tail) {\n            substitutions.push(this.tsParseType());\n            this.readTemplateContinuation();\n            quasis.push((curElt = this.parseTemplateElement(false)));\n          }\n          const node = this.startNodeAt<N.TsTemplateLiteralType>(startLoc);\n          node.types = substitutions;\n          node.quasis = quasis;\n          return this.finishNode(node, \"TSTemplateLiteralType\");\n        }\n      } else {\n        const node = this.startNode<N.TsLiteralType>();\n        node.literal = super.parseTemplate(false);\n        return this.finishNode(node, \"TSLiteralType\");\n      }\n    }\n\n    parseTemplateSubstitution(): N.TsType | N.Expression {\n      if (this.state.inType) return this.tsParseType();\n      return super.parseTemplateSubstitution();\n    }\n\n    tsParseThisTypeOrThisTypePredicate(): N.TsThisType | N.TsTypePredicate {\n      const thisKeyword = this.tsParseThisTypeNode();\n      if (this.isContextual(tt._is) && !this.hasPrecedingLineBreak()) {\n        return this.tsParseThisTypePredicate(thisKeyword);\n      } else {\n        return thisKeyword;\n      }\n    }\n\n    tsParseNonArrayType(): N.TsType {\n      switch (this.state.type) {\n        case tt.string:\n        case tt.num:\n        case tt.bigint:\n        case tt._true:\n        case tt._false:\n          return this.tsParseLiteralTypeNode();\n        case tt.plusMin:\n          if (this.state.value === \"-\") {\n            const node = this.startNode<N.TsLiteralType>();\n            const nextToken = this.lookahead();\n            if (nextToken.type !== tt.num && nextToken.type !== tt.bigint) {\n              this.unexpected();\n            }\n            node.literal = this.parseMaybeUnary() as N.UnaryExpression;\n            return this.finishNode(node, \"TSLiteralType\");\n          }\n          break;\n        case tt._this:\n          return this.tsParseThisTypeOrThisTypePredicate();\n        case tt._typeof:\n          return this.tsParseTypeQuery();\n        case tt._import:\n          return this.tsParseImportType();\n        case tt.braceL:\n          return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this))\n            ? this.tsParseMappedType()\n            : this.tsParseTypeLiteral();\n        case tt.bracketL:\n          return this.tsParseTupleType();\n        case tt.parenL:\n          if (process.env.BABEL_8_BREAKING) {\n            if (\n              !(this.optionFlags & OptionFlags.CreateParenthesizedExpressions)\n            ) {\n              const startLoc = this.state.startLoc;\n              this.next();\n              const type = this.tsParseType();\n              this.expect(tt.parenR);\n              this.addExtra(type, \"parenthesized\", true);\n              this.addExtra(type, \"parenStart\", startLoc.index);\n              return type;\n            }\n          }\n\n          return this.tsParseParenthesizedType();\n        case tt.templateNonTail:\n        case tt.templateTail:\n          return this.tsParseTemplateLiteralType();\n        default: {\n          const { type } = this.state;\n          if (\n            tokenIsIdentifier(type) ||\n            type === tt._void ||\n            type === tt._null\n          ) {\n            const nodeType =\n              type === tt._void\n                ? \"TSVoidKeyword\"\n                : type === tt._null\n                  ? \"TSNullKeyword\"\n                  : keywordTypeFromName(this.state.value);\n            if (\n              nodeType !== undefined &&\n              this.lookaheadCharCode() !== charCodes.dot\n            ) {\n              const node = this.startNode<N.TsKeywordType>();\n              this.next();\n              return this.finishNode(node, nodeType);\n            }\n            return this.tsParseTypeReference();\n          }\n        }\n      }\n\n      this.unexpected();\n    }\n\n    tsParseArrayTypeOrHigher(): N.TsType {\n      const { startLoc } = this.state;\n      let type = this.tsParseNonArrayType();\n      while (!this.hasPrecedingLineBreak() && this.eat(tt.bracketL)) {\n        if (this.match(tt.bracketR)) {\n          const node = this.startNodeAt<N.TsArrayType>(startLoc);\n          node.elementType = type;\n          this.expect(tt.bracketR);\n          type = this.finishNode(node, \"TSArrayType\");\n        } else {\n          const node = this.startNodeAt<N.TsIndexedAccessType>(startLoc);\n          node.objectType = type;\n          node.indexType = this.tsParseType();\n          this.expect(tt.bracketR);\n          type = this.finishNode(node, \"TSIndexedAccessType\");\n        }\n      }\n      return type;\n    }\n\n    tsParseTypeOperator(): N.TsTypeOperator {\n      const node = this.startNode<N.TsTypeOperator>();\n      const operator = this.state.value;\n      this.next(); // eat operator\n      node.operator = operator;\n      node.typeAnnotation = this.tsParseTypeOperatorOrHigher();\n\n      if (operator === \"readonly\") {\n        this.tsCheckTypeAnnotationForReadOnly(node);\n      }\n\n      return this.finishNode(node, \"TSTypeOperator\");\n    }\n\n    tsCheckTypeAnnotationForReadOnly(node: Undone<N.TsTypeOperator>) {\n      switch (node.typeAnnotation.type) {\n        case \"TSTupleType\":\n        case \"TSArrayType\":\n          return;\n        default:\n          this.raise(TSErrors.UnexpectedReadonly, node);\n      }\n    }\n\n    tsParseInferType(): N.TsInferType {\n      const node = this.startNode<N.TsInferType>();\n      this.expectContextual(tt._infer);\n      const typeParameter = this.startNode<N.TsTypeParameter>();\n      typeParameter.name = this.tsParseTypeParameterName();\n      typeParameter.constraint = this.tsTryParse(() =>\n        this.tsParseConstraintForInferType(),\n      );\n      node.typeParameter = this.finishNode(typeParameter, \"TSTypeParameter\");\n      return this.finishNode(node, \"TSInferType\");\n    }\n\n    tsParseConstraintForInferType() {\n      if (this.eat(tt._extends)) {\n        const constraint = this.tsInDisallowConditionalTypesContext(() =>\n          this.tsParseType(),\n        );\n        if (\n          this.state.inDisallowConditionalTypesContext ||\n          !this.match(tt.question)\n        ) {\n          return constraint;\n        }\n      }\n    }\n\n    tsParseTypeOperatorOrHigher(): N.TsType {\n      const isTypeOperator =\n        tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;\n      return isTypeOperator\n        ? this.tsParseTypeOperator()\n        : this.isContextual(tt._infer)\n          ? this.tsParseInferType()\n          : this.tsInAllowConditionalTypesContext(() =>\n              this.tsParseArrayTypeOrHigher(),\n            );\n    }\n\n    tsParseUnionOrIntersectionType(\n      kind: \"TSUnionType\" | \"TSIntersectionType\",\n      parseConstituentType: () => N.TsType,\n      operator: TokenType,\n    ): N.TsType {\n      const node = this.startNode<N.TsUnionType | N.TsIntersectionType>();\n      const hasLeadingOperator = this.eat(operator);\n      const types = [];\n      do {\n        types.push(parseConstituentType());\n      } while (this.eat(operator));\n      if (types.length === 1 && !hasLeadingOperator) {\n        return types[0];\n      }\n      node.types = types;\n      return this.finishNode(node, kind);\n    }\n\n    tsParseIntersectionTypeOrHigher(): N.TsType {\n      return this.tsParseUnionOrIntersectionType(\n        \"TSIntersectionType\",\n        this.tsParseTypeOperatorOrHigher.bind(this),\n        tt.bitwiseAND,\n      );\n    }\n\n    tsParseUnionTypeOrHigher() {\n      return this.tsParseUnionOrIntersectionType(\n        \"TSUnionType\",\n        this.tsParseIntersectionTypeOrHigher.bind(this),\n        tt.bitwiseOR,\n      );\n    }\n\n    tsIsStartOfFunctionType() {\n      if (this.match(tt.lt)) {\n        return true;\n      }\n      return (\n        this.match(tt.parenL) &&\n        this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this))\n      );\n    }\n\n    tsSkipParameterStart(): boolean {\n      if (tokenIsIdentifier(this.state.type) || this.match(tt._this)) {\n        this.next();\n        return true;\n      }\n\n      if (this.match(tt.braceL)) {\n        // Return true if we can parse an object pattern without errors\n        const { errors } = this.state;\n        const previousErrorCount = errors.length;\n        try {\n          this.parseObjectLike(tt.braceR, true);\n          return errors.length === previousErrorCount;\n        } catch {\n          return false;\n        }\n      }\n\n      if (this.match(tt.bracketL)) {\n        this.next();\n        // Return true if we can parse an array pattern without errors\n        const { errors } = this.state;\n        const previousErrorCount = errors.length;\n        try {\n          super.parseBindingList(\n            tt.bracketR,\n            charCodes.rightSquareBracket,\n            ParseBindingListFlags.ALLOW_EMPTY,\n          );\n          return errors.length === previousErrorCount;\n        } catch {\n          return false;\n        }\n      }\n\n      return false;\n    }\n\n    tsIsUnambiguouslyStartOfFunctionType(): boolean {\n      this.next();\n      if (this.match(tt.parenR) || this.match(tt.ellipsis)) {\n        // ( )\n        // ( ...\n        return true;\n      }\n      if (this.tsSkipParameterStart()) {\n        if (\n          this.match(tt.colon) ||\n          this.match(tt.comma) ||\n          this.match(tt.question) ||\n          this.match(tt.eq)\n        ) {\n          // ( xxx :\n          // ( xxx ,\n          // ( xxx ?\n          // ( xxx =\n          return true;\n        }\n        if (this.match(tt.parenR)) {\n          this.next();\n          if (this.match(tt.arrow)) {\n            // ( xxx ) =>\n            return true;\n          }\n        }\n      }\n      return false;\n    }\n\n    tsParseTypeOrTypePredicateAnnotation(\n      returnToken: TokenType,\n    ): N.TsTypeAnnotation {\n      return this.tsInType(() => {\n        const t = this.startNode<N.TsTypeAnnotation>();\n        this.expect(returnToken);\n\n        const node = this.startNode<N.TsTypePredicate>();\n\n        const asserts = !!this.tsTryParse(\n          this.tsParseTypePredicateAsserts.bind(this),\n        );\n\n        if (asserts && this.match(tt._this)) {\n          // When asserts is false, thisKeyword is handled by tsParseNonArrayType\n          // : asserts this is type\n          let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();\n          // if it turns out to be a `TSThisType`, wrap it with `TSTypePredicate`\n          // : asserts this\n          if (thisTypePredicate.type === \"TSThisType\") {\n            node.parameterName = thisTypePredicate;\n            node.asserts = true;\n            (node as N.TsTypePredicate).typeAnnotation = null;\n            thisTypePredicate = this.finishNode(node, \"TSTypePredicate\");\n          } else {\n            this.resetStartLocationFromNode(thisTypePredicate, node);\n            thisTypePredicate.asserts = true;\n          }\n          t.typeAnnotation = thisTypePredicate;\n          return this.finishNode(t, \"TSTypeAnnotation\");\n        }\n\n        const typePredicateVariable =\n          this.tsIsIdentifier() &&\n          this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));\n\n        if (!typePredicateVariable) {\n          if (!asserts) {\n            // : type\n            return this.tsParseTypeAnnotation(/* eatColon */ false, t);\n          }\n\n          // : asserts foo\n          node.parameterName = this.parseIdentifier();\n          node.asserts = asserts;\n          (node as N.TsTypePredicate).typeAnnotation = null;\n          t.typeAnnotation = this.finishNode(node, \"TSTypePredicate\");\n          return this.finishNode(t, \"TSTypeAnnotation\");\n        }\n\n        // : asserts foo is type\n        const type = this.tsParseTypeAnnotation(/* eatColon */ false);\n        node.parameterName = typePredicateVariable;\n        node.typeAnnotation = type;\n        node.asserts = asserts;\n        t.typeAnnotation = this.finishNode(node, \"TSTypePredicate\");\n        return this.finishNode(t, \"TSTypeAnnotation\");\n      });\n    }\n\n    tsTryParseTypeOrTypePredicateAnnotation(): N.TsTypeAnnotation | undefined {\n      if (this.match(tt.colon)) {\n        return this.tsParseTypeOrTypePredicateAnnotation(tt.colon);\n      }\n    }\n\n    tsTryParseTypeAnnotation(): N.TsTypeAnnotation | undefined {\n      if (this.match(tt.colon)) {\n        return this.tsParseTypeAnnotation();\n      }\n    }\n\n    tsTryParseType(): N.TsType | undefined {\n      return this.tsEatThenParseType(tt.colon);\n    }\n\n    tsParseTypePredicatePrefix(): N.Identifier | undefined {\n      const id = this.parseIdentifier();\n      if (this.isContextual(tt._is) && !this.hasPrecedingLineBreak()) {\n        this.next();\n        return id;\n      }\n    }\n\n    tsParseTypePredicateAsserts(): boolean {\n      if (this.state.type !== tt._asserts) {\n        return false;\n      }\n      const containsEsc = this.state.containsEsc;\n      this.next();\n      if (!tokenIsIdentifier(this.state.type) && !this.match(tt._this)) {\n        return false;\n      }\n\n      if (containsEsc) {\n        this.raise(\n          Errors.InvalidEscapedReservedWord,\n          this.state.lastTokStartLoc,\n          {\n            reservedWord: \"asserts\",\n          },\n        );\n      }\n\n      return true;\n    }\n\n    tsParseTypeAnnotation(\n      eatColon = true,\n      t: Undone<N.TsTypeAnnotation> = this.startNode<N.TsTypeAnnotation>(),\n    ): N.TsTypeAnnotation {\n      this.tsInType(() => {\n        if (eatColon) this.expect(tt.colon);\n        t.typeAnnotation = this.tsParseType();\n      });\n      return this.finishNode(t, \"TSTypeAnnotation\");\n    }\n\n    /** Be sure to be in a type context before calling this, using `tsInType`. */\n    tsParseType(): N.TsType {\n      // Need to set `state.inType` so that we don't parse JSX in a type context.\n      assert(this.state.inType);\n      const type = this.tsParseNonConditionalType();\n\n      if (\n        this.state.inDisallowConditionalTypesContext ||\n        this.hasPrecedingLineBreak() ||\n        !this.eat(tt._extends)\n      ) {\n        return type;\n      }\n      const node = this.startNodeAtNode<N.TsConditionalType>(type);\n      node.checkType = type;\n\n      node.extendsType = this.tsInDisallowConditionalTypesContext(() =>\n        this.tsParseNonConditionalType(),\n      );\n\n      this.expect(tt.question);\n      node.trueType = this.tsInAllowConditionalTypesContext(() =>\n        this.tsParseType(),\n      );\n\n      this.expect(tt.colon);\n      node.falseType = this.tsInAllowConditionalTypesContext(() =>\n        this.tsParseType(),\n      );\n\n      return this.finishNode(node, \"TSConditionalType\");\n    }\n\n    isAbstractConstructorSignature(): boolean {\n      return (\n        this.isContextual(tt._abstract) && this.isLookaheadContextual(\"new\")\n      );\n    }\n\n    tsParseNonConditionalType(): N.TsType {\n      if (this.tsIsStartOfFunctionType()) {\n        return this.tsParseFunctionOrConstructorType(\"TSFunctionType\");\n      }\n      if (this.match(tt._new)) {\n        // As in `new () => Date`\n        return this.tsParseFunctionOrConstructorType(\"TSConstructorType\");\n      } else if (this.isAbstractConstructorSignature()) {\n        // As in `abstract new () => Date`\n        return this.tsParseFunctionOrConstructorType(\n          \"TSConstructorType\",\n          /* abstract */ true,\n        );\n      }\n      return this.tsParseUnionTypeOrHigher();\n    }\n\n    tsParseTypeAssertion(): N.TsTypeAssertion {\n      if (this.getPluginOption(\"typescript\", \"disallowAmbiguousJSXLike\")) {\n        this.raise(TSErrors.ReservedTypeAssertion, this.state.startLoc);\n      }\n\n      const node = this.startNode<N.TsTypeAssertion>();\n      node.typeAnnotation = this.tsInType(() => {\n        this.next(); // \"<\"\n        return this.match(tt._const)\n          ? this.tsParseTypeReference()\n          : this.tsParseType();\n      });\n      this.expect(tt.gt);\n      node.expression = this.parseMaybeUnary();\n      return this.finishNode(node, \"TSTypeAssertion\");\n    }\n\n    tsParseHeritageClause(token: \"extends\"): Array<N.TSInterfaceHeritage>;\n    tsParseHeritageClause(token: \"implements\"): Array<N.TSClassImplements>;\n    tsParseHeritageClause(\n      token: \"extends\" | \"implements\",\n    ): Array<N.TSClassImplements> | Array<N.TSInterfaceHeritage> {\n      const originalStartLoc = this.state.startLoc;\n\n      const delimitedList = this.tsParseDelimitedList(\n        \"HeritageClauseElement\",\n        () => {\n          if (process.env.BABEL_8_BREAKING) {\n            const expression = super.parseExprSubscripts();\n            if (!tsIsEntityName(expression)) {\n              this.raise(\n                TSErrors.InvalidHeritageClauseType,\n                expression.loc.start,\n                { token },\n              );\n            }\n            const nodeType =\n              token === \"extends\" ? \"TSInterfaceHeritage\" : \"TSClassImplements\";\n            if (expression.type === \"TSInstantiationExpression\") {\n              // @ts-expect-error cast TSInstantiationExpression to TSInterfaceHeritage/TSClassImplements\n              expression.type = nodeType;\n              return expression;\n            }\n            const node = this.startNodeAtNode<\n              N.TSInterfaceHeritage | N.TSClassImplements\n            >(expression);\n            node.expression = expression;\n            // The last element can not form a TSInstantiationExpression because of the bail condition in\n            // `parseSubscript`, in this case we have to parse type arguments again\n            if (this.match(tt.lt) || this.match(tt.bitShiftL)) {\n              node.typeArguments = this.tsParseTypeArgumentsInExpression();\n            }\n            return this.finishNode(node, nodeType);\n          } else {\n            const node = this.startNode<\n              N.TSInterfaceHeritage | N.TSClassImplements\n            >();\n            // @ts-expect-error Babel 7 vs Babel 8\n            node.expression = this.tsParseEntityName(\n              tsParseEntityNameFlags.ALLOW_RESERVED_WORDS |\n                tsParseEntityNameFlags.LEADING_THIS_AS_IDENTIFIER,\n            );\n            if (this.match(tt.lt)) {\n              // @ts-expect-error Babel 7 vs Babel 8\n              node.typeParameters = this.tsParseTypeArguments();\n            }\n\n            return this.finishNode(\n              node,\n              // @ts-expect-error Babel 7 vs Babel 8\n              \"TSExpressionWithTypeArguments\",\n            );\n          }\n        },\n      );\n\n      if (!delimitedList.length) {\n        this.raise(TSErrors.EmptyHeritageClauseType, originalStartLoc, {\n          token,\n        });\n      }\n\n      return delimitedList as\n        | Array<N.TSClassImplements>\n        | Array<N.TSInterfaceHeritage>;\n    }\n\n    tsParseInterfaceDeclaration(\n      node: Undone<N.TsInterfaceDeclaration>,\n      properties: {\n        declare?: true;\n      } = {},\n    ): N.TsInterfaceDeclaration | null {\n      if (this.hasFollowingLineBreak()) return null;\n      this.expectContextual(tt._interface);\n      if (properties.declare) node.declare = true;\n      if (tokenIsIdentifier(this.state.type)) {\n        node.id = this.parseIdentifier();\n        this.checkIdentifier(node.id, BindingFlag.TYPE_TS_INTERFACE);\n      } else {\n        node.id = null;\n        this.raise(TSErrors.MissingInterfaceName, this.state.startLoc);\n      }\n\n      node.typeParameters = this.tsTryParseTypeParameters(\n        this.tsParseInOutConstModifiers,\n      );\n      if (this.eat(tt._extends)) {\n        node.extends = this.tsParseHeritageClause(\"extends\");\n      }\n      const body = this.startNode<N.TSInterfaceBody>();\n      body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));\n      node.body = this.finishNode(body, \"TSInterfaceBody\");\n      return this.finishNode(node, \"TSInterfaceDeclaration\");\n    }\n\n    tsParseTypeAliasDeclaration(\n      node: N.TsTypeAliasDeclaration,\n    ): N.TsTypeAliasDeclaration {\n      node.id = this.parseIdentifier();\n      this.checkIdentifier(node.id, BindingFlag.TYPE_TS_TYPE);\n\n      node.typeAnnotation = this.tsInType(() => {\n        node.typeParameters = this.tsTryParseTypeParameters(\n          this.tsParseInOutModifiers,\n        );\n\n        this.expect(tt.eq);\n\n        if (\n          this.isContextual(tt._intrinsic) &&\n          this.lookaheadCharCode() !== charCodes.dot\n        ) {\n          const node = this.startNode<N.TsKeywordType>();\n          this.next();\n          return this.finishNode(node, \"TSIntrinsicKeyword\");\n        }\n\n        return this.tsParseType();\n      });\n\n      this.semicolon();\n      return this.finishNode(node, \"TSTypeAliasDeclaration\");\n    }\n\n    // Parse in top level normal context if we are in a JSX context\n    tsInTopLevelContext<T>(cb: () => T): T {\n      if (this.curContext() !== tc.brace) {\n        const oldContext = this.state.context;\n        this.state.context = [oldContext[0]];\n        try {\n          return cb();\n        } finally {\n          this.state.context = oldContext;\n        }\n      } else {\n        return cb();\n      }\n    }\n\n    /**\n     * Runs `cb` in a type context.\n     * This should be called one token *before* the first type token,\n     * so that the call to `next()` is run in type context.\n     */\n    tsInType<T>(cb: () => T): T {\n      const oldInType = this.state.inType;\n      this.state.inType = true;\n      try {\n        return cb();\n      } finally {\n        this.state.inType = oldInType;\n      }\n    }\n\n    tsInDisallowConditionalTypesContext<T>(cb: () => T): T {\n      const oldInDisallowConditionalTypesContext =\n        this.state.inDisallowConditionalTypesContext;\n      this.state.inDisallowConditionalTypesContext = true;\n      try {\n        return cb();\n      } finally {\n        this.state.inDisallowConditionalTypesContext =\n          oldInDisallowConditionalTypesContext;\n      }\n    }\n\n    tsInAllowConditionalTypesContext<T>(cb: () => T): T {\n      const oldInDisallowConditionalTypesContext =\n        this.state.inDisallowConditionalTypesContext;\n      this.state.inDisallowConditionalTypesContext = false;\n      try {\n        return cb();\n      } finally {\n        this.state.inDisallowConditionalTypesContext =\n          oldInDisallowConditionalTypesContext;\n      }\n    }\n\n    tsEatThenParseType(token: TokenType): N.TsType | undefined {\n      if (this.match(token)) {\n        return this.tsNextThenParseType();\n      }\n    }\n\n    tsExpectThenParseType(token: TokenType): N.TsType {\n      return this.tsInType(() => {\n        this.expect(token);\n        return this.tsParseType();\n      });\n    }\n\n    tsNextThenParseType(): N.TsType {\n      return this.tsInType(() => {\n        this.next();\n        return this.tsParseType();\n      });\n    }\n\n    tsParseEnumMember(): N.TsEnumMember {\n      const node = this.startNode<N.TsEnumMember>();\n      // Computed property names are grammar errors in an enum, so accept just string literal or identifier.\n      node.id = this.match(tt.string)\n        ? super.parseStringLiteral(this.state.value)\n        : this.parseIdentifier(/* liberal */ true);\n      if (this.eat(tt.eq)) {\n        node.initializer = super.parseMaybeAssignAllowIn();\n      }\n      return this.finishNode(node, \"TSEnumMember\");\n    }\n\n    tsParseEnumDeclaration(\n      node: Undone<N.TsEnumDeclaration>,\n      properties: {\n        const?: true;\n        declare?: true;\n      } = {},\n    ): N.TsEnumDeclaration {\n      if (properties.const) node.const = true;\n      if (properties.declare) node.declare = true;\n      this.expectContextual(tt._enum);\n      node.id = this.parseIdentifier();\n      this.checkIdentifier(\n        node.id,\n        node.const ? BindingFlag.TYPE_TS_CONST_ENUM : BindingFlag.TYPE_TS_ENUM,\n      );\n\n      if (process.env.BABEL_8_BREAKING) {\n        node.body = this.tsParseEnumBody();\n      } else {\n        this.expect(tt.braceL);\n        node.members = this.tsParseDelimitedList(\n          \"EnumMembers\",\n          this.tsParseEnumMember.bind(this),\n        );\n        this.expect(tt.braceR);\n      }\n      return this.finishNode(node, \"TSEnumDeclaration\");\n    }\n\n    tsParseEnumBody(): N.TsEnumBody {\n      const node = this.startNode<N.TsEnumBody>();\n      this.expect(tt.braceL);\n      node.members = this.tsParseDelimitedList(\n        \"EnumMembers\",\n        this.tsParseEnumMember.bind(this),\n      );\n      this.expect(tt.braceR);\n      return this.finishNode(node, \"TSEnumBody\");\n    }\n\n    tsParseModuleBlock(): N.TsModuleBlock {\n      const node = this.startNode<N.TsModuleBlock>();\n      this.scope.enter(ScopeFlag.OTHER);\n\n      this.expect(tt.braceL);\n      // Inside of a module block is considered \"top-level\", meaning it can have imports and exports.\n      super.parseBlockOrModuleBlockBody(\n        (node.body = []),\n        /* directives */ undefined,\n        /* topLevel */ true,\n        /* end */ tt.braceR,\n      );\n      this.scope.exit();\n      return this.finishNode(node, \"TSModuleBlock\");\n    }\n\n    tsParseModuleOrNamespaceDeclaration(\n      node: Undone<N.TsModuleDeclaration>,\n      nested: boolean = false,\n    ): N.TsModuleDeclaration {\n      node.id = process.env.BABEL_8_BREAKING\n        ? this.tsParseEntityName(tsParseEntityNameFlags.ALLOW_RESERVED_WORDS)\n        : this.parseIdentifier();\n\n      if (\n        process.env.BABEL_8_BREAKING ? node.id.type === \"Identifier\" : !nested\n      ) {\n        // @ts-expect-error checked above\n        this.checkIdentifier(node.id, BindingFlag.TYPE_TS_NAMESPACE);\n      }\n\n      if (!process.env.BABEL_8_BREAKING && this.eat(tt.dot)) {\n        const inner = this.startNode<N.TsModuleDeclaration>();\n        this.tsParseModuleOrNamespaceDeclaration(inner, true);\n        // @ts-expect-error Fixme: refine typings\n        node.body = inner;\n      } else {\n        this.scope.enter(ScopeFlag.TS_MODULE);\n        this.prodParam.enter(ParamKind.PARAM);\n        node.body = this.tsParseModuleBlock();\n        this.prodParam.exit();\n        this.scope.exit();\n      }\n      return this.finishNode(node, \"TSModuleDeclaration\");\n    }\n\n    tsParseAmbientExternalModuleDeclaration(\n      node: N.TsModuleDeclaration,\n    ): N.TsModuleDeclaration {\n      if (this.isContextual(tt._global)) {\n        node.kind = \"global\";\n        if (!process.env.BABEL_8_BREAKING) {\n          node.global = true;\n        }\n        node.id = this.parseIdentifier();\n      } else if (this.match(tt.string)) {\n        node.kind = \"module\";\n        node.id = super.parseStringLiteral(this.state.value);\n      } else {\n        this.unexpected();\n      }\n      if (this.match(tt.braceL)) {\n        this.scope.enter(ScopeFlag.TS_MODULE);\n        this.prodParam.enter(ParamKind.PARAM);\n        node.body = this.tsParseModuleBlock();\n        this.prodParam.exit();\n        this.scope.exit();\n      } else {\n        this.semicolon();\n      }\n\n      return this.finishNode(node, \"TSModuleDeclaration\");\n    }\n\n    tsParseImportEqualsDeclaration(\n      node: Undone<N.TsImportEqualsDeclaration>,\n      maybeDefaultIdentifier?: N.Identifier | null,\n      isExport?: boolean,\n    ): N.TsImportEqualsDeclaration {\n      if (!process.env.BABEL_8_BREAKING) {\n        node.isExport = isExport || false;\n      }\n      node.id = maybeDefaultIdentifier || this.parseIdentifier();\n      this.checkIdentifier(node.id, BindingFlag.TYPE_TS_VALUE_IMPORT);\n      this.expect(tt.eq);\n      const moduleReference = this.tsParseModuleReference();\n      if (\n        node.importKind === \"type\" &&\n        moduleReference.type !== \"TSExternalModuleReference\"\n      ) {\n        this.raise(TSErrors.ImportAliasHasImportType, moduleReference);\n      }\n      node.moduleReference = moduleReference;\n      this.semicolon();\n      return this.finishNode(node, \"TSImportEqualsDeclaration\");\n    }\n\n    tsIsExternalModuleReference(): boolean {\n      return (\n        this.isContextual(tt._require) &&\n        this.lookaheadCharCode() === charCodes.leftParenthesis\n      );\n    }\n\n    tsParseModuleReference(): N.TsModuleReference {\n      return this.tsIsExternalModuleReference()\n        ? this.tsParseExternalModuleReference()\n        : this.tsParseEntityName(tsParseEntityNameFlags.NONE);\n    }\n\n    tsParseExternalModuleReference(): N.TsExternalModuleReference {\n      const node = this.startNode<N.TsExternalModuleReference>();\n      this.expectContextual(tt._require);\n      this.expect(tt.parenL);\n      if (!this.match(tt.string)) {\n        this.unexpected();\n      }\n      // For compatibility to estree we cannot call parseLiteral directly here\n      node.expression = super.parseExprAtom() as N.StringLiteral;\n      this.expect(tt.parenR);\n      this.sawUnambiguousESM = true;\n      return this.finishNode(node, \"TSExternalModuleReference\");\n    }\n\n    // Utilities\n\n    tsLookAhead<T>(f: () => T): T {\n      const state = this.state.clone();\n      const res = f();\n      this.state = state;\n      return res;\n    }\n\n    tsTryParseAndCatch<T extends N.NodeBase | undefined | null>(\n      f: () => T,\n    ): T | undefined | null {\n      const result = this.tryParse(\n        abort =>\n          // @ts-expect-error todo(flow->ts)\n          f() || abort(),\n      );\n\n      if (result.aborted || !result.node) return;\n      if (result.error) this.state = result.failState;\n      // @ts-expect-error refine typings\n      return result.node;\n    }\n\n    tsTryParse<T>(f: () => T | undefined | false): T | undefined {\n      const state = this.state.clone();\n      const result = f();\n      if (result !== undefined && result !== false) {\n        return result;\n      }\n      this.state = state;\n    }\n\n    tsTryParseDeclare(node: any) {\n      if (this.isLineTerminator()) {\n        return;\n      }\n      const startType = this.state.type;\n      return this.tsInAmbientContext(() => {\n        switch (startType) {\n          case tt._function:\n            node.declare = true;\n            return super.parseFunctionStatement(\n              node,\n              /* async */ false,\n              /* isHangingDeclaration */ false,\n            );\n          case tt._class:\n            // While this is also set by tsParseExpressionStatement, we need to set it\n            // before parsing the class declaration to know how to register it in the scope.\n            node.declare = true;\n            return this.parseClass(\n              node as Undone<N.ClassDeclaration>,\n              /* isStatement */ true,\n              /* optionalId */ false,\n            );\n          case tt._enum:\n            return this.tsParseEnumDeclaration(node, { declare: true });\n          case tt._global:\n            return this.tsParseAmbientExternalModuleDeclaration(node);\n          case tt._let:\n            if (this.state.containsEsc) {\n              return;\n            }\n          // fallthrough\n          case tt._const:\n          case tt._var:\n            if (!this.match(tt._const) || !this.isLookaheadContextual(\"enum\")) {\n              node.declare = true;\n              return this.parseVarStatement(node, this.state.value, true);\n            }\n\n            // `const enum = 0;` not allowed because \"enum\" is a strict mode reserved word.\n            this.expect(tt._const);\n            return this.tsParseEnumDeclaration(node, {\n              const: true,\n              declare: true,\n            });\n          case tt._using:\n            if (this.isUsing()) {\n              this.raise(\n                TSErrors.InvalidModifierOnUsingDeclaration,\n                this.state.startLoc,\n                \"declare\",\n              );\n              node.declare = true;\n              return this.parseVarStatement(node, \"using\", true);\n            }\n            break;\n          case tt._await:\n            if (this.isAwaitUsing()) {\n              this.raise(\n                TSErrors.InvalidModifierOnAwaitUsingDeclaration,\n                this.state.startLoc,\n                \"declare\",\n              );\n              node.declare = true;\n              this.next(); // eat 'await'\n              return this.parseVarStatement(node, \"await using\", true);\n            }\n            break;\n          case tt._interface: {\n            const result = this.tsParseInterfaceDeclaration(node, {\n              declare: true,\n            });\n            if (result) return result;\n          }\n          // fallthrough\n          default:\n            if (tokenIsIdentifier(startType)) {\n              return this.tsParseDeclaration(\n                node,\n                this.state.value,\n                /* next */ true,\n                /* decorators */ null,\n              );\n            }\n        }\n      });\n    }\n\n    // Note: this won't be called unless the keyword is allowed in `shouldParseExportDeclaration`.\n    tsTryParseExportDeclaration(): N.Declaration | undefined {\n      return this.tsParseDeclaration(\n        this.startNode(),\n        this.state.value,\n        /* next */ true,\n        /* decorators */ null,\n      );\n    }\n\n    tsParseExpressionStatement(\n      node: Undone<N.TsModuleDeclaration>,\n      expr: N.Identifier,\n      decorators: N.Decorator[] | null,\n    ): N.Declaration | undefined {\n      switch (expr.name) {\n        case \"declare\": {\n          const declaration = this.tsTryParseDeclare(node);\n          if (declaration) {\n            declaration.declare = true;\n          }\n          return declaration;\n        }\n        case \"global\":\n          // `global { }` (with no `declare`) may appear inside an ambient module declaration.\n          // Would like to use tsParseAmbientExternalModuleDeclaration here, but already ran past \"global\".\n          if (this.match(tt.braceL)) {\n            this.scope.enter(ScopeFlag.TS_MODULE);\n            this.prodParam.enter(ParamKind.PARAM);\n            const mod = node;\n            mod.kind = \"global\";\n            if (!process.env.BABEL_8_BREAKING) {\n              node.global = true;\n            }\n            mod.id = expr;\n            mod.body = this.tsParseModuleBlock();\n            this.scope.exit();\n            this.prodParam.exit();\n            return this.finishNode(mod, \"TSModuleDeclaration\");\n          }\n          break;\n\n        default:\n          return this.tsParseDeclaration(\n            node,\n            expr.name,\n            /* next */ false,\n            decorators,\n          );\n      }\n    }\n\n    // Common to tsTryParseDeclare, tsTryParseExportDeclaration, and tsParseExpressionStatement.\n    tsParseDeclaration(\n      node: any,\n      value: string,\n      next: boolean,\n      decorators: N.Decorator[] | null,\n    ) {\n      // no declaration apart from enum can be followed by a line break.\n      switch (value) {\n        case \"abstract\":\n          if (\n            this.tsCheckLineTerminator(next) &&\n            (this.match(tt._class) || tokenIsIdentifier(this.state.type))\n          ) {\n            return this.tsParseAbstractDeclaration(node, decorators);\n          }\n          break;\n\n        case \"module\":\n          if (this.tsCheckLineTerminator(next)) {\n            if (this.match(tt.string)) {\n              return this.tsParseAmbientExternalModuleDeclaration(node);\n            } else if (tokenIsIdentifier(this.state.type)) {\n              node.kind = \"module\";\n              return this.tsParseModuleOrNamespaceDeclaration(node);\n            }\n          }\n          break;\n\n        case \"namespace\":\n          if (\n            this.tsCheckLineTerminator(next) &&\n            tokenIsIdentifier(this.state.type)\n          ) {\n            node.kind = \"namespace\";\n            return this.tsParseModuleOrNamespaceDeclaration(node);\n          }\n          break;\n\n        case \"type\":\n          if (\n            this.tsCheckLineTerminator(next) &&\n            tokenIsIdentifier(this.state.type)\n          ) {\n            return this.tsParseTypeAliasDeclaration(node);\n          }\n          break;\n      }\n    }\n\n    tsCheckLineTerminator(next: boolean) {\n      if (next) {\n        if (this.hasFollowingLineBreak()) return false;\n        this.next();\n        return true;\n      }\n      return !this.isLineTerminator();\n    }\n\n    tsTryParseGenericAsyncArrowFunction(\n      startLoc: Position,\n    ): N.ArrowFunctionExpression | undefined {\n      if (!this.match(tt.lt)) return;\n\n      const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;\n      this.state.maybeInArrowParameters = true;\n\n      const res: Undone<N.ArrowFunctionExpression> | undefined =\n        this.tsTryParseAndCatch(() => {\n          const node = this.startNodeAt<N.ArrowFunctionExpression>(startLoc);\n          node.typeParameters = this.tsParseTypeParameters(\n            this.tsParseConstModifier,\n          );\n          // Don't use overloaded parseFunctionParams which would look for \"<\" again.\n          super.parseFunctionParams(node);\n          node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();\n          this.expect(tt.arrow);\n          return node;\n        });\n\n      this.state.maybeInArrowParameters = oldMaybeInArrowParameters;\n\n      if (!res) return;\n\n      return super.parseArrowExpression(\n        res,\n        /* params are already set */ null,\n        /* async */ true,\n      );\n    }\n\n    // Used when parsing type arguments from ES or JSX productions, where the first token\n    // has been created without state.inType. Thus we need to re-scan the lt token.\n    tsParseTypeArgumentsInExpression():\n      | N.TsTypeParameterInstantiation\n      | undefined {\n      if (this.reScan_lt() !== tt.lt) return;\n      return this.tsParseTypeArguments();\n    }\n\n    tsParseTypeArguments(): N.TsTypeParameterInstantiation {\n      const node = this.startNode<N.TsTypeParameterInstantiation>();\n      node.params = this.tsInType(() =>\n        this.tsInTopLevelContext(() => {\n          this.expect(tt.lt);\n          return this.tsParseDelimitedList(\n            \"TypeParametersOrArguments\",\n            this.tsParseType.bind(this),\n          );\n        }),\n      );\n      if (node.params.length === 0) {\n        this.raise(TSErrors.EmptyTypeArguments, node);\n      } else if (!this.state.inType && this.curContext() === tc.brace) {\n        // rescan `>` when we are no longer in type context and JSX parsing context\n        // since it was tokenized when `inType` is `true`.\n        this.reScan_lt_gt();\n      }\n      this.expect(tt.gt);\n      return this.finishNode(node, \"TSTypeParameterInstantiation\");\n    }\n\n    tsIsDeclarationStart(): boolean {\n      return tokenIsTSDeclarationStart(this.state.type);\n    }\n\n    // ======================================================\n    // OVERRIDES\n    // ======================================================\n\n    isExportDefaultSpecifier(): boolean {\n      if (this.tsIsDeclarationStart()) return false;\n      return super.isExportDefaultSpecifier();\n    }\n\n    parseBindingElement(\n      flags: ParseBindingListFlags,\n      decorators: N.Decorator[],\n    ): N.Pattern | N.TSParameterProperty {\n      // Store original location to include decorators/modifiers in range\n      const startLoc = decorators.length\n        ? decorators[0].loc.start\n        : this.state.startLoc;\n\n      const modified: ModifierBase = {};\n      this.tsParseModifiers(\n        {\n          allowedModifiers: [\n            \"public\",\n            \"private\",\n            \"protected\",\n            \"override\",\n            \"readonly\",\n          ],\n        },\n        modified,\n      );\n      const accessibility = modified.accessibility;\n      const override = modified.override;\n      const readonly = modified.readonly;\n      if (\n        !(flags & ParseBindingListFlags.IS_CONSTRUCTOR_PARAMS) &&\n        (accessibility || readonly || override)\n      ) {\n        this.raise(TSErrors.UnexpectedParameterModifier, startLoc);\n      }\n\n      const left = this.parseMaybeDefault();\n      if (flags & ParseBindingListFlags.IS_FUNCTION_PARAMS) {\n        this.parseFunctionParamType(left);\n      }\n      const elt = this.parseMaybeDefault(left.loc.start, left);\n      if (accessibility || readonly || override) {\n        const pp = this.startNodeAt<N.TSParameterProperty>(startLoc);\n        if (decorators.length) {\n          pp.decorators = decorators;\n        }\n        if (accessibility) pp.accessibility = accessibility;\n        if (readonly) pp.readonly = readonly;\n        if (override) pp.override = override;\n        if (elt.type !== \"Identifier\" && elt.type !== \"AssignmentPattern\") {\n          this.raise(TSErrors.UnsupportedParameterPropertyKind, pp);\n        }\n        pp.parameter = elt as any as N.Identifier | N.AssignmentPattern;\n        return this.finishNode(pp, \"TSParameterProperty\");\n      }\n\n      if (decorators.length) {\n        left.decorators = decorators;\n      }\n\n      return elt;\n    }\n\n    isSimpleParameter(node: N.Pattern | N.TSParameterProperty): boolean {\n      return (\n        (node.type === \"TSParameterProperty\" &&\n          super.isSimpleParameter(node.parameter)) ||\n        super.isSimpleParameter(node)\n      );\n    }\n\n    tsDisallowOptionalPattern(node: Undone<N.Function>) {\n      for (const param of node.params) {\n        if (\n          param.type !== \"Identifier\" &&\n          (param as any).optional &&\n          !this.state.isAmbientContext\n        ) {\n          this.raise(TSErrors.PatternIsOptional, param);\n        }\n      }\n    }\n\n    setArrowFunctionParameters(\n      node: Undone<N.ArrowFunctionExpression>,\n      params: N.Expression[],\n      trailingCommaLoc?: Position | null,\n    ): void {\n      super.setArrowFunctionParameters(node, params, trailingCommaLoc);\n      this.tsDisallowOptionalPattern(node);\n    }\n\n    parseFunctionBodyAndFinish<\n      T extends\n        | N.Function\n        | N.TSDeclareMethod\n        | N.TSDeclareFunction\n        | N.ClassPrivateMethod,\n    >(node: Undone<T>, type: T[\"type\"], isMethod: boolean = false): T {\n      if (this.match(tt.colon)) {\n        node.returnType = this.tsParseTypeOrTypePredicateAnnotation(tt.colon);\n      }\n\n      const bodilessType =\n        type === \"FunctionDeclaration\"\n          ? \"TSDeclareFunction\"\n          : type === \"ClassMethod\" || type === \"ClassPrivateMethod\"\n            ? \"TSDeclareMethod\"\n            : undefined;\n      if (bodilessType && !this.match(tt.braceL) && this.isLineTerminator()) {\n        return this.finishNode(node, bodilessType);\n      }\n      if (bodilessType === \"TSDeclareFunction\" && this.state.isAmbientContext) {\n        this.raise(TSErrors.DeclareFunctionHasImplementation, node);\n        if ((node as Undone<N.FunctionDeclaration>).declare) {\n          return super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);\n        }\n      }\n      this.tsDisallowOptionalPattern(node);\n\n      return super.parseFunctionBodyAndFinish(node, type, isMethod);\n    }\n\n    registerFunctionStatementId(node: N.Function): void {\n      if (!node.body && node.id) {\n        // Function ids are validated after parsing their body.\n        // For bodiless function, we need to do it here.\n        this.checkIdentifier(node.id, BindingFlag.TYPE_TS_AMBIENT);\n      } else {\n        super.registerFunctionStatementId(node);\n      }\n    }\n\n    tsCheckForInvalidTypeCasts(items: Array<N.Expression | N.SpreadElement>) {\n      items.forEach(node => {\n        if (node?.type === \"TSTypeCastExpression\") {\n          this.raise(TSErrors.UnexpectedTypeAnnotation, node.typeAnnotation);\n        }\n      });\n    }\n\n    toReferencedList(\n      exprList: Array<N.Expression | undefined | null>,\n      // eslint-disable-next-line @typescript-eslint/no-unused-vars\n      isInParens?: boolean,\n    ): Array<N.Expression | undefined | null> {\n      // Handles invalid scenarios like: `f(a:b)`, `(a:b);`, and `(a:b,c:d)`.\n      //\n      // Note that `f<T>(a:b)` goes through a different path and is handled\n      // in `parseSubscript` directly.\n      this.tsCheckForInvalidTypeCasts(exprList);\n      return exprList;\n    }\n\n    parseArrayLike(\n      close: TokenType,\n      canBePattern: boolean,\n      isTuple: boolean,\n      refExpressionErrors?: ExpressionErrors | null,\n    ): N.ArrayExpression | N.TupleExpression {\n      const node = super.parseArrayLike(\n        close,\n        canBePattern,\n        isTuple,\n        refExpressionErrors,\n      );\n\n      if (node.type === \"ArrayExpression\") {\n        this.tsCheckForInvalidTypeCasts(node.elements);\n      }\n\n      return node;\n    }\n\n    parseSubscript(\n      base: N.Expression,\n\n      startLoc: Position,\n      noCalls: boolean | undefined | null,\n      state: N.ParseSubscriptState,\n    ): N.Expression {\n      if (!this.hasPrecedingLineBreak() && this.match(tt.bang)) {\n        // When ! is consumed as a postfix operator (non-null assertion),\n        // disallow JSX tag forming after. e.g. When parsing `p! < n.p!`\n        // `<n.p` can not be a start of JSX tag\n        this.state.canStartJSXElement = false;\n        this.next();\n\n        const nonNullExpression =\n          this.startNodeAt<N.TsNonNullExpression>(startLoc);\n        nonNullExpression.expression = base;\n        return this.finishNode(nonNullExpression, \"TSNonNullExpression\");\n      }\n\n      let isOptionalCall = false;\n      if (\n        this.match(tt.questionDot) &&\n        this.lookaheadCharCode() === charCodes.lessThan\n      ) {\n        if (noCalls) {\n          state.stop = true;\n          return base;\n        }\n        state.optionalChainMember = isOptionalCall = true;\n        this.next();\n      }\n\n      // handles 'f<<T>'\n      if (this.match(tt.lt) || this.match(tt.bitShiftL)) {\n        let missingParenErrorLoc;\n        // tsTryParseAndCatch is expensive, so avoid if not necessary.\n        // There are number of things we are going to \"maybe\" parse, like type arguments on\n        // tagged template expressions. If any of them fail, walk it back and continue.\n        const result = this.tsTryParseAndCatch(() => {\n          if (!noCalls && this.atPossibleAsyncArrow(base)) {\n            // Almost certainly this is a generic async function `async <T>() => ...\n            // But it might be a call with a type argument `async<T>();`\n            const asyncArrowFn =\n              this.tsTryParseGenericAsyncArrowFunction(startLoc);\n            if (asyncArrowFn) {\n              state.stop = true;\n              return asyncArrowFn;\n            }\n          }\n\n          const typeArguments = this.tsParseTypeArgumentsInExpression();\n          if (!typeArguments) return;\n\n          if (isOptionalCall && !this.match(tt.parenL)) {\n            missingParenErrorLoc = this.state.curPosition();\n            return;\n          }\n\n          if (tokenIsTemplate(this.state.type)) {\n            const result = super.parseTaggedTemplateExpression(\n              base,\n              startLoc,\n              state,\n            );\n            if (process.env.BABEL_8_BREAKING) {\n              result.typeArguments = typeArguments;\n            } else {\n              result.typeParameters = typeArguments;\n            }\n            return result;\n          }\n\n          if (!noCalls && this.eat(tt.parenL)) {\n            const node = this.startNodeAt<\n              N.CallExpression | N.OptionalCallExpression\n            >(startLoc);\n            node.callee = base;\n            // @ts-expect-error (won't be any undefined arguments)\n            node.arguments = this.parseCallExpressionArguments();\n\n            // Handles invalid case: `f<T>(a:b)`\n            this.tsCheckForInvalidTypeCasts(node.arguments);\n\n            if (process.env.BABEL_8_BREAKING) {\n              node.typeArguments = typeArguments;\n            } else {\n              node.typeParameters = typeArguments;\n            }\n\n            if (state.optionalChainMember) {\n              (node as Undone<N.OptionalCallExpression>).optional =\n                isOptionalCall;\n            }\n\n            return this.finishCallExpression(node, state.optionalChainMember);\n          }\n\n          const tokenType = this.state.type;\n          if (\n            // a<b>>c is not (a<b>)>c, but a<(b>>c)\n            tokenType === tt.gt ||\n            // a<b>>>c is not (a<b>)>>c, but a<(b>>>c)\n            tokenType === tt.bitShiftR ||\n            // a<b>c is (a<b)>c\n            (tokenType !== tt.parenL &&\n              tokenCanStartExpression(tokenType) &&\n              !this.hasPrecedingLineBreak())\n          ) {\n            // Bail out.\n            return;\n          }\n\n          const node = this.startNodeAt<N.TsInstantiationExpression>(startLoc);\n          node.expression = base;\n          if (process.env.BABEL_8_BREAKING) {\n            node.typeArguments = typeArguments;\n          } else {\n            node.typeParameters = typeArguments;\n          }\n          return this.finishNode(node, \"TSInstantiationExpression\");\n        });\n\n        if (missingParenErrorLoc) {\n          this.unexpected(missingParenErrorLoc, tt.parenL);\n        }\n\n        if (result) {\n          if (result.type === \"TSInstantiationExpression\") {\n            if (\n              this.match(tt.dot) ||\n              (this.match(tt.questionDot) &&\n                this.lookaheadCharCode() !== charCodes.leftParenthesis)\n            ) {\n              this.raise(\n                TSErrors.InvalidPropertyAccessAfterInstantiationExpression,\n                this.state.startLoc,\n              );\n            }\n            if (!this.match(tt.dot) && !this.match(tt.questionDot)) {\n              // If TSInstantiationExpression is not followed by . / ?.,\n              // it must be the end of a subscript chain. Note that `(` already forms\n              // call expression arguments\n              result.expression = super.stopParseSubscript(base, state);\n            }\n          }\n          return result;\n        }\n      }\n\n      return super.parseSubscript(base, startLoc, noCalls, state);\n    }\n\n    parseNewCallee(node: N.NewExpression): void {\n      super.parseNewCallee(node);\n\n      const { callee } = node;\n      if (\n        callee.type === \"TSInstantiationExpression\" &&\n        !callee.extra?.parenthesized\n      ) {\n        if (process.env.BABEL_8_BREAKING) {\n          node.typeArguments = callee.typeArguments;\n        } else {\n          node.typeParameters = callee.typeParameters;\n        }\n        node.callee = callee.expression;\n      }\n    }\n\n    parseExprOp(\n      left: N.Expression,\n      leftStartLoc: Position,\n      minPrec: number,\n    ): N.Expression {\n      let isSatisfies: boolean;\n      if (\n        tokenOperatorPrecedence(tt._in) > minPrec &&\n        !this.hasPrecedingLineBreak() &&\n        (this.isContextual(tt._as) ||\n          (isSatisfies = this.isContextual(tt._satisfies)))\n      ) {\n        const node = this.startNodeAt<\n          N.TsAsExpression | N.TsSatisfiesExpression\n        >(leftStartLoc);\n        node.expression = left;\n        node.typeAnnotation = this.tsInType(() => {\n          this.next(); // \"as\" or \"satisfies\"\n          if (this.match(tt._const)) {\n            if (isSatisfies) {\n              this.raise(Errors.UnexpectedKeyword, this.state.startLoc, {\n                keyword: \"const\",\n              });\n            }\n            return this.tsParseTypeReference();\n          }\n\n          return this.tsParseType();\n        });\n        this.finishNode(\n          node,\n          isSatisfies ? \"TSSatisfiesExpression\" : \"TSAsExpression\",\n        );\n        // rescan `<`, `>` because they were scanned when this.state.inType was true\n        this.reScan_lt_gt();\n        return this.parseExprOp(\n          // @ts-expect-error todo(flow->ts)\n          node,\n          leftStartLoc,\n          minPrec,\n        );\n      }\n\n      return super.parseExprOp(left, leftStartLoc, minPrec);\n    }\n\n    checkReservedWord(\n      word: string,\n      startLoc: Position,\n      checkKeywords: boolean,\n      isBinding: boolean,\n    ): void {\n      // Strict mode words may be allowed as in `declare namespace N { const static: number; }`.\n      // And we have a type checker anyway, so don't bother having the parser do it.\n      if (!this.state.isAmbientContext) {\n        super.checkReservedWord(word, startLoc, checkKeywords, isBinding);\n      }\n    }\n\n    checkImportReflection(node: Undone<N.ImportDeclaration>) {\n      super.checkImportReflection(node);\n      if (node.module && node.importKind !== \"value\") {\n        this.raise(\n          TSErrors.ImportReflectionHasImportType,\n          node.specifiers[0].loc.start,\n        );\n      }\n    }\n\n    /*\n    Don't bother doing this check in TypeScript code because:\n    1. We may have a nested export statement with the same name:\n      export const x = 0;\n      export namespace N {\n        export const x = 1;\n      }\n    2. We have a type checker to warn us about this sort of thing.\n    */\n    checkDuplicateExports() {}\n\n    isPotentialImportPhase(isExport: boolean): boolean {\n      if (super.isPotentialImportPhase(isExport)) return true;\n      if (this.isContextual(tt._type)) {\n        const ch = this.lookaheadCharCode();\n        return isExport\n          ? ch === charCodes.leftCurlyBrace || ch === charCodes.asterisk\n          : ch !== charCodes.equalsTo;\n      }\n      return !isExport && this.isContextual(tt._typeof);\n    }\n\n    applyImportPhase(\n      node: Undone<N.ImportDeclaration | N.ExportNamedDeclaration>,\n      isExport: boolean,\n      phase: string | null,\n      loc?: Position,\n    ): void {\n      super.applyImportPhase(node, isExport, phase, loc);\n      if (isExport) {\n        (node as N.ExportNamedDeclaration).exportKind =\n          phase === \"type\" ? \"type\" : \"value\";\n      } else {\n        (node as N.ImportDeclaration).importKind =\n          phase === \"type\" || phase === \"typeof\" ? phase : \"value\";\n      }\n    }\n\n    parseImport(\n      node: Undone<N.ImportDeclaration | N.TsImportEqualsDeclaration>,\n    ): N.AnyImport {\n      if (this.match(tt.string)) {\n        node.importKind = \"value\";\n        return super.parseImport(node as Undone<N.ImportDeclaration>);\n      }\n\n      let importNode;\n      if (\n        tokenIsIdentifier(this.state.type) &&\n        this.lookaheadCharCode() === charCodes.equalsTo\n      ) {\n        node.importKind = \"value\";\n        return this.tsParseImportEqualsDeclaration(\n          node as Undone<N.TsImportEqualsDeclaration>,\n        );\n      } else if (this.isContextual(tt._type)) {\n        const maybeDefaultIdentifier = this.parseMaybeImportPhase(\n          node as Undone<N.ImportDeclaration>,\n          /* isExport */ false,\n        );\n        if (this.lookaheadCharCode() === charCodes.equalsTo) {\n          return this.tsParseImportEqualsDeclaration(\n            node as Undone<N.TsImportEqualsDeclaration>,\n            maybeDefaultIdentifier,\n          );\n        } else {\n          importNode = super.parseImportSpecifiersAndAfter(\n            node as Undone<N.ImportDeclaration>,\n            maybeDefaultIdentifier,\n          );\n        }\n      } else {\n        importNode = super.parseImport(node as Undone<N.ImportDeclaration>);\n      }\n\n      // `import type` can only be used on imports with named imports or with a\n      // default import - but not both\n      if (\n        importNode.importKind === \"type\" &&\n        // @ts-expect-error refine typings\n        importNode.specifiers.length > 1 &&\n        // @ts-expect-error refine typings\n        importNode.specifiers[0].type === \"ImportDefaultSpecifier\"\n      ) {\n        this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, importNode);\n      }\n\n      return importNode;\n    }\n\n    parseExport(\n      node: Undone<\n        | N.ExportDefaultDeclaration\n        | N.ExportAllDeclaration\n        | N.ExportNamedDeclaration\n      >,\n      decorators: N.Decorator[] | null,\n    ): N.AnyExport {\n      if (this.match(tt._import)) {\n        // `export import A = B;`\n        const nodeImportEquals = process.env.BABEL_8_BREAKING\n          ? this.startNode<N.TsImportEqualsDeclaration>()\n          : (node as Undone<N.TsImportEqualsDeclaration>);\n        this.next(); // eat `tt._import`\n        let maybeDefaultIdentifier: N.Identifier | null = null;\n        if (\n          this.isContextual(tt._type) &&\n          // We pass false here, because we are parsing an `import ... =`\n          this.isPotentialImportPhase(/* isExport */ false)\n        ) {\n          maybeDefaultIdentifier = this.parseMaybeImportPhase(\n            nodeImportEquals,\n            /* isExport */ false,\n          );\n        } else {\n          nodeImportEquals.importKind = \"value\";\n        }\n        const declaration = this.tsParseImportEqualsDeclaration(\n          nodeImportEquals,\n          maybeDefaultIdentifier,\n          /* isExport */ true,\n        );\n        if (process.env.BABEL_8_BREAKING) {\n          (node as Undone<N.ExportNamedDeclaration>).attributes = [];\n          (node as Undone<N.ExportNamedDeclaration>).declaration = declaration;\n          (node as Undone<N.ExportNamedDeclaration>).exportKind = \"value\";\n          (node as Undone<N.ExportNamedDeclaration>).source = null;\n          (node as Undone<N.ExportNamedDeclaration>).specifiers = [];\n          return this.finishNode(node, \"ExportNamedDeclaration\");\n        } else {\n          return declaration;\n        }\n      } else if (this.eat(tt.eq)) {\n        // `export = x;`\n        const assign = node as Undone<N.TsExportAssignment>;\n        assign.expression = super.parseExpression();\n        this.semicolon();\n        this.sawUnambiguousESM = true;\n        return this.finishNode(assign, \"TSExportAssignment\");\n      } else if (this.eatContextual(tt._as)) {\n        // `export as namespace A;`\n        const decl = node as Undone<N.TsNamespaceExportDeclaration>;\n        // See `parseNamespaceExportDeclaration` in TypeScript's own parser\n        this.expectContextual(tt._namespace);\n        decl.id = this.parseIdentifier();\n        this.semicolon();\n        return this.finishNode(decl, \"TSNamespaceExportDeclaration\");\n      } else {\n        return super.parseExport(\n          node as Undone<N.ExportAllDeclaration | N.ExportDefaultDeclaration>,\n          decorators,\n        );\n      }\n    }\n\n    isAbstractClass(): boolean {\n      return (\n        this.isContextual(tt._abstract) && this.isLookaheadContextual(\"class\")\n      );\n    }\n\n    parseExportDefaultExpression(): N.ExportDefaultDeclaration[\"declaration\"] {\n      if (this.isAbstractClass()) {\n        const cls = this.startNode<N.Class>();\n        this.next(); // Skip \"abstract\"\n        cls.abstract = true;\n        return this.parseClass(cls, true, true);\n      }\n\n      // export default interface allowed in:\n      // https://github.com/Microsoft/TypeScript/pull/16040\n      if (this.match(tt._interface)) {\n        const result = this.tsParseInterfaceDeclaration(\n          this.startNode<N.TsInterfaceDeclaration>(),\n        );\n        if (result) return result;\n      }\n\n      return super.parseExportDefaultExpression();\n    }\n\n    parseVarStatement(\n      node: N.VariableDeclaration,\n      kind: \"var\" | \"let\" | \"const\" | \"using\" | \"await using\",\n      allowMissingInitializer: boolean = false,\n    ) {\n      const { isAmbientContext } = this.state;\n      const declaration = super.parseVarStatement(\n        node,\n        kind,\n        allowMissingInitializer || isAmbientContext,\n      );\n\n      if (!isAmbientContext) return declaration;\n\n      // If node.declare is true, the error has already been raised in tsTryParseDeclare.\n      if (!node.declare && (kind === \"using\" || kind === \"await using\")) {\n        this.raiseOverwrite(\n          TSErrors.UsingDeclarationInAmbientContext,\n          node,\n          kind,\n        );\n        return declaration;\n      }\n\n      for (const { id, init } of declaration.declarations) {\n        // Empty initializer is the easy case that we want.\n        if (!init) continue;\n\n        // var and let aren't ever allowed initializers.\n        if (kind === \"var\" || kind === \"let\" || !!id.typeAnnotation) {\n          this.raise(TSErrors.InitializerNotAllowedInAmbientContext, init);\n        } else if (\n          !isValidAmbientConstInitializer(init, this.hasPlugin(\"estree\"))\n        ) {\n          this.raise(\n            TSErrors.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference,\n            init,\n          );\n        }\n      }\n\n      return declaration;\n    }\n\n    parseStatementContent(\n      flags: ParseStatementFlag,\n      decorators?: N.Decorator[] | null,\n    ): N.Statement {\n      if (this.match(tt._const) && this.isLookaheadContextual(\"enum\")) {\n        const node = this.startNode<N.TsEnumDeclaration>();\n        this.expect(tt._const); // eat 'const'\n        return this.tsParseEnumDeclaration(node, { const: true });\n      }\n\n      if (this.isContextual(tt._enum)) {\n        return this.tsParseEnumDeclaration(\n          this.startNode<N.TsEnumDeclaration>(),\n        );\n      }\n\n      if (this.isContextual(tt._interface)) {\n        const result = this.tsParseInterfaceDeclaration(this.startNode());\n        if (result) return result;\n      }\n\n      return super.parseStatementContent(flags, decorators);\n    }\n\n    parseAccessModifier(): N.Accessibility | undefined | null {\n      return this.tsParseModifier([\"public\", \"protected\", \"private\"]);\n    }\n\n    tsHasSomeModifiers(member: any, modifiers: readonly TsModifier[]): boolean {\n      return modifiers.some(modifier => {\n        if (tsIsAccessModifier(modifier)) {\n          return member.accessibility === modifier;\n        }\n        return !!member[modifier];\n      });\n    }\n\n    tsIsStartOfStaticBlocks() {\n      return (\n        this.isContextual(tt._static) &&\n        this.lookaheadCharCode() === charCodes.leftCurlyBrace\n      );\n    }\n\n    parseClassMember(\n      classBody: N.ClassBody,\n      member: any,\n      state: N.ParseClassMemberState,\n    ): void {\n      const modifiers = [\n        \"declare\",\n        \"private\",\n        \"public\",\n        \"protected\",\n        \"override\",\n        \"abstract\",\n        \"readonly\",\n        \"static\",\n      ] as const;\n      this.tsParseModifiers(\n        {\n          allowedModifiers: modifiers,\n          disallowedModifiers: [\"in\", \"out\"],\n          stopOnStartOfClassStaticBlock: true,\n          errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions,\n        },\n        member,\n      );\n\n      const callParseClassMemberWithIsStatic = () => {\n        if (this.tsIsStartOfStaticBlocks()) {\n          this.next(); // eat \"static\"\n          this.next(); // eat \"{\"\n          if (this.tsHasSomeModifiers(member, modifiers)) {\n            this.raise(\n              TSErrors.StaticBlockCannotHaveModifier,\n              this.state.curPosition(),\n            );\n          }\n          super.parseClassStaticBlock(classBody, member as N.StaticBlock);\n        } else {\n          this.parseClassMemberWithIsStatic(\n            classBody,\n            member,\n            state,\n            !!member.static,\n          );\n        }\n      };\n      if (member.declare) {\n        this.tsInAmbientContext(callParseClassMemberWithIsStatic);\n      } else {\n        callParseClassMemberWithIsStatic();\n      }\n    }\n\n    parseClassMemberWithIsStatic(\n      classBody: N.ClassBody,\n      member: Undone<N.ClassMember | N.TsIndexSignature>,\n      state: N.ParseClassMemberState,\n      isStatic: boolean,\n    ): void {\n      const idx = this.tsTryParseIndexSignature(\n        member as Undone<N.TsIndexSignature>,\n      );\n      if (idx) {\n        classBody.body.push(idx);\n\n        if ((member as any).abstract) {\n          this.raise(TSErrors.IndexSignatureHasAbstract, member);\n        }\n        if ((member as any).accessibility) {\n          this.raise(TSErrors.IndexSignatureHasAccessibility, member, {\n            modifier: (member as any).accessibility,\n          });\n        }\n        if ((member as any).declare) {\n          this.raise(TSErrors.IndexSignatureHasDeclare, member);\n        }\n        if ((member as any).override) {\n          this.raise(TSErrors.IndexSignatureHasOverride, member);\n        }\n\n        return;\n      }\n\n      if (!this.state.inAbstractClass && (member as any).abstract) {\n        this.raise(TSErrors.NonAbstractClassHasAbstractMethod, member);\n      }\n\n      if ((member as any).override) {\n        if (!state.hadSuperClass) {\n          this.raise(TSErrors.OverrideNotInSubClass, member);\n        }\n      }\n\n      /*:: invariant(member.type !== \"TSIndexSignature\") */\n\n      super.parseClassMemberWithIsStatic(\n        classBody,\n        member as Undone<N.ClassMember>,\n        state,\n        isStatic,\n      );\n    }\n\n    parsePostMemberNameModifiers(\n      methodOrProp: N.ClassMethod | N.ClassProperty | N.ClassPrivateProperty,\n    ): void {\n      const optional = this.eat(tt.question);\n      if (optional) methodOrProp.optional = true;\n\n      if ((methodOrProp as any).readonly && this.match(tt.parenL)) {\n        this.raise(TSErrors.ClassMethodHasReadonly, methodOrProp);\n      }\n\n      if ((methodOrProp as any).declare && this.match(tt.parenL)) {\n        this.raise(TSErrors.ClassMethodHasDeclare, methodOrProp);\n      }\n    }\n\n    // Note: The reason we do this in `parseExpressionStatement` and not `parseStatement`\n    // is that e.g. `type()` is valid JS, so we must try parsing that first.\n    // If it's really a type, we will parse `type` as the statement, and can correct it here\n    // by parsing the rest.\n    // @ts-expect-error plugin overrides interfaces\n    parseExpressionStatement(\n      node: Undone<N.ExpressionStatement>,\n      expr: N.Expression,\n      decorators: N.Decorator[] | null,\n    ): N.Statement {\n      const decl =\n        expr.type === \"Identifier\"\n          ? // @ts-expect-error refine typings\n            this.tsParseExpressionStatement(node, expr, decorators)\n          : undefined;\n      return decl || super.parseExpressionStatement(node, expr, decorators);\n    }\n\n    // export type\n    // Should be true for anything parsed by `tsTryParseExportDeclaration`.\n    shouldParseExportDeclaration(): boolean {\n      if (this.tsIsDeclarationStart()) return true;\n      return super.shouldParseExportDeclaration();\n    }\n\n    // An apparent conditional expression could actually be an optional parameter in an arrow function.\n    parseConditional(\n      expr: N.Expression,\n\n      startLoc: Position,\n      refExpressionErrors?: ExpressionErrors | null,\n    ): N.Expression {\n      if (!this.match(tt.question)) return expr;\n\n      if (this.state.maybeInArrowParameters) {\n        const nextCh = this.lookaheadCharCode();\n        // These tokens cannot start an expression, so if one of them follows\n        // ? then we are probably in an arrow function parameters list and we\n        // don't parse the conditional expression.\n        if (\n          nextCh === charCodes.comma || // (a?, b) => c\n          nextCh === charCodes.equalsTo || // (a? = b) => c\n          nextCh === charCodes.colon || // (a?: b) => c\n          nextCh === charCodes.rightParenthesis // (a?) => c\n        ) {\n          /*:: invariant(refExpressionErrors != null) */\n          this.setOptionalParametersError(refExpressionErrors);\n          return expr;\n        }\n      }\n\n      return super.parseConditional(expr, startLoc, refExpressionErrors);\n    }\n\n    // Note: These \"type casts\" are *not* valid TS expressions.\n    // But we parse them here and change them when completing the arrow function.\n    parseParenItem<T extends N.Expression | N.RestElement | N.SpreadElement>(\n      node: T,\n      startLoc: Position,\n    ): T | N.TsTypeCastExpression {\n      const newNode = super.parseParenItem(node, startLoc);\n      if (this.eat(tt.question)) {\n        (newNode as N.Identifier).optional = true;\n        // Include questionmark in location of node\n        // Don't use this.finishNode() as otherwise we might process comments twice and\n        // include already consumed parens\n        this.resetEndLocation(node);\n      }\n\n      if (this.match(tt.colon)) {\n        const typeCastNode = this.startNodeAt<N.TsTypeCastExpression>(startLoc);\n        typeCastNode.expression = node as N.Expression;\n        typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();\n\n        return this.finishNode(typeCastNode, \"TSTypeCastExpression\");\n      }\n\n      return node;\n    }\n\n    parseExportDeclaration(\n      node: N.ExportNamedDeclaration,\n    ): N.Declaration | undefined | null {\n      if (!this.state.isAmbientContext && this.isContextual(tt._declare)) {\n        return this.tsInAmbientContext(() => this.parseExportDeclaration(node));\n      }\n\n      // Store original location\n      const startLoc = this.state.startLoc;\n\n      const isDeclare = this.eatContextual(tt._declare);\n\n      if (\n        isDeclare &&\n        (this.isContextual(tt._declare) || !this.shouldParseExportDeclaration())\n      ) {\n        throw this.raise(\n          TSErrors.ExpectedAmbientAfterExportDeclare,\n          this.state.startLoc,\n        );\n      }\n\n      const isIdentifier = tokenIsIdentifier(this.state.type);\n      const declaration: N.Declaration | undefined | null =\n        (isIdentifier && this.tsTryParseExportDeclaration()) ||\n        super.parseExportDeclaration(node);\n\n      if (!declaration) return null;\n\n      if (\n        declaration.type === \"TSInterfaceDeclaration\" ||\n        declaration.type === \"TSTypeAliasDeclaration\" ||\n        isDeclare\n      ) {\n        node.exportKind = \"type\";\n      }\n\n      if (isDeclare && declaration.type !== \"TSImportEqualsDeclaration\") {\n        // Reset location to include `declare` in range\n        this.resetStartLocation(declaration, startLoc);\n\n        declaration.declare = true;\n      }\n\n      return declaration;\n    }\n\n    parseClassId(\n      node: N.Class,\n      isStatement: boolean,\n      optionalId?: boolean | null,\n      // eslint-disable-next-line @typescript-eslint/no-unused-vars\n      bindingType?: BindingFlag,\n    ): void {\n      if ((!isStatement || optionalId) && this.isContextual(tt._implements)) {\n        return;\n      }\n\n      super.parseClassId(\n        node,\n        isStatement,\n        optionalId,\n        (node as any).declare\n          ? BindingFlag.TYPE_TS_AMBIENT\n          : BindingFlag.TYPE_CLASS,\n      );\n      const typeParameters = this.tsTryParseTypeParameters(\n        this.tsParseInOutConstModifiers,\n      );\n      if (typeParameters) node.typeParameters = typeParameters;\n    }\n\n    parseClassPropertyAnnotation(\n      node: N.ClassProperty | N.ClassPrivateProperty | N.ClassAccessorProperty,\n    ): void {\n      if (!node.optional) {\n        if (this.eat(tt.bang)) {\n          node.definite = true;\n        } else if (this.eat(tt.question)) {\n          node.optional = true;\n        }\n      }\n\n      const type = this.tsTryParseTypeAnnotation();\n      if (type) node.typeAnnotation = type;\n    }\n\n    parseClassProperty(node: N.ClassProperty): N.ClassProperty {\n      this.parseClassPropertyAnnotation(node);\n\n      if (\n        this.state.isAmbientContext &&\n        !(node.readonly && !node.typeAnnotation) &&\n        this.match(tt.eq)\n      ) {\n        this.raise(\n          TSErrors.DeclareClassFieldHasInitializer,\n          this.state.startLoc,\n        );\n      }\n      if (node.abstract && this.match(tt.eq)) {\n        const { key } = node;\n        this.raise(\n          TSErrors.AbstractPropertyHasInitializer,\n          this.state.startLoc,\n          {\n            propertyName:\n              key.type === \"Identifier\" && !node.computed\n                ? key.name\n                : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]`,\n          },\n        );\n      }\n\n      return super.parseClassProperty(node);\n    }\n\n    parseClassPrivateProperty(\n      node: N.ClassPrivateProperty,\n    ): N.ClassPrivateProperty {\n      if (node.abstract) {\n        this.raise(TSErrors.PrivateElementHasAbstract, node);\n      }\n\n      if (node.accessibility) {\n        this.raise(TSErrors.PrivateElementHasAccessibility, node, {\n          modifier: node.accessibility,\n        });\n      }\n\n      this.parseClassPropertyAnnotation(node);\n      return super.parseClassPrivateProperty(node);\n    }\n\n    parseClassAccessorProperty(\n      node: N.ClassAccessorProperty,\n    ): N.ClassAccessorProperty {\n      this.parseClassPropertyAnnotation(node);\n      if (node.optional) {\n        this.raise(TSErrors.AccessorCannotBeOptional, node);\n      }\n      return super.parseClassAccessorProperty(node);\n    }\n\n    pushClassMethod(\n      classBody: N.ClassBody,\n      method: N.ClassMethod,\n      isGenerator: boolean,\n      isAsync: boolean,\n      isConstructor: boolean,\n      allowsDirectSuper: boolean,\n    ): void {\n      const typeParameters = this.tsTryParseTypeParameters(\n        this.tsParseConstModifier,\n      );\n      if (typeParameters && isConstructor) {\n        this.raise(TSErrors.ConstructorHasTypeParameters, typeParameters);\n      }\n\n      const { declare = false, kind } = method;\n\n      if (declare && (kind === \"get\" || kind === \"set\")) {\n        this.raise(TSErrors.DeclareAccessor, method, { kind });\n      }\n      if (typeParameters) method.typeParameters = typeParameters;\n      super.pushClassMethod(\n        classBody,\n        method,\n        isGenerator,\n        isAsync,\n        isConstructor,\n        allowsDirectSuper,\n      );\n    }\n\n    pushClassPrivateMethod(\n      classBody: N.ClassBody,\n      method: N.ClassPrivateMethod,\n      isGenerator: boolean,\n      isAsync: boolean,\n    ): void {\n      const typeParameters = this.tsTryParseTypeParameters(\n        this.tsParseConstModifier,\n      );\n      if (typeParameters) method.typeParameters = typeParameters;\n      super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);\n    }\n\n    declareClassPrivateMethodInScope(\n      node: N.ClassPrivateMethod | N.TSDeclareMethod,\n      kind: number,\n    ) {\n      if (node.type === \"TSDeclareMethod\") return;\n      // This happens when using the \"estree\" plugin.\n      if (\n        (node as N.Node).type === \"MethodDefinition\" &&\n        (node as unknown as N.EstreeMethodDefinition).value.body == null\n      ) {\n        return;\n      }\n\n      super.declareClassPrivateMethodInScope(node, kind);\n    }\n\n    parseClassSuper(node: N.Class): void {\n      super.parseClassSuper(node);\n      // handle `extends f<<T>\n      if (node.superClass && (this.match(tt.lt) || this.match(tt.bitShiftL))) {\n        if (process.env.BABEL_8_BREAKING) {\n          node.superTypeArguments = this.tsParseTypeArgumentsInExpression();\n        } else {\n          node.superTypeParameters = this.tsParseTypeArgumentsInExpression();\n        }\n      }\n      if (this.eatContextual(tt._implements)) {\n        node.implements = this.tsParseHeritageClause(\"implements\");\n      }\n    }\n\n    parseObjPropValue<T extends N.ObjectMember>(\n      prop: Undone<T>,\n      startLoc: Position | undefined | null,\n      isGenerator: boolean,\n      isAsync: boolean,\n      isPattern: boolean,\n      isAccessor: boolean,\n      refExpressionErrors?: ExpressionErrors | null,\n    ): T {\n      const typeParameters = this.tsTryParseTypeParameters(\n        this.tsParseConstModifier,\n      );\n      if (typeParameters) prop.typeParameters = typeParameters;\n\n      return super.parseObjPropValue(\n        prop,\n\n        startLoc,\n        isGenerator,\n        isAsync,\n        isPattern,\n        isAccessor,\n        refExpressionErrors,\n      );\n    }\n\n    parseFunctionParams(node: N.Function, isConstructor: boolean): void {\n      const typeParameters = this.tsTryParseTypeParameters(\n        this.tsParseConstModifier,\n      );\n      if (typeParameters) node.typeParameters = typeParameters;\n      super.parseFunctionParams(node, isConstructor);\n    }\n\n    // `let x: number;`\n    parseVarId(\n      decl: N.VariableDeclarator,\n      kind: \"var\" | \"let\" | \"const\" | \"using\" | \"await using\",\n    ): void {\n      super.parseVarId(decl, kind);\n      if (\n        decl.id.type === \"Identifier\" &&\n        !this.hasPrecedingLineBreak() &&\n        this.eat(tt.bang)\n      ) {\n        decl.definite = true;\n      }\n\n      const type = this.tsTryParseTypeAnnotation();\n      if (type) {\n        decl.id.typeAnnotation = type;\n        this.resetEndLocation(decl.id); // set end position to end of type\n      }\n    }\n\n    // parse the return type of an async arrow function - let foo = (async (): number => {});\n    parseAsyncArrowFromCallExpression(\n      node: N.ArrowFunctionExpression,\n      call: N.CallExpression,\n    ): N.ArrowFunctionExpression {\n      if (this.match(tt.colon)) {\n        node.returnType = this.tsParseTypeAnnotation();\n      }\n      return super.parseAsyncArrowFromCallExpression(node, call);\n    }\n\n    parseMaybeAssign(\n      refExpressionErrors?: ExpressionErrors | null,\n      afterLeftParse?: Function,\n    ): N.Expression {\n      // Note: When the JSX plugin is on, type assertions (`<T> x`) aren't valid syntax.\n\n      let state: State | undefined | null;\n      let jsx;\n      let typeCast;\n\n      if (\n        this.hasPlugin(\"jsx\") &&\n        (this.match(tt.jsxTagStart) || this.match(tt.lt))\n      ) {\n        // Prefer to parse JSX if possible. But may be an arrow fn.\n        state = this.state.clone();\n\n        jsx = this.tryParse(\n          () => super.parseMaybeAssign(refExpressionErrors, afterLeftParse),\n          state,\n        );\n\n        /*:: invariant(!jsx.aborted) */\n        /*:: invariant(jsx.node != null) */\n        if (!jsx.error) return jsx.node;\n\n        // Remove `tc.j_expr` or `tc.j_oTag` from context added\n        // by parsing `jsxTagStart` to stop the JSX plugin from\n        // messing with the tokens\n        const { context } = this.state;\n        const currentContext = context[context.length - 1];\n        if (currentContext === tc.j_oTag || currentContext === tc.j_expr) {\n          context.pop();\n        }\n      }\n\n      if (!jsx?.error && !this.match(tt.lt)) {\n        return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);\n      }\n\n      // Either way, we're looking at a '<': tt.jsxTagStart or relational.\n\n      // If the state was cloned in the JSX parsing branch above but there\n      // have been any error in the tryParse call, this.state is set to state\n      // so we still need to clone it.\n      if (!state || state === this.state) state = this.state.clone();\n\n      let typeParameters: N.TsTypeParameterDeclaration | undefined | null;\n      // We need to explicitly annotate 'abort' for microsoft/TypeScript#58170\n      const arrow = this.tryParse((abort: () => never) => {\n        // This is similar to TypeScript's `tryParseParenthesizedArrowFunctionExpression`.\n        typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);\n        const expr = super.parseMaybeAssign(\n          refExpressionErrors,\n          afterLeftParse,\n        );\n\n        if (\n          expr.type !== \"ArrowFunctionExpression\" ||\n          expr.extra?.parenthesized\n        ) {\n          abort();\n        }\n\n        // Correct TypeScript code should have at least 1 type parameter, but don't crash on bad code.\n        if (typeParameters?.params.length !== 0) {\n          this.resetStartLocationFromNode(expr, typeParameters);\n        }\n        expr.typeParameters = typeParameters;\n\n        if (process.env.BABEL_8_BREAKING) {\n          if (\n            this.hasPlugin(\"jsx\") &&\n            expr.typeParameters.params.length === 1 &&\n            !expr.typeParameters.extra?.trailingComma\n          ) {\n            // report error if single type parameter used without trailing comma.\n            const parameter = expr.typeParameters\n              .params[0] as N.TsTypeParameter;\n            if (!parameter.constraint) {\n              // A single type parameter must either have constraints\n              // or a trailing comma, otherwise it's ambiguous with JSX.\n              this.raise(\n                TSErrors.SingleTypeParameterWithoutTrailingComma,\n                createPositionWithColumnOffset(parameter.loc.end, 1),\n                {\n                  typeParameterName: process.env.BABEL_8_BREAKING\n                    ? (parameter.name as N.Identifier).name\n                    : (parameter.name as string),\n                },\n              );\n            }\n          }\n        }\n\n        return expr;\n      }, state);\n\n      /*:: invariant(arrow.node != null) */\n      if (!arrow.error && !arrow.aborted) {\n        // This error is reported outside of the this.tryParse call so that\n        // in case of <T>(x) => 2, we don't consider <T>(x) as a type assertion\n        // because of this error.\n        if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);\n        return arrow.node;\n      }\n\n      if (!jsx) {\n        // Try parsing a type cast instead of an arrow function.\n        // This will never happen outside of JSX.\n        // (Because in JSX the '<' should be a jsxTagStart and not a relational.\n        assert(!this.hasPlugin(\"jsx\"));\n\n        // This will start with a type assertion (via parseMaybeUnary).\n        // But don't directly call `this.tsParseTypeAssertion` because we want to handle any binary after it.\n        typeCast = this.tryParse(\n          () => super.parseMaybeAssign(refExpressionErrors, afterLeftParse),\n          state,\n        );\n        /*:: invariant(!typeCast.aborted) */\n        /*:: invariant(typeCast.node != null) */\n        if (!typeCast.error) return typeCast.node;\n      }\n\n      if (jsx?.node) {\n        /*:: invariant(jsx.failState) */\n        this.state = jsx.failState;\n        return jsx.node;\n      }\n\n      if (arrow.node) {\n        /*:: invariant(arrow.failState) */\n        this.state = arrow.failState;\n        if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);\n        return arrow.node;\n      }\n\n      if (typeCast?.node) {\n        /*:: invariant(typeCast.failState) */\n        this.state = typeCast.failState;\n        return typeCast.node;\n      }\n\n      throw jsx?.error || arrow.error || typeCast?.error;\n    }\n\n    reportReservedArrowTypeParam(node: any) {\n      if (\n        node.params.length === 1 &&\n        !node.params[0].constraint &&\n        !node.extra?.trailingComma &&\n        this.getPluginOption(\"typescript\", \"disallowAmbiguousJSXLike\")\n      ) {\n        this.raise(TSErrors.ReservedArrowTypeParam, node);\n      }\n    }\n\n    // Handle type assertions\n    parseMaybeUnary(\n      refExpressionErrors?: ExpressionErrors | null,\n      sawUnary?: boolean,\n    ): N.Expression {\n      if (!this.hasPlugin(\"jsx\") && this.match(tt.lt)) {\n        return this.tsParseTypeAssertion();\n      }\n      return super.parseMaybeUnary(refExpressionErrors, sawUnary);\n    }\n\n    parseArrow(\n      node: Undone<N.ArrowFunctionExpression>,\n    ): Undone<N.ArrowFunctionExpression> | undefined | null {\n      if (this.match(tt.colon)) {\n        // This is different from how the TS parser does it.\n        // TS uses lookahead. The Babel Parser parses it as a parenthesized expression and converts.\n\n        const result = this.tryParse(abort => {\n          const returnType = this.tsParseTypeOrTypePredicateAnnotation(\n            tt.colon,\n          );\n          if (this.canInsertSemicolon() || !this.match(tt.arrow)) abort();\n          return returnType;\n        });\n\n        if (result.aborted) return;\n\n        if (!result.thrown) {\n          if (result.error) this.state = result.failState;\n          // @ts-expect-error refine typings\n          node.returnType = result.node;\n        }\n      }\n\n      return super.parseArrow(node);\n    }\n\n    // Allow type annotations inside of a parameter list.\n    parseFunctionParamType(param: N.Pattern) {\n      if (this.eat(tt.question)) {\n        (param as any as N.Identifier).optional = true;\n      }\n      const type = this.tsTryParseTypeAnnotation();\n      if (type) param.typeAnnotation = type;\n      this.resetEndLocation(param);\n\n      return param;\n    }\n\n    isAssignable(node: N.Node, isBinding?: boolean): boolean {\n      switch (node.type) {\n        case \"TSTypeCastExpression\":\n          return this.isAssignable(node.expression, isBinding);\n        case \"TSParameterProperty\":\n          return true;\n        default:\n          return super.isAssignable(node, isBinding);\n      }\n    }\n\n    toAssignable(node: N.Node, isLHS: boolean = false): void {\n      switch (node.type) {\n        case \"ParenthesizedExpression\":\n          this.toAssignableParenthesizedExpression(node, isLHS);\n          break;\n        case \"TSAsExpression\":\n        case \"TSSatisfiesExpression\":\n        case \"TSNonNullExpression\":\n        case \"TSTypeAssertion\":\n          if (isLHS) {\n            this.expressionScope.recordArrowParameterBindingError(\n              TSErrors.UnexpectedTypeCastInParameter,\n              node,\n            );\n          } else {\n            this.raise(TSErrors.UnexpectedTypeCastInParameter, node);\n          }\n          this.toAssignable(node.expression, isLHS);\n          break;\n        case \"AssignmentExpression\":\n          if (!isLHS && node.left.type === \"TSTypeCastExpression\") {\n            node.left = this.typeCastToParameter(node.left) as N.Assignable;\n          }\n        /* fall through */\n        default:\n          super.toAssignable(node, isLHS);\n      }\n    }\n\n    toAssignableParenthesizedExpression(\n      node: N.ParenthesizedExpression,\n      isLHS: boolean,\n    ): void {\n      switch (node.expression.type) {\n        case \"TSAsExpression\":\n        case \"TSSatisfiesExpression\":\n        case \"TSNonNullExpression\":\n        case \"TSTypeAssertion\":\n        case \"ParenthesizedExpression\":\n          this.toAssignable(node.expression, isLHS);\n          break;\n        default:\n          super.toAssignable(node, isLHS);\n      }\n    }\n\n    checkToRestConversion(node: N.Node, allowPattern: boolean): void {\n      switch (node.type) {\n        case \"TSAsExpression\":\n        case \"TSSatisfiesExpression\":\n        case \"TSTypeAssertion\":\n        case \"TSNonNullExpression\":\n          this.checkToRestConversion(node.expression, false);\n          break;\n        default:\n          super.checkToRestConversion(node, allowPattern);\n      }\n    }\n\n    isValidLVal(\n      type:\n        | \"TSTypeCastExpression\"\n        | \"TSParameterProperty\"\n        | \"TSNonNullExpression\"\n        | \"TSInstantiationExpression\"\n        | \"TSAsExpression\"\n        | \"TSSatisfiesExpression\"\n        | \"TSTypeAssertion\",\n      isUnparenthesizedInAssign: boolean,\n      binding: BindingFlag,\n    ) {\n      switch (type) {\n        // Allow \"typecasts\" to appear on the left of assignment expressions,\n        // because it may be in an arrow function.\n        // e.g. `const f = (foo: number = 0) => foo;`\n        case \"TSTypeCastExpression\":\n          return true;\n        case \"TSParameterProperty\":\n          return \"parameter\";\n        case \"TSNonNullExpression\":\n          return \"expression\";\n        case \"TSAsExpression\":\n        case \"TSSatisfiesExpression\":\n        case \"TSTypeAssertion\":\n          return (\n            (binding !== BindingFlag.TYPE_NONE || !isUnparenthesizedInAssign) &&\n            ([\"expression\", true] as [string, boolean])\n          );\n        default:\n          return super.isValidLVal(type, isUnparenthesizedInAssign, binding);\n      }\n    }\n\n    parseBindingAtom(): N.Pattern {\n      if (this.state.type === tt._this) {\n        return this.parseIdentifier(/* liberal */ true);\n      }\n      return super.parseBindingAtom();\n    }\n\n    parseMaybeDecoratorArguments(\n      expr: N.Expression,\n      startLoc: Position,\n    ): N.Expression {\n      // handles `@f<<T>`\n      if (this.match(tt.lt) || this.match(tt.bitShiftL)) {\n        const typeArguments = this.tsParseTypeArgumentsInExpression();\n\n        if (this.match(tt.parenL)) {\n          const call = super.parseMaybeDecoratorArguments(\n            expr,\n            startLoc,\n          ) as N.CallExpression;\n          if (process.env.BABEL_8_BREAKING) {\n            call.typeArguments = typeArguments;\n          } else {\n            call.typeParameters = typeArguments;\n          }\n\n          return call;\n        }\n\n        this.unexpected(null, tt.parenL);\n      }\n\n      return super.parseMaybeDecoratorArguments(expr, startLoc);\n    }\n\n    checkCommaAfterRest(\n      close: (typeof charCodes)[keyof typeof charCodes],\n    ): boolean {\n      if (\n        this.state.isAmbientContext &&\n        this.match(tt.comma) &&\n        this.lookaheadCharCode() === close\n      ) {\n        this.next();\n        return false;\n      }\n      return super.checkCommaAfterRest(close);\n    }\n\n    // === === === === === === === === === === === === === === === ===\n    // Note: All below methods are duplicates of something in flow.js.\n    // Not sure what the best way to combine these is.\n    // === === === === === === === === === === === === === === === ===\n\n    isClassMethod(): boolean {\n      return this.match(tt.lt) || super.isClassMethod();\n    }\n\n    isClassProperty(): boolean {\n      return (\n        this.match(tt.bang) || this.match(tt.colon) || super.isClassProperty()\n      );\n    }\n\n    parseMaybeDefault<P extends N.Pattern>(\n      startLoc?: Position | null,\n      left?: P | null,\n    ): P | N.AssignmentPattern {\n      const node = super.parseMaybeDefault(startLoc, left);\n\n      if (\n        node.type === \"AssignmentPattern\" &&\n        node.typeAnnotation &&\n        node.right.start < node.typeAnnotation.start\n      ) {\n        this.raise(TSErrors.TypeAnnotationAfterAssign, node.typeAnnotation);\n      }\n\n      return node;\n    }\n\n    // ensure that inside types, we bypass the jsx parser plugin\n    getTokenFromCode(code: number): void {\n      if (this.state.inType) {\n        if (code === charCodes.greaterThan) {\n          this.finishOp(tt.gt, 1);\n          return;\n        }\n        if (code === charCodes.lessThan) {\n          this.finishOp(tt.lt, 1);\n          return;\n        }\n      }\n      super.getTokenFromCode(code);\n    }\n\n    // used after we have finished parsing types\n    reScan_lt_gt() {\n      const { type } = this.state;\n      if (type === tt.lt) {\n        this.state.pos -= 1;\n        this.readToken_lt();\n      } else if (type === tt.gt) {\n        this.state.pos -= 1;\n        this.readToken_gt();\n      }\n    }\n\n    reScan_lt() {\n      const { type } = this.state;\n      if (type === tt.bitShiftL) {\n        this.state.pos -= 2;\n        this.finishOp(tt.lt, 1);\n        return tt.lt;\n      }\n      return type;\n    }\n\n    toAssignableListItem(\n      exprList: (N.Expression | N.SpreadElement | N.RestElement)[],\n      index: number,\n      isLHS: boolean,\n    ): void {\n      const node = exprList[index];\n      if (node.type === \"TSTypeCastExpression\") {\n        exprList[index] = this.typeCastToParameter(node);\n      }\n      super.toAssignableListItem(exprList, index, isLHS);\n    }\n\n    typeCastToParameter(node: N.TsTypeCastExpression): N.Expression {\n      (node.expression as N.Identifier).typeAnnotation = node.typeAnnotation;\n\n      this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);\n\n      return node.expression;\n    }\n\n    shouldParseArrow(params: Array<N.Node>) {\n      if (this.match(tt.colon)) {\n        return params.every(expr => this.isAssignable(expr, true));\n      }\n      return super.shouldParseArrow(params);\n    }\n\n    shouldParseAsyncArrow(): boolean {\n      return this.match(tt.colon) || super.shouldParseAsyncArrow();\n    }\n\n    canHaveLeadingDecorator() {\n      // Avoid unnecessary lookahead in checking for abstract class unless needed!\n      return super.canHaveLeadingDecorator() || this.isAbstractClass();\n    }\n\n    jsxParseOpeningElementAfterName(\n      node: N.JSXOpeningElement,\n    ): N.JSXOpeningElement {\n      // handles `<Component<<T>`\n      if (this.match(tt.lt) || this.match(tt.bitShiftL)) {\n        const typeArguments = this.tsTryParseAndCatch(() =>\n          this.tsParseTypeArgumentsInExpression(),\n        );\n        if (typeArguments) {\n          if (process.env.BABEL_8_BREAKING) {\n            node.typeArguments = typeArguments;\n          } else {\n            node.typeParameters = typeArguments;\n          }\n        }\n      }\n      return super.jsxParseOpeningElementAfterName(node);\n    }\n\n    getGetterSetterExpectedParamCount(\n      method: N.ObjectMethod | N.ClassMethod,\n    ): number {\n      const baseCount = super.getGetterSetterExpectedParamCount(method);\n      const params = this.getObjectOrClassMethodParams(method);\n      const firstParam = params[0];\n      const hasContextParam = firstParam && this.isThisParam(firstParam);\n\n      return hasContextParam ? baseCount + 1 : baseCount;\n    }\n\n    parseCatchClauseParam(): N.Pattern {\n      const param = super.parseCatchClauseParam();\n      const type = this.tsTryParseTypeAnnotation();\n\n      if (type) {\n        param.typeAnnotation = type;\n        this.resetEndLocation(param);\n      }\n\n      return param;\n    }\n\n    tsInAmbientContext<T>(cb: () => T): T {\n      const { isAmbientContext: oldIsAmbientContext, strict: oldStrict } =\n        this.state;\n      this.state.isAmbientContext = true;\n      this.state.strict = false;\n      try {\n        return cb();\n      } finally {\n        this.state.isAmbientContext = oldIsAmbientContext;\n        this.state.strict = oldStrict;\n      }\n    }\n\n    parseClass<T extends N.Class>(\n      node: Undone<T>,\n      isStatement: boolean,\n      optionalId?: boolean,\n    ): T {\n      const oldInAbstractClass = this.state.inAbstractClass;\n      this.state.inAbstractClass = !!(node as any).abstract;\n      try {\n        return super.parseClass(node, isStatement, optionalId);\n      } finally {\n        this.state.inAbstractClass = oldInAbstractClass;\n      }\n    }\n\n    tsParseAbstractDeclaration(\n      node: any,\n      decorators: N.Decorator[] | null,\n    ): N.ClassDeclaration | N.TsInterfaceDeclaration | undefined | null {\n      if (this.match(tt._class)) {\n        node.abstract = true;\n        return this.maybeTakeDecorators(\n          decorators,\n          this.parseClass<N.ClassDeclaration>(\n            node as N.ClassDeclaration,\n            /* isStatement */ true,\n            /* optionalId */ false,\n          ),\n        );\n      } else if (this.isContextual(tt._interface)) {\n        // for invalid abstract interface\n\n        // To avoid\n        //   abstract interface\n        //   Foo {}\n        if (!this.hasFollowingLineBreak()) {\n          node.abstract = true;\n          this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifier, node);\n          return this.tsParseInterfaceDeclaration(\n            node as N.TsInterfaceDeclaration,\n          );\n        }\n      } else {\n        this.unexpected(null, tt._class);\n      }\n    }\n\n    parseMethod<\n      T extends N.ObjectMethod | N.ClassMethod | N.ClassPrivateMethod,\n    >(\n      node: Undone<T>,\n      isGenerator: boolean,\n      isAsync: boolean,\n      isConstructor: boolean,\n      allowDirectSuper: boolean,\n      type: T[\"type\"],\n      inClassScope?: boolean,\n    ) {\n      const method = super.parseMethod<T>(\n        node,\n        isGenerator,\n        isAsync,\n        isConstructor,\n        allowDirectSuper,\n        type,\n        inClassScope,\n      );\n      // @ts-expect-error todo(flow->ts) property not defined for all types in union\n      if (method.abstract || method.type === \"TSAbstractMethodDefinition\") {\n        const hasEstreePlugin = this.hasPlugin(\"estree\");\n        const methodFn = hasEstreePlugin\n          ? // @ts-expect-error estree typings\n            method.value\n          : method;\n        if (methodFn.body) {\n          const { key } = method;\n          this.raise(TSErrors.AbstractMethodHasImplementation, method, {\n            methodName:\n              key.type === \"Identifier\" && !method.computed\n                ? key.name\n                : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]`,\n          });\n        }\n      }\n      return method;\n    }\n\n    tsParseTypeParameterName(): N.Identifier | string {\n      const typeName: N.Identifier = this.parseIdentifier();\n      return process.env.BABEL_8_BREAKING ? typeName : typeName.name;\n    }\n\n    shouldParseAsAmbientContext(): boolean {\n      return !!this.getPluginOption(\"typescript\", \"dts\");\n    }\n\n    parse() {\n      if (this.shouldParseAsAmbientContext()) {\n        this.state.isAmbientContext = true;\n      }\n      return super.parse();\n    }\n\n    getExpression() {\n      if (this.shouldParseAsAmbientContext()) {\n        this.state.isAmbientContext = true;\n      }\n      return super.getExpression();\n    }\n\n    parseExportSpecifier(\n      node: Undone<N.ExportSpecifier>,\n      isString: boolean,\n      isInTypeExport: boolean,\n      isMaybeTypeOnly: boolean,\n    ) {\n      if (!isString && isMaybeTypeOnly) {\n        this.parseTypeOnlyImportExportSpecifier(\n          node,\n          /* isImport */ false,\n          isInTypeExport,\n        );\n        return this.finishNode<N.ExportSpecifier>(node, \"ExportSpecifier\");\n      }\n      node.exportKind = \"value\";\n      return super.parseExportSpecifier(\n        node,\n        isString,\n        isInTypeExport,\n        isMaybeTypeOnly,\n      );\n    }\n\n    parseImportSpecifier(\n      specifier: Undone<N.ImportSpecifier>,\n      importedIsString: boolean,\n      isInTypeOnlyImport: boolean,\n      isMaybeTypeOnly: boolean,\n      // eslint-disable-next-line @typescript-eslint/no-unused-vars\n      bindingType: BindingFlag | undefined,\n    ): N.ImportSpecifier {\n      if (!importedIsString && isMaybeTypeOnly) {\n        this.parseTypeOnlyImportExportSpecifier(\n          specifier,\n          /* isImport */ true,\n          isInTypeOnlyImport,\n        );\n        return this.finishNode<N.ImportSpecifier>(specifier, \"ImportSpecifier\");\n      }\n      specifier.importKind = \"value\";\n      return super.parseImportSpecifier(\n        specifier,\n        importedIsString,\n        isInTypeOnlyImport,\n        isMaybeTypeOnly,\n        isInTypeOnlyImport\n          ? BindingFlag.TYPE_TS_TYPE_IMPORT\n          : BindingFlag.TYPE_TS_VALUE_IMPORT,\n      );\n    }\n\n    parseTypeOnlyImportExportSpecifier(\n      node: any,\n      isImport: boolean,\n      isInTypeOnlyImportExport: boolean,\n    ): void {\n      const leftOfAsKey = isImport ? \"imported\" : \"local\";\n      const rightOfAsKey = isImport ? \"local\" : \"exported\";\n\n      let leftOfAs = node[leftOfAsKey];\n      let rightOfAs;\n\n      let hasTypeSpecifier = false;\n      let canParseAsKeyword = true;\n\n      const loc = leftOfAs.loc.start;\n\n      // https://github.com/microsoft/TypeScript/blob/fc4f9d83d5939047aa6bb2a43965c6e9bbfbc35b/src/compiler/parser.ts#L7411-L7456\n      // import { type } from \"mod\";          - hasTypeSpecifier: false, leftOfAs: type\n      // import { type as } from \"mod\";       - hasTypeSpecifier: true,  leftOfAs: as\n      // import { type as as } from \"mod\";    - hasTypeSpecifier: false, leftOfAs: type, rightOfAs: as\n      // import { type as as as } from \"mod\"; - hasTypeSpecifier: true,  leftOfAs: as,   rightOfAs: as\n      if (this.isContextual(tt._as)) {\n        // { type as ...? }\n        const firstAs = this.parseIdentifier();\n        if (this.isContextual(tt._as)) {\n          // { type as as ...? }\n          const secondAs = this.parseIdentifier();\n          if (tokenIsKeywordOrIdentifier(this.state.type)) {\n            // { type as as something }\n            hasTypeSpecifier = true;\n            leftOfAs = firstAs;\n            rightOfAs = isImport\n              ? this.parseIdentifier()\n              : this.parseModuleExportName();\n            canParseAsKeyword = false;\n          } else {\n            // { type as as }\n            rightOfAs = secondAs;\n            canParseAsKeyword = false;\n          }\n        } else if (tokenIsKeywordOrIdentifier(this.state.type)) {\n          // { type as something }\n          canParseAsKeyword = false;\n          rightOfAs = isImport\n            ? this.parseIdentifier()\n            : this.parseModuleExportName();\n        } else {\n          // { type as }\n          hasTypeSpecifier = true;\n          leftOfAs = firstAs;\n        }\n      } else if (tokenIsKeywordOrIdentifier(this.state.type)) {\n        // { type something ...? }\n        hasTypeSpecifier = true;\n        if (isImport) {\n          leftOfAs = this.parseIdentifier(true);\n          if (!this.isContextual(tt._as)) {\n            this.checkReservedWord(\n              leftOfAs.name,\n              leftOfAs.loc.start,\n              true,\n              true,\n            );\n          }\n        } else {\n          leftOfAs = this.parseModuleExportName();\n        }\n      }\n      if (hasTypeSpecifier && isInTypeOnlyImportExport) {\n        this.raise(\n          isImport\n            ? TSErrors.TypeModifierIsUsedInTypeImports\n            : TSErrors.TypeModifierIsUsedInTypeExports,\n          loc,\n        );\n      }\n\n      node[leftOfAsKey] = leftOfAs;\n      node[rightOfAsKey] = rightOfAs;\n\n      const kindKey = isImport ? \"importKind\" : \"exportKind\";\n      node[kindKey] = hasTypeSpecifier ? \"type\" : \"value\";\n\n      if (canParseAsKeyword && this.eatContextual(tt._as)) {\n        node[rightOfAsKey] = isImport\n          ? this.parseIdentifier()\n          : this.parseModuleExportName();\n      }\n      if (!node[rightOfAsKey]) {\n        node[rightOfAsKey] = this.cloneIdentifier(node[leftOfAsKey]);\n      }\n      if (isImport) {\n        this.checkIdentifier(\n          node[rightOfAsKey],\n          hasTypeSpecifier\n            ? BindingFlag.TYPE_TS_TYPE_IMPORT\n            : BindingFlag.TYPE_TS_VALUE_IMPORT,\n        );\n      }\n    }\n\n    /**\n     * This hook is defined in the ESTree plugin.\n     * The TS-ESLint always define optional AST properties, here we provide the\n     * default value for such properties immediately after `finishNode` was invoked.\n     *\n     * @param node The AST node finished by finishNode\n     * @returns\n     */\n    fillOptionalPropertiesForTSESLint(node: N.Node): void {\n      switch (node.type) {\n        case \"ExpressionStatement\":\n          node.directive ??= undefined;\n          return;\n        case \"RestElement\":\n          node.value = undefined;\n        /* fallthrough */\n        case \"Identifier\":\n        case \"ArrayPattern\":\n        case \"AssignmentPattern\":\n        case \"ObjectPattern\":\n          node.decorators ??= [];\n          node.optional ??= false;\n          node.typeAnnotation ??= undefined;\n          return;\n        case \"TSParameterProperty\":\n          node.accessibility ??= undefined;\n          node.decorators ??= [];\n          node.override ??= false;\n          node.readonly ??= false;\n          node.static ??= false;\n          return;\n        case \"TSEmptyBodyFunctionExpression\":\n          node.body = null;\n        /* fallthrough */\n        case \"TSDeclareFunction\":\n        case \"FunctionDeclaration\":\n        case \"FunctionExpression\":\n        case \"ClassMethod\":\n        case \"ClassPrivateMethod\":\n          node.declare ??= false;\n          node.returnType ??= undefined;\n          node.typeParameters ??= undefined;\n          return;\n        case \"Property\":\n          node.optional ??= false;\n          return;\n        case \"TSMethodSignature\":\n        case \"TSPropertySignature\":\n          node.optional ??= false;\n        /* fallthrough */\n        case \"TSIndexSignature\":\n          node.accessibility ??= undefined;\n          node.readonly ??= false;\n          node.static ??= false;\n          return;\n        case \"TSAbstractPropertyDefinition\":\n        case \"PropertyDefinition\":\n        case \"TSAbstractAccessorProperty\":\n        case \"AccessorProperty\":\n          node.declare ??= false;\n          node.definite ??= false;\n          node.readonly ??= false;\n          node.typeAnnotation ??= undefined;\n        /* fallthrough */\n        case \"TSAbstractMethodDefinition\":\n        case \"MethodDefinition\":\n          node.accessibility ??= undefined;\n          node.decorators ??= [];\n          node.override ??= false;\n          node.optional ??= false;\n          return;\n        case \"ClassExpression\":\n          node.id ??= null;\n        /* fallthrough */\n        case \"ClassDeclaration\":\n          node.abstract ??= false;\n          node.declare ??= false;\n          node.decorators ??= [];\n          node.implements ??= [];\n          node.superTypeArguments ??= undefined;\n          node.typeParameters ??= undefined;\n          return;\n        case \"TSTypeAliasDeclaration\":\n        case \"VariableDeclaration\":\n          node.declare ??= false;\n          return;\n        case \"VariableDeclarator\":\n          node.definite ??= false;\n          return;\n        case \"TSEnumDeclaration\":\n          node.const ??= false;\n          node.declare ??= false;\n          return;\n        case \"TSEnumMember\":\n          node.computed ??= false;\n          return;\n        case \"TSImportType\":\n          node.qualifier ??= null;\n          node.options ??= null;\n          if (process.env.BABEL_8_BREAKING) {\n            node.typeArguments ??= null;\n          }\n          return;\n        case \"TSInterfaceDeclaration\":\n          node.declare ??= false;\n          node.extends ??= [];\n          return;\n        case \"TSModuleDeclaration\":\n          node.declare ??= false;\n          node.global ??= node.kind === \"global\";\n          return;\n        case \"TSTypeParameter\":\n          node.const ??= false;\n          node.in ??= false;\n          node.out ??= false;\n          return;\n      }\n    }\n  };\n\nfunction isPossiblyLiteralEnum(expression: N.Expression): boolean {\n  if (expression.type !== \"MemberExpression\") return false;\n\n  const { computed, property } = expression;\n\n  if (\n    computed &&\n    property.type !== \"StringLiteral\" &&\n    (property.type !== \"TemplateLiteral\" || property.expressions.length > 0)\n  ) {\n    return false;\n  }\n\n  return isUncomputedMemberExpressionChain(expression.object);\n}\n\n// If a const declaration has no type annotation and is initialized to\n// a string literal, numeric literal, or enum reference, then it is\n// allowed. In an ideal world, we'd check whether init was *actually* an\n// enum reference, but we allow anything that \"could be\" a literal enum\n// in `isPossiblyLiteralEnum` since we don't have all the information\n// that the typescript compiler has.\nfunction isValidAmbientConstInitializer(\n  expression: N.Expression,\n  estree: boolean,\n): boolean {\n  const { type } = expression;\n  if (expression.extra?.parenthesized) {\n    return false;\n  }\n  if (estree) {\n    if (type === \"Literal\") {\n      const { value } = expression;\n      if (typeof value === \"string\" || typeof value === \"boolean\") {\n        return true;\n      }\n    }\n  } else {\n    if (type === \"StringLiteral\" || type === \"BooleanLiteral\") {\n      return true;\n    }\n  }\n  if (isNumber(expression, estree) || isNegativeNumber(expression, estree)) {\n    return true;\n  }\n  if (type === \"TemplateLiteral\" && expression.expressions.length === 0) {\n    return true;\n  }\n  if (isPossiblyLiteralEnum(expression)) {\n    return true;\n  }\n  return false;\n}\n\nfunction isNumber(expression: N.Expression, estree: boolean): boolean {\n  if (estree) {\n    return (\n      expression.type === \"Literal\" &&\n      (typeof expression.value === \"number\" || \"bigint\" in expression)\n    );\n  }\n  return (\n    expression.type === \"NumericLiteral\" || expression.type === \"BigIntLiteral\"\n  );\n}\n\nfunction isNegativeNumber(expression: N.Expression, estree: boolean): boolean {\n  if (expression.type === \"UnaryExpression\") {\n    const { operator, argument } = expression;\n    if (operator === \"-\" && isNumber(argument, estree)) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction isUncomputedMemberExpressionChain(expression: N.Expression): boolean {\n  if (expression.type === \"Identifier\") return true;\n  if (expression.type !== \"MemberExpression\" || expression.computed) {\n    return false;\n  }\n\n  return isUncomputedMemberExpressionChain(expression.object);\n}\n","import * as charCodes from \"charcodes\";\n\nimport { tokenLabelName, tt } from \"../tokenizer/types.ts\";\nimport type Parser from \"../parser/index.ts\";\nimport type * as N from \"../types.ts\";\nimport { ParseErrorEnum } from \"../parse-error.ts\";\nimport type { Undone } from \"../parser/node.ts\";\nimport type { ExpressionErrors } from \"../parser/util.ts\";\nimport type { BindingFlag } from \"../util/scopeflags.ts\";\nimport type { Position } from \"../util/location.ts\";\n\ntype PossiblePlaceholders = {\n  Identifier: N.Identifier;\n  StringLiteral: N.StringLiteral;\n  Expression: N.Expression;\n  Statement: N.Statement;\n  Declaration: N.Declaration;\n  BlockStatement: N.BlockStatement;\n  ClassBody: N.ClassBody;\n  Pattern: N.Pattern;\n};\nexport type PlaceholderTypes = keyof PossiblePlaceholders;\n\ntype NodeOf<T extends keyof PossiblePlaceholders> = PossiblePlaceholders[T];\n// todo: when there  is proper union type for Node\n// type NodeOf<T extends PlaceholderTypes> = Extract<N.Node, { type: T }>;\n\n// todo: Placeholder<T> breaks everything, because its type is incompatible with\n// the substituted nodes.\ntype MaybePlaceholder<T extends PlaceholderTypes> = NodeOf<T>; // | Placeholder<T>\n\n/* eslint sort-keys: \"error\" */\nconst PlaceholderErrors = ParseErrorEnum`placeholders`({\n  ClassNameIsRequired: \"A class name is required.\",\n  UnexpectedSpace: \"Unexpected space in placeholder.\",\n});\n\nexport default (superClass: typeof Parser) =>\n  class PlaceholdersParserMixin extends superClass implements Parser {\n    parsePlaceholder<T extends PlaceholderTypes>(\n      expectedNode: T,\n    ): /*?N.Placeholder<T>*/ MaybePlaceholder<T> | undefined {\n      if (this.match(tt.placeholder)) {\n        const node = this.startNode<N.Placeholder<T>>();\n        this.next();\n        this.assertNoSpace();\n\n        // We can't use this.parseIdentifier because\n        // we don't want nested placeholders.\n        node.name = super.parseIdentifier(/* liberal */ true);\n\n        this.assertNoSpace();\n        this.expect(tt.placeholder);\n        return this.finishPlaceholder(node, expectedNode);\n      }\n    }\n\n    finishPlaceholder<T extends PlaceholderTypes>(\n      node: Undone<N.Placeholder> | Undone<NodeOf<PlaceholderTypes>>,\n      expectedNode: T,\n    ): /*N.Placeholder<T>*/ MaybePlaceholder<T> {\n      let placeholder = node as unknown as N.Placeholder<T>;\n\n      if (!placeholder.expectedNode || !placeholder.type) {\n        placeholder = this.finishNode(\n          placeholder,\n          \"Placeholder\",\n        ) as unknown as N.Placeholder<T>;\n      }\n\n      placeholder.expectedNode = expectedNode;\n      return placeholder as unknown as MaybePlaceholder<T>;\n    }\n\n    /* ============================================================ *\n     * tokenizer/index.ts                                           *\n     * ============================================================ */\n\n    getTokenFromCode(code: number) {\n      if (\n        code === charCodes.percentSign &&\n        this.input.charCodeAt(this.state.pos + 1) === charCodes.percentSign\n      ) {\n        this.finishOp(tt.placeholder, 2);\n      } else {\n        super.getTokenFromCode(code);\n      }\n    }\n\n    /* ============================================================ *\n     * parser/expression.ts                                         *\n     * ============================================================ */\n\n    parseExprAtom(\n      refExpressionErrors?: ExpressionErrors | null,\n    ): MaybePlaceholder<\"Expression\"> {\n      return (\n        this.parsePlaceholder(\"Expression\") ||\n        super.parseExprAtom(refExpressionErrors)\n      );\n    }\n\n    parseIdentifier(liberal?: boolean): MaybePlaceholder<\"Identifier\"> {\n      // NOTE: This function only handles identifiers outside of\n      // expressions and binding patterns, since they are already\n      // handled by the parseExprAtom and parseBindingAtom functions.\n      // This is needed, for example, to parse \"class %%NAME%% {}\".\n      return (\n        this.parsePlaceholder(\"Identifier\") || super.parseIdentifier(liberal)\n      );\n    }\n\n    checkReservedWord(\n      word: string,\n      startLoc: Position,\n      checkKeywords: boolean,\n      isBinding: boolean,\n    ) {\n      // Sometimes we call #checkReservedWord(node.name), expecting\n      // that node is an Identifier. If it is a Placeholder, name\n      // will be undefined.\n      if (word !== undefined) {\n        super.checkReservedWord(word, startLoc, checkKeywords, isBinding);\n      }\n    }\n\n    /* ============================================================ *\n     * parser/node.ts                                               *\n     * ============================================================ */\n\n    cloneIdentifier<T extends N.Identifier | N.Placeholder>(node: T): T {\n      const cloned = super.cloneIdentifier(node);\n      if (cloned.type === \"Placeholder\") {\n        cloned.expectedNode = (node as N.Placeholder).expectedNode;\n      }\n      return cloned;\n    }\n\n    cloneStringLiteral<\n      T extends N.EstreeLiteral | N.StringLiteral | N.Placeholder,\n    >(node: T): T {\n      if (node.type === \"Placeholder\") {\n        return this.cloneIdentifier(node) as T;\n      }\n      return super.cloneStringLiteral(node);\n    }\n\n    /* ============================================================ *\n     * parser/lval.ts                                               *\n     * ============================================================ */\n\n    parseBindingAtom(): MaybePlaceholder<\"Pattern\"> {\n      return this.parsePlaceholder(\"Pattern\") || super.parseBindingAtom();\n    }\n\n    isValidLVal(type: string, isParenthesized: boolean, binding: BindingFlag) {\n      return (\n        type === \"Placeholder\" ||\n        super.isValidLVal(type, isParenthesized, binding)\n      );\n    }\n\n    toAssignable(node: N.Node, isLHS: boolean): void {\n      if (\n        node &&\n        node.type === \"Placeholder\" &&\n        node.expectedNode === \"Expression\"\n      ) {\n        node.expectedNode = \"Pattern\";\n      } else {\n        super.toAssignable(node, isLHS);\n      }\n    }\n\n    /* ============================================================ *\n     * parser/statement.ts                                          *\n     * ============================================================ */\n\n    chStartsBindingIdentifier(ch: number, pos: number): boolean {\n      if (super.chStartsBindingIdentifier(ch, pos)) {\n        return true;\n      }\n\n      // Accept \"let %%\" as the start of \"let %%placeholder%%\", as though the\n      // placeholder were an identifier.\n      const next = this.nextTokenStart();\n      if (\n        this.input.charCodeAt(next) === charCodes.percentSign &&\n        this.input.charCodeAt(next + 1) === charCodes.percentSign\n      ) {\n        return true;\n      }\n\n      return false;\n    }\n\n    verifyBreakContinue(\n      node: N.BreakStatement | N.ContinueStatement,\n      isBreak: boolean,\n    ) {\n      // @ts-expect-error: node.label could be Placeholder\n      if (node.label && node.label.type === \"Placeholder\") return;\n      super.verifyBreakContinue(node, isBreak);\n    }\n\n    // @ts-expect-error Plugin will override parser interface\n    parseExpressionStatement(\n      node: MaybePlaceholder<\"Statement\">,\n      expr: MaybePlaceholder<\"Expression\">,\n    ): MaybePlaceholder<\"Statement\"> {\n      // @ts-expect-error placeholder typings\n      if (expr.type !== \"Placeholder\" || expr.extra?.parenthesized) {\n        // @ts-expect-error placeholder typings\n        return super.parseExpressionStatement(node, expr);\n      }\n\n      if (this.match(tt.colon)) {\n        // @ts-expect-error placeholder typings\n        const stmt: N.LabeledStatement = node;\n        stmt.label = this.finishPlaceholder(expr, \"Identifier\");\n        this.next();\n        stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration();\n        return this.finishNode(stmt, \"LabeledStatement\");\n      }\n\n      this.semicolon();\n      const stmtPlaceholder = node as unknown as N.Placeholder<\"Statement\">;\n      stmtPlaceholder.name = (expr as N.Placeholder).name;\n      return this.finishPlaceholder(stmtPlaceholder, \"Statement\");\n    }\n\n    parseBlock(\n      allowDirectives?: boolean,\n      createNewLexicalScope?: boolean,\n      afterBlockParse?: (hasStrictModeDirective: boolean) => void,\n    ): MaybePlaceholder<\"BlockStatement\"> {\n      return (\n        this.parsePlaceholder(\"BlockStatement\") ||\n        super.parseBlock(\n          allowDirectives,\n          createNewLexicalScope,\n          afterBlockParse,\n        )\n      );\n    }\n\n    parseFunctionId(\n      requireId?: boolean,\n    ): MaybePlaceholder<\"Identifier\"> | undefined | null {\n      return (\n        this.parsePlaceholder(\"Identifier\") || super.parseFunctionId(requireId)\n      );\n    }\n    // @ts-expect-error Plugin will override parser interface\n    parseClass<T extends N.Class>(\n      node: T,\n      isStatement: /* T === ClassDeclaration */ boolean,\n      optionalId?: boolean,\n    ): T {\n      const type = isStatement ? \"ClassDeclaration\" : \"ClassExpression\";\n\n      this.next();\n      const oldStrict = this.state.strict;\n\n      const placeholder = this.parsePlaceholder(\"Identifier\");\n      if (placeholder) {\n        if (\n          this.match(tt._extends) ||\n          this.match(tt.placeholder) ||\n          this.match(tt.braceL)\n        ) {\n          node.id = placeholder;\n        } else if (optionalId || !isStatement) {\n          node.id = null;\n          node.body = this.finishPlaceholder(placeholder, \"ClassBody\");\n          return this.finishNode(node, type);\n        } else {\n          throw this.raise(\n            PlaceholderErrors.ClassNameIsRequired,\n            this.state.startLoc,\n          );\n        }\n      } else {\n        this.parseClassId(node, isStatement, optionalId);\n      }\n\n      super.parseClassSuper(node);\n      node.body =\n        this.parsePlaceholder(\"ClassBody\") ||\n        super.parseClassBody(!!node.superClass, oldStrict);\n      return this.finishNode(node, type);\n    }\n\n    parseExport(\n      node: Undone<\n        | N.ExportDefaultDeclaration\n        | N.ExportAllDeclaration\n        | N.ExportNamedDeclaration\n      >,\n      decorators: N.Decorator[] | null,\n    ): N.AnyExport {\n      const placeholder = this.parsePlaceholder(\"Identifier\");\n      if (!placeholder) return super.parseExport(node, decorators);\n\n      const node2 = node as Undone<N.ExportNamedDeclaration>;\n\n      if (!this.isContextual(tt._from) && !this.match(tt.comma)) {\n        // export %%DECL%%;\n        node2.specifiers = [];\n        node2.source = null;\n        node2.declaration = this.finishPlaceholder(placeholder, \"Declaration\");\n        return this.finishNode(node2, \"ExportNamedDeclaration\");\n      }\n\n      // export %%NAME%% from \"foo\";\n      this.expectPlugin(\"exportDefaultFrom\");\n      const specifier = this.startNode<N.ExportDefaultSpecifier>();\n      specifier.exported = placeholder;\n      node2.specifiers = [this.finishNode(specifier, \"ExportDefaultSpecifier\")];\n\n      return super.parseExport(node2, decorators);\n    }\n\n    isExportDefaultSpecifier(): boolean {\n      if (this.match(tt._default)) {\n        const next = this.nextTokenStart();\n        if (this.isUnparsedContextual(next, \"from\")) {\n          if (\n            this.input.startsWith(\n              tokenLabelName(tt.placeholder),\n              this.nextTokenStartSince(next + 4),\n            )\n          ) {\n            return true;\n          }\n        }\n      }\n      return super.isExportDefaultSpecifier();\n    }\n\n    maybeParseExportDefaultSpecifier(\n      node: Undone<\n        | N.ExportDefaultDeclaration\n        | N.ExportAllDeclaration\n        | N.ExportNamedDeclaration\n      >,\n      maybeDefaultIdentifier: N.Identifier | null,\n    ): node is Undone<N.ExportNamedDeclaration> {\n      if ((node as N.ExportNamedDeclaration).specifiers?.length) {\n        // \"export %%NAME%%\" has already been parsed by #parseExport.\n        return true;\n      }\n      return super.maybeParseExportDefaultSpecifier(\n        node,\n        maybeDefaultIdentifier,\n      );\n    }\n\n    checkExport(node: N.ExportNamedDeclaration): void {\n      const { specifiers } = node;\n      if (specifiers?.length) {\n        node.specifiers = specifiers.filter(\n          // @ts-expect-error placeholder typings\n          node => node.exported.type === \"Placeholder\",\n        );\n      }\n      super.checkExport(node);\n      node.specifiers = specifiers;\n    }\n\n    parseImport(\n      node: Undone<N.ImportDeclaration>,\n    ): N.ImportDeclaration | N.TsImportEqualsDeclaration {\n      const placeholder = this.parsePlaceholder(\"Identifier\");\n      if (!placeholder) return super.parseImport(node);\n\n      node.specifiers = [];\n\n      if (!this.isContextual(tt._from) && !this.match(tt.comma)) {\n        // import %%STRING%%;\n        node.source = this.finishPlaceholder(placeholder, \"StringLiteral\");\n        this.semicolon();\n        return this.finishNode(node, \"ImportDeclaration\");\n      }\n\n      // import %%DEFAULT%% ...\n      const specifier =\n        this.startNodeAtNode<N.ImportDefaultSpecifier>(placeholder);\n      specifier.local = placeholder;\n      node.specifiers.push(\n        this.finishNode(specifier, \"ImportDefaultSpecifier\"),\n      );\n\n      if (this.eat(tt.comma)) {\n        // import %%DEFAULT%%, * as ...\n        const hasStarImport = this.maybeParseStarImportSpecifier(node);\n\n        // import %%DEFAULT%%, { ...\n        if (!hasStarImport) this.parseNamedImportSpecifiers(node);\n      }\n\n      this.expectContextual(tt._from);\n      node.source = this.parseImportSource();\n      this.semicolon();\n      return this.finishNode(node, \"ImportDeclaration\");\n    }\n\n    parseImportSource(): MaybePlaceholder<\"StringLiteral\"> {\n      // import ... from %%STRING%%;\n\n      return (\n        this.parsePlaceholder(\"StringLiteral\") || super.parseImportSource()\n      );\n    }\n\n    // Throws if the current token and the prev one are separated by a space.\n    assertNoSpace(): void {\n      if (\n        this.state.start >\n        this.offsetToSourcePos(this.state.lastTokEndLoc.index)\n      ) {\n        this.raise(PlaceholderErrors.UnexpectedSpace, this.state.lastTokEndLoc);\n      }\n    }\n  };\n","import type Parser from \"../parser/index.ts\";\nimport { tokenIsIdentifier, tt } from \"../tokenizer/types.ts\";\nimport type * as N from \"../types.ts\";\nimport type { ExpressionErrors } from \"../parser/util.ts\";\n\nexport default (superClass: typeof Parser) =>\n  class V8IntrinsicMixin extends superClass implements Parser {\n    parseV8Intrinsic(): N.Expression {\n      if (this.match(tt.modulo)) {\n        const v8IntrinsicStartLoc = this.state.startLoc;\n        // let the `loc` of Identifier starts from `%`\n        const node = this.startNode<N.Identifier>();\n        this.next(); // eat '%'\n        if (tokenIsIdentifier(this.state.type)) {\n          const name = this.parseIdentifierName();\n          const identifier = this.createIdentifier(node, name);\n          this.castNodeTo(identifier, \"V8IntrinsicIdentifier\");\n          if (this.match(tt.parenL)) {\n            return identifier;\n          }\n        }\n        this.unexpected(v8IntrinsicStartLoc);\n      }\n    }\n\n    /* ============================================================ *\n     * parser/expression.js                                         *\n     * ============================================================ */\n\n    parseExprAtom(refExpressionErrors?: ExpressionErrors | null): N.Expression {\n      return (\n        this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors)\n      );\n    }\n  };\n","import type Parser from \"./parser/index.ts\";\nimport type { PluginConfig } from \"./typings.ts\";\n\nexport type Plugin = PluginConfig;\n\nexport type MixinPlugin = (\n  superClass: new (...args: any) => Parser,\n) => new (...args: any) => Parser;\n\nconst PIPELINE_PROPOSALS = process.env.BABEL_8_BREAKING\n  ? [\"fsharp\", \"hack\"]\n  : [\"minimal\", \"fsharp\", \"hack\", \"smart\"];\nconst TOPIC_TOKENS = [\"^^\", \"@@\", \"^\", \"%\", \"#\"];\n\nexport function validatePlugins(pluginsMap: Map<string, any>) {\n  if (pluginsMap.has(\"decorators\")) {\n    if (pluginsMap.has(\"decorators-legacy\")) {\n      throw new Error(\n        \"Cannot use the decorators and decorators-legacy plugin together\",\n      );\n    }\n\n    const decoratorsBeforeExport =\n      pluginsMap.get(\"decorators\").decoratorsBeforeExport;\n    if (\n      decoratorsBeforeExport != null &&\n      typeof decoratorsBeforeExport !== \"boolean\"\n    ) {\n      throw new Error(\n        \"'decoratorsBeforeExport' must be a boolean, if specified.\",\n      );\n    }\n\n    const allowCallParenthesized =\n      pluginsMap.get(\"decorators\").allowCallParenthesized;\n    if (\n      allowCallParenthesized != null &&\n      typeof allowCallParenthesized !== \"boolean\"\n    ) {\n      throw new Error(\"'allowCallParenthesized' must be a boolean.\");\n    }\n  }\n\n  if (pluginsMap.has(\"flow\") && pluginsMap.has(\"typescript\")) {\n    throw new Error(\"Cannot combine flow and typescript plugins.\");\n  }\n\n  if (pluginsMap.has(\"placeholders\") && pluginsMap.has(\"v8intrinsic\")) {\n    throw new Error(\"Cannot combine placeholders and v8intrinsic plugins.\");\n  }\n\n  if (pluginsMap.has(\"pipelineOperator\")) {\n    const proposal = pluginsMap.get(\"pipelineOperator\").proposal;\n\n    if (!PIPELINE_PROPOSALS.includes(proposal)) {\n      const proposalList = PIPELINE_PROPOSALS.map(p => `\"${p}\"`).join(\", \");\n      throw new Error(\n        `\"pipelineOperator\" requires \"proposal\" option whose value must be one of: ${proposalList}.`,\n      );\n    }\n\n    if (proposal === \"hack\") {\n      if (pluginsMap.has(\"placeholders\")) {\n        throw new Error(\n          \"Cannot combine placeholders plugin and Hack-style pipes.\",\n        );\n      }\n\n      if (pluginsMap.has(\"v8intrinsic\")) {\n        throw new Error(\n          \"Cannot combine v8intrinsic plugin and Hack-style pipes.\",\n        );\n      }\n\n      const topicToken = pluginsMap.get(\"pipelineOperator\").topicToken;\n\n      if (!TOPIC_TOKENS.includes(topicToken)) {\n        const tokenList = TOPIC_TOKENS.map(t => `\"${t}\"`).join(\", \");\n\n        throw new Error(\n          `\"pipelineOperator\" in \"proposal\": \"hack\" mode also requires a \"topicToken\" option whose value must be one of: ${tokenList}.`,\n        );\n      }\n\n      if (!process.env.BABEL_8_BREAKING) {\n        if (\n          topicToken === \"#\" &&\n          pluginsMap.get(\"recordAndTuple\")?.syntaxType === \"hash\"\n        ) {\n          throw new Error(\n            `Plugin conflict between \\`[\"pipelineOperator\", { proposal: \"hack\", topicToken: \"#\" }]\\` and \\`${JSON.stringify([\"recordAndTuple\", pluginsMap.get(\"recordAndTuple\")])}\\`.`,\n          );\n        }\n      }\n    } else if (\n      !process.env.BABEL_8_BREAKING &&\n      proposal === \"smart\" &&\n      pluginsMap.get(\"recordAndTuple\")?.syntaxType === \"hash\"\n    ) {\n      throw new Error(\n        `Plugin conflict between \\`[\"pipelineOperator\", { proposal: \"smart\" }]\\` and \\`${JSON.stringify([\"recordAndTuple\", pluginsMap.get(\"recordAndTuple\")])}\\`.`,\n      );\n    }\n  }\n\n  if (pluginsMap.has(\"moduleAttributes\")) {\n    if (process.env.BABEL_8_BREAKING) {\n      throw new Error(\n        \"`moduleAttributes` has been removed in Babel 8, please migrate to import attributes instead.\",\n      );\n    } else {\n      if (\n        pluginsMap.has(\"deprecatedImportAssert\") ||\n        pluginsMap.has(\"importAssertions\")\n      ) {\n        throw new Error(\n          \"Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.\",\n        );\n      }\n      const moduleAttributesVersionPluginOption =\n        pluginsMap.get(\"moduleAttributes\").version;\n      if (moduleAttributesVersionPluginOption !== \"may-2020\") {\n        throw new Error(\n          \"The 'moduleAttributes' plugin requires a 'version' option,\" +\n            \" representing the last proposal update. Currently, the\" +\n            \" only supported value is 'may-2020'.\",\n        );\n      }\n    }\n  }\n  if (pluginsMap.has(\"importAssertions\")) {\n    if (process.env.BABEL_8_BREAKING) {\n      throw new Error(\n        \"`importAssertions` has been removed in Babel 8, please use import attributes instead.\" +\n          \" To use the non-standard `assert` syntax you can enable the `deprecatedImportAssert` parser plugin.\",\n      );\n    } else if (pluginsMap.has(\"deprecatedImportAssert\")) {\n      throw new Error(\n        \"Cannot combine importAssertions and deprecatedImportAssert plugins.\",\n      );\n    }\n  }\n  if (\n    !pluginsMap.has(\"deprecatedImportAssert\") &&\n    pluginsMap.has(\"importAttributes\") &&\n    pluginsMap.get(\"importAttributes\").deprecatedAssertSyntax\n  ) {\n    if (process.env.BABEL_8_BREAKING) {\n      throw new Error(\n        \"The 'importAttributes' plugin has been removed in Babel 8. If you need to enable support \" +\n          \"for the deprecated `assert` syntax, you can enable the `deprecatedImportAssert` parser plugin.\",\n      );\n    } else {\n      pluginsMap.set(\"deprecatedImportAssert\", {});\n    }\n  }\n\n  if (pluginsMap.has(\"recordAndTuple\")) {\n    if (process.env.BABEL_8_BREAKING) {\n      throw new Error(\n        \"The 'recordAndTuple' plugin has been removed in Babel 8. Please remove it from your configuration.\",\n      );\n    } else {\n      const syntaxType = pluginsMap.get(\"recordAndTuple\").syntaxType;\n      if (syntaxType != null) {\n        const RECORD_AND_TUPLE_SYNTAX_TYPES = [\"hash\", \"bar\"];\n        if (!RECORD_AND_TUPLE_SYNTAX_TYPES.includes(syntaxType)) {\n          throw new Error(\n            \"The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: \" +\n              RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(\", \"),\n          );\n        }\n      }\n    }\n  }\n\n  if (\n    pluginsMap.has(\"asyncDoExpressions\") &&\n    !pluginsMap.has(\"doExpressions\")\n  ) {\n    const error = new Error(\n      \"'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.\",\n    );\n    // @ts-expect-error so @babel/core can provide better error message\n    error.missingPlugins = \"doExpressions\";\n    throw error;\n  }\n\n  if (\n    pluginsMap.has(\"optionalChainingAssign\") &&\n    pluginsMap.get(\"optionalChainingAssign\").version !== \"2023-07\"\n  ) {\n    throw new Error(\n      \"The 'optionalChainingAssign' plugin requires a 'version' option,\" +\n        \" representing the last proposal update. Currently, the\" +\n        \" only supported value is '2023-07'.\",\n    );\n  }\n\n  if (\n    pluginsMap.has(\"discardBinding\") &&\n    pluginsMap.get(\"discardBinding\").syntaxType !== \"void\"\n  ) {\n    throw new Error(\n      \"The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'.\",\n    );\n  }\n\n  if (process.env.BABEL_8_BREAKING) {\n    if (pluginsMap.has(\"decimal\")) {\n      throw new Error(\n        \"The 'decimal' plugin has been removed in Babel 8. Please remove it from your configuration.\",\n      );\n    }\n    if (pluginsMap.has(\"importReflection\")) {\n      throw new Error(\n        \"The 'importReflection' plugin has been removed in Babel 8. Use 'sourcePhaseImports' instead, and \" +\n          \"replace 'import module' with 'import source' in your code.\",\n      );\n    }\n  }\n}\n\n// These plugins are defined using a mixin which extends the parser class.\n\nimport estree from \"./plugins/estree.ts\";\nimport flow from \"./plugins/flow/index.ts\";\nimport jsx from \"./plugins/jsx/index.ts\";\nimport typescript from \"./plugins/typescript/index.ts\";\nimport placeholders from \"./plugins/placeholders.ts\";\nimport v8intrinsic from \"./plugins/v8intrinsic.ts\";\n\n// NOTE: order is important. estree must come first; placeholders must come last.\nexport const mixinPlugins = {\n  estree,\n  jsx,\n  flow,\n  typescript,\n  v8intrinsic,\n  placeholders,\n};\n\nexport const mixinPluginNames = Object.keys(mixinPlugins) as ReadonlyArray<\n  \"estree\" | \"jsx\" | \"flow\" | \"typescript\" | \"v8intrinsic\" | \"placeholders\"\n>;\n","// A recursive descent parser operates by defining functions for all\n// syntactic elements, and recursively calling those, each function\n// advancing the input stream and returning an AST node. Precedence\n// of constructs (for example, the fact that `!x[1]` means `!(x[1])`\n// instead of `(!x)[1]` is handled by the fact that the parser\n// function that parses unary prefix operators is called first, and\n// in turn calls the function that parses `[]` subscripts — that\n// way, it'll receive the node for `x[1]` already parsed, and wraps\n// *that* in the unary operator node.\n//\n// Acorn uses an [operator precedence parser][opp] to handle binary\n// operator precedence, because it is much more compact than using\n// the technique outlined above, which uses different, nesting\n// functions to specify precedence, for all of the ten binary\n// precedence levels that JavaScript defines.\n//\n// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser\n\nimport {\n  tokenCanStartExpression,\n  tokenIsAssignment,\n  tokenIsIdentifier,\n  tokenIsKeywordOrIdentifier,\n  tokenIsOperator,\n  tokenIsPostfix,\n  tokenIsPrefix,\n  tokenIsRightAssociative,\n  tokenIsTemplate,\n  tokenKeywordOrIdentifierIsKeyword,\n  tokenLabelName,\n  tokenOperatorPrecedence,\n  tt,\n  type TokenType,\n} from \"../tokenizer/types.ts\";\nimport type * as N from \"../types.ts\";\nimport LValParser from \"./lval.ts\";\nimport {\n  isKeyword,\n  isReservedWord,\n  isStrictReservedWord,\n  isStrictBindReservedWord,\n  isIdentifierStart,\n  canBeReservedWord,\n} from \"../util/identifier.ts\";\nimport {\n  type Position,\n  createPositionWithColumnOffset,\n} from \"../util/location.ts\";\nimport * as charCodes from \"charcodes\";\nimport { ScopeFlag, BindingFlag } from \"../util/scopeflags.ts\";\nimport { ExpressionErrors } from \"./util.ts\";\nimport { ParamKind, functionFlags } from \"../util/production-parameter.ts\";\nimport {\n  newArrowHeadScope,\n  newAsyncArrowScope,\n  newExpressionScope,\n} from \"../util/expression-scope.ts\";\nimport { Errors } from \"../parse-error.ts\";\nimport {\n  UnparenthesizedPipeBodyDescriptions,\n  type UnparenthesizedPipeBodyTypes,\n} from \"../parse-error/pipeline-operator-errors.ts\";\nimport { setInnerComments } from \"./comments.ts\";\nimport type { Undone } from \"./node.ts\";\nimport type Parser from \"./index.ts\";\n\nimport { OptionFlags, type SourceType } from \"../options.ts\";\n\nexport default abstract class ExpressionParser extends LValParser {\n  // Forward-declaration: defined in statement.js\n  abstract parseBlock(\n    allowDirectives?: boolean,\n    createNewLexicalScope?: boolean,\n    afterBlockParse?: (hasStrictModeDirective: boolean) => void,\n  ): N.BlockStatement;\n  abstract parseClass(\n    node: N.Class,\n    isStatement: boolean,\n    optionalId?: boolean,\n  ): N.Class;\n  abstract parseDecorators(allowExport?: boolean): void;\n  abstract parseFunction<T extends N.NormalFunction>(\n    node: T,\n    statement?: number,\n    allowExpressionBody?: boolean,\n    isAsync?: boolean,\n  ): T;\n  abstract parseFunctionParams(node: N.Function, isConstructor?: boolean): void;\n  abstract parseBlockOrModuleBlockBody(\n    body: N.Statement[],\n    directives: N.Directive[] | null | undefined,\n    topLevel: boolean,\n    end: TokenType,\n    afterBlockParse?: (hasStrictModeDirective: boolean) => void,\n  ): void;\n  abstract parseProgram(\n    program: N.Program,\n    end: TokenType,\n    sourceType?: SourceType,\n  ): N.Program;\n\n  // For object literal, check if property __proto__ has been used more than once.\n  // If the expression is a destructuring assignment, then __proto__ may appear\n  // multiple times. Otherwise, __proto__ is a duplicated key.\n\n  // For record expression, check if property __proto__ exists\n\n  checkProto(\n    prop: N.ObjectMember | N.SpreadElement,\n    isRecord: boolean | undefined | null,\n    sawProto: boolean,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): boolean {\n    if (\n      prop.type === \"SpreadElement\" ||\n      this.isObjectMethod(prop) ||\n      prop.computed ||\n      prop.shorthand\n    ) {\n      return sawProto;\n    }\n\n    const key = prop.key as\n      | N.Identifier\n      | N.StringLiteral\n      | N.NumericLiteral\n      | N.BigIntLiteral;\n    // It is either an Identifier or a String/NumericLiteral\n    const name = key.type === \"Identifier\" ? key.name : key.value;\n\n    if (name === \"__proto__\") {\n      if (isRecord) {\n        this.raise(Errors.RecordNoProto, key);\n        return true;\n      }\n      if (sawProto) {\n        if (refExpressionErrors) {\n          // Store the first redefinition's position, otherwise ignore because\n          // we are parsing ambiguous pattern\n          if (refExpressionErrors.doubleProtoLoc === null) {\n            refExpressionErrors.doubleProtoLoc = key.loc.start;\n          }\n        } else {\n          this.raise(Errors.DuplicateProto, key);\n        }\n      }\n\n      return true;\n    }\n\n    return sawProto;\n  }\n\n  shouldExitDescending(\n    expr: N.Expression | N.PrivateName,\n    potentialArrowAt: number,\n  ): expr is N.ArrowFunctionExpression {\n    return (\n      expr.type === \"ArrowFunctionExpression\" &&\n      this.offsetToSourcePos(expr.start) === potentialArrowAt\n    );\n  }\n\n  // Convenience method to parse an Expression only\n  getExpression(this: Parser): N.Expression & N.ParserOutput {\n    this.enterInitialScopes();\n    this.nextToken();\n    if (this.match(tt.eof)) {\n      throw this.raise(Errors.ParseExpressionEmptyInput, this.state.startLoc);\n    }\n    const expr = this.parseExpression() as N.Expression & N.ParserOutput;\n    if (!this.match(tt.eof)) {\n      throw this.raise(Errors.ParseExpressionExpectsEOF, this.state.startLoc, {\n        unexpected: this.input.codePointAt(this.state.start),\n      });\n    }\n    // Unlike parseTopLevel, we need to drain remaining commentStacks\n    // because the top level node is _not_ Program.\n    this.finalizeRemainingComments();\n    expr.comments = this.comments;\n    expr.errors = this.state.errors;\n    if (this.optionFlags & OptionFlags.Tokens) {\n      expr.tokens = this.tokens;\n    }\n    return expr;\n  }\n\n  // ### Expression parsing\n\n  // These nest, from the most general expression type at the top to\n  // 'atomic', nondivisible expression types at the bottom. Most of\n  // the functions will simply let the function (s) below them parse,\n  // and, *if* the syntactic construct they handle is present, wrap\n  // the AST node that the inner parser gave them in another node.\n\n  // Parse a full expression.\n  // - `disallowIn`\n  //   is used to forbid the `in` operator (in for loops initialization expressions)\n  //   When `disallowIn` is true, the production parameter [In] is not present.\n\n  // - `refExpressionErrors `\n  //   provides reference for storing '=' operator inside shorthand\n  //   property assignment in contexts where both object expression\n  //   and object pattern might appear (so it's possible to raise\n  //   delayed syntax error at correct position).\n\n  parseExpression(\n    this: Parser,\n    disallowIn?: boolean,\n    refExpressionErrors?: ExpressionErrors,\n  ): N.Expression {\n    if (disallowIn) {\n      return this.disallowInAnd(() =>\n        this.parseExpressionBase(refExpressionErrors),\n      );\n    }\n    return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));\n  }\n\n  // https://tc39.es/ecma262/#prod-Expression\n  parseExpressionBase(\n    this: Parser,\n    refExpressionErrors?: ExpressionErrors,\n  ): N.Expression {\n    const startLoc = this.state.startLoc;\n    const expr = this.parseMaybeAssign(refExpressionErrors);\n    if (this.match(tt.comma)) {\n      const node = this.startNodeAt<N.SequenceExpression>(startLoc);\n      node.expressions = [expr];\n      while (this.eat(tt.comma)) {\n        node.expressions.push(this.parseMaybeAssign(refExpressionErrors));\n      }\n      this.toReferencedList(node.expressions);\n      return this.finishNode(node, \"SequenceExpression\");\n    }\n    return expr;\n  }\n\n  // Set [~In] parameter for assignment expression\n  parseMaybeAssignDisallowIn(\n    this: Parser,\n    refExpressionErrors?: ExpressionErrors | null,\n    afterLeftParse?: Function,\n  ) {\n    return this.disallowInAnd(() =>\n      this.parseMaybeAssign(refExpressionErrors, afterLeftParse),\n    );\n  }\n\n  // Set [+In] parameter for assignment expression\n  parseMaybeAssignAllowIn(\n    this: Parser,\n    refExpressionErrors?: ExpressionErrors | null,\n    afterLeftParse?: Function,\n  ) {\n    return this.allowInAnd(() =>\n      this.parseMaybeAssign(refExpressionErrors, afterLeftParse),\n    );\n  }\n\n  // This method is only used by\n  // the typescript and flow plugins.\n  setOptionalParametersError(refExpressionErrors: ExpressionErrors) {\n    refExpressionErrors.optionalParametersLoc = this.state.startLoc;\n  }\n\n  // Parse an assignment expression. This includes applications of\n  // operators like `+=`.\n  // https://tc39.es/ecma262/#prod-AssignmentExpression\n  parseMaybeAssign(\n    this: Parser,\n    refExpressionErrors?: ExpressionErrors | null,\n    afterLeftParse?: Function,\n  ): N.Expression {\n    const startLoc = this.state.startLoc;\n    const isYield = this.isContextual(tt._yield);\n    if (isYield) {\n      if (this.prodParam.hasYield) {\n        this.next();\n        let left = this.parseYield(startLoc);\n        if (afterLeftParse) {\n          left = afterLeftParse.call(this, left, startLoc);\n        }\n        return left;\n      }\n    }\n\n    let ownExpressionErrors;\n    if (refExpressionErrors) {\n      ownExpressionErrors = false;\n    } else {\n      refExpressionErrors = new ExpressionErrors();\n      ownExpressionErrors = true;\n    }\n    const { type } = this.state;\n\n    if (type === tt.parenL || tokenIsIdentifier(type)) {\n      this.state.potentialArrowAt = this.state.start;\n    }\n\n    let left = this.parseMaybeConditional(refExpressionErrors);\n    if (afterLeftParse) {\n      left = afterLeftParse.call(this, left, startLoc);\n    }\n    if (tokenIsAssignment(this.state.type)) {\n      const node = this.startNodeAt<N.AssignmentExpression>(startLoc);\n      const operator = this.state.value;\n      node.operator = operator;\n\n      if (this.match(tt.eq)) {\n        this.toAssignable(left, /* isLHS */ true);\n        node.left = left;\n\n        const startIndex = startLoc.index;\n        if (\n          refExpressionErrors.doubleProtoLoc != null &&\n          refExpressionErrors.doubleProtoLoc.index >= startIndex\n        ) {\n          refExpressionErrors.doubleProtoLoc = null; // reset because double __proto__ is valid in assignment expression\n        }\n        if (\n          refExpressionErrors.shorthandAssignLoc != null &&\n          refExpressionErrors.shorthandAssignLoc.index >= startIndex\n        ) {\n          refExpressionErrors.shorthandAssignLoc = null; // reset because shorthand default was used correctly\n        }\n        if (\n          refExpressionErrors.privateKeyLoc != null &&\n          refExpressionErrors.privateKeyLoc.index >= startIndex\n        ) {\n          this.checkDestructuringPrivate(refExpressionErrors);\n          refExpressionErrors.privateKeyLoc = null; // reset because `({ #x: x })` is an assignable pattern\n        }\n        if (\n          refExpressionErrors.voidPatternLoc != null &&\n          refExpressionErrors.voidPatternLoc.index >= startIndex\n        ) {\n          refExpressionErrors.voidPatternLoc = null;\n        }\n      } else {\n        node.left = left as unknown as N.Assignable; // checked a few lines further down\n      }\n\n      this.next();\n      node.right = this.parseMaybeAssign();\n      this.checkLVal(left, this.finishNode(node, \"AssignmentExpression\"));\n      // @ts-expect-error todo(flow->ts) improve node types\n      return node;\n    } else if (ownExpressionErrors) {\n      this.checkExpressionErrors(refExpressionErrors, true);\n    }\n\n    if (isYield) {\n      const { type } = this.state;\n      const startsExpr = this.hasPlugin(\"v8intrinsic\")\n        ? tokenCanStartExpression(type)\n        : tokenCanStartExpression(type) && !this.match(tt.modulo);\n      if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) {\n        this.raiseOverwrite(Errors.YieldNotInGeneratorFunction, startLoc);\n        return this.parseYield(startLoc);\n      }\n    }\n\n    return left;\n  }\n\n  // Parse a ternary conditional (`?:`) operator.\n  // https://tc39.es/ecma262/#prod-ConditionalExpression\n\n  parseMaybeConditional(\n    this: Parser,\n    refExpressionErrors: ExpressionErrors,\n  ): N.Expression {\n    const startLoc = this.state.startLoc;\n    const potentialArrowAt = this.state.potentialArrowAt;\n    const expr = this.parseExprOps(refExpressionErrors);\n\n    if (this.shouldExitDescending(expr, potentialArrowAt)) {\n      return expr;\n    }\n\n    return this.parseConditional(expr, startLoc, refExpressionErrors);\n  }\n\n  parseConditional(\n    this: Parser,\n    expr: N.Expression,\n    startLoc: Position,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    refExpressionErrors?: ExpressionErrors | null,\n  ): N.Expression {\n    if (this.eat(tt.question)) {\n      const node = this.startNodeAt<N.ConditionalExpression>(startLoc);\n      node.test = expr;\n      node.consequent = this.parseMaybeAssignAllowIn();\n      this.expect(tt.colon);\n      node.alternate = this.parseMaybeAssign();\n      return this.finishNode(node, \"ConditionalExpression\");\n    }\n    return expr;\n  }\n\n  parseMaybeUnaryOrPrivate(\n    this: Parser,\n    refExpressionErrors?: ExpressionErrors,\n  ): N.Expression | N.PrivateName {\n    return this.match(tt.privateName)\n      ? this.parsePrivateName()\n      : this.parseMaybeUnary(refExpressionErrors);\n  }\n\n  // Start the precedence parser.\n  // https://tc39.es/ecma262/#prod-ShortCircuitExpression\n\n  parseExprOps(\n    this: Parser,\n    refExpressionErrors: ExpressionErrors,\n  ): N.Expression {\n    const startLoc = this.state.startLoc;\n    const potentialArrowAt = this.state.potentialArrowAt;\n    const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);\n\n    if (this.shouldExitDescending(expr, potentialArrowAt)) {\n      return expr;\n    }\n\n    return this.parseExprOp(expr, startLoc, -1);\n  }\n\n  // Parse binary operators with the operator precedence parsing\n  // algorithm. `left` is the left-hand side of the operator.\n  // `minPrec` provides context that allows the function to stop and\n  // defer further parser to one of its callers when it encounters an\n  // operator that has a lower precedence than the set it is parsing.\n\n  parseExprOp(\n    this: Parser,\n    left: N.Expression | N.PrivateName,\n    leftStartLoc: Position,\n    minPrec: number,\n  ): N.Expression {\n    if (this.isPrivateName(left)) {\n      // https://tc39.es/ecma262/#prod-RelationalExpression\n      // RelationalExpression [In, Yield, Await]\n      //   [+In] PrivateIdentifier in ShiftExpression[?Yield, ?Await]\n\n      const value = this.getPrivateNameSV(left);\n\n      if (\n        minPrec >= tokenOperatorPrecedence(tt._in) ||\n        !this.prodParam.hasIn ||\n        !this.match(tt._in)\n      ) {\n        this.raise(Errors.PrivateInExpectedIn, left, {\n          identifierName: value,\n        });\n      }\n\n      this.classScope.usePrivateName(value, left.loc.start);\n    }\n\n    const op = this.state.type;\n    if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(tt._in))) {\n      let prec = tokenOperatorPrecedence(op);\n      if (prec > minPrec) {\n        if (op === tt.pipeline) {\n          this.expectPlugin(\"pipelineOperator\");\n          if (this.state.inFSharpPipelineDirectBody) {\n            // PrivateName must be followed by `in`, but we have `|>`\n            return left as N.Expression;\n          }\n          this.checkPipelineAtInfixOperator(left as N.Expression, leftStartLoc);\n        }\n        const node = this.startNodeAt<N.LogicalExpression | N.BinaryExpression>(\n          leftStartLoc,\n        );\n        node.left = left;\n        node.operator = this.state.value;\n\n        const logical = op === tt.logicalOR || op === tt.logicalAND;\n        const coalesce = op === tt.nullishCoalescing;\n\n        if (coalesce) {\n          // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.\n          // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.\n          prec = tokenOperatorPrecedence(tt.logicalAND);\n        }\n\n        this.next();\n\n        if (\n          !process.env.BABEL_8_BREAKING &&\n          op === tt.pipeline &&\n          // @ts-expect-error: Only in Babel 7\n          this.hasPlugin([\"pipelineOperator\", { proposal: \"minimal\" }])\n        ) {\n          if (this.state.type === tt._await && this.prodParam.hasAwait) {\n            throw this.raise(\n              Errors.UnexpectedAwaitAfterPipelineBody,\n              this.state.startLoc,\n            );\n          }\n        }\n\n        node.right = this.parseExprOpRightExpr(op, prec);\n        const finishedNode = this.finishNode(\n          node,\n          logical || coalesce ? \"LogicalExpression\" : \"BinaryExpression\",\n        );\n        /* this check is for all ?? operators\n         * a ?? b && c for this example\n         * when op is coalesce and nextOp is logical (&&), throw at the pos of nextOp that it can not be mixed.\n         * Symmetrically it also throws when op is logical and nextOp is coalesce\n         */\n        const nextOp = this.state.type;\n        if (\n          (coalesce && (nextOp === tt.logicalOR || nextOp === tt.logicalAND)) ||\n          (logical && nextOp === tt.nullishCoalescing)\n        ) {\n          throw this.raise(\n            Errors.MixingCoalesceWithLogical,\n            this.state.startLoc,\n          );\n        }\n\n        return this.parseExprOp(finishedNode, leftStartLoc, minPrec);\n      }\n    }\n    // PrivateName is followed by `in` and handled by the previous if statement\n    return left as N.Expression;\n  }\n\n  // Helper function for `parseExprOp`. Parse the right-hand side of binary-\n  // operator expressions, then apply any operator-specific functions.\n\n  parseExprOpRightExpr(\n    this: Parser,\n    op: TokenType,\n    prec: number,\n  ): N.Expression {\n    const startLoc = this.state.startLoc;\n    switch (op) {\n      case tt.pipeline:\n        switch (this.getPluginOption(\"pipelineOperator\", \"proposal\")) {\n          case \"hack\":\n            return this.withTopicBindingContext(() => {\n              return this.parseHackPipeBody();\n            });\n\n          case \"fsharp\":\n            return this.withSoloAwaitPermittingContext(() => {\n              return this.parseFSharpPipelineBody(prec);\n            });\n        }\n\n        if (\n          !process.env.BABEL_8_BREAKING &&\n          // @ts-expect-error: Babel 7 only\n          this.getPluginOption(\"pipelineOperator\", \"proposal\") === \"smart\"\n        ) {\n          return this.withTopicBindingContext(() => {\n            if (this.prodParam.hasYield && this.isContextual(tt._yield)) {\n              throw this.raise(Errors.PipeBodyIsTighter, this.state.startLoc);\n            }\n            return this.parseSmartPipelineBodyInStyle(\n              this.parseExprOpBaseRightExpr(op, prec),\n              startLoc,\n            );\n          });\n        }\n\n      // Falls through.\n      default:\n        return this.parseExprOpBaseRightExpr(op, prec);\n    }\n  }\n\n  // Helper function for `parseExprOpRightExpr`. Parse the right-hand side of\n  // binary-operator expressions without applying any operator-specific functions.\n\n  parseExprOpBaseRightExpr(\n    this: Parser,\n    op: TokenType,\n    prec: number,\n  ): N.Expression {\n    const startLoc = this.state.startLoc;\n\n    return this.parseExprOp(\n      this.parseMaybeUnaryOrPrivate(),\n      startLoc,\n      tokenIsRightAssociative(op) ? prec - 1 : prec,\n    );\n  }\n\n  parseHackPipeBody(this: Parser): N.Expression {\n    const { startLoc } = this.state;\n    const body = this.parseMaybeAssign();\n    const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(\n      // @ts-expect-error TS2345: Argument of type 'string' is not assignable to parameter of type '\"ArrowFunctionExpression\" | \"YieldExpression\" | \"AssignmentExpression\" | \"ConditionalExpression\"'.\n      body.type,\n    );\n\n    // TODO: Check how to handle type casts in Flow and TS once they are supported\n    if (requiredParentheses && !body.extra?.parenthesized) {\n      this.raise(Errors.PipeUnparenthesizedBody, startLoc, {\n        type: body.type as UnparenthesizedPipeBodyTypes,\n      });\n    }\n    if (!this.topicReferenceWasUsedInCurrentContext()) {\n      // A Hack pipe body must use the topic reference at least once.\n      this.raise(Errors.PipeTopicUnused, startLoc);\n    }\n\n    return body;\n  }\n\n  checkExponentialAfterUnary(\n    node: N.AwaitExpression | Undone<N.UnaryExpression>,\n  ) {\n    if (this.match(tt.exponent)) {\n      this.raise(Errors.UnexpectedTokenUnaryExponentiation, node.argument);\n    }\n  }\n\n  // Parse unary operators, both prefix and postfix.\n  // https://tc39.es/ecma262/#prod-UnaryExpression\n  parseMaybeUnary(\n    this: Parser,\n    refExpressionErrors?: ExpressionErrors | null,\n    sawUnary?: boolean,\n  ): N.Expression {\n    const startLoc = this.state.startLoc;\n    const isAwait = this.isContextual(tt._await);\n\n    if (isAwait && this.recordAwaitIfAllowed()) {\n      this.next();\n      const expr = this.parseAwait(startLoc);\n      if (!sawUnary) this.checkExponentialAfterUnary(expr);\n      return expr;\n    }\n    const update = this.match(tt.incDec);\n    const node = this.startNode<N.UnaryExpression | N.UpdateExpression>();\n    if (tokenIsPrefix(this.state.type)) {\n      node.operator = this.state.value;\n      node.prefix = true;\n\n      if (this.match(tt._throw)) {\n        this.expectPlugin(\"throwExpressions\");\n      }\n      const isDelete = this.match(tt._delete);\n      this.next();\n\n      node.argument = this.parseMaybeUnary(null, true);\n\n      this.checkExpressionErrors(refExpressionErrors, true);\n\n      if (this.state.strict && isDelete) {\n        const arg = node.argument;\n\n        if (arg.type === \"Identifier\") {\n          this.raise(Errors.StrictDelete, node);\n        } else if (this.hasPropertyAsPrivateName(arg)) {\n          this.raise(Errors.DeletePrivateField, node);\n        }\n      }\n\n      if (!update) {\n        if (!sawUnary) {\n          this.checkExponentialAfterUnary(node as Undone<N.UnaryExpression>);\n        }\n        return this.finishNode(node, \"UnaryExpression\");\n      }\n    }\n\n    const expr = this.parseUpdate(\n      // @ts-expect-error using \"Undone\" node as \"done\"\n      node,\n      update,\n      refExpressionErrors,\n    );\n\n    if (isAwait) {\n      const { type } = this.state;\n      const startsExpr = this.hasPlugin(\"v8intrinsic\")\n        ? tokenCanStartExpression(type)\n        : tokenCanStartExpression(type) && !this.match(tt.modulo);\n      if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) {\n        this.raiseOverwrite(Errors.AwaitNotInAsyncContext, startLoc);\n        return this.parseAwait(startLoc);\n      }\n    }\n\n    return expr;\n  }\n\n  // https://tc39.es/ecma262/#prod-UpdateExpression\n  parseUpdate(\n    this: Parser,\n    node: N.Expression,\n    update: boolean,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): N.Expression {\n    if (update) {\n      const updateExpressionNode = node as Undone<N.UpdateExpression>;\n      this.checkLVal(\n        updateExpressionNode.argument,\n        this.finishNode(updateExpressionNode, \"UpdateExpression\"),\n      );\n      return node;\n    }\n\n    const startLoc = this.state.startLoc;\n    let expr = this.parseExprSubscripts(refExpressionErrors);\n    if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;\n    while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {\n      const node = this.startNodeAt<N.UpdateExpression>(startLoc);\n      node.operator = this.state.value;\n      node.prefix = false;\n      node.argument = expr;\n      this.next();\n      this.checkLVal(expr, (expr = this.finishNode(node, \"UpdateExpression\")));\n    }\n    return expr;\n  }\n\n  // Parse call, dot, and `[]`-subscript expressions.\n  // https://tc39.es/ecma262/#prod-LeftHandSideExpression\n  parseExprSubscripts(\n    this: Parser,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): N.Expression {\n    const startLoc = this.state.startLoc;\n    const potentialArrowAt = this.state.potentialArrowAt;\n    const expr = this.parseExprAtom(refExpressionErrors);\n\n    if (this.shouldExitDescending(expr, potentialArrowAt)) {\n      return expr;\n    }\n\n    return this.parseSubscripts(expr, startLoc);\n  }\n\n  parseSubscripts(\n    this: Parser,\n    base: N.Expression,\n    startLoc: Position,\n    noCalls?: boolean | null,\n  ): N.Expression {\n    const state = {\n      optionalChainMember: false,\n      maybeAsyncArrow: this.atPossibleAsyncArrow(base),\n      stop: false,\n    };\n    do {\n      base = this.parseSubscript(base, startLoc, noCalls, state);\n\n      // After parsing a subscript, this isn't \"async\" for sure.\n      state.maybeAsyncArrow = false;\n    } while (!state.stop);\n    return base;\n  }\n\n  /**\n   * @param state Set 'state.stop = true' to indicate that we should stop parsing subscripts.\n   *   state.optionalChainMember to indicate that the member is currently in OptionalChain\n   */\n  parseSubscript(\n    this: Parser,\n    base: N.Expression,\n    startLoc: Position,\n    noCalls: boolean | undefined | null,\n    state: N.ParseSubscriptState,\n  ): N.Expression {\n    const { type } = this.state;\n    if (!noCalls && type === tt.doubleColon) {\n      return this.parseBind(base, startLoc, noCalls, state);\n    } else if (tokenIsTemplate(type)) {\n      return this.parseTaggedTemplateExpression(base, startLoc, state);\n    }\n\n    let optional = false;\n\n    if (type === tt.questionDot) {\n      if (noCalls) {\n        this.raise(Errors.OptionalChainingNoNew, this.state.startLoc);\n        if (this.lookaheadCharCode() === charCodes.leftParenthesis) {\n          // stop at `?.` when parsing `new a?.()`\n          return this.stopParseSubscript(base, state);\n        }\n      }\n      state.optionalChainMember = optional = true;\n      this.next();\n    }\n\n    if (!noCalls && this.match(tt.parenL)) {\n      return this.parseCoverCallAndAsyncArrowHead(\n        base,\n        startLoc,\n        state,\n        optional,\n      );\n    } else {\n      const computed = this.eat(tt.bracketL);\n      if (computed || optional || this.eat(tt.dot)) {\n        return this.parseMember(base, startLoc, state, computed, optional);\n      } else {\n        return this.stopParseSubscript(base, state);\n      }\n    }\n  }\n\n  stopParseSubscript(\n    this: Parser,\n    base: N.Expression,\n    state: N.ParseSubscriptState,\n  ) {\n    state.stop = true;\n    return base;\n  }\n\n  // base[?Yield, ?Await] [ Expression[+In, ?Yield, ?Await] ]\n  // base[?Yield, ?Await] . IdentifierName\n  // base[?Yield, ?Await] . PrivateIdentifier\n  //   where `base` is one of CallExpression, MemberExpression and OptionalChain\n  parseMember(\n    this: Parser,\n    base: N.Expression,\n    startLoc: Position,\n    state: N.ParseSubscriptState,\n    computed: boolean,\n    optional: boolean,\n  ): N.OptionalMemberExpression | N.MemberExpression {\n    const node = this.startNodeAt<\n      N.OptionalMemberExpression | N.MemberExpression\n    >(startLoc);\n    node.object = base;\n    node.computed = computed;\n    if (computed) {\n      node.property = this.parseExpression();\n      this.expect(tt.bracketR);\n    } else if (this.match(tt.privateName)) {\n      if (base.type === \"Super\") {\n        this.raise(Errors.SuperPrivateField, startLoc);\n      }\n      this.classScope.usePrivateName(this.state.value, this.state.startLoc);\n      node.property = this.parsePrivateName();\n    } else {\n      node.property = this.parseIdentifier(true);\n    }\n\n    if (state.optionalChainMember) {\n      (node as Undone<N.OptionalMemberExpression>).optional = optional;\n      return this.finishNode(node, \"OptionalMemberExpression\");\n    } else {\n      return this.finishNode(node, \"MemberExpression\");\n    }\n  }\n\n  // https://github.com/tc39/proposal-bind-operator#syntax\n  parseBind(\n    this: Parser,\n    base: N.Expression,\n    startLoc: Position,\n    noCalls: boolean | undefined | null,\n    state: N.ParseSubscriptState,\n  ): N.Expression {\n    const node = this.startNodeAt<N.BindExpression>(startLoc);\n    node.object = base;\n    this.next(); // eat '::'\n    node.callee = this.parseNoCallExpr();\n    state.stop = true;\n    return this.parseSubscripts(\n      this.finishNode(node, \"BindExpression\"),\n      startLoc,\n      noCalls,\n    );\n  }\n\n  // https://tc39.es/ecma262/#prod-CoverCallExpressionAndAsyncArrowHead\n  // CoverCallExpressionAndAsyncArrowHead\n  // CallExpression[?Yield, ?Await] Arguments[?Yield, ?Await]\n  // OptionalChain[?Yield, ?Await] Arguments[?Yield, ?Await]\n  parseCoverCallAndAsyncArrowHead(\n    this: Parser,\n    base: N.Expression,\n    startLoc: Position,\n    state: N.ParseSubscriptState,\n    optional: boolean,\n  ): N.Expression {\n    const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;\n    let refExpressionErrors: ExpressionErrors | null = null;\n\n    this.state.maybeInArrowParameters = true;\n    this.next(); // eat `(`\n\n    const node = this.startNodeAt<N.CallExpression | N.OptionalCallExpression>(\n      startLoc,\n    );\n    node.callee = base;\n    const { maybeAsyncArrow, optionalChainMember } = state;\n\n    if (maybeAsyncArrow) {\n      this.expressionScope.enter(newAsyncArrowScope());\n      refExpressionErrors = new ExpressionErrors();\n    }\n\n    if (optionalChainMember) {\n      (node as Undone<N.OptionalCallExpression>).optional = optional;\n    }\n\n    if (optional) {\n      node.arguments = this.parseCallExpressionArguments();\n    } else {\n      node.arguments = this.parseCallExpressionArguments(\n        base.type !== \"Super\",\n        node,\n        refExpressionErrors,\n      );\n    }\n    let finishedNode:\n      | N.CallExpression\n      | N.OptionalCallExpression\n      | N.ArrowFunctionExpression = this.finishCallExpression(\n      node,\n      optionalChainMember,\n    );\n\n    if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {\n      /*:: invariant(refExpressionErrors != null) */\n      state.stop = true;\n      this.checkDestructuringPrivate(refExpressionErrors);\n      this.expressionScope.validateAsPattern();\n      this.expressionScope.exit();\n      finishedNode = this.parseAsyncArrowFromCallExpression(\n        this.startNodeAt<N.ArrowFunctionExpression>(startLoc),\n        finishedNode as N.CallExpression,\n      );\n    } else {\n      if (maybeAsyncArrow) {\n        this.checkExpressionErrors(refExpressionErrors, true);\n        this.expressionScope.exit();\n      }\n      this.toReferencedArguments(finishedNode);\n    }\n\n    this.state.maybeInArrowParameters = oldMaybeInArrowParameters;\n\n    return finishedNode;\n  }\n\n  toReferencedArguments(\n    node: N.CallExpression | N.OptionalCallExpression,\n    isParenthesizedExpr?: boolean,\n  ) {\n    this.toReferencedListDeep(node.arguments, isParenthesizedExpr);\n  }\n\n  // MemberExpression [?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged]\n  // CallExpression [?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged]\n  parseTaggedTemplateExpression(\n    this: Parser,\n    base: N.Expression,\n    startLoc: Position,\n    state: N.ParseSubscriptState,\n  ): N.TaggedTemplateExpression {\n    const node = this.startNodeAt<N.TaggedTemplateExpression>(startLoc);\n    node.tag = base;\n    node.quasi = this.parseTemplate(true);\n    if (state.optionalChainMember) {\n      this.raise(Errors.OptionalChainingNoTemplate, startLoc);\n    }\n    return this.finishNode(node, \"TaggedTemplateExpression\");\n  }\n\n  atPossibleAsyncArrow(base: N.Expression): boolean {\n    return (\n      base.type === \"Identifier\" &&\n      base.name === \"async\" &&\n      this.state.lastTokEndLoc.index === base.end &&\n      !this.canInsertSemicolon() &&\n      // check there are no escape sequences, such as \\u{61}sync\n      base.end - base.start === 5 &&\n      this.offsetToSourcePos(base.start) === this.state.potentialArrowAt\n    );\n  }\n\n  finishCallExpression<T extends N.CallExpression | N.OptionalCallExpression>(\n    node: Undone<T>,\n    optional: boolean,\n  ): T {\n    if (node.callee.type === \"Import\") {\n      if (node.arguments.length === 0 || node.arguments.length > 2) {\n        this.raise(Errors.ImportCallArity, node);\n      } else {\n        for (const arg of node.arguments) {\n          if (arg.type === \"SpreadElement\") {\n            this.raise(Errors.ImportCallSpreadArgument, arg);\n          }\n        }\n      }\n    }\n    return this.finishNode(\n      node,\n      optional ? \"OptionalCallExpression\" : \"CallExpression\",\n    );\n  }\n\n  parseCallExpressionArguments(\n    this: Parser,\n    allowPlaceholder?: boolean,\n    nodeForExtra?: Undone<N.Node> | null,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): Array<N.Expression> {\n    const elts: N.Expression[] = [];\n    let first = true;\n    const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;\n    this.state.inFSharpPipelineDirectBody = false;\n\n    while (!this.eat(tt.parenR)) {\n      if (first) {\n        first = false;\n      } else {\n        this.expect(tt.comma);\n        if (this.match(tt.parenR)) {\n          if (nodeForExtra) {\n            this.addTrailingCommaExtraToNode(nodeForExtra);\n          }\n          this.next();\n          break;\n        }\n      }\n\n      elts.push(\n        this.parseExprListItem(\n          tt.parenR,\n          false,\n          refExpressionErrors,\n          allowPlaceholder,\n        ),\n      );\n    }\n\n    this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;\n\n    return elts;\n  }\n\n  shouldParseAsyncArrow(): boolean {\n    return this.match(tt.arrow) && !this.canInsertSemicolon();\n  }\n\n  parseAsyncArrowFromCallExpression(\n    this: Parser,\n    node: Undone<N.ArrowFunctionExpression>,\n    call: N.CallExpression,\n  ): N.ArrowFunctionExpression {\n    this.resetPreviousNodeTrailingComments(call);\n    this.expect(tt.arrow);\n    this.parseArrowExpression(\n      node,\n      call.arguments,\n      true,\n      call.extra?.trailingCommaLoc,\n    );\n    // mark inner comments of `async()` as inner comments of `async () =>`\n    if (call.innerComments) {\n      setInnerComments(node, call.innerComments);\n    }\n    // mark trailing comments of `async` to be inner comments\n    if (call.callee.trailingComments) {\n      setInnerComments(node, call.callee.trailingComments);\n    }\n    return node as N.ArrowFunctionExpression;\n  }\n\n  // Parse a no-call expression (like argument of `new` or `::` operators).\n  // https://tc39.es/ecma262/#prod-MemberExpression\n  parseNoCallExpr(this: Parser): N.Expression {\n    const startLoc = this.state.startLoc;\n    return this.parseSubscripts(this.parseExprAtom(), startLoc, true);\n  }\n\n  // Parse an atomic expression — either a single token that is an\n  // expression, an expression started by a keyword like `function` or\n  // `new`, or an expression wrapped in punctuation like `()`, `[]`,\n  // or `{}`.\n\n  // https://tc39.es/ecma262/#prod-PrimaryExpression\n  // https://tc39.es/ecma262/#prod-AsyncArrowFunction\n  // PrimaryExpression\n  // Super\n  // Import\n  // AsyncArrowFunction\n\n  parseExprAtom(\n    this: Parser,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): N.Expression {\n    let node;\n    let decorators: N.Decorator[] | null = null;\n\n    const { type } = this.state;\n    switch (type) {\n      case tt._super:\n        return this.parseSuper();\n\n      case tt._import:\n        node = this.startNode<N.MetaProperty | N.Import | N.ImportExpression>();\n        this.next();\n\n        if (this.match(tt.dot)) {\n          return this.parseImportMetaPropertyOrPhaseCall(\n            node as Undone<N.MetaProperty | N.ImportExpression>,\n          );\n        }\n\n        if (this.match(tt.parenL)) {\n          if (this.optionFlags & OptionFlags.CreateImportExpressions) {\n            return this.parseImportCall(node as Undone<N.ImportExpression>);\n          } else {\n            return this.finishNode(node, \"Import\");\n          }\n        } else {\n          this.raise(Errors.UnsupportedImport, this.state.lastTokStartLoc);\n          return this.finishNode(node, \"Import\");\n        }\n\n      case tt._this:\n        node = this.startNode<N.ThisExpression>();\n        this.next();\n        return this.finishNode(node, \"ThisExpression\");\n\n      case tt._do: {\n        return this.parseDo(this.startNode(), false);\n      }\n\n      case tt.slash:\n      case tt.slashAssign: {\n        this.readRegexp();\n        return this.parseRegExpLiteral(this.state.value);\n      }\n\n      case tt.num:\n        return this.parseNumericLiteral(this.state.value);\n\n      case tt.bigint:\n        return this.parseBigIntLiteral(this.state.value);\n\n      case tt.string:\n        return this.parseStringLiteral(this.state.value);\n\n      case tt._null:\n        return this.parseNullLiteral();\n\n      case tt._true:\n        return this.parseBooleanLiteral(true);\n      case tt._false:\n        return this.parseBooleanLiteral(false);\n\n      case tt.parenL: {\n        const canBeArrow = this.state.potentialArrowAt === this.state.start;\n        return this.parseParenAndDistinguishExpression(canBeArrow);\n      }\n\n      case tt.bracketL: {\n        return this.parseArrayLike(\n          tt.bracketR,\n          /* canBePattern */ true,\n          /* isTuple */ false,\n          refExpressionErrors,\n        );\n      }\n      case tt.braceL: {\n        return this.parseObjectLike(\n          tt.braceR,\n          /* isPattern */ false,\n          /* isRecord */ false,\n          refExpressionErrors,\n        );\n      }\n      case tt._function:\n        return this.parseFunctionOrFunctionSent();\n\n      case tt.at:\n        decorators = this.parseDecorators();\n      // fall through\n      case tt._class:\n        return this.parseClass(\n          this.maybeTakeDecorators(\n            decorators,\n            this.startNode<N.ClassExpression>(),\n          ),\n          false,\n        );\n\n      case tt._new:\n        return this.parseNewOrNewTarget();\n\n      case tt.templateNonTail:\n      case tt.templateTail:\n        return this.parseTemplate(false);\n\n      // BindExpression[Yield]\n      //   :: MemberExpression[?Yield]\n      case tt.doubleColon: {\n        node = this.startNode<N.BindExpression>();\n        this.next();\n        node.object = null;\n        const callee = (node.callee = this.parseNoCallExpr());\n        if (callee.type === \"MemberExpression\") {\n          return this.finishNode(node, \"BindExpression\");\n        } else {\n          throw this.raise(Errors.UnsupportedBind, callee);\n        }\n      }\n\n      case tt.privateName: {\n        // Standalone private names are only allowed in \"#x in obj\"\n        // expressions, and they are directly handled by callers of\n        // parseExprOp. If we reach this, the input is always invalid.\n        // We can throw a better error message and recover, rather than\n        // just throwing \"Unexpected token\" (which is the default\n        // behavior of this big switch statement).\n        this.raise(Errors.PrivateInExpectedIn, this.state.startLoc, {\n          identifierName: this.state.value,\n        });\n        return this.parsePrivateName() as unknown as N.Expression;\n      }\n\n      case tt.moduloAssign: {\n        return this.parseTopicReferenceThenEqualsSign(tt.modulo, \"%\");\n      }\n\n      case tt.xorAssign: {\n        return this.parseTopicReferenceThenEqualsSign(tt.bitwiseXOR, \"^\");\n      }\n\n      case tt.doubleCaret:\n      case tt.doubleAt: {\n        return this.parseTopicReference(\"hack\");\n      }\n\n      case tt.bitwiseXOR:\n      case tt.modulo:\n      case tt.hash: {\n        const pipeProposal = this.getPluginOption(\n          \"pipelineOperator\",\n          \"proposal\",\n        );\n\n        if (pipeProposal) {\n          return this.parseTopicReference(pipeProposal);\n        }\n        this.unexpected();\n        break;\n      }\n\n      case tt.lt: {\n        const lookaheadCh = this.input.codePointAt(this.nextTokenStart());\n        if (\n          isIdentifierStart(lookaheadCh) || // Element/Type Parameter <foo>\n          lookaheadCh === charCodes.greaterThan // Fragment <>\n        ) {\n          this.expectOnePlugin([\"jsx\", \"flow\", \"typescript\"]);\n        } else {\n          this.unexpected();\n        }\n        break;\n      }\n\n      default:\n        if (!process.env.BABEL_8_BREAKING) {\n          if (type === tt.decimal) {\n            return this.parseDecimalLiteral(this.state.value);\n          } else if (type === tt.bracketBarL || type === tt.bracketHashL) {\n            return this.parseArrayLike(\n              this.state.type === tt.bracketBarL ? tt.bracketBarR : tt.bracketR,\n              /* canBePattern */ false,\n              /* isTuple */ true,\n            );\n          } else if (type === tt.braceBarL || type === tt.braceHashL) {\n            return this.parseObjectLike(\n              this.state.type === tt.braceBarL ? tt.braceBarR : tt.braceR,\n              /* isPattern */ false,\n              /* isRecord */ true,\n            );\n          }\n        }\n\n        if (tokenIsIdentifier(type)) {\n          if (\n            this.isContextual(tt._module) &&\n            this.lookaheadInLineCharCode() === charCodes.leftCurlyBrace\n          ) {\n            return this.parseModuleExpression();\n          }\n          const canBeArrow = this.state.potentialArrowAt === this.state.start;\n          const containsEsc = this.state.containsEsc;\n          const id = this.parseIdentifier();\n\n          if (\n            !containsEsc &&\n            id.name === \"async\" &&\n            !this.canInsertSemicolon()\n          ) {\n            const { type } = this.state;\n            if (type === tt._function) {\n              this.resetPreviousNodeTrailingComments(id);\n              this.next();\n              return this.parseAsyncFunctionExpression(\n                this.startNodeAtNode(id),\n              );\n            } else if (tokenIsIdentifier(type)) {\n              // If the next token begins with \"=\", commit to parsing an async\n              // arrow function. (Peeking ahead for \"=\" lets us avoid a more\n              // expensive full-token lookahead on this common path.)\n              if (this.lookaheadCharCode() === charCodes.equalsTo) {\n                // although `id` is not used in async arrow unary function,\n                // we don't need to reset `async`'s trailing comments because\n                // it will be attached to the upcoming async arrow binding identifier\n                return this.parseAsyncArrowUnaryFunction(\n                  this.startNodeAtNode(id),\n                );\n              } else {\n                // Otherwise, treat \"async\" as an identifier and let calling code\n                // deal with the current tt.name token.\n                return id;\n              }\n            } else if (type === tt._do) {\n              this.resetPreviousNodeTrailingComments(id);\n              return this.parseDo(this.startNodeAtNode(id), true);\n            }\n          }\n\n          if (\n            canBeArrow &&\n            this.match(tt.arrow) &&\n            !this.canInsertSemicolon()\n          ) {\n            this.next();\n            return this.parseArrowExpression(\n              this.startNodeAtNode(id),\n              [id],\n              false,\n            );\n          }\n\n          return id;\n        } else {\n          this.unexpected();\n        }\n    }\n  }\n\n  // This helper method should only be called\n  // when the parser has reached a potential Hack pipe topic token\n  // that is followed by an equals sign.\n  // See <https://github.com/js-choi/proposal-hack-pipes>.\n  // If we find ^= or %= in an expression position\n  // (i.e., the tt.moduloAssign or tt.xorAssign token types), and if the\n  // Hack-pipes proposal is active with ^ or % as its topicToken, then the ^ or\n  // % could be the topic token (e.g., in x |> ^==y or x |> ^===y), and so we\n  // reparse the current token as ^ or %.\n  // Otherwise, this throws an unexpected-token error.\n  parseTopicReferenceThenEqualsSign(\n    topicTokenType: TokenType,\n    topicTokenValue: string,\n  ): N.Expression {\n    const pipeProposal = this.getPluginOption(\"pipelineOperator\", \"proposal\");\n\n    if (pipeProposal) {\n      // Set the most-recent token to be a topic token\n      // given by the tokenType and tokenValue.\n      // Now the next readToken() call (in parseTopicReference)\n      // will consume that “topic token”.\n      this.state.type = topicTokenType;\n      this.state.value = topicTokenValue;\n      // Rewind the tokenizer to the end of the “topic token”, so that the\n      // following token starts at the equals sign after that topic token.\n      this.state.pos--;\n      this.state.end--;\n      // This is safe to do since the preceding character was either ^ or %, and\n      // thus not a newline.\n      this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1);\n      // Now actually consume the topic token.\n      return this.parseTopicReference(pipeProposal);\n    } else {\n      this.unexpected();\n    }\n  }\n\n  // This helper method should only be called\n  // when the proposal-pipeline-operator plugin is active,\n  // and when the parser has reached a potential Hack pipe topic token.\n  // Although a pipe-operator proposal is assumed to be active,\n  // its configuration might not match the current token’s type.\n  // See <https://github.com/js-choi/proposal-hack-pipes>.\n  parseTopicReference(pipeProposal: string): N.Expression {\n    const node = this.startNode<N.TopicReference>();\n    const startLoc = this.state.startLoc;\n    const tokenType = this.state.type;\n\n    // Consume the current token.\n    this.next();\n\n    // If the pipe-operator plugin’s configuration matches the current token’s type,\n    // then this will return `node`, will have been finished as a topic reference.\n    // Otherwise, this will throw a `PipeTopicUnconfiguredToken` error.\n    return this.finishTopicReference(node, startLoc, pipeProposal, tokenType);\n  }\n\n  // This helper method attempts to finish the given `node`\n  // into a topic-reference node for the given `pipeProposal`.\n  // See <https://github.com/js-choi/proposal-hack-pipes>.\n  //\n  // The method assumes that any topic token was consumed before it was called.\n  //\n  // If the `pipelineOperator` plugin is active,\n  // and if the given `tokenType` matches the plugin’s configuration,\n  // then this method will return the finished `node`.\n  //\n  // If the `pipelineOperator` plugin is active,\n  // but if the given `tokenType` does not match the plugin’s configuration,\n  // then this method will throw a `PipeTopicUnconfiguredToken` error.\n  finishTopicReference<\n    T extends N.PipelinePrimaryTopicReference | N.TopicReference,\n  >(\n    node: Undone<T>,\n    startLoc: Position,\n    pipeProposal: string,\n    tokenType: TokenType,\n  ): T {\n    if (\n      this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)\n    ) {\n      // The token matches the plugin’s configuration.\n      // The token is therefore a topic reference.\n\n      if (process.env.BABEL_8_BREAKING || pipeProposal === \"hack\") {\n        if (!this.topicReferenceIsAllowedInCurrentContext()) {\n          this.raise(Errors.PipeTopicUnbound, startLoc);\n        }\n\n        // Register the topic reference so that its pipe body knows\n        // that its topic was used at least once.\n        this.registerTopicReference();\n\n        return this.finishNode(node, \"TopicReference\");\n      } else {\n        // pipeProposal is \"smart\"\n\n        if (!this.topicReferenceIsAllowedInCurrentContext()) {\n          this.raise(Errors.PrimaryTopicNotAllowed, startLoc);\n        }\n        this.registerTopicReference();\n        return this.finishNode(node, \"PipelinePrimaryTopicReference\");\n      }\n    } else {\n      // The token does not match the plugin’s configuration.\n      throw this.raise(Errors.PipeTopicUnconfiguredToken, startLoc, {\n        token: tokenLabelName(tokenType),\n      });\n    }\n  }\n\n  // This helper method tests whether the given token type\n  // matches the pipelineOperator parser plugin’s configuration.\n  // If the active pipe proposal is Hack style,\n  // and if the given token is the same as the plugin configuration’s `topicToken`,\n  // then this is a valid topic reference.\n  // If the active pipe proposal is smart mix,\n  // then the topic token must always be `#`.\n  // If the active pipe proposal is neither (e.g., \"minimal\"(Babel 7) or \"fsharp\"),\n  // then an error is thrown.\n  testTopicReferenceConfiguration(\n    pipeProposal: string,\n    startLoc: Position,\n    tokenType: TokenType,\n  ): boolean {\n    switch (pipeProposal) {\n      case \"hack\": {\n        return this.hasPlugin([\n          \"pipelineOperator\",\n          {\n            // @ts-expect-error token must have a label\n            topicToken: tokenLabelName(tokenType),\n          },\n        ]);\n      }\n      case \"smart\":\n        return tokenType === tt.hash;\n      default:\n        throw this.raise(Errors.PipeTopicRequiresHackPipes, startLoc);\n    }\n  }\n\n  // async [no LineTerminator here] AsyncArrowBindingIdentifier[?Yield] [no LineTerminator here] => AsyncConciseBody[?In]\n  parseAsyncArrowUnaryFunction(\n    this: Parser,\n    node: Undone<N.ArrowFunctionExpression>,\n  ): N.ArrowFunctionExpression {\n    // We don't need to push a new ParameterDeclarationScope here since we are sure\n    // 1) it is an async arrow, 2) no biding pattern is allowed in params\n    this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));\n    const params = [this.parseIdentifier()];\n    this.prodParam.exit();\n    if (this.hasPrecedingLineBreak()) {\n      this.raise(Errors.LineTerminatorBeforeArrow, this.state.curPosition());\n    }\n    this.expect(tt.arrow);\n    // let foo = async bar => {};\n    return this.parseArrowExpression(node, params, true);\n  }\n\n  // https://github.com/tc39/proposal-do-expressions\n  // https://github.com/tc39/proposal-async-do-expressions\n  parseDo(\n    this: Parser,\n    node: Undone<N.DoExpression>,\n    isAsync: boolean,\n  ): N.DoExpression {\n    this.expectPlugin(\"doExpressions\");\n    if (isAsync) {\n      this.expectPlugin(\"asyncDoExpressions\");\n    }\n    node.async = isAsync;\n    this.next(); // eat `do`\n    const oldLabels = this.state.labels;\n    this.state.labels = [];\n    if (isAsync) {\n      // AsyncDoExpression :\n      // async [no LineTerminator here] do Block[~Yield, +Await, ~Return]\n      this.prodParam.enter(ParamKind.PARAM_AWAIT);\n      node.body = this.parseBlock();\n      this.prodParam.exit();\n    } else {\n      node.body = this.parseBlock();\n    }\n\n    this.state.labels = oldLabels;\n    return this.finishNode(node, \"DoExpression\");\n  }\n\n  // Parse the `super` keyword\n  parseSuper(): N.Super {\n    const node = this.startNode<N.Super>();\n    this.next(); // eat `super`\n    if (\n      this.match(tt.parenL) &&\n      !this.scope.allowDirectSuper &&\n      !(this.optionFlags & OptionFlags.AllowSuperOutsideMethod)\n    ) {\n      this.raise(Errors.SuperNotAllowed, node);\n    } else if (\n      !this.scope.allowSuper &&\n      !(this.optionFlags & OptionFlags.AllowSuperOutsideMethod)\n    ) {\n      this.raise(Errors.UnexpectedSuper, node);\n    }\n\n    if (\n      !this.match(tt.parenL) &&\n      !this.match(tt.bracketL) &&\n      !this.match(tt.dot)\n    ) {\n      this.raise(Errors.UnsupportedSuper, node);\n    }\n\n    return this.finishNode(node, \"Super\");\n  }\n\n  parsePrivateName(): N.PrivateName {\n    const node = this.startNode<N.PrivateName>();\n    const id = this.startNodeAt<N.Identifier>(\n      // The position is hardcoded because we merge `#` and name into a single\n      // tt.privateName token\n      createPositionWithColumnOffset(this.state.startLoc, 1),\n    );\n    const name = this.state.value;\n    this.next(); // eat #name;\n    node.id = this.createIdentifier(id, name);\n    return this.finishNode(node, \"PrivateName\");\n  }\n\n  parseFunctionOrFunctionSent(\n    this: Parser,\n  ): N.FunctionExpression | N.MetaProperty {\n    const node = this.startNode<N.FunctionExpression | N.MetaProperty>();\n\n    // We do not do parseIdentifier here because when parseFunctionOrFunctionSent\n    // is called we already know that the current token is a \"name\" with the value \"function\"\n    // This will improve perf a tiny little bit as we do not do validation but more importantly\n    // here is that parseIdentifier will remove an item from the expression stack\n    // if \"function\" or \"class\" is parsed as identifier (in objects e.g.), which should not happen here.\n    this.next(); // eat `function`\n\n    if (this.prodParam.hasYield && this.match(tt.dot)) {\n      const meta = this.createIdentifier(\n        this.startNodeAtNode<N.Identifier>(node),\n        \"function\",\n      );\n      this.next(); // eat `.`\n      // https://github.com/tc39/proposal-function.sent#syntax-1\n      if (this.match(tt._sent)) {\n        this.expectPlugin(\"functionSent\");\n      } else if (!this.hasPlugin(\"functionSent\")) {\n        // The code wasn't `function.sent` but just `function.`, so a simple error is less confusing.\n        this.unexpected();\n      }\n      return this.parseMetaProperty(\n        node as Undone<N.MetaProperty>,\n        meta,\n        \"sent\",\n      );\n    }\n    return this.parseFunction(node as Undone<N.FunctionExpression>);\n  }\n\n  parseMetaProperty(\n    node: Undone<N.MetaProperty>,\n    meta: N.Identifier,\n    propertyName: string,\n  ): N.MetaProperty {\n    node.meta = meta;\n\n    const containsEsc = this.state.containsEsc;\n\n    node.property = this.parseIdentifier(true);\n\n    if (node.property.name !== propertyName || containsEsc) {\n      this.raise(Errors.UnsupportedMetaProperty, node.property, {\n        target: meta.name,\n        onlyValidPropertyName: propertyName,\n      });\n    }\n\n    return this.finishNode(node, \"MetaProperty\");\n  }\n\n  // https://tc39.es/ecma262/#prod-ImportMeta\n  // https://tc39.es/proposal-source-phase-imports/\n  parseImportMetaPropertyOrPhaseCall(\n    this: Parser,\n    node: Undone<N.MetaProperty | N.ImportExpression>,\n  ): N.MetaProperty | N.ImportExpression {\n    this.next(); // eat `.`\n\n    if (this.isContextual(tt._source) || this.isContextual(tt._defer)) {\n      const isSource = this.isContextual(tt._source);\n\n      this.expectPlugin(\n        isSource ? \"sourcePhaseImports\" : \"deferredImportEvaluation\",\n      );\n      this.next();\n      (node as Undone<N.ImportExpression>).phase = isSource\n        ? \"source\"\n        : \"defer\";\n      return this.parseImportCall(node as Undone<N.ImportExpression>);\n    } else {\n      const id = this.createIdentifierAt(\n        this.startNodeAtNode<N.Identifier>(node),\n        \"import\",\n        this.state.lastTokStartLoc,\n      );\n      if (this.isContextual(tt._meta)) {\n        if (!this.inModule) {\n          this.raise(Errors.ImportMetaOutsideModule, id);\n        }\n        this.sawUnambiguousESM = true;\n      }\n      return this.parseMetaProperty(node as Undone<N.MetaProperty>, id, \"meta\");\n    }\n  }\n\n  parseLiteralAtNode<T extends N.Node>(\n    value: any,\n    type: T[\"type\"],\n    node: any,\n  ): T {\n    this.addExtra(node, \"rawValue\", value);\n    this.addExtra(\n      node,\n      \"raw\",\n      this.input.slice(this.offsetToSourcePos(node.start), this.state.end),\n    );\n    node.value = value;\n    this.next();\n    return this.finishNode<T>(node, type);\n  }\n\n  parseLiteral<T extends N.Node>(value: any, type: T[\"type\"]): T {\n    const node = this.startNode();\n    return this.parseLiteralAtNode(value, type, node);\n  }\n\n  parseStringLiteral(value: any) {\n    return this.parseLiteral<N.StringLiteral>(value, \"StringLiteral\");\n  }\n\n  parseNumericLiteral(value: any) {\n    return this.parseLiteral<N.NumericLiteral>(value, \"NumericLiteral\");\n  }\n\n  parseBigIntLiteral(value: any) {\n    if (process.env.BABEL_8_BREAKING) {\n      let bigInt: bigint | null;\n      try {\n        bigInt = BigInt(value);\n      } catch {\n        // parser supports invalid bigints like `1.0n` or `1e1n` such that it\n        // can throw a recoverable error, but BigInt constructor does not\n        // support them.\n        bigInt = null;\n      }\n      const node = this.parseLiteral<N.BigIntLiteral>(bigInt, \"BigIntLiteral\");\n      return node;\n    } else {\n      return this.parseLiteral<N.BigIntLiteral>(value, \"BigIntLiteral\");\n    }\n  }\n\n  // TODO: Remove this in Babel 8\n  parseDecimalLiteral(value: any) {\n    return this.parseLiteral<N.DecimalLiteral>(value, \"DecimalLiteral\");\n  }\n\n  parseRegExpLiteral(value: {\n    value: any;\n    pattern: string;\n    flags: N.RegExpLiteral[\"flags\"];\n  }) {\n    const node = this.startNode<N.RegExpLiteral>();\n    this.addExtra(\n      node,\n      \"raw\",\n      this.input.slice(this.offsetToSourcePos(node.start), this.state.end),\n    );\n    node.pattern = value.pattern;\n    node.flags = value.flags;\n    this.next();\n    return this.finishNode(node, \"RegExpLiteral\");\n  }\n\n  parseBooleanLiteral(value: boolean) {\n    const node = this.startNode<N.BooleanLiteral>();\n    node.value = value;\n    this.next();\n    return this.finishNode(node, \"BooleanLiteral\");\n  }\n\n  parseNullLiteral() {\n    const node = this.startNode<N.NullLiteral>();\n    this.next();\n    return this.finishNode(node, \"NullLiteral\");\n  }\n\n  // https://tc39.es/ecma262/#prod-CoverParenthesizedExpressionAndArrowParameterList\n  parseParenAndDistinguishExpression(\n    this: Parser,\n    canBeArrow: boolean,\n  ): N.Expression {\n    const startLoc = this.state.startLoc;\n\n    let val;\n    this.next(); // eat `(`\n    this.expressionScope.enter(newArrowHeadScope());\n\n    const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;\n    const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;\n    this.state.maybeInArrowParameters = true;\n    this.state.inFSharpPipelineDirectBody = false;\n\n    const innerStartLoc = this.state.startLoc;\n    const exprList: (\n      | N.Expression\n      | N.RestElement\n      | N.VoidPattern\n      | N.AssignmentPattern\n    )[] = [];\n    const refExpressionErrors = new ExpressionErrors();\n    let first = true;\n    let spreadStartLoc;\n    let optionalCommaStartLoc;\n\n    while (!this.match(tt.parenR)) {\n      if (first) {\n        first = false;\n      } else {\n        this.expect(\n          tt.comma,\n          refExpressionErrors.optionalParametersLoc === null\n            ? null\n            : refExpressionErrors.optionalParametersLoc,\n        );\n        if (this.match(tt.parenR)) {\n          optionalCommaStartLoc = this.state.startLoc;\n          break;\n        }\n      }\n\n      if (this.match(tt.ellipsis)) {\n        const spreadNodeStartLoc = this.state.startLoc;\n        spreadStartLoc = this.state.startLoc;\n        exprList.push(\n          this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc),\n        );\n\n        if (!this.checkCommaAfterRest(charCodes.rightParenthesis)) {\n          break;\n        }\n      } else {\n        exprList.push(\n          this.parseMaybeAssignAllowInOrVoidPattern(\n            tt.parenR,\n            refExpressionErrors,\n            this.parseParenItem,\n          ),\n        );\n      }\n    }\n\n    const innerEndLoc = this.state.lastTokEndLoc;\n    this.expect(tt.parenR);\n\n    this.state.maybeInArrowParameters = oldMaybeInArrowParameters;\n    this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;\n\n    let arrowNode = this.startNodeAt<N.ArrowFunctionExpression>(startLoc);\n    if (\n      canBeArrow &&\n      this.shouldParseArrow(exprList) &&\n      (arrowNode = this.parseArrow(arrowNode))\n    ) {\n      this.checkDestructuringPrivate(refExpressionErrors);\n      this.expressionScope.validateAsPattern();\n      this.expressionScope.exit();\n      this.parseArrowExpression(arrowNode, exprList, false);\n      // @ts-expect-error todo(flow->ts) improve node types\n      return arrowNode;\n    }\n    this.expressionScope.exit();\n\n    if (!exprList.length) {\n      this.unexpected(this.state.lastTokStartLoc);\n    }\n    if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc);\n    if (spreadStartLoc) this.unexpected(spreadStartLoc);\n    this.checkExpressionErrors(refExpressionErrors, true);\n\n    this.toReferencedListDeep(exprList, /* isParenthesizedExpr */ true);\n    if (exprList.length > 1) {\n      val = this.startNodeAt<N.SequenceExpression>(innerStartLoc);\n      val.expressions = exprList as N.Expression[];\n      // finish node at current location so it can pick up comments after `)`\n      this.finishNode(val, \"SequenceExpression\");\n      this.resetEndLocation(val, innerEndLoc);\n    } else {\n      val = exprList[0];\n    }\n\n    return this.wrapParenthesis(\n      startLoc,\n      // @ts-expect-error todo(flow->ts)\n      val,\n    );\n  }\n\n  wrapParenthesis(startLoc: Position, expression: N.Expression): N.Expression {\n    if (!(this.optionFlags & OptionFlags.CreateParenthesizedExpressions)) {\n      this.addExtra(expression, \"parenthesized\", true);\n      this.addExtra(expression, \"parenStart\", startLoc.index);\n\n      this.takeSurroundingComments(\n        expression,\n        startLoc.index,\n        this.state.lastTokEndLoc.index,\n      );\n\n      return expression;\n    }\n\n    const parenExpression =\n      this.startNodeAt<N.ParenthesizedExpression>(startLoc);\n    parenExpression.expression = expression;\n    return this.finishNode(parenExpression, \"ParenthesizedExpression\");\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars -- `params` is used in typescript plugin\n  shouldParseArrow(params: Array<N.Node>): boolean {\n    return !this.canInsertSemicolon();\n  }\n\n  parseArrow(\n    node: Undone<N.ArrowFunctionExpression>,\n  ): Undone<N.ArrowFunctionExpression> | undefined {\n    if (this.eat(tt.arrow)) {\n      return node;\n    }\n  }\n\n  parseParenItem<T extends N.Expression | N.RestElement | N.SpreadElement>(\n    node: T,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    startLoc: Position,\n  ): T | N.TypeCastExpression | N.TsTypeCastExpression {\n    return node;\n  }\n\n  parseNewOrNewTarget(this: Parser): N.NewExpression | N.MetaProperty {\n    const node = this.startNode<N.NewExpression | N.MetaProperty>();\n    this.next();\n    if (this.match(tt.dot)) {\n      // https://tc39.es/ecma262/#prod-NewTarget\n      const meta = this.createIdentifier(\n        this.startNodeAtNode<N.Identifier>(node),\n        \"new\",\n      );\n      this.next();\n      const metaProp = this.parseMetaProperty(\n        node as Undone<N.MetaProperty>,\n        meta,\n        \"target\",\n      );\n\n      if (!this.scope.allowNewTarget) {\n        this.raise(Errors.UnexpectedNewTarget, metaProp);\n      }\n\n      return metaProp;\n    }\n\n    return this.parseNew(node as Undone<N.NewExpression>);\n  }\n\n  // New's precedence is slightly tricky. It must allow its argument to\n  // be a `[]` or dot subscript expression, but not a call — at least,\n  // not without wrapping it in parentheses. Thus, it uses the noCalls\n  // argument to parseSubscripts to prevent it from consuming the\n  // argument list.\n  // https://tc39.es/ecma262/#prod-NewExpression\n  parseNew(this: Parser, node: Undone<N.NewExpression>): N.NewExpression {\n    this.parseNewCallee(node);\n\n    if (this.eat(tt.parenL)) {\n      const args = this.parseExprList(tt.parenR);\n      this.toReferencedList(args);\n      // (parseExprList should be all non-null in this case)\n      node.arguments = args;\n    } else {\n      node.arguments = [];\n    }\n\n    return this.finishNode(node, \"NewExpression\");\n  }\n\n  parseNewCallee(this: Parser, node: Undone<N.NewExpression>): void {\n    const isImport = this.match(tt._import);\n    const callee = this.parseNoCallExpr();\n    node.callee = callee;\n    if (\n      isImport &&\n      (callee.type === \"Import\" || callee.type === \"ImportExpression\")\n    ) {\n      this.raise(Errors.ImportCallNotNewExpression, callee);\n    }\n  }\n\n  // Parse template expression.\n\n  parseTemplateElement(isTagged: boolean): N.TemplateElement {\n    const { start, startLoc, end, value } = this.state;\n    const elemStart = start + 1;\n    const elem = this.startNodeAt<N.TemplateElement>(\n      createPositionWithColumnOffset(startLoc, 1),\n    );\n    if (value === null) {\n      if (!isTagged) {\n        this.raise(\n          Errors.InvalidEscapeSequenceTemplate,\n          // FIXME: Adding 1 is probably wrong.\n          createPositionWithColumnOffset(\n            this.state.firstInvalidTemplateEscapePos,\n            1,\n          ),\n        );\n      }\n    }\n\n    const isTail = this.match(tt.templateTail);\n    const endOffset = isTail ? -1 : -2;\n    const elemEnd = end + endOffset;\n    elem.value = {\n      raw: this.input.slice(elemStart, elemEnd).replace(/\\r\\n?/g, \"\\n\"),\n      cooked: value === null ? null : value.slice(1, endOffset),\n    };\n    elem.tail = isTail;\n    this.next();\n    const finishedNode = this.finishNode(elem, \"TemplateElement\");\n    this.resetEndLocation(\n      finishedNode,\n      createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset),\n    );\n    return finishedNode;\n  }\n\n  // https://tc39.es/ecma262/#prod-TemplateLiteral\n  parseTemplate(this: Parser, isTagged: boolean): N.TemplateLiteral {\n    const node = this.startNode<N.TemplateLiteral>();\n    let curElt = this.parseTemplateElement(isTagged);\n    const quasis = [curElt];\n    const substitutions = [];\n    while (!curElt.tail) {\n      substitutions.push(this.parseTemplateSubstitution());\n      this.readTemplateContinuation();\n      quasis.push((curElt = this.parseTemplateElement(isTagged)));\n    }\n    // Type cast from (N.Expression[] | N.TsType[]). parseTemplateSubstitution\n    // returns consistent results.\n    node.expressions = substitutions as N.Expression[] | N.TsType[];\n    node.quasis = quasis;\n    return this.finishNode(node, \"TemplateLiteral\");\n  }\n\n  // This is overwritten by the TypeScript plugin to parse template types\n  parseTemplateSubstitution(this: Parser): N.Expression | N.TsType {\n    return this.parseExpression();\n  }\n\n  // Parse an object literal, binding pattern, or record.\n\n  parseObjectLike(\n    close: TokenType,\n    isPattern: true,\n    isRecord?: boolean | null,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): N.ObjectPattern;\n  parseObjectLike(\n    close: TokenType,\n    isPattern: false,\n    isRecord?: false | null,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): N.ObjectExpression;\n  parseObjectLike(\n    close: TokenType,\n    isPattern: false,\n    isRecord?: true,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): N.RecordExpression;\n  parseObjectLike<T extends N.ObjectPattern | N.ObjectExpression>(\n    this: Parser,\n    close: TokenType,\n    isPattern: boolean,\n    isRecord?: boolean | null,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): T {\n    if (isRecord) {\n      this.expectPlugin(\"recordAndTuple\");\n    }\n    const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;\n    this.state.inFSharpPipelineDirectBody = false;\n    let sawProto = false;\n    let first = true;\n    const node = this.startNode<\n      N.ObjectExpression | N.ObjectPattern | N.RecordExpression\n    >();\n\n    node.properties = [];\n    this.next();\n\n    while (!this.match(close)) {\n      if (first) {\n        first = false;\n      } else {\n        this.expect(tt.comma);\n        if (this.match(close)) {\n          this.addTrailingCommaExtraToNode(node);\n          break;\n        }\n      }\n\n      let prop;\n      if (isPattern) {\n        prop = this.parseBindingProperty();\n      } else {\n        prop = this.parsePropertyDefinition(refExpressionErrors);\n        sawProto = this.checkProto(\n          prop,\n          isRecord,\n          sawProto,\n          refExpressionErrors,\n        );\n      }\n\n      if (\n        isRecord &&\n        !this.isObjectProperty(prop) &&\n        prop.type !== \"SpreadElement\"\n      ) {\n        this.raise(Errors.InvalidRecordProperty, prop);\n      }\n\n      if (!process.env.BABEL_8_BREAKING) {\n        // @ts-expect-error shorthand may not index prop\n        if (prop.shorthand) {\n          this.addExtra(prop, \"shorthand\", true);\n        }\n      }\n\n      // @ts-expect-error Fixme: refine typings\n      node.properties.push(prop);\n    }\n\n    this.next();\n\n    this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;\n    let type = \"ObjectExpression\";\n    if (isPattern) {\n      type = \"ObjectPattern\";\n    } else if (isRecord) {\n      type = \"RecordExpression\";\n    }\n    // @ts-expect-error type is well defined\n    return this.finishNode(node, type);\n  }\n\n  addTrailingCommaExtraToNode(node: Undone<N.Node>): void {\n    this.addExtra(node, \"trailingComma\", this.state.lastTokStartLoc.index);\n    this.addExtra(node, \"trailingCommaLoc\", this.state.lastTokStartLoc, false);\n  }\n\n  // Check grammar production:\n  //   IdentifierName *_opt PropertyName\n  // It is used in `parsePropertyDefinition` to detect AsyncMethod and Accessors\n  maybeAsyncOrAccessorProp(\n    prop: Undone<N.ObjectProperty>,\n  ): prop is typeof prop & { key: N.Identifier } {\n    return (\n      !prop.computed &&\n      prop.key.type === \"Identifier\" &&\n      (this.isLiteralPropertyName() ||\n        this.match(tt.bracketL) ||\n        this.match(tt.star))\n    );\n  }\n\n  // https://tc39.es/ecma262/#prod-PropertyDefinition\n  parsePropertyDefinition(\n    this: Parser,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): N.ObjectMember | N.SpreadElement {\n    let decorators = [];\n    if (this.match(tt.at)) {\n      if (this.hasPlugin(\"decorators\")) {\n        this.raise(Errors.UnsupportedPropertyDecorator, this.state.startLoc);\n      }\n\n      // we needn't check if decorators (stage 0) plugin is enabled since it's checked by\n      // the call to this.parseDecorator\n      while (this.match(tt.at)) {\n        decorators.push(this.parseDecorator());\n      }\n    }\n\n    const prop = this.startNode<N.ObjectProperty>();\n    let isAsync = false;\n    let isAccessor = false;\n    let startLoc;\n\n    if (this.match(tt.ellipsis)) {\n      if (decorators.length) this.unexpected();\n      return this.parseSpread();\n    }\n\n    if (decorators.length) {\n      prop.decorators = decorators;\n      decorators = [];\n    }\n\n    prop.method = false;\n\n    if (refExpressionErrors) {\n      startLoc = this.state.startLoc;\n    }\n\n    let isGenerator = this.eat(tt.star);\n    this.parsePropertyNamePrefixOperator(prop);\n    const containsEsc = this.state.containsEsc;\n    this.parsePropertyName(prop, refExpressionErrors);\n\n    if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {\n      const { key } = prop;\n      const keyName = key.name;\n      // https://tc39.es/ecma262/#prod-AsyncMethod\n      // https://tc39.es/ecma262/#prod-AsyncGeneratorMethod\n      if (keyName === \"async\" && !this.hasPrecedingLineBreak()) {\n        isAsync = true;\n        this.resetPreviousNodeTrailingComments(key);\n        isGenerator = this.eat(tt.star);\n        this.parsePropertyName(prop);\n      }\n      // get PropertyName[?Yield, ?Await] () { FunctionBody[~Yield, ~Await] }\n      // set PropertyName[?Yield, ?Await] ( PropertySetParameterList ) { FunctionBody[~Yield, ~Await] }\n      if (keyName === \"get\" || keyName === \"set\") {\n        isAccessor = true;\n        this.resetPreviousNodeTrailingComments(key);\n        prop.kind = keyName;\n        if (this.match(tt.star)) {\n          isGenerator = true;\n          this.raise(Errors.AccessorIsGenerator, this.state.curPosition(), {\n            kind: keyName,\n          });\n          this.next();\n        }\n        this.parsePropertyName(prop);\n      }\n    }\n\n    return this.parseObjPropValue(\n      prop,\n      startLoc,\n      isGenerator,\n      isAsync,\n      false /* isPattern */,\n      isAccessor,\n      refExpressionErrors,\n    );\n  }\n\n  getGetterSetterExpectedParamCount(\n    method: N.ObjectMethod | N.ClassMethod,\n  ): number {\n    return method.kind === \"get\" ? 0 : 1;\n  }\n\n  // This exists so we can override within the ESTree plugin\n  getObjectOrClassMethodParams(method: N.ObjectMethod | N.ClassMethod) {\n    return method.params;\n  }\n\n  // get methods aren't allowed to have any parameters\n  // set methods must have exactly 1 parameter which is not a rest parameter\n  checkGetterSetterParams(method: N.ObjectMethod | N.ClassMethod): void {\n    const paramCount = this.getGetterSetterExpectedParamCount(method);\n    const params = this.getObjectOrClassMethodParams(method);\n\n    if (params.length !== paramCount) {\n      this.raise(\n        method.kind === \"get\" ? Errors.BadGetterArity : Errors.BadSetterArity,\n        method,\n      );\n    }\n\n    if (\n      method.kind === \"set\" &&\n      params[params.length - 1]?.type === \"RestElement\"\n    ) {\n      this.raise(Errors.BadSetterRestParameter, method);\n    }\n  }\n\n  // https://tc39.es/ecma262/#prod-MethodDefinition\n  parseObjectMethod(\n    this: Parser,\n    prop: Undone<N.ObjectMethod>,\n    isGenerator: boolean,\n    isAsync: boolean,\n    isPattern: boolean,\n    isAccessor: boolean,\n  ): N.ObjectMethod | undefined | null {\n    if (isAccessor) {\n      // isAccessor implies isAsync: false, isPattern: false, isGenerator: false\n      const finishedProp = this.parseMethod(\n        prop,\n        // This _should_ be false, but with error recovery, we allow it to be\n        // set for informational purposes\n        isGenerator,\n        /* isAsync */ false,\n        /* isConstructor */ false,\n        false,\n        \"ObjectMethod\",\n      );\n      this.checkGetterSetterParams(finishedProp);\n      return finishedProp;\n    }\n\n    if (isAsync || isGenerator || this.match(tt.parenL)) {\n      if (isPattern) this.unexpected();\n      prop.kind = \"method\";\n      prop.method = true;\n      return this.parseMethod(\n        prop,\n        isGenerator,\n        isAsync,\n        /* isConstructor */ false,\n        false,\n        \"ObjectMethod\",\n      );\n    }\n  }\n\n  // if `isPattern` is true, parse https://tc39.es/ecma262/#prod-BindingProperty\n  // else https://tc39.es/ecma262/#prod-PropertyDefinition\n  parseObjectProperty(\n    this: Parser,\n    prop: Undone<N.ObjectProperty>,\n    startLoc: Position | undefined | null,\n    isPattern: boolean,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): N.ObjectProperty | undefined | null {\n    prop.shorthand = false;\n\n    if (this.eat(tt.colon)) {\n      prop.value = isPattern\n        ? this.parseMaybeDefault(this.state.startLoc)\n        : this.parseMaybeAssignAllowInOrVoidPattern(\n            tt.braceR,\n            refExpressionErrors,\n          );\n\n      return this.finishObjectProperty(prop);\n    }\n\n    if (!prop.computed && prop.key.type === \"Identifier\") {\n      // PropertyDefinition:\n      //   IdentifierReference\n      //   CoverInitializedName\n      // Note: `{ eval } = {}` will be checked in `checkLVal` later.\n      this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false);\n\n      if (isPattern) {\n        prop.value = this.parseMaybeDefault(\n          startLoc,\n          this.cloneIdentifier(prop.key),\n        );\n      } else if (this.match(tt.eq)) {\n        const shorthandAssignLoc = this.state.startLoc;\n        if (refExpressionErrors != null) {\n          if (refExpressionErrors.shorthandAssignLoc === null) {\n            refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc;\n          }\n        } else {\n          this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);\n        }\n        prop.value = this.parseMaybeDefault(\n          startLoc,\n          this.cloneIdentifier(prop.key),\n        );\n      } else {\n        prop.value = this.cloneIdentifier(prop.key);\n      }\n      prop.shorthand = true;\n\n      return this.finishObjectProperty(prop);\n    }\n  }\n\n  finishObjectProperty(node: Undone<N.ObjectProperty>) {\n    return this.finishNode(node, \"ObjectProperty\");\n  }\n\n  parseObjPropValue<T extends N.ObjectMember>(\n    this: Parser,\n    prop: Undone<T>,\n    startLoc: Position | undefined | null,\n    isGenerator: boolean,\n    isAsync: boolean,\n    isPattern: boolean,\n    isAccessor: boolean,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): T {\n    const node = (this.parseObjectMethod(\n      prop as Undone<N.ObjectMethod>,\n      isGenerator,\n      isAsync,\n      isPattern,\n      isAccessor,\n    ) ||\n      this.parseObjectProperty(\n        prop as Undone<N.ObjectProperty>,\n        startLoc,\n        isPattern,\n        refExpressionErrors,\n      )) as T;\n\n    if (!node) this.unexpected();\n\n    return node;\n  }\n\n  // https://tc39.es/ecma262/#prod-PropertyName\n  // when refExpressionErrors presents, it will parse private name\n  // and record the position of the first private name\n  parsePropertyName(\n    this: Parser,\n    prop:\n      | Undone<N.ObjectOrClassMember | N.ClassMember>\n      | N.TsNamedTypeElementBase,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): void {\n    if (this.eat(tt.bracketL)) {\n      (prop as Undone<N.ObjectOrClassMember>).computed = true;\n      prop.key = this.parseMaybeAssignAllowIn();\n      this.expect(tt.bracketR);\n    } else {\n      // We check if it's valid for it to be a private name when we push it.\n      const { type, value } = this.state;\n      let key;\n      // most un-computed property names are identifiers\n      if (tokenIsKeywordOrIdentifier(type)) {\n        key = this.parseIdentifier(true);\n      } else {\n        switch (type) {\n          case tt.num:\n            key = this.parseNumericLiteral(value);\n            break;\n          case tt.string:\n            key = this.parseStringLiteral(value);\n            break;\n          case tt.bigint:\n            key = this.parseBigIntLiteral(value);\n            break;\n          case tt.privateName: {\n            // the class private key has been handled in parseClassElementName\n            const privateKeyLoc = this.state.startLoc;\n            if (refExpressionErrors != null) {\n              if (refExpressionErrors.privateKeyLoc === null) {\n                refExpressionErrors.privateKeyLoc = privateKeyLoc;\n              }\n            } else {\n              this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);\n            }\n            key = this.parsePrivateName();\n            break;\n          }\n          default:\n            if (!process.env.BABEL_8_BREAKING && type === tt.decimal) {\n              key = this.parseDecimalLiteral(value);\n              break;\n            }\n\n            this.unexpected();\n        }\n      }\n      (prop as any).key = key;\n      if (type !== tt.privateName) {\n        // ClassPrivateProperty is never computed, so we don't assign in that case.\n        prop.computed = false;\n      }\n    }\n  }\n\n  // Initialize empty function node.\n\n  initFunction(node: N.BodilessFunctionOrMethodBase, isAsync: boolean): void {\n    node.id = null;\n    node.generator = false;\n    node.async = isAsync;\n  }\n\n  // Parse object or class method.\n\n  parseMethod<T extends N.ObjectMethod | N.ClassMethod | N.ClassPrivateMethod>(\n    this: Parser,\n    node: Undone<T>,\n    isGenerator: boolean,\n    isAsync: boolean,\n    isConstructor: boolean,\n    allowDirectSuper: boolean,\n    type: T[\"type\"],\n    inClassScope: boolean = false,\n  ): T {\n    this.initFunction(node, isAsync);\n    node.generator = isGenerator;\n    this.scope.enter(\n      ScopeFlag.FUNCTION |\n        ScopeFlag.SUPER |\n        (inClassScope ? ScopeFlag.CLASS : 0) |\n        (allowDirectSuper ? ScopeFlag.DIRECT_SUPER : 0),\n    );\n    this.prodParam.enter(functionFlags(isAsync, node.generator));\n    this.parseFunctionParams(node, isConstructor);\n    const finishedNode = this.parseFunctionBodyAndFinish(node, type, true);\n    this.prodParam.exit();\n    this.scope.exit();\n\n    return finishedNode;\n  }\n\n  // parse an array literal or tuple literal\n  // https://tc39.es/ecma262/#prod-ArrayLiteral\n  // https://tc39.es/proposal-record-tuple/#prod-TupleLiteral\n  parseArrayLike(\n    this: Parser,\n    close: TokenType,\n    canBePattern: boolean,\n    isTuple: boolean,\n    refExpressionErrors?: ExpressionErrors | null,\n  ): N.ArrayExpression | N.TupleExpression {\n    if (isTuple) {\n      this.expectPlugin(\"recordAndTuple\");\n    }\n    const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;\n    this.state.inFSharpPipelineDirectBody = false;\n    const node = this.startNode<N.ArrayExpression | N.TupleExpression>();\n    this.next();\n    node.elements = this.parseExprList(\n      close,\n      /* allowEmpty */ !isTuple,\n      refExpressionErrors,\n      // @ts-expect-error todo(flow->ts)\n      node,\n    );\n    this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;\n    return this.finishNode(\n      node,\n      isTuple ? \"TupleExpression\" : \"ArrayExpression\",\n    );\n  }\n\n  // Parse arrow function expression.\n  // If the parameters are provided, they will be converted to an\n  // assignable list.\n  parseArrowExpression(\n    this: Parser,\n    node: Undone<N.ArrowFunctionExpression>,\n    params:\n      | Array<\n          N.Expression | N.SpreadElement | N.VoidPattern | N.AssignmentPattern\n        >\n      | Array<\n          N.Expression | N.RestElement | N.VoidPattern | N.AssignmentPattern\n        >,\n    isAsync: boolean,\n    trailingCommaLoc?: Position | null,\n  ): N.ArrowFunctionExpression {\n    this.scope.enter(ScopeFlag.FUNCTION | ScopeFlag.ARROW);\n    let flags = functionFlags(isAsync, false);\n    // ConciseBody[In] :\n    //   [lookahead ≠ {] ExpressionBody[?In, ~Await]\n    //   { FunctionBody[~Yield, ~Await] }\n    if (!this.match(tt.braceL) && this.prodParam.hasIn) {\n      flags |= ParamKind.PARAM_IN;\n    }\n    this.prodParam.enter(flags);\n    this.initFunction(node, isAsync);\n    const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;\n\n    if (params) {\n      this.state.maybeInArrowParameters = true;\n      this.setArrowFunctionParameters(node, params, trailingCommaLoc);\n    }\n    this.state.maybeInArrowParameters = false;\n    this.parseFunctionBody(node, true);\n\n    this.prodParam.exit();\n    this.scope.exit();\n    this.state.maybeInArrowParameters = oldMaybeInArrowParameters;\n\n    return this.finishNode(node, \"ArrowFunctionExpression\");\n  }\n\n  setArrowFunctionParameters(\n    node: Undone<N.ArrowFunctionExpression>,\n    params:\n      | Array<\n          N.Expression | N.SpreadElement | N.VoidPattern | N.AssignmentPattern\n        >\n      | Array<\n          N.Expression | N.RestElement | N.VoidPattern | N.AssignmentPattern\n        >,\n    trailingCommaLoc?: Position | null,\n  ): void {\n    this.toAssignableList(params, trailingCommaLoc, false);\n    node.params = params as (N.Pattern | N.TSParameterProperty)[];\n  }\n\n  parseFunctionBodyAndFinish<\n    T extends\n      | N.Function\n      | N.TSDeclareMethod\n      | N.TSDeclareFunction\n      | N.ClassPrivateMethod,\n  >(node: Undone<T>, type: T[\"type\"], isMethod: boolean = false): T {\n    // @ts-expect-error (node is not bodiless if we get here)\n    this.parseFunctionBody(node, false, isMethod);\n    return this.finishNode(node, type);\n  }\n\n  // Parse function body and check parameters.\n  parseFunctionBody(\n    this: Parser,\n    node: Undone<N.Function>,\n    allowExpression?: boolean | null,\n    isMethod: boolean = false,\n  ): void {\n    const isExpression = allowExpression && !this.match(tt.braceL);\n    this.expressionScope.enter(newExpressionScope());\n\n    if (isExpression) {\n      // https://tc39.es/ecma262/#prod-ExpressionBody\n      (node as Undone<N.ArrowFunctionExpression>).body =\n        this.parseMaybeAssign();\n      this.checkParams(node, false, allowExpression, false);\n    } else {\n      const oldStrict = this.state.strict;\n      // Start a new scope with regard to labels\n      // flag (restore them to their old value afterwards).\n      const oldLabels = this.state.labels;\n      this.state.labels = [];\n\n      // FunctionBody[Yield, Await]:\n      //   StatementList[?Yield, ?Await, +Return] opt\n      this.prodParam.enter(\n        this.prodParam.currentFlags() | ParamKind.PARAM_RETURN,\n      );\n      node.body = this.parseBlock(\n        true,\n        false,\n        // Strict mode function checks after we parse the statements in the function body.\n        (hasStrictModeDirective: boolean) => {\n          const nonSimple = !this.isSimpleParamList(node.params);\n\n          if (hasStrictModeDirective && nonSimple) {\n            // This logic is here to align the error location with the ESTree plugin.\n            this.raise(\n              Errors.IllegalLanguageModeDirective,\n              // @ts-expect-error kind may not index node\n              (node.kind === \"method\" || node.kind === \"constructor\") &&\n                // @ts-expect-error key may not index node\n                !!node.key\n                ? // @ts-expect-error node.key has been guarded\n                  node.key.loc.end\n                : node,\n            );\n          }\n\n          const strictModeChanged = !oldStrict && this.state.strict;\n\n          // Add the params to varDeclaredNames to ensure that an error is thrown\n          // if a let/const declaration in the function clashes with one of the params.\n          this.checkParams(\n            node,\n            !this.state.strict && !allowExpression && !isMethod && !nonSimple,\n            allowExpression,\n            strictModeChanged,\n          );\n\n          // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'\n          if (this.state.strict && node.id) {\n            this.checkIdentifier(\n              node.id,\n              BindingFlag.TYPE_OUTSIDE,\n              strictModeChanged,\n            );\n          }\n        },\n      );\n      this.prodParam.exit();\n      this.state.labels = oldLabels;\n    }\n    this.expressionScope.exit();\n  }\n\n  isSimpleParameter(node: N.Pattern | N.TSParameterProperty): boolean {\n    return node.type === \"Identifier\";\n  }\n\n  isSimpleParamList(\n    params: ReadonlyArray<N.Pattern | N.TSParameterProperty>,\n  ): boolean {\n    for (let i = 0, len = params.length; i < len; i++) {\n      if (!this.isSimpleParameter(params[i])) return false;\n    }\n    return true;\n  }\n\n  checkParams(\n    node: Undone<N.Function>,\n    allowDuplicates: boolean,\n    isArrowFunction?: boolean | null,\n    strictModeChanged: boolean = true,\n  ): void {\n    const checkClashes = !allowDuplicates && new Set<string>();\n    // We create a fake node with the \"ephemeral\" type `FormalParameters`[1]\n    // since we just store an array of parameters. Perhaps someday we can have\n    // something like class FormalParameters extends Array { ... }, which would\n    // also be helpful when traversing this node.\n    //\n    // 1. https://tc39.es/ecma262/#prod-FormalParameters\n    const formalParameters = { type: \"FormalParameters\" } as const;\n    for (const param of node.params) {\n      this.checkLVal(\n        param,\n        formalParameters,\n        BindingFlag.TYPE_VAR,\n        checkClashes,\n        strictModeChanged,\n      );\n    }\n  }\n\n  // Parses a comma-separated list of expressions, and returns them as\n  // an array. `close` is the token type that ends the list, and\n  // `allowEmpty` can be turned on to allow subsequent commas with\n  // nothing in between them to be parsed as `null` (which is needed\n  // for array literals).\n  // https://tc39.es/ecma262/#prod-ElementList\n  parseExprList(\n    this: Parser,\n    close: TokenType,\n    allowEmpty?: boolean,\n    refExpressionErrors?: ExpressionErrors | null,\n    nodeForExtra?: N.Node | null,\n  ): (N.Expression | null)[] {\n    const elts: (N.Expression | null)[] = [];\n    let first = true;\n\n    while (!this.eat(close)) {\n      if (first) {\n        first = false;\n      } else {\n        this.expect(tt.comma);\n        if (this.match(close)) {\n          if (nodeForExtra) {\n            this.addTrailingCommaExtraToNode(nodeForExtra);\n          }\n          this.next();\n          break;\n        }\n      }\n\n      elts.push(this.parseExprListItem(close, allowEmpty, refExpressionErrors));\n    }\n    return elts;\n  }\n\n  parseExprListItem(\n    this: Parser,\n    close: TokenType,\n    allowEmpty?: boolean,\n    refExpressionErrors?: ExpressionErrors | null,\n    allowPlaceholder?: boolean | null,\n  ): N.Expression | null;\n  parseExprListItem(\n    this: Parser,\n    close: TokenType,\n    allowEmpty?: false,\n    refExpressionErrors?: ExpressionErrors | null,\n    allowPlaceholder?: boolean | null,\n  ): N.Expression;\n  parseExprListItem(\n    this: Parser,\n    close: TokenType,\n    allowEmpty?: boolean | null,\n    refExpressionErrors?: ExpressionErrors | null,\n    allowPlaceholder?: boolean | null,\n  ):\n    | N.Expression\n    | N.SpreadElement\n    | N.ArgumentPlaceholder\n    | N.VoidPattern\n    | N.AssignmentPattern\n    | null {\n    let elt;\n    if (this.match(tt.comma)) {\n      if (!allowEmpty) {\n        this.raise(Errors.UnexpectedToken, this.state.curPosition(), {\n          unexpected: \",\",\n        });\n      }\n      elt = null;\n    } else if (this.match(tt.ellipsis)) {\n      const spreadNodeStartLoc = this.state.startLoc;\n\n      elt = this.parseParenItem(\n        this.parseSpread(refExpressionErrors),\n        spreadNodeStartLoc,\n      );\n    } else if (this.match(tt.question)) {\n      this.expectPlugin(\"partialApplication\");\n      if (!allowPlaceholder) {\n        this.raise(Errors.UnexpectedArgumentPlaceholder, this.state.startLoc);\n      }\n      const node = this.startNode<N.ArgumentPlaceholder>();\n      this.next();\n      elt = this.finishNode(node, \"ArgumentPlaceholder\");\n    } else {\n      elt = this.parseMaybeAssignAllowInOrVoidPattern(\n        close,\n        refExpressionErrors,\n        this.parseParenItem,\n      );\n    }\n    return elt;\n  }\n\n  // Parse the next token as an identifier. If `liberal` is true (used\n  // when parsing properties), it will also convert keywords into\n  // identifiers.\n  // This shouldn't be used to parse the keywords of meta properties, since they\n  // are not identifiers and cannot contain escape sequences.\n\n  parseIdentifier(liberal?: boolean): N.Identifier {\n    const node = this.startNode<N.Identifier>();\n    const name = this.parseIdentifierName(liberal);\n\n    return this.createIdentifier(node, name);\n  }\n\n  createIdentifier(node: Undone<N.Identifier>, name: string): N.Identifier {\n    node.name = name;\n    node.loc.identifierName = name;\n\n    return this.finishNode(node, \"Identifier\");\n  }\n\n  createIdentifierAt(\n    node: Undone<N.Identifier>,\n    name: string,\n    endLoc: Position,\n  ): N.Identifier {\n    node.name = name;\n    node.loc.identifierName = name;\n\n    return this.finishNodeAt(node, \"Identifier\", endLoc);\n  }\n\n  parseIdentifierName(liberal?: boolean): string {\n    let name: string;\n\n    const { startLoc, type } = this.state;\n\n    if (tokenIsKeywordOrIdentifier(type)) {\n      name = this.state.value;\n    } else {\n      this.unexpected();\n    }\n\n    const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type);\n\n    if (liberal) {\n      // If the current token is not used as a keyword, set its type to \"tt.name\".\n      // This will prevent this.next() from throwing about unexpected escapes.\n      if (tokenIsKeyword) {\n        this.replaceToken(tt.name);\n      }\n    } else {\n      this.checkReservedWord(name, startLoc, tokenIsKeyword, false);\n    }\n\n    this.next();\n\n    return name;\n  }\n\n  checkReservedWord(\n    word: string,\n    startLoc: Position,\n    checkKeywords: boolean,\n    isBinding: boolean,\n  ): void {\n    // Every JavaScript reserved word is 10 characters or less.\n    if (word.length > 10) {\n      return;\n    }\n    // Most identifiers are not reservedWord-like, they don't need special\n    // treatments afterward, which very likely ends up throwing errors\n    if (!canBeReservedWord(word)) {\n      return;\n    }\n\n    if (checkKeywords && isKeyword(word)) {\n      this.raise(Errors.UnexpectedKeyword, startLoc, {\n        keyword: word,\n      });\n      return;\n    }\n\n    const reservedTest = !this.state.strict\n      ? isReservedWord\n      : isBinding\n        ? isStrictBindReservedWord\n        : isStrictReservedWord;\n\n    if (reservedTest(word, this.inModule)) {\n      this.raise(Errors.UnexpectedReservedWord, startLoc, {\n        reservedWord: word,\n      });\n      return;\n    } else if (word === \"yield\") {\n      if (this.prodParam.hasYield) {\n        this.raise(Errors.YieldBindingIdentifier, startLoc);\n        return;\n      }\n    } else if (word === \"await\") {\n      if (this.prodParam.hasAwait) {\n        this.raise(Errors.AwaitBindingIdentifier, startLoc);\n        return;\n      }\n\n      if (this.scope.inStaticBlock) {\n        this.raise(Errors.AwaitBindingIdentifierInStaticBlock, startLoc);\n        return;\n      }\n\n      this.expressionScope.recordAsyncArrowParametersError(startLoc);\n    } else if (word === \"arguments\") {\n      if (this.scope.inClassAndNotInNonArrowFunction) {\n        this.raise(Errors.ArgumentsInClass, startLoc);\n        return;\n      }\n    }\n  }\n\n  // Returns whether `await` is allowed or not in this context, and if it is\n  // keeps track of it to determine whether a module uses top-level await.\n  recordAwaitIfAllowed(): boolean {\n    const isAwaitAllowed = this.prodParam.hasAwait;\n\n    if (isAwaitAllowed && !this.scope.inFunction) {\n      this.state.hasTopLevelAwait = true;\n    }\n\n    return isAwaitAllowed;\n  }\n\n  // Parses await expression inside async function.\n\n  parseAwait(this: Parser, startLoc: Position): N.AwaitExpression {\n    const node = this.startNodeAt<N.AwaitExpression>(startLoc);\n\n    this.expressionScope.recordParameterInitializerError(\n      Errors.AwaitExpressionFormalParameter,\n      node,\n    );\n\n    if (this.eat(tt.star)) {\n      this.raise(Errors.ObsoleteAwaitStar, node);\n    }\n\n    if (\n      !this.scope.inFunction &&\n      !(this.optionFlags & OptionFlags.AllowAwaitOutsideFunction)\n    ) {\n      if (this.isAmbiguousPrefixOrIdentifier()) {\n        this.ambiguousScriptDifferentAst = true;\n      } else {\n        this.sawUnambiguousESM = true;\n      }\n    }\n\n    if (!this.state.soloAwait) {\n      node.argument = this.parseMaybeUnary(null, true);\n    }\n\n    return this.finishNode(node, \"AwaitExpression\");\n  }\n\n  isAmbiguousPrefixOrIdentifier(): boolean {\n    if (this.hasPrecedingLineBreak()) return true;\n    const { type } = this.state;\n    return (\n      // All the following expressions are ambiguous:\n      //   await + 0, await - 0, await ( 0 ), await [ 0 ], await / 0 /u, await ``, await of []\n      type === tt.plusMin ||\n      type === tt.parenL ||\n      type === tt.bracketL ||\n      tokenIsTemplate(type) ||\n      (type === tt._of && !this.state.containsEsc) ||\n      // Sometimes the tokenizer generates tt.slash for regexps, and this is\n      // handler by parseExprAtom\n      type === tt.regexp ||\n      type === tt.slash ||\n      // This code could be parsed both as a modulo operator or as an intrinsic:\n      //   await %x(0)\n      (this.hasPlugin(\"v8intrinsic\") && type === tt.modulo)\n    );\n  }\n\n  // Parses yield expression inside generator.\n\n  parseYield(this: Parser, startLoc: Position): N.YieldExpression {\n    const node = this.startNodeAt<N.YieldExpression>(startLoc);\n\n    this.expressionScope.recordParameterInitializerError(\n      Errors.YieldInParameter,\n      node,\n    );\n\n    let delegating = false;\n    let argument: N.Expression | null = null;\n    if (!this.hasPrecedingLineBreak()) {\n      delegating = this.eat(tt.star);\n      switch (this.state.type) {\n        case tt.semi:\n        case tt.eof:\n        case tt.braceR:\n        case tt.parenR:\n        case tt.bracketR:\n        case tt.braceBarR:\n        case tt.colon:\n        case tt.comma:\n          // The above is the complete set of tokens that can\n          // follow an AssignmentExpression, and none of them\n          // can start an AssignmentExpression\n          if (!delegating) break;\n        /* fallthrough */\n        default:\n          argument = this.parseMaybeAssign();\n      }\n    }\n    node.delegate = delegating;\n    node.argument = argument;\n    return this.finishNode(node, \"YieldExpression\");\n  }\n\n  // https://tc39.es/ecma262/#prod-ImportCall\n  parseImportCall(\n    this: Parser,\n    node: Undone<N.ImportExpression>,\n  ): N.ImportExpression {\n    this.next(); // eat tt.parenL\n    node.source = this.parseMaybeAssignAllowIn();\n    node.options = null;\n    if (this.eat(tt.comma)) {\n      if (!this.match(tt.parenR)) {\n        node.options = this.parseMaybeAssignAllowIn();\n        if (this.eat(tt.comma)) {\n          this.addTrailingCommaExtraToNode(node.options);\n          if (!this.match(tt.parenR)) {\n            // keep consuming arguments, to then throw ImportCallArity\n            // instead of \"expected )\"\n            do {\n              this.parseMaybeAssignAllowIn();\n            } while (this.eat(tt.comma) && !this.match(tt.parenR));\n\n            this.raise(Errors.ImportCallArity, node);\n          }\n        }\n      } else {\n        this.addTrailingCommaExtraToNode(node.source);\n      }\n    }\n    this.expect(tt.parenR);\n    return this.finishNode(node, \"ImportExpression\");\n  }\n\n  // Validates a pipeline (for any of the pipeline Babylon plugins) at the point\n  // of the infix operator `|>`.\n\n  checkPipelineAtInfixOperator(left: N.Expression, leftStartLoc: Position) {\n    // @ts-expect-error Remove this in Babel 8\n    if (this.hasPlugin([\"pipelineOperator\", { proposal: \"smart\" }])) {\n      if (left.type === \"SequenceExpression\") {\n        // Ensure that the pipeline head is not a comma-delimited\n        // sequence expression.\n        this.raise(Errors.PipelineHeadSequenceExpression, leftStartLoc);\n      }\n    }\n  }\n\n  parseSmartPipelineBodyInStyle(childExpr: N.Expression, startLoc: Position) {\n    if (this.isSimpleReference(childExpr)) {\n      const bodyNode = this.startNodeAt<N.PipelineBareFunction>(startLoc);\n      bodyNode.callee = childExpr;\n      return this.finishNode(bodyNode, \"PipelineBareFunction\");\n    } else {\n      const bodyNode = this.startNodeAt<N.PipelineTopicExpression>(startLoc);\n      this.checkSmartPipeTopicBodyEarlyErrors(startLoc);\n      bodyNode.expression = childExpr;\n      return this.finishNode(bodyNode, \"PipelineTopicExpression\");\n    }\n  }\n\n  isSimpleReference(expression: N.Expression): boolean {\n    switch (expression.type) {\n      case \"MemberExpression\":\n        return (\n          !expression.computed && this.isSimpleReference(expression.object)\n        );\n      case \"Identifier\":\n        return true;\n      default:\n        return false;\n    }\n  }\n\n  // This helper method is to be called immediately\n  // after a topic-style smart-mix pipe body is parsed.\n  // The `startLoc` is the starting position of the pipe body.\n\n  checkSmartPipeTopicBodyEarlyErrors(startLoc: Position): void {\n    // If the following token is invalidly `=>`, then throw a human-friendly error\n    // instead of something like 'Unexpected token, expected \";\"'.\n    // For example, `x => x |> y => #` (assuming `#` is the topic reference)\n    // groups into `x => (x |> y) => #`,\n    // and `(x |> y) => #` is an invalid arrow function.\n    // This is because smart-mix `|>` has tighter precedence than `=>`.\n    if (this.match(tt.arrow)) {\n      throw this.raise(Errors.PipelineBodyNoArrow, this.state.startLoc);\n    }\n\n    // A topic-style smart-mix pipe body must use the topic reference at least once.\n    if (!this.topicReferenceWasUsedInCurrentContext()) {\n      this.raise(Errors.PipelineTopicUnused, startLoc);\n    }\n  }\n\n  // Enable topic references from outer contexts within Hack-style pipe bodies.\n  // The function modifies the parser's topic-context state to enable or disable\n  // the use of topic references.\n  // The function then calls a callback, then resets the parser\n  // to the old topic-context state that it had before the function was called.\n\n  withTopicBindingContext<T>(callback: () => T): T {\n    const outerContextTopicState = this.state.topicContext;\n    this.state.topicContext = {\n      // Enable the use of the primary topic reference.\n      maxNumOfResolvableTopics: 1,\n      // Hide the use of any topic references from outer contexts.\n      maxTopicIndex: null,\n    };\n\n    try {\n      return callback();\n    } finally {\n      this.state.topicContext = outerContextTopicState;\n    }\n  }\n\n  // This helper method is used only with the deprecated smart-mix pipe proposal.\n  // Disables topic references from outer contexts within syntax constructs\n  // such as the bodies of iteration statements.\n  // The function modifies the parser's topic-context state to enable or disable\n  // the use of topic references with the smartPipelines plugin. They then run a\n  // callback, then they reset the parser to the old topic-context state that it\n  // had before the function was called.\n\n  withSmartMixTopicForbiddingContext<T>(callback: () => T): T {\n    // TODO(Babel 8): Remove this method\n\n    if (\n      !process.env.BABEL_8_BREAKING &&\n      // @ts-expect-error Babel 7 only\n      this.hasPlugin([\"pipelineOperator\", { proposal: \"smart\" }])\n    ) {\n      // Reset the parser’s topic context only if the smart-mix pipe proposal is active.\n      const outerContextTopicState = this.state.topicContext;\n      this.state.topicContext = {\n        // Disable the use of the primary topic reference.\n        maxNumOfResolvableTopics: 0,\n        // Hide the use of any topic references from outer contexts.\n        maxTopicIndex: null,\n      };\n\n      try {\n        return callback();\n      } finally {\n        this.state.topicContext = outerContextTopicState;\n      }\n    } else {\n      // If the pipe proposal is \"minimal\"(Babel 7), \"fsharp\", or \"hack\",\n      // or if no pipe proposal is active,\n      // then the callback result is returned\n      // without touching any extra parser state.\n      return callback();\n    }\n  }\n\n  withSoloAwaitPermittingContext<T>(callback: () => T): T {\n    const outerContextSoloAwaitState = this.state.soloAwait;\n    this.state.soloAwait = true;\n\n    try {\n      return callback();\n    } finally {\n      this.state.soloAwait = outerContextSoloAwaitState;\n    }\n  }\n\n  allowInAnd<T>(callback: () => T): T {\n    const flags = this.prodParam.currentFlags();\n    const prodParamToSet = ParamKind.PARAM_IN & ~flags;\n    if (prodParamToSet) {\n      this.prodParam.enter(flags | ParamKind.PARAM_IN);\n      try {\n        return callback();\n      } finally {\n        this.prodParam.exit();\n      }\n    }\n    return callback();\n  }\n\n  disallowInAnd<T>(callback: () => T): T {\n    const flags = this.prodParam.currentFlags();\n    const prodParamToClear = ParamKind.PARAM_IN & flags;\n    if (prodParamToClear) {\n      this.prodParam.enter(flags & ~ParamKind.PARAM_IN);\n      try {\n        return callback();\n      } finally {\n        this.prodParam.exit();\n      }\n    }\n    return callback();\n  }\n\n  // Register the use of a topic reference within the current\n  // topic-binding context.\n  registerTopicReference(): void {\n    this.state.topicContext.maxTopicIndex = 0;\n  }\n\n  topicReferenceIsAllowedInCurrentContext(): boolean {\n    return this.state.topicContext.maxNumOfResolvableTopics >= 1;\n  }\n\n  topicReferenceWasUsedInCurrentContext(): boolean {\n    return (\n      this.state.topicContext.maxTopicIndex != null &&\n      this.state.topicContext.maxTopicIndex >= 0\n    );\n  }\n\n  parseFSharpPipelineBody(this: Parser, prec: number): N.Expression {\n    const startLoc = this.state.startLoc;\n\n    this.state.potentialArrowAt = this.state.start;\n    const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;\n    this.state.inFSharpPipelineDirectBody = true;\n\n    const ret = this.parseExprOp(\n      this.parseMaybeUnaryOrPrivate(),\n      startLoc,\n      prec,\n    );\n\n    this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;\n\n    return ret;\n  }\n\n  // https://github.com/tc39/proposal-js-module-blocks\n  parseModuleExpression(this: Parser): N.ModuleExpression {\n    this.expectPlugin(\"moduleBlocks\");\n    const node = this.startNode<N.ModuleExpression>();\n    this.next(); // eat \"module\"\n    if (!this.match(tt.braceL)) {\n      this.unexpected(null, tt.braceL);\n    }\n    // start program node immediately after `{`\n    const program = this.startNodeAt<N.Program>(this.state.endLoc);\n    this.next(); // eat `{`\n\n    const revertScopes = this.initializeScopes(/** inModule */ true);\n    this.enterInitialScopes();\n\n    try {\n      node.body = this.parseProgram(program, tt.braceR, \"module\");\n    } finally {\n      revertScopes();\n    }\n    return this.finishNode<N.ModuleExpression>(node, \"ModuleExpression\");\n  }\n\n  parseVoidPattern(\n    this: Parser,\n    refExpressionErrors: ExpressionErrors | null,\n  ): N.VoidPattern {\n    this.expectPlugin(\"discardBinding\");\n    const node = this.startNode<N.VoidPattern>();\n    if (refExpressionErrors != null) {\n      refExpressionErrors.voidPatternLoc = this.state.startLoc;\n    }\n    this.next();\n    return this.finishNode(node, \"VoidPattern\");\n  }\n\n  parseMaybeAssignAllowInOrVoidPattern(\n    this: Parser,\n    close: TokenType,\n    refExpressionErrors: ExpressionErrors | null,\n    afterLeftParse?: Function,\n  ) {\n    if (refExpressionErrors != null && this.match(tt._void)) {\n      const nextCode = this.lookaheadCharCode();\n      if (\n        nextCode === charCodes.comma ||\n        nextCode ===\n          (close === tt.bracketR\n            ? charCodes.rightSquareBracket\n            : close === tt.braceR\n              ? charCodes.rightCurlyBrace\n              : charCodes.rightParenthesis) ||\n        nextCode === charCodes.equalsTo\n      ) {\n        // `void = Initializer` is not allowed, here we parse the production as an assignment pattern\n        // so that we can recover from this error\n        return this.parseMaybeDefault(\n          this.state.startLoc,\n          this.parseVoidPattern(refExpressionErrors),\n        );\n      }\n    }\n    return this.parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse);\n  }\n\n  // Used in Flow plugin\n  parsePropertyNamePrefixOperator(\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    prop: Undone<N.ObjectOrClassMember | N.ClassMember>,\n  ): void {}\n}\n","import type * as N from \"../types.ts\";\nimport {\n  tokenIsIdentifier,\n  tokenIsKeywordOrIdentifier,\n  tokenIsLoop,\n  tokenIsTemplate,\n  tt,\n  type TokenType,\n  getExportedToken,\n} from \"../tokenizer/types.ts\";\nimport ExpressionParser from \"./expression.ts\";\nimport { Errors } from \"../parse-error.ts\";\nimport { isIdentifierChar, isIdentifierStart } from \"../util/identifier.ts\";\nimport * as charCodes from \"charcodes\";\nimport {\n  ScopeFlag,\n  ClassElementType,\n  BindingFlag,\n} from \"../util/scopeflags.ts\";\nimport { ExpressionErrors } from \"./util.ts\";\nimport { ParamKind, functionFlags } from \"../util/production-parameter.ts\";\nimport {\n  newExpressionScope,\n  newParameterDeclarationScope,\n} from \"../util/expression-scope.ts\";\nimport { OptionFlags, type SourceType } from \"../options.ts\";\nimport { Token } from \"../tokenizer/index.ts\";\nimport type { Position } from \"../util/location.ts\";\nimport { createPositionWithColumnOffset } from \"../util/location.ts\";\nimport type { Undone } from \"./node.ts\";\nimport type Parser from \"./index.ts\";\nimport { ParseBindingListFlags } from \"./lval.ts\";\nimport { LoopLabelKind } from \"../tokenizer/state.ts\";\n\nconst loopLabel = { kind: LoopLabelKind.Loop } as const,\n  switchLabel = { kind: LoopLabelKind.Switch } as const;\n\nexport const enum ParseFunctionFlag {\n  Expression = 0b0000,\n  Declaration = 0b0001,\n  HangingDeclaration = 0b0010,\n  NullableId = 0b0100,\n  Async = 0b1000,\n}\n\nexport const enum ParseStatementFlag {\n  StatementOnly = 0b0000,\n  AllowImportExport = 0b0001,\n  AllowDeclaration = 0b0010,\n  AllowFunctionDeclaration = 0b0100,\n  AllowLabeledFunction = 0b1000,\n}\n\nconst loneSurrogate = /[\\uD800-\\uDFFF]/u;\n\nconst keywordRelationalOperator = /in(?:stanceof)?/y;\n\n/**\n * Convert tokens for backward Babel 7 compat.\n * tt.privateName => tt.hash + tt.name\n * tt.templateTail => tt.backquote/tt.braceR + tt.template + tt.backquote\n * tt.templateNonTail => tt.backquote/tt.braceR + tt.template + tt.dollarBraceL\n * For performance reasons this routine mutates `tokens`, it is okay\n * here since we execute `parseTopLevel` once for every file.\n */\nfunction babel7CompatTokens(\n  tokens: (Token | N.Comment)[],\n  input: string,\n  startIndex: number,\n) {\n  for (let i = 0; i < tokens.length; i++) {\n    const token = tokens[i];\n    const { type } = token;\n    if (typeof type === \"number\") {\n      if (!process.env.BABEL_8_BREAKING) {\n        if (type === tt.privateName) {\n          const { loc, start, value, end } = token;\n          const hashEndPos = start + 1;\n          const hashEndLoc = createPositionWithColumnOffset(loc.start, 1);\n          tokens.splice(\n            i,\n            1,\n            new Token({\n              // @ts-expect-error: hacky way to create token\n              type: getExportedToken(tt.hash),\n              value: \"#\",\n              start: start,\n              end: hashEndPos,\n              startLoc: loc.start,\n              endLoc: hashEndLoc,\n            }),\n            new Token({\n              // @ts-expect-error: hacky way to create token\n              type: getExportedToken(tt.name),\n              value: value,\n              start: hashEndPos,\n              end: end,\n              startLoc: hashEndLoc,\n              endLoc: loc.end,\n            }),\n          );\n          i++;\n          continue;\n        }\n\n        if (tokenIsTemplate(type)) {\n          const { loc, start, value, end } = token;\n          const backquoteEnd = start + 1;\n          const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1);\n          let startToken;\n          if (input.charCodeAt(start - startIndex) === charCodes.graveAccent) {\n            startToken = new Token({\n              // @ts-expect-error: hacky way to create token\n              type: getExportedToken(tt.backQuote),\n              value: \"`\",\n              start: start,\n              end: backquoteEnd,\n              startLoc: loc.start,\n              endLoc: backquoteEndLoc,\n            });\n          } else {\n            startToken = new Token({\n              // @ts-expect-error: hacky way to create token\n              type: getExportedToken(tt.braceR),\n              value: \"}\",\n              start: start,\n              end: backquoteEnd,\n              startLoc: loc.start,\n              endLoc: backquoteEndLoc,\n            });\n          }\n          let templateValue,\n            templateElementEnd,\n            templateElementEndLoc,\n            endToken;\n          if (type === tt.templateTail) {\n            // ends with '`'\n            templateElementEnd = end - 1;\n            templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1);\n            templateValue = value === null ? null : value.slice(1, -1);\n            endToken = new Token({\n              // @ts-expect-error: hacky way to create token\n              type: getExportedToken(tt.backQuote),\n              value: \"`\",\n              start: templateElementEnd,\n              end: end,\n              startLoc: templateElementEndLoc,\n              endLoc: loc.end,\n            });\n          } else {\n            // ends with `${`\n            templateElementEnd = end - 2;\n            templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2);\n            templateValue = value === null ? null : value.slice(1, -2);\n            endToken = new Token({\n              // @ts-expect-error: hacky way to create token\n              type: getExportedToken(tt.dollarBraceL),\n              value: \"${\",\n              start: templateElementEnd,\n              end: end,\n              startLoc: templateElementEndLoc,\n              endLoc: loc.end,\n            });\n          }\n          tokens.splice(\n            i,\n            1,\n            startToken,\n            new Token({\n              // @ts-expect-error: hacky way to create token\n              type: getExportedToken(tt.template),\n              value: templateValue,\n              start: backquoteEnd,\n              end: templateElementEnd,\n              startLoc: backquoteEndLoc,\n              endLoc: templateElementEndLoc,\n            }),\n            endToken,\n          );\n          i += 2;\n          continue;\n        }\n      }\n      // @ts-expect-error: we manipulate `token` for performance reasons\n      token.type = getExportedToken(type);\n    }\n  }\n  return tokens;\n}\nexport default abstract class StatementParser extends ExpressionParser {\n  // ### Statement parsing\n\n  // Parse a program. Initializes the parser, reads any number of\n  // statements, and wraps them in a Program node.  Optionally takes a\n  // `program` argument.  If present, the statements will be appended\n  // to its body instead of creating a new node.\n\n  parseTopLevel(\n    this: Parser,\n    file: Undone<N.File>,\n    program: Undone<N.Program>,\n  ): N.File {\n    file.program = this.parseProgram(\n      program,\n      tt.eof,\n      this.options.sourceType === \"module\" ? \"module\" : \"script\",\n    );\n    file.comments = this.comments;\n\n    if (this.optionFlags & OptionFlags.Tokens) {\n      file.tokens = babel7CompatTokens(\n        this.tokens,\n        this.input,\n        this.startIndex,\n      );\n    }\n\n    return this.finishNode(file, \"File\");\n  }\n\n  parseProgram(\n    this: Parser,\n    program: Undone<N.Program>,\n    end: TokenType,\n    sourceType: SourceType,\n  ): N.Program {\n    program.sourceType = sourceType;\n    program.interpreter = this.parseInterpreterDirective();\n    this.parseBlockBody(program, true, true, end);\n    if (this.inModule) {\n      if (\n        !(this.optionFlags & OptionFlags.AllowUndeclaredExports) &&\n        this.scope.undefinedExports.size > 0\n      ) {\n        for (const [localName, at] of Array.from(this.scope.undefinedExports)) {\n          this.raise(Errors.ModuleExportUndefined, at, { localName });\n        }\n      }\n      this.addExtra(program, \"topLevelAwait\", this.state.hasTopLevelAwait);\n    }\n    let finishedProgram: N.Program;\n    if (end === tt.eof) {\n      // finish at eof for top level program\n      finishedProgram = this.finishNode(program, \"Program\");\n    } else {\n      // finish immediately before the end token\n      finishedProgram = this.finishNodeAt(\n        program,\n        \"Program\",\n        createPositionWithColumnOffset(this.state.startLoc, -1),\n      );\n    }\n    return finishedProgram;\n  }\n\n  /**\n   * cast a Statement to a Directive. This method mutates input statement.\n   */\n  stmtToDirective(stmt: N.ExpressionStatement): N.Directive {\n    const directive = this.castNodeTo(stmt, \"Directive\");\n\n    const directiveLiteral = this.castNodeTo(\n      stmt.expression,\n      \"DirectiveLiteral\",\n    );\n    const expressionValue = directiveLiteral.value;\n    const raw = this.input.slice(\n      this.offsetToSourcePos(directiveLiteral.start),\n      this.offsetToSourcePos(directiveLiteral.end),\n    );\n    const val = (directiveLiteral.value = raw.slice(1, -1)); // remove quotes\n\n    this.addExtra(directiveLiteral, \"raw\", raw);\n    this.addExtra(directiveLiteral, \"rawValue\", val);\n    this.addExtra(directiveLiteral, \"expressionValue\", expressionValue);\n\n    directive.value = directiveLiteral;\n    delete stmt.expression;\n\n    return directive;\n  }\n\n  parseInterpreterDirective(): N.InterpreterDirective | null {\n    if (!this.match(tt.interpreterDirective)) {\n      return null;\n    }\n\n    const node = this.startNode<N.InterpreterDirective>();\n    node.value = this.state.value;\n    this.next();\n    return this.finishNode(node, \"InterpreterDirective\");\n  }\n\n  isLet(): boolean {\n    if (!this.isContextual(tt._let)) {\n      return false;\n    }\n    return this.hasFollowingBindingAtom();\n  }\n\n  isUsing(): boolean {\n    if (!this.isContextual(tt._using)) {\n      return false;\n    }\n    const next = this.nextTokenInLineStart();\n    const nextCh = this.codePointAtPos(next);\n    return this.chStartsBindingIdentifier(nextCh, next);\n  }\n\n  isForUsing(): boolean {\n    if (!this.isContextual(tt._using)) {\n      return false;\n    }\n    const next = this.nextTokenInLineStart();\n    const nextCh = this.codePointAtPos(next);\n    if (this.isUnparsedContextual(next, \"of\")) {\n      const nextCharAfterOf = this.lookaheadCharCodeSince(next + 2);\n      // `for( using of` must start either a for-lhs-of statement\n      // or a for lexical declaration\n      if (\n        nextCharAfterOf !== charCodes.equalsTo &&\n        nextCharAfterOf !== charCodes.colon &&\n        // recover from `for(using of;...);`\n        nextCharAfterOf !== charCodes.semicolon\n      ) {\n        return false;\n      }\n    }\n    if (\n      this.chStartsBindingIdentifier(nextCh, next) ||\n      this.isUnparsedContextual(next, \"void\")\n    ) {\n      return true;\n    }\n    return false;\n  }\n\n  isAwaitUsing(): boolean {\n    if (!this.isContextual(tt._await)) {\n      return false;\n    }\n    let next = this.nextTokenInLineStart();\n    if (this.isUnparsedContextual(next, \"using\")) {\n      next = this.nextTokenInLineStartSince(next + 5);\n      const nextCh = this.codePointAtPos(next);\n      if (this.chStartsBindingIdentifier(nextCh, next)) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  chStartsBindingIdentifier(ch: number, pos: number) {\n    if (isIdentifierStart(ch)) {\n      keywordRelationalOperator.lastIndex = pos;\n      if (keywordRelationalOperator.test(this.input)) {\n        // We have seen `in` or `instanceof` so far, now check if the identifier\n        // ends here\n        const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);\n        if (!isIdentifierChar(endCh) && endCh !== charCodes.backslash) {\n          return false;\n        }\n      }\n      return true;\n    } else if (ch === charCodes.backslash) {\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  chStartsBindingPattern(ch: number) {\n    return (\n      ch === charCodes.leftSquareBracket || ch === charCodes.leftCurlyBrace\n    );\n  }\n\n  /**\n   * Assuming we have seen a contextual `let` and declaration is allowed, check if it\n   * starts a variable declaration so that it should be interpreted as a keyword.\n   */\n  hasFollowingBindingAtom(): boolean {\n    const next = this.nextTokenStart();\n    const nextCh = this.codePointAtPos(next);\n    return (\n      this.chStartsBindingPattern(nextCh) ||\n      this.chStartsBindingIdentifier(nextCh, next)\n    );\n  }\n\n  /**\n   * Assuming we have seen a contextual `using` and declaration is allowed, check if it\n   * starts a variable declaration in the same line so that it should be interpreted as\n   * a keyword.\n   */\n  hasInLineFollowingBindingIdentifierOrBrace(): boolean {\n    const next = this.nextTokenInLineStart();\n    const nextCh = this.codePointAtPos(next);\n    return (\n      nextCh === charCodes.leftCurlyBrace ||\n      this.chStartsBindingIdentifier(nextCh, next)\n    );\n  }\n\n  allowsUsing(): boolean {\n    return (\n      (this.scope.inModule || !this.scope.inTopLevel) &&\n      !this.scope.inBareCaseStatement\n    );\n  }\n\n  // https://tc39.es/ecma262/#prod-ModuleItem\n  parseModuleItem(this: Parser) {\n    return this.parseStatementLike(\n      ParseStatementFlag.AllowImportExport |\n        ParseStatementFlag.AllowDeclaration |\n        ParseStatementFlag.AllowFunctionDeclaration |\n        // This function is actually also used to parse StatementItems,\n        // which with Annex B enabled allows labeled functions.\n        ParseStatementFlag.AllowLabeledFunction,\n    );\n  }\n\n  // https://tc39.es/ecma262/#prod-StatementListItem\n  parseStatementListItem(this: Parser) {\n    return this.parseStatementLike(\n      ParseStatementFlag.AllowDeclaration |\n        ParseStatementFlag.AllowFunctionDeclaration |\n        (!this.options.annexB || this.state.strict\n          ? 0\n          : ParseStatementFlag.AllowLabeledFunction),\n    );\n  }\n\n  parseStatementOrSloppyAnnexBFunctionDeclaration(\n    this: Parser,\n    allowLabeledFunction: boolean = false,\n  ) {\n    let flags: ParseStatementFlag = ParseStatementFlag.StatementOnly;\n    if (this.options.annexB && !this.state.strict) {\n      flags |= ParseStatementFlag.AllowFunctionDeclaration;\n      if (allowLabeledFunction) {\n        flags |= ParseStatementFlag.AllowLabeledFunction;\n      }\n    }\n    return this.parseStatementLike(flags);\n  }\n\n  // Parse a single statement.\n  //\n  // If expecting a statement and finding a slash operator, parse a\n  // regular expression literal. This is to handle cases like\n  // `if (foo) /blah/.exec(foo)`, where looking at the previous token\n  // does not help.\n  // https://tc39.es/ecma262/#prod-Statement\n  parseStatement(this: Parser) {\n    return this.parseStatementLike(ParseStatementFlag.StatementOnly);\n  }\n\n  // ImportDeclaration and ExportDeclaration are also handled here so we can throw recoverable errors\n  // when they are not at the top level\n  parseStatementLike(\n    this: Parser,\n    flags: ParseStatementFlag,\n  ):\n    | N.Statement\n    | N.Declaration\n    | N.ImportDeclaration\n    | N.ExportDefaultDeclaration\n    | N.ExportNamedDeclaration\n    | N.ExportAllDeclaration {\n    let decorators: N.Decorator[] | null = null;\n\n    if (this.match(tt.at)) {\n      decorators = this.parseDecorators(true);\n    }\n    return this.parseStatementContent(flags, decorators);\n  }\n\n  parseStatementContent(\n    this: Parser,\n    flags: ParseStatementFlag,\n    decorators?: N.Decorator[] | null,\n  ): N.Statement {\n    const startType = this.state.type;\n    const node = this.startNode();\n    const allowDeclaration = !!(flags & ParseStatementFlag.AllowDeclaration);\n    const allowFunctionDeclaration = !!(\n      flags & ParseStatementFlag.AllowFunctionDeclaration\n    );\n    const topLevel = flags & ParseStatementFlag.AllowImportExport;\n\n    // Most types of statements are recognized by the keyword they\n    // start with. Many are trivial to parse, some require a bit of\n    // complexity.\n\n    switch (startType) {\n      case tt._break:\n        return this.parseBreakContinueStatement(node, /* isBreak */ true);\n      case tt._continue:\n        return this.parseBreakContinueStatement(node, /* isBreak */ false);\n      case tt._debugger:\n        return this.parseDebuggerStatement(node as Undone<N.DebuggerStatement>);\n      case tt._do:\n        return this.parseDoWhileStatement(node as Undone<N.DoWhileStatement>);\n      case tt._for:\n        return this.parseForStatement(node as Undone<N.ForStatement>);\n      case tt._function:\n        if (this.lookaheadCharCode() === charCodes.dot) break;\n        if (!allowFunctionDeclaration) {\n          this.raise(\n            this.state.strict\n              ? Errors.StrictFunction\n              : this.options.annexB\n                ? Errors.SloppyFunctionAnnexB\n                : Errors.SloppyFunction,\n            this.state.startLoc,\n          );\n        }\n        return this.parseFunctionStatement(\n          node as Undone<N.FunctionDeclaration>,\n          false,\n          !allowDeclaration && allowFunctionDeclaration,\n        );\n      case tt._class:\n        if (!allowDeclaration) this.unexpected();\n        return this.parseClass(\n          this.maybeTakeDecorators(\n            decorators,\n            node as Undone<N.ClassDeclaration>,\n          ),\n          true,\n        );\n\n      case tt._if:\n        return this.parseIfStatement(node as Undone<N.IfStatement>);\n      case tt._return:\n        return this.parseReturnStatement(node as Undone<N.ReturnStatement>);\n      case tt._switch:\n        return this.parseSwitchStatement(node as Undone<N.SwitchStatement>);\n      case tt._throw:\n        return this.parseThrowStatement(node as Undone<N.ThrowStatement>);\n      case tt._try:\n        return this.parseTryStatement(node as Undone<N.TryStatement>);\n\n      case tt._await:\n        // [+Await] await [no LineTerminator here] using [no LineTerminator here] BindingList[+Using]\n        if (this.isAwaitUsing()) {\n          if (!this.allowsUsing()) {\n            this.raise(Errors.UnexpectedUsingDeclaration, node);\n          } else if (!allowDeclaration) {\n            this.raise(Errors.UnexpectedLexicalDeclaration, node);\n          } else if (!this.recordAwaitIfAllowed()) {\n            this.raise(Errors.AwaitUsingNotInAsyncContext, node);\n          }\n          this.next(); // eat 'await'\n          return this.parseVarStatement(\n            node as Undone<N.VariableDeclaration>,\n            \"await using\",\n          );\n        }\n        break;\n      case tt._using:\n        // using [no LineTerminator here] BindingList[+Using]\n        if (\n          this.state.containsEsc ||\n          !this.hasInLineFollowingBindingIdentifierOrBrace()\n        ) {\n          break;\n        }\n        if (!this.allowsUsing()) {\n          this.raise(Errors.UnexpectedUsingDeclaration, this.state.startLoc);\n        } else if (!allowDeclaration) {\n          this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);\n        }\n        return this.parseVarStatement(\n          node as Undone<N.VariableDeclaration>,\n          \"using\",\n        );\n      case tt._let: {\n        if (this.state.containsEsc) {\n          break;\n        }\n        // `let [` is an explicit negative lookahead for\n        // ExpressionStatement, so special-case it first.\n        const next = this.nextTokenStart();\n        const nextCh = this.codePointAtPos(next);\n        if (nextCh !== charCodes.leftSquareBracket) {\n          if (!allowDeclaration && this.hasFollowingLineBreak()) break;\n          if (\n            !this.chStartsBindingIdentifier(nextCh, next) &&\n            nextCh !== charCodes.leftCurlyBrace\n          ) {\n            break;\n          }\n        }\n      }\n      // fall through\n      case tt._const: {\n        if (!allowDeclaration) {\n          this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);\n        }\n      }\n      // fall through\n      case tt._var: {\n        const kind = this.state.value;\n        return this.parseVarStatement(\n          node as Undone<N.VariableDeclaration>,\n          kind,\n        );\n      }\n      case tt._while:\n        return this.parseWhileStatement(node as Undone<N.WhileStatement>);\n      case tt._with:\n        return this.parseWithStatement(node as Undone<N.WithStatement>);\n      case tt.braceL:\n        return this.parseBlock();\n      case tt.semi:\n        return this.parseEmptyStatement(node as Undone<N.EmptyStatement>);\n      case tt._import: {\n        const nextTokenCharCode = this.lookaheadCharCode();\n        if (\n          nextTokenCharCode === charCodes.leftParenthesis || // import()\n          nextTokenCharCode === charCodes.dot // import.meta\n        ) {\n          break;\n        }\n      }\n      // fall through\n      case tt._export: {\n        if (\n          !(this.optionFlags & OptionFlags.AllowImportExportEverywhere) &&\n          !topLevel\n        ) {\n          this.raise(Errors.UnexpectedImportExport, this.state.startLoc);\n        }\n\n        this.next(); // eat `import`/`export`\n\n        let result;\n        if (startType === tt._import) {\n          result = this.parseImport(node as Undone<N.ImportDeclaration>);\n        } else {\n          result = this.parseExport(\n            node as Undone<\n              | N.ExportAllDeclaration\n              | N.ExportDefaultDeclaration\n              | N.ExportNamedDeclaration\n            >,\n            decorators,\n          );\n        }\n\n        this.assertModuleNodeAllowed(result);\n\n        return result;\n      }\n\n      default: {\n        if (this.isAsyncFunction()) {\n          if (!allowDeclaration) {\n            this.raise(\n              Errors.AsyncFunctionInSingleStatementContext,\n              this.state.startLoc,\n            );\n          }\n          this.next(); // eat 'async'\n          return this.parseFunctionStatement(\n            node as Undone<N.FunctionDeclaration>,\n            true,\n            !allowDeclaration && allowFunctionDeclaration,\n          );\n        }\n      }\n    }\n\n    // If the statement does not start with a statement keyword or a\n    // brace, it's an ExpressionStatement or LabeledStatement. We\n    // simply start parsing an expression, and afterwards, if the\n    // next token is a colon and the expression was a simple\n    // Identifier node, we switch to interpreting it as a label.\n    const maybeName = this.state.value;\n    const expr = this.parseExpression();\n\n    if (\n      tokenIsIdentifier(startType) &&\n      expr.type === \"Identifier\" &&\n      this.eat(tt.colon)\n    ) {\n      return this.parseLabeledStatement(\n        node as Undone<N.LabeledStatement>,\n        maybeName,\n        expr,\n        flags,\n      );\n    } else {\n      return this.parseExpressionStatement(\n        node as Undone<N.ExpressionStatement>,\n        expr,\n        decorators,\n      );\n    }\n  }\n\n  assertModuleNodeAllowed(node: N.Node): void {\n    if (\n      !(this.optionFlags & OptionFlags.AllowImportExportEverywhere) &&\n      !this.inModule\n    ) {\n      this.raise(Errors.ImportOutsideModule, node);\n    }\n  }\n\n  decoratorsEnabledBeforeExport(): boolean {\n    if (this.hasPlugin(\"decorators-legacy\")) return true;\n    return (\n      this.hasPlugin(\"decorators\") &&\n      this.getPluginOption(\"decorators\", \"decoratorsBeforeExport\") !== false\n    );\n  }\n\n  // Attach the decorators to the given class.\n  // NOTE: This method changes the .start location of the class, and thus\n  // can affect comment attachment. Calling it before or after finalizing\n  // the class node (and thus finalizing its comments) changes how comments\n  // before the `class` keyword or before the final .start location of the\n  // class are attached.\n  maybeTakeDecorators<T extends Undone<N.Class>>(\n    maybeDecorators: N.Decorator[] | null,\n    classNode: T,\n    exportNode?: Undone<N.ExportDefaultDeclaration | N.ExportNamedDeclaration>,\n  ): T {\n    if (maybeDecorators) {\n      if (classNode.decorators?.length) {\n        // Note: decorators attachment is only attempred multiple times\n        // when the class is part of an export declaration.\n        if (\n          typeof this.getPluginOption(\n            \"decorators\",\n            \"decoratorsBeforeExport\",\n          ) !== \"boolean\"\n        ) {\n          // If `decoratorsBeforeExport` was set to `true` or `false`, we\n          // already threw an error about decorators not being in a valid\n          // position.\n          this.raise(\n            Errors.DecoratorsBeforeAfterExport,\n            classNode.decorators[0],\n          );\n        }\n        classNode.decorators.unshift(...maybeDecorators);\n      } else {\n        classNode.decorators = maybeDecorators;\n      }\n      this.resetStartLocationFromNode(classNode, maybeDecorators[0]);\n      if (exportNode) this.resetStartLocationFromNode(exportNode, classNode);\n    }\n    return classNode;\n  }\n\n  canHaveLeadingDecorator(): boolean {\n    return this.match(tt._class);\n  }\n\n  parseDecorators(this: Parser, allowExport?: boolean): N.Decorator[] {\n    const decorators = [];\n    do {\n      decorators.push(this.parseDecorator());\n    } while (this.match(tt.at));\n\n    if (this.match(tt._export)) {\n      if (!allowExport) {\n        this.unexpected();\n      }\n\n      if (!this.decoratorsEnabledBeforeExport()) {\n        this.raise(Errors.DecoratorExportClass, this.state.startLoc);\n      }\n    } else if (!this.canHaveLeadingDecorator()) {\n      throw this.raise(Errors.UnexpectedLeadingDecorator, this.state.startLoc);\n    }\n\n    return decorators;\n  }\n\n  parseDecorator(this: Parser): N.Decorator {\n    this.expectOnePlugin([\"decorators\", \"decorators-legacy\"]);\n\n    const node = this.startNode<N.Decorator>();\n    this.next();\n\n    if (this.hasPlugin(\"decorators\")) {\n      const startLoc = this.state.startLoc;\n      let expr: N.Expression;\n\n      if (this.match(tt.parenL)) {\n        const startLoc = this.state.startLoc;\n        this.next(); // eat '('\n        expr = this.parseExpression();\n        this.expect(tt.parenR);\n        expr = this.wrapParenthesis(startLoc, expr);\n\n        const paramsStartLoc = this.state.startLoc;\n        node.expression = this.parseMaybeDecoratorArguments(expr, startLoc);\n        if (\n          this.getPluginOption(\"decorators\", \"allowCallParenthesized\") ===\n            false &&\n          node.expression !== expr\n        ) {\n          this.raise(\n            Errors.DecoratorArgumentsOutsideParentheses,\n            paramsStartLoc,\n          );\n        }\n      } else {\n        expr = this.parseIdentifier(false);\n\n        while (this.eat(tt.dot)) {\n          const node = this.startNodeAt<N.MemberExpression>(startLoc);\n          node.object = expr;\n          if (this.match(tt.privateName)) {\n            this.classScope.usePrivateName(\n              this.state.value,\n              this.state.startLoc,\n            );\n            node.property = this.parsePrivateName();\n          } else {\n            node.property = this.parseIdentifier(true);\n          }\n          node.computed = false;\n          expr = this.finishNode(node, \"MemberExpression\");\n        }\n\n        node.expression = this.parseMaybeDecoratorArguments(expr, startLoc);\n      }\n    } else {\n      node.expression = this.parseExprSubscripts();\n    }\n    return this.finishNode(node, \"Decorator\");\n  }\n\n  parseMaybeDecoratorArguments(\n    this: Parser,\n    expr: N.Expression,\n    startLoc: Position,\n  ): N.Expression {\n    if (this.eat(tt.parenL)) {\n      const node = this.startNodeAt<N.CallExpression>(startLoc);\n      node.callee = expr;\n      node.arguments = this.parseCallExpressionArguments();\n      this.toReferencedList(node.arguments);\n      return this.finishNode(node, \"CallExpression\");\n    }\n\n    return expr;\n  }\n\n  parseBreakContinueStatement(\n    node: Undone<N.Node>,\n    isBreak: true,\n  ): N.BreakStatement;\n  parseBreakContinueStatement(\n    node: Undone<N.Node>,\n    isBreak: false,\n  ): N.ContinueStatement;\n  parseBreakContinueStatement(\n    node: Undone<N.BreakStatement | N.ContinueStatement>,\n    isBreak: boolean,\n  ): N.BreakStatement | N.ContinueStatement {\n    this.next();\n\n    if (this.isLineTerminator()) {\n      node.label = null;\n    } else {\n      node.label = this.parseIdentifier();\n      this.semicolon();\n    }\n\n    this.verifyBreakContinue(node, isBreak);\n\n    return this.finishNode(\n      node,\n      isBreak ? \"BreakStatement\" : \"ContinueStatement\",\n    );\n  }\n\n  verifyBreakContinue(\n    node: Undone<N.BreakStatement | N.ContinueStatement>,\n    isBreak: boolean,\n  ) {\n    let i;\n    for (i = 0; i < this.state.labels.length; ++i) {\n      const lab = this.state.labels[i];\n      if (node.label == null || lab.name === node.label.name) {\n        if (lab.kind != null && (isBreak || lab.kind === LoopLabelKind.Loop)) {\n          break;\n        }\n        if (node.label && isBreak) break;\n      }\n    }\n    if (i === this.state.labels.length) {\n      const type = isBreak ? \"BreakStatement\" : \"ContinueStatement\";\n      this.raise(Errors.IllegalBreakContinue, node, { type });\n    }\n  }\n\n  parseDebuggerStatement(\n    node: Undone<N.DebuggerStatement>,\n  ): N.DebuggerStatement {\n    this.next();\n    this.semicolon();\n    return this.finishNode(node, \"DebuggerStatement\");\n  }\n\n  parseHeaderExpression(this: Parser): N.Expression {\n    this.expect(tt.parenL);\n    const val = this.parseExpression();\n    this.expect(tt.parenR);\n    return val;\n  }\n\n  // https://tc39.es/ecma262/#prod-DoWhileStatement\n  parseDoWhileStatement(\n    this: Parser,\n    node: Undone<N.DoWhileStatement>,\n  ): N.DoWhileStatement {\n    this.next();\n    this.state.labels.push(loopLabel);\n\n    // Parse the loop body's body.\n    node.body =\n      // For the smartPipelines plugin: Disable topic references from outer\n      // contexts within the loop body. They are permitted in test expressions,\n      // outside of the loop body.\n      this.withSmartMixTopicForbiddingContext(() =>\n        // Parse the loop body's body.\n        this.parseStatement(),\n      );\n\n    this.state.labels.pop();\n\n    this.expect(tt._while);\n    node.test = this.parseHeaderExpression();\n    this.eat(tt.semi);\n    return this.finishNode(node, \"DoWhileStatement\");\n  }\n\n  // Disambiguating between a `for` and a `for`/`in` or `for`/`of`\n  // loop is non-trivial. Basically, we have to parse the init `var`\n  // statement or expression, disallowing the `in` operator (see\n  // the second parameter to `parseExpression`), and then check\n  // whether the next token is `in` or `of`. When there is no init\n  // part (semicolon immediately after the opening parenthesis), it\n  // is a regular `for` loop.\n\n  parseForStatement(\n    this: Parser,\n    node: Undone<N.ForStatement | N.ForInOf>,\n  ): N.ForLike {\n    this.next();\n    this.state.labels.push(loopLabel);\n\n    let awaitAt = null;\n\n    if (this.isContextual(tt._await) && this.recordAwaitIfAllowed()) {\n      awaitAt = this.state.startLoc;\n      this.next();\n    }\n    this.scope.enter(ScopeFlag.OTHER);\n    this.expect(tt.parenL);\n\n    if (this.match(tt.semi)) {\n      if (awaitAt !== null) {\n        this.unexpected(awaitAt);\n      }\n      return this.parseFor(node as Undone<N.ForStatement>, null);\n    }\n\n    const startsWithLet = this.isContextual(tt._let);\n    {\n      const startsWithAwaitUsing = this.isAwaitUsing();\n      const starsWithUsingDeclaration =\n        startsWithAwaitUsing || this.isForUsing();\n      const isLetOrUsing =\n        (startsWithLet && this.hasFollowingBindingAtom()) ||\n        starsWithUsingDeclaration;\n\n      if (this.match(tt._var) || this.match(tt._const) || isLetOrUsing) {\n        const initNode = this.startNode<N.VariableDeclaration>();\n        let kind;\n        if (startsWithAwaitUsing) {\n          kind = \"await using\";\n          if (!this.recordAwaitIfAllowed()) {\n            this.raise(Errors.AwaitUsingNotInAsyncContext, this.state.startLoc);\n          }\n          this.next(); // eat 'await'\n        } else {\n          kind = this.state.value;\n        }\n        this.next();\n        this.parseVar(initNode, true, kind);\n        const init = this.finishNode(initNode, \"VariableDeclaration\");\n\n        const isForIn = this.match(tt._in);\n        if (isForIn && starsWithUsingDeclaration) {\n          this.raise(Errors.ForInUsing, init);\n        }\n        if (\n          (isForIn || this.isContextual(tt._of)) &&\n          init.declarations.length === 1\n        ) {\n          return this.parseForIn(node as Undone<N.ForInOf>, init, awaitAt);\n        }\n        if (awaitAt !== null) {\n          this.unexpected(awaitAt);\n        }\n        return this.parseFor(node as Undone<N.ForStatement>, init);\n      }\n    }\n\n    // Check whether the first token is possibly a contextual keyword, so that\n    // we can forbid `for (async of` if this turns out to be a for-of loop.\n    const startsWithAsync = this.isContextual(tt._async);\n\n    const refExpressionErrors = new ExpressionErrors();\n    const init = this.parseExpression(true, refExpressionErrors);\n    const isForOf = this.isContextual(tt._of);\n    if (isForOf) {\n      // Check for leading tokens that are forbidden in for-of loops:\n      if (startsWithLet) {\n        this.raise(Errors.ForOfLet, init);\n      }\n\n      if (\n        // `for await (async of []);` is allowed.\n        awaitAt === null &&\n        startsWithAsync &&\n        init.type === \"Identifier\"\n      ) {\n        // This catches the case where the `async` in `for (async of` was\n        // parsed as an identifier. If it was parsed as the start of an async\n        // arrow function (e.g. `for (async of => {} of []);`), the LVal check\n        // further down will raise a more appropriate error.\n        this.raise(Errors.ForOfAsync, init);\n      }\n    }\n    if (isForOf || this.match(tt._in)) {\n      this.checkDestructuringPrivate(refExpressionErrors);\n      this.toAssignable(init, /* isLHS */ true);\n      const type = isForOf ? \"ForOfStatement\" : \"ForInStatement\";\n      this.checkLVal(init, { type });\n      return this.parseForIn(\n        node as Undone<N.ForInStatement | N.ForOfStatement>,\n        // @ts-expect-error init has been transformed to an assignable\n        init,\n        awaitAt,\n      );\n    } else {\n      this.checkExpressionErrors(refExpressionErrors, true);\n    }\n    if (awaitAt !== null) {\n      this.unexpected(awaitAt);\n    }\n    return this.parseFor(node as Undone<N.ForStatement>, init);\n  }\n\n  // https://tc39.es/ecma262/#prod-HoistableDeclaration\n  parseFunctionStatement(\n    this: Parser,\n    node: Undone<N.FunctionDeclaration>,\n    isAsync: boolean,\n    isHangingDeclaration: boolean,\n  ): N.FunctionDeclaration {\n    this.next(); // eat 'function'\n    return this.parseFunction(\n      node,\n      ParseFunctionFlag.Declaration |\n        (isHangingDeclaration ? ParseFunctionFlag.HangingDeclaration : 0) |\n        (isAsync ? ParseFunctionFlag.Async : 0),\n    );\n  }\n\n  // https://tc39.es/ecma262/#prod-IfStatement\n  parseIfStatement(this: Parser, node: Undone<N.IfStatement>) {\n    this.next();\n    node.test = this.parseHeaderExpression();\n    // Annex B.3.3\n    // https://tc39.es/ecma262/#sec-functiondeclarations-in-ifstatement-statement-clauses\n    node.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration();\n    node.alternate = this.eat(tt._else)\n      ? this.parseStatementOrSloppyAnnexBFunctionDeclaration()\n      : null;\n    return this.finishNode(node, \"IfStatement\");\n  }\n\n  parseReturnStatement(this: Parser, node: Undone<N.ReturnStatement>) {\n    if (!this.prodParam.hasReturn) {\n      this.raise(Errors.IllegalReturn, this.state.startLoc);\n    }\n\n    this.next();\n\n    // In `return` (and `break`/`continue`), the keywords with\n    // optional arguments, we eagerly look for a semicolon or the\n    // possibility to insert one.\n\n    if (this.isLineTerminator()) {\n      node.argument = null;\n    } else {\n      node.argument = this.parseExpression();\n      this.semicolon();\n    }\n\n    return this.finishNode(node, \"ReturnStatement\");\n  }\n\n  // https://tc39.es/ecma262/#prod-SwitchStatement\n  parseSwitchStatement(this: Parser, node: Undone<N.SwitchStatement>) {\n    this.next();\n    node.discriminant = this.parseHeaderExpression();\n    const cases: N.SwitchStatement[\"cases\"] = (node.cases = []);\n    this.expect(tt.braceL);\n    this.state.labels.push(switchLabel);\n    this.scope.enter(ScopeFlag.SWITCH);\n\n    // Statements under must be grouped (by label) in SwitchCase\n    // nodes. `cur` is used to keep the node that we are currently\n    // adding statements to.\n\n    let cur;\n    for (let sawDefault; !this.match(tt.braceR); ) {\n      if (this.match(tt._case) || this.match(tt._default)) {\n        const isCase = this.match(tt._case);\n        if (cur) this.finishNode(cur, \"SwitchCase\");\n        // @ts-expect-error Fixme\n        cases.push((cur = this.startNode<N.SwitchCase>()));\n        cur.consequent = [];\n        this.next();\n        if (isCase) {\n          cur.test = this.parseExpression();\n        } else {\n          if (sawDefault) {\n            this.raise(\n              Errors.MultipleDefaultsInSwitch,\n              this.state.lastTokStartLoc,\n            );\n          }\n          sawDefault = true;\n          cur.test = null;\n        }\n        this.expect(tt.colon);\n      } else {\n        if (cur) {\n          cur.consequent.push(this.parseStatementListItem());\n        } else {\n          this.unexpected();\n        }\n      }\n    }\n    this.scope.exit();\n    if (cur) this.finishNode(cur, \"SwitchCase\");\n    this.next(); // Closing brace\n    this.state.labels.pop();\n    return this.finishNode(node, \"SwitchStatement\");\n  }\n\n  parseThrowStatement(this: Parser, node: Undone<N.ThrowStatement>) {\n    this.next();\n    if (this.hasPrecedingLineBreak()) {\n      this.raise(Errors.NewlineAfterThrow, this.state.lastTokEndLoc);\n    }\n    node.argument = this.parseExpression();\n    this.semicolon();\n    return this.finishNode(node, \"ThrowStatement\");\n  }\n\n  parseCatchClauseParam(this: Parser): N.Pattern {\n    const param = this.parseBindingAtom();\n\n    this.scope.enter(\n      this.options.annexB && param.type === \"Identifier\"\n        ? ScopeFlag.SIMPLE_CATCH\n        : ScopeFlag.OTHER,\n    );\n    this.checkLVal(\n      param,\n      { type: \"CatchClause\" },\n      BindingFlag.TYPE_CATCH_PARAM,\n    );\n\n    return param;\n  }\n\n  parseTryStatement(\n    this: Parser,\n    node: Undone<N.TryStatement>,\n  ): N.TryStatement {\n    this.next();\n\n    node.block = this.parseBlock();\n    node.handler = null;\n\n    if (this.match(tt._catch)) {\n      const clause = this.startNode<N.CatchClause>();\n      this.next();\n      if (this.match(tt.parenL)) {\n        this.expect(tt.parenL);\n        clause.param = this.parseCatchClauseParam();\n        this.expect(tt.parenR);\n      } else {\n        clause.param = null;\n        this.scope.enter(ScopeFlag.OTHER);\n      }\n\n      // Parse the catch clause's body.\n      clause.body =\n        // For the smartPipelines plugin: Disable topic references from outer\n        // contexts within the catch clause's body.\n        this.withSmartMixTopicForbiddingContext(() =>\n          // Parse the catch clause's body.\n          this.parseBlock(false, false),\n        );\n\n      this.scope.exit();\n      node.handler = this.finishNode(clause, \"CatchClause\");\n    }\n\n    node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null;\n\n    if (!node.handler && !node.finalizer) {\n      this.raise(Errors.NoCatchOrFinally, node);\n    }\n\n    return this.finishNode(node, \"TryStatement\");\n  }\n\n  // https://tc39.es/ecma262/#prod-VariableStatement\n  // https://tc39.es/ecma262/#prod-LexicalDeclaration\n  parseVarStatement(\n    this: Parser,\n    node: Undone<N.VariableDeclaration>,\n    kind: \"var\" | \"let\" | \"const\" | \"using\" | \"await using\",\n    allowMissingInitializer: boolean = false,\n  ): N.VariableDeclaration {\n    this.next();\n    this.parseVar(node, false, kind, allowMissingInitializer);\n    this.semicolon();\n    return this.finishNode(node, \"VariableDeclaration\");\n  }\n\n  // https://tc39.es/ecma262/#prod-WhileStatement\n  parseWhileStatement(\n    this: Parser,\n    node: Undone<N.WhileStatement>,\n  ): N.WhileStatement {\n    this.next();\n    node.test = this.parseHeaderExpression();\n    this.state.labels.push(loopLabel);\n\n    // Parse the loop body.\n    node.body =\n      // For the smartPipelines plugin:\n      // Disable topic references from outer contexts within the loop body.\n      // They are permitted in test expressions, outside of the loop body.\n      this.withSmartMixTopicForbiddingContext(() =>\n        // Parse loop body.\n        this.parseStatement(),\n      );\n\n    this.state.labels.pop();\n\n    return this.finishNode(node, \"WhileStatement\");\n  }\n\n  parseWithStatement(\n    this: Parser,\n    node: Undone<N.WithStatement>,\n  ): N.WithStatement {\n    if (this.state.strict) {\n      this.raise(Errors.StrictWith, this.state.startLoc);\n    }\n    this.next();\n    node.object = this.parseHeaderExpression();\n\n    // Parse the statement body.\n    node.body =\n      // For the smartPipelines plugin:\n      // Disable topic references from outer contexts within the with statement's body.\n      // They are permitted in function default-parameter expressions, which are\n      // part of the outer context, outside of the with statement's body.\n      this.withSmartMixTopicForbiddingContext(() =>\n        // Parse the statement body.\n        this.parseStatement(),\n      );\n\n    return this.finishNode(node, \"WithStatement\");\n  }\n\n  parseEmptyStatement(node: Undone<N.EmptyStatement>): N.EmptyStatement {\n    this.next();\n    return this.finishNode(node, \"EmptyStatement\");\n  }\n\n  // https://tc39.es/ecma262/#prod-LabelledStatement\n  parseLabeledStatement(\n    this: Parser,\n    node: Undone<N.LabeledStatement>,\n    maybeName: string,\n    expr: N.Identifier,\n    flags: ParseStatementFlag,\n  ): N.LabeledStatement {\n    for (const label of this.state.labels) {\n      if (label.name === maybeName) {\n        this.raise(Errors.LabelRedeclaration, expr, {\n          labelName: maybeName,\n        });\n      }\n    }\n\n    const kind = tokenIsLoop(this.state.type)\n      ? LoopLabelKind.Loop\n      : this.match(tt._switch)\n        ? LoopLabelKind.Switch\n        : null;\n    for (let i = this.state.labels.length - 1; i >= 0; i--) {\n      const label = this.state.labels[i];\n      if (label.statementStart === node.start) {\n        label.statementStart = this.sourceToOffsetPos(this.state.start);\n        label.kind = kind;\n      } else {\n        break;\n      }\n    }\n\n    this.state.labels.push({\n      name: maybeName,\n      kind: kind,\n      statementStart: this.sourceToOffsetPos(this.state.start),\n    });\n    // https://tc39.es/ecma262/#prod-LabelledItem\n    node.body =\n      flags & ParseStatementFlag.AllowLabeledFunction\n        ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true)\n        : this.parseStatement();\n\n    this.state.labels.pop();\n    node.label = expr;\n    return this.finishNode(node, \"LabeledStatement\");\n  }\n\n  parseExpressionStatement(\n    node: Undone<N.ExpressionStatement>,\n    expr: N.Expression,\n    /* eslint-disable-next-line @typescript-eslint/no-unused-vars -- used in TypeScript parser */\n    decorators: N.Decorator[] | null,\n  ) {\n    node.expression = expr;\n    this.semicolon();\n    return this.finishNode(node, \"ExpressionStatement\");\n  }\n\n  // Parse a semicolon-enclosed block of statements, handling `\"use\n  // strict\"` declarations when `allowDirectives` is true (used for\n  // function bodies).\n\n  parseBlock(\n    this: Parser,\n    allowDirectives: boolean = false,\n    createNewLexicalScope: boolean = true,\n    afterBlockParse?: (hasStrictModeDirective: boolean) => void,\n  ): N.BlockStatement {\n    const node = this.startNode<N.BlockStatement>();\n    if (allowDirectives) {\n      this.state.strictErrors.clear();\n    }\n    this.expect(tt.braceL);\n    if (createNewLexicalScope) {\n      this.scope.enter(ScopeFlag.OTHER);\n    }\n    this.parseBlockBody(\n      node,\n      allowDirectives,\n      false,\n      tt.braceR,\n      afterBlockParse,\n    );\n    if (createNewLexicalScope) {\n      this.scope.exit();\n    }\n    return this.finishNode(node, \"BlockStatement\");\n  }\n\n  isValidDirective(stmt: N.Statement): stmt is N.ExpressionStatement {\n    return (\n      stmt.type === \"ExpressionStatement\" &&\n      stmt.expression.type === \"StringLiteral\" &&\n      !stmt.expression.extra.parenthesized\n    );\n  }\n\n  parseBlockBody(\n    this: Parser,\n    node: Undone<N.BlockStatementLike>,\n    allowDirectives: boolean | undefined | null,\n    topLevel: boolean,\n    end: TokenType,\n    afterBlockParse?: (hasStrictModeDirective: boolean) => void,\n  ): void {\n    const body: N.BlockStatementLike[\"body\"] = (node.body = []);\n    const directives: N.BlockStatementLike[\"directives\"] = (node.directives =\n      []);\n    this.parseBlockOrModuleBlockBody(\n      body,\n      allowDirectives ? directives : undefined,\n      topLevel,\n      end,\n      afterBlockParse,\n    );\n  }\n\n  // Undefined directives means that directives are not allowed.\n  // https://tc39.es/ecma262/#prod-Block\n  // https://tc39.es/ecma262/#prod-ModuleBody\n  parseBlockOrModuleBlockBody(\n    this: Parser,\n    body: N.Statement[],\n    directives: N.Directive[] | undefined | null,\n    topLevel: boolean,\n    end: TokenType,\n    afterBlockParse?: (hasStrictModeDirective: boolean) => void,\n  ): void {\n    const oldStrict = this.state.strict;\n    let hasStrictModeDirective = false;\n    let parsedNonDirective = false;\n\n    while (!this.match(end)) {\n      const stmt = topLevel\n        ? this.parseModuleItem()\n        : this.parseStatementListItem();\n\n      if (directives && !parsedNonDirective) {\n        if (this.isValidDirective(stmt)) {\n          const directive = this.stmtToDirective(stmt);\n          directives.push(directive);\n\n          if (\n            !hasStrictModeDirective &&\n            directive.value.value === \"use strict\"\n          ) {\n            hasStrictModeDirective = true;\n            this.setStrict(true);\n          }\n\n          continue;\n        }\n        parsedNonDirective = true;\n        // clear strict errors since the strict mode will not change within the block\n        this.state.strictErrors.clear();\n      }\n      body.push(stmt);\n    }\n\n    afterBlockParse?.call(this, hasStrictModeDirective);\n\n    if (!oldStrict) {\n      this.setStrict(false);\n    }\n\n    this.next();\n  }\n\n  // Parse a regular `for` loop. The disambiguation code in\n  // `parseStatement` will already have parsed the init statement or\n  // expression.\n\n  parseFor(\n    this: Parser,\n    node: Undone<N.ForStatement>,\n    init?: N.VariableDeclaration | N.Expression | null,\n  ): N.ForStatement {\n    node.init = init;\n    this.semicolon(/* allowAsi */ false);\n    node.test = this.match(tt.semi) ? null : this.parseExpression();\n    this.semicolon(/* allowAsi */ false);\n    node.update = this.match(tt.parenR) ? null : this.parseExpression();\n    this.expect(tt.parenR);\n\n    // Parse the loop body.\n    node.body =\n      // For the smartPipelines plugin: Disable topic references from outer\n      // contexts within the loop body. They are permitted in test expressions,\n      // outside of the loop body.\n      this.withSmartMixTopicForbiddingContext(() =>\n        // Parse the loop body.\n        this.parseStatement(),\n      );\n\n    this.scope.exit();\n    this.state.labels.pop();\n\n    return this.finishNode(node, \"ForStatement\");\n  }\n\n  // Parse a `for`/`in` and `for`/`of` loop, which are almost\n  // same from parser's perspective.\n\n  parseForIn(\n    this: Parser,\n    node: Undone<N.ForInOf>,\n    init: N.VariableDeclaration | N.AssignmentPattern,\n    awaitAt?: Position | null,\n  ): N.ForInOf {\n    const isForIn = this.match(tt._in);\n    this.next();\n\n    if (isForIn) {\n      if (awaitAt !== null) this.unexpected(awaitAt);\n    } else {\n      node.await = awaitAt !== null;\n    }\n\n    if (\n      init.type === \"VariableDeclaration\" &&\n      init.declarations[0].init != null &&\n      (!isForIn ||\n        !this.options.annexB ||\n        this.state.strict ||\n        init.kind !== \"var\" ||\n        init.declarations[0].id.type !== \"Identifier\")\n    ) {\n      this.raise(Errors.ForInOfLoopInitializer, init, {\n        type: isForIn ? \"ForInStatement\" : \"ForOfStatement\",\n      });\n    }\n\n    if (init.type === \"AssignmentPattern\") {\n      this.raise(Errors.InvalidLhs, init, {\n        ancestor: { type: \"ForStatement\" },\n      });\n    }\n\n    node.left = init;\n    node.right = isForIn\n      ? this.parseExpression()\n      : this.parseMaybeAssignAllowIn();\n    this.expect(tt.parenR);\n\n    // Parse the loop body.\n    node.body =\n      // For the smartPipelines plugin:\n      // Disable topic references from outer contexts within the loop body.\n      // They are permitted in test expressions, outside of the loop body.\n      this.withSmartMixTopicForbiddingContext(() =>\n        // Parse loop body.\n        this.parseStatement(),\n      );\n\n    this.scope.exit();\n    this.state.labels.pop();\n\n    return this.finishNode(node, isForIn ? \"ForInStatement\" : \"ForOfStatement\");\n  }\n\n  // Parse a list of variable declarations.\n\n  parseVar(\n    this: Parser,\n    node: Undone<N.VariableDeclaration>,\n    isFor: boolean,\n    kind: \"var\" | \"let\" | \"const\" | \"using\" | \"await using\",\n    allowMissingInitializer: boolean = false,\n  ): Undone<N.VariableDeclaration> {\n    const declarations: N.VariableDeclarator[] = (node.declarations = []);\n    node.kind = kind;\n    for (;;) {\n      const decl = this.startNode<N.VariableDeclarator>();\n      this.parseVarId(decl, kind);\n      decl.init = !this.eat(tt.eq)\n        ? null\n        : isFor\n          ? this.parseMaybeAssignDisallowIn()\n          : this.parseMaybeAssignAllowIn();\n\n      if (decl.init === null && !allowMissingInitializer) {\n        if (\n          decl.id.type !== \"Identifier\" &&\n          !(isFor && (this.match(tt._in) || this.isContextual(tt._of)))\n        ) {\n          this.raise(\n            Errors.DeclarationMissingInitializer,\n            this.state.lastTokEndLoc,\n            {\n              kind: \"destructuring\",\n            },\n          );\n        } else if (\n          (kind === \"const\" || kind === \"using\" || kind === \"await using\") &&\n          !(this.match(tt._in) || this.isContextual(tt._of))\n        ) {\n          this.raise(\n            Errors.DeclarationMissingInitializer,\n            this.state.lastTokEndLoc,\n            { kind },\n          );\n        }\n      }\n      declarations.push(this.finishNode(decl, \"VariableDeclarator\"));\n      if (!this.eat(tt.comma)) break;\n    }\n    return node;\n  }\n\n  parseVarId(\n    this: Parser,\n    decl: Undone<N.VariableDeclarator>,\n    kind: \"var\" | \"let\" | \"const\" | \"using\" | \"await using\",\n  ): void {\n    const id = this.parseBindingAtom();\n    if (kind === \"using\" || kind === \"await using\") {\n      if (id.type === \"ArrayPattern\" || id.type === \"ObjectPattern\") {\n        this.raise(Errors.UsingDeclarationHasBindingPattern, id.loc.start);\n      }\n    } else {\n      if (id.type === \"VoidPattern\") {\n        this.raise(Errors.UnexpectedVoidPattern, id.loc.start);\n      }\n    }\n    this.checkLVal(\n      id,\n      { type: \"VariableDeclarator\" },\n      kind === \"var\" ? BindingFlag.TYPE_VAR : BindingFlag.TYPE_LEXICAL,\n    );\n    decl.id = id;\n  }\n\n  // https://tc39.es/ecma262/#prod-AsyncFunctionExpression\n  parseAsyncFunctionExpression(\n    this: Parser,\n    node: Undone<N.FunctionExpression>,\n  ): N.FunctionExpression {\n    return this.parseFunction(node, ParseFunctionFlag.Async);\n  }\n\n  // Parse a function declaration or expression (depending on the\n  // ParseFunctionFlag.Declaration flag).\n\n  parseFunction<T extends N.NormalFunction>(\n    this: Parser,\n    node: Undone<T>,\n    flags: ParseFunctionFlag = ParseFunctionFlag.Expression,\n  ): T {\n    const hangingDeclaration = flags & ParseFunctionFlag.HangingDeclaration;\n    const isDeclaration = !!(flags & ParseFunctionFlag.Declaration);\n    const requireId = isDeclaration && !(flags & ParseFunctionFlag.NullableId);\n    const isAsync = !!(flags & ParseFunctionFlag.Async);\n\n    this.initFunction(node, isAsync);\n\n    if (this.match(tt.star)) {\n      if (hangingDeclaration) {\n        this.raise(\n          Errors.GeneratorInSingleStatementContext,\n          this.state.startLoc,\n        );\n      }\n      this.next(); // eat *\n      node.generator = true;\n    }\n\n    if (isDeclaration) {\n      node.id = this.parseFunctionId(requireId);\n    }\n\n    const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;\n    this.state.maybeInArrowParameters = false;\n    this.scope.enter(ScopeFlag.FUNCTION);\n    this.prodParam.enter(functionFlags(isAsync, node.generator));\n\n    if (!isDeclaration) {\n      node.id = this.parseFunctionId();\n    }\n\n    this.parseFunctionParams(node, /* isConstructor */ false);\n\n    // For the smartPipelines plugin: Disable topic references from outer\n    // contexts within the function body. They are permitted in function\n    // default-parameter expressions, outside of the function body.\n    this.withSmartMixTopicForbiddingContext(() => {\n      // Parse the function body.\n      this.parseFunctionBodyAndFinish(\n        node,\n        isDeclaration ? \"FunctionDeclaration\" : \"FunctionExpression\",\n      );\n    });\n\n    this.prodParam.exit();\n    this.scope.exit();\n\n    if (isDeclaration && !hangingDeclaration) {\n      // We need to register this _after_ parsing the function body\n      // because of TypeScript body-less function declarations,\n      // which shouldn't be added to the scope.\n      this.registerFunctionStatementId(node as T);\n    }\n\n    this.state.maybeInArrowParameters = oldMaybeInArrowParameters;\n    return node as T;\n  }\n\n  parseFunctionId(requireId?: boolean): N.Identifier | undefined | null {\n    return requireId || tokenIsIdentifier(this.state.type)\n      ? this.parseIdentifier()\n      : null;\n  }\n\n  parseFunctionParams(\n    this: Parser,\n    node: Undone<N.Function>,\n    isConstructor?: boolean,\n  ): void {\n    this.expect(tt.parenL);\n    this.expressionScope.enter(newParameterDeclarationScope());\n    node.params = this.parseBindingList(\n      tt.parenR,\n      charCodes.rightParenthesis,\n      ParseBindingListFlags.IS_FUNCTION_PARAMS |\n        (isConstructor ? ParseBindingListFlags.IS_CONSTRUCTOR_PARAMS : 0),\n    );\n\n    this.expressionScope.exit();\n  }\n\n  registerFunctionStatementId(node: N.Function): void {\n    if (!node.id) return;\n\n    // If it is a regular function declaration in sloppy mode, then it is\n    // subject to Annex B semantics (BindingFlag.TYPE_FUNCTION). Otherwise, the binding\n    // mode depends on properties of the current scope (see\n    // treatFunctionsAsVar).\n    this.scope.declareName(\n      node.id.name,\n      !this.options.annexB || this.state.strict || node.generator || node.async\n        ? this.scope.treatFunctionsAsVar\n          ? BindingFlag.TYPE_VAR\n          : BindingFlag.TYPE_LEXICAL\n        : BindingFlag.TYPE_FUNCTION,\n      node.id.loc.start,\n    );\n  }\n\n  // Parse a class declaration or literal (depending on the\n  // `isStatement` parameter).\n\n  parseClass<T extends N.Class>(\n    this: Parser,\n    node: Undone<T>,\n    isStatement: /* T === ClassDeclaration */ boolean,\n    optionalId?: boolean,\n  ): T {\n    this.next(); // 'class'\n\n    // A class definition is always strict mode code.\n    const oldStrict = this.state.strict;\n    this.state.strict = true;\n\n    this.parseClassId(node, isStatement, optionalId);\n    this.parseClassSuper(node);\n    // this.state.strict is restored in parseClassBody\n    node.body = this.parseClassBody(!!node.superClass, oldStrict);\n\n    return this.finishNode(\n      node,\n      isStatement ? \"ClassDeclaration\" : \"ClassExpression\",\n    );\n  }\n\n  isClassProperty(): boolean {\n    return this.match(tt.eq) || this.match(tt.semi) || this.match(tt.braceR);\n  }\n\n  isClassMethod(): boolean {\n    return this.match(tt.parenL);\n  }\n\n  nameIsConstructor(key: N.Expression | N.PrivateName): boolean {\n    return (\n      (key.type === \"Identifier\" && key.name === \"constructor\") ||\n      (key.type === \"StringLiteral\" && key.value === \"constructor\")\n    );\n  }\n\n  isNonstaticConstructor(method: N.ClassMethod | N.ClassProperty): boolean {\n    return (\n      !method.computed && !method.static && this.nameIsConstructor(method.key)\n    );\n  }\n\n  // https://tc39.es/ecma262/#prod-ClassBody\n  parseClassBody(\n    this: Parser,\n    hadSuperClass: boolean,\n    oldStrict: boolean,\n  ): N.ClassBody {\n    this.classScope.enter();\n\n    const state: N.ParseClassMemberState = {\n      hadConstructor: false,\n      hadSuperClass,\n    };\n    let decorators: N.Decorator[] = [];\n    const classBody = this.startNode<N.ClassBody>();\n    classBody.body = [];\n\n    this.expect(tt.braceL);\n\n    // For the smartPipelines plugin: Disable topic references from outer\n    // contexts within the class body.\n    this.withSmartMixTopicForbiddingContext(() => {\n      // Parse the contents within the braces.\n      while (!this.match(tt.braceR)) {\n        if (this.eat(tt.semi)) {\n          if (decorators.length > 0) {\n            throw this.raise(\n              Errors.DecoratorSemicolon,\n              this.state.lastTokEndLoc,\n            );\n          }\n          continue;\n        }\n\n        if (this.match(tt.at)) {\n          decorators.push(this.parseDecorator());\n          continue;\n        }\n\n        const member = this.startNode<N.ClassMember>();\n\n        // steal the decorators if there are any\n        if (decorators.length) {\n          // @ts-expect-error Fixme\n          member.decorators = decorators;\n          this.resetStartLocationFromNode(member, decorators[0]);\n          decorators = [];\n        }\n\n        this.parseClassMember(classBody, member, state);\n\n        if (\n          // @ts-expect-error Fixme\n          member.kind === \"constructor\" &&\n          // @ts-expect-error Fixme\n          member.decorators &&\n          // @ts-expect-error Fixme\n          member.decorators.length > 0\n        ) {\n          this.raise(Errors.DecoratorConstructor, member);\n        }\n      }\n    });\n\n    this.state.strict = oldStrict;\n\n    this.next(); // eat `}`\n\n    if (decorators.length) {\n      throw this.raise(Errors.TrailingDecorator, this.state.startLoc);\n    }\n\n    this.classScope.exit();\n\n    return this.finishNode(classBody, \"ClassBody\");\n  }\n\n  // returns true if the current identifier is a method/field name,\n  // false if it is a modifier\n  parseClassMemberFromModifier(\n    this: Parser,\n    classBody: Undone<N.ClassBody>,\n    member: Undone<N.ClassMember>,\n  ): boolean {\n    const key = this.parseIdentifier(true); // eats the modifier\n\n    if (this.isClassMethod()) {\n      const method: N.ClassMethod = member as any;\n\n      // a method named like the modifier\n      method.kind = \"method\";\n      method.computed = false;\n      method.key = key;\n      method.static = false;\n      this.pushClassMethod(\n        classBody,\n        method,\n        false,\n        false,\n        /* isConstructor */ false,\n        false,\n      );\n      return true;\n    } else if (this.isClassProperty()) {\n      const prop: N.ClassProperty = member as any;\n\n      // a property named like the modifier\n      prop.computed = false;\n      prop.key = key;\n      prop.static = false;\n      classBody.body.push(this.parseClassProperty(prop));\n      return true;\n    }\n    this.resetPreviousNodeTrailingComments(key);\n    return false;\n  }\n\n  parseClassMember(\n    this: Parser,\n    classBody: Undone<N.ClassBody>,\n    member: Undone<N.ClassMember>,\n    state: N.ParseClassMemberState,\n  ): void {\n    const isStatic = this.isContextual(tt._static);\n\n    if (isStatic) {\n      if (this.parseClassMemberFromModifier(classBody, member)) {\n        // a class element named 'static'\n        return;\n      }\n      if (this.eat(tt.braceL)) {\n        this.parseClassStaticBlock(classBody, member as any as N.StaticBlock);\n        return;\n      }\n    }\n\n    this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);\n  }\n\n  parseClassMemberWithIsStatic(\n    this: Parser,\n    classBody: Undone<N.ClassBody>,\n    member: Undone<N.ClassMember>,\n    state: N.ParseClassMemberState,\n    isStatic: boolean,\n  ) {\n    const publicMethod = member as N.ClassMethod;\n    const privateMethod = member as N.ClassPrivateMethod;\n    const publicProp = member as N.ClassProperty;\n    const privateProp = member as N.ClassPrivateProperty;\n    const accessorProp = member as N.ClassAccessorProperty;\n\n    const method: typeof publicMethod | typeof privateMethod = publicMethod;\n    const publicMember: typeof publicMethod | typeof publicProp = publicMethod;\n\n    member.static = isStatic;\n    this.parsePropertyNamePrefixOperator(member);\n\n    if (this.eat(tt.star)) {\n      // a generator\n      method.kind = \"method\";\n      const isPrivateName = this.match(tt.privateName);\n      this.parseClassElementName(method);\n      this.parsePostMemberNameModifiers(method);\n\n      if (isPrivateName) {\n        // Private generator method\n        this.pushClassPrivateMethod(classBody, privateMethod, true, false);\n        return;\n      }\n\n      if (this.isNonstaticConstructor(publicMethod)) {\n        this.raise(Errors.ConstructorIsGenerator, publicMethod.key);\n      }\n\n      this.pushClassMethod(\n        classBody,\n        publicMethod,\n        true,\n        false,\n        /* isConstructor */ false,\n        false,\n      );\n\n      return;\n    }\n\n    const isContextual =\n      !this.state.containsEsc && tokenIsIdentifier(this.state.type);\n    const key = this.parseClassElementName(member);\n    const maybeContextualKw = isContextual ? (key as N.Identifier).name : null;\n    const isPrivate = this.isPrivateName(key);\n    const maybeQuestionTokenStartLoc = this.state.startLoc;\n\n    this.parsePostMemberNameModifiers(publicMember);\n\n    if (this.isClassMethod()) {\n      method.kind = \"method\";\n\n      if (isPrivate) {\n        this.pushClassPrivateMethod(classBody, privateMethod, false, false);\n        return;\n      }\n\n      // a normal method\n      const isConstructor = this.isNonstaticConstructor(publicMethod);\n      let allowsDirectSuper = false;\n      if (isConstructor) {\n        publicMethod.kind = \"constructor\";\n\n        // TypeScript allows multiple overloaded constructor declarations.\n        if (state.hadConstructor && !this.hasPlugin(\"typescript\")) {\n          this.raise(Errors.DuplicateConstructor, key);\n        }\n        if (isConstructor && this.hasPlugin(\"typescript\") && member.override) {\n          this.raise(Errors.OverrideOnConstructor, key);\n        }\n        state.hadConstructor = true;\n        allowsDirectSuper = state.hadSuperClass;\n      }\n\n      this.pushClassMethod(\n        classBody,\n        publicMethod,\n        false,\n        false,\n        isConstructor,\n        allowsDirectSuper,\n      );\n    } else if (this.isClassProperty()) {\n      if (isPrivate) {\n        this.pushClassPrivateProperty(classBody, privateProp);\n      } else {\n        this.pushClassProperty(classBody, publicProp);\n      }\n    } else if (maybeContextualKw === \"async\" && !this.isLineTerminator()) {\n      // an async method\n      this.resetPreviousNodeTrailingComments(key);\n      const isGenerator = this.eat(tt.star);\n\n      if (publicMember.optional) {\n        this.unexpected(maybeQuestionTokenStartLoc);\n      }\n\n      method.kind = \"method\";\n      // The so-called parsed name would have been \"async\": get the real name.\n      const isPrivate = this.match(tt.privateName);\n      this.parseClassElementName(method);\n      this.parsePostMemberNameModifiers(publicMember);\n\n      if (isPrivate) {\n        // private async method\n        this.pushClassPrivateMethod(\n          classBody,\n          privateMethod,\n          isGenerator,\n          true,\n        );\n      } else {\n        if (this.isNonstaticConstructor(publicMethod)) {\n          this.raise(Errors.ConstructorIsAsync, publicMethod.key);\n        }\n\n        this.pushClassMethod(\n          classBody,\n          publicMethod,\n          isGenerator,\n          true,\n          /* isConstructor */ false,\n          false,\n        );\n      }\n    } else if (\n      (maybeContextualKw === \"get\" || maybeContextualKw === \"set\") &&\n      !(this.match(tt.star) && this.isLineTerminator())\n    ) {\n      // `get\\n*` is an uninitialized property named 'get' followed by a generator.\n      // a getter or setter\n      this.resetPreviousNodeTrailingComments(key);\n      method.kind = maybeContextualKw;\n      // The so-called parsed name would have been \"get/set\": get the real name.\n      const isPrivate = this.match(tt.privateName);\n      this.parseClassElementName(publicMethod);\n\n      if (isPrivate) {\n        // private getter/setter\n        this.pushClassPrivateMethod(classBody, privateMethod, false, false);\n      } else {\n        if (this.isNonstaticConstructor(publicMethod)) {\n          this.raise(Errors.ConstructorIsAccessor, publicMethod.key);\n        }\n        this.pushClassMethod(\n          classBody,\n          publicMethod,\n          false,\n          false,\n          /* isConstructor */ false,\n          false,\n        );\n      }\n\n      this.checkGetterSetterParams(publicMethod);\n    } else if (maybeContextualKw === \"accessor\" && !this.isLineTerminator()) {\n      this.expectPlugin(\"decoratorAutoAccessors\");\n      this.resetPreviousNodeTrailingComments(key);\n\n      // The so-called parsed name would have been \"accessor\": get the real name.\n      const isPrivate = this.match(tt.privateName);\n      this.parseClassElementName(publicProp);\n      this.pushClassAccessorProperty(classBody, accessorProp, isPrivate);\n    } else if (this.isLineTerminator()) {\n      // an uninitialized class property (due to ASI, since we don't otherwise recognize the next token)\n      if (isPrivate) {\n        this.pushClassPrivateProperty(classBody, privateProp);\n      } else {\n        this.pushClassProperty(classBody, publicProp);\n      }\n    } else {\n      this.unexpected();\n    }\n  }\n\n  // https://tc39.es/ecma262/#prod-ClassElementName\n  parseClassElementName(\n    this: Parser,\n    member: Undone<N.ClassMember>,\n  ): N.Expression | N.Identifier | N.PrivateName {\n    const { type, value } = this.state;\n    if (\n      (type === tt.name || type === tt.string) &&\n      member.static &&\n      value === \"prototype\"\n    ) {\n      this.raise(Errors.StaticPrototype, this.state.startLoc);\n    }\n\n    if (type === tt.privateName) {\n      if (value === \"constructor\") {\n        this.raise(Errors.ConstructorClassPrivateField, this.state.startLoc);\n      }\n      const key = this.parsePrivateName();\n      member.key = key;\n      return key;\n    }\n\n    this.parsePropertyName(member);\n    return member.key;\n  }\n\n  parseClassStaticBlock(\n    this: Parser,\n    classBody: Undone<N.ClassBody>,\n    member: Undone<\n      N.StaticBlock & {\n        decorators?: Array<N.Decorator>;\n      }\n    >,\n  ) {\n    // Start a new lexical scope\n    this.scope.enter(\n      ScopeFlag.CLASS | ScopeFlag.STATIC_BLOCK | ScopeFlag.SUPER,\n    );\n    // Start a new scope with regard to loop labels\n    const oldLabels = this.state.labels;\n    this.state.labels = [];\n    // ClassStaticBlockStatementList:\n    //   StatementList[~Yield, ~Await, ~Return] opt\n    this.prodParam.enter(ParamKind.PARAM);\n    const body: N.Statement[] = (member.body = []);\n    this.parseBlockOrModuleBlockBody(body, undefined, false, tt.braceR);\n    this.prodParam.exit();\n    this.scope.exit();\n    this.state.labels = oldLabels;\n    classBody.body.push(this.finishNode<N.StaticBlock>(member, \"StaticBlock\"));\n    if (member.decorators?.length) {\n      this.raise(Errors.DecoratorStaticBlock, member);\n    }\n  }\n\n  pushClassProperty(\n    this: Parser,\n    classBody: Undone<N.ClassBody>,\n    prop: N.ClassProperty,\n  ) {\n    if (!prop.computed && this.nameIsConstructor(prop.key)) {\n      // Non-computed field, which is either an identifier named \"constructor\"\n      // or a string literal named \"constructor\"\n      this.raise(Errors.ConstructorClassField, prop.key);\n    }\n\n    classBody.body.push(this.parseClassProperty(prop));\n  }\n\n  pushClassPrivateProperty(\n    this: Parser,\n    classBody: Undone<N.ClassBody>,\n    prop: Undone<N.ClassPrivateProperty>,\n  ) {\n    const node = this.parseClassPrivateProperty(prop);\n    classBody.body.push(node);\n\n    this.classScope.declarePrivateName(\n      this.getPrivateNameSV(node.key),\n      ClassElementType.OTHER,\n      node.key.loc.start,\n    );\n  }\n\n  pushClassAccessorProperty(\n    this: Parser,\n    classBody: Undone<N.ClassBody>,\n    prop: N.ClassAccessorProperty,\n    isPrivate: boolean,\n  ) {\n    if (!isPrivate && !prop.computed && this.nameIsConstructor(prop.key)) {\n      // Non-computed field, which is either an identifier named \"constructor\"\n      // or a string literal named \"constructor\"\n      this.raise(Errors.ConstructorClassField, prop.key);\n    }\n\n    const node = this.parseClassAccessorProperty(prop);\n    classBody.body.push(node);\n\n    if (isPrivate) {\n      this.classScope.declarePrivateName(\n        this.getPrivateNameSV(node.key as N.PrivateName),\n        ClassElementType.OTHER,\n        node.key.loc.start,\n      );\n    }\n  }\n\n  pushClassMethod(\n    this: Parser,\n    classBody: Undone<N.ClassBody>,\n    method: Undone<N.ClassMethod>,\n    isGenerator: boolean,\n    isAsync: boolean,\n    isConstructor: boolean,\n    allowsDirectSuper: boolean,\n  ): void {\n    classBody.body.push(\n      this.parseMethod(\n        method,\n        isGenerator,\n        isAsync,\n        isConstructor,\n        allowsDirectSuper,\n        \"ClassMethod\",\n        true,\n      ),\n    );\n  }\n\n  pushClassPrivateMethod(\n    this: Parser,\n    classBody: Undone<N.ClassBody>,\n    method: Undone<N.ClassPrivateMethod>,\n    isGenerator: boolean,\n    isAsync: boolean,\n  ): void {\n    const node = this.parseMethod(\n      method,\n      isGenerator,\n      isAsync,\n      /* isConstructor */ false,\n      false,\n      \"ClassPrivateMethod\",\n      true,\n    );\n    classBody.body.push(node);\n\n    const kind =\n      node.kind === \"get\"\n        ? node.static\n          ? ClassElementType.STATIC_GETTER\n          : ClassElementType.INSTANCE_GETTER\n        : node.kind === \"set\"\n          ? node.static\n            ? ClassElementType.STATIC_SETTER\n            : ClassElementType.INSTANCE_SETTER\n          : ClassElementType.OTHER;\n    this.declareClassPrivateMethodInScope(node, kind);\n  }\n\n  declareClassPrivateMethodInScope(\n    node: Undone<N.ClassPrivateMethod | N.TSDeclareMethod>,\n    kind: number,\n  ) {\n    this.classScope.declarePrivateName(\n      this.getPrivateNameSV(node.key as N.PrivateName),\n      kind,\n      node.key.loc.start,\n    );\n  }\n\n  // Overridden in typescript.js\n  parsePostMemberNameModifiers(\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    methodOrProp: Undone<N.ClassMethod | N.ClassProperty>,\n  ): void {}\n\n  // https://tc39.es/ecma262/#prod-FieldDefinition\n  parseClassPrivateProperty(\n    this: Parser,\n    node: Undone<N.ClassPrivateProperty>,\n  ): N.ClassPrivateProperty {\n    this.parseInitializer(node);\n    this.semicolon();\n    return this.finishNode(node, \"ClassPrivateProperty\");\n  }\n\n  // https://tc39.es/ecma262/#prod-FieldDefinition\n  parseClassProperty(this: Parser, node: N.ClassProperty): N.ClassProperty {\n    this.parseInitializer(node);\n    this.semicolon();\n    return this.finishNode(node, \"ClassProperty\");\n  }\n\n  parseClassAccessorProperty(\n    this: Parser,\n    node: N.ClassAccessorProperty,\n  ): N.ClassAccessorProperty {\n    this.parseInitializer(node);\n    this.semicolon();\n    return this.finishNode(node, \"ClassAccessorProperty\");\n  }\n\n  // https://tc39.es/ecma262/#prod-Initializer\n  parseInitializer(\n    this: Parser,\n    node: Undone<\n      N.ClassProperty | N.ClassPrivateProperty | N.ClassAccessorProperty\n    >,\n  ): void {\n    this.scope.enter(ScopeFlag.CLASS | ScopeFlag.SUPER);\n    this.expressionScope.enter(newExpressionScope());\n    this.prodParam.enter(ParamKind.PARAM);\n    node.value = this.eat(tt.eq) ? this.parseMaybeAssignAllowIn() : null;\n    this.expressionScope.exit();\n    this.prodParam.exit();\n    this.scope.exit();\n  }\n\n  parseClassId(\n    node: Undone<N.Class>,\n    isStatement: boolean,\n    optionalId?: boolean | null,\n    bindingType: BindingFlag = BindingFlag.TYPE_CLASS,\n  ): void {\n    if (tokenIsIdentifier(this.state.type)) {\n      node.id = this.parseIdentifier();\n      if (isStatement) {\n        this.declareNameFromIdentifier(node.id, bindingType);\n      }\n    } else {\n      if (optionalId || !isStatement) {\n        node.id = null;\n      } else {\n        throw this.raise(Errors.MissingClassName, this.state.startLoc);\n      }\n    }\n  }\n\n  // https://tc39.es/ecma262/#prod-ClassHeritage\n  parseClassSuper(this: Parser, node: Undone<N.Class>): void {\n    node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null;\n  }\n\n  // Parses module export declaration.\n  // https://tc39.es/ecma262/#prod-ExportDeclaration\n\n  parseExport(\n    this: Parser,\n    node: Undone<\n      | N.ExportDefaultDeclaration\n      | N.ExportAllDeclaration\n      | N.ExportNamedDeclaration\n    >,\n    decorators: N.Decorator[] | null,\n  ): N.AnyExport {\n    const maybeDefaultIdentifier = this.parseMaybeImportPhase(\n      node,\n      /* isExport */ true,\n    );\n    const hasDefault = this.maybeParseExportDefaultSpecifier(\n      node,\n      maybeDefaultIdentifier,\n    );\n    const parseAfterDefault = !hasDefault || this.eat(tt.comma);\n    const hasStar = parseAfterDefault && this.eatExportStar(node);\n    const hasNamespace =\n      hasStar && this.maybeParseExportNamespaceSpecifier(node);\n    const parseAfterNamespace =\n      parseAfterDefault && (!hasNamespace || this.eat(tt.comma));\n    const isFromRequired = hasDefault || hasStar;\n\n    if (hasStar && !hasNamespace) {\n      if (hasDefault) this.unexpected();\n      if (decorators) {\n        throw this.raise(Errors.UnsupportedDecoratorExport, node);\n      }\n      this.parseExportFrom(node, true);\n\n      this.sawUnambiguousESM = true;\n\n      return this.finishNode(node, \"ExportAllDeclaration\");\n    }\n\n    const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);\n\n    if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) {\n      this.unexpected(null, tt.braceL);\n    }\n\n    if (hasNamespace && parseAfterNamespace) {\n      this.unexpected(null, tt._from);\n    }\n\n    let hasDeclaration;\n    if (isFromRequired || hasSpecifiers) {\n      hasDeclaration = false;\n      if (decorators) {\n        throw this.raise(Errors.UnsupportedDecoratorExport, node);\n      }\n      this.parseExportFrom(\n        node as Undone<N.ExportNamedDeclaration>,\n        isFromRequired,\n      );\n    } else {\n      hasDeclaration = this.maybeParseExportDeclaration(\n        node as Undone<N.ExportNamedDeclaration>,\n      );\n    }\n\n    if (isFromRequired || hasSpecifiers || hasDeclaration) {\n      const node2 = node as Undone<N.ExportNamedDeclaration>;\n      this.checkExport(node2, true, false, !!node2.source);\n      if (node2.declaration?.type === \"ClassDeclaration\") {\n        this.maybeTakeDecorators(decorators, node2.declaration, node2);\n      } else if (decorators) {\n        throw this.raise(Errors.UnsupportedDecoratorExport, node);\n      }\n      this.sawUnambiguousESM = true;\n      return this.finishNode(node2, \"ExportNamedDeclaration\");\n    }\n\n    if (this.eat(tt._default)) {\n      const node2 = node as Undone<N.ExportDefaultDeclaration>;\n      // export default ...\n      const decl = this.parseExportDefaultExpression();\n      node2.declaration = decl;\n\n      if (decl.type === \"ClassDeclaration\") {\n        this.maybeTakeDecorators(decorators, decl as N.ClassDeclaration, node2);\n      } else if (decorators) {\n        throw this.raise(Errors.UnsupportedDecoratorExport, node);\n      }\n\n      this.checkExport(node2, true, true);\n      this.sawUnambiguousESM = true;\n      return this.finishNode(node2, \"ExportDefaultDeclaration\");\n    }\n\n    this.unexpected(null, tt.braceL);\n  }\n\n  eatExportStar(\n    node: Undone<N.Node>,\n  ): node is Undone<N.ExportNamedDeclaration | N.ExportAllDeclaration> {\n    return this.eat(tt.star);\n  }\n\n  maybeParseExportDefaultSpecifier(\n    node: Undone<\n      | N.ExportDefaultDeclaration\n      | N.ExportAllDeclaration\n      | N.ExportNamedDeclaration\n    >,\n    maybeDefaultIdentifier: N.Identifier | null,\n  ): node is Undone<N.ExportNamedDeclaration> {\n    if (maybeDefaultIdentifier || this.isExportDefaultSpecifier()) {\n      // export defaultObj ...\n      this.expectPlugin(\"exportDefaultFrom\", maybeDefaultIdentifier?.loc.start);\n      const id = maybeDefaultIdentifier || this.parseIdentifier(true);\n      const specifier = this.startNodeAtNode<N.ExportDefaultSpecifier>(id);\n      specifier.exported = id;\n      (node as Undone<N.ExportNamedDeclaration>).specifiers = [\n        this.finishNode(specifier, \"ExportDefaultSpecifier\"),\n      ];\n      return true;\n    }\n    return false;\n  }\n\n  maybeParseExportNamespaceSpecifier(\n    node: Undone<N.ExportNamedDeclaration | N.ExportAllDeclaration>,\n  ): node is Undone<N.ExportNamedDeclaration> {\n    if (this.isContextual(tt._as)) {\n      (node as Undone<N.ExportNamedDeclaration>).specifiers ??= [];\n\n      const specifier = this.startNodeAt<N.ExportNamespaceSpecifier>(\n        this.state.lastTokStartLoc,\n      );\n\n      this.next();\n\n      specifier.exported = this.parseModuleExportName();\n      (node as Undone<N.ExportNamedDeclaration>).specifiers.push(\n        this.finishNode(specifier, \"ExportNamespaceSpecifier\"),\n      );\n      return true;\n    }\n    return false;\n  }\n\n  maybeParseExportNamedSpecifiers(\n    node: Undone<N.Node>,\n  ): node is Undone<N.ExportNamedDeclaration> {\n    if (this.match(tt.braceL)) {\n      const node2 = node as Undone<N.ExportNamedDeclaration>;\n\n      if (!node2.specifiers) node2.specifiers = [];\n      const isTypeExport = node2.exportKind === \"type\";\n      node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport));\n      node2.source = null;\n      if (!process.env.BABEL_8_BREAKING && this.hasPlugin(\"importAssertions\")) {\n        node2.assertions = [];\n      } else {\n        node2.attributes = [];\n      }\n      node2.declaration = null;\n      return true;\n    }\n    return false;\n  }\n\n  maybeParseExportDeclaration(\n    this: Parser,\n    node: Undone<N.ExportNamedDeclaration>,\n  ): boolean {\n    if (this.shouldParseExportDeclaration()) {\n      node.specifiers = [];\n      node.source = null;\n      if (!process.env.BABEL_8_BREAKING && this.hasPlugin(\"importAssertions\")) {\n        node.assertions = [];\n      } else {\n        node.attributes = [];\n      }\n      node.declaration = this.parseExportDeclaration(node);\n      return true;\n    }\n    return false;\n  }\n\n  isAsyncFunction(): boolean {\n    if (!this.isContextual(tt._async)) return false;\n    const next = this.nextTokenInLineStart();\n    return this.isUnparsedContextual(next, \"function\");\n  }\n\n  parseExportDefaultExpression(\n    this: Parser,\n  ): N.ExportDefaultDeclaration[\"declaration\"] {\n    const expr = this.startNode();\n\n    if (this.match(tt._function)) {\n      this.next();\n      return this.parseFunction(\n        expr as Undone<N.FunctionDeclaration>,\n        ParseFunctionFlag.Declaration | ParseFunctionFlag.NullableId,\n      );\n    } else if (this.isAsyncFunction()) {\n      this.next(); // eat 'async'\n      this.next(); // eat 'function'\n      return this.parseFunction(\n        expr as Undone<N.FunctionDeclaration>,\n        ParseFunctionFlag.Declaration |\n          ParseFunctionFlag.NullableId |\n          ParseFunctionFlag.Async,\n      );\n    }\n\n    if (this.match(tt._class)) {\n      return this.parseClass(expr as Undone<N.ClassExpression>, true, true);\n    }\n\n    if (this.match(tt.at)) {\n      if (\n        this.hasPlugin(\"decorators\") &&\n        this.getPluginOption(\"decorators\", \"decoratorsBeforeExport\") === true\n      ) {\n        this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);\n      }\n      return this.parseClass(\n        this.maybeTakeDecorators(\n          this.parseDecorators(false),\n          this.startNode<N.ClassDeclaration>(),\n        ),\n        true,\n        true,\n      );\n    }\n\n    if (\n      this.match(tt._const) ||\n      this.match(tt._var) ||\n      this.isLet() ||\n      this.isUsing() ||\n      this.isAwaitUsing()\n    ) {\n      throw this.raise(Errors.UnsupportedDefaultExport, this.state.startLoc);\n    }\n\n    const res = this.parseMaybeAssignAllowIn();\n    this.semicolon();\n    return res;\n  }\n\n  // https://tc39.es/ecma262/#prod-ExportDeclaration\n  parseExportDeclaration(\n    this: Parser,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    node: Undone<N.ExportNamedDeclaration>,\n  ): N.Declaration | undefined | null {\n    if (this.match(tt._class)) {\n      const node = this.parseClass(\n        this.startNode<N.ClassDeclaration>(),\n        true,\n        false,\n      );\n      return node;\n    }\n    return this.parseStatementListItem() as N.Declaration;\n  }\n\n  isExportDefaultSpecifier(): boolean {\n    const { type } = this.state;\n    if (tokenIsIdentifier(type)) {\n      if ((type === tt._async && !this.state.containsEsc) || type === tt._let) {\n        return false;\n      }\n      if (\n        (type === tt._type || type === tt._interface) &&\n        !this.state.containsEsc\n      ) {\n        // If we see any variable name other than `from` after `type` keyword,\n        // we consider it as flow/typescript type exports\n        // note that this approach may fail on some pedantic cases\n        // export type from = number\n        const next = this.nextTokenStart();\n        const nextChar = this.input.charCodeAt(next);\n        if (\n          nextChar === charCodes.leftCurlyBrace ||\n          (this.chStartsBindingIdentifier(nextChar, next) &&\n            !this.input.startsWith(\"from\", next))\n        ) {\n          this.expectOnePlugin([\"flow\", \"typescript\"]);\n          return false;\n        }\n      }\n    } else if (!this.match(tt._default)) {\n      return false;\n    }\n\n    const next = this.nextTokenStart();\n    const hasFrom = this.isUnparsedContextual(next, \"from\");\n    if (\n      this.input.charCodeAt(next) === charCodes.comma ||\n      (tokenIsIdentifier(this.state.type) && hasFrom)\n    ) {\n      return true;\n    }\n    // lookahead again when `export default from` is seen\n    if (this.match(tt._default) && hasFrom) {\n      const nextAfterFrom = this.input.charCodeAt(\n        this.nextTokenStartSince(next + 4),\n      );\n      return (\n        nextAfterFrom === charCodes.quotationMark ||\n        nextAfterFrom === charCodes.apostrophe\n      );\n    }\n    return false;\n  }\n\n  parseExportFrom(\n    this: Parser,\n    node: Undone<N.ExportNamedDeclaration | N.ExportAllDeclaration>,\n    expect?: boolean,\n  ): void {\n    if (this.eatContextual(tt._from)) {\n      node.source = this.parseImportSource();\n      this.checkExport(node);\n      this.maybeParseImportAttributes(node);\n      this.checkJSONModuleImport(node);\n    } else if (expect) {\n      this.unexpected();\n    }\n\n    this.semicolon();\n  }\n\n  shouldParseExportDeclaration(): boolean {\n    const { type } = this.state;\n    if (type === tt.at) {\n      this.expectOnePlugin([\"decorators\", \"decorators-legacy\"]);\n      if (this.hasPlugin(\"decorators\")) {\n        if (\n          this.getPluginOption(\"decorators\", \"decoratorsBeforeExport\") === true\n        ) {\n          this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);\n        }\n\n        return true;\n      }\n    }\n\n    if (this.isUsing()) {\n      this.raise(Errors.UsingDeclarationExport, this.state.startLoc);\n      return true;\n    }\n\n    if (this.isAwaitUsing()) {\n      this.raise(Errors.UsingDeclarationExport, this.state.startLoc);\n      return true;\n    }\n\n    return (\n      type === tt._var ||\n      type === tt._const ||\n      type === tt._function ||\n      type === tt._class ||\n      this.isLet() ||\n      this.isAsyncFunction()\n    );\n  }\n\n  checkExport(\n    node: Undone<\n      | N.ExportNamedDeclaration\n      | N.ExportAllDeclaration\n      | N.ExportDefaultDeclaration\n    >,\n    checkNames?: boolean,\n    isDefault?: boolean,\n    isFrom?: boolean,\n  ): void {\n    if (checkNames) {\n      // Check for duplicate exports\n      if (isDefault) {\n        // Default exports\n        this.checkDuplicateExports(node, \"default\");\n        if (this.hasPlugin(\"exportDefaultFrom\")) {\n          const declaration = (node as any as N.ExportDefaultDeclaration)\n            .declaration;\n          if (\n            declaration.type === \"Identifier\" &&\n            declaration.name === \"from\" &&\n            declaration.end - declaration.start === 4 && // does not contain escape\n            !declaration.extra?.parenthesized\n          ) {\n            this.raise(Errors.ExportDefaultFromAsIdentifier, declaration);\n          }\n        }\n        // @ts-expect-error node.specifiers may not exist\n      } else if (node.specifiers?.length) {\n        // Named exports\n        // @ts-expect-error node.specifiers may not exist\n        for (const specifier of node.specifiers) {\n          const { exported } = specifier;\n          const exportName =\n            exported.type === \"Identifier\" ? exported.name : exported.value;\n          this.checkDuplicateExports(specifier, exportName);\n          if (!isFrom && specifier.local) {\n            const { local } = specifier;\n            if (local.type !== \"Identifier\") {\n              this.raise(Errors.ExportBindingIsString, specifier, {\n                localName: local.value,\n                exportName,\n              });\n            } else {\n              // check for keywords used as local names\n              this.checkReservedWord(local.name, local.loc.start, true, false);\n              // check if export is defined\n              this.scope.checkLocalExport(local);\n            }\n          }\n        }\n      } else if ((node as Undone<N.ExportNamedDeclaration>).declaration) {\n        const decl = (node as Undone<N.ExportNamedDeclaration>).declaration;\n        // Exported declarations\n        if (\n          decl.type === \"FunctionDeclaration\" ||\n          decl.type === \"ClassDeclaration\"\n        ) {\n          const { id } = decl;\n          if (!id) throw new Error(\"Assertion failure\");\n\n          this.checkDuplicateExports(node, id.name);\n        } else if (decl.type === \"VariableDeclaration\") {\n          for (const declaration of decl.declarations) {\n            this.checkDeclaration(declaration.id);\n          }\n        }\n      }\n    }\n  }\n\n  checkDeclaration(node: N.Pattern | N.ObjectProperty): void {\n    if (node.type === \"Identifier\") {\n      this.checkDuplicateExports(node, node.name);\n    } else if (node.type === \"ObjectPattern\") {\n      for (const prop of node.properties) {\n        this.checkDeclaration(prop);\n      }\n    } else if (node.type === \"ArrayPattern\") {\n      for (const elem of node.elements) {\n        if (elem) {\n          this.checkDeclaration(elem);\n        }\n      }\n    } else if (node.type === \"ObjectProperty\") {\n      // @ts-expect-error migrate to Babel types\n      this.checkDeclaration(node.value);\n    } else if (node.type === \"RestElement\") {\n      this.checkDeclaration(node.argument);\n    } else if (node.type === \"AssignmentPattern\") {\n      this.checkDeclaration(node.left);\n    }\n  }\n\n  checkDuplicateExports(\n    node: Undone<\n      | N.Identifier\n      | N.StringLiteral\n      | N.ExportNamedDeclaration\n      | N.ExportSpecifier\n      | N.ExportDefaultSpecifier\n    >,\n    exportName: string,\n  ): void {\n    if (this.exportedIdentifiers.has(exportName)) {\n      if (exportName === \"default\") {\n        this.raise(Errors.DuplicateDefaultExport, node);\n      } else {\n        this.raise(Errors.DuplicateExport, node, { exportName });\n      }\n    }\n    this.exportedIdentifiers.add(exportName);\n  }\n\n  // Parses a comma-separated list of module exports.\n\n  parseExportSpecifiers(isInTypeExport: boolean): Array<N.ExportSpecifier> {\n    const nodes = [];\n    let first = true;\n\n    // export { x, y as z } [from '...']\n    this.expect(tt.braceL);\n\n    while (!this.eat(tt.braceR)) {\n      if (first) {\n        first = false;\n      } else {\n        this.expect(tt.comma);\n        if (this.eat(tt.braceR)) break;\n      }\n      const isMaybeTypeOnly = this.isContextual(tt._type);\n      const isString = this.match(tt.string);\n      const node = this.startNode<N.ExportSpecifier>();\n      node.local = this.parseModuleExportName() as N.Identifier;\n      nodes.push(\n        this.parseExportSpecifier(\n          node,\n          isString,\n          isInTypeExport,\n          isMaybeTypeOnly,\n        ),\n      );\n    }\n\n    return nodes;\n  }\n\n  parseExportSpecifier(\n    node: any,\n    isString: boolean,\n    /* eslint-disable @typescript-eslint/no-unused-vars -- used in TypeScript parser */\n    isInTypeExport: boolean,\n    isMaybeTypeOnly: boolean,\n    /* eslint-enable @typescript-eslint/no-unused-vars */\n  ): N.ExportSpecifier {\n    if (this.eatContextual(tt._as)) {\n      node.exported = this.parseModuleExportName();\n    } else if (isString) {\n      node.exported = this.cloneStringLiteral(node.local);\n    } else if (!node.exported) {\n      node.exported = this.cloneIdentifier(node.local);\n    }\n    return this.finishNode<N.ExportSpecifier>(node, \"ExportSpecifier\");\n  }\n\n  // https://tc39.es/ecma262/#prod-ModuleExportName\n  parseModuleExportName(): N.StringLiteral | N.Identifier {\n    if (this.match(tt.string)) {\n      const result = this.parseStringLiteral(this.state.value);\n      const surrogate = loneSurrogate.exec(result.value);\n      if (surrogate) {\n        this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, {\n          surrogateCharCode: surrogate[0].charCodeAt(0),\n        });\n      }\n      return result;\n    }\n    return this.parseIdentifier(true);\n  }\n\n  isJSONModuleImport(\n    node: Undone<\n      N.ExportAllDeclaration | N.ExportNamedDeclaration | N.ImportDeclaration\n    >,\n  ): boolean {\n    if (node.assertions != null) {\n      return node.assertions.some(({ key, value }) => {\n        return (\n          value.value === \"json\" &&\n          (key.type === \"Identifier\"\n            ? key.name === \"type\"\n            : key.value === \"type\")\n        );\n      });\n    }\n    return false;\n  }\n\n  checkImportReflection(node: Undone<N.ImportDeclaration>) {\n    const { specifiers } = node;\n    const singleBindingType =\n      specifiers.length === 1 ? specifiers[0].type : null;\n\n    if (node.phase === \"source\") {\n      if (singleBindingType !== \"ImportDefaultSpecifier\") {\n        this.raise(\n          Errors.SourcePhaseImportRequiresDefault,\n          specifiers[0].loc.start,\n        );\n      }\n    } else if (node.phase === \"defer\") {\n      if (singleBindingType !== \"ImportNamespaceSpecifier\") {\n        this.raise(\n          Errors.DeferImportRequiresNamespace,\n          specifiers[0].loc.start,\n        );\n      }\n    } else if (node.module) {\n      if (singleBindingType !== \"ImportDefaultSpecifier\") {\n        this.raise(Errors.ImportReflectionNotBinding, specifiers[0].loc.start);\n      }\n      if (node.assertions?.length > 0) {\n        this.raise(\n          Errors.ImportReflectionHasAssertion,\n          specifiers[0].loc.start,\n        );\n      }\n    }\n  }\n\n  checkJSONModuleImport(\n    node: Undone<\n      N.ExportAllDeclaration | N.ExportNamedDeclaration | N.ImportDeclaration\n    >,\n  ) {\n    // @ts-expect-error Fixme: node.type must be undefined because they are undone\n    if (this.isJSONModuleImport(node) && node.type !== \"ExportAllDeclaration\") {\n      // @ts-expect-error specifiers may not index node\n      const { specifiers } = node;\n      if (specifiers != null) {\n        // @ts-expect-error refine specifier types\n        const nonDefaultNamedSpecifier = specifiers.find(specifier => {\n          let imported;\n          if (specifier.type === \"ExportSpecifier\") {\n            imported = specifier.local;\n          } else if (specifier.type === \"ImportSpecifier\") {\n            imported = specifier.imported;\n          }\n          if (imported !== undefined) {\n            return imported.type === \"Identifier\"\n              ? imported.name !== \"default\"\n              : imported.value !== \"default\";\n          }\n        });\n        if (nonDefaultNamedSpecifier !== undefined) {\n          this.raise(\n            Errors.ImportJSONBindingNotDefault,\n            nonDefaultNamedSpecifier.loc.start,\n          );\n        }\n      }\n    }\n  }\n\n  isPotentialImportPhase(isExport: boolean): boolean {\n    if (isExport) return false;\n    return (\n      this.isContextual(tt._source) ||\n      this.isContextual(tt._defer) ||\n      (!process.env.BABEL_8_BREAKING && this.isContextual(tt._module))\n    );\n  }\n\n  applyImportPhase(\n    node: Undone<N.ImportDeclaration | N.ExportNamedDeclaration>,\n    isExport: boolean,\n    phase: string | null,\n    loc?: Position,\n  ): void {\n    if (isExport) {\n      if (!process.env.IS_PUBLISH) {\n        if (\n          (!process.env.BABEL_8_BREAKING && phase === \"module\") ||\n          phase === \"source\"\n        ) {\n          throw new Error(\n            `Assertion failure: export declarations do not support the '${phase}' phase.`,\n          );\n        }\n      }\n      return;\n    }\n\n    if (!process.env.BABEL_8_BREAKING && phase === \"module\") {\n      this.expectPlugin(\"importReflection\", loc);\n      (node as N.ImportDeclaration).module = true;\n    } else if (this.hasPlugin(\"importReflection\")) {\n      (node as N.ImportDeclaration).module = false;\n    }\n\n    if (phase === \"source\") {\n      this.expectPlugin(\"sourcePhaseImports\", loc);\n      (node as N.ImportDeclaration).phase = \"source\";\n    } else if (phase === \"defer\") {\n      this.expectPlugin(\"deferredImportEvaluation\", loc);\n      (node as N.ImportDeclaration).phase = \"defer\";\n    } else if (this.hasPlugin(\"sourcePhaseImports\")) {\n      (node as N.ImportDeclaration).phase = null;\n    }\n  }\n\n  /*\n   * Parse `source` in `import source x from \"x\"`, disambiguating\n   * `import source from \"x\"` and `import source from from \"x\"`.\n   *\n   * This function might return an identifier representing the `source`\n   * if it eats `source` and then discovers that it was the default import\n   * binding and not the import reflection.\n   *\n   * This function is also used to parse `import type` and `import typeof`\n   * in the TS and Flow plugins, and for parsing `import defer`.\n   */\n  parseMaybeImportPhase(\n    node: Undone<N.ImportDeclaration | N.TsImportEqualsDeclaration>,\n    isExport: boolean,\n  ): N.Identifier | null {\n    if (!this.isPotentialImportPhase(isExport)) {\n      this.applyImportPhase(\n        node as Undone<N.ImportDeclaration>,\n        isExport,\n        null,\n      );\n      return null;\n    }\n\n    const phaseIdentifier = this.startNode<N.Identifier>();\n    const phaseIdentifierName = this.parseIdentifierName(true);\n\n    const { type } = this.state;\n    const isImportPhase = tokenIsKeywordOrIdentifier(type)\n      ? // OK: import <phase> x from \"foo\";\n        // OK: import <phase> from from \"foo\";\n        // NO: import <phase> from \"foo\";\n        // NO: import <phase> from 'foo';\n        // With the module declarations proposals, we will need further disambiguation\n        // for `import module from from;`.\n        type !== tt._from || this.lookaheadCharCode() === charCodes.lowercaseF\n      : // OK: import <phase> { x } from \"foo\";\n        // OK: import <phase> x from \"foo\";\n        // OK: import <phase> * as T from \"foo\";\n        // NO: import <phase> from \"foo\";\n        // OK: import <phase> \"foo\";\n        // The last one is invalid, we will continue parsing and throw\n        // an error later\n        type !== tt.comma;\n\n    if (isImportPhase) {\n      this.applyImportPhase(\n        node as Undone<N.ImportDeclaration>,\n        isExport,\n        phaseIdentifierName,\n        phaseIdentifier.loc.start,\n      );\n      return null;\n    } else {\n      this.applyImportPhase(\n        node as Undone<N.ImportDeclaration>,\n        isExport,\n        null,\n      );\n      // `<phase>` is a default binding, return it to the main import declaration parser\n      return this.createIdentifier(phaseIdentifier, phaseIdentifierName);\n    }\n  }\n\n  isPrecedingIdImportPhase(\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    phase: string,\n  ) {\n    const { type } = this.state;\n    return tokenIsIdentifier(type)\n      ? // OK: import <phase> x from \"foo\";\n        // OK: import <phase> from from \"foo\";\n        // NO: import <phase> from \"foo\";\n        // NO: import <phase> from 'foo';\n        // With the module declarations proposals, we will need further disambiguation\n        // for `import module from from;`.\n        type !== tt._from || this.lookaheadCharCode() === charCodes.lowercaseF\n      : // OK: import <phase> { x } from \"foo\";\n        // OK: import <phase> x from \"foo\";\n        // OK: import <phase> * as T from \"foo\";\n        // NO: import <phase> from \"foo\";\n        // OK: import <phase> \"foo\";\n        // The last one is invalid, we will continue parsing and throw\n        // an error later\n        type !== tt.comma;\n  }\n\n  // Parses import declaration.\n  // https://tc39.es/ecma262/#prod-ImportDeclaration\n\n  parseImport(this: Parser, node: Undone<N.ImportDeclaration>): N.AnyImport {\n    if (this.match(tt.string)) {\n      // import '...'\n      return this.parseImportSourceAndAttributes(node);\n    }\n\n    return this.parseImportSpecifiersAndAfter(\n      node,\n      this.parseMaybeImportPhase(node, /* isExport */ false),\n    );\n  }\n\n  parseImportSpecifiersAndAfter(\n    this: Parser,\n    node: Undone<N.ImportDeclaration>,\n    maybeDefaultIdentifier: N.Identifier | null,\n  ): N.AnyImport {\n    node.specifiers = [];\n\n    // check if we have a default import like\n    // import React from \"react\";\n    const hasDefault = this.maybeParseDefaultImportSpecifier(\n      node,\n      maybeDefaultIdentifier,\n    );\n    /* we are checking if we do not have a default import, then it is obvious that we need named imports\n     * import { get } from \"axios\";\n     * but if we do have a default import\n     * we need to check if we have a comma after that and\n     * that is where this `|| this.eat` condition comes into play\n     */\n    const parseNext = !hasDefault || this.eat(tt.comma);\n    // if we do have to parse the next set of specifiers, we first check for star imports\n    // import React, * from \"react\";\n    const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);\n    // now we check if we need to parse the next imports\n    // but only if they are not importing * (everything)\n    if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);\n    this.expectContextual(tt._from);\n\n    return this.parseImportSourceAndAttributes(node);\n  }\n\n  parseImportSourceAndAttributes(\n    this: Parser,\n    node: Undone<N.ImportDeclaration>,\n  ): N.AnyImport {\n    node.specifiers ??= [];\n    node.source = this.parseImportSource();\n    this.maybeParseImportAttributes(node);\n    this.checkImportReflection(node);\n    this.checkJSONModuleImport(node);\n\n    this.semicolon();\n    this.sawUnambiguousESM = true;\n    return this.finishNode(node, \"ImportDeclaration\");\n  }\n\n  parseImportSource(this: Parser): N.StringLiteral {\n    if (!this.match(tt.string)) this.unexpected();\n    return this.parseExprAtom() as N.StringLiteral;\n  }\n\n  parseImportSpecifierLocal<\n    T extends\n      | N.ImportSpecifier\n      | N.ImportDefaultSpecifier\n      | N.ImportNamespaceSpecifier,\n  >(\n    node: Undone<N.ImportDeclaration>,\n    specifier: Undone<T>,\n    type: T[\"type\"],\n  ): void {\n    specifier.local = this.parseIdentifier();\n    node.specifiers.push(this.finishImportSpecifier(specifier, type));\n  }\n\n  finishImportSpecifier<\n    T extends\n      | N.ImportSpecifier\n      | N.ImportDefaultSpecifier\n      | N.ImportNamespaceSpecifier,\n  >(\n    specifier: Undone<T>,\n    type: T[\"type\"],\n    bindingType: BindingFlag = BindingFlag.TYPE_LEXICAL,\n  ) {\n    this.checkLVal(specifier.local, { type }, bindingType);\n    return this.finishNode(specifier, type);\n  }\n\n  /**\n   * parse assert entries\n   *\n   * @see {@link https://tc39.es/proposal-import-attributes/#prod-WithEntries WithEntries}\n   */\n  parseImportAttributes(): N.ImportAttribute[] {\n    this.expect(tt.braceL);\n\n    const attrs = [];\n    const attrNames = new Set();\n\n    do {\n      if (this.match(tt.braceR)) {\n        break;\n      }\n\n      const node = this.startNode<N.ImportAttribute>();\n\n      // parse AssertionKey : IdentifierName, StringLiteral\n      const keyName = this.state.value;\n      // check if we already have an entry for an attribute\n      // if a duplicate entry is found, throw an error\n      // for now this logic will come into play only when someone declares `type` twice\n      if (attrNames.has(keyName)) {\n        this.raise(\n          Errors.ModuleAttributesWithDuplicateKeys,\n          this.state.startLoc,\n          {\n            key: keyName,\n          },\n        );\n      }\n      attrNames.add(keyName);\n      if (this.match(tt.string)) {\n        node.key = this.parseStringLiteral(keyName);\n      } else {\n        node.key = this.parseIdentifier(true);\n      }\n      this.expect(tt.colon);\n\n      if (!this.match(tt.string)) {\n        throw this.raise(\n          Errors.ModuleAttributeInvalidValue,\n          this.state.startLoc,\n        );\n      }\n      node.value = this.parseStringLiteral(this.state.value);\n      attrs.push(this.finishNode(node, \"ImportAttribute\"));\n    } while (this.eat(tt.comma));\n\n    this.expect(tt.braceR);\n\n    return attrs;\n  }\n\n  /**\n   * parse module attributes\n   * @deprecated It will be removed in Babel 8\n   */\n  parseModuleAttributes() {\n    const attrs: N.ImportAttribute[] = [];\n    const attributes = new Set();\n    do {\n      const node = this.startNode<N.ImportAttribute>();\n      node.key = this.parseIdentifier(true);\n\n      if (node.key.name !== \"type\") {\n        this.raise(Errors.ModuleAttributeDifferentFromType, node.key);\n      }\n\n      if (attributes.has(node.key.name)) {\n        this.raise(Errors.ModuleAttributesWithDuplicateKeys, node.key, {\n          key: node.key.name,\n        });\n      }\n      attributes.add(node.key.name);\n      this.expect(tt.colon);\n      if (!this.match(tt.string)) {\n        throw this.raise(\n          Errors.ModuleAttributeInvalidValue,\n          this.state.startLoc,\n        );\n      }\n      node.value = this.parseStringLiteral(this.state.value);\n      attrs.push(this.finishNode(node, \"ImportAttribute\"));\n    } while (this.eat(tt.comma));\n\n    return attrs;\n  }\n\n  maybeParseImportAttributes(\n    node: Undone<\n      N.ImportDeclaration | N.ExportNamedDeclaration | N.ExportAllDeclaration\n    >,\n  ) {\n    let attributes: N.ImportAttribute[];\n    if (!process.env.BABEL_8_BREAKING) {\n      // eslint-disable-next-line no-var\n      var useWith = false;\n    }\n\n    // https://tc39.es/proposal-import-attributes/#prod-WithClause\n    if (this.match(tt._with)) {\n      if (\n        this.hasPrecedingLineBreak() &&\n        this.lookaheadCharCode() === charCodes.leftParenthesis\n      ) {\n        // This will be parsed as a with statement, and we will throw a\n        // better error about it not being supported in strict mode.\n        return;\n      }\n\n      this.next(); // eat `with`\n\n      if (!process.env.BABEL_8_BREAKING && this.hasPlugin(\"moduleAttributes\")) {\n        attributes = this.parseModuleAttributes();\n        this.addExtra(node, \"deprecatedWithLegacySyntax\", true);\n      } else {\n        attributes = this.parseImportAttributes();\n      }\n      if (!process.env.BABEL_8_BREAKING) {\n        useWith = true;\n      }\n    } else if (this.isContextual(tt._assert) && !this.hasPrecedingLineBreak()) {\n      if (\n        !this.hasPlugin(\"deprecatedImportAssert\") &&\n        (process.env.BABEL_8_BREAKING || !this.hasPlugin(\"importAssertions\"))\n      ) {\n        this.raise(Errors.ImportAttributesUseAssert, this.state.startLoc);\n      }\n      if (process.env.BABEL_8_BREAKING || !this.hasPlugin(\"importAssertions\")) {\n        this.addExtra(node, \"deprecatedAssertSyntax\", true);\n      }\n      this.next(); // eat `assert`\n      attributes = this.parseImportAttributes();\n    } else {\n      attributes = [];\n    }\n\n    if (\n      !process.env.BABEL_8_BREAKING &&\n      !useWith &&\n      this.hasPlugin(\"importAssertions\")\n    ) {\n      node.assertions = attributes;\n    } else {\n      node.attributes = attributes;\n    }\n  }\n\n  maybeParseDefaultImportSpecifier(\n    node: Undone<N.ImportDeclaration>,\n    maybeDefaultIdentifier: N.Identifier | null,\n  ): boolean {\n    // import defaultObj, { x, y as z } from '...'\n    if (maybeDefaultIdentifier) {\n      const specifier = this.startNodeAtNode<N.ImportDefaultSpecifier>(\n        maybeDefaultIdentifier,\n      );\n      specifier.local = maybeDefaultIdentifier;\n      node.specifiers.push(\n        this.finishImportSpecifier(specifier, \"ImportDefaultSpecifier\"),\n      );\n      return true;\n    } else if (\n      // We allow keywords, and parseImportSpecifierLocal will report a recoverable error\n      tokenIsKeywordOrIdentifier(this.state.type)\n    ) {\n      this.parseImportSpecifierLocal(\n        node,\n        this.startNode<N.ImportDefaultSpecifier>(),\n        \"ImportDefaultSpecifier\",\n      );\n      return true;\n    }\n    return false;\n  }\n\n  maybeParseStarImportSpecifier(node: Undone<N.ImportDeclaration>): boolean {\n    if (this.match(tt.star)) {\n      const specifier = this.startNode<N.ImportNamespaceSpecifier>();\n      this.next();\n      this.expectContextual(tt._as);\n\n      this.parseImportSpecifierLocal(\n        node,\n        specifier,\n        \"ImportNamespaceSpecifier\",\n      );\n      return true;\n    }\n    return false;\n  }\n\n  parseNamedImportSpecifiers(node: Undone<N.ImportDeclaration>) {\n    let first = true;\n    this.expect(tt.braceL);\n    while (!this.eat(tt.braceR)) {\n      if (first) {\n        first = false;\n      } else {\n        // Detect an attempt to deep destructure\n        if (this.eat(tt.colon)) {\n          throw this.raise(Errors.DestructureNamedImport, this.state.startLoc);\n        }\n\n        this.expect(tt.comma);\n        if (this.eat(tt.braceR)) break;\n      }\n\n      const specifier = this.startNode<N.ImportSpecifier>();\n      const importedIsString = this.match(tt.string);\n      const isMaybeTypeOnly = this.isContextual(tt._type);\n      specifier.imported = this.parseModuleExportName();\n      const importSpecifier = this.parseImportSpecifier(\n        specifier,\n        importedIsString,\n        node.importKind === \"type\" || node.importKind === \"typeof\",\n        isMaybeTypeOnly,\n        undefined,\n      );\n      node.specifiers.push(importSpecifier);\n    }\n  }\n\n  // https://tc39.es/ecma262/#prod-ImportSpecifier\n  parseImportSpecifier(\n    specifier: Undone<N.ImportSpecifier>,\n    importedIsString: boolean,\n    /* used in TypeScript and Flow parser */\n    isInTypeOnlyImport: boolean,\n    isMaybeTypeOnly: boolean,\n    bindingType: BindingFlag | undefined,\n  ): N.ImportSpecifier {\n    if (this.eatContextual(tt._as)) {\n      specifier.local = this.parseIdentifier();\n    } else {\n      const { imported } = specifier;\n      if (importedIsString) {\n        throw this.raise(Errors.ImportBindingIsString, specifier, {\n          importName: (imported as N.StringLiteral).value,\n        });\n      }\n      this.checkReservedWord(\n        (imported as N.Identifier).name,\n        specifier.loc.start,\n        true,\n        true,\n      );\n      if (!specifier.local) {\n        specifier.local = this.cloneIdentifier(imported as N.Identifier);\n      }\n    }\n    return this.finishImportSpecifier(\n      specifier,\n      \"ImportSpecifier\",\n      bindingType,\n    );\n  }\n\n  // This is used in flow and typescript plugin\n  // Determine whether a parameter is a this param\n  isThisParam(\n    param: N.Pattern | N.Identifier | N.TSParameterProperty,\n  ): boolean {\n    return param.type === \"Identifier\" && param.name === \"this\";\n  }\n}\n","import type { Options } from \"../options.ts\";\nimport type * as N from \"../types.ts\";\nimport { getOptions, OptionFlags } from \"../options.ts\";\nimport StatementParser from \"./statement.ts\";\nimport ScopeHandler from \"../util/scope.ts\";\n\nexport type PluginsMap = Map<\n  string,\n  {\n    [x: string]: any;\n  }\n>;\n\nexport default class Parser extends StatementParser {\n  // Forward-declaration so typescript plugin can override jsx plugin\n  // todo(flow->ts) - this probably can be removed\n  // abstract jsxParseOpeningElementAfterName(\n  //   node: N.JSXOpeningElement,\n  // ): N.JSXOpeningElement;\n\n  constructor(\n    options: Options | undefined | null,\n    input: string,\n    pluginsMap: PluginsMap,\n  ) {\n    options = getOptions(options);\n    super(options, input);\n\n    this.options = options;\n    this.initializeScopes();\n    this.plugins = pluginsMap;\n    this.filename = options.sourceFilename;\n    this.startIndex = options.startIndex;\n\n    let optionFlags = 0;\n    if (options.allowAwaitOutsideFunction) {\n      optionFlags |= OptionFlags.AllowAwaitOutsideFunction;\n    }\n    if (options.allowReturnOutsideFunction) {\n      optionFlags |= OptionFlags.AllowReturnOutsideFunction;\n    }\n    if (options.allowImportExportEverywhere) {\n      optionFlags |= OptionFlags.AllowImportExportEverywhere;\n    }\n    if (options.allowSuperOutsideMethod) {\n      optionFlags |= OptionFlags.AllowSuperOutsideMethod;\n    }\n    if (options.allowUndeclaredExports) {\n      optionFlags |= OptionFlags.AllowUndeclaredExports;\n    }\n    if (options.allowNewTargetOutsideFunction) {\n      optionFlags |= OptionFlags.AllowNewTargetOutsideFunction;\n    }\n    if (options.allowYieldOutsideFunction) {\n      optionFlags |= OptionFlags.AllowYieldOutsideFunction;\n    }\n    if (options.ranges) {\n      optionFlags |= OptionFlags.Ranges;\n    }\n    if (options.tokens) {\n      optionFlags |= OptionFlags.Tokens;\n    }\n    if (options.createImportExpressions) {\n      optionFlags |= OptionFlags.CreateImportExpressions;\n    }\n    if (options.createParenthesizedExpressions) {\n      optionFlags |= OptionFlags.CreateParenthesizedExpressions;\n    }\n    if (options.errorRecovery) {\n      optionFlags |= OptionFlags.ErrorRecovery;\n    }\n    if (options.attachComment) {\n      optionFlags |= OptionFlags.AttachComment;\n    }\n    if (options.annexB) {\n      optionFlags |= OptionFlags.AnnexB;\n    }\n\n    this.optionFlags = optionFlags;\n  }\n\n  // This can be overwritten, for example, by the TypeScript plugin.\n  getScopeHandler(): new (...args: any) => ScopeHandler {\n    return ScopeHandler;\n  }\n\n  parse(): N.File {\n    this.enterInitialScopes();\n    const file = this.startNode<N.File>();\n    const program = this.startNode<N.Program>();\n    this.nextToken();\n    file.errors = null;\n    this.parseTopLevel(file, program);\n    file.errors = this.state.errors;\n    file.comments.length = this.state.commentsLen;\n    return file as N.File;\n  }\n}\n","import type { Options } from \"./options.ts\";\nimport {\n  validatePlugins,\n  mixinPluginNames,\n  mixinPlugins,\n} from \"./plugin-utils.ts\";\nexport type {\n  PluginConfig as ParserPlugin,\n  DecoratorsPluginOptions,\n  FlowPluginOptions,\n  PipelineOperatorPluginOptions,\n  RecordAndTuplePluginOptions,\n  TypeScriptPluginOptions,\n} from \"./typings.ts\";\nimport Parser, { type PluginsMap } from \"./parser/index.ts\";\n\nimport type { ExportedTokenType } from \"./tokenizer/types.ts\";\nimport {\n  getExportedToken,\n  tt as internalTokenTypes,\n  type InternalTokenTypes,\n} from \"./tokenizer/types.ts\";\nexport type { Token } from \"./tokenizer/index.ts\";\n\n// TODO: Rather than type-casting the internal AST definitions to the\n// @babel/types one, we should actually unify them.\nimport type { Expression, File } from \"@babel/types\";\nexport type { Expression, File };\n\nexport type ParserOptions = Partial<Options>;\n\nexport interface ParseError {\n  code: string;\n  reasonCode: string;\n}\nexport type ParseResult<Result extends File | Expression = File> = Result & {\n  errors: null | ParseError[];\n};\n\n/**\n * Parse the provided code as an entire ECMAScript program.\n */\nexport function parse(\n  input: string,\n  options?: ParserOptions,\n): ParseResult<File> {\n  if (options?.sourceType === \"unambiguous\") {\n    options = {\n      ...options,\n    };\n    try {\n      options.sourceType = \"module\";\n      const parser = getParser(options, input);\n      const ast = parser.parse();\n\n      if (parser.sawUnambiguousESM) {\n        return ast as unknown as ParseResult<File>;\n      }\n\n      if (parser.ambiguousScriptDifferentAst) {\n        // Top level await introduces code which can be both a valid script and\n        // a valid module, but which produces different ASTs:\n        //    await\n        //    0\n        // can be parsed either as an AwaitExpression, or as two ExpressionStatements.\n        try {\n          options.sourceType = \"script\";\n          return getParser(\n            options,\n            input,\n          ).parse() as unknown as ParseResult<File>;\n        } catch {}\n      } else {\n        // This is both a valid module and a valid script, but\n        // we parse it as a script by default\n        ast.program.sourceType = \"script\";\n      }\n\n      return ast as unknown as ParseResult<File>;\n    } catch (moduleError) {\n      try {\n        options.sourceType = \"script\";\n        return getParser(\n          options,\n          input,\n        ).parse() as unknown as ParseResult<File>;\n      } catch {}\n\n      throw moduleError;\n    }\n  } else {\n    return getParser(options, input).parse() as unknown as ParseResult<File>;\n  }\n}\n\nexport function parseExpression(\n  input: string,\n  options?: ParserOptions,\n): ParseResult<Expression> {\n  const parser = getParser(options, input);\n  if (parser.options.strictMode) {\n    parser.state.strict = true;\n  }\n  return parser.getExpression() as unknown as ParseResult<Expression>;\n}\n\nfunction generateExportedTokenTypes(\n  internalTokenTypes: InternalTokenTypes,\n): Record<string, ExportedTokenType> {\n  const tokenTypes: Record<string, ExportedTokenType> = {};\n  for (const typeName of Object.keys(\n    internalTokenTypes,\n  ) as (keyof InternalTokenTypes)[]) {\n    tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]);\n  }\n  return tokenTypes;\n}\n\nexport const tokTypes = generateExportedTokenTypes(internalTokenTypes);\n\nfunction getParser(options: Options | undefined | null, input: string): Parser {\n  let cls = Parser;\n  const pluginsMap: PluginsMap = new Map();\n  if (options?.plugins) {\n    for (const plugin of options.plugins) {\n      let name, opts;\n      if (typeof plugin === \"string\") {\n        name = plugin;\n      } else {\n        [name, opts] = plugin;\n      }\n      if (!pluginsMap.has(name)) {\n        pluginsMap.set(name, opts || {});\n      }\n    }\n    validatePlugins(pluginsMap);\n    cls = getParserClass(pluginsMap);\n  }\n\n  return new cls(options, input, pluginsMap);\n}\n\nconst parserClassCache = new Map<string, new (...args: any) => Parser>();\n\n/** Get a Parser class with plugins applied. */\nfunction getParserClass(\n  pluginsMap: Map<string, any>,\n): new (...args: any) => Parser {\n  const pluginList = [];\n  for (const name of mixinPluginNames) {\n    if (pluginsMap.has(name)) {\n      pluginList.push(name);\n    }\n  }\n  const key = pluginList.join(\"|\");\n  let cls = parserClassCache.get(key);\n  if (!cls) {\n    cls = Parser;\n    for (const plugin of pluginList) {\n      // @ts-expect-error todo(flow->ts)\n      cls = mixinPlugins[plugin](cls);\n    }\n    parserClassCache.set(key, cls);\n  }\n  return cls;\n}\n","(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n\ttypeof define === 'function' && define.amd ? define(['exports'], factory) :\n\t(global = global || self, factory(global.estreeWalker = {}));\n}(this, (function (exports) { 'use strict';\n\n\t// @ts-check\n\t/** @typedef { import('estree').BaseNode} BaseNode */\n\n\t/** @typedef {{\n\t\tskip: () => void;\n\t\tremove: () => void;\n\t\treplace: (node: BaseNode) => void;\n\t}} WalkerContext */\n\n\tclass WalkerBase {\n\t\tconstructor() {\n\t\t\t/** @type {boolean} */\n\t\t\tthis.should_skip = false;\n\n\t\t\t/** @type {boolean} */\n\t\t\tthis.should_remove = false;\n\n\t\t\t/** @type {BaseNode | null} */\n\t\t\tthis.replacement = null;\n\n\t\t\t/** @type {WalkerContext} */\n\t\t\tthis.context = {\n\t\t\t\tskip: () => (this.should_skip = true),\n\t\t\t\tremove: () => (this.should_remove = true),\n\t\t\t\treplace: (node) => (this.replacement = node)\n\t\t\t};\n\t\t}\n\n\t\t/**\n\t\t *\n\t\t * @param {any} parent\n\t\t * @param {string} prop\n\t\t * @param {number} index\n\t\t * @param {BaseNode} node\n\t\t */\n\t\treplace(parent, prop, index, node) {\n\t\t\tif (parent) {\n\t\t\t\tif (index !== null) {\n\t\t\t\t\tparent[prop][index] = node;\n\t\t\t\t} else {\n\t\t\t\t\tparent[prop] = node;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t *\n\t\t * @param {any} parent\n\t\t * @param {string} prop\n\t\t * @param {number} index\n\t\t */\n\t\tremove(parent, prop, index) {\n\t\t\tif (parent) {\n\t\t\t\tif (index !== null) {\n\t\t\t\t\tparent[prop].splice(index, 1);\n\t\t\t\t} else {\n\t\t\t\t\tdelete parent[prop];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// @ts-check\n\n\t/** @typedef { import('estree').BaseNode} BaseNode */\n\t/** @typedef { import('./walker.js').WalkerContext} WalkerContext */\n\n\t/** @typedef {(\n\t *    this: WalkerContext,\n\t *    node: BaseNode,\n\t *    parent: BaseNode,\n\t *    key: string,\n\t *    index: number\n\t * ) => void} SyncHandler */\n\n\tclass SyncWalker extends WalkerBase {\n\t\t/**\n\t\t *\n\t\t * @param {SyncHandler} enter\n\t\t * @param {SyncHandler} leave\n\t\t */\n\t\tconstructor(enter, leave) {\n\t\t\tsuper();\n\n\t\t\t/** @type {SyncHandler} */\n\t\t\tthis.enter = enter;\n\n\t\t\t/** @type {SyncHandler} */\n\t\t\tthis.leave = leave;\n\t\t}\n\n\t\t/**\n\t\t *\n\t\t * @param {BaseNode} node\n\t\t * @param {BaseNode} parent\n\t\t * @param {string} [prop]\n\t\t * @param {number} [index]\n\t\t * @returns {BaseNode}\n\t\t */\n\t\tvisit(node, parent, prop, index) {\n\t\t\tif (node) {\n\t\t\t\tif (this.enter) {\n\t\t\t\t\tconst _should_skip = this.should_skip;\n\t\t\t\t\tconst _should_remove = this.should_remove;\n\t\t\t\t\tconst _replacement = this.replacement;\n\t\t\t\t\tthis.should_skip = false;\n\t\t\t\t\tthis.should_remove = false;\n\t\t\t\t\tthis.replacement = null;\n\n\t\t\t\t\tthis.enter.call(this.context, node, parent, prop, index);\n\n\t\t\t\t\tif (this.replacement) {\n\t\t\t\t\t\tnode = this.replacement;\n\t\t\t\t\t\tthis.replace(parent, prop, index, node);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this.should_remove) {\n\t\t\t\t\t\tthis.remove(parent, prop, index);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst skipped = this.should_skip;\n\t\t\t\t\tconst removed = this.should_remove;\n\n\t\t\t\t\tthis.should_skip = _should_skip;\n\t\t\t\t\tthis.should_remove = _should_remove;\n\t\t\t\t\tthis.replacement = _replacement;\n\n\t\t\t\t\tif (skipped) return node;\n\t\t\t\t\tif (removed) return null;\n\t\t\t\t}\n\n\t\t\t\tfor (const key in node) {\n\t\t\t\t\tconst value = node[key];\n\n\t\t\t\t\tif (typeof value !== \"object\") {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t} else if (Array.isArray(value)) {\n\t\t\t\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\t\t\t\tif (value[i] !== null && typeof value[i].type === 'string') {\n\t\t\t\t\t\t\t\tif (!this.visit(value[i], node, key, i)) {\n\t\t\t\t\t\t\t\t\t// removed\n\t\t\t\t\t\t\t\t\ti--;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (value !== null && typeof value.type === \"string\") {\n\t\t\t\t\t\tthis.visit(value, node, key, null);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (this.leave) {\n\t\t\t\t\tconst _replacement = this.replacement;\n\t\t\t\t\tconst _should_remove = this.should_remove;\n\t\t\t\t\tthis.replacement = null;\n\t\t\t\t\tthis.should_remove = false;\n\n\t\t\t\t\tthis.leave.call(this.context, node, parent, prop, index);\n\n\t\t\t\t\tif (this.replacement) {\n\t\t\t\t\t\tnode = this.replacement;\n\t\t\t\t\t\tthis.replace(parent, prop, index, node);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this.should_remove) {\n\t\t\t\t\t\tthis.remove(parent, prop, index);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst removed = this.should_remove;\n\n\t\t\t\t\tthis.replacement = _replacement;\n\t\t\t\t\tthis.should_remove = _should_remove;\n\n\t\t\t\t\tif (removed) return null;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn node;\n\t\t}\n\t}\n\n\t// @ts-check\n\n\t/** @typedef { import('estree').BaseNode} BaseNode */\n\t/** @typedef { import('./walker').WalkerContext} WalkerContext */\n\n\t/** @typedef {(\n\t *    this: WalkerContext,\n\t *    node: BaseNode,\n\t *    parent: BaseNode,\n\t *    key: string,\n\t *    index: number\n\t * ) => Promise<void>} AsyncHandler */\n\n\tclass AsyncWalker extends WalkerBase {\n\t\t/**\n\t\t *\n\t\t * @param {AsyncHandler} enter\n\t\t * @param {AsyncHandler} leave\n\t\t */\n\t\tconstructor(enter, leave) {\n\t\t\tsuper();\n\n\t\t\t/** @type {AsyncHandler} */\n\t\t\tthis.enter = enter;\n\n\t\t\t/** @type {AsyncHandler} */\n\t\t\tthis.leave = leave;\n\t\t}\n\n\t\t/**\n\t\t *\n\t\t * @param {BaseNode} node\n\t\t * @param {BaseNode} parent\n\t\t * @param {string} [prop]\n\t\t * @param {number} [index]\n\t\t * @returns {Promise<BaseNode>}\n\t\t */\n\t\tasync visit(node, parent, prop, index) {\n\t\t\tif (node) {\n\t\t\t\tif (this.enter) {\n\t\t\t\t\tconst _should_skip = this.should_skip;\n\t\t\t\t\tconst _should_remove = this.should_remove;\n\t\t\t\t\tconst _replacement = this.replacement;\n\t\t\t\t\tthis.should_skip = false;\n\t\t\t\t\tthis.should_remove = false;\n\t\t\t\t\tthis.replacement = null;\n\n\t\t\t\t\tawait this.enter.call(this.context, node, parent, prop, index);\n\n\t\t\t\t\tif (this.replacement) {\n\t\t\t\t\t\tnode = this.replacement;\n\t\t\t\t\t\tthis.replace(parent, prop, index, node);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this.should_remove) {\n\t\t\t\t\t\tthis.remove(parent, prop, index);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst skipped = this.should_skip;\n\t\t\t\t\tconst removed = this.should_remove;\n\n\t\t\t\t\tthis.should_skip = _should_skip;\n\t\t\t\t\tthis.should_remove = _should_remove;\n\t\t\t\t\tthis.replacement = _replacement;\n\n\t\t\t\t\tif (skipped) return node;\n\t\t\t\t\tif (removed) return null;\n\t\t\t\t}\n\n\t\t\t\tfor (const key in node) {\n\t\t\t\t\tconst value = node[key];\n\n\t\t\t\t\tif (typeof value !== \"object\") {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t} else if (Array.isArray(value)) {\n\t\t\t\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\t\t\t\tif (value[i] !== null && typeof value[i].type === 'string') {\n\t\t\t\t\t\t\t\tif (!(await this.visit(value[i], node, key, i))) {\n\t\t\t\t\t\t\t\t\t// removed\n\t\t\t\t\t\t\t\t\ti--;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (value !== null && typeof value.type === \"string\") {\n\t\t\t\t\t\tawait this.visit(value, node, key, null);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (this.leave) {\n\t\t\t\t\tconst _replacement = this.replacement;\n\t\t\t\t\tconst _should_remove = this.should_remove;\n\t\t\t\t\tthis.replacement = null;\n\t\t\t\t\tthis.should_remove = false;\n\n\t\t\t\t\tawait this.leave.call(this.context, node, parent, prop, index);\n\n\t\t\t\t\tif (this.replacement) {\n\t\t\t\t\t\tnode = this.replacement;\n\t\t\t\t\t\tthis.replace(parent, prop, index, node);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this.should_remove) {\n\t\t\t\t\t\tthis.remove(parent, prop, index);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst removed = this.should_remove;\n\n\t\t\t\t\tthis.replacement = _replacement;\n\t\t\t\t\tthis.should_remove = _should_remove;\n\n\t\t\t\t\tif (removed) return null;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn node;\n\t\t}\n\t}\n\n\t// @ts-check\n\n\t/** @typedef { import('estree').BaseNode} BaseNode */\n\t/** @typedef { import('./sync.js').SyncHandler} SyncHandler */\n\t/** @typedef { import('./async.js').AsyncHandler} AsyncHandler */\n\n\t/**\n\t *\n\t * @param {BaseNode} ast\n\t * @param {{\n\t *   enter?: SyncHandler\n\t *   leave?: SyncHandler\n\t * }} walker\n\t * @returns {BaseNode}\n\t */\n\tfunction walk(ast, { enter, leave }) {\n\t\tconst instance = new SyncWalker(enter, leave);\n\t\treturn instance.visit(ast, null);\n\t}\n\n\t/**\n\t *\n\t * @param {BaseNode} ast\n\t * @param {{\n\t *   enter?: AsyncHandler\n\t *   leave?: AsyncHandler\n\t * }} walker\n\t * @returns {Promise<BaseNode>}\n\t */\n\tasync function asyncWalk(ast, { enter, leave }) {\n\t\tconst instance = new AsyncWalker(enter, leave);\n\t\treturn await instance.visit(ast, null);\n\t}\n\n\texports.asyncWalk = asyncWalk;\n\texports.walk = walk;\n\n\tObject.defineProperty(exports, '__esModule', { value: true });\n\n})));\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n  if (0 <= number && number < intToCharMap.length) {\n    return intToCharMap[number];\n  }\n  throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n  var bigA = 65;     // 'A'\n  var bigZ = 90;     // 'Z'\n\n  var littleA = 97;  // 'a'\n  var littleZ = 122; // 'z'\n\n  var zero = 48;     // '0'\n  var nine = 57;     // '9'\n\n  var plus = 43;     // '+'\n  var slash = 47;    // '/'\n\n  var littleOffset = 26;\n  var numberOffset = 52;\n\n  // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n  if (bigA <= charCode && charCode <= bigZ) {\n    return (charCode - bigA);\n  }\n\n  // 26 - 51: abcdefghijklmnopqrstuvwxyz\n  if (littleA <= charCode && charCode <= littleZ) {\n    return (charCode - littleA + littleOffset);\n  }\n\n  // 52 - 61: 0123456789\n  if (zero <= charCode && charCode <= nine) {\n    return (charCode - zero + numberOffset);\n  }\n\n  // 62: +\n  if (charCode == plus) {\n    return 62;\n  }\n\n  // 63: /\n  if (charCode == slash) {\n    return 63;\n  }\n\n  // Invalid base64 digit.\n  return -1;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *  * Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *  * Redistributions in binary form must reproduce the above\n *    copyright notice, this list of conditions and the following\n *    disclaimer in the documentation and/or other materials provided\n *    with the distribution.\n *  * Neither the name of Google Inc. nor the names of its\n *    contributors may be used to endorse or promote products derived\n *    from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = require('./base64');\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n//   Continuation\n//   |    Sign\n//   |    |\n//   V    V\n//   101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit.  For example, as decimals:\n *   1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n *   2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n  return aValue < 0\n    ? ((-aValue) << 1) + 1\n    : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit.  For example, as decimals:\n *   2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n *   4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n  var isNegative = (aValue & 1) === 1;\n  var shifted = aValue >> 1;\n  return isNegative\n    ? -shifted\n    : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n  var encoded = \"\";\n  var digit;\n\n  var vlq = toVLQSigned(aValue);\n\n  do {\n    digit = vlq & VLQ_BASE_MASK;\n    vlq >>>= VLQ_BASE_SHIFT;\n    if (vlq > 0) {\n      // There are still more digits in this value, so we must make sure the\n      // continuation bit is marked.\n      digit |= VLQ_CONTINUATION_BIT;\n    }\n    encoded += base64.encode(digit);\n  } while (vlq > 0);\n\n  return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n  var strLen = aStr.length;\n  var result = 0;\n  var shift = 0;\n  var continuation, digit;\n\n  do {\n    if (aIndex >= strLen) {\n      throw new Error(\"Expected more digits in base 64 VLQ value.\");\n    }\n\n    digit = base64.decode(aStr.charCodeAt(aIndex++));\n    if (digit === -1) {\n      throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n    }\n\n    continuation = !!(digit & VLQ_CONTINUATION_BIT);\n    digit &= VLQ_BASE_MASK;\n    result = result + (digit << shift);\n    shift += VLQ_BASE_SHIFT;\n  } while (continuation);\n\n  aOutParam.value = fromVLQSigned(result);\n  aOutParam.rest = aIndex;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n  if (aName in aArgs) {\n    return aArgs[aName];\n  } else if (arguments.length === 3) {\n    return aDefaultValue;\n  } else {\n    throw new Error('\"' + aName + '\" is a required argument.');\n  }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n  var match = aUrl.match(urlRegexp);\n  if (!match) {\n    return null;\n  }\n  return {\n    scheme: match[1],\n    auth: match[2],\n    host: match[3],\n    port: match[4],\n    path: match[5]\n  };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n  var url = '';\n  if (aParsedUrl.scheme) {\n    url += aParsedUrl.scheme + ':';\n  }\n  url += '//';\n  if (aParsedUrl.auth) {\n    url += aParsedUrl.auth + '@';\n  }\n  if (aParsedUrl.host) {\n    url += aParsedUrl.host;\n  }\n  if (aParsedUrl.port) {\n    url += \":\" + aParsedUrl.port\n  }\n  if (aParsedUrl.path) {\n    url += aParsedUrl.path;\n  }\n  return url;\n}\nexports.urlGenerate = urlGenerate;\n\nvar MAX_CACHED_INPUTS = 32;\n\n/**\n * Takes some function `f(input) -> result` and returns a memoized version of\n * `f`.\n *\n * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The\n * memoization is a dumb-simple, linear least-recently-used cache.\n */\nfunction lruMemoize(f) {\n  var cache = [];\n\n  return function(input) {\n    for (var i = 0; i < cache.length; i++) {\n      if (cache[i].input === input) {\n        var temp = cache[0];\n        cache[0] = cache[i];\n        cache[i] = temp;\n        return cache[0].result;\n      }\n    }\n\n    var result = f(input);\n\n    cache.unshift({\n      input,\n      result,\n    });\n\n    if (cache.length > MAX_CACHED_INPUTS) {\n      cache.pop();\n    }\n\n    return result;\n  };\n}\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '<dir>/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nvar normalize = lruMemoize(function normalize(aPath) {\n  var path = aPath;\n  var url = urlParse(aPath);\n  if (url) {\n    if (!url.path) {\n      return aPath;\n    }\n    path = url.path;\n  }\n  var isAbsolute = exports.isAbsolute(path);\n  // Split the path into parts between `/` characters. This is much faster than\n  // using `.split(/\\/+/g)`.\n  var parts = [];\n  var start = 0;\n  var i = 0;\n  while (true) {\n    start = i;\n    i = path.indexOf(\"/\", start);\n    if (i === -1) {\n      parts.push(path.slice(start));\n      break;\n    } else {\n      parts.push(path.slice(start, i));\n      while (i < path.length && path[i] === \"/\") {\n        i++;\n      }\n    }\n  }\n\n  for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n    part = parts[i];\n    if (part === '.') {\n      parts.splice(i, 1);\n    } else if (part === '..') {\n      up++;\n    } else if (up > 0) {\n      if (part === '') {\n        // The first part is blank if the path is absolute. Trying to go\n        // above the root is a no-op. Therefore we can remove all '..' parts\n        // directly after the root.\n        parts.splice(i + 1, up);\n        up = 0;\n      } else {\n        parts.splice(i, 2);\n        up--;\n      }\n    }\n  }\n  path = parts.join('/');\n\n  if (path === '') {\n    path = isAbsolute ? '/' : '.';\n  }\n\n  if (url) {\n    url.path = path;\n    return urlGenerate(url);\n  }\n  return path;\n});\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n *   scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n *   first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n *   is updated with the result and aRoot is returned. Otherwise the result\n *   is returned.\n *   - If aPath is absolute, the result is aPath.\n *   - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n  if (aRoot === \"\") {\n    aRoot = \".\";\n  }\n  if (aPath === \"\") {\n    aPath = \".\";\n  }\n  var aPathUrl = urlParse(aPath);\n  var aRootUrl = urlParse(aRoot);\n  if (aRootUrl) {\n    aRoot = aRootUrl.path || '/';\n  }\n\n  // `join(foo, '//www.example.org')`\n  if (aPathUrl && !aPathUrl.scheme) {\n    if (aRootUrl) {\n      aPathUrl.scheme = aRootUrl.scheme;\n    }\n    return urlGenerate(aPathUrl);\n  }\n\n  if (aPathUrl || aPath.match(dataUrlRegexp)) {\n    return aPath;\n  }\n\n  // `join('http://', 'www.example.com')`\n  if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n    aRootUrl.host = aPath;\n    return urlGenerate(aRootUrl);\n  }\n\n  var joined = aPath.charAt(0) === '/'\n    ? aPath\n    : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n  if (aRootUrl) {\n    aRootUrl.path = joined;\n    return urlGenerate(aRootUrl);\n  }\n  return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n  return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n  if (aRoot === \"\") {\n    aRoot = \".\";\n  }\n\n  aRoot = aRoot.replace(/\\/$/, '');\n\n  // It is possible for the path to be above the root. In this case, simply\n  // checking whether the root is a prefix of the path won't work. Instead, we\n  // need to remove components from the root one by one, until either we find\n  // a prefix that fits, or we run out of components to remove.\n  var level = 0;\n  while (aPath.indexOf(aRoot + '/') !== 0) {\n    var index = aRoot.lastIndexOf(\"/\");\n    if (index < 0) {\n      return aPath;\n    }\n\n    // If the only part of the root that is left is the scheme (i.e. http://,\n    // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n    // have exhausted all components, so the path is not relative to the root.\n    aRoot = aRoot.slice(0, index);\n    if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n      return aPath;\n    }\n\n    ++level;\n  }\n\n  // Make sure we add a \"../\" for each component we removed from the root.\n  return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n  var obj = Object.create(null);\n  return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n  return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n  if (isProtoString(aStr)) {\n    return '$' + aStr;\n  }\n\n  return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n  if (isProtoString(aStr)) {\n    return aStr.slice(1);\n  }\n\n  return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n  if (!s) {\n    return false;\n  }\n\n  var length = s.length;\n\n  if (length < 9 /* \"__proto__\".length */) {\n    return false;\n  }\n\n  if (s.charCodeAt(length - 1) !== 95  /* '_' */ ||\n      s.charCodeAt(length - 2) !== 95  /* '_' */ ||\n      s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n      s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n      s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n      s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n      s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n      s.charCodeAt(length - 8) !== 95  /* '_' */ ||\n      s.charCodeAt(length - 9) !== 95  /* '_' */) {\n    return false;\n  }\n\n  for (var i = length - 10; i >= 0; i--) {\n    if (s.charCodeAt(i) !== 36 /* '$' */) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n  var cmp = strcmp(mappingA.source, mappingB.source);\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = mappingA.originalLine - mappingB.originalLine;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = mappingA.originalColumn - mappingB.originalColumn;\n  if (cmp !== 0 || onlyCompareOriginal) {\n    return cmp;\n  }\n\n  cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = mappingA.generatedLine - mappingB.generatedLine;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\nfunction compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) {\n  var cmp\n\n  cmp = mappingA.originalLine - mappingB.originalLine;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = mappingA.originalColumn - mappingB.originalColumn;\n  if (cmp !== 0 || onlyCompareOriginal) {\n    return cmp;\n  }\n\n  cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = mappingA.generatedLine - mappingB.generatedLine;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n  var cmp = mappingA.generatedLine - mappingB.generatedLine;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n  if (cmp !== 0 || onlyCompareGenerated) {\n    return cmp;\n  }\n\n  cmp = strcmp(mappingA.source, mappingB.source);\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = mappingA.originalLine - mappingB.originalLine;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = mappingA.originalColumn - mappingB.originalColumn;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) {\n  var cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n  if (cmp !== 0 || onlyCompareGenerated) {\n    return cmp;\n  }\n\n  cmp = strcmp(mappingA.source, mappingB.source);\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = mappingA.originalLine - mappingB.originalLine;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = mappingA.originalColumn - mappingB.originalColumn;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine;\n\nfunction strcmp(aStr1, aStr2) {\n  if (aStr1 === aStr2) {\n    return 0;\n  }\n\n  if (aStr1 === null) {\n    return 1; // aStr2 !== null\n  }\n\n  if (aStr2 === null) {\n    return -1; // aStr1 !== null\n  }\n\n  if (aStr1 > aStr2) {\n    return 1;\n  }\n\n  return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n  var cmp = mappingA.generatedLine - mappingB.generatedLine;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = strcmp(mappingA.source, mappingB.source);\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = mappingA.originalLine - mappingB.originalLine;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  cmp = mappingA.originalColumn - mappingB.originalColumn;\n  if (cmp !== 0) {\n    return cmp;\n  }\n\n  return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\n/**\n * Strip any JSON XSSI avoidance prefix from the string (as documented\n * in the source maps specification), and then parse the string as\n * JSON.\n */\nfunction parseSourceMapInput(str) {\n  return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n}\nexports.parseSourceMapInput = parseSourceMapInput;\n\n/**\n * Compute the URL of a source given the the source root, the source's\n * URL, and the source map's URL.\n */\nfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n  sourceURL = sourceURL || '';\n\n  if (sourceRoot) {\n    // This follows what Chrome does.\n    if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n      sourceRoot += '/';\n    }\n    // The spec says:\n    //   Line 4: An optional source root, useful for relocating source\n    //   files on a server or removing repeated values in the\n    //   “sources” entry.  This value is prepended to the individual\n    //   entries in the “source” field.\n    sourceURL = sourceRoot + sourceURL;\n  }\n\n  // Historically, SourceMapConsumer did not take the sourceMapURL as\n  // a parameter.  This mode is still somewhat supported, which is why\n  // this code block is conditional.  However, it's preferable to pass\n  // the source map URL to SourceMapConsumer, so that this function\n  // can implement the source URL resolution algorithm as outlined in\n  // the spec.  This block is basically the equivalent of:\n  //    new URL(sourceURL, sourceMapURL).toString()\n  // ... except it avoids using URL, which wasn't available in the\n  // older releases of node still supported by this library.\n  //\n  // The spec says:\n  //   If the sources are not absolute URLs after prepending of the\n  //   “sourceRoot”, the sources are resolved relative to the\n  //   SourceMap (like resolving script src in a html document).\n  if (sourceMapURL) {\n    var parsed = urlParse(sourceMapURL);\n    if (!parsed) {\n      throw new Error(\"sourceMapURL could not be parsed\");\n    }\n    if (parsed.path) {\n      // Strip the last path component, but keep the \"/\".\n      var index = parsed.path.lastIndexOf('/');\n      if (index >= 0) {\n        parsed.path = parsed.path.substring(0, index + 1);\n      }\n    }\n    sourceURL = join(urlGenerate(parsed), sourceURL);\n  }\n\n  return normalize(sourceURL);\n}\nexports.computeSourceURL = computeSourceURL;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n  this._array = [];\n  this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n  var set = new ArraySet();\n  for (var i = 0, len = aArray.length; i < len; i++) {\n    set.add(aArray[i], aAllowDuplicates);\n  }\n  return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n  return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n  var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n  var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n  var idx = this._array.length;\n  if (!isDuplicate || aAllowDuplicates) {\n    this._array.push(aStr);\n  }\n  if (!isDuplicate) {\n    if (hasNativeMap) {\n      this._set.set(aStr, idx);\n    } else {\n      this._set[sStr] = idx;\n    }\n  }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n  if (hasNativeMap) {\n    return this._set.has(aStr);\n  } else {\n    var sStr = util.toSetString(aStr);\n    return has.call(this._set, sStr);\n  }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n  if (hasNativeMap) {\n    var idx = this._set.get(aStr);\n    if (idx >= 0) {\n        return idx;\n    }\n  } else {\n    var sStr = util.toSetString(aStr);\n    if (has.call(this._set, sStr)) {\n      return this._set[sStr];\n    }\n  }\n\n  throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n  if (aIdx >= 0 && aIdx < this._array.length) {\n    return this._array[aIdx];\n  }\n  throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n  return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n  // Optimized for most common case\n  var lineA = mappingA.generatedLine;\n  var lineB = mappingB.generatedLine;\n  var columnA = mappingA.generatedColumn;\n  var columnB = mappingB.generatedColumn;\n  return lineB > lineA || lineB == lineA && columnB >= columnA ||\n         util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n  this._array = [];\n  this._sorted = true;\n  // Serves as infimum\n  this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n  function MappingList_forEach(aCallback, aThisArg) {\n    this._array.forEach(aCallback, aThisArg);\n  };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n  if (generatedPositionAfter(this._last, aMapping)) {\n    this._last = aMapping;\n    this._array.push(aMapping);\n  } else {\n    this._sorted = false;\n    this._array.push(aMapping);\n  }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n  if (!this._sorted) {\n    this._array.sort(util.compareByGeneratedPositionsInflated);\n    this._sorted = true;\n  }\n  return this._array;\n};\n\nexports.MappingList = MappingList;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n *   - file: The filename of the generated source.\n *   - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n  if (!aArgs) {\n    aArgs = {};\n  }\n  this._file = util.getArg(aArgs, 'file', null);\n  this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n  this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n  this._ignoreInvalidMapping = util.getArg(aArgs, 'ignoreInvalidMapping', false);\n  this._sources = new ArraySet();\n  this._names = new ArraySet();\n  this._mappings = new MappingList();\n  this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n  function SourceMapGenerator_fromSourceMap(aSourceMapConsumer, generatorOps) {\n    var sourceRoot = aSourceMapConsumer.sourceRoot;\n    var generator = new SourceMapGenerator(Object.assign(generatorOps || {}, {\n      file: aSourceMapConsumer.file,\n      sourceRoot: sourceRoot\n    }));\n    aSourceMapConsumer.eachMapping(function (mapping) {\n      var newMapping = {\n        generated: {\n          line: mapping.generatedLine,\n          column: mapping.generatedColumn\n        }\n      };\n\n      if (mapping.source != null) {\n        newMapping.source = mapping.source;\n        if (sourceRoot != null) {\n          newMapping.source = util.relative(sourceRoot, newMapping.source);\n        }\n\n        newMapping.original = {\n          line: mapping.originalLine,\n          column: mapping.originalColumn\n        };\n\n        if (mapping.name != null) {\n          newMapping.name = mapping.name;\n        }\n      }\n\n      generator.addMapping(newMapping);\n    });\n    aSourceMapConsumer.sources.forEach(function (sourceFile) {\n      var sourceRelative = sourceFile;\n      if (sourceRoot !== null) {\n        sourceRelative = util.relative(sourceRoot, sourceFile);\n      }\n\n      if (!generator._sources.has(sourceRelative)) {\n        generator._sources.add(sourceRelative);\n      }\n\n      var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n      if (content != null) {\n        generator.setSourceContent(sourceFile, content);\n      }\n    });\n    return generator;\n  };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n *   - generated: An object with the generated line and column positions.\n *   - original: An object with the original line and column positions.\n *   - source: The original source file (relative to the sourceRoot).\n *   - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n  function SourceMapGenerator_addMapping(aArgs) {\n    var generated = util.getArg(aArgs, 'generated');\n    var original = util.getArg(aArgs, 'original', null);\n    var source = util.getArg(aArgs, 'source', null);\n    var name = util.getArg(aArgs, 'name', null);\n\n    if (!this._skipValidation) {\n      if (this._validateMapping(generated, original, source, name) === false) {\n        return;\n      }\n    }\n\n    if (source != null) {\n      source = String(source);\n      if (!this._sources.has(source)) {\n        this._sources.add(source);\n      }\n    }\n\n    if (name != null) {\n      name = String(name);\n      if (!this._names.has(name)) {\n        this._names.add(name);\n      }\n    }\n\n    this._mappings.add({\n      generatedLine: generated.line,\n      generatedColumn: generated.column,\n      originalLine: original != null && original.line,\n      originalColumn: original != null && original.column,\n      source: source,\n      name: name\n    });\n  };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n  function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n    var source = aSourceFile;\n    if (this._sourceRoot != null) {\n      source = util.relative(this._sourceRoot, source);\n    }\n\n    if (aSourceContent != null) {\n      // Add the source content to the _sourcesContents map.\n      // Create a new _sourcesContents map if the property is null.\n      if (!this._sourcesContents) {\n        this._sourcesContents = Object.create(null);\n      }\n      this._sourcesContents[util.toSetString(source)] = aSourceContent;\n    } else if (this._sourcesContents) {\n      // Remove the source file from the _sourcesContents map.\n      // If the _sourcesContents map is empty, set the property to null.\n      delete this._sourcesContents[util.toSetString(source)];\n      if (Object.keys(this._sourcesContents).length === 0) {\n        this._sourcesContents = null;\n      }\n    }\n  };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n *        If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n *        to be applied. If relative, it is relative to the SourceMapConsumer.\n *        This parameter is needed when the two source maps aren't in the same\n *        directory, and the source map to be applied contains relative source\n *        paths. If so, those relative source paths need to be rewritten\n *        relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n  function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n    var sourceFile = aSourceFile;\n    // If aSourceFile is omitted, we will use the file property of the SourceMap\n    if (aSourceFile == null) {\n      if (aSourceMapConsumer.file == null) {\n        throw new Error(\n          'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n          'or the source map\\'s \"file\" property. Both were omitted.'\n        );\n      }\n      sourceFile = aSourceMapConsumer.file;\n    }\n    var sourceRoot = this._sourceRoot;\n    // Make \"sourceFile\" relative if an absolute Url is passed.\n    if (sourceRoot != null) {\n      sourceFile = util.relative(sourceRoot, sourceFile);\n    }\n    // Applying the SourceMap can add and remove items from the sources and\n    // the names array.\n    var newSources = new ArraySet();\n    var newNames = new ArraySet();\n\n    // Find mappings for the \"sourceFile\"\n    this._mappings.unsortedForEach(function (mapping) {\n      if (mapping.source === sourceFile && mapping.originalLine != null) {\n        // Check if it can be mapped by the source map, then update the mapping.\n        var original = aSourceMapConsumer.originalPositionFor({\n          line: mapping.originalLine,\n          column: mapping.originalColumn\n        });\n        if (original.source != null) {\n          // Copy mapping\n          mapping.source = original.source;\n          if (aSourceMapPath != null) {\n            mapping.source = util.join(aSourceMapPath, mapping.source)\n          }\n          if (sourceRoot != null) {\n            mapping.source = util.relative(sourceRoot, mapping.source);\n          }\n          mapping.originalLine = original.line;\n          mapping.originalColumn = original.column;\n          if (original.name != null) {\n            mapping.name = original.name;\n          }\n        }\n      }\n\n      var source = mapping.source;\n      if (source != null && !newSources.has(source)) {\n        newSources.add(source);\n      }\n\n      var name = mapping.name;\n      if (name != null && !newNames.has(name)) {\n        newNames.add(name);\n      }\n\n    }, this);\n    this._sources = newSources;\n    this._names = newNames;\n\n    // Copy sourcesContents of applied map.\n    aSourceMapConsumer.sources.forEach(function (sourceFile) {\n      var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n      if (content != null) {\n        if (aSourceMapPath != null) {\n          sourceFile = util.join(aSourceMapPath, sourceFile);\n        }\n        if (sourceRoot != null) {\n          sourceFile = util.relative(sourceRoot, sourceFile);\n        }\n        this.setSourceContent(sourceFile, content);\n      }\n    }, this);\n  };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n *   1. Just the generated position.\n *   2. The Generated position, original position, and original source.\n *   3. Generated and original position, original source, as well as a name\n *      token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n  function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n                                              aName) {\n    // When aOriginal is truthy but has empty values for .line and .column,\n    // it is most likely a programmer error. In this case we throw a very\n    // specific error message to try to guide them the right way.\n    // For example: https://github.com/Polymer/polymer-bundler/pull/519\n    if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n      var message = 'original.line and original.column are not numbers -- you probably meant to omit ' +\n      'the original mapping entirely and only map the generated position. If so, pass ' +\n      'null for the original mapping instead of an object with empty or null values.'\n\n      if (this._ignoreInvalidMapping) {\n        if (typeof console !== 'undefined' && console.warn) {\n          console.warn(message);\n        }\n        return false;\n      } else {\n        throw new Error(message);\n      }\n    }\n\n    if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n        && aGenerated.line > 0 && aGenerated.column >= 0\n        && !aOriginal && !aSource && !aName) {\n      // Case 1.\n      return;\n    }\n    else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n             && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n             && aGenerated.line > 0 && aGenerated.column >= 0\n             && aOriginal.line > 0 && aOriginal.column >= 0\n             && aSource) {\n      // Cases 2 and 3.\n      return;\n    }\n    else {\n      var message = 'Invalid mapping: ' + JSON.stringify({\n        generated: aGenerated,\n        source: aSource,\n        original: aOriginal,\n        name: aName\n      });\n\n      if (this._ignoreInvalidMapping) {\n        if (typeof console !== 'undefined' && console.warn) {\n          console.warn(message);\n        }\n        return false;\n      } else {\n        throw new Error(message)\n      }\n    }\n  };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n  function SourceMapGenerator_serializeMappings() {\n    var previousGeneratedColumn = 0;\n    var previousGeneratedLine = 1;\n    var previousOriginalColumn = 0;\n    var previousOriginalLine = 0;\n    var previousName = 0;\n    var previousSource = 0;\n    var result = '';\n    var next;\n    var mapping;\n    var nameIdx;\n    var sourceIdx;\n\n    var mappings = this._mappings.toArray();\n    for (var i = 0, len = mappings.length; i < len; i++) {\n      mapping = mappings[i];\n      next = ''\n\n      if (mapping.generatedLine !== previousGeneratedLine) {\n        previousGeneratedColumn = 0;\n        while (mapping.generatedLine !== previousGeneratedLine) {\n          next += ';';\n          previousGeneratedLine++;\n        }\n      }\n      else {\n        if (i > 0) {\n          if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n            continue;\n          }\n          next += ',';\n        }\n      }\n\n      next += base64VLQ.encode(mapping.generatedColumn\n                                 - previousGeneratedColumn);\n      previousGeneratedColumn = mapping.generatedColumn;\n\n      if (mapping.source != null) {\n        sourceIdx = this._sources.indexOf(mapping.source);\n        next += base64VLQ.encode(sourceIdx - previousSource);\n        previousSource = sourceIdx;\n\n        // lines are stored 0-based in SourceMap spec version 3\n        next += base64VLQ.encode(mapping.originalLine - 1\n                                   - previousOriginalLine);\n        previousOriginalLine = mapping.originalLine - 1;\n\n        next += base64VLQ.encode(mapping.originalColumn\n                                   - previousOriginalColumn);\n        previousOriginalColumn = mapping.originalColumn;\n\n        if (mapping.name != null) {\n          nameIdx = this._names.indexOf(mapping.name);\n          next += base64VLQ.encode(nameIdx - previousName);\n          previousName = nameIdx;\n        }\n      }\n\n      result += next;\n    }\n\n    return result;\n  };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n  function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n    return aSources.map(function (source) {\n      if (!this._sourcesContents) {\n        return null;\n      }\n      if (aSourceRoot != null) {\n        source = util.relative(aSourceRoot, source);\n      }\n      var key = util.toSetString(source);\n      return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n        ? this._sourcesContents[key]\n        : null;\n    }, this);\n  };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n  function SourceMapGenerator_toJSON() {\n    var map = {\n      version: this._version,\n      sources: this._sources.toArray(),\n      names: this._names.toArray(),\n      mappings: this._serializeMappings()\n    };\n    if (this._file != null) {\n      map.file = this._file;\n    }\n    if (this._sourceRoot != null) {\n      map.sourceRoot = this._sourceRoot;\n    }\n    if (this._sourcesContents) {\n      map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n    }\n\n    return map;\n  };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n  function SourceMapGenerator_toString() {\n    return JSON.stringify(this.toJSON());\n  };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n *     'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n *     closest element that is smaller than or greater than the one we are\n *     searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n  // This function terminates when one of the following is true:\n  //\n  //   1. We find the exact element we are looking for.\n  //\n  //   2. We did not find the exact element, but we can return the index of\n  //      the next-closest element.\n  //\n  //   3. We did not find the exact element, and there is no next-closest\n  //      element than the one we are searching for, so we return -1.\n  var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n  var cmp = aCompare(aNeedle, aHaystack[mid], true);\n  if (cmp === 0) {\n    // Found the element we are looking for.\n    return mid;\n  }\n  else if (cmp > 0) {\n    // Our needle is greater than aHaystack[mid].\n    if (aHigh - mid > 1) {\n      // The element is in the upper half.\n      return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n    }\n\n    // The exact needle element was not found in this haystack. Determine if\n    // we are in termination case (3) or (2) and return the appropriate thing.\n    if (aBias == exports.LEAST_UPPER_BOUND) {\n      return aHigh < aHaystack.length ? aHigh : -1;\n    } else {\n      return mid;\n    }\n  }\n  else {\n    // Our needle is less than aHaystack[mid].\n    if (mid - aLow > 1) {\n      // The element is in the lower half.\n      return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n    }\n\n    // we are in termination case (3) or (2) and return the appropriate thing.\n    if (aBias == exports.LEAST_UPPER_BOUND) {\n      return mid;\n    } else {\n      return aLow < 0 ? -1 : aLow;\n    }\n  }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n *     array and returns -1, 0, or 1 depending on whether the needle is less\n *     than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n *     'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n *     closest element that is smaller than or greater than the one we are\n *     searching for, respectively, if the exact element cannot be found.\n *     Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n  if (aHaystack.length === 0) {\n    return -1;\n  }\n\n  var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n                              aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n  if (index < 0) {\n    return -1;\n  }\n\n  // We have found either the exact element, or the next-closest element than\n  // the one we are searching for. However, there may be more than one such\n  // element. Make sure we always return the smallest of these.\n  while (index - 1 >= 0) {\n    if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n      break;\n    }\n    --index;\n  }\n\n  return index;\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\nfunction SortTemplate(comparator) {\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n *        The array.\n * @param {Number} x\n *        The index of the first item.\n * @param {Number} y\n *        The index of the second item.\n */\nfunction swap(ary, x, y) {\n  var temp = ary[x];\n  ary[x] = ary[y];\n  ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n *        The lower bound on the range.\n * @param {Number} high\n *        The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n  return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n *        An array to sort.\n * @param {function} comparator\n *        Function to use to compare two items.\n * @param {Number} p\n *        Start index of the array\n * @param {Number} r\n *        End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n  // If our lower bound is less than our upper bound, we (1) partition the\n  // array into two pieces and (2) recurse on each half. If it is not, this is\n  // the empty array and our base case.\n\n  if (p < r) {\n    // (1) Partitioning.\n    //\n    // The partitioning chooses a pivot between `p` and `r` and moves all\n    // elements that are less than or equal to the pivot to the before it, and\n    // all the elements that are greater than it after it. The effect is that\n    // once partition is done, the pivot is in the exact place it will be when\n    // the array is put in sorted order, and it will not need to be moved\n    // again. This runs in O(n) time.\n\n    // Always choose a random pivot so that an input array which is reverse\n    // sorted does not cause O(n^2) running time.\n    var pivotIndex = randomIntInRange(p, r);\n    var i = p - 1;\n\n    swap(ary, pivotIndex, r);\n    var pivot = ary[r];\n\n    // Immediately after `j` is incremented in this loop, the following hold\n    // true:\n    //\n    //   * Every element in `ary[p .. i]` is less than or equal to the pivot.\n    //\n    //   * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n    for (var j = p; j < r; j++) {\n      if (comparator(ary[j], pivot, false) <= 0) {\n        i += 1;\n        swap(ary, i, j);\n      }\n    }\n\n    swap(ary, i + 1, j);\n    var q = i + 1;\n\n    // (2) Recurse on each half.\n\n    doQuickSort(ary, comparator, p, q - 1);\n    doQuickSort(ary, comparator, q + 1, r);\n  }\n}\n\n  return doQuickSort;\n}\n\nfunction cloneSort(comparator) {\n  let template = SortTemplate.toString();\n  let templateFn = new Function(`return ${template}`)();\n  return templateFn(comparator);\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n *        An array to sort.\n * @param {function} comparator\n *        Function to use to compare two items.\n */\n\nlet sortCache = new WeakMap();\nexports.quickSort = function (ary, comparator, start = 0) {\n  let doQuickSort = sortCache.get(comparator);\n  if (doQuickSort === void 0) {\n    doQuickSort = cloneSort(comparator);\n    sortCache.set(comparator, doQuickSort);\n  }\n  doQuickSort(ary, comparator, start, ary.length - 1);\n};\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n  var sourceMap = aSourceMap;\n  if (typeof aSourceMap === 'string') {\n    sourceMap = util.parseSourceMapInput(aSourceMap);\n  }\n\n  return sourceMap.sections != null\n    ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n    : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n  return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n//     {\n//       generatedLine: The line number in the generated code,\n//       generatedColumn: The column number in the generated code,\n//       source: The path to the original source file that generated this\n//               chunk of code,\n//       originalLine: The line number in the original source that\n//                     corresponds to this chunk of generated code,\n//       originalColumn: The column number in the original source that\n//                       corresponds to this chunk of generated code,\n//       name: The name of the original symbol which generated this chunk of\n//             code.\n//     }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n  configurable: true,\n  enumerable: true,\n  get: function () {\n    if (!this.__generatedMappings) {\n      this._parseMappings(this._mappings, this.sourceRoot);\n    }\n\n    return this.__generatedMappings;\n  }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n  configurable: true,\n  enumerable: true,\n  get: function () {\n    if (!this.__originalMappings) {\n      this._parseMappings(this._mappings, this.sourceRoot);\n    }\n\n    return this.__originalMappings;\n  }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n  function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n    var c = aStr.charAt(index);\n    return c === \";\" || c === \",\";\n  };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n  function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n    throw new Error(\"Subclasses must implement _parseMappings\");\n  };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n *        The function that is called with each mapping.\n * @param Object aContext\n *        Optional. If specified, this object will be the value of `this` every\n *        time that `aCallback` is called.\n * @param aOrder\n *        Either `SourceMapConsumer.GENERATED_ORDER` or\n *        `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n *        iterate over the mappings sorted by the generated file's line/column\n *        order or the original's source/line/column order, respectively. Defaults to\n *        `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n  function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n    var context = aContext || null;\n    var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n    var mappings;\n    switch (order) {\n    case SourceMapConsumer.GENERATED_ORDER:\n      mappings = this._generatedMappings;\n      break;\n    case SourceMapConsumer.ORIGINAL_ORDER:\n      mappings = this._originalMappings;\n      break;\n    default:\n      throw new Error(\"Unknown order of iteration.\");\n    }\n\n    var sourceRoot = this.sourceRoot;\n    var boundCallback = aCallback.bind(context);\n    var names = this._names;\n    var sources = this._sources;\n    var sourceMapURL = this._sourceMapURL;\n\n    for (var i = 0, n = mappings.length; i < n; i++) {\n      var mapping = mappings[i];\n      var source = mapping.source === null ? null : sources.at(mapping.source);\n      if(source !== null) {\n        source = util.computeSourceURL(sourceRoot, source, sourceMapURL);\n      }\n      boundCallback({\n        source: source,\n        generatedLine: mapping.generatedLine,\n        generatedColumn: mapping.generatedColumn,\n        originalLine: mapping.originalLine,\n        originalColumn: mapping.originalColumn,\n        name: mapping.name === null ? null : names.at(mapping.name)\n      });\n    }\n  };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n *   - source: The filename of the original source.\n *   - line: The line number in the original source.  The line number is 1-based.\n *   - column: Optional. the column number in the original source.\n *    The column number is 0-based.\n *\n * and an array of objects is returned, each with the following properties:\n *\n *   - line: The line number in the generated source, or null.  The\n *    line number is 1-based.\n *   - column: The column number in the generated source, or null.\n *    The column number is 0-based.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n  function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n    var line = util.getArg(aArgs, 'line');\n\n    // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n    // returns the index of the closest mapping less than the needle. By\n    // setting needle.originalColumn to 0, we thus find the last mapping for\n    // the given line, provided such a mapping exists.\n    var needle = {\n      source: util.getArg(aArgs, 'source'),\n      originalLine: line,\n      originalColumn: util.getArg(aArgs, 'column', 0)\n    };\n\n    needle.source = this._findSourceIndex(needle.source);\n    if (needle.source < 0) {\n      return [];\n    }\n\n    var mappings = [];\n\n    var index = this._findMapping(needle,\n                                  this._originalMappings,\n                                  \"originalLine\",\n                                  \"originalColumn\",\n                                  util.compareByOriginalPositions,\n                                  binarySearch.LEAST_UPPER_BOUND);\n    if (index >= 0) {\n      var mapping = this._originalMappings[index];\n\n      if (aArgs.column === undefined) {\n        var originalLine = mapping.originalLine;\n\n        // Iterate until either we run out of mappings, or we run into\n        // a mapping for a different line than the one we found. Since\n        // mappings are sorted, this is guaranteed to find all mappings for\n        // the line we found.\n        while (mapping && mapping.originalLine === originalLine) {\n          mappings.push({\n            line: util.getArg(mapping, 'generatedLine', null),\n            column: util.getArg(mapping, 'generatedColumn', null),\n            lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n          });\n\n          mapping = this._originalMappings[++index];\n        }\n      } else {\n        var originalColumn = mapping.originalColumn;\n\n        // Iterate until either we run out of mappings, or we run into\n        // a mapping for a different line than the one we were searching for.\n        // Since mappings are sorted, this is guaranteed to find all mappings for\n        // the line we are searching for.\n        while (mapping &&\n               mapping.originalLine === line &&\n               mapping.originalColumn == originalColumn) {\n          mappings.push({\n            line: util.getArg(mapping, 'generatedLine', null),\n            column: util.getArg(mapping, 'generatedColumn', null),\n            lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n          });\n\n          mapping = this._originalMappings[++index];\n        }\n      }\n    }\n\n    return mappings;\n  };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The first parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n *   - version: Which version of the source map spec this map is following.\n *   - sources: An array of URLs to the original source files.\n *   - names: An array of identifiers which can be referrenced by individual mappings.\n *   - sourceRoot: Optional. The URL root from which all sources are relative.\n *   - sourcesContent: Optional. An array of contents of the original source files.\n *   - mappings: A string of base64 VLQs which contain the actual mappings.\n *   - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n *     {\n *       version : 3,\n *       file: \"out.js\",\n *       sourceRoot : \"\",\n *       sources: [\"foo.js\", \"bar.js\"],\n *       names: [\"src\", \"maps\", \"are\", \"fun\"],\n *       mappings: \"AA,AB;;ABCDE;\"\n *     }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found.  This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n  var sourceMap = aSourceMap;\n  if (typeof aSourceMap === 'string') {\n    sourceMap = util.parseSourceMapInput(aSourceMap);\n  }\n\n  var version = util.getArg(sourceMap, 'version');\n  var sources = util.getArg(sourceMap, 'sources');\n  // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n  // requires the array) to play nice here.\n  var names = util.getArg(sourceMap, 'names', []);\n  var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n  var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n  var mappings = util.getArg(sourceMap, 'mappings');\n  var file = util.getArg(sourceMap, 'file', null);\n\n  // Once again, Sass deviates from the spec and supplies the version as a\n  // string rather than a number, so we use loose equality checking here.\n  if (version != this._version) {\n    throw new Error('Unsupported version: ' + version);\n  }\n\n  if (sourceRoot) {\n    sourceRoot = util.normalize(sourceRoot);\n  }\n\n  sources = sources\n    .map(String)\n    // Some source maps produce relative source paths like \"./foo.js\" instead of\n    // \"foo.js\".  Normalize these first so that future comparisons will succeed.\n    // See bugzil.la/1090768.\n    .map(util.normalize)\n    // Always ensure that absolute sources are internally stored relative to\n    // the source root, if the source root is absolute. Not doing this would\n    // be particularly problematic when the source root is a prefix of the\n    // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n    .map(function (source) {\n      return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n        ? util.relative(sourceRoot, source)\n        : source;\n    });\n\n  // Pass `true` below to allow duplicate names and sources. While source maps\n  // are intended to be compressed and deduplicated, the TypeScript compiler\n  // sometimes generates source maps with duplicates in them. See Github issue\n  // #72 and bugzil.la/889492.\n  this._names = ArraySet.fromArray(names.map(String), true);\n  this._sources = ArraySet.fromArray(sources, true);\n\n  this._absoluteSources = this._sources.toArray().map(function (s) {\n    return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n  });\n\n  this.sourceRoot = sourceRoot;\n  this.sourcesContent = sourcesContent;\n  this._mappings = mappings;\n  this._sourceMapURL = aSourceMapURL;\n  this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Utility function to find the index of a source.  Returns -1 if not\n * found.\n */\nBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n  var relativeSource = aSource;\n  if (this.sourceRoot != null) {\n    relativeSource = util.relative(this.sourceRoot, relativeSource);\n  }\n\n  if (this._sources.has(relativeSource)) {\n    return this._sources.indexOf(relativeSource);\n  }\n\n  // Maybe aSource is an absolute URL as returned by |sources|.  In\n  // this case we can't simply undo the transform.\n  var i;\n  for (i = 0; i < this._absoluteSources.length; ++i) {\n    if (this._absoluteSources[i] == aSource) {\n      return i;\n    }\n  }\n\n  return -1;\n};\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n *        The source map that will be consumed.\n * @param String aSourceMapURL\n *        The URL at which the source map can be found (optional)\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n  function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n    var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n    var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n    var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n    smc.sourceRoot = aSourceMap._sourceRoot;\n    smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n                                                            smc.sourceRoot);\n    smc.file = aSourceMap._file;\n    smc._sourceMapURL = aSourceMapURL;\n    smc._absoluteSources = smc._sources.toArray().map(function (s) {\n      return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n    });\n\n    // Because we are modifying the entries (by converting string sources and\n    // names to indices into the sources and names ArraySets), we have to make\n    // a copy of the entry or else bad things happen. Shared mutable state\n    // strikes again! See github issue #191.\n\n    var generatedMappings = aSourceMap._mappings.toArray().slice();\n    var destGeneratedMappings = smc.__generatedMappings = [];\n    var destOriginalMappings = smc.__originalMappings = [];\n\n    for (var i = 0, length = generatedMappings.length; i < length; i++) {\n      var srcMapping = generatedMappings[i];\n      var destMapping = new Mapping;\n      destMapping.generatedLine = srcMapping.generatedLine;\n      destMapping.generatedColumn = srcMapping.generatedColumn;\n\n      if (srcMapping.source) {\n        destMapping.source = sources.indexOf(srcMapping.source);\n        destMapping.originalLine = srcMapping.originalLine;\n        destMapping.originalColumn = srcMapping.originalColumn;\n\n        if (srcMapping.name) {\n          destMapping.name = names.indexOf(srcMapping.name);\n        }\n\n        destOriginalMappings.push(destMapping);\n      }\n\n      destGeneratedMappings.push(destMapping);\n    }\n\n    quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n    return smc;\n  };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n  get: function () {\n    return this._absoluteSources.slice();\n  }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n  this.generatedLine = 0;\n  this.generatedColumn = 0;\n  this.source = null;\n  this.originalLine = null;\n  this.originalColumn = null;\n  this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\n\nconst compareGenerated = util.compareByGeneratedPositionsDeflatedNoLine;\nfunction sortGenerated(array, start) {\n  let l = array.length;\n  let n = array.length - start;\n  if (n <= 1) {\n    return;\n  } else if (n == 2) {\n    let a = array[start];\n    let b = array[start + 1];\n    if (compareGenerated(a, b) > 0) {\n      array[start] = b;\n      array[start + 1] = a;\n    }\n  } else if (n < 20) {\n    for (let i = start; i < l; i++) {\n      for (let j = i; j > start; j--) {\n        let a = array[j - 1];\n        let b = array[j];\n        if (compareGenerated(a, b) <= 0) {\n          break;\n        }\n        array[j - 1] = b;\n        array[j] = a;\n      }\n    }\n  } else {\n    quickSort(array, compareGenerated, start);\n  }\n}\nBasicSourceMapConsumer.prototype._parseMappings =\n  function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n    var generatedLine = 1;\n    var previousGeneratedColumn = 0;\n    var previousOriginalLine = 0;\n    var previousOriginalColumn = 0;\n    var previousSource = 0;\n    var previousName = 0;\n    var length = aStr.length;\n    var index = 0;\n    var cachedSegments = {};\n    var temp = {};\n    var originalMappings = [];\n    var generatedMappings = [];\n    var mapping, str, segment, end, value;\n\n    let subarrayStart = 0;\n    while (index < length) {\n      if (aStr.charAt(index) === ';') {\n        generatedLine++;\n        index++;\n        previousGeneratedColumn = 0;\n\n        sortGenerated(generatedMappings, subarrayStart);\n        subarrayStart = generatedMappings.length;\n      }\n      else if (aStr.charAt(index) === ',') {\n        index++;\n      }\n      else {\n        mapping = new Mapping();\n        mapping.generatedLine = generatedLine;\n\n        for (end = index; end < length; end++) {\n          if (this._charIsMappingSeparator(aStr, end)) {\n            break;\n          }\n        }\n        str = aStr.slice(index, end);\n\n        segment = [];\n        while (index < end) {\n          base64VLQ.decode(aStr, index, temp);\n          value = temp.value;\n          index = temp.rest;\n          segment.push(value);\n        }\n\n        if (segment.length === 2) {\n          throw new Error('Found a source, but no line and column');\n        }\n\n        if (segment.length === 3) {\n          throw new Error('Found a source and line, but no column');\n        }\n\n        // Generated column.\n        mapping.generatedColumn = previousGeneratedColumn + segment[0];\n        previousGeneratedColumn = mapping.generatedColumn;\n\n        if (segment.length > 1) {\n          // Original source.\n          mapping.source = previousSource + segment[1];\n          previousSource += segment[1];\n\n          // Original line.\n          mapping.originalLine = previousOriginalLine + segment[2];\n          previousOriginalLine = mapping.originalLine;\n          // Lines are stored 0-based\n          mapping.originalLine += 1;\n\n          // Original column.\n          mapping.originalColumn = previousOriginalColumn + segment[3];\n          previousOriginalColumn = mapping.originalColumn;\n\n          if (segment.length > 4) {\n            // Original name.\n            mapping.name = previousName + segment[4];\n            previousName += segment[4];\n          }\n        }\n\n        generatedMappings.push(mapping);\n        if (typeof mapping.originalLine === 'number') {\n          let currentSource = mapping.source;\n          while (originalMappings.length <= currentSource) {\n            originalMappings.push(null);\n          }\n          if (originalMappings[currentSource] === null) {\n            originalMappings[currentSource] = [];\n          }\n          originalMappings[currentSource].push(mapping);\n        }\n      }\n    }\n\n    sortGenerated(generatedMappings, subarrayStart);\n    this.__generatedMappings = generatedMappings;\n\n    for (var i = 0; i < originalMappings.length; i++) {\n      if (originalMappings[i] != null) {\n        quickSort(originalMappings[i], util.compareByOriginalPositionsNoSource);\n      }\n    }\n    this.__originalMappings = [].concat(...originalMappings);\n  };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n  function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n                                         aColumnName, aComparator, aBias) {\n    // To return the position we are searching for, we must first find the\n    // mapping for the given position and then return the opposite position it\n    // points to. Because the mappings are sorted, we can use binary search to\n    // find the best mapping.\n\n    if (aNeedle[aLineName] <= 0) {\n      throw new TypeError('Line must be greater than or equal to 1, got '\n                          + aNeedle[aLineName]);\n    }\n    if (aNeedle[aColumnName] < 0) {\n      throw new TypeError('Column must be greater than or equal to 0, got '\n                          + aNeedle[aColumnName]);\n    }\n\n    return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n  };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n  function SourceMapConsumer_computeColumnSpans() {\n    for (var index = 0; index < this._generatedMappings.length; ++index) {\n      var mapping = this._generatedMappings[index];\n\n      // Mappings do not contain a field for the last generated columnt. We\n      // can come up with an optimistic estimate, however, by assuming that\n      // mappings are contiguous (i.e. given two consecutive mappings, the\n      // first mapping ends where the second one starts).\n      if (index + 1 < this._generatedMappings.length) {\n        var nextMapping = this._generatedMappings[index + 1];\n\n        if (mapping.generatedLine === nextMapping.generatedLine) {\n          mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n          continue;\n        }\n      }\n\n      // The last mapping for each line spans the entire line.\n      mapping.lastGeneratedColumn = Infinity;\n    }\n  };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n *   - line: The line number in the generated source.  The line number\n *     is 1-based.\n *   - column: The column number in the generated source.  The column\n *     number is 0-based.\n *   - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n *     'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n *     closest element that is smaller than or greater than the one we are\n *     searching for, respectively, if the exact element cannot be found.\n *     Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n *   - source: The original source file, or null.\n *   - line: The line number in the original source, or null.  The\n *     line number is 1-based.\n *   - column: The column number in the original source, or null.  The\n *     column number is 0-based.\n *   - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n  function SourceMapConsumer_originalPositionFor(aArgs) {\n    var needle = {\n      generatedLine: util.getArg(aArgs, 'line'),\n      generatedColumn: util.getArg(aArgs, 'column')\n    };\n\n    var index = this._findMapping(\n      needle,\n      this._generatedMappings,\n      \"generatedLine\",\n      \"generatedColumn\",\n      util.compareByGeneratedPositionsDeflated,\n      util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n    );\n\n    if (index >= 0) {\n      var mapping = this._generatedMappings[index];\n\n      if (mapping.generatedLine === needle.generatedLine) {\n        var source = util.getArg(mapping, 'source', null);\n        if (source !== null) {\n          source = this._sources.at(source);\n          source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n        }\n        var name = util.getArg(mapping, 'name', null);\n        if (name !== null) {\n          name = this._names.at(name);\n        }\n        return {\n          source: source,\n          line: util.getArg(mapping, 'originalLine', null),\n          column: util.getArg(mapping, 'originalColumn', null),\n          name: name\n        };\n      }\n    }\n\n    return {\n      source: null,\n      line: null,\n      column: null,\n      name: null\n    };\n  };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n  function BasicSourceMapConsumer_hasContentsOfAllSources() {\n    if (!this.sourcesContent) {\n      return false;\n    }\n    return this.sourcesContent.length >= this._sources.size() &&\n      !this.sourcesContent.some(function (sc) { return sc == null; });\n  };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n  function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n    if (!this.sourcesContent) {\n      return null;\n    }\n\n    var index = this._findSourceIndex(aSource);\n    if (index >= 0) {\n      return this.sourcesContent[index];\n    }\n\n    var relativeSource = aSource;\n    if (this.sourceRoot != null) {\n      relativeSource = util.relative(this.sourceRoot, relativeSource);\n    }\n\n    var url;\n    if (this.sourceRoot != null\n        && (url = util.urlParse(this.sourceRoot))) {\n      // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n      // many users. We can help them out when they expect file:// URIs to\n      // behave like it would if they were running a local HTTP server. See\n      // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n      var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n      if (url.scheme == \"file\"\n          && this._sources.has(fileUriAbsPath)) {\n        return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n      }\n\n      if ((!url.path || url.path == \"/\")\n          && this._sources.has(\"/\" + relativeSource)) {\n        return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n      }\n    }\n\n    // This function is used recursively from\n    // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n    // don't want to throw if we can't find the source - we just want to\n    // return null, so we provide a flag to exit gracefully.\n    if (nullOnMissing) {\n      return null;\n    }\n    else {\n      throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n    }\n  };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n *   - source: The filename of the original source.\n *   - line: The line number in the original source.  The line number\n *     is 1-based.\n *   - column: The column number in the original source.  The column\n *     number is 0-based.\n *   - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n *     'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n *     closest element that is smaller than or greater than the one we are\n *     searching for, respectively, if the exact element cannot be found.\n *     Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n *   - line: The line number in the generated source, or null.  The\n *     line number is 1-based.\n *   - column: The column number in the generated source, or null.\n *     The column number is 0-based.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n  function SourceMapConsumer_generatedPositionFor(aArgs) {\n    var source = util.getArg(aArgs, 'source');\n    source = this._findSourceIndex(source);\n    if (source < 0) {\n      return {\n        line: null,\n        column: null,\n        lastColumn: null\n      };\n    }\n\n    var needle = {\n      source: source,\n      originalLine: util.getArg(aArgs, 'line'),\n      originalColumn: util.getArg(aArgs, 'column')\n    };\n\n    var index = this._findMapping(\n      needle,\n      this._originalMappings,\n      \"originalLine\",\n      \"originalColumn\",\n      util.compareByOriginalPositions,\n      util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n    );\n\n    if (index >= 0) {\n      var mapping = this._originalMappings[index];\n\n      if (mapping.source === needle.source) {\n        return {\n          line: util.getArg(mapping, 'generatedLine', null),\n          column: util.getArg(mapping, 'generatedColumn', null),\n          lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n        };\n      }\n    }\n\n    return {\n      line: null,\n      column: null,\n      lastColumn: null\n    };\n  };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The first parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n *   - version: Which version of the source map spec this map is following.\n *   - file: Optional. The generated file this source map is associated with.\n *   - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n *   - offset: The offset into the original specified at which this section\n *       begins to apply, defined as an object with a \"line\" and \"column\"\n *       field.\n *   - map: A source map definition. This source map could also be indexed,\n *       but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n *  {\n *    version : 3,\n *    file: \"app.js\",\n *    sections: [{\n *      offset: {line:100, column:10},\n *      map: {\n *        version : 3,\n *        file: \"section.js\",\n *        sources: [\"foo.js\", \"bar.js\"],\n *        names: [\"src\", \"maps\", \"are\", \"fun\"],\n *        mappings: \"AAAA,E;;ABCDE;\"\n *      }\n *    }],\n *  }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found.  This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n  var sourceMap = aSourceMap;\n  if (typeof aSourceMap === 'string') {\n    sourceMap = util.parseSourceMapInput(aSourceMap);\n  }\n\n  var version = util.getArg(sourceMap, 'version');\n  var sections = util.getArg(sourceMap, 'sections');\n\n  if (version != this._version) {\n    throw new Error('Unsupported version: ' + version);\n  }\n\n  this._sources = new ArraySet();\n  this._names = new ArraySet();\n\n  var lastOffset = {\n    line: -1,\n    column: 0\n  };\n  this._sections = sections.map(function (s) {\n    if (s.url) {\n      // The url field will require support for asynchronicity.\n      // See https://github.com/mozilla/source-map/issues/16\n      throw new Error('Support for url field in sections not implemented.');\n    }\n    var offset = util.getArg(s, 'offset');\n    var offsetLine = util.getArg(offset, 'line');\n    var offsetColumn = util.getArg(offset, 'column');\n\n    if (offsetLine < lastOffset.line ||\n        (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n      throw new Error('Section offsets must be ordered and non-overlapping.');\n    }\n    lastOffset = offset;\n\n    return {\n      generatedOffset: {\n        // The offset fields are 0-based, but we use 1-based indices when\n        // encoding/decoding from VLQ.\n        generatedLine: offsetLine + 1,\n        generatedColumn: offsetColumn + 1\n      },\n      consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n    }\n  });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n  get: function () {\n    var sources = [];\n    for (var i = 0; i < this._sections.length; i++) {\n      for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n        sources.push(this._sections[i].consumer.sources[j]);\n      }\n    }\n    return sources;\n  }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n *   - line: The line number in the generated source.  The line number\n *     is 1-based.\n *   - column: The column number in the generated source.  The column\n *     number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n *   - source: The original source file, or null.\n *   - line: The line number in the original source, or null.  The\n *     line number is 1-based.\n *   - column: The column number in the original source, or null.  The\n *     column number is 0-based.\n *   - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n  function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n    var needle = {\n      generatedLine: util.getArg(aArgs, 'line'),\n      generatedColumn: util.getArg(aArgs, 'column')\n    };\n\n    // Find the section containing the generated position we're trying to map\n    // to an original position.\n    var sectionIndex = binarySearch.search(needle, this._sections,\n      function(needle, section) {\n        var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n        if (cmp) {\n          return cmp;\n        }\n\n        return (needle.generatedColumn -\n                section.generatedOffset.generatedColumn);\n      });\n    var section = this._sections[sectionIndex];\n\n    if (!section) {\n      return {\n        source: null,\n        line: null,\n        column: null,\n        name: null\n      };\n    }\n\n    return section.consumer.originalPositionFor({\n      line: needle.generatedLine -\n        (section.generatedOffset.generatedLine - 1),\n      column: needle.generatedColumn -\n        (section.generatedOffset.generatedLine === needle.generatedLine\n         ? section.generatedOffset.generatedColumn - 1\n         : 0),\n      bias: aArgs.bias\n    });\n  };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n  function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n    return this._sections.every(function (s) {\n      return s.consumer.hasContentsOfAllSources();\n    });\n  };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n  function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n    for (var i = 0; i < this._sections.length; i++) {\n      var section = this._sections[i];\n\n      var content = section.consumer.sourceContentFor(aSource, true);\n      if (content || content === '') {\n        return content;\n      }\n    }\n    if (nullOnMissing) {\n      return null;\n    }\n    else {\n      throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n    }\n  };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n *   - source: The filename of the original source.\n *   - line: The line number in the original source.  The line number\n *     is 1-based.\n *   - column: The column number in the original source.  The column\n *     number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n *   - line: The line number in the generated source, or null.  The\n *     line number is 1-based. \n *   - column: The column number in the generated source, or null.\n *     The column number is 0-based.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n  function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n    for (var i = 0; i < this._sections.length; i++) {\n      var section = this._sections[i];\n\n      // Only consider this section if the requested source is in the list of\n      // sources of the consumer.\n      if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n        continue;\n      }\n      var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n      if (generatedPosition) {\n        var ret = {\n          line: generatedPosition.line +\n            (section.generatedOffset.generatedLine - 1),\n          column: generatedPosition.column +\n            (section.generatedOffset.generatedLine === generatedPosition.line\n             ? section.generatedOffset.generatedColumn - 1\n             : 0)\n        };\n        return ret;\n      }\n    }\n\n    return {\n      line: null,\n      column: null\n    };\n  };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n  function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n    this.__generatedMappings = [];\n    this.__originalMappings = [];\n    for (var i = 0; i < this._sections.length; i++) {\n      var section = this._sections[i];\n      var sectionMappings = section.consumer._generatedMappings;\n      for (var j = 0; j < sectionMappings.length; j++) {\n        var mapping = sectionMappings[j];\n\n        var source = section.consumer._sources.at(mapping.source);\n        if(source !== null) {\n          source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n        }\n        this._sources.add(source);\n        source = this._sources.indexOf(source);\n\n        var name = null;\n        if (mapping.name) {\n          name = section.consumer._names.at(mapping.name);\n          this._names.add(name);\n          name = this._names.indexOf(name);\n        }\n\n        // The mappings coming from the consumer for the section have\n        // generated positions relative to the start of the section, so we\n        // need to offset them to be relative to the start of the concatenated\n        // generated file.\n        var adjustedMapping = {\n          source: source,\n          generatedLine: mapping.generatedLine +\n            (section.generatedOffset.generatedLine - 1),\n          generatedColumn: mapping.generatedColumn +\n            (section.generatedOffset.generatedLine === mapping.generatedLine\n            ? section.generatedOffset.generatedColumn - 1\n            : 0),\n          originalLine: mapping.originalLine,\n          originalColumn: mapping.originalColumn,\n          name: name\n        };\n\n        this.__generatedMappings.push(adjustedMapping);\n        if (typeof adjustedMapping.originalLine === 'number') {\n          this.__originalMappings.push(adjustedMapping);\n        }\n      }\n    }\n\n    quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n    quickSort(this.__originalMappings, util.compareByOriginalPositions);\n  };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n","/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n *        generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n  this.children = [];\n  this.sourceContents = {};\n  this.line = aLine == null ? null : aLine;\n  this.column = aColumn == null ? null : aColumn;\n  this.source = aSource == null ? null : aSource;\n  this.name = aName == null ? null : aName;\n  this[isSourceNode] = true;\n  if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n *        SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n  function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n    // The SourceNode we want to fill with the generated code\n    // and the SourceMap\n    var node = new SourceNode();\n\n    // All even indices of this array are one line of the generated code,\n    // while all odd indices are the newlines between two adjacent lines\n    // (since `REGEX_NEWLINE` captures its match).\n    // Processed fragments are accessed by calling `shiftNextLine`.\n    var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n    var remainingLinesIndex = 0;\n    var shiftNextLine = function() {\n      var lineContents = getNextLine();\n      // The last line of a file might not have a newline.\n      var newLine = getNextLine() || \"\";\n      return lineContents + newLine;\n\n      function getNextLine() {\n        return remainingLinesIndex < remainingLines.length ?\n            remainingLines[remainingLinesIndex++] : undefined;\n      }\n    };\n\n    // We need to remember the position of \"remainingLines\"\n    var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n    // The generate SourceNodes we need a code range.\n    // To extract it current and last mapping is used.\n    // Here we store the last mapping.\n    var lastMapping = null;\n\n    aSourceMapConsumer.eachMapping(function (mapping) {\n      if (lastMapping !== null) {\n        // We add the code from \"lastMapping\" to \"mapping\":\n        // First check if there is a new line in between.\n        if (lastGeneratedLine < mapping.generatedLine) {\n          // Associate first line with \"lastMapping\"\n          addMappingWithCode(lastMapping, shiftNextLine());\n          lastGeneratedLine++;\n          lastGeneratedColumn = 0;\n          // The remaining code is added without mapping\n        } else {\n          // There is no new line in between.\n          // Associate the code between \"lastGeneratedColumn\" and\n          // \"mapping.generatedColumn\" with \"lastMapping\"\n          var nextLine = remainingLines[remainingLinesIndex] || '';\n          var code = nextLine.substr(0, mapping.generatedColumn -\n                                        lastGeneratedColumn);\n          remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n                                              lastGeneratedColumn);\n          lastGeneratedColumn = mapping.generatedColumn;\n          addMappingWithCode(lastMapping, code);\n          // No more remaining code, continue\n          lastMapping = mapping;\n          return;\n        }\n      }\n      // We add the generated code until the first mapping\n      // to the SourceNode without any mapping.\n      // Each line is added as separate string.\n      while (lastGeneratedLine < mapping.generatedLine) {\n        node.add(shiftNextLine());\n        lastGeneratedLine++;\n      }\n      if (lastGeneratedColumn < mapping.generatedColumn) {\n        var nextLine = remainingLines[remainingLinesIndex] || '';\n        node.add(nextLine.substr(0, mapping.generatedColumn));\n        remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n        lastGeneratedColumn = mapping.generatedColumn;\n      }\n      lastMapping = mapping;\n    }, this);\n    // We have processed all mappings.\n    if (remainingLinesIndex < remainingLines.length) {\n      if (lastMapping) {\n        // Associate the remaining code in the current line with \"lastMapping\"\n        addMappingWithCode(lastMapping, shiftNextLine());\n      }\n      // and add the remaining lines without any mapping\n      node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n    }\n\n    // Copy sourcesContent into SourceNode\n    aSourceMapConsumer.sources.forEach(function (sourceFile) {\n      var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n      if (content != null) {\n        if (aRelativePath != null) {\n          sourceFile = util.join(aRelativePath, sourceFile);\n        }\n        node.setSourceContent(sourceFile, content);\n      }\n    });\n\n    return node;\n\n    function addMappingWithCode(mapping, code) {\n      if (mapping === null || mapping.source === undefined) {\n        node.add(code);\n      } else {\n        var source = aRelativePath\n          ? util.join(aRelativePath, mapping.source)\n          : mapping.source;\n        node.add(new SourceNode(mapping.originalLine,\n                                mapping.originalColumn,\n                                source,\n                                code,\n                                mapping.name));\n      }\n    }\n  };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n *        SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n  if (Array.isArray(aChunk)) {\n    aChunk.forEach(function (chunk) {\n      this.add(chunk);\n    }, this);\n  }\n  else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n    if (aChunk) {\n      this.children.push(aChunk);\n    }\n  }\n  else {\n    throw new TypeError(\n      \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n    );\n  }\n  return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n *        SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n  if (Array.isArray(aChunk)) {\n    for (var i = aChunk.length-1; i >= 0; i--) {\n      this.prepend(aChunk[i]);\n    }\n  }\n  else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n    this.children.unshift(aChunk);\n  }\n  else {\n    throw new TypeError(\n      \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n    );\n  }\n  return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n  var chunk;\n  for (var i = 0, len = this.children.length; i < len; i++) {\n    chunk = this.children[i];\n    if (chunk[isSourceNode]) {\n      chunk.walk(aFn);\n    }\n    else {\n      if (chunk !== '') {\n        aFn(chunk, { source: this.source,\n                     line: this.line,\n                     column: this.column,\n                     name: this.name });\n      }\n    }\n  }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n  var newChildren;\n  var i;\n  var len = this.children.length;\n  if (len > 0) {\n    newChildren = [];\n    for (i = 0; i < len-1; i++) {\n      newChildren.push(this.children[i]);\n      newChildren.push(aSep);\n    }\n    newChildren.push(this.children[i]);\n    this.children = newChildren;\n  }\n  return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n  var lastChild = this.children[this.children.length - 1];\n  if (lastChild[isSourceNode]) {\n    lastChild.replaceRight(aPattern, aReplacement);\n  }\n  else if (typeof lastChild === 'string') {\n    this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n  }\n  else {\n    this.children.push(''.replace(aPattern, aReplacement));\n  }\n  return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n  function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n    this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n  };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n  function SourceNode_walkSourceContents(aFn) {\n    for (var i = 0, len = this.children.length; i < len; i++) {\n      if (this.children[i][isSourceNode]) {\n        this.children[i].walkSourceContents(aFn);\n      }\n    }\n\n    var sources = Object.keys(this.sourceContents);\n    for (var i = 0, len = sources.length; i < len; i++) {\n      aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n    }\n  };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n  var str = \"\";\n  this.walk(function (chunk) {\n    str += chunk;\n  });\n  return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n  var generated = {\n    code: \"\",\n    line: 1,\n    column: 0\n  };\n  var map = new SourceMapGenerator(aArgs);\n  var sourceMappingActive = false;\n  var lastOriginalSource = null;\n  var lastOriginalLine = null;\n  var lastOriginalColumn = null;\n  var lastOriginalName = null;\n  this.walk(function (chunk, original) {\n    generated.code += chunk;\n    if (original.source !== null\n        && original.line !== null\n        && original.column !== null) {\n      if(lastOriginalSource !== original.source\n         || lastOriginalLine !== original.line\n         || lastOriginalColumn !== original.column\n         || lastOriginalName !== original.name) {\n        map.addMapping({\n          source: original.source,\n          original: {\n            line: original.line,\n            column: original.column\n          },\n          generated: {\n            line: generated.line,\n            column: generated.column\n          },\n          name: original.name\n        });\n      }\n      lastOriginalSource = original.source;\n      lastOriginalLine = original.line;\n      lastOriginalColumn = original.column;\n      lastOriginalName = original.name;\n      sourceMappingActive = true;\n    } else if (sourceMappingActive) {\n      map.addMapping({\n        generated: {\n          line: generated.line,\n          column: generated.column\n        }\n      });\n      lastOriginalSource = null;\n      sourceMappingActive = false;\n    }\n    for (var idx = 0, length = chunk.length; idx < length; idx++) {\n      if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n        generated.line++;\n        generated.column = 0;\n        // Mappings end at eol\n        if (idx + 1 === length) {\n          lastOriginalSource = null;\n          sourceMappingActive = false;\n        } else if (sourceMappingActive) {\n          map.addMapping({\n            source: original.source,\n            original: {\n              line: original.line,\n              column: original.column\n            },\n            generated: {\n              line: generated.line,\n              column: generated.column\n            },\n            name: original.name\n          });\n        }\n      } else {\n        generated.column++;\n      }\n    }\n  });\n  this.walkSourceContents(function (sourceFile, sourceContent) {\n    map.setSourceContent(sourceFile, sourceContent);\n  });\n\n  return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n","/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n","/**\n* @vue/compiler-core v3.5.18\n* (c) 2018-present Yuxi (Evan) You and Vue contributors\n* @license MIT\n**/\n'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar shared = require('@vue/shared');\nvar decode_js = require('entities/lib/decode.js');\nvar parser = require('@babel/parser');\nvar estreeWalker = require('estree-walker');\nvar sourceMapJs = require('source-map-js');\n\nconst FRAGMENT = Symbol(``);\nconst TELEPORT = Symbol(``);\nconst SUSPENSE = Symbol(``);\nconst KEEP_ALIVE = Symbol(``);\nconst BASE_TRANSITION = Symbol(\n  ``\n);\nconst OPEN_BLOCK = Symbol(``);\nconst CREATE_BLOCK = Symbol(``);\nconst CREATE_ELEMENT_BLOCK = Symbol(\n  ``\n);\nconst CREATE_VNODE = Symbol(``);\nconst CREATE_ELEMENT_VNODE = Symbol(\n  ``\n);\nconst CREATE_COMMENT = Symbol(\n  ``\n);\nconst CREATE_TEXT = Symbol(\n  ``\n);\nconst CREATE_STATIC = Symbol(\n  ``\n);\nconst RESOLVE_COMPONENT = Symbol(\n  ``\n);\nconst RESOLVE_DYNAMIC_COMPONENT = Symbol(\n  ``\n);\nconst RESOLVE_DIRECTIVE = Symbol(\n  ``\n);\nconst RESOLVE_FILTER = Symbol(\n  ``\n);\nconst WITH_DIRECTIVES = Symbol(\n  ``\n);\nconst RENDER_LIST = Symbol(``);\nconst RENDER_SLOT = Symbol(``);\nconst CREATE_SLOTS = Symbol(``);\nconst TO_DISPLAY_STRING = Symbol(\n  ``\n);\nconst MERGE_PROPS = Symbol(``);\nconst NORMALIZE_CLASS = Symbol(\n  ``\n);\nconst NORMALIZE_STYLE = Symbol(\n  ``\n);\nconst NORMALIZE_PROPS = Symbol(\n  ``\n);\nconst GUARD_REACTIVE_PROPS = Symbol(\n  ``\n);\nconst TO_HANDLERS = Symbol(``);\nconst CAMELIZE = Symbol(``);\nconst CAPITALIZE = Symbol(``);\nconst TO_HANDLER_KEY = Symbol(\n  ``\n);\nconst SET_BLOCK_TRACKING = Symbol(\n  ``\n);\nconst PUSH_SCOPE_ID = Symbol(``);\nconst POP_SCOPE_ID = Symbol(``);\nconst WITH_CTX = Symbol(``);\nconst UNREF = Symbol(``);\nconst IS_REF = Symbol(``);\nconst WITH_MEMO = Symbol(``);\nconst IS_MEMO_SAME = Symbol(``);\nconst helperNameMap = {\n  [FRAGMENT]: `Fragment`,\n  [TELEPORT]: `Teleport`,\n  [SUSPENSE]: `Suspense`,\n  [KEEP_ALIVE]: `KeepAlive`,\n  [BASE_TRANSITION]: `BaseTransition`,\n  [OPEN_BLOCK]: `openBlock`,\n  [CREATE_BLOCK]: `createBlock`,\n  [CREATE_ELEMENT_BLOCK]: `createElementBlock`,\n  [CREATE_VNODE]: `createVNode`,\n  [CREATE_ELEMENT_VNODE]: `createElementVNode`,\n  [CREATE_COMMENT]: `createCommentVNode`,\n  [CREATE_TEXT]: `createTextVNode`,\n  [CREATE_STATIC]: `createStaticVNode`,\n  [RESOLVE_COMPONENT]: `resolveComponent`,\n  [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,\n  [RESOLVE_DIRECTIVE]: `resolveDirective`,\n  [RESOLVE_FILTER]: `resolveFilter`,\n  [WITH_DIRECTIVES]: `withDirectives`,\n  [RENDER_LIST]: `renderList`,\n  [RENDER_SLOT]: `renderSlot`,\n  [CREATE_SLOTS]: `createSlots`,\n  [TO_DISPLAY_STRING]: `toDisplayString`,\n  [MERGE_PROPS]: `mergeProps`,\n  [NORMALIZE_CLASS]: `normalizeClass`,\n  [NORMALIZE_STYLE]: `normalizeStyle`,\n  [NORMALIZE_PROPS]: `normalizeProps`,\n  [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,\n  [TO_HANDLERS]: `toHandlers`,\n  [CAMELIZE]: `camelize`,\n  [CAPITALIZE]: `capitalize`,\n  [TO_HANDLER_KEY]: `toHandlerKey`,\n  [SET_BLOCK_TRACKING]: `setBlockTracking`,\n  [PUSH_SCOPE_ID]: `pushScopeId`,\n  [POP_SCOPE_ID]: `popScopeId`,\n  [WITH_CTX]: `withCtx`,\n  [UNREF]: `unref`,\n  [IS_REF]: `isRef`,\n  [WITH_MEMO]: `withMemo`,\n  [IS_MEMO_SAME]: `isMemoSame`\n};\nfunction registerRuntimeHelpers(helpers) {\n  Object.getOwnPropertySymbols(helpers).forEach((s) => {\n    helperNameMap[s] = helpers[s];\n  });\n}\n\nconst Namespaces = {\n  \"HTML\": 0,\n  \"0\": \"HTML\",\n  \"SVG\": 1,\n  \"1\": \"SVG\",\n  \"MATH_ML\": 2,\n  \"2\": \"MATH_ML\"\n};\nconst NodeTypes = {\n  \"ROOT\": 0,\n  \"0\": \"ROOT\",\n  \"ELEMENT\": 1,\n  \"1\": \"ELEMENT\",\n  \"TEXT\": 2,\n  \"2\": \"TEXT\",\n  \"COMMENT\": 3,\n  \"3\": \"COMMENT\",\n  \"SIMPLE_EXPRESSION\": 4,\n  \"4\": \"SIMPLE_EXPRESSION\",\n  \"INTERPOLATION\": 5,\n  \"5\": \"INTERPOLATION\",\n  \"ATTRIBUTE\": 6,\n  \"6\": \"ATTRIBUTE\",\n  \"DIRECTIVE\": 7,\n  \"7\": \"DIRECTIVE\",\n  \"COMPOUND_EXPRESSION\": 8,\n  \"8\": \"COMPOUND_EXPRESSION\",\n  \"IF\": 9,\n  \"9\": \"IF\",\n  \"IF_BRANCH\": 10,\n  \"10\": \"IF_BRANCH\",\n  \"FOR\": 11,\n  \"11\": \"FOR\",\n  \"TEXT_CALL\": 12,\n  \"12\": \"TEXT_CALL\",\n  \"VNODE_CALL\": 13,\n  \"13\": \"VNODE_CALL\",\n  \"JS_CALL_EXPRESSION\": 14,\n  \"14\": \"JS_CALL_EXPRESSION\",\n  \"JS_OBJECT_EXPRESSION\": 15,\n  \"15\": \"JS_OBJECT_EXPRESSION\",\n  \"JS_PROPERTY\": 16,\n  \"16\": \"JS_PROPERTY\",\n  \"JS_ARRAY_EXPRESSION\": 17,\n  \"17\": \"JS_ARRAY_EXPRESSION\",\n  \"JS_FUNCTION_EXPRESSION\": 18,\n  \"18\": \"JS_FUNCTION_EXPRESSION\",\n  \"JS_CONDITIONAL_EXPRESSION\": 19,\n  \"19\": \"JS_CONDITIONAL_EXPRESSION\",\n  \"JS_CACHE_EXPRESSION\": 20,\n  \"20\": \"JS_CACHE_EXPRESSION\",\n  \"JS_BLOCK_STATEMENT\": 21,\n  \"21\": \"JS_BLOCK_STATEMENT\",\n  \"JS_TEMPLATE_LITERAL\": 22,\n  \"22\": \"JS_TEMPLATE_LITERAL\",\n  \"JS_IF_STATEMENT\": 23,\n  \"23\": \"JS_IF_STATEMENT\",\n  \"JS_ASSIGNMENT_EXPRESSION\": 24,\n  \"24\": \"JS_ASSIGNMENT_EXPRESSION\",\n  \"JS_SEQUENCE_EXPRESSION\": 25,\n  \"25\": \"JS_SEQUENCE_EXPRESSION\",\n  \"JS_RETURN_STATEMENT\": 26,\n  \"26\": \"JS_RETURN_STATEMENT\"\n};\nconst ElementTypes = {\n  \"ELEMENT\": 0,\n  \"0\": \"ELEMENT\",\n  \"COMPONENT\": 1,\n  \"1\": \"COMPONENT\",\n  \"SLOT\": 2,\n  \"2\": \"SLOT\",\n  \"TEMPLATE\": 3,\n  \"3\": \"TEMPLATE\"\n};\nconst ConstantTypes = {\n  \"NOT_CONSTANT\": 0,\n  \"0\": \"NOT_CONSTANT\",\n  \"CAN_SKIP_PATCH\": 1,\n  \"1\": \"CAN_SKIP_PATCH\",\n  \"CAN_CACHE\": 2,\n  \"2\": \"CAN_CACHE\",\n  \"CAN_STRINGIFY\": 3,\n  \"3\": \"CAN_STRINGIFY\"\n};\nconst locStub = {\n  start: { line: 1, column: 1, offset: 0 },\n  end: { line: 1, column: 1, offset: 0 },\n  source: \"\"\n};\nfunction createRoot(children, source = \"\") {\n  return {\n    type: 0,\n    source,\n    children,\n    helpers: /* @__PURE__ */ new Set(),\n    components: [],\n    directives: [],\n    hoists: [],\n    imports: [],\n    cached: [],\n    temps: 0,\n    codegenNode: void 0,\n    loc: locStub\n  };\n}\nfunction createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {\n  if (context) {\n    if (isBlock) {\n      context.helper(OPEN_BLOCK);\n      context.helper(getVNodeBlockHelper(context.inSSR, isComponent));\n    } else {\n      context.helper(getVNodeHelper(context.inSSR, isComponent));\n    }\n    if (directives) {\n      context.helper(WITH_DIRECTIVES);\n    }\n  }\n  return {\n    type: 13,\n    tag,\n    props,\n    children,\n    patchFlag,\n    dynamicProps,\n    directives,\n    isBlock,\n    disableTracking,\n    isComponent,\n    loc\n  };\n}\nfunction createArrayExpression(elements, loc = locStub) {\n  return {\n    type: 17,\n    loc,\n    elements\n  };\n}\nfunction createObjectExpression(properties, loc = locStub) {\n  return {\n    type: 15,\n    loc,\n    properties\n  };\n}\nfunction createObjectProperty(key, value) {\n  return {\n    type: 16,\n    loc: locStub,\n    key: shared.isString(key) ? createSimpleExpression(key, true) : key,\n    value\n  };\n}\nfunction createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0) {\n  return {\n    type: 4,\n    loc,\n    content,\n    isStatic,\n    constType: isStatic ? 3 : constType\n  };\n}\nfunction createInterpolation(content, loc) {\n  return {\n    type: 5,\n    loc,\n    content: shared.isString(content) ? createSimpleExpression(content, false, loc) : content\n  };\n}\nfunction createCompoundExpression(children, loc = locStub) {\n  return {\n    type: 8,\n    loc,\n    children\n  };\n}\nfunction createCallExpression(callee, args = [], loc = locStub) {\n  return {\n    type: 14,\n    loc,\n    callee,\n    arguments: args\n  };\n}\nfunction createFunctionExpression(params, returns = void 0, newline = false, isSlot = false, loc = locStub) {\n  return {\n    type: 18,\n    params,\n    returns,\n    newline,\n    isSlot,\n    loc\n  };\n}\nfunction createConditionalExpression(test, consequent, alternate, newline = true) {\n  return {\n    type: 19,\n    test,\n    consequent,\n    alternate,\n    newline,\n    loc: locStub\n  };\n}\nfunction createCacheExpression(index, value, needPauseTracking = false, inVOnce = false) {\n  return {\n    type: 20,\n    index,\n    value,\n    needPauseTracking,\n    inVOnce,\n    needArraySpread: false,\n    loc: locStub\n  };\n}\nfunction createBlockStatement(body) {\n  return {\n    type: 21,\n    body,\n    loc: locStub\n  };\n}\nfunction createTemplateLiteral(elements) {\n  return {\n    type: 22,\n    elements,\n    loc: locStub\n  };\n}\nfunction createIfStatement(test, consequent, alternate) {\n  return {\n    type: 23,\n    test,\n    consequent,\n    alternate,\n    loc: locStub\n  };\n}\nfunction createAssignmentExpression(left, right) {\n  return {\n    type: 24,\n    left,\n    right,\n    loc: locStub\n  };\n}\nfunction createSequenceExpression(expressions) {\n  return {\n    type: 25,\n    expressions,\n    loc: locStub\n  };\n}\nfunction createReturnStatement(returns) {\n  return {\n    type: 26,\n    returns,\n    loc: locStub\n  };\n}\nfunction getVNodeHelper(ssr, isComponent) {\n  return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;\n}\nfunction getVNodeBlockHelper(ssr, isComponent) {\n  return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;\n}\nfunction convertToBlock(node, { helper, removeHelper, inSSR }) {\n  if (!node.isBlock) {\n    node.isBlock = true;\n    removeHelper(getVNodeHelper(inSSR, node.isComponent));\n    helper(OPEN_BLOCK);\n    helper(getVNodeBlockHelper(inSSR, node.isComponent));\n  }\n}\n\nconst defaultDelimitersOpen = new Uint8Array([123, 123]);\nconst defaultDelimitersClose = new Uint8Array([125, 125]);\nfunction isTagStartChar(c) {\n  return c >= 97 && c <= 122 || c >= 65 && c <= 90;\n}\nfunction isWhitespace(c) {\n  return c === 32 || c === 10 || c === 9 || c === 12 || c === 13;\n}\nfunction isEndOfTagSection(c) {\n  return c === 47 || c === 62 || isWhitespace(c);\n}\nfunction toCharCodes(str) {\n  const ret = new Uint8Array(str.length);\n  for (let i = 0; i < str.length; i++) {\n    ret[i] = str.charCodeAt(i);\n  }\n  return ret;\n}\nconst Sequences = {\n  Cdata: new Uint8Array([67, 68, 65, 84, 65, 91]),\n  // CDATA[\n  CdataEnd: new Uint8Array([93, 93, 62]),\n  // ]]>\n  CommentEnd: new Uint8Array([45, 45, 62]),\n  // `-->`\n  ScriptEnd: new Uint8Array([60, 47, 115, 99, 114, 105, 112, 116]),\n  // `<\\/script`\n  StyleEnd: new Uint8Array([60, 47, 115, 116, 121, 108, 101]),\n  // `</style`\n  TitleEnd: new Uint8Array([60, 47, 116, 105, 116, 108, 101]),\n  // `</title`\n  TextareaEnd: new Uint8Array([\n    60,\n    47,\n    116,\n    101,\n    120,\n    116,\n    97,\n    114,\n    101,\n    97\n  ])\n  // `</textarea\n};\nclass Tokenizer {\n  constructor(stack, cbs) {\n    this.stack = stack;\n    this.cbs = cbs;\n    /** The current state the tokenizer is in. */\n    this.state = 1;\n    /** The read buffer. */\n    this.buffer = \"\";\n    /** The beginning of the section that is currently being read. */\n    this.sectionStart = 0;\n    /** The index within the buffer that we are currently looking at. */\n    this.index = 0;\n    /** The start of the last entity. */\n    this.entityStart = 0;\n    /** Some behavior, eg. when decoding entities, is done while we are in another state. This keeps track of the other state type. */\n    this.baseState = 1;\n    /** For special parsing behavior inside of script and style tags. */\n    this.inRCDATA = false;\n    /** For disabling RCDATA tags handling */\n    this.inXML = false;\n    /** For disabling interpolation parsing in v-pre */\n    this.inVPre = false;\n    /** Record newline positions for fast line / column calculation */\n    this.newlines = [];\n    this.mode = 0;\n    this.delimiterOpen = defaultDelimitersOpen;\n    this.delimiterClose = defaultDelimitersClose;\n    this.delimiterIndex = -1;\n    this.currentSequence = void 0;\n    this.sequenceIndex = 0;\n    {\n      this.entityDecoder = new decode_js.EntityDecoder(\n        decode_js.htmlDecodeTree,\n        (cp, consumed) => this.emitCodePoint(cp, consumed)\n      );\n    }\n  }\n  get inSFCRoot() {\n    return this.mode === 2 && this.stack.length === 0;\n  }\n  reset() {\n    this.state = 1;\n    this.mode = 0;\n    this.buffer = \"\";\n    this.sectionStart = 0;\n    this.index = 0;\n    this.baseState = 1;\n    this.inRCDATA = false;\n    this.currentSequence = void 0;\n    this.newlines.length = 0;\n    this.delimiterOpen = defaultDelimitersOpen;\n    this.delimiterClose = defaultDelimitersClose;\n  }\n  /**\n   * Generate Position object with line / column information using recorded\n   * newline positions. We know the index is always going to be an already\n   * processed index, so all the newlines up to this index should have been\n   * recorded.\n   */\n  getPos(index) {\n    let line = 1;\n    let column = index + 1;\n    for (let i = this.newlines.length - 1; i >= 0; i--) {\n      const newlineIndex = this.newlines[i];\n      if (index > newlineIndex) {\n        line = i + 2;\n        column = index - newlineIndex;\n        break;\n      }\n    }\n    return {\n      column,\n      line,\n      offset: index\n    };\n  }\n  peek() {\n    return this.buffer.charCodeAt(this.index + 1);\n  }\n  stateText(c) {\n    if (c === 60) {\n      if (this.index > this.sectionStart) {\n        this.cbs.ontext(this.sectionStart, this.index);\n      }\n      this.state = 5;\n      this.sectionStart = this.index;\n    } else if (c === 38) {\n      this.startEntity();\n    } else if (!this.inVPre && c === this.delimiterOpen[0]) {\n      this.state = 2;\n      this.delimiterIndex = 0;\n      this.stateInterpolationOpen(c);\n    }\n  }\n  stateInterpolationOpen(c) {\n    if (c === this.delimiterOpen[this.delimiterIndex]) {\n      if (this.delimiterIndex === this.delimiterOpen.length - 1) {\n        const start = this.index + 1 - this.delimiterOpen.length;\n        if (start > this.sectionStart) {\n          this.cbs.ontext(this.sectionStart, start);\n        }\n        this.state = 3;\n        this.sectionStart = start;\n      } else {\n        this.delimiterIndex++;\n      }\n    } else if (this.inRCDATA) {\n      this.state = 32;\n      this.stateInRCDATA(c);\n    } else {\n      this.state = 1;\n      this.stateText(c);\n    }\n  }\n  stateInterpolation(c) {\n    if (c === this.delimiterClose[0]) {\n      this.state = 4;\n      this.delimiterIndex = 0;\n      this.stateInterpolationClose(c);\n    }\n  }\n  stateInterpolationClose(c) {\n    if (c === this.delimiterClose[this.delimiterIndex]) {\n      if (this.delimiterIndex === this.delimiterClose.length - 1) {\n        this.cbs.oninterpolation(this.sectionStart, this.index + 1);\n        if (this.inRCDATA) {\n          this.state = 32;\n        } else {\n          this.state = 1;\n        }\n        this.sectionStart = this.index + 1;\n      } else {\n        this.delimiterIndex++;\n      }\n    } else {\n      this.state = 3;\n      this.stateInterpolation(c);\n    }\n  }\n  stateSpecialStartSequence(c) {\n    const isEnd = this.sequenceIndex === this.currentSequence.length;\n    const isMatch = isEnd ? (\n      // If we are at the end of the sequence, make sure the tag name has ended\n      isEndOfTagSection(c)\n    ) : (\n      // Otherwise, do a case-insensitive comparison\n      (c | 32) === this.currentSequence[this.sequenceIndex]\n    );\n    if (!isMatch) {\n      this.inRCDATA = false;\n    } else if (!isEnd) {\n      this.sequenceIndex++;\n      return;\n    }\n    this.sequenceIndex = 0;\n    this.state = 6;\n    this.stateInTagName(c);\n  }\n  /** Look for an end tag. For <title> and <textarea>, also decode entities. */\n  stateInRCDATA(c) {\n    if (this.sequenceIndex === this.currentSequence.length) {\n      if (c === 62 || isWhitespace(c)) {\n        const endOfText = this.index - this.currentSequence.length;\n        if (this.sectionStart < endOfText) {\n          const actualIndex = this.index;\n          this.index = endOfText;\n          this.cbs.ontext(this.sectionStart, endOfText);\n          this.index = actualIndex;\n        }\n        this.sectionStart = endOfText + 2;\n        this.stateInClosingTagName(c);\n        this.inRCDATA = false;\n        return;\n      }\n      this.sequenceIndex = 0;\n    }\n    if ((c | 32) === this.currentSequence[this.sequenceIndex]) {\n      this.sequenceIndex += 1;\n    } else if (this.sequenceIndex === 0) {\n      if (this.currentSequence === Sequences.TitleEnd || this.currentSequence === Sequences.TextareaEnd && !this.inSFCRoot) {\n        if (c === 38) {\n          this.startEntity();\n        } else if (!this.inVPre && c === this.delimiterOpen[0]) {\n          this.state = 2;\n          this.delimiterIndex = 0;\n          this.stateInterpolationOpen(c);\n        }\n      } else if (this.fastForwardTo(60)) {\n        this.sequenceIndex = 1;\n      }\n    } else {\n      this.sequenceIndex = Number(c === 60);\n    }\n  }\n  stateCDATASequence(c) {\n    if (c === Sequences.Cdata[this.sequenceIndex]) {\n      if (++this.sequenceIndex === Sequences.Cdata.length) {\n        this.state = 28;\n        this.currentSequence = Sequences.CdataEnd;\n        this.sequenceIndex = 0;\n        this.sectionStart = this.index + 1;\n      }\n    } else {\n      this.sequenceIndex = 0;\n      this.state = 23;\n      this.stateInDeclaration(c);\n    }\n  }\n  /**\n   * When we wait for one specific character, we can speed things up\n   * by skipping through the buffer until we find it.\n   *\n   * @returns Whether the character was found.\n   */\n  fastForwardTo(c) {\n    while (++this.index < this.buffer.length) {\n      const cc = this.buffer.charCodeAt(this.index);\n      if (cc === 10) {\n        this.newlines.push(this.index);\n      }\n      if (cc === c) {\n        return true;\n      }\n    }\n    this.index = this.buffer.length - 1;\n    return false;\n  }\n  /**\n   * Comments and CDATA end with `-->` and `]]>`.\n   *\n   * Their common qualities are:\n   * - Their end sequences have a distinct character they start with.\n   * - That character is then repeated, so we have to check multiple repeats.\n   * - All characters but the start character of the sequence can be skipped.\n   */\n  stateInCommentLike(c) {\n    if (c === this.currentSequence[this.sequenceIndex]) {\n      if (++this.sequenceIndex === this.currentSequence.length) {\n        if (this.currentSequence === Sequences.CdataEnd) {\n          this.cbs.oncdata(this.sectionStart, this.index - 2);\n        } else {\n          this.cbs.oncomment(this.sectionStart, this.index - 2);\n        }\n        this.sequenceIndex = 0;\n        this.sectionStart = this.index + 1;\n        this.state = 1;\n      }\n    } else if (this.sequenceIndex === 0) {\n      if (this.fastForwardTo(this.currentSequence[0])) {\n        this.sequenceIndex = 1;\n      }\n    } else if (c !== this.currentSequence[this.sequenceIndex - 1]) {\n      this.sequenceIndex = 0;\n    }\n  }\n  startSpecial(sequence, offset) {\n    this.enterRCDATA(sequence, offset);\n    this.state = 31;\n  }\n  enterRCDATA(sequence, offset) {\n    this.inRCDATA = true;\n    this.currentSequence = sequence;\n    this.sequenceIndex = offset;\n  }\n  stateBeforeTagName(c) {\n    if (c === 33) {\n      this.state = 22;\n      this.sectionStart = this.index + 1;\n    } else if (c === 63) {\n      this.state = 24;\n      this.sectionStart = this.index + 1;\n    } else if (isTagStartChar(c)) {\n      this.sectionStart = this.index;\n      if (this.mode === 0) {\n        this.state = 6;\n      } else if (this.inSFCRoot) {\n        this.state = 34;\n      } else if (!this.inXML) {\n        if (c === 116) {\n          this.state = 30;\n        } else {\n          this.state = c === 115 ? 29 : 6;\n        }\n      } else {\n        this.state = 6;\n      }\n    } else if (c === 47) {\n      this.state = 8;\n    } else {\n      this.state = 1;\n      this.stateText(c);\n    }\n  }\n  stateInTagName(c) {\n    if (isEndOfTagSection(c)) {\n      this.handleTagName(c);\n    }\n  }\n  stateInSFCRootTagName(c) {\n    if (isEndOfTagSection(c)) {\n      const tag = this.buffer.slice(this.sectionStart, this.index);\n      if (tag !== \"template\") {\n        this.enterRCDATA(toCharCodes(`</` + tag), 0);\n      }\n      this.handleTagName(c);\n    }\n  }\n  handleTagName(c) {\n    this.cbs.onopentagname(this.sectionStart, this.index);\n    this.sectionStart = -1;\n    this.state = 11;\n    this.stateBeforeAttrName(c);\n  }\n  stateBeforeClosingTagName(c) {\n    if (isWhitespace(c)) ; else if (c === 62) {\n      {\n        this.cbs.onerr(14, this.index);\n      }\n      this.state = 1;\n      this.sectionStart = this.index + 1;\n    } else {\n      this.state = isTagStartChar(c) ? 9 : 27;\n      this.sectionStart = this.index;\n    }\n  }\n  stateInClosingTagName(c) {\n    if (c === 62 || isWhitespace(c)) {\n      this.cbs.onclosetag(this.sectionStart, this.index);\n      this.sectionStart = -1;\n      this.state = 10;\n      this.stateAfterClosingTagName(c);\n    }\n  }\n  stateAfterClosingTagName(c) {\n    if (c === 62) {\n      this.state = 1;\n      this.sectionStart = this.index + 1;\n    }\n  }\n  stateBeforeAttrName(c) {\n    if (c === 62) {\n      this.cbs.onopentagend(this.index);\n      if (this.inRCDATA) {\n        this.state = 32;\n      } else {\n        this.state = 1;\n      }\n      this.sectionStart = this.index + 1;\n    } else if (c === 47) {\n      this.state = 7;\n      if (this.peek() !== 62) {\n        this.cbs.onerr(22, this.index);\n      }\n    } else if (c === 60 && this.peek() === 47) {\n      this.cbs.onopentagend(this.index);\n      this.state = 5;\n      this.sectionStart = this.index;\n    } else if (!isWhitespace(c)) {\n      if (c === 61) {\n        this.cbs.onerr(\n          19,\n          this.index\n        );\n      }\n      this.handleAttrStart(c);\n    }\n  }\n  handleAttrStart(c) {\n    if (c === 118 && this.peek() === 45) {\n      this.state = 13;\n      this.sectionStart = this.index;\n    } else if (c === 46 || c === 58 || c === 64 || c === 35) {\n      this.cbs.ondirname(this.index, this.index + 1);\n      this.state = 14;\n      this.sectionStart = this.index + 1;\n    } else {\n      this.state = 12;\n      this.sectionStart = this.index;\n    }\n  }\n  stateInSelfClosingTag(c) {\n    if (c === 62) {\n      this.cbs.onselfclosingtag(this.index);\n      this.state = 1;\n      this.sectionStart = this.index + 1;\n      this.inRCDATA = false;\n    } else if (!isWhitespace(c)) {\n      this.state = 11;\n      this.stateBeforeAttrName(c);\n    }\n  }\n  stateInAttrName(c) {\n    if (c === 61 || isEndOfTagSection(c)) {\n      this.cbs.onattribname(this.sectionStart, this.index);\n      this.handleAttrNameEnd(c);\n    } else if (c === 34 || c === 39 || c === 60) {\n      this.cbs.onerr(\n        17,\n        this.index\n      );\n    }\n  }\n  stateInDirName(c) {\n    if (c === 61 || isEndOfTagSection(c)) {\n      this.cbs.ondirname(this.sectionStart, this.index);\n      this.handleAttrNameEnd(c);\n    } else if (c === 58) {\n      this.cbs.ondirname(this.sectionStart, this.index);\n      this.state = 14;\n      this.sectionStart = this.index + 1;\n    } else if (c === 46) {\n      this.cbs.ondirname(this.sectionStart, this.index);\n      this.state = 16;\n      this.sectionStart = this.index + 1;\n    }\n  }\n  stateInDirArg(c) {\n    if (c === 61 || isEndOfTagSection(c)) {\n      this.cbs.ondirarg(this.sectionStart, this.index);\n      this.handleAttrNameEnd(c);\n    } else if (c === 91) {\n      this.state = 15;\n    } else if (c === 46) {\n      this.cbs.ondirarg(this.sectionStart, this.index);\n      this.state = 16;\n      this.sectionStart = this.index + 1;\n    }\n  }\n  stateInDynamicDirArg(c) {\n    if (c === 93) {\n      this.state = 14;\n    } else if (c === 61 || isEndOfTagSection(c)) {\n      this.cbs.ondirarg(this.sectionStart, this.index + 1);\n      this.handleAttrNameEnd(c);\n      {\n        this.cbs.onerr(\n          27,\n          this.index\n        );\n      }\n    }\n  }\n  stateInDirModifier(c) {\n    if (c === 61 || isEndOfTagSection(c)) {\n      this.cbs.ondirmodifier(this.sectionStart, this.index);\n      this.handleAttrNameEnd(c);\n    } else if (c === 46) {\n      this.cbs.ondirmodifier(this.sectionStart, this.index);\n      this.sectionStart = this.index + 1;\n    }\n  }\n  handleAttrNameEnd(c) {\n    this.sectionStart = this.index;\n    this.state = 17;\n    this.cbs.onattribnameend(this.index);\n    this.stateAfterAttrName(c);\n  }\n  stateAfterAttrName(c) {\n    if (c === 61) {\n      this.state = 18;\n    } else if (c === 47 || c === 62) {\n      this.cbs.onattribend(0, this.sectionStart);\n      this.sectionStart = -1;\n      this.state = 11;\n      this.stateBeforeAttrName(c);\n    } else if (!isWhitespace(c)) {\n      this.cbs.onattribend(0, this.sectionStart);\n      this.handleAttrStart(c);\n    }\n  }\n  stateBeforeAttrValue(c) {\n    if (c === 34) {\n      this.state = 19;\n      this.sectionStart = this.index + 1;\n    } else if (c === 39) {\n      this.state = 20;\n      this.sectionStart = this.index + 1;\n    } else if (!isWhitespace(c)) {\n      this.sectionStart = this.index;\n      this.state = 21;\n      this.stateInAttrValueNoQuotes(c);\n    }\n  }\n  handleInAttrValue(c, quote) {\n    if (c === quote || false) {\n      this.cbs.onattribdata(this.sectionStart, this.index);\n      this.sectionStart = -1;\n      this.cbs.onattribend(\n        quote === 34 ? 3 : 2,\n        this.index + 1\n      );\n      this.state = 11;\n    } else if (c === 38) {\n      this.startEntity();\n    }\n  }\n  stateInAttrValueDoubleQuotes(c) {\n    this.handleInAttrValue(c, 34);\n  }\n  stateInAttrValueSingleQuotes(c) {\n    this.handleInAttrValue(c, 39);\n  }\n  stateInAttrValueNoQuotes(c) {\n    if (isWhitespace(c) || c === 62) {\n      this.cbs.onattribdata(this.sectionStart, this.index);\n      this.sectionStart = -1;\n      this.cbs.onattribend(1, this.index);\n      this.state = 11;\n      this.stateBeforeAttrName(c);\n    } else if (c === 34 || c === 39 || c === 60 || c === 61 || c === 96) {\n      this.cbs.onerr(\n        18,\n        this.index\n      );\n    } else if (c === 38) {\n      this.startEntity();\n    }\n  }\n  stateBeforeDeclaration(c) {\n    if (c === 91) {\n      this.state = 26;\n      this.sequenceIndex = 0;\n    } else {\n      this.state = c === 45 ? 25 : 23;\n    }\n  }\n  stateInDeclaration(c) {\n    if (c === 62 || this.fastForwardTo(62)) {\n      this.state = 1;\n      this.sectionStart = this.index + 1;\n    }\n  }\n  stateInProcessingInstruction(c) {\n    if (c === 62 || this.fastForwardTo(62)) {\n      this.cbs.onprocessinginstruction(this.sectionStart, this.index);\n      this.state = 1;\n      this.sectionStart = this.index + 1;\n    }\n  }\n  stateBeforeComment(c) {\n    if (c === 45) {\n      this.state = 28;\n      this.currentSequence = Sequences.CommentEnd;\n      this.sequenceIndex = 2;\n      this.sectionStart = this.index + 1;\n    } else {\n      this.state = 23;\n    }\n  }\n  stateInSpecialComment(c) {\n    if (c === 62 || this.fastForwardTo(62)) {\n      this.cbs.oncomment(this.sectionStart, this.index);\n      this.state = 1;\n      this.sectionStart = this.index + 1;\n    }\n  }\n  stateBeforeSpecialS(c) {\n    if (c === Sequences.ScriptEnd[3]) {\n      this.startSpecial(Sequences.ScriptEnd, 4);\n    } else if (c === Sequences.StyleEnd[3]) {\n      this.startSpecial(Sequences.StyleEnd, 4);\n    } else {\n      this.state = 6;\n      this.stateInTagName(c);\n    }\n  }\n  stateBeforeSpecialT(c) {\n    if (c === Sequences.TitleEnd[3]) {\n      this.startSpecial(Sequences.TitleEnd, 4);\n    } else if (c === Sequences.TextareaEnd[3]) {\n      this.startSpecial(Sequences.TextareaEnd, 4);\n    } else {\n      this.state = 6;\n      this.stateInTagName(c);\n    }\n  }\n  startEntity() {\n    {\n      this.baseState = this.state;\n      this.state = 33;\n      this.entityStart = this.index;\n      this.entityDecoder.startEntity(\n        this.baseState === 1 || this.baseState === 32 ? decode_js.DecodingMode.Legacy : decode_js.DecodingMode.Attribute\n      );\n    }\n  }\n  stateInEntity() {\n    {\n      const length = this.entityDecoder.write(this.buffer, this.index);\n      if (length >= 0) {\n        this.state = this.baseState;\n        if (length === 0) {\n          this.index = this.entityStart;\n        }\n      } else {\n        this.index = this.buffer.length - 1;\n      }\n    }\n  }\n  /**\n   * Iterates through the buffer, calling the function corresponding to the current state.\n   *\n   * States that are more likely to be hit are higher up, as a performance improvement.\n   */\n  parse(input) {\n    this.buffer = input;\n    while (this.index < this.buffer.length) {\n      const c = this.buffer.charCodeAt(this.index);\n      if (c === 10 && this.state !== 33) {\n        this.newlines.push(this.index);\n      }\n      switch (this.state) {\n        case 1: {\n          this.stateText(c);\n          break;\n        }\n        case 2: {\n          this.stateInterpolationOpen(c);\n          break;\n        }\n        case 3: {\n          this.stateInterpolation(c);\n          break;\n        }\n        case 4: {\n          this.stateInterpolationClose(c);\n          break;\n        }\n        case 31: {\n          this.stateSpecialStartSequence(c);\n          break;\n        }\n        case 32: {\n          this.stateInRCDATA(c);\n          break;\n        }\n        case 26: {\n          this.stateCDATASequence(c);\n          break;\n        }\n        case 19: {\n          this.stateInAttrValueDoubleQuotes(c);\n          break;\n        }\n        case 12: {\n          this.stateInAttrName(c);\n          break;\n        }\n        case 13: {\n          this.stateInDirName(c);\n          break;\n        }\n        case 14: {\n          this.stateInDirArg(c);\n          break;\n        }\n        case 15: {\n          this.stateInDynamicDirArg(c);\n          break;\n        }\n        case 16: {\n          this.stateInDirModifier(c);\n          break;\n        }\n        case 28: {\n          this.stateInCommentLike(c);\n          break;\n        }\n        case 27: {\n          this.stateInSpecialComment(c);\n          break;\n        }\n        case 11: {\n          this.stateBeforeAttrName(c);\n          break;\n        }\n        case 6: {\n          this.stateInTagName(c);\n          break;\n        }\n        case 34: {\n          this.stateInSFCRootTagName(c);\n          break;\n        }\n        case 9: {\n          this.stateInClosingTagName(c);\n          break;\n        }\n        case 5: {\n          this.stateBeforeTagName(c);\n          break;\n        }\n        case 17: {\n          this.stateAfterAttrName(c);\n          break;\n        }\n        case 20: {\n          this.stateInAttrValueSingleQuotes(c);\n          break;\n        }\n        case 18: {\n          this.stateBeforeAttrValue(c);\n          break;\n        }\n        case 8: {\n          this.stateBeforeClosingTagName(c);\n          break;\n        }\n        case 10: {\n          this.stateAfterClosingTagName(c);\n          break;\n        }\n        case 29: {\n          this.stateBeforeSpecialS(c);\n          break;\n        }\n        case 30: {\n          this.stateBeforeSpecialT(c);\n          break;\n        }\n        case 21: {\n          this.stateInAttrValueNoQuotes(c);\n          break;\n        }\n        case 7: {\n          this.stateInSelfClosingTag(c);\n          break;\n        }\n        case 23: {\n          this.stateInDeclaration(c);\n          break;\n        }\n        case 22: {\n          this.stateBeforeDeclaration(c);\n          break;\n        }\n        case 25: {\n          this.stateBeforeComment(c);\n          break;\n        }\n        case 24: {\n          this.stateInProcessingInstruction(c);\n          break;\n        }\n        case 33: {\n          this.stateInEntity();\n          break;\n        }\n      }\n      this.index++;\n    }\n    this.cleanup();\n    this.finish();\n  }\n  /**\n   * Remove data that has already been consumed from the buffer.\n   */\n  cleanup() {\n    if (this.sectionStart !== this.index) {\n      if (this.state === 1 || this.state === 32 && this.sequenceIndex === 0) {\n        this.cbs.ontext(this.sectionStart, this.index);\n        this.sectionStart = this.index;\n      } else if (this.state === 19 || this.state === 20 || this.state === 21) {\n        this.cbs.onattribdata(this.sectionStart, this.index);\n        this.sectionStart = this.index;\n      }\n    }\n  }\n  finish() {\n    if (this.state === 33) {\n      this.entityDecoder.end();\n      this.state = this.baseState;\n    }\n    this.handleTrailingData();\n    this.cbs.onend();\n  }\n  /** Handle any trailing data. */\n  handleTrailingData() {\n    const endIndex = this.buffer.length;\n    if (this.sectionStart >= endIndex) {\n      return;\n    }\n    if (this.state === 28) {\n      if (this.currentSequence === Sequences.CdataEnd) {\n        this.cbs.oncdata(this.sectionStart, endIndex);\n      } else {\n        this.cbs.oncomment(this.sectionStart, endIndex);\n      }\n    } else if (this.state === 6 || this.state === 11 || this.state === 18 || this.state === 17 || this.state === 12 || this.state === 13 || this.state === 14 || this.state === 15 || this.state === 16 || this.state === 20 || this.state === 19 || this.state === 21 || this.state === 9) ; else {\n      this.cbs.ontext(this.sectionStart, endIndex);\n    }\n  }\n  emitCodePoint(cp, consumed) {\n    {\n      if (this.baseState !== 1 && this.baseState !== 32) {\n        if (this.sectionStart < this.entityStart) {\n          this.cbs.onattribdata(this.sectionStart, this.entityStart);\n        }\n        this.sectionStart = this.entityStart + consumed;\n        this.index = this.sectionStart - 1;\n        this.cbs.onattribentity(\n          decode_js.fromCodePoint(cp),\n          this.entityStart,\n          this.sectionStart\n        );\n      } else {\n        if (this.sectionStart < this.entityStart) {\n          this.cbs.ontext(this.sectionStart, this.entityStart);\n        }\n        this.sectionStart = this.entityStart + consumed;\n        this.index = this.sectionStart - 1;\n        this.cbs.ontextentity(\n          decode_js.fromCodePoint(cp),\n          this.entityStart,\n          this.sectionStart\n        );\n      }\n    }\n  }\n}\n\nconst CompilerDeprecationTypes = {\n  \"COMPILER_IS_ON_ELEMENT\": \"COMPILER_IS_ON_ELEMENT\",\n  \"COMPILER_V_BIND_SYNC\": \"COMPILER_V_BIND_SYNC\",\n  \"COMPILER_V_BIND_OBJECT_ORDER\": \"COMPILER_V_BIND_OBJECT_ORDER\",\n  \"COMPILER_V_ON_NATIVE\": \"COMPILER_V_ON_NATIVE\",\n  \"COMPILER_V_IF_V_FOR_PRECEDENCE\": \"COMPILER_V_IF_V_FOR_PRECEDENCE\",\n  \"COMPILER_NATIVE_TEMPLATE\": \"COMPILER_NATIVE_TEMPLATE\",\n  \"COMPILER_INLINE_TEMPLATE\": \"COMPILER_INLINE_TEMPLATE\",\n  \"COMPILER_FILTERS\": \"COMPILER_FILTERS\"\n};\nconst deprecationData = {\n  [\"COMPILER_IS_ON_ELEMENT\"]: {\n    message: `Platform-native elements with \"is\" prop will no longer be treated as components in Vue 3 unless the \"is\" value is explicitly prefixed with \"vue:\".`,\n    link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`\n  },\n  [\"COMPILER_V_BIND_SYNC\"]: {\n    message: (key) => `.sync modifier for v-bind has been removed. Use v-model with argument instead. \\`v-bind:${key}.sync\\` should be changed to \\`v-model:${key}\\`.`,\n    link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`\n  },\n  [\"COMPILER_V_BIND_OBJECT_ORDER\"]: {\n    message: `v-bind=\"obj\" usage is now order sensitive and behaves like JavaScript object spread: it will now overwrite an existing non-mergeable attribute that appears before v-bind in the case of conflict. To retain 2.x behavior, move v-bind to make it the first attribute. You can also suppress this warning if the usage is intended.`,\n    link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`\n  },\n  [\"COMPILER_V_ON_NATIVE\"]: {\n    message: `.native modifier for v-on has been removed as is no longer necessary.`,\n    link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`\n  },\n  [\"COMPILER_V_IF_V_FOR_PRECEDENCE\"]: {\n    message: `v-if / v-for precedence when used on the same element has changed in Vue 3: v-if now takes higher precedence and will no longer have access to v-for scope variables. It is best to avoid the ambiguity with <template> tags or use a computed property that filters v-for data source.`,\n    link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`\n  },\n  [\"COMPILER_NATIVE_TEMPLATE\"]: {\n    message: `<template> with no special directives will render as a native template element instead of its inner content in Vue 3.`\n  },\n  [\"COMPILER_INLINE_TEMPLATE\"]: {\n    message: `\"inline-template\" has been removed in Vue 3.`,\n    link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`\n  },\n  [\"COMPILER_FILTERS\"]: {\n    message: `filters have been removed in Vue 3. The \"|\" symbol will be treated as native JavaScript bitwise OR operator. Use method calls or computed properties instead.`,\n    link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`\n  }\n};\nfunction getCompatValue(key, { compatConfig }) {\n  const value = compatConfig && compatConfig[key];\n  if (key === \"MODE\") {\n    return value || 3;\n  } else {\n    return value;\n  }\n}\nfunction isCompatEnabled(key, context) {\n  const mode = getCompatValue(\"MODE\", context);\n  const value = getCompatValue(key, context);\n  return mode === 3 ? value === true : value !== false;\n}\nfunction checkCompatEnabled(key, context, loc, ...args) {\n  const enabled = isCompatEnabled(key, context);\n  return enabled;\n}\nfunction warnDeprecation(key, context, loc, ...args) {\n  const val = getCompatValue(key, context);\n  if (val === \"suppress-warning\") {\n    return;\n  }\n  const { message, link } = deprecationData[key];\n  const msg = `(deprecation ${key}) ${typeof message === \"function\" ? message(...args) : message}${link ? `\n  Details: ${link}` : ``}`;\n  const err = new SyntaxError(msg);\n  err.code = key;\n  if (loc) err.loc = loc;\n  context.onWarn(err);\n}\n\nfunction defaultOnError(error) {\n  throw error;\n}\nfunction defaultOnWarn(msg) {\n}\nfunction createCompilerError(code, loc, messages, additionalMessage) {\n  const msg = (messages || errorMessages)[code] + (additionalMessage || ``) ;\n  const error = new SyntaxError(String(msg));\n  error.code = code;\n  error.loc = loc;\n  return error;\n}\nconst ErrorCodes = {\n  \"ABRUPT_CLOSING_OF_EMPTY_COMMENT\": 0,\n  \"0\": \"ABRUPT_CLOSING_OF_EMPTY_COMMENT\",\n  \"CDATA_IN_HTML_CONTENT\": 1,\n  \"1\": \"CDATA_IN_HTML_CONTENT\",\n  \"DUPLICATE_ATTRIBUTE\": 2,\n  \"2\": \"DUPLICATE_ATTRIBUTE\",\n  \"END_TAG_WITH_ATTRIBUTES\": 3,\n  \"3\": \"END_TAG_WITH_ATTRIBUTES\",\n  \"END_TAG_WITH_TRAILING_SOLIDUS\": 4,\n  \"4\": \"END_TAG_WITH_TRAILING_SOLIDUS\",\n  \"EOF_BEFORE_TAG_NAME\": 5,\n  \"5\": \"EOF_BEFORE_TAG_NAME\",\n  \"EOF_IN_CDATA\": 6,\n  \"6\": \"EOF_IN_CDATA\",\n  \"EOF_IN_COMMENT\": 7,\n  \"7\": \"EOF_IN_COMMENT\",\n  \"EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT\": 8,\n  \"8\": \"EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT\",\n  \"EOF_IN_TAG\": 9,\n  \"9\": \"EOF_IN_TAG\",\n  \"INCORRECTLY_CLOSED_COMMENT\": 10,\n  \"10\": \"INCORRECTLY_CLOSED_COMMENT\",\n  \"INCORRECTLY_OPENED_COMMENT\": 11,\n  \"11\": \"INCORRECTLY_OPENED_COMMENT\",\n  \"INVALID_FIRST_CHARACTER_OF_TAG_NAME\": 12,\n  \"12\": \"INVALID_FIRST_CHARACTER_OF_TAG_NAME\",\n  \"MISSING_ATTRIBUTE_VALUE\": 13,\n  \"13\": \"MISSING_ATTRIBUTE_VALUE\",\n  \"MISSING_END_TAG_NAME\": 14,\n  \"14\": \"MISSING_END_TAG_NAME\",\n  \"MISSING_WHITESPACE_BETWEEN_ATTRIBUTES\": 15,\n  \"15\": \"MISSING_WHITESPACE_BETWEEN_ATTRIBUTES\",\n  \"NESTED_COMMENT\": 16,\n  \"16\": \"NESTED_COMMENT\",\n  \"UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME\": 17,\n  \"17\": \"UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME\",\n  \"UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE\": 18,\n  \"18\": \"UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE\",\n  \"UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME\": 19,\n  \"19\": \"UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME\",\n  \"UNEXPECTED_NULL_CHARACTER\": 20,\n  \"20\": \"UNEXPECTED_NULL_CHARACTER\",\n  \"UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME\": 21,\n  \"21\": \"UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME\",\n  \"UNEXPECTED_SOLIDUS_IN_TAG\": 22,\n  \"22\": \"UNEXPECTED_SOLIDUS_IN_TAG\",\n  \"X_INVALID_END_TAG\": 23,\n  \"23\": \"X_INVALID_END_TAG\",\n  \"X_MISSING_END_TAG\": 24,\n  \"24\": \"X_MISSING_END_TAG\",\n  \"X_MISSING_INTERPOLATION_END\": 25,\n  \"25\": \"X_MISSING_INTERPOLATION_END\",\n  \"X_MISSING_DIRECTIVE_NAME\": 26,\n  \"26\": \"X_MISSING_DIRECTIVE_NAME\",\n  \"X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END\": 27,\n  \"27\": \"X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END\",\n  \"X_V_IF_NO_EXPRESSION\": 28,\n  \"28\": \"X_V_IF_NO_EXPRESSION\",\n  \"X_V_IF_SAME_KEY\": 29,\n  \"29\": \"X_V_IF_SAME_KEY\",\n  \"X_V_ELSE_NO_ADJACENT_IF\": 30,\n  \"30\": \"X_V_ELSE_NO_ADJACENT_IF\",\n  \"X_V_FOR_NO_EXPRESSION\": 31,\n  \"31\": \"X_V_FOR_NO_EXPRESSION\",\n  \"X_V_FOR_MALFORMED_EXPRESSION\": 32,\n  \"32\": \"X_V_FOR_MALFORMED_EXPRESSION\",\n  \"X_V_FOR_TEMPLATE_KEY_PLACEMENT\": 33,\n  \"33\": \"X_V_FOR_TEMPLATE_KEY_PLACEMENT\",\n  \"X_V_BIND_NO_EXPRESSION\": 34,\n  \"34\": \"X_V_BIND_NO_EXPRESSION\",\n  \"X_V_ON_NO_EXPRESSION\": 35,\n  \"35\": \"X_V_ON_NO_EXPRESSION\",\n  \"X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET\": 36,\n  \"36\": \"X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET\",\n  \"X_V_SLOT_MIXED_SLOT_USAGE\": 37,\n  \"37\": \"X_V_SLOT_MIXED_SLOT_USAGE\",\n  \"X_V_SLOT_DUPLICATE_SLOT_NAMES\": 38,\n  \"38\": \"X_V_SLOT_DUPLICATE_SLOT_NAMES\",\n  \"X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN\": 39,\n  \"39\": \"X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN\",\n  \"X_V_SLOT_MISPLACED\": 40,\n  \"40\": \"X_V_SLOT_MISPLACED\",\n  \"X_V_MODEL_NO_EXPRESSION\": 41,\n  \"41\": \"X_V_MODEL_NO_EXPRESSION\",\n  \"X_V_MODEL_MALFORMED_EXPRESSION\": 42,\n  \"42\": \"X_V_MODEL_MALFORMED_EXPRESSION\",\n  \"X_V_MODEL_ON_SCOPE_VARIABLE\": 43,\n  \"43\": \"X_V_MODEL_ON_SCOPE_VARIABLE\",\n  \"X_V_MODEL_ON_PROPS\": 44,\n  \"44\": \"X_V_MODEL_ON_PROPS\",\n  \"X_INVALID_EXPRESSION\": 45,\n  \"45\": \"X_INVALID_EXPRESSION\",\n  \"X_KEEP_ALIVE_INVALID_CHILDREN\": 46,\n  \"46\": \"X_KEEP_ALIVE_INVALID_CHILDREN\",\n  \"X_PREFIX_ID_NOT_SUPPORTED\": 47,\n  \"47\": \"X_PREFIX_ID_NOT_SUPPORTED\",\n  \"X_MODULE_MODE_NOT_SUPPORTED\": 48,\n  \"48\": \"X_MODULE_MODE_NOT_SUPPORTED\",\n  \"X_CACHE_HANDLER_NOT_SUPPORTED\": 49,\n  \"49\": \"X_CACHE_HANDLER_NOT_SUPPORTED\",\n  \"X_SCOPE_ID_NOT_SUPPORTED\": 50,\n  \"50\": \"X_SCOPE_ID_NOT_SUPPORTED\",\n  \"X_VNODE_HOOKS\": 51,\n  \"51\": \"X_VNODE_HOOKS\",\n  \"X_V_BIND_INVALID_SAME_NAME_ARGUMENT\": 52,\n  \"52\": \"X_V_BIND_INVALID_SAME_NAME_ARGUMENT\",\n  \"__EXTEND_POINT__\": 53,\n  \"53\": \"__EXTEND_POINT__\"\n};\nconst errorMessages = {\n  // parse errors\n  [0]: \"Illegal comment.\",\n  [1]: \"CDATA section is allowed only in XML context.\",\n  [2]: \"Duplicate attribute.\",\n  [3]: \"End tag cannot have attributes.\",\n  [4]: \"Illegal '/' in tags.\",\n  [5]: \"Unexpected EOF in tag.\",\n  [6]: \"Unexpected EOF in CDATA section.\",\n  [7]: \"Unexpected EOF in comment.\",\n  [8]: \"Unexpected EOF in script.\",\n  [9]: \"Unexpected EOF in tag.\",\n  [10]: \"Incorrectly closed comment.\",\n  [11]: \"Incorrectly opened comment.\",\n  [12]: \"Illegal tag name. Use '&lt;' to print '<'.\",\n  [13]: \"Attribute value was expected.\",\n  [14]: \"End tag name was expected.\",\n  [15]: \"Whitespace was expected.\",\n  [16]: \"Unexpected '<!--' in comment.\",\n  [17]: `Attribute name cannot contain U+0022 (\"), U+0027 ('), and U+003C (<).`,\n  [18]: \"Unquoted attribute value cannot contain U+0022 (\\\"), U+0027 ('), U+003C (<), U+003D (=), and U+0060 (`).\",\n  [19]: \"Attribute name cannot start with '='.\",\n  [21]: \"'<?' is allowed only in XML context.\",\n  [20]: `Unexpected null character.`,\n  [22]: \"Illegal '/' in tags.\",\n  // Vue-specific parse errors\n  [23]: \"Invalid end tag.\",\n  [24]: \"Element is missing end tag.\",\n  [25]: \"Interpolation end sign was not found.\",\n  [27]: \"End bracket for dynamic directive argument was not found. Note that dynamic directive argument cannot contain spaces.\",\n  [26]: \"Legal directive name was expected.\",\n  // transform errors\n  [28]: `v-if/v-else-if is missing expression.`,\n  [29]: `v-if/else branches must use unique keys.`,\n  [30]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,\n  [31]: `v-for is missing expression.`,\n  [32]: `v-for has invalid expression.`,\n  [33]: `<template v-for> key should be placed on the <template> tag.`,\n  [34]: `v-bind is missing expression.`,\n  [52]: `v-bind with same-name shorthand only allows static argument.`,\n  [35]: `v-on is missing expression.`,\n  [36]: `Unexpected custom directive on <slot> outlet.`,\n  [37]: `Mixed v-slot usage on both the component and nested <template>. When there are multiple named slots, all slots should use <template> syntax to avoid scope ambiguity.`,\n  [38]: `Duplicate slot names found. `,\n  [39]: `Extraneous children found when component already has explicitly named default slot. These children will be ignored.`,\n  [40]: `v-slot can only be used on components or <template> tags.`,\n  [41]: `v-model is missing expression.`,\n  [42]: `v-model value must be a valid JavaScript member expression.`,\n  [43]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,\n  [44]: `v-model cannot be used on a prop, because local prop bindings are not writable.\nUse a v-bind binding combined with a v-on listener that emits update:x event instead.`,\n  [45]: `Error parsing JavaScript expression: `,\n  [46]: `<KeepAlive> expects exactly one child component.`,\n  [51]: `@vnode-* hooks in templates are no longer supported. Use the vue: prefix instead. For example, @vnode-mounted should be changed to @vue:mounted. @vnode-* hooks support has been removed in 3.4.`,\n  // generic errors\n  [47]: `\"prefixIdentifiers\" option is not supported in this build of compiler.`,\n  [48]: `ES module mode is not supported in this build of compiler.`,\n  [49]: `\"cacheHandlers\" option is only supported when the \"prefixIdentifiers\" option is enabled.`,\n  [50]: `\"scopeId\" option is only supported in module mode.`,\n  // just to fulfill types\n  [53]: ``\n};\n\nfunction walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = /* @__PURE__ */ Object.create(null)) {\n  const rootExp = root.type === \"Program\" ? root.body[0].type === \"ExpressionStatement\" && root.body[0].expression : root;\n  estreeWalker.walk(root, {\n    enter(node, parent) {\n      parent && parentStack.push(parent);\n      if (parent && parent.type.startsWith(\"TS\") && !TS_NODE_TYPES.includes(parent.type)) {\n        return this.skip();\n      }\n      if (node.type === \"Identifier\") {\n        const isLocal = !!knownIds[node.name];\n        const isRefed = isReferencedIdentifier(node, parent, parentStack);\n        if (includeAll || isRefed && !isLocal) {\n          onIdentifier(node, parent, parentStack, isRefed, isLocal);\n        }\n      } else if (node.type === \"ObjectProperty\" && // eslint-disable-next-line no-restricted-syntax\n      (parent == null ? void 0 : parent.type) === \"ObjectPattern\") {\n        node.inPattern = true;\n      } else if (isFunctionType(node)) {\n        if (node.scopeIds) {\n          node.scopeIds.forEach((id) => markKnownIds(id, knownIds));\n        } else {\n          walkFunctionParams(\n            node,\n            (id) => markScopeIdentifier(node, id, knownIds)\n          );\n        }\n      } else if (node.type === \"BlockStatement\") {\n        if (node.scopeIds) {\n          node.scopeIds.forEach((id) => markKnownIds(id, knownIds));\n        } else {\n          walkBlockDeclarations(\n            node,\n            (id) => markScopeIdentifier(node, id, knownIds)\n          );\n        }\n      } else if (node.type === \"CatchClause\" && node.param) {\n        for (const id of extractIdentifiers(node.param)) {\n          markScopeIdentifier(node, id, knownIds);\n        }\n      } else if (isForStatement(node)) {\n        walkForStatement(\n          node,\n          false,\n          (id) => markScopeIdentifier(node, id, knownIds)\n        );\n      }\n    },\n    leave(node, parent) {\n      parent && parentStack.pop();\n      if (node !== rootExp && node.scopeIds) {\n        for (const id of node.scopeIds) {\n          knownIds[id]--;\n          if (knownIds[id] === 0) {\n            delete knownIds[id];\n          }\n        }\n      }\n    }\n  });\n}\nfunction isReferencedIdentifier(id, parent, parentStack) {\n  if (!parent) {\n    return true;\n  }\n  if (id.name === \"arguments\") {\n    return false;\n  }\n  if (isReferenced(id, parent, parentStack[parentStack.length - 2])) {\n    return true;\n  }\n  switch (parent.type) {\n    case \"AssignmentExpression\":\n    case \"AssignmentPattern\":\n      return true;\n    case \"ObjectProperty\":\n      return parent.key !== id && isInDestructureAssignment(parent, parentStack);\n    case \"ArrayPattern\":\n      return isInDestructureAssignment(parent, parentStack);\n  }\n  return false;\n}\nfunction isInDestructureAssignment(parent, parentStack) {\n  if (parent && (parent.type === \"ObjectProperty\" || parent.type === \"ArrayPattern\")) {\n    let i = parentStack.length;\n    while (i--) {\n      const p = parentStack[i];\n      if (p.type === \"AssignmentExpression\") {\n        return true;\n      } else if (p.type !== \"ObjectProperty\" && !p.type.endsWith(\"Pattern\")) {\n        break;\n      }\n    }\n  }\n  return false;\n}\nfunction isInNewExpression(parentStack) {\n  let i = parentStack.length;\n  while (i--) {\n    const p = parentStack[i];\n    if (p.type === \"NewExpression\") {\n      return true;\n    } else if (p.type !== \"MemberExpression\") {\n      break;\n    }\n  }\n  return false;\n}\nfunction walkFunctionParams(node, onIdent) {\n  for (const p of node.params) {\n    for (const id of extractIdentifiers(p)) {\n      onIdent(id);\n    }\n  }\n}\nfunction walkBlockDeclarations(block, onIdent) {\n  for (const stmt of block.body) {\n    if (stmt.type === \"VariableDeclaration\") {\n      if (stmt.declare) continue;\n      for (const decl of stmt.declarations) {\n        for (const id of extractIdentifiers(decl.id)) {\n          onIdent(id);\n        }\n      }\n    } else if (stmt.type === \"FunctionDeclaration\" || stmt.type === \"ClassDeclaration\") {\n      if (stmt.declare || !stmt.id) continue;\n      onIdent(stmt.id);\n    } else if (isForStatement(stmt)) {\n      walkForStatement(stmt, true, onIdent);\n    }\n  }\n}\nfunction isForStatement(stmt) {\n  return stmt.type === \"ForOfStatement\" || stmt.type === \"ForInStatement\" || stmt.type === \"ForStatement\";\n}\nfunction walkForStatement(stmt, isVar, onIdent) {\n  const variable = stmt.type === \"ForStatement\" ? stmt.init : stmt.left;\n  if (variable && variable.type === \"VariableDeclaration\" && (variable.kind === \"var\" ? isVar : !isVar)) {\n    for (const decl of variable.declarations) {\n      for (const id of extractIdentifiers(decl.id)) {\n        onIdent(id);\n      }\n    }\n  }\n}\nfunction extractIdentifiers(param, nodes = []) {\n  switch (param.type) {\n    case \"Identifier\":\n      nodes.push(param);\n      break;\n    case \"MemberExpression\":\n      let object = param;\n      while (object.type === \"MemberExpression\") {\n        object = object.object;\n      }\n      nodes.push(object);\n      break;\n    case \"ObjectPattern\":\n      for (const prop of param.properties) {\n        if (prop.type === \"RestElement\") {\n          extractIdentifiers(prop.argument, nodes);\n        } else {\n          extractIdentifiers(prop.value, nodes);\n        }\n      }\n      break;\n    case \"ArrayPattern\":\n      param.elements.forEach((element) => {\n        if (element) extractIdentifiers(element, nodes);\n      });\n      break;\n    case \"RestElement\":\n      extractIdentifiers(param.argument, nodes);\n      break;\n    case \"AssignmentPattern\":\n      extractIdentifiers(param.left, nodes);\n      break;\n  }\n  return nodes;\n}\nfunction markKnownIds(name, knownIds) {\n  if (name in knownIds) {\n    knownIds[name]++;\n  } else {\n    knownIds[name] = 1;\n  }\n}\nfunction markScopeIdentifier(node, child, knownIds) {\n  const { name } = child;\n  if (node.scopeIds && node.scopeIds.has(name)) {\n    return;\n  }\n  markKnownIds(name, knownIds);\n  (node.scopeIds || (node.scopeIds = /* @__PURE__ */ new Set())).add(name);\n}\nconst isFunctionType = (node) => {\n  return /Function(?:Expression|Declaration)$|Method$/.test(node.type);\n};\nconst isStaticProperty = (node) => node && (node.type === \"ObjectProperty\" || node.type === \"ObjectMethod\") && !node.computed;\nconst isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;\nfunction isReferenced(node, parent, grandparent) {\n  switch (parent.type) {\n    // yes: PARENT[NODE]\n    // yes: NODE.child\n    // no: parent.NODE\n    case \"MemberExpression\":\n    case \"OptionalMemberExpression\":\n      if (parent.property === node) {\n        return !!parent.computed;\n      }\n      return parent.object === node;\n    case \"JSXMemberExpression\":\n      return parent.object === node;\n    // no: let NODE = init;\n    // yes: let id = NODE;\n    case \"VariableDeclarator\":\n      return parent.init === node;\n    // yes: () => NODE\n    // no: (NODE) => {}\n    case \"ArrowFunctionExpression\":\n      return parent.body === node;\n    // no: class { #NODE; }\n    // no: class { get #NODE() {} }\n    // no: class { #NODE() {} }\n    // no: class { fn() { return this.#NODE; } }\n    case \"PrivateName\":\n      return false;\n    // no: class { NODE() {} }\n    // yes: class { [NODE]() {} }\n    // no: class { foo(NODE) {} }\n    case \"ClassMethod\":\n    case \"ClassPrivateMethod\":\n    case \"ObjectMethod\":\n      if (parent.key === node) {\n        return !!parent.computed;\n      }\n      return false;\n    // yes: { [NODE]: \"\" }\n    // no: { NODE: \"\" }\n    // depends: { NODE }\n    // depends: { key: NODE }\n    case \"ObjectProperty\":\n      if (parent.key === node) {\n        return !!parent.computed;\n      }\n      return !grandparent || grandparent.type !== \"ObjectPattern\";\n    // no: class { NODE = value; }\n    // yes: class { [NODE] = value; }\n    // yes: class { key = NODE; }\n    case \"ClassProperty\":\n      if (parent.key === node) {\n        return !!parent.computed;\n      }\n      return true;\n    case \"ClassPrivateProperty\":\n      return parent.key !== node;\n    // no: class NODE {}\n    // yes: class Foo extends NODE {}\n    case \"ClassDeclaration\":\n    case \"ClassExpression\":\n      return parent.superClass === node;\n    // yes: left = NODE;\n    // no: NODE = right;\n    case \"AssignmentExpression\":\n      return parent.right === node;\n    // no: [NODE = foo] = [];\n    // yes: [foo = NODE] = [];\n    case \"AssignmentPattern\":\n      return parent.right === node;\n    // no: NODE: for (;;) {}\n    case \"LabeledStatement\":\n      return false;\n    // no: try {} catch (NODE) {}\n    case \"CatchClause\":\n      return false;\n    // no: function foo(...NODE) {}\n    case \"RestElement\":\n      return false;\n    case \"BreakStatement\":\n    case \"ContinueStatement\":\n      return false;\n    // no: function NODE() {}\n    // no: function foo(NODE) {}\n    case \"FunctionDeclaration\":\n    case \"FunctionExpression\":\n      return false;\n    // no: export NODE from \"foo\";\n    // no: export * as NODE from \"foo\";\n    case \"ExportNamespaceSpecifier\":\n    case \"ExportDefaultSpecifier\":\n      return false;\n    // no: export { foo as NODE };\n    // yes: export { NODE as foo };\n    // no: export { NODE as foo } from \"foo\";\n    case \"ExportSpecifier\":\n      if (grandparent == null ? void 0 : grandparent.source) {\n        return false;\n      }\n      return parent.local === node;\n    // no: import NODE from \"foo\";\n    // no: import * as NODE from \"foo\";\n    // no: import { NODE as foo } from \"foo\";\n    // no: import { foo as NODE } from \"foo\";\n    // no: import NODE from \"bar\";\n    case \"ImportDefaultSpecifier\":\n    case \"ImportNamespaceSpecifier\":\n    case \"ImportSpecifier\":\n      return false;\n    // no: import \"foo\" assert { NODE: \"json\" }\n    case \"ImportAttribute\":\n      return false;\n    // no: <div NODE=\"foo\" />\n    case \"JSXAttribute\":\n      return false;\n    // no: [NODE] = [];\n    // no: ({ NODE }) = [];\n    case \"ObjectPattern\":\n    case \"ArrayPattern\":\n      return false;\n    // no: new.NODE\n    // no: NODE.target\n    case \"MetaProperty\":\n      return false;\n    // yes: type X = { someProperty: NODE }\n    // no: type X = { NODE: OtherType }\n    case \"ObjectTypeProperty\":\n      return parent.key !== node;\n    // yes: enum X { Foo = NODE }\n    // no: enum X { NODE }\n    case \"TSEnumMember\":\n      return parent.id !== node;\n    // yes: { [NODE]: value }\n    // no: { NODE: value }\n    case \"TSPropertySignature\":\n      if (parent.key === node) {\n        return !!parent.computed;\n      }\n      return true;\n  }\n  return true;\n}\nconst TS_NODE_TYPES = [\n  \"TSAsExpression\",\n  // foo as number\n  \"TSTypeAssertion\",\n  // (<number>foo)\n  \"TSNonNullExpression\",\n  // foo!\n  \"TSInstantiationExpression\",\n  // foo<string>\n  \"TSSatisfiesExpression\"\n  // foo satisfies T\n];\nfunction unwrapTSNode(node) {\n  if (TS_NODE_TYPES.includes(node.type)) {\n    return unwrapTSNode(node.expression);\n  } else {\n    return node;\n  }\n}\n\nconst isStaticExp = (p) => p.type === 4 && p.isStatic;\nfunction isCoreComponent(tag) {\n  switch (tag) {\n    case \"Teleport\":\n    case \"teleport\":\n      return TELEPORT;\n    case \"Suspense\":\n    case \"suspense\":\n      return SUSPENSE;\n    case \"KeepAlive\":\n    case \"keep-alive\":\n      return KEEP_ALIVE;\n    case \"BaseTransition\":\n    case \"base-transition\":\n      return BASE_TRANSITION;\n  }\n}\nconst nonIdentifierRE = /^$|^\\d|[^\\$\\w\\xA0-\\uFFFF]/;\nconst isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);\nconst validFirstIdentCharRE = /[A-Za-z_$\\xA0-\\uFFFF]/;\nconst validIdentCharRE = /[\\.\\?\\w$\\xA0-\\uFFFF]/;\nconst whitespaceRE = /\\s+[.[]\\s*|\\s*[.[]\\s+/g;\nconst getExpSource = (exp) => exp.type === 4 ? exp.content : exp.loc.source;\nconst isMemberExpressionBrowser = (exp) => {\n  const path = getExpSource(exp).trim().replace(whitespaceRE, (s) => s.trim());\n  let state = 0 /* inMemberExp */;\n  let stateStack = [];\n  let currentOpenBracketCount = 0;\n  let currentOpenParensCount = 0;\n  let currentStringType = null;\n  for (let i = 0; i < path.length; i++) {\n    const char = path.charAt(i);\n    switch (state) {\n      case 0 /* inMemberExp */:\n        if (char === \"[\") {\n          stateStack.push(state);\n          state = 1 /* inBrackets */;\n          currentOpenBracketCount++;\n        } else if (char === \"(\") {\n          stateStack.push(state);\n          state = 2 /* inParens */;\n          currentOpenParensCount++;\n        } else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {\n          return false;\n        }\n        break;\n      case 1 /* inBrackets */:\n        if (char === `'` || char === `\"` || char === \"`\") {\n          stateStack.push(state);\n          state = 3 /* inString */;\n          currentStringType = char;\n        } else if (char === `[`) {\n          currentOpenBracketCount++;\n        } else if (char === `]`) {\n          if (!--currentOpenBracketCount) {\n            state = stateStack.pop();\n          }\n        }\n        break;\n      case 2 /* inParens */:\n        if (char === `'` || char === `\"` || char === \"`\") {\n          stateStack.push(state);\n          state = 3 /* inString */;\n          currentStringType = char;\n        } else if (char === `(`) {\n          currentOpenParensCount++;\n        } else if (char === `)`) {\n          if (i === path.length - 1) {\n            return false;\n          }\n          if (!--currentOpenParensCount) {\n            state = stateStack.pop();\n          }\n        }\n        break;\n      case 3 /* inString */:\n        if (char === currentStringType) {\n          state = stateStack.pop();\n          currentStringType = null;\n        }\n        break;\n    }\n  }\n  return !currentOpenBracketCount && !currentOpenParensCount;\n};\nconst isMemberExpressionNode = (exp, context) => {\n  try {\n    let ret = exp.ast || parser.parseExpression(getExpSource(exp), {\n      plugins: context.expressionPlugins ? [...context.expressionPlugins, \"typescript\"] : [\"typescript\"]\n    });\n    ret = unwrapTSNode(ret);\n    return ret.type === \"MemberExpression\" || ret.type === \"OptionalMemberExpression\" || ret.type === \"Identifier\" && ret.name !== \"undefined\";\n  } catch (e) {\n    return false;\n  }\n};\nconst isMemberExpression = isMemberExpressionNode;\nconst fnExpRE = /^\\s*(async\\s*)?(\\([^)]*?\\)|[\\w$_]+)\\s*(:[^=]+)?=>|^\\s*(async\\s+)?function(?:\\s+[\\w$]+)?\\s*\\(/;\nconst isFnExpressionBrowser = (exp) => fnExpRE.test(getExpSource(exp));\nconst isFnExpressionNode = (exp, context) => {\n  try {\n    let ret = exp.ast || parser.parseExpression(getExpSource(exp), {\n      plugins: context.expressionPlugins ? [...context.expressionPlugins, \"typescript\"] : [\"typescript\"]\n    });\n    if (ret.type === \"Program\") {\n      ret = ret.body[0];\n      if (ret.type === \"ExpressionStatement\") {\n        ret = ret.expression;\n      }\n    }\n    ret = unwrapTSNode(ret);\n    return ret.type === \"FunctionExpression\" || ret.type === \"ArrowFunctionExpression\";\n  } catch (e) {\n    return false;\n  }\n};\nconst isFnExpression = isFnExpressionNode;\nfunction advancePositionWithClone(pos, source, numberOfCharacters = source.length) {\n  return advancePositionWithMutation(\n    {\n      offset: pos.offset,\n      line: pos.line,\n      column: pos.column\n    },\n    source,\n    numberOfCharacters\n  );\n}\nfunction advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {\n  let linesCount = 0;\n  let lastNewLinePos = -1;\n  for (let i = 0; i < numberOfCharacters; i++) {\n    if (source.charCodeAt(i) === 10) {\n      linesCount++;\n      lastNewLinePos = i;\n    }\n  }\n  pos.offset += numberOfCharacters;\n  pos.line += linesCount;\n  pos.column = lastNewLinePos === -1 ? pos.column + numberOfCharacters : numberOfCharacters - lastNewLinePos;\n  return pos;\n}\nfunction assert(condition, msg) {\n  if (!condition) {\n    throw new Error(msg || `unexpected compiler condition`);\n  }\n}\nfunction findDir(node, name, allowEmpty = false) {\n  for (let i = 0; i < node.props.length; i++) {\n    const p = node.props[i];\n    if (p.type === 7 && (allowEmpty || p.exp) && (shared.isString(name) ? p.name === name : name.test(p.name))) {\n      return p;\n    }\n  }\n}\nfunction findProp(node, name, dynamicOnly = false, allowEmpty = false) {\n  for (let i = 0; i < node.props.length; i++) {\n    const p = node.props[i];\n    if (p.type === 6) {\n      if (dynamicOnly) continue;\n      if (p.name === name && (p.value || allowEmpty)) {\n        return p;\n      }\n    } else if (p.name === \"bind\" && (p.exp || allowEmpty) && isStaticArgOf(p.arg, name)) {\n      return p;\n    }\n  }\n}\nfunction isStaticArgOf(arg, name) {\n  return !!(arg && isStaticExp(arg) && arg.content === name);\n}\nfunction hasDynamicKeyVBind(node) {\n  return node.props.some(\n    (p) => p.type === 7 && p.name === \"bind\" && (!p.arg || // v-bind=\"obj\"\n    p.arg.type !== 4 || // v-bind:[_ctx.foo]\n    !p.arg.isStatic)\n    // v-bind:[foo]\n  );\n}\nfunction isText$1(node) {\n  return node.type === 5 || node.type === 2;\n}\nfunction isVPre(p) {\n  return p.type === 7 && p.name === \"pre\";\n}\nfunction isVSlot(p) {\n  return p.type === 7 && p.name === \"slot\";\n}\nfunction isTemplateNode(node) {\n  return node.type === 1 && node.tagType === 3;\n}\nfunction isSlotOutlet(node) {\n  return node.type === 1 && node.tagType === 2;\n}\nconst propsHelperSet = /* @__PURE__ */ new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);\nfunction getUnnormalizedProps(props, callPath = []) {\n  if (props && !shared.isString(props) && props.type === 14) {\n    const callee = props.callee;\n    if (!shared.isString(callee) && propsHelperSet.has(callee)) {\n      return getUnnormalizedProps(\n        props.arguments[0],\n        callPath.concat(props)\n      );\n    }\n  }\n  return [props, callPath];\n}\nfunction injectProp(node, prop, context) {\n  let propsWithInjection;\n  let props = node.type === 13 ? node.props : node.arguments[2];\n  let callPath = [];\n  let parentCall;\n  if (props && !shared.isString(props) && props.type === 14) {\n    const ret = getUnnormalizedProps(props);\n    props = ret[0];\n    callPath = ret[1];\n    parentCall = callPath[callPath.length - 1];\n  }\n  if (props == null || shared.isString(props)) {\n    propsWithInjection = createObjectExpression([prop]);\n  } else if (props.type === 14) {\n    const first = props.arguments[0];\n    if (!shared.isString(first) && first.type === 15) {\n      if (!hasProp(prop, first)) {\n        first.properties.unshift(prop);\n      }\n    } else {\n      if (props.callee === TO_HANDLERS) {\n        propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [\n          createObjectExpression([prop]),\n          props\n        ]);\n      } else {\n        props.arguments.unshift(createObjectExpression([prop]));\n      }\n    }\n    !propsWithInjection && (propsWithInjection = props);\n  } else if (props.type === 15) {\n    if (!hasProp(prop, props)) {\n      props.properties.unshift(prop);\n    }\n    propsWithInjection = props;\n  } else {\n    propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [\n      createObjectExpression([prop]),\n      props\n    ]);\n    if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {\n      parentCall = callPath[callPath.length - 2];\n    }\n  }\n  if (node.type === 13) {\n    if (parentCall) {\n      parentCall.arguments[0] = propsWithInjection;\n    } else {\n      node.props = propsWithInjection;\n    }\n  } else {\n    if (parentCall) {\n      parentCall.arguments[0] = propsWithInjection;\n    } else {\n      node.arguments[2] = propsWithInjection;\n    }\n  }\n}\nfunction hasProp(prop, props) {\n  let result = false;\n  if (prop.key.type === 4) {\n    const propKeyName = prop.key.content;\n    result = props.properties.some(\n      (p) => p.key.type === 4 && p.key.content === propKeyName\n    );\n  }\n  return result;\n}\nfunction toValidAssetId(name, type) {\n  return `_${type}_${name.replace(/[^\\w]/g, (searchValue, replaceValue) => {\n    return searchValue === \"-\" ? \"_\" : name.charCodeAt(replaceValue).toString();\n  })}`;\n}\nfunction hasScopeRef(node, ids) {\n  if (!node || Object.keys(ids).length === 0) {\n    return false;\n  }\n  switch (node.type) {\n    case 1:\n      for (let i = 0; i < node.props.length; i++) {\n        const p = node.props[i];\n        if (p.type === 7 && (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {\n          return true;\n        }\n      }\n      return node.children.some((c) => hasScopeRef(c, ids));\n    case 11:\n      if (hasScopeRef(node.source, ids)) {\n        return true;\n      }\n      return node.children.some((c) => hasScopeRef(c, ids));\n    case 9:\n      return node.branches.some((b) => hasScopeRef(b, ids));\n    case 10:\n      if (hasScopeRef(node.condition, ids)) {\n        return true;\n      }\n      return node.children.some((c) => hasScopeRef(c, ids));\n    case 4:\n      return !node.isStatic && isSimpleIdentifier(node.content) && !!ids[node.content];\n    case 8:\n      return node.children.some((c) => shared.isObject(c) && hasScopeRef(c, ids));\n    case 5:\n    case 12:\n      return hasScopeRef(node.content, ids);\n    case 2:\n    case 3:\n    case 20:\n      return false;\n    default:\n      return false;\n  }\n}\nfunction getMemoedVNodeCall(node) {\n  if (node.type === 14 && node.callee === WITH_MEMO) {\n    return node.arguments[1].returns;\n  } else {\n    return node;\n  }\n}\nconst forAliasRE = /([\\s\\S]*?)\\s+(?:in|of)\\s+(\\S[\\s\\S]*)/;\n\nconst defaultParserOptions = {\n  parseMode: \"base\",\n  ns: 0,\n  delimiters: [`{{`, `}}`],\n  getNamespace: () => 0,\n  isVoidTag: shared.NO,\n  isPreTag: shared.NO,\n  isIgnoreNewlineTag: shared.NO,\n  isCustomElement: shared.NO,\n  onError: defaultOnError,\n  onWarn: defaultOnWarn,\n  comments: false,\n  prefixIdentifiers: false\n};\nlet currentOptions = defaultParserOptions;\nlet currentRoot = null;\nlet currentInput = \"\";\nlet currentOpenTag = null;\nlet currentProp = null;\nlet currentAttrValue = \"\";\nlet currentAttrStartIndex = -1;\nlet currentAttrEndIndex = -1;\nlet inPre = 0;\nlet inVPre = false;\nlet currentVPreBoundary = null;\nconst stack = [];\nconst tokenizer = new Tokenizer(stack, {\n  onerr: emitError,\n  ontext(start, end) {\n    onText(getSlice(start, end), start, end);\n  },\n  ontextentity(char, start, end) {\n    onText(char, start, end);\n  },\n  oninterpolation(start, end) {\n    if (inVPre) {\n      return onText(getSlice(start, end), start, end);\n    }\n    let innerStart = start + tokenizer.delimiterOpen.length;\n    let innerEnd = end - tokenizer.delimiterClose.length;\n    while (isWhitespace(currentInput.charCodeAt(innerStart))) {\n      innerStart++;\n    }\n    while (isWhitespace(currentInput.charCodeAt(innerEnd - 1))) {\n      innerEnd--;\n    }\n    let exp = getSlice(innerStart, innerEnd);\n    if (exp.includes(\"&\")) {\n      {\n        exp = decode_js.decodeHTML(exp);\n      }\n    }\n    addNode({\n      type: 5,\n      content: createExp(exp, false, getLoc(innerStart, innerEnd)),\n      loc: getLoc(start, end)\n    });\n  },\n  onopentagname(start, end) {\n    const name = getSlice(start, end);\n    currentOpenTag = {\n      type: 1,\n      tag: name,\n      ns: currentOptions.getNamespace(name, stack[0], currentOptions.ns),\n      tagType: 0,\n      // will be refined on tag close\n      props: [],\n      children: [],\n      loc: getLoc(start - 1, end),\n      codegenNode: void 0\n    };\n  },\n  onopentagend(end) {\n    endOpenTag(end);\n  },\n  onclosetag(start, end) {\n    const name = getSlice(start, end);\n    if (!currentOptions.isVoidTag(name)) {\n      let found = false;\n      for (let i = 0; i < stack.length; i++) {\n        const e = stack[i];\n        if (e.tag.toLowerCase() === name.toLowerCase()) {\n          found = true;\n          if (i > 0) {\n            emitError(24, stack[0].loc.start.offset);\n          }\n          for (let j = 0; j <= i; j++) {\n            const el = stack.shift();\n            onCloseTag(el, end, j < i);\n          }\n          break;\n        }\n      }\n      if (!found) {\n        emitError(23, backTrack(start, 60));\n      }\n    }\n  },\n  onselfclosingtag(end) {\n    const name = currentOpenTag.tag;\n    currentOpenTag.isSelfClosing = true;\n    endOpenTag(end);\n    if (stack[0] && stack[0].tag === name) {\n      onCloseTag(stack.shift(), end);\n    }\n  },\n  onattribname(start, end) {\n    currentProp = {\n      type: 6,\n      name: getSlice(start, end),\n      nameLoc: getLoc(start, end),\n      value: void 0,\n      loc: getLoc(start)\n    };\n  },\n  ondirname(start, end) {\n    const raw = getSlice(start, end);\n    const name = raw === \".\" || raw === \":\" ? \"bind\" : raw === \"@\" ? \"on\" : raw === \"#\" ? \"slot\" : raw.slice(2);\n    if (!inVPre && name === \"\") {\n      emitError(26, start);\n    }\n    if (inVPre || name === \"\") {\n      currentProp = {\n        type: 6,\n        name: raw,\n        nameLoc: getLoc(start, end),\n        value: void 0,\n        loc: getLoc(start)\n      };\n    } else {\n      currentProp = {\n        type: 7,\n        name,\n        rawName: raw,\n        exp: void 0,\n        arg: void 0,\n        modifiers: raw === \".\" ? [createSimpleExpression(\"prop\")] : [],\n        loc: getLoc(start)\n      };\n      if (name === \"pre\") {\n        inVPre = tokenizer.inVPre = true;\n        currentVPreBoundary = currentOpenTag;\n        const props = currentOpenTag.props;\n        for (let i = 0; i < props.length; i++) {\n          if (props[i].type === 7) {\n            props[i] = dirToAttr(props[i]);\n          }\n        }\n      }\n    }\n  },\n  ondirarg(start, end) {\n    if (start === end) return;\n    const arg = getSlice(start, end);\n    if (inVPre && !isVPre(currentProp)) {\n      currentProp.name += arg;\n      setLocEnd(currentProp.nameLoc, end);\n    } else {\n      const isStatic = arg[0] !== `[`;\n      currentProp.arg = createExp(\n        isStatic ? arg : arg.slice(1, -1),\n        isStatic,\n        getLoc(start, end),\n        isStatic ? 3 : 0\n      );\n    }\n  },\n  ondirmodifier(start, end) {\n    const mod = getSlice(start, end);\n    if (inVPre && !isVPre(currentProp)) {\n      currentProp.name += \".\" + mod;\n      setLocEnd(currentProp.nameLoc, end);\n    } else if (currentProp.name === \"slot\") {\n      const arg = currentProp.arg;\n      if (arg) {\n        arg.content += \".\" + mod;\n        setLocEnd(arg.loc, end);\n      }\n    } else {\n      const exp = createSimpleExpression(mod, true, getLoc(start, end));\n      currentProp.modifiers.push(exp);\n    }\n  },\n  onattribdata(start, end) {\n    currentAttrValue += getSlice(start, end);\n    if (currentAttrStartIndex < 0) currentAttrStartIndex = start;\n    currentAttrEndIndex = end;\n  },\n  onattribentity(char, start, end) {\n    currentAttrValue += char;\n    if (currentAttrStartIndex < 0) currentAttrStartIndex = start;\n    currentAttrEndIndex = end;\n  },\n  onattribnameend(end) {\n    const start = currentProp.loc.start.offset;\n    const name = getSlice(start, end);\n    if (currentProp.type === 7) {\n      currentProp.rawName = name;\n    }\n    if (currentOpenTag.props.some(\n      (p) => (p.type === 7 ? p.rawName : p.name) === name\n    )) {\n      emitError(2, start);\n    }\n  },\n  onattribend(quote, end) {\n    if (currentOpenTag && currentProp) {\n      setLocEnd(currentProp.loc, end);\n      if (quote !== 0) {\n        if (currentProp.type === 6) {\n          if (currentProp.name === \"class\") {\n            currentAttrValue = condense(currentAttrValue).trim();\n          }\n          if (quote === 1 && !currentAttrValue) {\n            emitError(13, end);\n          }\n          currentProp.value = {\n            type: 2,\n            content: currentAttrValue,\n            loc: quote === 1 ? getLoc(currentAttrStartIndex, currentAttrEndIndex) : getLoc(currentAttrStartIndex - 1, currentAttrEndIndex + 1)\n          };\n          if (tokenizer.inSFCRoot && currentOpenTag.tag === \"template\" && currentProp.name === \"lang\" && currentAttrValue && currentAttrValue !== \"html\") {\n            tokenizer.enterRCDATA(toCharCodes(`</template`), 0);\n          }\n        } else {\n          let expParseMode = 0 /* Normal */;\n          {\n            if (currentProp.name === \"for\") {\n              expParseMode = 3 /* Skip */;\n            } else if (currentProp.name === \"slot\") {\n              expParseMode = 1 /* Params */;\n            } else if (currentProp.name === \"on\" && currentAttrValue.includes(\";\")) {\n              expParseMode = 2 /* Statements */;\n            }\n          }\n          currentProp.exp = createExp(\n            currentAttrValue,\n            false,\n            getLoc(currentAttrStartIndex, currentAttrEndIndex),\n            0,\n            expParseMode\n          );\n          if (currentProp.name === \"for\") {\n            currentProp.forParseResult = parseForExpression(currentProp.exp);\n          }\n          let syncIndex = -1;\n          if (currentProp.name === \"bind\" && (syncIndex = currentProp.modifiers.findIndex(\n            (mod) => mod.content === \"sync\"\n          )) > -1 && checkCompatEnabled(\n            \"COMPILER_V_BIND_SYNC\",\n            currentOptions,\n            currentProp.loc,\n            currentProp.arg.loc.source\n          )) {\n            currentProp.name = \"model\";\n            currentProp.modifiers.splice(syncIndex, 1);\n          }\n        }\n      }\n      if (currentProp.type !== 7 || currentProp.name !== \"pre\") {\n        currentOpenTag.props.push(currentProp);\n      }\n    }\n    currentAttrValue = \"\";\n    currentAttrStartIndex = currentAttrEndIndex = -1;\n  },\n  oncomment(start, end) {\n    if (currentOptions.comments) {\n      addNode({\n        type: 3,\n        content: getSlice(start, end),\n        loc: getLoc(start - 4, end + 3)\n      });\n    }\n  },\n  onend() {\n    const end = currentInput.length;\n    if (tokenizer.state !== 1) {\n      switch (tokenizer.state) {\n        case 5:\n        case 8:\n          emitError(5, end);\n          break;\n        case 3:\n        case 4:\n          emitError(\n            25,\n            tokenizer.sectionStart\n          );\n          break;\n        case 28:\n          if (tokenizer.currentSequence === Sequences.CdataEnd) {\n            emitError(6, end);\n          } else {\n            emitError(7, end);\n          }\n          break;\n        case 6:\n        case 7:\n        case 9:\n        case 11:\n        case 12:\n        case 13:\n        case 14:\n        case 15:\n        case 16:\n        case 17:\n        case 18:\n        case 19:\n        // \"\n        case 20:\n        // '\n        case 21:\n          emitError(9, end);\n          break;\n      }\n    }\n    for (let index = 0; index < stack.length; index++) {\n      onCloseTag(stack[index], end - 1);\n      emitError(24, stack[index].loc.start.offset);\n    }\n  },\n  oncdata(start, end) {\n    if (stack[0].ns !== 0) {\n      onText(getSlice(start, end), start, end);\n    } else {\n      emitError(1, start - 9);\n    }\n  },\n  onprocessinginstruction(start) {\n    if ((stack[0] ? stack[0].ns : currentOptions.ns) === 0) {\n      emitError(\n        21,\n        start - 1\n      );\n    }\n  }\n});\nconst forIteratorRE = /,([^,\\}\\]]*)(?:,([^,\\}\\]]*))?$/;\nconst stripParensRE = /^\\(|\\)$/g;\nfunction parseForExpression(input) {\n  const loc = input.loc;\n  const exp = input.content;\n  const inMatch = exp.match(forAliasRE);\n  if (!inMatch) return;\n  const [, LHS, RHS] = inMatch;\n  const createAliasExpression = (content, offset, asParam = false) => {\n    const start = loc.start.offset + offset;\n    const end = start + content.length;\n    return createExp(\n      content,\n      false,\n      getLoc(start, end),\n      0,\n      asParam ? 1 /* Params */ : 0 /* Normal */\n    );\n  };\n  const result = {\n    source: createAliasExpression(RHS.trim(), exp.indexOf(RHS, LHS.length)),\n    value: void 0,\n    key: void 0,\n    index: void 0,\n    finalized: false\n  };\n  let valueContent = LHS.trim().replace(stripParensRE, \"\").trim();\n  const trimmedOffset = LHS.indexOf(valueContent);\n  const iteratorMatch = valueContent.match(forIteratorRE);\n  if (iteratorMatch) {\n    valueContent = valueContent.replace(forIteratorRE, \"\").trim();\n    const keyContent = iteratorMatch[1].trim();\n    let keyOffset;\n    if (keyContent) {\n      keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);\n      result.key = createAliasExpression(keyContent, keyOffset, true);\n    }\n    if (iteratorMatch[2]) {\n      const indexContent = iteratorMatch[2].trim();\n      if (indexContent) {\n        result.index = createAliasExpression(\n          indexContent,\n          exp.indexOf(\n            indexContent,\n            result.key ? keyOffset + keyContent.length : trimmedOffset + valueContent.length\n          ),\n          true\n        );\n      }\n    }\n  }\n  if (valueContent) {\n    result.value = createAliasExpression(valueContent, trimmedOffset, true);\n  }\n  return result;\n}\nfunction getSlice(start, end) {\n  return currentInput.slice(start, end);\n}\nfunction endOpenTag(end) {\n  if (tokenizer.inSFCRoot) {\n    currentOpenTag.innerLoc = getLoc(end + 1, end + 1);\n  }\n  addNode(currentOpenTag);\n  const { tag, ns } = currentOpenTag;\n  if (ns === 0 && currentOptions.isPreTag(tag)) {\n    inPre++;\n  }\n  if (currentOptions.isVoidTag(tag)) {\n    onCloseTag(currentOpenTag, end);\n  } else {\n    stack.unshift(currentOpenTag);\n    if (ns === 1 || ns === 2) {\n      tokenizer.inXML = true;\n    }\n  }\n  currentOpenTag = null;\n}\nfunction onText(content, start, end) {\n  const parent = stack[0] || currentRoot;\n  const lastNode = parent.children[parent.children.length - 1];\n  if (lastNode && lastNode.type === 2) {\n    lastNode.content += content;\n    setLocEnd(lastNode.loc, end);\n  } else {\n    parent.children.push({\n      type: 2,\n      content,\n      loc: getLoc(start, end)\n    });\n  }\n}\nfunction onCloseTag(el, end, isImplied = false) {\n  if (isImplied) {\n    setLocEnd(el.loc, backTrack(end, 60));\n  } else {\n    setLocEnd(el.loc, lookAhead(end, 62) + 1);\n  }\n  if (tokenizer.inSFCRoot) {\n    if (el.children.length) {\n      el.innerLoc.end = shared.extend({}, el.children[el.children.length - 1].loc.end);\n    } else {\n      el.innerLoc.end = shared.extend({}, el.innerLoc.start);\n    }\n    el.innerLoc.source = getSlice(\n      el.innerLoc.start.offset,\n      el.innerLoc.end.offset\n    );\n  }\n  const { tag, ns, children } = el;\n  if (!inVPre) {\n    if (tag === \"slot\") {\n      el.tagType = 2;\n    } else if (isFragmentTemplate(el)) {\n      el.tagType = 3;\n    } else if (isComponent(el)) {\n      el.tagType = 1;\n    }\n  }\n  if (!tokenizer.inRCDATA) {\n    el.children = condenseWhitespace(children);\n  }\n  if (ns === 0 && currentOptions.isIgnoreNewlineTag(tag)) {\n    const first = children[0];\n    if (first && first.type === 2) {\n      first.content = first.content.replace(/^\\r?\\n/, \"\");\n    }\n  }\n  if (ns === 0 && currentOptions.isPreTag(tag)) {\n    inPre--;\n  }\n  if (currentVPreBoundary === el) {\n    inVPre = tokenizer.inVPre = false;\n    currentVPreBoundary = null;\n  }\n  if (tokenizer.inXML && (stack[0] ? stack[0].ns : currentOptions.ns) === 0) {\n    tokenizer.inXML = false;\n  }\n  {\n    const props = el.props;\n    if (!tokenizer.inSFCRoot && isCompatEnabled(\n      \"COMPILER_NATIVE_TEMPLATE\",\n      currentOptions\n    ) && el.tag === \"template\" && !isFragmentTemplate(el)) {\n      const parent = stack[0] || currentRoot;\n      const index = parent.children.indexOf(el);\n      parent.children.splice(index, 1, ...el.children);\n    }\n    const inlineTemplateProp = props.find(\n      (p) => p.type === 6 && p.name === \"inline-template\"\n    );\n    if (inlineTemplateProp && checkCompatEnabled(\n      \"COMPILER_INLINE_TEMPLATE\",\n      currentOptions,\n      inlineTemplateProp.loc\n    ) && el.children.length) {\n      inlineTemplateProp.value = {\n        type: 2,\n        content: getSlice(\n          el.children[0].loc.start.offset,\n          el.children[el.children.length - 1].loc.end.offset\n        ),\n        loc: inlineTemplateProp.loc\n      };\n    }\n  }\n}\nfunction lookAhead(index, c) {\n  let i = index;\n  while (currentInput.charCodeAt(i) !== c && i < currentInput.length - 1) i++;\n  return i;\n}\nfunction backTrack(index, c) {\n  let i = index;\n  while (currentInput.charCodeAt(i) !== c && i >= 0) i--;\n  return i;\n}\nconst specialTemplateDir = /* @__PURE__ */ new Set([\"if\", \"else\", \"else-if\", \"for\", \"slot\"]);\nfunction isFragmentTemplate({ tag, props }) {\n  if (tag === \"template\") {\n    for (let i = 0; i < props.length; i++) {\n      if (props[i].type === 7 && specialTemplateDir.has(props[i].name)) {\n        return true;\n      }\n    }\n  }\n  return false;\n}\nfunction isComponent({ tag, props }) {\n  if (currentOptions.isCustomElement(tag)) {\n    return false;\n  }\n  if (tag === \"component\" || isUpperCase(tag.charCodeAt(0)) || isCoreComponent(tag) || currentOptions.isBuiltInComponent && currentOptions.isBuiltInComponent(tag) || currentOptions.isNativeTag && !currentOptions.isNativeTag(tag)) {\n    return true;\n  }\n  for (let i = 0; i < props.length; i++) {\n    const p = props[i];\n    if (p.type === 6) {\n      if (p.name === \"is\" && p.value) {\n        if (p.value.content.startsWith(\"vue:\")) {\n          return true;\n        } else if (checkCompatEnabled(\n          \"COMPILER_IS_ON_ELEMENT\",\n          currentOptions,\n          p.loc\n        )) {\n          return true;\n        }\n      }\n    } else if (// :is on plain element - only treat as component in compat mode\n    p.name === \"bind\" && isStaticArgOf(p.arg, \"is\") && checkCompatEnabled(\n      \"COMPILER_IS_ON_ELEMENT\",\n      currentOptions,\n      p.loc\n    )) {\n      return true;\n    }\n  }\n  return false;\n}\nfunction isUpperCase(c) {\n  return c > 64 && c < 91;\n}\nconst windowsNewlineRE = /\\r\\n/g;\nfunction condenseWhitespace(nodes) {\n  const shouldCondense = currentOptions.whitespace !== \"preserve\";\n  let removedWhitespace = false;\n  for (let i = 0; i < nodes.length; i++) {\n    const node = nodes[i];\n    if (node.type === 2) {\n      if (!inPre) {\n        if (isAllWhitespace(node.content)) {\n          const prev = nodes[i - 1] && nodes[i - 1].type;\n          const next = nodes[i + 1] && nodes[i + 1].type;\n          if (!prev || !next || shouldCondense && (prev === 3 && (next === 3 || next === 1) || prev === 1 && (next === 3 || next === 1 && hasNewlineChar(node.content)))) {\n            removedWhitespace = true;\n            nodes[i] = null;\n          } else {\n            node.content = \" \";\n          }\n        } else if (shouldCondense) {\n          node.content = condense(node.content);\n        }\n      } else {\n        node.content = node.content.replace(windowsNewlineRE, \"\\n\");\n      }\n    }\n  }\n  return removedWhitespace ? nodes.filter(Boolean) : nodes;\n}\nfunction isAllWhitespace(str) {\n  for (let i = 0; i < str.length; i++) {\n    if (!isWhitespace(str.charCodeAt(i))) {\n      return false;\n    }\n  }\n  return true;\n}\nfunction hasNewlineChar(str) {\n  for (let i = 0; i < str.length; i++) {\n    const c = str.charCodeAt(i);\n    if (c === 10 || c === 13) {\n      return true;\n    }\n  }\n  return false;\n}\nfunction condense(str) {\n  let ret = \"\";\n  let prevCharIsWhitespace = false;\n  for (let i = 0; i < str.length; i++) {\n    if (isWhitespace(str.charCodeAt(i))) {\n      if (!prevCharIsWhitespace) {\n        ret += \" \";\n        prevCharIsWhitespace = true;\n      }\n    } else {\n      ret += str[i];\n      prevCharIsWhitespace = false;\n    }\n  }\n  return ret;\n}\nfunction addNode(node) {\n  (stack[0] || currentRoot).children.push(node);\n}\nfunction getLoc(start, end) {\n  return {\n    start: tokenizer.getPos(start),\n    // @ts-expect-error allow late attachment\n    end: end == null ? end : tokenizer.getPos(end),\n    // @ts-expect-error allow late attachment\n    source: end == null ? end : getSlice(start, end)\n  };\n}\nfunction cloneLoc(loc) {\n  return getLoc(loc.start.offset, loc.end.offset);\n}\nfunction setLocEnd(loc, end) {\n  loc.end = tokenizer.getPos(end);\n  loc.source = getSlice(loc.start.offset, end);\n}\nfunction dirToAttr(dir) {\n  const attr = {\n    type: 6,\n    name: dir.rawName,\n    nameLoc: getLoc(\n      dir.loc.start.offset,\n      dir.loc.start.offset + dir.rawName.length\n    ),\n    value: void 0,\n    loc: dir.loc\n  };\n  if (dir.exp) {\n    const loc = dir.exp.loc;\n    if (loc.end.offset < dir.loc.end.offset) {\n      loc.start.offset--;\n      loc.start.column--;\n      loc.end.offset++;\n      loc.end.column++;\n    }\n    attr.value = {\n      type: 2,\n      content: dir.exp.content,\n      loc\n    };\n  }\n  return attr;\n}\nfunction createExp(content, isStatic = false, loc, constType = 0, parseMode = 0 /* Normal */) {\n  const exp = createSimpleExpression(content, isStatic, loc, constType);\n  if (!isStatic && currentOptions.prefixIdentifiers && parseMode !== 3 /* Skip */ && content.trim()) {\n    if (isSimpleIdentifier(content)) {\n      exp.ast = null;\n      return exp;\n    }\n    try {\n      const plugins = currentOptions.expressionPlugins;\n      const options = {\n        plugins: plugins ? [...plugins, \"typescript\"] : [\"typescript\"]\n      };\n      if (parseMode === 2 /* Statements */) {\n        exp.ast = parser.parse(` ${content} `, options).program;\n      } else if (parseMode === 1 /* Params */) {\n        exp.ast = parser.parseExpression(`(${content})=>{}`, options);\n      } else {\n        exp.ast = parser.parseExpression(`(${content})`, options);\n      }\n    } catch (e) {\n      exp.ast = false;\n      emitError(45, loc.start.offset, e.message);\n    }\n  }\n  return exp;\n}\nfunction emitError(code, index, message) {\n  currentOptions.onError(\n    createCompilerError(code, getLoc(index, index), void 0, message)\n  );\n}\nfunction reset() {\n  tokenizer.reset();\n  currentOpenTag = null;\n  currentProp = null;\n  currentAttrValue = \"\";\n  currentAttrStartIndex = -1;\n  currentAttrEndIndex = -1;\n  stack.length = 0;\n}\nfunction baseParse(input, options) {\n  reset();\n  currentInput = input;\n  currentOptions = shared.extend({}, defaultParserOptions);\n  if (options) {\n    let key;\n    for (key in options) {\n      if (options[key] != null) {\n        currentOptions[key] = options[key];\n      }\n    }\n  }\n  tokenizer.mode = currentOptions.parseMode === \"html\" ? 1 : currentOptions.parseMode === \"sfc\" ? 2 : 0;\n  tokenizer.inXML = currentOptions.ns === 1 || currentOptions.ns === 2;\n  const delimiters = options && options.delimiters;\n  if (delimiters) {\n    tokenizer.delimiterOpen = toCharCodes(delimiters[0]);\n    tokenizer.delimiterClose = toCharCodes(delimiters[1]);\n  }\n  const root = currentRoot = createRoot([], input);\n  tokenizer.parse(currentInput);\n  root.loc = getLoc(0, input.length);\n  root.children = condenseWhitespace(root.children);\n  currentRoot = null;\n  return root;\n}\n\nfunction cacheStatic(root, context) {\n  walk(\n    root,\n    void 0,\n    context,\n    // Root node is unfortunately non-hoistable due to potential parent\n    // fallthrough attributes.\n    !!getSingleElementRoot(root)\n  );\n}\nfunction getSingleElementRoot(root) {\n  const children = root.children.filter((x) => x.type !== 3);\n  return children.length === 1 && children[0].type === 1 && !isSlotOutlet(children[0]) ? children[0] : null;\n}\nfunction walk(node, parent, context, doNotHoistNode = false, inFor = false) {\n  const { children } = node;\n  const toCache = [];\n  for (let i = 0; i < children.length; i++) {\n    const child = children[i];\n    if (child.type === 1 && child.tagType === 0) {\n      const constantType = doNotHoistNode ? 0 : getConstantType(child, context);\n      if (constantType > 0) {\n        if (constantType >= 2) {\n          child.codegenNode.patchFlag = -1;\n          toCache.push(child);\n          continue;\n        }\n      } else {\n        const codegenNode = child.codegenNode;\n        if (codegenNode.type === 13) {\n          const flag = codegenNode.patchFlag;\n          if ((flag === void 0 || flag === 512 || flag === 1) && getGeneratedPropsConstantType(child, context) >= 2) {\n            const props = getNodeProps(child);\n            if (props) {\n              codegenNode.props = context.hoist(props);\n            }\n          }\n          if (codegenNode.dynamicProps) {\n            codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);\n          }\n        }\n      }\n    } else if (child.type === 12) {\n      const constantType = doNotHoistNode ? 0 : getConstantType(child, context);\n      if (constantType >= 2) {\n        if (child.codegenNode.type === 14 && child.codegenNode.arguments.length > 0) {\n          child.codegenNode.arguments.push(\n            -1 + (``)\n          );\n        }\n        toCache.push(child);\n        continue;\n      }\n    }\n    if (child.type === 1) {\n      const isComponent = child.tagType === 1;\n      if (isComponent) {\n        context.scopes.vSlot++;\n      }\n      walk(child, node, context, false, inFor);\n      if (isComponent) {\n        context.scopes.vSlot--;\n      }\n    } else if (child.type === 11) {\n      walk(child, node, context, child.children.length === 1, true);\n    } else if (child.type === 9) {\n      for (let i2 = 0; i2 < child.branches.length; i2++) {\n        walk(\n          child.branches[i2],\n          node,\n          context,\n          child.branches[i2].children.length === 1,\n          inFor\n        );\n      }\n    }\n  }\n  let cachedAsArray = false;\n  const slotCacheKeys = [];\n  if (toCache.length === children.length && node.type === 1) {\n    if (node.tagType === 0 && node.codegenNode && node.codegenNode.type === 13 && shared.isArray(node.codegenNode.children)) {\n      node.codegenNode.children = getCacheExpression(\n        createArrayExpression(node.codegenNode.children)\n      );\n      cachedAsArray = true;\n    } else if (node.tagType === 1 && node.codegenNode && node.codegenNode.type === 13 && node.codegenNode.children && !shared.isArray(node.codegenNode.children) && node.codegenNode.children.type === 15) {\n      const slot = getSlotNode(node.codegenNode, \"default\");\n      if (slot) {\n        slotCacheKeys.push(context.cached.length);\n        slot.returns = getCacheExpression(\n          createArrayExpression(slot.returns)\n        );\n        cachedAsArray = true;\n      }\n    } else if (node.tagType === 3 && parent && parent.type === 1 && parent.tagType === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !shared.isArray(parent.codegenNode.children) && parent.codegenNode.children.type === 15) {\n      const slotName = findDir(node, \"slot\", true);\n      const slot = slotName && slotName.arg && getSlotNode(parent.codegenNode, slotName.arg);\n      if (slot) {\n        slotCacheKeys.push(context.cached.length);\n        slot.returns = getCacheExpression(\n          createArrayExpression(slot.returns)\n        );\n        cachedAsArray = true;\n      }\n    }\n  }\n  if (!cachedAsArray) {\n    for (const child of toCache) {\n      slotCacheKeys.push(context.cached.length);\n      child.codegenNode = context.cache(child.codegenNode);\n    }\n  }\n  if (slotCacheKeys.length && node.type === 1 && node.tagType === 1 && node.codegenNode && node.codegenNode.type === 13 && node.codegenNode.children && !shared.isArray(node.codegenNode.children) && node.codegenNode.children.type === 15) {\n    node.codegenNode.children.properties.push(\n      createObjectProperty(\n        `__`,\n        createSimpleExpression(JSON.stringify(slotCacheKeys), false)\n      )\n    );\n  }\n  function getCacheExpression(value) {\n    const exp = context.cache(value);\n    if (inFor && context.hmr) {\n      exp.needArraySpread = true;\n    }\n    return exp;\n  }\n  function getSlotNode(node2, name) {\n    if (node2.children && !shared.isArray(node2.children) && node2.children.type === 15) {\n      const slot = node2.children.properties.find(\n        (p) => p.key === name || p.key.content === name\n      );\n      return slot && slot.value;\n    }\n  }\n  if (toCache.length && context.transformHoist) {\n    context.transformHoist(children, context, node);\n  }\n}\nfunction getConstantType(node, context) {\n  const { constantCache } = context;\n  switch (node.type) {\n    case 1:\n      if (node.tagType !== 0) {\n        return 0;\n      }\n      const cached = constantCache.get(node);\n      if (cached !== void 0) {\n        return cached;\n      }\n      const codegenNode = node.codegenNode;\n      if (codegenNode.type !== 13) {\n        return 0;\n      }\n      if (codegenNode.isBlock && node.tag !== \"svg\" && node.tag !== \"foreignObject\" && node.tag !== \"math\") {\n        return 0;\n      }\n      if (codegenNode.patchFlag === void 0) {\n        let returnType2 = 3;\n        const generatedPropsType = getGeneratedPropsConstantType(node, context);\n        if (generatedPropsType === 0) {\n          constantCache.set(node, 0);\n          return 0;\n        }\n        if (generatedPropsType < returnType2) {\n          returnType2 = generatedPropsType;\n        }\n        for (let i = 0; i < node.children.length; i++) {\n          const childType = getConstantType(node.children[i], context);\n          if (childType === 0) {\n            constantCache.set(node, 0);\n            return 0;\n          }\n          if (childType < returnType2) {\n            returnType2 = childType;\n          }\n        }\n        if (returnType2 > 1) {\n          for (let i = 0; i < node.props.length; i++) {\n            const p = node.props[i];\n            if (p.type === 7 && p.name === \"bind\" && p.exp) {\n              const expType = getConstantType(p.exp, context);\n              if (expType === 0) {\n                constantCache.set(node, 0);\n                return 0;\n              }\n              if (expType < returnType2) {\n                returnType2 = expType;\n              }\n            }\n          }\n        }\n        if (codegenNode.isBlock) {\n          for (let i = 0; i < node.props.length; i++) {\n            const p = node.props[i];\n            if (p.type === 7) {\n              constantCache.set(node, 0);\n              return 0;\n            }\n          }\n          context.removeHelper(OPEN_BLOCK);\n          context.removeHelper(\n            getVNodeBlockHelper(context.inSSR, codegenNode.isComponent)\n          );\n          codegenNode.isBlock = false;\n          context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));\n        }\n        constantCache.set(node, returnType2);\n        return returnType2;\n      } else {\n        constantCache.set(node, 0);\n        return 0;\n      }\n    case 2:\n    case 3:\n      return 3;\n    case 9:\n    case 11:\n    case 10:\n      return 0;\n    case 5:\n    case 12:\n      return getConstantType(node.content, context);\n    case 4:\n      return node.constType;\n    case 8:\n      let returnType = 3;\n      for (let i = 0; i < node.children.length; i++) {\n        const child = node.children[i];\n        if (shared.isString(child) || shared.isSymbol(child)) {\n          continue;\n        }\n        const childType = getConstantType(child, context);\n        if (childType === 0) {\n          return 0;\n        } else if (childType < returnType) {\n          returnType = childType;\n        }\n      }\n      return returnType;\n    case 20:\n      return 2;\n    default:\n      return 0;\n  }\n}\nconst allowHoistedHelperSet = /* @__PURE__ */ new Set([\n  NORMALIZE_CLASS,\n  NORMALIZE_STYLE,\n  NORMALIZE_PROPS,\n  GUARD_REACTIVE_PROPS\n]);\nfunction getConstantTypeOfHelperCall(value, context) {\n  if (value.type === 14 && !shared.isString(value.callee) && allowHoistedHelperSet.has(value.callee)) {\n    const arg = value.arguments[0];\n    if (arg.type === 4) {\n      return getConstantType(arg, context);\n    } else if (arg.type === 14) {\n      return getConstantTypeOfHelperCall(arg, context);\n    }\n  }\n  return 0;\n}\nfunction getGeneratedPropsConstantType(node, context) {\n  let returnType = 3;\n  const props = getNodeProps(node);\n  if (props && props.type === 15) {\n    const { properties } = props;\n    for (let i = 0; i < properties.length; i++) {\n      const { key, value } = properties[i];\n      const keyType = getConstantType(key, context);\n      if (keyType === 0) {\n        return keyType;\n      }\n      if (keyType < returnType) {\n        returnType = keyType;\n      }\n      let valueType;\n      if (value.type === 4) {\n        valueType = getConstantType(value, context);\n      } else if (value.type === 14) {\n        valueType = getConstantTypeOfHelperCall(value, context);\n      } else {\n        valueType = 0;\n      }\n      if (valueType === 0) {\n        return valueType;\n      }\n      if (valueType < returnType) {\n        returnType = valueType;\n      }\n    }\n  }\n  return returnType;\n}\nfunction getNodeProps(node) {\n  const codegenNode = node.codegenNode;\n  if (codegenNode.type === 13) {\n    return codegenNode.props;\n  }\n}\n\nfunction createTransformContext(root, {\n  filename = \"\",\n  prefixIdentifiers = false,\n  hoistStatic = false,\n  hmr = false,\n  cacheHandlers = false,\n  nodeTransforms = [],\n  directiveTransforms = {},\n  transformHoist = null,\n  isBuiltInComponent = shared.NOOP,\n  isCustomElement = shared.NOOP,\n  expressionPlugins = [],\n  scopeId = null,\n  slotted = true,\n  ssr = false,\n  inSSR = false,\n  ssrCssVars = ``,\n  bindingMetadata = shared.EMPTY_OBJ,\n  inline = false,\n  isTS = false,\n  onError = defaultOnError,\n  onWarn = defaultOnWarn,\n  compatConfig\n}) {\n  const nameMatch = filename.replace(/\\?.*$/, \"\").match(/([^/\\\\]+)\\.\\w+$/);\n  const context = {\n    // options\n    filename,\n    selfName: nameMatch && shared.capitalize(shared.camelize(nameMatch[1])),\n    prefixIdentifiers,\n    hoistStatic,\n    hmr,\n    cacheHandlers,\n    nodeTransforms,\n    directiveTransforms,\n    transformHoist,\n    isBuiltInComponent,\n    isCustomElement,\n    expressionPlugins,\n    scopeId,\n    slotted,\n    ssr,\n    inSSR,\n    ssrCssVars,\n    bindingMetadata,\n    inline,\n    isTS,\n    onError,\n    onWarn,\n    compatConfig,\n    // state\n    root,\n    helpers: /* @__PURE__ */ new Map(),\n    components: /* @__PURE__ */ new Set(),\n    directives: /* @__PURE__ */ new Set(),\n    hoists: [],\n    imports: [],\n    cached: [],\n    constantCache: /* @__PURE__ */ new WeakMap(),\n    temps: 0,\n    identifiers: /* @__PURE__ */ Object.create(null),\n    scopes: {\n      vFor: 0,\n      vSlot: 0,\n      vPre: 0,\n      vOnce: 0\n    },\n    parent: null,\n    grandParent: null,\n    currentNode: root,\n    childIndex: 0,\n    inVOnce: false,\n    // methods\n    helper(name) {\n      const count = context.helpers.get(name) || 0;\n      context.helpers.set(name, count + 1);\n      return name;\n    },\n    removeHelper(name) {\n      const count = context.helpers.get(name);\n      if (count) {\n        const currentCount = count - 1;\n        if (!currentCount) {\n          context.helpers.delete(name);\n        } else {\n          context.helpers.set(name, currentCount);\n        }\n      }\n    },\n    helperString(name) {\n      return `_${helperNameMap[context.helper(name)]}`;\n    },\n    replaceNode(node) {\n      context.parent.children[context.childIndex] = context.currentNode = node;\n    },\n    removeNode(node) {\n      const list = context.parent.children;\n      const removalIndex = node ? list.indexOf(node) : context.currentNode ? context.childIndex : -1;\n      if (!node || node === context.currentNode) {\n        context.currentNode = null;\n        context.onNodeRemoved();\n      } else {\n        if (context.childIndex > removalIndex) {\n          context.childIndex--;\n          context.onNodeRemoved();\n        }\n      }\n      context.parent.children.splice(removalIndex, 1);\n    },\n    onNodeRemoved: shared.NOOP,\n    addIdentifiers(exp) {\n      {\n        if (shared.isString(exp)) {\n          addId(exp);\n        } else if (exp.identifiers) {\n          exp.identifiers.forEach(addId);\n        } else if (exp.type === 4) {\n          addId(exp.content);\n        }\n      }\n    },\n    removeIdentifiers(exp) {\n      {\n        if (shared.isString(exp)) {\n          removeId(exp);\n        } else if (exp.identifiers) {\n          exp.identifiers.forEach(removeId);\n        } else if (exp.type === 4) {\n          removeId(exp.content);\n        }\n      }\n    },\n    hoist(exp) {\n      if (shared.isString(exp)) exp = createSimpleExpression(exp);\n      context.hoists.push(exp);\n      const identifier = createSimpleExpression(\n        `_hoisted_${context.hoists.length}`,\n        false,\n        exp.loc,\n        2\n      );\n      identifier.hoisted = exp;\n      return identifier;\n    },\n    cache(exp, isVNode = false, inVOnce = false) {\n      const cacheExp = createCacheExpression(\n        context.cached.length,\n        exp,\n        isVNode,\n        inVOnce\n      );\n      context.cached.push(cacheExp);\n      return cacheExp;\n    }\n  };\n  {\n    context.filters = /* @__PURE__ */ new Set();\n  }\n  function addId(id) {\n    const { identifiers } = context;\n    if (identifiers[id] === void 0) {\n      identifiers[id] = 0;\n    }\n    identifiers[id]++;\n  }\n  function removeId(id) {\n    context.identifiers[id]--;\n  }\n  return context;\n}\nfunction transform(root, options) {\n  const context = createTransformContext(root, options);\n  traverseNode(root, context);\n  if (options.hoistStatic) {\n    cacheStatic(root, context);\n  }\n  if (!options.ssr) {\n    createRootCodegen(root, context);\n  }\n  root.helpers = /* @__PURE__ */ new Set([...context.helpers.keys()]);\n  root.components = [...context.components];\n  root.directives = [...context.directives];\n  root.imports = context.imports;\n  root.hoists = context.hoists;\n  root.temps = context.temps;\n  root.cached = context.cached;\n  root.transformed = true;\n  {\n    root.filters = [...context.filters];\n  }\n}\nfunction createRootCodegen(root, context) {\n  const { helper } = context;\n  const { children } = root;\n  if (children.length === 1) {\n    const singleElementRootChild = getSingleElementRoot(root);\n    if (singleElementRootChild && singleElementRootChild.codegenNode) {\n      const codegenNode = singleElementRootChild.codegenNode;\n      if (codegenNode.type === 13) {\n        convertToBlock(codegenNode, context);\n      }\n      root.codegenNode = codegenNode;\n    } else {\n      root.codegenNode = children[0];\n    }\n  } else if (children.length > 1) {\n    let patchFlag = 64;\n    root.codegenNode = createVNodeCall(\n      context,\n      helper(FRAGMENT),\n      void 0,\n      root.children,\n      patchFlag,\n      void 0,\n      void 0,\n      true,\n      void 0,\n      false\n    );\n  } else ;\n}\nfunction traverseChildren(parent, context) {\n  let i = 0;\n  const nodeRemoved = () => {\n    i--;\n  };\n  for (; i < parent.children.length; i++) {\n    const child = parent.children[i];\n    if (shared.isString(child)) continue;\n    context.grandParent = context.parent;\n    context.parent = parent;\n    context.childIndex = i;\n    context.onNodeRemoved = nodeRemoved;\n    traverseNode(child, context);\n  }\n}\nfunction traverseNode(node, context) {\n  context.currentNode = node;\n  const { nodeTransforms } = context;\n  const exitFns = [];\n  for (let i2 = 0; i2 < nodeTransforms.length; i2++) {\n    const onExit = nodeTransforms[i2](node, context);\n    if (onExit) {\n      if (shared.isArray(onExit)) {\n        exitFns.push(...onExit);\n      } else {\n        exitFns.push(onExit);\n      }\n    }\n    if (!context.currentNode) {\n      return;\n    } else {\n      node = context.currentNode;\n    }\n  }\n  switch (node.type) {\n    case 3:\n      if (!context.ssr) {\n        context.helper(CREATE_COMMENT);\n      }\n      break;\n    case 5:\n      if (!context.ssr) {\n        context.helper(TO_DISPLAY_STRING);\n      }\n      break;\n    // for container types, further traverse downwards\n    case 9:\n      for (let i2 = 0; i2 < node.branches.length; i2++) {\n        traverseNode(node.branches[i2], context);\n      }\n      break;\n    case 10:\n    case 11:\n    case 1:\n    case 0:\n      traverseChildren(node, context);\n      break;\n  }\n  context.currentNode = node;\n  let i = exitFns.length;\n  while (i--) {\n    exitFns[i]();\n  }\n}\nfunction createStructuralDirectiveTransform(name, fn) {\n  const matches = shared.isString(name) ? (n) => n === name : (n) => name.test(n);\n  return (node, context) => {\n    if (node.type === 1) {\n      const { props } = node;\n      if (node.tagType === 3 && props.some(isVSlot)) {\n        return;\n      }\n      const exitFns = [];\n      for (let i = 0; i < props.length; i++) {\n        const prop = props[i];\n        if (prop.type === 7 && matches(prop.name)) {\n          props.splice(i, 1);\n          i--;\n          const onExit = fn(node, prop, context);\n          if (onExit) exitFns.push(onExit);\n        }\n      }\n      return exitFns;\n    }\n  };\n}\n\nconst PURE_ANNOTATION = `/*@__PURE__*/`;\nconst aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;\nfunction createCodegenContext(ast, {\n  mode = \"function\",\n  prefixIdentifiers = mode === \"module\",\n  sourceMap = false,\n  filename = `template.vue.html`,\n  scopeId = null,\n  optimizeImports = false,\n  runtimeGlobalName = `Vue`,\n  runtimeModuleName = `vue`,\n  ssrRuntimeModuleName = \"vue/server-renderer\",\n  ssr = false,\n  isTS = false,\n  inSSR = false\n}) {\n  const context = {\n    mode,\n    prefixIdentifiers,\n    sourceMap,\n    filename,\n    scopeId,\n    optimizeImports,\n    runtimeGlobalName,\n    runtimeModuleName,\n    ssrRuntimeModuleName,\n    ssr,\n    isTS,\n    inSSR,\n    source: ast.source,\n    code: ``,\n    column: 1,\n    line: 1,\n    offset: 0,\n    indentLevel: 0,\n    pure: false,\n    map: void 0,\n    helper(key) {\n      return `_${helperNameMap[key]}`;\n    },\n    push(code, newlineIndex = -2 /* None */, node) {\n      context.code += code;\n      if (context.map) {\n        if (node) {\n          let name;\n          if (node.type === 4 && !node.isStatic) {\n            const content = node.content.replace(/^_ctx\\./, \"\");\n            if (content !== node.content && isSimpleIdentifier(content)) {\n              name = content;\n            }\n          }\n          if (node.loc.source) {\n            addMapping(node.loc.start, name);\n          }\n        }\n        if (newlineIndex === -3 /* Unknown */) {\n          advancePositionWithMutation(context, code);\n        } else {\n          context.offset += code.length;\n          if (newlineIndex === -2 /* None */) {\n            context.column += code.length;\n          } else {\n            if (newlineIndex === -1 /* End */) {\n              newlineIndex = code.length - 1;\n            }\n            context.line++;\n            context.column = code.length - newlineIndex;\n          }\n        }\n        if (node && node.loc !== locStub && node.loc.source) {\n          addMapping(node.loc.end);\n        }\n      }\n    },\n    indent() {\n      newline(++context.indentLevel);\n    },\n    deindent(withoutNewLine = false) {\n      if (withoutNewLine) {\n        --context.indentLevel;\n      } else {\n        newline(--context.indentLevel);\n      }\n    },\n    newline() {\n      newline(context.indentLevel);\n    }\n  };\n  function newline(n) {\n    context.push(\"\\n\" + `  `.repeat(n), 0 /* Start */);\n  }\n  function addMapping(loc, name = null) {\n    const { _names, _mappings } = context.map;\n    if (name !== null && !_names.has(name)) _names.add(name);\n    _mappings.add({\n      originalLine: loc.line,\n      originalColumn: loc.column - 1,\n      // source-map column is 0 based\n      generatedLine: context.line,\n      generatedColumn: context.column - 1,\n      source: filename,\n      name\n    });\n  }\n  if (sourceMap) {\n    context.map = new sourceMapJs.SourceMapGenerator();\n    context.map.setSourceContent(filename, context.source);\n    context.map._sources.add(filename);\n  }\n  return context;\n}\nfunction generate(ast, options = {}) {\n  const context = createCodegenContext(ast, options);\n  if (options.onContextCreated) options.onContextCreated(context);\n  const {\n    mode,\n    push,\n    prefixIdentifiers,\n    indent,\n    deindent,\n    newline,\n    scopeId,\n    ssr\n  } = context;\n  const helpers = Array.from(ast.helpers);\n  const hasHelpers = helpers.length > 0;\n  const useWithBlock = !prefixIdentifiers && mode !== \"module\";\n  const genScopeId = scopeId != null && mode === \"module\";\n  const isSetupInlined = !!options.inline;\n  const preambleContext = isSetupInlined ? createCodegenContext(ast, options) : context;\n  if (mode === \"module\") {\n    genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined);\n  } else {\n    genFunctionPreamble(ast, preambleContext);\n  }\n  const functionName = ssr ? `ssrRender` : `render`;\n  const args = ssr ? [\"_ctx\", \"_push\", \"_parent\", \"_attrs\"] : [\"_ctx\", \"_cache\"];\n  if (options.bindingMetadata && !options.inline) {\n    args.push(\"$props\", \"$setup\", \"$data\", \"$options\");\n  }\n  const signature = options.isTS ? args.map((arg) => `${arg}: any`).join(\",\") : args.join(\", \");\n  if (isSetupInlined) {\n    push(`(${signature}) => {`);\n  } else {\n    push(`function ${functionName}(${signature}) {`);\n  }\n  indent();\n  if (useWithBlock) {\n    push(`with (_ctx) {`);\n    indent();\n    if (hasHelpers) {\n      push(\n        `const { ${helpers.map(aliasHelper).join(\", \")} } = _Vue\n`,\n        -1 /* End */\n      );\n      newline();\n    }\n  }\n  if (ast.components.length) {\n    genAssets(ast.components, \"component\", context);\n    if (ast.directives.length || ast.temps > 0) {\n      newline();\n    }\n  }\n  if (ast.directives.length) {\n    genAssets(ast.directives, \"directive\", context);\n    if (ast.temps > 0) {\n      newline();\n    }\n  }\n  if (ast.filters && ast.filters.length) {\n    newline();\n    genAssets(ast.filters, \"filter\", context);\n    newline();\n  }\n  if (ast.temps > 0) {\n    push(`let `);\n    for (let i = 0; i < ast.temps; i++) {\n      push(`${i > 0 ? `, ` : ``}_temp${i}`);\n    }\n  }\n  if (ast.components.length || ast.directives.length || ast.temps) {\n    push(`\n`, 0 /* Start */);\n    newline();\n  }\n  if (!ssr) {\n    push(`return `);\n  }\n  if (ast.codegenNode) {\n    genNode(ast.codegenNode, context);\n  } else {\n    push(`null`);\n  }\n  if (useWithBlock) {\n    deindent();\n    push(`}`);\n  }\n  deindent();\n  push(`}`);\n  return {\n    ast,\n    code: context.code,\n    preamble: isSetupInlined ? preambleContext.code : ``,\n    map: context.map ? context.map.toJSON() : void 0\n  };\n}\nfunction genFunctionPreamble(ast, context) {\n  const {\n    ssr,\n    prefixIdentifiers,\n    push,\n    newline,\n    runtimeModuleName,\n    runtimeGlobalName,\n    ssrRuntimeModuleName\n  } = context;\n  const VueBinding = ssr ? `require(${JSON.stringify(runtimeModuleName)})` : runtimeGlobalName;\n  const helpers = Array.from(ast.helpers);\n  if (helpers.length > 0) {\n    if (prefixIdentifiers) {\n      push(\n        `const { ${helpers.map(aliasHelper).join(\", \")} } = ${VueBinding}\n`,\n        -1 /* End */\n      );\n    } else {\n      push(`const _Vue = ${VueBinding}\n`, -1 /* End */);\n      if (ast.hoists.length) {\n        const staticHelpers = [\n          CREATE_VNODE,\n          CREATE_ELEMENT_VNODE,\n          CREATE_COMMENT,\n          CREATE_TEXT,\n          CREATE_STATIC\n        ].filter((helper) => helpers.includes(helper)).map(aliasHelper).join(\", \");\n        push(`const { ${staticHelpers} } = _Vue\n`, -1 /* End */);\n      }\n    }\n  }\n  if (ast.ssrHelpers && ast.ssrHelpers.length) {\n    push(\n      `const { ${ast.ssrHelpers.map(aliasHelper).join(\", \")} } = require(\"${ssrRuntimeModuleName}\")\n`,\n      -1 /* End */\n    );\n  }\n  genHoists(ast.hoists, context);\n  newline();\n  push(`return `);\n}\nfunction genModulePreamble(ast, context, genScopeId, inline) {\n  const {\n    push,\n    newline,\n    optimizeImports,\n    runtimeModuleName,\n    ssrRuntimeModuleName\n  } = context;\n  if (ast.helpers.size) {\n    const helpers = Array.from(ast.helpers);\n    if (optimizeImports) {\n      push(\n        `import { ${helpers.map((s) => helperNameMap[s]).join(\", \")} } from ${JSON.stringify(runtimeModuleName)}\n`,\n        -1 /* End */\n      );\n      push(\n        `\n// Binding optimization for webpack code-split\nconst ${helpers.map((s) => `_${helperNameMap[s]} = ${helperNameMap[s]}`).join(\", \")}\n`,\n        -1 /* End */\n      );\n    } else {\n      push(\n        `import { ${helpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(\", \")} } from ${JSON.stringify(runtimeModuleName)}\n`,\n        -1 /* End */\n      );\n    }\n  }\n  if (ast.ssrHelpers && ast.ssrHelpers.length) {\n    push(\n      `import { ${ast.ssrHelpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(\", \")} } from \"${ssrRuntimeModuleName}\"\n`,\n      -1 /* End */\n    );\n  }\n  if (ast.imports.length) {\n    genImports(ast.imports, context);\n    newline();\n  }\n  genHoists(ast.hoists, context);\n  newline();\n  if (!inline) {\n    push(`export `);\n  }\n}\nfunction genAssets(assets, type, { helper, push, newline, isTS }) {\n  const resolver = helper(\n    type === \"filter\" ? RESOLVE_FILTER : type === \"component\" ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE\n  );\n  for (let i = 0; i < assets.length; i++) {\n    let id = assets[i];\n    const maybeSelfReference = id.endsWith(\"__self\");\n    if (maybeSelfReference) {\n      id = id.slice(0, -6);\n    }\n    push(\n      `const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`\n    );\n    if (i < assets.length - 1) {\n      newline();\n    }\n  }\n}\nfunction genHoists(hoists, context) {\n  if (!hoists.length) {\n    return;\n  }\n  context.pure = true;\n  const { push, newline } = context;\n  newline();\n  for (let i = 0; i < hoists.length; i++) {\n    const exp = hoists[i];\n    if (exp) {\n      push(`const _hoisted_${i + 1} = `);\n      genNode(exp, context);\n      newline();\n    }\n  }\n  context.pure = false;\n}\nfunction genImports(importsOptions, context) {\n  if (!importsOptions.length) {\n    return;\n  }\n  importsOptions.forEach((imports) => {\n    context.push(`import `);\n    genNode(imports.exp, context);\n    context.push(` from '${imports.path}'`);\n    context.newline();\n  });\n}\nfunction isText(n) {\n  return shared.isString(n) || n.type === 4 || n.type === 2 || n.type === 5 || n.type === 8;\n}\nfunction genNodeListAsArray(nodes, context) {\n  const multilines = nodes.length > 3 || nodes.some((n) => shared.isArray(n) || !isText(n));\n  context.push(`[`);\n  multilines && context.indent();\n  genNodeList(nodes, context, multilines);\n  multilines && context.deindent();\n  context.push(`]`);\n}\nfunction genNodeList(nodes, context, multilines = false, comma = true) {\n  const { push, newline } = context;\n  for (let i = 0; i < nodes.length; i++) {\n    const node = nodes[i];\n    if (shared.isString(node)) {\n      push(node, -3 /* Unknown */);\n    } else if (shared.isArray(node)) {\n      genNodeListAsArray(node, context);\n    } else {\n      genNode(node, context);\n    }\n    if (i < nodes.length - 1) {\n      if (multilines) {\n        comma && push(\",\");\n        newline();\n      } else {\n        comma && push(\", \");\n      }\n    }\n  }\n}\nfunction genNode(node, context) {\n  if (shared.isString(node)) {\n    context.push(node, -3 /* Unknown */);\n    return;\n  }\n  if (shared.isSymbol(node)) {\n    context.push(context.helper(node));\n    return;\n  }\n  switch (node.type) {\n    case 1:\n    case 9:\n    case 11:\n      genNode(node.codegenNode, context);\n      break;\n    case 2:\n      genText(node, context);\n      break;\n    case 4:\n      genExpression(node, context);\n      break;\n    case 5:\n      genInterpolation(node, context);\n      break;\n    case 12:\n      genNode(node.codegenNode, context);\n      break;\n    case 8:\n      genCompoundExpression(node, context);\n      break;\n    case 3:\n      genComment(node, context);\n      break;\n    case 13:\n      genVNodeCall(node, context);\n      break;\n    case 14:\n      genCallExpression(node, context);\n      break;\n    case 15:\n      genObjectExpression(node, context);\n      break;\n    case 17:\n      genArrayExpression(node, context);\n      break;\n    case 18:\n      genFunctionExpression(node, context);\n      break;\n    case 19:\n      genConditionalExpression(node, context);\n      break;\n    case 20:\n      genCacheExpression(node, context);\n      break;\n    case 21:\n      genNodeList(node.body, context, true, false);\n      break;\n    // SSR only types\n    case 22:\n      genTemplateLiteral(node, context);\n      break;\n    case 23:\n      genIfStatement(node, context);\n      break;\n    case 24:\n      genAssignmentExpression(node, context);\n      break;\n    case 25:\n      genSequenceExpression(node, context);\n      break;\n    case 26:\n      genReturnStatement(node, context);\n      break;\n  }\n}\nfunction genText(node, context) {\n  context.push(JSON.stringify(node.content), -3 /* Unknown */, node);\n}\nfunction genExpression(node, context) {\n  const { content, isStatic } = node;\n  context.push(\n    isStatic ? JSON.stringify(content) : content,\n    -3 /* Unknown */,\n    node\n  );\n}\nfunction genInterpolation(node, context) {\n  const { push, helper, pure } = context;\n  if (pure) push(PURE_ANNOTATION);\n  push(`${helper(TO_DISPLAY_STRING)}(`);\n  genNode(node.content, context);\n  push(`)`);\n}\nfunction genCompoundExpression(node, context) {\n  for (let i = 0; i < node.children.length; i++) {\n    const child = node.children[i];\n    if (shared.isString(child)) {\n      context.push(child, -3 /* Unknown */);\n    } else {\n      genNode(child, context);\n    }\n  }\n}\nfunction genExpressionAsPropertyKey(node, context) {\n  const { push } = context;\n  if (node.type === 8) {\n    push(`[`);\n    genCompoundExpression(node, context);\n    push(`]`);\n  } else if (node.isStatic) {\n    const text = isSimpleIdentifier(node.content) ? node.content : JSON.stringify(node.content);\n    push(text, -2 /* None */, node);\n  } else {\n    push(`[${node.content}]`, -3 /* Unknown */, node);\n  }\n}\nfunction genComment(node, context) {\n  const { push, helper, pure } = context;\n  if (pure) {\n    push(PURE_ANNOTATION);\n  }\n  push(\n    `${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`,\n    -3 /* Unknown */,\n    node\n  );\n}\nfunction genVNodeCall(node, context) {\n  const { push, helper, pure } = context;\n  const {\n    tag,\n    props,\n    children,\n    patchFlag,\n    dynamicProps,\n    directives,\n    isBlock,\n    disableTracking,\n    isComponent\n  } = node;\n  let patchFlagString;\n  if (patchFlag) {\n    {\n      patchFlagString = String(patchFlag);\n    }\n  }\n  if (directives) {\n    push(helper(WITH_DIRECTIVES) + `(`);\n  }\n  if (isBlock) {\n    push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);\n  }\n  if (pure) {\n    push(PURE_ANNOTATION);\n  }\n  const callHelper = isBlock ? getVNodeBlockHelper(context.inSSR, isComponent) : getVNodeHelper(context.inSSR, isComponent);\n  push(helper(callHelper) + `(`, -2 /* None */, node);\n  genNodeList(\n    genNullableArgs([tag, props, children, patchFlagString, dynamicProps]),\n    context\n  );\n  push(`)`);\n  if (isBlock) {\n    push(`)`);\n  }\n  if (directives) {\n    push(`, `);\n    genNode(directives, context);\n    push(`)`);\n  }\n}\nfunction genNullableArgs(args) {\n  let i = args.length;\n  while (i--) {\n    if (args[i] != null) break;\n  }\n  return args.slice(0, i + 1).map((arg) => arg || `null`);\n}\nfunction genCallExpression(node, context) {\n  const { push, helper, pure } = context;\n  const callee = shared.isString(node.callee) ? node.callee : helper(node.callee);\n  if (pure) {\n    push(PURE_ANNOTATION);\n  }\n  push(callee + `(`, -2 /* None */, node);\n  genNodeList(node.arguments, context);\n  push(`)`);\n}\nfunction genObjectExpression(node, context) {\n  const { push, indent, deindent, newline } = context;\n  const { properties } = node;\n  if (!properties.length) {\n    push(`{}`, -2 /* None */, node);\n    return;\n  }\n  const multilines = properties.length > 1 || properties.some((p) => p.value.type !== 4);\n  push(multilines ? `{` : `{ `);\n  multilines && indent();\n  for (let i = 0; i < properties.length; i++) {\n    const { key, value } = properties[i];\n    genExpressionAsPropertyKey(key, context);\n    push(`: `);\n    genNode(value, context);\n    if (i < properties.length - 1) {\n      push(`,`);\n      newline();\n    }\n  }\n  multilines && deindent();\n  push(multilines ? `}` : ` }`);\n}\nfunction genArrayExpression(node, context) {\n  genNodeListAsArray(node.elements, context);\n}\nfunction genFunctionExpression(node, context) {\n  const { push, indent, deindent } = context;\n  const { params, returns, body, newline, isSlot } = node;\n  if (isSlot) {\n    push(`_${helperNameMap[WITH_CTX]}(`);\n  }\n  push(`(`, -2 /* None */, node);\n  if (shared.isArray(params)) {\n    genNodeList(params, context);\n  } else if (params) {\n    genNode(params, context);\n  }\n  push(`) => `);\n  if (newline || body) {\n    push(`{`);\n    indent();\n  }\n  if (returns) {\n    if (newline) {\n      push(`return `);\n    }\n    if (shared.isArray(returns)) {\n      genNodeListAsArray(returns, context);\n    } else {\n      genNode(returns, context);\n    }\n  } else if (body) {\n    genNode(body, context);\n  }\n  if (newline || body) {\n    deindent();\n    push(`}`);\n  }\n  if (isSlot) {\n    if (node.isNonScopedSlot) {\n      push(`, undefined, true`);\n    }\n    push(`)`);\n  }\n}\nfunction genConditionalExpression(node, context) {\n  const { test, consequent, alternate, newline: needNewline } = node;\n  const { push, indent, deindent, newline } = context;\n  if (test.type === 4) {\n    const needsParens = !isSimpleIdentifier(test.content);\n    needsParens && push(`(`);\n    genExpression(test, context);\n    needsParens && push(`)`);\n  } else {\n    push(`(`);\n    genNode(test, context);\n    push(`)`);\n  }\n  needNewline && indent();\n  context.indentLevel++;\n  needNewline || push(` `);\n  push(`? `);\n  genNode(consequent, context);\n  context.indentLevel--;\n  needNewline && newline();\n  needNewline || push(` `);\n  push(`: `);\n  const isNested = alternate.type === 19;\n  if (!isNested) {\n    context.indentLevel++;\n  }\n  genNode(alternate, context);\n  if (!isNested) {\n    context.indentLevel--;\n  }\n  needNewline && deindent(\n    true\n    /* without newline */\n  );\n}\nfunction genCacheExpression(node, context) {\n  const { push, helper, indent, deindent, newline } = context;\n  const { needPauseTracking, needArraySpread } = node;\n  if (needArraySpread) {\n    push(`[...(`);\n  }\n  push(`_cache[${node.index}] || (`);\n  if (needPauseTracking) {\n    indent();\n    push(`${helper(SET_BLOCK_TRACKING)}(-1`);\n    if (node.inVOnce) push(`, true`);\n    push(`),`);\n    newline();\n    push(`(`);\n  }\n  push(`_cache[${node.index}] = `);\n  genNode(node.value, context);\n  if (needPauseTracking) {\n    push(`).cacheIndex = ${node.index},`);\n    newline();\n    push(`${helper(SET_BLOCK_TRACKING)}(1),`);\n    newline();\n    push(`_cache[${node.index}]`);\n    deindent();\n  }\n  push(`)`);\n  if (needArraySpread) {\n    push(`)]`);\n  }\n}\nfunction genTemplateLiteral(node, context) {\n  const { push, indent, deindent } = context;\n  push(\"`\");\n  const l = node.elements.length;\n  const multilines = l > 3;\n  for (let i = 0; i < l; i++) {\n    const e = node.elements[i];\n    if (shared.isString(e)) {\n      push(e.replace(/(`|\\$|\\\\)/g, \"\\\\$1\"), -3 /* Unknown */);\n    } else {\n      push(\"${\");\n      if (multilines) indent();\n      genNode(e, context);\n      if (multilines) deindent();\n      push(\"}\");\n    }\n  }\n  push(\"`\");\n}\nfunction genIfStatement(node, context) {\n  const { push, indent, deindent } = context;\n  const { test, consequent, alternate } = node;\n  push(`if (`);\n  genNode(test, context);\n  push(`) {`);\n  indent();\n  genNode(consequent, context);\n  deindent();\n  push(`}`);\n  if (alternate) {\n    push(` else `);\n    if (alternate.type === 23) {\n      genIfStatement(alternate, context);\n    } else {\n      push(`{`);\n      indent();\n      genNode(alternate, context);\n      deindent();\n      push(`}`);\n    }\n  }\n}\nfunction genAssignmentExpression(node, context) {\n  genNode(node.left, context);\n  context.push(` = `);\n  genNode(node.right, context);\n}\nfunction genSequenceExpression(node, context) {\n  context.push(`(`);\n  genNodeList(node.expressions, context);\n  context.push(`)`);\n}\nfunction genReturnStatement({ returns }, context) {\n  context.push(`return `);\n  if (shared.isArray(returns)) {\n    genNodeListAsArray(returns, context);\n  } else {\n    genNode(returns, context);\n  }\n}\n\nconst isLiteralWhitelisted = /* @__PURE__ */ shared.makeMap(\"true,false,null,this\");\nconst transformExpression = (node, context) => {\n  if (node.type === 5) {\n    node.content = processExpression(\n      node.content,\n      context\n    );\n  } else if (node.type === 1) {\n    const memo = findDir(node, \"memo\");\n    for (let i = 0; i < node.props.length; i++) {\n      const dir = node.props[i];\n      if (dir.type === 7 && dir.name !== \"for\") {\n        const exp = dir.exp;\n        const arg = dir.arg;\n        if (exp && exp.type === 4 && !(dir.name === \"on\" && arg) && // key has been processed in transformFor(vMemo + vFor)\n        !(memo && arg && arg.type === 4 && arg.content === \"key\")) {\n          dir.exp = processExpression(\n            exp,\n            context,\n            // slot args must be processed as function params\n            dir.name === \"slot\"\n          );\n        }\n        if (arg && arg.type === 4 && !arg.isStatic) {\n          dir.arg = processExpression(arg, context);\n        }\n      }\n    }\n  }\n};\nfunction processExpression(node, context, asParams = false, asRawStatements = false, localVars = Object.create(context.identifiers)) {\n  if (!context.prefixIdentifiers || !node.content.trim()) {\n    return node;\n  }\n  const { inline, bindingMetadata } = context;\n  const rewriteIdentifier = (raw, parent, id) => {\n    const type = shared.hasOwn(bindingMetadata, raw) && bindingMetadata[raw];\n    if (inline) {\n      const isAssignmentLVal = parent && parent.type === \"AssignmentExpression\" && parent.left === id;\n      const isUpdateArg = parent && parent.type === \"UpdateExpression\" && parent.argument === id;\n      const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack);\n      const isNewExpression = parent && isInNewExpression(parentStack);\n      const wrapWithUnref = (raw2) => {\n        const wrapped = `${context.helperString(UNREF)}(${raw2})`;\n        return isNewExpression ? `(${wrapped})` : wrapped;\n      };\n      if (isConst(type) || type === \"setup-reactive-const\" || localVars[raw]) {\n        return raw;\n      } else if (type === \"setup-ref\") {\n        return `${raw}.value`;\n      } else if (type === \"setup-maybe-ref\") {\n        return isAssignmentLVal || isUpdateArg || isDestructureAssignment ? `${raw}.value` : wrapWithUnref(raw);\n      } else if (type === \"setup-let\") {\n        if (isAssignmentLVal) {\n          const { right: rVal, operator } = parent;\n          const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1);\n          const rExpString = stringifyExpression(\n            processExpression(\n              createSimpleExpression(rExp, false),\n              context,\n              false,\n              false,\n              knownIds\n            )\n          );\n          return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${raw}.value ${operator} ${rExpString} : ${raw}`;\n        } else if (isUpdateArg) {\n          id.start = parent.start;\n          id.end = parent.end;\n          const { prefix: isPrefix, operator } = parent;\n          const prefix = isPrefix ? operator : ``;\n          const postfix = isPrefix ? `` : operator;\n          return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`;\n        } else if (isDestructureAssignment) {\n          return raw;\n        } else {\n          return wrapWithUnref(raw);\n        }\n      } else if (type === \"props\") {\n        return shared.genPropsAccessExp(raw);\n      } else if (type === \"props-aliased\") {\n        return shared.genPropsAccessExp(bindingMetadata.__propsAliases[raw]);\n      }\n    } else {\n      if (type && type.startsWith(\"setup\") || type === \"literal-const\") {\n        return `$setup.${raw}`;\n      } else if (type === \"props-aliased\") {\n        return `$props['${bindingMetadata.__propsAliases[raw]}']`;\n      } else if (type) {\n        return `$${type}.${raw}`;\n      }\n    }\n    return `_ctx.${raw}`;\n  };\n  const rawExp = node.content;\n  let ast = node.ast;\n  if (ast === false) {\n    return node;\n  }\n  if (ast === null || !ast && isSimpleIdentifier(rawExp)) {\n    const isScopeVarReference = context.identifiers[rawExp];\n    const isAllowedGlobal = shared.isGloballyAllowed(rawExp);\n    const isLiteral = isLiteralWhitelisted(rawExp);\n    if (!asParams && !isScopeVarReference && !isLiteral && (!isAllowedGlobal || bindingMetadata[rawExp])) {\n      if (isConst(bindingMetadata[rawExp])) {\n        node.constType = 1;\n      }\n      node.content = rewriteIdentifier(rawExp);\n    } else if (!isScopeVarReference) {\n      if (isLiteral) {\n        node.constType = 3;\n      } else {\n        node.constType = 2;\n      }\n    }\n    return node;\n  }\n  if (!ast) {\n    const source = asRawStatements ? ` ${rawExp} ` : `(${rawExp})${asParams ? `=>{}` : ``}`;\n    try {\n      ast = parser.parseExpression(source, {\n        sourceType: \"module\",\n        plugins: context.expressionPlugins\n      });\n    } catch (e) {\n      context.onError(\n        createCompilerError(\n          45,\n          node.loc,\n          void 0,\n          e.message\n        )\n      );\n      return node;\n    }\n  }\n  const ids = [];\n  const parentStack = [];\n  const knownIds = Object.create(context.identifiers);\n  walkIdentifiers(\n    ast,\n    (node2, parent, _, isReferenced, isLocal) => {\n      if (isStaticPropertyKey(node2, parent)) {\n        return;\n      }\n      if (node2.name.startsWith(\"_filter_\")) {\n        return;\n      }\n      const needPrefix = isReferenced && canPrefix(node2);\n      if (needPrefix && !isLocal) {\n        if (isStaticProperty(parent) && parent.shorthand) {\n          node2.prefix = `${node2.name}: `;\n        }\n        node2.name = rewriteIdentifier(node2.name, parent, node2);\n        ids.push(node2);\n      } else {\n        if (!(needPrefix && isLocal) && (!parent || parent.type !== \"CallExpression\" && parent.type !== \"NewExpression\" && parent.type !== \"MemberExpression\")) {\n          node2.isConstant = true;\n        }\n        ids.push(node2);\n      }\n    },\n    true,\n    // invoke on ALL identifiers\n    parentStack,\n    knownIds\n  );\n  const children = [];\n  ids.sort((a, b) => a.start - b.start);\n  ids.forEach((id, i) => {\n    const start = id.start - 1;\n    const end = id.end - 1;\n    const last = ids[i - 1];\n    const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);\n    if (leadingText.length || id.prefix) {\n      children.push(leadingText + (id.prefix || ``));\n    }\n    const source = rawExp.slice(start, end);\n    children.push(\n      createSimpleExpression(\n        id.name,\n        false,\n        {\n          start: advancePositionWithClone(node.loc.start, source, start),\n          end: advancePositionWithClone(node.loc.start, source, end),\n          source\n        },\n        id.isConstant ? 3 : 0\n      )\n    );\n    if (i === ids.length - 1 && end < rawExp.length) {\n      children.push(rawExp.slice(end));\n    }\n  });\n  let ret;\n  if (children.length) {\n    ret = createCompoundExpression(children, node.loc);\n    ret.ast = ast;\n  } else {\n    ret = node;\n    ret.constType = 3;\n  }\n  ret.identifiers = Object.keys(knownIds);\n  return ret;\n}\nfunction canPrefix(id) {\n  if (shared.isGloballyAllowed(id.name)) {\n    return false;\n  }\n  if (id.name === \"require\") {\n    return false;\n  }\n  return true;\n}\nfunction stringifyExpression(exp) {\n  if (shared.isString(exp)) {\n    return exp;\n  } else if (exp.type === 4) {\n    return exp.content;\n  } else {\n    return exp.children.map(stringifyExpression).join(\"\");\n  }\n}\nfunction isConst(type) {\n  return type === \"setup-const\" || type === \"literal-const\";\n}\n\nconst transformIf = createStructuralDirectiveTransform(\n  /^(if|else|else-if)$/,\n  (node, dir, context) => {\n    return processIf(node, dir, context, (ifNode, branch, isRoot) => {\n      const siblings = context.parent.children;\n      let i = siblings.indexOf(ifNode);\n      let key = 0;\n      while (i-- >= 0) {\n        const sibling = siblings[i];\n        if (sibling && sibling.type === 9) {\n          key += sibling.branches.length;\n        }\n      }\n      return () => {\n        if (isRoot) {\n          ifNode.codegenNode = createCodegenNodeForBranch(\n            branch,\n            key,\n            context\n          );\n        } else {\n          const parentCondition = getParentCondition(ifNode.codegenNode);\n          parentCondition.alternate = createCodegenNodeForBranch(\n            branch,\n            key + ifNode.branches.length - 1,\n            context\n          );\n        }\n      };\n    });\n  }\n);\nfunction processIf(node, dir, context, processCodegen) {\n  if (dir.name !== \"else\" && (!dir.exp || !dir.exp.content.trim())) {\n    const loc = dir.exp ? dir.exp.loc : node.loc;\n    context.onError(\n      createCompilerError(28, dir.loc)\n    );\n    dir.exp = createSimpleExpression(`true`, false, loc);\n  }\n  if (context.prefixIdentifiers && dir.exp) {\n    dir.exp = processExpression(dir.exp, context);\n  }\n  if (dir.name === \"if\") {\n    const branch = createIfBranch(node, dir);\n    const ifNode = {\n      type: 9,\n      loc: cloneLoc(node.loc),\n      branches: [branch]\n    };\n    context.replaceNode(ifNode);\n    if (processCodegen) {\n      return processCodegen(ifNode, branch, true);\n    }\n  } else {\n    const siblings = context.parent.children;\n    let i = siblings.indexOf(node);\n    while (i-- >= -1) {\n      const sibling = siblings[i];\n      if (sibling && sibling.type === 3) {\n        context.removeNode(sibling);\n        continue;\n      }\n      if (sibling && sibling.type === 2 && !sibling.content.trim().length) {\n        context.removeNode(sibling);\n        continue;\n      }\n      if (sibling && sibling.type === 9) {\n        if (dir.name === \"else-if\" && sibling.branches[sibling.branches.length - 1].condition === void 0) {\n          context.onError(\n            createCompilerError(30, node.loc)\n          );\n        }\n        context.removeNode();\n        const branch = createIfBranch(node, dir);\n        {\n          const key = branch.userKey;\n          if (key) {\n            sibling.branches.forEach(({ userKey }) => {\n              if (isSameKey(userKey, key)) {\n                context.onError(\n                  createCompilerError(\n                    29,\n                    branch.userKey.loc\n                  )\n                );\n              }\n            });\n          }\n        }\n        sibling.branches.push(branch);\n        const onExit = processCodegen && processCodegen(sibling, branch, false);\n        traverseNode(branch, context);\n        if (onExit) onExit();\n        context.currentNode = null;\n      } else {\n        context.onError(\n          createCompilerError(30, node.loc)\n        );\n      }\n      break;\n    }\n  }\n}\nfunction createIfBranch(node, dir) {\n  const isTemplateIf = node.tagType === 3;\n  return {\n    type: 10,\n    loc: node.loc,\n    condition: dir.name === \"else\" ? void 0 : dir.exp,\n    children: isTemplateIf && !findDir(node, \"for\") ? node.children : [node],\n    userKey: findProp(node, `key`),\n    isTemplateIf\n  };\n}\nfunction createCodegenNodeForBranch(branch, keyIndex, context) {\n  if (branch.condition) {\n    return createConditionalExpression(\n      branch.condition,\n      createChildrenCodegenNode(branch, keyIndex, context),\n      // make sure to pass in asBlock: true so that the comment node call\n      // closes the current block.\n      createCallExpression(context.helper(CREATE_COMMENT), [\n        '\"\"',\n        \"true\"\n      ])\n    );\n  } else {\n    return createChildrenCodegenNode(branch, keyIndex, context);\n  }\n}\nfunction createChildrenCodegenNode(branch, keyIndex, context) {\n  const { helper } = context;\n  const keyProperty = createObjectProperty(\n    `key`,\n    createSimpleExpression(\n      `${keyIndex}`,\n      false,\n      locStub,\n      2\n    )\n  );\n  const { children } = branch;\n  const firstChild = children[0];\n  const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1;\n  if (needFragmentWrapper) {\n    if (children.length === 1 && firstChild.type === 11) {\n      const vnodeCall = firstChild.codegenNode;\n      injectProp(vnodeCall, keyProperty, context);\n      return vnodeCall;\n    } else {\n      let patchFlag = 64;\n      return createVNodeCall(\n        context,\n        helper(FRAGMENT),\n        createObjectExpression([keyProperty]),\n        children,\n        patchFlag,\n        void 0,\n        void 0,\n        true,\n        false,\n        false,\n        branch.loc\n      );\n    }\n  } else {\n    const ret = firstChild.codegenNode;\n    const vnodeCall = getMemoedVNodeCall(ret);\n    if (vnodeCall.type === 13) {\n      convertToBlock(vnodeCall, context);\n    }\n    injectProp(vnodeCall, keyProperty, context);\n    return ret;\n  }\n}\nfunction isSameKey(a, b) {\n  if (!a || a.type !== b.type) {\n    return false;\n  }\n  if (a.type === 6) {\n    if (a.value.content !== b.value.content) {\n      return false;\n    }\n  } else {\n    const exp = a.exp;\n    const branchExp = b.exp;\n    if (exp.type !== branchExp.type) {\n      return false;\n    }\n    if (exp.type !== 4 || exp.isStatic !== branchExp.isStatic || exp.content !== branchExp.content) {\n      return false;\n    }\n  }\n  return true;\n}\nfunction getParentCondition(node) {\n  while (true) {\n    if (node.type === 19) {\n      if (node.alternate.type === 19) {\n        node = node.alternate;\n      } else {\n        return node;\n      }\n    } else if (node.type === 20) {\n      node = node.value;\n    }\n  }\n}\n\nconst transformBind = (dir, _node, context) => {\n  const { modifiers, loc } = dir;\n  const arg = dir.arg;\n  let { exp } = dir;\n  if (exp && exp.type === 4 && !exp.content.trim()) {\n    {\n      context.onError(\n        createCompilerError(34, loc)\n      );\n      return {\n        props: [\n          createObjectProperty(arg, createSimpleExpression(\"\", true, loc))\n        ]\n      };\n    }\n  }\n  if (!exp) {\n    if (arg.type !== 4 || !arg.isStatic) {\n      context.onError(\n        createCompilerError(\n          52,\n          arg.loc\n        )\n      );\n      return {\n        props: [\n          createObjectProperty(arg, createSimpleExpression(\"\", true, loc))\n        ]\n      };\n    }\n    transformBindShorthand(dir, context);\n    exp = dir.exp;\n  }\n  if (arg.type !== 4) {\n    arg.children.unshift(`(`);\n    arg.children.push(`) || \"\"`);\n  } else if (!arg.isStatic) {\n    arg.content = arg.content ? `${arg.content} || \"\"` : `\"\"`;\n  }\n  if (modifiers.some((mod) => mod.content === \"camel\")) {\n    if (arg.type === 4) {\n      if (arg.isStatic) {\n        arg.content = shared.camelize(arg.content);\n      } else {\n        arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;\n      }\n    } else {\n      arg.children.unshift(`${context.helperString(CAMELIZE)}(`);\n      arg.children.push(`)`);\n    }\n  }\n  if (!context.inSSR) {\n    if (modifiers.some((mod) => mod.content === \"prop\")) {\n      injectPrefix(arg, \".\");\n    }\n    if (modifiers.some((mod) => mod.content === \"attr\")) {\n      injectPrefix(arg, \"^\");\n    }\n  }\n  return {\n    props: [createObjectProperty(arg, exp)]\n  };\n};\nconst transformBindShorthand = (dir, context) => {\n  const arg = dir.arg;\n  const propName = shared.camelize(arg.content);\n  dir.exp = createSimpleExpression(propName, false, arg.loc);\n  {\n    dir.exp = processExpression(dir.exp, context);\n  }\n};\nconst injectPrefix = (arg, prefix) => {\n  if (arg.type === 4) {\n    if (arg.isStatic) {\n      arg.content = prefix + arg.content;\n    } else {\n      arg.content = `\\`${prefix}\\${${arg.content}}\\``;\n    }\n  } else {\n    arg.children.unshift(`'${prefix}' + (`);\n    arg.children.push(`)`);\n  }\n};\n\nconst transformFor = createStructuralDirectiveTransform(\n  \"for\",\n  (node, dir, context) => {\n    const { helper, removeHelper } = context;\n    return processFor(node, dir, context, (forNode) => {\n      const renderExp = createCallExpression(helper(RENDER_LIST), [\n        forNode.source\n      ]);\n      const isTemplate = isTemplateNode(node);\n      const memo = findDir(node, \"memo\");\n      const keyProp = findProp(node, `key`, false, true);\n      const isDirKey = keyProp && keyProp.type === 7;\n      if (isDirKey && !keyProp.exp) {\n        transformBindShorthand(keyProp, context);\n      }\n      let keyExp = keyProp && (keyProp.type === 6 ? keyProp.value ? createSimpleExpression(keyProp.value.content, true) : void 0 : keyProp.exp);\n      if (memo && keyExp && isDirKey) {\n        {\n          keyProp.exp = keyExp = processExpression(\n            keyExp,\n            context\n          );\n        }\n      }\n      const keyProperty = keyProp && keyExp ? createObjectProperty(`key`, keyExp) : null;\n      if (isTemplate) {\n        if (memo) {\n          memo.exp = processExpression(\n            memo.exp,\n            context\n          );\n        }\n        if (keyProperty && keyProp.type !== 6) {\n          keyProperty.value = processExpression(\n            keyProperty.value,\n            context\n          );\n        }\n      }\n      const isStableFragment = forNode.source.type === 4 && forNode.source.constType > 0;\n      const fragmentFlag = isStableFragment ? 64 : keyProp ? 128 : 256;\n      forNode.codegenNode = createVNodeCall(\n        context,\n        helper(FRAGMENT),\n        void 0,\n        renderExp,\n        fragmentFlag,\n        void 0,\n        void 0,\n        true,\n        !isStableFragment,\n        false,\n        node.loc\n      );\n      return () => {\n        let childBlock;\n        const { children } = forNode;\n        if (isTemplate) {\n          node.children.some((c) => {\n            if (c.type === 1) {\n              const key = findProp(c, \"key\");\n              if (key) {\n                context.onError(\n                  createCompilerError(\n                    33,\n                    key.loc\n                  )\n                );\n                return true;\n              }\n            }\n          });\n        }\n        const needFragmentWrapper = children.length !== 1 || children[0].type !== 1;\n        const slotOutlet = isSlotOutlet(node) ? node : isTemplate && node.children.length === 1 && isSlotOutlet(node.children[0]) ? node.children[0] : null;\n        if (slotOutlet) {\n          childBlock = slotOutlet.codegenNode;\n          if (isTemplate && keyProperty) {\n            injectProp(childBlock, keyProperty, context);\n          }\n        } else if (needFragmentWrapper) {\n          childBlock = createVNodeCall(\n            context,\n            helper(FRAGMENT),\n            keyProperty ? createObjectExpression([keyProperty]) : void 0,\n            node.children,\n            64,\n            void 0,\n            void 0,\n            true,\n            void 0,\n            false\n          );\n        } else {\n          childBlock = children[0].codegenNode;\n          if (isTemplate && keyProperty) {\n            injectProp(childBlock, keyProperty, context);\n          }\n          if (childBlock.isBlock !== !isStableFragment) {\n            if (childBlock.isBlock) {\n              removeHelper(OPEN_BLOCK);\n              removeHelper(\n                getVNodeBlockHelper(context.inSSR, childBlock.isComponent)\n              );\n            } else {\n              removeHelper(\n                getVNodeHelper(context.inSSR, childBlock.isComponent)\n              );\n            }\n          }\n          childBlock.isBlock = !isStableFragment;\n          if (childBlock.isBlock) {\n            helper(OPEN_BLOCK);\n            helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));\n          } else {\n            helper(getVNodeHelper(context.inSSR, childBlock.isComponent));\n          }\n        }\n        if (memo) {\n          const loop = createFunctionExpression(\n            createForLoopParams(forNode.parseResult, [\n              createSimpleExpression(`_cached`)\n            ])\n          );\n          loop.body = createBlockStatement([\n            createCompoundExpression([`const _memo = (`, memo.exp, `)`]),\n            createCompoundExpression([\n              `if (_cached`,\n              ...keyExp ? [` && _cached.key === `, keyExp] : [],\n              ` && ${context.helperString(\n                IS_MEMO_SAME\n              )}(_cached, _memo)) return _cached`\n            ]),\n            createCompoundExpression([`const _item = `, childBlock]),\n            createSimpleExpression(`_item.memo = _memo`),\n            createSimpleExpression(`return _item`)\n          ]);\n          renderExp.arguments.push(\n            loop,\n            createSimpleExpression(`_cache`),\n            createSimpleExpression(String(context.cached.length))\n          );\n          context.cached.push(null);\n        } else {\n          renderExp.arguments.push(\n            createFunctionExpression(\n              createForLoopParams(forNode.parseResult),\n              childBlock,\n              true\n            )\n          );\n        }\n      };\n    });\n  }\n);\nfunction processFor(node, dir, context, processCodegen) {\n  if (!dir.exp) {\n    context.onError(\n      createCompilerError(31, dir.loc)\n    );\n    return;\n  }\n  const parseResult = dir.forParseResult;\n  if (!parseResult) {\n    context.onError(\n      createCompilerError(32, dir.loc)\n    );\n    return;\n  }\n  finalizeForParseResult(parseResult, context);\n  const { addIdentifiers, removeIdentifiers, scopes } = context;\n  const { source, value, key, index } = parseResult;\n  const forNode = {\n    type: 11,\n    loc: dir.loc,\n    source,\n    valueAlias: value,\n    keyAlias: key,\n    objectIndexAlias: index,\n    parseResult,\n    children: isTemplateNode(node) ? node.children : [node]\n  };\n  context.replaceNode(forNode);\n  scopes.vFor++;\n  if (context.prefixIdentifiers) {\n    value && addIdentifiers(value);\n    key && addIdentifiers(key);\n    index && addIdentifiers(index);\n  }\n  const onExit = processCodegen && processCodegen(forNode);\n  return () => {\n    scopes.vFor--;\n    if (context.prefixIdentifiers) {\n      value && removeIdentifiers(value);\n      key && removeIdentifiers(key);\n      index && removeIdentifiers(index);\n    }\n    if (onExit) onExit();\n  };\n}\nfunction finalizeForParseResult(result, context) {\n  if (result.finalized) return;\n  if (context.prefixIdentifiers) {\n    result.source = processExpression(\n      result.source,\n      context\n    );\n    if (result.key) {\n      result.key = processExpression(\n        result.key,\n        context,\n        true\n      );\n    }\n    if (result.index) {\n      result.index = processExpression(\n        result.index,\n        context,\n        true\n      );\n    }\n    if (result.value) {\n      result.value = processExpression(\n        result.value,\n        context,\n        true\n      );\n    }\n  }\n  result.finalized = true;\n}\nfunction createForLoopParams({ value, key, index }, memoArgs = []) {\n  return createParamsList([value, key, index, ...memoArgs]);\n}\nfunction createParamsList(args) {\n  let i = args.length;\n  while (i--) {\n    if (args[i]) break;\n  }\n  return args.slice(0, i + 1).map((arg, i2) => arg || createSimpleExpression(`_`.repeat(i2 + 1), false));\n}\n\nconst defaultFallback = createSimpleExpression(`undefined`, false);\nconst trackSlotScopes = (node, context) => {\n  if (node.type === 1 && (node.tagType === 1 || node.tagType === 3)) {\n    const vSlot = findDir(node, \"slot\");\n    if (vSlot) {\n      const slotProps = vSlot.exp;\n      if (context.prefixIdentifiers) {\n        slotProps && context.addIdentifiers(slotProps);\n      }\n      context.scopes.vSlot++;\n      return () => {\n        if (context.prefixIdentifiers) {\n          slotProps && context.removeIdentifiers(slotProps);\n        }\n        context.scopes.vSlot--;\n      };\n    }\n  }\n};\nconst trackVForSlotScopes = (node, context) => {\n  let vFor;\n  if (isTemplateNode(node) && node.props.some(isVSlot) && (vFor = findDir(node, \"for\"))) {\n    const result = vFor.forParseResult;\n    if (result) {\n      finalizeForParseResult(result, context);\n      const { value, key, index } = result;\n      const { addIdentifiers, removeIdentifiers } = context;\n      value && addIdentifiers(value);\n      key && addIdentifiers(key);\n      index && addIdentifiers(index);\n      return () => {\n        value && removeIdentifiers(value);\n        key && removeIdentifiers(key);\n        index && removeIdentifiers(index);\n      };\n    }\n  }\n};\nconst buildClientSlotFn = (props, _vForExp, children, loc) => createFunctionExpression(\n  props,\n  children,\n  false,\n  true,\n  children.length ? children[0].loc : loc\n);\nfunction buildSlots(node, context, buildSlotFn = buildClientSlotFn) {\n  context.helper(WITH_CTX);\n  const { children, loc } = node;\n  const slotsProperties = [];\n  const dynamicSlots = [];\n  let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;\n  if (!context.ssr && context.prefixIdentifiers) {\n    hasDynamicSlots = hasScopeRef(node, context.identifiers);\n  }\n  const onComponentSlot = findDir(node, \"slot\", true);\n  if (onComponentSlot) {\n    const { arg, exp } = onComponentSlot;\n    if (arg && !isStaticExp(arg)) {\n      hasDynamicSlots = true;\n    }\n    slotsProperties.push(\n      createObjectProperty(\n        arg || createSimpleExpression(\"default\", true),\n        buildSlotFn(exp, void 0, children, loc)\n      )\n    );\n  }\n  let hasTemplateSlots = false;\n  let hasNamedDefaultSlot = false;\n  const implicitDefaultChildren = [];\n  const seenSlotNames = /* @__PURE__ */ new Set();\n  let conditionalBranchIndex = 0;\n  for (let i = 0; i < children.length; i++) {\n    const slotElement = children[i];\n    let slotDir;\n    if (!isTemplateNode(slotElement) || !(slotDir = findDir(slotElement, \"slot\", true))) {\n      if (slotElement.type !== 3) {\n        implicitDefaultChildren.push(slotElement);\n      }\n      continue;\n    }\n    if (onComponentSlot) {\n      context.onError(\n        createCompilerError(37, slotDir.loc)\n      );\n      break;\n    }\n    hasTemplateSlots = true;\n    const { children: slotChildren, loc: slotLoc } = slotElement;\n    const {\n      arg: slotName = createSimpleExpression(`default`, true),\n      exp: slotProps,\n      loc: dirLoc\n    } = slotDir;\n    let staticSlotName;\n    if (isStaticExp(slotName)) {\n      staticSlotName = slotName ? slotName.content : `default`;\n    } else {\n      hasDynamicSlots = true;\n    }\n    const vFor = findDir(slotElement, \"for\");\n    const slotFunction = buildSlotFn(slotProps, vFor, slotChildren, slotLoc);\n    let vIf;\n    let vElse;\n    if (vIf = findDir(slotElement, \"if\")) {\n      hasDynamicSlots = true;\n      dynamicSlots.push(\n        createConditionalExpression(\n          vIf.exp,\n          buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++),\n          defaultFallback\n        )\n      );\n    } else if (vElse = findDir(\n      slotElement,\n      /^else(-if)?$/,\n      true\n      /* allowEmpty */\n    )) {\n      let j = i;\n      let prev;\n      while (j--) {\n        prev = children[j];\n        if (prev.type !== 3 && isNonWhitespaceContent(prev)) {\n          break;\n        }\n      }\n      if (prev && isTemplateNode(prev) && findDir(prev, /^(else-)?if$/)) {\n        let conditional = dynamicSlots[dynamicSlots.length - 1];\n        while (conditional.alternate.type === 19) {\n          conditional = conditional.alternate;\n        }\n        conditional.alternate = vElse.exp ? createConditionalExpression(\n          vElse.exp,\n          buildDynamicSlot(\n            slotName,\n            slotFunction,\n            conditionalBranchIndex++\n          ),\n          defaultFallback\n        ) : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);\n      } else {\n        context.onError(\n          createCompilerError(30, vElse.loc)\n        );\n      }\n    } else if (vFor) {\n      hasDynamicSlots = true;\n      const parseResult = vFor.forParseResult;\n      if (parseResult) {\n        finalizeForParseResult(parseResult, context);\n        dynamicSlots.push(\n          createCallExpression(context.helper(RENDER_LIST), [\n            parseResult.source,\n            createFunctionExpression(\n              createForLoopParams(parseResult),\n              buildDynamicSlot(slotName, slotFunction),\n              true\n            )\n          ])\n        );\n      } else {\n        context.onError(\n          createCompilerError(\n            32,\n            vFor.loc\n          )\n        );\n      }\n    } else {\n      if (staticSlotName) {\n        if (seenSlotNames.has(staticSlotName)) {\n          context.onError(\n            createCompilerError(\n              38,\n              dirLoc\n            )\n          );\n          continue;\n        }\n        seenSlotNames.add(staticSlotName);\n        if (staticSlotName === \"default\") {\n          hasNamedDefaultSlot = true;\n        }\n      }\n      slotsProperties.push(createObjectProperty(slotName, slotFunction));\n    }\n  }\n  if (!onComponentSlot) {\n    const buildDefaultSlotProperty = (props, children2) => {\n      const fn = buildSlotFn(props, void 0, children2, loc);\n      if (context.compatConfig) {\n        fn.isNonScopedSlot = true;\n      }\n      return createObjectProperty(`default`, fn);\n    };\n    if (!hasTemplateSlots) {\n      slotsProperties.push(buildDefaultSlotProperty(void 0, children));\n    } else if (implicitDefaultChildren.length && // #3766\n    // with whitespace: 'preserve', whitespaces between slots will end up in\n    // implicitDefaultChildren. Ignore if all implicit children are whitespaces.\n    implicitDefaultChildren.some((node2) => isNonWhitespaceContent(node2))) {\n      if (hasNamedDefaultSlot) {\n        context.onError(\n          createCompilerError(\n            39,\n            implicitDefaultChildren[0].loc\n          )\n        );\n      } else {\n        slotsProperties.push(\n          buildDefaultSlotProperty(void 0, implicitDefaultChildren)\n        );\n      }\n    }\n  }\n  const slotFlag = hasDynamicSlots ? 2 : hasForwardedSlots(node.children) ? 3 : 1;\n  let slots = createObjectExpression(\n    slotsProperties.concat(\n      createObjectProperty(\n        `_`,\n        // 2 = compiled but dynamic = can skip normalization, but must run diff\n        // 1 = compiled and static = can skip normalization AND diff as optimized\n        createSimpleExpression(\n          slotFlag + (``),\n          false\n        )\n      )\n    ),\n    loc\n  );\n  if (dynamicSlots.length) {\n    slots = createCallExpression(context.helper(CREATE_SLOTS), [\n      slots,\n      createArrayExpression(dynamicSlots)\n    ]);\n  }\n  return {\n    slots,\n    hasDynamicSlots\n  };\n}\nfunction buildDynamicSlot(name, fn, index) {\n  const props = [\n    createObjectProperty(`name`, name),\n    createObjectProperty(`fn`, fn)\n  ];\n  if (index != null) {\n    props.push(\n      createObjectProperty(`key`, createSimpleExpression(String(index), true))\n    );\n  }\n  return createObjectExpression(props);\n}\nfunction hasForwardedSlots(children) {\n  for (let i = 0; i < children.length; i++) {\n    const child = children[i];\n    switch (child.type) {\n      case 1:\n        if (child.tagType === 2 || hasForwardedSlots(child.children)) {\n          return true;\n        }\n        break;\n      case 9:\n        if (hasForwardedSlots(child.branches)) return true;\n        break;\n      case 10:\n      case 11:\n        if (hasForwardedSlots(child.children)) return true;\n        break;\n    }\n  }\n  return false;\n}\nfunction isNonWhitespaceContent(node) {\n  if (node.type !== 2 && node.type !== 12)\n    return true;\n  return node.type === 2 ? !!node.content.trim() : isNonWhitespaceContent(node.content);\n}\n\nconst directiveImportMap = /* @__PURE__ */ new WeakMap();\nconst transformElement = (node, context) => {\n  return function postTransformElement() {\n    node = context.currentNode;\n    if (!(node.type === 1 && (node.tagType === 0 || node.tagType === 1))) {\n      return;\n    }\n    const { tag, props } = node;\n    const isComponent = node.tagType === 1;\n    let vnodeTag = isComponent ? resolveComponentType(node, context) : `\"${tag}\"`;\n    const isDynamicComponent = shared.isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;\n    let vnodeProps;\n    let vnodeChildren;\n    let patchFlag = 0;\n    let vnodeDynamicProps;\n    let dynamicPropNames;\n    let vnodeDirectives;\n    let shouldUseBlock = (\n      // dynamic component may resolve to plain elements\n      isDynamicComponent || vnodeTag === TELEPORT || vnodeTag === SUSPENSE || !isComponent && // <svg> and <foreignObject> must be forced into blocks so that block\n      // updates inside get proper isSVG flag at runtime. (#639, #643)\n      // This is technically web-specific, but splitting the logic out of core\n      // leads to too much unnecessary complexity.\n      (tag === \"svg\" || tag === \"foreignObject\" || tag === \"math\")\n    );\n    if (props.length > 0) {\n      const propsBuildResult = buildProps(\n        node,\n        context,\n        void 0,\n        isComponent,\n        isDynamicComponent\n      );\n      vnodeProps = propsBuildResult.props;\n      patchFlag = propsBuildResult.patchFlag;\n      dynamicPropNames = propsBuildResult.dynamicPropNames;\n      const directives = propsBuildResult.directives;\n      vnodeDirectives = directives && directives.length ? createArrayExpression(\n        directives.map((dir) => buildDirectiveArgs(dir, context))\n      ) : void 0;\n      if (propsBuildResult.shouldUseBlock) {\n        shouldUseBlock = true;\n      }\n    }\n    if (node.children.length > 0) {\n      if (vnodeTag === KEEP_ALIVE) {\n        shouldUseBlock = true;\n        patchFlag |= 1024;\n      }\n      const shouldBuildAsSlots = isComponent && // Teleport is not a real component and has dedicated runtime handling\n      vnodeTag !== TELEPORT && // explained above.\n      vnodeTag !== KEEP_ALIVE;\n      if (shouldBuildAsSlots) {\n        const { slots, hasDynamicSlots } = buildSlots(node, context);\n        vnodeChildren = slots;\n        if (hasDynamicSlots) {\n          patchFlag |= 1024;\n        }\n      } else if (node.children.length === 1 && vnodeTag !== TELEPORT) {\n        const child = node.children[0];\n        const type = child.type;\n        const hasDynamicTextChild = type === 5 || type === 8;\n        if (hasDynamicTextChild && getConstantType(child, context) === 0) {\n          patchFlag |= 1;\n        }\n        if (hasDynamicTextChild || type === 2) {\n          vnodeChildren = child;\n        } else {\n          vnodeChildren = node.children;\n        }\n      } else {\n        vnodeChildren = node.children;\n      }\n    }\n    if (dynamicPropNames && dynamicPropNames.length) {\n      vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);\n    }\n    node.codegenNode = createVNodeCall(\n      context,\n      vnodeTag,\n      vnodeProps,\n      vnodeChildren,\n      patchFlag === 0 ? void 0 : patchFlag,\n      vnodeDynamicProps,\n      vnodeDirectives,\n      !!shouldUseBlock,\n      false,\n      isComponent,\n      node.loc\n    );\n  };\n};\nfunction resolveComponentType(node, context, ssr = false) {\n  let { tag } = node;\n  const isExplicitDynamic = isComponentTag(tag);\n  const isProp = findProp(\n    node,\n    \"is\",\n    false,\n    true\n    /* allow empty */\n  );\n  if (isProp) {\n    if (isExplicitDynamic || isCompatEnabled(\n      \"COMPILER_IS_ON_ELEMENT\",\n      context\n    )) {\n      let exp;\n      if (isProp.type === 6) {\n        exp = isProp.value && createSimpleExpression(isProp.value.content, true);\n      } else {\n        exp = isProp.exp;\n        if (!exp) {\n          exp = createSimpleExpression(`is`, false, isProp.arg.loc);\n          {\n            exp = isProp.exp = processExpression(exp, context);\n          }\n        }\n      }\n      if (exp) {\n        return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [\n          exp\n        ]);\n      }\n    } else if (isProp.type === 6 && isProp.value.content.startsWith(\"vue:\")) {\n      tag = isProp.value.content.slice(4);\n    }\n  }\n  const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);\n  if (builtIn) {\n    if (!ssr) context.helper(builtIn);\n    return builtIn;\n  }\n  {\n    const fromSetup = resolveSetupReference(tag, context);\n    if (fromSetup) {\n      return fromSetup;\n    }\n    const dotIndex = tag.indexOf(\".\");\n    if (dotIndex > 0) {\n      const ns = resolveSetupReference(tag.slice(0, dotIndex), context);\n      if (ns) {\n        return ns + tag.slice(dotIndex);\n      }\n    }\n  }\n  if (context.selfName && shared.capitalize(shared.camelize(tag)) === context.selfName) {\n    context.helper(RESOLVE_COMPONENT);\n    context.components.add(tag + `__self`);\n    return toValidAssetId(tag, `component`);\n  }\n  context.helper(RESOLVE_COMPONENT);\n  context.components.add(tag);\n  return toValidAssetId(tag, `component`);\n}\nfunction resolveSetupReference(name, context) {\n  const bindings = context.bindingMetadata;\n  if (!bindings || bindings.__isScriptSetup === false) {\n    return;\n  }\n  const camelName = shared.camelize(name);\n  const PascalName = shared.capitalize(camelName);\n  const checkType = (type) => {\n    if (bindings[name] === type) {\n      return name;\n    }\n    if (bindings[camelName] === type) {\n      return camelName;\n    }\n    if (bindings[PascalName] === type) {\n      return PascalName;\n    }\n  };\n  const fromConst = checkType(\"setup-const\") || checkType(\"setup-reactive-const\") || checkType(\"literal-const\");\n  if (fromConst) {\n    return context.inline ? (\n      // in inline mode, const setup bindings (e.g. imports) can be used as-is\n      fromConst\n    ) : `$setup[${JSON.stringify(fromConst)}]`;\n  }\n  const fromMaybeRef = checkType(\"setup-let\") || checkType(\"setup-ref\") || checkType(\"setup-maybe-ref\");\n  if (fromMaybeRef) {\n    return context.inline ? (\n      // setup scope bindings that may be refs need to be unrefed\n      `${context.helperString(UNREF)}(${fromMaybeRef})`\n    ) : `$setup[${JSON.stringify(fromMaybeRef)}]`;\n  }\n  const fromProps = checkType(\"props\");\n  if (fromProps) {\n    return `${context.helperString(UNREF)}(${context.inline ? \"__props\" : \"$props\"}[${JSON.stringify(fromProps)}])`;\n  }\n}\nfunction buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {\n  const { tag, loc: elementLoc, children } = node;\n  let properties = [];\n  const mergeArgs = [];\n  const runtimeDirectives = [];\n  const hasChildren = children.length > 0;\n  let shouldUseBlock = false;\n  let patchFlag = 0;\n  let hasRef = false;\n  let hasClassBinding = false;\n  let hasStyleBinding = false;\n  let hasHydrationEventBinding = false;\n  let hasDynamicKeys = false;\n  let hasVnodeHook = false;\n  const dynamicPropNames = [];\n  const pushMergeArg = (arg) => {\n    if (properties.length) {\n      mergeArgs.push(\n        createObjectExpression(dedupeProperties(properties), elementLoc)\n      );\n      properties = [];\n    }\n    if (arg) mergeArgs.push(arg);\n  };\n  const pushRefVForMarker = () => {\n    if (context.scopes.vFor > 0) {\n      properties.push(\n        createObjectProperty(\n          createSimpleExpression(\"ref_for\", true),\n          createSimpleExpression(\"true\")\n        )\n      );\n    }\n  };\n  const analyzePatchFlag = ({ key, value }) => {\n    if (isStaticExp(key)) {\n      const name = key.content;\n      const isEventHandler = shared.isOn(name);\n      if (isEventHandler && (!isComponent || isDynamicComponent) && // omit the flag for click handlers because hydration gives click\n      // dedicated fast path.\n      name.toLowerCase() !== \"onclick\" && // omit v-model handlers\n      name !== \"onUpdate:modelValue\" && // omit onVnodeXXX hooks\n      !shared.isReservedProp(name)) {\n        hasHydrationEventBinding = true;\n      }\n      if (isEventHandler && shared.isReservedProp(name)) {\n        hasVnodeHook = true;\n      }\n      if (isEventHandler && value.type === 14) {\n        value = value.arguments[0];\n      }\n      if (value.type === 20 || (value.type === 4 || value.type === 8) && getConstantType(value, context) > 0) {\n        return;\n      }\n      if (name === \"ref\") {\n        hasRef = true;\n      } else if (name === \"class\") {\n        hasClassBinding = true;\n      } else if (name === \"style\") {\n        hasStyleBinding = true;\n      } else if (name !== \"key\" && !dynamicPropNames.includes(name)) {\n        dynamicPropNames.push(name);\n      }\n      if (isComponent && (name === \"class\" || name === \"style\") && !dynamicPropNames.includes(name)) {\n        dynamicPropNames.push(name);\n      }\n    } else {\n      hasDynamicKeys = true;\n    }\n  };\n  for (let i = 0; i < props.length; i++) {\n    const prop = props[i];\n    if (prop.type === 6) {\n      const { loc, name, nameLoc, value } = prop;\n      let isStatic = true;\n      if (name === \"ref\") {\n        hasRef = true;\n        pushRefVForMarker();\n        if (value && context.inline) {\n          const binding = context.bindingMetadata[value.content];\n          if (binding === \"setup-let\" || binding === \"setup-ref\" || binding === \"setup-maybe-ref\") {\n            isStatic = false;\n            properties.push(\n              createObjectProperty(\n                createSimpleExpression(\"ref_key\", true),\n                createSimpleExpression(value.content, true, value.loc)\n              )\n            );\n          }\n        }\n      }\n      if (name === \"is\" && (isComponentTag(tag) || value && value.content.startsWith(\"vue:\") || isCompatEnabled(\n        \"COMPILER_IS_ON_ELEMENT\",\n        context\n      ))) {\n        continue;\n      }\n      properties.push(\n        createObjectProperty(\n          createSimpleExpression(name, true, nameLoc),\n          createSimpleExpression(\n            value ? value.content : \"\",\n            isStatic,\n            value ? value.loc : loc\n          )\n        )\n      );\n    } else {\n      const { name, arg, exp, loc, modifiers } = prop;\n      const isVBind = name === \"bind\";\n      const isVOn = name === \"on\";\n      if (name === \"slot\") {\n        if (!isComponent) {\n          context.onError(\n            createCompilerError(40, loc)\n          );\n        }\n        continue;\n      }\n      if (name === \"once\" || name === \"memo\") {\n        continue;\n      }\n      if (name === \"is\" || isVBind && isStaticArgOf(arg, \"is\") && (isComponentTag(tag) || isCompatEnabled(\n        \"COMPILER_IS_ON_ELEMENT\",\n        context\n      ))) {\n        continue;\n      }\n      if (isVOn && ssr) {\n        continue;\n      }\n      if (\n        // #938: elements with dynamic keys should be forced into blocks\n        isVBind && isStaticArgOf(arg, \"key\") || // inline before-update hooks need to force block so that it is invoked\n        // before children\n        isVOn && hasChildren && isStaticArgOf(arg, \"vue:before-update\")\n      ) {\n        shouldUseBlock = true;\n      }\n      if (isVBind && isStaticArgOf(arg, \"ref\")) {\n        pushRefVForMarker();\n      }\n      if (!arg && (isVBind || isVOn)) {\n        hasDynamicKeys = true;\n        if (exp) {\n          if (isVBind) {\n            {\n              pushMergeArg();\n              if (isCompatEnabled(\n                \"COMPILER_V_BIND_OBJECT_ORDER\",\n                context\n              )) {\n                mergeArgs.unshift(exp);\n                continue;\n              }\n            }\n            pushRefVForMarker();\n            pushMergeArg();\n            mergeArgs.push(exp);\n          } else {\n            pushMergeArg({\n              type: 14,\n              loc,\n              callee: context.helper(TO_HANDLERS),\n              arguments: isComponent ? [exp] : [exp, `true`]\n            });\n          }\n        } else {\n          context.onError(\n            createCompilerError(\n              isVBind ? 34 : 35,\n              loc\n            )\n          );\n        }\n        continue;\n      }\n      if (isVBind && modifiers.some((mod) => mod.content === \"prop\")) {\n        patchFlag |= 32;\n      }\n      const directiveTransform = context.directiveTransforms[name];\n      if (directiveTransform) {\n        const { props: props2, needRuntime } = directiveTransform(prop, node, context);\n        !ssr && props2.forEach(analyzePatchFlag);\n        if (isVOn && arg && !isStaticExp(arg)) {\n          pushMergeArg(createObjectExpression(props2, elementLoc));\n        } else {\n          properties.push(...props2);\n        }\n        if (needRuntime) {\n          runtimeDirectives.push(prop);\n          if (shared.isSymbol(needRuntime)) {\n            directiveImportMap.set(prop, needRuntime);\n          }\n        }\n      } else if (!shared.isBuiltInDirective(name)) {\n        runtimeDirectives.push(prop);\n        if (hasChildren) {\n          shouldUseBlock = true;\n        }\n      }\n    }\n  }\n  let propsExpression = void 0;\n  if (mergeArgs.length) {\n    pushMergeArg();\n    if (mergeArgs.length > 1) {\n      propsExpression = createCallExpression(\n        context.helper(MERGE_PROPS),\n        mergeArgs,\n        elementLoc\n      );\n    } else {\n      propsExpression = mergeArgs[0];\n    }\n  } else if (properties.length) {\n    propsExpression = createObjectExpression(\n      dedupeProperties(properties),\n      elementLoc\n    );\n  }\n  if (hasDynamicKeys) {\n    patchFlag |= 16;\n  } else {\n    if (hasClassBinding && !isComponent) {\n      patchFlag |= 2;\n    }\n    if (hasStyleBinding && !isComponent) {\n      patchFlag |= 4;\n    }\n    if (dynamicPropNames.length) {\n      patchFlag |= 8;\n    }\n    if (hasHydrationEventBinding) {\n      patchFlag |= 32;\n    }\n  }\n  if (!shouldUseBlock && (patchFlag === 0 || patchFlag === 32) && (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {\n    patchFlag |= 512;\n  }\n  if (!context.inSSR && propsExpression) {\n    switch (propsExpression.type) {\n      case 15:\n        let classKeyIndex = -1;\n        let styleKeyIndex = -1;\n        let hasDynamicKey = false;\n        for (let i = 0; i < propsExpression.properties.length; i++) {\n          const key = propsExpression.properties[i].key;\n          if (isStaticExp(key)) {\n            if (key.content === \"class\") {\n              classKeyIndex = i;\n            } else if (key.content === \"style\") {\n              styleKeyIndex = i;\n            }\n          } else if (!key.isHandlerKey) {\n            hasDynamicKey = true;\n          }\n        }\n        const classProp = propsExpression.properties[classKeyIndex];\n        const styleProp = propsExpression.properties[styleKeyIndex];\n        if (!hasDynamicKey) {\n          if (classProp && !isStaticExp(classProp.value)) {\n            classProp.value = createCallExpression(\n              context.helper(NORMALIZE_CLASS),\n              [classProp.value]\n            );\n          }\n          if (styleProp && // the static style is compiled into an object,\n          // so use `hasStyleBinding` to ensure that it is a dynamic style binding\n          (hasStyleBinding || styleProp.value.type === 4 && styleProp.value.content.trim()[0] === `[` || // v-bind:style and style both exist,\n          // v-bind:style with static literal object\n          styleProp.value.type === 17)) {\n            styleProp.value = createCallExpression(\n              context.helper(NORMALIZE_STYLE),\n              [styleProp.value]\n            );\n          }\n        } else {\n          propsExpression = createCallExpression(\n            context.helper(NORMALIZE_PROPS),\n            [propsExpression]\n          );\n        }\n        break;\n      case 14:\n        break;\n      default:\n        propsExpression = createCallExpression(\n          context.helper(NORMALIZE_PROPS),\n          [\n            createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [\n              propsExpression\n            ])\n          ]\n        );\n        break;\n    }\n  }\n  return {\n    props: propsExpression,\n    directives: runtimeDirectives,\n    patchFlag,\n    dynamicPropNames,\n    shouldUseBlock\n  };\n}\nfunction dedupeProperties(properties) {\n  const knownProps = /* @__PURE__ */ new Map();\n  const deduped = [];\n  for (let i = 0; i < properties.length; i++) {\n    const prop = properties[i];\n    if (prop.key.type === 8 || !prop.key.isStatic) {\n      deduped.push(prop);\n      continue;\n    }\n    const name = prop.key.content;\n    const existing = knownProps.get(name);\n    if (existing) {\n      if (name === \"style\" || name === \"class\" || shared.isOn(name)) {\n        mergeAsArray(existing, prop);\n      }\n    } else {\n      knownProps.set(name, prop);\n      deduped.push(prop);\n    }\n  }\n  return deduped;\n}\nfunction mergeAsArray(existing, incoming) {\n  if (existing.value.type === 17) {\n    existing.value.elements.push(incoming.value);\n  } else {\n    existing.value = createArrayExpression(\n      [existing.value, incoming.value],\n      existing.loc\n    );\n  }\n}\nfunction buildDirectiveArgs(dir, context) {\n  const dirArgs = [];\n  const runtime = directiveImportMap.get(dir);\n  if (runtime) {\n    dirArgs.push(context.helperString(runtime));\n  } else {\n    const fromSetup = resolveSetupReference(\"v-\" + dir.name, context);\n    if (fromSetup) {\n      dirArgs.push(fromSetup);\n    } else {\n      context.helper(RESOLVE_DIRECTIVE);\n      context.directives.add(dir.name);\n      dirArgs.push(toValidAssetId(dir.name, `directive`));\n    }\n  }\n  const { loc } = dir;\n  if (dir.exp) dirArgs.push(dir.exp);\n  if (dir.arg) {\n    if (!dir.exp) {\n      dirArgs.push(`void 0`);\n    }\n    dirArgs.push(dir.arg);\n  }\n  if (Object.keys(dir.modifiers).length) {\n    if (!dir.arg) {\n      if (!dir.exp) {\n        dirArgs.push(`void 0`);\n      }\n      dirArgs.push(`void 0`);\n    }\n    const trueExpression = createSimpleExpression(`true`, false, loc);\n    dirArgs.push(\n      createObjectExpression(\n        dir.modifiers.map(\n          (modifier) => createObjectProperty(modifier, trueExpression)\n        ),\n        loc\n      )\n    );\n  }\n  return createArrayExpression(dirArgs, dir.loc);\n}\nfunction stringifyDynamicPropNames(props) {\n  let propsNamesString = `[`;\n  for (let i = 0, l = props.length; i < l; i++) {\n    propsNamesString += JSON.stringify(props[i]);\n    if (i < l - 1) propsNamesString += \", \";\n  }\n  return propsNamesString + `]`;\n}\nfunction isComponentTag(tag) {\n  return tag === \"component\" || tag === \"Component\";\n}\n\nconst transformSlotOutlet = (node, context) => {\n  if (isSlotOutlet(node)) {\n    const { children, loc } = node;\n    const { slotName, slotProps } = processSlotOutlet(node, context);\n    const slotArgs = [\n      context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,\n      slotName,\n      \"{}\",\n      \"undefined\",\n      \"true\"\n    ];\n    let expectedLen = 2;\n    if (slotProps) {\n      slotArgs[2] = slotProps;\n      expectedLen = 3;\n    }\n    if (children.length) {\n      slotArgs[3] = createFunctionExpression([], children, false, false, loc);\n      expectedLen = 4;\n    }\n    if (context.scopeId && !context.slotted) {\n      expectedLen = 5;\n    }\n    slotArgs.splice(expectedLen);\n    node.codegenNode = createCallExpression(\n      context.helper(RENDER_SLOT),\n      slotArgs,\n      loc\n    );\n  }\n};\nfunction processSlotOutlet(node, context) {\n  let slotName = `\"default\"`;\n  let slotProps = void 0;\n  const nonNameProps = [];\n  for (let i = 0; i < node.props.length; i++) {\n    const p = node.props[i];\n    if (p.type === 6) {\n      if (p.value) {\n        if (p.name === \"name\") {\n          slotName = JSON.stringify(p.value.content);\n        } else {\n          p.name = shared.camelize(p.name);\n          nonNameProps.push(p);\n        }\n      }\n    } else {\n      if (p.name === \"bind\" && isStaticArgOf(p.arg, \"name\")) {\n        if (p.exp) {\n          slotName = p.exp;\n        } else if (p.arg && p.arg.type === 4) {\n          const name = shared.camelize(p.arg.content);\n          slotName = p.exp = createSimpleExpression(name, false, p.arg.loc);\n          {\n            slotName = p.exp = processExpression(p.exp, context);\n          }\n        }\n      } else {\n        if (p.name === \"bind\" && p.arg && isStaticExp(p.arg)) {\n          p.arg.content = shared.camelize(p.arg.content);\n        }\n        nonNameProps.push(p);\n      }\n    }\n  }\n  if (nonNameProps.length > 0) {\n    const { props, directives } = buildProps(\n      node,\n      context,\n      nonNameProps,\n      false,\n      false\n    );\n    slotProps = props;\n    if (directives.length) {\n      context.onError(\n        createCompilerError(\n          36,\n          directives[0].loc\n        )\n      );\n    }\n  }\n  return {\n    slotName,\n    slotProps\n  };\n}\n\nconst transformOn = (dir, node, context, augmentor) => {\n  const { loc, modifiers, arg } = dir;\n  if (!dir.exp && !modifiers.length) {\n    context.onError(createCompilerError(35, loc));\n  }\n  let eventName;\n  if (arg.type === 4) {\n    if (arg.isStatic) {\n      let rawName = arg.content;\n      if (rawName.startsWith(\"vue:\")) {\n        rawName = `vnode-${rawName.slice(4)}`;\n      }\n      const eventString = node.tagType !== 0 || rawName.startsWith(\"vnode\") || !/[A-Z]/.test(rawName) ? (\n        // for non-element and vnode lifecycle event listeners, auto convert\n        // it to camelCase. See issue #2249\n        shared.toHandlerKey(shared.camelize(rawName))\n      ) : (\n        // preserve case for plain element listeners that have uppercase\n        // letters, as these may be custom elements' custom events\n        `on:${rawName}`\n      );\n      eventName = createSimpleExpression(eventString, true, arg.loc);\n    } else {\n      eventName = createCompoundExpression([\n        `${context.helperString(TO_HANDLER_KEY)}(`,\n        arg,\n        `)`\n      ]);\n    }\n  } else {\n    eventName = arg;\n    eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);\n    eventName.children.push(`)`);\n  }\n  let exp = dir.exp;\n  if (exp && !exp.content.trim()) {\n    exp = void 0;\n  }\n  let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;\n  if (exp) {\n    const isMemberExp = isMemberExpression(exp, context);\n    const isInlineStatement = !(isMemberExp || isFnExpression(exp, context));\n    const hasMultipleStatements = exp.content.includes(`;`);\n    if (context.prefixIdentifiers) {\n      isInlineStatement && context.addIdentifiers(`$event`);\n      exp = dir.exp = processExpression(\n        exp,\n        context,\n        false,\n        hasMultipleStatements\n      );\n      isInlineStatement && context.removeIdentifiers(`$event`);\n      shouldCache = context.cacheHandlers && // unnecessary to cache inside v-once\n      !context.inVOnce && // runtime constants don't need to be cached\n      // (this is analyzed by compileScript in SFC <script setup>)\n      !(exp.type === 4 && exp.constType > 0) && // #1541 bail if this is a member exp handler passed to a component -\n      // we need to use the original function to preserve arity,\n      // e.g. <transition> relies on checking cb.length to determine\n      // transition end handling. Inline function is ok since its arity\n      // is preserved even when cached.\n      !(isMemberExp && node.tagType === 1) && // bail if the function references closure variables (v-for, v-slot)\n      // it must be passed fresh to avoid stale values.\n      !hasScopeRef(exp, context.identifiers);\n      if (shouldCache && isMemberExp) {\n        if (exp.type === 4) {\n          exp.content = `${exp.content} && ${exp.content}(...args)`;\n        } else {\n          exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`];\n        }\n      }\n    }\n    if (isInlineStatement || shouldCache && isMemberExp) {\n      exp = createCompoundExpression([\n        `${isInlineStatement ? context.isTS ? `($event: any)` : `$event` : `${context.isTS ? `\n//@ts-ignore\n` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,\n        exp,\n        hasMultipleStatements ? `}` : `)`\n      ]);\n    }\n  }\n  let ret = {\n    props: [\n      createObjectProperty(\n        eventName,\n        exp || createSimpleExpression(`() => {}`, false, loc)\n      )\n    ]\n  };\n  if (augmentor) {\n    ret = augmentor(ret);\n  }\n  if (shouldCache) {\n    ret.props[0].value = context.cache(ret.props[0].value);\n  }\n  ret.props.forEach((p) => p.key.isHandlerKey = true);\n  return ret;\n};\n\nconst transformText = (node, context) => {\n  if (node.type === 0 || node.type === 1 || node.type === 11 || node.type === 10) {\n    return () => {\n      const children = node.children;\n      let currentContainer = void 0;\n      let hasText = false;\n      for (let i = 0; i < children.length; i++) {\n        const child = children[i];\n        if (isText$1(child)) {\n          hasText = true;\n          for (let j = i + 1; j < children.length; j++) {\n            const next = children[j];\n            if (isText$1(next)) {\n              if (!currentContainer) {\n                currentContainer = children[i] = createCompoundExpression(\n                  [child],\n                  child.loc\n                );\n              }\n              currentContainer.children.push(` + `, next);\n              children.splice(j, 1);\n              j--;\n            } else {\n              currentContainer = void 0;\n              break;\n            }\n          }\n        }\n      }\n      if (!hasText || // if this is a plain element with a single text child, leave it\n      // as-is since the runtime has dedicated fast path for this by directly\n      // setting textContent of the element.\n      // for component root it's always normalized anyway.\n      children.length === 1 && (node.type === 0 || node.type === 1 && node.tagType === 0 && // #3756\n      // custom directives can potentially add DOM elements arbitrarily,\n      // we need to avoid setting textContent of the element at runtime\n      // to avoid accidentally overwriting the DOM elements added\n      // by the user through custom directives.\n      !node.props.find(\n        (p) => p.type === 7 && !context.directiveTransforms[p.name]\n      ) && // in compat mode, <template> tags with no special directives\n      // will be rendered as a fragment so its children must be\n      // converted into vnodes.\n      !(node.tag === \"template\"))) {\n        return;\n      }\n      for (let i = 0; i < children.length; i++) {\n        const child = children[i];\n        if (isText$1(child) || child.type === 8) {\n          const callArgs = [];\n          if (child.type !== 2 || child.content !== \" \") {\n            callArgs.push(child);\n          }\n          if (!context.ssr && getConstantType(child, context) === 0) {\n            callArgs.push(\n              1 + (``)\n            );\n          }\n          children[i] = {\n            type: 12,\n            content: child,\n            loc: child.loc,\n            codegenNode: createCallExpression(\n              context.helper(CREATE_TEXT),\n              callArgs\n            )\n          };\n        }\n      }\n    };\n  }\n};\n\nconst seen$1 = /* @__PURE__ */ new WeakSet();\nconst transformOnce = (node, context) => {\n  if (node.type === 1 && findDir(node, \"once\", true)) {\n    if (seen$1.has(node) || context.inVOnce || context.inSSR) {\n      return;\n    }\n    seen$1.add(node);\n    context.inVOnce = true;\n    context.helper(SET_BLOCK_TRACKING);\n    return () => {\n      context.inVOnce = false;\n      const cur = context.currentNode;\n      if (cur.codegenNode) {\n        cur.codegenNode = context.cache(\n          cur.codegenNode,\n          true,\n          true\n        );\n      }\n    };\n  }\n};\n\nconst transformModel = (dir, node, context) => {\n  const { exp, arg } = dir;\n  if (!exp) {\n    context.onError(\n      createCompilerError(41, dir.loc)\n    );\n    return createTransformProps();\n  }\n  const rawExp = exp.loc.source.trim();\n  const expString = exp.type === 4 ? exp.content : rawExp;\n  const bindingType = context.bindingMetadata[rawExp];\n  if (bindingType === \"props\" || bindingType === \"props-aliased\") {\n    context.onError(createCompilerError(44, exp.loc));\n    return createTransformProps();\n  }\n  const maybeRef = context.inline && (bindingType === \"setup-let\" || bindingType === \"setup-ref\" || bindingType === \"setup-maybe-ref\");\n  if (!expString.trim() || !isMemberExpression(exp, context) && !maybeRef) {\n    context.onError(\n      createCompilerError(42, exp.loc)\n    );\n    return createTransformProps();\n  }\n  if (context.prefixIdentifiers && isSimpleIdentifier(expString) && context.identifiers[expString]) {\n    context.onError(\n      createCompilerError(43, exp.loc)\n    );\n    return createTransformProps();\n  }\n  const propName = arg ? arg : createSimpleExpression(\"modelValue\", true);\n  const eventName = arg ? isStaticExp(arg) ? `onUpdate:${shared.camelize(arg.content)}` : createCompoundExpression(['\"onUpdate:\" + ', arg]) : `onUpdate:modelValue`;\n  let assignmentExp;\n  const eventArg = context.isTS ? `($event: any)` : `$event`;\n  if (maybeRef) {\n    if (bindingType === \"setup-ref\") {\n      assignmentExp = createCompoundExpression([\n        `${eventArg} => ((`,\n        createSimpleExpression(rawExp, false, exp.loc),\n        `).value = $event)`\n      ]);\n    } else {\n      const altAssignment = bindingType === \"setup-let\" ? `${rawExp} = $event` : `null`;\n      assignmentExp = createCompoundExpression([\n        `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? (`,\n        createSimpleExpression(rawExp, false, exp.loc),\n        `).value = $event : ${altAssignment})`\n      ]);\n    }\n  } else {\n    assignmentExp = createCompoundExpression([\n      `${eventArg} => ((`,\n      exp,\n      `) = $event)`\n    ]);\n  }\n  const props = [\n    // modelValue: foo\n    createObjectProperty(propName, dir.exp),\n    // \"onUpdate:modelValue\": $event => (foo = $event)\n    createObjectProperty(eventName, assignmentExp)\n  ];\n  if (context.prefixIdentifiers && !context.inVOnce && context.cacheHandlers && !hasScopeRef(exp, context.identifiers)) {\n    props[1].value = context.cache(props[1].value);\n  }\n  if (dir.modifiers.length && node.tagType === 1) {\n    const modifiers = dir.modifiers.map((m) => m.content).map((m) => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`).join(`, `);\n    const modifiersKey = arg ? isStaticExp(arg) ? `${arg.content}Modifiers` : createCompoundExpression([arg, ' + \"Modifiers\"']) : `modelModifiers`;\n    props.push(\n      createObjectProperty(\n        modifiersKey,\n        createSimpleExpression(\n          `{ ${modifiers} }`,\n          false,\n          dir.loc,\n          2\n        )\n      )\n    );\n  }\n  return createTransformProps(props);\n};\nfunction createTransformProps(props = []) {\n  return { props };\n}\n\nconst validDivisionCharRE = /[\\w).+\\-_$\\]]/;\nconst transformFilter = (node, context) => {\n  if (!isCompatEnabled(\"COMPILER_FILTERS\", context)) {\n    return;\n  }\n  if (node.type === 5) {\n    rewriteFilter(node.content, context);\n  } else if (node.type === 1) {\n    node.props.forEach((prop) => {\n      if (prop.type === 7 && prop.name !== \"for\" && prop.exp) {\n        rewriteFilter(prop.exp, context);\n      }\n    });\n  }\n};\nfunction rewriteFilter(node, context) {\n  if (node.type === 4) {\n    parseFilter(node, context);\n  } else {\n    for (let i = 0; i < node.children.length; i++) {\n      const child = node.children[i];\n      if (typeof child !== \"object\") continue;\n      if (child.type === 4) {\n        parseFilter(child, context);\n      } else if (child.type === 8) {\n        rewriteFilter(node, context);\n      } else if (child.type === 5) {\n        rewriteFilter(child.content, context);\n      }\n    }\n  }\n}\nfunction parseFilter(node, context) {\n  const exp = node.content;\n  let inSingle = false;\n  let inDouble = false;\n  let inTemplateString = false;\n  let inRegex = false;\n  let curly = 0;\n  let square = 0;\n  let paren = 0;\n  let lastFilterIndex = 0;\n  let c, prev, i, expression, filters = [];\n  for (i = 0; i < exp.length; i++) {\n    prev = c;\n    c = exp.charCodeAt(i);\n    if (inSingle) {\n      if (c === 39 && prev !== 92) inSingle = false;\n    } else if (inDouble) {\n      if (c === 34 && prev !== 92) inDouble = false;\n    } else if (inTemplateString) {\n      if (c === 96 && prev !== 92) inTemplateString = false;\n    } else if (inRegex) {\n      if (c === 47 && prev !== 92) inRegex = false;\n    } else if (c === 124 && // pipe\n    exp.charCodeAt(i + 1) !== 124 && exp.charCodeAt(i - 1) !== 124 && !curly && !square && !paren) {\n      if (expression === void 0) {\n        lastFilterIndex = i + 1;\n        expression = exp.slice(0, i).trim();\n      } else {\n        pushFilter();\n      }\n    } else {\n      switch (c) {\n        case 34:\n          inDouble = true;\n          break;\n        // \"\n        case 39:\n          inSingle = true;\n          break;\n        // '\n        case 96:\n          inTemplateString = true;\n          break;\n        // `\n        case 40:\n          paren++;\n          break;\n        // (\n        case 41:\n          paren--;\n          break;\n        // )\n        case 91:\n          square++;\n          break;\n        // [\n        case 93:\n          square--;\n          break;\n        // ]\n        case 123:\n          curly++;\n          break;\n        // {\n        case 125:\n          curly--;\n          break;\n      }\n      if (c === 47) {\n        let j = i - 1;\n        let p;\n        for (; j >= 0; j--) {\n          p = exp.charAt(j);\n          if (p !== \" \") break;\n        }\n        if (!p || !validDivisionCharRE.test(p)) {\n          inRegex = true;\n        }\n      }\n    }\n  }\n  if (expression === void 0) {\n    expression = exp.slice(0, i).trim();\n  } else if (lastFilterIndex !== 0) {\n    pushFilter();\n  }\n  function pushFilter() {\n    filters.push(exp.slice(lastFilterIndex, i).trim());\n    lastFilterIndex = i + 1;\n  }\n  if (filters.length) {\n    for (i = 0; i < filters.length; i++) {\n      expression = wrapFilter(expression, filters[i], context);\n    }\n    node.content = expression;\n    node.ast = void 0;\n  }\n}\nfunction wrapFilter(exp, filter, context) {\n  context.helper(RESOLVE_FILTER);\n  const i = filter.indexOf(\"(\");\n  if (i < 0) {\n    context.filters.add(filter);\n    return `${toValidAssetId(filter, \"filter\")}(${exp})`;\n  } else {\n    const name = filter.slice(0, i);\n    const args = filter.slice(i + 1);\n    context.filters.add(name);\n    return `${toValidAssetId(name, \"filter\")}(${exp}${args !== \")\" ? \",\" + args : args}`;\n  }\n}\n\nconst seen = /* @__PURE__ */ new WeakSet();\nconst transformMemo = (node, context) => {\n  if (node.type === 1) {\n    const dir = findDir(node, \"memo\");\n    if (!dir || seen.has(node)) {\n      return;\n    }\n    seen.add(node);\n    return () => {\n      const codegenNode = node.codegenNode || context.currentNode.codegenNode;\n      if (codegenNode && codegenNode.type === 13) {\n        if (node.tagType !== 1) {\n          convertToBlock(codegenNode, context);\n        }\n        node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [\n          dir.exp,\n          createFunctionExpression(void 0, codegenNode),\n          `_cache`,\n          String(context.cached.length)\n        ]);\n        context.cached.push(null);\n      }\n    };\n  }\n};\n\nfunction getBaseTransformPreset(prefixIdentifiers) {\n  return [\n    [\n      transformOnce,\n      transformIf,\n      transformMemo,\n      transformFor,\n      ...[transformFilter] ,\n      ...prefixIdentifiers ? [\n        // order is important\n        trackVForSlotScopes,\n        transformExpression\n      ] : [],\n      transformSlotOutlet,\n      transformElement,\n      trackSlotScopes,\n      transformText\n    ],\n    {\n      on: transformOn,\n      bind: transformBind,\n      model: transformModel\n    }\n  ];\n}\nfunction baseCompile(source, options = {}) {\n  const onError = options.onError || defaultOnError;\n  const isModuleMode = options.mode === \"module\";\n  const prefixIdentifiers = options.prefixIdentifiers === true || isModuleMode;\n  if (!prefixIdentifiers && options.cacheHandlers) {\n    onError(createCompilerError(49));\n  }\n  if (options.scopeId && !isModuleMode) {\n    onError(createCompilerError(50));\n  }\n  const resolvedOptions = shared.extend({}, options, {\n    prefixIdentifiers\n  });\n  const ast = shared.isString(source) ? baseParse(source, resolvedOptions) : source;\n  const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);\n  if (options.isTS) {\n    const { expressionPlugins } = options;\n    if (!expressionPlugins || !expressionPlugins.includes(\"typescript\")) {\n      options.expressionPlugins = [...expressionPlugins || [], \"typescript\"];\n    }\n  }\n  transform(\n    ast,\n    shared.extend({}, resolvedOptions, {\n      nodeTransforms: [\n        ...nodeTransforms,\n        ...options.nodeTransforms || []\n        // user transforms\n      ],\n      directiveTransforms: shared.extend(\n        {},\n        directiveTransforms,\n        options.directiveTransforms || {}\n        // user transforms\n      )\n    })\n  );\n  return generate(ast, resolvedOptions);\n}\n\nconst BindingTypes = {\n  \"DATA\": \"data\",\n  \"PROPS\": \"props\",\n  \"PROPS_ALIASED\": \"props-aliased\",\n  \"SETUP_LET\": \"setup-let\",\n  \"SETUP_CONST\": \"setup-const\",\n  \"SETUP_REACTIVE_CONST\": \"setup-reactive-const\",\n  \"SETUP_MAYBE_REF\": \"setup-maybe-ref\",\n  \"SETUP_REF\": \"setup-ref\",\n  \"OPTIONS\": \"options\",\n  \"LITERAL_CONST\": \"literal-const\"\n};\n\nconst noopDirectiveTransform = () => ({ props: [] });\n\nexports.generateCodeFrame = shared.generateCodeFrame;\nexports.BASE_TRANSITION = BASE_TRANSITION;\nexports.BindingTypes = BindingTypes;\nexports.CAMELIZE = CAMELIZE;\nexports.CAPITALIZE = CAPITALIZE;\nexports.CREATE_BLOCK = CREATE_BLOCK;\nexports.CREATE_COMMENT = CREATE_COMMENT;\nexports.CREATE_ELEMENT_BLOCK = CREATE_ELEMENT_BLOCK;\nexports.CREATE_ELEMENT_VNODE = CREATE_ELEMENT_VNODE;\nexports.CREATE_SLOTS = CREATE_SLOTS;\nexports.CREATE_STATIC = CREATE_STATIC;\nexports.CREATE_TEXT = CREATE_TEXT;\nexports.CREATE_VNODE = CREATE_VNODE;\nexports.CompilerDeprecationTypes = CompilerDeprecationTypes;\nexports.ConstantTypes = ConstantTypes;\nexports.ElementTypes = ElementTypes;\nexports.ErrorCodes = ErrorCodes;\nexports.FRAGMENT = FRAGMENT;\nexports.GUARD_REACTIVE_PROPS = GUARD_REACTIVE_PROPS;\nexports.IS_MEMO_SAME = IS_MEMO_SAME;\nexports.IS_REF = IS_REF;\nexports.KEEP_ALIVE = KEEP_ALIVE;\nexports.MERGE_PROPS = MERGE_PROPS;\nexports.NORMALIZE_CLASS = NORMALIZE_CLASS;\nexports.NORMALIZE_PROPS = NORMALIZE_PROPS;\nexports.NORMALIZE_STYLE = NORMALIZE_STYLE;\nexports.Namespaces = Namespaces;\nexports.NodeTypes = NodeTypes;\nexports.OPEN_BLOCK = OPEN_BLOCK;\nexports.POP_SCOPE_ID = POP_SCOPE_ID;\nexports.PUSH_SCOPE_ID = PUSH_SCOPE_ID;\nexports.RENDER_LIST = RENDER_LIST;\nexports.RENDER_SLOT = RENDER_SLOT;\nexports.RESOLVE_COMPONENT = RESOLVE_COMPONENT;\nexports.RESOLVE_DIRECTIVE = RESOLVE_DIRECTIVE;\nexports.RESOLVE_DYNAMIC_COMPONENT = RESOLVE_DYNAMIC_COMPONENT;\nexports.RESOLVE_FILTER = RESOLVE_FILTER;\nexports.SET_BLOCK_TRACKING = SET_BLOCK_TRACKING;\nexports.SUSPENSE = SUSPENSE;\nexports.TELEPORT = TELEPORT;\nexports.TO_DISPLAY_STRING = TO_DISPLAY_STRING;\nexports.TO_HANDLERS = TO_HANDLERS;\nexports.TO_HANDLER_KEY = TO_HANDLER_KEY;\nexports.TS_NODE_TYPES = TS_NODE_TYPES;\nexports.UNREF = UNREF;\nexports.WITH_CTX = WITH_CTX;\nexports.WITH_DIRECTIVES = WITH_DIRECTIVES;\nexports.WITH_MEMO = WITH_MEMO;\nexports.advancePositionWithClone = advancePositionWithClone;\nexports.advancePositionWithMutation = advancePositionWithMutation;\nexports.assert = assert;\nexports.baseCompile = baseCompile;\nexports.baseParse = baseParse;\nexports.buildDirectiveArgs = buildDirectiveArgs;\nexports.buildProps = buildProps;\nexports.buildSlots = buildSlots;\nexports.checkCompatEnabled = checkCompatEnabled;\nexports.convertToBlock = convertToBlock;\nexports.createArrayExpression = createArrayExpression;\nexports.createAssignmentExpression = createAssignmentExpression;\nexports.createBlockStatement = createBlockStatement;\nexports.createCacheExpression = createCacheExpression;\nexports.createCallExpression = createCallExpression;\nexports.createCompilerError = createCompilerError;\nexports.createCompoundExpression = createCompoundExpression;\nexports.createConditionalExpression = createConditionalExpression;\nexports.createForLoopParams = createForLoopParams;\nexports.createFunctionExpression = createFunctionExpression;\nexports.createIfStatement = createIfStatement;\nexports.createInterpolation = createInterpolation;\nexports.createObjectExpression = createObjectExpression;\nexports.createObjectProperty = createObjectProperty;\nexports.createReturnStatement = createReturnStatement;\nexports.createRoot = createRoot;\nexports.createSequenceExpression = createSequenceExpression;\nexports.createSimpleExpression = createSimpleExpression;\nexports.createStructuralDirectiveTransform = createStructuralDirectiveTransform;\nexports.createTemplateLiteral = createTemplateLiteral;\nexports.createTransformContext = createTransformContext;\nexports.createVNodeCall = createVNodeCall;\nexports.errorMessages = errorMessages;\nexports.extractIdentifiers = extractIdentifiers;\nexports.findDir = findDir;\nexports.findProp = findProp;\nexports.forAliasRE = forAliasRE;\nexports.generate = generate;\nexports.getBaseTransformPreset = getBaseTransformPreset;\nexports.getConstantType = getConstantType;\nexports.getMemoedVNodeCall = getMemoedVNodeCall;\nexports.getVNodeBlockHelper = getVNodeBlockHelper;\nexports.getVNodeHelper = getVNodeHelper;\nexports.hasDynamicKeyVBind = hasDynamicKeyVBind;\nexports.hasScopeRef = hasScopeRef;\nexports.helperNameMap = helperNameMap;\nexports.injectProp = injectProp;\nexports.isCoreComponent = isCoreComponent;\nexports.isFnExpression = isFnExpression;\nexports.isFnExpressionBrowser = isFnExpressionBrowser;\nexports.isFnExpressionNode = isFnExpressionNode;\nexports.isFunctionType = isFunctionType;\nexports.isInDestructureAssignment = isInDestructureAssignment;\nexports.isInNewExpression = isInNewExpression;\nexports.isMemberExpression = isMemberExpression;\nexports.isMemberExpressionBrowser = isMemberExpressionBrowser;\nexports.isMemberExpressionNode = isMemberExpressionNode;\nexports.isReferencedIdentifier = isReferencedIdentifier;\nexports.isSimpleIdentifier = isSimpleIdentifier;\nexports.isSlotOutlet = isSlotOutlet;\nexports.isStaticArgOf = isStaticArgOf;\nexports.isStaticExp = isStaticExp;\nexports.isStaticProperty = isStaticProperty;\nexports.isStaticPropertyKey = isStaticPropertyKey;\nexports.isTemplateNode = isTemplateNode;\nexports.isText = isText$1;\nexports.isVPre = isVPre;\nexports.isVSlot = isVSlot;\nexports.locStub = locStub;\nexports.noopDirectiveTransform = noopDirectiveTransform;\nexports.processExpression = processExpression;\nexports.processFor = processFor;\nexports.processIf = processIf;\nexports.processSlotOutlet = processSlotOutlet;\nexports.registerRuntimeHelpers = registerRuntimeHelpers;\nexports.resolveComponentType = resolveComponentType;\nexports.stringifyExpression = stringifyExpression;\nexports.toValidAssetId = toValidAssetId;\nexports.trackSlotScopes = trackSlotScopes;\nexports.trackVForSlotScopes = trackVForSlotScopes;\nexports.transform = transform;\nexports.transformBind = transformBind;\nexports.transformElement = transformElement;\nexports.transformExpression = transformExpression;\nexports.transformModel = transformModel;\nexports.transformOn = transformOn;\nexports.traverseNode = traverseNode;\nexports.unwrapTSNode = unwrapTSNode;\nexports.walkBlockDeclarations = walkBlockDeclarations;\nexports.walkFunctionParams = walkFunctionParams;\nexports.walkIdentifiers = walkIdentifiers;\nexports.warnDeprecation = warnDeprecation;\n","'use strict'\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./dist/compiler-core.cjs.prod.js')\n} else {\n  module.exports = require('./dist/compiler-core.cjs.js')\n}\n","/**\n* @vue/compiler-dom v3.5.18\n* (c) 2018-present Yuxi (Evan) You and Vue contributors\n* @license MIT\n**/\n'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar compilerCore = require('@vue/compiler-core');\nvar shared = require('@vue/shared');\n\nconst V_MODEL_RADIO = Symbol(``);\nconst V_MODEL_CHECKBOX = Symbol(\n  ``\n);\nconst V_MODEL_TEXT = Symbol(``);\nconst V_MODEL_SELECT = Symbol(\n  ``\n);\nconst V_MODEL_DYNAMIC = Symbol(\n  ``\n);\nconst V_ON_WITH_MODIFIERS = Symbol(\n  ``\n);\nconst V_ON_WITH_KEYS = Symbol(\n  ``\n);\nconst V_SHOW = Symbol(``);\nconst TRANSITION = Symbol(``);\nconst TRANSITION_GROUP = Symbol(\n  ``\n);\ncompilerCore.registerRuntimeHelpers({\n  [V_MODEL_RADIO]: `vModelRadio`,\n  [V_MODEL_CHECKBOX]: `vModelCheckbox`,\n  [V_MODEL_TEXT]: `vModelText`,\n  [V_MODEL_SELECT]: `vModelSelect`,\n  [V_MODEL_DYNAMIC]: `vModelDynamic`,\n  [V_ON_WITH_MODIFIERS]: `withModifiers`,\n  [V_ON_WITH_KEYS]: `withKeys`,\n  [V_SHOW]: `vShow`,\n  [TRANSITION]: `Transition`,\n  [TRANSITION_GROUP]: `TransitionGroup`\n});\n\nconst parserOptions = {\n  parseMode: \"html\",\n  isVoidTag: shared.isVoidTag,\n  isNativeTag: (tag) => shared.isHTMLTag(tag) || shared.isSVGTag(tag) || shared.isMathMLTag(tag),\n  isPreTag: (tag) => tag === \"pre\",\n  isIgnoreNewlineTag: (tag) => tag === \"pre\" || tag === \"textarea\",\n  decodeEntities: void 0,\n  isBuiltInComponent: (tag) => {\n    if (tag === \"Transition\" || tag === \"transition\") {\n      return TRANSITION;\n    } else if (tag === \"TransitionGroup\" || tag === \"transition-group\") {\n      return TRANSITION_GROUP;\n    }\n  },\n  // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher\n  getNamespace(tag, parent, rootNamespace) {\n    let ns = parent ? parent.ns : rootNamespace;\n    if (parent && ns === 2) {\n      if (parent.tag === \"annotation-xml\") {\n        if (tag === \"svg\") {\n          return 1;\n        }\n        if (parent.props.some(\n          (a) => a.type === 6 && a.name === \"encoding\" && a.value != null && (a.value.content === \"text/html\" || a.value.content === \"application/xhtml+xml\")\n        )) {\n          ns = 0;\n        }\n      } else if (/^m(?:[ions]|text)$/.test(parent.tag) && tag !== \"mglyph\" && tag !== \"malignmark\") {\n        ns = 0;\n      }\n    } else if (parent && ns === 1) {\n      if (parent.tag === \"foreignObject\" || parent.tag === \"desc\" || parent.tag === \"title\") {\n        ns = 0;\n      }\n    }\n    if (ns === 0) {\n      if (tag === \"svg\") {\n        return 1;\n      }\n      if (tag === \"math\") {\n        return 2;\n      }\n    }\n    return ns;\n  }\n};\n\nconst transformStyle = (node) => {\n  if (node.type === 1) {\n    node.props.forEach((p, i) => {\n      if (p.type === 6 && p.name === \"style\" && p.value) {\n        node.props[i] = {\n          type: 7,\n          name: `bind`,\n          arg: compilerCore.createSimpleExpression(`style`, true, p.loc),\n          exp: parseInlineCSS(p.value.content, p.loc),\n          modifiers: [],\n          loc: p.loc\n        };\n      }\n    });\n  }\n};\nconst parseInlineCSS = (cssText, loc) => {\n  const normalized = shared.parseStringStyle(cssText);\n  return compilerCore.createSimpleExpression(\n    JSON.stringify(normalized),\n    false,\n    loc,\n    3\n  );\n};\n\nfunction createDOMCompilerError(code, loc) {\n  return compilerCore.createCompilerError(\n    code,\n    loc,\n    DOMErrorMessages \n  );\n}\nconst DOMErrorCodes = {\n  \"X_V_HTML_NO_EXPRESSION\": 53,\n  \"53\": \"X_V_HTML_NO_EXPRESSION\",\n  \"X_V_HTML_WITH_CHILDREN\": 54,\n  \"54\": \"X_V_HTML_WITH_CHILDREN\",\n  \"X_V_TEXT_NO_EXPRESSION\": 55,\n  \"55\": \"X_V_TEXT_NO_EXPRESSION\",\n  \"X_V_TEXT_WITH_CHILDREN\": 56,\n  \"56\": \"X_V_TEXT_WITH_CHILDREN\",\n  \"X_V_MODEL_ON_INVALID_ELEMENT\": 57,\n  \"57\": \"X_V_MODEL_ON_INVALID_ELEMENT\",\n  \"X_V_MODEL_ARG_ON_ELEMENT\": 58,\n  \"58\": \"X_V_MODEL_ARG_ON_ELEMENT\",\n  \"X_V_MODEL_ON_FILE_INPUT_ELEMENT\": 59,\n  \"59\": \"X_V_MODEL_ON_FILE_INPUT_ELEMENT\",\n  \"X_V_MODEL_UNNECESSARY_VALUE\": 60,\n  \"60\": \"X_V_MODEL_UNNECESSARY_VALUE\",\n  \"X_V_SHOW_NO_EXPRESSION\": 61,\n  \"61\": \"X_V_SHOW_NO_EXPRESSION\",\n  \"X_TRANSITION_INVALID_CHILDREN\": 62,\n  \"62\": \"X_TRANSITION_INVALID_CHILDREN\",\n  \"X_IGNORED_SIDE_EFFECT_TAG\": 63,\n  \"63\": \"X_IGNORED_SIDE_EFFECT_TAG\",\n  \"__EXTEND_POINT__\": 64,\n  \"64\": \"__EXTEND_POINT__\"\n};\nconst DOMErrorMessages = {\n  [53]: `v-html is missing expression.`,\n  [54]: `v-html will override element children.`,\n  [55]: `v-text is missing expression.`,\n  [56]: `v-text will override element children.`,\n  [57]: `v-model can only be used on <input>, <textarea> and <select> elements.`,\n  [58]: `v-model argument is not supported on plain elements.`,\n  [59]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,\n  [60]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,\n  [61]: `v-show is missing expression.`,\n  [62]: `<Transition> expects exactly one child element or component.`,\n  [63]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`\n};\n\nconst transformVHtml = (dir, node, context) => {\n  const { exp, loc } = dir;\n  if (!exp) {\n    context.onError(\n      createDOMCompilerError(53, loc)\n    );\n  }\n  if (node.children.length) {\n    context.onError(\n      createDOMCompilerError(54, loc)\n    );\n    node.children.length = 0;\n  }\n  return {\n    props: [\n      compilerCore.createObjectProperty(\n        compilerCore.createSimpleExpression(`innerHTML`, true, loc),\n        exp || compilerCore.createSimpleExpression(\"\", true)\n      )\n    ]\n  };\n};\n\nconst transformVText = (dir, node, context) => {\n  const { exp, loc } = dir;\n  if (!exp) {\n    context.onError(\n      createDOMCompilerError(55, loc)\n    );\n  }\n  if (node.children.length) {\n    context.onError(\n      createDOMCompilerError(56, loc)\n    );\n    node.children.length = 0;\n  }\n  return {\n    props: [\n      compilerCore.createObjectProperty(\n        compilerCore.createSimpleExpression(`textContent`, true),\n        exp ? compilerCore.getConstantType(exp, context) > 0 ? exp : compilerCore.createCallExpression(\n          context.helperString(compilerCore.TO_DISPLAY_STRING),\n          [exp],\n          loc\n        ) : compilerCore.createSimpleExpression(\"\", true)\n      )\n    ]\n  };\n};\n\nconst transformModel = (dir, node, context) => {\n  const baseResult = compilerCore.transformModel(dir, node, context);\n  if (!baseResult.props.length || node.tagType === 1) {\n    return baseResult;\n  }\n  if (dir.arg) {\n    context.onError(\n      createDOMCompilerError(\n        58,\n        dir.arg.loc\n      )\n    );\n  }\n  const { tag } = node;\n  const isCustomElement = context.isCustomElement(tag);\n  if (tag === \"input\" || tag === \"textarea\" || tag === \"select\" || isCustomElement) {\n    let directiveToUse = V_MODEL_TEXT;\n    let isInvalidType = false;\n    if (tag === \"input\" || isCustomElement) {\n      const type = compilerCore.findProp(node, `type`);\n      if (type) {\n        if (type.type === 7) {\n          directiveToUse = V_MODEL_DYNAMIC;\n        } else if (type.value) {\n          switch (type.value.content) {\n            case \"radio\":\n              directiveToUse = V_MODEL_RADIO;\n              break;\n            case \"checkbox\":\n              directiveToUse = V_MODEL_CHECKBOX;\n              break;\n            case \"file\":\n              isInvalidType = true;\n              context.onError(\n                createDOMCompilerError(\n                  59,\n                  dir.loc\n                )\n              );\n              break;\n          }\n        }\n      } else if (compilerCore.hasDynamicKeyVBind(node)) {\n        directiveToUse = V_MODEL_DYNAMIC;\n      } else ;\n    } else if (tag === \"select\") {\n      directiveToUse = V_MODEL_SELECT;\n    } else ;\n    if (!isInvalidType) {\n      baseResult.needRuntime = context.helper(directiveToUse);\n    }\n  } else {\n    context.onError(\n      createDOMCompilerError(\n        57,\n        dir.loc\n      )\n    );\n  }\n  baseResult.props = baseResult.props.filter(\n    (p) => !(p.key.type === 4 && p.key.content === \"modelValue\")\n  );\n  return baseResult;\n};\n\nconst isEventOptionModifier = /* @__PURE__ */ shared.makeMap(`passive,once,capture`);\nconst isNonKeyModifier = /* @__PURE__ */ shared.makeMap(\n  // event propagation management\n  `stop,prevent,self,ctrl,shift,alt,meta,exact,middle`\n);\nconst maybeKeyModifier = /* @__PURE__ */ shared.makeMap(\"left,right\");\nconst isKeyboardEvent = /* @__PURE__ */ shared.makeMap(`onkeyup,onkeydown,onkeypress`);\nconst resolveModifiers = (key, modifiers, context, loc) => {\n  const keyModifiers = [];\n  const nonKeyModifiers = [];\n  const eventOptionModifiers = [];\n  for (let i = 0; i < modifiers.length; i++) {\n    const modifier = modifiers[i].content;\n    if (modifier === \"native\" && compilerCore.checkCompatEnabled(\n      \"COMPILER_V_ON_NATIVE\",\n      context,\n      loc\n    )) {\n      eventOptionModifiers.push(modifier);\n    } else if (isEventOptionModifier(modifier)) {\n      eventOptionModifiers.push(modifier);\n    } else {\n      if (maybeKeyModifier(modifier)) {\n        if (compilerCore.isStaticExp(key)) {\n          if (isKeyboardEvent(key.content.toLowerCase())) {\n            keyModifiers.push(modifier);\n          } else {\n            nonKeyModifiers.push(modifier);\n          }\n        } else {\n          keyModifiers.push(modifier);\n          nonKeyModifiers.push(modifier);\n        }\n      } else {\n        if (isNonKeyModifier(modifier)) {\n          nonKeyModifiers.push(modifier);\n        } else {\n          keyModifiers.push(modifier);\n        }\n      }\n    }\n  }\n  return {\n    keyModifiers,\n    nonKeyModifiers,\n    eventOptionModifiers\n  };\n};\nconst transformClick = (key, event) => {\n  const isStaticClick = compilerCore.isStaticExp(key) && key.content.toLowerCase() === \"onclick\";\n  return isStaticClick ? compilerCore.createSimpleExpression(event, true) : key.type !== 4 ? compilerCore.createCompoundExpression([\n    `(`,\n    key,\n    `) === \"onClick\" ? \"${event}\" : (`,\n    key,\n    `)`\n  ]) : key;\n};\nconst transformOn = (dir, node, context) => {\n  return compilerCore.transformOn(dir, node, context, (baseResult) => {\n    const { modifiers } = dir;\n    if (!modifiers.length) return baseResult;\n    let { key, value: handlerExp } = baseResult.props[0];\n    const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);\n    if (nonKeyModifiers.includes(\"right\")) {\n      key = transformClick(key, `onContextmenu`);\n    }\n    if (nonKeyModifiers.includes(\"middle\")) {\n      key = transformClick(key, `onMouseup`);\n    }\n    if (nonKeyModifiers.length) {\n      handlerExp = compilerCore.createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [\n        handlerExp,\n        JSON.stringify(nonKeyModifiers)\n      ]);\n    }\n    if (keyModifiers.length && // if event name is dynamic, always wrap with keys guard\n    (!compilerCore.isStaticExp(key) || isKeyboardEvent(key.content.toLowerCase()))) {\n      handlerExp = compilerCore.createCallExpression(context.helper(V_ON_WITH_KEYS), [\n        handlerExp,\n        JSON.stringify(keyModifiers)\n      ]);\n    }\n    if (eventOptionModifiers.length) {\n      const modifierPostfix = eventOptionModifiers.map(shared.capitalize).join(\"\");\n      key = compilerCore.isStaticExp(key) ? compilerCore.createSimpleExpression(`${key.content}${modifierPostfix}`, true) : compilerCore.createCompoundExpression([`(`, key, `) + \"${modifierPostfix}\"`]);\n    }\n    return {\n      props: [compilerCore.createObjectProperty(key, handlerExp)]\n    };\n  });\n};\n\nconst transformShow = (dir, node, context) => {\n  const { exp, loc } = dir;\n  if (!exp) {\n    context.onError(\n      createDOMCompilerError(61, loc)\n    );\n  }\n  return {\n    props: [],\n    needRuntime: context.helper(V_SHOW)\n  };\n};\n\nconst expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g;\nconst stringifyStatic = (children, context, parent) => {\n  if (context.scopes.vSlot > 0) {\n    return;\n  }\n  const isParentCached = parent.type === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !shared.isArray(parent.codegenNode.children) && parent.codegenNode.children.type === 20;\n  let nc = 0;\n  let ec = 0;\n  const currentChunk = [];\n  const stringifyCurrentChunk = (currentIndex) => {\n    if (nc >= 20 || ec >= 5) {\n      const staticCall = compilerCore.createCallExpression(context.helper(compilerCore.CREATE_STATIC), [\n        JSON.stringify(\n          currentChunk.map((node) => stringifyNode(node, context)).join(\"\")\n        ).replace(expReplaceRE, `\" + $1 + \"`),\n        // the 2nd argument indicates the number of DOM nodes this static vnode\n        // will insert / hydrate\n        String(currentChunk.length)\n      ]);\n      const deleteCount = currentChunk.length - 1;\n      if (isParentCached) {\n        children.splice(\n          currentIndex - currentChunk.length,\n          currentChunk.length,\n          // @ts-expect-error\n          staticCall\n        );\n      } else {\n        currentChunk[0].codegenNode.value = staticCall;\n        if (currentChunk.length > 1) {\n          children.splice(currentIndex - currentChunk.length + 1, deleteCount);\n          const cacheIndex = context.cached.indexOf(\n            currentChunk[currentChunk.length - 1].codegenNode\n          );\n          if (cacheIndex > -1) {\n            for (let i2 = cacheIndex; i2 < context.cached.length; i2++) {\n              const c = context.cached[i2];\n              if (c) c.index -= deleteCount;\n            }\n            context.cached.splice(cacheIndex - deleteCount + 1, deleteCount);\n          }\n        }\n      }\n      return deleteCount;\n    }\n    return 0;\n  };\n  let i = 0;\n  for (; i < children.length; i++) {\n    const child = children[i];\n    const isCached = isParentCached || getCachedNode(child);\n    if (isCached) {\n      const result = analyzeNode(child);\n      if (result) {\n        nc += result[0];\n        ec += result[1];\n        currentChunk.push(child);\n        continue;\n      }\n    }\n    i -= stringifyCurrentChunk(i);\n    nc = 0;\n    ec = 0;\n    currentChunk.length = 0;\n  }\n  stringifyCurrentChunk(i);\n};\nconst getCachedNode = (node) => {\n  if ((node.type === 1 && node.tagType === 0 || node.type === 12) && node.codegenNode && node.codegenNode.type === 20) {\n    return node.codegenNode;\n  }\n};\nconst dataAriaRE = /^(data|aria)-/;\nconst isStringifiableAttr = (name, ns) => {\n  return (ns === 0 ? shared.isKnownHtmlAttr(name) : ns === 1 ? shared.isKnownSvgAttr(name) : ns === 2 ? shared.isKnownMathMLAttr(name) : false) || dataAriaRE.test(name);\n};\nconst isNonStringifiable = /* @__PURE__ */ shared.makeMap(\n  `caption,thead,tr,th,tbody,td,tfoot,colgroup,col`\n);\nfunction analyzeNode(node) {\n  if (node.type === 1 && isNonStringifiable(node.tag)) {\n    return false;\n  }\n  if (node.type === 12) {\n    return [1, 0];\n  }\n  let nc = 1;\n  let ec = node.props.length > 0 ? 1 : 0;\n  let bailed = false;\n  const bail = () => {\n    bailed = true;\n    return false;\n  };\n  function walk(node2) {\n    const isOptionTag = node2.tag === \"option\" && node2.ns === 0;\n    for (let i = 0; i < node2.props.length; i++) {\n      const p = node2.props[i];\n      if (p.type === 6 && !isStringifiableAttr(p.name, node2.ns)) {\n        return bail();\n      }\n      if (p.type === 7 && p.name === \"bind\") {\n        if (p.arg && (p.arg.type === 8 || p.arg.isStatic && !isStringifiableAttr(p.arg.content, node2.ns))) {\n          return bail();\n        }\n        if (p.exp && (p.exp.type === 8 || p.exp.constType < 3)) {\n          return bail();\n        }\n        if (isOptionTag && compilerCore.isStaticArgOf(p.arg, \"value\") && p.exp && !p.exp.isStatic) {\n          return bail();\n        }\n      }\n    }\n    for (let i = 0; i < node2.children.length; i++) {\n      nc++;\n      const child = node2.children[i];\n      if (child.type === 1) {\n        if (child.props.length > 0) {\n          ec++;\n        }\n        walk(child);\n        if (bailed) {\n          return false;\n        }\n      }\n    }\n    return true;\n  }\n  return walk(node) ? [nc, ec] : false;\n}\nfunction stringifyNode(node, context) {\n  if (shared.isString(node)) {\n    return node;\n  }\n  if (shared.isSymbol(node)) {\n    return ``;\n  }\n  switch (node.type) {\n    case 1:\n      return stringifyElement(node, context);\n    case 2:\n      return shared.escapeHtml(node.content);\n    case 3:\n      return `<!--${shared.escapeHtml(node.content)}-->`;\n    case 5:\n      return shared.escapeHtml(shared.toDisplayString(evaluateConstant(node.content)));\n    case 8:\n      return shared.escapeHtml(evaluateConstant(node));\n    case 12:\n      return stringifyNode(node.content, context);\n    default:\n      return \"\";\n  }\n}\nfunction stringifyElement(node, context) {\n  let res = `<${node.tag}`;\n  let innerHTML = \"\";\n  for (let i = 0; i < node.props.length; i++) {\n    const p = node.props[i];\n    if (p.type === 6) {\n      res += ` ${p.name}`;\n      if (p.value) {\n        res += `=\"${shared.escapeHtml(p.value.content)}\"`;\n      }\n    } else if (p.type === 7) {\n      if (p.name === \"bind\") {\n        const exp = p.exp;\n        if (exp.content[0] === \"_\") {\n          res += ` ${p.arg.content}=\"__VUE_EXP_START__${exp.content}__VUE_EXP_END__\"`;\n          continue;\n        }\n        if (shared.isBooleanAttr(p.arg.content) && exp.content === \"false\") {\n          continue;\n        }\n        let evaluated = evaluateConstant(exp);\n        if (evaluated != null) {\n          const arg = p.arg && p.arg.content;\n          if (arg === \"class\") {\n            evaluated = shared.normalizeClass(evaluated);\n          } else if (arg === \"style\") {\n            evaluated = shared.stringifyStyle(shared.normalizeStyle(evaluated));\n          }\n          res += ` ${p.arg.content}=\"${shared.escapeHtml(\n            evaluated\n          )}\"`;\n        }\n      } else if (p.name === \"html\") {\n        innerHTML = evaluateConstant(p.exp);\n      } else if (p.name === \"text\") {\n        innerHTML = shared.escapeHtml(\n          shared.toDisplayString(evaluateConstant(p.exp))\n        );\n      }\n    }\n  }\n  if (context.scopeId) {\n    res += ` ${context.scopeId}`;\n  }\n  res += `>`;\n  if (innerHTML) {\n    res += innerHTML;\n  } else {\n    for (let i = 0; i < node.children.length; i++) {\n      res += stringifyNode(node.children[i], context);\n    }\n  }\n  if (!shared.isVoidTag(node.tag)) {\n    res += `</${node.tag}>`;\n  }\n  return res;\n}\nfunction evaluateConstant(exp) {\n  if (exp.type === 4) {\n    return new Function(`return (${exp.content})`)();\n  } else {\n    let res = ``;\n    exp.children.forEach((c) => {\n      if (shared.isString(c) || shared.isSymbol(c)) {\n        return;\n      }\n      if (c.type === 2) {\n        res += c.content;\n      } else if (c.type === 5) {\n        res += shared.toDisplayString(evaluateConstant(c.content));\n      } else {\n        res += evaluateConstant(c);\n      }\n    });\n    return res;\n  }\n}\n\nconst ignoreSideEffectTags = (node, context) => {\n  if (node.type === 1 && node.tagType === 0 && (node.tag === \"script\" || node.tag === \"style\")) {\n    context.removeNode();\n  }\n};\n\nconst DOMNodeTransforms = [\n  transformStyle,\n  ...[]\n];\nconst DOMDirectiveTransforms = {\n  cloak: compilerCore.noopDirectiveTransform,\n  html: transformVHtml,\n  text: transformVText,\n  model: transformModel,\n  // override compiler-core\n  on: transformOn,\n  // override compiler-core\n  show: transformShow\n};\nfunction compile(src, options = {}) {\n  return compilerCore.baseCompile(\n    src,\n    shared.extend({}, parserOptions, options, {\n      nodeTransforms: [\n        // ignore <script> and <tag>\n        // this is not put inside DOMNodeTransforms because that list is used\n        // by compiler-ssr to generate vnode fallback branches\n        ignoreSideEffectTags,\n        ...DOMNodeTransforms,\n        ...options.nodeTransforms || []\n      ],\n      directiveTransforms: shared.extend(\n        {},\n        DOMDirectiveTransforms,\n        options.directiveTransforms || {}\n      ),\n      transformHoist: stringifyStatic\n    })\n  );\n}\nfunction parse(template, options = {}) {\n  return compilerCore.baseParse(template, shared.extend({}, parserOptions, options));\n}\n\nexports.DOMDirectiveTransforms = DOMDirectiveTransforms;\nexports.DOMErrorCodes = DOMErrorCodes;\nexports.DOMErrorMessages = DOMErrorMessages;\nexports.DOMNodeTransforms = DOMNodeTransforms;\nexports.TRANSITION = TRANSITION;\nexports.TRANSITION_GROUP = TRANSITION_GROUP;\nexports.V_MODEL_CHECKBOX = V_MODEL_CHECKBOX;\nexports.V_MODEL_DYNAMIC = V_MODEL_DYNAMIC;\nexports.V_MODEL_RADIO = V_MODEL_RADIO;\nexports.V_MODEL_SELECT = V_MODEL_SELECT;\nexports.V_MODEL_TEXT = V_MODEL_TEXT;\nexports.V_ON_WITH_KEYS = V_ON_WITH_KEYS;\nexports.V_ON_WITH_MODIFIERS = V_ON_WITH_MODIFIERS;\nexports.V_SHOW = V_SHOW;\nexports.compile = compile;\nexports.createDOMCompilerError = createDOMCompilerError;\nexports.parse = parse;\nexports.parserOptions = parserOptions;\nexports.transformStyle = transformStyle;\nObject.keys(compilerCore).forEach(function (k) {\n  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = compilerCore[k];\n});\n","'use strict'\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./dist/compiler-dom.cjs.prod.js')\n} else {\n  module.exports = require('./dist/compiler-dom.cjs.js')\n}\n","/**\n* @vue/reactivity v3.5.18\n* (c) 2018-present Yuxi (Evan) You and Vue contributors\n* @license MIT\n**/\n'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar shared = require('@vue/shared');\n\nlet activeEffectScope;\nclass EffectScope {\n  constructor(detached = false) {\n    this.detached = detached;\n    /**\n     * @internal\n     */\n    this._active = true;\n    /**\n     * @internal track `on` calls, allow `on` call multiple times\n     */\n    this._on = 0;\n    /**\n     * @internal\n     */\n    this.effects = [];\n    /**\n     * @internal\n     */\n    this.cleanups = [];\n    this._isPaused = false;\n    this.parent = activeEffectScope;\n    if (!detached && activeEffectScope) {\n      this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(\n        this\n      ) - 1;\n    }\n  }\n  get active() {\n    return this._active;\n  }\n  pause() {\n    if (this._active) {\n      this._isPaused = true;\n      let i, l;\n      if (this.scopes) {\n        for (i = 0, l = this.scopes.length; i < l; i++) {\n          this.scopes[i].pause();\n        }\n      }\n      for (i = 0, l = this.effects.length; i < l; i++) {\n        this.effects[i].pause();\n      }\n    }\n  }\n  /**\n   * Resumes the effect scope, including all child scopes and effects.\n   */\n  resume() {\n    if (this._active) {\n      if (this._isPaused) {\n        this._isPaused = false;\n        let i, l;\n        if (this.scopes) {\n          for (i = 0, l = this.scopes.length; i < l; i++) {\n            this.scopes[i].resume();\n          }\n        }\n        for (i = 0, l = this.effects.length; i < l; i++) {\n          this.effects[i].resume();\n        }\n      }\n    }\n  }\n  run(fn) {\n    if (this._active) {\n      const currentEffectScope = activeEffectScope;\n      try {\n        activeEffectScope = this;\n        return fn();\n      } finally {\n        activeEffectScope = currentEffectScope;\n      }\n    }\n  }\n  /**\n   * This should only be called on non-detached scopes\n   * @internal\n   */\n  on() {\n    if (++this._on === 1) {\n      this.prevScope = activeEffectScope;\n      activeEffectScope = this;\n    }\n  }\n  /**\n   * This should only be called on non-detached scopes\n   * @internal\n   */\n  off() {\n    if (this._on > 0 && --this._on === 0) {\n      activeEffectScope = this.prevScope;\n      this.prevScope = void 0;\n    }\n  }\n  stop(fromParent) {\n    if (this._active) {\n      this._active = false;\n      let i, l;\n      for (i = 0, l = this.effects.length; i < l; i++) {\n        this.effects[i].stop();\n      }\n      this.effects.length = 0;\n      for (i = 0, l = this.cleanups.length; i < l; i++) {\n        this.cleanups[i]();\n      }\n      this.cleanups.length = 0;\n      if (this.scopes) {\n        for (i = 0, l = this.scopes.length; i < l; i++) {\n          this.scopes[i].stop(true);\n        }\n        this.scopes.length = 0;\n      }\n      if (!this.detached && this.parent && !fromParent) {\n        const last = this.parent.scopes.pop();\n        if (last && last !== this) {\n          this.parent.scopes[this.index] = last;\n          last.index = this.index;\n        }\n      }\n      this.parent = void 0;\n    }\n  }\n}\nfunction effectScope(detached) {\n  return new EffectScope(detached);\n}\nfunction getCurrentScope() {\n  return activeEffectScope;\n}\nfunction onScopeDispose(fn, failSilently = false) {\n  if (activeEffectScope) {\n    activeEffectScope.cleanups.push(fn);\n  }\n}\n\nlet activeSub;\nconst EffectFlags = {\n  \"ACTIVE\": 1,\n  \"1\": \"ACTIVE\",\n  \"RUNNING\": 2,\n  \"2\": \"RUNNING\",\n  \"TRACKING\": 4,\n  \"4\": \"TRACKING\",\n  \"NOTIFIED\": 8,\n  \"8\": \"NOTIFIED\",\n  \"DIRTY\": 16,\n  \"16\": \"DIRTY\",\n  \"ALLOW_RECURSE\": 32,\n  \"32\": \"ALLOW_RECURSE\",\n  \"PAUSED\": 64,\n  \"64\": \"PAUSED\",\n  \"EVALUATED\": 128,\n  \"128\": \"EVALUATED\"\n};\nconst pausedQueueEffects = /* @__PURE__ */ new WeakSet();\nclass ReactiveEffect {\n  constructor(fn) {\n    this.fn = fn;\n    /**\n     * @internal\n     */\n    this.deps = void 0;\n    /**\n     * @internal\n     */\n    this.depsTail = void 0;\n    /**\n     * @internal\n     */\n    this.flags = 1 | 4;\n    /**\n     * @internal\n     */\n    this.next = void 0;\n    /**\n     * @internal\n     */\n    this.cleanup = void 0;\n    this.scheduler = void 0;\n    if (activeEffectScope && activeEffectScope.active) {\n      activeEffectScope.effects.push(this);\n    }\n  }\n  pause() {\n    this.flags |= 64;\n  }\n  resume() {\n    if (this.flags & 64) {\n      this.flags &= -65;\n      if (pausedQueueEffects.has(this)) {\n        pausedQueueEffects.delete(this);\n        this.trigger();\n      }\n    }\n  }\n  /**\n   * @internal\n   */\n  notify() {\n    if (this.flags & 2 && !(this.flags & 32)) {\n      return;\n    }\n    if (!(this.flags & 8)) {\n      batch(this);\n    }\n  }\n  run() {\n    if (!(this.flags & 1)) {\n      return this.fn();\n    }\n    this.flags |= 2;\n    cleanupEffect(this);\n    prepareDeps(this);\n    const prevEffect = activeSub;\n    const prevShouldTrack = shouldTrack;\n    activeSub = this;\n    shouldTrack = true;\n    try {\n      return this.fn();\n    } finally {\n      cleanupDeps(this);\n      activeSub = prevEffect;\n      shouldTrack = prevShouldTrack;\n      this.flags &= -3;\n    }\n  }\n  stop() {\n    if (this.flags & 1) {\n      for (let link = this.deps; link; link = link.nextDep) {\n        removeSub(link);\n      }\n      this.deps = this.depsTail = void 0;\n      cleanupEffect(this);\n      this.onStop && this.onStop();\n      this.flags &= -2;\n    }\n  }\n  trigger() {\n    if (this.flags & 64) {\n      pausedQueueEffects.add(this);\n    } else if (this.scheduler) {\n      this.scheduler();\n    } else {\n      this.runIfDirty();\n    }\n  }\n  /**\n   * @internal\n   */\n  runIfDirty() {\n    if (isDirty(this)) {\n      this.run();\n    }\n  }\n  get dirty() {\n    return isDirty(this);\n  }\n}\nlet batchDepth = 0;\nlet batchedSub;\nlet batchedComputed;\nfunction batch(sub, isComputed = false) {\n  sub.flags |= 8;\n  if (isComputed) {\n    sub.next = batchedComputed;\n    batchedComputed = sub;\n    return;\n  }\n  sub.next = batchedSub;\n  batchedSub = sub;\n}\nfunction startBatch() {\n  batchDepth++;\n}\nfunction endBatch() {\n  if (--batchDepth > 0) {\n    return;\n  }\n  if (batchedComputed) {\n    let e = batchedComputed;\n    batchedComputed = void 0;\n    while (e) {\n      const next = e.next;\n      e.next = void 0;\n      e.flags &= -9;\n      e = next;\n    }\n  }\n  let error;\n  while (batchedSub) {\n    let e = batchedSub;\n    batchedSub = void 0;\n    while (e) {\n      const next = e.next;\n      e.next = void 0;\n      e.flags &= -9;\n      if (e.flags & 1) {\n        try {\n          ;\n          e.trigger();\n        } catch (err) {\n          if (!error) error = err;\n        }\n      }\n      e = next;\n    }\n  }\n  if (error) throw error;\n}\nfunction prepareDeps(sub) {\n  for (let link = sub.deps; link; link = link.nextDep) {\n    link.version = -1;\n    link.prevActiveLink = link.dep.activeLink;\n    link.dep.activeLink = link;\n  }\n}\nfunction cleanupDeps(sub) {\n  let head;\n  let tail = sub.depsTail;\n  let link = tail;\n  while (link) {\n    const prev = link.prevDep;\n    if (link.version === -1) {\n      if (link === tail) tail = prev;\n      removeSub(link);\n      removeDep(link);\n    } else {\n      head = link;\n    }\n    link.dep.activeLink = link.prevActiveLink;\n    link.prevActiveLink = void 0;\n    link = prev;\n  }\n  sub.deps = head;\n  sub.depsTail = tail;\n}\nfunction isDirty(sub) {\n  for (let link = sub.deps; link; link = link.nextDep) {\n    if (link.dep.version !== link.version || link.dep.computed && (refreshComputed(link.dep.computed) || link.dep.version !== link.version)) {\n      return true;\n    }\n  }\n  if (sub._dirty) {\n    return true;\n  }\n  return false;\n}\nfunction refreshComputed(computed) {\n  if (computed.flags & 4 && !(computed.flags & 16)) {\n    return;\n  }\n  computed.flags &= -17;\n  if (computed.globalVersion === globalVersion) {\n    return;\n  }\n  computed.globalVersion = globalVersion;\n  if (!computed.isSSR && computed.flags & 128 && (!computed.deps && !computed._dirty || !isDirty(computed))) {\n    return;\n  }\n  computed.flags |= 2;\n  const dep = computed.dep;\n  const prevSub = activeSub;\n  const prevShouldTrack = shouldTrack;\n  activeSub = computed;\n  shouldTrack = true;\n  try {\n    prepareDeps(computed);\n    const value = computed.fn(computed._value);\n    if (dep.version === 0 || shared.hasChanged(value, computed._value)) {\n      computed.flags |= 128;\n      computed._value = value;\n      dep.version++;\n    }\n  } catch (err) {\n    dep.version++;\n    throw err;\n  } finally {\n    activeSub = prevSub;\n    shouldTrack = prevShouldTrack;\n    cleanupDeps(computed);\n    computed.flags &= -3;\n  }\n}\nfunction removeSub(link, soft = false) {\n  const { dep, prevSub, nextSub } = link;\n  if (prevSub) {\n    prevSub.nextSub = nextSub;\n    link.prevSub = void 0;\n  }\n  if (nextSub) {\n    nextSub.prevSub = prevSub;\n    link.nextSub = void 0;\n  }\n  if (dep.subs === link) {\n    dep.subs = prevSub;\n    if (!prevSub && dep.computed) {\n      dep.computed.flags &= -5;\n      for (let l = dep.computed.deps; l; l = l.nextDep) {\n        removeSub(l, true);\n      }\n    }\n  }\n  if (!soft && !--dep.sc && dep.map) {\n    dep.map.delete(dep.key);\n  }\n}\nfunction removeDep(link) {\n  const { prevDep, nextDep } = link;\n  if (prevDep) {\n    prevDep.nextDep = nextDep;\n    link.prevDep = void 0;\n  }\n  if (nextDep) {\n    nextDep.prevDep = prevDep;\n    link.nextDep = void 0;\n  }\n}\nfunction effect(fn, options) {\n  if (fn.effect instanceof ReactiveEffect) {\n    fn = fn.effect.fn;\n  }\n  const e = new ReactiveEffect(fn);\n  if (options) {\n    shared.extend(e, options);\n  }\n  try {\n    e.run();\n  } catch (err) {\n    e.stop();\n    throw err;\n  }\n  const runner = e.run.bind(e);\n  runner.effect = e;\n  return runner;\n}\nfunction stop(runner) {\n  runner.effect.stop();\n}\nlet shouldTrack = true;\nconst trackStack = [];\nfunction pauseTracking() {\n  trackStack.push(shouldTrack);\n  shouldTrack = false;\n}\nfunction enableTracking() {\n  trackStack.push(shouldTrack);\n  shouldTrack = true;\n}\nfunction resetTracking() {\n  const last = trackStack.pop();\n  shouldTrack = last === void 0 ? true : last;\n}\nfunction onEffectCleanup(fn, failSilently = false) {\n  if (activeSub instanceof ReactiveEffect) {\n    activeSub.cleanup = fn;\n  }\n}\nfunction cleanupEffect(e) {\n  const { cleanup } = e;\n  e.cleanup = void 0;\n  if (cleanup) {\n    const prevSub = activeSub;\n    activeSub = void 0;\n    try {\n      cleanup();\n    } finally {\n      activeSub = prevSub;\n    }\n  }\n}\n\nlet globalVersion = 0;\nclass Link {\n  constructor(sub, dep) {\n    this.sub = sub;\n    this.dep = dep;\n    this.version = dep.version;\n    this.nextDep = this.prevDep = this.nextSub = this.prevSub = this.prevActiveLink = void 0;\n  }\n}\nclass Dep {\n  // TODO isolatedDeclarations \"__v_skip\"\n  constructor(computed) {\n    this.computed = computed;\n    this.version = 0;\n    /**\n     * Link between this dep and the current active effect\n     */\n    this.activeLink = void 0;\n    /**\n     * Doubly linked list representing the subscribing effects (tail)\n     */\n    this.subs = void 0;\n    /**\n     * For object property deps cleanup\n     */\n    this.map = void 0;\n    this.key = void 0;\n    /**\n     * Subscriber counter\n     */\n    this.sc = 0;\n    /**\n     * @internal\n     */\n    this.__v_skip = true;\n  }\n  track(debugInfo) {\n    if (!activeSub || !shouldTrack || activeSub === this.computed) {\n      return;\n    }\n    let link = this.activeLink;\n    if (link === void 0 || link.sub !== activeSub) {\n      link = this.activeLink = new Link(activeSub, this);\n      if (!activeSub.deps) {\n        activeSub.deps = activeSub.depsTail = link;\n      } else {\n        link.prevDep = activeSub.depsTail;\n        activeSub.depsTail.nextDep = link;\n        activeSub.depsTail = link;\n      }\n      addSub(link);\n    } else if (link.version === -1) {\n      link.version = this.version;\n      if (link.nextDep) {\n        const next = link.nextDep;\n        next.prevDep = link.prevDep;\n        if (link.prevDep) {\n          link.prevDep.nextDep = next;\n        }\n        link.prevDep = activeSub.depsTail;\n        link.nextDep = void 0;\n        activeSub.depsTail.nextDep = link;\n        activeSub.depsTail = link;\n        if (activeSub.deps === link) {\n          activeSub.deps = next;\n        }\n      }\n    }\n    return link;\n  }\n  trigger(debugInfo) {\n    this.version++;\n    globalVersion++;\n    this.notify(debugInfo);\n  }\n  notify(debugInfo) {\n    startBatch();\n    try {\n      if (false) ;\n      for (let link = this.subs; link; link = link.prevSub) {\n        if (link.sub.notify()) {\n          ;\n          link.sub.dep.notify();\n        }\n      }\n    } finally {\n      endBatch();\n    }\n  }\n}\nfunction addSub(link) {\n  link.dep.sc++;\n  if (link.sub.flags & 4) {\n    const computed = link.dep.computed;\n    if (computed && !link.dep.subs) {\n      computed.flags |= 4 | 16;\n      for (let l = computed.deps; l; l = l.nextDep) {\n        addSub(l);\n      }\n    }\n    const currentTail = link.dep.subs;\n    if (currentTail !== link) {\n      link.prevSub = currentTail;\n      if (currentTail) currentTail.nextSub = link;\n    }\n    link.dep.subs = link;\n  }\n}\nconst targetMap = /* @__PURE__ */ new WeakMap();\nconst ITERATE_KEY = Symbol(\n  \"\"\n);\nconst MAP_KEY_ITERATE_KEY = Symbol(\n  \"\"\n);\nconst ARRAY_ITERATE_KEY = Symbol(\n  \"\"\n);\nfunction track(target, type, key) {\n  if (shouldTrack && activeSub) {\n    let depsMap = targetMap.get(target);\n    if (!depsMap) {\n      targetMap.set(target, depsMap = /* @__PURE__ */ new Map());\n    }\n    let dep = depsMap.get(key);\n    if (!dep) {\n      depsMap.set(key, dep = new Dep());\n      dep.map = depsMap;\n      dep.key = key;\n    }\n    {\n      dep.track();\n    }\n  }\n}\nfunction trigger(target, type, key, newValue, oldValue, oldTarget) {\n  const depsMap = targetMap.get(target);\n  if (!depsMap) {\n    globalVersion++;\n    return;\n  }\n  const run = (dep) => {\n    if (dep) {\n      {\n        dep.trigger();\n      }\n    }\n  };\n  startBatch();\n  if (type === \"clear\") {\n    depsMap.forEach(run);\n  } else {\n    const targetIsArray = shared.isArray(target);\n    const isArrayIndex = targetIsArray && shared.isIntegerKey(key);\n    if (targetIsArray && key === \"length\") {\n      const newLength = Number(newValue);\n      depsMap.forEach((dep, key2) => {\n        if (key2 === \"length\" || key2 === ARRAY_ITERATE_KEY || !shared.isSymbol(key2) && key2 >= newLength) {\n          run(dep);\n        }\n      });\n    } else {\n      if (key !== void 0 || depsMap.has(void 0)) {\n        run(depsMap.get(key));\n      }\n      if (isArrayIndex) {\n        run(depsMap.get(ARRAY_ITERATE_KEY));\n      }\n      switch (type) {\n        case \"add\":\n          if (!targetIsArray) {\n            run(depsMap.get(ITERATE_KEY));\n            if (shared.isMap(target)) {\n              run(depsMap.get(MAP_KEY_ITERATE_KEY));\n            }\n          } else if (isArrayIndex) {\n            run(depsMap.get(\"length\"));\n          }\n          break;\n        case \"delete\":\n          if (!targetIsArray) {\n            run(depsMap.get(ITERATE_KEY));\n            if (shared.isMap(target)) {\n              run(depsMap.get(MAP_KEY_ITERATE_KEY));\n            }\n          }\n          break;\n        case \"set\":\n          if (shared.isMap(target)) {\n            run(depsMap.get(ITERATE_KEY));\n          }\n          break;\n      }\n    }\n  }\n  endBatch();\n}\nfunction getDepFromReactive(object, key) {\n  const depMap = targetMap.get(object);\n  return depMap && depMap.get(key);\n}\n\nfunction reactiveReadArray(array) {\n  const raw = toRaw(array);\n  if (raw === array) return raw;\n  track(raw, \"iterate\", ARRAY_ITERATE_KEY);\n  return isShallow(array) ? raw : raw.map(toReactive);\n}\nfunction shallowReadArray(arr) {\n  track(arr = toRaw(arr), \"iterate\", ARRAY_ITERATE_KEY);\n  return arr;\n}\nconst arrayInstrumentations = {\n  __proto__: null,\n  [Symbol.iterator]() {\n    return iterator(this, Symbol.iterator, toReactive);\n  },\n  concat(...args) {\n    return reactiveReadArray(this).concat(\n      ...args.map((x) => shared.isArray(x) ? reactiveReadArray(x) : x)\n    );\n  },\n  entries() {\n    return iterator(this, \"entries\", (value) => {\n      value[1] = toReactive(value[1]);\n      return value;\n    });\n  },\n  every(fn, thisArg) {\n    return apply(this, \"every\", fn, thisArg, void 0, arguments);\n  },\n  filter(fn, thisArg) {\n    return apply(this, \"filter\", fn, thisArg, (v) => v.map(toReactive), arguments);\n  },\n  find(fn, thisArg) {\n    return apply(this, \"find\", fn, thisArg, toReactive, arguments);\n  },\n  findIndex(fn, thisArg) {\n    return apply(this, \"findIndex\", fn, thisArg, void 0, arguments);\n  },\n  findLast(fn, thisArg) {\n    return apply(this, \"findLast\", fn, thisArg, toReactive, arguments);\n  },\n  findLastIndex(fn, thisArg) {\n    return apply(this, \"findLastIndex\", fn, thisArg, void 0, arguments);\n  },\n  // flat, flatMap could benefit from ARRAY_ITERATE but are not straight-forward to implement\n  forEach(fn, thisArg) {\n    return apply(this, \"forEach\", fn, thisArg, void 0, arguments);\n  },\n  includes(...args) {\n    return searchProxy(this, \"includes\", args);\n  },\n  indexOf(...args) {\n    return searchProxy(this, \"indexOf\", args);\n  },\n  join(separator) {\n    return reactiveReadArray(this).join(separator);\n  },\n  // keys() iterator only reads `length`, no optimisation required\n  lastIndexOf(...args) {\n    return searchProxy(this, \"lastIndexOf\", args);\n  },\n  map(fn, thisArg) {\n    return apply(this, \"map\", fn, thisArg, void 0, arguments);\n  },\n  pop() {\n    return noTracking(this, \"pop\");\n  },\n  push(...args) {\n    return noTracking(this, \"push\", args);\n  },\n  reduce(fn, ...args) {\n    return reduce(this, \"reduce\", fn, args);\n  },\n  reduceRight(fn, ...args) {\n    return reduce(this, \"reduceRight\", fn, args);\n  },\n  shift() {\n    return noTracking(this, \"shift\");\n  },\n  // slice could use ARRAY_ITERATE but also seems to beg for range tracking\n  some(fn, thisArg) {\n    return apply(this, \"some\", fn, thisArg, void 0, arguments);\n  },\n  splice(...args) {\n    return noTracking(this, \"splice\", args);\n  },\n  toReversed() {\n    return reactiveReadArray(this).toReversed();\n  },\n  toSorted(comparer) {\n    return reactiveReadArray(this).toSorted(comparer);\n  },\n  toSpliced(...args) {\n    return reactiveReadArray(this).toSpliced(...args);\n  },\n  unshift(...args) {\n    return noTracking(this, \"unshift\", args);\n  },\n  values() {\n    return iterator(this, \"values\", toReactive);\n  }\n};\nfunction iterator(self, method, wrapValue) {\n  const arr = shallowReadArray(self);\n  const iter = arr[method]();\n  if (arr !== self && !isShallow(self)) {\n    iter._next = iter.next;\n    iter.next = () => {\n      const result = iter._next();\n      if (result.value) {\n        result.value = wrapValue(result.value);\n      }\n      return result;\n    };\n  }\n  return iter;\n}\nconst arrayProto = Array.prototype;\nfunction apply(self, method, fn, thisArg, wrappedRetFn, args) {\n  const arr = shallowReadArray(self);\n  const needsWrap = arr !== self && !isShallow(self);\n  const methodFn = arr[method];\n  if (methodFn !== arrayProto[method]) {\n    const result2 = methodFn.apply(self, args);\n    return needsWrap ? toReactive(result2) : result2;\n  }\n  let wrappedFn = fn;\n  if (arr !== self) {\n    if (needsWrap) {\n      wrappedFn = function(item, index) {\n        return fn.call(this, toReactive(item), index, self);\n      };\n    } else if (fn.length > 2) {\n      wrappedFn = function(item, index) {\n        return fn.call(this, item, index, self);\n      };\n    }\n  }\n  const result = methodFn.call(arr, wrappedFn, thisArg);\n  return needsWrap && wrappedRetFn ? wrappedRetFn(result) : result;\n}\nfunction reduce(self, method, fn, args) {\n  const arr = shallowReadArray(self);\n  let wrappedFn = fn;\n  if (arr !== self) {\n    if (!isShallow(self)) {\n      wrappedFn = function(acc, item, index) {\n        return fn.call(this, acc, toReactive(item), index, self);\n      };\n    } else if (fn.length > 3) {\n      wrappedFn = function(acc, item, index) {\n        return fn.call(this, acc, item, index, self);\n      };\n    }\n  }\n  return arr[method](wrappedFn, ...args);\n}\nfunction searchProxy(self, method, args) {\n  const arr = toRaw(self);\n  track(arr, \"iterate\", ARRAY_ITERATE_KEY);\n  const res = arr[method](...args);\n  if ((res === -1 || res === false) && isProxy(args[0])) {\n    args[0] = toRaw(args[0]);\n    return arr[method](...args);\n  }\n  return res;\n}\nfunction noTracking(self, method, args = []) {\n  pauseTracking();\n  startBatch();\n  const res = toRaw(self)[method].apply(self, args);\n  endBatch();\n  resetTracking();\n  return res;\n}\n\nconst isNonTrackableKeys = /* @__PURE__ */ shared.makeMap(`__proto__,__v_isRef,__isVue`);\nconst builtInSymbols = new Set(\n  /* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== \"arguments\" && key !== \"caller\").map((key) => Symbol[key]).filter(shared.isSymbol)\n);\nfunction hasOwnProperty(key) {\n  if (!shared.isSymbol(key)) key = String(key);\n  const obj = toRaw(this);\n  track(obj, \"has\", key);\n  return obj.hasOwnProperty(key);\n}\nclass BaseReactiveHandler {\n  constructor(_isReadonly = false, _isShallow = false) {\n    this._isReadonly = _isReadonly;\n    this._isShallow = _isShallow;\n  }\n  get(target, key, receiver) {\n    if (key === \"__v_skip\") return target[\"__v_skip\"];\n    const isReadonly2 = this._isReadonly, isShallow2 = this._isShallow;\n    if (key === \"__v_isReactive\") {\n      return !isReadonly2;\n    } else if (key === \"__v_isReadonly\") {\n      return isReadonly2;\n    } else if (key === \"__v_isShallow\") {\n      return isShallow2;\n    } else if (key === \"__v_raw\") {\n      if (receiver === (isReadonly2 ? isShallow2 ? shallowReadonlyMap : readonlyMap : isShallow2 ? shallowReactiveMap : reactiveMap).get(target) || // receiver is not the reactive proxy, but has the same prototype\n      // this means the receiver is a user proxy of the reactive proxy\n      Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) {\n        return target;\n      }\n      return;\n    }\n    const targetIsArray = shared.isArray(target);\n    if (!isReadonly2) {\n      let fn;\n      if (targetIsArray && (fn = arrayInstrumentations[key])) {\n        return fn;\n      }\n      if (key === \"hasOwnProperty\") {\n        return hasOwnProperty;\n      }\n    }\n    const res = Reflect.get(\n      target,\n      key,\n      // if this is a proxy wrapping a ref, return methods using the raw ref\n      // as receiver so that we don't have to call `toRaw` on the ref in all\n      // its class methods\n      isRef(target) ? target : receiver\n    );\n    if (shared.isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {\n      return res;\n    }\n    if (!isReadonly2) {\n      track(target, \"get\", key);\n    }\n    if (isShallow2) {\n      return res;\n    }\n    if (isRef(res)) {\n      return targetIsArray && shared.isIntegerKey(key) ? res : res.value;\n    }\n    if (shared.isObject(res)) {\n      return isReadonly2 ? readonly(res) : reactive(res);\n    }\n    return res;\n  }\n}\nclass MutableReactiveHandler extends BaseReactiveHandler {\n  constructor(isShallow2 = false) {\n    super(false, isShallow2);\n  }\n  set(target, key, value, receiver) {\n    let oldValue = target[key];\n    if (!this._isShallow) {\n      const isOldValueReadonly = isReadonly(oldValue);\n      if (!isShallow(value) && !isReadonly(value)) {\n        oldValue = toRaw(oldValue);\n        value = toRaw(value);\n      }\n      if (!shared.isArray(target) && isRef(oldValue) && !isRef(value)) {\n        if (isOldValueReadonly) {\n          return false;\n        } else {\n          oldValue.value = value;\n          return true;\n        }\n      }\n    }\n    const hadKey = shared.isArray(target) && shared.isIntegerKey(key) ? Number(key) < target.length : shared.hasOwn(target, key);\n    const result = Reflect.set(\n      target,\n      key,\n      value,\n      isRef(target) ? target : receiver\n    );\n    if (target === toRaw(receiver)) {\n      if (!hadKey) {\n        trigger(target, \"add\", key, value);\n      } else if (shared.hasChanged(value, oldValue)) {\n        trigger(target, \"set\", key, value);\n      }\n    }\n    return result;\n  }\n  deleteProperty(target, key) {\n    const hadKey = shared.hasOwn(target, key);\n    target[key];\n    const result = Reflect.deleteProperty(target, key);\n    if (result && hadKey) {\n      trigger(target, \"delete\", key, void 0);\n    }\n    return result;\n  }\n  has(target, key) {\n    const result = Reflect.has(target, key);\n    if (!shared.isSymbol(key) || !builtInSymbols.has(key)) {\n      track(target, \"has\", key);\n    }\n    return result;\n  }\n  ownKeys(target) {\n    track(\n      target,\n      \"iterate\",\n      shared.isArray(target) ? \"length\" : ITERATE_KEY\n    );\n    return Reflect.ownKeys(target);\n  }\n}\nclass ReadonlyReactiveHandler extends BaseReactiveHandler {\n  constructor(isShallow2 = false) {\n    super(true, isShallow2);\n  }\n  set(target, key) {\n    return true;\n  }\n  deleteProperty(target, key) {\n    return true;\n  }\n}\nconst mutableHandlers = /* @__PURE__ */ new MutableReactiveHandler();\nconst readonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler();\nconst shallowReactiveHandlers = /* @__PURE__ */ new MutableReactiveHandler(true);\nconst shallowReadonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(true);\n\nconst toShallow = (value) => value;\nconst getProto = (v) => Reflect.getPrototypeOf(v);\nfunction createIterableMethod(method, isReadonly2, isShallow2) {\n  return function(...args) {\n    const target = this[\"__v_raw\"];\n    const rawTarget = toRaw(target);\n    const targetIsMap = shared.isMap(rawTarget);\n    const isPair = method === \"entries\" || method === Symbol.iterator && targetIsMap;\n    const isKeyOnly = method === \"keys\" && targetIsMap;\n    const innerIterator = target[method](...args);\n    const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive;\n    !isReadonly2 && track(\n      rawTarget,\n      \"iterate\",\n      isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY\n    );\n    return {\n      // iterator protocol\n      next() {\n        const { value, done } = innerIterator.next();\n        return done ? { value, done } : {\n          value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),\n          done\n        };\n      },\n      // iterable protocol\n      [Symbol.iterator]() {\n        return this;\n      }\n    };\n  };\n}\nfunction createReadonlyMethod(type) {\n  return function(...args) {\n    return type === \"delete\" ? false : type === \"clear\" ? void 0 : this;\n  };\n}\nfunction createInstrumentations(readonly, shallow) {\n  const instrumentations = {\n    get(key) {\n      const target = this[\"__v_raw\"];\n      const rawTarget = toRaw(target);\n      const rawKey = toRaw(key);\n      if (!readonly) {\n        if (shared.hasChanged(key, rawKey)) {\n          track(rawTarget, \"get\", key);\n        }\n        track(rawTarget, \"get\", rawKey);\n      }\n      const { has } = getProto(rawTarget);\n      const wrap = shallow ? toShallow : readonly ? toReadonly : toReactive;\n      if (has.call(rawTarget, key)) {\n        return wrap(target.get(key));\n      } else if (has.call(rawTarget, rawKey)) {\n        return wrap(target.get(rawKey));\n      } else if (target !== rawTarget) {\n        target.get(key);\n      }\n    },\n    get size() {\n      const target = this[\"__v_raw\"];\n      !readonly && track(toRaw(target), \"iterate\", ITERATE_KEY);\n      return Reflect.get(target, \"size\", target);\n    },\n    has(key) {\n      const target = this[\"__v_raw\"];\n      const rawTarget = toRaw(target);\n      const rawKey = toRaw(key);\n      if (!readonly) {\n        if (shared.hasChanged(key, rawKey)) {\n          track(rawTarget, \"has\", key);\n        }\n        track(rawTarget, \"has\", rawKey);\n      }\n      return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey);\n    },\n    forEach(callback, thisArg) {\n      const observed = this;\n      const target = observed[\"__v_raw\"];\n      const rawTarget = toRaw(target);\n      const wrap = shallow ? toShallow : readonly ? toReadonly : toReactive;\n      !readonly && track(rawTarget, \"iterate\", ITERATE_KEY);\n      return target.forEach((value, key) => {\n        return callback.call(thisArg, wrap(value), wrap(key), observed);\n      });\n    }\n  };\n  shared.extend(\n    instrumentations,\n    readonly ? {\n      add: createReadonlyMethod(\"add\"),\n      set: createReadonlyMethod(\"set\"),\n      delete: createReadonlyMethod(\"delete\"),\n      clear: createReadonlyMethod(\"clear\")\n    } : {\n      add(value) {\n        if (!shallow && !isShallow(value) && !isReadonly(value)) {\n          value = toRaw(value);\n        }\n        const target = toRaw(this);\n        const proto = getProto(target);\n        const hadKey = proto.has.call(target, value);\n        if (!hadKey) {\n          target.add(value);\n          trigger(target, \"add\", value, value);\n        }\n        return this;\n      },\n      set(key, value) {\n        if (!shallow && !isShallow(value) && !isReadonly(value)) {\n          value = toRaw(value);\n        }\n        const target = toRaw(this);\n        const { has, get } = getProto(target);\n        let hadKey = has.call(target, key);\n        if (!hadKey) {\n          key = toRaw(key);\n          hadKey = has.call(target, key);\n        }\n        const oldValue = get.call(target, key);\n        target.set(key, value);\n        if (!hadKey) {\n          trigger(target, \"add\", key, value);\n        } else if (shared.hasChanged(value, oldValue)) {\n          trigger(target, \"set\", key, value);\n        }\n        return this;\n      },\n      delete(key) {\n        const target = toRaw(this);\n        const { has, get } = getProto(target);\n        let hadKey = has.call(target, key);\n        if (!hadKey) {\n          key = toRaw(key);\n          hadKey = has.call(target, key);\n        }\n        get ? get.call(target, key) : void 0;\n        const result = target.delete(key);\n        if (hadKey) {\n          trigger(target, \"delete\", key, void 0);\n        }\n        return result;\n      },\n      clear() {\n        const target = toRaw(this);\n        const hadItems = target.size !== 0;\n        const result = target.clear();\n        if (hadItems) {\n          trigger(\n            target,\n            \"clear\",\n            void 0,\n            void 0);\n        }\n        return result;\n      }\n    }\n  );\n  const iteratorMethods = [\n    \"keys\",\n    \"values\",\n    \"entries\",\n    Symbol.iterator\n  ];\n  iteratorMethods.forEach((method) => {\n    instrumentations[method] = createIterableMethod(method, readonly, shallow);\n  });\n  return instrumentations;\n}\nfunction createInstrumentationGetter(isReadonly2, shallow) {\n  const instrumentations = createInstrumentations(isReadonly2, shallow);\n  return (target, key, receiver) => {\n    if (key === \"__v_isReactive\") {\n      return !isReadonly2;\n    } else if (key === \"__v_isReadonly\") {\n      return isReadonly2;\n    } else if (key === \"__v_raw\") {\n      return target;\n    }\n    return Reflect.get(\n      shared.hasOwn(instrumentations, key) && key in target ? instrumentations : target,\n      key,\n      receiver\n    );\n  };\n}\nconst mutableCollectionHandlers = {\n  get: /* @__PURE__ */ createInstrumentationGetter(false, false)\n};\nconst shallowCollectionHandlers = {\n  get: /* @__PURE__ */ createInstrumentationGetter(false, true)\n};\nconst readonlyCollectionHandlers = {\n  get: /* @__PURE__ */ createInstrumentationGetter(true, false)\n};\nconst shallowReadonlyCollectionHandlers = {\n  get: /* @__PURE__ */ createInstrumentationGetter(true, true)\n};\n\nconst reactiveMap = /* @__PURE__ */ new WeakMap();\nconst shallowReactiveMap = /* @__PURE__ */ new WeakMap();\nconst readonlyMap = /* @__PURE__ */ new WeakMap();\nconst shallowReadonlyMap = /* @__PURE__ */ new WeakMap();\nfunction targetTypeMap(rawType) {\n  switch (rawType) {\n    case \"Object\":\n    case \"Array\":\n      return 1 /* COMMON */;\n    case \"Map\":\n    case \"Set\":\n    case \"WeakMap\":\n    case \"WeakSet\":\n      return 2 /* COLLECTION */;\n    default:\n      return 0 /* INVALID */;\n  }\n}\nfunction getTargetType(value) {\n  return value[\"__v_skip\"] || !Object.isExtensible(value) ? 0 /* INVALID */ : targetTypeMap(shared.toRawType(value));\n}\nfunction reactive(target) {\n  if (isReadonly(target)) {\n    return target;\n  }\n  return createReactiveObject(\n    target,\n    false,\n    mutableHandlers,\n    mutableCollectionHandlers,\n    reactiveMap\n  );\n}\nfunction shallowReactive(target) {\n  return createReactiveObject(\n    target,\n    false,\n    shallowReactiveHandlers,\n    shallowCollectionHandlers,\n    shallowReactiveMap\n  );\n}\nfunction readonly(target) {\n  return createReactiveObject(\n    target,\n    true,\n    readonlyHandlers,\n    readonlyCollectionHandlers,\n    readonlyMap\n  );\n}\nfunction shallowReadonly(target) {\n  return createReactiveObject(\n    target,\n    true,\n    shallowReadonlyHandlers,\n    shallowReadonlyCollectionHandlers,\n    shallowReadonlyMap\n  );\n}\nfunction createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) {\n  if (!shared.isObject(target)) {\n    return target;\n  }\n  if (target[\"__v_raw\"] && !(isReadonly2 && target[\"__v_isReactive\"])) {\n    return target;\n  }\n  const targetType = getTargetType(target);\n  if (targetType === 0 /* INVALID */) {\n    return target;\n  }\n  const existingProxy = proxyMap.get(target);\n  if (existingProxy) {\n    return existingProxy;\n  }\n  const proxy = new Proxy(\n    target,\n    targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers\n  );\n  proxyMap.set(target, proxy);\n  return proxy;\n}\nfunction isReactive(value) {\n  if (isReadonly(value)) {\n    return isReactive(value[\"__v_raw\"]);\n  }\n  return !!(value && value[\"__v_isReactive\"]);\n}\nfunction isReadonly(value) {\n  return !!(value && value[\"__v_isReadonly\"]);\n}\nfunction isShallow(value) {\n  return !!(value && value[\"__v_isShallow\"]);\n}\nfunction isProxy(value) {\n  return value ? !!value[\"__v_raw\"] : false;\n}\nfunction toRaw(observed) {\n  const raw = observed && observed[\"__v_raw\"];\n  return raw ? toRaw(raw) : observed;\n}\nfunction markRaw(value) {\n  if (!shared.hasOwn(value, \"__v_skip\") && Object.isExtensible(value)) {\n    shared.def(value, \"__v_skip\", true);\n  }\n  return value;\n}\nconst toReactive = (value) => shared.isObject(value) ? reactive(value) : value;\nconst toReadonly = (value) => shared.isObject(value) ? readonly(value) : value;\n\nfunction isRef(r) {\n  return r ? r[\"__v_isRef\"] === true : false;\n}\nfunction ref(value) {\n  return createRef(value, false);\n}\nfunction shallowRef(value) {\n  return createRef(value, true);\n}\nfunction createRef(rawValue, shallow) {\n  if (isRef(rawValue)) {\n    return rawValue;\n  }\n  return new RefImpl(rawValue, shallow);\n}\nclass RefImpl {\n  constructor(value, isShallow2) {\n    this.dep = new Dep();\n    this[\"__v_isRef\"] = true;\n    this[\"__v_isShallow\"] = false;\n    this._rawValue = isShallow2 ? value : toRaw(value);\n    this._value = isShallow2 ? value : toReactive(value);\n    this[\"__v_isShallow\"] = isShallow2;\n  }\n  get value() {\n    {\n      this.dep.track();\n    }\n    return this._value;\n  }\n  set value(newValue) {\n    const oldValue = this._rawValue;\n    const useDirectValue = this[\"__v_isShallow\"] || isShallow(newValue) || isReadonly(newValue);\n    newValue = useDirectValue ? newValue : toRaw(newValue);\n    if (shared.hasChanged(newValue, oldValue)) {\n      this._rawValue = newValue;\n      this._value = useDirectValue ? newValue : toReactive(newValue);\n      {\n        this.dep.trigger();\n      }\n    }\n  }\n}\nfunction triggerRef(ref2) {\n  if (ref2.dep) {\n    {\n      ref2.dep.trigger();\n    }\n  }\n}\nfunction unref(ref2) {\n  return isRef(ref2) ? ref2.value : ref2;\n}\nfunction toValue(source) {\n  return shared.isFunction(source) ? source() : unref(source);\n}\nconst shallowUnwrapHandlers = {\n  get: (target, key, receiver) => key === \"__v_raw\" ? target : unref(Reflect.get(target, key, receiver)),\n  set: (target, key, value, receiver) => {\n    const oldValue = target[key];\n    if (isRef(oldValue) && !isRef(value)) {\n      oldValue.value = value;\n      return true;\n    } else {\n      return Reflect.set(target, key, value, receiver);\n    }\n  }\n};\nfunction proxyRefs(objectWithRefs) {\n  return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers);\n}\nclass CustomRefImpl {\n  constructor(factory) {\n    this[\"__v_isRef\"] = true;\n    this._value = void 0;\n    const dep = this.dep = new Dep();\n    const { get, set } = factory(dep.track.bind(dep), dep.trigger.bind(dep));\n    this._get = get;\n    this._set = set;\n  }\n  get value() {\n    return this._value = this._get();\n  }\n  set value(newVal) {\n    this._set(newVal);\n  }\n}\nfunction customRef(factory) {\n  return new CustomRefImpl(factory);\n}\nfunction toRefs(object) {\n  const ret = shared.isArray(object) ? new Array(object.length) : {};\n  for (const key in object) {\n    ret[key] = propertyToRef(object, key);\n  }\n  return ret;\n}\nclass ObjectRefImpl {\n  constructor(_object, _key, _defaultValue) {\n    this._object = _object;\n    this._key = _key;\n    this._defaultValue = _defaultValue;\n    this[\"__v_isRef\"] = true;\n    this._value = void 0;\n  }\n  get value() {\n    const val = this._object[this._key];\n    return this._value = val === void 0 ? this._defaultValue : val;\n  }\n  set value(newVal) {\n    this._object[this._key] = newVal;\n  }\n  get dep() {\n    return getDepFromReactive(toRaw(this._object), this._key);\n  }\n}\nclass GetterRefImpl {\n  constructor(_getter) {\n    this._getter = _getter;\n    this[\"__v_isRef\"] = true;\n    this[\"__v_isReadonly\"] = true;\n    this._value = void 0;\n  }\n  get value() {\n    return this._value = this._getter();\n  }\n}\nfunction toRef(source, key, defaultValue) {\n  if (isRef(source)) {\n    return source;\n  } else if (shared.isFunction(source)) {\n    return new GetterRefImpl(source);\n  } else if (shared.isObject(source) && arguments.length > 1) {\n    return propertyToRef(source, key, defaultValue);\n  } else {\n    return ref(source);\n  }\n}\nfunction propertyToRef(source, key, defaultValue) {\n  const val = source[key];\n  return isRef(val) ? val : new ObjectRefImpl(source, key, defaultValue);\n}\n\nclass ComputedRefImpl {\n  constructor(fn, setter, isSSR) {\n    this.fn = fn;\n    this.setter = setter;\n    /**\n     * @internal\n     */\n    this._value = void 0;\n    /**\n     * @internal\n     */\n    this.dep = new Dep(this);\n    /**\n     * @internal\n     */\n    this.__v_isRef = true;\n    // TODO isolatedDeclarations \"__v_isReadonly\"\n    // A computed is also a subscriber that tracks other deps\n    /**\n     * @internal\n     */\n    this.deps = void 0;\n    /**\n     * @internal\n     */\n    this.depsTail = void 0;\n    /**\n     * @internal\n     */\n    this.flags = 16;\n    /**\n     * @internal\n     */\n    this.globalVersion = globalVersion - 1;\n    /**\n     * @internal\n     */\n    this.next = void 0;\n    // for backwards compat\n    this.effect = this;\n    this[\"__v_isReadonly\"] = !setter;\n    this.isSSR = isSSR;\n  }\n  /**\n   * @internal\n   */\n  notify() {\n    this.flags |= 16;\n    if (!(this.flags & 8) && // avoid infinite self recursion\n    activeSub !== this) {\n      batch(this, true);\n      return true;\n    }\n  }\n  get value() {\n    const link = this.dep.track();\n    refreshComputed(this);\n    if (link) {\n      link.version = this.dep.version;\n    }\n    return this._value;\n  }\n  set value(newValue) {\n    if (this.setter) {\n      this.setter(newValue);\n    }\n  }\n}\nfunction computed(getterOrOptions, debugOptions, isSSR = false) {\n  let getter;\n  let setter;\n  if (shared.isFunction(getterOrOptions)) {\n    getter = getterOrOptions;\n  } else {\n    getter = getterOrOptions.get;\n    setter = getterOrOptions.set;\n  }\n  const cRef = new ComputedRefImpl(getter, setter, isSSR);\n  return cRef;\n}\n\nconst TrackOpTypes = {\n  \"GET\": \"get\",\n  \"HAS\": \"has\",\n  \"ITERATE\": \"iterate\"\n};\nconst TriggerOpTypes = {\n  \"SET\": \"set\",\n  \"ADD\": \"add\",\n  \"DELETE\": \"delete\",\n  \"CLEAR\": \"clear\"\n};\nconst ReactiveFlags = {\n  \"SKIP\": \"__v_skip\",\n  \"IS_REACTIVE\": \"__v_isReactive\",\n  \"IS_READONLY\": \"__v_isReadonly\",\n  \"IS_SHALLOW\": \"__v_isShallow\",\n  \"RAW\": \"__v_raw\",\n  \"IS_REF\": \"__v_isRef\"\n};\n\nconst WatchErrorCodes = {\n  \"WATCH_GETTER\": 2,\n  \"2\": \"WATCH_GETTER\",\n  \"WATCH_CALLBACK\": 3,\n  \"3\": \"WATCH_CALLBACK\",\n  \"WATCH_CLEANUP\": 4,\n  \"4\": \"WATCH_CLEANUP\"\n};\nconst INITIAL_WATCHER_VALUE = {};\nconst cleanupMap = /* @__PURE__ */ new WeakMap();\nlet activeWatcher = void 0;\nfunction getCurrentWatcher() {\n  return activeWatcher;\n}\nfunction onWatcherCleanup(cleanupFn, failSilently = false, owner = activeWatcher) {\n  if (owner) {\n    let cleanups = cleanupMap.get(owner);\n    if (!cleanups) cleanupMap.set(owner, cleanups = []);\n    cleanups.push(cleanupFn);\n  }\n}\nfunction watch(source, cb, options = shared.EMPTY_OBJ) {\n  const { immediate, deep, once, scheduler, augmentJob, call } = options;\n  const reactiveGetter = (source2) => {\n    if (deep) return source2;\n    if (isShallow(source2) || deep === false || deep === 0)\n      return traverse(source2, 1);\n    return traverse(source2);\n  };\n  let effect;\n  let getter;\n  let cleanup;\n  let boundCleanup;\n  let forceTrigger = false;\n  let isMultiSource = false;\n  if (isRef(source)) {\n    getter = () => source.value;\n    forceTrigger = isShallow(source);\n  } else if (isReactive(source)) {\n    getter = () => reactiveGetter(source);\n    forceTrigger = true;\n  } else if (shared.isArray(source)) {\n    isMultiSource = true;\n    forceTrigger = source.some((s) => isReactive(s) || isShallow(s));\n    getter = () => source.map((s) => {\n      if (isRef(s)) {\n        return s.value;\n      } else if (isReactive(s)) {\n        return reactiveGetter(s);\n      } else if (shared.isFunction(s)) {\n        return call ? call(s, 2) : s();\n      } else ;\n    });\n  } else if (shared.isFunction(source)) {\n    if (cb) {\n      getter = call ? () => call(source, 2) : source;\n    } else {\n      getter = () => {\n        if (cleanup) {\n          pauseTracking();\n          try {\n            cleanup();\n          } finally {\n            resetTracking();\n          }\n        }\n        const currentEffect = activeWatcher;\n        activeWatcher = effect;\n        try {\n          return call ? call(source, 3, [boundCleanup]) : source(boundCleanup);\n        } finally {\n          activeWatcher = currentEffect;\n        }\n      };\n    }\n  } else {\n    getter = shared.NOOP;\n  }\n  if (cb && deep) {\n    const baseGetter = getter;\n    const depth = deep === true ? Infinity : deep;\n    getter = () => traverse(baseGetter(), depth);\n  }\n  const scope = getCurrentScope();\n  const watchHandle = () => {\n    effect.stop();\n    if (scope && scope.active) {\n      shared.remove(scope.effects, effect);\n    }\n  };\n  if (once && cb) {\n    const _cb = cb;\n    cb = (...args) => {\n      _cb(...args);\n      watchHandle();\n    };\n  }\n  let oldValue = isMultiSource ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) : INITIAL_WATCHER_VALUE;\n  const job = (immediateFirstRun) => {\n    if (!(effect.flags & 1) || !effect.dirty && !immediateFirstRun) {\n      return;\n    }\n    if (cb) {\n      const newValue = effect.run();\n      if (deep || forceTrigger || (isMultiSource ? newValue.some((v, i) => shared.hasChanged(v, oldValue[i])) : shared.hasChanged(newValue, oldValue))) {\n        if (cleanup) {\n          cleanup();\n        }\n        const currentWatcher = activeWatcher;\n        activeWatcher = effect;\n        try {\n          const args = [\n            newValue,\n            // pass undefined as the old value when it's changed for the first time\n            oldValue === INITIAL_WATCHER_VALUE ? void 0 : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE ? [] : oldValue,\n            boundCleanup\n          ];\n          oldValue = newValue;\n          call ? call(cb, 3, args) : (\n            // @ts-expect-error\n            cb(...args)\n          );\n        } finally {\n          activeWatcher = currentWatcher;\n        }\n      }\n    } else {\n      effect.run();\n    }\n  };\n  if (augmentJob) {\n    augmentJob(job);\n  }\n  effect = new ReactiveEffect(getter);\n  effect.scheduler = scheduler ? () => scheduler(job, false) : job;\n  boundCleanup = (fn) => onWatcherCleanup(fn, false, effect);\n  cleanup = effect.onStop = () => {\n    const cleanups = cleanupMap.get(effect);\n    if (cleanups) {\n      if (call) {\n        call(cleanups, 4);\n      } else {\n        for (const cleanup2 of cleanups) cleanup2();\n      }\n      cleanupMap.delete(effect);\n    }\n  };\n  if (cb) {\n    if (immediate) {\n      job(true);\n    } else {\n      oldValue = effect.run();\n    }\n  } else if (scheduler) {\n    scheduler(job.bind(null, true), true);\n  } else {\n    effect.run();\n  }\n  watchHandle.pause = effect.pause.bind(effect);\n  watchHandle.resume = effect.resume.bind(effect);\n  watchHandle.stop = watchHandle;\n  return watchHandle;\n}\nfunction traverse(value, depth = Infinity, seen) {\n  if (depth <= 0 || !shared.isObject(value) || value[\"__v_skip\"]) {\n    return value;\n  }\n  seen = seen || /* @__PURE__ */ new Set();\n  if (seen.has(value)) {\n    return value;\n  }\n  seen.add(value);\n  depth--;\n  if (isRef(value)) {\n    traverse(value.value, depth, seen);\n  } else if (shared.isArray(value)) {\n    for (let i = 0; i < value.length; i++) {\n      traverse(value[i], depth, seen);\n    }\n  } else if (shared.isSet(value) || shared.isMap(value)) {\n    value.forEach((v) => {\n      traverse(v, depth, seen);\n    });\n  } else if (shared.isPlainObject(value)) {\n    for (const key in value) {\n      traverse(value[key], depth, seen);\n    }\n    for (const key of Object.getOwnPropertySymbols(value)) {\n      if (Object.prototype.propertyIsEnumerable.call(value, key)) {\n        traverse(value[key], depth, seen);\n      }\n    }\n  }\n  return value;\n}\n\nexports.ARRAY_ITERATE_KEY = ARRAY_ITERATE_KEY;\nexports.EffectFlags = EffectFlags;\nexports.EffectScope = EffectScope;\nexports.ITERATE_KEY = ITERATE_KEY;\nexports.MAP_KEY_ITERATE_KEY = MAP_KEY_ITERATE_KEY;\nexports.ReactiveEffect = ReactiveEffect;\nexports.ReactiveFlags = ReactiveFlags;\nexports.TrackOpTypes = TrackOpTypes;\nexports.TriggerOpTypes = TriggerOpTypes;\nexports.WatchErrorCodes = WatchErrorCodes;\nexports.computed = computed;\nexports.customRef = customRef;\nexports.effect = effect;\nexports.effectScope = effectScope;\nexports.enableTracking = enableTracking;\nexports.getCurrentScope = getCurrentScope;\nexports.getCurrentWatcher = getCurrentWatcher;\nexports.isProxy = isProxy;\nexports.isReactive = isReactive;\nexports.isReadonly = isReadonly;\nexports.isRef = isRef;\nexports.isShallow = isShallow;\nexports.markRaw = markRaw;\nexports.onEffectCleanup = onEffectCleanup;\nexports.onScopeDispose = onScopeDispose;\nexports.onWatcherCleanup = onWatcherCleanup;\nexports.pauseTracking = pauseTracking;\nexports.proxyRefs = proxyRefs;\nexports.reactive = reactive;\nexports.reactiveReadArray = reactiveReadArray;\nexports.readonly = readonly;\nexports.ref = ref;\nexports.resetTracking = resetTracking;\nexports.shallowReactive = shallowReactive;\nexports.shallowReadArray = shallowReadArray;\nexports.shallowReadonly = shallowReadonly;\nexports.shallowRef = shallowRef;\nexports.stop = stop;\nexports.toRaw = toRaw;\nexports.toReactive = toReactive;\nexports.toReadonly = toReadonly;\nexports.toRef = toRef;\nexports.toRefs = toRefs;\nexports.toValue = toValue;\nexports.track = track;\nexports.traverse = traverse;\nexports.trigger = trigger;\nexports.triggerRef = triggerRef;\nexports.unref = unref;\nexports.watch = watch;\n","'use strict'\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./dist/reactivity.cjs.prod.js')\n} else {\n  module.exports = require('./dist/reactivity.cjs.js')\n}\n","/**\n* @vue/runtime-core v3.5.18\n* (c) 2018-present Yuxi (Evan) You and Vue contributors\n* @license MIT\n**/\n'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar reactivity = require('@vue/reactivity');\nvar shared = require('@vue/shared');\n\nfunction pushWarningContext(vnode) {\n}\nfunction popWarningContext() {\n}\nfunction assertNumber(val, type) {\n  return;\n}\n\nconst ErrorCodes = {\n  \"SETUP_FUNCTION\": 0,\n  \"0\": \"SETUP_FUNCTION\",\n  \"RENDER_FUNCTION\": 1,\n  \"1\": \"RENDER_FUNCTION\",\n  \"NATIVE_EVENT_HANDLER\": 5,\n  \"5\": \"NATIVE_EVENT_HANDLER\",\n  \"COMPONENT_EVENT_HANDLER\": 6,\n  \"6\": \"COMPONENT_EVENT_HANDLER\",\n  \"VNODE_HOOK\": 7,\n  \"7\": \"VNODE_HOOK\",\n  \"DIRECTIVE_HOOK\": 8,\n  \"8\": \"DIRECTIVE_HOOK\",\n  \"TRANSITION_HOOK\": 9,\n  \"9\": \"TRANSITION_HOOK\",\n  \"APP_ERROR_HANDLER\": 10,\n  \"10\": \"APP_ERROR_HANDLER\",\n  \"APP_WARN_HANDLER\": 11,\n  \"11\": \"APP_WARN_HANDLER\",\n  \"FUNCTION_REF\": 12,\n  \"12\": \"FUNCTION_REF\",\n  \"ASYNC_COMPONENT_LOADER\": 13,\n  \"13\": \"ASYNC_COMPONENT_LOADER\",\n  \"SCHEDULER\": 14,\n  \"14\": \"SCHEDULER\",\n  \"COMPONENT_UPDATE\": 15,\n  \"15\": \"COMPONENT_UPDATE\",\n  \"APP_UNMOUNT_CLEANUP\": 16,\n  \"16\": \"APP_UNMOUNT_CLEANUP\"\n};\nconst ErrorTypeStrings$1 = {\n  [\"sp\"]: \"serverPrefetch hook\",\n  [\"bc\"]: \"beforeCreate hook\",\n  [\"c\"]: \"created hook\",\n  [\"bm\"]: \"beforeMount hook\",\n  [\"m\"]: \"mounted hook\",\n  [\"bu\"]: \"beforeUpdate hook\",\n  [\"u\"]: \"updated\",\n  [\"bum\"]: \"beforeUnmount hook\",\n  [\"um\"]: \"unmounted hook\",\n  [\"a\"]: \"activated hook\",\n  [\"da\"]: \"deactivated hook\",\n  [\"ec\"]: \"errorCaptured hook\",\n  [\"rtc\"]: \"renderTracked hook\",\n  [\"rtg\"]: \"renderTriggered hook\",\n  [0]: \"setup function\",\n  [1]: \"render function\",\n  [2]: \"watcher getter\",\n  [3]: \"watcher callback\",\n  [4]: \"watcher cleanup function\",\n  [5]: \"native event handler\",\n  [6]: \"component event handler\",\n  [7]: \"vnode hook\",\n  [8]: \"directive hook\",\n  [9]: \"transition hook\",\n  [10]: \"app errorHandler\",\n  [11]: \"app warnHandler\",\n  [12]: \"ref function\",\n  [13]: \"async component loader\",\n  [14]: \"scheduler flush\",\n  [15]: \"component update\",\n  [16]: \"app unmount cleanup function\"\n};\nfunction callWithErrorHandling(fn, instance, type, args) {\n  try {\n    return args ? fn(...args) : fn();\n  } catch (err) {\n    handleError(err, instance, type);\n  }\n}\nfunction callWithAsyncErrorHandling(fn, instance, type, args) {\n  if (shared.isFunction(fn)) {\n    const res = callWithErrorHandling(fn, instance, type, args);\n    if (res && shared.isPromise(res)) {\n      res.catch((err) => {\n        handleError(err, instance, type);\n      });\n    }\n    return res;\n  }\n  if (shared.isArray(fn)) {\n    const values = [];\n    for (let i = 0; i < fn.length; i++) {\n      values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));\n    }\n    return values;\n  }\n}\nfunction handleError(err, instance, type, throwInDev = true) {\n  const contextVNode = instance ? instance.vnode : null;\n  const { errorHandler, throwUnhandledErrorInProduction } = instance && instance.appContext.config || shared.EMPTY_OBJ;\n  if (instance) {\n    let cur = instance.parent;\n    const exposedInstance = instance.proxy;\n    const errorInfo = `https://vuejs.org/error-reference/#runtime-${type}`;\n    while (cur) {\n      const errorCapturedHooks = cur.ec;\n      if (errorCapturedHooks) {\n        for (let i = 0; i < errorCapturedHooks.length; i++) {\n          if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {\n            return;\n          }\n        }\n      }\n      cur = cur.parent;\n    }\n    if (errorHandler) {\n      reactivity.pauseTracking();\n      callWithErrorHandling(errorHandler, null, 10, [\n        err,\n        exposedInstance,\n        errorInfo\n      ]);\n      reactivity.resetTracking();\n      return;\n    }\n  }\n  logError(err, type, contextVNode, throwInDev, throwUnhandledErrorInProduction);\n}\nfunction logError(err, type, contextVNode, throwInDev = true, throwInProd = false) {\n  if (throwInProd) {\n    throw err;\n  } else {\n    console.error(err);\n  }\n}\n\nconst queue = [];\nlet flushIndex = -1;\nconst pendingPostFlushCbs = [];\nlet activePostFlushCbs = null;\nlet postFlushIndex = 0;\nconst resolvedPromise = /* @__PURE__ */ Promise.resolve();\nlet currentFlushPromise = null;\nfunction nextTick(fn) {\n  const p = currentFlushPromise || resolvedPromise;\n  return fn ? p.then(this ? fn.bind(this) : fn) : p;\n}\nfunction findInsertionIndex(id) {\n  let start = flushIndex + 1;\n  let end = queue.length;\n  while (start < end) {\n    const middle = start + end >>> 1;\n    const middleJob = queue[middle];\n    const middleJobId = getId(middleJob);\n    if (middleJobId < id || middleJobId === id && middleJob.flags & 2) {\n      start = middle + 1;\n    } else {\n      end = middle;\n    }\n  }\n  return start;\n}\nfunction queueJob(job) {\n  if (!(job.flags & 1)) {\n    const jobId = getId(job);\n    const lastJob = queue[queue.length - 1];\n    if (!lastJob || // fast path when the job id is larger than the tail\n    !(job.flags & 2) && jobId >= getId(lastJob)) {\n      queue.push(job);\n    } else {\n      queue.splice(findInsertionIndex(jobId), 0, job);\n    }\n    job.flags |= 1;\n    queueFlush();\n  }\n}\nfunction queueFlush() {\n  if (!currentFlushPromise) {\n    currentFlushPromise = resolvedPromise.then(flushJobs);\n  }\n}\nfunction queuePostFlushCb(cb) {\n  if (!shared.isArray(cb)) {\n    if (activePostFlushCbs && cb.id === -1) {\n      activePostFlushCbs.splice(postFlushIndex + 1, 0, cb);\n    } else if (!(cb.flags & 1)) {\n      pendingPostFlushCbs.push(cb);\n      cb.flags |= 1;\n    }\n  } else {\n    pendingPostFlushCbs.push(...cb);\n  }\n  queueFlush();\n}\nfunction flushPreFlushCbs(instance, seen, i = flushIndex + 1) {\n  for (; i < queue.length; i++) {\n    const cb = queue[i];\n    if (cb && cb.flags & 2) {\n      if (instance && cb.id !== instance.uid) {\n        continue;\n      }\n      queue.splice(i, 1);\n      i--;\n      if (cb.flags & 4) {\n        cb.flags &= -2;\n      }\n      cb();\n      if (!(cb.flags & 4)) {\n        cb.flags &= -2;\n      }\n    }\n  }\n}\nfunction flushPostFlushCbs(seen) {\n  if (pendingPostFlushCbs.length) {\n    const deduped = [...new Set(pendingPostFlushCbs)].sort(\n      (a, b) => getId(a) - getId(b)\n    );\n    pendingPostFlushCbs.length = 0;\n    if (activePostFlushCbs) {\n      activePostFlushCbs.push(...deduped);\n      return;\n    }\n    activePostFlushCbs = deduped;\n    for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {\n      const cb = activePostFlushCbs[postFlushIndex];\n      if (cb.flags & 4) {\n        cb.flags &= -2;\n      }\n      if (!(cb.flags & 8)) cb();\n      cb.flags &= -2;\n    }\n    activePostFlushCbs = null;\n    postFlushIndex = 0;\n  }\n}\nconst getId = (job) => job.id == null ? job.flags & 2 ? -1 : Infinity : job.id;\nfunction flushJobs(seen) {\n  try {\n    for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {\n      const job = queue[flushIndex];\n      if (job && !(job.flags & 8)) {\n        if (false) ;\n        if (job.flags & 4) {\n          job.flags &= ~1;\n        }\n        callWithErrorHandling(\n          job,\n          job.i,\n          job.i ? 15 : 14\n        );\n        if (!(job.flags & 4)) {\n          job.flags &= ~1;\n        }\n      }\n    }\n  } finally {\n    for (; flushIndex < queue.length; flushIndex++) {\n      const job = queue[flushIndex];\n      if (job) {\n        job.flags &= -2;\n      }\n    }\n    flushIndex = -1;\n    queue.length = 0;\n    flushPostFlushCbs();\n    currentFlushPromise = null;\n    if (queue.length || pendingPostFlushCbs.length) {\n      flushJobs();\n    }\n  }\n}\n\nlet currentRenderingInstance = null;\nlet currentScopeId = null;\nfunction setCurrentRenderingInstance(instance) {\n  const prev = currentRenderingInstance;\n  currentRenderingInstance = instance;\n  currentScopeId = instance && instance.type.__scopeId || null;\n  return prev;\n}\nfunction pushScopeId(id) {\n  currentScopeId = id;\n}\nfunction popScopeId() {\n  currentScopeId = null;\n}\nconst withScopeId = (_id) => withCtx;\nfunction withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) {\n  if (!ctx) return fn;\n  if (fn._n) {\n    return fn;\n  }\n  const renderFnWithContext = (...args) => {\n    if (renderFnWithContext._d) {\n      setBlockTracking(-1);\n    }\n    const prevInstance = setCurrentRenderingInstance(ctx);\n    let res;\n    try {\n      res = fn(...args);\n    } finally {\n      setCurrentRenderingInstance(prevInstance);\n      if (renderFnWithContext._d) {\n        setBlockTracking(1);\n      }\n    }\n    return res;\n  };\n  renderFnWithContext._n = true;\n  renderFnWithContext._c = true;\n  renderFnWithContext._d = true;\n  return renderFnWithContext;\n}\n\nfunction withDirectives(vnode, directives) {\n  if (currentRenderingInstance === null) {\n    return vnode;\n  }\n  const instance = getComponentPublicInstance(currentRenderingInstance);\n  const bindings = vnode.dirs || (vnode.dirs = []);\n  for (let i = 0; i < directives.length; i++) {\n    let [dir, value, arg, modifiers = shared.EMPTY_OBJ] = directives[i];\n    if (dir) {\n      if (shared.isFunction(dir)) {\n        dir = {\n          mounted: dir,\n          updated: dir\n        };\n      }\n      if (dir.deep) {\n        reactivity.traverse(value);\n      }\n      bindings.push({\n        dir,\n        instance,\n        value,\n        oldValue: void 0,\n        arg,\n        modifiers\n      });\n    }\n  }\n  return vnode;\n}\nfunction invokeDirectiveHook(vnode, prevVNode, instance, name) {\n  const bindings = vnode.dirs;\n  const oldBindings = prevVNode && prevVNode.dirs;\n  for (let i = 0; i < bindings.length; i++) {\n    const binding = bindings[i];\n    if (oldBindings) {\n      binding.oldValue = oldBindings[i].value;\n    }\n    let hook = binding.dir[name];\n    if (hook) {\n      reactivity.pauseTracking();\n      callWithAsyncErrorHandling(hook, instance, 8, [\n        vnode.el,\n        binding,\n        vnode,\n        prevVNode\n      ]);\n      reactivity.resetTracking();\n    }\n  }\n}\n\nconst TeleportEndKey = Symbol(\"_vte\");\nconst isTeleport = (type) => type.__isTeleport;\nconst isTeleportDisabled = (props) => props && (props.disabled || props.disabled === \"\");\nconst isTeleportDeferred = (props) => props && (props.defer || props.defer === \"\");\nconst isTargetSVG = (target) => typeof SVGElement !== \"undefined\" && target instanceof SVGElement;\nconst isTargetMathML = (target) => typeof MathMLElement === \"function\" && target instanceof MathMLElement;\nconst resolveTarget = (props, select) => {\n  const targetSelector = props && props.to;\n  if (shared.isString(targetSelector)) {\n    if (!select) {\n      return null;\n    } else {\n      const target = select(targetSelector);\n      return target;\n    }\n  } else {\n    return targetSelector;\n  }\n};\nconst TeleportImpl = {\n  name: \"Teleport\",\n  __isTeleport: true,\n  process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals) {\n    const {\n      mc: mountChildren,\n      pc: patchChildren,\n      pbc: patchBlockChildren,\n      o: { insert, querySelector, createText, createComment }\n    } = internals;\n    const disabled = isTeleportDisabled(n2.props);\n    let { shapeFlag, children, dynamicChildren } = n2;\n    if (n1 == null) {\n      const placeholder = n2.el = createText(\"\");\n      const mainAnchor = n2.anchor = createText(\"\");\n      insert(placeholder, container, anchor);\n      insert(mainAnchor, container, anchor);\n      const mount = (container2, anchor2) => {\n        if (shapeFlag & 16) {\n          if (parentComponent && parentComponent.isCE) {\n            parentComponent.ce._teleportTarget = container2;\n          }\n          mountChildren(\n            children,\n            container2,\n            anchor2,\n            parentComponent,\n            parentSuspense,\n            namespace,\n            slotScopeIds,\n            optimized\n          );\n        }\n      };\n      const mountToTarget = () => {\n        const target = n2.target = resolveTarget(n2.props, querySelector);\n        const targetAnchor = prepareAnchor(target, n2, createText, insert);\n        if (target) {\n          if (namespace !== \"svg\" && isTargetSVG(target)) {\n            namespace = \"svg\";\n          } else if (namespace !== \"mathml\" && isTargetMathML(target)) {\n            namespace = \"mathml\";\n          }\n          if (!disabled) {\n            mount(target, targetAnchor);\n            updateCssVars(n2, false);\n          }\n        }\n      };\n      if (disabled) {\n        mount(container, mainAnchor);\n        updateCssVars(n2, true);\n      }\n      if (isTeleportDeferred(n2.props)) {\n        n2.el.__isMounted = false;\n        queuePostRenderEffect(() => {\n          mountToTarget();\n          delete n2.el.__isMounted;\n        }, parentSuspense);\n      } else {\n        mountToTarget();\n      }\n    } else {\n      if (isTeleportDeferred(n2.props) && n1.el.__isMounted === false) {\n        queuePostRenderEffect(() => {\n          TeleportImpl.process(\n            n1,\n            n2,\n            container,\n            anchor,\n            parentComponent,\n            parentSuspense,\n            namespace,\n            slotScopeIds,\n            optimized,\n            internals\n          );\n        }, parentSuspense);\n        return;\n      }\n      n2.el = n1.el;\n      n2.targetStart = n1.targetStart;\n      const mainAnchor = n2.anchor = n1.anchor;\n      const target = n2.target = n1.target;\n      const targetAnchor = n2.targetAnchor = n1.targetAnchor;\n      const wasDisabled = isTeleportDisabled(n1.props);\n      const currentContainer = wasDisabled ? container : target;\n      const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;\n      if (namespace === \"svg\" || isTargetSVG(target)) {\n        namespace = \"svg\";\n      } else if (namespace === \"mathml\" || isTargetMathML(target)) {\n        namespace = \"mathml\";\n      }\n      if (dynamicChildren) {\n        patchBlockChildren(\n          n1.dynamicChildren,\n          dynamicChildren,\n          currentContainer,\n          parentComponent,\n          parentSuspense,\n          namespace,\n          slotScopeIds\n        );\n        traverseStaticChildren(n1, n2, true);\n      } else if (!optimized) {\n        patchChildren(\n          n1,\n          n2,\n          currentContainer,\n          currentAnchor,\n          parentComponent,\n          parentSuspense,\n          namespace,\n          slotScopeIds,\n          false\n        );\n      }\n      if (disabled) {\n        if (!wasDisabled) {\n          moveTeleport(\n            n2,\n            container,\n            mainAnchor,\n            internals,\n            1\n          );\n        } else {\n          if (n2.props && n1.props && n2.props.to !== n1.props.to) {\n            n2.props.to = n1.props.to;\n          }\n        }\n      } else {\n        if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {\n          const nextTarget = n2.target = resolveTarget(\n            n2.props,\n            querySelector\n          );\n          if (nextTarget) {\n            moveTeleport(\n              n2,\n              nextTarget,\n              null,\n              internals,\n              0\n            );\n          }\n        } else if (wasDisabled) {\n          moveTeleport(\n            n2,\n            target,\n            targetAnchor,\n            internals,\n            1\n          );\n        }\n      }\n      updateCssVars(n2, disabled);\n    }\n  },\n  remove(vnode, parentComponent, parentSuspense, { um: unmount, o: { remove: hostRemove } }, doRemove) {\n    const {\n      shapeFlag,\n      children,\n      anchor,\n      targetStart,\n      targetAnchor,\n      target,\n      props\n    } = vnode;\n    if (target) {\n      hostRemove(targetStart);\n      hostRemove(targetAnchor);\n    }\n    doRemove && hostRemove(anchor);\n    if (shapeFlag & 16) {\n      const shouldRemove = doRemove || !isTeleportDisabled(props);\n      for (let i = 0; i < children.length; i++) {\n        const child = children[i];\n        unmount(\n          child,\n          parentComponent,\n          parentSuspense,\n          shouldRemove,\n          !!child.dynamicChildren\n        );\n      }\n    }\n  },\n  move: moveTeleport,\n  hydrate: hydrateTeleport\n};\nfunction moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2) {\n  if (moveType === 0) {\n    insert(vnode.targetAnchor, container, parentAnchor);\n  }\n  const { el, anchor, shapeFlag, children, props } = vnode;\n  const isReorder = moveType === 2;\n  if (isReorder) {\n    insert(el, container, parentAnchor);\n  }\n  if (!isReorder || isTeleportDisabled(props)) {\n    if (shapeFlag & 16) {\n      for (let i = 0; i < children.length; i++) {\n        move(\n          children[i],\n          container,\n          parentAnchor,\n          2\n        );\n      }\n    }\n  }\n  if (isReorder) {\n    insert(anchor, container, parentAnchor);\n  }\n}\nfunction hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, {\n  o: { nextSibling, parentNode, querySelector, insert, createText }\n}, hydrateChildren) {\n  const target = vnode.target = resolveTarget(\n    vnode.props,\n    querySelector\n  );\n  if (target) {\n    const disabled = isTeleportDisabled(vnode.props);\n    const targetNode = target._lpa || target.firstChild;\n    if (vnode.shapeFlag & 16) {\n      if (disabled) {\n        vnode.anchor = hydrateChildren(\n          nextSibling(node),\n          vnode,\n          parentNode(node),\n          parentComponent,\n          parentSuspense,\n          slotScopeIds,\n          optimized\n        );\n        vnode.targetStart = targetNode;\n        vnode.targetAnchor = targetNode && nextSibling(targetNode);\n      } else {\n        vnode.anchor = nextSibling(node);\n        let targetAnchor = targetNode;\n        while (targetAnchor) {\n          if (targetAnchor && targetAnchor.nodeType === 8) {\n            if (targetAnchor.data === \"teleport start anchor\") {\n              vnode.targetStart = targetAnchor;\n            } else if (targetAnchor.data === \"teleport anchor\") {\n              vnode.targetAnchor = targetAnchor;\n              target._lpa = vnode.targetAnchor && nextSibling(vnode.targetAnchor);\n              break;\n            }\n          }\n          targetAnchor = nextSibling(targetAnchor);\n        }\n        if (!vnode.targetAnchor) {\n          prepareAnchor(target, vnode, createText, insert);\n        }\n        hydrateChildren(\n          targetNode && nextSibling(targetNode),\n          vnode,\n          target,\n          parentComponent,\n          parentSuspense,\n          slotScopeIds,\n          optimized\n        );\n      }\n    }\n    updateCssVars(vnode, disabled);\n  }\n  return vnode.anchor && nextSibling(vnode.anchor);\n}\nconst Teleport = TeleportImpl;\nfunction updateCssVars(vnode, isDisabled) {\n  const ctx = vnode.ctx;\n  if (ctx && ctx.ut) {\n    let node, anchor;\n    if (isDisabled) {\n      node = vnode.el;\n      anchor = vnode.anchor;\n    } else {\n      node = vnode.targetStart;\n      anchor = vnode.targetAnchor;\n    }\n    while (node && node !== anchor) {\n      if (node.nodeType === 1) node.setAttribute(\"data-v-owner\", ctx.uid);\n      node = node.nextSibling;\n    }\n    ctx.ut();\n  }\n}\nfunction prepareAnchor(target, vnode, createText, insert) {\n  const targetStart = vnode.targetStart = createText(\"\");\n  const targetAnchor = vnode.targetAnchor = createText(\"\");\n  targetStart[TeleportEndKey] = targetAnchor;\n  if (target) {\n    insert(targetStart, target);\n    insert(targetAnchor, target);\n  }\n  return targetAnchor;\n}\n\nconst leaveCbKey = Symbol(\"_leaveCb\");\nconst enterCbKey = Symbol(\"_enterCb\");\nfunction useTransitionState() {\n  const state = {\n    isMounted: false,\n    isLeaving: false,\n    isUnmounting: false,\n    leavingVNodes: /* @__PURE__ */ new Map()\n  };\n  onMounted(() => {\n    state.isMounted = true;\n  });\n  onBeforeUnmount(() => {\n    state.isUnmounting = true;\n  });\n  return state;\n}\nconst TransitionHookValidator = [Function, Array];\nconst BaseTransitionPropsValidators = {\n  mode: String,\n  appear: Boolean,\n  persisted: Boolean,\n  // enter\n  onBeforeEnter: TransitionHookValidator,\n  onEnter: TransitionHookValidator,\n  onAfterEnter: TransitionHookValidator,\n  onEnterCancelled: TransitionHookValidator,\n  // leave\n  onBeforeLeave: TransitionHookValidator,\n  onLeave: TransitionHookValidator,\n  onAfterLeave: TransitionHookValidator,\n  onLeaveCancelled: TransitionHookValidator,\n  // appear\n  onBeforeAppear: TransitionHookValidator,\n  onAppear: TransitionHookValidator,\n  onAfterAppear: TransitionHookValidator,\n  onAppearCancelled: TransitionHookValidator\n};\nconst recursiveGetSubtree = (instance) => {\n  const subTree = instance.subTree;\n  return subTree.component ? recursiveGetSubtree(subTree.component) : subTree;\n};\nconst BaseTransitionImpl = {\n  name: `BaseTransition`,\n  props: BaseTransitionPropsValidators,\n  setup(props, { slots }) {\n    const instance = getCurrentInstance();\n    const state = useTransitionState();\n    return () => {\n      const children = slots.default && getTransitionRawChildren(slots.default(), true);\n      if (!children || !children.length) {\n        return;\n      }\n      const child = findNonCommentChild(children);\n      const rawProps = reactivity.toRaw(props);\n      const { mode } = rawProps;\n      if (state.isLeaving) {\n        return emptyPlaceholder(child);\n      }\n      const innerChild = getInnerChild$1(child);\n      if (!innerChild) {\n        return emptyPlaceholder(child);\n      }\n      let enterHooks = resolveTransitionHooks(\n        innerChild,\n        rawProps,\n        state,\n        instance,\n        // #11061, ensure enterHooks is fresh after clone\n        (hooks) => enterHooks = hooks\n      );\n      if (innerChild.type !== Comment) {\n        setTransitionHooks(innerChild, enterHooks);\n      }\n      let oldInnerChild = instance.subTree && getInnerChild$1(instance.subTree);\n      if (oldInnerChild && oldInnerChild.type !== Comment && !isSameVNodeType(innerChild, oldInnerChild) && recursiveGetSubtree(instance).type !== Comment) {\n        let leavingHooks = resolveTransitionHooks(\n          oldInnerChild,\n          rawProps,\n          state,\n          instance\n        );\n        setTransitionHooks(oldInnerChild, leavingHooks);\n        if (mode === \"out-in\" && innerChild.type !== Comment) {\n          state.isLeaving = true;\n          leavingHooks.afterLeave = () => {\n            state.isLeaving = false;\n            if (!(instance.job.flags & 8)) {\n              instance.update();\n            }\n            delete leavingHooks.afterLeave;\n            oldInnerChild = void 0;\n          };\n          return emptyPlaceholder(child);\n        } else if (mode === \"in-out\" && innerChild.type !== Comment) {\n          leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {\n            const leavingVNodesCache = getLeavingNodesForType(\n              state,\n              oldInnerChild\n            );\n            leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;\n            el[leaveCbKey] = () => {\n              earlyRemove();\n              el[leaveCbKey] = void 0;\n              delete enterHooks.delayedLeave;\n              oldInnerChild = void 0;\n            };\n            enterHooks.delayedLeave = () => {\n              delayedLeave();\n              delete enterHooks.delayedLeave;\n              oldInnerChild = void 0;\n            };\n          };\n        } else {\n          oldInnerChild = void 0;\n        }\n      } else if (oldInnerChild) {\n        oldInnerChild = void 0;\n      }\n      return child;\n    };\n  }\n};\nfunction findNonCommentChild(children) {\n  let child = children[0];\n  if (children.length > 1) {\n    for (const c of children) {\n      if (c.type !== Comment) {\n        child = c;\n        break;\n      }\n    }\n  }\n  return child;\n}\nconst BaseTransition = BaseTransitionImpl;\nfunction getLeavingNodesForType(state, vnode) {\n  const { leavingVNodes } = state;\n  let leavingVNodesCache = leavingVNodes.get(vnode.type);\n  if (!leavingVNodesCache) {\n    leavingVNodesCache = /* @__PURE__ */ Object.create(null);\n    leavingVNodes.set(vnode.type, leavingVNodesCache);\n  }\n  return leavingVNodesCache;\n}\nfunction resolveTransitionHooks(vnode, props, state, instance, postClone) {\n  const {\n    appear,\n    mode,\n    persisted = false,\n    onBeforeEnter,\n    onEnter,\n    onAfterEnter,\n    onEnterCancelled,\n    onBeforeLeave,\n    onLeave,\n    onAfterLeave,\n    onLeaveCancelled,\n    onBeforeAppear,\n    onAppear,\n    onAfterAppear,\n    onAppearCancelled\n  } = props;\n  const key = String(vnode.key);\n  const leavingVNodesCache = getLeavingNodesForType(state, vnode);\n  const callHook = (hook, args) => {\n    hook && callWithAsyncErrorHandling(\n      hook,\n      instance,\n      9,\n      args\n    );\n  };\n  const callAsyncHook = (hook, args) => {\n    const done = args[1];\n    callHook(hook, args);\n    if (shared.isArray(hook)) {\n      if (hook.every((hook2) => hook2.length <= 1)) done();\n    } else if (hook.length <= 1) {\n      done();\n    }\n  };\n  const hooks = {\n    mode,\n    persisted,\n    beforeEnter(el) {\n      let hook = onBeforeEnter;\n      if (!state.isMounted) {\n        if (appear) {\n          hook = onBeforeAppear || onBeforeEnter;\n        } else {\n          return;\n        }\n      }\n      if (el[leaveCbKey]) {\n        el[leaveCbKey](\n          true\n          /* cancelled */\n        );\n      }\n      const leavingVNode = leavingVNodesCache[key];\n      if (leavingVNode && isSameVNodeType(vnode, leavingVNode) && leavingVNode.el[leaveCbKey]) {\n        leavingVNode.el[leaveCbKey]();\n      }\n      callHook(hook, [el]);\n    },\n    enter(el) {\n      let hook = onEnter;\n      let afterHook = onAfterEnter;\n      let cancelHook = onEnterCancelled;\n      if (!state.isMounted) {\n        if (appear) {\n          hook = onAppear || onEnter;\n          afterHook = onAfterAppear || onAfterEnter;\n          cancelHook = onAppearCancelled || onEnterCancelled;\n        } else {\n          return;\n        }\n      }\n      let called = false;\n      const done = el[enterCbKey] = (cancelled) => {\n        if (called) return;\n        called = true;\n        if (cancelled) {\n          callHook(cancelHook, [el]);\n        } else {\n          callHook(afterHook, [el]);\n        }\n        if (hooks.delayedLeave) {\n          hooks.delayedLeave();\n        }\n        el[enterCbKey] = void 0;\n      };\n      if (hook) {\n        callAsyncHook(hook, [el, done]);\n      } else {\n        done();\n      }\n    },\n    leave(el, remove) {\n      const key2 = String(vnode.key);\n      if (el[enterCbKey]) {\n        el[enterCbKey](\n          true\n          /* cancelled */\n        );\n      }\n      if (state.isUnmounting) {\n        return remove();\n      }\n      callHook(onBeforeLeave, [el]);\n      let called = false;\n      const done = el[leaveCbKey] = (cancelled) => {\n        if (called) return;\n        called = true;\n        remove();\n        if (cancelled) {\n          callHook(onLeaveCancelled, [el]);\n        } else {\n          callHook(onAfterLeave, [el]);\n        }\n        el[leaveCbKey] = void 0;\n        if (leavingVNodesCache[key2] === vnode) {\n          delete leavingVNodesCache[key2];\n        }\n      };\n      leavingVNodesCache[key2] = vnode;\n      if (onLeave) {\n        callAsyncHook(onLeave, [el, done]);\n      } else {\n        done();\n      }\n    },\n    clone(vnode2) {\n      const hooks2 = resolveTransitionHooks(\n        vnode2,\n        props,\n        state,\n        instance,\n        postClone\n      );\n      if (postClone) postClone(hooks2);\n      return hooks2;\n    }\n  };\n  return hooks;\n}\nfunction emptyPlaceholder(vnode) {\n  if (isKeepAlive(vnode)) {\n    vnode = cloneVNode(vnode);\n    vnode.children = null;\n    return vnode;\n  }\n}\nfunction getInnerChild$1(vnode) {\n  if (!isKeepAlive(vnode)) {\n    if (isTeleport(vnode.type) && vnode.children) {\n      return findNonCommentChild(vnode.children);\n    }\n    return vnode;\n  }\n  if (vnode.component) {\n    return vnode.component.subTree;\n  }\n  const { shapeFlag, children } = vnode;\n  if (children) {\n    if (shapeFlag & 16) {\n      return children[0];\n    }\n    if (shapeFlag & 32 && shared.isFunction(children.default)) {\n      return children.default();\n    }\n  }\n}\nfunction setTransitionHooks(vnode, hooks) {\n  if (vnode.shapeFlag & 6 && vnode.component) {\n    vnode.transition = hooks;\n    setTransitionHooks(vnode.component.subTree, hooks);\n  } else if (vnode.shapeFlag & 128) {\n    vnode.ssContent.transition = hooks.clone(vnode.ssContent);\n    vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);\n  } else {\n    vnode.transition = hooks;\n  }\n}\nfunction getTransitionRawChildren(children, keepComment = false, parentKey) {\n  let ret = [];\n  let keyedFragmentCount = 0;\n  for (let i = 0; i < children.length; i++) {\n    let child = children[i];\n    const key = parentKey == null ? child.key : String(parentKey) + String(child.key != null ? child.key : i);\n    if (child.type === Fragment) {\n      if (child.patchFlag & 128) keyedFragmentCount++;\n      ret = ret.concat(\n        getTransitionRawChildren(child.children, keepComment, key)\n      );\n    } else if (keepComment || child.type !== Comment) {\n      ret.push(key != null ? cloneVNode(child, { key }) : child);\n    }\n  }\n  if (keyedFragmentCount > 1) {\n    for (let i = 0; i < ret.length; i++) {\n      ret[i].patchFlag = -2;\n    }\n  }\n  return ret;\n}\n\n/*! #__NO_SIDE_EFFECTS__ */\n// @__NO_SIDE_EFFECTS__\nfunction defineComponent(options, extraOptions) {\n  return shared.isFunction(options) ? (\n    // #8236: extend call and options.name access are considered side-effects\n    // by Rollup, so we have to wrap it in a pure-annotated IIFE.\n    /* @__PURE__ */ (() => shared.extend({ name: options.name }, extraOptions, { setup: options }))()\n  ) : options;\n}\n\nfunction useId() {\n  const i = getCurrentInstance();\n  if (i) {\n    return (i.appContext.config.idPrefix || \"v\") + \"-\" + i.ids[0] + i.ids[1]++;\n  }\n  return \"\";\n}\nfunction markAsyncBoundary(instance) {\n  instance.ids = [instance.ids[0] + instance.ids[2]++ + \"-\", 0, 0];\n}\n\nfunction useTemplateRef(key) {\n  const i = getCurrentInstance();\n  const r = reactivity.shallowRef(null);\n  if (i) {\n    const refs = i.refs === shared.EMPTY_OBJ ? i.refs = {} : i.refs;\n    {\n      Object.defineProperty(refs, key, {\n        enumerable: true,\n        get: () => r.value,\n        set: (val) => r.value = val\n      });\n    }\n  }\n  const ret = r;\n  return ret;\n}\n\nfunction setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {\n  if (shared.isArray(rawRef)) {\n    rawRef.forEach(\n      (r, i) => setRef(\n        r,\n        oldRawRef && (shared.isArray(oldRawRef) ? oldRawRef[i] : oldRawRef),\n        parentSuspense,\n        vnode,\n        isUnmount\n      )\n    );\n    return;\n  }\n  if (isAsyncWrapper(vnode) && !isUnmount) {\n    if (vnode.shapeFlag & 512 && vnode.type.__asyncResolved && vnode.component.subTree.component) {\n      setRef(rawRef, oldRawRef, parentSuspense, vnode.component.subTree);\n    }\n    return;\n  }\n  const refValue = vnode.shapeFlag & 4 ? getComponentPublicInstance(vnode.component) : vnode.el;\n  const value = isUnmount ? null : refValue;\n  const { i: owner, r: ref } = rawRef;\n  const oldRef = oldRawRef && oldRawRef.r;\n  const refs = owner.refs === shared.EMPTY_OBJ ? owner.refs = {} : owner.refs;\n  const setupState = owner.setupState;\n  const rawSetupState = reactivity.toRaw(setupState);\n  const canSetSetupRef = setupState === shared.EMPTY_OBJ ? () => false : (key) => {\n    return shared.hasOwn(rawSetupState, key);\n  };\n  if (oldRef != null && oldRef !== ref) {\n    if (shared.isString(oldRef)) {\n      refs[oldRef] = null;\n      if (canSetSetupRef(oldRef)) {\n        setupState[oldRef] = null;\n      }\n    } else if (reactivity.isRef(oldRef)) {\n      oldRef.value = null;\n    }\n  }\n  if (shared.isFunction(ref)) {\n    callWithErrorHandling(ref, owner, 12, [value, refs]);\n  } else {\n    const _isString = shared.isString(ref);\n    const _isRef = reactivity.isRef(ref);\n    if (_isString || _isRef) {\n      const doSet = () => {\n        if (rawRef.f) {\n          const existing = _isString ? canSetSetupRef(ref) ? setupState[ref] : refs[ref] : ref.value;\n          if (isUnmount) {\n            shared.isArray(existing) && shared.remove(existing, refValue);\n          } else {\n            if (!shared.isArray(existing)) {\n              if (_isString) {\n                refs[ref] = [refValue];\n                if (canSetSetupRef(ref)) {\n                  setupState[ref] = refs[ref];\n                }\n              } else {\n                ref.value = [refValue];\n                if (rawRef.k) refs[rawRef.k] = ref.value;\n              }\n            } else if (!existing.includes(refValue)) {\n              existing.push(refValue);\n            }\n          }\n        } else if (_isString) {\n          refs[ref] = value;\n          if (canSetSetupRef(ref)) {\n            setupState[ref] = value;\n          }\n        } else if (_isRef) {\n          ref.value = value;\n          if (rawRef.k) refs[rawRef.k] = value;\n        } else ;\n      };\n      if (value) {\n        doSet.id = -1;\n        queuePostRenderEffect(doSet, parentSuspense);\n      } else {\n        doSet();\n      }\n    }\n  }\n}\n\nlet hasLoggedMismatchError = false;\nconst logMismatchError = () => {\n  if (hasLoggedMismatchError) {\n    return;\n  }\n  console.error(\"Hydration completed but contains mismatches.\");\n  hasLoggedMismatchError = true;\n};\nconst isSVGContainer = (container) => container.namespaceURI.includes(\"svg\") && container.tagName !== \"foreignObject\";\nconst isMathMLContainer = (container) => container.namespaceURI.includes(\"MathML\");\nconst getContainerType = (container) => {\n  if (container.nodeType !== 1) return void 0;\n  if (isSVGContainer(container)) return \"svg\";\n  if (isMathMLContainer(container)) return \"mathml\";\n  return void 0;\n};\nconst isComment = (node) => node.nodeType === 8;\nfunction createHydrationFunctions(rendererInternals) {\n  const {\n    mt: mountComponent,\n    p: patch,\n    o: {\n      patchProp,\n      createText,\n      nextSibling,\n      parentNode,\n      remove,\n      insert,\n      createComment\n    }\n  } = rendererInternals;\n  const hydrate = (vnode, container) => {\n    if (!container.hasChildNodes()) {\n      patch(null, vnode, container);\n      flushPostFlushCbs();\n      container._vnode = vnode;\n      return;\n    }\n    hydrateNode(container.firstChild, vnode, null, null, null);\n    flushPostFlushCbs();\n    container._vnode = vnode;\n  };\n  const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {\n    optimized = optimized || !!vnode.dynamicChildren;\n    const isFragmentStart = isComment(node) && node.data === \"[\";\n    const onMismatch = () => handleMismatch(\n      node,\n      vnode,\n      parentComponent,\n      parentSuspense,\n      slotScopeIds,\n      isFragmentStart\n    );\n    const { type, ref, shapeFlag, patchFlag } = vnode;\n    let domType = node.nodeType;\n    vnode.el = node;\n    if (patchFlag === -2) {\n      optimized = false;\n      vnode.dynamicChildren = null;\n    }\n    let nextNode = null;\n    switch (type) {\n      case Text:\n        if (domType !== 3) {\n          if (vnode.children === \"\") {\n            insert(vnode.el = createText(\"\"), parentNode(node), node);\n            nextNode = node;\n          } else {\n            nextNode = onMismatch();\n          }\n        } else {\n          if (node.data !== vnode.children) {\n            logMismatchError();\n            node.data = vnode.children;\n          }\n          nextNode = nextSibling(node);\n        }\n        break;\n      case Comment:\n        if (isTemplateNode(node)) {\n          nextNode = nextSibling(node);\n          replaceNode(\n            vnode.el = node.content.firstChild,\n            node,\n            parentComponent\n          );\n        } else if (domType !== 8 || isFragmentStart) {\n          nextNode = onMismatch();\n        } else {\n          nextNode = nextSibling(node);\n        }\n        break;\n      case Static:\n        if (isFragmentStart) {\n          node = nextSibling(node);\n          domType = node.nodeType;\n        }\n        if (domType === 1 || domType === 3) {\n          nextNode = node;\n          const needToAdoptContent = !vnode.children.length;\n          for (let i = 0; i < vnode.staticCount; i++) {\n            if (needToAdoptContent)\n              vnode.children += nextNode.nodeType === 1 ? nextNode.outerHTML : nextNode.data;\n            if (i === vnode.staticCount - 1) {\n              vnode.anchor = nextNode;\n            }\n            nextNode = nextSibling(nextNode);\n          }\n          return isFragmentStart ? nextSibling(nextNode) : nextNode;\n        } else {\n          onMismatch();\n        }\n        break;\n      case Fragment:\n        if (!isFragmentStart) {\n          nextNode = onMismatch();\n        } else {\n          nextNode = hydrateFragment(\n            node,\n            vnode,\n            parentComponent,\n            parentSuspense,\n            slotScopeIds,\n            optimized\n          );\n        }\n        break;\n      default:\n        if (shapeFlag & 1) {\n          if ((domType !== 1 || vnode.type.toLowerCase() !== node.tagName.toLowerCase()) && !isTemplateNode(node)) {\n            nextNode = onMismatch();\n          } else {\n            nextNode = hydrateElement(\n              node,\n              vnode,\n              parentComponent,\n              parentSuspense,\n              slotScopeIds,\n              optimized\n            );\n          }\n        } else if (shapeFlag & 6) {\n          vnode.slotScopeIds = slotScopeIds;\n          const container = parentNode(node);\n          if (isFragmentStart) {\n            nextNode = locateClosingAnchor(node);\n          } else if (isComment(node) && node.data === \"teleport start\") {\n            nextNode = locateClosingAnchor(node, node.data, \"teleport end\");\n          } else {\n            nextNode = nextSibling(node);\n          }\n          mountComponent(\n            vnode,\n            container,\n            null,\n            parentComponent,\n            parentSuspense,\n            getContainerType(container),\n            optimized\n          );\n          if (isAsyncWrapper(vnode) && !vnode.type.__asyncResolved) {\n            let subTree;\n            if (isFragmentStart) {\n              subTree = createVNode(Fragment);\n              subTree.anchor = nextNode ? nextNode.previousSibling : container.lastChild;\n            } else {\n              subTree = node.nodeType === 3 ? createTextVNode(\"\") : createVNode(\"div\");\n            }\n            subTree.el = node;\n            vnode.component.subTree = subTree;\n          }\n        } else if (shapeFlag & 64) {\n          if (domType !== 8) {\n            nextNode = onMismatch();\n          } else {\n            nextNode = vnode.type.hydrate(\n              node,\n              vnode,\n              parentComponent,\n              parentSuspense,\n              slotScopeIds,\n              optimized,\n              rendererInternals,\n              hydrateChildren\n            );\n          }\n        } else if (shapeFlag & 128) {\n          nextNode = vnode.type.hydrate(\n            node,\n            vnode,\n            parentComponent,\n            parentSuspense,\n            getContainerType(parentNode(node)),\n            slotScopeIds,\n            optimized,\n            rendererInternals,\n            hydrateNode\n          );\n        } else ;\n    }\n    if (ref != null) {\n      setRef(ref, null, parentSuspense, vnode);\n    }\n    return nextNode;\n  };\n  const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {\n    optimized = optimized || !!vnode.dynamicChildren;\n    const { type, props, patchFlag, shapeFlag, dirs, transition } = vnode;\n    const forcePatch = type === \"input\" || type === \"option\";\n    if (forcePatch || patchFlag !== -1) {\n      if (dirs) {\n        invokeDirectiveHook(vnode, null, parentComponent, \"created\");\n      }\n      let needCallTransitionHooks = false;\n      if (isTemplateNode(el)) {\n        needCallTransitionHooks = needTransition(\n          null,\n          // no need check parentSuspense in hydration\n          transition\n        ) && parentComponent && parentComponent.vnode.props && parentComponent.vnode.props.appear;\n        const content = el.content.firstChild;\n        if (needCallTransitionHooks) {\n          const cls = content.getAttribute(\"class\");\n          if (cls) content.$cls = cls;\n          transition.beforeEnter(content);\n        }\n        replaceNode(content, el, parentComponent);\n        vnode.el = el = content;\n      }\n      if (shapeFlag & 16 && // skip if element has innerHTML / textContent\n      !(props && (props.innerHTML || props.textContent))) {\n        let next = hydrateChildren(\n          el.firstChild,\n          vnode,\n          el,\n          parentComponent,\n          parentSuspense,\n          slotScopeIds,\n          optimized\n        );\n        while (next) {\n          if (!isMismatchAllowed(el, 1 /* CHILDREN */)) {\n            logMismatchError();\n          }\n          const cur = next;\n          next = next.nextSibling;\n          remove(cur);\n        }\n      } else if (shapeFlag & 8) {\n        let clientText = vnode.children;\n        if (clientText[0] === \"\\n\" && (el.tagName === \"PRE\" || el.tagName === \"TEXTAREA\")) {\n          clientText = clientText.slice(1);\n        }\n        if (el.textContent !== clientText) {\n          if (!isMismatchAllowed(el, 0 /* TEXT */)) {\n            logMismatchError();\n          }\n          el.textContent = vnode.children;\n        }\n      }\n      if (props) {\n        if (forcePatch || !optimized || patchFlag & (16 | 32)) {\n          const isCustomElement = el.tagName.includes(\"-\");\n          for (const key in props) {\n            if (forcePatch && (key.endsWith(\"value\") || key === \"indeterminate\") || shared.isOn(key) && !shared.isReservedProp(key) || // force hydrate v-bind with .prop modifiers\n            key[0] === \".\" || isCustomElement) {\n              patchProp(el, key, null, props[key], void 0, parentComponent);\n            }\n          }\n        } else if (props.onClick) {\n          patchProp(\n            el,\n            \"onClick\",\n            null,\n            props.onClick,\n            void 0,\n            parentComponent\n          );\n        } else if (patchFlag & 4 && reactivity.isReactive(props.style)) {\n          for (const key in props.style) props.style[key];\n        }\n      }\n      let vnodeHooks;\n      if (vnodeHooks = props && props.onVnodeBeforeMount) {\n        invokeVNodeHook(vnodeHooks, parentComponent, vnode);\n      }\n      if (dirs) {\n        invokeDirectiveHook(vnode, null, parentComponent, \"beforeMount\");\n      }\n      if ((vnodeHooks = props && props.onVnodeMounted) || dirs || needCallTransitionHooks) {\n        queueEffectWithSuspense(() => {\n          vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);\n          needCallTransitionHooks && transition.enter(el);\n          dirs && invokeDirectiveHook(vnode, null, parentComponent, \"mounted\");\n        }, parentSuspense);\n      }\n    }\n    return el.nextSibling;\n  };\n  const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {\n    optimized = optimized || !!parentVNode.dynamicChildren;\n    const children = parentVNode.children;\n    const l = children.length;\n    for (let i = 0; i < l; i++) {\n      const vnode = optimized ? children[i] : children[i] = normalizeVNode(children[i]);\n      const isText = vnode.type === Text;\n      if (node) {\n        if (isText && !optimized) {\n          if (i + 1 < l && normalizeVNode(children[i + 1]).type === Text) {\n            insert(\n              createText(\n                node.data.slice(vnode.children.length)\n              ),\n              container,\n              nextSibling(node)\n            );\n            node.data = vnode.children;\n          }\n        }\n        node = hydrateNode(\n          node,\n          vnode,\n          parentComponent,\n          parentSuspense,\n          slotScopeIds,\n          optimized\n        );\n      } else if (isText && !vnode.children) {\n        insert(vnode.el = createText(\"\"), container);\n      } else {\n        if (!isMismatchAllowed(container, 1 /* CHILDREN */)) {\n          logMismatchError();\n        }\n        patch(\n          null,\n          vnode,\n          container,\n          null,\n          parentComponent,\n          parentSuspense,\n          getContainerType(container),\n          slotScopeIds\n        );\n      }\n    }\n    return node;\n  };\n  const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {\n    const { slotScopeIds: fragmentSlotScopeIds } = vnode;\n    if (fragmentSlotScopeIds) {\n      slotScopeIds = slotScopeIds ? slotScopeIds.concat(fragmentSlotScopeIds) : fragmentSlotScopeIds;\n    }\n    const container = parentNode(node);\n    const next = hydrateChildren(\n      nextSibling(node),\n      vnode,\n      container,\n      parentComponent,\n      parentSuspense,\n      slotScopeIds,\n      optimized\n    );\n    if (next && isComment(next) && next.data === \"]\") {\n      return nextSibling(vnode.anchor = next);\n    } else {\n      logMismatchError();\n      insert(vnode.anchor = createComment(`]`), container, next);\n      return next;\n    }\n  };\n  const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {\n    if (!isMismatchAllowed(node.parentElement, 1 /* CHILDREN */)) {\n      logMismatchError();\n    }\n    vnode.el = null;\n    if (isFragment) {\n      const end = locateClosingAnchor(node);\n      while (true) {\n        const next2 = nextSibling(node);\n        if (next2 && next2 !== end) {\n          remove(next2);\n        } else {\n          break;\n        }\n      }\n    }\n    const next = nextSibling(node);\n    const container = parentNode(node);\n    remove(node);\n    patch(\n      null,\n      vnode,\n      container,\n      next,\n      parentComponent,\n      parentSuspense,\n      getContainerType(container),\n      slotScopeIds\n    );\n    if (parentComponent) {\n      parentComponent.vnode.el = vnode.el;\n      updateHOCHostEl(parentComponent, vnode.el);\n    }\n    return next;\n  };\n  const locateClosingAnchor = (node, open = \"[\", close = \"]\") => {\n    let match = 0;\n    while (node) {\n      node = nextSibling(node);\n      if (node && isComment(node)) {\n        if (node.data === open) match++;\n        if (node.data === close) {\n          if (match === 0) {\n            return nextSibling(node);\n          } else {\n            match--;\n          }\n        }\n      }\n    }\n    return node;\n  };\n  const replaceNode = (newNode, oldNode, parentComponent) => {\n    const parentNode2 = oldNode.parentNode;\n    if (parentNode2) {\n      parentNode2.replaceChild(newNode, oldNode);\n    }\n    let parent = parentComponent;\n    while (parent) {\n      if (parent.vnode.el === oldNode) {\n        parent.vnode.el = parent.subTree.el = newNode;\n      }\n      parent = parent.parent;\n    }\n  };\n  const isTemplateNode = (node) => {\n    return node.nodeType === 1 && node.tagName === \"TEMPLATE\";\n  };\n  return [hydrate, hydrateNode];\n}\nconst allowMismatchAttr = \"data-allow-mismatch\";\nconst MismatchTypeString = {\n  [0 /* TEXT */]: \"text\",\n  [1 /* CHILDREN */]: \"children\",\n  [2 /* CLASS */]: \"class\",\n  [3 /* STYLE */]: \"style\",\n  [4 /* ATTRIBUTE */]: \"attribute\"\n};\nfunction isMismatchAllowed(el, allowedType) {\n  if (allowedType === 0 /* TEXT */ || allowedType === 1 /* CHILDREN */) {\n    while (el && !el.hasAttribute(allowMismatchAttr)) {\n      el = el.parentElement;\n    }\n  }\n  const allowedAttr = el && el.getAttribute(allowMismatchAttr);\n  if (allowedAttr == null) {\n    return false;\n  } else if (allowedAttr === \"\") {\n    return true;\n  } else {\n    const list = allowedAttr.split(\",\");\n    if (allowedType === 0 /* TEXT */ && list.includes(\"children\")) {\n      return true;\n    }\n    return list.includes(MismatchTypeString[allowedType]);\n  }\n}\n\nconst requestIdleCallback = shared.getGlobalThis().requestIdleCallback || ((cb) => setTimeout(cb, 1));\nconst cancelIdleCallback = shared.getGlobalThis().cancelIdleCallback || ((id) => clearTimeout(id));\nconst hydrateOnIdle = (timeout = 1e4) => (hydrate) => {\n  const id = requestIdleCallback(hydrate, { timeout });\n  return () => cancelIdleCallback(id);\n};\nfunction elementIsVisibleInViewport(el) {\n  const { top, left, bottom, right } = el.getBoundingClientRect();\n  const { innerHeight, innerWidth } = window;\n  return (top > 0 && top < innerHeight || bottom > 0 && bottom < innerHeight) && (left > 0 && left < innerWidth || right > 0 && right < innerWidth);\n}\nconst hydrateOnVisible = (opts) => (hydrate, forEach) => {\n  const ob = new IntersectionObserver((entries) => {\n    for (const e of entries) {\n      if (!e.isIntersecting) continue;\n      ob.disconnect();\n      hydrate();\n      break;\n    }\n  }, opts);\n  forEach((el) => {\n    if (!(el instanceof Element)) return;\n    if (elementIsVisibleInViewport(el)) {\n      hydrate();\n      ob.disconnect();\n      return false;\n    }\n    ob.observe(el);\n  });\n  return () => ob.disconnect();\n};\nconst hydrateOnMediaQuery = (query) => (hydrate) => {\n  if (query) {\n    const mql = matchMedia(query);\n    if (mql.matches) {\n      hydrate();\n    } else {\n      mql.addEventListener(\"change\", hydrate, { once: true });\n      return () => mql.removeEventListener(\"change\", hydrate);\n    }\n  }\n};\nconst hydrateOnInteraction = (interactions = []) => (hydrate, forEach) => {\n  if (shared.isString(interactions)) interactions = [interactions];\n  let hasHydrated = false;\n  const doHydrate = (e) => {\n    if (!hasHydrated) {\n      hasHydrated = true;\n      teardown();\n      hydrate();\n      e.target.dispatchEvent(new e.constructor(e.type, e));\n    }\n  };\n  const teardown = () => {\n    forEach((el) => {\n      for (const i of interactions) {\n        el.removeEventListener(i, doHydrate);\n      }\n    });\n  };\n  forEach((el) => {\n    for (const i of interactions) {\n      el.addEventListener(i, doHydrate, { once: true });\n    }\n  });\n  return teardown;\n};\nfunction forEachElement(node, cb) {\n  if (isComment(node) && node.data === \"[\") {\n    let depth = 1;\n    let next = node.nextSibling;\n    while (next) {\n      if (next.nodeType === 1) {\n        const result = cb(next);\n        if (result === false) {\n          break;\n        }\n      } else if (isComment(next)) {\n        if (next.data === \"]\") {\n          if (--depth === 0) break;\n        } else if (next.data === \"[\") {\n          depth++;\n        }\n      }\n      next = next.nextSibling;\n    }\n  } else {\n    cb(node);\n  }\n}\n\nconst isAsyncWrapper = (i) => !!i.type.__asyncLoader;\n/*! #__NO_SIDE_EFFECTS__ */\n// @__NO_SIDE_EFFECTS__\nfunction defineAsyncComponent(source) {\n  if (shared.isFunction(source)) {\n    source = { loader: source };\n  }\n  const {\n    loader,\n    loadingComponent,\n    errorComponent,\n    delay = 200,\n    hydrate: hydrateStrategy,\n    timeout,\n    // undefined = never times out\n    suspensible = true,\n    onError: userOnError\n  } = source;\n  let pendingRequest = null;\n  let resolvedComp;\n  let retries = 0;\n  const retry = () => {\n    retries++;\n    pendingRequest = null;\n    return load();\n  };\n  const load = () => {\n    let thisRequest;\n    return pendingRequest || (thisRequest = pendingRequest = loader().catch((err) => {\n      err = err instanceof Error ? err : new Error(String(err));\n      if (userOnError) {\n        return new Promise((resolve, reject) => {\n          const userRetry = () => resolve(retry());\n          const userFail = () => reject(err);\n          userOnError(err, userRetry, userFail, retries + 1);\n        });\n      } else {\n        throw err;\n      }\n    }).then((comp) => {\n      if (thisRequest !== pendingRequest && pendingRequest) {\n        return pendingRequest;\n      }\n      if (comp && (comp.__esModule || comp[Symbol.toStringTag] === \"Module\")) {\n        comp = comp.default;\n      }\n      resolvedComp = comp;\n      return comp;\n    }));\n  };\n  return defineComponent({\n    name: \"AsyncComponentWrapper\",\n    __asyncLoader: load,\n    __asyncHydrate(el, instance, hydrate) {\n      let patched = false;\n      (instance.bu || (instance.bu = [])).push(() => patched = true);\n      const performHydrate = () => {\n        if (patched) {\n          return;\n        }\n        hydrate();\n      };\n      const doHydrate = hydrateStrategy ? () => {\n        const teardown = hydrateStrategy(\n          performHydrate,\n          (cb) => forEachElement(el, cb)\n        );\n        if (teardown) {\n          (instance.bum || (instance.bum = [])).push(teardown);\n        }\n      } : performHydrate;\n      if (resolvedComp) {\n        doHydrate();\n      } else {\n        load().then(() => !instance.isUnmounted && doHydrate());\n      }\n    },\n    get __asyncResolved() {\n      return resolvedComp;\n    },\n    setup() {\n      const instance = currentInstance;\n      markAsyncBoundary(instance);\n      if (resolvedComp) {\n        return () => createInnerComp(resolvedComp, instance);\n      }\n      const onError = (err) => {\n        pendingRequest = null;\n        handleError(\n          err,\n          instance,\n          13,\n          !errorComponent\n        );\n      };\n      if (suspensible && instance.suspense || isInSSRComponentSetup) {\n        return load().then((comp) => {\n          return () => createInnerComp(comp, instance);\n        }).catch((err) => {\n          onError(err);\n          return () => errorComponent ? createVNode(errorComponent, {\n            error: err\n          }) : null;\n        });\n      }\n      const loaded = reactivity.ref(false);\n      const error = reactivity.ref();\n      const delayed = reactivity.ref(!!delay);\n      if (delay) {\n        setTimeout(() => {\n          delayed.value = false;\n        }, delay);\n      }\n      if (timeout != null) {\n        setTimeout(() => {\n          if (!loaded.value && !error.value) {\n            const err = new Error(\n              `Async component timed out after ${timeout}ms.`\n            );\n            onError(err);\n            error.value = err;\n          }\n        }, timeout);\n      }\n      load().then(() => {\n        loaded.value = true;\n        if (instance.parent && isKeepAlive(instance.parent.vnode)) {\n          instance.parent.update();\n        }\n      }).catch((err) => {\n        onError(err);\n        error.value = err;\n      });\n      return () => {\n        if (loaded.value && resolvedComp) {\n          return createInnerComp(resolvedComp, instance);\n        } else if (error.value && errorComponent) {\n          return createVNode(errorComponent, {\n            error: error.value\n          });\n        } else if (loadingComponent && !delayed.value) {\n          return createVNode(loadingComponent);\n        }\n      };\n    }\n  });\n}\nfunction createInnerComp(comp, parent) {\n  const { ref: ref2, props, children, ce } = parent.vnode;\n  const vnode = createVNode(comp, props, children);\n  vnode.ref = ref2;\n  vnode.ce = ce;\n  delete parent.vnode.ce;\n  return vnode;\n}\n\nconst isKeepAlive = (vnode) => vnode.type.__isKeepAlive;\nconst KeepAliveImpl = {\n  name: `KeepAlive`,\n  // Marker for special handling inside the renderer. We are not using a ===\n  // check directly on KeepAlive in the renderer, because importing it directly\n  // would prevent it from being tree-shaken.\n  __isKeepAlive: true,\n  props: {\n    include: [String, RegExp, Array],\n    exclude: [String, RegExp, Array],\n    max: [String, Number]\n  },\n  setup(props, { slots }) {\n    const instance = getCurrentInstance();\n    const sharedContext = instance.ctx;\n    if (!sharedContext.renderer) {\n      return () => {\n        const children = slots.default && slots.default();\n        return children && children.length === 1 ? children[0] : children;\n      };\n    }\n    const cache = /* @__PURE__ */ new Map();\n    const keys = /* @__PURE__ */ new Set();\n    let current = null;\n    const parentSuspense = instance.suspense;\n    const {\n      renderer: {\n        p: patch,\n        m: move,\n        um: _unmount,\n        o: { createElement }\n      }\n    } = sharedContext;\n    const storageContainer = createElement(\"div\");\n    sharedContext.activate = (vnode, container, anchor, namespace, optimized) => {\n      const instance2 = vnode.component;\n      move(vnode, container, anchor, 0, parentSuspense);\n      patch(\n        instance2.vnode,\n        vnode,\n        container,\n        anchor,\n        instance2,\n        parentSuspense,\n        namespace,\n        vnode.slotScopeIds,\n        optimized\n      );\n      queuePostRenderEffect(() => {\n        instance2.isDeactivated = false;\n        if (instance2.a) {\n          shared.invokeArrayFns(instance2.a);\n        }\n        const vnodeHook = vnode.props && vnode.props.onVnodeMounted;\n        if (vnodeHook) {\n          invokeVNodeHook(vnodeHook, instance2.parent, vnode);\n        }\n      }, parentSuspense);\n    };\n    sharedContext.deactivate = (vnode) => {\n      const instance2 = vnode.component;\n      invalidateMount(instance2.m);\n      invalidateMount(instance2.a);\n      move(vnode, storageContainer, null, 1, parentSuspense);\n      queuePostRenderEffect(() => {\n        if (instance2.da) {\n          shared.invokeArrayFns(instance2.da);\n        }\n        const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;\n        if (vnodeHook) {\n          invokeVNodeHook(vnodeHook, instance2.parent, vnode);\n        }\n        instance2.isDeactivated = true;\n      }, parentSuspense);\n    };\n    function unmount(vnode) {\n      resetShapeFlag(vnode);\n      _unmount(vnode, instance, parentSuspense, true);\n    }\n    function pruneCache(filter) {\n      cache.forEach((vnode, key) => {\n        const name = getComponentName(vnode.type);\n        if (name && !filter(name)) {\n          pruneCacheEntry(key);\n        }\n      });\n    }\n    function pruneCacheEntry(key) {\n      const cached = cache.get(key);\n      if (cached && (!current || !isSameVNodeType(cached, current))) {\n        unmount(cached);\n      } else if (current) {\n        resetShapeFlag(current);\n      }\n      cache.delete(key);\n      keys.delete(key);\n    }\n    watch(\n      () => [props.include, props.exclude],\n      ([include, exclude]) => {\n        include && pruneCache((name) => matches(include, name));\n        exclude && pruneCache((name) => !matches(exclude, name));\n      },\n      // prune post-render after `current` has been updated\n      { flush: \"post\", deep: true }\n    );\n    let pendingCacheKey = null;\n    const cacheSubtree = () => {\n      if (pendingCacheKey != null) {\n        if (isSuspense(instance.subTree.type)) {\n          queuePostRenderEffect(() => {\n            cache.set(pendingCacheKey, getInnerChild(instance.subTree));\n          }, instance.subTree.suspense);\n        } else {\n          cache.set(pendingCacheKey, getInnerChild(instance.subTree));\n        }\n      }\n    };\n    onMounted(cacheSubtree);\n    onUpdated(cacheSubtree);\n    onBeforeUnmount(() => {\n      cache.forEach((cached) => {\n        const { subTree, suspense } = instance;\n        const vnode = getInnerChild(subTree);\n        if (cached.type === vnode.type && cached.key === vnode.key) {\n          resetShapeFlag(vnode);\n          const da = vnode.component.da;\n          da && queuePostRenderEffect(da, suspense);\n          return;\n        }\n        unmount(cached);\n      });\n    });\n    return () => {\n      pendingCacheKey = null;\n      if (!slots.default) {\n        return current = null;\n      }\n      const children = slots.default();\n      const rawVNode = children[0];\n      if (children.length > 1) {\n        current = null;\n        return children;\n      } else if (!isVNode(rawVNode) || !(rawVNode.shapeFlag & 4) && !(rawVNode.shapeFlag & 128)) {\n        current = null;\n        return rawVNode;\n      }\n      let vnode = getInnerChild(rawVNode);\n      if (vnode.type === Comment) {\n        current = null;\n        return vnode;\n      }\n      const comp = vnode.type;\n      const name = getComponentName(\n        isAsyncWrapper(vnode) ? vnode.type.__asyncResolved || {} : comp\n      );\n      const { include, exclude, max } = props;\n      if (include && (!name || !matches(include, name)) || exclude && name && matches(exclude, name)) {\n        vnode.shapeFlag &= -257;\n        current = vnode;\n        return rawVNode;\n      }\n      const key = vnode.key == null ? comp : vnode.key;\n      const cachedVNode = cache.get(key);\n      if (vnode.el) {\n        vnode = cloneVNode(vnode);\n        if (rawVNode.shapeFlag & 128) {\n          rawVNode.ssContent = vnode;\n        }\n      }\n      pendingCacheKey = key;\n      if (cachedVNode) {\n        vnode.el = cachedVNode.el;\n        vnode.component = cachedVNode.component;\n        if (vnode.transition) {\n          setTransitionHooks(vnode, vnode.transition);\n        }\n        vnode.shapeFlag |= 512;\n        keys.delete(key);\n        keys.add(key);\n      } else {\n        keys.add(key);\n        if (max && keys.size > parseInt(max, 10)) {\n          pruneCacheEntry(keys.values().next().value);\n        }\n      }\n      vnode.shapeFlag |= 256;\n      current = vnode;\n      return isSuspense(rawVNode.type) ? rawVNode : vnode;\n    };\n  }\n};\nconst KeepAlive = KeepAliveImpl;\nfunction matches(pattern, name) {\n  if (shared.isArray(pattern)) {\n    return pattern.some((p) => matches(p, name));\n  } else if (shared.isString(pattern)) {\n    return pattern.split(\",\").includes(name);\n  } else if (shared.isRegExp(pattern)) {\n    pattern.lastIndex = 0;\n    return pattern.test(name);\n  }\n  return false;\n}\nfunction onActivated(hook, target) {\n  registerKeepAliveHook(hook, \"a\", target);\n}\nfunction onDeactivated(hook, target) {\n  registerKeepAliveHook(hook, \"da\", target);\n}\nfunction registerKeepAliveHook(hook, type, target = currentInstance) {\n  const wrappedHook = hook.__wdc || (hook.__wdc = () => {\n    let current = target;\n    while (current) {\n      if (current.isDeactivated) {\n        return;\n      }\n      current = current.parent;\n    }\n    return hook();\n  });\n  injectHook(type, wrappedHook, target);\n  if (target) {\n    let current = target.parent;\n    while (current && current.parent) {\n      if (isKeepAlive(current.parent.vnode)) {\n        injectToKeepAliveRoot(wrappedHook, type, target, current);\n      }\n      current = current.parent;\n    }\n  }\n}\nfunction injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {\n  const injected = injectHook(\n    type,\n    hook,\n    keepAliveRoot,\n    true\n    /* prepend */\n  );\n  onUnmounted(() => {\n    shared.remove(keepAliveRoot[type], injected);\n  }, target);\n}\nfunction resetShapeFlag(vnode) {\n  vnode.shapeFlag &= -257;\n  vnode.shapeFlag &= -513;\n}\nfunction getInnerChild(vnode) {\n  return vnode.shapeFlag & 128 ? vnode.ssContent : vnode;\n}\n\nfunction injectHook(type, hook, target = currentInstance, prepend = false) {\n  if (target) {\n    const hooks = target[type] || (target[type] = []);\n    const wrappedHook = hook.__weh || (hook.__weh = (...args) => {\n      reactivity.pauseTracking();\n      const reset = setCurrentInstance(target);\n      const res = callWithAsyncErrorHandling(hook, target, type, args);\n      reset();\n      reactivity.resetTracking();\n      return res;\n    });\n    if (prepend) {\n      hooks.unshift(wrappedHook);\n    } else {\n      hooks.push(wrappedHook);\n    }\n    return wrappedHook;\n  }\n}\nconst createHook = (lifecycle) => (hook, target = currentInstance) => {\n  if (!isInSSRComponentSetup || lifecycle === \"sp\") {\n    injectHook(lifecycle, (...args) => hook(...args), target);\n  }\n};\nconst onBeforeMount = createHook(\"bm\");\nconst onMounted = createHook(\"m\");\nconst onBeforeUpdate = createHook(\n  \"bu\"\n);\nconst onUpdated = createHook(\"u\");\nconst onBeforeUnmount = createHook(\n  \"bum\"\n);\nconst onUnmounted = createHook(\"um\");\nconst onServerPrefetch = createHook(\n  \"sp\"\n);\nconst onRenderTriggered = createHook(\"rtg\");\nconst onRenderTracked = createHook(\"rtc\");\nfunction onErrorCaptured(hook, target = currentInstance) {\n  injectHook(\"ec\", hook, target);\n}\n\nconst COMPONENTS = \"components\";\nconst DIRECTIVES = \"directives\";\nfunction resolveComponent(name, maybeSelfReference) {\n  return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;\n}\nconst NULL_DYNAMIC_COMPONENT = Symbol.for(\"v-ndc\");\nfunction resolveDynamicComponent(component) {\n  if (shared.isString(component)) {\n    return resolveAsset(COMPONENTS, component, false) || component;\n  } else {\n    return component || NULL_DYNAMIC_COMPONENT;\n  }\n}\nfunction resolveDirective(name) {\n  return resolveAsset(DIRECTIVES, name);\n}\nfunction resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {\n  const instance = currentRenderingInstance || currentInstance;\n  if (instance) {\n    const Component = instance.type;\n    if (type === COMPONENTS) {\n      const selfName = getComponentName(\n        Component,\n        false\n      );\n      if (selfName && (selfName === name || selfName === shared.camelize(name) || selfName === shared.capitalize(shared.camelize(name)))) {\n        return Component;\n      }\n    }\n    const res = (\n      // local registration\n      // check instance[type] first which is resolved for options API\n      resolve(instance[type] || Component[type], name) || // global registration\n      resolve(instance.appContext[type], name)\n    );\n    if (!res && maybeSelfReference) {\n      return Component;\n    }\n    return res;\n  }\n}\nfunction resolve(registry, name) {\n  return registry && (registry[name] || registry[shared.camelize(name)] || registry[shared.capitalize(shared.camelize(name))]);\n}\n\nfunction renderList(source, renderItem, cache, index) {\n  let ret;\n  const cached = cache && cache[index];\n  const sourceIsArray = shared.isArray(source);\n  if (sourceIsArray || shared.isString(source)) {\n    const sourceIsReactiveArray = sourceIsArray && reactivity.isReactive(source);\n    let needsWrap = false;\n    let isReadonlySource = false;\n    if (sourceIsReactiveArray) {\n      needsWrap = !reactivity.isShallow(source);\n      isReadonlySource = reactivity.isReadonly(source);\n      source = reactivity.shallowReadArray(source);\n    }\n    ret = new Array(source.length);\n    for (let i = 0, l = source.length; i < l; i++) {\n      ret[i] = renderItem(\n        needsWrap ? isReadonlySource ? reactivity.toReadonly(reactivity.toReactive(source[i])) : reactivity.toReactive(source[i]) : source[i],\n        i,\n        void 0,\n        cached && cached[i]\n      );\n    }\n  } else if (typeof source === \"number\") {\n    ret = new Array(source);\n    for (let i = 0; i < source; i++) {\n      ret[i] = renderItem(i + 1, i, void 0, cached && cached[i]);\n    }\n  } else if (shared.isObject(source)) {\n    if (source[Symbol.iterator]) {\n      ret = Array.from(\n        source,\n        (item, i) => renderItem(item, i, void 0, cached && cached[i])\n      );\n    } else {\n      const keys = Object.keys(source);\n      ret = new Array(keys.length);\n      for (let i = 0, l = keys.length; i < l; i++) {\n        const key = keys[i];\n        ret[i] = renderItem(source[key], key, i, cached && cached[i]);\n      }\n    }\n  } else {\n    ret = [];\n  }\n  if (cache) {\n    cache[index] = ret;\n  }\n  return ret;\n}\n\nfunction createSlots(slots, dynamicSlots) {\n  for (let i = 0; i < dynamicSlots.length; i++) {\n    const slot = dynamicSlots[i];\n    if (shared.isArray(slot)) {\n      for (let j = 0; j < slot.length; j++) {\n        slots[slot[j].name] = slot[j].fn;\n      }\n    } else if (slot) {\n      slots[slot.name] = slot.key ? (...args) => {\n        const res = slot.fn(...args);\n        if (res) res.key = slot.key;\n        return res;\n      } : slot.fn;\n    }\n  }\n  return slots;\n}\n\nfunction renderSlot(slots, name, props = {}, fallback, noSlotted) {\n  if (currentRenderingInstance.ce || currentRenderingInstance.parent && isAsyncWrapper(currentRenderingInstance.parent) && currentRenderingInstance.parent.ce) {\n    if (name !== \"default\") props.name = name;\n    return openBlock(), createBlock(\n      Fragment,\n      null,\n      [createVNode(\"slot\", props, fallback && fallback())],\n      64\n    );\n  }\n  let slot = slots[name];\n  if (slot && slot._c) {\n    slot._d = false;\n  }\n  openBlock();\n  const validSlotContent = slot && ensureValidVNode(slot(props));\n  const slotKey = props.key || // slot content array of a dynamic conditional slot may have a branch\n  // key attached in the `createSlots` helper, respect that\n  validSlotContent && validSlotContent.key;\n  const rendered = createBlock(\n    Fragment,\n    {\n      key: (slotKey && !shared.isSymbol(slotKey) ? slotKey : `_${name}`) + // #7256 force differentiate fallback content from actual content\n      (!validSlotContent && fallback ? \"_fb\" : \"\")\n    },\n    validSlotContent || (fallback ? fallback() : []),\n    validSlotContent && slots._ === 1 ? 64 : -2\n  );\n  if (!noSlotted && rendered.scopeId) {\n    rendered.slotScopeIds = [rendered.scopeId + \"-s\"];\n  }\n  if (slot && slot._c) {\n    slot._d = true;\n  }\n  return rendered;\n}\nfunction ensureValidVNode(vnodes) {\n  return vnodes.some((child) => {\n    if (!isVNode(child)) return true;\n    if (child.type === Comment) return false;\n    if (child.type === Fragment && !ensureValidVNode(child.children))\n      return false;\n    return true;\n  }) ? vnodes : null;\n}\n\nfunction toHandlers(obj, preserveCaseIfNecessary) {\n  const ret = {};\n  for (const key in obj) {\n    ret[preserveCaseIfNecessary && /[A-Z]/.test(key) ? `on:${key}` : shared.toHandlerKey(key)] = obj[key];\n  }\n  return ret;\n}\n\nconst getPublicInstance = (i) => {\n  if (!i) return null;\n  if (isStatefulComponent(i)) return getComponentPublicInstance(i);\n  return getPublicInstance(i.parent);\n};\nconst publicPropertiesMap = (\n  // Move PURE marker to new line to workaround compiler discarding it\n  // due to type annotation\n  /* @__PURE__ */ shared.extend(/* @__PURE__ */ Object.create(null), {\n    $: (i) => i,\n    $el: (i) => i.vnode.el,\n    $data: (i) => i.data,\n    $props: (i) => i.props,\n    $attrs: (i) => i.attrs,\n    $slots: (i) => i.slots,\n    $refs: (i) => i.refs,\n    $parent: (i) => getPublicInstance(i.parent),\n    $root: (i) => getPublicInstance(i.root),\n    $host: (i) => i.ce,\n    $emit: (i) => i.emit,\n    $options: (i) => resolveMergedOptions(i) ,\n    $forceUpdate: (i) => i.f || (i.f = () => {\n      queueJob(i.update);\n    }),\n    $nextTick: (i) => i.n || (i.n = nextTick.bind(i.proxy)),\n    $watch: (i) => instanceWatch.bind(i) \n  })\n);\nconst hasSetupBinding = (state, key) => state !== shared.EMPTY_OBJ && !state.__isScriptSetup && shared.hasOwn(state, key);\nconst PublicInstanceProxyHandlers = {\n  get({ _: instance }, key) {\n    if (key === \"__v_skip\") {\n      return true;\n    }\n    const { ctx, setupState, data, props, accessCache, type, appContext } = instance;\n    let normalizedProps;\n    if (key[0] !== \"$\") {\n      const n = accessCache[key];\n      if (n !== void 0) {\n        switch (n) {\n          case 1 /* SETUP */:\n            return setupState[key];\n          case 2 /* DATA */:\n            return data[key];\n          case 4 /* CONTEXT */:\n            return ctx[key];\n          case 3 /* PROPS */:\n            return props[key];\n        }\n      } else if (hasSetupBinding(setupState, key)) {\n        accessCache[key] = 1 /* SETUP */;\n        return setupState[key];\n      } else if (data !== shared.EMPTY_OBJ && shared.hasOwn(data, key)) {\n        accessCache[key] = 2 /* DATA */;\n        return data[key];\n      } else if (\n        // only cache other properties when instance has declared (thus stable)\n        // props\n        (normalizedProps = instance.propsOptions[0]) && shared.hasOwn(normalizedProps, key)\n      ) {\n        accessCache[key] = 3 /* PROPS */;\n        return props[key];\n      } else if (ctx !== shared.EMPTY_OBJ && shared.hasOwn(ctx, key)) {\n        accessCache[key] = 4 /* CONTEXT */;\n        return ctx[key];\n      } else if (shouldCacheAccess) {\n        accessCache[key] = 0 /* OTHER */;\n      }\n    }\n    const publicGetter = publicPropertiesMap[key];\n    let cssModule, globalProperties;\n    if (publicGetter) {\n      if (key === \"$attrs\") {\n        reactivity.track(instance.attrs, \"get\", \"\");\n      }\n      return publicGetter(instance);\n    } else if (\n      // css module (injected by vue-loader)\n      (cssModule = type.__cssModules) && (cssModule = cssModule[key])\n    ) {\n      return cssModule;\n    } else if (ctx !== shared.EMPTY_OBJ && shared.hasOwn(ctx, key)) {\n      accessCache[key] = 4 /* CONTEXT */;\n      return ctx[key];\n    } else if (\n      // global properties\n      globalProperties = appContext.config.globalProperties, shared.hasOwn(globalProperties, key)\n    ) {\n      {\n        return globalProperties[key];\n      }\n    } else ;\n  },\n  set({ _: instance }, key, value) {\n    const { data, setupState, ctx } = instance;\n    if (hasSetupBinding(setupState, key)) {\n      setupState[key] = value;\n      return true;\n    } else if (data !== shared.EMPTY_OBJ && shared.hasOwn(data, key)) {\n      data[key] = value;\n      return true;\n    } else if (shared.hasOwn(instance.props, key)) {\n      return false;\n    }\n    if (key[0] === \"$\" && key.slice(1) in instance) {\n      return false;\n    } else {\n      {\n        ctx[key] = value;\n      }\n    }\n    return true;\n  },\n  has({\n    _: { data, setupState, accessCache, ctx, appContext, propsOptions }\n  }, key) {\n    let normalizedProps;\n    return !!accessCache[key] || data !== shared.EMPTY_OBJ && shared.hasOwn(data, key) || hasSetupBinding(setupState, key) || (normalizedProps = propsOptions[0]) && shared.hasOwn(normalizedProps, key) || shared.hasOwn(ctx, key) || shared.hasOwn(publicPropertiesMap, key) || shared.hasOwn(appContext.config.globalProperties, key);\n  },\n  defineProperty(target, key, descriptor) {\n    if (descriptor.get != null) {\n      target._.accessCache[key] = 0;\n    } else if (shared.hasOwn(descriptor, \"value\")) {\n      this.set(target, key, descriptor.value, null);\n    }\n    return Reflect.defineProperty(target, key, descriptor);\n  }\n};\nconst RuntimeCompiledPublicInstanceProxyHandlers = /* @__PURE__ */ shared.extend({}, PublicInstanceProxyHandlers, {\n  get(target, key) {\n    if (key === Symbol.unscopables) {\n      return;\n    }\n    return PublicInstanceProxyHandlers.get(target, key, target);\n  },\n  has(_, key) {\n    const has = key[0] !== \"_\" && !shared.isGloballyAllowed(key);\n    return has;\n  }\n});\n\nfunction defineProps() {\n  return null;\n}\nfunction defineEmits() {\n  return null;\n}\nfunction defineExpose(exposed) {\n}\nfunction defineOptions(options) {\n}\nfunction defineSlots() {\n  return null;\n}\nfunction defineModel() {\n}\nfunction withDefaults(props, defaults) {\n  return null;\n}\nfunction useSlots() {\n  return getContext().slots;\n}\nfunction useAttrs() {\n  return getContext().attrs;\n}\nfunction getContext(calledFunctionName) {\n  const i = getCurrentInstance();\n  return i.setupContext || (i.setupContext = createSetupContext(i));\n}\nfunction normalizePropsOrEmits(props) {\n  return shared.isArray(props) ? props.reduce(\n    (normalized, p) => (normalized[p] = null, normalized),\n    {}\n  ) : props;\n}\nfunction mergeDefaults(raw, defaults) {\n  const props = normalizePropsOrEmits(raw);\n  for (const key in defaults) {\n    if (key.startsWith(\"__skip\")) continue;\n    let opt = props[key];\n    if (opt) {\n      if (shared.isArray(opt) || shared.isFunction(opt)) {\n        opt = props[key] = { type: opt, default: defaults[key] };\n      } else {\n        opt.default = defaults[key];\n      }\n    } else if (opt === null) {\n      opt = props[key] = { default: defaults[key] };\n    } else ;\n    if (opt && defaults[`__skip_${key}`]) {\n      opt.skipFactory = true;\n    }\n  }\n  return props;\n}\nfunction mergeModels(a, b) {\n  if (!a || !b) return a || b;\n  if (shared.isArray(a) && shared.isArray(b)) return a.concat(b);\n  return shared.extend({}, normalizePropsOrEmits(a), normalizePropsOrEmits(b));\n}\nfunction createPropsRestProxy(props, excludedKeys) {\n  const ret = {};\n  for (const key in props) {\n    if (!excludedKeys.includes(key)) {\n      Object.defineProperty(ret, key, {\n        enumerable: true,\n        get: () => props[key]\n      });\n    }\n  }\n  return ret;\n}\nfunction withAsyncContext(getAwaitable) {\n  const ctx = getCurrentInstance();\n  let awaitable = getAwaitable();\n  unsetCurrentInstance();\n  if (shared.isPromise(awaitable)) {\n    awaitable = awaitable.catch((e) => {\n      setCurrentInstance(ctx);\n      throw e;\n    });\n  }\n  return [awaitable, () => setCurrentInstance(ctx)];\n}\n\nlet shouldCacheAccess = true;\nfunction applyOptions(instance) {\n  const options = resolveMergedOptions(instance);\n  const publicThis = instance.proxy;\n  const ctx = instance.ctx;\n  shouldCacheAccess = false;\n  if (options.beforeCreate) {\n    callHook(options.beforeCreate, instance, \"bc\");\n  }\n  const {\n    // state\n    data: dataOptions,\n    computed: computedOptions,\n    methods,\n    watch: watchOptions,\n    provide: provideOptions,\n    inject: injectOptions,\n    // lifecycle\n    created,\n    beforeMount,\n    mounted,\n    beforeUpdate,\n    updated,\n    activated,\n    deactivated,\n    beforeDestroy,\n    beforeUnmount,\n    destroyed,\n    unmounted,\n    render,\n    renderTracked,\n    renderTriggered,\n    errorCaptured,\n    serverPrefetch,\n    // public API\n    expose,\n    inheritAttrs,\n    // assets\n    components,\n    directives,\n    filters\n  } = options;\n  const checkDuplicateProperties = null;\n  if (injectOptions) {\n    resolveInjections(injectOptions, ctx, checkDuplicateProperties);\n  }\n  if (methods) {\n    for (const key in methods) {\n      const methodHandler = methods[key];\n      if (shared.isFunction(methodHandler)) {\n        {\n          ctx[key] = methodHandler.bind(publicThis);\n        }\n      }\n    }\n  }\n  if (dataOptions) {\n    const data = dataOptions.call(publicThis, publicThis);\n    if (!shared.isObject(data)) ; else {\n      instance.data = reactivity.reactive(data);\n    }\n  }\n  shouldCacheAccess = true;\n  if (computedOptions) {\n    for (const key in computedOptions) {\n      const opt = computedOptions[key];\n      const get = shared.isFunction(opt) ? opt.bind(publicThis, publicThis) : shared.isFunction(opt.get) ? opt.get.bind(publicThis, publicThis) : shared.NOOP;\n      const set = !shared.isFunction(opt) && shared.isFunction(opt.set) ? opt.set.bind(publicThis) : shared.NOOP;\n      const c = computed({\n        get,\n        set\n      });\n      Object.defineProperty(ctx, key, {\n        enumerable: true,\n        configurable: true,\n        get: () => c.value,\n        set: (v) => c.value = v\n      });\n    }\n  }\n  if (watchOptions) {\n    for (const key in watchOptions) {\n      createWatcher(watchOptions[key], ctx, publicThis, key);\n    }\n  }\n  if (provideOptions) {\n    const provides = shared.isFunction(provideOptions) ? provideOptions.call(publicThis) : provideOptions;\n    Reflect.ownKeys(provides).forEach((key) => {\n      provide(key, provides[key]);\n    });\n  }\n  if (created) {\n    callHook(created, instance, \"c\");\n  }\n  function registerLifecycleHook(register, hook) {\n    if (shared.isArray(hook)) {\n      hook.forEach((_hook) => register(_hook.bind(publicThis)));\n    } else if (hook) {\n      register(hook.bind(publicThis));\n    }\n  }\n  registerLifecycleHook(onBeforeMount, beforeMount);\n  registerLifecycleHook(onMounted, mounted);\n  registerLifecycleHook(onBeforeUpdate, beforeUpdate);\n  registerLifecycleHook(onUpdated, updated);\n  registerLifecycleHook(onActivated, activated);\n  registerLifecycleHook(onDeactivated, deactivated);\n  registerLifecycleHook(onErrorCaptured, errorCaptured);\n  registerLifecycleHook(onRenderTracked, renderTracked);\n  registerLifecycleHook(onRenderTriggered, renderTriggered);\n  registerLifecycleHook(onBeforeUnmount, beforeUnmount);\n  registerLifecycleHook(onUnmounted, unmounted);\n  registerLifecycleHook(onServerPrefetch, serverPrefetch);\n  if (shared.isArray(expose)) {\n    if (expose.length) {\n      const exposed = instance.exposed || (instance.exposed = {});\n      expose.forEach((key) => {\n        Object.defineProperty(exposed, key, {\n          get: () => publicThis[key],\n          set: (val) => publicThis[key] = val,\n          enumerable: true\n        });\n      });\n    } else if (!instance.exposed) {\n      instance.exposed = {};\n    }\n  }\n  if (render && instance.render === shared.NOOP) {\n    instance.render = render;\n  }\n  if (inheritAttrs != null) {\n    instance.inheritAttrs = inheritAttrs;\n  }\n  if (components) instance.components = components;\n  if (directives) instance.directives = directives;\n  if (serverPrefetch) {\n    markAsyncBoundary(instance);\n  }\n}\nfunction resolveInjections(injectOptions, ctx, checkDuplicateProperties = shared.NOOP) {\n  if (shared.isArray(injectOptions)) {\n    injectOptions = normalizeInject(injectOptions);\n  }\n  for (const key in injectOptions) {\n    const opt = injectOptions[key];\n    let injected;\n    if (shared.isObject(opt)) {\n      if (\"default\" in opt) {\n        injected = inject(\n          opt.from || key,\n          opt.default,\n          true\n        );\n      } else {\n        injected = inject(opt.from || key);\n      }\n    } else {\n      injected = inject(opt);\n    }\n    if (reactivity.isRef(injected)) {\n      Object.defineProperty(ctx, key, {\n        enumerable: true,\n        configurable: true,\n        get: () => injected.value,\n        set: (v) => injected.value = v\n      });\n    } else {\n      ctx[key] = injected;\n    }\n  }\n}\nfunction callHook(hook, instance, type) {\n  callWithAsyncErrorHandling(\n    shared.isArray(hook) ? hook.map((h) => h.bind(instance.proxy)) : hook.bind(instance.proxy),\n    instance,\n    type\n  );\n}\nfunction createWatcher(raw, ctx, publicThis, key) {\n  let getter = key.includes(\".\") ? createPathGetter(publicThis, key) : () => publicThis[key];\n  if (shared.isString(raw)) {\n    const handler = ctx[raw];\n    if (shared.isFunction(handler)) {\n      {\n        watch(getter, handler);\n      }\n    }\n  } else if (shared.isFunction(raw)) {\n    {\n      watch(getter, raw.bind(publicThis));\n    }\n  } else if (shared.isObject(raw)) {\n    if (shared.isArray(raw)) {\n      raw.forEach((r) => createWatcher(r, ctx, publicThis, key));\n    } else {\n      const handler = shared.isFunction(raw.handler) ? raw.handler.bind(publicThis) : ctx[raw.handler];\n      if (shared.isFunction(handler)) {\n        watch(getter, handler, raw);\n      }\n    }\n  } else ;\n}\nfunction resolveMergedOptions(instance) {\n  const base = instance.type;\n  const { mixins, extends: extendsOptions } = base;\n  const {\n    mixins: globalMixins,\n    optionsCache: cache,\n    config: { optionMergeStrategies }\n  } = instance.appContext;\n  const cached = cache.get(base);\n  let resolved;\n  if (cached) {\n    resolved = cached;\n  } else if (!globalMixins.length && !mixins && !extendsOptions) {\n    {\n      resolved = base;\n    }\n  } else {\n    resolved = {};\n    if (globalMixins.length) {\n      globalMixins.forEach(\n        (m) => mergeOptions(resolved, m, optionMergeStrategies, true)\n      );\n    }\n    mergeOptions(resolved, base, optionMergeStrategies);\n  }\n  if (shared.isObject(base)) {\n    cache.set(base, resolved);\n  }\n  return resolved;\n}\nfunction mergeOptions(to, from, strats, asMixin = false) {\n  const { mixins, extends: extendsOptions } = from;\n  if (extendsOptions) {\n    mergeOptions(to, extendsOptions, strats, true);\n  }\n  if (mixins) {\n    mixins.forEach(\n      (m) => mergeOptions(to, m, strats, true)\n    );\n  }\n  for (const key in from) {\n    if (asMixin && key === \"expose\") ; else {\n      const strat = internalOptionMergeStrats[key] || strats && strats[key];\n      to[key] = strat ? strat(to[key], from[key]) : from[key];\n    }\n  }\n  return to;\n}\nconst internalOptionMergeStrats = {\n  data: mergeDataFn,\n  props: mergeEmitsOrPropsOptions,\n  emits: mergeEmitsOrPropsOptions,\n  // objects\n  methods: mergeObjectOptions,\n  computed: mergeObjectOptions,\n  // lifecycle\n  beforeCreate: mergeAsArray,\n  created: mergeAsArray,\n  beforeMount: mergeAsArray,\n  mounted: mergeAsArray,\n  beforeUpdate: mergeAsArray,\n  updated: mergeAsArray,\n  beforeDestroy: mergeAsArray,\n  beforeUnmount: mergeAsArray,\n  destroyed: mergeAsArray,\n  unmounted: mergeAsArray,\n  activated: mergeAsArray,\n  deactivated: mergeAsArray,\n  errorCaptured: mergeAsArray,\n  serverPrefetch: mergeAsArray,\n  // assets\n  components: mergeObjectOptions,\n  directives: mergeObjectOptions,\n  // watch\n  watch: mergeWatchOptions,\n  // provide / inject\n  provide: mergeDataFn,\n  inject: mergeInject\n};\nfunction mergeDataFn(to, from) {\n  if (!from) {\n    return to;\n  }\n  if (!to) {\n    return from;\n  }\n  return function mergedDataFn() {\n    return (shared.extend)(\n      shared.isFunction(to) ? to.call(this, this) : to,\n      shared.isFunction(from) ? from.call(this, this) : from\n    );\n  };\n}\nfunction mergeInject(to, from) {\n  return mergeObjectOptions(normalizeInject(to), normalizeInject(from));\n}\nfunction normalizeInject(raw) {\n  if (shared.isArray(raw)) {\n    const res = {};\n    for (let i = 0; i < raw.length; i++) {\n      res[raw[i]] = raw[i];\n    }\n    return res;\n  }\n  return raw;\n}\nfunction mergeAsArray(to, from) {\n  return to ? [...new Set([].concat(to, from))] : from;\n}\nfunction mergeObjectOptions(to, from) {\n  return to ? shared.extend(/* @__PURE__ */ Object.create(null), to, from) : from;\n}\nfunction mergeEmitsOrPropsOptions(to, from) {\n  if (to) {\n    if (shared.isArray(to) && shared.isArray(from)) {\n      return [.../* @__PURE__ */ new Set([...to, ...from])];\n    }\n    return shared.extend(\n      /* @__PURE__ */ Object.create(null),\n      normalizePropsOrEmits(to),\n      normalizePropsOrEmits(from != null ? from : {})\n    );\n  } else {\n    return from;\n  }\n}\nfunction mergeWatchOptions(to, from) {\n  if (!to) return from;\n  if (!from) return to;\n  const merged = shared.extend(/* @__PURE__ */ Object.create(null), to);\n  for (const key in from) {\n    merged[key] = mergeAsArray(to[key], from[key]);\n  }\n  return merged;\n}\n\nfunction createAppContext() {\n  return {\n    app: null,\n    config: {\n      isNativeTag: shared.NO,\n      performance: false,\n      globalProperties: {},\n      optionMergeStrategies: {},\n      errorHandler: void 0,\n      warnHandler: void 0,\n      compilerOptions: {}\n    },\n    mixins: [],\n    components: {},\n    directives: {},\n    provides: /* @__PURE__ */ Object.create(null),\n    optionsCache: /* @__PURE__ */ new WeakMap(),\n    propsCache: /* @__PURE__ */ new WeakMap(),\n    emitsCache: /* @__PURE__ */ new WeakMap()\n  };\n}\nlet uid$1 = 0;\nfunction createAppAPI(render, hydrate) {\n  return function createApp(rootComponent, rootProps = null) {\n    if (!shared.isFunction(rootComponent)) {\n      rootComponent = shared.extend({}, rootComponent);\n    }\n    if (rootProps != null && !shared.isObject(rootProps)) {\n      rootProps = null;\n    }\n    const context = createAppContext();\n    const installedPlugins = /* @__PURE__ */ new WeakSet();\n    const pluginCleanupFns = [];\n    let isMounted = false;\n    const app = context.app = {\n      _uid: uid$1++,\n      _component: rootComponent,\n      _props: rootProps,\n      _container: null,\n      _context: context,\n      _instance: null,\n      version,\n      get config() {\n        return context.config;\n      },\n      set config(v) {\n      },\n      use(plugin, ...options) {\n        if (installedPlugins.has(plugin)) ; else if (plugin && shared.isFunction(plugin.install)) {\n          installedPlugins.add(plugin);\n          plugin.install(app, ...options);\n        } else if (shared.isFunction(plugin)) {\n          installedPlugins.add(plugin);\n          plugin(app, ...options);\n        } else ;\n        return app;\n      },\n      mixin(mixin) {\n        {\n          if (!context.mixins.includes(mixin)) {\n            context.mixins.push(mixin);\n          }\n        }\n        return app;\n      },\n      component(name, component) {\n        if (!component) {\n          return context.components[name];\n        }\n        context.components[name] = component;\n        return app;\n      },\n      directive(name, directive) {\n        if (!directive) {\n          return context.directives[name];\n        }\n        context.directives[name] = directive;\n        return app;\n      },\n      mount(rootContainer, isHydrate, namespace) {\n        if (!isMounted) {\n          const vnode = app._ceVNode || createVNode(rootComponent, rootProps);\n          vnode.appContext = context;\n          if (namespace === true) {\n            namespace = \"svg\";\n          } else if (namespace === false) {\n            namespace = void 0;\n          }\n          if (isHydrate && hydrate) {\n            hydrate(vnode, rootContainer);\n          } else {\n            render(vnode, rootContainer, namespace);\n          }\n          isMounted = true;\n          app._container = rootContainer;\n          rootContainer.__vue_app__ = app;\n          return getComponentPublicInstance(vnode.component);\n        }\n      },\n      onUnmount(cleanupFn) {\n        pluginCleanupFns.push(cleanupFn);\n      },\n      unmount() {\n        if (isMounted) {\n          callWithAsyncErrorHandling(\n            pluginCleanupFns,\n            app._instance,\n            16\n          );\n          render(null, app._container);\n          delete app._container.__vue_app__;\n        }\n      },\n      provide(key, value) {\n        context.provides[key] = value;\n        return app;\n      },\n      runWithContext(fn) {\n        const lastApp = currentApp;\n        currentApp = app;\n        try {\n          return fn();\n        } finally {\n          currentApp = lastApp;\n        }\n      }\n    };\n    return app;\n  };\n}\nlet currentApp = null;\n\nfunction provide(key, value) {\n  if (!currentInstance) ; else {\n    let provides = currentInstance.provides;\n    const parentProvides = currentInstance.parent && currentInstance.parent.provides;\n    if (parentProvides === provides) {\n      provides = currentInstance.provides = Object.create(parentProvides);\n    }\n    provides[key] = value;\n  }\n}\nfunction inject(key, defaultValue, treatDefaultAsFactory = false) {\n  const instance = getCurrentInstance();\n  if (instance || currentApp) {\n    let provides = currentApp ? currentApp._context.provides : instance ? instance.parent == null || instance.ce ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides : void 0;\n    if (provides && key in provides) {\n      return provides[key];\n    } else if (arguments.length > 1) {\n      return treatDefaultAsFactory && shared.isFunction(defaultValue) ? defaultValue.call(instance && instance.proxy) : defaultValue;\n    } else ;\n  }\n}\nfunction hasInjectionContext() {\n  return !!(getCurrentInstance() || currentApp);\n}\n\nconst internalObjectProto = {};\nconst createInternalObject = () => Object.create(internalObjectProto);\nconst isInternalObject = (obj) => Object.getPrototypeOf(obj) === internalObjectProto;\n\nfunction initProps(instance, rawProps, isStateful, isSSR = false) {\n  const props = {};\n  const attrs = createInternalObject();\n  instance.propsDefaults = /* @__PURE__ */ Object.create(null);\n  setFullProps(instance, rawProps, props, attrs);\n  for (const key in instance.propsOptions[0]) {\n    if (!(key in props)) {\n      props[key] = void 0;\n    }\n  }\n  if (isStateful) {\n    instance.props = isSSR ? props : reactivity.shallowReactive(props);\n  } else {\n    if (!instance.type.props) {\n      instance.props = attrs;\n    } else {\n      instance.props = props;\n    }\n  }\n  instance.attrs = attrs;\n}\nfunction updateProps(instance, rawProps, rawPrevProps, optimized) {\n  const {\n    props,\n    attrs,\n    vnode: { patchFlag }\n  } = instance;\n  const rawCurrentProps = reactivity.toRaw(props);\n  const [options] = instance.propsOptions;\n  let hasAttrsChanged = false;\n  if (\n    // always force full diff in dev\n    // - #1942 if hmr is enabled with sfc component\n    // - vite#872 non-sfc component used by sfc component\n    (optimized || patchFlag > 0) && !(patchFlag & 16)\n  ) {\n    if (patchFlag & 8) {\n      const propsToUpdate = instance.vnode.dynamicProps;\n      for (let i = 0; i < propsToUpdate.length; i++) {\n        let key = propsToUpdate[i];\n        if (isEmitListener(instance.emitsOptions, key)) {\n          continue;\n        }\n        const value = rawProps[key];\n        if (options) {\n          if (shared.hasOwn(attrs, key)) {\n            if (value !== attrs[key]) {\n              attrs[key] = value;\n              hasAttrsChanged = true;\n            }\n          } else {\n            const camelizedKey = shared.camelize(key);\n            props[camelizedKey] = resolvePropValue(\n              options,\n              rawCurrentProps,\n              camelizedKey,\n              value,\n              instance,\n              false\n            );\n          }\n        } else {\n          if (value !== attrs[key]) {\n            attrs[key] = value;\n            hasAttrsChanged = true;\n          }\n        }\n      }\n    }\n  } else {\n    if (setFullProps(instance, rawProps, props, attrs)) {\n      hasAttrsChanged = true;\n    }\n    let kebabKey;\n    for (const key in rawCurrentProps) {\n      if (!rawProps || // for camelCase\n      !shared.hasOwn(rawProps, key) && // it's possible the original props was passed in as kebab-case\n      // and converted to camelCase (#955)\n      ((kebabKey = shared.hyphenate(key)) === key || !shared.hasOwn(rawProps, kebabKey))) {\n        if (options) {\n          if (rawPrevProps && // for camelCase\n          (rawPrevProps[key] !== void 0 || // for kebab-case\n          rawPrevProps[kebabKey] !== void 0)) {\n            props[key] = resolvePropValue(\n              options,\n              rawCurrentProps,\n              key,\n              void 0,\n              instance,\n              true\n            );\n          }\n        } else {\n          delete props[key];\n        }\n      }\n    }\n    if (attrs !== rawCurrentProps) {\n      for (const key in attrs) {\n        if (!rawProps || !shared.hasOwn(rawProps, key) && true) {\n          delete attrs[key];\n          hasAttrsChanged = true;\n        }\n      }\n    }\n  }\n  if (hasAttrsChanged) {\n    reactivity.trigger(instance.attrs, \"set\", \"\");\n  }\n}\nfunction setFullProps(instance, rawProps, props, attrs) {\n  const [options, needCastKeys] = instance.propsOptions;\n  let hasAttrsChanged = false;\n  let rawCastValues;\n  if (rawProps) {\n    for (let key in rawProps) {\n      if (shared.isReservedProp(key)) {\n        continue;\n      }\n      const value = rawProps[key];\n      let camelKey;\n      if (options && shared.hasOwn(options, camelKey = shared.camelize(key))) {\n        if (!needCastKeys || !needCastKeys.includes(camelKey)) {\n          props[camelKey] = value;\n        } else {\n          (rawCastValues || (rawCastValues = {}))[camelKey] = value;\n        }\n      } else if (!isEmitListener(instance.emitsOptions, key)) {\n        if (!(key in attrs) || value !== attrs[key]) {\n          attrs[key] = value;\n          hasAttrsChanged = true;\n        }\n      }\n    }\n  }\n  if (needCastKeys) {\n    const rawCurrentProps = reactivity.toRaw(props);\n    const castValues = rawCastValues || shared.EMPTY_OBJ;\n    for (let i = 0; i < needCastKeys.length; i++) {\n      const key = needCastKeys[i];\n      props[key] = resolvePropValue(\n        options,\n        rawCurrentProps,\n        key,\n        castValues[key],\n        instance,\n        !shared.hasOwn(castValues, key)\n      );\n    }\n  }\n  return hasAttrsChanged;\n}\nfunction resolvePropValue(options, props, key, value, instance, isAbsent) {\n  const opt = options[key];\n  if (opt != null) {\n    const hasDefault = shared.hasOwn(opt, \"default\");\n    if (hasDefault && value === void 0) {\n      const defaultValue = opt.default;\n      if (opt.type !== Function && !opt.skipFactory && shared.isFunction(defaultValue)) {\n        const { propsDefaults } = instance;\n        if (key in propsDefaults) {\n          value = propsDefaults[key];\n        } else {\n          const reset = setCurrentInstance(instance);\n          value = propsDefaults[key] = defaultValue.call(\n            null,\n            props\n          );\n          reset();\n        }\n      } else {\n        value = defaultValue;\n      }\n      if (instance.ce) {\n        instance.ce._setProp(key, value);\n      }\n    }\n    if (opt[0 /* shouldCast */]) {\n      if (isAbsent && !hasDefault) {\n        value = false;\n      } else if (opt[1 /* shouldCastTrue */] && (value === \"\" || value === shared.hyphenate(key))) {\n        value = true;\n      }\n    }\n  }\n  return value;\n}\nconst mixinPropsCache = /* @__PURE__ */ new WeakMap();\nfunction normalizePropsOptions(comp, appContext, asMixin = false) {\n  const cache = asMixin ? mixinPropsCache : appContext.propsCache;\n  const cached = cache.get(comp);\n  if (cached) {\n    return cached;\n  }\n  const raw = comp.props;\n  const normalized = {};\n  const needCastKeys = [];\n  let hasExtends = false;\n  if (!shared.isFunction(comp)) {\n    const extendProps = (raw2) => {\n      hasExtends = true;\n      const [props, keys] = normalizePropsOptions(raw2, appContext, true);\n      shared.extend(normalized, props);\n      if (keys) needCastKeys.push(...keys);\n    };\n    if (!asMixin && appContext.mixins.length) {\n      appContext.mixins.forEach(extendProps);\n    }\n    if (comp.extends) {\n      extendProps(comp.extends);\n    }\n    if (comp.mixins) {\n      comp.mixins.forEach(extendProps);\n    }\n  }\n  if (!raw && !hasExtends) {\n    if (shared.isObject(comp)) {\n      cache.set(comp, shared.EMPTY_ARR);\n    }\n    return shared.EMPTY_ARR;\n  }\n  if (shared.isArray(raw)) {\n    for (let i = 0; i < raw.length; i++) {\n      const normalizedKey = shared.camelize(raw[i]);\n      if (validatePropName(normalizedKey)) {\n        normalized[normalizedKey] = shared.EMPTY_OBJ;\n      }\n    }\n  } else if (raw) {\n    for (const key in raw) {\n      const normalizedKey = shared.camelize(key);\n      if (validatePropName(normalizedKey)) {\n        const opt = raw[key];\n        const prop = normalized[normalizedKey] = shared.isArray(opt) || shared.isFunction(opt) ? { type: opt } : shared.extend({}, opt);\n        const propType = prop.type;\n        let shouldCast = false;\n        let shouldCastTrue = true;\n        if (shared.isArray(propType)) {\n          for (let index = 0; index < propType.length; ++index) {\n            const type = propType[index];\n            const typeName = shared.isFunction(type) && type.name;\n            if (typeName === \"Boolean\") {\n              shouldCast = true;\n              break;\n            } else if (typeName === \"String\") {\n              shouldCastTrue = false;\n            }\n          }\n        } else {\n          shouldCast = shared.isFunction(propType) && propType.name === \"Boolean\";\n        }\n        prop[0 /* shouldCast */] = shouldCast;\n        prop[1 /* shouldCastTrue */] = shouldCastTrue;\n        if (shouldCast || shared.hasOwn(prop, \"default\")) {\n          needCastKeys.push(normalizedKey);\n        }\n      }\n    }\n  }\n  const res = [normalized, needCastKeys];\n  if (shared.isObject(comp)) {\n    cache.set(comp, res);\n  }\n  return res;\n}\nfunction validatePropName(key) {\n  if (key[0] !== \"$\" && !shared.isReservedProp(key)) {\n    return true;\n  }\n  return false;\n}\n\nconst isInternalKey = (key) => key === \"_\" || key === \"__\" || key === \"_ctx\" || key === \"$stable\";\nconst normalizeSlotValue = (value) => shared.isArray(value) ? value.map(normalizeVNode) : [normalizeVNode(value)];\nconst normalizeSlot = (key, rawSlot, ctx) => {\n  if (rawSlot._n) {\n    return rawSlot;\n  }\n  const normalized = withCtx((...args) => {\n    if (false) ;\n    return normalizeSlotValue(rawSlot(...args));\n  }, ctx);\n  normalized._c = false;\n  return normalized;\n};\nconst normalizeObjectSlots = (rawSlots, slots, instance) => {\n  const ctx = rawSlots._ctx;\n  for (const key in rawSlots) {\n    if (isInternalKey(key)) continue;\n    const value = rawSlots[key];\n    if (shared.isFunction(value)) {\n      slots[key] = normalizeSlot(key, value, ctx);\n    } else if (value != null) {\n      const normalized = normalizeSlotValue(value);\n      slots[key] = () => normalized;\n    }\n  }\n};\nconst normalizeVNodeSlots = (instance, children) => {\n  const normalized = normalizeSlotValue(children);\n  instance.slots.default = () => normalized;\n};\nconst assignSlots = (slots, children, optimized) => {\n  for (const key in children) {\n    if (optimized || !isInternalKey(key)) {\n      slots[key] = children[key];\n    }\n  }\n};\nconst initSlots = (instance, children, optimized) => {\n  const slots = instance.slots = createInternalObject();\n  if (instance.vnode.shapeFlag & 32) {\n    const cacheIndexes = children.__;\n    if (cacheIndexes) shared.def(slots, \"__\", cacheIndexes, true);\n    const type = children._;\n    if (type) {\n      assignSlots(slots, children, optimized);\n      if (optimized) {\n        shared.def(slots, \"_\", type, true);\n      }\n    } else {\n      normalizeObjectSlots(children, slots);\n    }\n  } else if (children) {\n    normalizeVNodeSlots(instance, children);\n  }\n};\nconst updateSlots = (instance, children, optimized) => {\n  const { vnode, slots } = instance;\n  let needDeletionCheck = true;\n  let deletionComparisonTarget = shared.EMPTY_OBJ;\n  if (vnode.shapeFlag & 32) {\n    const type = children._;\n    if (type) {\n      if (optimized && type === 1) {\n        needDeletionCheck = false;\n      } else {\n        assignSlots(slots, children, optimized);\n      }\n    } else {\n      needDeletionCheck = !children.$stable;\n      normalizeObjectSlots(children, slots);\n    }\n    deletionComparisonTarget = children;\n  } else if (children) {\n    normalizeVNodeSlots(instance, children);\n    deletionComparisonTarget = { default: 1 };\n  }\n  if (needDeletionCheck) {\n    for (const key in slots) {\n      if (!isInternalKey(key) && deletionComparisonTarget[key] == null) {\n        delete slots[key];\n      }\n    }\n  }\n};\n\nconst queuePostRenderEffect = queueEffectWithSuspense ;\nfunction createRenderer(options) {\n  return baseCreateRenderer(options);\n}\nfunction createHydrationRenderer(options) {\n  return baseCreateRenderer(options, createHydrationFunctions);\n}\nfunction baseCreateRenderer(options, createHydrationFns) {\n  const target = shared.getGlobalThis();\n  target.__VUE__ = true;\n  const {\n    insert: hostInsert,\n    remove: hostRemove,\n    patchProp: hostPatchProp,\n    createElement: hostCreateElement,\n    createText: hostCreateText,\n    createComment: hostCreateComment,\n    setText: hostSetText,\n    setElementText: hostSetElementText,\n    parentNode: hostParentNode,\n    nextSibling: hostNextSibling,\n    setScopeId: hostSetScopeId = shared.NOOP,\n    insertStaticContent: hostInsertStaticContent\n  } = options;\n  const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, namespace = void 0, slotScopeIds = null, optimized = !!n2.dynamicChildren) => {\n    if (n1 === n2) {\n      return;\n    }\n    if (n1 && !isSameVNodeType(n1, n2)) {\n      anchor = getNextHostNode(n1);\n      unmount(n1, parentComponent, parentSuspense, true);\n      n1 = null;\n    }\n    if (n2.patchFlag === -2) {\n      optimized = false;\n      n2.dynamicChildren = null;\n    }\n    const { type, ref, shapeFlag } = n2;\n    switch (type) {\n      case Text:\n        processText(n1, n2, container, anchor);\n        break;\n      case Comment:\n        processCommentNode(n1, n2, container, anchor);\n        break;\n      case Static:\n        if (n1 == null) {\n          mountStaticNode(n2, container, anchor, namespace);\n        }\n        break;\n      case Fragment:\n        processFragment(\n          n1,\n          n2,\n          container,\n          anchor,\n          parentComponent,\n          parentSuspense,\n          namespace,\n          slotScopeIds,\n          optimized\n        );\n        break;\n      default:\n        if (shapeFlag & 1) {\n          processElement(\n            n1,\n            n2,\n            container,\n            anchor,\n            parentComponent,\n            parentSuspense,\n            namespace,\n            slotScopeIds,\n            optimized\n          );\n        } else if (shapeFlag & 6) {\n          processComponent(\n            n1,\n            n2,\n            container,\n            anchor,\n            parentComponent,\n            parentSuspense,\n            namespace,\n            slotScopeIds,\n            optimized\n          );\n        } else if (shapeFlag & 64) {\n          type.process(\n            n1,\n            n2,\n            container,\n            anchor,\n            parentComponent,\n            parentSuspense,\n            namespace,\n            slotScopeIds,\n            optimized,\n            internals\n          );\n        } else if (shapeFlag & 128) {\n          type.process(\n            n1,\n            n2,\n            container,\n            anchor,\n            parentComponent,\n            parentSuspense,\n            namespace,\n            slotScopeIds,\n            optimized,\n            internals\n          );\n        } else ;\n    }\n    if (ref != null && parentComponent) {\n      setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);\n    } else if (ref == null && n1 && n1.ref != null) {\n      setRef(n1.ref, null, parentSuspense, n1, true);\n    }\n  };\n  const processText = (n1, n2, container, anchor) => {\n    if (n1 == null) {\n      hostInsert(\n        n2.el = hostCreateText(n2.children),\n        container,\n        anchor\n      );\n    } else {\n      const el = n2.el = n1.el;\n      if (n2.children !== n1.children) {\n        hostSetText(el, n2.children);\n      }\n    }\n  };\n  const processCommentNode = (n1, n2, container, anchor) => {\n    if (n1 == null) {\n      hostInsert(\n        n2.el = hostCreateComment(n2.children || \"\"),\n        container,\n        anchor\n      );\n    } else {\n      n2.el = n1.el;\n    }\n  };\n  const mountStaticNode = (n2, container, anchor, namespace) => {\n    [n2.el, n2.anchor] = hostInsertStaticContent(\n      n2.children,\n      container,\n      anchor,\n      namespace,\n      n2.el,\n      n2.anchor\n    );\n  };\n  const moveStaticNode = ({ el, anchor }, container, nextSibling) => {\n    let next;\n    while (el && el !== anchor) {\n      next = hostNextSibling(el);\n      hostInsert(el, container, nextSibling);\n      el = next;\n    }\n    hostInsert(anchor, container, nextSibling);\n  };\n  const removeStaticNode = ({ el, anchor }) => {\n    let next;\n    while (el && el !== anchor) {\n      next = hostNextSibling(el);\n      hostRemove(el);\n      el = next;\n    }\n    hostRemove(anchor);\n  };\n  const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {\n    if (n2.type === \"svg\") {\n      namespace = \"svg\";\n    } else if (n2.type === \"math\") {\n      namespace = \"mathml\";\n    }\n    if (n1 == null) {\n      mountElement(\n        n2,\n        container,\n        anchor,\n        parentComponent,\n        parentSuspense,\n        namespace,\n        slotScopeIds,\n        optimized\n      );\n    } else {\n      patchElement(\n        n1,\n        n2,\n        parentComponent,\n        parentSuspense,\n        namespace,\n        slotScopeIds,\n        optimized\n      );\n    }\n  };\n  const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {\n    let el;\n    let vnodeHook;\n    const { props, shapeFlag, transition, dirs } = vnode;\n    el = vnode.el = hostCreateElement(\n      vnode.type,\n      namespace,\n      props && props.is,\n      props\n    );\n    if (shapeFlag & 8) {\n      hostSetElementText(el, vnode.children);\n    } else if (shapeFlag & 16) {\n      mountChildren(\n        vnode.children,\n        el,\n        null,\n        parentComponent,\n        parentSuspense,\n        resolveChildrenNamespace(vnode, namespace),\n        slotScopeIds,\n        optimized\n      );\n    }\n    if (dirs) {\n      invokeDirectiveHook(vnode, null, parentComponent, \"created\");\n    }\n    setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);\n    if (props) {\n      for (const key in props) {\n        if (key !== \"value\" && !shared.isReservedProp(key)) {\n          hostPatchProp(el, key, null, props[key], namespace, parentComponent);\n        }\n      }\n      if (\"value\" in props) {\n        hostPatchProp(el, \"value\", null, props.value, namespace);\n      }\n      if (vnodeHook = props.onVnodeBeforeMount) {\n        invokeVNodeHook(vnodeHook, parentComponent, vnode);\n      }\n    }\n    if (dirs) {\n      invokeDirectiveHook(vnode, null, parentComponent, \"beforeMount\");\n    }\n    const needCallTransitionHooks = needTransition(parentSuspense, transition);\n    if (needCallTransitionHooks) {\n      transition.beforeEnter(el);\n    }\n    hostInsert(el, container, anchor);\n    if ((vnodeHook = props && props.onVnodeMounted) || needCallTransitionHooks || dirs) {\n      queuePostRenderEffect(() => {\n        vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);\n        needCallTransitionHooks && transition.enter(el);\n        dirs && invokeDirectiveHook(vnode, null, parentComponent, \"mounted\");\n      }, parentSuspense);\n    }\n  };\n  const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {\n    if (scopeId) {\n      hostSetScopeId(el, scopeId);\n    }\n    if (slotScopeIds) {\n      for (let i = 0; i < slotScopeIds.length; i++) {\n        hostSetScopeId(el, slotScopeIds[i]);\n      }\n    }\n    if (parentComponent) {\n      let subTree = parentComponent.subTree;\n      if (vnode === subTree || isSuspense(subTree.type) && (subTree.ssContent === vnode || subTree.ssFallback === vnode)) {\n        const parentVNode = parentComponent.vnode;\n        setScopeId(\n          el,\n          parentVNode,\n          parentVNode.scopeId,\n          parentVNode.slotScopeIds,\n          parentComponent.parent\n        );\n      }\n    }\n  };\n  const mountChildren = (children, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, start = 0) => {\n    for (let i = start; i < children.length; i++) {\n      const child = children[i] = optimized ? cloneIfMounted(children[i]) : normalizeVNode(children[i]);\n      patch(\n        null,\n        child,\n        container,\n        anchor,\n        parentComponent,\n        parentSuspense,\n        namespace,\n        slotScopeIds,\n        optimized\n      );\n    }\n  };\n  const patchElement = (n1, n2, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {\n    const el = n2.el = n1.el;\n    let { patchFlag, dynamicChildren, dirs } = n2;\n    patchFlag |= n1.patchFlag & 16;\n    const oldProps = n1.props || shared.EMPTY_OBJ;\n    const newProps = n2.props || shared.EMPTY_OBJ;\n    let vnodeHook;\n    parentComponent && toggleRecurse(parentComponent, false);\n    if (vnodeHook = newProps.onVnodeBeforeUpdate) {\n      invokeVNodeHook(vnodeHook, parentComponent, n2, n1);\n    }\n    if (dirs) {\n      invokeDirectiveHook(n2, n1, parentComponent, \"beforeUpdate\");\n    }\n    parentComponent && toggleRecurse(parentComponent, true);\n    if (oldProps.innerHTML && newProps.innerHTML == null || oldProps.textContent && newProps.textContent == null) {\n      hostSetElementText(el, \"\");\n    }\n    if (dynamicChildren) {\n      patchBlockChildren(\n        n1.dynamicChildren,\n        dynamicChildren,\n        el,\n        parentComponent,\n        parentSuspense,\n        resolveChildrenNamespace(n2, namespace),\n        slotScopeIds\n      );\n    } else if (!optimized) {\n      patchChildren(\n        n1,\n        n2,\n        el,\n        null,\n        parentComponent,\n        parentSuspense,\n        resolveChildrenNamespace(n2, namespace),\n        slotScopeIds,\n        false\n      );\n    }\n    if (patchFlag > 0) {\n      if (patchFlag & 16) {\n        patchProps(el, oldProps, newProps, parentComponent, namespace);\n      } else {\n        if (patchFlag & 2) {\n          if (oldProps.class !== newProps.class) {\n            hostPatchProp(el, \"class\", null, newProps.class, namespace);\n          }\n        }\n        if (patchFlag & 4) {\n          hostPatchProp(el, \"style\", oldProps.style, newProps.style, namespace);\n        }\n        if (patchFlag & 8) {\n          const propsToUpdate = n2.dynamicProps;\n          for (let i = 0; i < propsToUpdate.length; i++) {\n            const key = propsToUpdate[i];\n            const prev = oldProps[key];\n            const next = newProps[key];\n            if (next !== prev || key === \"value\") {\n              hostPatchProp(el, key, prev, next, namespace, parentComponent);\n            }\n          }\n        }\n      }\n      if (patchFlag & 1) {\n        if (n1.children !== n2.children) {\n          hostSetElementText(el, n2.children);\n        }\n      }\n    } else if (!optimized && dynamicChildren == null) {\n      patchProps(el, oldProps, newProps, parentComponent, namespace);\n    }\n    if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {\n      queuePostRenderEffect(() => {\n        vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);\n        dirs && invokeDirectiveHook(n2, n1, parentComponent, \"updated\");\n      }, parentSuspense);\n    }\n  };\n  const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, namespace, slotScopeIds) => {\n    for (let i = 0; i < newChildren.length; i++) {\n      const oldVNode = oldChildren[i];\n      const newVNode = newChildren[i];\n      const container = (\n        // oldVNode may be an errored async setup() component inside Suspense\n        // which will not have a mounted element\n        oldVNode.el && // - In the case of a Fragment, we need to provide the actual parent\n        // of the Fragment itself so it can move its children.\n        (oldVNode.type === Fragment || // - In the case of different nodes, there is going to be a replacement\n        // which also requires the correct parent container\n        !isSameVNodeType(oldVNode, newVNode) || // - In the case of a component, it could contain anything.\n        oldVNode.shapeFlag & (6 | 64 | 128)) ? hostParentNode(oldVNode.el) : (\n          // In other cases, the parent container is not actually used so we\n          // just pass the block element here to avoid a DOM parentNode call.\n          fallbackContainer\n        )\n      );\n      patch(\n        oldVNode,\n        newVNode,\n        container,\n        null,\n        parentComponent,\n        parentSuspense,\n        namespace,\n        slotScopeIds,\n        true\n      );\n    }\n  };\n  const patchProps = (el, oldProps, newProps, parentComponent, namespace) => {\n    if (oldProps !== newProps) {\n      if (oldProps !== shared.EMPTY_OBJ) {\n        for (const key in oldProps) {\n          if (!shared.isReservedProp(key) && !(key in newProps)) {\n            hostPatchProp(\n              el,\n              key,\n              oldProps[key],\n              null,\n              namespace,\n              parentComponent\n            );\n          }\n        }\n      }\n      for (const key in newProps) {\n        if (shared.isReservedProp(key)) continue;\n        const next = newProps[key];\n        const prev = oldProps[key];\n        if (next !== prev && key !== \"value\") {\n          hostPatchProp(el, key, prev, next, namespace, parentComponent);\n        }\n      }\n      if (\"value\" in newProps) {\n        hostPatchProp(el, \"value\", oldProps.value, newProps.value, namespace);\n      }\n    }\n  };\n  const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {\n    const fragmentStartAnchor = n2.el = n1 ? n1.el : hostCreateText(\"\");\n    const fragmentEndAnchor = n2.anchor = n1 ? n1.anchor : hostCreateText(\"\");\n    let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;\n    if (fragmentSlotScopeIds) {\n      slotScopeIds = slotScopeIds ? slotScopeIds.concat(fragmentSlotScopeIds) : fragmentSlotScopeIds;\n    }\n    if (n1 == null) {\n      hostInsert(fragmentStartAnchor, container, anchor);\n      hostInsert(fragmentEndAnchor, container, anchor);\n      mountChildren(\n        // #10007\n        // such fragment like `<></>` will be compiled into\n        // a fragment which doesn't have a children.\n        // In this case fallback to an empty array\n        n2.children || [],\n        container,\n        fragmentEndAnchor,\n        parentComponent,\n        parentSuspense,\n        namespace,\n        slotScopeIds,\n        optimized\n      );\n    } else {\n      if (patchFlag > 0 && patchFlag & 64 && dynamicChildren && // #2715 the previous fragment could've been a BAILed one as a result\n      // of renderSlot() with no valid children\n      n1.dynamicChildren) {\n        patchBlockChildren(\n          n1.dynamicChildren,\n          dynamicChildren,\n          container,\n          parentComponent,\n          parentSuspense,\n          namespace,\n          slotScopeIds\n        );\n        if (\n          // #2080 if the stable fragment has a key, it's a <template v-for> that may\n          //  get moved around. Make sure all root level vnodes inherit el.\n          // #2134 or if it's a component root, it may also get moved around\n          // as the component is being moved.\n          n2.key != null || parentComponent && n2 === parentComponent.subTree\n        ) {\n          traverseStaticChildren(\n            n1,\n            n2,\n            true\n            /* shallow */\n          );\n        }\n      } else {\n        patchChildren(\n          n1,\n          n2,\n          container,\n          fragmentEndAnchor,\n          parentComponent,\n          parentSuspense,\n          namespace,\n          slotScopeIds,\n          optimized\n        );\n      }\n    }\n  };\n  const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {\n    n2.slotScopeIds = slotScopeIds;\n    if (n1 == null) {\n      if (n2.shapeFlag & 512) {\n        parentComponent.ctx.activate(\n          n2,\n          container,\n          anchor,\n          namespace,\n          optimized\n        );\n      } else {\n        mountComponent(\n          n2,\n          container,\n          anchor,\n          parentComponent,\n          parentSuspense,\n          namespace,\n          optimized\n        );\n      }\n    } else {\n      updateComponent(n1, n2, optimized);\n    }\n  };\n  const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, namespace, optimized) => {\n    const instance = (initialVNode.component = createComponentInstance(\n      initialVNode,\n      parentComponent,\n      parentSuspense\n    ));\n    if (isKeepAlive(initialVNode)) {\n      instance.ctx.renderer = internals;\n    }\n    {\n      setupComponent(instance, false, optimized);\n    }\n    if (instance.asyncDep) {\n      parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect, optimized);\n      if (!initialVNode.el) {\n        const placeholder = instance.subTree = createVNode(Comment);\n        processCommentNode(null, placeholder, container, anchor);\n        initialVNode.placeholder = placeholder.el;\n      }\n    } else {\n      setupRenderEffect(\n        instance,\n        initialVNode,\n        container,\n        anchor,\n        parentSuspense,\n        namespace,\n        optimized\n      );\n    }\n  };\n  const updateComponent = (n1, n2, optimized) => {\n    const instance = n2.component = n1.component;\n    if (shouldUpdateComponent(n1, n2, optimized)) {\n      if (instance.asyncDep && !instance.asyncResolved) {\n        updateComponentPreRender(instance, n2, optimized);\n        return;\n      } else {\n        instance.next = n2;\n        instance.update();\n      }\n    } else {\n      n2.el = n1.el;\n      instance.vnode = n2;\n    }\n  };\n  const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, namespace, optimized) => {\n    const componentUpdateFn = () => {\n      if (!instance.isMounted) {\n        let vnodeHook;\n        const { el, props } = initialVNode;\n        const { bm, m, parent, root, type } = instance;\n        const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);\n        toggleRecurse(instance, false);\n        if (bm) {\n          shared.invokeArrayFns(bm);\n        }\n        if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeBeforeMount)) {\n          invokeVNodeHook(vnodeHook, parent, initialVNode);\n        }\n        toggleRecurse(instance, true);\n        if (el && hydrateNode) {\n          const hydrateSubTree = () => {\n            instance.subTree = renderComponentRoot(instance);\n            hydrateNode(\n              el,\n              instance.subTree,\n              instance,\n              parentSuspense,\n              null\n            );\n          };\n          if (isAsyncWrapperVNode && type.__asyncHydrate) {\n            type.__asyncHydrate(\n              el,\n              instance,\n              hydrateSubTree\n            );\n          } else {\n            hydrateSubTree();\n          }\n        } else {\n          if (root.ce && // @ts-expect-error _def is private\n          root.ce._def.shadowRoot !== false) {\n            root.ce._injectChildStyle(type);\n          }\n          const subTree = instance.subTree = renderComponentRoot(instance);\n          patch(\n            null,\n            subTree,\n            container,\n            anchor,\n            instance,\n            parentSuspense,\n            namespace\n          );\n          initialVNode.el = subTree.el;\n        }\n        if (m) {\n          queuePostRenderEffect(m, parentSuspense);\n        }\n        if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeMounted)) {\n          const scopedInitialVNode = initialVNode;\n          queuePostRenderEffect(\n            () => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode),\n            parentSuspense\n          );\n        }\n        if (initialVNode.shapeFlag & 256 || parent && isAsyncWrapper(parent.vnode) && parent.vnode.shapeFlag & 256) {\n          instance.a && queuePostRenderEffect(instance.a, parentSuspense);\n        }\n        instance.isMounted = true;\n        initialVNode = container = anchor = null;\n      } else {\n        let { next, bu, u, parent, vnode } = instance;\n        {\n          const nonHydratedAsyncRoot = locateNonHydratedAsyncRoot(instance);\n          if (nonHydratedAsyncRoot) {\n            if (next) {\n              next.el = vnode.el;\n              updateComponentPreRender(instance, next, optimized);\n            }\n            nonHydratedAsyncRoot.asyncDep.then(() => {\n              if (!instance.isUnmounted) {\n                componentUpdateFn();\n              }\n            });\n            return;\n          }\n        }\n        let originNext = next;\n        let vnodeHook;\n        toggleRecurse(instance, false);\n        if (next) {\n          next.el = vnode.el;\n          updateComponentPreRender(instance, next, optimized);\n        } else {\n          next = vnode;\n        }\n        if (bu) {\n          shared.invokeArrayFns(bu);\n        }\n        if (vnodeHook = next.props && next.props.onVnodeBeforeUpdate) {\n          invokeVNodeHook(vnodeHook, parent, next, vnode);\n        }\n        toggleRecurse(instance, true);\n        const nextTree = renderComponentRoot(instance);\n        const prevTree = instance.subTree;\n        instance.subTree = nextTree;\n        patch(\n          prevTree,\n          nextTree,\n          // parent may have changed if it's in a teleport\n          hostParentNode(prevTree.el),\n          // anchor may have changed if it's in a fragment\n          getNextHostNode(prevTree),\n          instance,\n          parentSuspense,\n          namespace\n        );\n        next.el = nextTree.el;\n        if (originNext === null) {\n          updateHOCHostEl(instance, nextTree.el);\n        }\n        if (u) {\n          queuePostRenderEffect(u, parentSuspense);\n        }\n        if (vnodeHook = next.props && next.props.onVnodeUpdated) {\n          queuePostRenderEffect(\n            () => invokeVNodeHook(vnodeHook, parent, next, vnode),\n            parentSuspense\n          );\n        }\n      }\n    };\n    instance.scope.on();\n    const effect = instance.effect = new reactivity.ReactiveEffect(componentUpdateFn);\n    instance.scope.off();\n    const update = instance.update = effect.run.bind(effect);\n    const job = instance.job = effect.runIfDirty.bind(effect);\n    job.i = instance;\n    job.id = instance.uid;\n    effect.scheduler = () => queueJob(job);\n    toggleRecurse(instance, true);\n    update();\n  };\n  const updateComponentPreRender = (instance, nextVNode, optimized) => {\n    nextVNode.component = instance;\n    const prevProps = instance.vnode.props;\n    instance.vnode = nextVNode;\n    instance.next = null;\n    updateProps(instance, nextVNode.props, prevProps, optimized);\n    updateSlots(instance, nextVNode.children, optimized);\n    reactivity.pauseTracking();\n    flushPreFlushCbs(instance);\n    reactivity.resetTracking();\n  };\n  const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized = false) => {\n    const c1 = n1 && n1.children;\n    const prevShapeFlag = n1 ? n1.shapeFlag : 0;\n    const c2 = n2.children;\n    const { patchFlag, shapeFlag } = n2;\n    if (patchFlag > 0) {\n      if (patchFlag & 128) {\n        patchKeyedChildren(\n          c1,\n          c2,\n          container,\n          anchor,\n          parentComponent,\n          parentSuspense,\n          namespace,\n          slotScopeIds,\n          optimized\n        );\n        return;\n      } else if (patchFlag & 256) {\n        patchUnkeyedChildren(\n          c1,\n          c2,\n          container,\n          anchor,\n          parentComponent,\n          parentSuspense,\n          namespace,\n          slotScopeIds,\n          optimized\n        );\n        return;\n      }\n    }\n    if (shapeFlag & 8) {\n      if (prevShapeFlag & 16) {\n        unmountChildren(c1, parentComponent, parentSuspense);\n      }\n      if (c2 !== c1) {\n        hostSetElementText(container, c2);\n      }\n    } else {\n      if (prevShapeFlag & 16) {\n        if (shapeFlag & 16) {\n          patchKeyedChildren(\n            c1,\n            c2,\n            container,\n            anchor,\n            parentComponent,\n            parentSuspense,\n            namespace,\n            slotScopeIds,\n            optimized\n          );\n        } else {\n          unmountChildren(c1, parentComponent, parentSuspense, true);\n        }\n      } else {\n        if (prevShapeFlag & 8) {\n          hostSetElementText(container, \"\");\n        }\n        if (shapeFlag & 16) {\n          mountChildren(\n            c2,\n            container,\n            anchor,\n            parentComponent,\n            parentSuspense,\n            namespace,\n            slotScopeIds,\n            optimized\n          );\n        }\n      }\n    }\n  };\n  const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {\n    c1 = c1 || shared.EMPTY_ARR;\n    c2 = c2 || shared.EMPTY_ARR;\n    const oldLength = c1.length;\n    const newLength = c2.length;\n    const commonLength = Math.min(oldLength, newLength);\n    let i;\n    for (i = 0; i < commonLength; i++) {\n      const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]);\n      patch(\n        c1[i],\n        nextChild,\n        container,\n        null,\n        parentComponent,\n        parentSuspense,\n        namespace,\n        slotScopeIds,\n        optimized\n      );\n    }\n    if (oldLength > newLength) {\n      unmountChildren(\n        c1,\n        parentComponent,\n        parentSuspense,\n        true,\n        false,\n        commonLength\n      );\n    } else {\n      mountChildren(\n        c2,\n        container,\n        anchor,\n        parentComponent,\n        parentSuspense,\n        namespace,\n        slotScopeIds,\n        optimized,\n        commonLength\n      );\n    }\n  };\n  const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {\n    let i = 0;\n    const l2 = c2.length;\n    let e1 = c1.length - 1;\n    let e2 = l2 - 1;\n    while (i <= e1 && i <= e2) {\n      const n1 = c1[i];\n      const n2 = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]);\n      if (isSameVNodeType(n1, n2)) {\n        patch(\n          n1,\n          n2,\n          container,\n          null,\n          parentComponent,\n          parentSuspense,\n          namespace,\n          slotScopeIds,\n          optimized\n        );\n      } else {\n        break;\n      }\n      i++;\n    }\n    while (i <= e1 && i <= e2) {\n      const n1 = c1[e1];\n      const n2 = c2[e2] = optimized ? cloneIfMounted(c2[e2]) : normalizeVNode(c2[e2]);\n      if (isSameVNodeType(n1, n2)) {\n        patch(\n          n1,\n          n2,\n          container,\n          null,\n          parentComponent,\n          parentSuspense,\n          namespace,\n          slotScopeIds,\n          optimized\n        );\n      } else {\n        break;\n      }\n      e1--;\n      e2--;\n    }\n    if (i > e1) {\n      if (i <= e2) {\n        const nextPos = e2 + 1;\n        const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;\n        while (i <= e2) {\n          patch(\n            null,\n            c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]),\n            container,\n            anchor,\n            parentComponent,\n            parentSuspense,\n            namespace,\n            slotScopeIds,\n            optimized\n          );\n          i++;\n        }\n      }\n    } else if (i > e2) {\n      while (i <= e1) {\n        unmount(c1[i], parentComponent, parentSuspense, true);\n        i++;\n      }\n    } else {\n      const s1 = i;\n      const s2 = i;\n      const keyToNewIndexMap = /* @__PURE__ */ new Map();\n      for (i = s2; i <= e2; i++) {\n        const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]);\n        if (nextChild.key != null) {\n          keyToNewIndexMap.set(nextChild.key, i);\n        }\n      }\n      let j;\n      let patched = 0;\n      const toBePatched = e2 - s2 + 1;\n      let moved = false;\n      let maxNewIndexSoFar = 0;\n      const newIndexToOldIndexMap = new Array(toBePatched);\n      for (i = 0; i < toBePatched; i++) newIndexToOldIndexMap[i] = 0;\n      for (i = s1; i <= e1; i++) {\n        const prevChild = c1[i];\n        if (patched >= toBePatched) {\n          unmount(prevChild, parentComponent, parentSuspense, true);\n          continue;\n        }\n        let newIndex;\n        if (prevChild.key != null) {\n          newIndex = keyToNewIndexMap.get(prevChild.key);\n        } else {\n          for (j = s2; j <= e2; j++) {\n            if (newIndexToOldIndexMap[j - s2] === 0 && isSameVNodeType(prevChild, c2[j])) {\n              newIndex = j;\n              break;\n            }\n          }\n        }\n        if (newIndex === void 0) {\n          unmount(prevChild, parentComponent, parentSuspense, true);\n        } else {\n          newIndexToOldIndexMap[newIndex - s2] = i + 1;\n          if (newIndex >= maxNewIndexSoFar) {\n            maxNewIndexSoFar = newIndex;\n          } else {\n            moved = true;\n          }\n          patch(\n            prevChild,\n            c2[newIndex],\n            container,\n            null,\n            parentComponent,\n            parentSuspense,\n            namespace,\n            slotScopeIds,\n            optimized\n          );\n          patched++;\n        }\n      }\n      const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : shared.EMPTY_ARR;\n      j = increasingNewIndexSequence.length - 1;\n      for (i = toBePatched - 1; i >= 0; i--) {\n        const nextIndex = s2 + i;\n        const nextChild = c2[nextIndex];\n        const anchorVNode = c2[nextIndex + 1];\n        const anchor = nextIndex + 1 < l2 ? (\n          // #13559, fallback to el placeholder for unresolved async component\n          anchorVNode.el || anchorVNode.placeholder\n        ) : parentAnchor;\n        if (newIndexToOldIndexMap[i] === 0) {\n          patch(\n            null,\n            nextChild,\n            container,\n            anchor,\n            parentComponent,\n            parentSuspense,\n            namespace,\n            slotScopeIds,\n            optimized\n          );\n        } else if (moved) {\n          if (j < 0 || i !== increasingNewIndexSequence[j]) {\n            move(nextChild, container, anchor, 2);\n          } else {\n            j--;\n          }\n        }\n      }\n    }\n  };\n  const move = (vnode, container, anchor, moveType, parentSuspense = null) => {\n    const { el, type, transition, children, shapeFlag } = vnode;\n    if (shapeFlag & 6) {\n      move(vnode.component.subTree, container, anchor, moveType);\n      return;\n    }\n    if (shapeFlag & 128) {\n      vnode.suspense.move(container, anchor, moveType);\n      return;\n    }\n    if (shapeFlag & 64) {\n      type.move(vnode, container, anchor, internals);\n      return;\n    }\n    if (type === Fragment) {\n      hostInsert(el, container, anchor);\n      for (let i = 0; i < children.length; i++) {\n        move(children[i], container, anchor, moveType);\n      }\n      hostInsert(vnode.anchor, container, anchor);\n      return;\n    }\n    if (type === Static) {\n      moveStaticNode(vnode, container, anchor);\n      return;\n    }\n    const needTransition2 = moveType !== 2 && shapeFlag & 1 && transition;\n    if (needTransition2) {\n      if (moveType === 0) {\n        transition.beforeEnter(el);\n        hostInsert(el, container, anchor);\n        queuePostRenderEffect(() => transition.enter(el), parentSuspense);\n      } else {\n        const { leave, delayLeave, afterLeave } = transition;\n        const remove2 = () => {\n          if (vnode.ctx.isUnmounted) {\n            hostRemove(el);\n          } else {\n            hostInsert(el, container, anchor);\n          }\n        };\n        const performLeave = () => {\n          leave(el, () => {\n            remove2();\n            afterLeave && afterLeave();\n          });\n        };\n        if (delayLeave) {\n          delayLeave(el, remove2, performLeave);\n        } else {\n          performLeave();\n        }\n      }\n    } else {\n      hostInsert(el, container, anchor);\n    }\n  };\n  const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {\n    const {\n      type,\n      props,\n      ref,\n      children,\n      dynamicChildren,\n      shapeFlag,\n      patchFlag,\n      dirs,\n      cacheIndex\n    } = vnode;\n    if (patchFlag === -2) {\n      optimized = false;\n    }\n    if (ref != null) {\n      reactivity.pauseTracking();\n      setRef(ref, null, parentSuspense, vnode, true);\n      reactivity.resetTracking();\n    }\n    if (cacheIndex != null) {\n      parentComponent.renderCache[cacheIndex] = void 0;\n    }\n    if (shapeFlag & 256) {\n      parentComponent.ctx.deactivate(vnode);\n      return;\n    }\n    const shouldInvokeDirs = shapeFlag & 1 && dirs;\n    const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);\n    let vnodeHook;\n    if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeBeforeUnmount)) {\n      invokeVNodeHook(vnodeHook, parentComponent, vnode);\n    }\n    if (shapeFlag & 6) {\n      unmountComponent(vnode.component, parentSuspense, doRemove);\n    } else {\n      if (shapeFlag & 128) {\n        vnode.suspense.unmount(parentSuspense, doRemove);\n        return;\n      }\n      if (shouldInvokeDirs) {\n        invokeDirectiveHook(vnode, null, parentComponent, \"beforeUnmount\");\n      }\n      if (shapeFlag & 64) {\n        vnode.type.remove(\n          vnode,\n          parentComponent,\n          parentSuspense,\n          internals,\n          doRemove\n        );\n      } else if (dynamicChildren && // #5154\n      // when v-once is used inside a block, setBlockTracking(-1) marks the\n      // parent block with hasOnce: true\n      // so that it doesn't take the fast path during unmount - otherwise\n      // components nested in v-once are never unmounted.\n      !dynamicChildren.hasOnce && // #1153: fast path should not be taken for non-stable (v-for) fragments\n      (type !== Fragment || patchFlag > 0 && patchFlag & 64)) {\n        unmountChildren(\n          dynamicChildren,\n          parentComponent,\n          parentSuspense,\n          false,\n          true\n        );\n      } else if (type === Fragment && patchFlag & (128 | 256) || !optimized && shapeFlag & 16) {\n        unmountChildren(children, parentComponent, parentSuspense);\n      }\n      if (doRemove) {\n        remove(vnode);\n      }\n    }\n    if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs) {\n      queuePostRenderEffect(() => {\n        vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);\n        shouldInvokeDirs && invokeDirectiveHook(vnode, null, parentComponent, \"unmounted\");\n      }, parentSuspense);\n    }\n  };\n  const remove = (vnode) => {\n    const { type, el, anchor, transition } = vnode;\n    if (type === Fragment) {\n      {\n        removeFragment(el, anchor);\n      }\n      return;\n    }\n    if (type === Static) {\n      removeStaticNode(vnode);\n      return;\n    }\n    const performRemove = () => {\n      hostRemove(el);\n      if (transition && !transition.persisted && transition.afterLeave) {\n        transition.afterLeave();\n      }\n    };\n    if (vnode.shapeFlag & 1 && transition && !transition.persisted) {\n      const { leave, delayLeave } = transition;\n      const performLeave = () => leave(el, performRemove);\n      if (delayLeave) {\n        delayLeave(vnode.el, performRemove, performLeave);\n      } else {\n        performLeave();\n      }\n    } else {\n      performRemove();\n    }\n  };\n  const removeFragment = (cur, end) => {\n    let next;\n    while (cur !== end) {\n      next = hostNextSibling(cur);\n      hostRemove(cur);\n      cur = next;\n    }\n    hostRemove(end);\n  };\n  const unmountComponent = (instance, parentSuspense, doRemove) => {\n    const {\n      bum,\n      scope,\n      job,\n      subTree,\n      um,\n      m,\n      a,\n      parent,\n      slots: { __: slotCacheKeys }\n    } = instance;\n    invalidateMount(m);\n    invalidateMount(a);\n    if (bum) {\n      shared.invokeArrayFns(bum);\n    }\n    if (parent && shared.isArray(slotCacheKeys)) {\n      slotCacheKeys.forEach((v) => {\n        parent.renderCache[v] = void 0;\n      });\n    }\n    scope.stop();\n    if (job) {\n      job.flags |= 8;\n      unmount(subTree, instance, parentSuspense, doRemove);\n    }\n    if (um) {\n      queuePostRenderEffect(um, parentSuspense);\n    }\n    queuePostRenderEffect(() => {\n      instance.isUnmounted = true;\n    }, parentSuspense);\n    if (parentSuspense && parentSuspense.pendingBranch && !parentSuspense.isUnmounted && instance.asyncDep && !instance.asyncResolved && instance.suspenseId === parentSuspense.pendingId) {\n      parentSuspense.deps--;\n      if (parentSuspense.deps === 0) {\n        parentSuspense.resolve();\n      }\n    }\n  };\n  const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {\n    for (let i = start; i < children.length; i++) {\n      unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);\n    }\n  };\n  const getNextHostNode = (vnode) => {\n    if (vnode.shapeFlag & 6) {\n      return getNextHostNode(vnode.component.subTree);\n    }\n    if (vnode.shapeFlag & 128) {\n      return vnode.suspense.next();\n    }\n    const el = hostNextSibling(vnode.anchor || vnode.el);\n    const teleportEnd = el && el[TeleportEndKey];\n    return teleportEnd ? hostNextSibling(teleportEnd) : el;\n  };\n  let isFlushing = false;\n  const render = (vnode, container, namespace) => {\n    if (vnode == null) {\n      if (container._vnode) {\n        unmount(container._vnode, null, null, true);\n      }\n    } else {\n      patch(\n        container._vnode || null,\n        vnode,\n        container,\n        null,\n        null,\n        null,\n        namespace\n      );\n    }\n    container._vnode = vnode;\n    if (!isFlushing) {\n      isFlushing = true;\n      flushPreFlushCbs();\n      flushPostFlushCbs();\n      isFlushing = false;\n    }\n  };\n  const internals = {\n    p: patch,\n    um: unmount,\n    m: move,\n    r: remove,\n    mt: mountComponent,\n    mc: mountChildren,\n    pc: patchChildren,\n    pbc: patchBlockChildren,\n    n: getNextHostNode,\n    o: options\n  };\n  let hydrate;\n  let hydrateNode;\n  if (createHydrationFns) {\n    [hydrate, hydrateNode] = createHydrationFns(\n      internals\n    );\n  }\n  return {\n    render,\n    hydrate,\n    createApp: createAppAPI(render, hydrate)\n  };\n}\nfunction resolveChildrenNamespace({ type, props }, currentNamespace) {\n  return currentNamespace === \"svg\" && type === \"foreignObject\" || currentNamespace === \"mathml\" && type === \"annotation-xml\" && props && props.encoding && props.encoding.includes(\"html\") ? void 0 : currentNamespace;\n}\nfunction toggleRecurse({ effect, job }, allowed) {\n  if (allowed) {\n    effect.flags |= 32;\n    job.flags |= 4;\n  } else {\n    effect.flags &= -33;\n    job.flags &= -5;\n  }\n}\nfunction needTransition(parentSuspense, transition) {\n  return (!parentSuspense || parentSuspense && !parentSuspense.pendingBranch) && transition && !transition.persisted;\n}\nfunction traverseStaticChildren(n1, n2, shallow = false) {\n  const ch1 = n1.children;\n  const ch2 = n2.children;\n  if (shared.isArray(ch1) && shared.isArray(ch2)) {\n    for (let i = 0; i < ch1.length; i++) {\n      const c1 = ch1[i];\n      let c2 = ch2[i];\n      if (c2.shapeFlag & 1 && !c2.dynamicChildren) {\n        if (c2.patchFlag <= 0 || c2.patchFlag === 32) {\n          c2 = ch2[i] = cloneIfMounted(ch2[i]);\n          c2.el = c1.el;\n        }\n        if (!shallow && c2.patchFlag !== -2)\n          traverseStaticChildren(c1, c2);\n      }\n      if (c2.type === Text) {\n        c2.el = c1.el;\n      }\n      if (c2.type === Comment && !c2.el) {\n        c2.el = c1.el;\n      }\n    }\n  }\n}\nfunction getSequence(arr) {\n  const p = arr.slice();\n  const result = [0];\n  let i, j, u, v, c;\n  const len = arr.length;\n  for (i = 0; i < len; i++) {\n    const arrI = arr[i];\n    if (arrI !== 0) {\n      j = result[result.length - 1];\n      if (arr[j] < arrI) {\n        p[i] = j;\n        result.push(i);\n        continue;\n      }\n      u = 0;\n      v = result.length - 1;\n      while (u < v) {\n        c = u + v >> 1;\n        if (arr[result[c]] < arrI) {\n          u = c + 1;\n        } else {\n          v = c;\n        }\n      }\n      if (arrI < arr[result[u]]) {\n        if (u > 0) {\n          p[i] = result[u - 1];\n        }\n        result[u] = i;\n      }\n    }\n  }\n  u = result.length;\n  v = result[u - 1];\n  while (u-- > 0) {\n    result[u] = v;\n    v = p[v];\n  }\n  return result;\n}\nfunction locateNonHydratedAsyncRoot(instance) {\n  const subComponent = instance.subTree.component;\n  if (subComponent) {\n    if (subComponent.asyncDep && !subComponent.asyncResolved) {\n      return subComponent;\n    } else {\n      return locateNonHydratedAsyncRoot(subComponent);\n    }\n  }\n}\nfunction invalidateMount(hooks) {\n  if (hooks) {\n    for (let i = 0; i < hooks.length; i++)\n      hooks[i].flags |= 8;\n  }\n}\n\nconst ssrContextKey = Symbol.for(\"v-scx\");\nconst useSSRContext = () => {\n  {\n    const ctx = inject(ssrContextKey);\n    return ctx;\n  }\n};\n\nfunction watchEffect(effect, options) {\n  return doWatch(effect, null, options);\n}\nfunction watchPostEffect(effect, options) {\n  return doWatch(\n    effect,\n    null,\n    { flush: \"post\" }\n  );\n}\nfunction watchSyncEffect(effect, options) {\n  return doWatch(\n    effect,\n    null,\n    { flush: \"sync\" }\n  );\n}\nfunction watch(source, cb, options) {\n  return doWatch(source, cb, options);\n}\nfunction doWatch(source, cb, options = shared.EMPTY_OBJ) {\n  const { immediate, deep, flush, once } = options;\n  const baseWatchOptions = shared.extend({}, options);\n  const runsImmediately = cb && immediate || !cb && flush !== \"post\";\n  let ssrCleanup;\n  if (isInSSRComponentSetup) {\n    if (flush === \"sync\") {\n      const ctx = useSSRContext();\n      ssrCleanup = ctx.__watcherHandles || (ctx.__watcherHandles = []);\n    } else if (!runsImmediately) {\n      const watchStopHandle = () => {\n      };\n      watchStopHandle.stop = shared.NOOP;\n      watchStopHandle.resume = shared.NOOP;\n      watchStopHandle.pause = shared.NOOP;\n      return watchStopHandle;\n    }\n  }\n  const instance = currentInstance;\n  baseWatchOptions.call = (fn, type, args) => callWithAsyncErrorHandling(fn, instance, type, args);\n  let isPre = false;\n  if (flush === \"post\") {\n    baseWatchOptions.scheduler = (job) => {\n      queuePostRenderEffect(job, instance && instance.suspense);\n    };\n  } else if (flush !== \"sync\") {\n    isPre = true;\n    baseWatchOptions.scheduler = (job, isFirstRun) => {\n      if (isFirstRun) {\n        job();\n      } else {\n        queueJob(job);\n      }\n    };\n  }\n  baseWatchOptions.augmentJob = (job) => {\n    if (cb) {\n      job.flags |= 4;\n    }\n    if (isPre) {\n      job.flags |= 2;\n      if (instance) {\n        job.id = instance.uid;\n        job.i = instance;\n      }\n    }\n  };\n  const watchHandle = reactivity.watch(source, cb, baseWatchOptions);\n  if (isInSSRComponentSetup) {\n    if (ssrCleanup) {\n      ssrCleanup.push(watchHandle);\n    } else if (runsImmediately) {\n      watchHandle();\n    }\n  }\n  return watchHandle;\n}\nfunction instanceWatch(source, value, options) {\n  const publicThis = this.proxy;\n  const getter = shared.isString(source) ? source.includes(\".\") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis);\n  let cb;\n  if (shared.isFunction(value)) {\n    cb = value;\n  } else {\n    cb = value.handler;\n    options = value;\n  }\n  const reset = setCurrentInstance(this);\n  const res = doWatch(getter, cb.bind(publicThis), options);\n  reset();\n  return res;\n}\nfunction createPathGetter(ctx, path) {\n  const segments = path.split(\".\");\n  return () => {\n    let cur = ctx;\n    for (let i = 0; i < segments.length && cur; i++) {\n      cur = cur[segments[i]];\n    }\n    return cur;\n  };\n}\n\nfunction useModel(props, name, options = shared.EMPTY_OBJ) {\n  const i = getCurrentInstance();\n  const camelizedName = shared.camelize(name);\n  const hyphenatedName = shared.hyphenate(name);\n  const modifiers = getModelModifiers(props, camelizedName);\n  const res = reactivity.customRef((track, trigger) => {\n    let localValue;\n    let prevSetValue = shared.EMPTY_OBJ;\n    let prevEmittedValue;\n    watchSyncEffect(() => {\n      const propValue = props[camelizedName];\n      if (shared.hasChanged(localValue, propValue)) {\n        localValue = propValue;\n        trigger();\n      }\n    });\n    return {\n      get() {\n        track();\n        return options.get ? options.get(localValue) : localValue;\n      },\n      set(value) {\n        const emittedValue = options.set ? options.set(value) : value;\n        if (!shared.hasChanged(emittedValue, localValue) && !(prevSetValue !== shared.EMPTY_OBJ && shared.hasChanged(value, prevSetValue))) {\n          return;\n        }\n        const rawProps = i.vnode.props;\n        if (!(rawProps && // check if parent has passed v-model\n        (name in rawProps || camelizedName in rawProps || hyphenatedName in rawProps) && (`onUpdate:${name}` in rawProps || `onUpdate:${camelizedName}` in rawProps || `onUpdate:${hyphenatedName}` in rawProps))) {\n          localValue = value;\n          trigger();\n        }\n        i.emit(`update:${name}`, emittedValue);\n        if (shared.hasChanged(value, emittedValue) && shared.hasChanged(value, prevSetValue) && !shared.hasChanged(emittedValue, prevEmittedValue)) {\n          trigger();\n        }\n        prevSetValue = value;\n        prevEmittedValue = emittedValue;\n      }\n    };\n  });\n  res[Symbol.iterator] = () => {\n    let i2 = 0;\n    return {\n      next() {\n        if (i2 < 2) {\n          return { value: i2++ ? modifiers || shared.EMPTY_OBJ : res, done: false };\n        } else {\n          return { done: true };\n        }\n      }\n    };\n  };\n  return res;\n}\nconst getModelModifiers = (props, modelName) => {\n  return modelName === \"modelValue\" || modelName === \"model-value\" ? props.modelModifiers : props[`${modelName}Modifiers`] || props[`${shared.camelize(modelName)}Modifiers`] || props[`${shared.hyphenate(modelName)}Modifiers`];\n};\n\nfunction emit(instance, event, ...rawArgs) {\n  if (instance.isUnmounted) return;\n  const props = instance.vnode.props || shared.EMPTY_OBJ;\n  let args = rawArgs;\n  const isModelListener = event.startsWith(\"update:\");\n  const modifiers = isModelListener && getModelModifiers(props, event.slice(7));\n  if (modifiers) {\n    if (modifiers.trim) {\n      args = rawArgs.map((a) => shared.isString(a) ? a.trim() : a);\n    }\n    if (modifiers.number) {\n      args = rawArgs.map(shared.looseToNumber);\n    }\n  }\n  let handlerName;\n  let handler = props[handlerName = shared.toHandlerKey(event)] || // also try camelCase event handler (#2249)\n  props[handlerName = shared.toHandlerKey(shared.camelize(event))];\n  if (!handler && isModelListener) {\n    handler = props[handlerName = shared.toHandlerKey(shared.hyphenate(event))];\n  }\n  if (handler) {\n    callWithAsyncErrorHandling(\n      handler,\n      instance,\n      6,\n      args\n    );\n  }\n  const onceHandler = props[handlerName + `Once`];\n  if (onceHandler) {\n    if (!instance.emitted) {\n      instance.emitted = {};\n    } else if (instance.emitted[handlerName]) {\n      return;\n    }\n    instance.emitted[handlerName] = true;\n    callWithAsyncErrorHandling(\n      onceHandler,\n      instance,\n      6,\n      args\n    );\n  }\n}\nfunction normalizeEmitsOptions(comp, appContext, asMixin = false) {\n  const cache = appContext.emitsCache;\n  const cached = cache.get(comp);\n  if (cached !== void 0) {\n    return cached;\n  }\n  const raw = comp.emits;\n  let normalized = {};\n  let hasExtends = false;\n  if (!shared.isFunction(comp)) {\n    const extendEmits = (raw2) => {\n      const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true);\n      if (normalizedFromExtend) {\n        hasExtends = true;\n        shared.extend(normalized, normalizedFromExtend);\n      }\n    };\n    if (!asMixin && appContext.mixins.length) {\n      appContext.mixins.forEach(extendEmits);\n    }\n    if (comp.extends) {\n      extendEmits(comp.extends);\n    }\n    if (comp.mixins) {\n      comp.mixins.forEach(extendEmits);\n    }\n  }\n  if (!raw && !hasExtends) {\n    if (shared.isObject(comp)) {\n      cache.set(comp, null);\n    }\n    return null;\n  }\n  if (shared.isArray(raw)) {\n    raw.forEach((key) => normalized[key] = null);\n  } else {\n    shared.extend(normalized, raw);\n  }\n  if (shared.isObject(comp)) {\n    cache.set(comp, normalized);\n  }\n  return normalized;\n}\nfunction isEmitListener(options, key) {\n  if (!options || !shared.isOn(key)) {\n    return false;\n  }\n  key = key.slice(2).replace(/Once$/, \"\");\n  return shared.hasOwn(options, key[0].toLowerCase() + key.slice(1)) || shared.hasOwn(options, shared.hyphenate(key)) || shared.hasOwn(options, key);\n}\n\nfunction markAttrsAccessed() {\n}\nfunction renderComponentRoot(instance) {\n  const {\n    type: Component,\n    vnode,\n    proxy,\n    withProxy,\n    propsOptions: [propsOptions],\n    slots,\n    attrs,\n    emit,\n    render,\n    renderCache,\n    props,\n    data,\n    setupState,\n    ctx,\n    inheritAttrs\n  } = instance;\n  const prev = setCurrentRenderingInstance(instance);\n  let result;\n  let fallthroughAttrs;\n  try {\n    if (vnode.shapeFlag & 4) {\n      const proxyToUse = withProxy || proxy;\n      const thisProxy = false ? new Proxy(proxyToUse, {\n        get(target, key, receiver) {\n          warn(\n            `Property '${String(\n              key\n            )}' was accessed via 'this'. Avoid using 'this' in templates.`\n          );\n          return Reflect.get(target, key, receiver);\n        }\n      }) : proxyToUse;\n      result = normalizeVNode(\n        render.call(\n          thisProxy,\n          proxyToUse,\n          renderCache,\n          false ? shallowReadonly(props) : props,\n          setupState,\n          data,\n          ctx\n        )\n      );\n      fallthroughAttrs = attrs;\n    } else {\n      const render2 = Component;\n      if (false) ;\n      result = normalizeVNode(\n        render2.length > 1 ? render2(\n          false ? shallowReadonly(props) : props,\n          false ? {\n            get attrs() {\n              markAttrsAccessed();\n              return shallowReadonly(attrs);\n            },\n            slots,\n            emit\n          } : { attrs, slots, emit }\n        ) : render2(\n          false ? shallowReadonly(props) : props,\n          null\n        )\n      );\n      fallthroughAttrs = Component.props ? attrs : getFunctionalFallthrough(attrs);\n    }\n  } catch (err) {\n    blockStack.length = 0;\n    handleError(err, instance, 1);\n    result = createVNode(Comment);\n  }\n  let root = result;\n  if (fallthroughAttrs && inheritAttrs !== false) {\n    const keys = Object.keys(fallthroughAttrs);\n    const { shapeFlag } = root;\n    if (keys.length) {\n      if (shapeFlag & (1 | 6)) {\n        if (propsOptions && keys.some(shared.isModelListener)) {\n          fallthroughAttrs = filterModelListeners(\n            fallthroughAttrs,\n            propsOptions\n          );\n        }\n        root = cloneVNode(root, fallthroughAttrs, false, true);\n      }\n    }\n  }\n  if (vnode.dirs) {\n    root = cloneVNode(root, null, false, true);\n    root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;\n  }\n  if (vnode.transition) {\n    setTransitionHooks(root, vnode.transition);\n  }\n  {\n    result = root;\n  }\n  setCurrentRenderingInstance(prev);\n  return result;\n}\nfunction filterSingleRoot(children, recurse = true) {\n  let singleRoot;\n  for (let i = 0; i < children.length; i++) {\n    const child = children[i];\n    if (isVNode(child)) {\n      if (child.type !== Comment || child.children === \"v-if\") {\n        if (singleRoot) {\n          return;\n        } else {\n          singleRoot = child;\n        }\n      }\n    } else {\n      return;\n    }\n  }\n  return singleRoot;\n}\nconst getFunctionalFallthrough = (attrs) => {\n  let res;\n  for (const key in attrs) {\n    if (key === \"class\" || key === \"style\" || shared.isOn(key)) {\n      (res || (res = {}))[key] = attrs[key];\n    }\n  }\n  return res;\n};\nconst filterModelListeners = (attrs, props) => {\n  const res = {};\n  for (const key in attrs) {\n    if (!shared.isModelListener(key) || !(key.slice(9) in props)) {\n      res[key] = attrs[key];\n    }\n  }\n  return res;\n};\nfunction shouldUpdateComponent(prevVNode, nextVNode, optimized) {\n  const { props: prevProps, children: prevChildren, component } = prevVNode;\n  const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;\n  const emits = component.emitsOptions;\n  if (nextVNode.dirs || nextVNode.transition) {\n    return true;\n  }\n  if (optimized && patchFlag >= 0) {\n    if (patchFlag & 1024) {\n      return true;\n    }\n    if (patchFlag & 16) {\n      if (!prevProps) {\n        return !!nextProps;\n      }\n      return hasPropsChanged(prevProps, nextProps, emits);\n    } else if (patchFlag & 8) {\n      const dynamicProps = nextVNode.dynamicProps;\n      for (let i = 0; i < dynamicProps.length; i++) {\n        const key = dynamicProps[i];\n        if (nextProps[key] !== prevProps[key] && !isEmitListener(emits, key)) {\n          return true;\n        }\n      }\n    }\n  } else {\n    if (prevChildren || nextChildren) {\n      if (!nextChildren || !nextChildren.$stable) {\n        return true;\n      }\n    }\n    if (prevProps === nextProps) {\n      return false;\n    }\n    if (!prevProps) {\n      return !!nextProps;\n    }\n    if (!nextProps) {\n      return true;\n    }\n    return hasPropsChanged(prevProps, nextProps, emits);\n  }\n  return false;\n}\nfunction hasPropsChanged(prevProps, nextProps, emitsOptions) {\n  const nextKeys = Object.keys(nextProps);\n  if (nextKeys.length !== Object.keys(prevProps).length) {\n    return true;\n  }\n  for (let i = 0; i < nextKeys.length; i++) {\n    const key = nextKeys[i];\n    if (nextProps[key] !== prevProps[key] && !isEmitListener(emitsOptions, key)) {\n      return true;\n    }\n  }\n  return false;\n}\nfunction updateHOCHostEl({ vnode, parent }, el) {\n  while (parent) {\n    const root = parent.subTree;\n    if (root.suspense && root.suspense.activeBranch === vnode) {\n      root.el = vnode.el;\n    }\n    if (root === vnode) {\n      (vnode = parent.vnode).el = el;\n      parent = parent.parent;\n    } else {\n      break;\n    }\n  }\n}\n\nconst isSuspense = (type) => type.__isSuspense;\nlet suspenseId = 0;\nconst SuspenseImpl = {\n  name: \"Suspense\",\n  // In order to make Suspense tree-shakable, we need to avoid importing it\n  // directly in the renderer. The renderer checks for the __isSuspense flag\n  // on a vnode's type and calls the `process` method, passing in renderer\n  // internals.\n  __isSuspense: true,\n  process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) {\n    if (n1 == null) {\n      mountSuspense(\n        n2,\n        container,\n        anchor,\n        parentComponent,\n        parentSuspense,\n        namespace,\n        slotScopeIds,\n        optimized,\n        rendererInternals\n      );\n    } else {\n      if (parentSuspense && parentSuspense.deps > 0 && !n1.suspense.isInFallback) {\n        n2.suspense = n1.suspense;\n        n2.suspense.vnode = n2;\n        n2.el = n1.el;\n        return;\n      }\n      patchSuspense(\n        n1,\n        n2,\n        container,\n        anchor,\n        parentComponent,\n        namespace,\n        slotScopeIds,\n        optimized,\n        rendererInternals\n      );\n    }\n  },\n  hydrate: hydrateSuspense,\n  normalize: normalizeSuspenseChildren\n};\nconst Suspense = SuspenseImpl ;\nfunction triggerEvent(vnode, name) {\n  const eventListener = vnode.props && vnode.props[name];\n  if (shared.isFunction(eventListener)) {\n    eventListener();\n  }\n}\nfunction mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) {\n  const {\n    p: patch,\n    o: { createElement }\n  } = rendererInternals;\n  const hiddenContainer = createElement(\"div\");\n  const suspense = vnode.suspense = createSuspenseBoundary(\n    vnode,\n    parentSuspense,\n    parentComponent,\n    container,\n    hiddenContainer,\n    anchor,\n    namespace,\n    slotScopeIds,\n    optimized,\n    rendererInternals\n  );\n  patch(\n    null,\n    suspense.pendingBranch = vnode.ssContent,\n    hiddenContainer,\n    null,\n    parentComponent,\n    suspense,\n    namespace,\n    slotScopeIds\n  );\n  if (suspense.deps > 0) {\n    triggerEvent(vnode, \"onPending\");\n    triggerEvent(vnode, \"onFallback\");\n    patch(\n      null,\n      vnode.ssFallback,\n      container,\n      anchor,\n      parentComponent,\n      null,\n      // fallback tree will not have suspense context\n      namespace,\n      slotScopeIds\n    );\n    setActiveBranch(suspense, vnode.ssFallback);\n  } else {\n    suspense.resolve(false, true);\n  }\n}\nfunction patchSuspense(n1, n2, container, anchor, parentComponent, namespace, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {\n  const suspense = n2.suspense = n1.suspense;\n  suspense.vnode = n2;\n  n2.el = n1.el;\n  const newBranch = n2.ssContent;\n  const newFallback = n2.ssFallback;\n  const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;\n  if (pendingBranch) {\n    suspense.pendingBranch = newBranch;\n    if (isSameVNodeType(newBranch, pendingBranch)) {\n      patch(\n        pendingBranch,\n        newBranch,\n        suspense.hiddenContainer,\n        null,\n        parentComponent,\n        suspense,\n        namespace,\n        slotScopeIds,\n        optimized\n      );\n      if (suspense.deps <= 0) {\n        suspense.resolve();\n      } else if (isInFallback) {\n        if (!isHydrating) {\n          patch(\n            activeBranch,\n            newFallback,\n            container,\n            anchor,\n            parentComponent,\n            null,\n            // fallback tree will not have suspense context\n            namespace,\n            slotScopeIds,\n            optimized\n          );\n          setActiveBranch(suspense, newFallback);\n        }\n      }\n    } else {\n      suspense.pendingId = suspenseId++;\n      if (isHydrating) {\n        suspense.isHydrating = false;\n        suspense.activeBranch = pendingBranch;\n      } else {\n        unmount(pendingBranch, parentComponent, suspense);\n      }\n      suspense.deps = 0;\n      suspense.effects.length = 0;\n      suspense.hiddenContainer = createElement(\"div\");\n      if (isInFallback) {\n        patch(\n          null,\n          newBranch,\n          suspense.hiddenContainer,\n          null,\n          parentComponent,\n          suspense,\n          namespace,\n          slotScopeIds,\n          optimized\n        );\n        if (suspense.deps <= 0) {\n          suspense.resolve();\n        } else {\n          patch(\n            activeBranch,\n            newFallback,\n            container,\n            anchor,\n            parentComponent,\n            null,\n            // fallback tree will not have suspense context\n            namespace,\n            slotScopeIds,\n            optimized\n          );\n          setActiveBranch(suspense, newFallback);\n        }\n      } else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {\n        patch(\n          activeBranch,\n          newBranch,\n          container,\n          anchor,\n          parentComponent,\n          suspense,\n          namespace,\n          slotScopeIds,\n          optimized\n        );\n        suspense.resolve(true);\n      } else {\n        patch(\n          null,\n          newBranch,\n          suspense.hiddenContainer,\n          null,\n          parentComponent,\n          suspense,\n          namespace,\n          slotScopeIds,\n          optimized\n        );\n        if (suspense.deps <= 0) {\n          suspense.resolve();\n        }\n      }\n    }\n  } else {\n    if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {\n      patch(\n        activeBranch,\n        newBranch,\n        container,\n        anchor,\n        parentComponent,\n        suspense,\n        namespace,\n        slotScopeIds,\n        optimized\n      );\n      setActiveBranch(suspense, newBranch);\n    } else {\n      triggerEvent(n2, \"onPending\");\n      suspense.pendingBranch = newBranch;\n      if (newBranch.shapeFlag & 512) {\n        suspense.pendingId = newBranch.component.suspenseId;\n      } else {\n        suspense.pendingId = suspenseId++;\n      }\n      patch(\n        null,\n        newBranch,\n        suspense.hiddenContainer,\n        null,\n        parentComponent,\n        suspense,\n        namespace,\n        slotScopeIds,\n        optimized\n      );\n      if (suspense.deps <= 0) {\n        suspense.resolve();\n      } else {\n        const { timeout, pendingId } = suspense;\n        if (timeout > 0) {\n          setTimeout(() => {\n            if (suspense.pendingId === pendingId) {\n              suspense.fallback(newFallback);\n            }\n          }, timeout);\n        } else if (timeout === 0) {\n          suspense.fallback(newFallback);\n        }\n      }\n    }\n  }\n}\nfunction createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, namespace, slotScopeIds, optimized, rendererInternals, isHydrating = false) {\n  const {\n    p: patch,\n    m: move,\n    um: unmount,\n    n: next,\n    o: { parentNode, remove }\n  } = rendererInternals;\n  let parentSuspenseId;\n  const isSuspensible = isVNodeSuspensible(vnode);\n  if (isSuspensible) {\n    if (parentSuspense && parentSuspense.pendingBranch) {\n      parentSuspenseId = parentSuspense.pendingId;\n      parentSuspense.deps++;\n    }\n  }\n  const timeout = vnode.props ? shared.toNumber(vnode.props.timeout) : void 0;\n  const initialAnchor = anchor;\n  const suspense = {\n    vnode,\n    parent: parentSuspense,\n    parentComponent,\n    namespace,\n    container,\n    hiddenContainer,\n    deps: 0,\n    pendingId: suspenseId++,\n    timeout: typeof timeout === \"number\" ? timeout : -1,\n    activeBranch: null,\n    pendingBranch: null,\n    isInFallback: !isHydrating,\n    isHydrating,\n    isUnmounted: false,\n    effects: [],\n    resolve(resume = false, sync = false) {\n      const {\n        vnode: vnode2,\n        activeBranch,\n        pendingBranch,\n        pendingId,\n        effects,\n        parentComponent: parentComponent2,\n        container: container2\n      } = suspense;\n      let delayEnter = false;\n      if (suspense.isHydrating) {\n        suspense.isHydrating = false;\n      } else if (!resume) {\n        delayEnter = activeBranch && pendingBranch.transition && pendingBranch.transition.mode === \"out-in\";\n        if (delayEnter) {\n          activeBranch.transition.afterLeave = () => {\n            if (pendingId === suspense.pendingId) {\n              move(\n                pendingBranch,\n                container2,\n                anchor === initialAnchor ? next(activeBranch) : anchor,\n                0\n              );\n              queuePostFlushCb(effects);\n            }\n          };\n        }\n        if (activeBranch) {\n          if (parentNode(activeBranch.el) === container2) {\n            anchor = next(activeBranch);\n          }\n          unmount(activeBranch, parentComponent2, suspense, true);\n        }\n        if (!delayEnter) {\n          move(pendingBranch, container2, anchor, 0);\n        }\n      }\n      setActiveBranch(suspense, pendingBranch);\n      suspense.pendingBranch = null;\n      suspense.isInFallback = false;\n      let parent = suspense.parent;\n      let hasUnresolvedAncestor = false;\n      while (parent) {\n        if (parent.pendingBranch) {\n          parent.effects.push(...effects);\n          hasUnresolvedAncestor = true;\n          break;\n        }\n        parent = parent.parent;\n      }\n      if (!hasUnresolvedAncestor && !delayEnter) {\n        queuePostFlushCb(effects);\n      }\n      suspense.effects = [];\n      if (isSuspensible) {\n        if (parentSuspense && parentSuspense.pendingBranch && parentSuspenseId === parentSuspense.pendingId) {\n          parentSuspense.deps--;\n          if (parentSuspense.deps === 0 && !sync) {\n            parentSuspense.resolve();\n          }\n        }\n      }\n      triggerEvent(vnode2, \"onResolve\");\n    },\n    fallback(fallbackVNode) {\n      if (!suspense.pendingBranch) {\n        return;\n      }\n      const { vnode: vnode2, activeBranch, parentComponent: parentComponent2, container: container2, namespace: namespace2 } = suspense;\n      triggerEvent(vnode2, \"onFallback\");\n      const anchor2 = next(activeBranch);\n      const mountFallback = () => {\n        if (!suspense.isInFallback) {\n          return;\n        }\n        patch(\n          null,\n          fallbackVNode,\n          container2,\n          anchor2,\n          parentComponent2,\n          null,\n          // fallback tree will not have suspense context\n          namespace2,\n          slotScopeIds,\n          optimized\n        );\n        setActiveBranch(suspense, fallbackVNode);\n      };\n      const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === \"out-in\";\n      if (delayEnter) {\n        activeBranch.transition.afterLeave = mountFallback;\n      }\n      suspense.isInFallback = true;\n      unmount(\n        activeBranch,\n        parentComponent2,\n        null,\n        // no suspense so unmount hooks fire now\n        true\n        // shouldRemove\n      );\n      if (!delayEnter) {\n        mountFallback();\n      }\n    },\n    move(container2, anchor2, type) {\n      suspense.activeBranch && move(suspense.activeBranch, container2, anchor2, type);\n      suspense.container = container2;\n    },\n    next() {\n      return suspense.activeBranch && next(suspense.activeBranch);\n    },\n    registerDep(instance, setupRenderEffect, optimized2) {\n      const isInPendingSuspense = !!suspense.pendingBranch;\n      if (isInPendingSuspense) {\n        suspense.deps++;\n      }\n      const hydratedEl = instance.vnode.el;\n      instance.asyncDep.catch((err) => {\n        handleError(err, instance, 0);\n      }).then((asyncSetupResult) => {\n        if (instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId) {\n          return;\n        }\n        instance.asyncResolved = true;\n        const { vnode: vnode2 } = instance;\n        handleSetupResult(instance, asyncSetupResult, false);\n        if (hydratedEl) {\n          vnode2.el = hydratedEl;\n        }\n        const placeholder = !hydratedEl && instance.subTree.el;\n        setupRenderEffect(\n          instance,\n          vnode2,\n          // component may have been moved before resolve.\n          // if this is not a hydration, instance.subTree will be the comment\n          // placeholder.\n          parentNode(hydratedEl || instance.subTree.el),\n          // anchor will not be used if this is hydration, so only need to\n          // consider the comment placeholder case.\n          hydratedEl ? null : next(instance.subTree),\n          suspense,\n          namespace,\n          optimized2\n        );\n        if (placeholder) {\n          remove(placeholder);\n        }\n        updateHOCHostEl(instance, vnode2.el);\n        if (isInPendingSuspense && --suspense.deps === 0) {\n          suspense.resolve();\n        }\n      });\n    },\n    unmount(parentSuspense2, doRemove) {\n      suspense.isUnmounted = true;\n      if (suspense.activeBranch) {\n        unmount(\n          suspense.activeBranch,\n          parentComponent,\n          parentSuspense2,\n          doRemove\n        );\n      }\n      if (suspense.pendingBranch) {\n        unmount(\n          suspense.pendingBranch,\n          parentComponent,\n          parentSuspense2,\n          doRemove\n        );\n      }\n    }\n  };\n  return suspense;\n}\nfunction hydrateSuspense(node, vnode, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals, hydrateNode) {\n  const suspense = vnode.suspense = createSuspenseBoundary(\n    vnode,\n    parentSuspense,\n    parentComponent,\n    node.parentNode,\n    // eslint-disable-next-line no-restricted-globals\n    document.createElement(\"div\"),\n    null,\n    namespace,\n    slotScopeIds,\n    optimized,\n    rendererInternals,\n    true\n  );\n  const result = hydrateNode(\n    node,\n    suspense.pendingBranch = vnode.ssContent,\n    parentComponent,\n    suspense,\n    slotScopeIds,\n    optimized\n  );\n  if (suspense.deps === 0) {\n    suspense.resolve(false, true);\n  }\n  return result;\n}\nfunction normalizeSuspenseChildren(vnode) {\n  const { shapeFlag, children } = vnode;\n  const isSlotChildren = shapeFlag & 32;\n  vnode.ssContent = normalizeSuspenseSlot(\n    isSlotChildren ? children.default : children\n  );\n  vnode.ssFallback = isSlotChildren ? normalizeSuspenseSlot(children.fallback) : createVNode(Comment);\n}\nfunction normalizeSuspenseSlot(s) {\n  let block;\n  if (shared.isFunction(s)) {\n    const trackBlock = isBlockTreeEnabled && s._c;\n    if (trackBlock) {\n      s._d = false;\n      openBlock();\n    }\n    s = s();\n    if (trackBlock) {\n      s._d = true;\n      block = currentBlock;\n      closeBlock();\n    }\n  }\n  if (shared.isArray(s)) {\n    const singleChild = filterSingleRoot(s);\n    s = singleChild;\n  }\n  s = normalizeVNode(s);\n  if (block && !s.dynamicChildren) {\n    s.dynamicChildren = block.filter((c) => c !== s);\n  }\n  return s;\n}\nfunction queueEffectWithSuspense(fn, suspense) {\n  if (suspense && suspense.pendingBranch) {\n    if (shared.isArray(fn)) {\n      suspense.effects.push(...fn);\n    } else {\n      suspense.effects.push(fn);\n    }\n  } else {\n    queuePostFlushCb(fn);\n  }\n}\nfunction setActiveBranch(suspense, branch) {\n  suspense.activeBranch = branch;\n  const { vnode, parentComponent } = suspense;\n  let el = branch.el;\n  while (!el && branch.component) {\n    branch = branch.component.subTree;\n    el = branch.el;\n  }\n  vnode.el = el;\n  if (parentComponent && parentComponent.subTree === vnode) {\n    parentComponent.vnode.el = el;\n    updateHOCHostEl(parentComponent, el);\n  }\n}\nfunction isVNodeSuspensible(vnode) {\n  const suspensible = vnode.props && vnode.props.suspensible;\n  return suspensible != null && suspensible !== false;\n}\n\nconst Fragment = Symbol.for(\"v-fgt\");\nconst Text = Symbol.for(\"v-txt\");\nconst Comment = Symbol.for(\"v-cmt\");\nconst Static = Symbol.for(\"v-stc\");\nconst blockStack = [];\nlet currentBlock = null;\nfunction openBlock(disableTracking = false) {\n  blockStack.push(currentBlock = disableTracking ? null : []);\n}\nfunction closeBlock() {\n  blockStack.pop();\n  currentBlock = blockStack[blockStack.length - 1] || null;\n}\nlet isBlockTreeEnabled = 1;\nfunction setBlockTracking(value, inVOnce = false) {\n  isBlockTreeEnabled += value;\n  if (value < 0 && currentBlock && inVOnce) {\n    currentBlock.hasOnce = true;\n  }\n}\nfunction setupBlock(vnode) {\n  vnode.dynamicChildren = isBlockTreeEnabled > 0 ? currentBlock || shared.EMPTY_ARR : null;\n  closeBlock();\n  if (isBlockTreeEnabled > 0 && currentBlock) {\n    currentBlock.push(vnode);\n  }\n  return vnode;\n}\nfunction createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {\n  return setupBlock(\n    createBaseVNode(\n      type,\n      props,\n      children,\n      patchFlag,\n      dynamicProps,\n      shapeFlag,\n      true\n    )\n  );\n}\nfunction createBlock(type, props, children, patchFlag, dynamicProps) {\n  return setupBlock(\n    createVNode(\n      type,\n      props,\n      children,\n      patchFlag,\n      dynamicProps,\n      true\n    )\n  );\n}\nfunction isVNode(value) {\n  return value ? value.__v_isVNode === true : false;\n}\nfunction isSameVNodeType(n1, n2) {\n  return n1.type === n2.type && n1.key === n2.key;\n}\nfunction transformVNodeArgs(transformer) {\n}\nconst normalizeKey = ({ key }) => key != null ? key : null;\nconst normalizeRef = ({\n  ref,\n  ref_key,\n  ref_for\n}) => {\n  if (typeof ref === \"number\") {\n    ref = \"\" + ref;\n  }\n  return ref != null ? shared.isString(ref) || reactivity.isRef(ref) || shared.isFunction(ref) ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for } : ref : null;\n};\nfunction createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1, isBlockNode = false, needFullChildrenNormalization = false) {\n  const vnode = {\n    __v_isVNode: true,\n    __v_skip: true,\n    type,\n    props,\n    key: props && normalizeKey(props),\n    ref: props && normalizeRef(props),\n    scopeId: currentScopeId,\n    slotScopeIds: null,\n    children,\n    component: null,\n    suspense: null,\n    ssContent: null,\n    ssFallback: null,\n    dirs: null,\n    transition: null,\n    el: null,\n    anchor: null,\n    target: null,\n    targetStart: null,\n    targetAnchor: null,\n    staticCount: 0,\n    shapeFlag,\n    patchFlag,\n    dynamicProps,\n    dynamicChildren: null,\n    appContext: null,\n    ctx: currentRenderingInstance\n  };\n  if (needFullChildrenNormalization) {\n    normalizeChildren(vnode, children);\n    if (shapeFlag & 128) {\n      type.normalize(vnode);\n    }\n  } else if (children) {\n    vnode.shapeFlag |= shared.isString(children) ? 8 : 16;\n  }\n  if (isBlockTreeEnabled > 0 && // avoid a block node from tracking itself\n  !isBlockNode && // has current parent block\n  currentBlock && // presence of a patch flag indicates this node needs patching on updates.\n  // component nodes also should always be patched, because even if the\n  // component doesn't need to update, it needs to persist the instance on to\n  // the next vnode so that it can be properly unmounted later.\n  (vnode.patchFlag > 0 || shapeFlag & 6) && // the EVENTS flag is only for hydration and if it is the only flag, the\n  // vnode should not be considered dynamic due to handler caching.\n  vnode.patchFlag !== 32) {\n    currentBlock.push(vnode);\n  }\n  return vnode;\n}\nconst createVNode = _createVNode;\nfunction _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {\n  if (!type || type === NULL_DYNAMIC_COMPONENT) {\n    type = Comment;\n  }\n  if (isVNode(type)) {\n    const cloned = cloneVNode(\n      type,\n      props,\n      true\n      /* mergeRef: true */\n    );\n    if (children) {\n      normalizeChildren(cloned, children);\n    }\n    if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) {\n      if (cloned.shapeFlag & 6) {\n        currentBlock[currentBlock.indexOf(type)] = cloned;\n      } else {\n        currentBlock.push(cloned);\n      }\n    }\n    cloned.patchFlag = -2;\n    return cloned;\n  }\n  if (isClassComponent(type)) {\n    type = type.__vccOpts;\n  }\n  if (props) {\n    props = guardReactiveProps(props);\n    let { class: klass, style } = props;\n    if (klass && !shared.isString(klass)) {\n      props.class = shared.normalizeClass(klass);\n    }\n    if (shared.isObject(style)) {\n      if (reactivity.isProxy(style) && !shared.isArray(style)) {\n        style = shared.extend({}, style);\n      }\n      props.style = shared.normalizeStyle(style);\n    }\n  }\n  const shapeFlag = shared.isString(type) ? 1 : isSuspense(type) ? 128 : isTeleport(type) ? 64 : shared.isObject(type) ? 4 : shared.isFunction(type) ? 2 : 0;\n  return createBaseVNode(\n    type,\n    props,\n    children,\n    patchFlag,\n    dynamicProps,\n    shapeFlag,\n    isBlockNode,\n    true\n  );\n}\nfunction guardReactiveProps(props) {\n  if (!props) return null;\n  return reactivity.isProxy(props) || isInternalObject(props) ? shared.extend({}, props) : props;\n}\nfunction cloneVNode(vnode, extraProps, mergeRef = false, cloneTransition = false) {\n  const { props, ref, patchFlag, children, transition } = vnode;\n  const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;\n  const cloned = {\n    __v_isVNode: true,\n    __v_skip: true,\n    type: vnode.type,\n    props: mergedProps,\n    key: mergedProps && normalizeKey(mergedProps),\n    ref: extraProps && extraProps.ref ? (\n      // #2078 in the case of <component :is=\"vnode\" ref=\"extra\"/>\n      // if the vnode itself already has a ref, cloneVNode will need to merge\n      // the refs so the single vnode can be set on multiple refs\n      mergeRef && ref ? shared.isArray(ref) ? ref.concat(normalizeRef(extraProps)) : [ref, normalizeRef(extraProps)] : normalizeRef(extraProps)\n    ) : ref,\n    scopeId: vnode.scopeId,\n    slotScopeIds: vnode.slotScopeIds,\n    children: children,\n    target: vnode.target,\n    targetStart: vnode.targetStart,\n    targetAnchor: vnode.targetAnchor,\n    staticCount: vnode.staticCount,\n    shapeFlag: vnode.shapeFlag,\n    // if the vnode is cloned with extra props, we can no longer assume its\n    // existing patch flag to be reliable and need to add the FULL_PROPS flag.\n    // note: preserve flag for fragments since they use the flag for children\n    // fast paths only.\n    patchFlag: extraProps && vnode.type !== Fragment ? patchFlag === -1 ? 16 : patchFlag | 16 : patchFlag,\n    dynamicProps: vnode.dynamicProps,\n    dynamicChildren: vnode.dynamicChildren,\n    appContext: vnode.appContext,\n    dirs: vnode.dirs,\n    transition,\n    // These should technically only be non-null on mounted VNodes. However,\n    // they *should* be copied for kept-alive vnodes. So we just always copy\n    // them since them being non-null during a mount doesn't affect the logic as\n    // they will simply be overwritten.\n    component: vnode.component,\n    suspense: vnode.suspense,\n    ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),\n    ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),\n    placeholder: vnode.placeholder,\n    el: vnode.el,\n    anchor: vnode.anchor,\n    ctx: vnode.ctx,\n    ce: vnode.ce\n  };\n  if (transition && cloneTransition) {\n    setTransitionHooks(\n      cloned,\n      transition.clone(cloned)\n    );\n  }\n  return cloned;\n}\nfunction createTextVNode(text = \" \", flag = 0) {\n  return createVNode(Text, null, text, flag);\n}\nfunction createStaticVNode(content, numberOfNodes) {\n  const vnode = createVNode(Static, null, content);\n  vnode.staticCount = numberOfNodes;\n  return vnode;\n}\nfunction createCommentVNode(text = \"\", asBlock = false) {\n  return asBlock ? (openBlock(), createBlock(Comment, null, text)) : createVNode(Comment, null, text);\n}\nfunction normalizeVNode(child) {\n  if (child == null || typeof child === \"boolean\") {\n    return createVNode(Comment);\n  } else if (shared.isArray(child)) {\n    return createVNode(\n      Fragment,\n      null,\n      // #3666, avoid reference pollution when reusing vnode\n      child.slice()\n    );\n  } else if (isVNode(child)) {\n    return cloneIfMounted(child);\n  } else {\n    return createVNode(Text, null, String(child));\n  }\n}\nfunction cloneIfMounted(child) {\n  return child.el === null && child.patchFlag !== -1 || child.memo ? child : cloneVNode(child);\n}\nfunction normalizeChildren(vnode, children) {\n  let type = 0;\n  const { shapeFlag } = vnode;\n  if (children == null) {\n    children = null;\n  } else if (shared.isArray(children)) {\n    type = 16;\n  } else if (typeof children === \"object\") {\n    if (shapeFlag & (1 | 64)) {\n      const slot = children.default;\n      if (slot) {\n        slot._c && (slot._d = false);\n        normalizeChildren(vnode, slot());\n        slot._c && (slot._d = true);\n      }\n      return;\n    } else {\n      type = 32;\n      const slotFlag = children._;\n      if (!slotFlag && !isInternalObject(children)) {\n        children._ctx = currentRenderingInstance;\n      } else if (slotFlag === 3 && currentRenderingInstance) {\n        if (currentRenderingInstance.slots._ === 1) {\n          children._ = 1;\n        } else {\n          children._ = 2;\n          vnode.patchFlag |= 1024;\n        }\n      }\n    }\n  } else if (shared.isFunction(children)) {\n    children = { default: children, _ctx: currentRenderingInstance };\n    type = 32;\n  } else {\n    children = String(children);\n    if (shapeFlag & 64) {\n      type = 16;\n      children = [createTextVNode(children)];\n    } else {\n      type = 8;\n    }\n  }\n  vnode.children = children;\n  vnode.shapeFlag |= type;\n}\nfunction mergeProps(...args) {\n  const ret = {};\n  for (let i = 0; i < args.length; i++) {\n    const toMerge = args[i];\n    for (const key in toMerge) {\n      if (key === \"class\") {\n        if (ret.class !== toMerge.class) {\n          ret.class = shared.normalizeClass([ret.class, toMerge.class]);\n        }\n      } else if (key === \"style\") {\n        ret.style = shared.normalizeStyle([ret.style, toMerge.style]);\n      } else if (shared.isOn(key)) {\n        const existing = ret[key];\n        const incoming = toMerge[key];\n        if (incoming && existing !== incoming && !(shared.isArray(existing) && existing.includes(incoming))) {\n          ret[key] = existing ? [].concat(existing, incoming) : incoming;\n        }\n      } else if (key !== \"\") {\n        ret[key] = toMerge[key];\n      }\n    }\n  }\n  return ret;\n}\nfunction invokeVNodeHook(hook, instance, vnode, prevVNode = null) {\n  callWithAsyncErrorHandling(hook, instance, 7, [\n    vnode,\n    prevVNode\n  ]);\n}\n\nconst emptyAppContext = createAppContext();\nlet uid = 0;\nfunction createComponentInstance(vnode, parent, suspense) {\n  const type = vnode.type;\n  const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;\n  const instance = {\n    uid: uid++,\n    vnode,\n    type,\n    parent,\n    appContext,\n    root: null,\n    // to be immediately set\n    next: null,\n    subTree: null,\n    // will be set synchronously right after creation\n    effect: null,\n    update: null,\n    // will be set synchronously right after creation\n    job: null,\n    scope: new reactivity.EffectScope(\n      true\n      /* detached */\n    ),\n    render: null,\n    proxy: null,\n    exposed: null,\n    exposeProxy: null,\n    withProxy: null,\n    provides: parent ? parent.provides : Object.create(appContext.provides),\n    ids: parent ? parent.ids : [\"\", 0, 0],\n    accessCache: null,\n    renderCache: [],\n    // local resolved assets\n    components: null,\n    directives: null,\n    // resolved props and emits options\n    propsOptions: normalizePropsOptions(type, appContext),\n    emitsOptions: normalizeEmitsOptions(type, appContext),\n    // emit\n    emit: null,\n    // to be set immediately\n    emitted: null,\n    // props default value\n    propsDefaults: shared.EMPTY_OBJ,\n    // inheritAttrs\n    inheritAttrs: type.inheritAttrs,\n    // state\n    ctx: shared.EMPTY_OBJ,\n    data: shared.EMPTY_OBJ,\n    props: shared.EMPTY_OBJ,\n    attrs: shared.EMPTY_OBJ,\n    slots: shared.EMPTY_OBJ,\n    refs: shared.EMPTY_OBJ,\n    setupState: shared.EMPTY_OBJ,\n    setupContext: null,\n    // suspense related\n    suspense,\n    suspenseId: suspense ? suspense.pendingId : 0,\n    asyncDep: null,\n    asyncResolved: false,\n    // lifecycle hooks\n    // not using enums here because it results in computed properties\n    isMounted: false,\n    isUnmounted: false,\n    isDeactivated: false,\n    bc: null,\n    c: null,\n    bm: null,\n    m: null,\n    bu: null,\n    u: null,\n    um: null,\n    bum: null,\n    da: null,\n    a: null,\n    rtg: null,\n    rtc: null,\n    ec: null,\n    sp: null\n  };\n  {\n    instance.ctx = { _: instance };\n  }\n  instance.root = parent ? parent.root : instance;\n  instance.emit = emit.bind(null, instance);\n  if (vnode.ce) {\n    vnode.ce(instance);\n  }\n  return instance;\n}\nlet currentInstance = null;\nconst getCurrentInstance = () => currentInstance || currentRenderingInstance;\nlet internalSetCurrentInstance;\nlet setInSSRSetupState;\n{\n  const g = shared.getGlobalThis();\n  const registerGlobalSetter = (key, setter) => {\n    let setters;\n    if (!(setters = g[key])) setters = g[key] = [];\n    setters.push(setter);\n    return (v) => {\n      if (setters.length > 1) setters.forEach((set) => set(v));\n      else setters[0](v);\n    };\n  };\n  internalSetCurrentInstance = registerGlobalSetter(\n    `__VUE_INSTANCE_SETTERS__`,\n    (v) => currentInstance = v\n  );\n  setInSSRSetupState = registerGlobalSetter(\n    `__VUE_SSR_SETTERS__`,\n    (v) => isInSSRComponentSetup = v\n  );\n}\nconst setCurrentInstance = (instance) => {\n  const prev = currentInstance;\n  internalSetCurrentInstance(instance);\n  instance.scope.on();\n  return () => {\n    instance.scope.off();\n    internalSetCurrentInstance(prev);\n  };\n};\nconst unsetCurrentInstance = () => {\n  currentInstance && currentInstance.scope.off();\n  internalSetCurrentInstance(null);\n};\nfunction isStatefulComponent(instance) {\n  return instance.vnode.shapeFlag & 4;\n}\nlet isInSSRComponentSetup = false;\nfunction setupComponent(instance, isSSR = false, optimized = false) {\n  isSSR && setInSSRSetupState(isSSR);\n  const { props, children } = instance.vnode;\n  const isStateful = isStatefulComponent(instance);\n  initProps(instance, props, isStateful, isSSR);\n  initSlots(instance, children, optimized || isSSR);\n  const setupResult = isStateful ? setupStatefulComponent(instance, isSSR) : void 0;\n  isSSR && setInSSRSetupState(false);\n  return setupResult;\n}\nfunction setupStatefulComponent(instance, isSSR) {\n  const Component = instance.type;\n  instance.accessCache = /* @__PURE__ */ Object.create(null);\n  instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers);\n  const { setup } = Component;\n  if (setup) {\n    reactivity.pauseTracking();\n    const setupContext = instance.setupContext = setup.length > 1 ? createSetupContext(instance) : null;\n    const reset = setCurrentInstance(instance);\n    const setupResult = callWithErrorHandling(\n      setup,\n      instance,\n      0,\n      [\n        instance.props,\n        setupContext\n      ]\n    );\n    const isAsyncSetup = shared.isPromise(setupResult);\n    reactivity.resetTracking();\n    reset();\n    if ((isAsyncSetup || instance.sp) && !isAsyncWrapper(instance)) {\n      markAsyncBoundary(instance);\n    }\n    if (isAsyncSetup) {\n      setupResult.then(unsetCurrentInstance, unsetCurrentInstance);\n      if (isSSR) {\n        return setupResult.then((resolvedResult) => {\n          handleSetupResult(instance, resolvedResult, isSSR);\n        }).catch((e) => {\n          handleError(e, instance, 0);\n        });\n      } else {\n        instance.asyncDep = setupResult;\n      }\n    } else {\n      handleSetupResult(instance, setupResult, isSSR);\n    }\n  } else {\n    finishComponentSetup(instance, isSSR);\n  }\n}\nfunction handleSetupResult(instance, setupResult, isSSR) {\n  if (shared.isFunction(setupResult)) {\n    if (instance.type.__ssrInlineRender) {\n      instance.ssrRender = setupResult;\n    } else {\n      instance.render = setupResult;\n    }\n  } else if (shared.isObject(setupResult)) {\n    instance.setupState = reactivity.proxyRefs(setupResult);\n  } else ;\n  finishComponentSetup(instance, isSSR);\n}\nlet compile;\nlet installWithProxy;\nfunction registerRuntimeCompiler(_compile) {\n  compile = _compile;\n  installWithProxy = (i) => {\n    if (i.render._rc) {\n      i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);\n    }\n  };\n}\nconst isRuntimeOnly = () => !compile;\nfunction finishComponentSetup(instance, isSSR, skipOptions) {\n  const Component = instance.type;\n  if (!instance.render) {\n    if (!isSSR && compile && !Component.render) {\n      const template = Component.template || resolveMergedOptions(instance).template;\n      if (template) {\n        const { isCustomElement, compilerOptions } = instance.appContext.config;\n        const { delimiters, compilerOptions: componentCompilerOptions } = Component;\n        const finalCompilerOptions = shared.extend(\n          shared.extend(\n            {\n              isCustomElement,\n              delimiters\n            },\n            compilerOptions\n          ),\n          componentCompilerOptions\n        );\n        Component.render = compile(template, finalCompilerOptions);\n      }\n    }\n    instance.render = Component.render || shared.NOOP;\n    if (installWithProxy) {\n      installWithProxy(instance);\n    }\n  }\n  {\n    const reset = setCurrentInstance(instance);\n    reactivity.pauseTracking();\n    try {\n      applyOptions(instance);\n    } finally {\n      reactivity.resetTracking();\n      reset();\n    }\n  }\n}\nconst attrsProxyHandlers = {\n  get(target, key) {\n    reactivity.track(target, \"get\", \"\");\n    return target[key];\n  }\n};\nfunction createSetupContext(instance) {\n  const expose = (exposed) => {\n    instance.exposed = exposed || {};\n  };\n  {\n    return {\n      attrs: new Proxy(instance.attrs, attrsProxyHandlers),\n      slots: instance.slots,\n      emit: instance.emit,\n      expose\n    };\n  }\n}\nfunction getComponentPublicInstance(instance) {\n  if (instance.exposed) {\n    return instance.exposeProxy || (instance.exposeProxy = new Proxy(reactivity.proxyRefs(reactivity.markRaw(instance.exposed)), {\n      get(target, key) {\n        if (key in target) {\n          return target[key];\n        } else if (key in publicPropertiesMap) {\n          return publicPropertiesMap[key](instance);\n        }\n      },\n      has(target, key) {\n        return key in target || key in publicPropertiesMap;\n      }\n    }));\n  } else {\n    return instance.proxy;\n  }\n}\nfunction getComponentName(Component, includeInferred = true) {\n  return shared.isFunction(Component) ? Component.displayName || Component.name : Component.name || includeInferred && Component.__name;\n}\nfunction isClassComponent(value) {\n  return shared.isFunction(value) && \"__vccOpts\" in value;\n}\n\nconst computed = (getterOrOptions, debugOptions) => {\n  const c = reactivity.computed(getterOrOptions, debugOptions, isInSSRComponentSetup);\n  return c;\n};\n\nfunction h(type, propsOrChildren, children) {\n  const l = arguments.length;\n  if (l === 2) {\n    if (shared.isObject(propsOrChildren) && !shared.isArray(propsOrChildren)) {\n      if (isVNode(propsOrChildren)) {\n        return createVNode(type, null, [propsOrChildren]);\n      }\n      return createVNode(type, propsOrChildren);\n    } else {\n      return createVNode(type, null, propsOrChildren);\n    }\n  } else {\n    if (l > 3) {\n      children = Array.prototype.slice.call(arguments, 2);\n    } else if (l === 3 && isVNode(children)) {\n      children = [children];\n    }\n    return createVNode(type, propsOrChildren, children);\n  }\n}\n\nfunction initCustomFormatter() {\n  {\n    return;\n  }\n}\n\nfunction withMemo(memo, render, cache, index) {\n  const cached = cache[index];\n  if (cached && isMemoSame(cached, memo)) {\n    return cached;\n  }\n  const ret = render();\n  ret.memo = memo.slice();\n  ret.cacheIndex = index;\n  return cache[index] = ret;\n}\nfunction isMemoSame(cached, memo) {\n  const prev = cached.memo;\n  if (prev.length != memo.length) {\n    return false;\n  }\n  for (let i = 0; i < prev.length; i++) {\n    if (shared.hasChanged(prev[i], memo[i])) {\n      return false;\n    }\n  }\n  if (isBlockTreeEnabled > 0 && currentBlock) {\n    currentBlock.push(cached);\n  }\n  return true;\n}\n\nconst version = \"3.5.18\";\nconst warn$1 = shared.NOOP;\nconst ErrorTypeStrings = ErrorTypeStrings$1 ;\nconst devtools = void 0;\nconst setDevtoolsHook = shared.NOOP;\nconst _ssrUtils = {\n  createComponentInstance,\n  setupComponent,\n  renderComponentRoot,\n  setCurrentRenderingInstance,\n  isVNode: isVNode,\n  normalizeVNode,\n  getComponentPublicInstance,\n  ensureValidVNode,\n  pushWarningContext,\n  popWarningContext\n};\nconst ssrUtils = _ssrUtils ;\nconst resolveFilter = null;\nconst compatUtils = null;\nconst DeprecationTypes = null;\n\nexports.EffectScope = reactivity.EffectScope;\nexports.ReactiveEffect = reactivity.ReactiveEffect;\nexports.TrackOpTypes = reactivity.TrackOpTypes;\nexports.TriggerOpTypes = reactivity.TriggerOpTypes;\nexports.customRef = reactivity.customRef;\nexports.effect = reactivity.effect;\nexports.effectScope = reactivity.effectScope;\nexports.getCurrentScope = reactivity.getCurrentScope;\nexports.getCurrentWatcher = reactivity.getCurrentWatcher;\nexports.isProxy = reactivity.isProxy;\nexports.isReactive = reactivity.isReactive;\nexports.isReadonly = reactivity.isReadonly;\nexports.isRef = reactivity.isRef;\nexports.isShallow = reactivity.isShallow;\nexports.markRaw = reactivity.markRaw;\nexports.onScopeDispose = reactivity.onScopeDispose;\nexports.onWatcherCleanup = reactivity.onWatcherCleanup;\nexports.proxyRefs = reactivity.proxyRefs;\nexports.reactive = reactivity.reactive;\nexports.readonly = reactivity.readonly;\nexports.ref = reactivity.ref;\nexports.shallowReactive = reactivity.shallowReactive;\nexports.shallowReadonly = reactivity.shallowReadonly;\nexports.shallowRef = reactivity.shallowRef;\nexports.stop = reactivity.stop;\nexports.toRaw = reactivity.toRaw;\nexports.toRef = reactivity.toRef;\nexports.toRefs = reactivity.toRefs;\nexports.toValue = reactivity.toValue;\nexports.triggerRef = reactivity.triggerRef;\nexports.unref = reactivity.unref;\nexports.camelize = shared.camelize;\nexports.capitalize = shared.capitalize;\nexports.normalizeClass = shared.normalizeClass;\nexports.normalizeProps = shared.normalizeProps;\nexports.normalizeStyle = shared.normalizeStyle;\nexports.toDisplayString = shared.toDisplayString;\nexports.toHandlerKey = shared.toHandlerKey;\nexports.BaseTransition = BaseTransition;\nexports.BaseTransitionPropsValidators = BaseTransitionPropsValidators;\nexports.Comment = Comment;\nexports.DeprecationTypes = DeprecationTypes;\nexports.ErrorCodes = ErrorCodes;\nexports.ErrorTypeStrings = ErrorTypeStrings;\nexports.Fragment = Fragment;\nexports.KeepAlive = KeepAlive;\nexports.Static = Static;\nexports.Suspense = Suspense;\nexports.Teleport = Teleport;\nexports.Text = Text;\nexports.assertNumber = assertNumber;\nexports.callWithAsyncErrorHandling = callWithAsyncErrorHandling;\nexports.callWithErrorHandling = callWithErrorHandling;\nexports.cloneVNode = cloneVNode;\nexports.compatUtils = compatUtils;\nexports.computed = computed;\nexports.createBlock = createBlock;\nexports.createCommentVNode = createCommentVNode;\nexports.createElementBlock = createElementBlock;\nexports.createElementVNode = createBaseVNode;\nexports.createHydrationRenderer = createHydrationRenderer;\nexports.createPropsRestProxy = createPropsRestProxy;\nexports.createRenderer = createRenderer;\nexports.createSlots = createSlots;\nexports.createStaticVNode = createStaticVNode;\nexports.createTextVNode = createTextVNode;\nexports.createVNode = createVNode;\nexports.defineAsyncComponent = defineAsyncComponent;\nexports.defineComponent = defineComponent;\nexports.defineEmits = defineEmits;\nexports.defineExpose = defineExpose;\nexports.defineModel = defineModel;\nexports.defineOptions = defineOptions;\nexports.defineProps = defineProps;\nexports.defineSlots = defineSlots;\nexports.devtools = devtools;\nexports.getCurrentInstance = getCurrentInstance;\nexports.getTransitionRawChildren = getTransitionRawChildren;\nexports.guardReactiveProps = guardReactiveProps;\nexports.h = h;\nexports.handleError = handleError;\nexports.hasInjectionContext = hasInjectionContext;\nexports.hydrateOnIdle = hydrateOnIdle;\nexports.hydrateOnInteraction = hydrateOnInteraction;\nexports.hydrateOnMediaQuery = hydrateOnMediaQuery;\nexports.hydrateOnVisible = hydrateOnVisible;\nexports.initCustomFormatter = initCustomFormatter;\nexports.inject = inject;\nexports.isMemoSame = isMemoSame;\nexports.isRuntimeOnly = isRuntimeOnly;\nexports.isVNode = isVNode;\nexports.mergeDefaults = mergeDefaults;\nexports.mergeModels = mergeModels;\nexports.mergeProps = mergeProps;\nexports.nextTick = nextTick;\nexports.onActivated = onActivated;\nexports.onBeforeMount = onBeforeMount;\nexports.onBeforeUnmount = onBeforeUnmount;\nexports.onBeforeUpdate = onBeforeUpdate;\nexports.onDeactivated = onDeactivated;\nexports.onErrorCaptured = onErrorCaptured;\nexports.onMounted = onMounted;\nexports.onRenderTracked = onRenderTracked;\nexports.onRenderTriggered = onRenderTriggered;\nexports.onServerPrefetch = onServerPrefetch;\nexports.onUnmounted = onUnmounted;\nexports.onUpdated = onUpdated;\nexports.openBlock = openBlock;\nexports.popScopeId = popScopeId;\nexports.provide = provide;\nexports.pushScopeId = pushScopeId;\nexports.queuePostFlushCb = queuePostFlushCb;\nexports.registerRuntimeCompiler = registerRuntimeCompiler;\nexports.renderList = renderList;\nexports.renderSlot = renderSlot;\nexports.resolveComponent = resolveComponent;\nexports.resolveDirective = resolveDirective;\nexports.resolveDynamicComponent = resolveDynamicComponent;\nexports.resolveFilter = resolveFilter;\nexports.resolveTransitionHooks = resolveTransitionHooks;\nexports.setBlockTracking = setBlockTracking;\nexports.setDevtoolsHook = setDevtoolsHook;\nexports.setTransitionHooks = setTransitionHooks;\nexports.ssrContextKey = ssrContextKey;\nexports.ssrUtils = ssrUtils;\nexports.toHandlers = toHandlers;\nexports.transformVNodeArgs = transformVNodeArgs;\nexports.useAttrs = useAttrs;\nexports.useId = useId;\nexports.useModel = useModel;\nexports.useSSRContext = useSSRContext;\nexports.useSlots = useSlots;\nexports.useTemplateRef = useTemplateRef;\nexports.useTransitionState = useTransitionState;\nexports.version = version;\nexports.warn = warn$1;\nexports.watch = watch;\nexports.watchEffect = watchEffect;\nexports.watchPostEffect = watchPostEffect;\nexports.watchSyncEffect = watchSyncEffect;\nexports.withAsyncContext = withAsyncContext;\nexports.withCtx = withCtx;\nexports.withDefaults = withDefaults;\nexports.withDirectives = withDirectives;\nexports.withMemo = withMemo;\nexports.withScopeId = withScopeId;\n","'use strict'\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./dist/runtime-core.cjs.prod.js')\n} else {\n  module.exports = require('./dist/runtime-core.cjs.js')\n}\n","/**\n* @vue/runtime-dom v3.5.18\n* (c) 2018-present Yuxi (Evan) You and Vue contributors\n* @license MIT\n**/\n'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar runtimeCore = require('@vue/runtime-core');\nvar shared = require('@vue/shared');\n\nlet policy = void 0;\nconst tt = typeof window !== \"undefined\" && window.trustedTypes;\nif (tt) {\n  try {\n    policy = /* @__PURE__ */ tt.createPolicy(\"vue\", {\n      createHTML: (val) => val\n    });\n  } catch (e) {\n  }\n}\nconst unsafeToTrustedHTML = policy ? (val) => policy.createHTML(val) : (val) => val;\nconst svgNS = \"http://www.w3.org/2000/svg\";\nconst mathmlNS = \"http://www.w3.org/1998/Math/MathML\";\nconst doc = typeof document !== \"undefined\" ? document : null;\nconst templateContainer = doc && /* @__PURE__ */ doc.createElement(\"template\");\nconst nodeOps = {\n  insert: (child, parent, anchor) => {\n    parent.insertBefore(child, anchor || null);\n  },\n  remove: (child) => {\n    const parent = child.parentNode;\n    if (parent) {\n      parent.removeChild(child);\n    }\n  },\n  createElement: (tag, namespace, is, props) => {\n    const el = namespace === \"svg\" ? doc.createElementNS(svgNS, tag) : namespace === \"mathml\" ? doc.createElementNS(mathmlNS, tag) : is ? doc.createElement(tag, { is }) : doc.createElement(tag);\n    if (tag === \"select\" && props && props.multiple != null) {\n      el.setAttribute(\"multiple\", props.multiple);\n    }\n    return el;\n  },\n  createText: (text) => doc.createTextNode(text),\n  createComment: (text) => doc.createComment(text),\n  setText: (node, text) => {\n    node.nodeValue = text;\n  },\n  setElementText: (el, text) => {\n    el.textContent = text;\n  },\n  parentNode: (node) => node.parentNode,\n  nextSibling: (node) => node.nextSibling,\n  querySelector: (selector) => doc.querySelector(selector),\n  setScopeId(el, id) {\n    el.setAttribute(id, \"\");\n  },\n  // __UNSAFE__\n  // Reason: innerHTML.\n  // Static content here can only come from compiled templates.\n  // As long as the user only uses trusted templates, this is safe.\n  insertStaticContent(content, parent, anchor, namespace, start, end) {\n    const before = anchor ? anchor.previousSibling : parent.lastChild;\n    if (start && (start === end || start.nextSibling)) {\n      while (true) {\n        parent.insertBefore(start.cloneNode(true), anchor);\n        if (start === end || !(start = start.nextSibling)) break;\n      }\n    } else {\n      templateContainer.innerHTML = unsafeToTrustedHTML(\n        namespace === \"svg\" ? `<svg>${content}</svg>` : namespace === \"mathml\" ? `<math>${content}</math>` : content\n      );\n      const template = templateContainer.content;\n      if (namespace === \"svg\" || namespace === \"mathml\") {\n        const wrapper = template.firstChild;\n        while (wrapper.firstChild) {\n          template.appendChild(wrapper.firstChild);\n        }\n        template.removeChild(wrapper);\n      }\n      parent.insertBefore(template, anchor);\n    }\n    return [\n      // first\n      before ? before.nextSibling : parent.firstChild,\n      // last\n      anchor ? anchor.previousSibling : parent.lastChild\n    ];\n  }\n};\n\nconst TRANSITION = \"transition\";\nconst ANIMATION = \"animation\";\nconst vtcKey = Symbol(\"_vtc\");\nconst DOMTransitionPropsValidators = {\n  name: String,\n  type: String,\n  css: {\n    type: Boolean,\n    default: true\n  },\n  duration: [String, Number, Object],\n  enterFromClass: String,\n  enterActiveClass: String,\n  enterToClass: String,\n  appearFromClass: String,\n  appearActiveClass: String,\n  appearToClass: String,\n  leaveFromClass: String,\n  leaveActiveClass: String,\n  leaveToClass: String\n};\nconst TransitionPropsValidators = /* @__PURE__ */ shared.extend(\n  {},\n  runtimeCore.BaseTransitionPropsValidators,\n  DOMTransitionPropsValidators\n);\nconst decorate$1 = (t) => {\n  t.displayName = \"Transition\";\n  t.props = TransitionPropsValidators;\n  return t;\n};\nconst Transition = /* @__PURE__ */ decorate$1(\n  (props, { slots }) => runtimeCore.h(runtimeCore.BaseTransition, resolveTransitionProps(props), slots)\n);\nconst callHook = (hook, args = []) => {\n  if (shared.isArray(hook)) {\n    hook.forEach((h2) => h2(...args));\n  } else if (hook) {\n    hook(...args);\n  }\n};\nconst hasExplicitCallback = (hook) => {\n  return hook ? shared.isArray(hook) ? hook.some((h2) => h2.length > 1) : hook.length > 1 : false;\n};\nfunction resolveTransitionProps(rawProps) {\n  const baseProps = {};\n  for (const key in rawProps) {\n    if (!(key in DOMTransitionPropsValidators)) {\n      baseProps[key] = rawProps[key];\n    }\n  }\n  if (rawProps.css === false) {\n    return baseProps;\n  }\n  const {\n    name = \"v\",\n    type,\n    duration,\n    enterFromClass = `${name}-enter-from`,\n    enterActiveClass = `${name}-enter-active`,\n    enterToClass = `${name}-enter-to`,\n    appearFromClass = enterFromClass,\n    appearActiveClass = enterActiveClass,\n    appearToClass = enterToClass,\n    leaveFromClass = `${name}-leave-from`,\n    leaveActiveClass = `${name}-leave-active`,\n    leaveToClass = `${name}-leave-to`\n  } = rawProps;\n  const durations = normalizeDuration(duration);\n  const enterDuration = durations && durations[0];\n  const leaveDuration = durations && durations[1];\n  const {\n    onBeforeEnter,\n    onEnter,\n    onEnterCancelled,\n    onLeave,\n    onLeaveCancelled,\n    onBeforeAppear = onBeforeEnter,\n    onAppear = onEnter,\n    onAppearCancelled = onEnterCancelled\n  } = baseProps;\n  const finishEnter = (el, isAppear, done, isCancelled) => {\n    el._enterCancelled = isCancelled;\n    removeTransitionClass(el, isAppear ? appearToClass : enterToClass);\n    removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);\n    done && done();\n  };\n  const finishLeave = (el, done) => {\n    el._isLeaving = false;\n    removeTransitionClass(el, leaveFromClass);\n    removeTransitionClass(el, leaveToClass);\n    removeTransitionClass(el, leaveActiveClass);\n    done && done();\n  };\n  const makeEnterHook = (isAppear) => {\n    return (el, done) => {\n      const hook = isAppear ? onAppear : onEnter;\n      const resolve = () => finishEnter(el, isAppear, done);\n      callHook(hook, [el, resolve]);\n      nextFrame(() => {\n        removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);\n        addTransitionClass(el, isAppear ? appearToClass : enterToClass);\n        if (!hasExplicitCallback(hook)) {\n          whenTransitionEnds(el, type, enterDuration, resolve);\n        }\n      });\n    };\n  };\n  return shared.extend(baseProps, {\n    onBeforeEnter(el) {\n      callHook(onBeforeEnter, [el]);\n      addTransitionClass(el, enterFromClass);\n      addTransitionClass(el, enterActiveClass);\n    },\n    onBeforeAppear(el) {\n      callHook(onBeforeAppear, [el]);\n      addTransitionClass(el, appearFromClass);\n      addTransitionClass(el, appearActiveClass);\n    },\n    onEnter: makeEnterHook(false),\n    onAppear: makeEnterHook(true),\n    onLeave(el, done) {\n      el._isLeaving = true;\n      const resolve = () => finishLeave(el, done);\n      addTransitionClass(el, leaveFromClass);\n      if (!el._enterCancelled) {\n        forceReflow();\n        addTransitionClass(el, leaveActiveClass);\n      } else {\n        addTransitionClass(el, leaveActiveClass);\n        forceReflow();\n      }\n      nextFrame(() => {\n        if (!el._isLeaving) {\n          return;\n        }\n        removeTransitionClass(el, leaveFromClass);\n        addTransitionClass(el, leaveToClass);\n        if (!hasExplicitCallback(onLeave)) {\n          whenTransitionEnds(el, type, leaveDuration, resolve);\n        }\n      });\n      callHook(onLeave, [el, resolve]);\n    },\n    onEnterCancelled(el) {\n      finishEnter(el, false, void 0, true);\n      callHook(onEnterCancelled, [el]);\n    },\n    onAppearCancelled(el) {\n      finishEnter(el, true, void 0, true);\n      callHook(onAppearCancelled, [el]);\n    },\n    onLeaveCancelled(el) {\n      finishLeave(el);\n      callHook(onLeaveCancelled, [el]);\n    }\n  });\n}\nfunction normalizeDuration(duration) {\n  if (duration == null) {\n    return null;\n  } else if (shared.isObject(duration)) {\n    return [NumberOf(duration.enter), NumberOf(duration.leave)];\n  } else {\n    const n = NumberOf(duration);\n    return [n, n];\n  }\n}\nfunction NumberOf(val) {\n  const res = shared.toNumber(val);\n  return res;\n}\nfunction addTransitionClass(el, cls) {\n  cls.split(/\\s+/).forEach((c) => c && el.classList.add(c));\n  (el[vtcKey] || (el[vtcKey] = /* @__PURE__ */ new Set())).add(cls);\n}\nfunction removeTransitionClass(el, cls) {\n  cls.split(/\\s+/).forEach((c) => c && el.classList.remove(c));\n  const _vtc = el[vtcKey];\n  if (_vtc) {\n    _vtc.delete(cls);\n    if (!_vtc.size) {\n      el[vtcKey] = void 0;\n    }\n  }\n}\nfunction nextFrame(cb) {\n  requestAnimationFrame(() => {\n    requestAnimationFrame(cb);\n  });\n}\nlet endId = 0;\nfunction whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {\n  const id = el._endId = ++endId;\n  const resolveIfNotStale = () => {\n    if (id === el._endId) {\n      resolve();\n    }\n  };\n  if (explicitTimeout != null) {\n    return setTimeout(resolveIfNotStale, explicitTimeout);\n  }\n  const { type, timeout, propCount } = getTransitionInfo(el, expectedType);\n  if (!type) {\n    return resolve();\n  }\n  const endEvent = type + \"end\";\n  let ended = 0;\n  const end = () => {\n    el.removeEventListener(endEvent, onEnd);\n    resolveIfNotStale();\n  };\n  const onEnd = (e) => {\n    if (e.target === el && ++ended >= propCount) {\n      end();\n    }\n  };\n  setTimeout(() => {\n    if (ended < propCount) {\n      end();\n    }\n  }, timeout + 1);\n  el.addEventListener(endEvent, onEnd);\n}\nfunction getTransitionInfo(el, expectedType) {\n  const styles = window.getComputedStyle(el);\n  const getStyleProperties = (key) => (styles[key] || \"\").split(\", \");\n  const transitionDelays = getStyleProperties(`${TRANSITION}Delay`);\n  const transitionDurations = getStyleProperties(`${TRANSITION}Duration`);\n  const transitionTimeout = getTimeout(transitionDelays, transitionDurations);\n  const animationDelays = getStyleProperties(`${ANIMATION}Delay`);\n  const animationDurations = getStyleProperties(`${ANIMATION}Duration`);\n  const animationTimeout = getTimeout(animationDelays, animationDurations);\n  let type = null;\n  let timeout = 0;\n  let propCount = 0;\n  if (expectedType === TRANSITION) {\n    if (transitionTimeout > 0) {\n      type = TRANSITION;\n      timeout = transitionTimeout;\n      propCount = transitionDurations.length;\n    }\n  } else if (expectedType === ANIMATION) {\n    if (animationTimeout > 0) {\n      type = ANIMATION;\n      timeout = animationTimeout;\n      propCount = animationDurations.length;\n    }\n  } else {\n    timeout = Math.max(transitionTimeout, animationTimeout);\n    type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null;\n    propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0;\n  }\n  const hasTransform = type === TRANSITION && /\\b(transform|all)(,|$)/.test(\n    getStyleProperties(`${TRANSITION}Property`).toString()\n  );\n  return {\n    type,\n    timeout,\n    propCount,\n    hasTransform\n  };\n}\nfunction getTimeout(delays, durations) {\n  while (delays.length < durations.length) {\n    delays = delays.concat(delays);\n  }\n  return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));\n}\nfunction toMs(s) {\n  if (s === \"auto\") return 0;\n  return Number(s.slice(0, -1).replace(\",\", \".\")) * 1e3;\n}\nfunction forceReflow() {\n  return document.body.offsetHeight;\n}\n\nfunction patchClass(el, value, isSVG) {\n  const transitionClasses = el[vtcKey];\n  if (transitionClasses) {\n    value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(\" \");\n  }\n  if (value == null) {\n    el.removeAttribute(\"class\");\n  } else if (isSVG) {\n    el.setAttribute(\"class\", value);\n  } else {\n    el.className = value;\n  }\n}\n\nconst vShowOriginalDisplay = Symbol(\"_vod\");\nconst vShowHidden = Symbol(\"_vsh\");\nconst vShow = {\n  beforeMount(el, { value }, { transition }) {\n    el[vShowOriginalDisplay] = el.style.display === \"none\" ? \"\" : el.style.display;\n    if (transition && value) {\n      transition.beforeEnter(el);\n    } else {\n      setDisplay(el, value);\n    }\n  },\n  mounted(el, { value }, { transition }) {\n    if (transition && value) {\n      transition.enter(el);\n    }\n  },\n  updated(el, { value, oldValue }, { transition }) {\n    if (!value === !oldValue) return;\n    if (transition) {\n      if (value) {\n        transition.beforeEnter(el);\n        setDisplay(el, true);\n        transition.enter(el);\n      } else {\n        transition.leave(el, () => {\n          setDisplay(el, false);\n        });\n      }\n    } else {\n      setDisplay(el, value);\n    }\n  },\n  beforeUnmount(el, { value }) {\n    setDisplay(el, value);\n  }\n};\nfunction setDisplay(el, value) {\n  el.style.display = value ? el[vShowOriginalDisplay] : \"none\";\n  el[vShowHidden] = !value;\n}\nfunction initVShowForSSR() {\n  vShow.getSSRProps = ({ value }) => {\n    if (!value) {\n      return { style: { display: \"none\" } };\n    }\n  };\n}\n\nconst CSS_VAR_TEXT = Symbol(\"\");\nfunction useCssVars(getter) {\n  return;\n}\n\nconst displayRE = /(^|;)\\s*display\\s*:/;\nfunction patchStyle(el, prev, next) {\n  const style = el.style;\n  const isCssString = shared.isString(next);\n  let hasControlledDisplay = false;\n  if (next && !isCssString) {\n    if (prev) {\n      if (!shared.isString(prev)) {\n        for (const key in prev) {\n          if (next[key] == null) {\n            setStyle(style, key, \"\");\n          }\n        }\n      } else {\n        for (const prevStyle of prev.split(\";\")) {\n          const key = prevStyle.slice(0, prevStyle.indexOf(\":\")).trim();\n          if (next[key] == null) {\n            setStyle(style, key, \"\");\n          }\n        }\n      }\n    }\n    for (const key in next) {\n      if (key === \"display\") {\n        hasControlledDisplay = true;\n      }\n      setStyle(style, key, next[key]);\n    }\n  } else {\n    if (isCssString) {\n      if (prev !== next) {\n        const cssVarText = style[CSS_VAR_TEXT];\n        if (cssVarText) {\n          next += \";\" + cssVarText;\n        }\n        style.cssText = next;\n        hasControlledDisplay = displayRE.test(next);\n      }\n    } else if (prev) {\n      el.removeAttribute(\"style\");\n    }\n  }\n  if (vShowOriginalDisplay in el) {\n    el[vShowOriginalDisplay] = hasControlledDisplay ? style.display : \"\";\n    if (el[vShowHidden]) {\n      style.display = \"none\";\n    }\n  }\n}\nconst importantRE = /\\s*!important$/;\nfunction setStyle(style, name, val) {\n  if (shared.isArray(val)) {\n    val.forEach((v) => setStyle(style, name, v));\n  } else {\n    if (val == null) val = \"\";\n    if (name.startsWith(\"--\")) {\n      style.setProperty(name, val);\n    } else {\n      const prefixed = autoPrefix(style, name);\n      if (importantRE.test(val)) {\n        style.setProperty(\n          shared.hyphenate(prefixed),\n          val.replace(importantRE, \"\"),\n          \"important\"\n        );\n      } else {\n        style[prefixed] = val;\n      }\n    }\n  }\n}\nconst prefixes = [\"Webkit\", \"Moz\", \"ms\"];\nconst prefixCache = {};\nfunction autoPrefix(style, rawName) {\n  const cached = prefixCache[rawName];\n  if (cached) {\n    return cached;\n  }\n  let name = runtimeCore.camelize(rawName);\n  if (name !== \"filter\" && name in style) {\n    return prefixCache[rawName] = name;\n  }\n  name = shared.capitalize(name);\n  for (let i = 0; i < prefixes.length; i++) {\n    const prefixed = prefixes[i] + name;\n    if (prefixed in style) {\n      return prefixCache[rawName] = prefixed;\n    }\n  }\n  return rawName;\n}\n\nconst xlinkNS = \"http://www.w3.org/1999/xlink\";\nfunction patchAttr(el, key, value, isSVG, instance, isBoolean = shared.isSpecialBooleanAttr(key)) {\n  if (isSVG && key.startsWith(\"xlink:\")) {\n    if (value == null) {\n      el.removeAttributeNS(xlinkNS, key.slice(6, key.length));\n    } else {\n      el.setAttributeNS(xlinkNS, key, value);\n    }\n  } else {\n    if (value == null || isBoolean && !shared.includeBooleanAttr(value)) {\n      el.removeAttribute(key);\n    } else {\n      el.setAttribute(\n        key,\n        isBoolean ? \"\" : shared.isSymbol(value) ? String(value) : value\n      );\n    }\n  }\n}\n\nfunction patchDOMProp(el, key, value, parentComponent, attrName) {\n  if (key === \"innerHTML\" || key === \"textContent\") {\n    if (value != null) {\n      el[key] = key === \"innerHTML\" ? unsafeToTrustedHTML(value) : value;\n    }\n    return;\n  }\n  const tag = el.tagName;\n  if (key === \"value\" && tag !== \"PROGRESS\" && // custom elements may use _value internally\n  !tag.includes(\"-\")) {\n    const oldValue = tag === \"OPTION\" ? el.getAttribute(\"value\") || \"\" : el.value;\n    const newValue = value == null ? (\n      // #11647: value should be set as empty string for null and undefined,\n      // but <input type=\"checkbox\"> should be set as 'on'.\n      el.type === \"checkbox\" ? \"on\" : \"\"\n    ) : String(value);\n    if (oldValue !== newValue || !(\"_value\" in el)) {\n      el.value = newValue;\n    }\n    if (value == null) {\n      el.removeAttribute(key);\n    }\n    el._value = value;\n    return;\n  }\n  let needRemove = false;\n  if (value === \"\" || value == null) {\n    const type = typeof el[key];\n    if (type === \"boolean\") {\n      value = shared.includeBooleanAttr(value);\n    } else if (value == null && type === \"string\") {\n      value = \"\";\n      needRemove = true;\n    } else if (type === \"number\") {\n      value = 0;\n      needRemove = true;\n    }\n  }\n  try {\n    el[key] = value;\n  } catch (e) {\n  }\n  needRemove && el.removeAttribute(attrName || key);\n}\n\nfunction addEventListener(el, event, handler, options) {\n  el.addEventListener(event, handler, options);\n}\nfunction removeEventListener(el, event, handler, options) {\n  el.removeEventListener(event, handler, options);\n}\nconst veiKey = Symbol(\"_vei\");\nfunction patchEvent(el, rawName, prevValue, nextValue, instance = null) {\n  const invokers = el[veiKey] || (el[veiKey] = {});\n  const existingInvoker = invokers[rawName];\n  if (nextValue && existingInvoker) {\n    existingInvoker.value = nextValue;\n  } else {\n    const [name, options] = parseName(rawName);\n    if (nextValue) {\n      const invoker = invokers[rawName] = createInvoker(\n        nextValue,\n        instance\n      );\n      addEventListener(el, name, invoker, options);\n    } else if (existingInvoker) {\n      removeEventListener(el, name, existingInvoker, options);\n      invokers[rawName] = void 0;\n    }\n  }\n}\nconst optionsModifierRE = /(?:Once|Passive|Capture)$/;\nfunction parseName(name) {\n  let options;\n  if (optionsModifierRE.test(name)) {\n    options = {};\n    let m;\n    while (m = name.match(optionsModifierRE)) {\n      name = name.slice(0, name.length - m[0].length);\n      options[m[0].toLowerCase()] = true;\n    }\n  }\n  const event = name[2] === \":\" ? name.slice(3) : shared.hyphenate(name.slice(2));\n  return [event, options];\n}\nlet cachedNow = 0;\nconst p = /* @__PURE__ */ Promise.resolve();\nconst getNow = () => cachedNow || (p.then(() => cachedNow = 0), cachedNow = Date.now());\nfunction createInvoker(initialValue, instance) {\n  const invoker = (e) => {\n    if (!e._vts) {\n      e._vts = Date.now();\n    } else if (e._vts <= invoker.attached) {\n      return;\n    }\n    runtimeCore.callWithAsyncErrorHandling(\n      patchStopImmediatePropagation(e, invoker.value),\n      instance,\n      5,\n      [e]\n    );\n  };\n  invoker.value = initialValue;\n  invoker.attached = getNow();\n  return invoker;\n}\nfunction patchStopImmediatePropagation(e, value) {\n  if (shared.isArray(value)) {\n    const originalStop = e.stopImmediatePropagation;\n    e.stopImmediatePropagation = () => {\n      originalStop.call(e);\n      e._stopped = true;\n    };\n    return value.map(\n      (fn) => (e2) => !e2._stopped && fn && fn(e2)\n    );\n  } else {\n    return value;\n  }\n}\n\nconst isNativeOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // lowercase letter\nkey.charCodeAt(2) > 96 && key.charCodeAt(2) < 123;\nconst patchProp = (el, key, prevValue, nextValue, namespace, parentComponent) => {\n  const isSVG = namespace === \"svg\";\n  if (key === \"class\") {\n    patchClass(el, nextValue, isSVG);\n  } else if (key === \"style\") {\n    patchStyle(el, prevValue, nextValue);\n  } else if (shared.isOn(key)) {\n    if (!shared.isModelListener(key)) {\n      patchEvent(el, key, prevValue, nextValue, parentComponent);\n    }\n  } else if (key[0] === \".\" ? (key = key.slice(1), true) : key[0] === \"^\" ? (key = key.slice(1), false) : shouldSetAsProp(el, key, nextValue, isSVG)) {\n    patchDOMProp(el, key, nextValue);\n    if (!el.tagName.includes(\"-\") && (key === \"value\" || key === \"checked\" || key === \"selected\")) {\n      patchAttr(el, key, nextValue, isSVG, parentComponent, key !== \"value\");\n    }\n  } else if (\n    // #11081 force set props for possible async custom element\n    el._isVueCE && (/[A-Z]/.test(key) || !shared.isString(nextValue))\n  ) {\n    patchDOMProp(el, shared.camelize(key), nextValue, parentComponent, key);\n  } else {\n    if (key === \"true-value\") {\n      el._trueValue = nextValue;\n    } else if (key === \"false-value\") {\n      el._falseValue = nextValue;\n    }\n    patchAttr(el, key, nextValue, isSVG);\n  }\n};\nfunction shouldSetAsProp(el, key, value, isSVG) {\n  if (isSVG) {\n    if (key === \"innerHTML\" || key === \"textContent\") {\n      return true;\n    }\n    if (key in el && isNativeOn(key) && shared.isFunction(value)) {\n      return true;\n    }\n    return false;\n  }\n  if (key === \"spellcheck\" || key === \"draggable\" || key === \"translate\" || key === \"autocorrect\") {\n    return false;\n  }\n  if (key === \"form\") {\n    return false;\n  }\n  if (key === \"list\" && el.tagName === \"INPUT\") {\n    return false;\n  }\n  if (key === \"type\" && el.tagName === \"TEXTAREA\") {\n    return false;\n  }\n  if (key === \"width\" || key === \"height\") {\n    const tag = el.tagName;\n    if (tag === \"IMG\" || tag === \"VIDEO\" || tag === \"CANVAS\" || tag === \"SOURCE\") {\n      return false;\n    }\n  }\n  if (isNativeOn(key) && shared.isString(value)) {\n    return false;\n  }\n  return key in el;\n}\n\nconst REMOVAL = {};\n/*! #__NO_SIDE_EFFECTS__ */\n// @__NO_SIDE_EFFECTS__\nfunction defineCustomElement(options, extraOptions, _createApp) {\n  const Comp = runtimeCore.defineComponent(options, extraOptions);\n  if (shared.isPlainObject(Comp)) shared.extend(Comp, extraOptions);\n  class VueCustomElement extends VueElement {\n    constructor(initialProps) {\n      super(Comp, initialProps, _createApp);\n    }\n  }\n  VueCustomElement.def = Comp;\n  return VueCustomElement;\n}\n/*! #__NO_SIDE_EFFECTS__ */\nconst defineSSRCustomElement = /* @__NO_SIDE_EFFECTS__ */ (options, extraOptions) => {\n  return /* @__PURE__ */ defineCustomElement(options, extraOptions, createSSRApp);\n};\nconst BaseClass = typeof HTMLElement !== \"undefined\" ? HTMLElement : class {\n};\nclass VueElement extends BaseClass {\n  constructor(_def, _props = {}, _createApp = createApp) {\n    super();\n    this._def = _def;\n    this._props = _props;\n    this._createApp = _createApp;\n    this._isVueCE = true;\n    /**\n     * @internal\n     */\n    this._instance = null;\n    /**\n     * @internal\n     */\n    this._app = null;\n    /**\n     * @internal\n     */\n    this._nonce = this._def.nonce;\n    this._connected = false;\n    this._resolved = false;\n    this._numberProps = null;\n    this._styleChildren = /* @__PURE__ */ new WeakSet();\n    this._ob = null;\n    if (this.shadowRoot && _createApp !== createApp) {\n      this._root = this.shadowRoot;\n    } else {\n      if (_def.shadowRoot !== false) {\n        this.attachShadow({ mode: \"open\" });\n        this._root = this.shadowRoot;\n      } else {\n        this._root = this;\n      }\n    }\n  }\n  connectedCallback() {\n    if (!this.isConnected) return;\n    if (!this.shadowRoot && !this._resolved) {\n      this._parseSlots();\n    }\n    this._connected = true;\n    let parent = this;\n    while (parent = parent && (parent.parentNode || parent.host)) {\n      if (parent instanceof VueElement) {\n        this._parent = parent;\n        break;\n      }\n    }\n    if (!this._instance) {\n      if (this._resolved) {\n        this._mount(this._def);\n      } else {\n        if (parent && parent._pendingResolve) {\n          this._pendingResolve = parent._pendingResolve.then(() => {\n            this._pendingResolve = void 0;\n            this._resolveDef();\n          });\n        } else {\n          this._resolveDef();\n        }\n      }\n    }\n  }\n  _setParent(parent = this._parent) {\n    if (parent) {\n      this._instance.parent = parent._instance;\n      this._inheritParentContext(parent);\n    }\n  }\n  _inheritParentContext(parent = this._parent) {\n    if (parent && this._app) {\n      Object.setPrototypeOf(\n        this._app._context.provides,\n        parent._instance.provides\n      );\n    }\n  }\n  disconnectedCallback() {\n    this._connected = false;\n    runtimeCore.nextTick(() => {\n      if (!this._connected) {\n        if (this._ob) {\n          this._ob.disconnect();\n          this._ob = null;\n        }\n        this._app && this._app.unmount();\n        if (this._instance) this._instance.ce = void 0;\n        this._app = this._instance = null;\n      }\n    });\n  }\n  /**\n   * resolve inner component definition (handle possible async component)\n   */\n  _resolveDef() {\n    if (this._pendingResolve) {\n      return;\n    }\n    for (let i = 0; i < this.attributes.length; i++) {\n      this._setAttr(this.attributes[i].name);\n    }\n    this._ob = new MutationObserver((mutations) => {\n      for (const m of mutations) {\n        this._setAttr(m.attributeName);\n      }\n    });\n    this._ob.observe(this, { attributes: true });\n    const resolve = (def, isAsync = false) => {\n      this._resolved = true;\n      this._pendingResolve = void 0;\n      const { props, styles } = def;\n      let numberProps;\n      if (props && !shared.isArray(props)) {\n        for (const key in props) {\n          const opt = props[key];\n          if (opt === Number || opt && opt.type === Number) {\n            if (key in this._props) {\n              this._props[key] = shared.toNumber(this._props[key]);\n            }\n            (numberProps || (numberProps = /* @__PURE__ */ Object.create(null)))[shared.camelize(key)] = true;\n          }\n        }\n      }\n      this._numberProps = numberProps;\n      this._resolveProps(def);\n      if (this.shadowRoot) {\n        this._applyStyles(styles);\n      }\n      this._mount(def);\n    };\n    const asyncDef = this._def.__asyncLoader;\n    if (asyncDef) {\n      this._pendingResolve = asyncDef().then((def) => {\n        def.configureApp = this._def.configureApp;\n        resolve(this._def = def, true);\n      });\n    } else {\n      resolve(this._def);\n    }\n  }\n  _mount(def) {\n    this._app = this._createApp(def);\n    this._inheritParentContext();\n    if (def.configureApp) {\n      def.configureApp(this._app);\n    }\n    this._app._ceVNode = this._createVNode();\n    this._app.mount(this._root);\n    const exposed = this._instance && this._instance.exposed;\n    if (!exposed) return;\n    for (const key in exposed) {\n      if (!shared.hasOwn(this, key)) {\n        Object.defineProperty(this, key, {\n          // unwrap ref to be consistent with public instance behavior\n          get: () => runtimeCore.unref(exposed[key])\n        });\n      }\n    }\n  }\n  _resolveProps(def) {\n    const { props } = def;\n    const declaredPropKeys = shared.isArray(props) ? props : Object.keys(props || {});\n    for (const key of Object.keys(this)) {\n      if (key[0] !== \"_\" && declaredPropKeys.includes(key)) {\n        this._setProp(key, this[key]);\n      }\n    }\n    for (const key of declaredPropKeys.map(shared.camelize)) {\n      Object.defineProperty(this, key, {\n        get() {\n          return this._getProp(key);\n        },\n        set(val) {\n          this._setProp(key, val, true, true);\n        }\n      });\n    }\n  }\n  _setAttr(key) {\n    if (key.startsWith(\"data-v-\")) return;\n    const has = this.hasAttribute(key);\n    let value = has ? this.getAttribute(key) : REMOVAL;\n    const camelKey = shared.camelize(key);\n    if (has && this._numberProps && this._numberProps[camelKey]) {\n      value = shared.toNumber(value);\n    }\n    this._setProp(camelKey, value, false, true);\n  }\n  /**\n   * @internal\n   */\n  _getProp(key) {\n    return this._props[key];\n  }\n  /**\n   * @internal\n   */\n  _setProp(key, val, shouldReflect = true, shouldUpdate = false) {\n    if (val !== this._props[key]) {\n      if (val === REMOVAL) {\n        delete this._props[key];\n      } else {\n        this._props[key] = val;\n        if (key === \"key\" && this._app) {\n          this._app._ceVNode.key = val;\n        }\n      }\n      if (shouldUpdate && this._instance) {\n        this._update();\n      }\n      if (shouldReflect) {\n        const ob = this._ob;\n        ob && ob.disconnect();\n        if (val === true) {\n          this.setAttribute(shared.hyphenate(key), \"\");\n        } else if (typeof val === \"string\" || typeof val === \"number\") {\n          this.setAttribute(shared.hyphenate(key), val + \"\");\n        } else if (!val) {\n          this.removeAttribute(shared.hyphenate(key));\n        }\n        ob && ob.observe(this, { attributes: true });\n      }\n    }\n  }\n  _update() {\n    const vnode = this._createVNode();\n    if (this._app) vnode.appContext = this._app._context;\n    render(vnode, this._root);\n  }\n  _createVNode() {\n    const baseProps = {};\n    if (!this.shadowRoot) {\n      baseProps.onVnodeMounted = baseProps.onVnodeUpdated = this._renderSlots.bind(this);\n    }\n    const vnode = runtimeCore.createVNode(this._def, shared.extend(baseProps, this._props));\n    if (!this._instance) {\n      vnode.ce = (instance) => {\n        this._instance = instance;\n        instance.ce = this;\n        instance.isCE = true;\n        const dispatch = (event, args) => {\n          this.dispatchEvent(\n            new CustomEvent(\n              event,\n              shared.isPlainObject(args[0]) ? shared.extend({ detail: args }, args[0]) : { detail: args }\n            )\n          );\n        };\n        instance.emit = (event, ...args) => {\n          dispatch(event, args);\n          if (shared.hyphenate(event) !== event) {\n            dispatch(shared.hyphenate(event), args);\n          }\n        };\n        this._setParent();\n      };\n    }\n    return vnode;\n  }\n  _applyStyles(styles, owner) {\n    if (!styles) return;\n    if (owner) {\n      if (owner === this._def || this._styleChildren.has(owner)) {\n        return;\n      }\n      this._styleChildren.add(owner);\n    }\n    const nonce = this._nonce;\n    for (let i = styles.length - 1; i >= 0; i--) {\n      const s = document.createElement(\"style\");\n      if (nonce) s.setAttribute(\"nonce\", nonce);\n      s.textContent = styles[i];\n      this.shadowRoot.prepend(s);\n    }\n  }\n  /**\n   * Only called when shadowRoot is false\n   */\n  _parseSlots() {\n    const slots = this._slots = {};\n    let n;\n    while (n = this.firstChild) {\n      const slotName = n.nodeType === 1 && n.getAttribute(\"slot\") || \"default\";\n      (slots[slotName] || (slots[slotName] = [])).push(n);\n      this.removeChild(n);\n    }\n  }\n  /**\n   * Only called when shadowRoot is false\n   */\n  _renderSlots() {\n    const outlets = (this._teleportTarget || this).querySelectorAll(\"slot\");\n    const scopeId = this._instance.type.__scopeId;\n    for (let i = 0; i < outlets.length; i++) {\n      const o = outlets[i];\n      const slotName = o.getAttribute(\"name\") || \"default\";\n      const content = this._slots[slotName];\n      const parent = o.parentNode;\n      if (content) {\n        for (const n of content) {\n          if (scopeId && n.nodeType === 1) {\n            const id = scopeId + \"-s\";\n            const walker = document.createTreeWalker(n, 1);\n            n.setAttribute(id, \"\");\n            let child;\n            while (child = walker.nextNode()) {\n              child.setAttribute(id, \"\");\n            }\n          }\n          parent.insertBefore(n, o);\n        }\n      } else {\n        while (o.firstChild) parent.insertBefore(o.firstChild, o);\n      }\n      parent.removeChild(o);\n    }\n  }\n  /**\n   * @internal\n   */\n  _injectChildStyle(comp) {\n    this._applyStyles(comp.styles, comp);\n  }\n  /**\n   * @internal\n   */\n  _removeChildStyle(comp) {\n  }\n}\nfunction useHost(caller) {\n  const instance = runtimeCore.getCurrentInstance();\n  const el = instance && instance.ce;\n  if (el) {\n    return el;\n  }\n  return null;\n}\nfunction useShadowRoot() {\n  const el = useHost();\n  return el && el.shadowRoot;\n}\n\nfunction useCssModule(name = \"$style\") {\n  {\n    const instance = runtimeCore.getCurrentInstance();\n    if (!instance) {\n      return shared.EMPTY_OBJ;\n    }\n    const modules = instance.type.__cssModules;\n    if (!modules) {\n      return shared.EMPTY_OBJ;\n    }\n    const mod = modules[name];\n    if (!mod) {\n      return shared.EMPTY_OBJ;\n    }\n    return mod;\n  }\n}\n\nconst positionMap = /* @__PURE__ */ new WeakMap();\nconst newPositionMap = /* @__PURE__ */ new WeakMap();\nconst moveCbKey = Symbol(\"_moveCb\");\nconst enterCbKey = Symbol(\"_enterCb\");\nconst decorate = (t) => {\n  delete t.props.mode;\n  return t;\n};\nconst TransitionGroupImpl = /* @__PURE__ */ decorate({\n  name: \"TransitionGroup\",\n  props: /* @__PURE__ */ shared.extend({}, TransitionPropsValidators, {\n    tag: String,\n    moveClass: String\n  }),\n  setup(props, { slots }) {\n    const instance = runtimeCore.getCurrentInstance();\n    const state = runtimeCore.useTransitionState();\n    let prevChildren;\n    let children;\n    runtimeCore.onUpdated(() => {\n      if (!prevChildren.length) {\n        return;\n      }\n      const moveClass = props.moveClass || `${props.name || \"v\"}-move`;\n      if (!hasCSSTransform(\n        prevChildren[0].el,\n        instance.vnode.el,\n        moveClass\n      )) {\n        prevChildren = [];\n        return;\n      }\n      prevChildren.forEach(callPendingCbs);\n      prevChildren.forEach(recordPosition);\n      const movedChildren = prevChildren.filter(applyTranslation);\n      forceReflow();\n      movedChildren.forEach((c) => {\n        const el = c.el;\n        const style = el.style;\n        addTransitionClass(el, moveClass);\n        style.transform = style.webkitTransform = style.transitionDuration = \"\";\n        const cb = el[moveCbKey] = (e) => {\n          if (e && e.target !== el) {\n            return;\n          }\n          if (!e || /transform$/.test(e.propertyName)) {\n            el.removeEventListener(\"transitionend\", cb);\n            el[moveCbKey] = null;\n            removeTransitionClass(el, moveClass);\n          }\n        };\n        el.addEventListener(\"transitionend\", cb);\n      });\n      prevChildren = [];\n    });\n    return () => {\n      const rawProps = runtimeCore.toRaw(props);\n      const cssTransitionProps = resolveTransitionProps(rawProps);\n      let tag = rawProps.tag || runtimeCore.Fragment;\n      prevChildren = [];\n      if (children) {\n        for (let i = 0; i < children.length; i++) {\n          const child = children[i];\n          if (child.el && child.el instanceof Element) {\n            prevChildren.push(child);\n            runtimeCore.setTransitionHooks(\n              child,\n              runtimeCore.resolveTransitionHooks(\n                child,\n                cssTransitionProps,\n                state,\n                instance\n              )\n            );\n            positionMap.set(\n              child,\n              child.el.getBoundingClientRect()\n            );\n          }\n        }\n      }\n      children = slots.default ? runtimeCore.getTransitionRawChildren(slots.default()) : [];\n      for (let i = 0; i < children.length; i++) {\n        const child = children[i];\n        if (child.key != null) {\n          runtimeCore.setTransitionHooks(\n            child,\n            runtimeCore.resolveTransitionHooks(child, cssTransitionProps, state, instance)\n          );\n        }\n      }\n      return runtimeCore.createVNode(tag, null, children);\n    };\n  }\n});\nconst TransitionGroup = TransitionGroupImpl;\nfunction callPendingCbs(c) {\n  const el = c.el;\n  if (el[moveCbKey]) {\n    el[moveCbKey]();\n  }\n  if (el[enterCbKey]) {\n    el[enterCbKey]();\n  }\n}\nfunction recordPosition(c) {\n  newPositionMap.set(c, c.el.getBoundingClientRect());\n}\nfunction applyTranslation(c) {\n  const oldPos = positionMap.get(c);\n  const newPos = newPositionMap.get(c);\n  const dx = oldPos.left - newPos.left;\n  const dy = oldPos.top - newPos.top;\n  if (dx || dy) {\n    const s = c.el.style;\n    s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;\n    s.transitionDuration = \"0s\";\n    return c;\n  }\n}\nfunction hasCSSTransform(el, root, moveClass) {\n  const clone = el.cloneNode();\n  const _vtc = el[vtcKey];\n  if (_vtc) {\n    _vtc.forEach((cls) => {\n      cls.split(/\\s+/).forEach((c) => c && clone.classList.remove(c));\n    });\n  }\n  moveClass.split(/\\s+/).forEach((c) => c && clone.classList.add(c));\n  clone.style.display = \"none\";\n  const container = root.nodeType === 1 ? root : root.parentNode;\n  container.appendChild(clone);\n  const { hasTransform } = getTransitionInfo(clone);\n  container.removeChild(clone);\n  return hasTransform;\n}\n\nconst getModelAssigner = (vnode) => {\n  const fn = vnode.props[\"onUpdate:modelValue\"] || false;\n  return shared.isArray(fn) ? (value) => shared.invokeArrayFns(fn, value) : fn;\n};\nfunction onCompositionStart(e) {\n  e.target.composing = true;\n}\nfunction onCompositionEnd(e) {\n  const target = e.target;\n  if (target.composing) {\n    target.composing = false;\n    target.dispatchEvent(new Event(\"input\"));\n  }\n}\nconst assignKey = Symbol(\"_assign\");\nconst vModelText = {\n  created(el, { modifiers: { lazy, trim, number } }, vnode) {\n    el[assignKey] = getModelAssigner(vnode);\n    const castToNumber = number || vnode.props && vnode.props.type === \"number\";\n    addEventListener(el, lazy ? \"change\" : \"input\", (e) => {\n      if (e.target.composing) return;\n      let domValue = el.value;\n      if (trim) {\n        domValue = domValue.trim();\n      }\n      if (castToNumber) {\n        domValue = shared.looseToNumber(domValue);\n      }\n      el[assignKey](domValue);\n    });\n    if (trim) {\n      addEventListener(el, \"change\", () => {\n        el.value = el.value.trim();\n      });\n    }\n    if (!lazy) {\n      addEventListener(el, \"compositionstart\", onCompositionStart);\n      addEventListener(el, \"compositionend\", onCompositionEnd);\n      addEventListener(el, \"change\", onCompositionEnd);\n    }\n  },\n  // set value on mounted so it's after min/max for type=\"range\"\n  mounted(el, { value }) {\n    el.value = value == null ? \"\" : value;\n  },\n  beforeUpdate(el, { value, oldValue, modifiers: { lazy, trim, number } }, vnode) {\n    el[assignKey] = getModelAssigner(vnode);\n    if (el.composing) return;\n    const elValue = (number || el.type === \"number\") && !/^0\\d/.test(el.value) ? shared.looseToNumber(el.value) : el.value;\n    const newValue = value == null ? \"\" : value;\n    if (elValue === newValue) {\n      return;\n    }\n    if (document.activeElement === el && el.type !== \"range\") {\n      if (lazy && value === oldValue) {\n        return;\n      }\n      if (trim && el.value.trim() === newValue) {\n        return;\n      }\n    }\n    el.value = newValue;\n  }\n};\nconst vModelCheckbox = {\n  // #4096 array checkboxes need to be deep traversed\n  deep: true,\n  created(el, _, vnode) {\n    el[assignKey] = getModelAssigner(vnode);\n    addEventListener(el, \"change\", () => {\n      const modelValue = el._modelValue;\n      const elementValue = getValue(el);\n      const checked = el.checked;\n      const assign = el[assignKey];\n      if (shared.isArray(modelValue)) {\n        const index = shared.looseIndexOf(modelValue, elementValue);\n        const found = index !== -1;\n        if (checked && !found) {\n          assign(modelValue.concat(elementValue));\n        } else if (!checked && found) {\n          const filtered = [...modelValue];\n          filtered.splice(index, 1);\n          assign(filtered);\n        }\n      } else if (shared.isSet(modelValue)) {\n        const cloned = new Set(modelValue);\n        if (checked) {\n          cloned.add(elementValue);\n        } else {\n          cloned.delete(elementValue);\n        }\n        assign(cloned);\n      } else {\n        assign(getCheckboxValue(el, checked));\n      }\n    });\n  },\n  // set initial checked on mount to wait for true-value/false-value\n  mounted: setChecked,\n  beforeUpdate(el, binding, vnode) {\n    el[assignKey] = getModelAssigner(vnode);\n    setChecked(el, binding, vnode);\n  }\n};\nfunction setChecked(el, { value, oldValue }, vnode) {\n  el._modelValue = value;\n  let checked;\n  if (shared.isArray(value)) {\n    checked = shared.looseIndexOf(value, vnode.props.value) > -1;\n  } else if (shared.isSet(value)) {\n    checked = value.has(vnode.props.value);\n  } else {\n    if (value === oldValue) return;\n    checked = shared.looseEqual(value, getCheckboxValue(el, true));\n  }\n  if (el.checked !== checked) {\n    el.checked = checked;\n  }\n}\nconst vModelRadio = {\n  created(el, { value }, vnode) {\n    el.checked = shared.looseEqual(value, vnode.props.value);\n    el[assignKey] = getModelAssigner(vnode);\n    addEventListener(el, \"change\", () => {\n      el[assignKey](getValue(el));\n    });\n  },\n  beforeUpdate(el, { value, oldValue }, vnode) {\n    el[assignKey] = getModelAssigner(vnode);\n    if (value !== oldValue) {\n      el.checked = shared.looseEqual(value, vnode.props.value);\n    }\n  }\n};\nconst vModelSelect = {\n  // <select multiple> value need to be deep traversed\n  deep: true,\n  created(el, { value, modifiers: { number } }, vnode) {\n    const isSetModel = shared.isSet(value);\n    addEventListener(el, \"change\", () => {\n      const selectedVal = Array.prototype.filter.call(el.options, (o) => o.selected).map(\n        (o) => number ? shared.looseToNumber(getValue(o)) : getValue(o)\n      );\n      el[assignKey](\n        el.multiple ? isSetModel ? new Set(selectedVal) : selectedVal : selectedVal[0]\n      );\n      el._assigning = true;\n      runtimeCore.nextTick(() => {\n        el._assigning = false;\n      });\n    });\n    el[assignKey] = getModelAssigner(vnode);\n  },\n  // set value in mounted & updated because <select> relies on its children\n  // <option>s.\n  mounted(el, { value }) {\n    setSelected(el, value);\n  },\n  beforeUpdate(el, _binding, vnode) {\n    el[assignKey] = getModelAssigner(vnode);\n  },\n  updated(el, { value }) {\n    if (!el._assigning) {\n      setSelected(el, value);\n    }\n  }\n};\nfunction setSelected(el, value) {\n  const isMultiple = el.multiple;\n  const isArrayValue = shared.isArray(value);\n  if (isMultiple && !isArrayValue && !shared.isSet(value)) {\n    return;\n  }\n  for (let i = 0, l = el.options.length; i < l; i++) {\n    const option = el.options[i];\n    const optionValue = getValue(option);\n    if (isMultiple) {\n      if (isArrayValue) {\n        const optionType = typeof optionValue;\n        if (optionType === \"string\" || optionType === \"number\") {\n          option.selected = value.some((v) => String(v) === String(optionValue));\n        } else {\n          option.selected = shared.looseIndexOf(value, optionValue) > -1;\n        }\n      } else {\n        option.selected = value.has(optionValue);\n      }\n    } else if (shared.looseEqual(getValue(option), value)) {\n      if (el.selectedIndex !== i) el.selectedIndex = i;\n      return;\n    }\n  }\n  if (!isMultiple && el.selectedIndex !== -1) {\n    el.selectedIndex = -1;\n  }\n}\nfunction getValue(el) {\n  return \"_value\" in el ? el._value : el.value;\n}\nfunction getCheckboxValue(el, checked) {\n  const key = checked ? \"_trueValue\" : \"_falseValue\";\n  return key in el ? el[key] : checked;\n}\nconst vModelDynamic = {\n  created(el, binding, vnode) {\n    callModelHook(el, binding, vnode, null, \"created\");\n  },\n  mounted(el, binding, vnode) {\n    callModelHook(el, binding, vnode, null, \"mounted\");\n  },\n  beforeUpdate(el, binding, vnode, prevVNode) {\n    callModelHook(el, binding, vnode, prevVNode, \"beforeUpdate\");\n  },\n  updated(el, binding, vnode, prevVNode) {\n    callModelHook(el, binding, vnode, prevVNode, \"updated\");\n  }\n};\nfunction resolveDynamicModel(tagName, type) {\n  switch (tagName) {\n    case \"SELECT\":\n      return vModelSelect;\n    case \"TEXTAREA\":\n      return vModelText;\n    default:\n      switch (type) {\n        case \"checkbox\":\n          return vModelCheckbox;\n        case \"radio\":\n          return vModelRadio;\n        default:\n          return vModelText;\n      }\n  }\n}\nfunction callModelHook(el, binding, vnode, prevVNode, hook) {\n  const modelToUse = resolveDynamicModel(\n    el.tagName,\n    vnode.props && vnode.props.type\n  );\n  const fn = modelToUse[hook];\n  fn && fn(el, binding, vnode, prevVNode);\n}\nfunction initVModelForSSR() {\n  vModelText.getSSRProps = ({ value }) => ({ value });\n  vModelRadio.getSSRProps = ({ value }, vnode) => {\n    if (vnode.props && shared.looseEqual(vnode.props.value, value)) {\n      return { checked: true };\n    }\n  };\n  vModelCheckbox.getSSRProps = ({ value }, vnode) => {\n    if (shared.isArray(value)) {\n      if (vnode.props && shared.looseIndexOf(value, vnode.props.value) > -1) {\n        return { checked: true };\n      }\n    } else if (shared.isSet(value)) {\n      if (vnode.props && value.has(vnode.props.value)) {\n        return { checked: true };\n      }\n    } else if (value) {\n      return { checked: true };\n    }\n  };\n  vModelDynamic.getSSRProps = (binding, vnode) => {\n    if (typeof vnode.type !== \"string\") {\n      return;\n    }\n    const modelToUse = resolveDynamicModel(\n      // resolveDynamicModel expects an uppercase tag name, but vnode.type is lowercase\n      vnode.type.toUpperCase(),\n      vnode.props && vnode.props.type\n    );\n    if (modelToUse.getSSRProps) {\n      return modelToUse.getSSRProps(binding, vnode);\n    }\n  };\n}\n\nconst systemModifiers = [\"ctrl\", \"shift\", \"alt\", \"meta\"];\nconst modifierGuards = {\n  stop: (e) => e.stopPropagation(),\n  prevent: (e) => e.preventDefault(),\n  self: (e) => e.target !== e.currentTarget,\n  ctrl: (e) => !e.ctrlKey,\n  shift: (e) => !e.shiftKey,\n  alt: (e) => !e.altKey,\n  meta: (e) => !e.metaKey,\n  left: (e) => \"button\" in e && e.button !== 0,\n  middle: (e) => \"button\" in e && e.button !== 1,\n  right: (e) => \"button\" in e && e.button !== 2,\n  exact: (e, modifiers) => systemModifiers.some((m) => e[`${m}Key`] && !modifiers.includes(m))\n};\nconst withModifiers = (fn, modifiers) => {\n  const cache = fn._withMods || (fn._withMods = {});\n  const cacheKey = modifiers.join(\".\");\n  return cache[cacheKey] || (cache[cacheKey] = (event, ...args) => {\n    for (let i = 0; i < modifiers.length; i++) {\n      const guard = modifierGuards[modifiers[i]];\n      if (guard && guard(event, modifiers)) return;\n    }\n    return fn(event, ...args);\n  });\n};\nconst keyNames = {\n  esc: \"escape\",\n  space: \" \",\n  up: \"arrow-up\",\n  left: \"arrow-left\",\n  right: \"arrow-right\",\n  down: \"arrow-down\",\n  delete: \"backspace\"\n};\nconst withKeys = (fn, modifiers) => {\n  const cache = fn._withKeys || (fn._withKeys = {});\n  const cacheKey = modifiers.join(\".\");\n  return cache[cacheKey] || (cache[cacheKey] = (event) => {\n    if (!(\"key\" in event)) {\n      return;\n    }\n    const eventKey = shared.hyphenate(event.key);\n    if (modifiers.some(\n      (k) => k === eventKey || keyNames[k] === eventKey\n    )) {\n      return fn(event);\n    }\n  });\n};\n\nconst rendererOptions = /* @__PURE__ */ shared.extend({ patchProp }, nodeOps);\nlet renderer;\nlet enabledHydration = false;\nfunction ensureRenderer() {\n  return renderer || (renderer = runtimeCore.createRenderer(rendererOptions));\n}\nfunction ensureHydrationRenderer() {\n  renderer = enabledHydration ? renderer : runtimeCore.createHydrationRenderer(rendererOptions);\n  enabledHydration = true;\n  return renderer;\n}\nconst render = (...args) => {\n  ensureRenderer().render(...args);\n};\nconst hydrate = (...args) => {\n  ensureHydrationRenderer().hydrate(...args);\n};\nconst createApp = (...args) => {\n  const app = ensureRenderer().createApp(...args);\n  const { mount } = app;\n  app.mount = (containerOrSelector) => {\n    const container = normalizeContainer(containerOrSelector);\n    if (!container) return;\n    const component = app._component;\n    if (!shared.isFunction(component) && !component.render && !component.template) {\n      component.template = container.innerHTML;\n    }\n    if (container.nodeType === 1) {\n      container.textContent = \"\";\n    }\n    const proxy = mount(container, false, resolveRootNamespace(container));\n    if (container instanceof Element) {\n      container.removeAttribute(\"v-cloak\");\n      container.setAttribute(\"data-v-app\", \"\");\n    }\n    return proxy;\n  };\n  return app;\n};\nconst createSSRApp = (...args) => {\n  const app = ensureHydrationRenderer().createApp(...args);\n  const { mount } = app;\n  app.mount = (containerOrSelector) => {\n    const container = normalizeContainer(containerOrSelector);\n    if (container) {\n      return mount(container, true, resolveRootNamespace(container));\n    }\n  };\n  return app;\n};\nfunction resolveRootNamespace(container) {\n  if (container instanceof SVGElement) {\n    return \"svg\";\n  }\n  if (typeof MathMLElement === \"function\" && container instanceof MathMLElement) {\n    return \"mathml\";\n  }\n}\nfunction normalizeContainer(container) {\n  if (shared.isString(container)) {\n    const res = document.querySelector(container);\n    return res;\n  }\n  return container;\n}\nlet ssrDirectiveInitialized = false;\nconst initDirectivesForSSR = () => {\n  if (!ssrDirectiveInitialized) {\n    ssrDirectiveInitialized = true;\n    initVModelForSSR();\n    initVShowForSSR();\n  }\n} ;\n\nexports.Transition = Transition;\nexports.TransitionGroup = TransitionGroup;\nexports.VueElement = VueElement;\nexports.createApp = createApp;\nexports.createSSRApp = createSSRApp;\nexports.defineCustomElement = defineCustomElement;\nexports.defineSSRCustomElement = defineSSRCustomElement;\nexports.hydrate = hydrate;\nexports.initDirectivesForSSR = initDirectivesForSSR;\nexports.render = render;\nexports.useCssModule = useCssModule;\nexports.useCssVars = useCssVars;\nexports.useHost = useHost;\nexports.useShadowRoot = useShadowRoot;\nexports.vModelCheckbox = vModelCheckbox;\nexports.vModelDynamic = vModelDynamic;\nexports.vModelRadio = vModelRadio;\nexports.vModelSelect = vModelSelect;\nexports.vModelText = vModelText;\nexports.vShow = vShow;\nexports.withKeys = withKeys;\nexports.withModifiers = withModifiers;\nObject.keys(runtimeCore).forEach(function (k) {\n  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = runtimeCore[k];\n});\n","'use strict'\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./dist/runtime-dom.cjs.prod.js')\n} else {\n  module.exports = require('./dist/runtime-dom.cjs.js')\n}\n","/**\n* vue v3.5.18\n* (c) 2018-present Yuxi (Evan) You and Vue contributors\n* @license MIT\n**/\n'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar compilerDom = require('@vue/compiler-dom');\nvar runtimeDom = require('@vue/runtime-dom');\nvar shared = require('@vue/shared');\n\nfunction _interopNamespaceDefault(e) {\n  var n = Object.create(null);\n  if (e) {\n    for (var k in e) {\n      n[k] = e[k];\n    }\n  }\n  n.default = e;\n  return Object.freeze(n);\n}\n\nvar runtimeDom__namespace = /*#__PURE__*/_interopNamespaceDefault(runtimeDom);\n\nconst compileCache = /* @__PURE__ */ Object.create(null);\nfunction compileToFunction(template, options) {\n  if (!shared.isString(template)) {\n    if (template.nodeType) {\n      template = template.innerHTML;\n    } else {\n      return shared.NOOP;\n    }\n  }\n  const key = shared.genCacheKey(template, options);\n  const cached = compileCache[key];\n  if (cached) {\n    return cached;\n  }\n  if (template[0] === \"#\") {\n    const el = document.querySelector(template);\n    template = el ? el.innerHTML : ``;\n  }\n  const opts = shared.extend(\n    {\n      hoistStatic: true,\n      onError: void 0,\n      onWarn: shared.NOOP\n    },\n    options\n  );\n  if (!opts.isCustomElement && typeof customElements !== \"undefined\") {\n    opts.isCustomElement = (tag) => !!customElements.get(tag);\n  }\n  const { code } = compilerDom.compile(template, opts);\n  const render = new Function(\"Vue\", code)(runtimeDom__namespace);\n  render._rc = true;\n  return compileCache[key] = render;\n}\nruntimeDom.registerRuntimeCompiler(compileToFunction);\n\nexports.compile = compileToFunction;\nObject.keys(runtimeDom).forEach(function (k) {\n  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = runtimeDom[k];\n});\n","'use strict'\n\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./dist/vue.cjs.prod.js')\n} else {\n  module.exports = require('./dist/vue.cjs.js')\n}\n","'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\nvar defineProperty = Object.defineProperty;\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) { /**/ }\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\n// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target\nvar setProperty = function setProperty(target, options) {\n\tif (defineProperty && options.name === '__proto__') {\n\t\tdefineProperty(target, options.name, {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\tvalue: options.newValue,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\ttarget[options.name] = options.newValue;\n\t}\n};\n\n// Return undefined instead of __proto__ if '__proto__' is not an own property\nvar getProperty = function getProperty(obj, name) {\n\tif (name === '__proto__') {\n\t\tif (!hasOwn.call(obj, name)) {\n\t\t\treturn void 0;\n\t\t} else if (gOPD) {\n\t\t\t// In early versions of node, obj['__proto__'] is buggy when obj has\n\t\t\t// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.\n\t\t\treturn gOPD(obj, name).value;\n\t\t}\n\t}\n\n\treturn obj[name];\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone;\n\tvar target = arguments[0];\n\tvar i = 1;\n\tvar length = arguments.length;\n\tvar deep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\tif (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = getProperty(target, name);\n\t\t\t\tcopy = getProperty(options, name);\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: extend(deep, clone, copy) });\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: copy });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n","//#region rolldown:runtime\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __copyProps = (to, from, except, desc) => {\n\tif (from && typeof from === \"object\" || typeof from === \"function\") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {\n\t\tkey = keys[i];\n\t\tif (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {\n\t\t\tget: ((k) => from[k]).bind(null, key),\n\t\t\tenumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable\n\t\t});\n\t}\n\treturn to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", {\n\tvalue: mod,\n\tenumerable: true\n}) : target, mod));\n\n//#endregion\n\nObject.defineProperty(exports, '__toESM', {\n  enumerable: true,\n  get: function () {\n    return __toESM;\n  }\n});","function serialize(o){return typeof o==\"string\"?`'${o}'`:new c().serialize(o)}const c=/*@__PURE__*/function(){class o{#t=new Map;compare(t,r){const e=typeof t,n=typeof r;return e===\"string\"&&n===\"string\"?t.localeCompare(r):e===\"number\"&&n===\"number\"?t-r:String.prototype.localeCompare.call(this.serialize(t,true),this.serialize(r,true))}serialize(t,r){if(t===null)return \"null\";switch(typeof t){case \"string\":return r?t:`'${t}'`;case \"bigint\":return `${t}n`;case \"object\":return this.$object(t);case \"function\":return this.$function(t)}return String(t)}serializeObject(t){const r=Object.prototype.toString.call(t);if(r!==\"[object Object]\")return this.serializeBuiltInType(r.length<10?`unknown:${r}`:r.slice(8,-1),t);const e=t.constructor,n=e===Object||e===void 0?\"\":e.name;if(n!==\"\"&&globalThis[n]===e)return this.serializeBuiltInType(n,t);if(typeof t.toJSON==\"function\"){const i=t.toJSON();return n+(i!==null&&typeof i==\"object\"?this.$object(i):`(${this.serialize(i)})`)}return this.serializeObjectEntries(n,Object.entries(t))}serializeBuiltInType(t,r){const e=this[\"$\"+t];if(e)return e.call(this,r);if(typeof r?.entries==\"function\")return this.serializeObjectEntries(t,r.entries());throw new Error(`Cannot serialize ${t}`)}serializeObjectEntries(t,r){const e=Array.from(r).sort((i,a)=>this.compare(i[0],a[0]));let n=`${t}{`;for(let i=0;i<e.length;i++){const[a,l]=e[i];n+=`${this.serialize(a,true)}:${this.serialize(l)}`,i<e.length-1&&(n+=\",\");}return n+\"}\"}$object(t){let r=this.#t.get(t);return r===void 0&&(this.#t.set(t,`#${this.#t.size}`),r=this.serializeObject(t),this.#t.set(t,r)),r}$function(t){const r=Function.prototype.toString.call(t);return r.slice(-15)===\"[native code] }\"?`${t.name||\"\"}()[native]`:`${t.name}(${t.length})${r.replace(/\\s*\\n\\s*/g,\"\")}`}$Array(t){let r=\"[\";for(let e=0;e<t.length;e++)r+=this.serialize(t[e]),e<t.length-1&&(r+=\",\");return r+\"]\"}$Date(t){try{return `Date(${t.toISOString()})`}catch{return \"Date(null)\"}}$ArrayBuffer(t){return `ArrayBuffer[${new Uint8Array(t).join(\",\")}]`}$Set(t){return `Set${this.$Array(Array.from(t).sort((r,e)=>this.compare(r,e)))}`}$Map(t){return this.serializeObjectEntries(\"Map\",t.entries())}}for(const s of [\"Error\",\"RegExp\",\"URL\"])o.prototype[\"$\"+s]=function(t){return `${s}(${t})`};for(const s of [\"Int8Array\",\"Uint8Array\",\"Uint8ClampedArray\",\"Int16Array\",\"Uint16Array\",\"Int32Array\",\"Uint32Array\",\"Float32Array\",\"Float64Array\"])o.prototype[\"$\"+s]=function(t){return `${s}[${t.join(\",\")}]`};for(const s of [\"BigInt64Array\",\"BigUint64Array\"])o.prototype[\"$\"+s]=function(t){return `${s}[${t.join(\"n,\")}${t.length>0?\"n\":\"\"}]`};return o}();\n\nfunction isEqual(object1, object2) {\n  if (object1 === object2) {\n    return true;\n  }\n  if (serialize(object1) === serialize(object2)) {\n    return true;\n  }\n  return false;\n}\n\nexport { isEqual as i, serialize as s };\n","const z=[1779033703,-1150833019,1013904242,-1521486534,1359893119,-1694144372,528734635,1541459225],R=[1116352408,1899447441,-1245643825,-373957723,961987163,1508970993,-1841331548,-1424204075,-670586216,310598401,607225278,1426881987,1925078388,-2132889090,-1680079193,-1046744716,-459576895,-272742522,264347078,604807628,770255983,1249150122,1555081692,1996064986,-1740746414,-1473132947,-1341970488,-1084653625,-958395405,-710438585,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,-2117940946,-1838011259,-1564481375,-1474664885,-1035236496,-949202525,-778901479,-694614492,-200395387,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,-2067236844,-1933114872,-1866530822,-1538233109,-1090935817,-965641998],S=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\",r=[];class k{_data=new l;_hash=new l([...z]);_nDataBytes=0;_minBufferSize=0;finalize(e){e&&this._append(e);const s=this._nDataBytes*8,t=this._data.sigBytes*8;return this._data.words[t>>>5]|=128<<24-t%32,this._data.words[(t+64>>>9<<4)+14]=Math.floor(s/4294967296),this._data.words[(t+64>>>9<<4)+15]=s,this._data.sigBytes=this._data.words.length*4,this._process(),this._hash}_doProcessBlock(e,s){const t=this._hash.words;let i=t[0],o=t[1],a=t[2],c=t[3],h=t[4],g=t[5],f=t[6],y=t[7];for(let n=0;n<64;n++){if(n<16)r[n]=e[s+n]|0;else {const d=r[n-15],j=(d<<25|d>>>7)^(d<<14|d>>>18)^d>>>3,B=r[n-2],x=(B<<15|B>>>17)^(B<<13|B>>>19)^B>>>10;r[n]=j+r[n-7]+x+r[n-16];}const m=h&g^~h&f,p=i&o^i&a^o&a,u=(i<<30|i>>>2)^(i<<19|i>>>13)^(i<<10|i>>>22),b=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=y+b+m+R[n]+r[n],M=u+p;y=f,f=g,g=h,h=c+w|0,c=a,a=o,o=i,i=w+M|0;}t[0]=t[0]+i|0,t[1]=t[1]+o|0,t[2]=t[2]+a|0,t[3]=t[3]+c|0,t[4]=t[4]+h|0,t[5]=t[5]+g|0,t[6]=t[6]+f|0,t[7]=t[7]+y|0;}_append(e){typeof e==\"string\"&&(e=l.fromUtf8(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes;}_process(e){let s,t=this._data.sigBytes/64;e?t=Math.ceil(t):t=Math.max((t|0)-this._minBufferSize,0);const i=t*16,o=Math.min(i*4,this._data.sigBytes);if(i){for(let a=0;a<i;a+=16)this._doProcessBlock(this._data.words,a);s=this._data.words.splice(0,i),this._data.sigBytes-=o;}return new l(s,o)}}class l{words;sigBytes;constructor(e,s){e=this.words=e||[],this.sigBytes=s===void 0?e.length*4:s;}static fromUtf8(e){const s=unescape(encodeURIComponent(e)),t=s.length,i=[];for(let o=0;o<t;o++)i[o>>>2]|=(s.charCodeAt(o)&255)<<24-o%4*8;return new l(i,t)}toBase64(){const e=[];for(let s=0;s<this.sigBytes;s+=3){const t=this.words[s>>>2]>>>24-s%4*8&255,i=this.words[s+1>>>2]>>>24-(s+1)%4*8&255,o=this.words[s+2>>>2]>>>24-(s+2)%4*8&255,a=t<<16|i<<8|o;for(let c=0;c<4&&s*8+c*6<this.sigBytes*8;c++)e.push(S.charAt(a>>>6*(3-c)&63));}return e.join(\"\")}concat(e){if(this.words[this.sigBytes>>>2]&=4294967295<<32-this.sigBytes%4*8,this.words.length=Math.ceil(this.sigBytes/4),this.sigBytes%4)for(let s=0;s<e.sigBytes;s++){const t=e.words[s>>>2]>>>24-s%4*8&255;this.words[this.sigBytes+s>>>2]|=t<<24-(this.sigBytes+s)%4*8;}else for(let s=0;s<e.sigBytes;s+=4)this.words[this.sigBytes+s>>>2]=e.words[s>>>2];this.sigBytes+=e.sigBytes;}}function digest(_){return new k().finalize(_).toBase64()}\n\nexport { digest };\n","import { s as serialize } from './shared/ohash.D__AXeF1.mjs';\nexport { i as isEqual } from './shared/ohash.D__AXeF1.mjs';\nimport { digest } from 'ohash/crypto';\nexport { digest } from 'ohash/crypto';\n\nfunction hash(input) {\n  return digest(serialize(input));\n}\n\nexport { hash, serialize };\n","import { isEqual } from 'ohash'\n\n/**\n * The function `areEqual` compares two arrays and returns true if they are equal in length and have\n * the same elements at corresponding indexes.\n * @param {any[]} arrayA - An array of any type of elements.\n * @param {any[]} arrayB - It looks like you haven't provided the value for `arrayB`. Could you please\n * provide the arrayB value so that I can assist you further?\n * @returns The function `areEqual` is returning a boolean value, either `true` if the two input arrays\n * `arrayA` and `arrayB` are equal, or `false` if they are not equal.\n */\nexport function areEqual(arrayA: any[], arrayB: any[]): boolean {\n  if (arrayA.length !== arrayB.length)\n    return false\n\n  for (let index = 0; index < arrayA.length; index++) {\n    if (arrayA[index] !== arrayB[index])\n      return false\n  }\n\n  return true\n}\n\n/**\n * Splits an array into chunks of a given size.\n * @param arr The array to split.\n * @param size The size of each chunk.\n * @returns An array of arrays, where each sub-array has `size` elements from the original array.\n * @example ```ts\n * const arr = [1, 2, 3, 4, 5, 6, 7, 8];\n * const chunks = chunk(arr, 3);\n * // chunks = [[1, 2, 3], [4, 5, 6], [7, 8]]\n * ```\n */\nexport function chunk<T>(arr: T[], size: number): T[][] {\n  const result = []\n  for (let i = 0; i < arr.length; i += size)\n    result.push(arr.slice(i, i + size))\n\n  return result\n}\n\n/**\n * The function `findValuesBetween` takes an array and two values, then returns a subarray containing\n * elements between the first occurrence of the start value and the first occurrence of the end value\n * in the array.\n * @param {T[]} array - The `array` parameter is an array of values of type `T`.\n * @param {T} start - The `start` parameter is the value that marks the beginning of the range you want\n * to find in the array.\n * @param {T} end - The `end` parameter in the `findValuesBetween` function represents the end value\n * that you want to find in the array. This function will return a subarray of values that are between\n * the `start` and `end` values in the original array.\n * @returns The `findValuesBetween` function returns an array of values from the input array that are\n * between the `start` and `end` values (inclusive). If either the `start` or `end` values are not\n * found in the input array, an empty array is returned.\n */\nexport function findValuesBetween<T>(array: T[], start: T, end: T) {\n  const startIndex = array.findIndex(i => isEqual(i, start))\n  const endIndex = array.findIndex(i => isEqual(i, end))\n  if (startIndex === -1 || endIndex === -1)\n    return []\n\n  const [minIndex, maxIndex] = [startIndex, endIndex].sort((a, b) => a - b)\n\n  return array.slice(minIndex, maxIndex + 1)\n}\n","export const isBrowser = typeof document !== 'undefined'\n","/**\n * The `clamp` function restricts a number within a specified range by returning the value itself if it\n * falls within the range, or the closest boundary value if it exceeds the range.\n * @param {number} value - The `value` parameter represents the number that you want to clamp within\n * the specified range defined by `min` and `max` values.\n * @param {number} min - If the `value` parameter is less than the `min` value, the\n * function will return the `min` value.\n * @param {number} max - If the `value` parameter is greater than the `max` value,\n * the function will return `max`.\n * @returns The `clamp` function returns the value of `value` constrained within the range defined by\n * `min` and `max`.\n */\nexport function clamp(value: number, min: number = Number.NEGATIVE_INFINITY, max: number = Number.POSITIVE_INFINITY): number {\n  return Math.min(max, Math.max(min, value))\n}\n\n/**\n * The function `roundToStepPrecision` rounds a number to a specified precision step.\n * @param {number} value - The `value` parameter is the number that you want to round to a specific\n * precision based on the `step` parameter.\n * @param {number} step - The `step` parameter in the `roundToStepPrecision` function represents the\n * interval at which you want to round the `value`. For example, if `step` is 0.5, the `value` will be\n * rounded to the nearest half.\n * @returns the `roundedValue` after rounding it to the precision specified by the `step`.\n */\nexport function roundToStepPrecision(value: number, step: number) {\n  let roundedValue = value\n  const stepString = step.toString()\n  const pointIndex = stepString.indexOf('.')\n  const precision = pointIndex >= 0 ? stepString.length - pointIndex : 0\n  if (precision > 0) {\n    const pow = 10 ** precision\n    roundedValue = Math.round(roundedValue * pow) / pow\n  }\n  return roundedValue\n}\n\n/**\n * The function `snapValueToStep` snaps a given value to the nearest step within a specified range.\n * @param {number} value - The `value` parameter represents the number that you want to snap to the\n * nearest step value.\n * @param {number | undefined} min - The `min` parameter represents the minimum value that the `value`\n * should be snapped to. If `value` is less than `min`, it will be snapped to `min`. If `min` is not\n * provided (undefined), then the snapping will not consider a minimum value.\n * @param {number | undefined} max - The `max` parameter represents the maximum value that the `value`\n * should be snapped to. It ensures that the snapped value does not exceed this maximum value.\n * @param {number} step - The `step` parameter in the `snapValueToStep` function represents the\n * interval at which the `value` should be snapped to. It determines the granularity of the snapping\n * operation. For example, if `step` is 5, the `value` will be snapped to the nearest multiple of\n * @returns a number that has been snapped to the nearest step value within the specified range of minimum and maximum values.\n */\nexport function snapValueToStep(value: number, min: number | undefined, max: number | undefined, step: number): number {\n  min = Number(min)\n  max = Number(max)\n  const remainder = ((value - (Number.isNaN(min) ? 0 : min)) % step)\n  let snappedValue = roundToStepPrecision(Math.abs(remainder) * 2 >= step\n    ? value + Math.sign(remainder) * (step - Math.abs(remainder))\n    : value - remainder, step)\n\n  if (!Number.isNaN(min)) {\n    if (snappedValue < min)\n      snappedValue = min\n    else if (!Number.isNaN(max) && snappedValue > max)\n      snappedValue = min + Math.floor(roundToStepPrecision((max - min) / step, step)) * step\n  }\n  else if (!Number.isNaN(max) && snappedValue > max) {\n    snappedValue = Math.floor(roundToStepPrecision(max / step, step)) * step\n  }\n\n  // correct floating point behavior by rounding to step precision\n  snappedValue = roundToStepPrecision(snappedValue, step)\n\n  return snappedValue\n}\n","import type { InjectionKey } from 'vue'\nimport { inject, provide } from 'vue'\n\n/**\n * @param providerComponentName - The name(s) of the component(s) providing the context.\n *\n * There are situations where context can come from multiple components. In such cases, you might need to give an array of component names to provide your context, instead of just a single string.\n *\n * @param contextName The description for injection key symbol.\n */\nexport function createContext<ContextValue>(\n  providerComponentName: string | string[],\n  contextName?: string,\n) {\n  const symbolDescription\n    = typeof providerComponentName === 'string' && !contextName\n      ? `${providerComponentName}Context`\n      : contextName\n\n  const injectionKey: InjectionKey<ContextValue | null> = Symbol(symbolDescription)\n\n  /**\n   * @param fallback The context value to return if the injection fails.\n   *\n   * @throws When context injection failed and no fallback is specified.\n   * This happens when the component injecting the context is not a child of the root component providing the context.\n   */\n  const injectContext = <\n    T extends ContextValue | null | undefined = ContextValue,\n  >(\n    fallback?: T,\n  ): T extends null ? ContextValue | null : ContextValue => {\n    const context = inject(injectionKey, fallback)\n    if (context)\n      return context\n\n    if (context === null)\n      return context as any\n\n    throw new Error(\n      `Injection \\`${injectionKey.toString()}\\` not found. Component must be used within ${\n        Array.isArray(providerComponentName)\n          ? `one of the following components: ${providerComponentName.join(\n            ', ',\n          )}`\n          : `\\`${providerComponentName}\\``\n      }`,\n    )\n  }\n\n  const provideContext = (contextValue: ContextValue) => {\n    provide(injectionKey, contextValue)\n    return contextValue\n  }\n\n  return [injectContext, provideContext] as const\n}\n","export function getActiveElement(): Element | null {\n  let activeElement = document.activeElement\n  if (activeElement == null) {\n    return null\n  }\n\n  while (activeElement != null && activeElement.shadowRoot != null && activeElement.shadowRoot.activeElement != null) {\n    activeElement = activeElement.shadowRoot.activeElement\n  }\n\n  return activeElement\n}\n","export function handleAndDispatchCustomEvent<\n  E extends CustomEvent,\n  OriginalEvent extends Event,\n>(\n  name: string,\n  handler: ((event: E) => void) | undefined,\n  detail: { originalEvent: OriginalEvent } & (E extends CustomEvent<infer D>\n    ? D\n    : never),\n) {\n  const target = detail.originalEvent.target\n  const event = new CustomEvent(name, {\n    bubbles: false,\n    cancelable: true,\n    detail,\n  })\n  if (handler)\n    target.addEventListener(name, handler as EventListener, { once: true })\n\n  target.dispatchEvent(event)\n}\n","/**\n * Checks whether a given VNode is a render-vialble element.\n */\nexport function isValidVNodeElement(input: any): boolean {\n  return (\n    input\n    && (typeof input.type === 'string'\n      || typeof input.type === 'object'\n      || typeof input.type === 'function')\n  )\n}\n","export function isNullish(value: any): value is null | undefined {\n  return value === null || value === undefined\n}\n","import { isEqual } from 'ohash'\nimport { isNullish } from './nullish'\n\n/**\n * The function `isValueEqualOrExist` checks if a value is equal to or exists in another value or\n * array.\n * @param {T | T[] | undefined} base - It represents the base value that you want to compare with the `current` value.\n * @param {T | T[] | undefined} current - The `current` parameter represents the current value that you want to compare with the `base` value or values.\n * @returns The `isValueEqualOrExist` function returns a boolean value. It checks if the `base` value\n * is equal to the `current` value or if the `current` value exists within the `base` value. The\n * function handles cases where `base` can be a single value, an array of values, or undefined.\n */\nexport function isValueEqualOrExist<T>(base: T | T[] | undefined, current: T | T[] | undefined) {\n  if (isNullish(base))\n    return false\n  if (Array.isArray(base)) {\n    return base.some(val => isEqual(val, current))\n  }\n  else {\n    return isEqual(base, current)\n  }\n}\n","export function pick<T, K extends keyof T>(object: T, keys: K[]): Pick<T, K> {\n  return Object.assign(\n    {},\n    // eslint-disable-next-line array-callback-return\n    ...keys.map((key) => {\n      if (object && Object.hasOwn(object, key))\n        return { [key]: object[key] }\n    }),\n  )\n}\n\nexport function omit<T extends object, K extends keyof T>(obj: T, ...keys: K[]): Omit<T, K> {\n  keys.forEach(key => delete obj[key])\n  return obj\n}\n","import { computed, customRef, effectScope, getCurrentInstance, getCurrentScope, hasInjectionContext, inject, isReactive, isRef, nextTick, onBeforeMount, onBeforeUnmount, onMounted, onScopeDispose, onUnmounted, provide, reactive, readonly, ref, shallowReadonly, shallowRef, toRef as toRef$1, toRefs as toRefs$1, toValue, unref, watch, watchEffect } from \"vue\";\n//#region computedEager/index.ts\n/**\n*\n* @deprecated This function will be removed in future version.\n*\n* Note: If you are using Vue 3.4+, you can straight use computed instead.\n* Because in Vue 3.4+, if computed new value does not change,\n* computed, effect, watch, watchEffect, render dependencies will not be triggered.\n* refer: https://github.com/vuejs/core/pull/5912\n*\n* @param fn effect function\n* @param options WatchOptionsBase\n* @returns readonly shallowRef\n*/\nfunction computedEager(fn, options) {\n\tvar _options$flush;\n\tconst result = shallowRef();\n\twatchEffect(() => {\n\t\tresult.value = fn();\n\t}, {\n\t\t...options,\n\t\tflush: (_options$flush = options === null || options === void 0 ? void 0 : options.flush) !== null && _options$flush !== void 0 ? _options$flush : \"sync\"\n\t});\n\treturn readonly(result);\n}\n/** @deprecated use `computedEager` instead */\nconst eagerComputed = computedEager;\n//#endregion\n//#region computedWithControl/index.ts\n/**\n* Explicitly define the deps of computed.\n*\n* @param source\n* @param fn\n*/\nfunction computedWithControl(source, fn, options = {}) {\n\tlet v = void 0;\n\tlet track;\n\tlet trigger;\n\tlet dirty = true;\n\tconst update = () => {\n\t\tdirty = true;\n\t\ttrigger();\n\t};\n\twatch(source, update, {\n\t\tflush: \"sync\",\n\t\t...options\n\t});\n\tconst get = typeof fn === \"function\" ? fn : fn.get;\n\tconst set = typeof fn === \"function\" ? void 0 : fn.set;\n\tconst result = customRef((_track, _trigger) => {\n\t\ttrack = _track;\n\t\ttrigger = _trigger;\n\t\treturn {\n\t\t\tget() {\n\t\t\t\tif (dirty) {\n\t\t\t\t\tv = get(v);\n\t\t\t\t\tdirty = false;\n\t\t\t\t}\n\t\t\t\ttrack();\n\t\t\t\treturn v;\n\t\t\t},\n\t\t\tset(v) {\n\t\t\t\tset === null || set === void 0 || set(v);\n\t\t\t}\n\t\t};\n\t});\n\tresult.trigger = update;\n\treturn result;\n}\n/** @deprecated use `computedWithControl` instead */\nconst controlledComputed = computedWithControl;\n//#endregion\n//#region createDisposableDirective/index.ts\n/**\n* Utility for authoring disposable directives. Reactive effects created within `mounted` directive hook will be tracked and automatically disposed when directive is unmounted.\n*\n* @see https://vueuse.org/createDisposableDirective\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction createDisposableDirective(origin = {}) {\n\tfunction isFunc(fn) {\n\t\treturn typeof fn === \"function\";\n\t}\n\tconst normalisedOrigin = isFunc(origin) ? {\n\t\tmounted: origin,\n\t\tupdated: origin\n\t} : origin;\n\tconst { mounted, unmounted } = normalisedOrigin;\n\tif (!isFunc(mounted)) return origin;\n\tconst scopeWeakMap = /* @__PURE__ */ new WeakMap();\n\treturn {\n\t\t...normalisedOrigin,\n\t\tmounted(el, binding, vNode, prevNode) {\n\t\t\tvar _scopeWeakMap$get;\n\t\t\tconst scope = (_scopeWeakMap$get = scopeWeakMap.get(el)) !== null && _scopeWeakMap$get !== void 0 ? _scopeWeakMap$get : effectScope();\n\t\t\tscopeWeakMap.set(el, scope);\n\t\t\tscope.run(() => {\n\t\t\t\tmounted === null || mounted === void 0 || mounted(el, binding, vNode, prevNode);\n\t\t\t});\n\t\t},\n\t\tunmounted(el, binding, vNode, prevNode) {\n\t\t\tvar _scopeWeakMap$get2;\n\t\t\t(_scopeWeakMap$get2 = scopeWeakMap.get(el)) === null || _scopeWeakMap$get2 === void 0 || _scopeWeakMap$get2.stop();\n\t\t\tscopeWeakMap.delete(el);\n\t\t\tif (isFunc(unmounted)) unmounted(el, binding, vNode, prevNode);\n\t\t}\n\t};\n}\n//#endregion\n//#region tryOnScopeDispose/index.ts\n/**\n* Call onScopeDispose() if it's inside an effect scope lifecycle, if not, do nothing\n*\n* @param fn\n*/\nfunction tryOnScopeDispose(fn, failSilently) {\n\tif (getCurrentScope()) {\n\t\tonScopeDispose(fn, failSilently);\n\t\treturn true;\n\t}\n\treturn false;\n}\n//#endregion\n//#region createEventHook/index.ts\n/**\n* Utility for creating event hooks\n*\n* @see https://vueuse.org/createEventHook\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction createEventHook() {\n\tconst fns = /* @__PURE__ */ new Set();\n\tconst off = (fn) => {\n\t\tfns.delete(fn);\n\t};\n\tconst clear = () => {\n\t\tfns.clear();\n\t};\n\tconst on = (fn) => {\n\t\tfns.add(fn);\n\t\tconst offFn = () => off(fn);\n\t\ttryOnScopeDispose(offFn);\n\t\treturn { off: offFn };\n\t};\n\tconst trigger = (...args) => {\n\t\treturn Promise.all(Array.from(fns).map((fn) => fn(...args)));\n\t};\n\treturn {\n\t\ton,\n\t\toff,\n\t\ttrigger,\n\t\tclear\n\t};\n}\n//#endregion\n//#region createGlobalState/index.ts\n/**\n* Keep states in the global scope to be reusable across Vue instances.\n*\n* @see https://vueuse.org/createGlobalState\n* @param stateFactory A factory function to create the state\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction createGlobalState(stateFactory) {\n\tlet initialized = false;\n\tlet state;\n\tconst scope = effectScope(true);\n\treturn ((...args) => {\n\t\tif (!initialized) {\n\t\t\tstate = scope.run(() => stateFactory(...args));\n\t\t\tinitialized = true;\n\t\t}\n\t\treturn state;\n\t});\n}\n//#endregion\n//#region provideLocal/map.ts\nconst localProvidedStateMap = /* @__PURE__ */ new WeakMap();\n//#endregion\n//#region injectLocal/index.ts\n/**\n* On the basis of `inject`, it is allowed to directly call inject to obtain the value after call provide in the same component.\n*\n* @example\n* ```ts\n* injectLocal('MyInjectionKey', 1)\n* const injectedValue = injectLocal('MyInjectionKey') // injectedValue === 1\n* ```\n*\n* @__NO_SIDE_EFFECTS__\n*/\nconst injectLocal = (...args) => {\n\tvar _getCurrentInstance;\n\tconst key = args[0];\n\tconst instance = (_getCurrentInstance = getCurrentInstance()) === null || _getCurrentInstance === void 0 ? void 0 : _getCurrentInstance.proxy;\n\tconst owner = instance !== null && instance !== void 0 ? instance : getCurrentScope();\n\tif (owner == null && !hasInjectionContext()) throw new Error(\"injectLocal must be called in setup\");\n\tif (owner && localProvidedStateMap.has(owner) && key in localProvidedStateMap.get(owner)) return localProvidedStateMap.get(owner)[key];\n\treturn inject(...args);\n};\n//#endregion\n//#region provideLocal/index.ts\n/**\n* On the basis of `provide`, it is allowed to directly call inject to obtain the value after call provide in the same component.\n*\n* @example\n* ```ts\n* provideLocal('MyInjectionKey', 1)\n* const injectedValue = injectLocal('MyInjectionKey') // injectedValue === 1\n* ```\n*/\nfunction provideLocal(key, value) {\n\tvar _getCurrentInstance;\n\tconst instance = (_getCurrentInstance = getCurrentInstance()) === null || _getCurrentInstance === void 0 ? void 0 : _getCurrentInstance.proxy;\n\tconst owner = instance !== null && instance !== void 0 ? instance : getCurrentScope();\n\tif (owner == null) throw new Error(\"provideLocal must be called in setup\");\n\tif (!localProvidedStateMap.has(owner)) localProvidedStateMap.set(owner, Object.create(null));\n\tconst localProvidedState = localProvidedStateMap.get(owner);\n\tlocalProvidedState[key] = value;\n\treturn provide(key, value);\n}\n//#endregion\n//#region createInjectionState/index.ts\nfunction createInjectionState(composable, options) {\n\tconst key = (options === null || options === void 0 ? void 0 : options.injectionKey) || Symbol(composable.name || \"InjectionState\");\n\tconst defaultValue = options === null || options === void 0 ? void 0 : options.defaultValue;\n\tconst useProvidingState = (...args) => {\n\t\tconst state = composable(...args);\n\t\tprovideLocal(key, state);\n\t\treturn state;\n\t};\n\tconst useInjectedState = () => injectLocal(key, defaultValue);\n\treturn [useProvidingState, useInjectedState];\n}\n//#endregion\n//#region createRef/index.ts\n/**\n* Returns a `deepRef` or `shallowRef` depending on the `deep` param.\n*\n* @example createRef(1) // ShallowRef<number>\n* @example createRef(1, false) // ShallowRef<number>\n* @example createRef(1, true) // Ref<number>\n* @example createRef(\"string\") // ShallowRef<string>\n* @example createRef<\"A\"|\"B\">(\"A\", true) // Ref<\"A\"|\"B\">\n*\n* @param value\n* @param deep\n* @returns the `deepRef` or `shallowRef`\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction createRef(value, deep) {\n\tif (deep === true) return ref(value);\n\telse return shallowRef(value);\n}\n//#endregion\n//#region utils/is.ts\nconst isClient = typeof window !== \"undefined\" && typeof document !== \"undefined\";\nconst isWorker = typeof WorkerGlobalScope !== \"undefined\" && globalThis instanceof WorkerGlobalScope;\nconst isDef = (val) => typeof val !== \"undefined\";\nconst notNullish = (val) => val != null;\nconst assert = (condition, ...infos) => {\n\tif (!condition) console.warn(...infos);\n};\nconst toString = Object.prototype.toString;\nconst isObject = (val) => toString.call(val) === \"[object Object]\";\nconst now = () => Date.now();\nconst timestamp = () => +Date.now();\nconst clamp = (n, min, max) => Math.min(max, Math.max(min, n));\nconst noop = () => {};\nconst rand = (min, max) => {\n\tmin = Math.ceil(min);\n\tmax = Math.floor(max);\n\treturn Math.floor(Math.random() * (max - min + 1)) + min;\n};\nconst hasOwn = (val, key) => Object.hasOwn(val, key);\nconst isIOS = /* @__PURE__ */ getIsIOS();\nfunction getIsIOS() {\n\tvar _window, _window2, _window3;\n\treturn isClient && !!((_window = window) === null || _window === void 0 || (_window = _window.navigator) === null || _window === void 0 ? void 0 : _window.userAgent) && (/iP(?:ad|hone|od)/.test(window.navigator.userAgent) || ((_window2 = window) === null || _window2 === void 0 || (_window2 = _window2.navigator) === null || _window2 === void 0 ? void 0 : _window2.maxTouchPoints) > 2 && /iPad|Macintosh/.test((_window3 = window) === null || _window3 === void 0 ? void 0 : _window3.navigator.userAgent));\n}\n//#endregion\n//#region toRef/index.ts\nfunction toRef(...args) {\n\tif (args.length !== 1) return toRef$1(...args);\n\tconst r = args[0];\n\treturn typeof r === \"function\" ? readonly(customRef(() => ({\n\t\tget: r,\n\t\tset: noop\n\t}))) : ref(r);\n}\n//#endregion\n//#region utils/filters.ts\n/**\n* @internal\n*/\nfunction createFilterWrapper(filter, fn) {\n\tfunction wrapper(...args) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tPromise.resolve(filter(() => fn.apply(this, args), {\n\t\t\t\tfn,\n\t\t\t\tthisArg: this,\n\t\t\t\targs\n\t\t\t})).then(resolve).catch(reject);\n\t\t});\n\t}\n\treturn wrapper;\n}\nconst bypassFilter = (invoke) => {\n\treturn invoke();\n};\n/**\n* Create an EventFilter that debounce the events\n*/\nfunction debounceFilter(ms, options = {}) {\n\tlet timer;\n\tlet maxTimer;\n\tlet lastRejector = noop;\n\tconst _clearTimeout = (timer) => {\n\t\tclearTimeout(timer);\n\t\tlastRejector();\n\t\tlastRejector = noop;\n\t};\n\tlet lastInvoker;\n\tconst filter = (invoke) => {\n\t\tconst duration = toValue(ms);\n\t\tconst maxDuration = toValue(options.maxWait);\n\t\tif (timer) _clearTimeout(timer);\n\t\tif (duration <= 0 || maxDuration !== void 0 && maxDuration <= 0) {\n\t\t\tif (maxTimer) {\n\t\t\t\t_clearTimeout(maxTimer);\n\t\t\t\tmaxTimer = void 0;\n\t\t\t}\n\t\t\treturn Promise.resolve(invoke());\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlastRejector = options.rejectOnCancel ? reject : resolve;\n\t\t\tlastInvoker = invoke;\n\t\t\tif (maxDuration && !maxTimer) maxTimer = setTimeout(() => {\n\t\t\t\tif (timer) _clearTimeout(timer);\n\t\t\t\tmaxTimer = void 0;\n\t\t\t\tresolve(lastInvoker());\n\t\t\t}, maxDuration);\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\tif (maxTimer) _clearTimeout(maxTimer);\n\t\t\t\tmaxTimer = void 0;\n\t\t\t\tresolve(invoke());\n\t\t\t}, duration);\n\t\t});\n\t};\n\treturn filter;\n}\nfunction throttleFilter(...args) {\n\tlet lastExec = 0;\n\tlet timer;\n\tlet isLeading = true;\n\tlet lastRejector = noop;\n\tlet lastValue;\n\tlet ms;\n\tlet trailing;\n\tlet leading;\n\tlet rejectOnCancel;\n\tif (!isRef(args[0]) && typeof args[0] === \"object\") ({delay: ms, trailing = true, leading = true, rejectOnCancel = false} = args[0]);\n\telse [ms, trailing = true, leading = true, rejectOnCancel = false] = args;\n\tconst clear = () => {\n\t\tif (timer) {\n\t\t\tclearTimeout(timer);\n\t\t\ttimer = void 0;\n\t\t\tlastRejector();\n\t\t\tlastRejector = noop;\n\t\t}\n\t};\n\tconst filter = (_invoke) => {\n\t\tconst duration = toValue(ms);\n\t\tconst elapsed = Date.now() - lastExec;\n\t\tconst invoke = () => {\n\t\t\treturn lastValue = _invoke();\n\t\t};\n\t\tclear();\n\t\tif (duration <= 0) {\n\t\t\tlastExec = Date.now();\n\t\t\treturn invoke();\n\t\t}\n\t\tif (elapsed > duration) {\n\t\t\tlastExec = Date.now();\n\t\t\tif (leading || !isLeading) invoke();\n\t\t} else if (trailing) lastValue = new Promise((resolve, reject) => {\n\t\t\tlastRejector = rejectOnCancel ? reject : resolve;\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\tlastExec = Date.now();\n\t\t\t\tisLeading = true;\n\t\t\t\tresolve(invoke());\n\t\t\t\tclear();\n\t\t\t}, Math.max(0, duration - elapsed));\n\t\t});\n\t\tif (!leading && !timer) timer = setTimeout(() => isLeading = true, duration);\n\t\tisLeading = false;\n\t\treturn lastValue;\n\t};\n\treturn filter;\n}\n/**\n* EventFilter that gives extra controls to pause and resume the filter\n*\n* @param extendFilter  Extra filter to apply when the PausableFilter is active, default to none\n* @param options Options to configure the filter\n*/\nfunction pausableFilter(extendFilter = bypassFilter, options = {}) {\n\tconst { initialState = \"active\" } = options;\n\tconst isActive = toRef(initialState === \"active\");\n\tfunction pause() {\n\t\tisActive.value = false;\n\t}\n\tfunction resume() {\n\t\tisActive.value = true;\n\t}\n\tconst eventFilter = (...args) => {\n\t\tif (isActive.value) extendFilter(...args);\n\t};\n\treturn {\n\t\tisActive: shallowReadonly(isActive),\n\t\tpause,\n\t\tresume,\n\t\teventFilter\n\t};\n}\n//#endregion\n//#region utils/general.ts\nfunction promiseTimeout(ms, throwOnTimeout = false, reason = \"Timeout\") {\n\treturn new Promise((resolve, reject) => {\n\t\tif (throwOnTimeout) setTimeout(reject, ms, reason);\n\t\telse setTimeout(resolve, ms);\n\t});\n}\nfunction identity(arg) {\n\treturn arg;\n}\n/**\n* Create singleton promise function\n*\n* @example\n* ```\n* const promise = createSingletonPromise(async () => { ... })\n*\n* await promise()\n* await promise() // all of them will be bind to a single promise instance\n* await promise() // and be resolved together\n* ```\n*/\nfunction createSingletonPromise(fn) {\n\tlet _promise;\n\tfunction wrapper() {\n\t\tif (!_promise) _promise = fn();\n\t\treturn _promise;\n\t}\n\twrapper.reset = async () => {\n\t\tconst _prev = _promise;\n\t\t_promise = void 0;\n\t\tif (_prev) await _prev;\n\t};\n\treturn wrapper;\n}\nfunction invoke(fn) {\n\treturn fn();\n}\nfunction containsProp(obj, ...props) {\n\treturn props.some((k) => k in obj);\n}\nfunction increaseWithUnit(target, delta) {\n\tvar _target$match;\n\tif (typeof target === \"number\") return target + delta;\n\tconst value = ((_target$match = target.match(/^-?\\d+\\.?\\d*/)) === null || _target$match === void 0 ? void 0 : _target$match[0]) || \"\";\n\tconst unit = target.slice(value.length);\n\tconst result = Number.parseFloat(value) + delta;\n\tif (Number.isNaN(result)) return target;\n\treturn result + unit;\n}\n/**\n* Get a px value for SSR use, do not rely on this method outside of SSR as REM unit is assumed at 16px, which might not be the case on the client\n*/\nfunction pxValue(px) {\n\treturn px.endsWith(\"rem\") ? Number.parseFloat(px) * 16 : Number.parseFloat(px);\n}\n/**\n* Create a new subset object by giving keys\n*/\nfunction objectPick(obj, keys, omitUndefined = false) {\n\treturn keys.reduce((n, k) => {\n\t\tif (k in obj) {\n\t\t\tif (!omitUndefined || obj[k] !== void 0) n[k] = obj[k];\n\t\t}\n\t\treturn n;\n\t}, {});\n}\n/**\n* Create a new subset object by omit giving keys\n*/\nfunction objectOmit(obj, keys, omitUndefined = false) {\n\treturn Object.fromEntries(Object.entries(obj).filter(([key, value]) => {\n\t\treturn (!omitUndefined || value !== void 0) && !keys.includes(key);\n\t}));\n}\nfunction objectEntries(obj) {\n\treturn Object.entries(obj);\n}\nfunction toArray(value) {\n\treturn Array.isArray(value) ? value : [value];\n}\n//#endregion\n//#region utils/port.ts\nfunction cacheStringFunction(fn) {\n\tconst cache = Object.create(null);\n\treturn ((str) => {\n\t\treturn cache[str] || (cache[str] = fn(str));\n\t});\n}\nconst hyphenateRE = /\\B([A-Z])/g;\nconst hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, \"-$1\").toLowerCase());\nconst camelizeRE = /-(\\w)/g;\nconst camelize = cacheStringFunction((str) => {\n\treturn str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : \"\");\n});\n//#endregion\n//#region utils/vue.ts\nfunction getLifeCycleTarget(target) {\n\treturn target || getCurrentInstance();\n}\n//#endregion\n//#region createSharedComposable/index.ts\n/**\n* Make a composable function usable with multiple Vue instances.\n*\n* @see https://vueuse.org/createSharedComposable\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction createSharedComposable(composable) {\n\tif (!isClient) return composable;\n\tlet subscribers = 0;\n\tlet state;\n\tlet scope;\n\tconst dispose = () => {\n\t\tsubscribers -= 1;\n\t\tif (scope && subscribers <= 0) {\n\t\t\tscope.stop();\n\t\t\tstate = void 0;\n\t\t\tscope = void 0;\n\t\t}\n\t};\n\treturn ((...args) => {\n\t\tsubscribers += 1;\n\t\tif (!scope) {\n\t\t\tscope = effectScope(true);\n\t\t\tstate = scope.run(() => composable(...args));\n\t\t}\n\t\ttryOnScopeDispose(dispose);\n\t\treturn state;\n\t});\n}\n//#endregion\n//#region extendRef/index.ts\nfunction extendRef(ref, extend, { enumerable = false, unwrap = true } = {}) {\n\tfor (const [key, value] of Object.entries(extend)) {\n\t\tif (key === \"value\") continue;\n\t\tif (isRef(value) && unwrap) Object.defineProperty(ref, key, {\n\t\t\tget() {\n\t\t\t\treturn value.value;\n\t\t\t},\n\t\t\tset(v) {\n\t\t\t\tvalue.value = v;\n\t\t\t},\n\t\t\tenumerable\n\t\t});\n\t\telse Object.defineProperty(ref, key, {\n\t\t\tvalue,\n\t\t\tenumerable\n\t\t});\n\t}\n\treturn ref;\n}\n//#endregion\n//#region get/index.ts\nfunction get(obj, key) {\n\tif (key == null) return unref(obj);\n\treturn unref(obj)[key];\n}\n//#endregion\n//#region isDefined/index.ts\nfunction isDefined(v) {\n\treturn unref(v) != null;\n}\n//#endregion\n//#region makeDestructurable/index.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction makeDestructurable(obj, arr) {\n\tif (typeof Symbol !== \"undefined\") {\n\t\tconst clone = { ...obj };\n\t\tObject.defineProperty(clone, Symbol.iterator, {\n\t\t\tenumerable: false,\n\t\t\tvalue() {\n\t\t\t\tlet index = 0;\n\t\t\t\treturn { next: () => ({\n\t\t\t\t\tvalue: arr[index++],\n\t\t\t\t\tdone: index > arr.length\n\t\t\t\t}) };\n\t\t\t}\n\t\t});\n\t\treturn clone;\n\t} else return Object.assign([...arr], obj);\n}\n//#endregion\n//#region reactify/index.ts\n/**\n* Converts plain function into a reactive function.\n* The converted function accepts refs as it's arguments\n* and returns a ComputedRef, with proper typing.\n*\n* @param fn - Source function\n* @param options - Options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction reactify(fn, options) {\n\tconst unrefFn = (options === null || options === void 0 ? void 0 : options.computedGetter) === false ? unref : toValue;\n\treturn function(...args) {\n\t\treturn computed(() => fn.apply(this, args.map((i) => unrefFn(i))));\n\t};\n}\n/** @deprecated use `reactify` instead */\nconst createReactiveFn = reactify;\n//#endregion\n//#region reactifyObject/index.ts\n/**\n* Apply `reactify` to an object\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction reactifyObject(obj, optionsOrKeys = {}) {\n\tlet keys = [];\n\tlet options;\n\tif (Array.isArray(optionsOrKeys)) keys = optionsOrKeys;\n\telse {\n\t\toptions = optionsOrKeys;\n\t\tconst { includeOwnProperties = true } = optionsOrKeys;\n\t\tkeys.push(...Object.keys(obj));\n\t\tif (includeOwnProperties) keys.push(...Object.getOwnPropertyNames(obj));\n\t}\n\treturn Object.fromEntries(keys.map((key) => {\n\t\tconst value = obj[key];\n\t\treturn [key, typeof value === \"function\" ? reactify(value.bind(obj), options) : value];\n\t}));\n}\n//#endregion\n//#region toReactive/index.ts\n/**\n* Converts ref to reactive.\n*\n* @see https://vueuse.org/toReactive\n* @param objectRef A ref of object\n*/\nfunction toReactive(objectRef) {\n\tif (!isRef(objectRef)) return reactive(objectRef);\n\treturn reactive(new Proxy({}, {\n\t\tget(_, p, receiver) {\n\t\t\treturn unref(Reflect.get(objectRef.value, p, receiver));\n\t\t},\n\t\tset(_, p, value) {\n\t\t\tif (isRef(objectRef.value[p]) && !isRef(value)) objectRef.value[p].value = value;\n\t\t\telse objectRef.value[p] = value;\n\t\t\treturn true;\n\t\t},\n\t\tdeleteProperty(_, p) {\n\t\t\treturn Reflect.deleteProperty(objectRef.value, p);\n\t\t},\n\t\thas(_, p) {\n\t\t\treturn Reflect.has(objectRef.value, p);\n\t\t},\n\t\townKeys() {\n\t\t\treturn Object.keys(objectRef.value);\n\t\t},\n\t\tgetOwnPropertyDescriptor() {\n\t\t\treturn {\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: true\n\t\t\t};\n\t\t}\n\t}));\n}\n//#endregion\n//#region reactiveComputed/index.ts\n/**\n* Computed reactive object.\n*/\nfunction reactiveComputed(fn) {\n\treturn toReactive(computed(fn));\n}\n//#endregion\n//#region reactiveOmit/index.ts\n/**\n* Reactively omit fields from a reactive object\n*\n* @see https://vueuse.org/reactiveOmit\n*/\nfunction reactiveOmit(obj, ...keys) {\n\tconst flatKeys = keys.flat();\n\tconst predicate = flatKeys[0];\n\treturn reactiveComputed(() => typeof predicate === \"function\" ? Object.fromEntries(Object.entries(toRefs$1(obj)).filter(([k, v]) => !predicate(toValue(v), k))) : Object.fromEntries(Object.entries(toRefs$1(obj)).filter((e) => !flatKeys.includes(e[0]))));\n}\n//#endregion\n//#region reactivePick/index.ts\n/**\n* Reactively pick fields from a reactive object\n*\n* @see https://vueuse.org/reactivePick\n*/\nfunction reactivePick(obj, ...keys) {\n\tconst flatKeys = keys.flat();\n\tconst predicate = flatKeys[0];\n\treturn reactiveComputed(() => typeof predicate === \"function\" ? Object.fromEntries(Object.entries(toRefs$1(obj)).filter(([k, v]) => predicate(toValue(v), k))) : Object.fromEntries(flatKeys.map((k) => [k, toRef(obj, k)])));\n}\n//#endregion\n//#region refAutoReset/index.ts\n/**\n* Create a ref which will be reset to the default value after some time.\n*\n* @see https://vueuse.org/refAutoReset\n* @param defaultValue The value which will be set.\n* @param afterMs      A zero-or-greater delay in milliseconds.\n*/\nfunction refAutoReset(defaultValue, afterMs = 1e4) {\n\treturn customRef((track, trigger) => {\n\t\tlet value = toValue(defaultValue);\n\t\tlet timer;\n\t\tconst resetAfter = () => setTimeout(() => {\n\t\t\tvalue = toValue(defaultValue);\n\t\t\ttrigger();\n\t\t}, toValue(afterMs));\n\t\ttryOnScopeDispose(() => {\n\t\t\tclearTimeout(timer);\n\t\t});\n\t\treturn {\n\t\t\tget() {\n\t\t\t\ttrack();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\tset(newValue) {\n\t\t\t\tvalue = newValue;\n\t\t\t\ttrigger();\n\t\t\t\tclearTimeout(timer);\n\t\t\t\ttimer = resetAfter();\n\t\t\t}\n\t\t};\n\t});\n}\n/** @deprecated use `refAutoReset` instead */\nconst autoResetRef = refAutoReset;\n//#endregion\n//#region useDebounceFn/index.ts\n/**\n* Debounce execution of a function.\n*\n* @see https://vueuse.org/useDebounceFn\n* @param  fn          A function to be executed after delay milliseconds debounced.\n* @param  ms          A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.\n* @param  options     Options\n*\n* @return A new, debounce, function.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useDebounceFn(fn, ms = 200, options = {}) {\n\treturn createFilterWrapper(debounceFilter(ms, options), fn);\n}\n//#endregion\n//#region refDebounced/index.ts\n/**\n* Debounce updates of a ref.\n*\n* @return A new debounced ref.\n*/\nfunction refDebounced(value, ms = 200, options = {}) {\n\tconst debounced = ref(toValue(value));\n\tconst updater = useDebounceFn(() => {\n\t\tdebounced.value = value.value;\n\t}, ms, options);\n\twatch(value, () => updater());\n\treturn shallowReadonly(debounced);\n}\n/** @deprecated use `refDebounced` instead */\nconst debouncedRef = refDebounced;\n/** @deprecated use `refDebounced` instead */\nconst useDebounce = refDebounced;\n//#endregion\n//#region refDefault/index.ts\n/**\n* Apply default value to a ref.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction refDefault(source, defaultValue) {\n\treturn computed({\n\t\tget() {\n\t\t\tvar _source$value;\n\t\t\treturn (_source$value = source.value) !== null && _source$value !== void 0 ? _source$value : defaultValue;\n\t\t},\n\t\tset(value) {\n\t\t\tsource.value = value;\n\t\t}\n\t});\n}\n//#endregion\n//#region refManualReset/index.ts\n/**\n* Create a ref with manual reset functionality.\n*\n* @see https://vueuse.org/refManualReset\n* @param defaultValue The value which will be set.\n*/\nfunction refManualReset(defaultValue) {\n\tlet value = toValue(defaultValue);\n\tlet trigger;\n\tconst reset = () => {\n\t\tvalue = toValue(defaultValue);\n\t\ttrigger();\n\t};\n\tconst refValue = customRef((track, _trigger) => {\n\t\ttrigger = _trigger;\n\t\treturn {\n\t\t\tget() {\n\t\t\t\ttrack();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\tset(newValue) {\n\t\t\t\tvalue = newValue;\n\t\t\t\ttrigger();\n\t\t\t}\n\t\t};\n\t});\n\trefValue.reset = reset;\n\treturn refValue;\n}\n//#endregion\n//#region useThrottleFn/index.ts\n/**\n* Throttle execution of a function. Especially useful for rate limiting\n* execution of handlers on events like resize and scroll.\n*\n* @param   fn             A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,\n*                                    to `callback` when the throttled-function is executed.\n* @param   ms             A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.\n*                                    (default value: 200)\n*\n* @param [trailing] if true, call fn again after the time is up (default value: false)\n*\n* @param [leading] if true, call fn on the leading edge of the ms timeout (default value: true)\n*\n* @param [rejectOnCancel] if true, reject the last call if it's been cancel (default value: false)\n*\n* @return  A new, throttled, function.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useThrottleFn(fn, ms = 200, trailing = false, leading = true, rejectOnCancel = false) {\n\treturn createFilterWrapper(throttleFilter(ms, trailing, leading, rejectOnCancel), fn);\n}\n//#endregion\n//#region refThrottled/index.ts\n/**\n* Throttle execution of a function. Especially useful for rate limiting\n* execution of handlers on events like resize and scroll.\n*\n* @param value Ref value to be watched with throttle effect\n* @param  delay  A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.\n* @param trailing if true, update the value again after the delay time is up\n* @param leading if true, update the value on the leading edge of the ms timeout\n*/\nfunction refThrottled(value, delay = 200, trailing = true, leading = true) {\n\tif (delay <= 0) return value;\n\tconst throttled = ref(toValue(value));\n\tconst updater = useThrottleFn(() => {\n\t\tthrottled.value = value.value;\n\t}, delay, trailing, leading);\n\twatch(value, () => updater());\n\treturn throttled;\n}\n/** @deprecated use `refThrottled` instead */\nconst throttledRef = refThrottled;\n/** @deprecated use `refThrottled` instead */\nconst useThrottle = refThrottled;\n//#endregion\n//#region refWithControl/index.ts\n/**\n* Fine-grained controls over ref and its reactivity.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction refWithControl(initial, options = {}) {\n\tlet source = initial;\n\tlet track;\n\tlet trigger;\n\tconst ref = customRef((_track, _trigger) => {\n\t\ttrack = _track;\n\t\ttrigger = _trigger;\n\t\treturn {\n\t\t\tget() {\n\t\t\t\treturn get();\n\t\t\t},\n\t\t\tset(v) {\n\t\t\t\tset(v);\n\t\t\t}\n\t\t};\n\t});\n\tfunction get(tracking = true) {\n\t\tif (tracking) track();\n\t\treturn source;\n\t}\n\tfunction set(value, triggering = true) {\n\t\tvar _options$onBeforeChan, _options$onChanged;\n\t\tif (value === source) return;\n\t\tconst old = source;\n\t\tif (((_options$onBeforeChan = options.onBeforeChange) === null || _options$onBeforeChan === void 0 ? void 0 : _options$onBeforeChan.call(options, value, old)) === false) return;\n\t\tsource = value;\n\t\t(_options$onChanged = options.onChanged) === null || _options$onChanged === void 0 || _options$onChanged.call(options, value, old);\n\t\tif (triggering) trigger();\n\t}\n\t/**\n\t* Get the value without tracked in the reactivity system\n\t*/\n\tconst untrackedGet = () => get(false);\n\t/**\n\t* Set the value without triggering the reactivity system\n\t*/\n\tconst silentSet = (v) => set(v, false);\n\t/**\n\t* Get the value without tracked in the reactivity system.\n\t*\n\t* Alias for `untrackedGet()`\n\t*/\n\tconst peek = () => get(false);\n\t/**\n\t* Set the value without triggering the reactivity system\n\t*\n\t* Alias for `silentSet(v)`\n\t*/\n\tconst lay = (v) => set(v, false);\n\treturn extendRef(ref, {\n\t\tget,\n\t\tset,\n\t\tuntrackedGet,\n\t\tsilentSet,\n\t\tpeek,\n\t\tlay\n\t}, { enumerable: true });\n}\n/** @deprecated use `refWithControl` instead */\nconst controlledRef = refWithControl;\n//#endregion\n//#region set/index.ts\n/**\n*  Shorthand for `ref.value = x`\n*/\nfunction set(...args) {\n\tif (args.length === 2) {\n\t\tconst [ref, value] = args;\n\t\tref.value = value;\n\t}\n\tif (args.length === 3) {\n\t\tconst [target, key, value] = args;\n\t\ttarget[key] = value;\n\t}\n}\n//#endregion\n//#region watchWithFilter/index.ts\nfunction watchWithFilter(source, cb, options = {}) {\n\tconst { eventFilter = bypassFilter, ...watchOptions } = options;\n\treturn watch(source, createFilterWrapper(eventFilter, cb), watchOptions);\n}\n//#endregion\n//#region watchPausable/index.ts\n/** @deprecated Use Vue's built-in `watch` instead. This function will be removed in future version. */\nfunction watchPausable(source, cb, options = {}) {\n\tconst { eventFilter: filter, initialState = \"active\", ...watchOptions } = options;\n\tconst { eventFilter, pause, resume, isActive } = pausableFilter(filter, { initialState });\n\treturn {\n\t\tstop: watchWithFilter(source, cb, {\n\t\t\t...watchOptions,\n\t\t\teventFilter\n\t\t}),\n\t\tpause,\n\t\tresume,\n\t\tisActive\n\t};\n}\n/** @deprecated Use Vue's built-in `watch` instead. This function will be removed in future version. */\nconst pausableWatch = watchPausable;\n//#endregion\n//#region syncRef/index.ts\n/**\n* Two-way refs synchronization.\n* From the set theory perspective to restrict the option's type\n* Check in the following order:\n* 1. L = R\n* 2. L ∩ R ≠ ∅\n* 3. L ⊆ R\n* 4. L ∩ R = ∅\n*/\nfunction syncRef(left, right, ...[options]) {\n\tconst { flush = \"sync\", deep = false, immediate = true, direction = \"both\", transform = {} } = options || {};\n\tconst watchers = [];\n\tconst transformLTR = \"ltr\" in transform && transform.ltr || ((v) => v);\n\tconst transformRTL = \"rtl\" in transform && transform.rtl || ((v) => v);\n\tif (direction === \"both\" || direction === \"ltr\") watchers.push(watchPausable(left, (newValue) => {\n\t\twatchers.forEach((w) => w.pause());\n\t\tright.value = transformLTR(newValue);\n\t\twatchers.forEach((w) => w.resume());\n\t}, {\n\t\tflush,\n\t\tdeep,\n\t\timmediate\n\t}));\n\tif (direction === \"both\" || direction === \"rtl\") watchers.push(watchPausable(right, (newValue) => {\n\t\twatchers.forEach((w) => w.pause());\n\t\tleft.value = transformRTL(newValue);\n\t\twatchers.forEach((w) => w.resume());\n\t}, {\n\t\tflush,\n\t\tdeep,\n\t\timmediate\n\t}));\n\tconst stop = () => {\n\t\twatchers.forEach((w) => w.stop());\n\t};\n\treturn stop;\n}\n//#endregion\n//#region syncRefs/index.ts\n/**\n* Keep target ref(s) in sync with the source ref\n*\n* @param source source ref\n* @param targets\n*/\nfunction syncRefs(source, targets, options = {}) {\n\tconst { flush = \"sync\", deep = false, immediate = true } = options;\n\tconst targetsArray = toArray(targets);\n\treturn watch(source, (newValue) => targetsArray.forEach((target) => target.value = newValue), {\n\t\tflush,\n\t\tdeep,\n\t\timmediate\n\t});\n}\n//#endregion\n//#region toRefs/index.ts\n/**\n* Extended `toRefs` that also accepts refs of an object.\n*\n* @see https://vueuse.org/toRefs\n* @param objectRef A ref or normal object or array.\n* @param options Options\n*/\nfunction toRefs(objectRef, options = {}) {\n\tif (!isRef(objectRef)) return toRefs$1(objectRef);\n\tconst result = Array.isArray(objectRef.value) ? Array.from({ length: objectRef.value.length }) : {};\n\tfor (const key in objectRef.value) result[key] = customRef(() => ({\n\t\tget() {\n\t\t\treturn objectRef.value[key];\n\t\t},\n\t\tset(v) {\n\t\t\tvar _toValue;\n\t\t\tif ((_toValue = toValue(options.replaceRef)) !== null && _toValue !== void 0 ? _toValue : true) if (Array.isArray(objectRef.value)) {\n\t\t\t\tconst copy = [...objectRef.value];\n\t\t\t\tcopy[key] = v;\n\t\t\t\tobjectRef.value = copy;\n\t\t\t} else {\n\t\t\t\tconst newObject = {\n\t\t\t\t\t...objectRef.value,\n\t\t\t\t\t[key]: v\n\t\t\t\t};\n\t\t\t\tObject.setPrototypeOf(newObject, Object.getPrototypeOf(objectRef.value));\n\t\t\t\tobjectRef.value = newObject;\n\t\t\t}\n\t\t\telse objectRef.value[key] = v;\n\t\t}\n\t}));\n\treturn result;\n}\n//#endregion\n//#region tryOnBeforeMount/index.ts\n/**\n* Call onBeforeMount() if it's inside a component lifecycle, if not, just call the function\n*\n* @param fn\n* @param sync if set to false, it will run in the nextTick() of Vue\n* @param target\n*/\nfunction tryOnBeforeMount(fn, sync = true, target) {\n\tif (getLifeCycleTarget(target)) onBeforeMount(fn, target);\n\telse if (sync) fn();\n\telse nextTick(fn);\n}\n//#endregion\n//#region tryOnBeforeUnmount/index.ts\n/**\n* Call onBeforeUnmount() if it's inside a component lifecycle, if not, do nothing\n*\n* @param fn\n* @param target\n*/\nfunction tryOnBeforeUnmount(fn, target) {\n\tif (getLifeCycleTarget(target)) onBeforeUnmount(fn, target);\n}\n//#endregion\n//#region tryOnMounted/index.ts\n/**\n* Call onMounted() if it's inside a component lifecycle, if not, just call the function\n*\n* @param fn\n* @param sync if set to false, it will run in the nextTick() of Vue\n* @param target\n*/\nfunction tryOnMounted(fn, sync = true, target) {\n\tif (getLifeCycleTarget(target)) onMounted(fn, target);\n\telse if (sync) fn();\n\telse nextTick(fn);\n}\n//#endregion\n//#region tryOnUnmounted/index.ts\n/**\n* Call onUnmounted() if it's inside a component lifecycle, if not, do nothing\n*\n* @param fn\n* @param target\n*/\nfunction tryOnUnmounted(fn, target) {\n\tif (getLifeCycleTarget(target)) onUnmounted(fn, target);\n}\n//#endregion\n//#region until/index.ts\nfunction createUntil(r, isNot = false) {\n\tfunction toMatch(condition, { flush = \"sync\", deep = false, timeout, throwOnTimeout } = {}) {\n\t\tlet stop = null;\n\t\tconst promises = [new Promise((resolve) => {\n\t\t\tstop = watch(r, (v) => {\n\t\t\t\tif (condition(v) !== isNot) {\n\t\t\t\t\tif (stop) stop();\n\t\t\t\t\telse nextTick(() => stop === null || stop === void 0 ? void 0 : stop());\n\t\t\t\t\tresolve(v);\n\t\t\t\t}\n\t\t\t}, {\n\t\t\t\tflush,\n\t\t\t\tdeep,\n\t\t\t\timmediate: true\n\t\t\t});\n\t\t})];\n\t\tif (timeout != null) promises.push(promiseTimeout(timeout, throwOnTimeout).then(() => toValue(r)).finally(() => stop === null || stop === void 0 ? void 0 : stop()));\n\t\treturn Promise.race(promises);\n\t}\n\tfunction toBe(value, options) {\n\t\tif (!isRef(value)) return toMatch((v) => v === value, options);\n\t\tconst { flush = \"sync\", deep = false, timeout, throwOnTimeout } = options !== null && options !== void 0 ? options : {};\n\t\tlet stop = null;\n\t\tconst promises = [new Promise((resolve) => {\n\t\t\tstop = watch([r, value], ([v1, v2]) => {\n\t\t\t\tif (isNot !== (v1 === v2)) {\n\t\t\t\t\tif (stop) stop();\n\t\t\t\t\telse nextTick(() => stop === null || stop === void 0 ? void 0 : stop());\n\t\t\t\t\tresolve(v1);\n\t\t\t\t}\n\t\t\t}, {\n\t\t\t\tflush,\n\t\t\t\tdeep,\n\t\t\t\timmediate: true\n\t\t\t});\n\t\t})];\n\t\tif (timeout != null) promises.push(promiseTimeout(timeout, throwOnTimeout).then(() => toValue(r)).finally(() => {\n\t\t\tstop === null || stop === void 0 || stop();\n\t\t\treturn toValue(r);\n\t\t}));\n\t\treturn Promise.race(promises);\n\t}\n\tfunction toBeTruthy(options) {\n\t\treturn toMatch((v) => Boolean(v), options);\n\t}\n\tfunction toBeNull(options) {\n\t\treturn toBe(null, options);\n\t}\n\tfunction toBeUndefined(options) {\n\t\treturn toBe(void 0, options);\n\t}\n\tfunction toBeNaN(options) {\n\t\treturn toMatch(Number.isNaN, options);\n\t}\n\tfunction toContains(value, options) {\n\t\treturn toMatch((v) => {\n\t\t\tconst array = Array.from(v);\n\t\t\treturn array.includes(value) || array.includes(toValue(value));\n\t\t}, options);\n\t}\n\tfunction changed(options) {\n\t\treturn changedTimes(1, options);\n\t}\n\tfunction changedTimes(n = 1, options) {\n\t\tlet count = -1;\n\t\treturn toMatch(() => {\n\t\t\tcount += 1;\n\t\t\treturn count >= n;\n\t\t}, options);\n\t}\n\tif (Array.isArray(toValue(r))) return {\n\t\ttoMatch,\n\t\ttoContains,\n\t\tchanged,\n\t\tchangedTimes,\n\t\tget not() {\n\t\t\treturn createUntil(r, !isNot);\n\t\t}\n\t};\n\telse return {\n\t\ttoMatch,\n\t\ttoBe,\n\t\ttoBeTruthy,\n\t\ttoBeNull,\n\t\ttoBeNaN,\n\t\ttoBeUndefined,\n\t\tchanged,\n\t\tchangedTimes,\n\t\tget not() {\n\t\t\treturn createUntil(r, !isNot);\n\t\t}\n\t};\n}\nfunction until(r) {\n\treturn createUntil(r);\n}\n//#endregion\n//#region useArrayDifference/index.ts\nfunction defaultComparator(value, othVal) {\n\treturn value === othVal;\n}\n/**\n* Reactive get array difference of two array\n* @see https://vueuse.org/useArrayDifference\n* @returns - the difference of two array\n* @param args\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useArrayDifference(...args) {\n\tvar _args$, _args$2;\n\tconst list = args[0];\n\tconst values = args[1];\n\tlet compareFn = (_args$ = args[2]) !== null && _args$ !== void 0 ? _args$ : defaultComparator;\n\tconst { symmetric = false } = (_args$2 = args[3]) !== null && _args$2 !== void 0 ? _args$2 : {};\n\tif (typeof compareFn === \"string\") {\n\t\tconst key = compareFn;\n\t\tcompareFn = (value, othVal) => value[key] === othVal[key];\n\t}\n\tconst diff1 = computed(() => toValue(list).filter((x) => toValue(values).findIndex((y) => compareFn(x, y)) === -1));\n\tif (symmetric) {\n\t\tconst diff2 = computed(() => toValue(values).filter((x) => toValue(list).findIndex((y) => compareFn(x, y)) === -1));\n\t\treturn computed(() => symmetric ? [...toValue(diff1), ...toValue(diff2)] : toValue(diff1));\n\t} else return diff1;\n}\n//#endregion\n//#region useArrayEvery/index.ts\n/**\n* Reactive `Array.every`\n*\n* @see https://vueuse.org/useArrayEvery\n* @param list - the array was called upon.\n* @param fn - a function to test each element.\n*\n* @returns **true** if the `fn` function returns a **truthy** value for every element from the array. Otherwise, **false**.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useArrayEvery(list, fn) {\n\treturn computed(() => toValue(list).every((element, index, array) => fn(toValue(element), index, array)));\n}\n//#endregion\n//#region useArrayFilter/index.ts\n/**\n* Reactive `Array.filter`\n*\n* @see https://vueuse.org/useArrayFilter\n* @param list - the array was called upon.\n* @param fn - a function that is called for every element of the given `list`. Each time `fn` executes, the returned value is added to the new array.\n*\n* @returns a shallow copy of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useArrayFilter(list, fn) {\n\treturn computed(() => toValue(list).map((i) => toValue(i)).filter(fn));\n}\n//#endregion\n//#region useArrayFind/index.ts\n/**\n* Reactive `Array.find`\n*\n* @see https://vueuse.org/useArrayFind\n* @param list - the array was called upon.\n* @param fn - a function to test each element.\n*\n* @returns the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useArrayFind(list, fn) {\n\treturn computed(() => toValue(toValue(list).find((element, index, array) => fn(toValue(element), index, array))));\n}\n//#endregion\n//#region useArrayFindIndex/index.ts\n/**\n* Reactive `Array.findIndex`\n*\n* @see https://vueuse.org/useArrayFindIndex\n* @param list - the array was called upon.\n* @param fn - a function to test each element.\n*\n* @returns the index of the first element in the array that passes the test. Otherwise, \"-1\".\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useArrayFindIndex(list, fn) {\n\treturn computed(() => toValue(list).findIndex((element, index, array) => fn(toValue(element), index, array)));\n}\n//#endregion\n//#region useArrayFindLast/index.ts\nfunction findLast(arr, cb) {\n\tlet index = arr.length;\n\twhile (index-- > 0) if (cb(arr[index], index, arr)) return arr[index];\n}\n/**\n* Reactive `Array.findLast`\n*\n* @see https://vueuse.org/useArrayFindLast\n* @param list - the array was called upon.\n* @param fn - a function to test each element.\n*\n* @returns the last element in the array that satisfies the provided testing function. Otherwise, undefined is returned.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useArrayFindLast(list, fn) {\n\treturn computed(() => toValue(!Array.prototype.findLast ? findLast(toValue(list), (element, index, array) => fn(toValue(element), index, array)) : toValue(list).findLast((element, index, array) => fn(toValue(element), index, array))));\n}\n//#endregion\n//#region useArrayIncludes/index.ts\nfunction isArrayIncludesOptions(obj) {\n\treturn isObject(obj) && containsProp(obj, \"formIndex\", \"comparator\");\n}\n/**\n* Reactive `Array.includes`\n*\n* @see https://vueuse.org/useArrayIncludes\n*\n* @returns true if the `value` is found in the array. Otherwise, false.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useArrayIncludes(...args) {\n\tvar _comparator;\n\tconst list = args[0];\n\tconst value = args[1];\n\tlet comparator = args[2];\n\tlet formIndex = 0;\n\tif (isArrayIncludesOptions(comparator)) {\n\t\tvar _comparator$fromIndex;\n\t\tformIndex = (_comparator$fromIndex = comparator.fromIndex) !== null && _comparator$fromIndex !== void 0 ? _comparator$fromIndex : 0;\n\t\tcomparator = comparator.comparator;\n\t}\n\tif (typeof comparator === \"string\") {\n\t\tconst key = comparator;\n\t\tcomparator = (element, value) => element[key] === toValue(value);\n\t}\n\tcomparator = (_comparator = comparator) !== null && _comparator !== void 0 ? _comparator : ((element, value) => element === toValue(value));\n\treturn computed(() => toValue(list).slice(formIndex).some((element, index, array) => comparator(toValue(element), toValue(value), index, toValue(array))));\n}\n//#endregion\n//#region useArrayJoin/index.ts\n/**\n* Reactive `Array.join`\n*\n* @see https://vueuse.org/useArrayJoin\n* @param list - the array was called upon.\n* @param separator - a string to separate each pair of adjacent elements of the array. If omitted, the array elements are separated with a comma (\",\").\n*\n* @returns a string with all array elements joined. If arr.length is 0, the empty string is returned.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useArrayJoin(list, separator) {\n\treturn computed(() => toValue(list).map((i) => toValue(i)).join(toValue(separator)));\n}\n//#endregion\n//#region useArrayMap/index.ts\n/**\n* Reactive `Array.map`\n*\n* @see https://vueuse.org/useArrayMap\n* @param list - the array was called upon.\n* @param fn - a function that is called for every element of the given `list`. Each time `fn` executes, the returned value is added to the new array.\n*\n* @returns a new array with each element being the result of the callback function.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useArrayMap(list, fn) {\n\treturn computed(() => toValue(list).map((i) => toValue(i)).map(fn));\n}\n//#endregion\n//#region useArrayReduce/index.ts\n/**\n* Reactive `Array.reduce`\n*\n* @see https://vueuse.org/useArrayReduce\n* @param list - the array was called upon.\n* @param reducer - a \"reducer\" function.\n* @param args\n*\n* @returns the value that results from running the \"reducer\" callback function to completion over the entire array.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useArrayReduce(list, reducer, ...args) {\n\tconst reduceCallback = (sum, value, index) => reducer(toValue(sum), toValue(value), index);\n\treturn computed(() => {\n\t\tconst resolved = toValue(list);\n\t\treturn args.length ? resolved.reduce(reduceCallback, typeof args[0] === \"function\" ? toValue(args[0]()) : toValue(args[0])) : resolved.reduce(reduceCallback);\n\t});\n}\n//#endregion\n//#region useArraySome/index.ts\n/**\n* Reactive `Array.some`\n*\n* @see https://vueuse.org/useArraySome\n* @param list - the array was called upon.\n* @param fn - a function to test each element.\n*\n* @returns **true** if the `fn` function returns a **truthy** value for any element from the array. Otherwise, **false**.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useArraySome(list, fn) {\n\treturn computed(() => toValue(list).some((element, index, array) => fn(toValue(element), index, array)));\n}\n//#endregion\n//#region useArrayUnique/index.ts\nfunction uniq(array) {\n\treturn Array.from(new Set(array));\n}\nfunction uniqueElementsBy(array, fn) {\n\treturn array.reduce((acc, v) => {\n\t\tif (!acc.some((x) => fn(v, x, array))) acc.push(v);\n\t\treturn acc;\n\t}, []);\n}\n/**\n* reactive unique array\n* @see https://vueuse.org/useArrayUnique\n* @param list - the array was called upon.\n* @param compareFn\n* @returns A computed ref that returns a unique array of items.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useArrayUnique(list, compareFn) {\n\treturn computed(() => {\n\t\tconst resolvedList = toValue(list).map((element) => toValue(element));\n\t\treturn compareFn ? uniqueElementsBy(resolvedList, compareFn) : uniq(resolvedList);\n\t});\n}\n//#endregion\n//#region useCounter/index.ts\n/**\n* Basic counter with utility functions.\n*\n* @see https://vueuse.org/useCounter\n* @param [initialValue]\n* @param options\n*/\nfunction useCounter(initialValue = 0, options = {}) {\n\tlet _initialValue = unref(initialValue);\n\tconst count = shallowRef(initialValue);\n\tconst { max = Number.POSITIVE_INFINITY, min = Number.NEGATIVE_INFINITY } = options;\n\tconst inc = (delta = 1) => count.value = Math.max(Math.min(max, count.value + delta), min);\n\tconst dec = (delta = 1) => count.value = Math.min(Math.max(min, count.value - delta), max);\n\tconst get = () => count.value;\n\tconst set = (val) => count.value = Math.max(min, Math.min(max, val));\n\tconst reset = (val = _initialValue) => {\n\t\t_initialValue = val;\n\t\treturn set(val);\n\t};\n\treturn {\n\t\tcount: shallowReadonly(count),\n\t\tinc,\n\t\tdec,\n\t\tget,\n\t\tset,\n\t\treset\n\t};\n}\n//#endregion\n//#region useDateFormat/index.ts\nconst REGEX_PARSE = /^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[T\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/i;\nconst REGEX_FORMAT = /[YMDHhms]o|\\[([^\\]]+)\\]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a{1,2}|A{1,2}|m{1,2}|s{1,2}|Z{1,2}|z{1,4}|SSS/g;\nfunction defaultMeridiem(hours, minutes, isLowercase, hasPeriod) {\n\tlet m = hours < 12 ? \"AM\" : \"PM\";\n\tif (hasPeriod) m = m.split(\"\").reduce((acc, curr) => acc += `${curr}.`, \"\");\n\treturn isLowercase ? m.toLowerCase() : m;\n}\nfunction formatOrdinal(num) {\n\tconst suffixes = [\n\t\t\"th\",\n\t\t\"st\",\n\t\t\"nd\",\n\t\t\"rd\"\n\t];\n\tconst v = num % 100;\n\treturn num + (suffixes[(v - 20) % 10] || suffixes[v] || suffixes[0]);\n}\nfunction formatDate(date, formatStr, options = {}) {\n\tvar _options$customMeridi;\n\tconst years = date.getFullYear();\n\tconst month = date.getMonth();\n\tconst days = date.getDate();\n\tconst hours = date.getHours();\n\tconst minutes = date.getMinutes();\n\tconst seconds = date.getSeconds();\n\tconst milliseconds = date.getMilliseconds();\n\tconst day = date.getDay();\n\tconst meridiem = (_options$customMeridi = options.customMeridiem) !== null && _options$customMeridi !== void 0 ? _options$customMeridi : defaultMeridiem;\n\tconst stripTimeZone = (dateString) => {\n\t\tvar _dateString$split$;\n\t\treturn (_dateString$split$ = dateString.split(\" \")[1]) !== null && _dateString$split$ !== void 0 ? _dateString$split$ : \"\";\n\t};\n\tconst matches = {\n\t\tYo: () => formatOrdinal(years),\n\t\tYY: () => String(years).slice(-2),\n\t\tYYYY: () => years,\n\t\tM: () => month + 1,\n\t\tMo: () => formatOrdinal(month + 1),\n\t\tMM: () => `${month + 1}`.padStart(2, \"0\"),\n\t\tMMM: () => date.toLocaleDateString(toValue(options.locales), { month: \"short\" }),\n\t\tMMMM: () => date.toLocaleDateString(toValue(options.locales), { month: \"long\" }),\n\t\tD: () => String(days),\n\t\tDo: () => formatOrdinal(days),\n\t\tDD: () => `${days}`.padStart(2, \"0\"),\n\t\tH: () => String(hours),\n\t\tHo: () => formatOrdinal(hours),\n\t\tHH: () => `${hours}`.padStart(2, \"0\"),\n\t\th: () => `${hours % 12 || 12}`.padStart(1, \"0\"),\n\t\tho: () => formatOrdinal(hours % 12 || 12),\n\t\thh: () => `${hours % 12 || 12}`.padStart(2, \"0\"),\n\t\tm: () => String(minutes),\n\t\tmo: () => formatOrdinal(minutes),\n\t\tmm: () => `${minutes}`.padStart(2, \"0\"),\n\t\ts: () => String(seconds),\n\t\tso: () => formatOrdinal(seconds),\n\t\tss: () => `${seconds}`.padStart(2, \"0\"),\n\t\tSSS: () => `${milliseconds}`.padStart(3, \"0\"),\n\t\td: () => day,\n\t\tdd: () => date.toLocaleDateString(toValue(options.locales), { weekday: \"narrow\" }),\n\t\tddd: () => date.toLocaleDateString(toValue(options.locales), { weekday: \"short\" }),\n\t\tdddd: () => date.toLocaleDateString(toValue(options.locales), { weekday: \"long\" }),\n\t\tA: () => meridiem(hours, minutes),\n\t\tAA: () => meridiem(hours, minutes, false, true),\n\t\ta: () => meridiem(hours, minutes, true),\n\t\taa: () => meridiem(hours, minutes, true, true),\n\t\tz: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: \"shortOffset\" })),\n\t\tzz: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: \"shortOffset\" })),\n\t\tzzz: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: \"shortOffset\" })),\n\t\tzzzz: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: \"longOffset\" }))\n\t};\n\treturn formatStr.replace(REGEX_FORMAT, (match, $1) => {\n\t\tvar _ref, _matches$match;\n\t\treturn (_ref = $1 !== null && $1 !== void 0 ? $1 : (_matches$match = matches[match]) === null || _matches$match === void 0 ? void 0 : _matches$match.call(matches)) !== null && _ref !== void 0 ? _ref : match;\n\t});\n}\nfunction normalizeDate(date) {\n\tif (date === null) return /* @__PURE__ */ new Date(NaN);\n\tif (date === void 0) return /* @__PURE__ */ new Date();\n\tif (date instanceof Date) return new Date(date);\n\tif (typeof date === \"string\" && !/Z$/i.test(date)) {\n\t\tconst d = date.match(REGEX_PARSE);\n\t\tif (d) {\n\t\t\tconst m = d[2] - 1 || 0;\n\t\t\tconst ms = (d[7] || \"0\").substring(0, 3);\n\t\t\treturn new Date(d[1], m, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, ms);\n\t\t}\n\t}\n\treturn new Date(date);\n}\n/**\n* Get the formatted date according to the string of tokens passed in.\n*\n* @see https://vueuse.org/useDateFormat\n* @param date - The date to format, can either be a `Date` object, a timestamp, or a string\n* @param formatStr - The combination of tokens to format the date\n* @param options - UseDateFormatOptions\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useDateFormat(date, formatStr = \"HH:mm:ss\", options = {}) {\n\treturn computed(() => formatDate(normalizeDate(toValue(date)), toValue(formatStr), options));\n}\n//#endregion\n//#region useIntervalFn/index.ts\n/**\n* Wrapper for `setInterval` with controls\n*\n* @see https://vueuse.org/useIntervalFn\n* @param cb\n* @param interval\n* @param options\n*/\nfunction useIntervalFn(cb, interval = 1e3, options = {}) {\n\tconst { immediate = true, immediateCallback = false } = options;\n\tlet timer = null;\n\tconst isActive = shallowRef(false);\n\tfunction clean() {\n\t\tif (timer) {\n\t\t\tclearInterval(timer);\n\t\t\ttimer = null;\n\t\t}\n\t}\n\tfunction pause() {\n\t\tisActive.value = false;\n\t\tclean();\n\t}\n\tfunction resume() {\n\t\tconst intervalValue = toValue(interval);\n\t\tif (intervalValue <= 0) return;\n\t\tisActive.value = true;\n\t\tif (immediateCallback) cb();\n\t\tclean();\n\t\tif (isActive.value) timer = setInterval(cb, intervalValue);\n\t}\n\tif (immediate && isClient) resume();\n\tif (isRef(interval) || typeof interval === \"function\") tryOnScopeDispose(watch(interval, () => {\n\t\tif (isActive.value && isClient) resume();\n\t}));\n\ttryOnScopeDispose(pause);\n\treturn {\n\t\tisActive: shallowReadonly(isActive),\n\t\tpause,\n\t\tresume\n\t};\n}\n//#endregion\n//#region useInterval/index.ts\nfunction useInterval(interval = 1e3, options = {}) {\n\tconst { controls: exposeControls = false, immediate = true, callback } = options;\n\tconst counter = shallowRef(0);\n\tconst update = () => counter.value += 1;\n\tconst reset = () => {\n\t\tcounter.value = 0;\n\t};\n\tconst controls = useIntervalFn(callback ? () => {\n\t\tupdate();\n\t\tcallback(counter.value);\n\t} : update, interval, { immediate });\n\tif (exposeControls) return {\n\t\tcounter: shallowReadonly(counter),\n\t\treset,\n\t\t...controls\n\t};\n\telse return shallowReadonly(counter);\n}\n//#endregion\n//#region useLastChanged/index.ts\nfunction useLastChanged(source, options = {}) {\n\tvar _options$initialValue;\n\tconst ms = shallowRef((_options$initialValue = options.initialValue) !== null && _options$initialValue !== void 0 ? _options$initialValue : null);\n\twatch(source, () => ms.value = timestamp(), options);\n\treturn shallowReadonly(ms);\n}\n//#endregion\n//#region useTimeoutFn/index.ts\n/**\n* Wrapper for `setTimeout` with controls.\n*\n* @param cb\n* @param interval\n* @param options\n*/\nfunction useTimeoutFn(cb, interval, options = {}) {\n\tconst { immediate = true, immediateCallback = false } = options;\n\tconst isPending = shallowRef(false);\n\tlet timer;\n\tfunction clear() {\n\t\tif (timer) {\n\t\t\tclearTimeout(timer);\n\t\t\ttimer = void 0;\n\t\t}\n\t}\n\tfunction stop() {\n\t\tisPending.value = false;\n\t\tclear();\n\t}\n\tfunction start(...args) {\n\t\tif (immediateCallback) cb();\n\t\tclear();\n\t\tisPending.value = true;\n\t\ttimer = setTimeout(() => {\n\t\t\tisPending.value = false;\n\t\t\ttimer = void 0;\n\t\t\tcb(...args);\n\t\t}, toValue(interval));\n\t}\n\tif (immediate) {\n\t\tisPending.value = true;\n\t\tif (isClient) start();\n\t}\n\ttryOnScopeDispose(stop);\n\treturn {\n\t\tisPending: shallowReadonly(isPending),\n\t\tstart,\n\t\tstop\n\t};\n}\n//#endregion\n//#region useTimeout/index.ts\nfunction useTimeout(interval = 1e3, options = {}) {\n\tconst { controls: exposeControls = false, callback } = options;\n\tconst controls = useTimeoutFn(callback !== null && callback !== void 0 ? callback : noop, interval, options);\n\tconst ready = computed(() => !controls.isPending.value);\n\tif (exposeControls) return {\n\t\tready,\n\t\t...controls\n\t};\n\telse return ready;\n}\n//#endregion\n//#region useToNumber/index.ts\n/**\n* Reactively convert a string ref to number.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useToNumber(value, options = {}) {\n\tconst { method = \"parseFloat\", radix, nanToZero } = options;\n\treturn computed(() => {\n\t\tlet resolved = toValue(value);\n\t\tif (typeof method === \"function\") resolved = method(resolved);\n\t\telse if (typeof resolved === \"string\") resolved = Number[method](resolved, radix);\n\t\tif (nanToZero && Number.isNaN(resolved)) resolved = 0;\n\t\treturn resolved;\n\t});\n}\n//#endregion\n//#region useToString/index.ts\n/**\n* Reactively convert a ref to string.\n*\n* @see https://vueuse.org/useToString\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useToString(value) {\n\treturn computed(() => `${toValue(value)}`);\n}\n//#endregion\n//#region useToggle/index.ts\n/**\n* A boolean ref with a toggler\n*\n* @see https://vueuse.org/useToggle\n* @param [initialValue]\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useToggle(initialValue = false, options = {}) {\n\tconst { truthyValue = true, falsyValue = false } = options;\n\tconst valueIsRef = isRef(initialValue);\n\tconst _value = shallowRef(initialValue);\n\tfunction toggle(value) {\n\t\tif (arguments.length) {\n\t\t\t_value.value = value;\n\t\t\treturn _value.value;\n\t\t} else {\n\t\t\tconst truthy = toValue(truthyValue);\n\t\t\t_value.value = _value.value === truthy ? toValue(falsyValue) : truthy;\n\t\t\treturn _value.value;\n\t\t}\n\t}\n\tif (valueIsRef) return toggle;\n\telse return [_value, toggle];\n}\n//#endregion\n//#region watchArray/index.ts\n/**\n* Watch for an array with additions and removals.\n*\n* @see https://vueuse.org/watchArray\n*/\nfunction watchArray(source, cb, options) {\n\tlet oldList = (options === null || options === void 0 ? void 0 : options.immediate) ? [] : [...typeof source === \"function\" ? source() : Array.isArray(source) ? source : toValue(source)];\n\treturn watch(source, (newList, _, onCleanup) => {\n\t\tconst oldListRemains = Array.from({ length: oldList.length });\n\t\tconst added = [];\n\t\tfor (const obj of newList) {\n\t\t\tlet found = false;\n\t\t\tfor (let i = 0; i < oldList.length; i++) if (!oldListRemains[i] && obj === oldList[i]) {\n\t\t\t\toldListRemains[i] = true;\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!found) added.push(obj);\n\t\t}\n\t\tconst removed = oldList.filter((_, i) => !oldListRemains[i]);\n\t\tcb(newList, oldList, added, removed, onCleanup);\n\t\toldList = [...newList];\n\t}, options);\n}\n//#endregion\n//#region watchAtMost/index.ts\nfunction watchAtMost(source, cb, options) {\n\tconst { count, ...watchOptions } = options;\n\tconst current = shallowRef(0);\n\tconst { stop, resume, pause } = watchWithFilter(source, (...args) => {\n\t\tcurrent.value += 1;\n\t\tif (current.value >= toValue(count)) nextTick(() => stop());\n\t\tcb(...args);\n\t}, watchOptions);\n\treturn {\n\t\tcount: current,\n\t\tstop,\n\t\tresume,\n\t\tpause\n\t};\n}\n//#endregion\n//#region watchDebounced/index.ts\nfunction watchDebounced(source, cb, options = {}) {\n\tconst { debounce = 0, maxWait = void 0, ...watchOptions } = options;\n\treturn watchWithFilter(source, cb, {\n\t\t...watchOptions,\n\t\teventFilter: debounceFilter(debounce, { maxWait })\n\t});\n}\n/** @deprecated use `watchDebounced` instead */\nconst debouncedWatch = watchDebounced;\n//#endregion\n//#region watchDeep/index.ts\n/**\n* Shorthand for watching value with {deep: true}\n*\n* @see https://vueuse.org/watchDeep\n*/\nfunction watchDeep(source, cb, options) {\n\treturn watch(source, cb, {\n\t\t...options,\n\t\tdeep: true\n\t});\n}\n//#endregion\n//#region watchIgnorable/index.ts\nfunction watchIgnorable(source, cb, options = {}) {\n\tconst { eventFilter = bypassFilter, ...watchOptions } = options;\n\tconst filteredCb = createFilterWrapper(eventFilter, cb);\n\tlet ignoreUpdates;\n\tlet ignorePrevAsyncUpdates;\n\tlet stop;\n\tif (watchOptions.flush === \"sync\") {\n\t\tlet ignore = false;\n\t\tignorePrevAsyncUpdates = () => {};\n\t\tignoreUpdates = (updater) => {\n\t\t\tignore = true;\n\t\t\tupdater();\n\t\t\tignore = false;\n\t\t};\n\t\tstop = watch(source, (...args) => {\n\t\t\tif (!ignore) filteredCb(...args);\n\t\t}, watchOptions);\n\t} else {\n\t\tconst disposables = [];\n\t\tlet ignoreCounter = 0;\n\t\tlet syncCounter = 0;\n\t\tignorePrevAsyncUpdates = () => {\n\t\t\tignoreCounter = syncCounter;\n\t\t};\n\t\tdisposables.push(watch(source, () => {\n\t\t\tsyncCounter++;\n\t\t}, {\n\t\t\t...watchOptions,\n\t\t\tflush: \"sync\"\n\t\t}));\n\t\tignoreUpdates = (updater) => {\n\t\t\tconst syncCounterPrev = syncCounter;\n\t\t\tupdater();\n\t\t\tignoreCounter += syncCounter - syncCounterPrev;\n\t\t};\n\t\tdisposables.push(watch(source, (...args) => {\n\t\t\tconst ignore = ignoreCounter > 0 && ignoreCounter === syncCounter;\n\t\t\tignoreCounter = 0;\n\t\t\tsyncCounter = 0;\n\t\t\tif (ignore) return;\n\t\t\tfilteredCb(...args);\n\t\t}, watchOptions));\n\t\tstop = () => {\n\t\t\tdisposables.forEach((fn) => fn());\n\t\t};\n\t}\n\treturn {\n\t\tstop,\n\t\tignoreUpdates,\n\t\tignorePrevAsyncUpdates\n\t};\n}\n/** @deprecated use `watchIgnorable` instead */\nconst ignorableWatch = watchIgnorable;\n//#endregion\n//#region watchImmediate/index.ts\n/**\n* Shorthand for watching value with {immediate: true}\n*\n* @see https://vueuse.org/watchImmediate\n*/\nfunction watchImmediate(source, cb, options) {\n\treturn watch(source, cb, {\n\t\t...options,\n\t\timmediate: true\n\t});\n}\n//#endregion\n//#region watchOnce/index.ts\n/**\n* Shorthand for watching value with { once: true }\n*\n* @see https://vueuse.org/watchOnce\n*/\nfunction watchOnce(source, cb, options) {\n\treturn watch(source, cb, {\n\t\t...options,\n\t\tonce: true\n\t});\n}\n//#endregion\n//#region watchThrottled/index.ts\nfunction watchThrottled(source, cb, options = {}) {\n\tconst { throttle = 0, trailing = true, leading = true, ...watchOptions } = options;\n\treturn watchWithFilter(source, cb, {\n\t\t...watchOptions,\n\t\teventFilter: throttleFilter(throttle, trailing, leading)\n\t});\n}\n/** @deprecated use `watchThrottled` instead */\nconst throttledWatch = watchThrottled;\n//#endregion\n//#region watchTriggerable/index.ts\nfunction watchTriggerable(source, cb, options = {}) {\n\tlet cleanupFn;\n\tfunction onEffect() {\n\t\tif (!cleanupFn) return;\n\t\tconst fn = cleanupFn;\n\t\tcleanupFn = void 0;\n\t\tfn();\n\t}\n\t/** Register the function `cleanupFn` */\n\tfunction onCleanup(callback) {\n\t\tcleanupFn = callback;\n\t}\n\tconst _cb = (value, oldValue) => {\n\t\tonEffect();\n\t\treturn cb(value, oldValue, onCleanup);\n\t};\n\tconst res = watchIgnorable(source, _cb, options);\n\tconst { ignoreUpdates } = res;\n\tconst trigger = () => {\n\t\tlet res;\n\t\tignoreUpdates(() => {\n\t\t\tres = _cb(getWatchSources(source), getOldValue(source));\n\t\t});\n\t\treturn res;\n\t};\n\treturn {\n\t\t...res,\n\t\ttrigger\n\t};\n}\nfunction getWatchSources(sources) {\n\tif (isReactive(sources)) return sources;\n\tif (Array.isArray(sources)) return sources.map((item) => toValue(item));\n\treturn toValue(sources);\n}\nfunction getOldValue(source) {\n\treturn Array.isArray(source) ? source.map(() => void 0) : void 0;\n}\n//#endregion\n//#region whenever/index.ts\nfunction whenever(source, cb, options) {\n\tconst stop = watch(source, (v, ov, onInvalidate) => {\n\t\tif (v) {\n\t\t\tif (options === null || options === void 0 ? void 0 : options.once) nextTick(() => stop());\n\t\t\tcb(v, ov, onInvalidate);\n\t\t}\n\t}, {\n\t\t...options,\n\t\tonce: false\n\t});\n\treturn stop;\n}\n//#endregion\nexport { assert, autoResetRef, bypassFilter, camelize, clamp, computedEager, computedWithControl, containsProp, controlledComputed, controlledRef, createDisposableDirective, createEventHook, createFilterWrapper, createGlobalState, createInjectionState, createReactiveFn, createRef, createSharedComposable, createSingletonPromise, debounceFilter, debouncedRef, debouncedWatch, eagerComputed, extendRef, formatDate, get, getLifeCycleTarget, hasOwn, hyphenate, identity, ignorableWatch, increaseWithUnit, injectLocal, invoke, isClient, isDef, isDefined, isIOS, isObject, isWorker, makeDestructurable, noop, normalizeDate, notNullish, now, objectEntries, objectOmit, objectPick, pausableFilter, pausableWatch, promiseTimeout, provideLocal, pxValue, rand, reactify, reactifyObject, reactiveComputed, reactiveOmit, reactivePick, refAutoReset, refDebounced, refDefault, refManualReset, refThrottled, refWithControl, set, syncRef, syncRefs, throttleFilter, throttledRef, throttledWatch, timestamp, toArray, toReactive, toRef, toRefs, tryOnBeforeMount, tryOnBeforeUnmount, tryOnMounted, tryOnScopeDispose, tryOnUnmounted, until, useArrayDifference, useArrayEvery, useArrayFilter, useArrayFind, useArrayFindIndex, useArrayFindLast, useArrayIncludes, useArrayJoin, useArrayMap, useArrayReduce, useArraySome, useArrayUnique, useCounter, useDateFormat, useDebounce, useDebounceFn, useInterval, useIntervalFn, useLastChanged, useThrottle, useThrottleFn, useTimeout, useTimeoutFn, useToNumber, useToString, useToggle, watchArray, watchAtMost, watchDebounced, watchDeep, watchIgnorable, watchImmediate, watchOnce, watchPausable, watchThrottled, watchTriggerable, watchWithFilter, whenever };\n","import { bypassFilter, camelize, clamp, computedWithControl, containsProp, createEventHook, createFilterWrapper, createRef, createSingletonPromise, debounceFilter, hasOwn, identity, increaseWithUnit, injectLocal, isClient, isDef, isIOS, isObject, isWorker, makeDestructurable, noop, notNullish, objectEntries, objectOmit, objectPick, pausableFilter, promiseTimeout, provideLocal, pxValue, syncRef, throttleFilter, timestamp, toArray, toRef, toRefs, tryOnMounted, tryOnScopeDispose, tryOnUnmounted, until, useDebounceFn, useIntervalFn, useThrottleFn, useTimeoutFn, watchIgnorable, watchImmediate, watchOnce, watchPausable, watchWithFilter, whenever } from \"@vueuse/shared\";\nimport { Fragment, TransitionGroup, computed, customRef, defineComponent, getCurrentInstance, getCurrentScope, h, hasInjectionContext, inject, isReadonly, isRef, markRaw, nextTick, onBeforeUpdate, onMounted, onUpdated, reactive, readonly, ref, shallowReactive, shallowReadonly, shallowRef, toRaw, toValue, unref, watch, watchEffect } from \"vue\";\nexport * from \"@vueuse/shared\";\n//#region computedAsync/index.ts\nfunction computedAsync(evaluationCallback, initialState, optionsOrRef) {\n\tvar _globalThis$reportErr;\n\tlet options;\n\tif (isRef(optionsOrRef)) options = { evaluating: optionsOrRef };\n\telse options = optionsOrRef || {};\n\tconst { lazy = false, flush = \"sync\", evaluating = void 0, shallow = true, onError = (_globalThis$reportErr = globalThis.reportError) !== null && _globalThis$reportErr !== void 0 ? _globalThis$reportErr : noop } = options;\n\tconst started = shallowRef(!lazy);\n\tconst current = shallow ? shallowRef(initialState) : ref(initialState);\n\tlet counter = 0;\n\twatchEffect(async (onInvalidate) => {\n\t\tif (!started.value) return;\n\t\tcounter++;\n\t\tconst counterAtBeginning = counter;\n\t\tlet hasFinished = false;\n\t\tif (evaluating) Promise.resolve().then(() => {\n\t\t\tevaluating.value = true;\n\t\t});\n\t\ttry {\n\t\t\tconst result = await evaluationCallback((cancelCallback) => {\n\t\t\t\tonInvalidate(() => {\n\t\t\t\t\tif (evaluating) evaluating.value = false;\n\t\t\t\t\tif (!hasFinished) cancelCallback();\n\t\t\t\t});\n\t\t\t});\n\t\t\tif (counterAtBeginning === counter) current.value = result;\n\t\t} catch (e) {\n\t\t\tonError(e);\n\t\t} finally {\n\t\t\tif (evaluating && counterAtBeginning === counter) evaluating.value = false;\n\t\t\thasFinished = true;\n\t\t}\n\t}, { flush });\n\tif (lazy) return computed(() => {\n\t\tstarted.value = true;\n\t\treturn current.value;\n\t});\n\telse return current;\n}\n/** @deprecated use `computedAsync` instead */\nconst asyncComputed = computedAsync;\n//#endregion\n//#region computedInject/index.ts\nfunction computedInject(key, options, defaultSource, treatDefaultAsFactory) {\n\tlet source = inject(key);\n\tif (defaultSource) source = inject(key, defaultSource);\n\tif (treatDefaultAsFactory) source = inject(key, defaultSource, treatDefaultAsFactory);\n\tif (typeof options === \"function\") return computed((oldValue) => options(source, oldValue));\n\telse return computed({\n\t\tget: (oldValue) => options.get(source, oldValue),\n\t\tset: options.set\n\t});\n}\n//#endregion\n//#region createReusableTemplate/index.ts\n/**\n* This function creates `define` and `reuse` components in pair,\n* It also allow to pass a generic to bind with type.\n*\n* @see https://vueuse.org/createReusableTemplate\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction createReusableTemplate(options = {}) {\n\tconst { inheritAttrs = true, name = \"ReusableTemplate\" } = options;\n\tconst render = shallowRef();\n\tconst define = defineComponent({\n\t\tname: `${name}.define`,\n\t\tsetup(_, { slots }) {\n\t\t\treturn () => {\n\t\t\t\trender.value = slots.default;\n\t\t\t};\n\t\t}\n\t});\n\tconst reuse = defineComponent({\n\t\tinheritAttrs,\n\t\tname: `${name}.reuse`,\n\t\tprops: options.props,\n\t\tsetup(props, { attrs, slots }) {\n\t\t\treturn () => {\n\t\t\t\tvar _render$value;\n\t\t\t\tif (!render.value && true) throw new Error(\"[VueUse] Failed to find the definition of reusable template\");\n\t\t\t\tconst vnode = (_render$value = render.value) === null || _render$value === void 0 ? void 0 : _render$value.call(render, {\n\t\t\t\t\t...options.props == null ? keysToCamelKebabCase(attrs) : props,\n\t\t\t\t\t$slots: slots\n\t\t\t\t});\n\t\t\t\treturn inheritAttrs && (vnode === null || vnode === void 0 ? void 0 : vnode.length) === 1 ? vnode[0] : vnode;\n\t\t\t};\n\t\t}\n\t});\n\treturn makeDestructurable({\n\t\tdefine,\n\t\treuse\n\t}, [define, reuse]);\n}\nfunction keysToCamelKebabCase(obj) {\n\tconst newObj = {};\n\tfor (const key in obj) newObj[camelize(key)] = obj[key];\n\treturn newObj;\n}\n//#endregion\n//#region createTemplatePromise/index.ts\n/**\n* Creates a template promise component.\n*\n* @see https://vueuse.org/createTemplatePromise\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction createTemplatePromise(options = {}) {\n\tlet index = 0;\n\tconst instances = ref([]);\n\tfunction create(...args) {\n\t\tconst props = shallowReactive({\n\t\t\tkey: index++,\n\t\t\targs,\n\t\t\tpromise: void 0,\n\t\t\tresolve: () => {},\n\t\t\treject: () => {},\n\t\t\tisResolving: false,\n\t\t\toptions\n\t\t});\n\t\tinstances.value.push(props);\n\t\tprops.promise = new Promise((_resolve, _reject) => {\n\t\t\tprops.resolve = (v) => {\n\t\t\t\tprops.isResolving = true;\n\t\t\t\treturn _resolve(v);\n\t\t\t};\n\t\t\tprops.reject = _reject;\n\t\t}).finally(() => {\n\t\t\tprops.promise = void 0;\n\t\t\tconst index = instances.value.indexOf(props);\n\t\t\tif (index !== -1) instances.value.splice(index, 1);\n\t\t});\n\t\treturn props.promise;\n\t}\n\tfunction start(...args) {\n\t\tif (options.singleton && instances.value.length > 0) return instances.value[0].promise;\n\t\treturn create(...args);\n\t}\n\tconst component = defineComponent((_, { slots }) => {\n\t\tconst renderList = () => instances.value.map((props) => {\n\t\t\tvar _slots$default;\n\t\t\treturn h(Fragment, { key: props.key }, (_slots$default = slots.default) === null || _slots$default === void 0 ? void 0 : _slots$default.call(slots, props));\n\t\t});\n\t\tif (options.transition) return () => h(TransitionGroup, options.transition, renderList);\n\t\treturn renderList;\n\t});\n\tcomponent.start = start;\n\treturn component;\n}\n//#endregion\n//#region createUnrefFn/index.ts\n/**\n* Make a plain function accepting ref and raw values as arguments.\n* Returns the same value the unconverted function returns, with proper typing.\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction createUnrefFn(fn) {\n\treturn function(...args) {\n\t\treturn fn.apply(this, args.map((i) => toValue(i)));\n\t};\n}\n//#endregion\n//#region _configurable.ts\nconst defaultWindow = isClient ? window : void 0;\nconst defaultDocument = isClient ? window.document : void 0;\nconst defaultNavigator = isClient ? window.navigator : void 0;\nconst defaultLocation = isClient ? window.location : void 0;\n//#endregion\n//#region unrefElement/index.ts\n/**\n* Get the dom element of a ref of element or Vue component instance\n*\n* @param elRef\n*/\nfunction unrefElement(elRef) {\n\tvar _$el;\n\tconst plain = toValue(elRef);\n\treturn (_$el = plain === null || plain === void 0 ? void 0 : plain.$el) !== null && _$el !== void 0 ? _$el : plain;\n}\n//#endregion\n//#region useEventListener/index.ts\nfunction useEventListener(...args) {\n\tconst register = (el, event, listener, options) => {\n\t\tel.addEventListener(event, listener, options);\n\t\treturn () => el.removeEventListener(event, listener, options);\n\t};\n\tconst firstParamTargets = computed(() => {\n\t\tconst test = toArray(toValue(args[0])).filter((e) => e != null);\n\t\treturn test.every((e) => typeof e !== \"string\") ? test : void 0;\n\t});\n\treturn watchImmediate(() => {\n\t\tvar _firstParamTargets$va, _firstParamTargets$va2;\n\t\treturn [\n\t\t\t(_firstParamTargets$va = (_firstParamTargets$va2 = firstParamTargets.value) === null || _firstParamTargets$va2 === void 0 ? void 0 : _firstParamTargets$va2.map((e) => unrefElement(e))) !== null && _firstParamTargets$va !== void 0 ? _firstParamTargets$va : [defaultWindow].filter((e) => e != null),\n\t\t\ttoArray(toValue(firstParamTargets.value ? args[1] : args[0])),\n\t\t\ttoArray(unref(firstParamTargets.value ? args[2] : args[1])),\n\t\t\ttoValue(firstParamTargets.value ? args[3] : args[2])\n\t\t];\n\t}, ([raw_targets, raw_events, raw_listeners, raw_options], _, onCleanup) => {\n\t\tif (!(raw_targets === null || raw_targets === void 0 ? void 0 : raw_targets.length) || !(raw_events === null || raw_events === void 0 ? void 0 : raw_events.length) || !(raw_listeners === null || raw_listeners === void 0 ? void 0 : raw_listeners.length)) return;\n\t\tconst optionsClone = isObject(raw_options) ? { ...raw_options } : raw_options;\n\t\tconst cleanups = raw_targets.flatMap((el) => raw_events.flatMap((event) => raw_listeners.map((listener) => register(el, event, listener, optionsClone))));\n\t\tonCleanup(() => {\n\t\t\tcleanups.forEach((fn) => fn());\n\t\t});\n\t}, { flush: \"post\" });\n}\n//#endregion\n//#region onClickOutside/index.ts\nlet _iOSWorkaround = false;\nfunction onClickOutside(target, handler, options = {}) {\n\tconst { window = defaultWindow, ignore = [], capture = true, detectIframe = false, controls = false } = options;\n\tif (!window) return controls ? {\n\t\tstop: noop,\n\t\tcancel: noop,\n\t\ttrigger: noop\n\t} : noop;\n\tif (isIOS && !_iOSWorkaround) {\n\t\t_iOSWorkaround = true;\n\t\tconst listenerOptions = { passive: true };\n\t\tArray.from(window.document.body.children).forEach((el) => el.addEventListener(\"click\", noop, listenerOptions));\n\t\twindow.document.documentElement.addEventListener(\"click\", noop, listenerOptions);\n\t}\n\tlet shouldListen = true;\n\tconst shouldIgnore = (event) => {\n\t\treturn toValue(ignore).some((target) => {\n\t\t\tif (typeof target === \"string\") return Array.from(window.document.querySelectorAll(target)).some((el) => el === event.target || event.composedPath().includes(el));\n\t\t\telse {\n\t\t\t\tconst el = unrefElement(target);\n\t\t\t\treturn el && (event.target === el || event.composedPath().includes(el));\n\t\t\t}\n\t\t});\n\t};\n\t/**\n\t* Determines if the given target has multiple root elements.\n\t* Referenced from: https://github.com/vuejs/test-utils/blob/ccb460be55f9f6be05ab708500a41ec8adf6f4bc/src/vue-wrapper.ts#L21\n\t*/\n\tfunction hasMultipleRoots(target) {\n\t\tconst vm = toValue(target);\n\t\treturn vm && vm.$.subTree.shapeFlag === 16;\n\t}\n\tfunction checkMultipleRoots(target, event) {\n\t\tconst vm = toValue(target);\n\t\tconst children = vm.$.subTree && vm.$.subTree.children;\n\t\tif (children == null || !Array.isArray(children)) return false;\n\t\treturn children.some((child) => child.el === event.target || event.composedPath().includes(child.el));\n\t}\n\tconst listener = (event) => {\n\t\tconst el = unrefElement(target);\n\t\tif (event.target == null) return;\n\t\tif (!(el instanceof Element) && hasMultipleRoots(target) && checkMultipleRoots(target, event)) return;\n\t\tif (!el || el === event.target || event.composedPath().includes(el)) return;\n\t\tif (\"detail\" in event && event.detail === 0) shouldListen = !shouldIgnore(event);\n\t\tif (!shouldListen) {\n\t\t\tshouldListen = true;\n\t\t\treturn;\n\t\t}\n\t\thandler(event);\n\t};\n\tlet isProcessingClick = false;\n\tconst cleanup = [\n\t\tuseEventListener(window, \"click\", (event) => {\n\t\t\tif (!isProcessingClick) {\n\t\t\t\tisProcessingClick = true;\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tisProcessingClick = false;\n\t\t\t\t}, 0);\n\t\t\t\tlistener(event);\n\t\t\t}\n\t\t}, {\n\t\t\tpassive: true,\n\t\t\tcapture\n\t\t}),\n\t\tuseEventListener(window, \"pointerdown\", (e) => {\n\t\t\tconst el = unrefElement(target);\n\t\t\tshouldListen = !shouldIgnore(e) && !!(el && !e.composedPath().includes(el));\n\t\t}, { passive: true }),\n\t\tdetectIframe && useEventListener(window, \"blur\", (event) => {\n\t\t\tsetTimeout(() => {\n\t\t\t\tconst el = unrefElement(target);\n\t\t\t\tlet activeEl = window.document.activeElement;\n\t\t\t\twhile (activeEl === null || activeEl === void 0 ? void 0 : activeEl.shadowRoot) activeEl = activeEl.shadowRoot.activeElement;\n\t\t\t\tif ((activeEl === null || activeEl === void 0 ? void 0 : activeEl.tagName) === \"IFRAME\" && !(el === null || el === void 0 ? void 0 : el.contains(window.document.activeElement))) handler(event);\n\t\t\t}, 0);\n\t\t}, { passive: true })\n\t].filter(Boolean);\n\tconst stop = () => cleanup.forEach((fn) => fn());\n\tif (controls) return {\n\t\tstop,\n\t\tcancel: () => {\n\t\t\tshouldListen = false;\n\t\t},\n\t\ttrigger: (event) => {\n\t\t\tshouldListen = true;\n\t\t\tlistener(event);\n\t\t\tshouldListen = false;\n\t\t}\n\t};\n\treturn stop;\n}\n//#endregion\n//#region useMounted/index.ts\n/**\n* Mounted state in ref.\n*\n* @see https://vueuse.org/useMounted\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useMounted() {\n\tconst isMounted = shallowRef(false);\n\tconst instance = getCurrentInstance();\n\tif (instance) onMounted(() => {\n\t\tisMounted.value = true;\n\t}, instance);\n\treturn isMounted;\n}\n//#endregion\n//#region useSupported/index.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction useSupported(callback) {\n\tconst isMounted = useMounted();\n\treturn computed(() => {\n\t\tisMounted.value;\n\t\treturn Boolean(callback());\n\t});\n}\n//#endregion\n//#region useMutationObserver/index.ts\n/**\n* Watch for changes being made to the DOM tree.\n*\n* @see https://vueuse.org/useMutationObserver\n* @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver MutationObserver MDN\n* @param target\n* @param callback\n* @param options\n*/\nfunction useMutationObserver(target, callback, options = {}) {\n\tconst { window = defaultWindow, ...mutationOptions } = options;\n\tlet observer;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => window && \"MutationObserver\" in window);\n\tconst cleanup = () => {\n\t\tif (observer) {\n\t\t\tobserver.disconnect();\n\t\t\tobserver = void 0;\n\t\t}\n\t};\n\tconst stopWatch = watch(computed(() => {\n\t\tconst items = toArray(toValue(target)).map(unrefElement).filter(notNullish);\n\t\treturn new Set(items);\n\t}), (newTargets) => {\n\t\tcleanup();\n\t\tif (isSupported.value && newTargets.size) {\n\t\t\tobserver = new MutationObserver(callback);\n\t\t\tnewTargets.forEach((el) => observer.observe(el, mutationOptions));\n\t\t}\n\t}, {\n\t\timmediate: true,\n\t\tflush: \"post\"\n\t});\n\tconst takeRecords = () => {\n\t\treturn observer === null || observer === void 0 ? void 0 : observer.takeRecords();\n\t};\n\tconst stop = () => {\n\t\tstopWatch();\n\t\tcleanup();\n\t};\n\ttryOnScopeDispose(stop);\n\treturn {\n\t\tisSupported,\n\t\tstop,\n\t\ttakeRecords\n\t};\n}\n//#endregion\n//#region onElementRemoval/index.ts\n/**\n* Fires when the element or any element containing it is removed.\n*\n* @param target\n* @param callback\n* @param options\n*/\nfunction onElementRemoval(target, callback, options = {}) {\n\tconst { window = defaultWindow, document = window === null || window === void 0 ? void 0 : window.document, flush = \"sync\" } = options;\n\tif (!window || !document) return noop;\n\tlet stopFn;\n\tconst cleanupAndUpdate = (fn) => {\n\t\tstopFn === null || stopFn === void 0 || stopFn();\n\t\tstopFn = fn;\n\t};\n\tconst stopWatch = watchEffect(() => {\n\t\tconst el = unrefElement(target);\n\t\tif (el) {\n\t\t\tconst { stop } = useMutationObserver(document, (mutationsList) => {\n\t\t\t\tif (mutationsList.map((mutation) => [...mutation.removedNodes]).flat().some((node) => node === el || node.contains(el))) callback(mutationsList);\n\t\t\t}, {\n\t\t\t\twindow,\n\t\t\t\tchildList: true,\n\t\t\t\tsubtree: true\n\t\t\t});\n\t\t\tcleanupAndUpdate(stop);\n\t\t}\n\t}, { flush });\n\tconst stopHandle = () => {\n\t\tstopWatch();\n\t\tcleanupAndUpdate();\n\t};\n\ttryOnScopeDispose(stopHandle);\n\treturn stopHandle;\n}\n//#endregion\n//#region onKeyStroke/index.ts\nfunction createKeyPredicate(keyFilter) {\n\tif (typeof keyFilter === \"function\") return keyFilter;\n\telse if (typeof keyFilter === \"string\") return (event) => event.key === keyFilter;\n\telse if (Array.isArray(keyFilter)) return (event) => keyFilter.includes(event.key);\n\treturn () => true;\n}\nfunction onKeyStroke(...args) {\n\tlet key;\n\tlet handler;\n\tlet options = {};\n\tif (args.length === 3) {\n\t\tkey = args[0];\n\t\thandler = args[1];\n\t\toptions = args[2];\n\t} else if (args.length === 2) if (typeof args[1] === \"object\") {\n\t\tkey = true;\n\t\thandler = args[0];\n\t\toptions = args[1];\n\t} else {\n\t\tkey = args[0];\n\t\thandler = args[1];\n\t}\n\telse {\n\t\tkey = true;\n\t\thandler = args[0];\n\t}\n\tconst { target = defaultWindow, eventName = \"keydown\", passive = false, dedupe = false } = options;\n\tconst predicate = createKeyPredicate(key);\n\tconst listener = (e) => {\n\t\tif (e.repeat && toValue(dedupe)) return;\n\t\tif (predicate(e)) handler(e);\n\t};\n\treturn useEventListener(target, eventName, listener, passive);\n}\n/**\n* Listen to the keydown event of the given key.\n*\n* @see https://vueuse.org/onKeyStroke\n* @param key\n* @param handler\n* @param options\n*/\nfunction onKeyDown(key, handler, options = {}) {\n\treturn onKeyStroke(key, handler, {\n\t\t...options,\n\t\teventName: \"keydown\"\n\t});\n}\n/**\n* Listen to the keypress event of the given key.\n*\n* @see https://vueuse.org/onKeyStroke\n* @param key\n* @param handler\n* @param options\n*/\nfunction onKeyPressed(key, handler, options = {}) {\n\treturn onKeyStroke(key, handler, {\n\t\t...options,\n\t\teventName: \"keypress\"\n\t});\n}\n/**\n* Listen to the keyup event of the given key.\n*\n* @see https://vueuse.org/onKeyStroke\n* @param key\n* @param handler\n* @param options\n*/\nfunction onKeyUp(key, handler, options = {}) {\n\treturn onKeyStroke(key, handler, {\n\t\t...options,\n\t\teventName: \"keyup\"\n\t});\n}\n//#endregion\n//#region onLongPress/index.ts\nconst DEFAULT_DELAY = 500;\nconst DEFAULT_THRESHOLD = 10;\nfunction onLongPress(target, handler, options) {\n\tvar _options$modifiers10, _options$modifiers11;\n\tconst elementRef = computed(() => unrefElement(target));\n\tlet timeout;\n\tlet posStart;\n\tlet startTimestamp;\n\tlet hasLongPressed = false;\n\tfunction clear() {\n\t\tif (timeout) {\n\t\t\tclearTimeout(timeout);\n\t\t\ttimeout = void 0;\n\t\t}\n\t\tposStart = void 0;\n\t\tstartTimestamp = void 0;\n\t\thasLongPressed = false;\n\t}\n\tfunction getDelay(ev) {\n\t\tconst delay = options === null || options === void 0 ? void 0 : options.delay;\n\t\tif (typeof delay === \"function\") return delay(ev);\n\t\treturn delay !== null && delay !== void 0 ? delay : DEFAULT_DELAY;\n\t}\n\tfunction onRelease(ev) {\n\t\tvar _options$modifiers, _options$modifiers2, _options$modifiers3;\n\t\tconst [_startTimestamp, _posStart, _hasLongPressed] = [\n\t\t\tstartTimestamp,\n\t\t\tposStart,\n\t\t\thasLongPressed\n\t\t];\n\t\tclear();\n\t\tif (!(options === null || options === void 0 ? void 0 : options.onMouseUp) || !_posStart || !_startTimestamp) return;\n\t\tif ((options === null || options === void 0 || (_options$modifiers = options.modifiers) === null || _options$modifiers === void 0 ? void 0 : _options$modifiers.self) && ev.target !== elementRef.value) return;\n\t\tif (options === null || options === void 0 || (_options$modifiers2 = options.modifiers) === null || _options$modifiers2 === void 0 ? void 0 : _options$modifiers2.prevent) ev.preventDefault();\n\t\tif (options === null || options === void 0 || (_options$modifiers3 = options.modifiers) === null || _options$modifiers3 === void 0 ? void 0 : _options$modifiers3.stop) ev.stopPropagation();\n\t\tconst dx = ev.x - _posStart.x;\n\t\tconst dy = ev.y - _posStart.y;\n\t\tconst distance = Math.sqrt(dx * dx + dy * dy);\n\t\toptions.onMouseUp(ev.timeStamp - _startTimestamp, distance, _hasLongPressed, ev);\n\t}\n\tfunction onDown(ev) {\n\t\tvar _options$modifiers4, _options$modifiers5, _options$modifiers6;\n\t\tif ((options === null || options === void 0 || (_options$modifiers4 = options.modifiers) === null || _options$modifiers4 === void 0 ? void 0 : _options$modifiers4.self) && ev.target !== elementRef.value) return;\n\t\tclear();\n\t\tif (options === null || options === void 0 || (_options$modifiers5 = options.modifiers) === null || _options$modifiers5 === void 0 ? void 0 : _options$modifiers5.prevent) ev.preventDefault();\n\t\tif (options === null || options === void 0 || (_options$modifiers6 = options.modifiers) === null || _options$modifiers6 === void 0 ? void 0 : _options$modifiers6.stop) ev.stopPropagation();\n\t\tposStart = {\n\t\t\tx: ev.x,\n\t\t\ty: ev.y\n\t\t};\n\t\tstartTimestamp = ev.timeStamp;\n\t\ttimeout = setTimeout(() => {\n\t\t\thasLongPressed = true;\n\t\t\thandler(ev);\n\t\t}, getDelay(ev));\n\t}\n\tfunction onMove(ev) {\n\t\tvar _options$modifiers7, _options$modifiers8, _options$modifiers9, _options$distanceThre;\n\t\tif ((options === null || options === void 0 || (_options$modifiers7 = options.modifiers) === null || _options$modifiers7 === void 0 ? void 0 : _options$modifiers7.self) && ev.target !== elementRef.value) return;\n\t\tif (!posStart || (options === null || options === void 0 ? void 0 : options.distanceThreshold) === false) return;\n\t\tif (options === null || options === void 0 || (_options$modifiers8 = options.modifiers) === null || _options$modifiers8 === void 0 ? void 0 : _options$modifiers8.prevent) ev.preventDefault();\n\t\tif (options === null || options === void 0 || (_options$modifiers9 = options.modifiers) === null || _options$modifiers9 === void 0 ? void 0 : _options$modifiers9.stop) ev.stopPropagation();\n\t\tconst dx = ev.x - posStart.x;\n\t\tconst dy = ev.y - posStart.y;\n\t\tif (Math.sqrt(dx * dx + dy * dy) >= ((_options$distanceThre = options === null || options === void 0 ? void 0 : options.distanceThreshold) !== null && _options$distanceThre !== void 0 ? _options$distanceThre : DEFAULT_THRESHOLD)) clear();\n\t}\n\tconst listenerOptions = {\n\t\tcapture: options === null || options === void 0 || (_options$modifiers10 = options.modifiers) === null || _options$modifiers10 === void 0 ? void 0 : _options$modifiers10.capture,\n\t\tonce: options === null || options === void 0 || (_options$modifiers11 = options.modifiers) === null || _options$modifiers11 === void 0 ? void 0 : _options$modifiers11.once\n\t};\n\tconst cleanup = [\n\t\tuseEventListener(elementRef, \"pointerdown\", onDown, listenerOptions),\n\t\tuseEventListener(elementRef, \"pointermove\", onMove, listenerOptions),\n\t\tuseEventListener(elementRef, [\"pointerup\", \"pointerleave\"], onRelease, listenerOptions)\n\t];\n\tconst stop = () => cleanup.forEach((fn) => fn());\n\treturn stop;\n}\n//#endregion\n//#region onStartTyping/index.ts\nfunction isFocusedElementEditable() {\n\tconst { activeElement, body } = document;\n\tif (!activeElement) return false;\n\tif (activeElement === body) return false;\n\tswitch (activeElement.tagName) {\n\t\tcase \"INPUT\":\n\t\tcase \"TEXTAREA\": return true;\n\t}\n\treturn activeElement.hasAttribute(\"contenteditable\");\n}\nfunction isTypedCharValid({ keyCode, metaKey, ctrlKey, altKey }) {\n\tif (metaKey || ctrlKey || altKey) return false;\n\tif (keyCode >= 48 && keyCode <= 57 || keyCode >= 96 && keyCode <= 105) return true;\n\tif (keyCode >= 65 && keyCode <= 90) return true;\n\treturn false;\n}\n/**\n* Fires when users start typing on non-editable elements.\n*\n* @see https://vueuse.org/onStartTyping\n* @param callback\n* @param options\n*/\nfunction onStartTyping(callback, options = {}) {\n\tconst { document = defaultDocument } = options;\n\tconst keydown = (event) => {\n\t\tif (!isFocusedElementEditable() && isTypedCharValid(event)) callback(event);\n\t};\n\tif (document) useEventListener(document, \"keydown\", keydown, { passive: true });\n}\n//#endregion\n//#region templateRef/index.ts\n/**\n* @deprecated Use Vue's built-in `useTemplateRef` instead.\n*\n* Shorthand for binding ref to template element.\n*\n* @see https://vueuse.org/templateRef\n* @param key\n* @param initialValue\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction templateRef(key, initialValue = null) {\n\tconst instance = getCurrentInstance();\n\tlet _trigger = () => {};\n\tconst element = customRef((track, trigger) => {\n\t\t_trigger = trigger;\n\t\treturn {\n\t\t\tget() {\n\t\t\t\tvar _instance$proxy$$refs, _instance$proxy;\n\t\t\t\ttrack();\n\t\t\t\treturn (_instance$proxy$$refs = instance === null || instance === void 0 || (_instance$proxy = instance.proxy) === null || _instance$proxy === void 0 ? void 0 : _instance$proxy.$refs[key]) !== null && _instance$proxy$$refs !== void 0 ? _instance$proxy$$refs : initialValue;\n\t\t\t},\n\t\t\tset() {}\n\t\t};\n\t});\n\ttryOnMounted(_trigger);\n\tonUpdated(_trigger);\n\treturn element;\n}\n//#endregion\n//#region useActiveElement/index.ts\n/**\n* Reactive `document.activeElement`\n*\n* @see https://vueuse.org/useActiveElement\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useActiveElement(options = {}) {\n\tvar _options$document;\n\tconst { window = defaultWindow, deep = true, triggerOnRemoval = false } = options;\n\tconst document = (_options$document = options.document) !== null && _options$document !== void 0 ? _options$document : window === null || window === void 0 ? void 0 : window.document;\n\tconst getDeepActiveElement = () => {\n\t\tlet element = document === null || document === void 0 ? void 0 : document.activeElement;\n\t\tif (deep) {\n\t\t\tvar _element$shadowRoot;\n\t\t\twhile (element === null || element === void 0 ? void 0 : element.shadowRoot) element = element === null || element === void 0 || (_element$shadowRoot = element.shadowRoot) === null || _element$shadowRoot === void 0 ? void 0 : _element$shadowRoot.activeElement;\n\t\t}\n\t\treturn element;\n\t};\n\tconst activeElement = shallowRef();\n\tconst trigger = () => {\n\t\tactiveElement.value = getDeepActiveElement();\n\t};\n\tif (window) {\n\t\tconst listenerOptions = {\n\t\t\tcapture: true,\n\t\t\tpassive: true\n\t\t};\n\t\tuseEventListener(window, \"blur\", (event) => {\n\t\t\tif (event.relatedTarget !== null) return;\n\t\t\ttrigger();\n\t\t}, listenerOptions);\n\t\tuseEventListener(window, \"focus\", trigger, listenerOptions);\n\t}\n\tif (triggerOnRemoval) onElementRemoval(activeElement, trigger, { document });\n\ttrigger();\n\treturn activeElement;\n}\n//#endregion\n//#region useRafFn/index.ts\n/**\n* Call function on every `requestAnimationFrame`. With controls of pausing and resuming.\n*\n* @see https://vueuse.org/useRafFn\n* @param fn\n* @param options\n*/\nfunction useRafFn(fn, options = {}) {\n\tconst { immediate = true, fpsLimit = null, window = defaultWindow, once = false } = options;\n\tconst isActive = shallowRef(false);\n\tconst intervalLimit = computed(() => {\n\t\tconst limit = toValue(fpsLimit);\n\t\treturn limit ? 1e3 / limit : null;\n\t});\n\tlet previousFrameTimestamp = 0;\n\tlet rafId = null;\n\tfunction loop(timestamp) {\n\t\tif (!isActive.value || !window) return;\n\t\tif (!previousFrameTimestamp) previousFrameTimestamp = timestamp;\n\t\tconst delta = timestamp - previousFrameTimestamp;\n\t\tif (intervalLimit.value && delta < intervalLimit.value) {\n\t\t\trafId = window.requestAnimationFrame(loop);\n\t\t\treturn;\n\t\t}\n\t\tpreviousFrameTimestamp = timestamp;\n\t\tfn({\n\t\t\tdelta,\n\t\t\ttimestamp\n\t\t});\n\t\tif (once) {\n\t\t\tisActive.value = false;\n\t\t\trafId = null;\n\t\t\treturn;\n\t\t}\n\t\trafId = window.requestAnimationFrame(loop);\n\t}\n\tfunction resume() {\n\t\tif (!isActive.value && window) {\n\t\t\tisActive.value = true;\n\t\t\tpreviousFrameTimestamp = 0;\n\t\t\trafId = window.requestAnimationFrame(loop);\n\t\t}\n\t}\n\tfunction pause() {\n\t\tisActive.value = false;\n\t\tif (rafId != null && window) {\n\t\t\twindow.cancelAnimationFrame(rafId);\n\t\t\trafId = null;\n\t\t}\n\t}\n\tif (immediate) resume();\n\ttryOnScopeDispose(pause);\n\treturn {\n\t\tisActive: shallowReadonly(isActive),\n\t\tpause,\n\t\tresume\n\t};\n}\n//#endregion\n//#region useAnimate/index.ts\n/**\n* Reactive Web Animations API\n*\n* @see https://vueuse.org/useAnimate\n* @param target\n* @param keyframes\n* @param options\n*/\nfunction useAnimate(target, keyframes, options) {\n\tlet config;\n\tlet animateOptions;\n\tif (isObject(options)) {\n\t\tconfig = options;\n\t\tanimateOptions = objectOmit(options, [\n\t\t\t\"window\",\n\t\t\t\"immediate\",\n\t\t\t\"commitStyles\",\n\t\t\t\"persist\",\n\t\t\t\"onReady\",\n\t\t\t\"onError\"\n\t\t]);\n\t} else {\n\t\tconfig = { duration: options };\n\t\tanimateOptions = options;\n\t}\n\tconst { window = defaultWindow, immediate = true, commitStyles, persist, playbackRate: _playbackRate = 1, onReady, onError = (e) => {\n\t\tconsole.error(e);\n\t} } = config;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => window && HTMLElement && \"animate\" in HTMLElement.prototype);\n\tconst animate = shallowRef(void 0);\n\tconst store = shallowReactive({\n\t\tstartTime: null,\n\t\tcurrentTime: null,\n\t\ttimeline: null,\n\t\tplaybackRate: _playbackRate,\n\t\tpending: false,\n\t\tplayState: immediate ? \"idle\" : \"paused\",\n\t\treplaceState: \"active\"\n\t});\n\tconst pending = computed(() => store.pending);\n\tconst playState = computed(() => store.playState);\n\tconst replaceState = computed(() => store.replaceState);\n\tconst startTime = computed({\n\t\tget() {\n\t\t\treturn store.startTime;\n\t\t},\n\t\tset(value) {\n\t\t\tstore.startTime = value;\n\t\t\tif (animate.value) animate.value.startTime = value;\n\t\t}\n\t});\n\tconst currentTime = computed({\n\t\tget() {\n\t\t\treturn store.currentTime;\n\t\t},\n\t\tset(value) {\n\t\t\tstore.currentTime = value;\n\t\t\tif (animate.value) {\n\t\t\t\tanimate.value.currentTime = value;\n\t\t\t\tsyncResume();\n\t\t\t}\n\t\t}\n\t});\n\tconst timeline = computed({\n\t\tget() {\n\t\t\treturn store.timeline;\n\t\t},\n\t\tset(value) {\n\t\t\tstore.timeline = value;\n\t\t\tif (animate.value) animate.value.timeline = value;\n\t\t}\n\t});\n\tconst playbackRate = computed({\n\t\tget() {\n\t\t\treturn store.playbackRate;\n\t\t},\n\t\tset(value) {\n\t\t\tstore.playbackRate = value;\n\t\t\tif (animate.value) animate.value.playbackRate = value;\n\t\t}\n\t});\n\tconst play = () => {\n\t\tif (animate.value) try {\n\t\t\tanimate.value.play();\n\t\t\tsyncResume();\n\t\t} catch (e) {\n\t\t\tsyncPause();\n\t\t\tonError(e);\n\t\t}\n\t\telse update();\n\t};\n\tconst pause = () => {\n\t\ttry {\n\t\t\tvar _animate$value;\n\t\t\t(_animate$value = animate.value) === null || _animate$value === void 0 || _animate$value.pause();\n\t\t\tsyncPause();\n\t\t} catch (e) {\n\t\t\tonError(e);\n\t\t}\n\t};\n\tconst reverse = () => {\n\t\tif (!animate.value) update();\n\t\ttry {\n\t\t\tvar _animate$value2;\n\t\t\t(_animate$value2 = animate.value) === null || _animate$value2 === void 0 || _animate$value2.reverse();\n\t\t\tsyncResume();\n\t\t} catch (e) {\n\t\t\tsyncPause();\n\t\t\tonError(e);\n\t\t}\n\t};\n\tconst finish = () => {\n\t\ttry {\n\t\t\tvar _animate$value3;\n\t\t\t(_animate$value3 = animate.value) === null || _animate$value3 === void 0 || _animate$value3.finish();\n\t\t\tsyncPause();\n\t\t} catch (e) {\n\t\t\tonError(e);\n\t\t}\n\t};\n\tconst cancel = () => {\n\t\ttry {\n\t\t\tvar _animate$value4;\n\t\t\t(_animate$value4 = animate.value) === null || _animate$value4 === void 0 || _animate$value4.cancel();\n\t\t\tsyncPause();\n\t\t} catch (e) {\n\t\t\tonError(e);\n\t\t}\n\t};\n\twatch(() => unrefElement(target), (el) => {\n\t\tif (el) update(true);\n\t\telse animate.value = void 0;\n\t});\n\twatch(() => keyframes, (value) => {\n\t\tif (animate.value) {\n\t\t\tupdate();\n\t\t\tconst targetEl = unrefElement(target);\n\t\t\tif (targetEl) animate.value.effect = new KeyframeEffect(targetEl, toValue(value), animateOptions);\n\t\t}\n\t}, { deep: true });\n\ttryOnMounted(() => update(true), false);\n\ttryOnScopeDispose(cancel);\n\tfunction update(init) {\n\t\tconst el = unrefElement(target);\n\t\tif (!isSupported.value || !el) return;\n\t\tif (!animate.value) animate.value = el.animate(toValue(keyframes), animateOptions);\n\t\tif (persist) animate.value.persist();\n\t\tif (_playbackRate !== 1) animate.value.playbackRate = _playbackRate;\n\t\tif (init && !immediate) animate.value.pause();\n\t\telse syncResume();\n\t\tonReady === null || onReady === void 0 || onReady(animate.value);\n\t}\n\tconst listenerOptions = { passive: true };\n\tuseEventListener(animate, [\n\t\t\"cancel\",\n\t\t\"finish\",\n\t\t\"remove\"\n\t], syncPause, listenerOptions);\n\tuseEventListener(animate, \"finish\", () => {\n\t\tvar _animate$value5;\n\t\tif (commitStyles) (_animate$value5 = animate.value) === null || _animate$value5 === void 0 || _animate$value5.commitStyles();\n\t}, listenerOptions);\n\tconst { resume: resumeRef, pause: pauseRef } = useRafFn(() => {\n\t\tif (!animate.value) return;\n\t\tstore.pending = animate.value.pending;\n\t\tstore.playState = animate.value.playState;\n\t\tstore.replaceState = animate.value.replaceState;\n\t\tstore.startTime = animate.value.startTime;\n\t\tstore.currentTime = animate.value.currentTime;\n\t\tstore.timeline = animate.value.timeline;\n\t\tstore.playbackRate = animate.value.playbackRate;\n\t}, { immediate: false });\n\tfunction syncResume() {\n\t\tif (isSupported.value) resumeRef();\n\t}\n\tfunction syncPause() {\n\t\tif (isSupported.value && window) window.requestAnimationFrame(pauseRef);\n\t}\n\treturn {\n\t\tisSupported,\n\t\tanimate,\n\t\tplay,\n\t\tpause,\n\t\treverse,\n\t\tfinish,\n\t\tcancel,\n\t\tpending,\n\t\tplayState,\n\t\treplaceState,\n\t\tstartTime,\n\t\tcurrentTime,\n\t\ttimeline,\n\t\tplaybackRate\n\t};\n}\n//#endregion\n//#region useAsyncQueue/index.ts\n/**\n* Asynchronous queue task controller.\n*\n* @see https://vueuse.org/useAsyncQueue\n* @param tasks\n* @param options\n*/\nfunction useAsyncQueue(tasks, options) {\n\tconst { interrupt = true, onError = noop, onFinished = noop, signal } = options || {};\n\tconst promiseState = {\n\t\taborted: \"aborted\",\n\t\tfulfilled: \"fulfilled\",\n\t\tpending: \"pending\",\n\t\trejected: \"rejected\"\n\t};\n\tconst result = reactive(Array.from(Array.from({ length: tasks.length }), () => ({\n\t\tstate: promiseState.pending,\n\t\tdata: null\n\t})));\n\tconst activeIndex = shallowRef(-1);\n\tif (!tasks || tasks.length === 0) {\n\t\tonFinished();\n\t\treturn {\n\t\t\tactiveIndex,\n\t\t\tresult\n\t\t};\n\t}\n\tfunction updateResult(state, res) {\n\t\tactiveIndex.value++;\n\t\tresult[activeIndex.value].data = res;\n\t\tresult[activeIndex.value].state = state;\n\t}\n\ttasks.reduce((prev, curr) => {\n\t\treturn prev.then((prevRes) => {\n\t\t\tvar _result$activeIndex$v;\n\t\t\tif (signal === null || signal === void 0 ? void 0 : signal.aborted) {\n\t\t\t\tupdateResult(promiseState.aborted, /* @__PURE__ */ new Error(\"aborted\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (((_result$activeIndex$v = result[activeIndex.value]) === null || _result$activeIndex$v === void 0 ? void 0 : _result$activeIndex$v.state) === promiseState.rejected && interrupt) {\n\t\t\t\tonFinished();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst done = curr(prevRes).then((currentRes) => {\n\t\t\t\tupdateResult(promiseState.fulfilled, currentRes);\n\t\t\t\tif (activeIndex.value === tasks.length - 1) onFinished();\n\t\t\t\treturn currentRes;\n\t\t\t});\n\t\t\tif (!signal) return done;\n\t\t\treturn Promise.race([done, whenAborted(signal)]);\n\t\t}).catch((e) => {\n\t\t\tif (signal === null || signal === void 0 ? void 0 : signal.aborted) {\n\t\t\t\tupdateResult(promiseState.aborted, e);\n\t\t\t\treturn e;\n\t\t\t}\n\t\t\tupdateResult(promiseState.rejected, e);\n\t\t\tonError();\n\t\t\tif (activeIndex.value === tasks.length - 1) onFinished();\n\t\t\treturn e;\n\t\t});\n\t}, Promise.resolve());\n\treturn {\n\t\tactiveIndex,\n\t\tresult\n\t};\n}\nfunction whenAborted(signal) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst error = /* @__PURE__ */ new Error(\"aborted\");\n\t\tif (signal.aborted) reject(error);\n\t\telse signal.addEventListener(\"abort\", () => reject(error), { once: true });\n\t});\n}\n//#endregion\n//#region useAsyncState/index.ts\n/**\n* Reactive async state. Will not block your setup function and will trigger changes once\n* the promise is ready.\n*\n* @see https://vueuse.org/useAsyncState\n* @param promise         The promise / async function to be resolved\n* @param initialState    The initial state, used until the first evaluation finishes\n* @param options\n*/\nfunction useAsyncState(promise, initialState, options) {\n\tvar _globalThis$reportErr;\n\tconst { immediate = true, delay = 0, onError = (_globalThis$reportErr = globalThis.reportError) !== null && _globalThis$reportErr !== void 0 ? _globalThis$reportErr : noop, onSuccess = noop, resetOnExecute = true, shallow = true, throwError } = options !== null && options !== void 0 ? options : {};\n\tconst state = shallow ? shallowRef(initialState) : ref(initialState);\n\tconst isReady = shallowRef(false);\n\tconst isLoading = shallowRef(false);\n\tconst error = shallowRef(void 0);\n\tlet executionsCount = 0;\n\tasync function execute(delay = 0, ...args) {\n\t\tconst executionId = executionsCount += 1;\n\t\tif (resetOnExecute) state.value = toValue(initialState);\n\t\terror.value = void 0;\n\t\tisReady.value = false;\n\t\tisLoading.value = true;\n\t\tif (delay > 0) await promiseTimeout(delay);\n\t\tconst _promise = typeof promise === \"function\" ? promise(...args) : promise;\n\t\ttry {\n\t\t\tconst data = await _promise;\n\t\t\tif (executionId === executionsCount) {\n\t\t\t\tstate.value = data;\n\t\t\t\tisReady.value = true;\n\t\t\t}\n\t\t\tonSuccess(data);\n\t\t\treturn data;\n\t\t} catch (e) {\n\t\t\tif (executionId === executionsCount) error.value = e;\n\t\t\tonError(e);\n\t\t\tif (throwError) throw e;\n\t\t} finally {\n\t\t\tif (executionId === executionsCount) isLoading.value = false;\n\t\t}\n\t}\n\tif (immediate) execute(delay);\n\tconst shell = {\n\t\tstate,\n\t\tisReady,\n\t\tisLoading,\n\t\terror,\n\t\texecute,\n\t\texecuteImmediate: (...args) => execute(0, ...args)\n\t};\n\tfunction waitUntilIsLoaded() {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tuntil(isLoading).toBe(false).then(() => resolve(shell)).catch(reject);\n\t\t});\n\t}\n\treturn {\n\t\t...shell,\n\t\tthen(onFulfilled, onRejected) {\n\t\t\treturn waitUntilIsLoaded().then(onFulfilled, onRejected);\n\t\t}\n\t};\n}\n//#endregion\n//#region useBase64/serialization.ts\nconst defaults = {\n\tarray: (v) => JSON.stringify(v),\n\tobject: (v) => JSON.stringify(v),\n\tset: (v) => JSON.stringify(Array.from(v)),\n\tmap: (v) => JSON.stringify(Object.fromEntries(v)),\n\tnull: () => \"\"\n};\nfunction getDefaultSerialization(target) {\n\tif (!target) return defaults.null;\n\tif (target instanceof Map) return defaults.map;\n\telse if (target instanceof Set) return defaults.set;\n\telse if (Array.isArray(target)) return defaults.array;\n\telse return defaults.object;\n}\n//#endregion\n//#region useBase64/index.ts\nfunction useBase64(target, options) {\n\tconst base64 = shallowRef(\"\");\n\tconst promise = shallowRef();\n\tfunction execute() {\n\t\tif (!isClient) return;\n\t\tpromise.value = new Promise((resolve, reject) => {\n\t\t\ttry {\n\t\t\t\tconst _target = toValue(target);\n\t\t\t\tif (_target == null) resolve(\"\");\n\t\t\t\telse if (typeof _target === \"string\") resolve(blobToBase64(new Blob([_target], { type: \"text/plain\" })));\n\t\t\t\telse if (_target instanceof Blob) resolve(blobToBase64(_target));\n\t\t\t\telse if (_target instanceof ArrayBuffer) resolve(window.btoa(String.fromCharCode(...new Uint8Array(_target))));\n\t\t\t\telse if (_target instanceof HTMLCanvasElement) resolve(_target.toDataURL(options === null || options === void 0 ? void 0 : options.type, options === null || options === void 0 ? void 0 : options.quality));\n\t\t\t\telse if (_target instanceof HTMLImageElement) {\n\t\t\t\t\tconst img = _target.cloneNode(false);\n\t\t\t\t\timg.crossOrigin = \"Anonymous\";\n\t\t\t\t\timgLoaded(img).then(() => {\n\t\t\t\t\t\tconst canvas = document.createElement(\"canvas\");\n\t\t\t\t\t\tconst ctx = canvas.getContext(\"2d\");\n\t\t\t\t\t\tcanvas.width = img.width;\n\t\t\t\t\t\tcanvas.height = img.height;\n\t\t\t\t\t\tctx.drawImage(img, 0, 0, canvas.width, canvas.height);\n\t\t\t\t\t\tresolve(canvas.toDataURL(options === null || options === void 0 ? void 0 : options.type, options === null || options === void 0 ? void 0 : options.quality));\n\t\t\t\t\t}).catch(reject);\n\t\t\t\t} else if (typeof _target === \"object\") {\n\t\t\t\t\tconst serialized = ((options === null || options === void 0 ? void 0 : options.serializer) || getDefaultSerialization(_target))(_target);\n\t\t\t\t\treturn resolve(blobToBase64(new Blob([serialized], { type: \"application/json\" })));\n\t\t\t\t} else reject(/* @__PURE__ */ new Error(\"target is unsupported types\"));\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t});\n\t\tpromise.value.then((res) => {\n\t\t\tbase64.value = (options === null || options === void 0 ? void 0 : options.dataUrl) === false ? res.replace(/^data:.*?;base64,/, \"\") : res;\n\t\t});\n\t\treturn promise.value;\n\t}\n\tif (isRef(target) || typeof target === \"function\") watch(target, execute, { immediate: true });\n\telse execute();\n\treturn {\n\t\tbase64,\n\t\tpromise,\n\t\texecute\n\t};\n}\nfunction imgLoaded(img) {\n\treturn new Promise((resolve, reject) => {\n\t\tif (!img.complete) {\n\t\t\timg.onload = () => {\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\timg.onerror = reject;\n\t\t} else resolve();\n\t});\n}\nfunction blobToBase64(blob) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst fr = new FileReader();\n\t\tfr.onload = (e) => {\n\t\t\tresolve(e.target.result);\n\t\t};\n\t\tfr.onerror = reject;\n\t\tfr.readAsDataURL(blob);\n\t});\n}\n//#endregion\n//#region useBattery/index.ts\n/**\n* Reactive Battery Status API.\n*\n* @see https://vueuse.org/useBattery\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useBattery(options = {}) {\n\tconst { navigator = defaultNavigator } = options;\n\tconst events = [\n\t\t\"chargingchange\",\n\t\t\"chargingtimechange\",\n\t\t\"dischargingtimechange\",\n\t\t\"levelchange\"\n\t];\n\tconst isSupported = /* @__PURE__ */ useSupported(() => navigator && \"getBattery\" in navigator && typeof navigator.getBattery === \"function\");\n\tconst charging = shallowRef(false);\n\tconst chargingTime = shallowRef(0);\n\tconst dischargingTime = shallowRef(0);\n\tconst level = shallowRef(1);\n\tlet battery;\n\tfunction updateBatteryInfo() {\n\t\tcharging.value = this.charging;\n\t\tchargingTime.value = this.chargingTime || 0;\n\t\tdischargingTime.value = this.dischargingTime || 0;\n\t\tlevel.value = this.level;\n\t}\n\tif (isSupported.value) navigator.getBattery().then((_battery) => {\n\t\tbattery = _battery;\n\t\tupdateBatteryInfo.call(battery);\n\t\tuseEventListener(battery, events, updateBatteryInfo, { passive: true });\n\t});\n\treturn {\n\t\tisSupported,\n\t\tcharging,\n\t\tchargingTime,\n\t\tdischargingTime,\n\t\tlevel\n\t};\n}\n//#endregion\n//#region useBluetooth/index.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction useBluetooth(options) {\n\tlet { acceptAllDevices = false } = options || {};\n\tconst { filters = void 0, optionalServices = void 0, navigator = defaultNavigator } = options || {};\n\tconst isSupported = /* @__PURE__ */ useSupported(() => navigator && \"bluetooth\" in navigator);\n\tconst device = shallowRef();\n\tconst error = shallowRef(null);\n\twatch(device, () => {\n\t\tconnectToBluetoothGATTServer();\n\t});\n\tasync function requestDevice() {\n\t\tif (!isSupported.value) return;\n\t\terror.value = null;\n\t\tif (filters && filters.length > 0) acceptAllDevices = false;\n\t\ttry {\n\t\t\tdevice.value = await (navigator === null || navigator === void 0 ? void 0 : navigator.bluetooth.requestDevice({\n\t\t\t\tacceptAllDevices,\n\t\t\t\tfilters,\n\t\t\t\toptionalServices\n\t\t\t}));\n\t\t} catch (err) {\n\t\t\terror.value = err;\n\t\t}\n\t}\n\tconst server = shallowRef();\n\tconst isConnected = shallowRef(false);\n\tfunction reset() {\n\t\tisConnected.value = false;\n\t\tdevice.value = void 0;\n\t\tserver.value = void 0;\n\t}\n\tasync function connectToBluetoothGATTServer() {\n\t\terror.value = null;\n\t\tif (device.value && device.value.gatt) {\n\t\t\tuseEventListener(device, \"gattserverdisconnected\", reset, { passive: true });\n\t\t\ttry {\n\t\t\t\tserver.value = await device.value.gatt.connect();\n\t\t\t\tisConnected.value = server.value.connected;\n\t\t\t} catch (err) {\n\t\t\t\terror.value = err;\n\t\t\t}\n\t\t}\n\t}\n\ttryOnMounted(() => {\n\t\tvar _device$value$gatt;\n\t\tif (device.value) (_device$value$gatt = device.value.gatt) === null || _device$value$gatt === void 0 || _device$value$gatt.connect();\n\t});\n\ttryOnScopeDispose(() => {\n\t\tvar _device$value$gatt2;\n\t\tif (device.value) (_device$value$gatt2 = device.value.gatt) === null || _device$value$gatt2 === void 0 || _device$value$gatt2.disconnect();\n\t});\n\treturn {\n\t\tisSupported,\n\t\tisConnected: shallowReadonly(isConnected),\n\t\tdevice,\n\t\trequestDevice,\n\t\tserver,\n\t\terror\n\t};\n}\n//#endregion\n//#region useSSRWidth/index.ts\nconst ssrWidthSymbol = Symbol(\"vueuse-ssr-width\");\n/* @__NO_SIDE_EFFECTS__ */\nfunction useSSRWidth() {\n\tconst ssrWidth = hasInjectionContext() ? injectLocal(ssrWidthSymbol, null) : null;\n\treturn typeof ssrWidth === \"number\" ? ssrWidth : void 0;\n}\nfunction provideSSRWidth(width, app) {\n\tif (app !== void 0) app.provide(ssrWidthSymbol, width);\n\telse provideLocal(ssrWidthSymbol, width);\n}\n//#endregion\n//#region useMediaQuery/index.ts\n/**\n* Reactive Media Query.\n*\n* @see https://vueuse.org/useMediaQuery\n* @param query\n* @param options\n*/\nfunction useMediaQuery(query, options = {}) {\n\tconst { window = defaultWindow, ssrWidth = /* @__PURE__ */ useSSRWidth() } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => window && \"matchMedia\" in window && typeof window.matchMedia === \"function\");\n\tconst ssrSupport = shallowRef(typeof ssrWidth === \"number\");\n\tconst mediaQuery = shallowRef();\n\tconst matches = shallowRef(false);\n\tconst handler = (event) => {\n\t\tmatches.value = event.matches;\n\t};\n\twatchEffect(() => {\n\t\tif (ssrSupport.value) {\n\t\t\tssrSupport.value = !isSupported.value;\n\t\t\tmatches.value = toValue(query).split(\",\").some((queryString) => {\n\t\t\t\tconst not = queryString.includes(\"not all\");\n\t\t\t\tconst minWidth = queryString.match(/\\(\\s*min-width:\\s*(-?\\d+(?:\\.\\d*)?[a-z]+\\s*)\\)/);\n\t\t\t\tconst maxWidth = queryString.match(/\\(\\s*max-width:\\s*(-?\\d+(?:\\.\\d*)?[a-z]+\\s*)\\)/);\n\t\t\t\tlet res = Boolean(minWidth || maxWidth);\n\t\t\t\tif (minWidth && res) res = ssrWidth >= pxValue(minWidth[1]);\n\t\t\t\tif (maxWidth && res) res = ssrWidth <= pxValue(maxWidth[1]);\n\t\t\t\treturn not ? !res : res;\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (!isSupported.value) return;\n\t\tmediaQuery.value = window.matchMedia(toValue(query));\n\t\tmatches.value = mediaQuery.value.matches;\n\t});\n\tuseEventListener(mediaQuery, \"change\", handler, { passive: true });\n\treturn computed(() => matches.value);\n}\n//#endregion\n//#region useBreakpoints/breakpoints.ts\n/**\n* Breakpoints from Tailwind V2\n*\n* @see https://tailwindcss.com/docs/breakpoints\n*/\nconst breakpointsTailwind = {\n\t\"sm\": 640,\n\t\"md\": 768,\n\t\"lg\": 1024,\n\t\"xl\": 1280,\n\t\"2xl\": 1536\n};\n/**\n* Breakpoints from Bootstrap V5\n*\n* @see https://getbootstrap.com/docs/5.0/layout/breakpoints\n*/\nconst breakpointsBootstrapV5 = {\n\txs: 0,\n\tsm: 576,\n\tmd: 768,\n\tlg: 992,\n\txl: 1200,\n\txxl: 1400\n};\n/**\n* Breakpoints from Vuetify V2\n*\n* @see https://v2.vuetifyjs.com/en/features/breakpoints/\n*/\nconst breakpointsVuetifyV2 = {\n\txs: 0,\n\tsm: 600,\n\tmd: 960,\n\tlg: 1264,\n\txl: 1904\n};\n/**\n* Breakpoints from Vuetify V3\n*\n* @see https://vuetifyjs.com/en/styles/float/#overview\n*/\nconst breakpointsVuetifyV3 = {\n\txs: 0,\n\tsm: 600,\n\tmd: 960,\n\tlg: 1280,\n\txl: 1920,\n\txxl: 2560\n};\n/**\n* Alias to `breakpointsVuetifyV2`\n*\n* @deprecated explictly use `breakpointsVuetifyV2` or `breakpointsVuetifyV3` instead\n*/\nconst breakpointsVuetify = breakpointsVuetifyV2;\n/**\n* Breakpoints from Ant Design\n*\n* @see https://ant.design/components/layout/#breakpoint-width\n*/\nconst breakpointsAntDesign = {\n\txs: 480,\n\tsm: 576,\n\tmd: 768,\n\tlg: 992,\n\txl: 1200,\n\txxl: 1600\n};\n/**\n* Breakpoints from Quasar V2\n*\n* @see https://quasar.dev/style/breakpoints\n*/\nconst breakpointsQuasar = {\n\txs: 0,\n\tsm: 600,\n\tmd: 1024,\n\tlg: 1440,\n\txl: 1920\n};\n/**\n* Sematic Breakpoints\n*/\nconst breakpointsSematic = {\n\tmobileS: 320,\n\tmobileM: 375,\n\tmobileL: 425,\n\ttablet: 768,\n\tlaptop: 1024,\n\tlaptopL: 1440,\n\tdesktop4K: 2560\n};\n/**\n* Breakpoints from Master CSS\n*\n* @see https://docs.master.co/css/breakpoints\n*/\nconst breakpointsMasterCss = {\n\t\"3xs\": 360,\n\t\"2xs\": 480,\n\t\"xs\": 600,\n\t\"sm\": 768,\n\t\"md\": 1024,\n\t\"lg\": 1280,\n\t\"xl\": 1440,\n\t\"2xl\": 1600,\n\t\"3xl\": 1920,\n\t\"4xl\": 2560\n};\n/**\n* Breakpoints from PrimeFlex\n*\n* @see https://primeflex.org/installation\n*/\nconst breakpointsPrimeFlex = {\n\tsm: 576,\n\tmd: 768,\n\tlg: 992,\n\txl: 1200\n};\n/**\n* Breakpoints from ElementUI/ElementPlus\n*\n* @see https://element.eleme.io/#/en-US/component/layout\n* @see https://element-plus.org/en-US/component/layout.html\n*/\nconst breakpointsElement = {\n\txs: 0,\n\tsm: 768,\n\tmd: 992,\n\tlg: 1200,\n\txl: 1920\n};\n//#endregion\n//#region useBreakpoints/index.ts\n/**\n* Reactively viewport breakpoints\n*\n* @see https://vueuse.org/useBreakpoints\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useBreakpoints(breakpoints, options = {}) {\n\tfunction getValue(k, delta) {\n\t\tlet v = toValue(breakpoints[toValue(k)]);\n\t\tif (delta != null) v = increaseWithUnit(v, delta);\n\t\tif (typeof v === \"number\") v = `${v}px`;\n\t\treturn v;\n\t}\n\tconst { window = defaultWindow, strategy = \"min-width\", ssrWidth = /* @__PURE__ */ useSSRWidth() } = options;\n\tconst ssrSupport = typeof ssrWidth === \"number\";\n\tconst mounted = ssrSupport ? shallowRef(false) : { value: true };\n\tif (ssrSupport) tryOnMounted(() => mounted.value = !!window);\n\tfunction match(query, size) {\n\t\tif (!mounted.value && ssrSupport) return query === \"min\" ? ssrWidth >= pxValue(size) : ssrWidth <= pxValue(size);\n\t\tif (!window) return false;\n\t\treturn window.matchMedia(`(${query}-width: ${size})`).matches;\n\t}\n\tconst greaterOrEqual = (k) => {\n\t\treturn useMediaQuery(() => `(min-width: ${getValue(k)})`, options);\n\t};\n\tconst smallerOrEqual = (k) => {\n\t\treturn useMediaQuery(() => `(max-width: ${getValue(k)})`, options);\n\t};\n\tconst shortcutMethods = Object.keys(breakpoints).reduce((shortcuts, k) => {\n\t\tObject.defineProperty(shortcuts, k, {\n\t\t\tget: () => strategy === \"min-width\" ? greaterOrEqual(k) : smallerOrEqual(k),\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true\n\t\t});\n\t\treturn shortcuts;\n\t}, {});\n\tfunction current() {\n\t\tconst points = Object.keys(breakpoints).map((k) => [\n\t\t\tk,\n\t\t\tshortcutMethods[k],\n\t\t\tpxValue(getValue(k))\n\t\t]).sort((a, b) => a[2] - b[2]);\n\t\treturn computed(() => points.filter(([, v]) => v.value).map(([k]) => k));\n\t}\n\treturn Object.assign(shortcutMethods, {\n\t\tgreaterOrEqual,\n\t\tsmallerOrEqual,\n\t\tgreater(k) {\n\t\t\treturn useMediaQuery(() => `(min-width: ${getValue(k, .1)})`, options);\n\t\t},\n\t\tsmaller(k) {\n\t\t\treturn useMediaQuery(() => `(max-width: ${getValue(k, -.1)})`, options);\n\t\t},\n\t\tbetween(a, b) {\n\t\t\treturn useMediaQuery(() => `(min-width: ${getValue(a)}) and (max-width: ${getValue(b, -.1)})`, options);\n\t\t},\n\t\tisGreater(k) {\n\t\t\treturn match(\"min\", getValue(k, .1));\n\t\t},\n\t\tisGreaterOrEqual(k) {\n\t\t\treturn match(\"min\", getValue(k));\n\t\t},\n\t\tisSmaller(k) {\n\t\t\treturn match(\"max\", getValue(k, -.1));\n\t\t},\n\t\tisSmallerOrEqual(k) {\n\t\t\treturn match(\"max\", getValue(k));\n\t\t},\n\t\tisInBetween(a, b) {\n\t\t\treturn match(\"min\", getValue(a)) && match(\"max\", getValue(b, -.1));\n\t\t},\n\t\tcurrent,\n\t\tactive() {\n\t\t\tconst bps = current();\n\t\t\treturn computed(() => bps.value.length === 0 ? \"\" : bps.value.at(strategy === \"min-width\" ? -1 : 0));\n\t\t}\n\t});\n}\n//#endregion\n//#region useBroadcastChannel/index.ts\n/**\n* Reactive BroadcastChannel\n*\n* @see https://vueuse.org/useBroadcastChannel\n* @see https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel\n* @param options\n*\n*/\nfunction useBroadcastChannel(options) {\n\tconst { name, window = defaultWindow } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => window && \"BroadcastChannel\" in window);\n\tconst isClosed = shallowRef(false);\n\tconst channel = shallowRef();\n\tconst data = shallowRef();\n\tconst error = shallowRef(null);\n\tconst post = (data) => {\n\t\tif (channel.value) channel.value.postMessage(data);\n\t};\n\tconst close = () => {\n\t\tif (channel.value) channel.value.close();\n\t\tisClosed.value = true;\n\t};\n\tif (isSupported.value) tryOnMounted(() => {\n\t\terror.value = null;\n\t\tchannel.value = new BroadcastChannel(name);\n\t\tconst listenerOptions = { passive: true };\n\t\tuseEventListener(channel, \"message\", (e) => {\n\t\t\tdata.value = e.data;\n\t\t}, listenerOptions);\n\t\tuseEventListener(channel, \"messageerror\", (e) => {\n\t\t\terror.value = e;\n\t\t}, listenerOptions);\n\t\tuseEventListener(channel, \"close\", () => {\n\t\t\tisClosed.value = true;\n\t\t}, listenerOptions);\n\t});\n\ttryOnScopeDispose(() => {\n\t\tclose();\n\t});\n\treturn {\n\t\tisSupported,\n\t\tchannel,\n\t\tdata,\n\t\tpost,\n\t\tclose,\n\t\terror,\n\t\tisClosed\n\t};\n}\n//#endregion\n//#region useBrowserLocation/index.ts\nconst WRITABLE_PROPERTIES = [\n\t\"hash\",\n\t\"host\",\n\t\"hostname\",\n\t\"href\",\n\t\"pathname\",\n\t\"port\",\n\t\"protocol\",\n\t\"search\"\n];\n/**\n* Reactive browser location.\n*\n* @see https://vueuse.org/useBrowserLocation\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useBrowserLocation(options = {}) {\n\tconst { window = defaultWindow } = options;\n\tconst refs = Object.fromEntries(WRITABLE_PROPERTIES.map((key) => [key, ref()]));\n\tfor (const [key, ref] of objectEntries(refs)) watch(ref, (value) => {\n\t\tif (!(window === null || window === void 0 ? void 0 : window.location) || window.location[key] === value) return;\n\t\twindow.location[key] = value;\n\t});\n\tconst buildState = (trigger) => {\n\t\tvar _window$location;\n\t\tconst { state, length } = (window === null || window === void 0 ? void 0 : window.history) || {};\n\t\tconst { origin } = (window === null || window === void 0 ? void 0 : window.location) || {};\n\t\tfor (const key of WRITABLE_PROPERTIES) refs[key].value = window === null || window === void 0 || (_window$location = window.location) === null || _window$location === void 0 ? void 0 : _window$location[key];\n\t\treturn reactive({\n\t\t\ttrigger,\n\t\t\tstate,\n\t\t\tlength,\n\t\t\torigin,\n\t\t\t...refs\n\t\t});\n\t};\n\tconst state = ref(buildState(\"load\"));\n\tif (window) {\n\t\tconst listenerOptions = { passive: true };\n\t\tuseEventListener(window, \"popstate\", () => state.value = buildState(\"popstate\"), listenerOptions);\n\t\tuseEventListener(window, \"hashchange\", () => state.value = buildState(\"hashchange\"), listenerOptions);\n\t}\n\treturn state;\n}\n//#endregion\n//#region useCached/index.ts\nfunction useCached(refValue, comparator = (newSourceValue, cachedValue) => newSourceValue === cachedValue, options) {\n\tconst { deepRefs = true, ...watchOptions } = options || {};\n\tconst cachedValue = createRef(refValue.value, deepRefs);\n\twatch(() => refValue.value, (value) => {\n\t\tif (!comparator(value, cachedValue.value)) cachedValue.value = value;\n\t}, watchOptions);\n\treturn cachedValue;\n}\n//#endregion\n//#region usePermission/index.ts\n/**\n* Reactive Permissions API.\n*\n* @see https://vueuse.org/usePermission\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction usePermission(permissionDesc, options = {}) {\n\tconst { controls = false, navigator = defaultNavigator } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => navigator && \"permissions\" in navigator);\n\tconst permissionStatus = shallowRef();\n\tconst desc = typeof permissionDesc === \"string\" ? { name: permissionDesc } : permissionDesc;\n\tconst state = shallowRef();\n\tconst update = () => {\n\t\tvar _permissionStatus$val, _permissionStatus$val2;\n\t\tstate.value = (_permissionStatus$val = (_permissionStatus$val2 = permissionStatus.value) === null || _permissionStatus$val2 === void 0 ? void 0 : _permissionStatus$val2.state) !== null && _permissionStatus$val !== void 0 ? _permissionStatus$val : \"prompt\";\n\t};\n\tuseEventListener(permissionStatus, \"change\", update, { passive: true });\n\tconst query = createSingletonPromise(async () => {\n\t\tif (!isSupported.value) return;\n\t\tif (!permissionStatus.value) try {\n\t\t\tpermissionStatus.value = await navigator.permissions.query(desc);\n\t\t} catch (_unused) {\n\t\t\tpermissionStatus.value = void 0;\n\t\t} finally {\n\t\t\tupdate();\n\t\t}\n\t\tif (controls) return toRaw(permissionStatus.value);\n\t});\n\tquery();\n\tif (controls) return {\n\t\tstate,\n\t\tisSupported,\n\t\tquery\n\t};\n\telse return state;\n}\n//#endregion\n//#region useClipboard/index.ts\nfunction useClipboard(options = {}) {\n\tconst { navigator = defaultNavigator, read = false, source, copiedDuring = 1500, legacy = false } = options;\n\tconst isClipboardApiSupported = /* @__PURE__ */ useSupported(() => navigator && \"clipboard\" in navigator);\n\tconst permissionRead = usePermission(\"clipboard-read\");\n\tconst permissionWrite = usePermission(\"clipboard-write\");\n\tconst isSupported = computed(() => isClipboardApiSupported.value || legacy);\n\tconst text = shallowRef(\"\");\n\tconst copied = shallowRef(false);\n\tconst copyPending = shallowRef(false);\n\tconst timeout = useTimeoutFn(() => copied.value = false, copiedDuring, { immediate: false });\n\tlet lastLegacyId = 0;\n\tasync function updateText() {\n\t\tlet useLegacy = !(isClipboardApiSupported.value && isAllowed(permissionRead.value));\n\t\tif (!useLegacy) try {\n\t\t\ttext.value = await navigator.clipboard.readText();\n\t\t} catch (_unused) {\n\t\t\tuseLegacy = true;\n\t\t}\n\t\tif (useLegacy) text.value = legacyRead();\n\t}\n\tif (isSupported.value && read) useEventListener([\"copy\", \"cut\"], updateText, { passive: true });\n\tasync function copy(value) {\n\t\tconst resolvedValue = value !== null && value !== void 0 ? value : toValue(source);\n\t\tif (isSupported.value && resolvedValue != null) {\n\t\t\tcopyPending.value = true;\n\t\t\tlet useLegacy = !(isClipboardApiSupported.value && isAllowed(permissionWrite.value));\n\t\t\tif (!useLegacy) try {\n\t\t\t\tconst clipboardItem = createClipboardItem(resolvedValue);\n\t\t\t\tawait navigator.clipboard.write([clipboardItem]);\n\t\t\t} catch (_unused2) {\n\t\t\t\tuseLegacy = true;\n\t\t\t}\n\t\t\tif (useLegacy) if (typeof resolvedValue === \"string\") {\n\t\t\t\ttext.value = resolvedValue;\n\t\t\t\tlegacyCopy(resolvedValue);\n\t\t\t} else {\n\t\t\t\tconst currentId = ++lastLegacyId;\n\t\t\t\tconst resolvedText = await resolvedValue();\n\t\t\t\tif (resolvedText != null && currentId === lastLegacyId) {\n\t\t\t\t\ttext.value = resolvedText;\n\t\t\t\t\tlegacyCopy(resolvedText);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcopied.value = true;\n\t\t\ttimeout.start();\n\t\t\tcopyPending.value = false;\n\t\t}\n\t}\n\tfunction createClipboardItem(value) {\n\t\tif (typeof value === \"string\") {\n\t\t\ttext.value = value;\n\t\t\treturn new ClipboardItem({ \"text/plain\": value });\n\t\t} else return new ClipboardItem({ \"text/plain\": value().then((resolvedText = \"\") => {\n\t\t\ttext.value = resolvedText;\n\t\t\treturn new Blob([resolvedText], { type: \"text/plain\" });\n\t\t}) });\n\t}\n\tfunction legacyCopy(value) {\n\t\tconst ta = document.createElement(\"textarea\");\n\t\tta.value = value;\n\t\tta.style.position = \"absolute\";\n\t\tta.style.opacity = \"0\";\n\t\tta.setAttribute(\"readonly\", \"\");\n\t\tdocument.body.appendChild(ta);\n\t\tta.select();\n\t\tdocument.execCommand(\"copy\");\n\t\tta.remove();\n\t}\n\tfunction legacyRead() {\n\t\tvar _document$getSelectio, _document, _document$getSelectio2;\n\t\treturn (_document$getSelectio = (_document = document) === null || _document === void 0 || (_document$getSelectio2 = _document.getSelection) === null || _document$getSelectio2 === void 0 || (_document$getSelectio2 = _document$getSelectio2.call(_document)) === null || _document$getSelectio2 === void 0 ? void 0 : _document$getSelectio2.toString()) !== null && _document$getSelectio !== void 0 ? _document$getSelectio : \"\";\n\t}\n\tfunction isAllowed(status) {\n\t\treturn status === \"granted\" || status === \"prompt\";\n\t}\n\treturn {\n\t\tcopyPending: shallowReadonly(copyPending),\n\t\tisSupported,\n\t\ttext: shallowReadonly(text),\n\t\tcopied: shallowReadonly(copied),\n\t\tcopy\n\t};\n}\n//#endregion\n//#region useClipboardItems/index.ts\nfunction useClipboardItems(options = {}) {\n\tconst { navigator = defaultNavigator, read = false, source, copiedDuring = 1500 } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => navigator && \"clipboard\" in navigator);\n\tconst content = shallowRef([]);\n\tconst copied = shallowRef(false);\n\tconst timeout = useTimeoutFn(() => copied.value = false, copiedDuring, { immediate: false });\n\tfunction updateContent() {\n\t\tif (isSupported.value) navigator.clipboard.read().then((items) => {\n\t\t\tcontent.value = items;\n\t\t});\n\t}\n\tif (isSupported.value && read) useEventListener([\"copy\", \"cut\"], updateContent, { passive: true });\n\tasync function copy(value = toValue(source)) {\n\t\tif (isSupported.value && value != null) {\n\t\t\tawait navigator.clipboard.write(value);\n\t\t\tcontent.value = value;\n\t\t\tcopied.value = true;\n\t\t\ttimeout.start();\n\t\t}\n\t}\n\treturn {\n\t\tisSupported,\n\t\tcontent: shallowReadonly(content),\n\t\tcopied: shallowReadonly(copied),\n\t\tcopy,\n\t\tread: updateContent\n\t};\n}\n//#endregion\n//#region useCloned/index.ts\nfunction cloneFnJSON(source) {\n\treturn JSON.parse(JSON.stringify(source));\n}\nfunction useCloned(source, options = {}) {\n\tconst cloned = ref({});\n\tconst isModified = shallowRef(false);\n\tlet _lastSync = false;\n\tconst { manual, clone = cloneFnJSON, deep = true, immediate = true } = options;\n\twatch(cloned, () => {\n\t\tif (_lastSync) {\n\t\t\t_lastSync = false;\n\t\t\treturn;\n\t\t}\n\t\tisModified.value = true;\n\t}, {\n\t\tdeep: true,\n\t\tflush: \"sync\"\n\t});\n\tfunction sync() {\n\t\t_lastSync = true;\n\t\tisModified.value = false;\n\t\tcloned.value = clone(toValue(source));\n\t}\n\tif (!manual && (isRef(source) || typeof source === \"function\")) watch(source, sync, {\n\t\t...options,\n\t\tdeep,\n\t\timmediate\n\t});\n\telse sync();\n\treturn {\n\t\tcloned,\n\t\tisModified,\n\t\tsync\n\t};\n}\n//#endregion\n//#region ssr-handlers.ts\nconst _global = typeof globalThis !== \"undefined\" ? globalThis : typeof window !== \"undefined\" ? window : typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : {};\nconst globalKey = \"__vueuse_ssr_handlers__\";\nconst handlers = /* @__PURE__ */ getHandlers();\nfunction getHandlers() {\n\tif (!(globalKey in _global)) _global[globalKey] = _global[globalKey] || {};\n\treturn _global[globalKey];\n}\nfunction getSSRHandler(key, fallback) {\n\treturn handlers[key] || fallback;\n}\nfunction setSSRHandler(key, fn) {\n\thandlers[key] = fn;\n}\n//#endregion\n//#region usePreferredDark/index.ts\n/**\n* Reactive dark theme preference.\n*\n* @see https://vueuse.org/usePreferredDark\n* @param [options]\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction usePreferredDark(options) {\n\treturn useMediaQuery(\"(prefers-color-scheme: dark)\", options);\n}\n//#endregion\n//#region useStorage/guess.ts\nfunction guessSerializerType(rawInit) {\n\treturn rawInit == null ? \"any\" : rawInit instanceof Set ? \"set\" : rawInit instanceof Map ? \"map\" : rawInit instanceof Date ? \"date\" : typeof rawInit === \"boolean\" ? \"boolean\" : typeof rawInit === \"string\" ? \"string\" : typeof rawInit === \"object\" ? \"object\" : !Number.isNaN(rawInit) ? \"number\" : \"any\";\n}\n//#endregion\n//#region useStorage/index.ts\nconst StorageSerializers = {\n\tboolean: {\n\t\tread: (v) => v === \"true\",\n\t\twrite: (v) => String(v)\n\t},\n\tobject: {\n\t\tread: (v) => JSON.parse(v),\n\t\twrite: (v) => JSON.stringify(v)\n\t},\n\tnumber: {\n\t\tread: (v) => Number.parseFloat(v),\n\t\twrite: (v) => String(v)\n\t},\n\tany: {\n\t\tread: (v) => v,\n\t\twrite: (v) => String(v)\n\t},\n\tstring: {\n\t\tread: (v) => v,\n\t\twrite: (v) => String(v)\n\t},\n\tmap: {\n\t\tread: (v) => new Map(JSON.parse(v)),\n\t\twrite: (v) => JSON.stringify(Array.from(v.entries()))\n\t},\n\tset: {\n\t\tread: (v) => new Set(JSON.parse(v)),\n\t\twrite: (v) => JSON.stringify(Array.from(v))\n\t},\n\tdate: {\n\t\tread: (v) => new Date(v),\n\t\twrite: (v) => v.toISOString()\n\t}\n};\nconst customStorageEventName = \"vueuse-storage\";\n/**\n* Reactive LocalStorage/SessionStorage.\n*\n* @see https://vueuse.org/useStorage\n*/\nfunction useStorage(key, defaults, storage, options = {}) {\n\tvar _options$serializer;\n\tconst { flush = \"pre\", deep = true, listenToStorageChanges = true, writeDefaults = true, mergeDefaults = false, shallow, window = defaultWindow, eventFilter, onError = (e) => {\n\t\tconsole.error(e);\n\t}, initOnMounted } = options;\n\tconst data = (shallow ? shallowRef : ref)(typeof defaults === \"function\" ? defaults() : defaults);\n\tconst keyComputed = computed(() => toValue(key));\n\tif (!storage) try {\n\t\tstorage = getSSRHandler(\"getDefaultStorage\", () => defaultWindow === null || defaultWindow === void 0 ? void 0 : defaultWindow.localStorage)();\n\t} catch (e) {\n\t\tonError(e);\n\t}\n\tif (!storage) return data;\n\tconst rawInit = toValue(defaults);\n\tconst type = guessSerializerType(rawInit);\n\tconst serializer = (_options$serializer = options.serializer) !== null && _options$serializer !== void 0 ? _options$serializer : StorageSerializers[type];\n\tconst { pause: pauseWatch, resume: resumeWatch } = watchPausable(data, (newValue) => write(newValue), {\n\t\tflush,\n\t\tdeep,\n\t\teventFilter\n\t});\n\twatch(keyComputed, () => update(), { flush });\n\tlet firstMounted = false;\n\tconst onStorageEvent = (ev) => {\n\t\tif (initOnMounted && !firstMounted) return;\n\t\tupdate(ev);\n\t};\n\tconst onStorageCustomEvent = (ev) => {\n\t\tif (initOnMounted && !firstMounted) return;\n\t\tupdateFromCustomEvent(ev);\n\t};\n\t/**\n\t* The custom event is needed for same-document syncing when using custom\n\t* storage backends, but it doesn't work across different documents.\n\t*\n\t* TODO: Consider implementing a BroadcastChannel-based solution that fixes this.\n\t*/\n\tif (window && listenToStorageChanges) if (storage instanceof Storage) useEventListener(window, \"storage\", onStorageEvent, { passive: true });\n\telse useEventListener(window, customStorageEventName, onStorageCustomEvent);\n\tif (initOnMounted) tryOnMounted(() => {\n\t\tfirstMounted = true;\n\t\tupdate();\n\t});\n\telse update();\n\tfunction dispatchWriteEvent(oldValue, newValue) {\n\t\tif (window) {\n\t\t\tconst payload = {\n\t\t\t\tkey: keyComputed.value,\n\t\t\t\toldValue,\n\t\t\t\tnewValue,\n\t\t\t\tstorageArea: storage\n\t\t\t};\n\t\t\twindow.dispatchEvent(storage instanceof Storage ? new StorageEvent(\"storage\", payload) : new CustomEvent(customStorageEventName, { detail: payload }));\n\t\t}\n\t}\n\tfunction write(v) {\n\t\ttry {\n\t\t\tconst oldValue = storage.getItem(keyComputed.value);\n\t\t\tif (v == null) {\n\t\t\t\tdispatchWriteEvent(oldValue, null);\n\t\t\t\tstorage.removeItem(keyComputed.value);\n\t\t\t} else {\n\t\t\t\tconst serialized = serializer.write(v);\n\t\t\t\tif (oldValue !== serialized) {\n\t\t\t\t\tstorage.setItem(keyComputed.value, serialized);\n\t\t\t\t\tdispatchWriteEvent(oldValue, serialized);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tonError(e);\n\t\t}\n\t}\n\tfunction read(event) {\n\t\tconst rawValue = event ? event.newValue : storage.getItem(keyComputed.value);\n\t\tif (rawValue == null) {\n\t\t\tif (writeDefaults && rawInit != null) storage.setItem(keyComputed.value, serializer.write(rawInit));\n\t\t\treturn rawInit;\n\t\t} else if (!event && mergeDefaults) {\n\t\t\tconst value = serializer.read(rawValue);\n\t\t\tif (typeof mergeDefaults === \"function\") return mergeDefaults(value, rawInit);\n\t\t\telse if (type === \"object\" && !Array.isArray(value)) return {\n\t\t\t\t...rawInit,\n\t\t\t\t...value\n\t\t\t};\n\t\t\treturn value;\n\t\t} else if (typeof rawValue !== \"string\") return rawValue;\n\t\telse return serializer.read(rawValue);\n\t}\n\tfunction update(event) {\n\t\tif (event && event.storageArea !== storage) return;\n\t\tif (event && event.key == null) {\n\t\t\tdata.value = rawInit;\n\t\t\treturn;\n\t\t}\n\t\tif (event && event.key !== keyComputed.value) return;\n\t\tpauseWatch();\n\t\ttry {\n\t\t\tconst serializedData = serializer.write(data.value);\n\t\t\tif (event === void 0 || (event === null || event === void 0 ? void 0 : event.newValue) !== serializedData) data.value = read(event);\n\t\t} catch (e) {\n\t\t\tonError(e);\n\t\t} finally {\n\t\t\tif (event) nextTick(resumeWatch);\n\t\t\telse resumeWatch();\n\t\t}\n\t}\n\tfunction updateFromCustomEvent(event) {\n\t\tupdate(event.detail);\n\t}\n\treturn data;\n}\n//#endregion\n//#region useColorMode/index.ts\nconst CSS_DISABLE_TRANS = \"*,*::before,*::after{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}\";\n/**\n* Reactive color mode with auto data persistence.\n*\n* @see https://vueuse.org/useColorMode\n* @param options\n*/\nfunction useColorMode(options = {}) {\n\tconst { selector = \"html\", attribute = \"class\", initialValue = \"auto\", window = defaultWindow, storage, storageKey = \"vueuse-color-scheme\", listenToStorageChanges = true, storageRef, emitAuto, disableTransition = true } = options;\n\tconst modes = {\n\t\tauto: \"\",\n\t\tlight: \"light\",\n\t\tdark: \"dark\",\n\t\t...options.modes || {}\n\t};\n\tconst preferredDark = usePreferredDark({ window });\n\tconst system = computed(() => preferredDark.value ? \"dark\" : \"light\");\n\tconst store = storageRef || (storageKey == null ? toRef(initialValue) : useStorage(storageKey, initialValue, storage, {\n\t\twindow,\n\t\tlistenToStorageChanges\n\t}));\n\tconst state = computed(() => store.value === \"auto\" ? system.value : store.value);\n\tconst updateHTMLAttrs = getSSRHandler(\"updateHTMLAttrs\", (selector, attribute, value) => {\n\t\tconst el = typeof selector === \"string\" ? window === null || window === void 0 ? void 0 : window.document.querySelector(selector) : unrefElement(selector);\n\t\tif (!el) return;\n\t\tconst classesToAdd = /* @__PURE__ */ new Set();\n\t\tconst classesToRemove = /* @__PURE__ */ new Set();\n\t\tlet attributeToChange = null;\n\t\tif (attribute === \"class\") {\n\t\t\tconst current = value.split(/\\s/g);\n\t\t\tObject.values(modes).flatMap((i) => (i || \"\").split(/\\s/g)).filter(Boolean).forEach((v) => {\n\t\t\t\tif (current.includes(v)) classesToAdd.add(v);\n\t\t\t\telse classesToRemove.add(v);\n\t\t\t});\n\t\t} else attributeToChange = {\n\t\t\tkey: attribute,\n\t\t\tvalue\n\t\t};\n\t\tif (classesToAdd.size === 0 && classesToRemove.size === 0 && attributeToChange === null) return;\n\t\tlet style;\n\t\tif (disableTransition) {\n\t\t\tstyle = window.document.createElement(\"style\");\n\t\t\tstyle.appendChild(document.createTextNode(CSS_DISABLE_TRANS));\n\t\t\twindow.document.head.appendChild(style);\n\t\t}\n\t\tfor (const c of classesToAdd) el.classList.add(c);\n\t\tfor (const c of classesToRemove) el.classList.remove(c);\n\t\tif (attributeToChange) el.setAttribute(attributeToChange.key, attributeToChange.value);\n\t\tif (disableTransition) {\n\t\t\twindow.getComputedStyle(style).opacity;\n\t\t\tdocument.head.removeChild(style);\n\t\t}\n\t});\n\tfunction defaultOnChanged(mode) {\n\t\tvar _modes$mode;\n\t\tupdateHTMLAttrs(selector, attribute, (_modes$mode = modes[mode]) !== null && _modes$mode !== void 0 ? _modes$mode : mode);\n\t}\n\tfunction onChanged(mode) {\n\t\tif (options.onChanged) options.onChanged(mode, defaultOnChanged);\n\t\telse defaultOnChanged(mode);\n\t}\n\twatch(state, onChanged, {\n\t\tflush: \"post\",\n\t\timmediate: true\n\t});\n\ttryOnMounted(() => onChanged(state.value));\n\tconst auto = computed({\n\t\tget() {\n\t\t\treturn emitAuto ? store.value : state.value;\n\t\t},\n\t\tset(v) {\n\t\t\tstore.value = v;\n\t\t}\n\t});\n\treturn Object.assign(auto, {\n\t\tstore,\n\t\tsystem,\n\t\tstate\n\t});\n}\n//#endregion\n//#region useConfirmDialog/index.ts\n/**\n* Hooks for creating confirm dialogs. Useful for modal windows, popups and logins.\n*\n* @see https://vueuse.org/useConfirmDialog/\n* @param revealed `boolean` `ref` that handles a modal window\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useConfirmDialog(revealed = shallowRef(false)) {\n\tconst confirmHook = createEventHook();\n\tconst cancelHook = createEventHook();\n\tconst revealHook = createEventHook();\n\tlet _resolve = noop;\n\tconst reveal = (data) => {\n\t\trevealHook.trigger(data);\n\t\trevealed.value = true;\n\t\treturn new Promise((resolve) => {\n\t\t\t_resolve = resolve;\n\t\t});\n\t};\n\tconst confirm = (data) => {\n\t\trevealed.value = false;\n\t\tconfirmHook.trigger(data);\n\t\t_resolve({\n\t\t\tdata,\n\t\t\tisCanceled: false\n\t\t});\n\t};\n\tconst cancel = (data) => {\n\t\trevealed.value = false;\n\t\tcancelHook.trigger(data);\n\t\t_resolve({\n\t\t\tdata,\n\t\t\tisCanceled: true\n\t\t});\n\t};\n\treturn {\n\t\tisRevealed: computed(() => revealed.value),\n\t\treveal,\n\t\tconfirm,\n\t\tcancel,\n\t\tonReveal: revealHook.on,\n\t\tonConfirm: confirmHook.on,\n\t\tonCancel: cancelHook.on\n\t};\n}\n//#endregion\n//#region useCountdown/index.ts\nfunction getDefaultScheduler$8(options) {\n\tif (\"interval\" in options || \"immediate\" in options) {\n\t\tconst { interval = 1e3, immediate = false } = options;\n\t\treturn (cb) => useIntervalFn(cb, interval, { immediate });\n\t}\n\treturn (cb) => useIntervalFn(cb, 1e3, { immediate: false });\n}\n/**\n* Reactive countdown timer in seconds.\n*\n* @param initialCountdown\n* @param options\n*\n* @see https://vueuse.org/useCountdown\n*/\nfunction useCountdown(initialCountdown, options = {}) {\n\tconst remaining = shallowRef(toValue(initialCountdown));\n\tconst { scheduler = getDefaultScheduler$8(options), onTick, onComplete } = options;\n\tconst controls = scheduler(() => {\n\t\tconst value = remaining.value - 1;\n\t\tremaining.value = value < 0 ? 0 : value;\n\t\tonTick === null || onTick === void 0 || onTick();\n\t\tif (remaining.value <= 0) {\n\t\t\tcontrols.pause();\n\t\t\tonComplete === null || onComplete === void 0 || onComplete();\n\t\t}\n\t});\n\tconst reset = (countdown) => {\n\t\tvar _toValue;\n\t\tremaining.value = (_toValue = toValue(countdown)) !== null && _toValue !== void 0 ? _toValue : toValue(initialCountdown);\n\t};\n\tconst stop = () => {\n\t\tcontrols.pause();\n\t\treset();\n\t};\n\tconst resume = () => {\n\t\tif (!controls.isActive.value) {\n\t\t\tif (remaining.value > 0) controls.resume();\n\t\t}\n\t};\n\tconst start = (countdown) => {\n\t\treset(countdown);\n\t\tcontrols.resume();\n\t};\n\treturn {\n\t\tremaining,\n\t\treset,\n\t\tstop,\n\t\tstart,\n\t\tpause: controls.pause,\n\t\tresume,\n\t\tisActive: controls.isActive\n\t};\n}\n//#endregion\n//#region useCssSupports/index.ts\nfunction useCssSupports(...args) {\n\tlet options = {};\n\tif (typeof toValue(args.at(-1)) === \"object\") options = args.pop();\n\tconst [prop, value] = args;\n\tconst { window = defaultWindow, ssrValue = false } = options;\n\tconst isMounted = useMounted();\n\treturn { isSupported: computed(() => {\n\t\tif (!isClient || !isMounted.value) return ssrValue;\n\t\treturn args.length === 2 ? window === null || window === void 0 ? void 0 : window.CSS.supports(toValue(prop), toValue(value)) : window === null || window === void 0 ? void 0 : window.CSS.supports(toValue(prop));\n\t}) };\n}\n//#endregion\n//#region useCssVar/index.ts\n/**\n* Manipulate CSS variables.\n*\n* @see https://vueuse.org/useCssVar\n* @param prop\n* @param target\n* @param options\n*/\nfunction useCssVar(prop, target, options = {}) {\n\tconst { window = defaultWindow, initialValue, observe = false } = options;\n\tconst variable = shallowRef(initialValue);\n\tconst elRef = computed(() => {\n\t\tvar _window$document;\n\t\treturn unrefElement(target) || (window === null || window === void 0 || (_window$document = window.document) === null || _window$document === void 0 ? void 0 : _window$document.documentElement);\n\t});\n\tfunction updateCssVar() {\n\t\tconst key = toValue(prop);\n\t\tconst el = toValue(elRef);\n\t\tif (el && window && key) {\n\t\t\tvar _window$getComputedSt;\n\t\t\tvariable.value = ((_window$getComputedSt = window.getComputedStyle(el).getPropertyValue(key)) === null || _window$getComputedSt === void 0 ? void 0 : _window$getComputedSt.trim()) || variable.value || initialValue;\n\t\t}\n\t}\n\tif (observe) useMutationObserver(elRef, updateCssVar, {\n\t\tattributeFilter: [\"style\", \"class\"],\n\t\twindow\n\t});\n\twatch([elRef, () => toValue(prop)], (_, old) => {\n\t\tif (old[0] && old[1]) old[0].style.removeProperty(old[1]);\n\t\tupdateCssVar();\n\t}, { immediate: true });\n\twatch([variable, elRef], ([val, el]) => {\n\t\tconst raw_prop = toValue(prop);\n\t\tif ((el === null || el === void 0 ? void 0 : el.style) && raw_prop) if (val == null) el.style.removeProperty(raw_prop);\n\t\telse el.style.setProperty(raw_prop, val);\n\t}, { immediate: true });\n\treturn variable;\n}\n//#endregion\n//#region useCurrentElement/index.ts\nfunction useCurrentElement(rootComponent) {\n\tconst vm = getCurrentInstance();\n\tconst currentElement = computedWithControl(() => null, () => rootComponent ? unrefElement(rootComponent) : vm.proxy.$el);\n\tonUpdated(currentElement.trigger);\n\tonMounted(currentElement.trigger);\n\treturn currentElement;\n}\n//#endregion\n//#region useCycleList/index.ts\n/**\n* Cycle through a list of items\n*\n* @see https://vueuse.org/useCycleList\n*/\nfunction useCycleList(list, options) {\n\tconst state = shallowRef(getInitialValue());\n\tconst listRef = toRef(list);\n\tconst index = computed({\n\t\tget() {\n\t\t\tvar _options$fallbackInde;\n\t\t\tconst targetList = listRef.value;\n\t\t\tlet index = (options === null || options === void 0 ? void 0 : options.getIndexOf) ? options.getIndexOf(state.value, targetList) : targetList.indexOf(state.value);\n\t\t\tif (index < 0) index = (_options$fallbackInde = options === null || options === void 0 ? void 0 : options.fallbackIndex) !== null && _options$fallbackInde !== void 0 ? _options$fallbackInde : 0;\n\t\t\treturn index;\n\t\t},\n\t\tset(v) {\n\t\t\tset(v);\n\t\t}\n\t});\n\tfunction set(i) {\n\t\tconst targetList = listRef.value;\n\t\tconst length = targetList.length;\n\t\tconst value = targetList[(i % length + length) % length];\n\t\tstate.value = value;\n\t\treturn value;\n\t}\n\tfunction shift(delta = 1) {\n\t\treturn set(index.value + delta);\n\t}\n\tfunction next(n = 1) {\n\t\treturn shift(n);\n\t}\n\tfunction prev(n = 1) {\n\t\treturn shift(-n);\n\t}\n\tfunction getInitialValue() {\n\t\tvar _toValue, _options$initialValue;\n\t\treturn (_toValue = toValue((_options$initialValue = options === null || options === void 0 ? void 0 : options.initialValue) !== null && _options$initialValue !== void 0 ? _options$initialValue : toValue(list)[0])) !== null && _toValue !== void 0 ? _toValue : void 0;\n\t}\n\twatch(listRef, () => set(index.value));\n\treturn {\n\t\tstate,\n\t\tindex,\n\t\tnext,\n\t\tprev,\n\t\tgo: set\n\t};\n}\n//#endregion\n//#region useDark/index.ts\n/**\n* Reactive dark mode with auto data persistence.\n*\n* @see https://vueuse.org/useDark\n* @param options\n*/\nfunction useDark(options = {}) {\n\tconst { valueDark = \"dark\", valueLight = \"\" } = options;\n\tconst mode = useColorMode({\n\t\t...options,\n\t\tonChanged: (mode, defaultHandler) => {\n\t\t\tvar _options$onChanged;\n\t\t\tif (options.onChanged) (_options$onChanged = options.onChanged) === null || _options$onChanged === void 0 || _options$onChanged.call(options, mode === \"dark\", defaultHandler, mode);\n\t\t\telse defaultHandler(mode);\n\t\t},\n\t\tmodes: {\n\t\t\tdark: valueDark,\n\t\t\tlight: valueLight\n\t\t}\n\t});\n\tconst system = computed(() => mode.system.value);\n\treturn computed({\n\t\tget() {\n\t\t\treturn mode.value === \"dark\";\n\t\t},\n\t\tset(v) {\n\t\t\tconst modeVal = v ? \"dark\" : \"light\";\n\t\t\tif (system.value === modeVal) mode.value = \"auto\";\n\t\t\telse mode.value = modeVal;\n\t\t}\n\t});\n}\n//#endregion\n//#region useManualRefHistory/index.ts\nfunction fnBypass(v) {\n\treturn v;\n}\nfunction fnSetSource(source, value) {\n\treturn source.value = value;\n}\nfunction defaultDump(clone) {\n\treturn clone ? typeof clone === \"function\" ? clone : cloneFnJSON : fnBypass;\n}\nfunction defaultParse(clone) {\n\treturn clone ? typeof clone === \"function\" ? clone : cloneFnJSON : fnBypass;\n}\n/**\n* Track the change history of a ref, also provides undo and redo functionality.\n*\n* @see https://vueuse.org/useManualRefHistory\n* @param source\n* @param options\n*/\nfunction useManualRefHistory(source, options = {}) {\n\tconst { clone = false, dump = defaultDump(clone), parse = defaultParse(clone), setSource = fnSetSource } = options;\n\tfunction _createHistoryRecord() {\n\t\treturn markRaw({\n\t\t\tsnapshot: dump(source.value),\n\t\t\ttimestamp: timestamp()\n\t\t});\n\t}\n\tconst last = ref(_createHistoryRecord());\n\tconst undoStack = ref([]);\n\tconst redoStack = ref([]);\n\tconst _setSource = (record) => {\n\t\tsetSource(source, parse(record.snapshot));\n\t\tlast.value = record;\n\t};\n\tconst commit = () => {\n\t\tundoStack.value.unshift(last.value);\n\t\tlast.value = _createHistoryRecord();\n\t\tif (options.capacity && undoStack.value.length > options.capacity) undoStack.value.splice(options.capacity, Number.POSITIVE_INFINITY);\n\t\tif (redoStack.value.length) redoStack.value.splice(0, redoStack.value.length);\n\t};\n\tconst clear = () => {\n\t\tundoStack.value.splice(0, undoStack.value.length);\n\t\tredoStack.value.splice(0, redoStack.value.length);\n\t};\n\tconst undo = () => {\n\t\tconst state = undoStack.value.shift();\n\t\tif (state) {\n\t\t\tredoStack.value.unshift(last.value);\n\t\t\t_setSource(state);\n\t\t}\n\t};\n\tconst redo = () => {\n\t\tconst state = redoStack.value.shift();\n\t\tif (state) {\n\t\t\tundoStack.value.unshift(last.value);\n\t\t\t_setSource(state);\n\t\t}\n\t};\n\tconst reset = () => {\n\t\t_setSource(last.value);\n\t};\n\treturn {\n\t\tsource,\n\t\tundoStack,\n\t\tredoStack,\n\t\tlast,\n\t\thistory: computed(() => [last.value, ...undoStack.value]),\n\t\tcanUndo: computed(() => undoStack.value.length > 0),\n\t\tcanRedo: computed(() => redoStack.value.length > 0),\n\t\tclear,\n\t\tcommit,\n\t\treset,\n\t\tundo,\n\t\tredo\n\t};\n}\n//#endregion\n//#region useRefHistory/index.ts\n/**\n* Track the change history of a ref, also provides undo and redo functionality.\n*\n* @see https://vueuse.org/useRefHistory\n* @param source\n* @param options\n*/\nfunction useRefHistory(source, options = {}) {\n\tconst { deep = false, flush = \"pre\", eventFilter, shouldCommit = () => true } = options;\n\tconst { eventFilter: composedFilter, pause, resume: resumeTracking, isActive: isTracking } = pausableFilter(eventFilter);\n\tlet lastRawValue = source.value;\n\tconst { ignoreUpdates, ignorePrevAsyncUpdates, stop } = watchIgnorable(source, commit, {\n\t\tdeep,\n\t\tflush,\n\t\teventFilter: composedFilter\n\t});\n\tfunction setSource(source, value) {\n\t\tignorePrevAsyncUpdates();\n\t\tignoreUpdates(() => {\n\t\t\tsource.value = value;\n\t\t\tlastRawValue = value;\n\t\t});\n\t}\n\tconst manualHistory = useManualRefHistory(source, {\n\t\t...options,\n\t\tclone: options.clone || deep,\n\t\tsetSource\n\t});\n\tconst { clear, commit: manualCommit } = manualHistory;\n\tfunction commit() {\n\t\tignorePrevAsyncUpdates();\n\t\tif (!shouldCommit(lastRawValue, source.value)) return;\n\t\tlastRawValue = source.value;\n\t\tmanualCommit();\n\t}\n\tfunction resume(commitNow) {\n\t\tresumeTracking();\n\t\tif (commitNow) commit();\n\t}\n\tfunction batch(fn) {\n\t\tlet canceled = false;\n\t\tconst cancel = () => canceled = true;\n\t\tignoreUpdates(() => {\n\t\t\tfn(cancel);\n\t\t});\n\t\tif (!canceled) commit();\n\t}\n\tfunction dispose() {\n\t\tstop();\n\t\tclear();\n\t}\n\treturn {\n\t\t...manualHistory,\n\t\tisTracking,\n\t\tpause,\n\t\tresume,\n\t\tcommit,\n\t\tbatch,\n\t\tdispose\n\t};\n}\n//#endregion\n//#region useDebouncedRefHistory/index.ts\n/**\n* Shorthand for [useRefHistory](https://vueuse.org/useRefHistory) with debounce filter.\n*\n* @see https://vueuse.org/useDebouncedRefHistory\n* @param source\n* @param options\n*/\nfunction useDebouncedRefHistory(source, options = {}) {\n\tconst filter = options.debounce ? debounceFilter(options.debounce) : void 0;\n\treturn { ...useRefHistory(source, {\n\t\t...options,\n\t\teventFilter: filter\n\t}) };\n}\n//#endregion\n//#region useDeviceMotion/index.ts\n/**\n* Reactive DeviceMotionEvent.\n*\n* @see https://vueuse.org/useDeviceMotion\n* @param options\n*/\nfunction useDeviceMotion(options = {}) {\n\tconst { window = defaultWindow, requestPermissions = false, eventFilter = bypassFilter } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => typeof DeviceMotionEvent !== \"undefined\");\n\tconst requirePermissions = /* @__PURE__ */ useSupported(() => isSupported.value && \"requestPermission\" in DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === \"function\");\n\tconst permissionGranted = shallowRef(false);\n\tconst acceleration = ref({\n\t\tx: null,\n\t\ty: null,\n\t\tz: null\n\t});\n\tconst rotationRate = ref({\n\t\talpha: null,\n\t\tbeta: null,\n\t\tgamma: null\n\t});\n\tconst interval = shallowRef(0);\n\tconst accelerationIncludingGravity = ref({\n\t\tx: null,\n\t\ty: null,\n\t\tz: null\n\t});\n\tfunction init() {\n\t\tif (window) useEventListener(window, \"devicemotion\", createFilterWrapper(eventFilter, (event) => {\n\t\t\tvar _event$acceleration, _event$acceleration2, _event$acceleration3, _event$accelerationIn, _event$accelerationIn2, _event$accelerationIn3, _event$rotationRate, _event$rotationRate2, _event$rotationRate3;\n\t\t\tacceleration.value = {\n\t\t\t\tx: ((_event$acceleration = event.acceleration) === null || _event$acceleration === void 0 ? void 0 : _event$acceleration.x) || null,\n\t\t\t\ty: ((_event$acceleration2 = event.acceleration) === null || _event$acceleration2 === void 0 ? void 0 : _event$acceleration2.y) || null,\n\t\t\t\tz: ((_event$acceleration3 = event.acceleration) === null || _event$acceleration3 === void 0 ? void 0 : _event$acceleration3.z) || null\n\t\t\t};\n\t\t\taccelerationIncludingGravity.value = {\n\t\t\t\tx: ((_event$accelerationIn = event.accelerationIncludingGravity) === null || _event$accelerationIn === void 0 ? void 0 : _event$accelerationIn.x) || null,\n\t\t\t\ty: ((_event$accelerationIn2 = event.accelerationIncludingGravity) === null || _event$accelerationIn2 === void 0 ? void 0 : _event$accelerationIn2.y) || null,\n\t\t\t\tz: ((_event$accelerationIn3 = event.accelerationIncludingGravity) === null || _event$accelerationIn3 === void 0 ? void 0 : _event$accelerationIn3.z) || null\n\t\t\t};\n\t\t\trotationRate.value = {\n\t\t\t\talpha: ((_event$rotationRate = event.rotationRate) === null || _event$rotationRate === void 0 ? void 0 : _event$rotationRate.alpha) || null,\n\t\t\t\tbeta: ((_event$rotationRate2 = event.rotationRate) === null || _event$rotationRate2 === void 0 ? void 0 : _event$rotationRate2.beta) || null,\n\t\t\t\tgamma: ((_event$rotationRate3 = event.rotationRate) === null || _event$rotationRate3 === void 0 ? void 0 : _event$rotationRate3.gamma) || null\n\t\t\t};\n\t\t\tinterval.value = event.interval;\n\t\t}), { passive: true });\n\t}\n\tconst ensurePermissions = async () => {\n\t\tif (!requirePermissions.value) permissionGranted.value = true;\n\t\tif (permissionGranted.value) return;\n\t\tif (requirePermissions.value) {\n\t\t\tconst requestPermission = DeviceMotionEvent.requestPermission;\n\t\t\ttry {\n\t\t\t\tif (await requestPermission() === \"granted\") {\n\t\t\t\t\tpermissionGranted.value = true;\n\t\t\t\t\tinit();\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(error);\n\t\t\t}\n\t\t}\n\t};\n\tif (isSupported.value) if (requestPermissions && requirePermissions.value) ensurePermissions().then(() => init());\n\telse init();\n\treturn {\n\t\tacceleration,\n\t\taccelerationIncludingGravity,\n\t\trotationRate,\n\t\tinterval,\n\t\tisSupported,\n\t\trequirePermissions,\n\t\tensurePermissions,\n\t\tpermissionGranted\n\t};\n}\n//#endregion\n//#region useDeviceOrientation/index.ts\n/**\n* Reactive DeviceOrientationEvent.\n*\n* @see https://vueuse.org/useDeviceOrientation\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useDeviceOrientation(options = {}) {\n\tconst { window = defaultWindow } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => window && \"DeviceOrientationEvent\" in window);\n\tconst isAbsolute = shallowRef(false);\n\tconst alpha = shallowRef(null);\n\tconst beta = shallowRef(null);\n\tconst gamma = shallowRef(null);\n\tif (window && isSupported.value) useEventListener(window, \"deviceorientation\", (event) => {\n\t\tisAbsolute.value = event.absolute;\n\t\talpha.value = event.alpha;\n\t\tbeta.value = event.beta;\n\t\tgamma.value = event.gamma;\n\t}, { passive: true });\n\treturn {\n\t\tisSupported,\n\t\tisAbsolute,\n\t\talpha,\n\t\tbeta,\n\t\tgamma\n\t};\n}\n//#endregion\n//#region useDevicePixelRatio/index.ts\n/**\n* Reactively track `window.devicePixelRatio`.\n*\n* @see https://vueuse.org/useDevicePixelRatio\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useDevicePixelRatio(options = {}) {\n\tconst { window = defaultWindow } = options;\n\tconst pixelRatio = shallowRef(1);\n\tconst query = useMediaQuery(() => `(resolution: ${pixelRatio.value}dppx)`, options);\n\tlet stop = noop;\n\tif (window) stop = watchImmediate(query, () => pixelRatio.value = window.devicePixelRatio);\n\treturn {\n\t\tpixelRatio: shallowReadonly(pixelRatio),\n\t\tstop\n\t};\n}\n//#endregion\n//#region useDevicesList/index.ts\n/**\n* Reactive `enumerateDevices` listing available input/output devices\n*\n* @see https://vueuse.org/useDevicesList\n* @param options\n*/\nfunction useDevicesList(options = {}) {\n\tconst { navigator = defaultNavigator, requestPermissions = false, constraints = {\n\t\taudio: true,\n\t\tvideo: true\n\t}, onUpdated } = options;\n\tconst devices = shallowRef([]);\n\tconst videoInputs = computed(() => devices.value.filter((i) => i.kind === \"videoinput\"));\n\tconst audioInputs = computed(() => devices.value.filter((i) => i.kind === \"audioinput\"));\n\tconst audioOutputs = computed(() => devices.value.filter((i) => i.kind === \"audiooutput\"));\n\tconst isSupported = /* @__PURE__ */ useSupported(() => navigator && navigator.mediaDevices && navigator.mediaDevices.enumerateDevices);\n\tconst permissionGranted = shallowRef(false);\n\tlet stream;\n\tasync function update() {\n\t\tif (!isSupported.value) return;\n\t\tdevices.value = await navigator.mediaDevices.enumerateDevices();\n\t\tonUpdated === null || onUpdated === void 0 || onUpdated(devices.value);\n\t\tif (stream) {\n\t\t\tstream.getTracks().forEach((t) => t.stop());\n\t\t\tstream = null;\n\t\t}\n\t}\n\tasync function ensurePermissions() {\n\t\tconst deviceName = constraints.video ? \"camera\" : \"microphone\";\n\t\tif (!isSupported.value) return false;\n\t\tif (permissionGranted.value) return true;\n\t\tconst { state, query } = usePermission(deviceName, { controls: true });\n\t\tawait query();\n\t\tif (state.value !== \"granted\") {\n\t\t\tlet granted = true;\n\t\t\ttry {\n\t\t\t\tconst allDevices = await navigator.mediaDevices.enumerateDevices();\n\t\t\t\tconst hasCamera = allDevices.some((device) => device.kind === \"videoinput\");\n\t\t\t\tconst hasMicrophone = allDevices.some((device) => device.kind === \"audioinput\" || device.kind === \"audiooutput\");\n\t\t\t\tconstraints.video = hasCamera ? constraints.video : false;\n\t\t\t\tconstraints.audio = hasMicrophone ? constraints.audio : false;\n\t\t\t\tstream = await navigator.mediaDevices.getUserMedia(constraints);\n\t\t\t} catch (_unused) {\n\t\t\t\tstream = null;\n\t\t\t\tgranted = false;\n\t\t\t}\n\t\t\tupdate();\n\t\t\tpermissionGranted.value = granted;\n\t\t} else permissionGranted.value = true;\n\t\treturn permissionGranted.value;\n\t}\n\tif (isSupported.value) {\n\t\tif (requestPermissions) ensurePermissions();\n\t\tuseEventListener(navigator.mediaDevices, \"devicechange\", update, { passive: true });\n\t\tupdate();\n\t}\n\treturn {\n\t\tdevices,\n\t\tensurePermissions,\n\t\tpermissionGranted,\n\t\tvideoInputs,\n\t\taudioInputs,\n\t\taudioOutputs,\n\t\tisSupported\n\t};\n}\n//#endregion\n//#region useDisplayMedia/index.ts\n/**\n* Reactive `mediaDevices.getDisplayMedia` streaming\n*\n* @see https://vueuse.org/useDisplayMedia\n* @param options\n*/\nfunction useDisplayMedia(options = {}) {\n\tvar _options$enabled;\n\tconst enabled = shallowRef((_options$enabled = options.enabled) !== null && _options$enabled !== void 0 ? _options$enabled : false);\n\tconst video = options.video;\n\tconst audio = options.audio;\n\tconst { navigator = defaultNavigator } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => {\n\t\tvar _navigator$mediaDevic;\n\t\treturn navigator === null || navigator === void 0 || (_navigator$mediaDevic = navigator.mediaDevices) === null || _navigator$mediaDevic === void 0 ? void 0 : _navigator$mediaDevic.getDisplayMedia;\n\t});\n\tconst constraint = {\n\t\taudio,\n\t\tvideo\n\t};\n\tconst stream = shallowRef();\n\tasync function _start() {\n\t\tvar _stream$value;\n\t\tif (!isSupported.value || stream.value) return;\n\t\tstream.value = await navigator.mediaDevices.getDisplayMedia(constraint);\n\t\t(_stream$value = stream.value) === null || _stream$value === void 0 || _stream$value.getTracks().forEach((t) => useEventListener(t, \"ended\", stop, { passive: true }));\n\t\treturn stream.value;\n\t}\n\tasync function _stop() {\n\t\tvar _stream$value2;\n\t\t(_stream$value2 = stream.value) === null || _stream$value2 === void 0 || _stream$value2.getTracks().forEach((t) => t.stop());\n\t\tstream.value = void 0;\n\t}\n\tfunction stop() {\n\t\t_stop();\n\t\tenabled.value = false;\n\t}\n\tasync function start() {\n\t\tawait _start();\n\t\tif (stream.value) enabled.value = true;\n\t\treturn stream.value;\n\t}\n\twatch(enabled, (v) => {\n\t\tif (v) _start();\n\t\telse _stop();\n\t}, { immediate: true });\n\treturn {\n\t\tisSupported,\n\t\tstream,\n\t\tstart,\n\t\tstop,\n\t\tenabled\n\t};\n}\n//#endregion\n//#region useDocumentVisibility/index.ts\n/**\n* Reactively track `document.visibilityState`.\n*\n* @see https://vueuse.org/useDocumentVisibility\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useDocumentVisibility(options = {}) {\n\tconst { document = defaultDocument } = options;\n\tif (!document) return shallowRef(\"visible\");\n\tconst visibility = shallowRef(document.visibilityState);\n\tuseEventListener(document, \"visibilitychange\", () => {\n\t\tvisibility.value = document.visibilityState;\n\t}, { passive: true });\n\treturn visibility;\n}\n//#endregion\n//#region useDraggable/index.ts\nconst defaultScrollConfig = {\n\tspeed: 2,\n\tmargin: 30,\n\tdirection: \"both\"\n};\nfunction clampContainerScroll(container) {\n\tif (container.scrollLeft > container.scrollWidth - container.clientWidth) container.scrollLeft = Math.max(0, container.scrollWidth - container.clientWidth);\n\tif (container.scrollTop > container.scrollHeight - container.clientHeight) container.scrollTop = Math.max(0, container.scrollHeight - container.clientHeight);\n}\n/**\n* Make elements draggable.\n*\n* @see https://vueuse.org/useDraggable\n* @param target\n* @param options\n*/\nfunction useDraggable(target, options = {}) {\n\tvar _toValue, _toValue2, _toValue3, _scrollConfig$directi;\n\tconst { pointerTypes, preventDefault, stopPropagation, exact, onMove, onEnd, onStart, initialValue, axis = \"both\", draggingElement = defaultWindow, containerElement, handle: draggingHandle = target, buttons = [0], restrictInView, autoScroll = false } = options;\n\tconst position = ref((_toValue = toValue(initialValue)) !== null && _toValue !== void 0 ? _toValue : {\n\t\tx: 0,\n\t\ty: 0\n\t});\n\tconst pressedDelta = ref();\n\tconst filterEvent = (e) => {\n\t\tif (pointerTypes) return pointerTypes.includes(e.pointerType);\n\t\treturn true;\n\t};\n\tconst handleEvent = (e) => {\n\t\tif (toValue(preventDefault)) e.preventDefault();\n\t\tif (toValue(stopPropagation)) e.stopPropagation();\n\t};\n\tconst scrollConfig = toValue(autoScroll);\n\tconst scrollSettings = typeof scrollConfig === \"object\" ? {\n\t\tspeed: (_toValue2 = toValue(scrollConfig.speed)) !== null && _toValue2 !== void 0 ? _toValue2 : defaultScrollConfig.speed,\n\t\tmargin: (_toValue3 = toValue(scrollConfig.margin)) !== null && _toValue3 !== void 0 ? _toValue3 : defaultScrollConfig.margin,\n\t\tdirection: (_scrollConfig$directi = scrollConfig.direction) !== null && _scrollConfig$directi !== void 0 ? _scrollConfig$directi : defaultScrollConfig.direction\n\t} : defaultScrollConfig;\n\tconst getScrollAxisValues = (value) => typeof value === \"number\" ? [value, value] : [value.x, value.y];\n\tconst handleAutoScroll = (container, targetRect, position) => {\n\t\tconst { clientWidth, clientHeight, scrollLeft, scrollTop, scrollWidth, scrollHeight } = container;\n\t\tconst [marginX, marginY] = getScrollAxisValues(scrollSettings.margin);\n\t\tconst [speedX, speedY] = getScrollAxisValues(scrollSettings.speed);\n\t\tlet deltaX = 0;\n\t\tlet deltaY = 0;\n\t\tif (scrollSettings.direction === \"x\" || scrollSettings.direction === \"both\") {\n\t\t\tif (position.x < marginX && scrollLeft > 0) deltaX = -speedX;\n\t\t\telse if (position.x + targetRect.width > clientWidth - marginX && scrollLeft < scrollWidth - clientWidth) deltaX = speedX;\n\t\t}\n\t\tif (scrollSettings.direction === \"y\" || scrollSettings.direction === \"both\") {\n\t\t\tif (position.y < marginY && scrollTop > 0) deltaY = -speedY;\n\t\t\telse if (position.y + targetRect.height > clientHeight - marginY && scrollTop < scrollHeight - clientHeight) deltaY = speedY;\n\t\t}\n\t\tif (deltaX || deltaY) container.scrollBy({\n\t\t\tleft: deltaX,\n\t\t\ttop: deltaY,\n\t\t\tbehavior: \"auto\"\n\t\t});\n\t};\n\tlet autoScrollInterval = null;\n\tconst startAutoScroll = () => {\n\t\tconst container = toValue(containerElement);\n\t\tif (container && !autoScrollInterval) autoScrollInterval = setInterval(() => {\n\t\t\tconst targetRect = toValue(target).getBoundingClientRect();\n\t\t\tconst { x, y } = position.value;\n\t\t\tconst relativePosition = {\n\t\t\t\tx: x - container.scrollLeft,\n\t\t\t\ty: y - container.scrollTop\n\t\t\t};\n\t\t\tif (relativePosition.x >= 0 && relativePosition.y >= 0) {\n\t\t\t\thandleAutoScroll(container, targetRect, relativePosition);\n\t\t\t\trelativePosition.x += container.scrollLeft;\n\t\t\t\trelativePosition.y += container.scrollTop;\n\t\t\t\tposition.value = relativePosition;\n\t\t\t}\n\t\t}, 1e3 / 60);\n\t};\n\tconst stopAutoScroll = () => {\n\t\tif (autoScrollInterval) {\n\t\t\tclearInterval(autoScrollInterval);\n\t\t\tautoScrollInterval = null;\n\t\t}\n\t};\n\tconst isPointerNearEdge = (pointer, container, margin, targetRect) => {\n\t\tconst [marginX, marginY] = typeof margin === \"number\" ? [margin, margin] : [margin.x, margin.y];\n\t\tconst { clientWidth, clientHeight } = container;\n\t\treturn pointer.x < marginX || pointer.x + targetRect.width > clientWidth - marginX || pointer.y < marginY || pointer.y + targetRect.height > clientHeight - marginY;\n\t};\n\tconst checkAutoScroll = () => {\n\t\tif (toValue(options.disabled) || !pressedDelta.value) return;\n\t\tconst container = toValue(containerElement);\n\t\tif (!container) return;\n\t\tconst targetRect = toValue(target).getBoundingClientRect();\n\t\tconst { x, y } = position.value;\n\t\tif (isPointerNearEdge({\n\t\t\tx: x - container.scrollLeft,\n\t\t\ty: y - container.scrollTop\n\t\t}, container, scrollSettings.margin, targetRect)) startAutoScroll();\n\t\telse stopAutoScroll();\n\t};\n\tif (toValue(autoScroll)) watch(position, checkAutoScroll);\n\tconst start = (e) => {\n\t\tvar _container$getBoundin;\n\t\tif (!toValue(buttons).includes(e.button)) return;\n\t\tif (toValue(options.disabled) || !filterEvent(e)) return;\n\t\tif (toValue(exact) && e.target !== toValue(target)) return;\n\t\tconst container = toValue(containerElement);\n\t\tconst containerRect = container === null || container === void 0 || (_container$getBoundin = container.getBoundingClientRect) === null || _container$getBoundin === void 0 ? void 0 : _container$getBoundin.call(container);\n\t\tconst targetRect = toValue(target).getBoundingClientRect();\n\t\tconst pos = {\n\t\t\tx: e.clientX - (container ? targetRect.left - containerRect.left + (autoScroll ? 0 : container.scrollLeft) : targetRect.left),\n\t\t\ty: e.clientY - (container ? targetRect.top - containerRect.top + (autoScroll ? 0 : container.scrollTop) : targetRect.top)\n\t\t};\n\t\tif ((onStart === null || onStart === void 0 ? void 0 : onStart(pos, e)) === false) return;\n\t\tpressedDelta.value = pos;\n\t\thandleEvent(e);\n\t};\n\tconst move = (e) => {\n\t\tif (toValue(options.disabled) || !filterEvent(e)) return;\n\t\tif (!pressedDelta.value) return;\n\t\tconst container = toValue(containerElement);\n\t\tif (container instanceof HTMLElement) clampContainerScroll(container);\n\t\tconst targetRect = toValue(target).getBoundingClientRect();\n\t\tlet { x, y } = position.value;\n\t\tif (axis === \"x\" || axis === \"both\") {\n\t\t\tx = e.clientX - pressedDelta.value.x;\n\t\t\tif (container) x = Math.min(Math.max(0, x), container.scrollWidth - targetRect.width);\n\t\t}\n\t\tif (axis === \"y\" || axis === \"both\") {\n\t\t\ty = e.clientY - pressedDelta.value.y;\n\t\t\tif (container) y = Math.min(Math.max(0, y), container.scrollHeight - targetRect.height);\n\t\t}\n\t\tif (toValue(autoScroll) && container) {\n\t\t\tif (autoScrollInterval === null) handleAutoScroll(container, targetRect, {\n\t\t\t\tx,\n\t\t\t\ty\n\t\t\t});\n\t\t\tx += container.scrollLeft;\n\t\t\ty += container.scrollTop;\n\t\t}\n\t\tif (container && (restrictInView || autoScroll)) {\n\t\t\tif (axis !== \"y\") {\n\t\t\t\tconst relativeX = x - container.scrollLeft;\n\t\t\t\tif (relativeX < 0) x = container.scrollLeft;\n\t\t\t\telse if (relativeX > container.clientWidth - targetRect.width) x = container.clientWidth - targetRect.width + container.scrollLeft;\n\t\t\t}\n\t\t\tif (axis !== \"x\") {\n\t\t\t\tconst relativeY = y - container.scrollTop;\n\t\t\t\tif (relativeY < 0) y = container.scrollTop;\n\t\t\t\telse if (relativeY > container.clientHeight - targetRect.height) y = container.clientHeight - targetRect.height + container.scrollTop;\n\t\t\t}\n\t\t}\n\t\tposition.value = {\n\t\t\tx,\n\t\t\ty\n\t\t};\n\t\tonMove === null || onMove === void 0 || onMove(position.value, e);\n\t\thandleEvent(e);\n\t};\n\tconst end = (e) => {\n\t\tif (toValue(options.disabled) || !filterEvent(e)) return;\n\t\tif (!pressedDelta.value) return;\n\t\tpressedDelta.value = void 0;\n\t\tif (autoScroll) stopAutoScroll();\n\t\tonEnd === null || onEnd === void 0 || onEnd(position.value, e);\n\t\thandleEvent(e);\n\t};\n\tif (isClient) {\n\t\tconst config = () => {\n\t\t\tvar _options$capture;\n\t\t\treturn {\n\t\t\t\tcapture: (_options$capture = options.capture) !== null && _options$capture !== void 0 ? _options$capture : true,\n\t\t\t\tpassive: !toValue(preventDefault)\n\t\t\t};\n\t\t};\n\t\tuseEventListener(draggingHandle, \"pointerdown\", start, config);\n\t\tuseEventListener(draggingElement, \"pointermove\", move, config);\n\t\tuseEventListener(draggingElement, \"pointerup\", end, config);\n\t}\n\treturn {\n\t\t...toRefs(position),\n\t\tposition,\n\t\tisDragging: computed(() => !!pressedDelta.value),\n\t\tstyle: computed(() => `\n      left: ${position.value.x}px;\n      top: ${position.value.y}px;\n      ${autoScroll ? \"text-wrap: nowrap;\" : \"\"}\n    `)\n\t};\n}\n//#endregion\n//#region useDropZone/index.ts\nfunction useDropZone(target, options = {}) {\n\tconst isOverDropZone = shallowRef(false);\n\tconst files = shallowRef(null);\n\tlet counter = 0;\n\tlet isValid = true;\n\tif (isClient) {\n\t\tvar _options$multiple, _options$preventDefau;\n\t\tconst _options = typeof options === \"function\" ? { onDrop: options } : options;\n\t\tconst multiple = (_options$multiple = _options.multiple) !== null && _options$multiple !== void 0 ? _options$multiple : true;\n\t\tconst preventDefaultForUnhandled = (_options$preventDefau = _options.preventDefaultForUnhandled) !== null && _options$preventDefau !== void 0 ? _options$preventDefau : false;\n\t\tconst getFiles = (event) => {\n\t\t\tvar _event$dataTransfer$f, _event$dataTransfer;\n\t\t\tconst list = Array.from((_event$dataTransfer$f = (_event$dataTransfer = event.dataTransfer) === null || _event$dataTransfer === void 0 ? void 0 : _event$dataTransfer.files) !== null && _event$dataTransfer$f !== void 0 ? _event$dataTransfer$f : []);\n\t\t\treturn list.length === 0 ? null : multiple ? list : [list[0]];\n\t\t};\n\t\tconst checkDataTypes = (types) => {\n\t\t\tconst dataTypes = unref(_options.dataTypes);\n\t\t\tif (typeof dataTypes === \"function\") return dataTypes(types);\n\t\t\tif (!(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length)) return true;\n\t\t\tif (types.length === 0) return false;\n\t\t\treturn types.every((type) => dataTypes.some((allowedType) => type.includes(allowedType)));\n\t\t};\n\t\tconst checkValidity = (items) => {\n\t\t\tif (_options.checkValidity) return _options.checkValidity(items);\n\t\t\tconst dataTypesValid = checkDataTypes(Array.from(items !== null && items !== void 0 ? items : []).map((item) => item.type));\n\t\t\tconst multipleFilesValid = multiple || items.length <= 1;\n\t\t\treturn dataTypesValid && multipleFilesValid;\n\t\t};\n\t\tconst isSafari = () => /^(?:(?!chrome|android).)*safari/i.test(navigator.userAgent) && !(\"chrome\" in window);\n\t\tconst handleDragEvent = (event, eventType) => {\n\t\t\tvar _event$dataTransfer2, _ref;\n\t\t\tconst dataTransferItemList = (_event$dataTransfer2 = event.dataTransfer) === null || _event$dataTransfer2 === void 0 ? void 0 : _event$dataTransfer2.items;\n\t\t\tisValid = (_ref = dataTransferItemList && checkValidity(dataTransferItemList)) !== null && _ref !== void 0 ? _ref : false;\n\t\t\tif (preventDefaultForUnhandled) event.preventDefault();\n\t\t\tif (!isSafari() && !isValid) {\n\t\t\t\tif (event.dataTransfer) event.dataTransfer.dropEffect = \"none\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tevent.preventDefault();\n\t\t\tif (event.dataTransfer) event.dataTransfer.dropEffect = \"copy\";\n\t\t\tconst currentFiles = getFiles(event);\n\t\t\tswitch (eventType) {\n\t\t\t\tcase \"enter\":\n\t\t\t\t\tvar _options$onEnter;\n\t\t\t\t\tcounter += 1;\n\t\t\t\t\tisOverDropZone.value = true;\n\t\t\t\t\t(_options$onEnter = _options.onEnter) === null || _options$onEnter === void 0 || _options$onEnter.call(_options, null, event);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"over\":\n\t\t\t\t\tvar _options$onOver;\n\t\t\t\t\t(_options$onOver = _options.onOver) === null || _options$onOver === void 0 || _options$onOver.call(_options, null, event);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"leave\":\n\t\t\t\t\tvar _options$onLeave;\n\t\t\t\t\tcounter -= 1;\n\t\t\t\t\tif (counter === 0) isOverDropZone.value = false;\n\t\t\t\t\t(_options$onLeave = _options.onLeave) === null || _options$onLeave === void 0 || _options$onLeave.call(_options, null, event);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"drop\":\n\t\t\t\t\tcounter = 0;\n\t\t\t\t\tisOverDropZone.value = false;\n\t\t\t\t\tif (isValid) {\n\t\t\t\t\t\tvar _options$onDrop;\n\t\t\t\t\t\tfiles.value = currentFiles;\n\t\t\t\t\t\t(_options$onDrop = _options.onDrop) === null || _options$onDrop === void 0 || _options$onDrop.call(_options, currentFiles, event);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t};\n\t\tuseEventListener(target, \"dragenter\", (event) => handleDragEvent(event, \"enter\"));\n\t\tuseEventListener(target, \"dragover\", (event) => handleDragEvent(event, \"over\"));\n\t\tuseEventListener(target, \"dragleave\", (event) => handleDragEvent(event, \"leave\"));\n\t\tuseEventListener(target, \"drop\", (event) => handleDragEvent(event, \"drop\"));\n\t}\n\treturn {\n\t\tfiles,\n\t\tisOverDropZone\n\t};\n}\n//#endregion\n//#region useResizeObserver/index.ts\n/**\n* Reports changes to the dimensions of an Element's content or the border-box\n*\n* @see https://vueuse.org/useResizeObserver\n* @param target\n* @param callback\n* @param options\n*/\nfunction useResizeObserver(target, callback, options = {}) {\n\tconst { window = defaultWindow, ...observerOptions } = options;\n\tlet observer;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => window && \"ResizeObserver\" in window);\n\tconst cleanup = () => {\n\t\tif (observer) {\n\t\t\tobserver.disconnect();\n\t\t\tobserver = void 0;\n\t\t}\n\t};\n\tconst stopWatch = watch(computed(() => {\n\t\tconst _targets = toValue(target);\n\t\treturn Array.isArray(_targets) ? _targets.map((el) => unrefElement(el)) : [unrefElement(_targets)];\n\t}), (els) => {\n\t\tcleanup();\n\t\tif (isSupported.value && window) {\n\t\t\tobserver = new ResizeObserver(callback);\n\t\t\tfor (const _el of els) if (_el) observer.observe(_el, observerOptions);\n\t\t}\n\t}, {\n\t\timmediate: true,\n\t\tflush: \"post\"\n\t});\n\tconst stop = () => {\n\t\tcleanup();\n\t\tstopWatch();\n\t};\n\ttryOnScopeDispose(stop);\n\treturn {\n\t\tisSupported,\n\t\tstop\n\t};\n}\n//#endregion\n//#region useElementBounding/index.ts\n/**\n* Reactive bounding box of an HTML element.\n*\n* @see https://vueuse.org/useElementBounding\n* @param target\n*/\nfunction useElementBounding(target, options = {}) {\n\tconst { reset = true, windowResize = true, windowScroll = true, immediate = true, updateTiming = \"sync\" } = options;\n\tconst height = shallowRef(0);\n\tconst bottom = shallowRef(0);\n\tconst left = shallowRef(0);\n\tconst right = shallowRef(0);\n\tconst top = shallowRef(0);\n\tconst width = shallowRef(0);\n\tconst x = shallowRef(0);\n\tconst y = shallowRef(0);\n\tfunction recalculate() {\n\t\tconst el = unrefElement(target);\n\t\tif (!el) {\n\t\t\tif (reset) {\n\t\t\t\theight.value = 0;\n\t\t\t\tbottom.value = 0;\n\t\t\t\tleft.value = 0;\n\t\t\t\tright.value = 0;\n\t\t\t\ttop.value = 0;\n\t\t\t\twidth.value = 0;\n\t\t\t\tx.value = 0;\n\t\t\t\ty.value = 0;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tconst rect = el.getBoundingClientRect();\n\t\theight.value = rect.height;\n\t\tbottom.value = rect.bottom;\n\t\tleft.value = rect.left;\n\t\tright.value = rect.right;\n\t\ttop.value = rect.top;\n\t\twidth.value = rect.width;\n\t\tx.value = rect.x;\n\t\ty.value = rect.y;\n\t}\n\tfunction update() {\n\t\tif (updateTiming === \"sync\") recalculate();\n\t\telse if (updateTiming === \"next-frame\") requestAnimationFrame(() => recalculate());\n\t}\n\tuseResizeObserver(target, update);\n\twatch(() => unrefElement(target), (ele) => !ele && update());\n\tuseMutationObserver(target, update, { attributeFilter: [\"style\", \"class\"] });\n\tif (windowScroll) useEventListener(\"scroll\", update, {\n\t\tcapture: true,\n\t\tpassive: true\n\t});\n\tif (windowResize) useEventListener(\"resize\", update, { passive: true });\n\ttryOnMounted(() => {\n\t\tif (immediate) update();\n\t});\n\treturn {\n\t\theight,\n\t\tbottom,\n\t\tleft,\n\t\tright,\n\t\ttop,\n\t\twidth,\n\t\tx,\n\t\ty,\n\t\tupdate\n\t};\n}\n//#endregion\n//#region useElementByPoint/index.ts\nfunction getDefaultScheduler$7(options) {\n\tif (\"interval\" in options || \"immediate\" in options) {\n\t\tconst { interval = \"requestAnimationFrame\", immediate = true } = options;\n\t\treturn interval === \"requestAnimationFrame\" ? (cb) => useRafFn(cb, { immediate }) : (cb) => useIntervalFn(cb, interval, { immediate });\n\t}\n\treturn useRafFn;\n}\n/**\n* Reactive element by point.\n*\n* @see https://vueuse.org/useElementByPoint\n* @param options - UseElementByPointOptions\n*/\nfunction useElementByPoint(options) {\n\tconst { x, y, document = defaultDocument, multiple, scheduler = getDefaultScheduler$7(options) } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => {\n\t\tif (toValue(multiple)) return document && \"elementsFromPoint\" in document;\n\t\treturn document && \"elementFromPoint\" in document;\n\t});\n\tconst element = shallowRef(null);\n\treturn {\n\t\tisSupported,\n\t\telement,\n\t\t...scheduler(() => {\n\t\t\tvar _document$elementsFro, _document$elementFrom;\n\t\t\telement.value = toValue(multiple) ? (_document$elementsFro = document === null || document === void 0 ? void 0 : document.elementsFromPoint(toValue(x), toValue(y))) !== null && _document$elementsFro !== void 0 ? _document$elementsFro : [] : (_document$elementFrom = document === null || document === void 0 ? void 0 : document.elementFromPoint(toValue(x), toValue(y))) !== null && _document$elementFrom !== void 0 ? _document$elementFrom : null;\n\t\t})\n\t};\n}\n//#endregion\n//#region useElementHover/index.ts\nfunction useElementHover(el, options = {}) {\n\tconst { delayEnter = 0, delayLeave = 0, triggerOnRemoval = false, window = defaultWindow } = options;\n\tconst isHovered = shallowRef(false);\n\tlet timer;\n\tconst toggle = (entering) => {\n\t\tconst delay = entering ? delayEnter : delayLeave;\n\t\tif (timer) {\n\t\t\tclearTimeout(timer);\n\t\t\ttimer = void 0;\n\t\t}\n\t\tif (delay) timer = setTimeout(() => isHovered.value = entering, delay);\n\t\telse isHovered.value = entering;\n\t};\n\tif (!window) return isHovered;\n\tuseEventListener(el, \"mouseenter\", () => toggle(true), { passive: true });\n\tuseEventListener(el, \"mouseleave\", () => toggle(false), { passive: true });\n\tif (triggerOnRemoval) onElementRemoval(computed(() => unrefElement(el)), () => toggle(false));\n\treturn isHovered;\n}\n//#endregion\n//#region useElementSize/index.ts\n/**\n* Reactive size of an HTML element.\n*\n* @see https://vueuse.org/useElementSize\n*/\nfunction useElementSize(target, initialSize = {\n\twidth: 0,\n\theight: 0\n}, options = {}) {\n\tconst { window = defaultWindow, box = \"content-box\" } = options;\n\tconst isSVG = computed(() => {\n\t\tvar _unrefElement;\n\t\treturn (_unrefElement = unrefElement(target)) === null || _unrefElement === void 0 || (_unrefElement = _unrefElement.namespaceURI) === null || _unrefElement === void 0 ? void 0 : _unrefElement.includes(\"svg\");\n\t});\n\tconst width = shallowRef(initialSize.width);\n\tconst height = shallowRef(initialSize.height);\n\tconst { stop: stop1 } = useResizeObserver(target, ([entry]) => {\n\t\tconst boxSize = box === \"border-box\" ? entry.borderBoxSize : box === \"content-box\" ? entry.contentBoxSize : entry.devicePixelContentBoxSize;\n\t\tif (window && isSVG.value) {\n\t\t\tconst $elem = unrefElement(target);\n\t\t\tif ($elem) {\n\t\t\t\tconst rect = $elem.getBoundingClientRect();\n\t\t\t\twidth.value = rect.width;\n\t\t\t\theight.value = rect.height;\n\t\t\t}\n\t\t} else if (boxSize) {\n\t\t\tconst formatBoxSize = toArray(boxSize);\n\t\t\twidth.value = formatBoxSize.reduce((acc, { inlineSize }) => acc + inlineSize, 0);\n\t\t\theight.value = formatBoxSize.reduce((acc, { blockSize }) => acc + blockSize, 0);\n\t\t} else {\n\t\t\twidth.value = entry.contentRect.width;\n\t\t\theight.value = entry.contentRect.height;\n\t\t}\n\t}, options);\n\ttryOnMounted(() => {\n\t\tconst ele = unrefElement(target);\n\t\tif (ele) {\n\t\t\twidth.value = \"offsetWidth\" in ele ? ele.offsetWidth : initialSize.width;\n\t\t\theight.value = \"offsetHeight\" in ele ? ele.offsetHeight : initialSize.height;\n\t\t}\n\t});\n\tconst stop2 = watch(() => unrefElement(target), (ele) => {\n\t\twidth.value = ele ? initialSize.width : 0;\n\t\theight.value = ele ? initialSize.height : 0;\n\t});\n\tfunction stop() {\n\t\tstop1();\n\t\tstop2();\n\t}\n\treturn {\n\t\twidth,\n\t\theight,\n\t\tstop\n\t};\n}\n//#endregion\n//#region useIntersectionObserver/index.ts\n/**\n* Detects changes to a target element's visibility.\n*\n* @see https://vueuse.org/useIntersectionObserver\n* @param target\n* @param callback\n* @param options\n*/\nfunction useIntersectionObserver(target, callback, options = {}) {\n\tconst { root, rootMargin, threshold = 0, window = defaultWindow, immediate = true } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => window && \"IntersectionObserver\" in window);\n\tconst targets = computed(() => {\n\t\treturn toArray(toValue(target)).map(unrefElement).filter(notNullish);\n\t});\n\tlet cleanup = noop;\n\tconst isActive = shallowRef(immediate);\n\tconst stopWatch = isSupported.value ? watch(() => [\n\t\ttargets.value,\n\t\tunrefElement(root),\n\t\ttoValue(rootMargin),\n\t\tisActive.value\n\t], ([targets, root, rootMargin]) => {\n\t\tcleanup();\n\t\tif (!isActive.value) return;\n\t\tif (!targets.length) return;\n\t\tconst observer = new IntersectionObserver(callback, {\n\t\t\troot: unrefElement(root),\n\t\t\trootMargin,\n\t\t\tthreshold\n\t\t});\n\t\ttargets.forEach((el) => el && observer.observe(el));\n\t\tcleanup = () => {\n\t\t\tobserver.disconnect();\n\t\t\tcleanup = noop;\n\t\t};\n\t}, {\n\t\timmediate,\n\t\tflush: \"post\"\n\t}) : noop;\n\tconst stop = () => {\n\t\tcleanup();\n\t\tstopWatch();\n\t\tisActive.value = false;\n\t};\n\ttryOnScopeDispose(stop);\n\treturn {\n\t\tisSupported,\n\t\tisActive,\n\t\tpause() {\n\t\t\tcleanup();\n\t\t\tisActive.value = false;\n\t\t},\n\t\tresume() {\n\t\t\tisActive.value = true;\n\t\t},\n\t\tstop\n\t};\n}\n//#endregion\n//#region useElementVisibility/index.ts\nfunction useElementVisibility(element, options = {}) {\n\tconst { window = defaultWindow, scrollTarget, threshold = 0, rootMargin, once = false, initialValue = false } = options;\n\tconst isVisible = shallowRef(initialValue);\n\tconst observerController = useIntersectionObserver(element, (intersectionObserverEntries) => {\n\t\tlet isIntersecting = isVisible.value;\n\t\tlet latestTime = 0;\n\t\tfor (const entry of intersectionObserverEntries) if (entry.time >= latestTime) {\n\t\t\tlatestTime = entry.time;\n\t\t\tisIntersecting = entry.isIntersecting;\n\t\t}\n\t\tisVisible.value = isIntersecting;\n\t\tif (once) watchOnce(isVisible, () => {\n\t\t\tobserverController.stop();\n\t\t});\n\t}, {\n\t\troot: scrollTarget,\n\t\twindow,\n\t\tthreshold,\n\t\trootMargin\n\t});\n\treturn options.controls ? {\n\t\t...observerController,\n\t\tisVisible\n\t} : isVisible;\n}\n//#endregion\n//#region useEventBus/internal.ts\n/* #__PURE__ */\nconst events = /* @__PURE__ */ new Map();\n//#endregion\n//#region useEventBus/index.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction useEventBus(key) {\n\tconst scope = getCurrentScope();\n\tfunction on(listener) {\n\t\tvar _scope$cleanups;\n\t\tconst listeners = events.get(key) || /* @__PURE__ */ new Set();\n\t\tlisteners.add(listener);\n\t\tevents.set(key, listeners);\n\t\tconst _off = () => off(listener);\n\t\tscope === null || scope === void 0 || (_scope$cleanups = scope.cleanups) === null || _scope$cleanups === void 0 || _scope$cleanups.push(_off);\n\t\treturn _off;\n\t}\n\tfunction once(listener) {\n\t\tfunction _listener(...args) {\n\t\t\toff(_listener);\n\t\t\tlistener(...args);\n\t\t}\n\t\treturn on(_listener);\n\t}\n\tfunction off(listener) {\n\t\tconst listeners = events.get(key);\n\t\tif (!listeners) return;\n\t\tlisteners.delete(listener);\n\t\tif (!listeners.size) reset();\n\t}\n\tfunction reset() {\n\t\tevents.delete(key);\n\t}\n\tfunction emit(event, payload) {\n\t\tvar _events$get;\n\t\t(_events$get = events.get(key)) === null || _events$get === void 0 || _events$get.forEach((v) => v(event, payload));\n\t}\n\treturn {\n\t\ton,\n\t\tonce,\n\t\toff,\n\t\temit,\n\t\treset\n\t};\n}\n//#endregion\n//#region useEventSource/index.ts\nfunction resolveNestedOptions$1(options) {\n\tif (options === true) return {};\n\treturn options;\n}\n/**\n* Reactive wrapper for EventSource.\n*\n* @see https://vueuse.org/useEventSource\n* @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/EventSource EventSource\n* @param url\n* @param events\n* @param options\n*/\nfunction useEventSource(url, events = [], options = {}) {\n\tconst event = shallowRef(null);\n\tconst data = shallowRef(null);\n\tconst status = shallowRef(\"CONNECTING\");\n\tconst eventSource = shallowRef(null);\n\tconst error = shallowRef(null);\n\tconst urlRef = toRef(url);\n\tconst lastEventId = shallowRef(null);\n\tlet explicitlyClosed = false;\n\tlet retried = 0;\n\tconst { withCredentials = false, immediate = true, autoConnect = true, autoReconnect, serializer = { read: (v) => v } } = options;\n\tconst close = () => {\n\t\tif (isClient && eventSource.value) {\n\t\t\teventSource.value.close();\n\t\t\teventSource.value = null;\n\t\t\tstatus.value = \"CLOSED\";\n\t\t\texplicitlyClosed = true;\n\t\t}\n\t};\n\tconst _init = () => {\n\t\tif (explicitlyClosed || typeof urlRef.value === \"undefined\") return;\n\t\tconst es = new EventSource(urlRef.value, { withCredentials });\n\t\tstatus.value = \"CONNECTING\";\n\t\teventSource.value = es;\n\t\tes.onopen = () => {\n\t\t\tstatus.value = \"OPEN\";\n\t\t\terror.value = null;\n\t\t};\n\t\tes.onerror = (e) => {\n\t\t\tstatus.value = \"CLOSED\";\n\t\t\terror.value = e;\n\t\t\tif (es.readyState === 2 && !explicitlyClosed && autoReconnect) {\n\t\t\t\tes.close();\n\t\t\t\tconst { retries = -1, delay = 1e3, onFailed } = resolveNestedOptions$1(autoReconnect);\n\t\t\t\tretried += 1;\n\t\t\t\tif (typeof retries === \"number\" && (retries < 0 || retried < retries)) setTimeout(_init, delay);\n\t\t\t\telse if (typeof retries === \"function\" && retries()) setTimeout(_init, delay);\n\t\t\t\telse onFailed === null || onFailed === void 0 || onFailed();\n\t\t\t}\n\t\t};\n\t\tes.onmessage = (e) => {\n\t\t\tvar _serializer$read;\n\t\t\tevent.value = null;\n\t\t\tdata.value = (_serializer$read = serializer.read(e.data)) !== null && _serializer$read !== void 0 ? _serializer$read : null;\n\t\t\tlastEventId.value = e.lastEventId;\n\t\t};\n\t\tfor (const event_name of events) useEventListener(es, event_name, (e) => {\n\t\t\tvar _serializer$read2, _e$lastEventId;\n\t\t\tevent.value = event_name;\n\t\t\tdata.value = (_serializer$read2 = serializer.read(e.data)) !== null && _serializer$read2 !== void 0 ? _serializer$read2 : null;\n\t\t\tlastEventId.value = (_e$lastEventId = e.lastEventId) !== null && _e$lastEventId !== void 0 ? _e$lastEventId : null;\n\t\t}, { passive: true });\n\t};\n\tconst open = () => {\n\t\tif (!isClient) return;\n\t\tclose();\n\t\texplicitlyClosed = false;\n\t\tretried = 0;\n\t\t_init();\n\t};\n\tif (immediate) open();\n\tif (autoConnect) watch(urlRef, open);\n\ttryOnScopeDispose(close);\n\treturn {\n\t\teventSource,\n\t\tevent,\n\t\tdata,\n\t\tstatus,\n\t\terror,\n\t\topen,\n\t\tclose,\n\t\tlastEventId\n\t};\n}\n//#endregion\n//#region useEyeDropper/index.ts\n/**\n* Reactive [EyeDropper API](https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper_API)\n*\n* @see https://vueuse.org/useEyeDropper\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useEyeDropper(options = {}) {\n\tconst { initialValue = \"\" } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => typeof window !== \"undefined\" && \"EyeDropper\" in window);\n\tconst sRGBHex = shallowRef(initialValue);\n\tasync function open(openOptions) {\n\t\tif (!isSupported.value) return;\n\t\tconst result = await new window.EyeDropper().open(openOptions);\n\t\tsRGBHex.value = result.sRGBHex;\n\t\treturn result;\n\t}\n\treturn {\n\t\tisSupported,\n\t\tsRGBHex,\n\t\topen\n\t};\n}\n//#endregion\n//#region useFavicon/index.ts\nfunction useFavicon(newIcon = null, options = {}) {\n\tconst { baseUrl = \"\", rel = \"icon\", document = defaultDocument } = options;\n\tconst favicon = toRef(newIcon);\n\tconst applyIcon = (icon) => {\n\t\tconst elements = document === null || document === void 0 ? void 0 : document.head.querySelectorAll(`link[rel*=\"${rel}\"]`);\n\t\tif (!elements || elements.length === 0) {\n\t\t\tconst link = document === null || document === void 0 ? void 0 : document.createElement(\"link\");\n\t\t\tif (link) {\n\t\t\t\tlink.rel = rel;\n\t\t\t\tlink.href = `${baseUrl}${icon}`;\n\t\t\t\tlink.type = `image/${icon.split(\".\").pop()}`;\n\t\t\t\tdocument === null || document === void 0 || document.head.append(link);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\telements === null || elements === void 0 || elements.forEach((el) => el.href = `${baseUrl}${icon}`);\n\t};\n\twatch(favicon, (i, o) => {\n\t\tif (typeof i === \"string\" && i !== o) applyIcon(i);\n\t}, { immediate: true });\n\treturn favicon;\n}\n//#endregion\n//#region useFetch/index.ts\nconst payloadMapping = {\n\tjson: \"application/json\",\n\ttext: \"text/plain\"\n};\n/**\n* !!!IMPORTANT!!!\n*\n* If you update the UseFetchOptions interface, be sure to update this object\n* to include the new options\n*/\nfunction isFetchOptions(obj) {\n\treturn obj && containsProp(obj, \"immediate\", \"refetch\", \"initialData\", \"timeout\", \"beforeFetch\", \"afterFetch\", \"onFetchError\", \"fetch\", \"updateDataOnError\");\n}\nconst reAbsolute = /^(?:[a-z][a-z\\d+\\-.]*:)?\\/\\//i;\nfunction isAbsoluteURL(url) {\n\treturn reAbsolute.test(url);\n}\nfunction headersToObject(headers) {\n\tif (typeof Headers !== \"undefined\" && headers instanceof Headers) return Object.fromEntries(headers.entries());\n\treturn headers;\n}\nfunction combineCallbacks(combination, ...callbacks) {\n\tif (combination === \"overwrite\") return async (ctx) => {\n\t\tlet callback;\n\t\tfor (let i = callbacks.length - 1; i >= 0; i--) if (callbacks[i] != null) {\n\t\t\tcallback = callbacks[i];\n\t\t\tbreak;\n\t\t}\n\t\tif (callback) return {\n\t\t\t...ctx,\n\t\t\t...await callback(ctx)\n\t\t};\n\t\treturn ctx;\n\t};\n\telse return async (ctx) => {\n\t\tfor (const callback of callbacks) if (callback) ctx = {\n\t\t\t...ctx,\n\t\t\t...await callback(ctx)\n\t\t};\n\t\treturn ctx;\n\t};\n}\nfunction createFetch(config = {}) {\n\tconst _combination = config.combination || \"chain\";\n\tconst _options = config.options || {};\n\tconst _fetchOptions = config.fetchOptions || {};\n\tfunction useFactoryFetch(url, ...args) {\n\t\tconst computedUrl = computed(() => {\n\t\t\tconst baseUrl = toValue(config.baseUrl);\n\t\t\tconst targetUrl = toValue(url);\n\t\t\treturn baseUrl && !isAbsoluteURL(targetUrl) ? joinPaths(baseUrl, targetUrl) : targetUrl;\n\t\t});\n\t\tlet options = _options;\n\t\tlet fetchOptions = _fetchOptions;\n\t\tif (args.length > 0) if (isFetchOptions(args[0])) options = {\n\t\t\t...options,\n\t\t\t...args[0],\n\t\t\tbeforeFetch: combineCallbacks(_combination, _options.beforeFetch, args[0].beforeFetch),\n\t\t\tafterFetch: combineCallbacks(_combination, _options.afterFetch, args[0].afterFetch),\n\t\t\tonFetchError: combineCallbacks(_combination, _options.onFetchError, args[0].onFetchError)\n\t\t};\n\t\telse fetchOptions = {\n\t\t\t...fetchOptions,\n\t\t\t...args[0],\n\t\t\theaders: {\n\t\t\t\t...headersToObject(fetchOptions.headers) || {},\n\t\t\t\t...headersToObject(args[0].headers) || {}\n\t\t\t}\n\t\t};\n\t\tif (args.length > 1 && isFetchOptions(args[1])) options = {\n\t\t\t...options,\n\t\t\t...args[1],\n\t\t\tbeforeFetch: combineCallbacks(_combination, _options.beforeFetch, args[1].beforeFetch),\n\t\t\tafterFetch: combineCallbacks(_combination, _options.afterFetch, args[1].afterFetch),\n\t\t\tonFetchError: combineCallbacks(_combination, _options.onFetchError, args[1].onFetchError)\n\t\t};\n\t\treturn useFetch(computedUrl, fetchOptions, options);\n\t}\n\treturn useFactoryFetch;\n}\nfunction useFetch(url, ...args) {\n\tvar _defaultWindow$fetch, _globalThis;\n\tconst supportsAbort = typeof AbortController === \"function\";\n\tlet fetchOptions = {};\n\tlet options = {\n\t\timmediate: true,\n\t\trefetch: false,\n\t\ttimeout: 0,\n\t\tupdateDataOnError: false\n\t};\n\tconst config = {\n\t\tmethod: \"GET\",\n\t\ttype: \"text\",\n\t\tpayload: void 0\n\t};\n\tif (args.length > 0) if (isFetchOptions(args[0])) options = {\n\t\t...options,\n\t\t...args[0]\n\t};\n\telse fetchOptions = args[0];\n\tif (args.length > 1) {\n\t\tif (isFetchOptions(args[1])) options = {\n\t\t\t...options,\n\t\t\t...args[1]\n\t\t};\n\t}\n\tconst { fetch = (_defaultWindow$fetch = defaultWindow === null || defaultWindow === void 0 ? void 0 : defaultWindow.fetch) !== null && _defaultWindow$fetch !== void 0 ? _defaultWindow$fetch : (_globalThis = globalThis) === null || _globalThis === void 0 ? void 0 : _globalThis.fetch, initialData, timeout } = options;\n\tconst responseEvent = createEventHook();\n\tconst errorEvent = createEventHook();\n\tconst finallyEvent = createEventHook();\n\tconst isFinished = shallowRef(false);\n\tconst isFetching = shallowRef(false);\n\tconst aborted = shallowRef(false);\n\tconst statusCode = shallowRef(null);\n\tconst response = shallowRef(null);\n\tconst error = shallowRef(null);\n\tconst data = shallowRef(initialData || null);\n\tconst canAbort = computed(() => supportsAbort && isFetching.value);\n\tlet controller;\n\tlet timer;\n\tconst abort = (reason) => {\n\t\tif (supportsAbort) {\n\t\t\tcontroller === null || controller === void 0 || controller.abort(reason);\n\t\t\tcontroller = new AbortController();\n\t\t\tcontroller.signal.onabort = () => aborted.value = true;\n\t\t\tfetchOptions = {\n\t\t\t\t...fetchOptions,\n\t\t\t\tsignal: controller.signal\n\t\t\t};\n\t\t}\n\t};\n\tconst loading = (isLoading) => {\n\t\tisFetching.value = isLoading;\n\t\tisFinished.value = !isLoading;\n\t};\n\tif (timeout) timer = useTimeoutFn(abort, timeout, { immediate: false });\n\tlet executeCounter = 0;\n\tconst execute = async (throwOnFailed = false) => {\n\t\tvar _context$options;\n\t\tabort();\n\t\tloading(true);\n\t\terror.value = null;\n\t\tstatusCode.value = null;\n\t\taborted.value = false;\n\t\texecuteCounter += 1;\n\t\tconst currentExecuteCounter = executeCounter;\n\t\tconst defaultFetchOptions = {\n\t\t\tmethod: config.method,\n\t\t\theaders: {}\n\t\t};\n\t\tconst payload = toValue(config.payload);\n\t\tif (payload) {\n\t\t\tvar _payloadMapping$confi;\n\t\t\tconst headers = headersToObject(defaultFetchOptions.headers);\n\t\t\tconst proto = Object.getPrototypeOf(payload);\n\t\t\tif (!config.payloadType && payload && (proto === Object.prototype || Array.isArray(proto)) && !(payload instanceof FormData)) config.payloadType = \"json\";\n\t\t\tif (config.payloadType) headers[\"Content-Type\"] = (_payloadMapping$confi = payloadMapping[config.payloadType]) !== null && _payloadMapping$confi !== void 0 ? _payloadMapping$confi : config.payloadType;\n\t\t\tdefaultFetchOptions.body = config.payloadType === \"json\" ? JSON.stringify(payload) : payload;\n\t\t}\n\t\tlet isCanceled = false;\n\t\tconst context = {\n\t\t\turl: toValue(url),\n\t\t\toptions: {\n\t\t\t\t...defaultFetchOptions,\n\t\t\t\t...fetchOptions\n\t\t\t},\n\t\t\tcancel: () => {\n\t\t\t\tisCanceled = true;\n\t\t\t}\n\t\t};\n\t\tif (options.beforeFetch) Object.assign(context, await options.beforeFetch(context));\n\t\tif (isCanceled || !fetch) {\n\t\t\tloading(false);\n\t\t\treturn Promise.resolve(null);\n\t\t}\n\t\tlet responseData = null;\n\t\tif (timer) timer.start();\n\t\treturn fetch(context.url, {\n\t\t\t...defaultFetchOptions,\n\t\t\t...context.options,\n\t\t\theaders: {\n\t\t\t\t...headersToObject(defaultFetchOptions.headers),\n\t\t\t\t...headersToObject((_context$options = context.options) === null || _context$options === void 0 ? void 0 : _context$options.headers)\n\t\t\t}\n\t\t}).then(async (fetchResponse) => {\n\t\t\tresponse.value = fetchResponse;\n\t\t\tstatusCode.value = fetchResponse.status;\n\t\t\tresponseData = await fetchResponse.clone()[config.type]();\n\t\t\tif (!fetchResponse.ok) {\n\t\t\t\tdata.value = initialData || null;\n\t\t\t\tthrow new Error(fetchResponse.statusText);\n\t\t\t}\n\t\t\tif (options.afterFetch) ({data: responseData} = await options.afterFetch({\n\t\t\t\tdata: responseData,\n\t\t\t\tresponse: fetchResponse,\n\t\t\t\tcontext,\n\t\t\t\texecute\n\t\t\t}));\n\t\t\tdata.value = responseData;\n\t\t\tresponseEvent.trigger(fetchResponse);\n\t\t\treturn fetchResponse;\n\t\t}).catch(async (fetchError) => {\n\t\t\tlet errorData = fetchError.message || fetchError.name;\n\t\t\tif (options.onFetchError) ({error: errorData, data: responseData} = await options.onFetchError({\n\t\t\t\tdata: responseData,\n\t\t\t\terror: fetchError,\n\t\t\t\tresponse: response.value,\n\t\t\t\tcontext,\n\t\t\t\texecute\n\t\t\t}));\n\t\t\terror.value = errorData;\n\t\t\tif (options.updateDataOnError) data.value = responseData;\n\t\t\terrorEvent.trigger(fetchError);\n\t\t\tif (throwOnFailed) throw fetchError;\n\t\t\treturn null;\n\t\t}).finally(() => {\n\t\t\tif (currentExecuteCounter === executeCounter) loading(false);\n\t\t\tif (timer) timer.stop();\n\t\t\tfinallyEvent.trigger(null);\n\t\t});\n\t};\n\tconst refetch = toRef(options.refetch);\n\twatch([refetch, toRef(url)], ([refetch]) => refetch && execute(), { deep: true });\n\tconst shell = {\n\t\tisFinished: shallowReadonly(isFinished),\n\t\tisFetching: shallowReadonly(isFetching),\n\t\tstatusCode,\n\t\tresponse,\n\t\terror,\n\t\tdata,\n\t\tcanAbort,\n\t\taborted,\n\t\tabort,\n\t\texecute,\n\t\tonFetchResponse: responseEvent.on,\n\t\tonFetchError: errorEvent.on,\n\t\tonFetchFinally: finallyEvent.on,\n\t\tget: setMethod(\"GET\"),\n\t\tput: setMethod(\"PUT\"),\n\t\tpost: setMethod(\"POST\"),\n\t\tdelete: setMethod(\"DELETE\"),\n\t\tpatch: setMethod(\"PATCH\"),\n\t\thead: setMethod(\"HEAD\"),\n\t\toptions: setMethod(\"OPTIONS\"),\n\t\tjson: setType(\"json\"),\n\t\ttext: setType(\"text\"),\n\t\tblob: setType(\"blob\"),\n\t\tarrayBuffer: setType(\"arrayBuffer\"),\n\t\tformData: setType(\"formData\")\n\t};\n\tfunction setMethod(method) {\n\t\treturn (payload, payloadType) => {\n\t\t\tif (!isFetching.value) {\n\t\t\t\tconfig.method = method;\n\t\t\t\tconfig.payload = payload;\n\t\t\t\tconfig.payloadType = payloadType;\n\t\t\t\tif (isRef(config.payload)) watch([refetch, toRef(config.payload)], ([refetch]) => refetch && execute(), { deep: true });\n\t\t\t\treturn {\n\t\t\t\t\t...shell,\n\t\t\t\t\tthen(onFulfilled, onRejected) {\n\t\t\t\t\t\treturn waitUntilFinished().then(onFulfilled, onRejected);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\t}\n\tfunction waitUntilFinished() {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tuntil(isFinished).toBe(true).then(() => resolve(shell)).catch(reject);\n\t\t});\n\t}\n\tfunction setType(type) {\n\t\treturn () => {\n\t\t\tif (!isFetching.value) {\n\t\t\t\tconfig.type = type;\n\t\t\t\treturn {\n\t\t\t\t\t...shell,\n\t\t\t\t\tthen(onFulfilled, onRejected) {\n\t\t\t\t\t\treturn waitUntilFinished().then(onFulfilled, onRejected);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\t}\n\tif (options.immediate) Promise.resolve().then(() => execute());\n\treturn {\n\t\t...shell,\n\t\tthen(onFulfilled, onRejected) {\n\t\t\treturn waitUntilFinished().then(onFulfilled, onRejected);\n\t\t}\n\t};\n}\nfunction joinPaths(start, end) {\n\tif (!start.endsWith(\"/\") && !end.startsWith(\"/\")) return `${start}/${end}`;\n\tif (start.endsWith(\"/\") && end.startsWith(\"/\")) return `${start.slice(0, -1)}${end}`;\n\treturn `${start}${end}`;\n}\n//#endregion\n//#region useFileDialog/index.ts\nconst DEFAULT_OPTIONS = {\n\tmultiple: true,\n\taccept: \"*\",\n\treset: false,\n\tdirectory: false\n};\nfunction prepareInitialFiles(files) {\n\tif (!files) return null;\n\tif (files instanceof FileList) return files;\n\tconst dt = new DataTransfer();\n\tfor (const file of files) dt.items.add(file);\n\treturn dt.files;\n}\n/**\n* Open file dialog with ease.\n*\n* @see https://vueuse.org/useFileDialog\n* @param options\n*/\nfunction useFileDialog(options = {}) {\n\tconst { document = defaultDocument } = options;\n\tconst files = ref(prepareInitialFiles(options.initialFiles));\n\tconst { on: onChange, trigger: changeTrigger } = createEventHook();\n\tconst { on: onCancel, trigger: cancelTrigger } = createEventHook();\n\tconst inputRef = computed(() => {\n\t\tvar _unrefElement;\n\t\tconst input = (_unrefElement = unrefElement(options.input)) !== null && _unrefElement !== void 0 ? _unrefElement : document ? document.createElement(\"input\") : void 0;\n\t\tif (input) {\n\t\t\tinput.type = \"file\";\n\t\t\tinput.onchange = (event) => {\n\t\t\t\tfiles.value = event.target.files;\n\t\t\t\tchangeTrigger(files.value);\n\t\t\t};\n\t\t\tinput.oncancel = () => {\n\t\t\t\tcancelTrigger();\n\t\t\t};\n\t\t}\n\t\treturn input;\n\t});\n\tconst reset = () => {\n\t\tfiles.value = null;\n\t\tif (inputRef.value && inputRef.value.value) {\n\t\t\tinputRef.value.value = \"\";\n\t\t\tchangeTrigger(null);\n\t\t}\n\t};\n\tconst applyOptions = (options) => {\n\t\tconst el = inputRef.value;\n\t\tif (!el) return;\n\t\tel.multiple = toValue(options.multiple);\n\t\tel.accept = toValue(options.accept);\n\t\tel.webkitdirectory = toValue(options.directory);\n\t\tif (hasOwn(options, \"capture\")) el.capture = toValue(options.capture);\n\t};\n\tconst open = (localOptions) => {\n\t\tconst el = inputRef.value;\n\t\tif (!el) return;\n\t\tconst mergedOptions = {\n\t\t\t...DEFAULT_OPTIONS,\n\t\t\t...options,\n\t\t\t...localOptions\n\t\t};\n\t\tapplyOptions(mergedOptions);\n\t\tif (toValue(mergedOptions.reset)) reset();\n\t\tel.click();\n\t};\n\twatchEffect(() => {\n\t\tapplyOptions(options);\n\t});\n\treturn {\n\t\tfiles: readonly(files),\n\t\topen,\n\t\treset,\n\t\tonCancel,\n\t\tonChange\n\t};\n}\n//#endregion\n//#region useFileSystemAccess/index.ts\nfunction useFileSystemAccess(options = {}) {\n\tconst { window: _window = defaultWindow, dataType = \"Text\" } = options;\n\tconst window = _window;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => window && \"showSaveFilePicker\" in window && \"showOpenFilePicker\" in window);\n\tconst fileHandle = shallowRef();\n\tconst data = shallowRef();\n\tconst file = shallowRef();\n\tconst fileName = computed(() => {\n\t\tvar _file$value$name, _file$value;\n\t\treturn (_file$value$name = (_file$value = file.value) === null || _file$value === void 0 ? void 0 : _file$value.name) !== null && _file$value$name !== void 0 ? _file$value$name : \"\";\n\t});\n\tconst fileMIME = computed(() => {\n\t\tvar _file$value$type, _file$value2;\n\t\treturn (_file$value$type = (_file$value2 = file.value) === null || _file$value2 === void 0 ? void 0 : _file$value2.type) !== null && _file$value$type !== void 0 ? _file$value$type : \"\";\n\t});\n\tconst fileSize = computed(() => {\n\t\tvar _file$value$size, _file$value3;\n\t\treturn (_file$value$size = (_file$value3 = file.value) === null || _file$value3 === void 0 ? void 0 : _file$value3.size) !== null && _file$value$size !== void 0 ? _file$value$size : 0;\n\t});\n\tconst fileLastModified = computed(() => {\n\t\tvar _file$value$lastModif, _file$value4;\n\t\treturn (_file$value$lastModif = (_file$value4 = file.value) === null || _file$value4 === void 0 ? void 0 : _file$value4.lastModified) !== null && _file$value$lastModif !== void 0 ? _file$value$lastModif : 0;\n\t});\n\tasync function open(_options = {}) {\n\t\tif (!isSupported.value) return;\n\t\tconst [handle] = await window.showOpenFilePicker({\n\t\t\t...toValue(options),\n\t\t\t..._options\n\t\t});\n\t\tfileHandle.value = handle;\n\t\tawait updateData();\n\t}\n\tasync function create(_options = {}) {\n\t\tif (!isSupported.value) return;\n\t\tfileHandle.value = await window.showSaveFilePicker({\n\t\t\t...options,\n\t\t\t..._options\n\t\t});\n\t\tdata.value = void 0;\n\t\tawait updateData();\n\t}\n\tasync function save(_options = {}) {\n\t\tif (!isSupported.value) return;\n\t\tif (!fileHandle.value) return saveAs(_options);\n\t\tif (data.value) {\n\t\t\tconst writableStream = await fileHandle.value.createWritable();\n\t\t\tawait writableStream.write(data.value);\n\t\t\tawait writableStream.close();\n\t\t}\n\t\tawait updateFile();\n\t}\n\tasync function saveAs(_options = {}) {\n\t\tif (!isSupported.value) return;\n\t\tfileHandle.value = await window.showSaveFilePicker({\n\t\t\t...options,\n\t\t\t..._options\n\t\t});\n\t\tif (data.value) {\n\t\t\tconst writableStream = await fileHandle.value.createWritable();\n\t\t\tawait writableStream.write(data.value);\n\t\t\tawait writableStream.close();\n\t\t}\n\t\tawait updateFile();\n\t}\n\tasync function updateFile() {\n\t\tvar _fileHandle$value;\n\t\tfile.value = await ((_fileHandle$value = fileHandle.value) === null || _fileHandle$value === void 0 ? void 0 : _fileHandle$value.getFile());\n\t}\n\tasync function updateData() {\n\t\tvar _file$value5, _file$value6;\n\t\tawait updateFile();\n\t\tconst type = toValue(dataType);\n\t\tif (type === \"Text\") data.value = await ((_file$value5 = file.value) === null || _file$value5 === void 0 ? void 0 : _file$value5.text());\n\t\telse if (type === \"ArrayBuffer\") data.value = await ((_file$value6 = file.value) === null || _file$value6 === void 0 ? void 0 : _file$value6.arrayBuffer());\n\t\telse if (type === \"Blob\") data.value = file.value;\n\t}\n\twatch(() => toValue(dataType), updateData);\n\treturn {\n\t\tisSupported,\n\t\tdata,\n\t\tfile,\n\t\tfileName,\n\t\tfileMIME,\n\t\tfileSize,\n\t\tfileLastModified,\n\t\topen,\n\t\tcreate,\n\t\tsave,\n\t\tsaveAs,\n\t\tupdateData\n\t};\n}\n//#endregion\n//#region useFocus/index.ts\n/**\n* Track or set the focus state of a DOM element.\n*\n* @see https://vueuse.org/useFocus\n* @param target The target element for the focus and blur events.\n* @param options\n*/\nfunction useFocus(target, options = {}) {\n\tconst { initialValue = false, focusVisible = false, preventScroll = false } = options;\n\tconst innerFocused = shallowRef(false);\n\tconst targetElement = computed(() => unrefElement(target));\n\tconst listenerOptions = { passive: true };\n\tuseEventListener(targetElement, \"focus\", (event) => {\n\t\tvar _matches, _ref;\n\t\tif (!focusVisible || ((_matches = (_ref = event.target).matches) === null || _matches === void 0 ? void 0 : _matches.call(_ref, \":focus-visible\"))) innerFocused.value = true;\n\t}, listenerOptions);\n\tuseEventListener(targetElement, \"blur\", () => innerFocused.value = false, listenerOptions);\n\tconst focused = computed({\n\t\tget: () => innerFocused.value,\n\t\tset(value) {\n\t\t\tvar _targetElement$value, _targetElement$value2;\n\t\t\tif (!value && innerFocused.value) (_targetElement$value = targetElement.value) === null || _targetElement$value === void 0 || _targetElement$value.blur();\n\t\t\telse if (value && !innerFocused.value) (_targetElement$value2 = targetElement.value) === null || _targetElement$value2 === void 0 || _targetElement$value2.focus({ preventScroll });\n\t\t}\n\t});\n\twatch(targetElement, () => {\n\t\tfocused.value = initialValue;\n\t}, {\n\t\timmediate: true,\n\t\tflush: \"post\"\n\t});\n\treturn { focused };\n}\n//#endregion\n//#region useFocusWithin/index.ts\nconst EVENT_FOCUS_IN = \"focusin\";\nconst EVENT_FOCUS_OUT = \"focusout\";\nconst PSEUDO_CLASS_FOCUS_WITHIN = \":focus-within\";\n/**\n* Track if focus is contained within the target element\n*\n* @see https://vueuse.org/useFocusWithin\n* @param target The target element to track\n* @param options Focus within options\n*/\nfunction useFocusWithin(target, options = {}) {\n\tconst { window = defaultWindow } = options;\n\tconst targetElement = computed(() => unrefElement(target));\n\tconst _focused = shallowRef(false);\n\tconst focused = computed(() => _focused.value);\n\tconst activeElement = useActiveElement(options);\n\tif (!window || !activeElement.value) return { focused };\n\tconst listenerOptions = { passive: true };\n\tuseEventListener(targetElement, EVENT_FOCUS_IN, () => _focused.value = true, listenerOptions);\n\tuseEventListener(targetElement, EVENT_FOCUS_OUT, () => {\n\t\tvar _targetElement$value$, _targetElement$value, _targetElement$value$2;\n\t\treturn _focused.value = (_targetElement$value$ = (_targetElement$value = targetElement.value) === null || _targetElement$value === void 0 || (_targetElement$value$2 = _targetElement$value.matches) === null || _targetElement$value$2 === void 0 ? void 0 : _targetElement$value$2.call(_targetElement$value, PSEUDO_CLASS_FOCUS_WITHIN)) !== null && _targetElement$value$ !== void 0 ? _targetElement$value$ : false;\n\t}, listenerOptions);\n\treturn { focused };\n}\n//#endregion\n//#region useFps/index.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction useFps(options) {\n\tvar _options$every;\n\tconst fps = shallowRef(0);\n\tif (typeof performance === \"undefined\") return fps;\n\tconst every = (_options$every = options === null || options === void 0 ? void 0 : options.every) !== null && _options$every !== void 0 ? _options$every : 10;\n\tlet last = performance.now();\n\tlet ticks = 0;\n\tuseRafFn(() => {\n\t\tticks += 1;\n\t\tif (ticks >= every) {\n\t\t\tconst now = performance.now();\n\t\t\tconst diff = now - last;\n\t\t\tfps.value = Math.round(1e3 / (diff / ticks));\n\t\t\tlast = now;\n\t\t\tticks = 0;\n\t\t}\n\t});\n\treturn fps;\n}\n//#endregion\n//#region useFullscreen/index.ts\nconst eventHandlers = [\n\t\"fullscreenchange\",\n\t\"webkitfullscreenchange\",\n\t\"webkitendfullscreen\",\n\t\"mozfullscreenchange\",\n\t\"MSFullscreenChange\"\n];\n/**\n* Reactive Fullscreen API.\n*\n* @see https://vueuse.org/useFullscreen\n* @param target\n* @param options\n*/\nfunction useFullscreen(target, options = {}) {\n\tconst { document = defaultDocument, autoExit = false } = options;\n\tconst targetRef = computed(() => {\n\t\tvar _unrefElement;\n\t\treturn (_unrefElement = unrefElement(target)) !== null && _unrefElement !== void 0 ? _unrefElement : document === null || document === void 0 ? void 0 : document.documentElement;\n\t});\n\tconst isFullscreen = shallowRef(false);\n\tconst requestMethod = computed(() => {\n\t\treturn [\n\t\t\t\"requestFullscreen\",\n\t\t\t\"webkitRequestFullscreen\",\n\t\t\t\"webkitEnterFullscreen\",\n\t\t\t\"webkitEnterFullScreen\",\n\t\t\t\"webkitRequestFullScreen\",\n\t\t\t\"mozRequestFullScreen\",\n\t\t\t\"msRequestFullscreen\"\n\t\t].find((m) => document && m in document || targetRef.value && m in targetRef.value);\n\t});\n\tconst exitMethod = computed(() => {\n\t\treturn [\n\t\t\t\"exitFullscreen\",\n\t\t\t\"webkitExitFullscreen\",\n\t\t\t\"webkitExitFullScreen\",\n\t\t\t\"webkitCancelFullScreen\",\n\t\t\t\"mozCancelFullScreen\",\n\t\t\t\"msExitFullscreen\"\n\t\t].find((m) => document && m in document || targetRef.value && m in targetRef.value);\n\t});\n\tconst fullscreenEnabled = computed(() => {\n\t\treturn [\n\t\t\t\"fullScreen\",\n\t\t\t\"webkitIsFullScreen\",\n\t\t\t\"webkitDisplayingFullscreen\",\n\t\t\t\"mozFullScreen\",\n\t\t\t\"msFullscreenElement\"\n\t\t].find((m) => document && m in document || targetRef.value && m in targetRef.value);\n\t});\n\tconst fullscreenElementMethod = [\n\t\t\"fullscreenElement\",\n\t\t\"webkitFullscreenElement\",\n\t\t\"mozFullScreenElement\",\n\t\t\"msFullscreenElement\"\n\t].find((m) => document && m in document);\n\tconst isSupported = /* @__PURE__ */ useSupported(() => targetRef.value && document && requestMethod.value !== void 0 && exitMethod.value !== void 0 && fullscreenEnabled.value !== void 0);\n\tconst isCurrentElementFullScreen = () => {\n\t\tif (fullscreenElementMethod) return (document === null || document === void 0 ? void 0 : document[fullscreenElementMethod]) === targetRef.value;\n\t\treturn false;\n\t};\n\tconst isElementFullScreen = () => {\n\t\tif (fullscreenEnabled.value) if (document && document[fullscreenEnabled.value] != null) return document[fullscreenEnabled.value];\n\t\telse {\n\t\t\tconst target = targetRef.value;\n\t\t\tif ((target === null || target === void 0 ? void 0 : target[fullscreenEnabled.value]) != null) return Boolean(target[fullscreenEnabled.value]);\n\t\t}\n\t\treturn false;\n\t};\n\tasync function exit() {\n\t\tif (!isSupported.value || !isFullscreen.value) return;\n\t\tif (exitMethod.value) if ((document === null || document === void 0 ? void 0 : document[exitMethod.value]) != null) await document[exitMethod.value]();\n\t\telse {\n\t\t\tconst target = targetRef.value;\n\t\t\tif ((target === null || target === void 0 ? void 0 : target[exitMethod.value]) != null) await target[exitMethod.value]();\n\t\t}\n\t\tisFullscreen.value = false;\n\t}\n\tasync function enter() {\n\t\tif (!isSupported.value || isFullscreen.value) return;\n\t\tif (isElementFullScreen()) await exit();\n\t\tconst target = targetRef.value;\n\t\tif (requestMethod.value && (target === null || target === void 0 ? void 0 : target[requestMethod.value]) != null) {\n\t\t\tawait target[requestMethod.value]();\n\t\t\tisFullscreen.value = true;\n\t\t}\n\t}\n\tasync function toggle() {\n\t\tawait (isFullscreen.value ? exit() : enter());\n\t}\n\tconst handlerCallback = () => {\n\t\tconst isElementFullScreenValue = isElementFullScreen();\n\t\tif (!isElementFullScreenValue || isElementFullScreenValue && isCurrentElementFullScreen()) isFullscreen.value = isElementFullScreenValue;\n\t};\n\tconst listenerOptions = {\n\t\tcapture: false,\n\t\tpassive: true\n\t};\n\tuseEventListener(document, eventHandlers, handlerCallback, listenerOptions);\n\tuseEventListener(() => unrefElement(targetRef), eventHandlers, handlerCallback, listenerOptions);\n\ttryOnMounted(handlerCallback, false);\n\tif (autoExit) tryOnScopeDispose(exit);\n\treturn {\n\t\tisSupported,\n\t\tisFullscreen,\n\t\tenter,\n\t\texit,\n\t\ttoggle\n\t};\n}\n//#endregion\n//#region useGamepad/index.ts\n/**\n* Maps a standard standard gamepad to an Xbox 360 Controller.\n*/\nfunction mapGamepadToXbox360Controller(gamepad) {\n\treturn computed(() => {\n\t\tif (gamepad.value) return {\n\t\t\tbuttons: {\n\t\t\t\ta: gamepad.value.buttons[0],\n\t\t\t\tb: gamepad.value.buttons[1],\n\t\t\t\tx: gamepad.value.buttons[2],\n\t\t\t\ty: gamepad.value.buttons[3]\n\t\t\t},\n\t\t\tbumper: {\n\t\t\t\tleft: gamepad.value.buttons[4],\n\t\t\t\tright: gamepad.value.buttons[5]\n\t\t\t},\n\t\t\ttriggers: {\n\t\t\t\tleft: gamepad.value.buttons[6],\n\t\t\t\tright: gamepad.value.buttons[7]\n\t\t\t},\n\t\t\tstick: {\n\t\t\t\tleft: {\n\t\t\t\t\thorizontal: gamepad.value.axes[0],\n\t\t\t\t\tvertical: gamepad.value.axes[1],\n\t\t\t\t\tbutton: gamepad.value.buttons[10]\n\t\t\t\t},\n\t\t\t\tright: {\n\t\t\t\t\thorizontal: gamepad.value.axes[2],\n\t\t\t\t\tvertical: gamepad.value.axes[3],\n\t\t\t\t\tbutton: gamepad.value.buttons[11]\n\t\t\t\t}\n\t\t\t},\n\t\t\tdpad: {\n\t\t\t\tup: gamepad.value.buttons[12],\n\t\t\t\tdown: gamepad.value.buttons[13],\n\t\t\t\tleft: gamepad.value.buttons[14],\n\t\t\t\tright: gamepad.value.buttons[15]\n\t\t\t},\n\t\t\tback: gamepad.value.buttons[8],\n\t\t\tstart: gamepad.value.buttons[9]\n\t\t};\n\t\treturn null;\n\t});\n}\n/* @__NO_SIDE_EFFECTS__ */\nfunction useGamepad(options = {}) {\n\tconst { navigator = defaultNavigator } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => navigator && \"getGamepads\" in navigator);\n\tconst gamepads = ref([]);\n\tconst onConnectedHook = createEventHook();\n\tconst onDisconnectedHook = createEventHook();\n\tconst stateFromGamepad = (gamepad) => {\n\t\tconst hapticActuators = [];\n\t\tconst vibrationActuator = \"vibrationActuator\" in gamepad ? gamepad.vibrationActuator : null;\n\t\tif (vibrationActuator) hapticActuators.push(vibrationActuator);\n\t\tif (gamepad.hapticActuators) hapticActuators.push(...gamepad.hapticActuators);\n\t\treturn {\n\t\t\tid: gamepad.id,\n\t\t\tindex: gamepad.index,\n\t\t\tconnected: gamepad.connected,\n\t\t\tmapping: gamepad.mapping,\n\t\t\ttimestamp: gamepad.timestamp,\n\t\t\tvibrationActuator: gamepad.vibrationActuator,\n\t\t\thapticActuators,\n\t\t\taxes: gamepad.axes.map((axes) => axes),\n\t\t\tbuttons: gamepad.buttons.map((button) => ({\n\t\t\t\tpressed: button.pressed,\n\t\t\t\ttouched: button.touched,\n\t\t\t\tvalue: button.value\n\t\t\t}))\n\t\t};\n\t};\n\tconst updateGamepadState = () => {\n\t\tconst _gamepads = (navigator === null || navigator === void 0 ? void 0 : navigator.getGamepads()) || [];\n\t\tfor (const gamepad of _gamepads) if (gamepad && gamepads.value[gamepad.index]) gamepads.value[gamepad.index] = stateFromGamepad(gamepad);\n\t};\n\tconst { isActive, pause, resume } = useRafFn(updateGamepadState);\n\tconst onGamepadConnected = (gamepad) => {\n\t\tif (!gamepads.value.some(({ index }) => index === gamepad.index)) {\n\t\t\tgamepads.value.push(stateFromGamepad(gamepad));\n\t\t\tonConnectedHook.trigger(gamepad.index);\n\t\t}\n\t\tresume();\n\t};\n\tconst onGamepadDisconnected = (gamepad) => {\n\t\tgamepads.value = gamepads.value.filter((x) => x.index !== gamepad.index);\n\t\tonDisconnectedHook.trigger(gamepad.index);\n\t};\n\tconst listenerOptions = { passive: true };\n\tuseEventListener(\"gamepadconnected\", (e) => onGamepadConnected(e.gamepad), listenerOptions);\n\tuseEventListener(\"gamepaddisconnected\", (e) => onGamepadDisconnected(e.gamepad), listenerOptions);\n\ttryOnMounted(() => {\n\t\tconst _gamepads = (navigator === null || navigator === void 0 ? void 0 : navigator.getGamepads()) || [];\n\t\tfor (const gamepad of _gamepads) if (gamepad && gamepads.value[gamepad.index]) onGamepadConnected(gamepad);\n\t});\n\tpause();\n\treturn {\n\t\tisSupported,\n\t\tonConnected: onConnectedHook.on,\n\t\tonDisconnected: onDisconnectedHook.on,\n\t\tgamepads,\n\t\tpause,\n\t\tresume,\n\t\tisActive\n\t};\n}\n//#endregion\n//#region useGeolocation/index.ts\n/**\n* Reactive Geolocation API.\n*\n* @see https://vueuse.org/useGeolocation\n* @param options\n*/\nfunction useGeolocation(options = {}) {\n\tconst { enableHighAccuracy = true, maximumAge = 3e4, timeout = 27e3, navigator = defaultNavigator, immediate = true } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => navigator && \"geolocation\" in navigator);\n\tconst locatedAt = shallowRef(null);\n\tconst error = shallowRef(null);\n\tconst coords = shallowRef({\n\t\taccuracy: 0,\n\t\tlatitude: Number.POSITIVE_INFINITY,\n\t\tlongitude: Number.POSITIVE_INFINITY,\n\t\taltitude: null,\n\t\taltitudeAccuracy: null,\n\t\theading: null,\n\t\tspeed: null\n\t});\n\tfunction updatePosition(position) {\n\t\tlocatedAt.value = position.timestamp;\n\t\tcoords.value = position.coords;\n\t\terror.value = null;\n\t}\n\tlet watcher;\n\tfunction resume() {\n\t\tif (isSupported.value) watcher = navigator.geolocation.watchPosition(updatePosition, (err) => error.value = err, {\n\t\t\tenableHighAccuracy,\n\t\t\tmaximumAge,\n\t\t\ttimeout\n\t\t});\n\t}\n\tif (immediate) resume();\n\tfunction pause() {\n\t\tif (watcher && navigator) navigator.geolocation.clearWatch(watcher);\n\t}\n\ttryOnScopeDispose(() => {\n\t\tpause();\n\t});\n\treturn {\n\t\tisSupported,\n\t\tcoords,\n\t\tlocatedAt,\n\t\terror,\n\t\tresume,\n\t\tpause\n\t};\n}\n//#endregion\n//#region useIdle/index.ts\nconst defaultEvents$1 = [\n\t\"mousemove\",\n\t\"mousedown\",\n\t\"resize\",\n\t\"keydown\",\n\t\"touchstart\",\n\t\"wheel\"\n];\nconst oneMinute = 6e4;\n/**\n* Tracks whether the user is being inactive.\n*\n* @see https://vueuse.org/useIdle\n* @param timeout default to 1 minute\n* @param options IdleOptions\n*/\nfunction useIdle(timeout = oneMinute, options = {}) {\n\tconst { initialState = false, listenForVisibilityChange = true, events = defaultEvents$1, window = defaultWindow, eventFilter = throttleFilter(50) } = options;\n\tconst idle = shallowRef(initialState);\n\tconst lastActive = shallowRef(timestamp());\n\tconst isPending = shallowRef(false);\n\tlet timer;\n\tconst reset = () => {\n\t\tidle.value = false;\n\t\tclearTimeout(timer);\n\t\ttimer = setTimeout(() => idle.value = true, timeout);\n\t};\n\tconst onEvent = createFilterWrapper(eventFilter, () => {\n\t\tlastActive.value = timestamp();\n\t\treset();\n\t});\n\tif (window) {\n\t\tconst document = window.document;\n\t\tconst listenerOptions = { passive: true };\n\t\tfor (const event of events) useEventListener(window, event, () => {\n\t\t\tif (!isPending.value) return;\n\t\t\tonEvent();\n\t\t}, listenerOptions);\n\t\tif (listenForVisibilityChange) useEventListener(document, \"visibilitychange\", () => {\n\t\t\tif (document.hidden || !isPending.value) return;\n\t\t\tonEvent();\n\t\t}, listenerOptions);\n\t\tstart();\n\t}\n\tfunction start() {\n\t\tif (isPending.value) return;\n\t\tisPending.value = true;\n\t\tif (!initialState) reset();\n\t}\n\tfunction stop() {\n\t\tidle.value = initialState;\n\t\tclearTimeout(timer);\n\t\tisPending.value = false;\n\t}\n\treturn {\n\t\tidle,\n\t\tlastActive,\n\t\treset,\n\t\tstop,\n\t\tstart,\n\t\tisPending: shallowReadonly(isPending)\n\t};\n}\n//#endregion\n//#region useImage/index.ts\nasync function loadImage(options) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst img = new Image();\n\t\tconst { src, srcset, sizes, class: clazz, loading, crossorigin, referrerPolicy, width, height, decoding, fetchPriority, ismap, usemap } = options;\n\t\timg.src = src;\n\t\tif (srcset != null) img.srcset = srcset;\n\t\tif (sizes != null) img.sizes = sizes;\n\t\tif (clazz != null) img.className = clazz;\n\t\tif (loading != null) img.loading = loading;\n\t\tif (crossorigin != null) img.crossOrigin = crossorigin;\n\t\tif (referrerPolicy != null) img.referrerPolicy = referrerPolicy;\n\t\tif (width != null) img.width = width;\n\t\tif (height != null) img.height = height;\n\t\tif (decoding != null) img.decoding = decoding;\n\t\tif (fetchPriority != null) img.fetchPriority = fetchPriority;\n\t\tif (ismap != null) img.isMap = ismap;\n\t\tif (usemap != null) img.useMap = usemap;\n\t\timg.onload = () => resolve(img);\n\t\timg.onerror = reject;\n\t});\n}\n/**\n* Reactive load an image in the browser, you can wait the result to display it or show a fallback.\n*\n* @see https://vueuse.org/useImage\n* @param options Image attributes, as used in the <img> tag\n* @param asyncStateOptions\n*/\nfunction useImage(options, asyncStateOptions = {}) {\n\tconst state = useAsyncState(() => loadImage(toValue(options)), void 0, {\n\t\tresetOnExecute: true,\n\t\t...asyncStateOptions\n\t});\n\twatch(() => toValue(options), () => state.execute(asyncStateOptions.delay), { deep: true });\n\treturn state;\n}\n//#endregion\n//#region _resolve-element.ts\n/**\n* Resolves an element from a given element, window, or document.\n*\n* @internal\n*/\nfunction resolveElement(el) {\n\tif (typeof Window !== \"undefined\" && el instanceof Window) return el.document.documentElement;\n\tif (typeof Document !== \"undefined\" && el instanceof Document) return el.documentElement;\n\treturn el;\n}\n//#endregion\n//#region useScroll/index.ts\n/**\n* We have to check if the scroll amount is close enough to some threshold in order to\n* more accurately calculate arrivedState. This is because scrollTop/scrollLeft are non-rounded\n* numbers, while scrollHeight/scrollWidth and clientHeight/clientWidth are rounded.\n* https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#determine_if_an_element_has_been_totally_scrolled\n*/\nconst ARRIVED_STATE_THRESHOLD_PIXELS = 1;\n/**\n* Reactive scroll.\n*\n* @see https://vueuse.org/useScroll\n* @param element\n* @param options\n*/\nfunction useScroll(element, options = {}) {\n\tconst { throttle = 0, idle = 200, onStop = noop, onScroll = noop, offset = {\n\t\tleft: 0,\n\t\tright: 0,\n\t\ttop: 0,\n\t\tbottom: 0\n\t}, observe: _observe = { mutation: false }, eventListenerOptions = {\n\t\tcapture: false,\n\t\tpassive: true\n\t}, behavior = \"auto\", window = defaultWindow, onError = (e) => {\n\t\tconsole.error(e);\n\t} } = options;\n\tconst observe = typeof _observe === \"boolean\" ? { mutation: _observe } : _observe;\n\tconst internalX = shallowRef(0);\n\tconst internalY = shallowRef(0);\n\tconst x = computed({\n\t\tget() {\n\t\t\treturn internalX.value;\n\t\t},\n\t\tset(x) {\n\t\t\tscrollTo(x, void 0);\n\t\t}\n\t});\n\tconst y = computed({\n\t\tget() {\n\t\t\treturn internalY.value;\n\t\t},\n\t\tset(y) {\n\t\t\tscrollTo(void 0, y);\n\t\t}\n\t});\n\tfunction scrollTo(_x, _y) {\n\t\tvar _ref, _toValue, _toValue2, _document;\n\t\tif (!window) return;\n\t\tconst _element = toValue(element);\n\t\tif (!_element) return;\n\t\t(_ref = _element instanceof Document ? window.document.body : _element) === null || _ref === void 0 || _ref.scrollTo({\n\t\t\ttop: (_toValue = toValue(_y)) !== null && _toValue !== void 0 ? _toValue : y.value,\n\t\t\tleft: (_toValue2 = toValue(_x)) !== null && _toValue2 !== void 0 ? _toValue2 : x.value,\n\t\t\tbehavior: toValue(behavior)\n\t\t});\n\t\tconst scrollContainer = (_element === null || _element === void 0 || (_document = _element.document) === null || _document === void 0 ? void 0 : _document.documentElement) || (_element === null || _element === void 0 ? void 0 : _element.documentElement) || _element;\n\t\tif (x != null) internalX.value = scrollContainer.scrollLeft;\n\t\tif (y != null) internalY.value = scrollContainer.scrollTop;\n\t}\n\tconst isScrolling = shallowRef(false);\n\tconst arrivedState = reactive({\n\t\tleft: true,\n\t\tright: false,\n\t\ttop: true,\n\t\tbottom: false\n\t});\n\tconst directions = reactive({\n\t\tleft: false,\n\t\tright: false,\n\t\ttop: false,\n\t\tbottom: false\n\t});\n\tconst onScrollEnd = (e) => {\n\t\tif (!isScrolling.value) return;\n\t\tisScrolling.value = false;\n\t\tdirections.left = false;\n\t\tdirections.right = false;\n\t\tdirections.top = false;\n\t\tdirections.bottom = false;\n\t\tonStop(e);\n\t};\n\tconst onScrollEndDebounced = useDebounceFn(onScrollEnd, throttle + idle);\n\tconst setArrivedState = (target) => {\n\t\tvar _document2;\n\t\tif (!window) return;\n\t\tconst el = (target === null || target === void 0 || (_document2 = target.document) === null || _document2 === void 0 ? void 0 : _document2.documentElement) || (target === null || target === void 0 ? void 0 : target.documentElement) || unrefElement(target);\n\t\tconst { display, flexDirection, direction } = window.getComputedStyle(el);\n\t\tconst directionMultipler = direction === \"rtl\" ? -1 : 1;\n\t\tconst scrollLeft = el.scrollLeft;\n\t\tdirections.left = scrollLeft < internalX.value;\n\t\tdirections.right = scrollLeft > internalX.value;\n\t\tconst left = Math.abs(scrollLeft * directionMultipler) <= (offset.left || 0);\n\t\tconst right = Math.abs(scrollLeft * directionMultipler) + el.clientWidth >= el.scrollWidth - (offset.right || 0) - ARRIVED_STATE_THRESHOLD_PIXELS;\n\t\tif (display === \"flex\" && flexDirection === \"row-reverse\") {\n\t\t\tarrivedState.left = right;\n\t\t\tarrivedState.right = left;\n\t\t} else {\n\t\t\tarrivedState.left = left;\n\t\t\tarrivedState.right = right;\n\t\t}\n\t\tinternalX.value = scrollLeft;\n\t\tlet scrollTop = el.scrollTop;\n\t\tif (target === window.document && !scrollTop) scrollTop = window.document.body.scrollTop;\n\t\tdirections.top = scrollTop < internalY.value;\n\t\tdirections.bottom = scrollTop > internalY.value;\n\t\tconst top = Math.abs(scrollTop) <= (offset.top || 0);\n\t\tconst bottom = Math.abs(scrollTop) + el.clientHeight >= el.scrollHeight - (offset.bottom || 0) - ARRIVED_STATE_THRESHOLD_PIXELS;\n\t\t/**\n\t\t* reverse columns and rows behave exactly the other way around,\n\t\t* bottom is treated as top and top is treated as the negative version of bottom\n\t\t*/\n\t\tif (display === \"flex\" && flexDirection === \"column-reverse\") {\n\t\t\tarrivedState.top = bottom;\n\t\t\tarrivedState.bottom = top;\n\t\t} else {\n\t\t\tarrivedState.top = top;\n\t\t\tarrivedState.bottom = bottom;\n\t\t}\n\t\tinternalY.value = scrollTop;\n\t};\n\tconst onScrollHandler = (e) => {\n\t\tvar _documentElement;\n\t\tif (!window) return;\n\t\tsetArrivedState((_documentElement = e.target.documentElement) !== null && _documentElement !== void 0 ? _documentElement : e.target);\n\t\tisScrolling.value = true;\n\t\tonScrollEndDebounced(e);\n\t\tonScroll(e);\n\t};\n\tuseEventListener(element, \"scroll\", throttle ? useThrottleFn(onScrollHandler, throttle, true, false) : onScrollHandler, eventListenerOptions);\n\ttryOnMounted(() => {\n\t\ttry {\n\t\t\tconst _element = toValue(element);\n\t\t\tif (!_element) return;\n\t\t\tsetArrivedState(_element);\n\t\t} catch (e) {\n\t\t\tonError(e);\n\t\t}\n\t});\n\tif ((observe === null || observe === void 0 ? void 0 : observe.mutation) && element != null && element !== window && element !== document) useMutationObserver(element, () => {\n\t\tconst _element = toValue(element);\n\t\tif (!_element) return;\n\t\tsetArrivedState(_element);\n\t}, {\n\t\tattributes: true,\n\t\tchildList: true,\n\t\tsubtree: true\n\t});\n\tuseEventListener(element, \"scrollend\", onScrollEnd, eventListenerOptions);\n\treturn {\n\t\tx,\n\t\ty,\n\t\tisScrolling,\n\t\tarrivedState,\n\t\tdirections,\n\t\tmeasure() {\n\t\t\tconst _element = toValue(element);\n\t\t\tif (window && _element) setArrivedState(_element);\n\t\t}\n\t};\n}\n//#endregion\n//#region useInfiniteScroll/index.ts\n/**\n* Reactive infinite scroll.\n*\n* @see https://vueuse.org/useInfiniteScroll\n*/\nfunction useInfiniteScroll(element, onLoadMore, options = {}) {\n\tvar _options$distance;\n\tconst { direction = \"bottom\", interval = 100, canLoadMore = () => true } = options;\n\tconst state = reactive(useScroll(element, {\n\t\t...options,\n\t\toffset: {\n\t\t\t[direction]: (_options$distance = options.distance) !== null && _options$distance !== void 0 ? _options$distance : 0,\n\t\t\t...options.offset\n\t\t}\n\t}));\n\tconst promise = shallowRef();\n\tconst isLoading = computed(() => !!promise.value);\n\tconst observedElement = computed(() => {\n\t\treturn resolveElement(toValue(element));\n\t});\n\tconst isElementVisible = useElementVisibility(observedElement);\n\tconst canLoad = computed(() => {\n\t\tif (!observedElement.value) return false;\n\t\treturn canLoadMore(observedElement.value);\n\t});\n\tfunction checkAndLoad() {\n\t\tstate.measure();\n\t\tif (!observedElement.value || !isElementVisible.value || !canLoad.value || promise.value) return;\n\t\tconst { scrollHeight, clientHeight, scrollWidth, clientWidth } = observedElement.value;\n\t\tconst isNarrower = direction === \"bottom\" || direction === \"top\" ? scrollHeight <= clientHeight : scrollWidth <= clientWidth;\n\t\tif (state.arrivedState[direction] || isNarrower) promise.value = Promise.all([onLoadMore(state), new Promise((resolve) => setTimeout(resolve, interval))]).finally(() => {\n\t\t\tpromise.value = null;\n\t\t\tnextTick(() => checkAndLoad());\n\t\t});\n\t}\n\ttryOnUnmounted(watch(() => [\n\t\tstate.arrivedState[direction],\n\t\tisElementVisible.value,\n\t\tcanLoad.value\n\t], checkAndLoad, {\n\t\timmediate: true,\n\t\tflush: \"post\"\n\t}));\n\treturn {\n\t\tisLoading,\n\t\treset() {\n\t\t\tnextTick(() => checkAndLoad());\n\t\t}\n\t};\n}\n//#endregion\n//#region useKeyModifier/index.ts\nconst defaultEvents = [\n\t\"mousedown\",\n\t\"mouseup\",\n\t\"keydown\",\n\t\"keyup\"\n];\n/* @__NO_SIDE_EFFECTS__ */\nfunction useKeyModifier(modifier, options = {}) {\n\tconst { events = defaultEvents, document = defaultDocument, initial = null } = options;\n\tconst state = shallowRef(initial);\n\tif (document) events.forEach((listenerEvent) => {\n\t\tuseEventListener(document, listenerEvent, (evt) => {\n\t\t\tif (typeof evt.getModifierState === \"function\") state.value = evt.getModifierState(modifier);\n\t\t}, { passive: true });\n\t});\n\treturn state;\n}\n//#endregion\n//#region useLocalStorage/index.ts\n/**\n* Reactive LocalStorage.\n*\n* @see https://vueuse.org/useLocalStorage\n* @param key\n* @param initialValue\n* @param options\n*/\nfunction useLocalStorage(key, initialValue, options = {}) {\n\tconst { window = defaultWindow } = options;\n\treturn useStorage(key, initialValue, window === null || window === void 0 ? void 0 : window.localStorage, options);\n}\n//#endregion\n//#region useMagicKeys/aliasMap.ts\nconst DefaultMagicKeysAliasMap = {\n\tctrl: \"control\",\n\tcommand: \"meta\",\n\tcmd: \"meta\",\n\toption: \"alt\",\n\tup: \"arrowup\",\n\tdown: \"arrowdown\",\n\tleft: \"arrowleft\",\n\tright: \"arrowright\"\n};\n//#endregion\n//#region useMagicKeys/index.ts\n/**\n* Reactive keys pressed state, with magical keys combination support.\n*\n* @see https://vueuse.org/useMagicKeys\n*/\nfunction useMagicKeys(options = {}) {\n\tconst { reactive: useReactive = false, target = defaultWindow, aliasMap = DefaultMagicKeysAliasMap, passive = true, onEventFired = noop } = options;\n\tconst current = reactive(/* @__PURE__ */ new Set());\n\tconst obj = {\n\t\ttoJSON() {\n\t\t\treturn {};\n\t\t},\n\t\tcurrent\n\t};\n\tconst refs = useReactive ? reactive(obj) : obj;\n\tconst metaDeps = /* @__PURE__ */ new Set();\n\tconst depsMap = new Map([\n\t\t[\"Meta\", metaDeps],\n\t\t[\"Shift\", /* @__PURE__ */ new Set()],\n\t\t[\"Alt\", /* @__PURE__ */ new Set()]\n\t]);\n\tconst usedKeys = /* @__PURE__ */ new Set();\n\tfunction setRefs(key, value) {\n\t\tif (key in refs) if (useReactive) refs[key] = value;\n\t\telse refs[key].value = value;\n\t}\n\tfunction reset() {\n\t\tcurrent.clear();\n\t\tfor (const key of usedKeys) setRefs(key, false);\n\t}\n\tfunction updateDeps(value, e, keys) {\n\t\tif (!value || typeof e.getModifierState !== \"function\") return;\n\t\tfor (const [modifier, depsSet] of depsMap) if (e.getModifierState(modifier)) {\n\t\t\tkeys.forEach((key) => depsSet.add(key));\n\t\t\tbreak;\n\t\t}\n\t}\n\tfunction clearDeps(value, key) {\n\t\tif (value) return;\n\t\tconst depsMapKey = `${key[0].toUpperCase()}${key.slice(1)}`;\n\t\tconst deps = depsMap.get(depsMapKey);\n\t\tif (![\"shift\", \"alt\"].includes(key) || !deps) return;\n\t\tconst depsArray = Array.from(deps);\n\t\tconst depsIndex = depsArray.indexOf(key);\n\t\tdepsArray.forEach((key, index) => {\n\t\t\tif (index >= depsIndex) {\n\t\t\t\tcurrent.delete(key);\n\t\t\t\tsetRefs(key, false);\n\t\t\t}\n\t\t});\n\t\tdeps.clear();\n\t}\n\tfunction updateRefs(e, value) {\n\t\tvar _e$key, _e$code;\n\t\tconst key = (_e$key = e.key) === null || _e$key === void 0 ? void 0 : _e$key.toLowerCase();\n\t\tconst values = [(_e$code = e.code) === null || _e$code === void 0 ? void 0 : _e$code.toLowerCase(), key].filter(Boolean);\n\t\tif (!key) return;\n\t\tif (key) if (value) current.add(key);\n\t\telse current.delete(key);\n\t\tfor (const key of values) {\n\t\t\tusedKeys.add(key);\n\t\t\tsetRefs(key, value);\n\t\t}\n\t\tupdateDeps(value, e, [...current, ...values]);\n\t\tclearDeps(value, key);\n\t\tif (key === \"meta\" && !value) {\n\t\t\tmetaDeps.forEach((key) => {\n\t\t\t\tcurrent.delete(key);\n\t\t\t\tsetRefs(key, false);\n\t\t\t});\n\t\t\tmetaDeps.clear();\n\t\t}\n\t}\n\tuseEventListener(target, \"keydown\", (e) => {\n\t\tupdateRefs(e, true);\n\t\treturn onEventFired(e);\n\t}, { passive });\n\tuseEventListener(target, \"keyup\", (e) => {\n\t\tupdateRefs(e, false);\n\t\treturn onEventFired(e);\n\t}, { passive });\n\tuseEventListener(\"blur\", reset, { passive });\n\tuseEventListener(\"focus\", reset, { passive });\n\tconst proxy = new Proxy(refs, { get(target, prop, rec) {\n\t\tif (typeof prop !== \"string\") return Reflect.get(target, prop, rec);\n\t\tprop = prop.toLowerCase();\n\t\tif (prop in aliasMap) prop = aliasMap[prop];\n\t\tif (!(prop in refs)) if (/[+_-]/.test(prop)) {\n\t\t\tconst keys = prop.split(/[+_-]/g).map((i) => i.trim());\n\t\t\trefs[prop] = computed(() => keys.map((key) => toValue(proxy[key])).every(Boolean));\n\t\t} else refs[prop] = shallowRef(false);\n\t\tconst r = Reflect.get(target, prop, rec);\n\t\treturn useReactive ? toValue(r) : r;\n\t} });\n\treturn proxy;\n}\n//#endregion\n//#region useMediaControls/index.ts\n/**\n* Automatically check if the ref exists and if it does run the cb fn\n*/\nfunction usingElRef(source, cb) {\n\tif (toValue(source)) cb(toValue(source));\n}\n/**\n* Converts a TimeRange object to an array\n*/\nfunction timeRangeToArray(timeRanges) {\n\tlet ranges = [];\n\tfor (let i = 0; i < timeRanges.length; ++i) ranges = [...ranges, [timeRanges.start(i), timeRanges.end(i)]];\n\treturn ranges;\n}\n/**\n* Converts a TextTrackList object to an array of `UseMediaTextTrack`\n*/\nfunction tracksToArray(tracks) {\n\treturn Array.from(tracks).map(({ label, kind, language, mode, activeCues, cues, inBandMetadataTrackDispatchType }, id) => ({\n\t\tid,\n\t\tlabel,\n\t\tkind,\n\t\tlanguage,\n\t\tmode,\n\t\tactiveCues,\n\t\tcues,\n\t\tinBandMetadataTrackDispatchType\n\t}));\n}\nconst defaultOptions = {\n\tsrc: \"\",\n\ttracks: []\n};\nfunction useMediaControls(target, options = {}) {\n\ttarget = toRef(target);\n\toptions = {\n\t\t...defaultOptions,\n\t\t...options\n\t};\n\tconst { document = defaultDocument } = options;\n\tconst listenerOptions = { passive: true };\n\tconst currentTime = shallowRef(0);\n\tconst duration = shallowRef(0);\n\tconst seeking = shallowRef(false);\n\tconst volume = shallowRef(1);\n\tconst waiting = shallowRef(false);\n\tconst ended = shallowRef(false);\n\tconst playing = shallowRef(false);\n\tconst rate = shallowRef(1);\n\tconst stalled = shallowRef(false);\n\tconst buffered = shallowRef([]);\n\tconst tracks = shallowRef([]);\n\tconst selectedTrack = shallowRef(-1);\n\tconst isPictureInPicture = shallowRef(false);\n\tconst muted = shallowRef(false);\n\tconst supportsPictureInPicture = Boolean(document && \"pictureInPictureEnabled\" in document);\n\tconst sourceErrorEvent = createEventHook();\n\tconst playbackErrorEvent = createEventHook();\n\t/**\n\t* Disables the specified track. If no track is specified then\n\t* all tracks will be disabled\n\t*\n\t* @param track The id of the track to disable\n\t*/\n\tconst disableTrack = (track) => {\n\t\tusingElRef(target, (el) => {\n\t\t\tif (track) {\n\t\t\t\tconst id = typeof track === \"number\" ? track : track.id;\n\t\t\t\tel.textTracks[id].mode = \"disabled\";\n\t\t\t} else for (let i = 0; i < el.textTracks.length; ++i) el.textTracks[i].mode = \"disabled\";\n\t\t\tselectedTrack.value = -1;\n\t\t});\n\t};\n\t/**\n\t* Enables the specified track and disables the\n\t* other tracks unless otherwise specified\n\t*\n\t* @param track The track of the id of the track to enable\n\t* @param disableTracks Disable all other tracks\n\t*/\n\tconst enableTrack = (track, disableTracks = true) => {\n\t\tusingElRef(target, (el) => {\n\t\t\tconst id = typeof track === \"number\" ? track : track.id;\n\t\t\tif (disableTracks) disableTrack();\n\t\t\tel.textTracks[id].mode = \"showing\";\n\t\t\tselectedTrack.value = id;\n\t\t});\n\t};\n\t/**\n\t* Toggle picture in picture mode for the player.\n\t*/\n\tconst togglePictureInPicture = () => {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tusingElRef(target, async (el) => {\n\t\t\t\tif (supportsPictureInPicture) if (!isPictureInPicture.value) el.requestPictureInPicture().then(resolve).catch(reject);\n\t\t\t\telse document.exitPictureInPicture().then(resolve).catch(reject);\n\t\t\t});\n\t\t});\n\t};\n\t/**\n\t* This will automatically inject sources to the media element. The sources will be\n\t* appended as children to the media element as `<source>` elements.\n\t*/\n\twatchEffect(() => {\n\t\tif (!document) return;\n\t\tconst el = toValue(target);\n\t\tif (!el) return;\n\t\tconst src = toValue(options.src);\n\t\tlet sources = [];\n\t\tif (!src) return;\n\t\tif (typeof src === \"string\") sources = [{ src }];\n\t\telse if (Array.isArray(src)) sources = src;\n\t\telse if (isObject(src)) sources = [src];\n\t\tel.querySelectorAll(\"source\").forEach((e) => {\n\t\t\te.remove();\n\t\t});\n\t\tsources.forEach(({ src, type, media }) => {\n\t\t\tconst source = document.createElement(\"source\");\n\t\t\tsource.setAttribute(\"src\", src);\n\t\t\tsource.setAttribute(\"type\", type || \"\");\n\t\t\tsource.setAttribute(\"media\", media || \"\");\n\t\t\tuseEventListener(source, \"error\", sourceErrorEvent.trigger, listenerOptions);\n\t\t\tel.appendChild(source);\n\t\t});\n\t\tel.load();\n\t});\n\t/**\n\t* Apply composable state to the element, also when element is changed\n\t*/\n\twatch([target, volume], () => {\n\t\tconst el = toValue(target);\n\t\tif (!el) return;\n\t\tel.volume = volume.value;\n\t});\n\twatch([target, muted], () => {\n\t\tconst el = toValue(target);\n\t\tif (!el) return;\n\t\tel.muted = muted.value;\n\t});\n\twatch([target, rate], () => {\n\t\tconst el = toValue(target);\n\t\tif (!el) return;\n\t\tel.playbackRate = rate.value;\n\t});\n\t/**\n\t* Load Tracks\n\t*/\n\twatchEffect(() => {\n\t\tif (!document) return;\n\t\tconst textTracks = toValue(options.tracks);\n\t\tconst el = toValue(target);\n\t\tif (!textTracks || !textTracks.length || !el) return;\n\t\t/**\n\t\t* The MediaAPI provides an API for adding text tracks, but they don't currently\n\t\t* have an API for removing text tracks, so instead we will just create and remove\n\t\t* the tracks manually using the HTML api.\n\t\t*/\n\t\tel.querySelectorAll(\"track\").forEach((e) => e.remove());\n\t\ttextTracks.forEach(({ default: isDefault, kind, label, src, srcLang }, i) => {\n\t\t\tconst track = document.createElement(\"track\");\n\t\t\ttrack.default = isDefault || false;\n\t\t\ttrack.kind = kind;\n\t\t\ttrack.label = label;\n\t\t\ttrack.src = src;\n\t\t\ttrack.srclang = srcLang;\n\t\t\tif (track.default) selectedTrack.value = i;\n\t\t\tel.appendChild(track);\n\t\t});\n\t});\n\t/**\n\t* This will allow us to update the current time from the timeupdate event\n\t* without setting the medias current position, but if the user changes the\n\t* current time via the ref, then the media will seek.\n\t*\n\t* If we did not use an ignorable watch, then the current time update from\n\t* the timeupdate event would cause the media to stutter.\n\t*/\n\tconst { ignoreUpdates: ignoreCurrentTimeUpdates } = watchIgnorable(currentTime, (time) => {\n\t\tconst el = toValue(target);\n\t\tif (!el) return;\n\t\tel.currentTime = time;\n\t});\n\t/**\n\t* Using an ignorable watch so we can control the play state using a ref and not\n\t* a function\n\t*/\n\tconst { ignoreUpdates: ignorePlayingUpdates } = watchIgnorable(playing, (isPlaying) => {\n\t\tconst el = toValue(target);\n\t\tif (!el) return;\n\t\tif (isPlaying) el.play().catch((e) => {\n\t\t\tplaybackErrorEvent.trigger(e);\n\t\t\tthrow e;\n\t\t});\n\t\telse el.pause();\n\t});\n\tuseEventListener(target, \"timeupdate\", () => ignoreCurrentTimeUpdates(() => currentTime.value = toValue(target).currentTime), listenerOptions);\n\tuseEventListener(target, \"durationchange\", () => duration.value = toValue(target).duration, listenerOptions);\n\tuseEventListener(target, \"progress\", () => buffered.value = timeRangeToArray(toValue(target).buffered), listenerOptions);\n\tuseEventListener(target, \"seeking\", () => seeking.value = true, listenerOptions);\n\tuseEventListener(target, \"seeked\", () => seeking.value = false, listenerOptions);\n\tuseEventListener(target, [\"waiting\", \"loadstart\"], () => {\n\t\twaiting.value = true;\n\t\tignorePlayingUpdates(() => playing.value = false);\n\t}, listenerOptions);\n\tuseEventListener(target, \"loadeddata\", () => waiting.value = false, listenerOptions);\n\tuseEventListener(target, \"playing\", () => {\n\t\twaiting.value = false;\n\t\tended.value = false;\n\t\tignorePlayingUpdates(() => playing.value = true);\n\t}, listenerOptions);\n\tuseEventListener(target, \"ratechange\", () => rate.value = toValue(target).playbackRate, listenerOptions);\n\tuseEventListener(target, \"stalled\", () => stalled.value = true, listenerOptions);\n\tuseEventListener(target, \"ended\", () => ended.value = true, listenerOptions);\n\tuseEventListener(target, \"pause\", () => ignorePlayingUpdates(() => playing.value = false), listenerOptions);\n\tuseEventListener(target, \"play\", () => ignorePlayingUpdates(() => playing.value = true), listenerOptions);\n\tuseEventListener(target, \"enterpictureinpicture\", () => isPictureInPicture.value = true, listenerOptions);\n\tuseEventListener(target, \"leavepictureinpicture\", () => isPictureInPicture.value = false, listenerOptions);\n\tuseEventListener(target, \"volumechange\", () => {\n\t\tconst el = toValue(target);\n\t\tif (!el) return;\n\t\tvolume.value = el.volume;\n\t\tmuted.value = el.muted;\n\t}, listenerOptions);\n\t/**\n\t* The following listeners need to listen to a nested\n\t* object on the target, so we will have to use a nested\n\t* watch and manually remove the listeners\n\t*/\n\tconst listeners = [];\n\tconst stop = watch([target], () => {\n\t\tconst el = toValue(target);\n\t\tif (!el) return;\n\t\tstop();\n\t\tlisteners[0] = useEventListener(el.textTracks, \"addtrack\", () => tracks.value = tracksToArray(el.textTracks), listenerOptions);\n\t\tlisteners[1] = useEventListener(el.textTracks, \"removetrack\", () => tracks.value = tracksToArray(el.textTracks), listenerOptions);\n\t\tlisteners[2] = useEventListener(el.textTracks, \"change\", () => tracks.value = tracksToArray(el.textTracks), listenerOptions);\n\t});\n\ttryOnScopeDispose(() => listeners.forEach((listener) => listener()));\n\treturn {\n\t\tcurrentTime,\n\t\tduration,\n\t\twaiting,\n\t\tseeking,\n\t\tended,\n\t\tstalled,\n\t\tbuffered,\n\t\tplaying,\n\t\trate,\n\t\tvolume,\n\t\tmuted,\n\t\ttracks,\n\t\tselectedTrack,\n\t\tenableTrack,\n\t\tdisableTrack,\n\t\tsupportsPictureInPicture,\n\t\ttogglePictureInPicture,\n\t\tisPictureInPicture,\n\t\tonSourceError: sourceErrorEvent.on,\n\t\tonPlaybackError: playbackErrorEvent.on\n\t};\n}\n//#endregion\n//#region useMemoize/index.ts\n/**\n* Reactive function result cache based on arguments\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useMemoize(resolver, options) {\n\tconst initCache = () => {\n\t\tif (options === null || options === void 0 ? void 0 : options.cache) return shallowReactive(options.cache);\n\t\treturn shallowReactive(/* @__PURE__ */ new Map());\n\t};\n\tconst cache = initCache();\n\t/**\n\t* Generate key from args\n\t*/\n\tconst generateKey = (...args) => (options === null || options === void 0 ? void 0 : options.getKey) ? options.getKey(...args) : JSON.stringify(args);\n\t/**\n\t* Load data and save in cache\n\t*/\n\tconst _loadData = (key, ...args) => {\n\t\tcache.set(key, resolver(...args));\n\t\treturn cache.get(key);\n\t};\n\tconst loadData = (...args) => _loadData(generateKey(...args), ...args);\n\t/**\n\t* Delete key from cache\n\t*/\n\tconst deleteData = (...args) => {\n\t\tcache.delete(generateKey(...args));\n\t};\n\t/**\n\t* Clear cached data\n\t*/\n\tconst clearData = () => {\n\t\tcache.clear();\n\t};\n\tconst memoized = (...args) => {\n\t\tconst key = generateKey(...args);\n\t\tif (cache.has(key)) return cache.get(key);\n\t\treturn _loadData(key, ...args);\n\t};\n\tmemoized.load = loadData;\n\tmemoized.delete = deleteData;\n\tmemoized.clear = clearData;\n\tmemoized.generateKey = generateKey;\n\tmemoized.cache = cache;\n\treturn memoized;\n}\n//#endregion\n//#region useMemory/index.ts\nfunction getDefaultScheduler$6(options) {\n\tif (\"interval\" in options || \"immediate\" in options || \"immediateCallback\" in options) {\n\t\tconst { interval = 1e3, immediate, immediateCallback } = options;\n\t\treturn (cb) => useIntervalFn(cb, interval, {\n\t\t\timmediate,\n\t\t\timmediateCallback\n\t\t});\n\t}\n\treturn useIntervalFn;\n}\n/**\n* Reactive Memory Info.\n*\n* @see https://vueuse.org/useMemory\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useMemory(options = {}) {\n\tconst memory = shallowRef();\n\tconst isSupported = /* @__PURE__ */ useSupported(() => typeof performance !== \"undefined\" && \"memory\" in performance);\n\tif (isSupported.value) {\n\t\tconst { scheduler = getDefaultScheduler$6 } = options;\n\t\tscheduler(() => {\n\t\t\tmemory.value = performance.memory;\n\t\t});\n\t}\n\treturn {\n\t\tisSupported,\n\t\tmemory\n\t};\n}\n//#endregion\n//#region useMouse/index.ts\nconst UseMouseBuiltinExtractors = {\n\tpage: (event) => [event.pageX, event.pageY],\n\tclient: (event) => [event.clientX, event.clientY],\n\tscreen: (event) => [event.screenX, event.screenY],\n\tmovement: (event) => event instanceof MouseEvent ? [event.movementX, event.movementY] : null\n};\n/**\n* Reactive mouse position.\n*\n* @see https://vueuse.org/useMouse\n* @param options\n*/\nfunction useMouse(options = {}) {\n\tconst { type = \"page\", touch = true, resetOnTouchEnds = false, initialValue = {\n\t\tx: 0,\n\t\ty: 0\n\t}, window = defaultWindow, target = window, scroll = true, eventFilter } = options;\n\tlet _prevMouseEvent = null;\n\tlet _prevScrollX = 0;\n\tlet _prevScrollY = 0;\n\tconst x = shallowRef(initialValue.x);\n\tconst y = shallowRef(initialValue.y);\n\tconst sourceType = shallowRef(null);\n\tconst extractor = typeof type === \"function\" ? type : UseMouseBuiltinExtractors[type];\n\tconst mouseHandler = (event) => {\n\t\tconst result = extractor(event);\n\t\t_prevMouseEvent = event;\n\t\tif (result) {\n\t\t\t[x.value, y.value] = result;\n\t\t\tsourceType.value = \"mouse\";\n\t\t}\n\t\tif (window) {\n\t\t\t_prevScrollX = window.scrollX;\n\t\t\t_prevScrollY = window.scrollY;\n\t\t}\n\t};\n\tconst touchHandler = (event) => {\n\t\tif (event.touches.length > 0) {\n\t\t\tconst result = extractor(event.touches[0]);\n\t\t\tif (result) {\n\t\t\t\t[x.value, y.value] = result;\n\t\t\t\tsourceType.value = \"touch\";\n\t\t\t}\n\t\t}\n\t};\n\tconst scrollHandler = () => {\n\t\tif (!_prevMouseEvent || !window) return;\n\t\tconst pos = extractor(_prevMouseEvent);\n\t\tif (_prevMouseEvent instanceof MouseEvent && pos) {\n\t\t\tx.value = pos[0] + window.scrollX - _prevScrollX;\n\t\t\ty.value = pos[1] + window.scrollY - _prevScrollY;\n\t\t}\n\t};\n\tconst reset = () => {\n\t\tx.value = initialValue.x;\n\t\ty.value = initialValue.y;\n\t};\n\tconst mouseHandlerWrapper = eventFilter ? (event) => eventFilter(() => mouseHandler(event), {}) : (event) => mouseHandler(event);\n\tconst touchHandlerWrapper = eventFilter ? (event) => eventFilter(() => touchHandler(event), {}) : (event) => touchHandler(event);\n\tconst scrollHandlerWrapper = eventFilter ? () => eventFilter(() => scrollHandler(), {}) : () => scrollHandler();\n\tif (target) {\n\t\tconst listenerOptions = { passive: true };\n\t\tuseEventListener(target, [\"mousemove\", \"dragover\"], mouseHandlerWrapper, listenerOptions);\n\t\tif (touch && type !== \"movement\") {\n\t\t\tuseEventListener(target, [\"touchstart\", \"touchmove\"], touchHandlerWrapper, listenerOptions);\n\t\t\tif (resetOnTouchEnds) useEventListener(target, \"touchend\", reset, listenerOptions);\n\t\t}\n\t\tif (scroll && type === \"page\") useEventListener(window, \"scroll\", scrollHandlerWrapper, listenerOptions);\n\t}\n\treturn {\n\t\tx,\n\t\ty,\n\t\tsourceType\n\t};\n}\n//#endregion\n//#region useMouseInElement/index.ts\n/**\n* Reactive mouse position related to an element.\n*\n* @see https://vueuse.org/useMouseInElement\n* @param target\n* @param options\n*/\nfunction useMouseInElement(target, options = {}) {\n\tconst { windowResize = true, windowScroll = true, handleOutside = true, window = defaultWindow } = options;\n\tconst type = options.type || \"page\";\n\tconst { x, y, sourceType } = useMouse(options);\n\tconst targetRef = shallowRef(target !== null && target !== void 0 ? target : window === null || window === void 0 ? void 0 : window.document.body);\n\tconst elementX = shallowRef(0);\n\tconst elementY = shallowRef(0);\n\tconst elementPositionX = shallowRef(0);\n\tconst elementPositionY = shallowRef(0);\n\tconst elementHeight = shallowRef(0);\n\tconst elementWidth = shallowRef(0);\n\tconst isOutside = shallowRef(true);\n\tfunction update() {\n\t\tif (!window) return;\n\t\tconst el = unrefElement(targetRef);\n\t\tif (!el || !(el instanceof Element)) return;\n\t\tfor (const rect of el.getClientRects()) {\n\t\t\tconst { left, top, width, height } = rect;\n\t\t\telementPositionX.value = left + (type === \"page\" ? window.pageXOffset : 0);\n\t\t\telementPositionY.value = top + (type === \"page\" ? window.pageYOffset : 0);\n\t\t\telementHeight.value = height;\n\t\t\telementWidth.value = width;\n\t\t\tconst elX = x.value - elementPositionX.value;\n\t\t\tconst elY = y.value - elementPositionY.value;\n\t\t\tisOutside.value = width === 0 || height === 0 || elX < 0 || elY < 0 || elX > width || elY > height;\n\t\t\tif (handleOutside || !isOutside.value) {\n\t\t\t\telementX.value = elX;\n\t\t\t\telementY.value = elY;\n\t\t\t}\n\t\t\tif (!isOutside.value) break;\n\t\t}\n\t}\n\tconst stopFnList = [];\n\tfunction stop() {\n\t\tstopFnList.forEach((fn) => fn());\n\t\tstopFnList.length = 0;\n\t}\n\ttryOnMounted(() => {\n\t\tupdate();\n\t});\n\tif (window) {\n\t\tconst { stop: stopResizeObserver } = useResizeObserver(targetRef, update);\n\t\tconst { stop: stopMutationObserver } = useMutationObserver(targetRef, update, { attributeFilter: [\"style\", \"class\"] });\n\t\tconst stopWatch = watch([\n\t\t\ttargetRef,\n\t\t\tx,\n\t\t\ty\n\t\t], update);\n\t\tstopFnList.push(stopResizeObserver, stopMutationObserver, stopWatch);\n\t\tuseEventListener(document, \"mouseleave\", () => isOutside.value = true, { passive: true });\n\t\tif (windowScroll) stopFnList.push(useEventListener(\"scroll\", update, {\n\t\t\tcapture: true,\n\t\t\tpassive: true\n\t\t}));\n\t\tif (windowResize) stopFnList.push(useEventListener(\"resize\", update, { passive: true }));\n\t}\n\treturn {\n\t\tx,\n\t\ty,\n\t\tsourceType,\n\t\telementX,\n\t\telementY,\n\t\telementPositionX,\n\t\telementPositionY,\n\t\telementHeight,\n\t\telementWidth,\n\t\tisOutside,\n\t\tstop\n\t};\n}\n//#endregion\n//#region useMousePressed/index.ts\n/**\n* Reactive mouse pressing state.\n*\n* @see https://vueuse.org/useMousePressed\n* @param options\n*/\nfunction useMousePressed(options = {}) {\n\tconst { touch = true, drag = true, capture = false, initialValue = false, window = defaultWindow } = options;\n\tconst pressed = shallowRef(initialValue);\n\tconst sourceType = shallowRef(null);\n\tif (!window) return {\n\t\tpressed,\n\t\tsourceType\n\t};\n\tconst onPressed = (srcType) => (event) => {\n\t\tvar _options$onPressed;\n\t\tpressed.value = true;\n\t\tsourceType.value = srcType;\n\t\t(_options$onPressed = options.onPressed) === null || _options$onPressed === void 0 || _options$onPressed.call(options, event);\n\t};\n\tconst onReleased = (event) => {\n\t\tvar _options$onReleased;\n\t\tpressed.value = false;\n\t\tsourceType.value = null;\n\t\t(_options$onReleased = options.onReleased) === null || _options$onReleased === void 0 || _options$onReleased.call(options, event);\n\t};\n\tconst target = computed(() => unrefElement(options.target) || window);\n\tconst listenerOptions = {\n\t\tpassive: true,\n\t\tcapture\n\t};\n\tuseEventListener(target, \"mousedown\", onPressed(\"mouse\"), listenerOptions);\n\tuseEventListener(window, \"mouseleave\", onReleased, listenerOptions);\n\tuseEventListener(window, \"mouseup\", onReleased, listenerOptions);\n\tif (drag) {\n\t\tuseEventListener(target, \"dragstart\", onPressed(\"mouse\"), listenerOptions);\n\t\tuseEventListener(window, \"drop\", onReleased, listenerOptions);\n\t\tuseEventListener(window, \"dragend\", onReleased, listenerOptions);\n\t}\n\tif (touch) {\n\t\tuseEventListener(target, \"touchstart\", onPressed(\"touch\"), listenerOptions);\n\t\tuseEventListener(window, \"touchend\", onReleased, listenerOptions);\n\t\tuseEventListener(window, \"touchcancel\", onReleased, listenerOptions);\n\t}\n\treturn {\n\t\tpressed,\n\t\tsourceType\n\t};\n}\n//#endregion\n//#region useNavigatorLanguage/index.ts\n/**\n*\n* Reactive useNavigatorLanguage\n*\n* Detects the currently selected user language and returns a reactive language\n* @see https://vueuse.org/useNavigatorLanguage\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useNavigatorLanguage(options = {}) {\n\tconst { window = defaultWindow } = options;\n\tconst navigator = window === null || window === void 0 ? void 0 : window.navigator;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => navigator && \"language\" in navigator);\n\tconst language = shallowRef(navigator === null || navigator === void 0 ? void 0 : navigator.language);\n\tuseEventListener(window, \"languagechange\", () => {\n\t\tif (navigator) language.value = navigator.language;\n\t}, { passive: true });\n\treturn {\n\t\tisSupported,\n\t\tlanguage\n\t};\n}\n//#endregion\n//#region useNetwork/index.ts\n/**\n* Reactive Network status.\n*\n* @see https://vueuse.org/useNetwork\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useNetwork(options = {}) {\n\tconst { window = defaultWindow } = options;\n\tconst navigator = window === null || window === void 0 ? void 0 : window.navigator;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => navigator && \"connection\" in navigator);\n\tconst isOnline = shallowRef(true);\n\tconst saveData = shallowRef(false);\n\tconst offlineAt = shallowRef(void 0);\n\tconst onlineAt = shallowRef(void 0);\n\tconst downlink = shallowRef(void 0);\n\tconst downlinkMax = shallowRef(void 0);\n\tconst rtt = shallowRef(void 0);\n\tconst effectiveType = shallowRef(void 0);\n\tconst type = shallowRef(\"unknown\");\n\tconst connection = isSupported.value && navigator.connection;\n\tfunction updateNetworkInformation() {\n\t\tif (!navigator) return;\n\t\tisOnline.value = navigator.onLine;\n\t\tofflineAt.value = isOnline.value ? void 0 : Date.now();\n\t\tonlineAt.value = isOnline.value ? Date.now() : void 0;\n\t\tif (connection) {\n\t\t\tdownlink.value = connection.downlink;\n\t\t\tdownlinkMax.value = connection.downlinkMax;\n\t\t\teffectiveType.value = connection.effectiveType;\n\t\t\trtt.value = connection.rtt;\n\t\t\tsaveData.value = connection.saveData;\n\t\t\ttype.value = connection.type;\n\t\t}\n\t}\n\tconst listenerOptions = { passive: true };\n\tif (window) {\n\t\tuseEventListener(window, \"offline\", () => {\n\t\t\tisOnline.value = false;\n\t\t\tofflineAt.value = Date.now();\n\t\t}, listenerOptions);\n\t\tuseEventListener(window, \"online\", () => {\n\t\t\tisOnline.value = true;\n\t\t\tonlineAt.value = Date.now();\n\t\t}, listenerOptions);\n\t}\n\tif (connection) useEventListener(connection, \"change\", updateNetworkInformation, listenerOptions);\n\tupdateNetworkInformation();\n\treturn {\n\t\tisSupported,\n\t\tisOnline: shallowReadonly(isOnline),\n\t\tsaveData: shallowReadonly(saveData),\n\t\tofflineAt: shallowReadonly(offlineAt),\n\t\tonlineAt: shallowReadonly(onlineAt),\n\t\tdownlink: shallowReadonly(downlink),\n\t\tdownlinkMax: shallowReadonly(downlinkMax),\n\t\teffectiveType: shallowReadonly(effectiveType),\n\t\trtt: shallowReadonly(rtt),\n\t\ttype: shallowReadonly(type)\n\t};\n}\n//#endregion\n//#region useNow/index.ts\nfunction getDefaultScheduler$5(options) {\n\tif (\"interval\" in options || \"immediate\" in options) {\n\t\tconst { interval = \"requestAnimationFrame\", immediate = true } = options;\n\t\treturn interval === \"requestAnimationFrame\" ? (fn) => useRafFn(fn, { immediate }) : (fn) => useIntervalFn(fn, interval, options);\n\t}\n\treturn useRafFn;\n}\n/**\n* Reactive current Date instance.\n*\n* @see https://vueuse.org/useNow\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useNow(options = {}) {\n\tconst { controls: exposeControls = false, scheduler = getDefaultScheduler$5(options) } = options;\n\tconst now = shallowRef(/* @__PURE__ */ new Date());\n\tconst update = () => now.value = /* @__PURE__ */ new Date();\n\tconst controls = scheduler(update);\n\tif (exposeControls) return {\n\t\tnow,\n\t\t...controls\n\t};\n\telse return now;\n}\n//#endregion\n//#region useObjectUrl/index.ts\n/**\n* Reactive URL representing an object.\n*\n* @see https://vueuse.org/useObjectUrl\n* @param object\n*/\nfunction useObjectUrl(object) {\n\tconst url = shallowRef();\n\tconst release = () => {\n\t\tif (url.value) URL.revokeObjectURL(url.value);\n\t\turl.value = void 0;\n\t};\n\twatch(() => toValue(object), (newObject) => {\n\t\trelease();\n\t\tif (newObject) url.value = URL.createObjectURL(newObject);\n\t}, { immediate: true });\n\ttryOnScopeDispose(release);\n\treturn shallowReadonly(url);\n}\n//#endregion\n//#region ../math/useClamp/index.ts\n/**\n* Reactively clamp a value between two other values.\n*\n* @see https://vueuse.org/useClamp\n* @param value number\n* @param min\n* @param max\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useClamp(value, min, max) {\n\tif (typeof value === \"function\" || isReadonly(value)) return computed(() => clamp(toValue(value), toValue(min), toValue(max)));\n\tconst _value = ref(value);\n\treturn computed({\n\t\tget() {\n\t\t\treturn _value.value = clamp(_value.value, toValue(min), toValue(max));\n\t\t},\n\t\tset(value) {\n\t\t\t_value.value = clamp(value, toValue(min), toValue(max));\n\t\t}\n\t});\n}\n//#endregion\n//#region useOffsetPagination/index.ts\nfunction useOffsetPagination(options) {\n\tconst { total = Number.POSITIVE_INFINITY, pageSize = 10, page = 1, onPageChange = noop, onPageSizeChange = noop, onPageCountChange = noop } = options;\n\tconst currentPageSize = useClamp(pageSize, 1, Number.POSITIVE_INFINITY);\n\tconst pageCount = computed(() => Math.max(1, Math.ceil(toValue(total) / toValue(currentPageSize))));\n\tconst currentPage = useClamp(page, 1, pageCount);\n\tconst isFirstPage = computed(() => currentPage.value === 1);\n\tconst isLastPage = computed(() => currentPage.value === pageCount.value);\n\tif (isRef(page)) syncRef(page, currentPage, { direction: isReadonly(page) ? \"ltr\" : \"both\" });\n\tif (isRef(pageSize)) syncRef(pageSize, currentPageSize, { direction: isReadonly(pageSize) ? \"ltr\" : \"both\" });\n\tfunction prev() {\n\t\tcurrentPage.value--;\n\t}\n\tfunction next() {\n\t\tcurrentPage.value++;\n\t}\n\tconst returnValue = {\n\t\tcurrentPage,\n\t\tcurrentPageSize,\n\t\tpageCount,\n\t\tisFirstPage,\n\t\tisLastPage,\n\t\tprev,\n\t\tnext\n\t};\n\twatch(currentPage, () => {\n\t\tonPageChange(reactive(returnValue));\n\t});\n\twatch(currentPageSize, () => {\n\t\tonPageSizeChange(reactive(returnValue));\n\t});\n\twatch(pageCount, () => {\n\t\tonPageCountChange(reactive(returnValue));\n\t});\n\treturn returnValue;\n}\n//#endregion\n//#region useOnline/index.ts\n/**\n* Reactive online state.\n*\n* @see https://vueuse.org/useOnline\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useOnline(options = {}) {\n\tconst { isOnline } = useNetwork(options);\n\treturn isOnline;\n}\n//#endregion\n//#region usePageLeave/index.ts\n/**\n* Reactive state to show whether mouse leaves the page.\n*\n* @see https://vueuse.org/usePageLeave\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction usePageLeave(options = {}) {\n\tconst { window = defaultWindow } = options;\n\tconst isLeft = shallowRef(false);\n\tconst handler = (event) => {\n\t\tif (!window) return;\n\t\tevent = event || window.event;\n\t\tisLeft.value = !(event.relatedTarget || event.toElement);\n\t};\n\tif (window) {\n\t\tconst listenerOptions = { passive: true };\n\t\tuseEventListener(window, \"mouseout\", handler, listenerOptions);\n\t\tuseEventListener(window.document, \"mouseleave\", handler, listenerOptions);\n\t\tuseEventListener(window.document, \"mouseenter\", handler, listenerOptions);\n\t}\n\treturn isLeft;\n}\n//#endregion\n//#region useScreenOrientation/index.ts\n/**\n* Reactive screen orientation\n*\n* @see https://vueuse.org/useScreenOrientation\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useScreenOrientation(options = {}) {\n\tconst { window = defaultWindow } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => window && \"screen\" in window && \"orientation\" in window.screen);\n\tconst screenOrientation = isSupported.value ? window.screen.orientation : {};\n\tconst orientation = shallowRef(screenOrientation.type);\n\tconst angle = shallowRef(screenOrientation.angle || 0);\n\tif (isSupported.value) useEventListener(window, \"orientationchange\", () => {\n\t\torientation.value = screenOrientation.type;\n\t\tangle.value = screenOrientation.angle;\n\t}, { passive: true });\n\tconst lockOrientation = (type) => {\n\t\tif (isSupported.value && typeof screenOrientation.lock === \"function\") return screenOrientation.lock(type);\n\t\treturn Promise.reject(/* @__PURE__ */ new Error(\"Not supported\"));\n\t};\n\tconst unlockOrientation = () => {\n\t\tif (isSupported.value && typeof screenOrientation.unlock === \"function\") screenOrientation.unlock();\n\t};\n\treturn {\n\t\tisSupported,\n\t\torientation,\n\t\tangle,\n\t\tlockOrientation,\n\t\tunlockOrientation\n\t};\n}\n//#endregion\n//#region useParallax/index.ts\n/**\n* Create parallax effect easily. It uses `useDeviceOrientation` and fallback to `useMouse`\n* if orientation is not supported.\n*\n* @param target\n* @param options\n*/\nfunction useParallax(target, options = {}) {\n\tconst { deviceOrientationTiltAdjust = (i) => i, deviceOrientationRollAdjust = (i) => i, mouseTiltAdjust = (i) => i, mouseRollAdjust = (i) => i, window = defaultWindow } = options;\n\tconst orientation = reactive(useDeviceOrientation({ window }));\n\tconst screenOrientation = reactive(useScreenOrientation({ window }));\n\tconst { elementX: x, elementY: y, elementWidth: width, elementHeight: height } = useMouseInElement(target, {\n\t\thandleOutside: false,\n\t\twindow\n\t});\n\tconst source = computed(() => {\n\t\tif (orientation.isSupported && (orientation.alpha != null && orientation.alpha !== 0 || orientation.gamma != null && orientation.gamma !== 0)) return \"deviceOrientation\";\n\t\treturn \"mouse\";\n\t});\n\treturn {\n\t\troll: computed(() => {\n\t\t\tif (source.value === \"deviceOrientation\") {\n\t\t\t\tlet value;\n\t\t\t\tswitch (screenOrientation.orientation) {\n\t\t\t\t\tcase \"landscape-primary\":\n\t\t\t\t\t\tvalue = orientation.gamma / 90;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"landscape-secondary\":\n\t\t\t\t\t\tvalue = -orientation.gamma / 90;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"portrait-primary\":\n\t\t\t\t\t\tvalue = -orientation.beta / 90;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"portrait-secondary\":\n\t\t\t\t\t\tvalue = orientation.beta / 90;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault: value = -orientation.beta / 90;\n\t\t\t\t}\n\t\t\t\treturn deviceOrientationRollAdjust(value);\n\t\t\t} else return mouseRollAdjust(-(y.value - height.value / 2) / height.value);\n\t\t}),\n\t\ttilt: computed(() => {\n\t\t\tif (source.value === \"deviceOrientation\") {\n\t\t\t\tlet value;\n\t\t\t\tswitch (screenOrientation.orientation) {\n\t\t\t\t\tcase \"landscape-primary\":\n\t\t\t\t\t\tvalue = orientation.beta / 90;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"landscape-secondary\":\n\t\t\t\t\t\tvalue = -orientation.beta / 90;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"portrait-primary\":\n\t\t\t\t\t\tvalue = orientation.gamma / 90;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"portrait-secondary\":\n\t\t\t\t\t\tvalue = -orientation.gamma / 90;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault: value = orientation.gamma / 90;\n\t\t\t\t}\n\t\t\t\treturn deviceOrientationTiltAdjust(value);\n\t\t\t} else return mouseTiltAdjust((x.value - width.value / 2) / width.value);\n\t\t}),\n\t\tsource\n\t};\n}\n//#endregion\n//#region useParentElement/index.ts\nfunction useParentElement(element = useCurrentElement()) {\n\tconst parentElement = shallowRef();\n\tconst update = () => {\n\t\tconst el = unrefElement(element);\n\t\tif (el) parentElement.value = el.parentElement;\n\t};\n\ttryOnMounted(update);\n\twatch(() => toValue(element), update);\n\treturn parentElement;\n}\n//#endregion\n//#region usePerformanceObserver/index.ts\n/**\n* Observe performance metrics.\n*\n* @see https://vueuse.org/usePerformanceObserver\n* @param options\n*/\nfunction usePerformanceObserver(options, callback) {\n\tconst { window = defaultWindow, immediate = true, ...performanceOptions } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => window && \"PerformanceObserver\" in window);\n\tlet observer;\n\tconst stop = () => {\n\t\tobserver === null || observer === void 0 || observer.disconnect();\n\t};\n\tconst start = () => {\n\t\tif (isSupported.value) {\n\t\t\tstop();\n\t\t\tobserver = new PerformanceObserver(callback);\n\t\t\tobserver.observe(performanceOptions);\n\t\t}\n\t};\n\ttryOnScopeDispose(stop);\n\tif (immediate) start();\n\treturn {\n\t\tisSupported,\n\t\tstart,\n\t\tstop\n\t};\n}\n//#endregion\n//#region usePointer/index.ts\nconst defaultState = (/* #__PURE__ */ {\n\tx: 0,\n\ty: 0,\n\tpointerId: 0,\n\tpressure: 0,\n\ttiltX: 0,\n\ttiltY: 0,\n\twidth: 0,\n\theight: 0,\n\ttwist: 0,\n\tpointerType: null\n});\nconst keys = /* @__PURE__ */ Object.keys(defaultState);\n/**\n* Reactive pointer state.\n*\n* @see https://vueuse.org/usePointer\n* @param options\n*/\nfunction usePointer(options = {}) {\n\tconst { target = defaultWindow } = options;\n\tconst isInside = shallowRef(false);\n\tconst state = shallowRef(options.initialValue || {});\n\tObject.assign(state.value, defaultState, state.value);\n\tconst handler = (event) => {\n\t\tisInside.value = true;\n\t\tif (options.pointerTypes && !options.pointerTypes.includes(event.pointerType)) return;\n\t\tstate.value = objectPick(event, keys, false);\n\t};\n\tif (target) {\n\t\tconst listenerOptions = { passive: true };\n\t\tuseEventListener(target, [\n\t\t\t\"pointerdown\",\n\t\t\t\"pointermove\",\n\t\t\t\"pointerup\"\n\t\t], handler, listenerOptions);\n\t\tuseEventListener(target, \"pointerleave\", () => isInside.value = false, listenerOptions);\n\t}\n\treturn {\n\t\t...toRefs(state),\n\t\tisInside\n\t};\n}\n//#endregion\n//#region usePointerLock/index.ts\n/**\n* Reactive pointer lock.\n*\n* @see https://vueuse.org/usePointerLock\n* @param target\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction usePointerLock(target, options = {}) {\n\tconst { document = defaultDocument } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => document && \"pointerLockElement\" in document);\n\tconst element = shallowRef();\n\tconst triggerElement = shallowRef();\n\tlet targetElement;\n\tif (isSupported.value) {\n\t\tconst listenerOptions = { passive: true };\n\t\tuseEventListener(document, \"pointerlockchange\", () => {\n\t\t\tvar _pointerLockElement;\n\t\t\tconst currentElement = (_pointerLockElement = document.pointerLockElement) !== null && _pointerLockElement !== void 0 ? _pointerLockElement : element.value;\n\t\t\tif (targetElement && currentElement === targetElement) {\n\t\t\t\telement.value = document.pointerLockElement;\n\t\t\t\tif (!element.value) targetElement = triggerElement.value = null;\n\t\t\t}\n\t\t}, listenerOptions);\n\t\tuseEventListener(document, \"pointerlockerror\", () => {\n\t\t\tvar _pointerLockElement2;\n\t\t\tconst currentElement = (_pointerLockElement2 = document.pointerLockElement) !== null && _pointerLockElement2 !== void 0 ? _pointerLockElement2 : element.value;\n\t\t\tif (targetElement && currentElement === targetElement) {\n\t\t\t\tconst action = document.pointerLockElement ? \"release\" : \"acquire\";\n\t\t\t\tthrow new Error(`Failed to ${action} pointer lock.`);\n\t\t\t}\n\t\t}, listenerOptions);\n\t}\n\tasync function lock(e) {\n\t\tvar _unrefElement;\n\t\tif (!isSupported.value) throw new Error(\"Pointer Lock API is not supported by your browser.\");\n\t\ttriggerElement.value = e instanceof Event ? e.currentTarget : null;\n\t\ttargetElement = e instanceof Event ? (_unrefElement = unrefElement(target)) !== null && _unrefElement !== void 0 ? _unrefElement : triggerElement.value : unrefElement(e);\n\t\tif (!targetElement) throw new Error(\"Target element undefined.\");\n\t\ttargetElement.requestPointerLock();\n\t\treturn await until(element).toBe(targetElement);\n\t}\n\tasync function unlock() {\n\t\tif (!element.value) return false;\n\t\tdocument.exitPointerLock();\n\t\tawait until(element).toBeNull();\n\t\treturn true;\n\t}\n\treturn {\n\t\tisSupported,\n\t\telement,\n\t\ttriggerElement,\n\t\tlock,\n\t\tunlock\n\t};\n}\n//#endregion\n//#region usePointerSwipe/index.ts\n/**\n* Reactive swipe detection based on PointerEvents.\n*\n* @see https://vueuse.org/usePointerSwipe\n* @param target\n* @param options\n*/\nfunction usePointerSwipe(target, options = {}) {\n\tconst targetRef = toRef(target);\n\tconst { threshold = 50, onSwipe, onSwipeEnd, onSwipeStart, disableTextSelect = false } = options;\n\tconst posStart = reactive({\n\t\tx: 0,\n\t\ty: 0\n\t});\n\tconst updatePosStart = (x, y) => {\n\t\tposStart.x = x;\n\t\tposStart.y = y;\n\t};\n\tconst posEnd = reactive({\n\t\tx: 0,\n\t\ty: 0\n\t});\n\tconst updatePosEnd = (x, y) => {\n\t\tposEnd.x = x;\n\t\tposEnd.y = y;\n\t};\n\tconst distanceX = computed(() => posStart.x - posEnd.x);\n\tconst distanceY = computed(() => posStart.y - posEnd.y);\n\tconst { max, abs } = Math;\n\tconst isThresholdExceeded = computed(() => max(abs(distanceX.value), abs(distanceY.value)) >= threshold);\n\tconst isSwiping = shallowRef(false);\n\tconst isPointerDown = shallowRef(false);\n\tconst direction = computed(() => {\n\t\tif (!isThresholdExceeded.value) return \"none\";\n\t\tif (abs(distanceX.value) > abs(distanceY.value)) return distanceX.value > 0 ? \"left\" : \"right\";\n\t\telse return distanceY.value > 0 ? \"up\" : \"down\";\n\t});\n\tconst eventIsAllowed = (e) => {\n\t\tvar _ref, _options$pointerTypes, _options$pointerTypes2;\n\t\tconst isReleasingButton = e.buttons === 0;\n\t\tconst isPrimaryButton = e.buttons === 1;\n\t\treturn (_ref = (_options$pointerTypes = (_options$pointerTypes2 = options.pointerTypes) === null || _options$pointerTypes2 === void 0 ? void 0 : _options$pointerTypes2.includes(e.pointerType)) !== null && _options$pointerTypes !== void 0 ? _options$pointerTypes : isReleasingButton || isPrimaryButton) !== null && _ref !== void 0 ? _ref : true;\n\t};\n\tconst listenerOptions = { passive: true };\n\tconst stops = [\n\t\tuseEventListener(target, \"pointerdown\", (e) => {\n\t\t\tif (!eventIsAllowed(e)) return;\n\t\t\tisPointerDown.value = true;\n\t\t\tconst eventTarget = e.target;\n\t\t\teventTarget === null || eventTarget === void 0 || eventTarget.setPointerCapture(e.pointerId);\n\t\t\tconst { clientX: x, clientY: y } = e;\n\t\t\tupdatePosStart(x, y);\n\t\t\tupdatePosEnd(x, y);\n\t\t\tonSwipeStart === null || onSwipeStart === void 0 || onSwipeStart(e);\n\t\t}, listenerOptions),\n\t\tuseEventListener(target, \"pointermove\", (e) => {\n\t\t\tif (!eventIsAllowed(e)) return;\n\t\t\tif (!isPointerDown.value) return;\n\t\t\tconst { clientX: x, clientY: y } = e;\n\t\t\tupdatePosEnd(x, y);\n\t\t\tif (!isSwiping.value && isThresholdExceeded.value) isSwiping.value = true;\n\t\t\tif (isSwiping.value) onSwipe === null || onSwipe === void 0 || onSwipe(e);\n\t\t}, listenerOptions),\n\t\tuseEventListener(target, \"pointerup\", (e) => {\n\t\t\tif (!eventIsAllowed(e)) return;\n\t\t\tif (isSwiping.value) onSwipeEnd === null || onSwipeEnd === void 0 || onSwipeEnd(e, direction.value);\n\t\t\tisPointerDown.value = false;\n\t\t\tisSwiping.value = false;\n\t\t}, listenerOptions)\n\t];\n\ttryOnMounted(() => {\n\t\tvar _targetRef$value;\n\t\t(_targetRef$value = targetRef.value) === null || _targetRef$value === void 0 || (_targetRef$value = _targetRef$value.style) === null || _targetRef$value === void 0 || _targetRef$value.setProperty(\"touch-action\", \"pan-y\");\n\t\tif (disableTextSelect) {\n\t\t\tvar _targetRef$value2, _targetRef$value3, _targetRef$value4;\n\t\t\t(_targetRef$value2 = targetRef.value) === null || _targetRef$value2 === void 0 || (_targetRef$value2 = _targetRef$value2.style) === null || _targetRef$value2 === void 0 || _targetRef$value2.setProperty(\"-webkit-user-select\", \"none\");\n\t\t\t(_targetRef$value3 = targetRef.value) === null || _targetRef$value3 === void 0 || (_targetRef$value3 = _targetRef$value3.style) === null || _targetRef$value3 === void 0 || _targetRef$value3.setProperty(\"-ms-user-select\", \"none\");\n\t\t\t(_targetRef$value4 = targetRef.value) === null || _targetRef$value4 === void 0 || (_targetRef$value4 = _targetRef$value4.style) === null || _targetRef$value4 === void 0 || _targetRef$value4.setProperty(\"user-select\", \"none\");\n\t\t}\n\t});\n\tconst stop = () => stops.forEach((s) => s());\n\treturn {\n\t\tisSwiping: shallowReadonly(isSwiping),\n\t\tdirection: shallowReadonly(direction),\n\t\tposStart: readonly(posStart),\n\t\tposEnd: readonly(posEnd),\n\t\tdistanceX,\n\t\tdistanceY,\n\t\tstop\n\t};\n}\n//#endregion\n//#region usePreferredColorScheme/index.ts\n/**\n* Reactive prefers-color-scheme media query.\n*\n* @see https://vueuse.org/usePreferredColorScheme\n* @param [options]\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction usePreferredColorScheme(options) {\n\tconst isLight = useMediaQuery(\"(prefers-color-scheme: light)\", options);\n\tconst isDark = useMediaQuery(\"(prefers-color-scheme: dark)\", options);\n\treturn computed(() => {\n\t\tif (isDark.value) return \"dark\";\n\t\tif (isLight.value) return \"light\";\n\t\treturn \"no-preference\";\n\t});\n}\n//#endregion\n//#region usePreferredContrast/index.ts\n/**\n* Reactive prefers-contrast media query.\n*\n* @see https://vueuse.org/usePreferredContrast\n* @param [options]\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction usePreferredContrast(options) {\n\tconst isMore = useMediaQuery(\"(prefers-contrast: more)\", options);\n\tconst isLess = useMediaQuery(\"(prefers-contrast: less)\", options);\n\tconst isCustom = useMediaQuery(\"(prefers-contrast: custom)\", options);\n\treturn computed(() => {\n\t\tif (isMore.value) return \"more\";\n\t\tif (isLess.value) return \"less\";\n\t\tif (isCustom.value) return \"custom\";\n\t\treturn \"no-preference\";\n\t});\n}\n//#endregion\n//#region usePreferredLanguages/index.ts\n/**\n* Reactive Navigator Languages.\n*\n* @see https://vueuse.org/usePreferredLanguages\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction usePreferredLanguages(options = {}) {\n\tconst { window = defaultWindow } = options;\n\tif (!window) return shallowRef([\"en\"]);\n\tconst navigator = window.navigator;\n\tconst value = shallowRef(navigator.languages);\n\tuseEventListener(window, \"languagechange\", () => {\n\t\tvalue.value = navigator.languages;\n\t}, { passive: true });\n\treturn value;\n}\n//#endregion\n//#region usePreferredReducedMotion/index.ts\n/**\n* Reactive prefers-reduced-motion media query.\n*\n* @see https://vueuse.org/usePreferredReducedMotion\n* @param [options]\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction usePreferredReducedMotion(options) {\n\tconst isReduced = useMediaQuery(\"(prefers-reduced-motion: reduce)\", options);\n\treturn computed(() => {\n\t\tif (isReduced.value) return \"reduce\";\n\t\treturn \"no-preference\";\n\t});\n}\n//#endregion\n//#region usePreferredReducedTransparency/index.ts\n/**\n* Reactive prefers-reduced-transparency media query.\n*\n* @see https://vueuse.org/usePreferredReducedTransparency\n* @param [options]\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction usePreferredReducedTransparency(options) {\n\tconst isReduced = useMediaQuery(\"(prefers-reduced-transparency: reduce)\", options);\n\treturn computed(() => {\n\t\tif (isReduced.value) return \"reduce\";\n\t\treturn \"no-preference\";\n\t});\n}\n//#endregion\n//#region usePrevious/index.ts\nfunction usePrevious(value, initialValue) {\n\tconst previous = shallowRef(initialValue);\n\twatch(toRef(value), (_, oldValue) => {\n\t\tprevious.value = oldValue;\n\t}, { flush: \"sync\" });\n\treturn readonly(previous);\n}\n//#endregion\n//#region useScreenSafeArea/index.ts\nconst topVarName = \"--vueuse-safe-area-top\";\nconst rightVarName = \"--vueuse-safe-area-right\";\nconst bottomVarName = \"--vueuse-safe-area-bottom\";\nconst leftVarName = \"--vueuse-safe-area-left\";\n/**\n* Reactive `env(safe-area-inset-*)`\n*\n* @see https://vueuse.org/useScreenSafeArea\n*/\nfunction useScreenSafeArea() {\n\tconst top = shallowRef(\"\");\n\tconst right = shallowRef(\"\");\n\tconst bottom = shallowRef(\"\");\n\tconst left = shallowRef(\"\");\n\tif (isClient) {\n\t\tconst topCssVar = useCssVar(topVarName);\n\t\tconst rightCssVar = useCssVar(rightVarName);\n\t\tconst bottomCssVar = useCssVar(bottomVarName);\n\t\tconst leftCssVar = useCssVar(leftVarName);\n\t\ttopCssVar.value = \"env(safe-area-inset-top, 0px)\";\n\t\trightCssVar.value = \"env(safe-area-inset-right, 0px)\";\n\t\tbottomCssVar.value = \"env(safe-area-inset-bottom, 0px)\";\n\t\tleftCssVar.value = \"env(safe-area-inset-left, 0px)\";\n\t\ttryOnMounted(update);\n\t\tuseEventListener(\"resize\", useDebounceFn(update), { passive: true });\n\t}\n\tfunction update() {\n\t\ttop.value = getValue(topVarName);\n\t\tright.value = getValue(rightVarName);\n\t\tbottom.value = getValue(bottomVarName);\n\t\tleft.value = getValue(leftVarName);\n\t}\n\treturn {\n\t\ttop,\n\t\tright,\n\t\tbottom,\n\t\tleft,\n\t\tupdate\n\t};\n}\nfunction getValue(position) {\n\treturn getComputedStyle(document.documentElement).getPropertyValue(position);\n}\n//#endregion\n//#region useScriptTag/index.ts\n/**\n* Async script tag loading.\n*\n* @see https://vueuse.org/useScriptTag\n* @param src\n* @param onLoaded\n* @param options\n*/\nfunction useScriptTag(src, onLoaded = noop, options = {}) {\n\tconst { immediate = true, manual = false, type = \"text/javascript\", async = true, crossOrigin, referrerPolicy, noModule, defer, document = defaultDocument, attrs = {}, nonce = void 0 } = options;\n\tconst scriptTag = shallowRef(null);\n\tlet _promise = null;\n\t/**\n\t* Load the script specified via `src`.\n\t*\n\t* @param waitForScriptLoad Whether if the Promise should resolve once the \"load\" event is emitted by the <script> attribute, or right after appending it to the DOM.\n\t* @returns Promise<HTMLScriptElement>\n\t*/\n\tconst loadScript = (waitForScriptLoad) => new Promise((resolve, reject) => {\n\t\tconst resolveWithElement = (el) => {\n\t\t\tscriptTag.value = el;\n\t\t\tresolve(el);\n\t\t\treturn el;\n\t\t};\n\t\tif (!document) {\n\t\t\tresolve(false);\n\t\t\treturn;\n\t\t}\n\t\tlet shouldAppend = false;\n\t\tlet el = document.querySelector(`script[src=\"${toValue(src)}\"]`);\n\t\tif (!el) {\n\t\t\tel = document.createElement(\"script\");\n\t\t\tel.type = type;\n\t\t\tel.async = async;\n\t\t\tel.src = toValue(src);\n\t\t\tif (defer) el.defer = defer;\n\t\t\tif (crossOrigin) el.crossOrigin = crossOrigin;\n\t\t\tif (noModule) el.noModule = noModule;\n\t\t\tif (referrerPolicy) el.referrerPolicy = referrerPolicy;\n\t\t\tif (nonce) el.nonce = nonce;\n\t\t\tObject.entries(attrs).forEach(([name, value]) => el === null || el === void 0 ? void 0 : el.setAttribute(name, value));\n\t\t\tshouldAppend = true;\n\t\t} else if (el.hasAttribute(\"data-loaded\")) resolveWithElement(el);\n\t\tconst listenerOptions = { passive: true };\n\t\tuseEventListener(el, \"error\", (event) => reject(event), listenerOptions);\n\t\tuseEventListener(el, \"abort\", (event) => reject(event), listenerOptions);\n\t\tuseEventListener(el, \"load\", () => {\n\t\t\tel.setAttribute(\"data-loaded\", \"true\");\n\t\t\tonLoaded(el);\n\t\t\tresolveWithElement(el);\n\t\t}, listenerOptions);\n\t\tif (shouldAppend) el = document.head.appendChild(el);\n\t\tif (!waitForScriptLoad) resolveWithElement(el);\n\t});\n\t/**\n\t* Exposed singleton wrapper for `loadScript`, avoiding calling it twice.\n\t*\n\t* @param waitForScriptLoad Whether if the Promise should resolve once the \"load\" event is emitted by the <script> attribute, or right after appending it to the DOM.\n\t* @returns Promise<HTMLScriptElement>\n\t*/\n\tconst load = (waitForScriptLoad = true) => {\n\t\tif (!_promise) _promise = loadScript(waitForScriptLoad);\n\t\treturn _promise;\n\t};\n\t/**\n\t* Unload the script specified by `src`.\n\t*/\n\tconst unload = () => {\n\t\tif (!document) return;\n\t\t_promise = null;\n\t\tif (scriptTag.value) scriptTag.value = null;\n\t\tconst el = document.querySelector(`script[src=\"${toValue(src)}\"]`);\n\t\tif (el) document.head.removeChild(el);\n\t};\n\tif (immediate && !manual) tryOnMounted(load);\n\tif (!manual) tryOnUnmounted(unload);\n\treturn {\n\t\tscriptTag,\n\t\tload,\n\t\tunload\n\t};\n}\n//#endregion\n//#region useScrollLock/index.ts\nfunction checkOverflowScroll(ele) {\n\tconst style = window.getComputedStyle(ele);\n\tif (style.overflowX === \"scroll\" || style.overflowY === \"scroll\" || style.overflowX === \"auto\" && ele.clientWidth < ele.scrollWidth || style.overflowY === \"auto\" && ele.clientHeight < ele.scrollHeight) return true;\n\telse {\n\t\tconst parent = ele.parentNode;\n\t\tif (!parent || parent.tagName === \"BODY\") return false;\n\t\treturn checkOverflowScroll(parent);\n\t}\n}\nfunction preventDefault(rawEvent) {\n\tconst e = rawEvent || window.event;\n\tconst _target = e.target;\n\tif (checkOverflowScroll(_target)) return false;\n\tif (e.touches.length > 1) return true;\n\tif (e.preventDefault) e.preventDefault();\n\treturn false;\n}\nconst elInitialOverflow = /* @__PURE__ */ new WeakMap();\n/**\n* Lock scrolling of the element.\n*\n* @see https://vueuse.org/useScrollLock\n* @param element\n*/\nfunction useScrollLock(element, initialState = false) {\n\tconst isLocked = shallowRef(initialState);\n\tlet stopTouchMoveListener = null;\n\tlet initialOverflow = \"\";\n\twatch(toRef(element), (el) => {\n\t\tconst target = resolveElement(toValue(el));\n\t\tif (target) {\n\t\t\tconst ele = target;\n\t\t\tif (!elInitialOverflow.get(ele)) elInitialOverflow.set(ele, ele.style.overflow);\n\t\t\tif (ele.style.overflow !== \"hidden\") initialOverflow = ele.style.overflow;\n\t\t\tif (ele.style.overflow === \"hidden\") return isLocked.value = true;\n\t\t\tif (isLocked.value) return ele.style.overflow = \"hidden\";\n\t\t}\n\t}, { immediate: true });\n\tconst lock = () => {\n\t\tconst el = resolveElement(toValue(element));\n\t\tif (!el || isLocked.value) return;\n\t\tif (isIOS) stopTouchMoveListener = useEventListener(el, \"touchmove\", (e) => {\n\t\t\tpreventDefault(e);\n\t\t}, { passive: false });\n\t\tel.style.overflow = \"hidden\";\n\t\tisLocked.value = true;\n\t};\n\tconst unlock = () => {\n\t\tconst el = resolveElement(toValue(element));\n\t\tif (!el || !isLocked.value) return;\n\t\tif (isIOS) stopTouchMoveListener === null || stopTouchMoveListener === void 0 || stopTouchMoveListener();\n\t\tel.style.overflow = initialOverflow;\n\t\telInitialOverflow.delete(el);\n\t\tisLocked.value = false;\n\t};\n\ttryOnScopeDispose(unlock);\n\treturn computed({\n\t\tget() {\n\t\t\treturn isLocked.value;\n\t\t},\n\t\tset(v) {\n\t\t\tif (v) lock();\n\t\t\telse unlock();\n\t\t}\n\t});\n}\n//#endregion\n//#region useSessionStorage/index.ts\n/**\n* Reactive SessionStorage.\n*\n* @see https://vueuse.org/useSessionStorage\n* @param key\n* @param initialValue\n* @param options\n*/\nfunction useSessionStorage(key, initialValue, options = {}) {\n\tconst { window = defaultWindow } = options;\n\treturn useStorage(key, initialValue, window === null || window === void 0 ? void 0 : window.sessionStorage, options);\n}\n//#endregion\n//#region useShare/index.ts\n/**\n* Reactive Web Share API.\n*\n* @see https://vueuse.org/useShare\n* @param shareOptions\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useShare(shareOptions = {}, options = {}) {\n\tconst { navigator = defaultNavigator } = options;\n\tconst _navigator = navigator;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => _navigator && \"canShare\" in _navigator);\n\tconst share = async (overrideOptions = {}) => {\n\t\tif (isSupported.value) {\n\t\t\tconst data = {\n\t\t\t\t...toValue(shareOptions),\n\t\t\t\t...toValue(overrideOptions)\n\t\t\t};\n\t\t\tlet granted = false;\n\t\t\tif (_navigator.canShare) granted = _navigator.canShare(data);\n\t\t\tif (granted) return _navigator.share(data);\n\t\t}\n\t};\n\treturn {\n\t\tisSupported,\n\t\tshare\n\t};\n}\n//#endregion\n//#region useSorted/index.ts\nconst defaultSortFn = (source, compareFn) => source.sort(compareFn);\nconst defaultCompare = (a, b) => a - b;\nfunction useSorted(...args) {\n\tconst [source] = args;\n\tlet compareFn = defaultCompare;\n\tlet options = {};\n\tif (args.length === 2) if (typeof args[1] === \"object\") {\n\t\tvar _options$compareFn;\n\t\toptions = args[1];\n\t\tcompareFn = (_options$compareFn = options.compareFn) !== null && _options$compareFn !== void 0 ? _options$compareFn : defaultCompare;\n\t} else {\n\t\tvar _args$;\n\t\tcompareFn = (_args$ = args[1]) !== null && _args$ !== void 0 ? _args$ : defaultCompare;\n\t}\n\telse if (args.length > 2) {\n\t\tvar _args$2, _args$3;\n\t\tcompareFn = (_args$2 = args[1]) !== null && _args$2 !== void 0 ? _args$2 : defaultCompare;\n\t\toptions = (_args$3 = args[2]) !== null && _args$3 !== void 0 ? _args$3 : {};\n\t}\n\tconst { dirty = false, sortFn = defaultSortFn } = options;\n\tif (!dirty) return computed(() => sortFn([...toValue(source)], compareFn));\n\twatchEffect(() => {\n\t\tconst result = sortFn(toValue(source), compareFn);\n\t\tif (isRef(source)) source.value = result;\n\t\telse source.splice(0, source.length, ...result);\n\t});\n\treturn source;\n}\n//#endregion\n//#region useSpeechRecognition/index.ts\n/**\n* Reactive SpeechRecognition.\n*\n* @see https://vueuse.org/useSpeechRecognition\n* @see https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition SpeechRecognition\n* @param options\n*/\nfunction useSpeechRecognition(options = {}) {\n\tconst { interimResults = true, continuous = true, maxAlternatives = 1, window = defaultWindow } = options;\n\tconst lang = toRef(options.lang || \"en-US\");\n\tconst isListening = shallowRef(false);\n\tconst isFinal = shallowRef(false);\n\tconst result = shallowRef(\"\");\n\tconst error = shallowRef(void 0);\n\tlet recognition;\n\tconst start = () => {\n\t\tisListening.value = true;\n\t};\n\tconst stop = () => {\n\t\tisListening.value = false;\n\t};\n\tconst toggle = (value = !isListening.value) => {\n\t\tif (value) start();\n\t\telse stop();\n\t};\n\tconst SpeechRecognition = window && (window.SpeechRecognition || window.webkitSpeechRecognition);\n\tconst isSupported = /* @__PURE__ */ useSupported(() => SpeechRecognition);\n\tif (isSupported.value) {\n\t\trecognition = new SpeechRecognition();\n\t\trecognition.continuous = continuous;\n\t\trecognition.interimResults = interimResults;\n\t\trecognition.lang = toValue(lang);\n\t\trecognition.maxAlternatives = maxAlternatives;\n\t\trecognition.onstart = () => {\n\t\t\tisListening.value = true;\n\t\t\tisFinal.value = false;\n\t\t};\n\t\twatch(lang, (lang) => {\n\t\t\tif (recognition && !isListening.value) recognition.lang = lang;\n\t\t});\n\t\trecognition.onresult = (event) => {\n\t\t\tconst currentResult = event.results[event.resultIndex];\n\t\t\tconst { transcript } = currentResult[0];\n\t\t\tisFinal.value = currentResult.isFinal;\n\t\t\tresult.value = transcript;\n\t\t\terror.value = void 0;\n\t\t};\n\t\trecognition.onerror = (event) => {\n\t\t\terror.value = event;\n\t\t};\n\t\trecognition.onend = () => {\n\t\t\tisListening.value = false;\n\t\t\trecognition.lang = toValue(lang);\n\t\t};\n\t\twatch(isListening, (newValue, oldValue) => {\n\t\t\tif (newValue === oldValue) return;\n\t\t\ttry {\n\t\t\t\tif (newValue) recognition.start();\n\t\t\t\telse recognition.stop();\n\t\t\t} catch (err) {\n\t\t\t\terror.value = err;\n\t\t\t}\n\t\t});\n\t}\n\ttryOnScopeDispose(() => {\n\t\tstop();\n\t});\n\treturn {\n\t\tisSupported,\n\t\tisListening,\n\t\tisFinal,\n\t\trecognition,\n\t\tresult,\n\t\terror,\n\t\ttoggle,\n\t\tstart,\n\t\tstop\n\t};\n}\n//#endregion\n//#region useSpeechSynthesis/index.ts\n/**\n* Reactive SpeechSynthesis.\n*\n* @see https://vueuse.org/useSpeechSynthesis\n* @see https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis SpeechSynthesis\n*/\nfunction useSpeechSynthesis(text, options = {}) {\n\tconst { pitch = 1, rate = 1, volume = 1, window = defaultWindow, onBoundary } = options;\n\tconst synth = window && window.speechSynthesis;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => synth);\n\tconst isPlaying = shallowRef(false);\n\tconst status = shallowRef(\"init\");\n\tconst spokenText = toRef(text || \"\");\n\tconst lang = toRef(options.lang || \"en-US\");\n\tconst error = shallowRef(void 0);\n\tconst toggle = (value = !isPlaying.value) => {\n\t\tisPlaying.value = value;\n\t};\n\tconst bindEventsForUtterance = (utterance) => {\n\t\tutterance.lang = toValue(lang);\n\t\tutterance.voice = toValue(options.voice) || null;\n\t\tutterance.pitch = toValue(pitch);\n\t\tutterance.rate = toValue(rate);\n\t\tutterance.volume = toValue(volume);\n\t\tutterance.onstart = () => {\n\t\t\tisPlaying.value = true;\n\t\t\tstatus.value = \"play\";\n\t\t};\n\t\tutterance.onpause = () => {\n\t\t\tisPlaying.value = false;\n\t\t\tstatus.value = \"pause\";\n\t\t};\n\t\tutterance.onresume = () => {\n\t\t\tisPlaying.value = true;\n\t\t\tstatus.value = \"play\";\n\t\t};\n\t\tutterance.onend = () => {\n\t\t\tisPlaying.value = false;\n\t\t\tstatus.value = \"end\";\n\t\t};\n\t\tutterance.onerror = (event) => {\n\t\t\terror.value = event;\n\t\t};\n\t\tutterance.onboundary = (event) => {\n\t\t\tonBoundary === null || onBoundary === void 0 || onBoundary(event);\n\t\t};\n\t};\n\tconst utterance = computed(() => {\n\t\tisPlaying.value = false;\n\t\tstatus.value = \"init\";\n\t\tconst newUtterance = new SpeechSynthesisUtterance(spokenText.value);\n\t\tbindEventsForUtterance(newUtterance);\n\t\treturn newUtterance;\n\t});\n\tconst speak = () => {\n\t\tsynth.cancel();\n\t\tif (utterance) synth.speak(utterance.value);\n\t};\n\tconst stop = () => {\n\t\tsynth.cancel();\n\t\tisPlaying.value = false;\n\t};\n\tif (isSupported.value) {\n\t\tbindEventsForUtterance(utterance.value);\n\t\twatch(lang, (lang) => {\n\t\t\tif (utterance.value && !isPlaying.value) utterance.value.lang = lang;\n\t\t});\n\t\tif (options.voice) watch(options.voice, () => {\n\t\t\tsynth.cancel();\n\t\t});\n\t\twatch(isPlaying, () => {\n\t\t\tif (isPlaying.value) synth.resume();\n\t\t\telse synth.pause();\n\t\t});\n\t}\n\ttryOnScopeDispose(() => {\n\t\tisPlaying.value = false;\n\t});\n\treturn {\n\t\tisSupported,\n\t\tisPlaying,\n\t\tstatus,\n\t\tutterance,\n\t\terror,\n\t\tstop,\n\t\ttoggle,\n\t\tspeak\n\t};\n}\n//#endregion\n//#region useStepper/index.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction useStepper(steps, initialStep) {\n\tconst stepsRef = ref(steps);\n\tconst stepNames = computed(() => Array.isArray(stepsRef.value) ? stepsRef.value : Object.keys(stepsRef.value));\n\tconst index = ref(stepNames.value.indexOf(initialStep !== null && initialStep !== void 0 ? initialStep : stepNames.value[0]));\n\tconst current = computed(() => at(index.value));\n\tconst isFirst = computed(() => index.value === 0);\n\tconst isLast = computed(() => index.value === stepNames.value.length - 1);\n\tconst next = computed(() => stepNames.value[index.value + 1]);\n\tconst previous = computed(() => stepNames.value[index.value - 1]);\n\tfunction at(index) {\n\t\tif (Array.isArray(stepsRef.value)) return stepsRef.value[index];\n\t\treturn stepsRef.value[stepNames.value[index]];\n\t}\n\tfunction get(step) {\n\t\tif (!stepNames.value.includes(step)) return;\n\t\treturn at(stepNames.value.indexOf(step));\n\t}\n\tfunction goTo(step) {\n\t\tif (stepNames.value.includes(step)) index.value = stepNames.value.indexOf(step);\n\t}\n\tfunction goToNext() {\n\t\tif (isLast.value) return;\n\t\tindex.value++;\n\t}\n\tfunction goToPrevious() {\n\t\tif (isFirst.value) return;\n\t\tindex.value--;\n\t}\n\tfunction goBackTo(step) {\n\t\tif (isAfter(step)) goTo(step);\n\t}\n\tfunction isNext(step) {\n\t\treturn stepNames.value.indexOf(step) === index.value + 1;\n\t}\n\tfunction isPrevious(step) {\n\t\treturn stepNames.value.indexOf(step) === index.value - 1;\n\t}\n\tfunction isCurrent(step) {\n\t\treturn stepNames.value.indexOf(step) === index.value;\n\t}\n\tfunction isBefore(step) {\n\t\treturn index.value < stepNames.value.indexOf(step);\n\t}\n\tfunction isAfter(step) {\n\t\treturn index.value > stepNames.value.indexOf(step);\n\t}\n\treturn {\n\t\tsteps: stepsRef,\n\t\tstepNames,\n\t\tindex,\n\t\tcurrent,\n\t\tnext,\n\t\tprevious,\n\t\tisFirst,\n\t\tisLast,\n\t\tat,\n\t\tget,\n\t\tgoTo,\n\t\tgoToNext,\n\t\tgoToPrevious,\n\t\tgoBackTo,\n\t\tisNext,\n\t\tisPrevious,\n\t\tisCurrent,\n\t\tisBefore,\n\t\tisAfter\n\t};\n}\n//#endregion\n//#region useStorageAsync/index.ts\n/**\n* Reactive Storage with async support.\n*\n* @see https://vueuse.org/useStorageAsync\n* @param key\n* @param initialValue\n* @param storage\n* @param options\n*/\nfunction useStorageAsync(key, initialValue, storage, options = {}) {\n\tvar _options$serializer;\n\tconst { flush = \"pre\", deep = true, listenToStorageChanges = true, writeDefaults = true, mergeDefaults = false, shallow, window = defaultWindow, eventFilter, onError = (e) => {\n\t\tconsole.error(e);\n\t}, onReady } = options;\n\tconst rawInit = toValue(initialValue);\n\tconst type = guessSerializerType(rawInit);\n\tconst data = (shallow ? shallowRef : ref)(toValue(initialValue));\n\tconst serializer = (_options$serializer = options.serializer) !== null && _options$serializer !== void 0 ? _options$serializer : StorageSerializers[type];\n\tif (!storage) try {\n\t\tstorage = getSSRHandler(\"getDefaultStorageAsync\", () => defaultWindow === null || defaultWindow === void 0 ? void 0 : defaultWindow.localStorage)();\n\t} catch (e) {\n\t\tonError(e);\n\t}\n\tasync function read(event) {\n\t\tif (!storage || event && event.key !== key) return;\n\t\ttry {\n\t\t\tconst rawValue = event ? event.newValue : await storage.getItem(key);\n\t\t\tif (rawValue == null) {\n\t\t\t\tdata.value = rawInit;\n\t\t\t\tif (writeDefaults && rawInit !== null) await storage.setItem(key, await serializer.write(rawInit));\n\t\t\t} else if (mergeDefaults) {\n\t\t\t\tconst value = await serializer.read(rawValue);\n\t\t\t\tif (typeof mergeDefaults === \"function\") data.value = mergeDefaults(value, rawInit);\n\t\t\t\telse if (type === \"object\" && !Array.isArray(value)) data.value = {\n\t\t\t\t\t...rawInit,\n\t\t\t\t\t...value\n\t\t\t\t};\n\t\t\t\telse data.value = value;\n\t\t\t} else data.value = await serializer.read(rawValue);\n\t\t} catch (e) {\n\t\t\tonError(e);\n\t\t}\n\t}\n\tconst promise = new Promise((resolve) => {\n\t\tread().then(() => {\n\t\t\tonReady === null || onReady === void 0 || onReady(data.value);\n\t\t\tresolve(data);\n\t\t});\n\t});\n\tif (window && listenToStorageChanges) useEventListener(window, \"storage\", (e) => Promise.resolve().then(() => read(e)), { passive: true });\n\tif (storage) watchWithFilter(data, async () => {\n\t\ttry {\n\t\t\tif (data.value == null) await storage.removeItem(key);\n\t\t\telse await storage.setItem(key, await serializer.write(data.value));\n\t\t} catch (e) {\n\t\t\tonError(e);\n\t\t}\n\t}, {\n\t\tflush,\n\t\tdeep,\n\t\teventFilter\n\t});\n\tObject.assign(data, {\n\t\tthen: promise.then.bind(promise),\n\t\tcatch: promise.catch.bind(promise)\n\t});\n\treturn data;\n}\n//#endregion\n//#region useStyleTag/index.ts\nlet _id = 0;\n/**\n* Inject <style> element in head.\n*\n* Overload: Omitted id\n*\n* @see https://vueuse.org/useStyleTag\n* @param css\n* @param options\n*/\nfunction useStyleTag(css, options = {}) {\n\tconst isLoaded = shallowRef(false);\n\tconst { document = defaultDocument, immediate = true, manual = false, id = `vueuse_styletag_${++_id}` } = options;\n\tconst cssRef = shallowRef(css);\n\tlet stop = () => {};\n\tconst load = () => {\n\t\tif (!document) return;\n\t\tconst el = document.getElementById(id) || document.createElement(\"style\");\n\t\tif (!el.isConnected) {\n\t\t\tel.id = id;\n\t\t\tif (options.nonce) el.nonce = options.nonce;\n\t\t\tif (options.media) el.media = options.media;\n\t\t\tdocument.head.appendChild(el);\n\t\t}\n\t\tif (isLoaded.value) return;\n\t\tstop = watch(cssRef, (value) => {\n\t\t\tel.textContent = value;\n\t\t}, { immediate: true });\n\t\tisLoaded.value = true;\n\t};\n\tconst unload = () => {\n\t\tif (!document || !isLoaded.value) return;\n\t\tstop();\n\t\tdocument.head.removeChild(document.getElementById(id));\n\t\tisLoaded.value = false;\n\t};\n\tif (immediate && !manual) tryOnMounted(load);\n\tif (!manual) tryOnScopeDispose(unload);\n\treturn {\n\t\tid,\n\t\tcss: cssRef,\n\t\tunload,\n\t\tload,\n\t\tisLoaded: shallowReadonly(isLoaded)\n\t};\n}\n//#endregion\n//#region useSwipe/index.ts\n/**\n* Reactive swipe detection.\n*\n* @see https://vueuse.org/useSwipe\n* @param target\n* @param options\n*/\nfunction useSwipe(target, options = {}) {\n\tconst { threshold = 50, onSwipe, onSwipeEnd, onSwipeStart, passive = true } = options;\n\tconst coordsStart = reactive({\n\t\tx: 0,\n\t\ty: 0\n\t});\n\tconst coordsEnd = reactive({\n\t\tx: 0,\n\t\ty: 0\n\t});\n\tconst diffX = computed(() => coordsStart.x - coordsEnd.x);\n\tconst diffY = computed(() => coordsStart.y - coordsEnd.y);\n\tconst { max, abs } = Math;\n\tconst isThresholdExceeded = computed(() => max(abs(diffX.value), abs(diffY.value)) >= threshold);\n\tconst isSwiping = shallowRef(false);\n\tconst direction = computed(() => {\n\t\tif (!isThresholdExceeded.value) return \"none\";\n\t\tif (abs(diffX.value) > abs(diffY.value)) return diffX.value > 0 ? \"left\" : \"right\";\n\t\telse return diffY.value > 0 ? \"up\" : \"down\";\n\t});\n\tconst getTouchEventCoords = (e) => [e.touches[0].clientX, e.touches[0].clientY];\n\tconst updateCoordsStart = (x, y) => {\n\t\tcoordsStart.x = x;\n\t\tcoordsStart.y = y;\n\t};\n\tconst updateCoordsEnd = (x, y) => {\n\t\tcoordsEnd.x = x;\n\t\tcoordsEnd.y = y;\n\t};\n\tconst listenerOptions = {\n\t\tpassive,\n\t\tcapture: !passive\n\t};\n\tconst onTouchEnd = (e) => {\n\t\tif (isSwiping.value) onSwipeEnd === null || onSwipeEnd === void 0 || onSwipeEnd(e, direction.value);\n\t\tisSwiping.value = false;\n\t};\n\tconst stops = [\n\t\tuseEventListener(target, \"touchstart\", (e) => {\n\t\t\tif (e.touches.length !== 1) return;\n\t\t\tconst [x, y] = getTouchEventCoords(e);\n\t\t\tupdateCoordsStart(x, y);\n\t\t\tupdateCoordsEnd(x, y);\n\t\t\tonSwipeStart === null || onSwipeStart === void 0 || onSwipeStart(e);\n\t\t}, listenerOptions),\n\t\tuseEventListener(target, \"touchmove\", (e) => {\n\t\t\tif (e.touches.length !== 1) return;\n\t\t\tconst [x, y] = getTouchEventCoords(e);\n\t\t\tupdateCoordsEnd(x, y);\n\t\t\tif (listenerOptions.capture && !listenerOptions.passive && Math.abs(diffX.value) > Math.abs(diffY.value)) e.preventDefault();\n\t\t\tif (!isSwiping.value && isThresholdExceeded.value) isSwiping.value = true;\n\t\t\tif (isSwiping.value) onSwipe === null || onSwipe === void 0 || onSwipe(e);\n\t\t}, listenerOptions),\n\t\tuseEventListener(target, [\"touchend\", \"touchcancel\"], onTouchEnd, listenerOptions)\n\t];\n\tconst stop = () => stops.forEach((s) => s());\n\treturn {\n\t\tisSwiping,\n\t\tdirection,\n\t\tcoordsStart,\n\t\tcoordsEnd,\n\t\tlengthX: diffX,\n\t\tlengthY: diffY,\n\t\tstop\n\t};\n}\n//#endregion\n//#region useTemplateRefsList/index.ts\n/* @__NO_SIDE_EFFECTS__ */\nfunction useTemplateRefsList() {\n\tconst refs = ref([]);\n\trefs.value.set = (el) => {\n\t\tif (el) refs.value.push(el);\n\t};\n\tonBeforeUpdate(() => {\n\t\trefs.value.length = 0;\n\t});\n\treturn refs;\n}\n//#endregion\n//#region useTextDirection/index.ts\n/**\n* Reactive dir of the element's text.\n*\n* @see https://vueuse.org/useTextDirection\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useTextDirection(options = {}) {\n\tconst { document = defaultDocument, selector = \"html\", observe = false, initialValue = \"ltr\" } = options;\n\tfunction getValue() {\n\t\tvar _ref, _document$querySelect;\n\t\treturn (_ref = document === null || document === void 0 || (_document$querySelect = document.querySelector(selector)) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.getAttribute(\"dir\")) !== null && _ref !== void 0 ? _ref : initialValue;\n\t}\n\tconst dir = shallowRef(getValue());\n\ttryOnMounted(() => dir.value = getValue());\n\tif (observe && document) useMutationObserver(document.querySelector(selector), () => dir.value = getValue(), { attributes: true });\n\treturn computed({\n\t\tget() {\n\t\t\treturn dir.value;\n\t\t},\n\t\tset(v) {\n\t\t\tvar _document$querySelect2, _document$querySelect3;\n\t\t\tdir.value = v;\n\t\t\tif (!document) return;\n\t\t\tif (dir.value) (_document$querySelect2 = document.querySelector(selector)) === null || _document$querySelect2 === void 0 || _document$querySelect2.setAttribute(\"dir\", dir.value);\n\t\t\telse (_document$querySelect3 = document.querySelector(selector)) === null || _document$querySelect3 === void 0 || _document$querySelect3.removeAttribute(\"dir\");\n\t\t}\n\t});\n}\n//#endregion\n//#region useTextSelection/index.ts\nfunction getRangesFromSelection(selection) {\n\tvar _selection$rangeCount;\n\tconst rangeCount = (_selection$rangeCount = selection.rangeCount) !== null && _selection$rangeCount !== void 0 ? _selection$rangeCount : 0;\n\treturn Array.from({ length: rangeCount }, (_, i) => selection.getRangeAt(i));\n}\n/**\n* Reactively track user text selection based on [`Window.getSelection`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection).\n*\n* @see https://vueuse.org/useTextSelection\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useTextSelection(options = {}) {\n\tvar _window$getSelection;\n\tconst { window = defaultWindow } = options;\n\tconst selection = shallowRef((_window$getSelection = window === null || window === void 0 ? void 0 : window.getSelection()) !== null && _window$getSelection !== void 0 ? _window$getSelection : null);\n\tconst text = computed(() => {\n\t\tvar _selection$value$toSt, _selection$value;\n\t\treturn (_selection$value$toSt = (_selection$value = selection.value) === null || _selection$value === void 0 ? void 0 : _selection$value.toString()) !== null && _selection$value$toSt !== void 0 ? _selection$value$toSt : \"\";\n\t});\n\tconst ranges = computed(() => selection.value ? getRangesFromSelection(selection.value) : []);\n\tconst rects = computed(() => ranges.value.map((range) => range.getBoundingClientRect()));\n\tfunction onSelectionChange() {\n\t\tselection.value = null;\n\t\tif (window) selection.value = window.getSelection();\n\t}\n\tif (window) useEventListener(window.document, \"selectionchange\", onSelectionChange, { passive: true });\n\treturn {\n\t\ttext,\n\t\trects,\n\t\tranges,\n\t\tselection\n\t};\n}\n//#endregion\n//#region useTextareaAutosize/index.ts\n/**\n* Call window.requestAnimationFrame(), if not available, just call the function\n*\n* @param window\n* @param fn\n*/\nfunction tryRequestAnimationFrame(window = defaultWindow, fn) {\n\tif (window && typeof window.requestAnimationFrame === \"function\") window.requestAnimationFrame(fn);\n\telse fn();\n}\nfunction useTextareaAutosize(options = {}) {\n\tvar _options$input, _options$styleProp;\n\tconst { window = defaultWindow } = options;\n\tconst textarea = toRef(options === null || options === void 0 ? void 0 : options.element);\n\tconst input = toRef((_options$input = options === null || options === void 0 ? void 0 : options.input) !== null && _options$input !== void 0 ? _options$input : \"\");\n\tconst styleProp = (_options$styleProp = options === null || options === void 0 ? void 0 : options.styleProp) !== null && _options$styleProp !== void 0 ? _options$styleProp : \"height\";\n\tconst textareaScrollHeight = shallowRef(1);\n\tconst textareaOldWidth = shallowRef(0);\n\tfunction triggerResize() {\n\t\tvar _textarea$value;\n\t\tif (!textarea.value) return;\n\t\tlet height = \"\";\n\t\tconst maxHeight = options === null || options === void 0 ? void 0 : options.maxHeight;\n\t\ttextarea.value.style[styleProp] = \"1px\";\n\t\ttextareaScrollHeight.value = (_textarea$value = textarea.value) === null || _textarea$value === void 0 ? void 0 : _textarea$value.scrollHeight;\n\t\tconst _styleTarget = toValue(options === null || options === void 0 ? void 0 : options.styleTarget);\n\t\tconst styleHeight = maxHeight != null ? `${Math.min(textareaScrollHeight.value, maxHeight)}px` : `${textareaScrollHeight.value}px`;\n\t\tif (_styleTarget) _styleTarget.style[styleProp] = styleHeight;\n\t\telse height = styleHeight;\n\t\ttextarea.value.style[styleProp] = height;\n\t}\n\twatch([input, textarea], () => nextTick(triggerResize), { immediate: true });\n\twatch(textareaScrollHeight, () => {\n\t\tvar _options$onResize;\n\t\treturn options === null || options === void 0 || (_options$onResize = options.onResize) === null || _options$onResize === void 0 ? void 0 : _options$onResize.call(options);\n\t});\n\tuseResizeObserver(textarea, ([{ contentRect }]) => {\n\t\tif (textareaOldWidth.value === contentRect.width) return;\n\t\ttryRequestAnimationFrame(window, () => {\n\t\t\ttextareaOldWidth.value = contentRect.width;\n\t\t\ttriggerResize();\n\t\t});\n\t});\n\tif (options === null || options === void 0 ? void 0 : options.watch) watch(options.watch, triggerResize, {\n\t\timmediate: true,\n\t\tdeep: true\n\t});\n\treturn {\n\t\ttextarea,\n\t\tinput,\n\t\ttriggerResize\n\t};\n}\n//#endregion\n//#region useThrottledRefHistory/index.ts\n/**\n* Shorthand for [useRefHistory](https://vueuse.org/useRefHistory) with throttled filter.\n*\n* @see https://vueuse.org/useThrottledRefHistory\n* @param source\n* @param options\n*/\nfunction useThrottledRefHistory(source, options = {}) {\n\tconst { throttle = 200, trailing = true } = options;\n\tconst filter = throttleFilter(throttle, trailing);\n\treturn { ...useRefHistory(source, {\n\t\t...options,\n\t\teventFilter: filter\n\t}) };\n}\n//#endregion\n//#region useTimeAgo/index.ts\nconst DEFAULT_UNITS = [\n\t{\n\t\tmax: 6e4,\n\t\tvalue: 1e3,\n\t\tname: \"second\"\n\t},\n\t{\n\t\tmax: 276e4,\n\t\tvalue: 6e4,\n\t\tname: \"minute\"\n\t},\n\t{\n\t\tmax: 72e6,\n\t\tvalue: 36e5,\n\t\tname: \"hour\"\n\t},\n\t{\n\t\tmax: 5184e5,\n\t\tvalue: 864e5,\n\t\tname: \"day\"\n\t},\n\t{\n\t\tmax: 24192e5,\n\t\tvalue: 6048e5,\n\t\tname: \"week\"\n\t},\n\t{\n\t\tmax: 28512e6,\n\t\tvalue: 2592e6,\n\t\tname: \"month\"\n\t},\n\t{\n\t\tmax: Number.POSITIVE_INFINITY,\n\t\tvalue: 31536e6,\n\t\tname: \"year\"\n\t}\n];\nconst DEFAULT_MESSAGES = {\n\tjustNow: \"just now\",\n\tpast: (n) => /\\d/.test(n) ? `${n} ago` : n,\n\tfuture: (n) => /\\d/.test(n) ? `in ${n}` : n,\n\tmonth: (n, past) => n === 1 ? past ? \"last month\" : \"next month\" : `${n} month${n > 1 ? \"s\" : \"\"}`,\n\tyear: (n, past) => n === 1 ? past ? \"last year\" : \"next year\" : `${n} year${n > 1 ? \"s\" : \"\"}`,\n\tday: (n, past) => n === 1 ? past ? \"yesterday\" : \"tomorrow\" : `${n} day${n > 1 ? \"s\" : \"\"}`,\n\tweek: (n, past) => n === 1 ? past ? \"last week\" : \"next week\" : `${n} week${n > 1 ? \"s\" : \"\"}`,\n\thour: (n) => `${n} hour${n > 1 ? \"s\" : \"\"}`,\n\tminute: (n) => `${n} minute${n > 1 ? \"s\" : \"\"}`,\n\tsecond: (n) => `${n} second${n > 1 ? \"s\" : \"\"}`,\n\tinvalid: \"\"\n};\nfunction DEFAULT_FORMATTER(date) {\n\treturn date.toISOString().slice(0, 10);\n}\nfunction getDefaultScheduler$4(options) {\n\tif (\"updateInterval\" in options) {\n\t\tconst { updateInterval = 3e4 } = options;\n\t\treturn (cb) => useIntervalFn(cb, updateInterval);\n\t}\n\treturn (cb) => useIntervalFn(cb, 3e4);\n}\n/**\n* Reactive time ago formatter.\n*\n* @see https://vueuse.org/useTimeAgo\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useTimeAgo(time, options = {}) {\n\tconst { controls: exposeControls = false, scheduler = getDefaultScheduler$4(options) } = options;\n\tconst { now, ...controls } = useNow({\n\t\tscheduler,\n\t\tcontrols: true\n\t});\n\tconst timeAgo = computed(() => formatTimeAgo(new Date(toValue(time)), options, toValue(now)));\n\tif (exposeControls) return {\n\t\ttimeAgo,\n\t\t...controls\n\t};\n\telse return timeAgo;\n}\nfunction formatTimeAgo(from, options = {}, now = Date.now()) {\n\tconst { max, messages = DEFAULT_MESSAGES, fullDateFormatter = DEFAULT_FORMATTER, units = DEFAULT_UNITS, showSecond = false, rounding = \"round\" } = options;\n\tconst roundFn = typeof rounding === \"number\" ? (n) => +n.toFixed(rounding) : Math[rounding];\n\tconst diff = +now - +from;\n\tconst absDiff = Math.abs(diff);\n\tfunction getValue(diff, unit) {\n\t\treturn roundFn(Math.abs(diff) / unit.value);\n\t}\n\tfunction format(diff, unit) {\n\t\tconst val = getValue(diff, unit);\n\t\tconst past = diff > 0;\n\t\tconst str = applyFormat(unit.name, val, past);\n\t\treturn applyFormat(past ? \"past\" : \"future\", str, past);\n\t}\n\tfunction applyFormat(name, val, isPast) {\n\t\tconst formatter = messages[name];\n\t\tif (typeof formatter === \"function\") return formatter(val, isPast);\n\t\treturn formatter.replace(\"{0}\", val.toString());\n\t}\n\tif (absDiff < 6e4 && !showSecond) return messages.justNow;\n\tif (typeof max === \"number\" && absDiff > max) return fullDateFormatter(new Date(from));\n\tif (typeof max === \"string\") {\n\t\tvar _units$find;\n\t\tconst unitMax = (_units$find = units.find((i) => i.name === max)) === null || _units$find === void 0 ? void 0 : _units$find.max;\n\t\tif (unitMax && absDiff > unitMax) return fullDateFormatter(new Date(from));\n\t}\n\tfor (const [idx, unit] of units.entries()) {\n\t\tif (getValue(diff, unit) <= 0 && units[idx - 1]) return format(diff, units[idx - 1]);\n\t\tif (absDiff < unit.max) return format(diff, unit);\n\t}\n\treturn messages.invalid;\n}\n//#endregion\n//#region useTimeAgoIntl/index.ts\nconst UNITS = [\n\t{\n\t\tname: \"year\",\n\t\tms: 31536e6\n\t},\n\t{\n\t\tname: \"month\",\n\t\tms: 2592e6\n\t},\n\t{\n\t\tname: \"week\",\n\t\tms: 6048e5\n\t},\n\t{\n\t\tname: \"day\",\n\t\tms: 864e5\n\t},\n\t{\n\t\tname: \"hour\",\n\t\tms: 36e5\n\t},\n\t{\n\t\tname: \"minute\",\n\t\tms: 6e4\n\t},\n\t{\n\t\tname: \"second\",\n\t\tms: 1e3\n\t}\n];\nfunction getDefaultScheduler$3(options) {\n\tif (\"updateInterval\" in options) {\n\t\tconst { updateInterval = 3e4 } = options;\n\t\treturn (cb) => useIntervalFn(cb, updateInterval);\n\t}\n\treturn (cb) => useIntervalFn(cb, 3e4);\n}\nfunction useTimeAgoIntl(time, options = {}) {\n\tconst { controls: exposeControls = false, scheduler = getDefaultScheduler$3(options) } = options;\n\tconst { now, ...controls } = useNow({\n\t\tscheduler,\n\t\tcontrols: true\n\t});\n\tconst result = computed(() => getTimeAgoIntlResult(new Date(toValue(time)), options, toValue(now)));\n\tconst parts = computed(() => result.value.parts);\n\tconst timeAgoIntl = computed(() => formatTimeAgoIntlParts(parts.value, {\n\t\t...options,\n\t\tlocale: result.value.resolvedLocale\n\t}));\n\treturn exposeControls ? {\n\t\ttimeAgoIntl,\n\t\tparts,\n\t\t...controls\n\t} : timeAgoIntl;\n}\n/**\n* Non-reactive version of useTimeAgoIntl\n*/\nfunction formatTimeAgoIntl(from, options = {}, now = Date.now()) {\n\tconst { parts, resolvedLocale } = getTimeAgoIntlResult(from, options, now);\n\treturn formatTimeAgoIntlParts(parts, {\n\t\t...options,\n\t\tlocale: resolvedLocale\n\t});\n}\n/**\n* Get parts from `Intl.RelativeTimeFormat.formatToParts`.\n*/\nfunction getTimeAgoIntlResult(from, options = {}, now = Date.now()) {\n\tvar _options$units;\n\tconst { locale, relativeTimeFormatOptions = { numeric: \"auto\" } } = options;\n\tconst rtf = new Intl.RelativeTimeFormat(locale, relativeTimeFormatOptions);\n\tconst { locale: resolvedLocale } = rtf.resolvedOptions();\n\tconst diff = +from - +now;\n\tconst absDiff = Math.abs(diff);\n\tconst units = (_options$units = options.units) !== null && _options$units !== void 0 ? _options$units : UNITS;\n\tfor (const { name, ms } of units) if (absDiff >= ms) return {\n\t\tresolvedLocale,\n\t\tparts: rtf.formatToParts(Math.round(diff / ms), name)\n\t};\n\treturn {\n\t\tresolvedLocale,\n\t\tparts: rtf.formatToParts(0, units[units.length - 1].name)\n\t};\n}\n/**\n* Format parts into a string\n*/\nfunction formatTimeAgoIntlParts(parts, options = {}) {\n\tconst { insertSpace = true, joinParts, locale } = options;\n\tif (typeof joinParts === \"function\") return joinParts(parts, locale);\n\tif (!insertSpace) return parts.map((part) => part.value).join(\"\");\n\treturn parts.map((part) => part.value.trim()).join(\" \");\n}\n//#endregion\n//#region useTimeoutPoll/index.ts\nfunction useTimeoutPoll(fn, interval, options = {}) {\n\tconst { immediate = true, immediateCallback = false } = options;\n\tconst { start } = useTimeoutFn(loop, interval, { immediate });\n\tconst isActive = shallowRef(false);\n\tasync function loop() {\n\t\tif (!isActive.value) return;\n\t\tawait fn();\n\t\tstart();\n\t}\n\tfunction resume() {\n\t\tif (!isActive.value) {\n\t\t\tisActive.value = true;\n\t\t\tif (immediateCallback) fn();\n\t\t\tstart();\n\t\t}\n\t}\n\tfunction pause() {\n\t\tisActive.value = false;\n\t}\n\tif (immediate && isClient) resume();\n\ttryOnScopeDispose(pause);\n\treturn {\n\t\tisActive,\n\t\tpause,\n\t\tresume\n\t};\n}\n//#endregion\n//#region useTimestamp/index.ts\nfunction getDefaultScheduler$2(options) {\n\tif (\"interval\" in options || \"immediate\" in options) {\n\t\tconst { interval = \"requestAnimationFrame\", immediate = true } = options;\n\t\treturn interval === \"requestAnimationFrame\" ? (cb) => useRafFn(cb, { immediate }) : (cb) => useIntervalFn(cb, interval, { immediate });\n\t}\n\treturn useRafFn;\n}\nfunction useTimestamp(options = {}) {\n\tconst { controls: exposeControls = false, offset = 0, scheduler = getDefaultScheduler$2(options), callback } = options;\n\tconst ts = shallowRef(timestamp() + offset);\n\tconst update = () => ts.value = timestamp() + offset;\n\tconst controls = scheduler(callback ? () => {\n\t\tupdate();\n\t\tcallback(ts.value);\n\t} : update);\n\tif (exposeControls) return {\n\t\ttimestamp: ts,\n\t\t...controls\n\t};\n\telse return ts;\n}\n//#endregion\n//#region useTitle/index.ts\nfunction useTitle(newTitle = null, options = {}) {\n\tvar _document$title, _ref;\n\tconst { document = defaultDocument, restoreOnUnmount = (t) => t } = options;\n\tconst originalTitle = (_document$title = document === null || document === void 0 ? void 0 : document.title) !== null && _document$title !== void 0 ? _document$title : \"\";\n\tconst title = toRef((_ref = newTitle !== null && newTitle !== void 0 ? newTitle : document === null || document === void 0 ? void 0 : document.title) !== null && _ref !== void 0 ? _ref : null);\n\tconst isReadonly = !!(newTitle && typeof newTitle === \"function\");\n\tfunction format(t) {\n\t\tif (!(\"titleTemplate\" in options)) return t;\n\t\tconst template = options.titleTemplate || \"%s\";\n\t\treturn typeof template === \"function\" ? template(t) : toValue(template).replace(/%s/g, t);\n\t}\n\twatch(title, (newValue, oldValue) => {\n\t\tif (newValue !== oldValue && document) document.title = format(newValue !== null && newValue !== void 0 ? newValue : \"\");\n\t}, { immediate: true });\n\tif (options.observe && !options.titleTemplate && document && !isReadonly) {\n\t\tvar _document$head;\n\t\tuseMutationObserver((_document$head = document.head) === null || _document$head === void 0 ? void 0 : _document$head.querySelector(\"title\"), () => {\n\t\t\tif (document && document.title !== title.value) title.value = format(document.title);\n\t\t}, { childList: true });\n\t}\n\ttryOnScopeDispose(() => {\n\t\tif (restoreOnUnmount) {\n\t\t\tconst restoredTitle = restoreOnUnmount(originalTitle, title.value || \"\");\n\t\t\tif (restoredTitle != null && document) document.title = restoredTitle;\n\t\t}\n\t});\n\treturn title;\n}\n/**\n* Common transitions\n*\n* @see https://easings.net\n*/\nconst TransitionPresets = /* @__PURE__ */ Object.assign({}, { linear: identity }, {\n\teaseInSine: [\n\t\t.12,\n\t\t0,\n\t\t.39,\n\t\t0\n\t],\n\teaseOutSine: [\n\t\t.61,\n\t\t1,\n\t\t.88,\n\t\t1\n\t],\n\teaseInOutSine: [\n\t\t.37,\n\t\t0,\n\t\t.63,\n\t\t1\n\t],\n\teaseInQuad: [\n\t\t.11,\n\t\t0,\n\t\t.5,\n\t\t0\n\t],\n\teaseOutQuad: [\n\t\t.5,\n\t\t1,\n\t\t.89,\n\t\t1\n\t],\n\teaseInOutQuad: [\n\t\t.45,\n\t\t0,\n\t\t.55,\n\t\t1\n\t],\n\teaseInCubic: [\n\t\t.32,\n\t\t0,\n\t\t.67,\n\t\t0\n\t],\n\teaseOutCubic: [\n\t\t.33,\n\t\t1,\n\t\t.68,\n\t\t1\n\t],\n\teaseInOutCubic: [\n\t\t.65,\n\t\t0,\n\t\t.35,\n\t\t1\n\t],\n\teaseInQuart: [\n\t\t.5,\n\t\t0,\n\t\t.75,\n\t\t0\n\t],\n\teaseOutQuart: [\n\t\t.25,\n\t\t1,\n\t\t.5,\n\t\t1\n\t],\n\teaseInOutQuart: [\n\t\t.76,\n\t\t0,\n\t\t.24,\n\t\t1\n\t],\n\teaseInQuint: [\n\t\t.64,\n\t\t0,\n\t\t.78,\n\t\t0\n\t],\n\teaseOutQuint: [\n\t\t.22,\n\t\t1,\n\t\t.36,\n\t\t1\n\t],\n\teaseInOutQuint: [\n\t\t.83,\n\t\t0,\n\t\t.17,\n\t\t1\n\t],\n\teaseInExpo: [\n\t\t.7,\n\t\t0,\n\t\t.84,\n\t\t0\n\t],\n\teaseOutExpo: [\n\t\t.16,\n\t\t1,\n\t\t.3,\n\t\t1\n\t],\n\teaseInOutExpo: [\n\t\t.87,\n\t\t0,\n\t\t.13,\n\t\t1\n\t],\n\teaseInCirc: [\n\t\t.55,\n\t\t0,\n\t\t1,\n\t\t.45\n\t],\n\teaseOutCirc: [\n\t\t0,\n\t\t.55,\n\t\t.45,\n\t\t1\n\t],\n\teaseInOutCirc: [\n\t\t.85,\n\t\t0,\n\t\t.15,\n\t\t1\n\t],\n\teaseInBack: [\n\t\t.36,\n\t\t0,\n\t\t.66,\n\t\t-.56\n\t],\n\teaseOutBack: [\n\t\t.34,\n\t\t1.56,\n\t\t.64,\n\t\t1\n\t],\n\teaseInOutBack: [\n\t\t.68,\n\t\t-.6,\n\t\t.32,\n\t\t1.6\n\t]\n});\n/**\n* Create an easing function from cubic bezier points.\n*/\nfunction createEasingFunction([p0, p1, p2, p3]) {\n\tconst a = (a1, a2) => 1 - 3 * a2 + 3 * a1;\n\tconst b = (a1, a2) => 3 * a2 - 6 * a1;\n\tconst c = (a1) => 3 * a1;\n\tconst calcBezier = (t, a1, a2) => ((a(a1, a2) * t + b(a1, a2)) * t + c(a1)) * t;\n\tconst getSlope = (t, a1, a2) => 3 * a(a1, a2) * t * t + 2 * b(a1, a2) * t + c(a1);\n\tconst getTforX = (x) => {\n\t\tlet aGuessT = x;\n\t\tfor (let i = 0; i < 4; ++i) {\n\t\t\tconst currentSlope = getSlope(aGuessT, p0, p2);\n\t\t\tif (currentSlope === 0) return aGuessT;\n\t\t\tconst currentX = calcBezier(aGuessT, p0, p2) - x;\n\t\t\taGuessT -= currentX / currentSlope;\n\t\t}\n\t\treturn aGuessT;\n\t};\n\treturn (x) => p0 === p1 && p2 === p3 ? x : calcBezier(getTforX(x), p1, p3);\n}\nfunction lerp(a, b, alpha) {\n\treturn a + alpha * (b - a);\n}\nfunction defaultInterpolation(a, b, t) {\n\tconst aVal = toValue(a);\n\tconst bVal = toValue(b);\n\tif (typeof aVal === \"number\" && typeof bVal === \"number\") return lerp(aVal, bVal, t);\n\tif (Array.isArray(aVal) && Array.isArray(bVal)) return aVal.map((v, i) => lerp(v, toValue(bVal[i]), t));\n\tthrow new TypeError(\"Unknown transition type, specify an interpolation function.\");\n}\nfunction normalizeEasing(easing) {\n\tvar _toValue;\n\treturn typeof easing === \"function\" ? easing : (_toValue = toValue(easing)) !== null && _toValue !== void 0 ? _toValue : identity;\n}\n/**\n* Transition from one value to another.\n*\n* @param source\n* @param from\n* @param to\n* @param options\n*/\nfunction transition(source, from, to, options = {}) {\n\tvar _toValue2;\n\tconst { window = defaultWindow } = options;\n\tconst fromVal = toValue(from);\n\tconst toVal = toValue(to);\n\tconst duration = (_toValue2 = toValue(options.duration)) !== null && _toValue2 !== void 0 ? _toValue2 : 1e3;\n\tconst startedAt = Date.now();\n\tconst endAt = Date.now() + duration;\n\tconst interpolation = typeof options.interpolation === \"function\" ? options.interpolation : defaultInterpolation;\n\tconst trans = typeof options.easing !== \"undefined\" ? normalizeEasing(options.easing) : normalizeEasing(options.transition);\n\tconst ease = typeof trans === \"function\" ? trans : createEasingFunction(trans);\n\treturn new Promise((resolve) => {\n\t\tsource.value = fromVal;\n\t\tconst tick = () => {\n\t\t\tvar _options$abort;\n\t\t\tif ((_options$abort = options.abort) === null || _options$abort === void 0 ? void 0 : _options$abort.call(options)) {\n\t\t\t\tresolve();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst now = Date.now();\n\t\t\tsource.value = interpolation(fromVal, toVal, ease((now - startedAt) / duration));\n\t\t\tif (now < endAt) window === null || window === void 0 || window.requestAnimationFrame(tick);\n\t\t\telse {\n\t\t\t\tsource.value = toVal;\n\t\t\t\tresolve();\n\t\t\t}\n\t\t};\n\t\ttick();\n\t});\n}\n/**\n* Transition from one value to another.\n* @deprecated The `executeTransition` function is deprecated, use `transition` instead.\n*\n* @param source\n* @param from\n* @param to\n* @param options\n*/\nfunction executeTransition(source, from, to, options = {}) {\n\treturn transition(source, from, to, options);\n}\n/**\n* Follow value with a transition.\n*\n* @see https://vueuse.org/useTransition\n* @param source\n* @param options\n*/\nfunction useTransition(source, options = {}) {\n\tlet currentId = 0;\n\tconst sourceVal = () => {\n\t\tconst v = toValue(source);\n\t\treturn typeof options.interpolation === \"undefined\" && Array.isArray(v) ? v.map(toValue) : v;\n\t};\n\tconst outputRef = shallowRef(sourceVal());\n\twatch(sourceVal, async (to) => {\n\t\tvar _options$onStarted, _options$onFinished;\n\t\tif (toValue(options.disabled)) return;\n\t\tconst id = ++currentId;\n\t\tif (options.delay) await promiseTimeout(toValue(options.delay));\n\t\tif (id !== currentId) return;\n\t\t(_options$onStarted = options.onStarted) === null || _options$onStarted === void 0 || _options$onStarted.call(options);\n\t\tawait transition(outputRef, outputRef.value, to, {\n\t\t\t...options,\n\t\t\tabort: () => {\n\t\t\t\tvar _options$abort2;\n\t\t\t\treturn id !== currentId || ((_options$abort2 = options.abort) === null || _options$abort2 === void 0 ? void 0 : _options$abort2.call(options));\n\t\t\t}\n\t\t});\n\t\t(_options$onFinished = options.onFinished) === null || _options$onFinished === void 0 || _options$onFinished.call(options);\n\t}, { deep: true });\n\twatch(() => toValue(options.disabled), (disabled) => {\n\t\tif (disabled) {\n\t\t\tcurrentId++;\n\t\t\toutputRef.value = sourceVal();\n\t\t}\n\t});\n\ttryOnScopeDispose(() => {\n\t\tcurrentId++;\n\t});\n\treturn computed(() => toValue(options.disabled) ? sourceVal() : outputRef.value);\n}\n//#endregion\n//#region useUrlSearchParams/index.ts\n/**\n* Reactive URLSearchParams\n*\n* @see https://vueuse.org/useUrlSearchParams\n* @param mode\n* @param options\n*/\nfunction useUrlSearchParams(mode = \"history\", options = {}) {\n\tconst { initialValue = {}, removeNullishValues = true, removeFalsyValues = false, write: enableWrite = true, writeMode = \"replace\", window = defaultWindow, stringify = (params) => params.toString() } = options;\n\tif (!window) return reactive(initialValue);\n\tconst state = reactive({});\n\tfunction getRawParams() {\n\t\tif (mode === \"history\") return window.location.search || \"\";\n\t\telse if (mode === \"hash\") {\n\t\t\tconst hash = window.location.hash || \"\";\n\t\t\tconst index = hash.indexOf(\"?\");\n\t\t\treturn index > 0 ? hash.slice(index) : \"\";\n\t\t} else return (window.location.hash || \"\").replace(/^#/, \"\");\n\t}\n\tfunction constructQuery(params) {\n\t\tconst stringified = stringify(params);\n\t\tif (mode === \"history\") return `${stringified ? `?${stringified}` : \"\"}${window.location.hash || \"\"}`;\n\t\tif (mode === \"hash-params\") return `${window.location.search || \"\"}${stringified ? `#${stringified}` : \"\"}`;\n\t\tconst hash = window.location.hash || \"#\";\n\t\tconst index = hash.indexOf(\"?\");\n\t\tif (index > 0) return `${window.location.search || \"\"}${hash.slice(0, index)}${stringified ? `?${stringified}` : \"\"}`;\n\t\treturn `${window.location.search || \"\"}${hash}${stringified ? `?${stringified}` : \"\"}`;\n\t}\n\tfunction read() {\n\t\treturn new URLSearchParams(getRawParams());\n\t}\n\tfunction updateState(params) {\n\t\tconst unusedKeys = new Set(Object.keys(state));\n\t\tfor (const key of params.keys()) {\n\t\t\tconst paramsForKey = params.getAll(key);\n\t\t\tstate[key] = paramsForKey.length > 1 ? paramsForKey : params.get(key) || \"\";\n\t\t\tunusedKeys.delete(key);\n\t\t}\n\t\tArray.from(unusedKeys).forEach((key) => delete state[key]);\n\t}\n\tconst { pause, resume } = watchPausable(state, () => {\n\t\tconst params = new URLSearchParams(\"\");\n\t\tObject.keys(state).forEach((key) => {\n\t\t\tconst mapEntry = state[key];\n\t\t\tif (Array.isArray(mapEntry)) mapEntry.forEach((value) => params.append(key, value));\n\t\t\telse if (removeNullishValues && mapEntry == null) params.delete(key);\n\t\t\telse if (removeFalsyValues && !mapEntry) params.delete(key);\n\t\t\telse params.set(key, mapEntry);\n\t\t});\n\t\twrite(params, false);\n\t}, { deep: true });\n\tfunction write(params, shouldUpdate, shouldWriteHistory = true) {\n\t\tpause();\n\t\tif (shouldUpdate) updateState(params);\n\t\tif (writeMode === \"replace\") window.history.replaceState(window.history.state, window.document.title, window.location.pathname + constructQuery(params));\n\t\telse if (shouldWriteHistory) window.history.pushState(window.history.state, window.document.title, window.location.pathname + constructQuery(params));\n\t\tnextTick(() => resume());\n\t}\n\tfunction onChanged() {\n\t\tif (!enableWrite) return;\n\t\twrite(read(), true, false);\n\t}\n\tconst listenerOptions = { passive: true };\n\tuseEventListener(window, \"popstate\", onChanged, listenerOptions);\n\tif (mode !== \"history\") useEventListener(window, \"hashchange\", onChanged, listenerOptions);\n\tconst initial = read();\n\tif (initial.keys().next().value) updateState(initial);\n\telse Object.assign(state, initialValue);\n\treturn state;\n}\n//#endregion\n//#region useUserMedia/index.ts\n/**\n* Reactive `mediaDevices.getUserMedia` streaming\n*\n* @see https://vueuse.org/useUserMedia\n* @param options\n*/\nfunction useUserMedia(options = {}) {\n\tvar _options$enabled, _options$autoSwitch;\n\tconst enabled = shallowRef((_options$enabled = options.enabled) !== null && _options$enabled !== void 0 ? _options$enabled : false);\n\tconst autoSwitch = shallowRef((_options$autoSwitch = options.autoSwitch) !== null && _options$autoSwitch !== void 0 ? _options$autoSwitch : true);\n\tconst constraints = ref(options.constraints);\n\tconst { navigator = defaultNavigator } = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => {\n\t\tvar _navigator$mediaDevic;\n\t\treturn navigator === null || navigator === void 0 || (_navigator$mediaDevic = navigator.mediaDevices) === null || _navigator$mediaDevic === void 0 ? void 0 : _navigator$mediaDevic.getUserMedia;\n\t});\n\tconst stream = shallowRef();\n\tfunction getDeviceOptions(type) {\n\t\tswitch (type) {\n\t\t\tcase \"video\":\n\t\t\t\tif (constraints.value) return constraints.value.video || false;\n\t\t\t\tbreak;\n\t\t\tcase \"audio\":\n\t\t\t\tif (constraints.value) return constraints.value.audio || false;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tasync function _start() {\n\t\tif (!isSupported.value || stream.value) return;\n\t\tstream.value = await navigator.mediaDevices.getUserMedia({\n\t\t\tvideo: getDeviceOptions(\"video\"),\n\t\t\taudio: getDeviceOptions(\"audio\")\n\t\t});\n\t\treturn stream.value;\n\t}\n\tfunction _stop() {\n\t\tvar _stream$value;\n\t\t(_stream$value = stream.value) === null || _stream$value === void 0 || _stream$value.getTracks().forEach((t) => t.stop());\n\t\tstream.value = void 0;\n\t}\n\tfunction stop() {\n\t\t_stop();\n\t\tenabled.value = false;\n\t}\n\tasync function start() {\n\t\tawait _start();\n\t\tif (stream.value) enabled.value = true;\n\t\treturn stream.value;\n\t}\n\tasync function restart() {\n\t\t_stop();\n\t\treturn await start();\n\t}\n\twatch(enabled, (v) => {\n\t\tif (v) _start();\n\t\telse _stop();\n\t}, { immediate: true });\n\twatch(constraints, () => {\n\t\tif (autoSwitch.value && stream.value) restart();\n\t}, {\n\t\timmediate: true,\n\t\tdeep: true\n\t});\n\ttryOnScopeDispose(() => {\n\t\tstop();\n\t});\n\treturn {\n\t\tisSupported,\n\t\tstream,\n\t\tstart,\n\t\tstop,\n\t\trestart,\n\t\tconstraints,\n\t\tenabled,\n\t\tautoSwitch\n\t};\n}\n//#endregion\n//#region useVModel/index.ts\n/**\n* Shorthand for v-model binding, props + emit -> ref\n*\n* @see https://vueuse.org/useVModel\n* @param props\n* @param key (default 'modelValue')\n* @param emit\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useVModel(props, key, emit, options = {}) {\n\tvar _vm$$emit, _vm$proxy;\n\tconst { clone = false, passive = false, eventName, deep = false, defaultValue, shouldEmit } = options;\n\tconst vm = getCurrentInstance();\n\tconst _emit = emit || (vm === null || vm === void 0 ? void 0 : vm.emit) || (vm === null || vm === void 0 || (_vm$$emit = vm.$emit) === null || _vm$$emit === void 0 ? void 0 : _vm$$emit.bind(vm)) || (vm === null || vm === void 0 || (_vm$proxy = vm.proxy) === null || _vm$proxy === void 0 || (_vm$proxy = _vm$proxy.$emit) === null || _vm$proxy === void 0 ? void 0 : _vm$proxy.bind(vm === null || vm === void 0 ? void 0 : vm.proxy));\n\tlet event = eventName;\n\tif (!key) key = \"modelValue\";\n\tevent = event || `update:${key.toString()}`;\n\tconst cloneFn = (val) => !clone ? val : typeof clone === \"function\" ? clone(val) : cloneFnJSON(val);\n\tconst getValue = () => isDef(props[key]) ? cloneFn(props[key]) : defaultValue;\n\tconst triggerEmit = (value) => {\n\t\tif (shouldEmit) {\n\t\t\tif (shouldEmit(value)) _emit(event, value);\n\t\t} else _emit(event, value);\n\t};\n\tif (passive) {\n\t\tconst proxy = ref(getValue());\n\t\tlet isUpdating = false;\n\t\twatch(() => props[key], (v) => {\n\t\t\tif (!isUpdating) {\n\t\t\t\tisUpdating = true;\n\t\t\t\tproxy.value = cloneFn(v);\n\t\t\t\tnextTick(() => isUpdating = false);\n\t\t\t}\n\t\t});\n\t\twatch(proxy, (v) => {\n\t\t\tif (!isUpdating && (v !== props[key] || deep)) triggerEmit(v);\n\t\t}, { deep });\n\t\treturn proxy;\n\t} else return computed({\n\t\tget() {\n\t\t\treturn getValue();\n\t\t},\n\t\tset(value) {\n\t\t\ttriggerEmit(value);\n\t\t}\n\t});\n}\n//#endregion\n//#region useVModels/index.ts\n/**\n* Shorthand for props v-model binding. Think like `toRefs(props)` but changes will also emit out.\n*\n* @see https://vueuse.org/useVModels\n* @param props\n* @param emit\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useVModels(props, emit, options = {}) {\n\tconst ret = {};\n\tfor (const key in props) ret[key] = useVModel(props, key, emit, options);\n\treturn ret;\n}\n//#endregion\n//#region useVibrate/index.ts\nfunction getDefaultScheduler$1(options = { interval: 0 }) {\n\tconst { interval } = options;\n\tif (interval === 0) return;\n\treturn (fn) => useIntervalFn(fn, interval, {\n\t\timmediate: false,\n\t\timmediateCallback: false\n\t});\n}\n/**\n* Reactive vibrate\n*\n* @see https://vueuse.org/useVibrate\n* @see https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useVibrate(options) {\n\tconst { pattern = [], scheduler = getDefaultScheduler$1(options), navigator = defaultNavigator } = options || {};\n\tconst isSupported = /* @__PURE__ */ useSupported(() => typeof navigator !== \"undefined\" && \"vibrate\" in navigator);\n\tconst patternRef = toRef(pattern);\n\tconst vibrate = (pattern = patternRef.value) => {\n\t\tif (isSupported.value) navigator.vibrate(pattern);\n\t};\n\tconst intervalControls = scheduler === null || scheduler === void 0 ? void 0 : scheduler(vibrate);\n\tconst stop = () => {\n\t\tif (isSupported.value) navigator.vibrate(0);\n\t\tintervalControls === null || intervalControls === void 0 || intervalControls.pause();\n\t};\n\treturn {\n\t\tisSupported,\n\t\tpattern,\n\t\tintervalControls,\n\t\tvibrate,\n\t\tstop\n\t};\n}\n//#endregion\n//#region useVirtualList/index.ts\n/**\n* Please consider using [`vue-virtual-scroller`](https://github.com/Akryum/vue-virtual-scroller) if you are looking for more features.\n*/\nfunction useVirtualList(list, options) {\n\tconst { containerStyle, wrapperProps, scrollTo, calculateRange, currentList, containerRef } = \"itemHeight\" in options ? useVerticalVirtualList(options, list) : useHorizontalVirtualList(options, list);\n\treturn {\n\t\tlist: currentList,\n\t\tscrollTo,\n\t\tcontainerProps: {\n\t\t\tref: containerRef,\n\t\t\tonScroll: () => {\n\t\t\t\tcalculateRange();\n\t\t\t},\n\t\t\tstyle: containerStyle\n\t\t},\n\t\twrapperProps\n\t};\n}\nfunction useVirtualListResources(list) {\n\tconst containerRef = shallowRef(null);\n\tconst size = useElementSize(containerRef);\n\tconst currentList = ref([]);\n\tconst source = shallowRef(list);\n\treturn {\n\t\tstate: ref({\n\t\t\tstart: 0,\n\t\t\tend: 10\n\t\t}),\n\t\tsource,\n\t\tcurrentList,\n\t\tsize,\n\t\tcontainerRef\n\t};\n}\nfunction createGetViewCapacity(state, source, itemSize) {\n\treturn (containerSize) => {\n\t\tif (typeof itemSize === \"number\") return Math.ceil(containerSize / itemSize);\n\t\tconst { start = 0 } = state.value;\n\t\tlet sum = 0;\n\t\tlet capacity = 0;\n\t\tfor (let i = start; i < source.value.length; i++) {\n\t\t\tconst size = itemSize(i);\n\t\t\tsum += size;\n\t\t\tcapacity = i;\n\t\t\tif (sum > containerSize) break;\n\t\t}\n\t\treturn capacity - start;\n\t};\n}\nfunction createGetOffset(source, itemSize) {\n\treturn (scrollDirection) => {\n\t\tif (typeof itemSize === \"number\") return Math.floor(scrollDirection / itemSize) + 1;\n\t\tlet sum = 0;\n\t\tlet offset = 0;\n\t\tfor (let i = 0; i < source.value.length; i++) {\n\t\t\tconst size = itemSize(i);\n\t\t\tsum += size;\n\t\t\tif (sum >= scrollDirection) {\n\t\t\t\toffset = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn offset + 1;\n\t};\n}\nfunction createCalculateRange(type, overscan, getOffset, getViewCapacity, { containerRef, state, currentList, source }) {\n\treturn () => {\n\t\tconst element = containerRef.value;\n\t\tif (element) {\n\t\t\tconst offset = getOffset(type === \"vertical\" ? element.scrollTop : element.scrollLeft);\n\t\t\tconst viewCapacity = getViewCapacity(type === \"vertical\" ? element.clientHeight : element.clientWidth);\n\t\t\tconst from = offset - overscan;\n\t\t\tconst to = offset + viewCapacity + overscan;\n\t\t\tstate.value = {\n\t\t\t\tstart: from < 0 ? 0 : from,\n\t\t\t\tend: to > source.value.length ? source.value.length : to\n\t\t\t};\n\t\t\tcurrentList.value = source.value.slice(state.value.start, state.value.end).map((ele, index) => ({\n\t\t\t\tdata: ele,\n\t\t\t\tindex: index + state.value.start\n\t\t\t}));\n\t\t}\n\t};\n}\nfunction createGetDistance(itemSize, source) {\n\treturn (index) => {\n\t\tif (typeof itemSize === \"number\") return index * itemSize;\n\t\treturn source.value.slice(0, index).reduce((sum, _, i) => sum + itemSize(i), 0);\n\t};\n}\nfunction useWatchForSizes(size, listRef, containerRef, calculateRange) {\n\twatch([\n\t\tsize.width,\n\t\tsize.height,\n\t\tlistRef,\n\t\tcontainerRef\n\t], () => {\n\t\tcalculateRange();\n\t});\n}\nfunction createComputedTotalSize(itemSize, source) {\n\treturn computed(() => {\n\t\tif (typeof itemSize === \"number\") return source.value.length * itemSize;\n\t\treturn source.value.reduce((sum, _, index) => sum + itemSize(index), 0);\n\t});\n}\nconst scrollToDictionaryForElementScrollKey = {\n\thorizontal: \"scrollLeft\",\n\tvertical: \"scrollTop\"\n};\nfunction createScrollTo(type, calculateRange, getDistance, containerRef) {\n\treturn (index) => {\n\t\tif (containerRef.value) {\n\t\t\tcontainerRef.value[scrollToDictionaryForElementScrollKey[type]] = getDistance(index);\n\t\t\tcalculateRange();\n\t\t}\n\t};\n}\nfunction useHorizontalVirtualList(options, list) {\n\tconst resources = useVirtualListResources(list);\n\tconst { state, source, currentList, size, containerRef } = resources;\n\tconst containerStyle = { overflowX: \"auto\" };\n\tconst { itemWidth, overscan = 5 } = options;\n\tconst getViewCapacity = createGetViewCapacity(state, source, itemWidth);\n\tconst calculateRange = createCalculateRange(\"horizontal\", overscan, createGetOffset(source, itemWidth), getViewCapacity, resources);\n\tconst getDistanceLeft = createGetDistance(itemWidth, source);\n\tconst offsetLeft = computed(() => getDistanceLeft(state.value.start));\n\tconst totalWidth = createComputedTotalSize(itemWidth, source);\n\tuseWatchForSizes(size, source, containerRef, calculateRange);\n\treturn {\n\t\tscrollTo: createScrollTo(\"horizontal\", calculateRange, getDistanceLeft, containerRef),\n\t\tcalculateRange,\n\t\twrapperProps: computed(() => {\n\t\t\treturn { style: {\n\t\t\t\theight: \"100%\",\n\t\t\t\twidth: `${totalWidth.value - offsetLeft.value}px`,\n\t\t\t\tmarginLeft: `${offsetLeft.value}px`,\n\t\t\t\tdisplay: \"flex\"\n\t\t\t} };\n\t\t}),\n\t\tcontainerStyle,\n\t\tcurrentList,\n\t\tcontainerRef\n\t};\n}\nfunction useVerticalVirtualList(options, list) {\n\tconst resources = useVirtualListResources(list);\n\tconst { state, source, currentList, size, containerRef } = resources;\n\tconst containerStyle = { overflowY: \"auto\" };\n\tconst { itemHeight, overscan = 5 } = options;\n\tconst getViewCapacity = createGetViewCapacity(state, source, itemHeight);\n\tconst calculateRange = createCalculateRange(\"vertical\", overscan, createGetOffset(source, itemHeight), getViewCapacity, resources);\n\tconst getDistanceTop = createGetDistance(itemHeight, source);\n\tconst offsetTop = computed(() => getDistanceTop(state.value.start));\n\tconst totalHeight = createComputedTotalSize(itemHeight, source);\n\tuseWatchForSizes(size, source, containerRef, calculateRange);\n\treturn {\n\t\tcalculateRange,\n\t\tscrollTo: createScrollTo(\"vertical\", calculateRange, getDistanceTop, containerRef),\n\t\tcontainerStyle,\n\t\twrapperProps: computed(() => {\n\t\t\treturn { style: {\n\t\t\t\twidth: \"100%\",\n\t\t\t\theight: `${totalHeight.value - offsetTop.value}px`,\n\t\t\t\tmarginTop: `${offsetTop.value}px`\n\t\t\t} };\n\t\t}),\n\t\tcurrentList,\n\t\tcontainerRef\n\t};\n}\n//#endregion\n//#region useWakeLock/index.ts\n/**\n* Reactive Screen Wake Lock API.\n*\n* @see https://vueuse.org/useWakeLock\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useWakeLock(options = {}) {\n\tconst { navigator = defaultNavigator, document = defaultDocument } = options;\n\tconst requestedType = shallowRef(false);\n\tconst sentinel = shallowRef(null);\n\tconst documentVisibility = useDocumentVisibility({ document });\n\tconst isSupported = /* @__PURE__ */ useSupported(() => navigator && \"wakeLock\" in navigator);\n\tconst isActive = computed(() => !!sentinel.value && documentVisibility.value === \"visible\");\n\tif (isSupported.value) {\n\t\tuseEventListener(sentinel, \"release\", () => {\n\t\t\tvar _sentinel$value$type, _sentinel$value;\n\t\t\trequestedType.value = (_sentinel$value$type = (_sentinel$value = sentinel.value) === null || _sentinel$value === void 0 ? void 0 : _sentinel$value.type) !== null && _sentinel$value$type !== void 0 ? _sentinel$value$type : false;\n\t\t}, { passive: true });\n\t\twhenever(() => documentVisibility.value === \"visible\" && (document === null || document === void 0 ? void 0 : document.visibilityState) === \"visible\" && requestedType.value, (type) => {\n\t\t\trequestedType.value = false;\n\t\t\tforceRequest(type);\n\t\t});\n\t}\n\tasync function forceRequest(type) {\n\t\tvar _sentinel$value2;\n\t\tawait ((_sentinel$value2 = sentinel.value) === null || _sentinel$value2 === void 0 ? void 0 : _sentinel$value2.release());\n\t\tsentinel.value = isSupported.value ? await navigator.wakeLock.request(type) : null;\n\t}\n\tasync function request(type) {\n\t\tif (documentVisibility.value === \"visible\") await forceRequest(type);\n\t\telse requestedType.value = type;\n\t}\n\tasync function release() {\n\t\trequestedType.value = false;\n\t\tconst s = sentinel.value;\n\t\tsentinel.value = null;\n\t\tawait (s === null || s === void 0 ? void 0 : s.release());\n\t}\n\ttryOnScopeDispose(() => {\n\t\trelease();\n\t});\n\treturn {\n\t\tsentinel,\n\t\tisSupported,\n\t\tisActive,\n\t\trequest,\n\t\tforceRequest,\n\t\trelease\n\t};\n}\n//#endregion\n//#region useWebNotification/index.ts\n/**\n* Reactive useWebNotification\n*\n* @see https://vueuse.org/useWebNotification\n* @see https://developer.mozilla.org/en-US/docs/Web/API/notification\n*/\nfunction useWebNotification(options = {}) {\n\tconst { window = defaultWindow, requestPermissions: _requestForPermissions = true } = options;\n\tconst defaultWebNotificationOptions = options;\n\tconst isSupported = /* @__PURE__ */ useSupported(() => {\n\t\tif (!window || !(\"Notification\" in window)) return false;\n\t\tif (Notification.permission === \"granted\") return true;\n\t\ttry {\n\t\t\tconst notification = new Notification(\"\");\n\t\t\tnotification.onshow = () => {\n\t\t\t\tnotification.close();\n\t\t\t};\n\t\t} catch (e) {\n\t\t\tif (e.name === \"TypeError\") return false;\n\t\t}\n\t\treturn true;\n\t});\n\tconst permissionGranted = shallowRef(isSupported.value && \"permission\" in Notification && Notification.permission === \"granted\");\n\tconst notification = shallowRef(null);\n\tconst ensurePermissions = async () => {\n\t\tif (!isSupported.value) return;\n\t\tif (!permissionGranted.value && Notification.permission !== \"denied\") {\n\t\t\tif (await Notification.requestPermission() === \"granted\") permissionGranted.value = true;\n\t\t}\n\t\treturn permissionGranted.value;\n\t};\n\tconst { on: onClick, trigger: clickTrigger } = createEventHook();\n\tconst { on: onShow, trigger: showTrigger } = createEventHook();\n\tconst { on: onError, trigger: errorTrigger } = createEventHook();\n\tconst { on: onClose, trigger: closeTrigger } = createEventHook();\n\tconst show = async (overrides) => {\n\t\tif (!isSupported.value || !permissionGranted.value) return;\n\t\tconst options = Object.assign({}, defaultWebNotificationOptions, overrides);\n\t\tnotification.value = new Notification(options.title || \"\", options);\n\t\tnotification.value.onclick = clickTrigger;\n\t\tnotification.value.onshow = showTrigger;\n\t\tnotification.value.onerror = errorTrigger;\n\t\tnotification.value.onclose = closeTrigger;\n\t\treturn notification.value;\n\t};\n\tconst close = () => {\n\t\tif (notification.value) notification.value.close();\n\t\tnotification.value = null;\n\t};\n\tif (_requestForPermissions) tryOnMounted(ensurePermissions);\n\ttryOnScopeDispose(close);\n\tif (isSupported.value && window) {\n\t\tconst document = window.document;\n\t\tuseEventListener(document, \"visibilitychange\", (e) => {\n\t\t\te.preventDefault();\n\t\t\tif (document.visibilityState === \"visible\") close();\n\t\t});\n\t}\n\treturn {\n\t\tisSupported,\n\t\tnotification,\n\t\tensurePermissions,\n\t\tpermissionGranted,\n\t\tshow,\n\t\tclose,\n\t\tonClick,\n\t\tonShow,\n\t\tonError,\n\t\tonClose\n\t};\n}\n//#endregion\n//#region useWebSocket/index.ts\nconst DEFAULT_PING_MESSAGE = \"ping\";\nfunction resolveNestedOptions(options) {\n\tif (options === true) return {};\n\treturn options;\n}\nfunction getDefaultScheduler(options) {\n\tif (\"interval\" in options) {\n\t\tconst { interval = 1e3 } = options;\n\t\treturn (cb) => useIntervalFn(cb, interval, { immediate: false });\n\t}\n\treturn (cb) => useIntervalFn(cb, 1e3, { immediate: false });\n}\n/**\n* Reactive WebSocket client.\n*\n* @see https://vueuse.org/useWebSocket\n* @param url\n*/\nfunction useWebSocket(url, options = {}) {\n\tconst { onConnected, onDisconnected, onError, onMessage, immediate = true, autoConnect = true, autoClose = true, protocols = [] } = options;\n\tconst data = shallowRef(null);\n\tconst status = shallowRef(\"CLOSED\");\n\tconst wsRef = shallowRef();\n\tconst urlRef = toRef(url);\n\tlet heartbeatPause;\n\tlet heartbeatResume;\n\tlet explicitlyClosed = false;\n\tlet retried = 0;\n\tlet bufferedData = [];\n\tlet retryTimeout;\n\tlet pongTimeoutWait;\n\tconst _sendBuffer = () => {\n\t\tif (bufferedData.length && wsRef.value && status.value === \"OPEN\") {\n\t\t\tfor (const buffer of bufferedData) wsRef.value.send(buffer);\n\t\t\tbufferedData = [];\n\t\t}\n\t};\n\tconst resetRetry = () => {\n\t\tif (retryTimeout != null) {\n\t\t\tclearTimeout(retryTimeout);\n\t\t\tretryTimeout = void 0;\n\t\t}\n\t};\n\tconst resetHeartbeat = () => {\n\t\tclearTimeout(pongTimeoutWait);\n\t\tpongTimeoutWait = void 0;\n\t};\n\tconst close = (code = 1e3, reason) => {\n\t\tresetRetry();\n\t\tif (!isClient && !isWorker || !wsRef.value) return;\n\t\texplicitlyClosed = true;\n\t\tresetHeartbeat();\n\t\theartbeatPause === null || heartbeatPause === void 0 || heartbeatPause();\n\t\twsRef.value.close(code, reason);\n\t\twsRef.value = void 0;\n\t};\n\tconst send = (data, useBuffer = true) => {\n\t\tif (!wsRef.value || status.value !== \"OPEN\") {\n\t\t\tif (useBuffer) bufferedData.push(data);\n\t\t\treturn false;\n\t\t}\n\t\t_sendBuffer();\n\t\twsRef.value.send(data);\n\t\treturn true;\n\t};\n\tconst _init = () => {\n\t\tif (explicitlyClosed || typeof urlRef.value === \"undefined\") return;\n\t\tconst ws = new WebSocket(urlRef.value, protocols);\n\t\twsRef.value = ws;\n\t\tstatus.value = \"CONNECTING\";\n\t\tws.onopen = () => {\n\t\t\tif (wsRef.value !== ws) return;\n\t\t\tstatus.value = \"OPEN\";\n\t\t\tretried = 0;\n\t\t\tonConnected === null || onConnected === void 0 || onConnected(ws);\n\t\t\theartbeatResume === null || heartbeatResume === void 0 || heartbeatResume();\n\t\t\t_sendBuffer();\n\t\t};\n\t\tws.onclose = (ev) => {\n\t\t\tif (wsRef.value === ws) status.value = \"CLOSED\";\n\t\t\tresetHeartbeat();\n\t\t\theartbeatPause === null || heartbeatPause === void 0 || heartbeatPause();\n\t\t\tonDisconnected === null || onDisconnected === void 0 || onDisconnected(ws, ev);\n\t\t\tif (!explicitlyClosed && options.autoReconnect && (wsRef.value == null || ws === wsRef.value)) {\n\t\t\t\tconst { retries = -1, delay = 1e3, onFailed } = resolveNestedOptions(options.autoReconnect);\n\t\t\t\tif ((typeof retries === \"function\" ? retries : () => typeof retries === \"number\" && (retries < 0 || retried < retries))(retried)) {\n\t\t\t\t\tretried += 1;\n\t\t\t\t\tconst delayTime = typeof delay === \"function\" ? delay(retried) : delay;\n\t\t\t\t\tretryTimeout = setTimeout(_init, delayTime);\n\t\t\t\t} else onFailed === null || onFailed === void 0 || onFailed();\n\t\t\t}\n\t\t};\n\t\tws.onerror = (e) => {\n\t\t\tonError === null || onError === void 0 || onError(ws, e);\n\t\t};\n\t\tws.onmessage = (e) => {\n\t\t\tif (options.heartbeat) {\n\t\t\t\tresetHeartbeat();\n\t\t\t\tconst { message = DEFAULT_PING_MESSAGE, responseMessage = message } = resolveNestedOptions(options.heartbeat);\n\t\t\t\tif (e.data === toValue(responseMessage)) return;\n\t\t\t}\n\t\t\tdata.value = e.data;\n\t\t\tonMessage === null || onMessage === void 0 || onMessage(ws, e);\n\t\t};\n\t};\n\tif (options.heartbeat) {\n\t\tconst { message = DEFAULT_PING_MESSAGE, scheduler = getDefaultScheduler(resolveNestedOptions(options.heartbeat)), pongTimeout = 1e3 } = resolveNestedOptions(options.heartbeat);\n\t\tconst { pause, resume } = scheduler(() => {\n\t\t\tsend(toValue(message), false);\n\t\t\tif (pongTimeoutWait != null) return;\n\t\t\tpongTimeoutWait = setTimeout(() => {\n\t\t\t\tclose();\n\t\t\t\texplicitlyClosed = false;\n\t\t\t}, pongTimeout);\n\t\t});\n\t\theartbeatPause = pause;\n\t\theartbeatResume = resume;\n\t}\n\tif (autoClose) {\n\t\tif (isClient) useEventListener(\"beforeunload\", () => close(), { passive: true });\n\t\ttryOnScopeDispose(close);\n\t}\n\tconst open = () => {\n\t\tif (!isClient && !isWorker) return;\n\t\tclose();\n\t\texplicitlyClosed = false;\n\t\tretried = 0;\n\t\t_init();\n\t};\n\tif (immediate) open();\n\tif (autoConnect) watch(urlRef, open);\n\treturn {\n\t\tdata,\n\t\tstatus,\n\t\tclose,\n\t\tsend,\n\t\topen,\n\t\tws: wsRef\n\t};\n}\n//#endregion\n//#region useWebWorker/index.ts\nfunction useWebWorker(arg0, workerOptions, options) {\n\tconst { window = defaultWindow } = options !== null && options !== void 0 ? options : {};\n\tconst data = shallowRef(null);\n\tconst worker = shallowRef();\n\tconst post = (...args) => {\n\t\tif (!worker.value) return;\n\t\tworker.value.postMessage(...args);\n\t};\n\tconst terminate = function terminate() {\n\t\tif (!worker.value) return;\n\t\tworker.value.terminate();\n\t};\n\tif (window) {\n\t\tif (typeof arg0 === \"string\") worker.value = new Worker(arg0, workerOptions);\n\t\telse if (typeof arg0 === \"function\") worker.value = arg0();\n\t\telse worker.value = arg0;\n\t\tworker.value.onmessage = (e) => {\n\t\t\tdata.value = e.data;\n\t\t};\n\t\ttryOnScopeDispose(() => {\n\t\t\tif (worker.value) worker.value.terminate();\n\t\t});\n\t}\n\treturn {\n\t\tdata,\n\t\tpost,\n\t\tterminate,\n\t\tworker\n\t};\n}\n//#endregion\n//#region useWebWorkerFn/lib/depsParser.ts\n/**\n*\n* Concatenates the dependencies into a comma separated string.\n* this string will then be passed as an argument to the \"importScripts\" function\n*\n* @param deps array of string\n* @param localDeps array of function\n* @returns a string composed by the concatenation of the array\n* elements \"deps\" and \"importScripts\".\n*\n* @example\n* depsParser(['demo1', 'demo2']) // return importScripts('demo1', 'demo2')\n*/\nfunction depsParser(deps, localDeps) {\n\tif (deps.length === 0 && localDeps.length === 0) return \"\";\n\tconst depsString = deps.map((dep) => `'${dep}'`).toString();\n\tconst depsFunctionString = localDeps.filter((dep) => typeof dep === \"function\").map((fn) => {\n\t\tconst str = fn.toString();\n\t\tif (str.trim().startsWith(\"function\")) return str;\n\t\telse return `const ${fn.name} = ${str}`;\n\t}).join(\";\");\n\tconst importString = `importScripts(${depsString});`;\n\treturn `${depsString.trim() === \"\" ? \"\" : importString} ${depsFunctionString}`;\n}\n//#endregion\n//#region useWebWorkerFn/lib/jobRunner.ts\n/**\n* This function accepts as a parameter a function \"userFunc\"\n* And as a result returns an anonymous function.\n* This anonymous function, accepts as arguments,\n* the parameters to pass to the function \"useArgs\" and returns a Promise\n* This function can be used as a wrapper, only inside a Worker\n* because it depends by \"postMessage\".\n*\n* @param userFunc {Function} fn the function to run with web worker\n*\n* @returns returns a function that accepts the parameters\n* to be passed to the \"userFunc\" function\n*/\nfunction jobRunner(userFunc) {\n\treturn (e) => {\n\t\tconst userFuncArgs = e.data[0];\n\t\treturn Promise.resolve(userFunc.apply(void 0, userFuncArgs)).then((result) => {\n\t\t\tpostMessage([\"SUCCESS\", result]);\n\t\t}).catch((error) => {\n\t\t\tpostMessage([\"ERROR\", error]);\n\t\t});\n\t};\n}\n//#endregion\n//#region useWebWorkerFn/lib/createWorkerBlobUrl.ts\n/**\n* Converts the \"fn\" function into the syntax needed to be executed within a web worker\n*\n* @param fn the function to run with web worker\n* @param deps array of strings, imported into the worker through \"importScripts\"\n* @param localDeps array of function, local dependencies\n*\n* @returns a blob url, containing the code of \"fn\" as a string\n*\n* @example\n* createWorkerBlobUrl((a,b) => a+b, [])\n* // return \"onmessage=return Promise.resolve((a,b) => a + b)\n* .then(postMessage(['SUCCESS', result]))\n* .catch(postMessage(['ERROR', error])\"\n*/\nfunction createWorkerBlobUrl(fn, deps, localDeps) {\n\tconst blobCode = `${depsParser(deps, localDeps)}; onmessage=(${jobRunner})(${fn})`;\n\tconst blob = new Blob([blobCode], { type: \"text/javascript\" });\n\treturn URL.createObjectURL(blob);\n}\n//#endregion\n//#region useWebWorkerFn/index.ts\n/**\n* Run expensive function without blocking the UI, using a simple syntax that makes use of Promise.\n*\n* @see https://vueuse.org/useWebWorkerFn\n* @param fn\n* @param options\n*/\nfunction useWebWorkerFn(fn, options = {}) {\n\tconst { dependencies = [], localDependencies = [], timeout, window = defaultWindow } = options;\n\tlet worker;\n\tconst workerStatus = shallowRef(\"PENDING\");\n\tconst promise = shallowRef({});\n\tconst timeoutId = shallowRef();\n\tconst workerTerminate = (status = \"PENDING\") => {\n\t\tif (worker && worker._url && window) {\n\t\t\tworker.terminate();\n\t\t\tURL.revokeObjectURL(worker._url);\n\t\t\tpromise.value = {};\n\t\t\tworker = void 0;\n\t\t\twindow.clearTimeout(timeoutId.value);\n\t\t\tworkerStatus.value = status;\n\t\t}\n\t};\n\tworkerTerminate();\n\ttryOnScopeDispose(workerTerminate);\n\tconst generateWorker = () => {\n\t\tconst blobUrl = createWorkerBlobUrl(fn, dependencies, localDependencies);\n\t\tconst newWorker = new Worker(blobUrl);\n\t\tnewWorker._url = blobUrl;\n\t\tnewWorker.onmessage = (e) => {\n\t\t\tconst { resolve = () => {}, reject = () => {} } = promise.value;\n\t\t\tconst [status, result] = e.data;\n\t\t\tswitch (status) {\n\t\t\t\tcase \"SUCCESS\":\n\t\t\t\t\tresolve(result);\n\t\t\t\t\tworkerTerminate(status);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\treject(result);\n\t\t\t\t\tworkerTerminate(\"ERROR\");\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t};\n\t\tnewWorker.onerror = (e) => {\n\t\t\tconst { reject = () => {} } = promise.value;\n\t\t\te.preventDefault();\n\t\t\treject(e);\n\t\t\tworkerTerminate(\"ERROR\");\n\t\t};\n\t\tif (timeout) timeoutId.value = setTimeout(workerTerminate, timeout, \"TIMEOUT_EXPIRED\");\n\t\treturn newWorker;\n\t};\n\tconst callWorker = (...fnArgs) => new Promise((resolve, reject) => {\n\t\tpromise.value = {\n\t\t\tresolve,\n\t\t\treject\n\t\t};\n\t\tworker === null || worker === void 0 || worker.postMessage([[...fnArgs]]);\n\t\tworkerStatus.value = \"RUNNING\";\n\t});\n\tconst workerFn = (...fnArgs) => {\n\t\tif (workerStatus.value === \"RUNNING\") {\n\t\t\tconsole.error(\"[useWebWorkerFn] You can only run one instance of the worker at a time.\");\n\t\t\treturn Promise.reject();\n\t\t}\n\t\tworker = generateWorker();\n\t\treturn callWorker(...fnArgs);\n\t};\n\treturn {\n\t\tworkerFn,\n\t\tworkerStatus,\n\t\tworkerTerminate\n\t};\n}\n//#endregion\n//#region useWindowFocus/index.ts\n/**\n* Reactively track window focus with `window.onfocus` and `window.onblur`.\n*\n* @see https://vueuse.org/useWindowFocus\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useWindowFocus(options = {}) {\n\tconst { window = defaultWindow } = options;\n\tif (!window) return shallowRef(false);\n\tconst focused = shallowRef(window.document.hasFocus());\n\tconst listenerOptions = { passive: true };\n\tuseEventListener(window, \"blur\", () => {\n\t\tfocused.value = false;\n\t}, listenerOptions);\n\tuseEventListener(window, \"focus\", () => {\n\t\tfocused.value = true;\n\t}, listenerOptions);\n\treturn focused;\n}\n//#endregion\n//#region useWindowScroll/index.ts\n/**\n* Reactive window scroll.\n*\n* @see https://vueuse.org/useWindowScroll\n* @param options\n*/\nfunction useWindowScroll(options = {}) {\n\tconst { window = defaultWindow, ...rest } = options;\n\treturn useScroll(window, rest);\n}\n//#endregion\n//#region useWindowSize/index.ts\n/**\n* Reactive window size.\n*\n* @see https://vueuse.org/useWindowSize\n* @param options\n*\n* @__NO_SIDE_EFFECTS__\n*/\nfunction useWindowSize(options = {}) {\n\tconst { window = defaultWindow, initialWidth = Number.POSITIVE_INFINITY, initialHeight = Number.POSITIVE_INFINITY, listenOrientation = true, includeScrollbar = true, type = \"inner\" } = options;\n\tconst width = shallowRef(initialWidth);\n\tconst height = shallowRef(initialHeight);\n\tconst update = () => {\n\t\tif (window) if (type === \"outer\") {\n\t\t\twidth.value = window.outerWidth;\n\t\t\theight.value = window.outerHeight;\n\t\t} else if (type === \"visual\" && window.visualViewport) {\n\t\t\tconst { width: visualViewportWidth, height: visualViewportHeight, scale } = window.visualViewport;\n\t\t\twidth.value = Math.round(visualViewportWidth * scale);\n\t\t\theight.value = Math.round(visualViewportHeight * scale);\n\t\t} else if (includeScrollbar) {\n\t\t\twidth.value = window.innerWidth;\n\t\t\theight.value = window.innerHeight;\n\t\t} else {\n\t\t\twidth.value = window.document.documentElement.clientWidth;\n\t\t\theight.value = window.document.documentElement.clientHeight;\n\t\t}\n\t};\n\tupdate();\n\ttryOnMounted(update);\n\tconst listenerOptions = { passive: true };\n\tuseEventListener(\"resize\", update, listenerOptions);\n\tif (window && type === \"visual\" && window.visualViewport) useEventListener(window.visualViewport, \"resize\", update, listenerOptions);\n\tif (listenOrientation) watch(useMediaQuery(\"(orientation: portrait)\"), () => update());\n\treturn {\n\t\twidth,\n\t\theight\n\t};\n}\n//#endregion\nexport { DefaultMagicKeysAliasMap, StorageSerializers, TransitionPresets, asyncComputed, breakpointsAntDesign, breakpointsBootstrapV5, breakpointsElement, breakpointsMasterCss, breakpointsPrimeFlex, breakpointsQuasar, breakpointsSematic, breakpointsTailwind, breakpointsVuetify, breakpointsVuetifyV2, breakpointsVuetifyV3, cloneFnJSON, computedAsync, computedInject, createFetch, createReusableTemplate, createTemplatePromise, createUnrefFn, customStorageEventName, defaultDocument, defaultLocation, defaultNavigator, defaultWindow, executeTransition, formatTimeAgo, formatTimeAgoIntl, formatTimeAgoIntlParts, getSSRHandler, mapGamepadToXbox360Controller, onClickOutside, onElementRemoval, onKeyDown, onKeyPressed, onKeyStroke, onKeyUp, onLongPress, onStartTyping, provideSSRWidth, setSSRHandler, templateRef, transition, unrefElement, useActiveElement, useAnimate, useAsyncQueue, useAsyncState, useBase64, useBattery, useBluetooth, useBreakpoints, useBroadcastChannel, useBrowserLocation, useCached, useClipboard, useClipboardItems, useCloned, useColorMode, useConfirmDialog, useCountdown, useCssSupports, useCssVar, useCurrentElement, useCycleList, useDark, useDebouncedRefHistory, useDeviceMotion, useDeviceOrientation, useDevicePixelRatio, useDevicesList, useDisplayMedia, useDocumentVisibility, useDraggable, useDropZone, useElementBounding, useElementByPoint, useElementHover, useElementSize, useElementVisibility, useEventBus, useEventListener, useEventSource, useEyeDropper, useFavicon, useFetch, useFileDialog, useFileSystemAccess, useFocus, useFocusWithin, useFps, useFullscreen, useGamepad, useGeolocation, useIdle, useImage, useInfiniteScroll, useIntersectionObserver, useKeyModifier, useLocalStorage, useMagicKeys, useManualRefHistory, useMediaControls, useMediaQuery, useMemoize, useMemory, useMounted, useMouse, useMouseInElement, useMousePressed, useMutationObserver, useNavigatorLanguage, useNetwork, useNow, useObjectUrl, useOffsetPagination, useOnline, usePageLeave, useParallax, useParentElement, usePerformanceObserver, usePermission, usePointer, usePointerLock, usePointerSwipe, usePreferredColorScheme, usePreferredContrast, usePreferredDark, usePreferredLanguages, usePreferredReducedMotion, usePreferredReducedTransparency, usePrevious, useRafFn, useRefHistory, useResizeObserver, useSSRWidth, useScreenOrientation, useScreenSafeArea, useScriptTag, useScroll, useScrollLock, useSessionStorage, useShare, useSorted, useSpeechRecognition, useSpeechSynthesis, useStepper, useStorage, useStorageAsync, useStyleTag, useSupported, useSwipe, useTemplateRefsList, useTextDirection, useTextSelection, useTextareaAutosize, useThrottledRefHistory, useTimeAgo, useTimeAgoIntl, useTimeoutPoll, useTimestamp, useTitle, useTransition, useUrlSearchParams, useUserMedia, useVModel, useVModels, useVibrate, useVirtualList, useWakeLock, useWebNotification, useWebSocket, useWebWorker, useWebWorkerFn, useWindowFocus, useWindowScroll, useWindowSize };\n","import type { MaybeElementRef } from '@vueuse/core'\nimport { unrefElement } from '@vueuse/core'\nimport { onMounted, onUnmounted } from 'vue'\n\nexport function onFocusOutside(\n  element: MaybeElementRef,\n  handler: (event: FocusEvent) => void,\n) {\n  const handleFocusOut = (ev: FocusEvent) => {\n    const el = unrefElement(element)\n    if (!ev.relatedTarget)\n      return\n    const isFocusInsideElement = el?.contains(ev.relatedTarget as Node)\n\n    if (!isFocusInsideElement)\n      handler(ev)\n  }\n\n  onMounted(() => {\n    const el = unrefElement(element)\n    // @ts-expect-error focusout should received FocusEvent\n    el?.addEventListener('focusout', handleFocusOut)\n  })\n  onUnmounted(() => {\n    const el = unrefElement(element)\n    // @ts-expect-error focusout should received FocusEvent\n    el?.removeEventListener('focusout', handleFocusOut)\n  })\n}\n","import type { VNode } from 'vue'\nimport { Fragment } from 'vue'\n\nexport function renderSlotFragments(children?: VNode[]): VNode[] {\n  if (!children)\n    return []\n  return children.flatMap((child) => {\n    if (child.type === Fragment)\n      return renderSlotFragments(child.children as VNode[])\n\n    return [child]\n  })\n}\n","import { getActiveElement } from './getActiveElement'\n\nexport function trapFocus(element: HTMLElement) {\n  if (element) {\n    const focusableEls = [\n      ...Array.from(\n        element.querySelectorAll(\n          'a[href], button, input, textarea, select, details,[tabindex]:not([tabindex=\"-1\"])',\n        ),\n      ),\n    ].filter(\n      el => !el.hasAttribute('disabled') && !el.getAttribute('aria-hidden'),\n    )\n    const firstFocusableEl = focusableEls[0] as HTMLElement\n    const lastFocusableEl = focusableEls.at(-1) as HTMLElement\n    const KEYCODE_TAB = 9\n\n    if (firstFocusableEl)\n      firstFocusableEl.focus()\n\n    element.addEventListener('keydown', (e) => {\n      const isTabPressed = e.key === 'Tab' || e.keyCode === KEYCODE_TAB\n\n      if (!isTabPressed)\n        return\n\n      if (e.shiftKey) {\n        /* shift + tab */ if (getActiveElement() === firstFocusableEl) {\n          lastFocusableEl.focus()\n          e.preventDefault()\n        }\n      }\n      else {\n      /* tab */\n        if (getActiveElement() === lastFocusableEl) {\n          firstFocusableEl.focus()\n          e.preventDefault()\n        }\n      }\n    })\n    return firstFocusableEl\n  }\n}\n","import type { Direction } from './types'\n\ntype ArrowKeyOptions = 'horizontal' | 'vertical' | 'both'\n\ninterface ArrowNavigationOptions {\n  /**\n   * The arrow key options to allow navigation\n   *\n   * @defaultValue \"both\"\n   */\n  arrowKeyOptions?: ArrowKeyOptions\n\n  /**\n   * The attribute name to find the collection items in the parent element.\n   *\n   * @defaultValue \"data-reka-collection-item\"\n   */\n  attributeName?: string\n\n  /**\n   * The parent element where contains all the collection items, this will collect every item to be used when nav\n   * It will be ignored if attributeName is provided\n   *\n   * @defaultValue []\n   */\n  itemsArray?: HTMLElement[]\n\n  /**\n   * Allow loop navigation. If false, it will stop at the first and last element\n   *\n   * @defaultValue true\n   */\n  loop?: boolean\n\n  /**\n   * The orientation of the collection\n   *\n   * @defaultValue \"ltr\"\n   */\n  dir?: Direction\n\n  /**\n   * Prevent the scroll when navigating. This happens when the direction of the\n   * key matches the scroll direction of any ancestor scrollable elements.\n   *\n   * @defaultValue true\n   */\n  preventScroll?: boolean\n\n  /**\n   * By default all currentElement would trigger navigation. If `true`, currentElement nodeName in the ignore list will return null\n   *\n   * @defaultValue false\n   */\n  enableIgnoredElement?: boolean\n\n  /**\n   * Focus the element after navigation\n   *\n   * @defaultValue false\n   */\n  focus?: boolean\n}\n\nconst ignoredElement = ['INPUT', 'TEXTAREA']\n\n/**\n * Allow arrow navigation for every html element with data-reka-collection-item tag\n *\n * @param e               Keyboard event\n * @param currentElement  Event initiator element or any element that wants to handle the navigation\n * @param parentElement   Parent element where contains all the collection items, this will collect every item to be used when nav\n * @param options         further options\n * @returns               the navigated html element or null if none\n */\nexport function useArrowNavigation(\n  e: KeyboardEvent,\n  currentElement: HTMLElement,\n  parentElement: HTMLElement | undefined,\n  options: ArrowNavigationOptions = {},\n): HTMLElement | null {\n  if (!currentElement || (options.enableIgnoredElement && ignoredElement.includes(currentElement.nodeName)))\n    return null\n\n  const {\n    arrowKeyOptions = 'both',\n    attributeName = '[data-reka-collection-item]',\n    itemsArray = [],\n    loop = true,\n    dir = 'ltr',\n    preventScroll = true,\n    focus = false,\n  } = options\n\n  const [right, left, up, down, home, end] = [\n    e.key === 'ArrowRight',\n    e.key === 'ArrowLeft',\n    e.key === 'ArrowUp',\n    e.key === 'ArrowDown',\n    e.key === 'Home',\n    e.key === 'End',\n  ]\n  const goingVertical = up || down\n  const goingHorizontal = right || left\n  if (\n    !home\n    && !end\n    && ((!goingVertical && !goingHorizontal)\n      || (arrowKeyOptions === 'vertical' && goingHorizontal)\n      || (arrowKeyOptions === 'horizontal' && goingVertical))\n  ) {\n    return null\n  }\n\n  const allCollectionItems: HTMLElement[] = parentElement\n    ? Array.from(parentElement.querySelectorAll(attributeName))\n    : itemsArray\n\n  if (!allCollectionItems.length)\n    return null\n\n  if (preventScroll)\n    e.preventDefault()\n\n  let item: HTMLElement | null = null\n\n  if (goingHorizontal || goingVertical) {\n    const goForward = goingVertical ? down : dir === 'ltr' ? right : left\n    item = findNextFocusableElement(allCollectionItems, currentElement, {\n      goForward,\n      loop,\n    })\n  }\n  else if (home) {\n    item = allCollectionItems.at(0) || null\n  }\n  else if (end) {\n    item = allCollectionItems.at(-1) || null\n  }\n\n  if (focus)\n    item?.focus()\n\n  return item\n}\n\ninterface FindNextFocusableElementOptions {\n  /**\n   * Whether to search forwards or backwards.\n   */\n  goForward: boolean\n  /**\n   * Whether to allow looping the search. If false, it will stop at the first/last element.\n   *\n   * @default true\n   */\n  loop?: boolean\n}\n\n/**\n * Recursive function to find the next focusable element to avoid disabled elements\n *\n * @param elements Elements to navigate\n * @param currentElement Current active element\n * @param options\n * @returns next focusable element\n */\nfunction findNextFocusableElement(\n  elements: HTMLElement[],\n  currentElement: HTMLElement,\n  options: FindNextFocusableElementOptions,\n  iterations = !elements.includes(currentElement) ? elements.length + 1 : elements.length,\n): HTMLElement | null {\n  if (--iterations === 0)\n    return null\n\n  const index = elements.indexOf(currentElement)\n  let newIndex: number\n  if (index === -1) {\n    newIndex = options.goForward ? 0 : elements.length - 1\n  }\n  else {\n    newIndex = options.goForward ? index + 1 : index - 1\n  }\n\n  if (!options.loop && (newIndex < 0 || newIndex >= elements.length))\n    return null\n\n  const adjustedNewIndex = (newIndex + elements.length) % elements.length\n  const candidate = elements[adjustedNewIndex]\n  if (!candidate)\n    return null\n\n  const isDisabled\n    = candidate.hasAttribute('disabled')\n      && candidate.getAttribute('disabled') !== 'false'\n  if (isDisabled) {\n    return findNextFocusableElement(\n      elements,\n      candidate,\n      options,\n      iterations,\n    )\n  }\n  return candidate\n}\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Direction, ScrollBodyOption } from '@/shared/types'\nimport { createContext } from '@/shared'\n\ninterface ConfigProviderContextValue {\n  dir?: Ref<Direction>\n  locale?: Ref<string>\n  scrollBody?: Ref<boolean | ScrollBodyOption>\n  nonce?: Ref<string | undefined>\n  useId?: () => string\n}\n\nexport const [injectConfigProviderContext, provideConfigProviderContext]\n  = createContext<ConfigProviderContextValue>('ConfigProvider')\n\nexport interface ConfigProviderProps {\n  /**\n   * The global reading direction of your application. This will be inherited by all primitives.\n   * @defaultValue 'ltr'\n   */\n  dir?: Direction\n  /**\n   * The global locale of your application. This will be inherited by all primitives.\n   * @defaultValue 'en'\n   */\n  locale?: string\n  /**\n   * The global scroll body behavior of your application. This will be inherited by the related primitives.\n   * @type boolean | ScrollBodyOption\n   */\n  scrollBody?: boolean | ScrollBodyOption\n  /**\n   * The global `nonce` value of your application. This will be inherited by the related primitives.\n   * @type string\n   */\n  nonce?: string\n  /**\n   * The global `useId` injection as a workaround for preventing hydration issue.\n   */\n  useId?: () => string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { toRefs } from 'vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ConfigProviderProps>(), {\n  dir: 'ltr',\n  locale: 'en',\n  scrollBody: true,\n  nonce: undefined,\n  useId: undefined,\n})\n\nconst { dir, locale, scrollBody, nonce } = toRefs(props)\n\nprovideConfigProviderContext({\n  dir,\n  locale,\n  scrollBody,\n  nonce,\n  useId: props.useId,\n})\n</script>\n\n<template>\n  <slot />\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Direction, ScrollBodyOption } from '@/shared/types'\nimport { createContext } from '@/shared'\n\ninterface ConfigProviderContextValue {\n  dir?: Ref<Direction>\n  locale?: Ref<string>\n  scrollBody?: Ref<boolean | ScrollBodyOption>\n  nonce?: Ref<string | undefined>\n  useId?: () => string\n}\n\nexport const [injectConfigProviderContext, provideConfigProviderContext]\n  = createContext<ConfigProviderContextValue>('ConfigProvider')\n\nexport interface ConfigProviderProps {\n  /**\n   * The global reading direction of your application. This will be inherited by all primitives.\n   * @defaultValue 'ltr'\n   */\n  dir?: Direction\n  /**\n   * The global locale of your application. This will be inherited by all primitives.\n   * @defaultValue 'en'\n   */\n  locale?: string\n  /**\n   * The global scroll body behavior of your application. This will be inherited by the related primitives.\n   * @type boolean | ScrollBodyOption\n   */\n  scrollBody?: boolean | ScrollBodyOption\n  /**\n   * The global `nonce` value of your application. This will be inherited by the related primitives.\n   * @type string\n   */\n  nonce?: string\n  /**\n   * The global `useId` injection as a workaround for preventing hydration issue.\n   */\n  useId?: () => string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { toRefs } from 'vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ConfigProviderProps>(), {\n  dir: 'ltr',\n  locale: 'en',\n  scrollBody: true,\n  nonce: undefined,\n  useId: undefined,\n})\n\nconst { dir, locale, scrollBody, nonce } = toRefs(props)\n\nprovideConfigProviderContext({\n  dir,\n  locale,\n  scrollBody,\n  nonce,\n  useId: props.useId,\n})\n</script>\n\n<template>\n  <slot />\n</template>\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction isPlainObject(value) {\n  if (value === null || typeof value !== \"object\") {\n    return false;\n  }\n  const prototype = Object.getPrototypeOf(value);\n  if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {\n    return false;\n  }\n  if (Symbol.iterator in value) {\n    return false;\n  }\n  if (Symbol.toStringTag in value) {\n    return Object.prototype.toString.call(value) === \"[object Module]\";\n  }\n  return true;\n}\n\nfunction _defu(baseObject, defaults, namespace = \".\", merger) {\n  if (!isPlainObject(defaults)) {\n    return _defu(baseObject, {}, namespace, merger);\n  }\n  const object = { ...defaults };\n  for (const key of Object.keys(baseObject)) {\n    if (key === \"__proto__\" || key === \"constructor\") {\n      continue;\n    }\n    const value = baseObject[key];\n    if (value === null || value === void 0) {\n      continue;\n    }\n    if (merger && merger(object, key, value, namespace)) {\n      continue;\n    }\n    if (Array.isArray(value) && Array.isArray(object[key])) {\n      object[key] = [...value, ...object[key]];\n    } else if (isPlainObject(value) && isPlainObject(object[key])) {\n      object[key] = _defu(\n        value,\n        object[key],\n        (namespace ? `${namespace}.` : \"\") + key.toString(),\n        merger\n      );\n    } else {\n      object[key] = value;\n    }\n  }\n  return object;\n}\nfunction createDefu(merger) {\n  return (...arguments_) => (\n    // eslint-disable-next-line unicorn/no-array-reduce\n    arguments_.reduce((p, c) => _defu(p, c, \"\", merger), {})\n  );\n}\nconst defu = createDefu();\nconst defuFn = createDefu((object, key, currentValue) => {\n  if (object[key] !== void 0 && typeof currentValue === \"function\") {\n    object[key] = currentValue(object[key]);\n    return true;\n  }\n});\nconst defuArrayFn = createDefu((object, key, currentValue) => {\n  if (Array.isArray(object[key]) && typeof currentValue === \"function\") {\n    object[key] = currentValue(object[key]);\n    return true;\n  }\n});\n\nexports.createDefu = createDefu;\nexports.default = defu;\nexports.defu = defu;\nexports.defuArrayFn = defuArrayFn;\nexports.defuFn = defuFn;\n","const { defu, createDefu, defuFn, defuArrayFn } = require(\"../dist/defu.cjs\");\n\nmodule.exports = defu;\n\nmodule.exports.defu = defu;\nmodule.exports.default = defu;\n\nmodule.exports.createDefu = createDefu;\nmodule.exports.defuFn = defuFn;\nmodule.exports.defuArrayFn = defuArrayFn;\n","import type { Fn } from '@vueuse/shared'\nimport {\n  createSharedComposable,\n  useEventListener,\n} from '@vueuse/core'\nimport { isClient, isIOS, tryOnBeforeUnmount } from '@vueuse/shared'\nimport { defu } from 'defu'\nimport { computed, nextTick, ref, watch } from 'vue'\nimport { injectConfigProviderContext } from '@/ConfigProvider/ConfigProvider.vue'\n\nconst useBodyLockStackCount = createSharedComposable(() => {\n  const map = ref<Map<string, boolean>>(new Map())\n  const initialOverflow = ref<string | undefined>()\n\n  const locked = computed(() => {\n    for (const value of map.value.values()) {\n      if (value)\n        return true\n    }\n    return false\n  })\n\n  const context = injectConfigProviderContext({\n    scrollBody: ref(true),\n  })\n\n  let stopTouchMoveListener: Fn | null = null\n\n  const resetBodyStyle = () => {\n    document.body.style.paddingRight = ''\n    document.body.style.marginRight = ''\n    document.body.style.pointerEvents = ''\n    document.documentElement.style.removeProperty('--scrollbar-width')\n    document.body.style.overflow = initialOverflow.value ?? ''\n    isIOS && stopTouchMoveListener?.()\n\n    initialOverflow.value = undefined\n  }\n\n  watch(locked, (val, oldVal) => {\n    if (!isClient)\n      return\n\n    if (!val) {\n      if (oldVal)\n        resetBodyStyle()\n      return\n    }\n\n    if (initialOverflow.value === undefined)\n      initialOverflow.value = document.body.style.overflow\n\n    const verticalScrollbarWidth = window.innerWidth - document.documentElement.clientWidth\n    const defaultConfig = { padding: verticalScrollbarWidth, margin: 0 }\n\n    const config = context.scrollBody?.value\n      ? typeof context.scrollBody.value === 'object'\n        ? defu({\n            padding: context.scrollBody.value.padding === true ? verticalScrollbarWidth : context.scrollBody.value.padding,\n            margin: context.scrollBody.value.margin === true ? verticalScrollbarWidth : context.scrollBody.value.margin,\n          }, defaultConfig)\n        : defaultConfig\n      : ({ padding: 0, margin: 0 })\n\n    if (verticalScrollbarWidth > 0) {\n      document.body.style.paddingRight = typeof config.padding === 'number' ? `${config.padding}px` : String(config.padding)\n      document.body.style.marginRight = typeof config.margin === 'number' ? `${config.margin}px` : String(config.margin)\n      document.documentElement.style.setProperty('--scrollbar-width', `${verticalScrollbarWidth}px`)\n      document.body.style.overflow = 'hidden'\n    }\n\n    if (isIOS) {\n      stopTouchMoveListener = useEventListener(\n        document,\n        'touchmove',\n        (e: TouchEvent) => preventDefault(e),\n        { passive: false },\n      )\n    }\n\n    // let dismissibleLayer set previous pointerEvent first\n    nextTick(() => {\n      if (!locked.value)\n        return\n      document.body.style.pointerEvents = 'none'\n      document.body.style.overflow = 'hidden'\n    })\n  }, { immediate: true, flush: 'sync' })\n\n  return map\n})\n\nexport function useBodyScrollLock(initialState?: boolean | undefined) {\n  const id = Math.random().toString(36).substring(2, 7) // just simple random id, need not to be cryptographically secure\n  const map = useBodyLockStackCount()\n\n  map.value.set(id, initialState ?? false)\n\n  const locked = computed({\n    get: () => map.value.get(id) ?? false,\n    set: value => map.value.set(id, value),\n  })\n\n  tryOnBeforeUnmount(() => {\n    map.value.delete(id)\n  })\n\n  return locked\n}\n\n// Adapt from https://github.com/vueuse/vueuse/blob/main/packages/core/useScrollLock/index.ts#L28C10-L28C24\nfunction checkOverflowScroll(ele: Element): boolean {\n  const style = window.getComputedStyle(ele)\n  if (\n    style.overflowX === 'scroll'\n    || style.overflowY === 'scroll'\n    || (style.overflowX === 'auto' && ele.clientWidth < ele.scrollWidth)\n    || (style.overflowY === 'auto' && ele.clientHeight < ele.scrollHeight)\n  ) {\n    return true\n  }\n  else {\n    const parent = ele.parentNode\n\n    if (!(parent instanceof Element) || parent.tagName === 'BODY')\n      return false\n\n    return checkOverflowScroll(parent)\n  }\n}\n\nfunction preventDefault(rawEvent: TouchEvent): boolean {\n  const e = rawEvent || window.event\n\n  const _target = e.target\n\n  // Do not prevent if element or parentNodes have overflow: scroll set.\n  if (_target instanceof Element && checkOverflowScroll(_target))\n    return false\n\n  // Do not prevent if the event has more than one touch (usually meaning this is a multi touch gesture like pinch to zoom).\n  if (e.touches.length > 1)\n    return true\n\n  if (e.preventDefault && e.cancelable)\n    e.preventDefault()\n\n  return false\n}\n","import { nextTick, ref } from 'vue'\n\nexport function useComposing(onEnd?: (event: CompositionEvent) => void) {\n  const isComposing = ref(false)\n\n  function handleCompositionStart() {\n    isComposing.value = true\n  }\n\n  function handleCompositionEnd(event: CompositionEvent) {\n    nextTick(() => {\n      isComposing.value = false\n      onEnd?.(event)\n    })\n  }\n\n  return { isComposing, handleCompositionStart, handleCompositionEnd }\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nexport type Mutable<T> = {\n  -readonly [P in keyof T]: T[P];\n};\n\nexport function mod(amount: number, numerator: number): number {\n  return amount - numerator * Math.floor(amount / numerator);\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar, CalendarIdentifier} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {mod, Mutable} from '../utils';\n\nconst EPOCH = 1721426; // 001/01/03 Julian C.E.\nexport function gregorianToJulianDay(\n  era: string,\n  year: number,\n  month: number,\n  day: number\n): number {\n  year = getExtendedYear(era, year);\n\n  let y1 = year - 1;\n  let monthOffset = -2;\n  if (month <= 2) {\n    monthOffset = 0;\n  } else if (isLeapYear(year)) {\n    monthOffset = -1;\n  }\n\n  return (\n    EPOCH -\n    1 +\n    365 * y1 +\n    Math.floor(y1 / 4) -\n    Math.floor(y1 / 100) +\n    Math.floor(y1 / 400) +\n    Math.floor((367 * month - 362) / 12 + monthOffset + day)\n  );\n}\n\nexport function isLeapYear(year: number): boolean {\n  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n\nexport function getExtendedYear(era: string, year: number): number {\n  return era === 'BC' ? 1 - year : year;\n}\n\nexport function fromExtendedYear(year: number): [string, number] {\n  let era = 'AD';\n  if (year <= 0) {\n    era = 'BC';\n    year = 1 - year;\n  }\n\n  return [era, year];\n}\n\nconst daysInMonth = {\n  standard: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],\n  leapyear: [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n};\n\n/**\n * The Gregorian calendar is the most commonly used calendar system in the world. It supports two\n * eras: BC, and AD. Years always contain 12 months, and 365 or 366 days depending on whether it is\n * a leap year.\n */\nexport class GregorianCalendar implements Calendar {\n  identifier: CalendarIdentifier = 'gregory';\n\n  fromJulianDay(jd: number): CalendarDate {\n    let jd0 = jd;\n    let depoch = jd0 - EPOCH;\n    let quadricent = Math.floor(depoch / 146097);\n    let dqc = mod(depoch, 146097);\n    let cent = Math.floor(dqc / 36524);\n    let dcent = mod(dqc, 36524);\n    let quad = Math.floor(dcent / 1461);\n    let dquad = mod(dcent, 1461);\n    let yindex = Math.floor(dquad / 365);\n\n    let extendedYear =\n      quadricent * 400 + cent * 100 + quad * 4 + yindex + (cent !== 4 && yindex !== 4 ? 1 : 0);\n    let [era, year] = fromExtendedYear(extendedYear);\n    let yearDay = jd0 - gregorianToJulianDay(era, year, 1, 1);\n    let leapAdj = 2;\n    if (jd0 < gregorianToJulianDay(era, year, 3, 1)) {\n      leapAdj = 0;\n    } else if (isLeapYear(year)) {\n      leapAdj = 1;\n    }\n    let month = Math.floor(((yearDay + leapAdj) * 12 + 373) / 367);\n    let day = jd0 - gregorianToJulianDay(era, year, month, 1) + 1;\n\n    return new CalendarDate(era, year, month, day);\n  }\n\n  toJulianDay(date: AnyCalendarDate): number {\n    return gregorianToJulianDay(date.era, date.year, date.month, date.day);\n  }\n\n  getDaysInMonth(date: AnyCalendarDate): number {\n    return daysInMonth[isLeapYear(date.year) ? 'leapyear' : 'standard'][date.month - 1];\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  getMonthsInYear(date: AnyCalendarDate): number {\n    return 12;\n  }\n\n  getDaysInYear(date: AnyCalendarDate): number {\n    return isLeapYear(date.year) ? 366 : 365;\n  }\n\n  getMaximumMonthsInYear(): number {\n    return 12;\n  }\n\n  getMaximumDaysInMonth(): number {\n    return 31;\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  getYearsInEra(date: AnyCalendarDate): number {\n    return 9999;\n  }\n\n  getEras(): string[] {\n    return ['BC', 'AD'];\n  }\n\n  isInverseEra(date: AnyCalendarDate): boolean {\n    return date.era === 'BC';\n  }\n\n  balanceDate(date: Mutable<AnyCalendarDate>): void {\n    if (date.year <= 0) {\n      date.era = date.era === 'BC' ? 'AD' : 'BC';\n      date.year = 1 - date.year;\n    }\n  }\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Data from https://github.com/unicode-cldr/cldr-core/blob/master/supplemental/weekData.json\n// Locales starting on Sunday have been removed for compression.\nexport const weekStartData = {\n  '001': 1,\n  AD: 1,\n  AE: 6,\n  AF: 6,\n  AI: 1,\n  AL: 1,\n  AM: 1,\n  AN: 1,\n  AR: 1,\n  AT: 1,\n  AU: 1,\n  AX: 1,\n  AZ: 1,\n  BA: 1,\n  BE: 1,\n  BG: 1,\n  BH: 6,\n  BM: 1,\n  BN: 1,\n  BY: 1,\n  CH: 1,\n  CL: 1,\n  CM: 1,\n  CN: 1,\n  CR: 1,\n  CY: 1,\n  CZ: 1,\n  DE: 1,\n  DJ: 6,\n  DK: 1,\n  DZ: 6,\n  EC: 1,\n  EE: 1,\n  EG: 6,\n  ES: 1,\n  FI: 1,\n  FJ: 1,\n  FO: 1,\n  FR: 1,\n  GB: 1,\n  GE: 1,\n  GF: 1,\n  GP: 1,\n  GR: 1,\n  HR: 1,\n  HU: 1,\n  IE: 1,\n  IQ: 6,\n  IR: 6,\n  IS: 1,\n  IT: 1,\n  JO: 6,\n  KG: 1,\n  KW: 6,\n  KZ: 1,\n  LB: 1,\n  LI: 1,\n  LK: 1,\n  LT: 1,\n  LU: 1,\n  LV: 1,\n  LY: 6,\n  MC: 1,\n  MD: 1,\n  ME: 1,\n  MK: 1,\n  MN: 1,\n  MQ: 1,\n  MV: 5,\n  MY: 1,\n  NL: 1,\n  NO: 1,\n  NZ: 1,\n  OM: 6,\n  PL: 1,\n  QA: 6,\n  RE: 1,\n  RO: 1,\n  RS: 1,\n  RU: 1,\n  SD: 6,\n  SE: 1,\n  SI: 1,\n  SK: 1,\n  SM: 1,\n  SY: 6,\n  TJ: 1,\n  TM: 1,\n  TR: 1,\n  UA: 1,\n  UY: 1,\n  UZ: 1,\n  VA: 1,\n  VN: 1,\n  XK: 1\n};\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {AnyCalendarDate, AnyTime, Calendar} from './types';\nimport {CalendarDate, CalendarDateTime, DateValue, ZonedDateTime} from './CalendarDate';\nimport {fromAbsolute, toAbsolute, toCalendar, toCalendarDate} from './conversion';\nimport {weekStartData} from './weekStartData';\n\n/** Returns whether the given dates occur on the same day, regardless of the time or calendar system. */\nexport function isSameDay(a: DateValue, b: DateValue): boolean {\n  b = toCalendar(b, a.calendar);\n  return a.era === b.era && a.year === b.year && a.month === b.month && a.day === b.day;\n}\n\n/**\n * Returns whether the given dates occur in the same month, using the calendar system of the first\n * date.\n */\nexport function isSameMonth(a: DateValue, b: DateValue): boolean {\n  b = toCalendar(b, a.calendar);\n  // In the Japanese calendar, months can span multiple eras/years, so only compare the first of the month.\n  a = startOfMonth(a);\n  b = startOfMonth(b);\n  return a.era === b.era && a.year === b.year && a.month === b.month;\n}\n\n/**\n * Returns whether the given dates occur in the same year, using the calendar system of the first\n * date.\n */\nexport function isSameYear(a: DateValue, b: DateValue): boolean {\n  b = toCalendar(b, a.calendar);\n  a = startOfYear(a);\n  b = startOfYear(b);\n  return a.era === b.era && a.year === b.year;\n}\n\n/** Returns whether the given dates occur on the same day, and are of the same calendar system. */\nexport function isEqualDay(a: DateValue, b: DateValue): boolean {\n  return isEqualCalendar(a.calendar, b.calendar) && isSameDay(a, b);\n}\n\n/** Returns whether the given dates occur in the same month, and are of the same calendar system. */\nexport function isEqualMonth(a: DateValue, b: DateValue): boolean {\n  return isEqualCalendar(a.calendar, b.calendar) && isSameMonth(a, b);\n}\n\n/** Returns whether the given dates occur in the same year, and are of the same calendar system. */\nexport function isEqualYear(a: DateValue, b: DateValue): boolean {\n  return isEqualCalendar(a.calendar, b.calendar) && isSameYear(a, b);\n}\n\n/** Returns whether two calendars are the same. */\nexport function isEqualCalendar(a: Calendar, b: Calendar): boolean {\n  return a.isEqual?.(b) ?? b.isEqual?.(a) ?? a.identifier === b.identifier;\n}\n\n/** Returns whether the date is today in the given time zone. */\nexport function isToday(date: DateValue, timeZone: string): boolean {\n  return isSameDay(date, today(timeZone));\n}\n\nconst DAY_MAP = {\n  sun: 0,\n  mon: 1,\n  tue: 2,\n  wed: 3,\n  thu: 4,\n  fri: 5,\n  sat: 6\n};\n\ntype DayOfWeek = 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat';\n\n/**\n * Returns the day of week for the given date and locale. Days are numbered from zero to six,\n * where zero is the first day of the week in the given locale. For example, in the United States,\n * the first day of the week is Sunday, but in France it is Monday.\n */\nexport function getDayOfWeek(date: DateValue, locale: string, firstDayOfWeek?: DayOfWeek): number {\n  let julian = date.calendar.toJulianDay(date);\n\n  // If julian is negative, then julian % 7 will be negative, so we adjust\n  // accordingly.  Julian day 0 is Monday.\n  let weekStart = firstDayOfWeek ? DAY_MAP[firstDayOfWeek] : getWeekStart(locale);\n  let dayOfWeek = Math.ceil(julian + 1 - weekStart) % 7;\n  if (dayOfWeek < 0) {\n    dayOfWeek += 7;\n  }\n\n  return dayOfWeek;\n}\n\n/** Returns the current time in the given time zone. */\nexport function now(timeZone: string): ZonedDateTime {\n  return fromAbsolute(Date.now(), timeZone);\n}\n\n/** Returns today's date in the given time zone. */\nexport function today(timeZone: string): CalendarDate {\n  return toCalendarDate(now(timeZone));\n}\n\nexport function compareDate(a: AnyCalendarDate, b: AnyCalendarDate): number {\n  return a.calendar.toJulianDay(a) - b.calendar.toJulianDay(b);\n}\n\nexport function compareTime(a: AnyTime, b: AnyTime): number {\n  return timeToMs(a) - timeToMs(b);\n}\n\nfunction timeToMs(a: AnyTime): number {\n  return a.hour * 60 * 60 * 1000 + a.minute * 60 * 1000 + a.second * 1000 + a.millisecond;\n}\n\n/**\n * Returns the number of hours in the given date and time zone.\n * Usually this is 24, but it could be 23 or 25 if the date is on a daylight saving transition.\n */\nexport function getHoursInDay(a: CalendarDate, timeZone: string): number {\n  let ms = toAbsolute(a, timeZone);\n  let tomorrow = a.add({days: 1});\n  let tomorrowMs = toAbsolute(tomorrow, timeZone);\n  return (tomorrowMs - ms) / 3600000;\n}\n\nlet localTimeZone: string | null = null;\nlet localTimeZoneOverride = false;\n\n/** Returns the time zone identifier for the current user. */\nexport function getLocalTimeZone(): string {\n  if (localTimeZone == null) {\n    localTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone;\n  }\n\n  return localTimeZone!;\n}\n\n/** Sets the time zone identifier for the current user. */\nexport function setLocalTimeZone(timeZone: string): void {\n  localTimeZoneOverride = true;\n  localTimeZone = timeZone;\n}\n\n/** Resets the time zone identifier for the current user. */\nexport function resetLocalTimeZone(): void {\n  localTimeZoneOverride = false;\n  localTimeZone = null;\n}\n\n/** Returns whether the local time zone has been explicitly overridden via `setLocalTimeZone`. */\nexport function isLocalTimeZoneOverridden(): boolean {\n  return localTimeZoneOverride;\n}\n\n/** Returns the first date of the month for the given date. */\nexport function startOfMonth(date: ZonedDateTime): ZonedDateTime;\nexport function startOfMonth(date: CalendarDateTime): CalendarDateTime;\nexport function startOfMonth(date: CalendarDate): CalendarDate;\nexport function startOfMonth(date: DateValue): DateValue;\nexport function startOfMonth(date: DateValue): DateValue {\n  // Use `subtract` instead of `set` so we don't get constrained in an era.\n  return date.subtract({days: date.day - 1});\n}\n\n/** Returns the last date of the month for the given date. */\nexport function endOfMonth(date: ZonedDateTime): ZonedDateTime;\nexport function endOfMonth(date: CalendarDateTime): CalendarDateTime;\nexport function endOfMonth(date: CalendarDate): CalendarDate;\nexport function endOfMonth(date: DateValue): DateValue;\nexport function endOfMonth(date: DateValue): DateValue {\n  return date.add({days: date.calendar.getDaysInMonth(date) - date.day});\n}\n\n/** Returns the first day of the year for the given date. */\nexport function startOfYear(date: ZonedDateTime): ZonedDateTime;\nexport function startOfYear(date: CalendarDateTime): CalendarDateTime;\nexport function startOfYear(date: CalendarDate): CalendarDate;\nexport function startOfYear(date: DateValue): DateValue;\nexport function startOfYear(date: DateValue): DateValue {\n  return startOfMonth(date.subtract({months: date.month - 1}));\n}\n\n/** Returns the last day of the year for the given date. */\nexport function endOfYear(date: ZonedDateTime): ZonedDateTime;\nexport function endOfYear(date: CalendarDateTime): CalendarDateTime;\nexport function endOfYear(date: CalendarDate): CalendarDate;\nexport function endOfYear(date: DateValue): DateValue;\nexport function endOfYear(date: DateValue): DateValue {\n  return endOfMonth(date.add({months: date.calendar.getMonthsInYear(date) - date.month}));\n}\n\nexport function getMinimumMonthInYear(date: AnyCalendarDate): number {\n  if (date.calendar.getMinimumMonthInYear) {\n    return date.calendar.getMinimumMonthInYear(date);\n  }\n\n  return 1;\n}\n\nexport function getMinimumDayInMonth(date: AnyCalendarDate): number {\n  if (date.calendar.getMinimumDayInMonth) {\n    return date.calendar.getMinimumDayInMonth(date);\n  }\n\n  return 1;\n}\n\n/** Returns the first date of the week for the given date and locale. */\nexport function startOfWeek(\n  date: ZonedDateTime,\n  locale: string,\n  firstDayOfWeek?: DayOfWeek\n): ZonedDateTime;\nexport function startOfWeek(\n  date: CalendarDateTime,\n  locale: string,\n  firstDayOfWeek?: DayOfWeek\n): CalendarDateTime;\nexport function startOfWeek(\n  date: CalendarDate,\n  locale: string,\n  firstDayOfWeek?: DayOfWeek\n): CalendarDate;\nexport function startOfWeek(date: DateValue, locale: string, firstDayOfWeek?: DayOfWeek): DateValue;\nexport function startOfWeek(\n  date: DateValue,\n  locale: string,\n  firstDayOfWeek?: DayOfWeek\n): DateValue {\n  let dayOfWeek = getDayOfWeek(date, locale, firstDayOfWeek);\n  return date.subtract({days: dayOfWeek});\n}\n\n/** Returns the last date of the week for the given date and locale. */\nexport function endOfWeek(\n  date: ZonedDateTime,\n  locale: string,\n  firstDayOfWeek?: DayOfWeek\n): ZonedDateTime;\nexport function endOfWeek(\n  date: CalendarDateTime,\n  locale: string,\n  firstDayOfWeek?: DayOfWeek\n): CalendarDateTime;\nexport function endOfWeek(\n  date: CalendarDate,\n  locale: string,\n  firstDayOfWeek?: DayOfWeek\n): CalendarDate;\nexport function endOfWeek(date: DateValue, locale: string, firstDayOfWeek?: DayOfWeek): DateValue;\nexport function endOfWeek(date: DateValue, locale: string, firstDayOfWeek?: DayOfWeek): DateValue {\n  return startOfWeek(date, locale, firstDayOfWeek).add({days: 6});\n}\n\nconst cachedRegions = new Map<string, string>();\nconst cachedWeekInfo = new Map<string, {firstDay: number}>();\n\nfunction getRegion(locale: string): string | undefined {\n  // If the Intl.Locale API is available, use it to get the region for the locale.\n  // @ts-ignore\n  if (Intl.Locale) {\n    // Constructing an Intl.Locale is expensive, so cache the result.\n    let region = cachedRegions.get(locale);\n    if (!region) {\n      // @ts-ignore\n      region = new Intl.Locale(locale).maximize().region;\n      if (region) {\n        cachedRegions.set(locale, region);\n      }\n    }\n    return region;\n  }\n\n  // If not, just try splitting the string.\n  // If the second part of the locale string is 'u',\n  // then this is a unicode extension, so ignore it.\n  // Otherwise, it should be the region.\n  let part = locale.split('-')[1];\n  return part === 'u' ? undefined : part;\n}\n\nfunction getWeekStart(locale: string): number {\n  // TODO: use Intl.Locale for this once browsers support the weekInfo property\n  // https://github.com/tc39/proposal-intl-locale-info\n  let weekInfo = cachedWeekInfo.get(locale);\n  if (!weekInfo) {\n    if (Intl.Locale) {\n      // @ts-ignore\n      let localeInst = new Intl.Locale(locale);\n      if ('getWeekInfo' in localeInst) {\n        // @ts-expect-error\n        weekInfo = localeInst.getWeekInfo();\n        if (weekInfo) {\n          cachedWeekInfo.set(locale, weekInfo);\n          return weekInfo.firstDay;\n        }\n      }\n    }\n    let region = getRegion(locale);\n    if (locale.includes('-fw-')) {\n      // pull the value for the attribute fw from strings such as en-US-u-ca-iso8601-fw-tue or en-US-u-ca-iso8601-fw-mon-nu-thai\n      // where the fw attribute could be followed by another unicode locale extension or not\n      let day = locale.split('-fw-')[1].split('-')[0];\n      if (day === 'mon') {\n        weekInfo = {firstDay: 1};\n      } else if (day === 'tue') {\n        weekInfo = {firstDay: 2};\n      } else if (day === 'wed') {\n        weekInfo = {firstDay: 3};\n      } else if (day === 'thu') {\n        weekInfo = {firstDay: 4};\n      } else if (day === 'fri') {\n        weekInfo = {firstDay: 5};\n      } else if (day === 'sat') {\n        weekInfo = {firstDay: 6};\n      } else {\n        weekInfo = {firstDay: 0};\n      }\n    } else if (locale.includes('-ca-iso8601')) {\n      weekInfo = {firstDay: 1};\n    } else {\n      weekInfo = {firstDay: region ? weekStartData[region] || 0 : 0};\n    }\n    cachedWeekInfo.set(locale, weekInfo);\n  }\n\n  return weekInfo.firstDay;\n}\n\n/** Returns the number of weeks in the given month and locale. */\nexport function getWeeksInMonth(\n  date: DateValue,\n  locale: string,\n  firstDayOfWeek?: DayOfWeek\n): number {\n  let days = date.calendar.getDaysInMonth(date);\n  return Math.ceil((getDayOfWeek(startOfMonth(date), locale, firstDayOfWeek) + days) / 7);\n}\n\n/** Returns the lesser of the two provider dates. */\nexport function minDate<A extends DateValue, B extends DateValue>(\n  a?: A | null,\n  b?: B | null\n): A | B | null | undefined {\n  if (a && b) {\n    return a.compare(b) <= 0 ? a : b;\n  }\n\n  return a || b;\n}\n\n/** Returns the greater of the two provider dates. */\nexport function maxDate<A extends DateValue, B extends DateValue>(\n  a?: A | null,\n  b?: B | null\n): A | B | null | undefined {\n  if (a && b) {\n    return a.compare(b) >= 0 ? a : b;\n  }\n\n  return a || b;\n}\n\nconst WEEKEND_DATA = {\n  AF: [4, 5],\n  AE: [5, 6],\n  BH: [5, 6],\n  DZ: [5, 6],\n  EG: [5, 6],\n  IL: [5, 6],\n  IQ: [5, 6],\n  IR: [5, 5],\n  JO: [5, 6],\n  KW: [5, 6],\n  LY: [5, 6],\n  OM: [5, 6],\n  QA: [5, 6],\n  SA: [5, 6],\n  SD: [5, 6],\n  SY: [5, 6],\n  YE: [5, 6]\n};\n\n/** Returns whether the given date is on a weekend in the given locale. */\nexport function isWeekend(date: DateValue, locale: string): boolean {\n  let julian = date.calendar.toJulianDay(date);\n\n  // If julian is negative, then julian % 7 will be negative, so we adjust\n  // accordingly.  Julian day 0 is Monday.\n  let dayOfWeek = Math.ceil(julian + 1) % 7;\n  if (dayOfWeek < 0) {\n    dayOfWeek += 7;\n  }\n\n  let region = getRegion(locale);\n  // Use Intl.Locale for this once weekInfo is supported.\n  // https://github.com/tc39/proposal-intl-locale-info\n  let [start, end] = WEEKEND_DATA[region!] || [6, 0];\n  return dayOfWeek === start || dayOfWeek === end;\n}\n\n/** Returns whether the given date is on a weekday in the given locale. */\nexport function isWeekday(date: DateValue, locale: string): boolean {\n  return !isWeekend(date, locale);\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from the TC39 Temporal proposal.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {\n  AnyCalendarDate,\n  AnyDateTime,\n  AnyTime,\n  Calendar,\n  DateFields,\n  Disambiguation,\n  TimeFields\n} from './types';\nimport {CalendarDate, CalendarDateTime, Time, ZonedDateTime} from './CalendarDate';\nimport {constrain} from './manipulation';\nimport {getExtendedYear, GregorianCalendar} from './calendars/GregorianCalendar';\nimport {getLocalTimeZone, isEqualCalendar, isLocalTimeZoneOverridden} from './queries';\nimport {Mutable} from './utils';\n\nexport function epochFromDate(date: AnyDateTime): number {\n  date = toCalendar(date, new GregorianCalendar());\n  let year = getExtendedYear(date.era, date.year);\n  return epochFromParts(\n    year,\n    date.month,\n    date.day,\n    date.hour,\n    date.minute,\n    date.second,\n    date.millisecond\n  );\n}\n\nfunction epochFromParts(\n  year: number,\n  month: number,\n  day: number,\n  hour: number,\n  minute: number,\n  second: number,\n  millisecond: number\n): number {\n  // Note: Date.UTC() interprets one and two-digit years as being in the\n  // 20th century, so don't use it\n  let date = new Date();\n  date.setUTCHours(hour, minute, second, millisecond);\n  date.setUTCFullYear(year, month - 1, day);\n  return date.getTime();\n}\n\nexport function getTimeZoneOffset(ms: number, timeZone: string): number {\n  // Fast path for UTC.\n  if (timeZone === 'UTC') {\n    return 0;\n  }\n\n  // Fast path: for local timezone after 1970, use native Date.\n  // Skip this fast path if the local timezone was explicitly overridden via setLocalTimeZone,\n  // since native Date always uses the browser's timezone, not the overridden one.\n  if (ms > 0 && timeZone === getLocalTimeZone() && !isLocalTimeZoneOverridden()) {\n    return new Date(ms).getTimezoneOffset() * -60 * 1000;\n  }\n\n  let {year, month, day, hour, minute, second} = getTimeZoneParts(ms, timeZone);\n  let utc = epochFromParts(year, month, day, hour, minute, second, 0);\n  return utc - Math.floor(ms / 1000) * 1000;\n}\n\nconst formattersByTimeZone = new Map<string, Intl.DateTimeFormat>();\n\nfunction getTimeZoneParts(ms: number, timeZone: string) {\n  let formatter = formattersByTimeZone.get(timeZone);\n  if (!formatter) {\n    formatter = new Intl.DateTimeFormat('en-US', {\n      timeZone,\n      hour12: false,\n      era: 'short',\n      year: 'numeric',\n      month: 'numeric',\n      day: 'numeric',\n      hour: 'numeric',\n      minute: 'numeric',\n      second: 'numeric'\n    });\n\n    formattersByTimeZone.set(timeZone, formatter);\n  }\n\n  let parts = formatter.formatToParts(new Date(ms));\n  let namedParts: {[name: string]: string} = {};\n  for (let part of parts) {\n    if (part.type !== 'literal') {\n      namedParts[part.type] = part.value;\n    }\n  }\n\n  return {\n    // Firefox returns B instead of BC... https://bugzilla.mozilla.org/show_bug.cgi?id=1752253\n    year:\n      namedParts.era === 'BC' || namedParts.era === 'B' ? -namedParts.year + 1 : +namedParts.year,\n    month: +namedParts.month,\n    day: +namedParts.day,\n    hour: namedParts.hour === '24' ? 0 : +namedParts.hour, // bugs.chromium.org/p/chromium/issues/detail?id=1045791\n    minute: +namedParts.minute,\n    second: +namedParts.second\n  };\n}\n\nconst DAYMILLIS = 86400000;\n\nexport function possibleAbsolutes(date: CalendarDateTime, timeZone: string): number[] {\n  let ms = epochFromDate(date);\n  let earlier = ms - getTimeZoneOffset(ms - DAYMILLIS, timeZone);\n  let later = ms - getTimeZoneOffset(ms + DAYMILLIS, timeZone);\n  return getValidWallTimes(date, timeZone, earlier, later);\n}\n\nfunction getValidWallTimes(\n  date: CalendarDateTime,\n  timeZone: string,\n  earlier: number,\n  later: number\n): number[] {\n  let found = earlier === later ? [earlier] : [earlier, later];\n  return found.filter(absolute => isValidWallTime(date, timeZone, absolute));\n}\n\nfunction isValidWallTime(date: CalendarDateTime, timeZone: string, absolute: number) {\n  let parts = getTimeZoneParts(absolute, timeZone);\n  return (\n    date.year === parts.year &&\n    date.month === parts.month &&\n    date.day === parts.day &&\n    date.hour === parts.hour &&\n    date.minute === parts.minute &&\n    date.second === parts.second\n  );\n}\n\nexport function toAbsolute(\n  date: CalendarDate | CalendarDateTime,\n  timeZone: string,\n  disambiguation: Disambiguation = 'compatible'\n): number {\n  let dateTime = toCalendarDateTime(date);\n\n  // Fast path: if the time zone is UTC, use native Date.\n  if (timeZone === 'UTC') {\n    return epochFromDate(dateTime);\n  }\n\n  // Fast path: if the time zone is the local timezone and disambiguation is compatible, use native Date.\n  // Skip this fast path if the local timezone was explicitly overridden via setLocalTimeZone,\n  // since native Date always uses the browser's timezone, not the overridden one.\n  if (\n    timeZone === getLocalTimeZone() &&\n    disambiguation === 'compatible' &&\n    !isLocalTimeZoneOverridden()\n  ) {\n    dateTime = toCalendar(dateTime, new GregorianCalendar());\n\n    // Don't use Date constructor here because two-digit years are interpreted in the 20th century.\n    let date = new Date();\n    let year = getExtendedYear(dateTime.era, dateTime.year);\n    date.setFullYear(year, dateTime.month - 1, dateTime.day);\n    date.setHours(dateTime.hour, dateTime.minute, dateTime.second, dateTime.millisecond);\n    return date.getTime();\n  }\n\n  let ms = epochFromDate(dateTime);\n  let offsetBefore = getTimeZoneOffset(ms - DAYMILLIS, timeZone);\n  let offsetAfter = getTimeZoneOffset(ms + DAYMILLIS, timeZone);\n  let valid = getValidWallTimes(dateTime, timeZone, ms - offsetBefore, ms - offsetAfter);\n\n  if (valid.length === 1) {\n    return valid[0];\n  }\n\n  if (valid.length > 1) {\n    switch (disambiguation) {\n      // 'compatible' means 'earlier' for \"fall back\" transitions\n      case 'compatible':\n      case 'earlier':\n        return valid[0];\n      case 'later':\n        return valid[valid.length - 1];\n      case 'reject':\n        throw new RangeError('Multiple possible absolute times found');\n    }\n  }\n\n  switch (disambiguation) {\n    case 'earlier':\n      return Math.min(ms - offsetBefore, ms - offsetAfter);\n    // 'compatible' means 'later' for \"spring forward\" transitions\n    case 'compatible':\n    case 'later':\n      return Math.max(ms - offsetBefore, ms - offsetAfter);\n    case 'reject':\n      throw new RangeError('No such absolute time found');\n  }\n}\n\nexport function toDate(\n  dateTime: CalendarDate | CalendarDateTime,\n  timeZone: string,\n  disambiguation: Disambiguation = 'compatible'\n): Date {\n  return new Date(toAbsolute(dateTime, timeZone, disambiguation));\n}\n\n/**\n * Takes a Unix epoch (milliseconds since 1970) and converts it to the provided time zone.\n */\nexport function fromAbsolute(ms: number, timeZone: string): ZonedDateTime {\n  let offset = getTimeZoneOffset(ms, timeZone);\n  let date = new Date(ms + offset);\n  let year = date.getUTCFullYear();\n  let month = date.getUTCMonth() + 1;\n  let day = date.getUTCDate();\n  let hour = date.getUTCHours();\n  let minute = date.getUTCMinutes();\n  let second = date.getUTCSeconds();\n  let millisecond = date.getUTCMilliseconds();\n\n  return new ZonedDateTime(\n    year < 1 ? 'BC' : 'AD',\n    year < 1 ? -year + 1 : year,\n    month,\n    day,\n    timeZone,\n    offset,\n    hour,\n    minute,\n    second,\n    millisecond\n  );\n}\n\n/**\n * Takes a `Date` object and converts it to the provided time zone.\n */\nexport function fromDate(date: Date, timeZone: string): ZonedDateTime {\n  return fromAbsolute(date.getTime(), timeZone);\n}\n\n/**\n * Takes a `Date` object and converts it to the time zone identifier for the current user.\n */\nexport function fromDateToLocal(date: Date): ZonedDateTime {\n  return fromDate(date, getLocalTimeZone());\n}\n\n/**\n * Converts a value with date components such as a `CalendarDateTime` or `ZonedDateTime` into a\n * `CalendarDate`.\n */\nexport function toCalendarDate(dateTime: AnyCalendarDate): CalendarDate {\n  return new CalendarDate(\n    dateTime.calendar,\n    dateTime.era,\n    dateTime.year,\n    dateTime.month,\n    dateTime.day\n  );\n}\n\nexport function toDateFields(date: AnyCalendarDate): DateFields {\n  return {\n    era: date.era,\n    year: date.year,\n    month: date.month,\n    day: date.day\n  };\n}\n\nexport function toTimeFields(date: AnyTime): TimeFields {\n  return {\n    hour: date.hour,\n    minute: date.minute,\n    second: date.second,\n    millisecond: date.millisecond\n  };\n}\n\n/**\n * Converts a date value to a `CalendarDateTime`. An optional `Time` value can be passed to set the\n * time of the resulting value, otherwise it will default to midnight.\n */\nexport function toCalendarDateTime(\n  date: CalendarDate | CalendarDateTime | ZonedDateTime,\n  time?: AnyTime\n): CalendarDateTime {\n  let hour = 0,\n    minute = 0,\n    second = 0,\n    millisecond = 0;\n  if ('timeZone' in date) {\n    ({hour, minute, second, millisecond} = date);\n  } else if ('hour' in date && !time) {\n    return date;\n  }\n\n  if (time) {\n    ({hour, minute, second, millisecond} = time);\n  }\n\n  return new CalendarDateTime(\n    date.calendar,\n    date.era,\n    date.year,\n    date.month,\n    date.day,\n    hour,\n    minute,\n    second,\n    millisecond\n  );\n}\n\n/** Extracts the time components from a value containing a date and time. */\nexport function toTime(dateTime: CalendarDateTime | ZonedDateTime): Time {\n  return new Time(dateTime.hour, dateTime.minute, dateTime.second, dateTime.millisecond);\n}\n\n/** Converts a date from one calendar system to another. */\nexport function toCalendar<T extends AnyCalendarDate>(date: T, calendar: Calendar): T {\n  if (isEqualCalendar(date.calendar, calendar)) {\n    return date;\n  }\n\n  let calendarDate = calendar.fromJulianDay(date.calendar.toJulianDay(date));\n  let copy: Mutable<T> = date.copy();\n  copy.calendar = calendar;\n  copy.era = calendarDate.era;\n  copy.year = calendarDate.year;\n  copy.month = calendarDate.month;\n  copy.day = calendarDate.day;\n  constrain(copy);\n  return copy;\n}\n\n/**\n * Converts a date value to a `ZonedDateTime` in the provided time zone. The `disambiguation` option\n * can be set to control how values that fall on daylight saving time changes are interpreted.\n */\nexport function toZoned(\n  date: CalendarDate | CalendarDateTime | ZonedDateTime,\n  timeZone: string,\n  disambiguation?: Disambiguation\n): ZonedDateTime {\n  if (date instanceof ZonedDateTime) {\n    if (date.timeZone === timeZone) {\n      return date;\n    }\n\n    return toTimeZone(date, timeZone);\n  }\n\n  let ms = toAbsolute(date, timeZone, disambiguation);\n  return fromAbsolute(ms, timeZone);\n}\n\nexport function zonedToDate(date: ZonedDateTime): Date {\n  let ms = epochFromDate(date) - date.offset;\n  return new Date(ms);\n}\n\n/** Converts a `ZonedDateTime` from one time zone to another. */\nexport function toTimeZone(date: ZonedDateTime, timeZone: string): ZonedDateTime {\n  let ms = epochFromDate(date) - date.offset;\n  return toCalendar(fromAbsolute(ms, timeZone), date.calendar);\n}\n\n/** Converts the given `ZonedDateTime` into the user's local time zone. */\nexport function toLocalTimeZone(date: ZonedDateTime): ZonedDateTime {\n  return toTimeZone(date, getLocalTimeZone());\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {\n  AnyCalendarDate,\n  AnyDateTime,\n  AnyTime,\n  CycleOptions,\n  CycleTimeOptions,\n  DateDuration,\n  DateField,\n  DateFields,\n  DateTimeDuration,\n  Disambiguation,\n  TimeDuration,\n  TimeField,\n  TimeFields\n} from './types';\nimport {CalendarDate, CalendarDateTime, Time, ZonedDateTime} from './CalendarDate';\nimport {\n  epochFromDate,\n  fromAbsolute,\n  toAbsolute,\n  toCalendar,\n  toCalendarDateTime\n} from './conversion';\nimport {GregorianCalendar} from './calendars/GregorianCalendar';\nimport {Mutable} from './utils';\n\nconst ONE_HOUR = 3600000;\n\nexport function add(date: CalendarDateTime, duration: DateTimeDuration): CalendarDateTime;\nexport function add(date: CalendarDate, duration: DateDuration): CalendarDate;\nexport function add(\n  date: CalendarDate | CalendarDateTime,\n  duration: DateTimeDuration\n): CalendarDate | CalendarDateTime;\nexport function add(\n  date: CalendarDate | CalendarDateTime,\n  duration: DateTimeDuration\n): Mutable<AnyCalendarDate | AnyDateTime> {\n  let mutableDate: Mutable<AnyCalendarDate | AnyDateTime> = date.copy();\n  let days = 'hour' in mutableDate ? addTimeFields(mutableDate, duration) : 0;\n\n  addYears(mutableDate, duration.years || 0);\n  if (mutableDate.calendar.balanceYearMonth) {\n    mutableDate.calendar.balanceYearMonth(mutableDate, date);\n  }\n\n  mutableDate.month += duration.months || 0;\n\n  balanceYearMonth(mutableDate);\n  constrainMonthDay(mutableDate);\n\n  mutableDate.day += (duration.weeks || 0) * 7;\n  mutableDate.day += duration.days || 0;\n  mutableDate.day += days;\n\n  balanceDay(mutableDate);\n\n  if (mutableDate.calendar.balanceDate) {\n    mutableDate.calendar.balanceDate(mutableDate);\n  }\n\n  // Constrain in case adding ended up with a date outside the valid range for the calendar system.\n  // The behavior here is slightly different than when constraining in the `set` function in that\n  // we adjust smaller fields to their minimum/maximum values rather than constraining each field\n  // individually. This matches the general behavior of `add` vs `set` regarding how fields are balanced.\n  if (mutableDate.year < 1) {\n    mutableDate.year = 1;\n    mutableDate.month = 1;\n    mutableDate.day = 1;\n  }\n\n  let maxYear = mutableDate.calendar.getYearsInEra(mutableDate);\n  if (mutableDate.year > maxYear) {\n    let isInverseEra = mutableDate.calendar.isInverseEra?.(mutableDate);\n    mutableDate.year = maxYear;\n    mutableDate.month = isInverseEra ? 1 : mutableDate.calendar.getMonthsInYear(mutableDate);\n    mutableDate.day = isInverseEra ? 1 : mutableDate.calendar.getDaysInMonth(mutableDate);\n  }\n\n  if (mutableDate.month < 1) {\n    mutableDate.month = 1;\n    mutableDate.day = 1;\n  }\n\n  let maxMonth = mutableDate.calendar.getMonthsInYear(mutableDate);\n  if (mutableDate.month > maxMonth) {\n    mutableDate.month = maxMonth;\n    mutableDate.day = mutableDate.calendar.getDaysInMonth(mutableDate);\n  }\n\n  mutableDate.day = Math.max(\n    1,\n    Math.min(mutableDate.calendar.getDaysInMonth(mutableDate), mutableDate.day)\n  );\n  return mutableDate;\n}\n\nfunction addYears(date: Mutable<AnyCalendarDate>, years: number) {\n  if (date.calendar.isInverseEra?.(date)) {\n    years = -years;\n  }\n\n  date.year += years;\n}\n\nfunction balanceYearMonth(date: Mutable<AnyCalendarDate>) {\n  while (date.month < 1) {\n    addYears(date, -1);\n    date.month += date.calendar.getMonthsInYear(date);\n  }\n\n  let monthsInYear = 0;\n  while (date.month > (monthsInYear = date.calendar.getMonthsInYear(date))) {\n    date.month -= monthsInYear;\n    addYears(date, 1);\n  }\n}\n\nfunction balanceDay(date: Mutable<AnyCalendarDate>) {\n  while (date.day < 1) {\n    date.month--;\n    balanceYearMonth(date);\n    date.day += date.calendar.getDaysInMonth(date);\n  }\n\n  while (date.day > date.calendar.getDaysInMonth(date)) {\n    date.day -= date.calendar.getDaysInMonth(date);\n    date.month++;\n    balanceYearMonth(date);\n  }\n}\n\nfunction constrainMonthDay(date: Mutable<AnyCalendarDate>) {\n  date.month = Math.max(1, Math.min(date.calendar.getMonthsInYear(date), date.month));\n  date.day = Math.max(1, Math.min(date.calendar.getDaysInMonth(date), date.day));\n}\n\nexport function constrain(date: Mutable<AnyCalendarDate>): void {\n  if (date.calendar.constrainDate) {\n    date.calendar.constrainDate(date);\n  }\n\n  date.year = Math.max(1, Math.min(date.calendar.getYearsInEra(date), date.year));\n  constrainMonthDay(date);\n}\n\nexport function invertDuration(duration: DateTimeDuration): DateTimeDuration {\n  let inverseDuration = {};\n  for (let key in duration) {\n    if (typeof duration[key] === 'number') {\n      inverseDuration[key] = -duration[key];\n    }\n  }\n\n  return inverseDuration;\n}\n\nexport function subtract(date: CalendarDateTime, duration: DateTimeDuration): CalendarDateTime;\nexport function subtract(date: CalendarDate, duration: DateDuration): CalendarDate;\nexport function subtract(\n  date: CalendarDate | CalendarDateTime,\n  duration: DateTimeDuration\n): CalendarDate | CalendarDateTime {\n  return add(date, invertDuration(duration));\n}\n\nexport function set(date: CalendarDateTime, fields: DateFields): CalendarDateTime;\nexport function set(date: CalendarDate, fields: DateFields): CalendarDate;\nexport function set(\n  date: CalendarDate | CalendarDateTime,\n  fields: DateFields\n): Mutable<AnyCalendarDate> {\n  let mutableDate: Mutable<AnyCalendarDate> = date.copy();\n\n  if (fields.era != null) {\n    mutableDate.era = fields.era;\n  }\n\n  if (fields.year != null) {\n    mutableDate.year = fields.year;\n  }\n\n  if (fields.month != null) {\n    mutableDate.month = fields.month;\n  }\n\n  if (fields.day != null) {\n    mutableDate.day = fields.day;\n  }\n\n  constrain(mutableDate);\n  return mutableDate;\n}\n\nexport function setTime(value: CalendarDateTime, fields: TimeFields): CalendarDateTime;\nexport function setTime(value: Time, fields: TimeFields): Time;\nexport function setTime(\n  value: Time | CalendarDateTime,\n  fields: TimeFields\n): Mutable<Time | CalendarDateTime> {\n  let mutableValue: Mutable<Time | CalendarDateTime> = value.copy();\n\n  if (fields.hour != null) {\n    mutableValue.hour = fields.hour;\n  }\n\n  if (fields.minute != null) {\n    mutableValue.minute = fields.minute;\n  }\n\n  if (fields.second != null) {\n    mutableValue.second = fields.second;\n  }\n\n  if (fields.millisecond != null) {\n    mutableValue.millisecond = fields.millisecond;\n  }\n\n  constrainTime(mutableValue);\n  return mutableValue;\n}\n\nfunction balanceTime(time: Mutable<AnyTime>): number {\n  time.second += Math.floor(time.millisecond / 1000);\n  time.millisecond = nonNegativeMod(time.millisecond, 1000);\n\n  time.minute += Math.floor(time.second / 60);\n  time.second = nonNegativeMod(time.second, 60);\n\n  time.hour += Math.floor(time.minute / 60);\n  time.minute = nonNegativeMod(time.minute, 60);\n\n  let days = Math.floor(time.hour / 24);\n  time.hour = nonNegativeMod(time.hour, 24);\n\n  return days;\n}\n\nexport function constrainTime(time: Mutable<AnyTime>): void {\n  time.millisecond = Math.max(0, Math.min(time.millisecond, 1000));\n  time.second = Math.max(0, Math.min(time.second, 59));\n  time.minute = Math.max(0, Math.min(time.minute, 59));\n  time.hour = Math.max(0, Math.min(time.hour, 23));\n}\n\nfunction nonNegativeMod(a: number, b: number) {\n  let result = a % b;\n  if (result < 0) {\n    result += b;\n  }\n  return result;\n}\n\nfunction addTimeFields(time: Mutable<AnyTime>, duration: TimeDuration): number {\n  time.hour += duration.hours || 0;\n  time.minute += duration.minutes || 0;\n  time.second += duration.seconds || 0;\n  time.millisecond += duration.milliseconds || 0;\n  return balanceTime(time);\n}\n\nexport function addTime(time: Time, duration: TimeDuration): Time {\n  let res = time.copy();\n  addTimeFields(res, duration);\n  return res;\n}\n\nexport function subtractTime(time: Time, duration: TimeDuration): Time {\n  return addTime(time, invertDuration(duration));\n}\n\nexport function cycleDate(\n  value: CalendarDateTime,\n  field: DateField,\n  amount: number,\n  options?: CycleOptions\n): CalendarDateTime;\nexport function cycleDate(\n  value: CalendarDate,\n  field: DateField,\n  amount: number,\n  options?: CycleOptions\n): CalendarDate;\nexport function cycleDate(\n  value: CalendarDate | CalendarDateTime,\n  field: DateField,\n  amount: number,\n  options?: CycleOptions\n): Mutable<CalendarDate | CalendarDateTime> {\n  let mutable: Mutable<CalendarDate | CalendarDateTime> = value.copy();\n\n  switch (field) {\n    case 'era': {\n      let eras = value.calendar.getEras();\n      let eraIndex = eras.indexOf(value.era);\n      if (eraIndex < 0) {\n        throw new Error('Invalid era: ' + value.era);\n      }\n      eraIndex = cycleValue(eraIndex, amount, 0, eras.length - 1, options?.round);\n      mutable.era = eras[eraIndex];\n\n      // Constrain the year and other fields within the era, so the era doesn't change when we balance below.\n      constrain(mutable);\n      break;\n    }\n    case 'year': {\n      if (mutable.calendar.isInverseEra?.(mutable)) {\n        amount = -amount;\n      }\n\n      // The year field should not cycle within the era as that can cause weird behavior affecting other fields.\n      // We need to also allow values < 1 so that decrementing goes to the previous era. If we get -Infinity back\n      // we know we wrapped around after reaching 9999 (the maximum), so set the year back to 1.\n      mutable.year = cycleValue(value.year, amount, -Infinity, 9999, options?.round);\n      if (mutable.year === -Infinity) {\n        mutable.year = 1;\n      }\n\n      if (mutable.calendar.balanceYearMonth) {\n        mutable.calendar.balanceYearMonth(mutable, value);\n      }\n      break;\n    }\n    case 'month':\n      mutable.month = cycleValue(\n        value.month,\n        amount,\n        1,\n        value.calendar.getMonthsInYear(value),\n        options?.round\n      );\n      break;\n    case 'day':\n      mutable.day = cycleValue(\n        value.day,\n        amount,\n        1,\n        value.calendar.getDaysInMonth(value),\n        options?.round\n      );\n      break;\n    default:\n      throw new Error('Unsupported field ' + field);\n  }\n\n  if (value.calendar.balanceDate) {\n    value.calendar.balanceDate(mutable);\n  }\n\n  constrain(mutable);\n  return mutable;\n}\n\nexport function cycleTime(\n  value: CalendarDateTime,\n  field: TimeField,\n  amount: number,\n  options?: CycleTimeOptions\n): CalendarDateTime;\nexport function cycleTime(\n  value: Time,\n  field: TimeField,\n  amount: number,\n  options?: CycleTimeOptions\n): Time;\nexport function cycleTime(\n  value: Time | CalendarDateTime,\n  field: TimeField,\n  amount: number,\n  options?: CycleTimeOptions\n): Mutable<Time | CalendarDateTime> {\n  let mutable: Mutable<Time | CalendarDateTime> = value.copy();\n\n  switch (field) {\n    case 'hour': {\n      let hours = value.hour;\n      let min = 0;\n      let max = 23;\n      if (options?.hourCycle === 12) {\n        let isPM = hours >= 12;\n        min = isPM ? 12 : 0;\n        max = isPM ? 23 : 11;\n      }\n      mutable.hour = cycleValue(hours, amount, min, max, options?.round);\n      break;\n    }\n    case 'minute':\n      mutable.minute = cycleValue(value.minute, amount, 0, 59, options?.round);\n      break;\n    case 'second':\n      mutable.second = cycleValue(value.second, amount, 0, 59, options?.round);\n      break;\n    case 'millisecond':\n      mutable.millisecond = cycleValue(value.millisecond, amount, 0, 999, options?.round);\n      break;\n    default:\n      throw new Error('Unsupported field ' + field);\n  }\n\n  return mutable;\n}\n\nfunction cycleValue(value: number, amount: number, min: number, max: number, round = false) {\n  if (round) {\n    value += Math.sign(amount);\n\n    if (value < min) {\n      value = max;\n    }\n\n    let div = Math.abs(amount);\n    if (amount > 0) {\n      value = Math.ceil(value / div) * div;\n    } else {\n      value = Math.floor(value / div) * div;\n    }\n\n    if (value > max) {\n      value = min;\n    }\n  } else {\n    value += amount;\n    if (value < min) {\n      value = max - (min - value - 1);\n    } else if (value > max) {\n      value = min + (value - max - 1);\n    }\n  }\n\n  return value;\n}\n\nexport function addZoned(dateTime: ZonedDateTime, duration: DateTimeDuration): ZonedDateTime {\n  let ms: number;\n  if (\n    (duration.years != null && duration.years !== 0) ||\n    (duration.months != null && duration.months !== 0) ||\n    (duration.weeks != null && duration.weeks !== 0) ||\n    (duration.days != null && duration.days !== 0)\n  ) {\n    let res = add(toCalendarDateTime(dateTime), {\n      years: duration.years,\n      months: duration.months,\n      weeks: duration.weeks,\n      days: duration.days\n    });\n\n    // Changing the date may change the timezone offset, so we need to recompute\n    // using the 'compatible' disambiguation.\n    ms = toAbsolute(res, dateTime.timeZone);\n  } else {\n    // Otherwise, preserve the offset of the original date.\n    ms = epochFromDate(dateTime) - dateTime.offset;\n  }\n\n  // Perform time manipulation in milliseconds rather than on the original time fields to account for DST.\n  // For example, adding one hour during a DST transition may result in the hour field staying the same or\n  // skipping an hour. This results in the offset field changing value instead of the specified field.\n  ms += duration.milliseconds || 0;\n  ms += (duration.seconds || 0) * 1000;\n  ms += (duration.minutes || 0) * 60 * 1000;\n  ms += (duration.hours || 0) * 60 * 60 * 1000;\n\n  let res = fromAbsolute(ms, dateTime.timeZone);\n  return toCalendar(res, dateTime.calendar);\n}\n\nexport function subtractZoned(dateTime: ZonedDateTime, duration: DateTimeDuration): ZonedDateTime {\n  return addZoned(dateTime, invertDuration(duration));\n}\n\nexport function cycleZoned(\n  dateTime: ZonedDateTime,\n  field: DateField | TimeField,\n  amount: number,\n  options?: CycleTimeOptions\n): ZonedDateTime {\n  // For date fields, we want the time to remain consistent and the UTC offset to potentially change to account for DST changes.\n  // For time fields, we want the time to change by the amount given. This may result in the hour field staying the same, but the UTC\n  // offset changing in the case of a backward DST transition, or skipping an hour in the case of a forward DST transition.\n  switch (field) {\n    case 'hour': {\n      let min = 0;\n      let max = 23;\n      if (options?.hourCycle === 12) {\n        let isPM = dateTime.hour >= 12;\n        min = isPM ? 12 : 0;\n        max = isPM ? 23 : 11;\n      }\n\n      // The minimum and maximum hour may be affected by daylight saving time.\n      // For example, it might jump forward at midnight, and skip 1am.\n      // Or it might end at midnight and repeat the 11pm hour. To handle this, we get\n      // the possible absolute times for the min and max, and find the maximum range\n      // that is within the current day.\n      let plainDateTime = toCalendarDateTime(dateTime);\n      let minDate = toCalendar(setTime(plainDateTime, {hour: min}), new GregorianCalendar());\n      let minAbsolute = [\n        toAbsolute(minDate, dateTime.timeZone, 'earlier'),\n        toAbsolute(minDate, dateTime.timeZone, 'later')\n      ].filter(ms => fromAbsolute(ms, dateTime.timeZone).day === minDate.day)[0];\n\n      let maxDate = toCalendar(setTime(plainDateTime, {hour: max}), new GregorianCalendar());\n      let maxAbsolute = [\n        toAbsolute(maxDate, dateTime.timeZone, 'earlier'),\n        toAbsolute(maxDate, dateTime.timeZone, 'later')\n      ]\n        .filter(ms => fromAbsolute(ms, dateTime.timeZone).day === maxDate.day)\n        .pop()!;\n\n      // Since hours may repeat, we need to operate on the absolute time in milliseconds.\n      // This is done in hours from the Unix epoch so that cycleValue works correctly,\n      // and then converted back to milliseconds.\n      let ms = epochFromDate(dateTime) - dateTime.offset;\n      let hours = Math.floor(ms / ONE_HOUR);\n      let remainder = ms % ONE_HOUR;\n      ms =\n        cycleValue(\n          hours,\n          amount,\n          Math.floor(minAbsolute / ONE_HOUR),\n          Math.floor(maxAbsolute / ONE_HOUR),\n          options?.round\n        ) *\n          ONE_HOUR +\n        remainder;\n\n      // Now compute the new timezone offset, and convert the absolute time back to local time.\n      return toCalendar(fromAbsolute(ms, dateTime.timeZone), dateTime.calendar);\n    }\n    case 'minute':\n    case 'second':\n    case 'millisecond':\n      // @ts-ignore\n      return cycleTime(dateTime, field, amount, options);\n    case 'era':\n    case 'year':\n    case 'month':\n    case 'day': {\n      let res = cycleDate(toCalendarDateTime(dateTime), field, amount, options);\n      let ms = toAbsolute(res, dateTime.timeZone);\n      return toCalendar(fromAbsolute(ms, dateTime.timeZone), dateTime.calendar);\n    }\n    default:\n      throw new Error('Unsupported field ' + field);\n  }\n}\n\nexport function setZoned(\n  dateTime: ZonedDateTime,\n  fields: DateFields & TimeFields,\n  disambiguation?: Disambiguation\n): ZonedDateTime {\n  // Set the date/time fields, and recompute the UTC offset to account for DST changes.\n  // We also need to validate by converting back to a local time in case hours are skipped during forward DST transitions.\n  let plainDateTime = toCalendarDateTime(dateTime);\n  let res = setTime(set(plainDateTime, fields), fields);\n\n  // If the resulting plain date time values are equal, return the original time.\n  // We don't want to change the offset when setting the time to the same value.\n  if (res.compare(plainDateTime) === 0) {\n    return dateTime;\n  }\n\n  let ms = toAbsolute(res, dateTime.timeZone, disambiguation);\n  return toCalendar(fromAbsolute(ms, dateTime.timeZone), dateTime.calendar);\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {AnyDateTime, DateTimeDuration, Disambiguation} from './types';\nimport {CalendarDate, CalendarDateTime, Time, ZonedDateTime} from './CalendarDate';\nimport {\n  epochFromDate,\n  fromAbsolute,\n  possibleAbsolutes,\n  toAbsolute,\n  toCalendar,\n  toCalendarDateTime,\n  toTimeZone\n} from './conversion';\nimport {getLocalTimeZone} from './queries';\nimport {GregorianCalendar} from './calendars/GregorianCalendar';\nimport {Mutable} from './utils';\n\nconst TIME_RE = /^(\\d{2})(?::(\\d{2}))?(?::(\\d{2}))?(\\.\\d+)?$/;\nconst DATE_RE = /^([+-]\\d{6}|\\d{4})-(\\d{2})-(\\d{2})$/;\nconst DATE_TIME_RE =\n  /^([+-]\\d{6}|\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}))?(?::(\\d{2}))?(?::(\\d{2}))?(\\.\\d+)?$/;\nconst ZONED_DATE_TIME_RE =\n  /^([+-]\\d{6}|\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}))?(?::(\\d{2}))?(?::(\\d{2}))?(\\.\\d+)?(?:([+-]\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?\\[(.*?)\\]$/;\nconst ABSOLUTE_RE =\n  /^([+-]\\d{6}|\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}))?(?::(\\d{2}))?(?::(\\d{2}))?(\\.\\d+)?(?:(?:([+-]\\d{2})(?::?(\\d{2}))?)|Z)$/;\nconst DATE_TIME_DURATION_RE =\n  /^((?<negative>-)|\\+)?P((?<years>\\d*)Y)?((?<months>\\d*)M)?((?<weeks>\\d*)W)?((?<days>\\d*)D)?((?<time>T)((?<hours>\\d*[.,]?\\d{1,9})H)?((?<minutes>\\d*[.,]?\\d{1,9})M)?((?<seconds>\\d*[.,]?\\d{1,9})S)?)?$/;\nconst requiredDurationTimeGroups = ['hours', 'minutes', 'seconds'];\nconst requiredDurationGroups = ['years', 'months', 'weeks', 'days', ...requiredDurationTimeGroups];\n\n/** Parses an ISO 8601 time string. */\nexport function parseTime(value: string): Time {\n  let m = value.match(TIME_RE);\n  if (!m) {\n    throw new Error('Invalid ISO 8601 time string: ' + value);\n  }\n\n  return new Time(\n    parseNumber(m[1], 0, 23),\n    m[2] ? parseNumber(m[2], 0, 59) : 0,\n    m[3] ? parseNumber(m[3], 0, 59) : 0,\n    m[4] ? parseNumber(m[4], 0, Infinity) * 1000 : 0\n  );\n}\n\n/** Parses an ISO 8601 date string, with no time components. */\nexport function parseDate(value: string): CalendarDate {\n  let m = value.match(DATE_RE);\n  if (!m) {\n    if (ABSOLUTE_RE.test(value)) {\n      throw new Error(`Invalid ISO 8601 date string: ${value}. Use parseAbsolute() instead.`);\n    }\n    throw new Error('Invalid ISO 8601 date string: ' + value);\n  }\n\n  let date: Mutable<CalendarDate> = new CalendarDate(\n    parseNumber(m[1], 0, 9999),\n    parseNumber(m[2], 1, 12),\n    1\n  );\n\n  date.day = parseNumber(m[3], 1, date.calendar.getDaysInMonth(date));\n  return date as CalendarDate;\n}\n\n/** Parses an ISO 8601 date and time string, with no time zone. */\nexport function parseDateTime(value: string): CalendarDateTime {\n  let m = value.match(DATE_TIME_RE);\n  if (!m) {\n    if (ABSOLUTE_RE.test(value)) {\n      throw new Error(`Invalid ISO 8601 date time string: ${value}. Use parseAbsolute() instead.`);\n    }\n    throw new Error('Invalid ISO 8601 date time string: ' + value);\n  }\n\n  let year = parseNumber(m[1], -9999, 9999);\n  let era = year < 1 ? 'BC' : 'AD';\n\n  let date: Mutable<CalendarDateTime> = new CalendarDateTime(\n    era,\n    year < 1 ? -year + 1 : year,\n    parseNumber(m[2], 1, 12),\n    1,\n    m[4] ? parseNumber(m[4], 0, 23) : 0,\n    m[5] ? parseNumber(m[5], 0, 59) : 0,\n    m[6] ? parseNumber(m[6], 0, 59) : 0,\n    m[7] ? parseNumber(m[7], 0, Infinity) * 1000 : 0\n  );\n\n  date.day = parseNumber(m[3], 0, date.calendar.getDaysInMonth(date));\n  return date as CalendarDateTime;\n}\n\n/**\n * Parses an ISO 8601 date and time string with a time zone extension and optional UTC offset (e.g.\n * \"2021-11-07T00:45[America/Los_Angeles]\" or \"2021-11-07T00:45-07:00[America/Los_Angeles]\").\n * Ambiguous times due to daylight saving time transitions are resolved according to the\n * `disambiguation` parameter.\n */\nexport function parseZonedDateTime(value: string, disambiguation?: Disambiguation): ZonedDateTime {\n  let m = value.match(ZONED_DATE_TIME_RE);\n  if (!m) {\n    throw new Error('Invalid ISO 8601 date time string: ' + value);\n  }\n\n  let year = parseNumber(m[1], -9999, 9999);\n  let era = year < 1 ? 'BC' : 'AD';\n\n  let date: Mutable<ZonedDateTime> = new ZonedDateTime(\n    era,\n    year < 1 ? -year + 1 : year,\n    parseNumber(m[2], 1, 12),\n    1,\n    m[11],\n    0,\n    m[4] ? parseNumber(m[4], 0, 23) : 0,\n    m[5] ? parseNumber(m[5], 0, 59) : 0,\n    m[6] ? parseNumber(m[6], 0, 59) : 0,\n    m[7] ? parseNumber(m[7], 0, Infinity) * 1000 : 0\n  );\n\n  date.day = parseNumber(m[3], 0, date.calendar.getDaysInMonth(date));\n\n  let plainDateTime = toCalendarDateTime(date as ZonedDateTime);\n\n  let ms: number;\n  if (m[8]) {\n    let hourOffset = parseNumber(m[8], -23, 23);\n    date.offset =\n      Math.sign(hourOffset) *\n      (Math.abs(hourOffset) * 60 * 60 * 1000 +\n        parseNumber(m[9] ?? '0', 0, 59) * 60 * 1000 +\n        parseNumber(m[10] ?? '0', 0, 59) * 1000);\n    ms = epochFromDate(date as ZonedDateTime) - date.offset;\n\n    // Validate offset against parsed date.\n    let absolutes = possibleAbsolutes(plainDateTime, date.timeZone);\n    if (!absolutes.includes(ms)) {\n      throw new Error(\n        `Offset ${offsetToString(date.offset)} is invalid for ${dateTimeToString(date)} in ${date.timeZone}`\n      );\n    }\n  } else {\n    // Convert to absolute and back to fix invalid times due to DST.\n    ms = toAbsolute(toCalendarDateTime(plainDateTime), date.timeZone, disambiguation);\n  }\n\n  return fromAbsolute(ms, date.timeZone);\n}\n\n/**\n * Parses an ISO 8601 date and time string with a UTC offset (e.g. \"2021-11-07T07:45:00Z\"\n * or \"2021-11-07T07:45:00-07:00\"). The result is converted to the provided time zone.\n */\nexport function parseAbsolute(value: string, timeZone: string): ZonedDateTime {\n  let m = value.match(ABSOLUTE_RE);\n  if (!m) {\n    throw new Error('Invalid ISO 8601 date time string: ' + value);\n  }\n\n  let year = parseNumber(m[1], -9999, 9999);\n  let era = year < 1 ? 'BC' : 'AD';\n\n  let date: Mutable<ZonedDateTime> = new ZonedDateTime(\n    era,\n    year < 1 ? -year + 1 : year,\n    parseNumber(m[2], 1, 12),\n    1,\n    timeZone,\n    0,\n    m[4] ? parseNumber(m[4], 0, 23) : 0,\n    m[5] ? parseNumber(m[5], 0, 59) : 0,\n    m[6] ? parseNumber(m[6], 0, 59) : 0,\n    m[7] ? parseNumber(m[7], 0, Infinity) * 1000 : 0\n  );\n\n  date.day = parseNumber(m[3], 0, date.calendar.getDaysInMonth(date));\n\n  if (m[8]) {\n    date.offset =\n      parseNumber(m[8], -23, 23) * 60 * 60 * 1000 + parseNumber(m[9] ?? '0', 0, 59) * 60 * 1000;\n  }\n\n  return toTimeZone(date as ZonedDateTime, timeZone);\n}\n\n/**\n * Parses an ISO 8601 date and time string with a UTC offset (e.g. \"2021-11-07T07:45:00Z\"\n * or \"2021-11-07T07:45:00-07:00\"). The result is converted to the user's local time zone.\n */\nexport function parseAbsoluteToLocal(value: string): ZonedDateTime {\n  return parseAbsolute(value, getLocalTimeZone());\n}\n\nfunction parseNumber(value: string, min: number, max: number) {\n  let val = Number(value);\n  if (val < min || val > max) {\n    throw new RangeError(`Value out of range: ${min} <= ${val} <= ${max}`);\n  }\n\n  return val;\n}\n\nexport function timeToString(time: Time): string {\n  return `${String(time.hour).padStart(2, '0')}:${String(time.minute).padStart(2, '0')}:${String(time.second).padStart(2, '0')}${time.millisecond ? String(time.millisecond / 1000).slice(1) : ''}`;\n}\n\nexport function dateToString(date: CalendarDate): string {\n  let gregorianDate = toCalendar(date, new GregorianCalendar());\n  let year: string;\n  if (gregorianDate.era === 'BC') {\n    year =\n      gregorianDate.year === 1\n        ? '0000'\n        : '-' + String(Math.abs(1 - gregorianDate.year)).padStart(6, '00');\n  } else {\n    year = String(gregorianDate.year).padStart(4, '0');\n  }\n  return `${year}-${String(gregorianDate.month).padStart(2, '0')}-${String(gregorianDate.day).padStart(2, '0')}`;\n}\n\nexport function dateTimeToString(date: AnyDateTime): string {\n  // @ts-ignore\n  return `${dateToString(date)}T${timeToString(date)}`;\n}\n\nfunction offsetToString(offset: number) {\n  let sign = Math.sign(offset) < 0 ? '-' : '+';\n  offset = Math.abs(offset);\n  let offsetHours = Math.floor(offset / (60 * 60 * 1000));\n  let offsetMinutes = Math.floor((offset % (60 * 60 * 1000)) / (60 * 1000));\n  let offsetSeconds = Math.floor(((offset % (60 * 60 * 1000)) % (60 * 1000)) / 1000);\n  let stringOffset = `${sign}${String(offsetHours).padStart(2, '0')}:${String(offsetMinutes).padStart(2, '0')}`;\n  if (offsetSeconds !== 0) {\n    stringOffset += `:${String(offsetSeconds).padStart(2, '0')}`;\n  }\n\n  return stringOffset;\n}\n\nexport function zonedDateTimeToString(date: ZonedDateTime): string {\n  return `${dateTimeToString(date)}${offsetToString(date.offset)}[${date.timeZone}]`;\n}\n\n/**\n * Parses an ISO 8601 duration string (e.g. \"P3Y6M6W4DT12H30M5S\").\n *\n * @param value An ISO 8601 duration string.\n * @returns A DateTimeDuration object.\n */\nexport function parseDuration(value: string): Required<DateTimeDuration> {\n  const match = value.match(DATE_TIME_DURATION_RE);\n\n  if (!match) {\n    throw new Error(`Invalid ISO 8601 Duration string: ${value}`);\n  }\n\n  const parseDurationGroup = (group: string | undefined, isNegative: boolean): number => {\n    if (!group) {\n      return 0;\n    }\n    try {\n      const sign = isNegative ? -1 : 1;\n      return sign * Number(group.replace(',', '.'));\n    } catch {\n      throw new Error(`Invalid ISO 8601 Duration string: ${value}`);\n    }\n  };\n\n  const isNegative = !!match.groups?.negative;\n\n  const hasRequiredGroups = requiredDurationGroups.some(group => match.groups?.[group]);\n\n  if (!hasRequiredGroups) {\n    throw new Error(`Invalid ISO 8601 Duration string: ${value}`);\n  }\n\n  const durationStringIncludesTime = match.groups?.time;\n\n  if (durationStringIncludesTime) {\n    const hasRequiredDurationTimeGroups = requiredDurationTimeGroups.some(\n      group => match.groups?.[group]\n    );\n    if (!hasRequiredDurationTimeGroups) {\n      throw new Error(`Invalid ISO 8601 Duration string: ${value}`);\n    }\n  }\n\n  const duration: Mutable<DateTimeDuration> = {\n    years: parseDurationGroup(match.groups?.years, isNegative),\n    months: parseDurationGroup(match.groups?.months, isNegative),\n    weeks: parseDurationGroup(match.groups?.weeks, isNegative),\n    days: parseDurationGroup(match.groups?.days, isNegative),\n    hours: parseDurationGroup(match.groups?.hours, isNegative),\n    minutes: parseDurationGroup(match.groups?.minutes, isNegative),\n    seconds: parseDurationGroup(match.groups?.seconds, isNegative)\n  };\n\n  if (\n    duration.hours !== undefined &&\n    duration.hours % 1 !== 0 &&\n    (duration.minutes || duration.seconds)\n  ) {\n    throw new Error(\n      `Invalid ISO 8601 Duration string: ${value} - only the smallest unit can be fractional`\n    );\n  }\n\n  if (duration.minutes !== undefined && duration.minutes % 1 !== 0 && duration.seconds) {\n    throw new Error(\n      `Invalid ISO 8601 Duration string: ${value} - only the smallest unit can be fractional`\n    );\n  }\n\n  return duration as Required<DateTimeDuration>;\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {\n  add,\n  addTime,\n  addZoned,\n  constrain,\n  constrainTime,\n  cycleDate,\n  cycleTime,\n  cycleZoned,\n  set,\n  setTime,\n  setZoned,\n  subtract,\n  subtractTime,\n  subtractZoned\n} from './manipulation';\nimport {\n  AnyCalendarDate,\n  AnyTime,\n  Calendar,\n  CycleOptions,\n  CycleTimeOptions,\n  DateDuration,\n  DateField,\n  DateFields,\n  DateTimeDuration,\n  Disambiguation,\n  TimeDuration,\n  TimeField,\n  TimeFields\n} from './types';\nimport {compareDate, compareTime} from './queries';\nimport {dateTimeToString, dateToString, timeToString, zonedDateTimeToString} from './string';\nimport {GregorianCalendar} from './calendars/GregorianCalendar';\nimport {toCalendarDateTime, toDate, toZoned, zonedToDate} from './conversion';\n\nexport type DateValue = CalendarDate | CalendarDateTime | ZonedDateTime;\n\nfunction shiftArgs(args: any[]) {\n  let calendar: Calendar = typeof args[0] === 'object' ? args.shift() : new GregorianCalendar();\n\n  let era: string;\n  if (typeof args[0] === 'string') {\n    era = args.shift();\n  } else {\n    let eras = calendar.getEras();\n    era = eras[eras.length - 1];\n  }\n\n  let year = args.shift();\n  let month = args.shift();\n  let day = args.shift();\n\n  return [calendar, era, year, month, day];\n}\n\n/** A CalendarDate represents a date without any time components in a specific calendar system. */\nexport class CalendarDate {\n  // This prevents TypeScript from allowing other types with the same fields to match.\n  // i.e. a ZonedDateTime should not be be passable to a parameter that expects CalendarDate.\n  // If that behavior is desired, use the AnyCalendarDate interface instead.\n  // @ts-ignore\n  #type;\n  /** The calendar system associated with this date, e.g. Gregorian. */\n  public readonly calendar: Calendar;\n  /** The calendar era for this date, e.g. \"BC\" or \"AD\". */\n  public readonly era: string;\n  /** The year of this date within the era. */\n  public readonly year: number;\n  /**\n   * The month number within the year. Note that some calendar systems such as Hebrew\n   * may have a variable number of months per year. Therefore, month numbers may not\n   * always correspond to the same month names in different years.\n   */\n  public readonly month: number;\n  /** The day number within the month. */\n  public readonly day: number;\n\n  constructor(year: number, month: number, day: number);\n  constructor(era: string, year: number, month: number, day: number);\n  constructor(calendar: Calendar, year: number, month: number, day: number);\n  constructor(calendar: Calendar, era: string, year: number, month: number, day: number);\n  constructor(...args: any[]) {\n    let [calendar, era, year, month, day] = shiftArgs(args);\n    this.calendar = calendar;\n    this.era = era;\n    this.year = year;\n    this.month = month;\n    this.day = day;\n\n    constrain(this);\n  }\n\n  /** Returns a copy of this date. */\n  copy(): CalendarDate {\n    if (this.era) {\n      return new CalendarDate(this.calendar, this.era, this.year, this.month, this.day);\n    } else {\n      return new CalendarDate(this.calendar, this.year, this.month, this.day);\n    }\n  }\n\n  /** Returns a new `CalendarDate` with the given duration added to it. */\n  add(duration: DateDuration): CalendarDate {\n    return add(this, duration);\n  }\n\n  /** Returns a new `CalendarDate` with the given duration subtracted from it. */\n  subtract(duration: DateDuration): CalendarDate {\n    return subtract(this, duration);\n  }\n\n  /**\n   * Returns a new `CalendarDate` with the given fields set to the provided values. Other fields\n   * will be constrained accordingly.\n   */\n  set(fields: DateFields): CalendarDate {\n    return set(this, fields);\n  }\n\n  /**\n   * Returns a new `CalendarDate` with the given field adjusted by a specified amount.\n   * When the resulting value reaches the limits of the field, it wraps around.\n   */\n  cycle(field: DateField, amount: number, options?: CycleOptions): CalendarDate {\n    return cycleDate(this, field, amount, options);\n  }\n\n  /**\n   * Converts the date to a native JavaScript Date object, with the time set to midnight in the\n   * given time zone.\n   */\n  toDate(timeZone: string): Date {\n    return toDate(this, timeZone);\n  }\n\n  /** Converts the date to an ISO 8601 formatted string. */\n  toString(): string {\n    return dateToString(this);\n  }\n\n  /**\n   * Compares this date with another. A negative result indicates that this date is before the given\n   * one, and a positive date indicates that it is after.\n   */\n  compare(b: AnyCalendarDate): number {\n    return compareDate(this, b);\n  }\n}\n\n/** A Time represents a clock time without any date components. */\nexport class Time {\n  // This prevents TypeScript from allowing other types with the same fields to match.\n  // @ts-ignore\n  #type;\n  /** The hour, numbered from 0 to 23. */\n  public readonly hour: number;\n  /** The minute in the hour. */\n  public readonly minute: number;\n  /** The second in the minute. */\n  public readonly second: number;\n  /** The millisecond in the second. */\n  public readonly millisecond: number;\n\n  constructor(hour: number = 0, minute: number = 0, second: number = 0, millisecond: number = 0) {\n    this.hour = hour;\n    this.minute = minute;\n    this.second = second;\n    this.millisecond = millisecond;\n    constrainTime(this);\n  }\n\n  /** Returns a copy of this time. */\n  copy(): Time {\n    return new Time(this.hour, this.minute, this.second, this.millisecond);\n  }\n\n  /** Returns a new `Time` with the given duration added to it. */\n  add(duration: TimeDuration): Time {\n    return addTime(this, duration);\n  }\n\n  /** Returns a new `Time` with the given duration subtracted from it. */\n  subtract(duration: TimeDuration): Time {\n    return subtractTime(this, duration);\n  }\n\n  /**\n   * Returns a new `Time` with the given fields set to the provided values. Other fields will be\n   * constrained accordingly.\n   */\n  set(fields: TimeFields): Time {\n    return setTime(this, fields);\n  }\n\n  /**\n   * Returns a new `Time` with the given field adjusted by a specified amount.\n   * When the resulting value reaches the limits of the field, it wraps around.\n   */\n  cycle(field: TimeField, amount: number, options?: CycleTimeOptions): Time {\n    return cycleTime(this, field, amount, options);\n  }\n\n  /** Converts the time to an ISO 8601 formatted string. */\n  toString(): string {\n    return timeToString(this);\n  }\n\n  /**\n   * Compares this time with another. A negative result indicates that this time is before the given\n   * one, and a positive time indicates that it is after.\n   */\n  compare(b: AnyTime): number {\n    return compareTime(this, b);\n  }\n}\n\n/** A CalendarDateTime represents a date and time without a time zone, in a specific calendar system. */\nexport class CalendarDateTime {\n  // This prevents TypeScript from allowing other types with the same fields to match.\n  // @ts-ignore\n  #type;\n  /** The calendar system associated with this date, e.g. Gregorian. */\n  public readonly calendar: Calendar;\n  /** The calendar era for this date, e.g. \"BC\" or \"AD\". */\n  public readonly era: string;\n  /** The year of this date within the era. */\n  public readonly year: number;\n  /**\n   * The month number within the year. Note that some calendar systems such as Hebrew\n   * may have a variable number of months per year. Therefore, month numbers may not\n   * always correspond to the same month names in different years.\n   */\n  public readonly month: number;\n  /** The day number within the month. */\n  public readonly day: number;\n  /** The hour in the day, numbered from 0 to 23. */\n  public readonly hour: number;\n  /** The minute in the hour. */\n  public readonly minute: number;\n  /** The second in the minute. */\n  public readonly second: number;\n  /** The millisecond in the second. */\n  public readonly millisecond: number;\n\n  constructor(\n    year: number,\n    month: number,\n    day: number,\n    hour?: number,\n    minute?: number,\n    second?: number,\n    millisecond?: number\n  );\n  constructor(\n    era: string,\n    year: number,\n    month: number,\n    day: number,\n    hour?: number,\n    minute?: number,\n    second?: number,\n    millisecond?: number\n  );\n  constructor(\n    calendar: Calendar,\n    year: number,\n    month: number,\n    day: number,\n    hour?: number,\n    minute?: number,\n    second?: number,\n    millisecond?: number\n  );\n  constructor(\n    calendar: Calendar,\n    era: string,\n    year: number,\n    month: number,\n    day: number,\n    hour?: number,\n    minute?: number,\n    second?: number,\n    millisecond?: number\n  );\n  constructor(...args: any[]) {\n    let [calendar, era, year, month, day] = shiftArgs(args);\n    this.calendar = calendar;\n    this.era = era;\n    this.year = year;\n    this.month = month;\n    this.day = day;\n    this.hour = args.shift() || 0;\n    this.minute = args.shift() || 0;\n    this.second = args.shift() || 0;\n    this.millisecond = args.shift() || 0;\n\n    constrain(this);\n  }\n\n  /** Returns a copy of this date. */\n  copy(): CalendarDateTime {\n    if (this.era) {\n      return new CalendarDateTime(\n        this.calendar,\n        this.era,\n        this.year,\n        this.month,\n        this.day,\n        this.hour,\n        this.minute,\n        this.second,\n        this.millisecond\n      );\n    } else {\n      return new CalendarDateTime(\n        this.calendar,\n        this.year,\n        this.month,\n        this.day,\n        this.hour,\n        this.minute,\n        this.second,\n        this.millisecond\n      );\n    }\n  }\n\n  /** Returns a new `CalendarDateTime` with the given duration added to it. */\n  add(duration: DateTimeDuration): CalendarDateTime {\n    return add(this, duration);\n  }\n\n  /** Returns a new `CalendarDateTime` with the given duration subtracted from it. */\n  subtract(duration: DateTimeDuration): CalendarDateTime {\n    return subtract(this, duration);\n  }\n\n  /**\n   * Returns a new `CalendarDateTime` with the given fields set to the provided values. Other fields\n   * will be constrained accordingly.\n   */\n  set(fields: DateFields & TimeFields): CalendarDateTime {\n    return set(setTime(this, fields), fields);\n  }\n\n  /**\n   * Returns a new `CalendarDateTime` with the given field adjusted by a specified amount.\n   * When the resulting value reaches the limits of the field, it wraps around.\n   */\n  cycle(\n    field: DateField | TimeField,\n    amount: number,\n    options?: CycleTimeOptions\n  ): CalendarDateTime {\n    switch (field) {\n      case 'era':\n      case 'year':\n      case 'month':\n      case 'day':\n        return cycleDate(this, field, amount, options);\n      default:\n        return cycleTime(this, field, amount, options);\n    }\n  }\n\n  /** Converts the date to a native JavaScript Date object in the given time zone. */\n  toDate(timeZone: string, disambiguation?: Disambiguation): Date {\n    return toDate(this, timeZone, disambiguation);\n  }\n\n  /** Converts the date to an ISO 8601 formatted string. */\n  toString(): string {\n    return dateTimeToString(this);\n  }\n\n  /**\n   * Compares this date with another. A negative result indicates that this date is before the given\n   * one, and a positive date indicates that it is after.\n   */\n  compare(b: CalendarDate | CalendarDateTime | ZonedDateTime): number {\n    let res = compareDate(this, b);\n    if (res === 0) {\n      return compareTime(this, toCalendarDateTime(b));\n    }\n\n    return res;\n  }\n}\n\n/** A ZonedDateTime represents a date and time in a specific time zone and calendar system. */\nexport class ZonedDateTime {\n  // This prevents TypeScript from allowing other types with the same fields to match.\n  // @ts-ignore\n  #type;\n  /** The calendar system associated with this date, e.g. Gregorian. */\n  public readonly calendar: Calendar;\n  /** The calendar era for this date, e.g. \"BC\" or \"AD\". */\n  public readonly era: string;\n  /** The year of this date within the era. */\n  public readonly year: number;\n  /**\n   * The month number within the year. Note that some calendar systems such as Hebrew\n   * may have a variable number of months per year. Therefore, month numbers may not\n   * always correspond to the same month names in different years.\n   */\n  public readonly month: number;\n  /** The day number within the month. */\n  public readonly day: number;\n  /** The hour in the day, numbered from 0 to 23. */\n  public readonly hour: number;\n  /** The minute in the hour. */\n  public readonly minute: number;\n  /** The second in the minute. */\n  public readonly second: number;\n  /** The millisecond in the second. */\n  public readonly millisecond: number;\n  /** The IANA time zone identifier that this date and time is represented in. */\n  public readonly timeZone: string;\n  /** The UTC offset for this time, in milliseconds. */\n  public readonly offset: number;\n\n  constructor(\n    year: number,\n    month: number,\n    day: number,\n    timeZone: string,\n    offset: number,\n    hour?: number,\n    minute?: number,\n    second?: number,\n    millisecond?: number\n  );\n  constructor(\n    era: string,\n    year: number,\n    month: number,\n    day: number,\n    timeZone: string,\n    offset: number,\n    hour?: number,\n    minute?: number,\n    second?: number,\n    millisecond?: number\n  );\n  constructor(\n    calendar: Calendar,\n    year: number,\n    month: number,\n    day: number,\n    timeZone: string,\n    offset: number,\n    hour?: number,\n    minute?: number,\n    second?: number,\n    millisecond?: number\n  );\n  constructor(\n    calendar: Calendar,\n    era: string,\n    year: number,\n    month: number,\n    day: number,\n    timeZone: string,\n    offset: number,\n    hour?: number,\n    minute?: number,\n    second?: number,\n    millisecond?: number\n  );\n  constructor(...args: any[]) {\n    let [calendar, era, year, month, day] = shiftArgs(args);\n    let timeZone = args.shift();\n    let offset = args.shift();\n    this.calendar = calendar;\n    this.era = era;\n    this.year = year;\n    this.month = month;\n    this.day = day;\n    this.timeZone = timeZone;\n    this.offset = offset;\n    this.hour = args.shift() || 0;\n    this.minute = args.shift() || 0;\n    this.second = args.shift() || 0;\n    this.millisecond = args.shift() || 0;\n\n    constrain(this);\n  }\n\n  /** Returns a copy of this date. */\n  copy(): ZonedDateTime {\n    if (this.era) {\n      return new ZonedDateTime(\n        this.calendar,\n        this.era,\n        this.year,\n        this.month,\n        this.day,\n        this.timeZone,\n        this.offset,\n        this.hour,\n        this.minute,\n        this.second,\n        this.millisecond\n      );\n    } else {\n      return new ZonedDateTime(\n        this.calendar,\n        this.year,\n        this.month,\n        this.day,\n        this.timeZone,\n        this.offset,\n        this.hour,\n        this.minute,\n        this.second,\n        this.millisecond\n      );\n    }\n  }\n\n  /** Returns a new `ZonedDateTime` with the given duration added to it. */\n  add(duration: DateTimeDuration): ZonedDateTime {\n    return addZoned(this, duration);\n  }\n\n  /** Returns a new `ZonedDateTime` with the given duration subtracted from it. */\n  subtract(duration: DateTimeDuration): ZonedDateTime {\n    return subtractZoned(this, duration);\n  }\n\n  /**\n   * Returns a new `ZonedDateTime` with the given fields set to the provided values. Other fields\n   * will be constrained accordingly.\n   */\n  set(fields: DateFields & TimeFields, disambiguation?: Disambiguation): ZonedDateTime {\n    return setZoned(this, fields, disambiguation);\n  }\n\n  /**\n   * Returns a new `ZonedDateTime` with the given field adjusted by a specified amount.\n   * When the resulting value reaches the limits of the field, it wraps around.\n   */\n  cycle(field: DateField | TimeField, amount: number, options?: CycleTimeOptions): ZonedDateTime {\n    return cycleZoned(this, field, amount, options);\n  }\n\n  /** Converts the date to a native JavaScript Date object. */\n  toDate(): Date {\n    return zonedToDate(this);\n  }\n\n  /**\n   * Converts the date to an ISO 8601 formatted string, including the UTC offset and time zone\n   * identifier.\n   */\n  toString(): string {\n    return zonedDateTimeToString(this);\n  }\n\n  /** Converts the date to an ISO 8601 formatted string in UTC. */\n  toAbsoluteString(): string {\n    return this.toDate().toISOString();\n  }\n\n  /**\n   * Compares this date with another. A negative result indicates that this date is before the given\n   * one, and a positive date indicates that it is after.\n   */\n  compare(b: CalendarDate | CalendarDateTime | ZonedDateTime): number {\n    // TODO: Is this a bad idea??\n    return this.toDate().getTime() - toZoned(b, this.timeZone).toDate().getTime();\n  }\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from the TC39 Temporal proposal.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, CalendarIdentifier} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {GregorianCalendar} from './GregorianCalendar';\nimport {Mutable} from '../utils';\n\nconst ERA_START_DATES = [\n  [1868, 9, 8],\n  [1912, 7, 30],\n  [1926, 12, 25],\n  [1989, 1, 8],\n  [2019, 5, 1]\n];\nconst ERA_END_DATES = [\n  [1912, 7, 29],\n  [1926, 12, 24],\n  [1989, 1, 7],\n  [2019, 4, 30]\n];\nconst ERA_ADDENDS = [1867, 1911, 1925, 1988, 2018];\nconst ERA_NAMES = ['meiji', 'taisho', 'showa', 'heisei', 'reiwa'];\n\nfunction findEraFromGregorianDate(date: AnyCalendarDate) {\n  const idx = ERA_START_DATES.findIndex(([year, month, day]) => {\n    if (date.year < year) {\n      return true;\n    }\n\n    if (date.year === year && date.month < month) {\n      return true;\n    }\n\n    if (date.year === year && date.month === month && date.day < day) {\n      return true;\n    }\n\n    return false;\n  });\n\n  if (idx === -1) {\n    return ERA_START_DATES.length - 1;\n  }\n\n  if (idx === 0) {\n    return 0;\n  }\n\n  return idx - 1;\n}\n\nfunction toGregorian(date: AnyCalendarDate) {\n  let eraAddend = ERA_ADDENDS[ERA_NAMES.indexOf(date.era)];\n  if (!eraAddend) {\n    throw new Error('Unknown era: ' + date.era);\n  }\n\n  return new CalendarDate(date.year + eraAddend, date.month, date.day);\n}\n\n/**\n * The Japanese calendar is based on the Gregorian calendar, but with eras for the reign of each\n * Japanese emperor. Whenever a new emperor ascends to the throne, a new era begins and the year\n * starts again from 1. Note that eras before 1868 (Gregorian) are not currently supported by this\n * implementation.\n */\nexport class JapaneseCalendar extends GregorianCalendar {\n  identifier: CalendarIdentifier = 'japanese';\n\n  fromJulianDay(jd: number): CalendarDate {\n    let date = super.fromJulianDay(jd);\n    let era = findEraFromGregorianDate(date);\n\n    return new CalendarDate(\n      this,\n      ERA_NAMES[era],\n      date.year - ERA_ADDENDS[era],\n      date.month,\n      date.day\n    );\n  }\n\n  toJulianDay(date: AnyCalendarDate): number {\n    return super.toJulianDay(toGregorian(date));\n  }\n\n  balanceDate(date: Mutable<AnyCalendarDate>): void {\n    let gregorianDate = toGregorian(date);\n    let era = findEraFromGregorianDate(gregorianDate);\n\n    if (ERA_NAMES[era] !== date.era) {\n      date.era = ERA_NAMES[era];\n      date.year = gregorianDate.year - ERA_ADDENDS[era];\n    }\n\n    // Constrain in case we went before the first supported era.\n    this.constrainDate(date);\n  }\n\n  constrainDate(date: Mutable<AnyCalendarDate>): void {\n    let idx = ERA_NAMES.indexOf(date.era);\n    let end = ERA_END_DATES[idx];\n    if (end != null) {\n      let [endYear, endMonth, endDay] = end;\n\n      // Constrain the year to the maximum possible value in the era.\n      // Then constrain the month and day fields within that.\n      let maxYear = endYear - ERA_ADDENDS[idx];\n      date.year = Math.max(1, Math.min(maxYear, date.year));\n      if (date.year === maxYear) {\n        date.month = Math.min(endMonth, date.month);\n\n        if (date.month === endMonth) {\n          date.day = Math.min(endDay, date.day);\n        }\n      }\n    }\n\n    if (date.year === 1 && idx >= 0) {\n      let [, startMonth, startDay] = ERA_START_DATES[idx];\n      date.month = Math.max(startMonth, date.month);\n\n      if (date.month === startMonth) {\n        date.day = Math.max(startDay, date.day);\n      }\n    }\n  }\n\n  getEras(): string[] {\n    return ERA_NAMES;\n  }\n\n  getYearsInEra(date: AnyCalendarDate): number {\n    // Get the number of years in the era, taking into account the date's month and day fields.\n    let era = ERA_NAMES.indexOf(date.era);\n    let cur = ERA_START_DATES[era];\n    let next = ERA_START_DATES[era + 1];\n    if (next == null) {\n      // 9999 gregorian is the maximum year allowed.\n      return 9999 - cur[0] + 1;\n    }\n\n    let years = next[0] - cur[0];\n\n    if (date.month < next[1] || (date.month === next[1] && date.day < next[2])) {\n      years++;\n    }\n\n    return years;\n  }\n\n  getDaysInMonth(date: AnyCalendarDate): number {\n    return super.getDaysInMonth(toGregorian(date));\n  }\n\n  getMinimumMonthInYear(date: AnyCalendarDate): number {\n    let start = getMinimums(date);\n    return start ? start[1] : 1;\n  }\n\n  getMinimumDayInMonth(date: AnyCalendarDate): number {\n    let start = getMinimums(date);\n    return start && date.month === start[1] ? start[2] : 1;\n  }\n}\n\nfunction getMinimums(date: AnyCalendarDate) {\n  if (date.year === 1) {\n    let idx = ERA_NAMES.indexOf(date.era);\n    return ERA_START_DATES[idx];\n  }\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, CalendarIdentifier} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {fromExtendedYear, getExtendedYear, GregorianCalendar} from './GregorianCalendar';\n\nconst BUDDHIST_ERA_START = -543;\n\n/**\n * The Buddhist calendar is the same as the Gregorian calendar, but counts years\n * starting from the birth of Buddha in 543 BC (Gregorian). It supports only one\n * era, identified as 'BE'.\n */\nexport class BuddhistCalendar extends GregorianCalendar {\n  identifier: CalendarIdentifier = 'buddhist';\n\n  fromJulianDay(jd: number): CalendarDate {\n    let gregorianDate = super.fromJulianDay(jd);\n    let year = getExtendedYear(gregorianDate.era, gregorianDate.year);\n    return new CalendarDate(\n      this,\n      year - BUDDHIST_ERA_START,\n      gregorianDate.month,\n      gregorianDate.day\n    );\n  }\n\n  toJulianDay(date: AnyCalendarDate): number {\n    return super.toJulianDay(toGregorian(date));\n  }\n\n  getEras(): string[] {\n    return ['BE'];\n  }\n\n  getDaysInMonth(date: AnyCalendarDate): number {\n    return super.getDaysInMonth(toGregorian(date));\n  }\n\n  balanceDate(): void {}\n}\n\nfunction toGregorian(date: AnyCalendarDate) {\n  let [era, year] = fromExtendedYear(date.year + BUDDHIST_ERA_START);\n  return new CalendarDate(era, year, date.month, date.day);\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, CalendarIdentifier} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {fromExtendedYear, getExtendedYear, GregorianCalendar} from './GregorianCalendar';\nimport {Mutable} from '../utils';\n\nconst TAIWAN_ERA_START = 1911;\n\nfunction gregorianYear(date: AnyCalendarDate) {\n  return date.era === 'minguo' ? date.year + TAIWAN_ERA_START : 1 - date.year + TAIWAN_ERA_START;\n}\n\nfunction gregorianToTaiwan(year: number): [string, number] {\n  let y = year - TAIWAN_ERA_START;\n  if (y > 0) {\n    return ['minguo', y];\n  } else {\n    return ['before_minguo', 1 - y];\n  }\n}\n\n/**\n * The Taiwanese calendar is the same as the Gregorian calendar, but years\n * are numbered starting from 1912 (Gregorian). Two eras are supported:\n * 'before_minguo' and 'minguo'.\n */\nexport class TaiwanCalendar extends GregorianCalendar {\n  identifier: CalendarIdentifier = 'roc'; // Republic of China\n\n  fromJulianDay(jd: number): CalendarDate {\n    let date = super.fromJulianDay(jd);\n    let extendedYear = getExtendedYear(date.era, date.year);\n    let [era, year] = gregorianToTaiwan(extendedYear);\n    return new CalendarDate(this, era, year, date.month, date.day);\n  }\n\n  toJulianDay(date: AnyCalendarDate): number {\n    return super.toJulianDay(toGregorian(date));\n  }\n\n  getEras(): string[] {\n    return ['before_minguo', 'minguo'];\n  }\n\n  balanceDate(date: Mutable<AnyCalendarDate>): void {\n    let [era, year] = gregorianToTaiwan(gregorianYear(date));\n    date.era = era;\n    date.year = year;\n  }\n\n  isInverseEra(date: AnyCalendarDate): boolean {\n    return date.era === 'before_minguo';\n  }\n\n  getDaysInMonth(date: AnyCalendarDate): number {\n    return super.getDaysInMonth(toGregorian(date));\n  }\n\n  getYearsInEra(date: AnyCalendarDate): number {\n    return date.era === 'before_minguo' ? 9999 : 9999 - TAIWAN_ERA_START;\n  }\n}\n\nfunction toGregorian(date: AnyCalendarDate) {\n  let [era, year] = fromExtendedYear(gregorianYear(date));\n  return new CalendarDate(era, year, date.month, date.day);\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar, CalendarIdentifier} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {mod} from '../utils';\n\nconst PERSIAN_EPOCH = 1948320;\n\n// Number of days from the start of the year to the start of each month.\nconst MONTH_START = [\n  0, // Farvardin\n  31, // Ordibehesht\n  62, // Khordad\n  93, // Tir\n  124, // Mordad\n  155, // Shahrivar\n  186, // Mehr\n  216, // Aban\n  246, // Azar\n  276, // Dey\n  306, // Bahman\n  336 // Esfand\n];\n\n/**\n * The Persian calendar is the main calendar used in Iran and Afghanistan. It has 12 months\n * in each year, the first 6 of which have 31 days, and the next 5 have 30 days. The 12th month\n * has either 29 or 30 days depending on whether it is a leap year. The Persian year starts\n * around the March equinox.\n */\nexport class PersianCalendar implements Calendar {\n  identifier: CalendarIdentifier = 'persian';\n\n  fromJulianDay(jd: number): CalendarDate {\n    let daysSinceEpoch = jd - PERSIAN_EPOCH;\n    let year = 1 + Math.floor((33 * daysSinceEpoch + 3) / 12053);\n    let farvardin1 = 365 * (year - 1) + Math.floor((8 * year + 21) / 33);\n    let dayOfYear = daysSinceEpoch - farvardin1;\n    let month = dayOfYear < 216 ? Math.floor(dayOfYear / 31) : Math.floor((dayOfYear - 6) / 30);\n    let day = dayOfYear - MONTH_START[month] + 1;\n    return new CalendarDate(this, year, month + 1, day);\n  }\n\n  toJulianDay(date: AnyCalendarDate): number {\n    let jd = PERSIAN_EPOCH - 1 + 365 * (date.year - 1) + Math.floor((8 * date.year + 21) / 33);\n    jd += MONTH_START[date.month - 1];\n    jd += date.day;\n    return jd;\n  }\n\n  getMonthsInYear(): number {\n    return 12;\n  }\n\n  getDaysInMonth(date: AnyCalendarDate): number {\n    if (date.month <= 6) {\n      return 31;\n    }\n\n    if (date.month <= 11) {\n      return 30;\n    }\n\n    let isLeapYear = mod(25 * date.year + 11, 33) < 8;\n    return isLeapYear ? 30 : 29;\n  }\n\n  getMaximumMonthsInYear(): number {\n    return 12;\n  }\n\n  getMaximumDaysInMonth(): number {\n    return 31;\n  }\n\n  getEras(): string[] {\n    return ['AP'];\n  }\n\n  getYearsInEra(): number {\n    // 9378-10-10 persian is 9999-12-31 gregorian.\n    // Round down to 9377 to set the maximum full year.\n    return 9377;\n  }\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, CalendarIdentifier} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {\n  fromExtendedYear,\n  GregorianCalendar,\n  gregorianToJulianDay,\n  isLeapYear\n} from './GregorianCalendar';\n\n// Starts in 78 AD,\nconst INDIAN_ERA_START = 78;\n\n// The Indian year starts 80 days later than the Gregorian year.\nconst INDIAN_YEAR_START = 80;\n\n/**\n * The Indian National Calendar is similar to the Gregorian calendar, but with\n * years numbered since the Saka era in 78 AD (Gregorian). There are 12 months\n * in each year, with either 30 or 31 days. Only one era identifier is supported: 'saka'.\n */\nexport class IndianCalendar extends GregorianCalendar {\n  identifier: CalendarIdentifier = 'indian';\n\n  fromJulianDay(jd: number): CalendarDate {\n    // Gregorian date for Julian day\n    let date = super.fromJulianDay(jd);\n\n    // Year in Saka era\n    let indianYear = date.year - INDIAN_ERA_START;\n\n    // Day number in Gregorian year (starting from 0)\n    let yDay = jd - gregorianToJulianDay(date.era, date.year, 1, 1);\n\n    let leapMonth: number;\n    if (yDay < INDIAN_YEAR_START) {\n      //  Day is at the end of the preceding Saka year\n      indianYear--;\n\n      // Days in leapMonth this year, previous Gregorian year\n      leapMonth = isLeapYear(date.year - 1) ? 31 : 30;\n      yDay += leapMonth + 31 * 5 + 30 * 3 + 10;\n    } else {\n      // Days in leapMonth this year\n      leapMonth = isLeapYear(date.year) ? 31 : 30;\n      yDay -= INDIAN_YEAR_START;\n    }\n\n    let indianMonth: number;\n    let indianDay: number;\n    if (yDay < leapMonth) {\n      indianMonth = 1;\n      indianDay = yDay + 1;\n    } else {\n      let mDay = yDay - leapMonth;\n      if (mDay < 31 * 5) {\n        indianMonth = Math.floor(mDay / 31) + 2;\n        indianDay = (mDay % 31) + 1;\n      } else {\n        mDay -= 31 * 5;\n        indianMonth = Math.floor(mDay / 30) + 7;\n        indianDay = (mDay % 30) + 1;\n      }\n    }\n\n    return new CalendarDate(this, indianYear, indianMonth, indianDay);\n  }\n\n  toJulianDay(date: AnyCalendarDate): number {\n    let extendedYear = date.year + INDIAN_ERA_START;\n    let [era, year] = fromExtendedYear(extendedYear);\n\n    let leapMonth: number;\n    let jd: number;\n    if (isLeapYear(year)) {\n      leapMonth = 31;\n      jd = gregorianToJulianDay(era, year, 3, 21);\n    } else {\n      leapMonth = 30;\n      jd = gregorianToJulianDay(era, year, 3, 22);\n    }\n\n    if (date.month === 1) {\n      return jd + date.day - 1;\n    }\n\n    jd += leapMonth + Math.min(date.month - 2, 5) * 31;\n\n    if (date.month >= 8) {\n      jd += (date.month - 7) * 30;\n    }\n\n    jd += date.day - 1;\n    return jd;\n  }\n\n  getDaysInMonth(date: AnyCalendarDate): number {\n    if (date.month === 1 && isLeapYear(date.year + INDIAN_ERA_START)) {\n      return 31;\n    }\n\n    if (date.month >= 2 && date.month <= 6) {\n      return 31;\n    }\n\n    return 30;\n  }\n\n  getYearsInEra(): number {\n    // 9999-12-31 gregorian is 9920-10-10 indian.\n    // Round down to 9919 for the last full year.\n    return 9919;\n  }\n\n  getEras(): string[] {\n    return ['saka'];\n  }\n\n  balanceDate(): void {}\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar, CalendarIdentifier} from '../types';\nimport {CalendarDate} from '../CalendarDate';\n\nconst CIVIL_EPOC = 1948440; // CE 622 July 16 Friday (Julian calendar) / CE 622 July 19 (Gregorian calendar)\nconst ASTRONOMICAL_EPOC = 1948439; // CE 622 July 15 Thursday (Julian calendar)\nconst UMALQURA_YEAR_START = 1300;\nconst UMALQURA_YEAR_END = 1600;\nconst UMALQURA_START_DAYS = 460322;\n\nfunction islamicToJulianDay(epoch: number, year: number, month: number, day: number): number {\n  return (\n    day +\n    Math.ceil(29.5 * (month - 1)) +\n    (year - 1) * 354 +\n    Math.floor((3 + 11 * year) / 30) +\n    epoch -\n    1\n  );\n}\n\nfunction julianDayToIslamic(calendar: Calendar, epoch: number, jd: number) {\n  let year = Math.floor((30 * (jd - epoch) + 10646) / 10631);\n  let month = Math.min(\n    12,\n    Math.ceil((jd - (29 + islamicToJulianDay(epoch, year, 1, 1))) / 29.5) + 1\n  );\n  let day = jd - islamicToJulianDay(epoch, year, month, 1) + 1;\n\n  return new CalendarDate(calendar, year, month, day);\n}\n\nfunction isLeapYear(year: number): boolean {\n  return (14 + 11 * year) % 30 < 11;\n}\n\n/**\n * The Islamic calendar, also known as the \"Hijri\" calendar, is used throughout much of the Arab\n * world. The civil variant uses simple arithmetic rules rather than astronomical calculations to\n * approximate the traditional calendar, which is based on sighting of the crescent moon. It uses\n * Friday, July 16 622 CE (Julian) as the epoch. Each year has 12 months, with either 354 or 355\n * days depending on whether it is a leap year. Learn more about the available Islamic calendars\n * [here](https://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types).\n */\nexport class IslamicCivilCalendar implements Calendar {\n  identifier: CalendarIdentifier = 'islamic-civil';\n\n  fromJulianDay(jd: number): CalendarDate {\n    return julianDayToIslamic(this, CIVIL_EPOC, jd);\n  }\n\n  toJulianDay(date: AnyCalendarDate): number {\n    return islamicToJulianDay(CIVIL_EPOC, date.year, date.month, date.day);\n  }\n\n  getDaysInMonth(date: AnyCalendarDate): number {\n    let length = 29 + (date.month % 2);\n    if (date.month === 12 && isLeapYear(date.year)) {\n      length++;\n    }\n\n    return length;\n  }\n\n  getMonthsInYear(): number {\n    return 12;\n  }\n\n  getDaysInYear(date: AnyCalendarDate): number {\n    return isLeapYear(date.year) ? 355 : 354;\n  }\n\n  getMaximumMonthsInYear(): number {\n    return 12;\n  }\n\n  getMaximumDaysInMonth(): number {\n    return 30;\n  }\n\n  getYearsInEra(): number {\n    // 9999 gregorian\n    return 9665;\n  }\n\n  getEras(): string[] {\n    return ['AH'];\n  }\n}\n\n/**\n * The Islamic calendar, also known as the \"Hijri\" calendar, is used throughout much of the Arab\n * world. The tabular variant uses simple arithmetic rules rather than astronomical calculations to\n * approximate the traditional calendar, which is based on sighting of the crescent moon. It uses\n * Thursday, July 15 622 CE (Julian) as the epoch. Each year has 12 months, with either 354 or 355\n * days depending on whether it is a leap year. Learn more about the available Islamic calendars\n * [here](https://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types).\n */\nexport class IslamicTabularCalendar extends IslamicCivilCalendar {\n  identifier: CalendarIdentifier = 'islamic-tbla';\n\n  fromJulianDay(jd: number): CalendarDate {\n    return julianDayToIslamic(this, ASTRONOMICAL_EPOC, jd);\n  }\n\n  toJulianDay(date: AnyCalendarDate): number {\n    return islamicToJulianDay(ASTRONOMICAL_EPOC, date.year, date.month, date.day);\n  }\n}\n\n// Generated by scripts/generate-umalqura.js\nconst UMALQURA_DATA =\n  'qgpUDckO1AbqBmwDrQpVBakGkgepC9QF2gpcBS0NlQZKB1QLagutBa4ETwoXBYsGpQbVCtYCWwmdBE0KJg2VDawFtgm6AlsKKwWVCsoG6Qr0AnYJtgJWCcoKpAvSC9kF3AJtCU0FpQpSC6ULtAW2CVcFlwJLBaMGUgdlC2oFqworBZUMSg2lDcoF1gpXCasESwmlClILagt1BXYCtwhbBFUFqQW0BdoJ3QRuAjYJqgpUDbIN1QXaAlsJqwRVCkkLZAtxC7QFtQpVCiUNkg7JDtQG6QprCasEkwpJDaQNsg25CroEWworBZUKKgtVC1wFvQQ9Ah0JlQpKC1oLbQW2AjsJmwRVBqkGVAdqC2wFrQpVBSkLkgupC9QF2gpaBasKlQVJB2QHqgu1BbYCVgpNDiULUgtqC60FrgIvCZcESwalBqwG1gpdBZ0ETQoWDZUNqgW1BdoCWwmtBJUFygbkBuoK9QS2AlYJqgpUC9IL2QXqAm0JrQSVCkoLpQuyBbUJ1gSXCkcFkwZJB1ULagVrCisFiwpGDaMNygXWCtsEawJLCaUKUgtpC3UFdgG3CFsCKwVlBbQF2gntBG0BtgimClINqQ3UBdoKWwmrBFMGKQdiB6kLsgW1ClUFJQuSDckO0gbpCmsFqwRVCikNVA2qDbUJugQ7CpsETQqqCtUK2gJdCV4ELgqaDFUNsga5BroEXQotBZUKUguoC7QLuQXaAloJSgukDdEO6AZqC20FNQWVBkoNqA3UDdoGWwWdAisGFQtKC5ULqgWuCi4JjwwnBZUGqgbWCl0FnQI=';\nlet UMALQURA_MONTHLENGTH: Uint16Array;\nlet UMALQURA_YEAR_START_TABLE: Uint32Array;\n\nfunction umalquraYearStart(year: number): number {\n  return UMALQURA_START_DAYS + UMALQURA_YEAR_START_TABLE[year - UMALQURA_YEAR_START];\n}\n\nfunction umalquraMonthLength(year: number, month: number): number {\n  let idx = year - UMALQURA_YEAR_START;\n  let mask = 0x01 << (11 - (month - 1));\n  if ((UMALQURA_MONTHLENGTH[idx] & mask) === 0) {\n    return 29;\n  } else {\n    return 30;\n  }\n}\n\nfunction umalquraMonthStart(year: number, month: number): number {\n  let day = umalquraYearStart(year);\n  for (let i = 1; i < month; i++) {\n    day += umalquraMonthLength(year, i);\n  }\n  return day;\n}\n\nfunction umalquraYearLength(year: number): number {\n  return (\n    UMALQURA_YEAR_START_TABLE[year + 1 - UMALQURA_YEAR_START] -\n    UMALQURA_YEAR_START_TABLE[year - UMALQURA_YEAR_START]\n  );\n}\n\n/**\n * The Islamic calendar, also known as the \"Hijri\" calendar, is used throughout much of the Arab\n * world. The Umalqura variant is primarily used in Saudi Arabia. It is a lunar calendar, based on\n * astronomical calculations that predict the sighting of a crescent moon. Month and year lengths\n * vary between years depending on these calculations. Learn more about the available Islamic\n * calendars\n * [here](https://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types).\n */\nexport class IslamicUmalquraCalendar extends IslamicCivilCalendar {\n  identifier: CalendarIdentifier = 'islamic-umalqura';\n\n  constructor() {\n    super();\n    if (!UMALQURA_MONTHLENGTH) {\n      UMALQURA_MONTHLENGTH = new Uint16Array(\n        Uint8Array.from(atob(UMALQURA_DATA), c => c.charCodeAt(0)).buffer\n      );\n    }\n\n    if (!UMALQURA_YEAR_START_TABLE) {\n      UMALQURA_YEAR_START_TABLE = new Uint32Array(UMALQURA_YEAR_END - UMALQURA_YEAR_START + 1);\n\n      let yearStart = 0;\n      for (let year = UMALQURA_YEAR_START; year <= UMALQURA_YEAR_END; year++) {\n        UMALQURA_YEAR_START_TABLE[year - UMALQURA_YEAR_START] = yearStart;\n        for (let i = 1; i <= 12; i++) {\n          yearStart += umalquraMonthLength(year, i);\n        }\n      }\n    }\n  }\n\n  fromJulianDay(jd: number): CalendarDate {\n    let days = jd - CIVIL_EPOC;\n    let startDays = umalquraYearStart(UMALQURA_YEAR_START);\n    let endDays = umalquraYearStart(UMALQURA_YEAR_END);\n    if (days < startDays || days > endDays) {\n      return super.fromJulianDay(jd);\n    } else {\n      let y = UMALQURA_YEAR_START - 1;\n      let m = 1;\n      let d = 1;\n      while (d > 0) {\n        y++;\n        d = days - umalquraYearStart(y) + 1;\n        let yearLength = umalquraYearLength(y);\n        if (d === yearLength) {\n          m = 12;\n          break;\n        } else if (d < yearLength) {\n          let monthLength = umalquraMonthLength(y, m);\n          m = 1;\n          while (d > monthLength) {\n            d -= monthLength;\n            m++;\n            monthLength = umalquraMonthLength(y, m);\n          }\n          break;\n        }\n      }\n\n      return new CalendarDate(this, y, m, days - umalquraMonthStart(y, m) + 1);\n    }\n  }\n\n  toJulianDay(date: AnyCalendarDate): number {\n    if (date.year < UMALQURA_YEAR_START || date.year > UMALQURA_YEAR_END) {\n      return super.toJulianDay(date);\n    }\n\n    return CIVIL_EPOC + umalquraMonthStart(date.year, date.month) + (date.day - 1);\n  }\n\n  getDaysInMonth(date: AnyCalendarDate): number {\n    if (date.year < UMALQURA_YEAR_START || date.year > UMALQURA_YEAR_END) {\n      return super.getDaysInMonth(date);\n    }\n\n    return umalquraMonthLength(date.year, date.month);\n  }\n\n  getDaysInYear(date: AnyCalendarDate): number {\n    if (date.year < UMALQURA_YEAR_START || date.year > UMALQURA_YEAR_END) {\n      return super.getDaysInYear(date);\n    }\n\n    return umalquraYearLength(date.year);\n  }\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar, CalendarIdentifier} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {mod, Mutable} from '../utils';\n\nconst HEBREW_EPOCH = 347997;\n\n// Hebrew date calculations are performed in terms of days, hours, and\n// \"parts\" (or halakim), which are 1/1080 of an hour, or 3 1/3 seconds.\nconst HOUR_PARTS = 1080;\nconst DAY_PARTS = 24 * HOUR_PARTS;\n\n// An approximate value for the length of a lunar month.\n// It is used to calculate the approximate year and month of a given\n// absolute date.\nconst MONTH_DAYS = 29;\nconst MONTH_FRACT = 12 * HOUR_PARTS + 793;\nconst MONTH_PARTS = MONTH_DAYS * DAY_PARTS + MONTH_FRACT;\n\nfunction isLeapYear(year: number) {\n  return mod(year * 7 + 1, 19) < 7;\n}\n\n// Test for delay of start of new year and to avoid\n// Sunday, Wednesday, and Friday as start of the new year.\nfunction hebrewDelay1(year: number) {\n  let months = Math.floor((235 * year - 234) / 19);\n  let parts = 12084 + 13753 * months;\n  let day = months * 29 + Math.floor(parts / 25920);\n\n  if (mod(3 * (day + 1), 7) < 3) {\n    day += 1;\n  }\n\n  return day;\n}\n\n// Check for delay in start of new year due to length of adjacent years\nfunction hebrewDelay2(year: number) {\n  let last = hebrewDelay1(year - 1);\n  let present = hebrewDelay1(year);\n  let next = hebrewDelay1(year + 1);\n\n  if (next - present === 356) {\n    return 2;\n  }\n\n  if (present - last === 382) {\n    return 1;\n  }\n\n  return 0;\n}\n\nfunction startOfYear(year: number) {\n  return hebrewDelay1(year) + hebrewDelay2(year);\n}\n\nfunction getDaysInYear(year: number) {\n  return startOfYear(year + 1) - startOfYear(year);\n}\n\nfunction getYearType(year: number) {\n  let yearLength = getDaysInYear(year);\n\n  if (yearLength > 380) {\n    yearLength -= 30; // Subtract length of leap month.\n  }\n\n  switch (yearLength) {\n    case 353:\n      return 0; // deficient\n    case 354:\n      return 1; // normal\n    case 355:\n      return 2; // complete\n  }\n}\n\nfunction getDaysInMonth(year: number, month: number): number {\n  // Normalize month numbers from 1 - 13, even on non-leap years\n  if (month >= 6 && !isLeapYear(year)) {\n    month++;\n  }\n\n  // First of all, dispose of fixed-length 29 day months\n  if (month === 4 || month === 7 || month === 9 || month === 11 || month === 13) {\n    return 29;\n  }\n\n  let yearType = getYearType(year);\n\n  // If it's Heshvan, days depend on length of year\n  if (month === 2) {\n    return yearType === 2 ? 30 : 29;\n  }\n\n  // Similarly, Kislev varies with the length of year\n  if (month === 3) {\n    return yearType === 0 ? 29 : 30;\n  }\n\n  // Adar I only exists in leap years\n  if (month === 6) {\n    return isLeapYear(year) ? 30 : 0;\n  }\n\n  return 30;\n}\n\n/**\n * The Hebrew calendar is used in Israel and around the world by the Jewish faith.\n * Years include either 12 or 13 months depending on whether it is a leap year.\n * In leap years, an extra month is inserted at month 6.\n */\nexport class HebrewCalendar implements Calendar {\n  identifier: CalendarIdentifier = 'hebrew';\n\n  fromJulianDay(jd: number): CalendarDate {\n    let d = jd - HEBREW_EPOCH;\n    let m = (d * DAY_PARTS) / MONTH_PARTS; // Months (approx)\n    let year = Math.floor((19 * m + 234) / 235) + 1; // Years (approx)\n    let ys = startOfYear(year); // 1st day of year\n    let dayOfYear = Math.floor(d - ys);\n\n    // Because of the postponement rules, it's possible to guess wrong.  Fix it.\n    while (dayOfYear < 1) {\n      year--;\n      ys = startOfYear(year);\n      dayOfYear = Math.floor(d - ys);\n    }\n\n    // Now figure out which month we're in, and the date within that month\n    let month = 1;\n    let monthStart = 0;\n    while (monthStart < dayOfYear) {\n      monthStart += getDaysInMonth(year, month);\n      month++;\n    }\n\n    month--;\n    monthStart -= getDaysInMonth(year, month);\n\n    let day = dayOfYear - monthStart;\n    return new CalendarDate(this, year, month, day);\n  }\n\n  toJulianDay(date: AnyCalendarDate): number {\n    let jd = startOfYear(date.year);\n    for (let month = 1; month < date.month; month++) {\n      jd += getDaysInMonth(date.year, month);\n    }\n\n    return jd + date.day + HEBREW_EPOCH;\n  }\n\n  getDaysInMonth(date: AnyCalendarDate): number {\n    return getDaysInMonth(date.year, date.month);\n  }\n\n  getMonthsInYear(date: AnyCalendarDate): number {\n    return isLeapYear(date.year) ? 13 : 12;\n  }\n\n  getDaysInYear(date: AnyCalendarDate): number {\n    return getDaysInYear(date.year);\n  }\n\n  getMaximumMonthsInYear(): number {\n    return 13;\n  }\n\n  getMaximumDaysInMonth(): number {\n    return 30;\n  }\n\n  getYearsInEra(): number {\n    // 6239 gregorian\n    return 9999;\n  }\n\n  getEras(): string[] {\n    return ['AM'];\n  }\n\n  balanceYearMonth(date: Mutable<AnyCalendarDate>, previousDate: AnyCalendarDate): void {\n    // Keep date in the same month when switching between leap years and non leap years\n    if (previousDate.year !== date.year) {\n      if (isLeapYear(previousDate.year) && !isLeapYear(date.year) && previousDate.month > 6) {\n        date.month--;\n      } else if (\n        !isLeapYear(previousDate.year) &&\n        isLeapYear(date.year) &&\n        previousDate.month > 6\n      ) {\n        date.month++;\n      }\n    }\n  }\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Portions of the code in this file are based on code from ICU.\n// Original licensing can be found in the NOTICE file in the root directory of this source tree.\n\nimport {AnyCalendarDate, Calendar, CalendarIdentifier} from '../types';\nimport {CalendarDate} from '../CalendarDate';\nimport {Mutable} from '../utils';\n\nconst ETHIOPIC_EPOCH = 1723856;\nconst COPTIC_EPOCH = 1824665;\n\n// The delta between Amete Alem 1 and Amete Mihret 1\n// AA 5501 = AM 1\nconst AMETE_MIHRET_DELTA = 5500;\n\nfunction ceToJulianDay(epoch: number, year: number, month: number, day: number): number {\n  return (\n    epoch + // difference from Julian epoch to 1,1,1\n    365 * year + // number of days from years\n    Math.floor(year / 4) + // extra day of leap year\n    30 * (month - 1) + // number of days from months (1 based)\n    day -\n    1 // number of days for present month (1 based)\n  );\n}\n\nfunction julianDayToCE(epoch: number, jd: number) {\n  let year = Math.floor((4 * (jd - epoch)) / 1461);\n  let month = 1 + Math.floor((jd - ceToJulianDay(epoch, year, 1, 1)) / 30);\n  let day = jd + 1 - ceToJulianDay(epoch, year, month, 1);\n  return [year, month, day];\n}\n\nfunction getLeapDay(year: number) {\n  return Math.floor((year % 4) / 3);\n}\n\nfunction getDaysInMonth(year: number, month: number) {\n  // The Ethiopian and Coptic calendars have 13 months, 12 of 30 days each and\n  // an intercalary month at the end of the year of 5 or 6 days, depending whether\n  // the year is a leap year or not. The Leap Year follows the same rules as the\n  // Julian Calendar so that the extra month always has six days in the year before\n  // a Julian Leap Year.\n  if (month % 13 !== 0) {\n    // not intercalary month\n    return 30;\n  } else {\n    // intercalary month 5 days + possible leap day\n    return getLeapDay(year) + 5;\n  }\n}\n\n/**\n * The Ethiopic calendar system is the official calendar used in Ethiopia.\n * It includes 12 months of 30 days each, plus 5 or 6 intercalary days depending\n * on whether it is a leap year. Two eras are supported: 'AA' and 'AM'.\n */\nexport class EthiopicCalendar implements Calendar {\n  identifier: CalendarIdentifier = 'ethiopic';\n\n  fromJulianDay(jd: number): CalendarDate {\n    let [year, month, day] = julianDayToCE(ETHIOPIC_EPOCH, jd);\n    let era = 'AM';\n    if (year <= 0) {\n      era = 'AA';\n      year += AMETE_MIHRET_DELTA;\n    }\n\n    return new CalendarDate(this, era, year, month, day);\n  }\n\n  toJulianDay(date: AnyCalendarDate): number {\n    let year = date.year;\n    if (date.era === 'AA') {\n      year -= AMETE_MIHRET_DELTA;\n    }\n\n    return ceToJulianDay(ETHIOPIC_EPOCH, year, date.month, date.day);\n  }\n\n  getDaysInMonth(date: AnyCalendarDate): number {\n    return getDaysInMonth(date.year, date.month);\n  }\n\n  getMonthsInYear(): number {\n    return 13;\n  }\n\n  getDaysInYear(date: AnyCalendarDate): number {\n    return 365 + getLeapDay(date.year);\n  }\n\n  getMaximumMonthsInYear(): number {\n    return 13;\n  }\n\n  getMaximumDaysInMonth(): number {\n    return 30;\n  }\n\n  getYearsInEra(date: AnyCalendarDate): number {\n    // 9999-12-31 gregorian is 9992-20-02 ethiopic.\n    // Round down to 9991 for the last full year.\n    // AA 9999-01-01 ethiopic is 4506-09-30 gregorian.\n    return date.era === 'AA' ? 9999 : 9991;\n  }\n\n  getEras(): string[] {\n    return ['AA', 'AM'];\n  }\n}\n\n/**\n * The Ethiopic (Amete Alem) calendar is the same as the modern Ethiopic calendar,\n * except years were measured from a different epoch. Only one era is supported: 'AA'.\n */\nexport class EthiopicAmeteAlemCalendar extends EthiopicCalendar {\n  identifier: CalendarIdentifier = 'ethioaa'; // also known as 'ethiopic-amete-alem' in ICU\n\n  fromJulianDay(jd: number): CalendarDate {\n    let [year, month, day] = julianDayToCE(ETHIOPIC_EPOCH, jd);\n    year += AMETE_MIHRET_DELTA;\n    return new CalendarDate(this, 'AA', year, month, day);\n  }\n\n  getEras(): string[] {\n    return ['AA'];\n  }\n\n  getYearsInEra(): number {\n    // 9999-13-04 ethioaa is the maximum date, which is equivalent to 4506-09-29 gregorian.\n    return 9999;\n  }\n}\n\n/**\n * The Coptic calendar is similar to the Ethiopic calendar.\n * It includes 12 months of 30 days each, plus 5 or 6 intercalary days depending\n * on whether it is a leap year. Two eras are supported: 'BCE' and 'CE'.\n */\nexport class CopticCalendar extends EthiopicCalendar {\n  identifier: CalendarIdentifier = 'coptic';\n\n  fromJulianDay(jd: number): CalendarDate {\n    let [year, month, day] = julianDayToCE(COPTIC_EPOCH, jd);\n    let era = 'CE';\n    if (year <= 0) {\n      era = 'BCE';\n      year = 1 - year;\n    }\n\n    return new CalendarDate(this, era, year, month, day);\n  }\n\n  toJulianDay(date: AnyCalendarDate): number {\n    let year = date.year;\n    if (date.era === 'BCE') {\n      year = 1 - year;\n    }\n\n    return ceToJulianDay(COPTIC_EPOCH, year, date.month, date.day);\n  }\n\n  getDaysInMonth(date: AnyCalendarDate): number {\n    let year = date.year;\n    if (date.era === 'BCE') {\n      year = 1 - year;\n    }\n\n    return getDaysInMonth(year, date.month);\n  }\n\n  isInverseEra(date: AnyCalendarDate): boolean {\n    return date.era === 'BCE';\n  }\n\n  balanceDate(date: Mutable<AnyCalendarDate>): void {\n    if (date.year <= 0) {\n      date.era = date.era === 'BCE' ? 'CE' : 'BCE';\n      date.year = 1 - date.year;\n    }\n  }\n\n  getEras(): string[] {\n    return ['BCE', 'CE'];\n  }\n\n  getYearsInEra(date: AnyCalendarDate): number {\n    // 9999-12-30 gregorian is 9716-02-20 coptic.\n    // Round down to 9715 for the last full year.\n    // BCE 9999-01-01 coptic is BC 9716-06-15 gregorian.\n    return date.era === 'BCE' ? 9999 : 9715;\n  }\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {BuddhistCalendar} from './calendars/BuddhistCalendar';\nimport {Calendar, CalendarIdentifier} from './types';\nimport {\n  CopticCalendar,\n  EthiopicAmeteAlemCalendar,\n  EthiopicCalendar\n} from './calendars/EthiopicCalendar';\nimport {GregorianCalendar} from './calendars/GregorianCalendar';\nimport {HebrewCalendar} from './calendars/HebrewCalendar';\nimport {IndianCalendar} from './calendars/IndianCalendar';\nimport {\n  IslamicCivilCalendar,\n  IslamicTabularCalendar,\n  IslamicUmalquraCalendar\n} from './calendars/IslamicCalendar';\nimport {JapaneseCalendar} from './calendars/JapaneseCalendar';\nimport {PersianCalendar} from './calendars/PersianCalendar';\nimport {TaiwanCalendar} from './calendars/TaiwanCalendar';\n\n/** Creates a `Calendar` instance from a Unicode calendar identifier string. */\nexport function createCalendar(name: CalendarIdentifier): Calendar {\n  switch (name) {\n    case 'buddhist':\n      return new BuddhistCalendar();\n    case 'ethiopic':\n      return new EthiopicCalendar();\n    case 'ethioaa':\n      return new EthiopicAmeteAlemCalendar();\n    case 'coptic':\n      return new CopticCalendar();\n    case 'hebrew':\n      return new HebrewCalendar();\n    case 'indian':\n      return new IndianCalendar();\n    case 'islamic-civil':\n      return new IslamicCivilCalendar();\n    case 'islamic-tbla':\n      return new IslamicTabularCalendar();\n    case 'islamic-umalqura':\n      return new IslamicUmalquraCalendar();\n    case 'japanese':\n      return new JapaneseCalendar();\n    case 'persian':\n      return new PersianCalendar();\n    case 'roc':\n      return new TaiwanCalendar();\n    case 'gregory':\n    default:\n      return new GregorianCalendar();\n  }\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nlet formatterCache = new Map<string, Intl.DateTimeFormat>();\n\ninterface DateRangeFormatPart extends Intl.DateTimeFormatPart {\n  source: 'startRange' | 'endRange' | 'shared';\n}\n\n/** A wrapper around Intl.DateTimeFormat that fixes various browser bugs, and polyfills new features. */\nexport class DateFormatter implements Intl.DateTimeFormat {\n  private formatter: Intl.DateTimeFormat;\n  private options: Intl.DateTimeFormatOptions;\n  private resolvedHourCycle: Intl.DateTimeFormatOptions['hourCycle'];\n\n  constructor(locale: string, options: Intl.DateTimeFormatOptions = {}) {\n    this.formatter = getCachedDateFormatter(locale, options);\n    this.options = options;\n  }\n\n  /**\n   * Formats a date as a string according to the locale and format options passed to the\n   * constructor.\n   */\n  format(value: Date): string {\n    return this.formatter.format(value);\n  }\n\n  /** Formats a date to an array of parts such as separators, numbers, punctuation, and more. */\n  formatToParts(value: Date): Intl.DateTimeFormatPart[] {\n    return this.formatter.formatToParts(value);\n  }\n\n  /** Formats a date range as a string. */\n  formatRange(start: Date, end: Date): string {\n    // @ts-ignore\n    if (typeof this.formatter.formatRange === 'function') {\n      // @ts-ignore\n      return this.formatter.formatRange(start, end);\n    }\n\n    if (end < start) {\n      throw new RangeError('End date must be >= start date');\n    }\n\n    // Very basic fallback for old browsers.\n    return `${this.formatter.format(start)} – ${this.formatter.format(end)}`;\n  }\n\n  /** Formats a date range as an array of parts. */\n  formatRangeToParts(start: Date, end: Date): DateRangeFormatPart[] {\n    // @ts-ignore\n    if (typeof this.formatter.formatRangeToParts === 'function') {\n      // @ts-ignore\n      return this.formatter.formatRangeToParts(start, end);\n    }\n\n    if (end < start) {\n      throw new RangeError('End date must be >= start date');\n    }\n\n    let startParts = this.formatter.formatToParts(start);\n    let endParts = this.formatter.formatToParts(end);\n    return [\n      ...startParts.map(p => ({...p, source: 'startRange'}) as DateRangeFormatPart),\n      {type: 'literal', value: ' – ', source: 'shared'},\n      ...endParts.map(p => ({...p, source: 'endRange'}) as DateRangeFormatPart)\n    ];\n  }\n\n  /** Returns the resolved formatting options based on the values passed to the constructor. */\n  resolvedOptions(): Intl.ResolvedDateTimeFormatOptions {\n    let resolvedOptions = this.formatter.resolvedOptions();\n    if (hasBuggyResolvedHourCycle()) {\n      if (!this.resolvedHourCycle) {\n        this.resolvedHourCycle = getResolvedHourCycle(resolvedOptions.locale, this.options);\n      }\n      resolvedOptions.hourCycle = this.resolvedHourCycle;\n      resolvedOptions.hour12 = this.resolvedHourCycle === 'h11' || this.resolvedHourCycle === 'h12';\n    }\n\n    // Safari uses a different name for the Ethiopic (Amete Alem) calendar.\n    // https://bugs.webkit.org/show_bug.cgi?id=241564\n    if (resolvedOptions.calendar === 'ethiopic-amete-alem') {\n      resolvedOptions.calendar = 'ethioaa';\n    }\n\n    return resolvedOptions;\n  }\n}\n\n// There are multiple bugs involving the hour12 and hourCycle options in various browser engines.\n//   - Chrome [1] (and the ECMA 402 spec [2]) resolve hour12: false in English and other locales to h24 (24:00 - 23:59)\n//     rather than h23 (00:00 - 23:59). Same can happen with hour12: true in French, which Chrome resolves to h11 (00:00 - 11:59)\n//     rather than h12 (12:00 - 11:59).\n//   - WebKit returns an incorrect hourCycle resolved option in the French locale due to incorrect parsing of 'h' literal\n//     in the resolved pattern. It also formats incorrectly when specifying the hourCycle option for the same reason. [3]\n// [1] https://bugs.chromium.org/p/chromium/issues/detail?id=1045791\n// [2] https://github.com/tc39/ecma402/issues/402\n// [3] https://bugs.webkit.org/show_bug.cgi?id=229313\n\n// https://github.com/unicode-org/cldr/blob/018b55eff7ceb389c7e3fc44e2f657eae3b10b38/common/supplemental/supplementalData.xml#L4774-L4802\nconst hour12Preferences = {\n  true: {\n    // Only Japanese uses the h11 style for 12 hour time. All others use h12.\n    ja: 'h11'\n  },\n  false: {\n    // All locales use h23 for 24 hour time. None use h24.\n  }\n};\n\nfunction getCachedDateFormatter(\n  locale: string,\n  options: Intl.DateTimeFormatOptions = {}\n): Intl.DateTimeFormat {\n  // Work around buggy hour12 behavior in Chrome / ECMA 402 spec by using hourCycle instead.\n  // Only apply the workaround if the issue is detected, because the hourCycle option is buggy in Safari.\n  if (typeof options.hour12 === 'boolean' && hasBuggyHour12Behavior()) {\n    options = {...options};\n    let pref = hour12Preferences[String(options.hour12)][locale.split('-')[0]];\n    let defaultHourCycle = options.hour12 ? 'h12' : 'h23';\n    options.hourCycle = pref ?? defaultHourCycle;\n    delete options.hour12;\n  }\n\n  let cacheKey =\n    locale +\n    (options\n      ? Object.entries(options)\n          .sort((a, b) => (a[0] < b[0] ? -1 : 1))\n          .join()\n      : '');\n  if (formatterCache.has(cacheKey)) {\n    return formatterCache.get(cacheKey)!;\n  }\n\n  let numberFormatter = new Intl.DateTimeFormat(locale, options);\n  formatterCache.set(cacheKey, numberFormatter);\n  return numberFormatter;\n}\n\nlet _hasBuggyHour12Behavior: boolean | null = null;\nfunction hasBuggyHour12Behavior() {\n  if (_hasBuggyHour12Behavior == null) {\n    _hasBuggyHour12Behavior =\n      new Intl.DateTimeFormat('en-US', {\n        hour: 'numeric',\n        hour12: false\n      }).format(new Date(2020, 2, 3, 0)) === '24';\n  }\n\n  return _hasBuggyHour12Behavior;\n}\n\nlet _hasBuggyResolvedHourCycle: boolean | null = null;\nfunction hasBuggyResolvedHourCycle() {\n  if (_hasBuggyResolvedHourCycle == null) {\n    _hasBuggyResolvedHourCycle =\n      new Intl.DateTimeFormat('fr', {\n        hour: 'numeric',\n        hour12: false\n      }).resolvedOptions().hourCycle === 'h12';\n  }\n\n  return _hasBuggyResolvedHourCycle;\n}\n\nfunction getResolvedHourCycle(locale: string, options: Intl.DateTimeFormatOptions) {\n  if (!options.timeStyle && !options.hour) {\n    return undefined;\n  }\n\n  // Work around buggy results in resolved hourCycle and hour12 options in WebKit.\n  // Format the minimum possible hour and maximum possible hour in a day and parse the results.\n  locale = locale.replace(/(-u-)?-nu-[a-zA-Z0-9]+/, '');\n  locale += (locale.includes('-u-') ? '' : '-u') + '-nu-latn';\n  let formatter = getCachedDateFormatter(locale, {\n    ...options,\n    timeZone: undefined // use local timezone\n  });\n\n  let min = parseInt(\n    formatter.formatToParts(new Date(2020, 2, 3, 0)).find(p => p.type === 'hour')!.value,\n    10\n  );\n  let max = parseInt(\n    formatter.formatToParts(new Date(2020, 2, 3, 23)).find(p => p.type === 'hour')!.value,\n    10\n  );\n\n  if (min === 0 && max === 23) {\n    return 'h23';\n  }\n\n  if (min === 24 && max === 23) {\n    return 'h24';\n  }\n\n  if (min === 0 && max === 11) {\n    return 'h11';\n  }\n\n  if (min === 12 && max === 11) {\n    return 'h12';\n  }\n\n  throw new Error('Unexpected hour cycle result');\n}\n","import type { DateValue } from '@internationalized/date'\nimport type { Matcher } from './types'\nimport { CalendarDateTime, getDayOfWeek, getLocalTimeZone, parseDate, parseDateTime, parseZonedDateTime, toCalendar, ZonedDateTime } from '@internationalized/date'\n\n/**\n * Given a date string and a reference `DateValue` object, parse the\n * string to the same type as the reference object.\n *\n * Useful for parsing strings from data attributes, which are always\n * strings, to the same type being used by the date component.\n */\nexport function parseStringToDateValue(dateStr: string, referenceVal: DateValue): DateValue {\n  let dateValue: DateValue\n  if (isZonedDateTime(referenceVal))\n    dateValue = parseZonedDateTime(dateStr)\n\n  else if (isCalendarDateTime(referenceVal))\n    dateValue = parseDateTime(dateStr)\n\n  else\n    dateValue = parseDate(dateStr)\n\n  return dateValue.calendar !== referenceVal.calendar ? toCalendar(dateValue, referenceVal.calendar) : dateValue\n}\n\n/**\n * Given a `DateValue` object, convert it to a native `Date` object.\n * If a timezone is provided, the date will be converted to that timezone.\n * If no timezone is provided, the date will be converted to the local timezone.\n */\nexport function toDate(dateValue: DateValue, tz: string = getLocalTimeZone()) {\n  if (isZonedDateTime(dateValue))\n    return dateValue.toDate()\n  else\n    return dateValue.toDate(tz)\n}\n\nexport function isCalendarDateTime(dateValue: DateValue): dateValue is CalendarDateTime {\n  return dateValue instanceof CalendarDateTime\n}\n\nexport function isZonedDateTime(dateValue: DateValue): dateValue is ZonedDateTime {\n  return dateValue instanceof ZonedDateTime\n}\n\nexport function hasTime(dateValue: DateValue) {\n  return isCalendarDateTime(dateValue) || isZonedDateTime(dateValue)\n}\n\n/**\n * Given a date, return the number of days in the month.\n */\nexport function getDaysInMonth(date: Date | DateValue) {\n  if (date instanceof Date) {\n    const year = date.getFullYear()\n    const month = date.getMonth() + 1\n    /**\n     * By using zero as the day, we get the\n     * last day of the previous month, which\n     * is the month we originally passed in.\n     */\n    return new Date(year, month, 0).getDate()\n  }\n  else {\n    return date.set({ day: 100 }).day\n  }\n}\n\n/**\n * Determine if a date is before the reference date.\n * @param dateToCompare - is this date before the `referenceDate`\n * @param referenceDate - is the `dateToCompare` before this date\n *\n * @see {@link isBeforeOrSame} for inclusive\n */\nexport function isBefore(dateToCompare: DateValue, referenceDate: DateValue) {\n  return dateToCompare.compare(referenceDate) < 0\n}\n\n/**\n * Determine if a date is after the reference date.\n * @param dateToCompare - is this date after the `referenceDate`\n * @param referenceDate - is the `dateToCompare` after this date\n *\n * @see {@link isAfterOrSame} for inclusive\n */\nexport function isAfter(dateToCompare: DateValue, referenceDate: DateValue) {\n  return dateToCompare.compare(referenceDate) > 0\n}\n\n/**\n * Determine if a date is before or the same as the reference date.\n *\n * @param dateToCompare - the date to compare\n * @param referenceDate - the reference date to make the comparison against\n *\n * @see {@link isBefore} for non-inclusive\n */\nexport function isBeforeOrSame(dateToCompare: DateValue, referenceDate: DateValue) {\n  return dateToCompare.compare(referenceDate) <= 0\n}\n\n/**\n * Determine if a date is after or the same as the reference date.\n *\n * @param dateToCompare - is this date after or the same as the `referenceDate`\n * @param referenceDate - is the `dateToCompare` after or the same as this date\n *\n * @see {@link isAfter} for non-inclusive\n */\nexport function isAfterOrSame(dateToCompare: DateValue, referenceDate: DateValue) {\n  return dateToCompare.compare(referenceDate) >= 0\n}\n\n/**\n * Determine if a date is inclusively between a start and end reference date.\n *\n * @param date - is this date inclusively between the `start` and `end` dates\n * @param start - the start reference date to make the comparison against\n * @param end - the end reference date to make the comparison against\n *\n * @see {@link isBetween} for non-inclusive\n */\nexport function isBetweenInclusive(date: DateValue, start: DateValue, end: DateValue) {\n  return isAfterOrSame(date, start) && isBeforeOrSame(date, end)\n}\n\n/**\n * Determine if a date is between a start and end reference date.\n *\n * @param date - is this date between the `start` and `end` dates\n * @param start - the start reference date to make the comparison against\n * @param end - the end reference date to make the comparison against\n *\n * @see {@link isBetweenInclusive} for inclusive\n */\nexport function isBetween(date: DateValue, start: DateValue, end: DateValue) {\n  return isAfter(date, start) && isBefore(date, end)\n}\n\nexport function getLastFirstDayOfWeek<T extends DateValue = DateValue>(\n  date: T,\n  firstDayOfWeek: number,\n  locale: string,\n): T {\n  /**\n   * \"firstDayOfWeek\" is fixed to 0(Sunday) to avoid confusion regarding locales.\n   * This also aligns with other date libraries, e.g., date-fns.\n   *\n   * #see https://github.com/unovue/reka-ui/issues/2157\n   */\n  const day = getDayOfWeek(date, locale, 'sun')\n\n  if (firstDayOfWeek > day)\n    return date.subtract({ days: day + 7 - firstDayOfWeek }) as T\n\n  if (firstDayOfWeek === day)\n    return date as T\n\n  return date.subtract({ days: day - firstDayOfWeek }) as T\n}\n\nexport function getNextLastDayOfWeek<T extends DateValue = DateValue>(\n  date: T,\n  firstDayOfWeek: number,\n  locale: string,\n): T {\n  /**\n   * \"firstDayOfWeek\" is fixed to 0(Sunday) to avoid confusion regarding locales.\n   * This also aligns with other date libraries, e.g., date-fns.\n   *\n   * #see https://github.com/unovue/reka-ui/issues/2157\n   */\n  const day = getDayOfWeek(date, locale, 'sun')\n\n  const lastDayOfWeek = firstDayOfWeek === 0 ? 6 : firstDayOfWeek - 1\n\n  if (day === lastDayOfWeek)\n    return date as T\n\n  if (day > lastDayOfWeek)\n    return date.add({ days: 7 - day + lastDayOfWeek }) as T\n\n  return date.add({ days: lastDayOfWeek - day }) as T\n}\n\n/**\n * Check if two dates are in the same year and month.\n */\nexport function isSameYearMonth(a: DateValue, b: DateValue): boolean {\n  return a.year === b.year && a.month === b.month\n}\n\n/**\n * Check if two dates are in the same year.\n */\nexport function isSameYear(a: DateValue, b: DateValue): boolean {\n  return a.year === b.year\n}\n\nexport function areAllDaysBetweenValid(\n  start: DateValue,\n  end: DateValue,\n  isUnavailable: Matcher | undefined,\n  isDisabled: Matcher | undefined,\n  isHighlightable?: Matcher | undefined,\n) {\n  if (isUnavailable === undefined && isDisabled === undefined && isHighlightable === undefined)\n    return true\n\n  let dCurrent = start.add({ days: 1 })\n  if ((isDisabled?.(dCurrent) || isUnavailable?.(dCurrent))\n    && !isHighlightable?.(dCurrent)) {\n    return false\n  }\n\n  const dEnd = end\n  while (dCurrent.compare(dEnd) < 0) {\n    dCurrent = dCurrent.add({ days: 1 })\n    if ((isDisabled?.(dCurrent) || isUnavailable?.(dCurrent))\n      && !isHighlightable?.(dCurrent)) {\n      return false\n    }\n  }\n  return true\n}\n\n/**\n * Compare two dates by year and month only (ignoring day).\n */\nexport function compareYearMonth(a: DateValue, b: DateValue): number {\n  if (a.year !== b.year)\n    return a.year - b.year\n  return a.month - b.month\n}\n\n/**\n * Check if a date's month is between start and end (inclusive), comparing year+month only.\n */\nexport function isMonthBetweenInclusive(date: DateValue, start: DateValue, end: DateValue): boolean {\n  return compareYearMonth(date, start) >= 0 && compareYearMonth(date, end) <= 0\n}\n\n/**\n * Check if a date's year is between start and end (inclusive), comparing year only.\n */\nexport function isYearBetweenInclusive(date: DateValue, start: DateValue, end: DateValue): boolean {\n  return date.year >= start.year && date.year <= end.year\n}\n\n/**\n * Get the number of months between two dates (inclusive).\n */\nexport function getMonthsBetween(start: DateValue, end: DateValue): number {\n  return (end.year - start.year) * 12 + (end.month - start.month) + 1\n}\n\n/**\n * Get the number of years between two dates (inclusive).\n */\nexport function getYearsBetween(start: DateValue, end: DateValue): number {\n  return end.year - start.year + 1\n}\n\n/**\n * Check if all months between start and end are valid (not unavailable/disabled).\n */\nexport function areAllMonthsBetweenValid(\n  start: DateValue,\n  end: DateValue,\n  isUnavailable: Matcher | undefined,\n  isDisabled: Matcher | undefined,\n): boolean {\n  if (isUnavailable === undefined && isDisabled === undefined)\n    return true\n\n  let current = start.set({ day: 1 })\n  const endMonth = end.set({ day: 1 })\n\n  while (compareYearMonth(current, endMonth) <= 0) {\n    if (isDisabled?.(current) || isUnavailable?.(current))\n      return false\n    current = current.add({ months: 1 })\n  }\n  return true\n}\n\n/**\n * Check if all years between start and end are valid (not unavailable/disabled).\n */\nexport function areAllYearsBetweenValid(\n  start: DateValue,\n  end: DateValue,\n  isUnavailable: Matcher | undefined,\n  isDisabled: Matcher | undefined,\n): boolean {\n  if (isUnavailable === undefined && isDisabled === undefined)\n    return true\n\n  let current = start.set({ day: 1, month: 1 })\n  const endYear = end.set({ day: 1, month: 1 })\n\n  while (current.year <= endYear.year) {\n    if (isDisabled?.(current) || isUnavailable?.(current))\n      return false\n    current = current.add({ years: 1 })\n  }\n  return true\n}\n","/*\n  * Implementation ported from https://github.com/melt-ui/melt-ui/blob/develop/src/lib/internal/helpers/date/utils.ts\n*/\n\nimport type { DateValue, ZonedDateTime } from '@internationalized/date'\nimport { CalendarDate, CalendarDateTime, createCalendar, DateFormatter, Time, toCalendar } from '@internationalized/date'\n\nexport type TimeValue = Time | CalendarDateTime | ZonedDateTime\n\nexport type Granularity = 'day' | 'hour' | 'minute' | 'second'\nexport type TimeGranularity = 'hour' | 'minute' | 'second'\n\ntype GetDefaultDateProps = {\n  defaultValue?: DateValue | DateValue[] | undefined\n  defaultPlaceholder?: DateValue | undefined\n  granularity?: Granularity\n  locale?: string\n}\n\n/**\n * A helper function used throughout the various date builders\n * to generate a default `DateValue` using the `defaultValue`,\n * `defaultPlaceholder`, and `granularity` props.\n *\n * It's important to match the `DateValue` type being used\n * elsewhere in the builder, so they behave according to the\n * behavior the user expects based on the props they've provided.\n *\n */\nexport function getDefaultDate(props: GetDefaultDateProps): DateValue {\n  const { defaultValue, defaultPlaceholder, granularity = 'day', locale = 'en' } = props\n\n  if (Array.isArray(defaultValue) && defaultValue.length)\n    return defaultValue.at(-1)!.copy()\n\n  if (defaultValue && !Array.isArray(defaultValue))\n    return defaultValue.copy()\n\n  if (defaultPlaceholder)\n    return defaultPlaceholder.copy()\n\n  const date = new Date()\n  const year = date.getFullYear()\n  const month = date.getMonth() + 1\n  const day = date.getDate()\n  const calendarDateTimeGranularities = ['hour', 'minute', 'second']\n\n  const defaultFormatter = new DateFormatter(locale)\n  const calendar = createCalendar(defaultFormatter.resolvedOptions().calendar)\n\n  if (calendarDateTimeGranularities.includes(granularity ?? 'day'))\n    return toCalendar(new CalendarDateTime(year, month, day, 0, 0, 0), calendar)\n\n  return toCalendar(new CalendarDate(year, month, day), calendar)\n}\n\ntype GetDefaultTimeProps = {\n  defaultValue?: TimeValue | undefined\n  defaultPlaceholder?: TimeValue | undefined\n}\n\nexport function getDefaultTime(props: GetDefaultTimeProps): TimeValue {\n  const { defaultValue, defaultPlaceholder } = props\n\n  if (defaultValue) {\n    return defaultValue.copy()\n  }\n\n  if (defaultPlaceholder) {\n    return defaultPlaceholder.copy()\n  }\n\n  return new Time(0, 0, 0)\n}\n","/**\n * Splits an array into chunks of a given size.\n * @param arr The array to split.\n * @param size The size of each chunk.\n * @returns An array of arrays, where each sub-array has `size` elements from the original array.\n * @example ```ts\n * const arr = [1, 2, 3, 4, 5, 6, 7, 8];\n * const chunks = chunk(arr, 3);\n * // chunks = [[1, 2, 3], [4, 5, 6], [7, 8]]\n * ```\n */\nexport function chunk<T>(arr: T[], size: number): T[][] {\n  const result = []\n  for (let i = 0; i < arr.length; i += size)\n    result.push(arr.slice(i, i + size))\n\n  return result\n}\n","import type { Granularity } from './comparators'\nimport type { DateInputType, DateStep, DateValue, HourCycle } from './types'\nimport { defu } from 'defu'\n\nexport function getOptsByGranularity(granularity: Granularity, hourCycle: HourCycle, isTimeValue: boolean = false) {\n  const opts: Intl.DateTimeFormatOptions = {\n    year: 'numeric',\n    month: '2-digit',\n    day: '2-digit',\n    hour: '2-digit',\n    minute: '2-digit',\n    second: '2-digit',\n    timeZoneName: 'short',\n    hourCycle: normalizeHourCycle(hourCycle),\n    hour12: normalizeHour12(hourCycle),\n  }\n  if (isTimeValue) {\n    delete opts.year\n    delete opts.month\n    delete opts.day\n  }\n\n  if (granularity === 'day') {\n    delete opts.second\n    delete opts.hour\n    delete opts.minute\n    delete opts.timeZoneName\n  }\n  if (granularity === 'hour') {\n    delete opts.minute\n    delete opts.second\n  }\n\n  if (granularity === 'minute')\n    delete opts.second\n\n  return opts\n}\n\ntype GetDefaultDateStepProps = {\n  step?: DateStep\n}\n\nexport function normalizeDateStep(props?: GetDefaultDateStepProps): DateStep {\n  return defu(props?.step, {\n    year: 1,\n    month: 1,\n    day: 1,\n    hour: 1,\n    minute: 1,\n    second: 1,\n    millisecond: 1,\n  } satisfies DateStep)\n}\n\nexport function handleCalendarInitialFocus(calendar: HTMLElement) {\n  const selectedDay = calendar.querySelector<HTMLElement>('[data-selected]')\n  if (selectedDay)\n    return selectedDay.focus()\n\n  const today = calendar.querySelector<HTMLElement>('[data-today]')\n  if (today)\n    return today.focus()\n\n  const firstDay = calendar.querySelector<HTMLElement>('[data-reka-calendar-day]')\n  if (firstDay)\n    return firstDay.focus()\n}\n\nexport function normalizeHourCycle(hourCycle: HourCycle) {\n  if (hourCycle === 24)\n    return 'h23'\n  if (hourCycle === 12)\n    return 'h11'\n  return undefined\n}\n\nexport function normalizeHour12(hourCycle: HourCycle) {\n  if (hourCycle === 24)\n    return false\n  if (hourCycle === 12)\n    return true\n  return undefined\n}\n\nexport function getInputType(granularity: Granularity): DateInputType {\n  return granularity === 'day' ? 'date' : 'datetime-local'\n}\n\nexport function normalizeInputValue(date: DateValue | undefined, granularity: Granularity): string {\n  if (!date)\n    return ''\n\n  const type = getInputType(granularity)\n\n  const year = String(date.year).padStart(4, '0')\n  const month = String(date.month).padStart(2, '0')\n  const day = String(date.day).padStart(2, '0')\n\n  if (type === 'date')\n    return `${year}-${month}-${day}`\n\n  const hour = String('hour' in date ? date.hour : 0).padStart(2, '0')\n  const minute = String('minute' in date ? date.minute : 0).padStart(2, '0')\n\n  if (granularity === 'second') {\n    const second = String('second' in date ? date.second : 0).padStart(2, '0')\n    return `${year}-${month}-${day}T${hour}:${minute}:${second}`\n  }\n\n  return `${year}-${month}-${day}T${hour}:${minute}`\n}\n","/*\n * Implementation ported from from from https://github.com/melt-ui/melt-ui/blob/develop/src/lib/builders/calendar/create.ts\n*/\n\nimport type { DateValue, DayOfWeek } from '@internationalized/date'\nimport type { Grid } from './types'\nimport type { DateRange } from '@/shared'\nimport { CalendarDate, endOfMonth, endOfYear, getDayOfWeek, startOfMonth, startOfWeek, startOfYear } from '@internationalized/date'\nimport { getDaysInMonth, getLastFirstDayOfWeek, getNextLastDayOfWeek } from './comparators'\nimport { chunk } from './utils'\n\nexport type WeekDayFormat = 'narrow' | 'short' | 'long'\n\nexport type WeekStartsOn = 0 | 1 | 2 | 3 | 4 | 5 | 6\n\nexport type CreateSelectProps = {\n  /**\n   * The date object representing the date (usually the first day of the month/year).\n   */\n  dateObj: DateValue\n}\n\nexport type CreateMonthProps = {\n  /**\n   * The date object representing the month's date (usually the first day of the month).\n   */\n  dateObj: DateValue\n\n  /**\n   * The day of the week to start the calendar on (0 for Sunday, 1 for Monday, etc.).\n   */\n  weekStartsOn: WeekStartsOn\n\n  /**\n   * Whether to always render 6 weeks in the calendar, even if the month doesn't\n   * span 6 weeks.\n   */\n  fixedWeeks: boolean\n\n  /**\n   * The locale to use when creating the calendar month.\n   */\n  locale: string\n}\n\n/**\n * Retrieves an array of date values representing the days between\n * the provided start and end dates.\n */\nexport function getDaysBetween(start: DateValue, end: DateValue) {\n  const days: DateValue[] = []\n  let dCurrent = start.add({ days: 1 })\n  const dEnd = end\n  while (dCurrent.compare(dEnd) < 0) {\n    days.push(dCurrent)\n    dCurrent = dCurrent.add({ days: 1 })\n  }\n  return days\n}\n\nexport function createMonth(props: CreateMonthProps): Grid<DateValue> {\n  const { dateObj, weekStartsOn, fixedWeeks, locale } = props\n  const daysInMonth = getDaysInMonth(dateObj)\n\n  const datesArray = Array.from({ length: daysInMonth }, (_, i) => dateObj.set({ day: i + 1 }))\n\n  const firstDayOfMonth = startOfMonth(dateObj)\n  const lastDayOfMonth = endOfMonth(dateObj)\n\n  const lastSunday = getLastFirstDayOfWeek(firstDayOfMonth, weekStartsOn, locale)\n  const nextSaturday = getNextLastDayOfWeek(lastDayOfMonth, weekStartsOn, locale)\n\n  const lastMonthDays = getDaysBetween(lastSunday.subtract({ days: 1 }), firstDayOfMonth)\n  const nextMonthDays = getDaysBetween(lastDayOfMonth, nextSaturday.add({ days: 1 }))\n\n  const totalDays = lastMonthDays.length + datesArray.length + nextMonthDays.length\n\n  if (fixedWeeks && totalDays < 42) {\n    const extraDays = 42 - totalDays\n\n    let startFrom = nextMonthDays.at(-1)\n\n    if (!startFrom)\n      startFrom = endOfMonth(dateObj)\n\n    const extraDaysArray = Array.from({ length: extraDays }, (_, i) => {\n      const incr = i + 1\n      return startFrom.add({ days: incr })\n    })\n    nextMonthDays.push(...extraDaysArray)\n  }\n\n  const allDays = lastMonthDays.concat(datesArray, nextMonthDays)\n\n  const weeks = chunk(allDays, 7)\n\n  return {\n    value: dateObj,\n    cells: allDays,\n    rows: weeks,\n  }\n}\n\ntype SetMonthProps = CreateMonthProps & {\n  numberOfMonths: number | undefined\n  currentMonths?: Grid<DateValue>[]\n}\n\ntype SetYearProps = CreateSelectProps & {\n  numberOfMonths?: number\n  pagedNavigation?: boolean\n}\n\ntype SetDecadeProps = CreateSelectProps & {\n  startIndex?: number\n  endIndex: number\n}\n\nexport function startOfDecade(dateObj: DateValue) {\n  // round to the lowest nearest 10 when building the decade\n  return startOfYear(dateObj.subtract({ years: dateObj.year - Math.floor(dateObj.year / 10) * 10 }).set({ day: 1, month: 1 }))\n}\n\nexport function endOfDecade(dateObj: DateValue) {\n  // round to the lowest nearest 10 when building the decade\n  return endOfYear(dateObj.add({ years: Math.ceil((dateObj.year + 1) / 10) * 10 - dateObj.year - 1 }).set({ day: 35, month: 12 }))\n}\n\nexport function createDecade(props: SetDecadeProps): DateValue[] {\n  const { dateObj, startIndex, endIndex } = props\n\n  const decadeArray = Array.from({ length: Math.abs(startIndex ?? 0) + endIndex }, (_, i) =>\n    i <= Math.abs((startIndex ?? 0))\n      ? dateObj.subtract({ years: i }).set({ day: 1, month: 1 })\n      : dateObj.add({ years: i - endIndex }).set({ day: 1, month: 1 }))\n\n  decadeArray.sort((a: DateValue, b: DateValue) => a.year - b.year)\n\n  return decadeArray\n}\n\nexport function createYear(props: SetYearProps): DateValue[] {\n  const { dateObj, numberOfMonths = 1, pagedNavigation = false } = props\n\n  if (numberOfMonths && pagedNavigation) {\n    const monthsArray = Array.from({ length: Math.floor(12 / numberOfMonths) }, (_, i) => startOfMonth(dateObj.set({ month: i * numberOfMonths + 1 })))\n\n    return monthsArray\n  }\n\n  const monthsArray = Array.from({ length: 12 }, (_, i) => startOfMonth(dateObj.set({ month: i + 1 })))\n  return monthsArray\n}\n\nexport function createMonths(props: SetMonthProps) {\n  const { numberOfMonths, dateObj, ...monthProps } = props\n\n  const months: Grid<DateValue>[] = []\n\n  if (!numberOfMonths || numberOfMonths === 1) {\n    months.push(\n      createMonth({\n        ...monthProps,\n        dateObj,\n      }),\n    )\n    return months\n  }\n\n  months.push(\n    createMonth({\n      ...monthProps,\n      dateObj,\n    }),\n  )\n\n  // Create all the months, starting with the current month\n  for (let i = 1; i < numberOfMonths; i++) {\n    const nextMonth = dateObj.add({ months: i })\n    months.push(\n      createMonth({\n        ...monthProps,\n        dateObj: nextMonth,\n      }),\n    )\n  }\n\n  return months\n}\n\n/**\n * Creates a 3x4 grid of months for a given year.\n */\nexport function createMonthGrid(props: CreateSelectProps): Grid<DateValue> {\n  const { dateObj } = props\n  const months = createYear({ dateObj })\n  return { value: dateObj, cells: months, rows: chunk(months, 4) }\n}\n\n/**\n * Creates a 3x4 grid of years (decade-aligned).\n * The grid starts from the decade that contains the given date.\n */\nexport function createYearGrid(props: CreateSelectProps & { yearsPerPage?: number, decadeAligned?: boolean }): Grid<DateValue> {\n  const { dateObj, yearsPerPage = 12, decadeAligned = true } = props\n\n  let startYear: number\n  if (decadeAligned) {\n    startYear = startOfDecade(dateObj).year\n  }\n  else {\n    startYear = dateObj.year\n  }\n\n  const years = Array.from({ length: yearsPerPage }, (_, i) => startOfYear(dateObj.set({ year: startYear + i })))\n  const firstYear = years[0]\n  return { value: firstYear, cells: years, rows: chunk(years, 4) }\n}\n\nexport function createYearRange({ start, end }: DateRange): DateValue[] {\n  const years: DateValue[] = []\n\n  if (!start || !end)\n    return years\n\n  let current = startOfYear(start)\n\n  while (current.compare(end) <= 0) {\n    years.push(current)\n    // Move to the first day of the next year\n    current = startOfYear(current.add({ years: 1 }))\n  }\n\n  return years\n}\n\nexport function createDateRange({ start, end }: DateRange): DateValue[] {\n  const dates: DateValue[] = []\n\n  if (!start || !end)\n    return dates\n\n  let current = start\n\n  while (current.compare(end) <= 0) {\n    dates.push(current)\n    current = current.add({ days: 1 })\n  }\n\n  return dates\n}\n\n/**\n * It's better to use `getWeekStart` from `@internationalized/date`,\n * but sadly it is not yet exported from the package.\n * And the `Intl.Locale` API is not supported well enough yet.\n */\nexport function getWeekStartsOn(locale: string): WeekStartsOn {\n  // Jan 6, 2025 is a Monday (ISO day = 1)\n  const monday = new CalendarDate(2025, 1, 6)\n  const dayOfWeek = getDayOfWeek(monday, locale)\n  // dayOfWeek tells us Monday's position in the locale's week (0-indexed)\n  // If Monday is position 0 → week starts Monday (1)\n  // If Monday is position 1 → week starts Sunday (0)\n  return (1 - dayOfWeek + 7) % 7 as WeekStartsOn\n}\n\n/**\n * Returns the locale-specific week number\n */\nexport function getWeekNumber(date: DateValue, locale: string = 'en-US', firstDayOfWeek?: DayOfWeek): number {\n  const jan1 = new CalendarDate(date.year, 1, 1)\n\n  // Detect ISO locale by comparing JS day of week with locale day of week\n  const usesISOWeek = jan1.toDate('UTC').getUTCDay() !== getDayOfWeek(jan1, locale)\n  const weekStartsOn = firstDayOfWeek ?? (usesISOWeek ? 'mon' : 'sun')\n  const firstWeekContainsDate = usesISOWeek ? 4 : 1\n\n  // Find the \"deciding day\" - its year determines which year's week numbering to use\n  const dayOfWeek = getDayOfWeek(date, locale, weekStartsOn)\n  const decidingDay = date.add({ days: 7 - firstWeekContainsDate - dayOfWeek })\n  const weekYear = decidingDay.year\n\n  // Calculate week number from week 1 start\n  const week1Ref = new CalendarDate(weekYear, 1, firstWeekContainsDate)\n  const week1Start = startOfWeek(week1Ref, locale, weekStartsOn)\n  const currentWeekStart = startOfWeek(date, locale, weekStartsOn)\n\n  const MS_PER_WEEK = 7 * 24 * 60 * 60 * 1000\n  const daysDiff = Math.round(\n    (currentWeekStart.toDate('UTC').getTime() - week1Start.toDate('UTC').getTime())\n    / MS_PER_WEEK,\n  )\n  return daysDiff + 1\n}\n","","/*\n  * Implementation ported from https://github.com/melt-ui/melt-ui/blob/develop/src/lib/internal/helpers/date/formatter.ts\n*/\n\nimport type { DateValue, ZonedDateTime } from '@internationalized/date'\nimport { DateFormatter, getLocalTimeZone, today } from '@internationalized/date'\nimport { ref } from 'vue'\nimport { hasTime, isZonedDateTime, toDate } from '@/date'\n\nexport interface DateFormatterOptions extends Intl.DateTimeFormatOptions {\n  calendar?: string\n}\n\nexport type Formatter = {\n  getLocale: () => string\n  setLocale: (newLocale: string) => void\n  custom: (date: Date, options: DateFormatterOptions) => string\n  selectedDate: (date: DateValue, includeTime?: boolean) => string\n  dayOfWeek: (date: Date, length?: DateFormatterOptions['weekday']) => string\n  fullMonthAndYear: (date: Date, options?: DateFormatterOptions) => string\n  fullMonth: (date: Date, options?: DateFormatterOptions) => string\n  fullYear: (date: Date, options?: DateFormatterOptions) => string\n  dayPeriod: (date: Date) => string\n  part: (dateObj: DateValue, type: Intl.DateTimeFormatPartTypes, options?: DateFormatterOptions) => string\n  toParts: (date: DateValue, options?: DateFormatterOptions) => Intl.DateTimeFormatPart[]\n  getMonths: () => { label: string, value: number }[]\n}\n\n/**\n * Creates a wrapper around the `DateFormatter`, which is\n * an improved version of the {@link Intl.DateTimeFormat} API,\n * that is used internally by the various date builders to\n * easily format dates in a consistent way.\n *\n * @see [DateFormatter](https://react-spectrum.adobe.com/internationalized/date/DateFormatter.html)\n */\nexport function useDateFormatter(initialLocale: string, opts: DateFormatterOptions = {}): Formatter {\n  const locale = ref(initialLocale)\n\n  function getLocale() {\n    return locale.value\n  }\n\n  function setLocale(newLocale: string) {\n    locale.value = newLocale\n  }\n\n  function custom(date: Date, options: DateFormatterOptions) {\n    return new DateFormatter(locale.value, { ...opts, ...options }).format(date)\n  }\n\n  function selectedDate(date: DateValue, includeTime = true) {\n    if (hasTime(date) && includeTime) {\n      return custom(toDate(date), {\n        dateStyle: 'long',\n        timeStyle: 'long',\n      })\n    }\n    else {\n      return custom(toDate(date), {\n        dateStyle: 'long',\n      })\n    }\n  }\n\n  function fullMonthAndYear(date: Date, options: DateFormatterOptions = {}) {\n    return new DateFormatter(locale.value, { ...opts, month: 'long', year: 'numeric', ...options }).format(date)\n  }\n\n  function fullMonth(date: Date, options: DateFormatterOptions = {}) {\n    return new DateFormatter(locale.value, { ...opts, month: 'long', ...options }).format(date)\n  }\n\n  function getMonths() {\n    const defaultDate = today(getLocalTimeZone())\n    const months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n    return months.map(item => ({ label: fullMonth(toDate(defaultDate.set({ month: item }))), value: item }))\n  }\n\n  function fullYear(date: Date, options: DateFormatterOptions = {}) {\n    return new DateFormatter(locale.value, { ...opts, year: 'numeric', ...options }).format(date)\n  }\n\n  function toParts(date: DateValue, options?: DateFormatterOptions) {\n    if (isZonedDateTime(date)) {\n      return new DateFormatter(locale.value, {\n        ...opts,\n        ...options,\n        timeZone: (date as ZonedDateTime).timeZone,\n      }).formatToParts(toDate(date))\n    }\n    else {\n      return new DateFormatter(locale.value, { ...opts, ...options }).formatToParts(toDate(date))\n    }\n  }\n\n  function dayOfWeek(date: Date, length: DateFormatterOptions['weekday'] = 'narrow') {\n    return new DateFormatter(locale.value, { ...opts, weekday: length }).format(date)\n  }\n\n  function dayPeriod(date: Date) {\n    const parts = new DateFormatter(locale.value, {\n      ...opts,\n      hour: 'numeric',\n      minute: 'numeric',\n    }).formatToParts(date)\n    const value = parts.find(p => p.type === 'dayPeriod')?.value\n    // Day period can be \"AM\"/\"PM\" or \"am\"/\"pm\" or \"a.m.\"/\"p.m.\" in some locales\n    if (value === 'PM' || value === 'pm' || value === 'p.m.')\n      return 'PM'\n\n    return 'AM'\n  }\n\n  const defaultPartOptions: DateFormatterOptions = {\n    year: 'numeric',\n    month: 'numeric',\n    day: 'numeric',\n    hour: 'numeric',\n    minute: 'numeric',\n    second: 'numeric',\n  }\n\n  function part(\n    dateObj: DateValue,\n    type: Intl.DateTimeFormatPartTypes,\n    options: DateFormatterOptions = {},\n  ) {\n    const opts = { ...defaultPartOptions, ...options }\n    const parts = toParts(dateObj, opts)\n    const part = parts.find(p => p.type === type)\n    return part ? part.value : ''\n  }\n\n  return {\n    setLocale,\n    getLocale,\n    fullMonth,\n    fullYear,\n    fullMonthAndYear,\n    toParts,\n    custom,\n    part,\n    dayPeriod,\n    selectedDate,\n    dayOfWeek,\n    getMonths,\n  }\n}\n","import type { Ref } from 'vue'\nimport type { Direction } from './types'\nimport { computed, ref } from 'vue'\nimport { injectConfigProviderContext } from '@/ConfigProvider/ConfigProvider.vue'\n\n/**\n * The `useDirection` function provides a way to access the current direction in your application.\n * @param {Ref<Direction | undefined>} [dir] - An optional ref containing the direction (ltr or rtl).\n * @returns  computed value that combines with the resolved direction.\n */\nexport function useDirection(dir?: Ref<Direction | undefined>) {\n  const context = injectConfigProviderContext({\n    dir: ref('ltr'),\n  })\n  return computed(() => dir?.value || context.dir?.value || 'ltr')\n}\n","import { camelize, getCurrentInstance, toHandlerKey } from 'vue'\n\n// Vue doesn't have emits forwarding, in order to bind the emits we have to convert events into `onXXX` handlers\n// issue: https://github.com/vuejs/core/issues/5917\n/**\n * The `useEmitAsProps` function is a TypeScript utility that converts emitted events into props for a\n * Vue component.\n * @param emit - The `emit` parameter is a function that is used to emit events from a component. It\n * takes two parameters: `name` which is the name of the event to be emitted, and `...args` which are\n * the arguments to be passed along with the event.\n * @returns The function `useEmitAsProps` returns an object that maps event names to functions that\n * call the `emit` function with the corresponding event name and arguments.\n */\nexport function useEmitAsProps<Name extends string>(\n  emit: (name: Name, ...args: any[]) => void,\n) {\n  const vm = getCurrentInstance()\n\n  const events = vm?.type.emits as Name[]\n  const result: Record<string, any> = {}\n\n  if (!events?.length) {\n    console.warn(\n      `No emitted event found. Please check component: ${vm?.type.__name}`,\n    )\n  }\n\n  events?.forEach((ev) => {\n    result[toHandlerKey(camelize(ev))] = (...arg: any) => emit(ev, ...arg)\n  })\n  return result\n}\n","import type { MaybeRef } from 'vue'\nimport { computed, unref } from 'vue'\n\n/**\n * Provides locale-aware string filtering functions.\n * Uses `Intl.Collator` for comparison to ensure proper Unicode handling.\n *\n * @param options - Optional collator options to customize comparison behavior.\n *   See [Intl.CollatorOptions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) for details.\n * @returns An object with methods to check if a string starts with, ends with, or contains a substring.\n *\n * @example\n * const { startsWith, endsWith, contains } = useFilter();\n *\n * startsWith('hello', 'he'); // true\n * endsWith('hello', 'lo'); // true\n * contains('hello', 'ell'); // true\n */\nexport function useFilter(options?: MaybeRef<Intl.CollatorOptions>) {\n  const computedOptions = computed(() => unref(options))\n  const collator = computed(() => new Intl.Collator('en', { usage: 'search', ...computedOptions.value }))\n\n  const startsWith = (string: string, substring: string) => {\n    if (substring.length === 0)\n      return true\n\n    string = string.normalize('NFC')\n    substring = substring.normalize('NFC')\n    return collator.value.compare(string.slice(0, substring.length), substring) === 0\n  }\n\n  const endsWith = (string: string, substring: string) => {\n    if (substring.length === 0)\n      return true\n\n    string = string.normalize('NFC')\n    substring = substring.normalize('NFC')\n    return collator.value.compare(string.slice(-substring.length), substring) === 0\n  }\n\n  const contains = (string: string, substring: string) => {\n    if (substring.length === 0)\n      return true\n\n    string = string.normalize('NFC')\n    substring = substring.normalize('NFC')\n\n    let scan = 0\n    const sliceLen = substring.length\n    for (; scan + sliceLen <= string.length; scan++) {\n      const slice = string.slice(scan, scan + sliceLen)\n      if (collator.value.compare(substring, slice) === 0)\n        return true\n    }\n\n    return false\n  }\n\n  return {\n    startsWith,\n    endsWith,\n    contains,\n  }\n}\n","import { isClient } from '@vueuse/shared'\nimport { watchEffect } from 'vue'\n\n/** Number of components which have requested interest to have focus guards */\nlet count = 0\n\n/**\n * Injects a pair of focus guards at the edges of the whole DOM tree\n * to ensure `focusin` & `focusout` events can be caught consistently.\n */\nexport function useFocusGuards() {\n  watchEffect((cleanupFn) => {\n    if (!isClient)\n      return\n    const edgeGuards = document.querySelectorAll('[data-reka-focus-guard]')\n    document.body.insertAdjacentElement(\n      'afterbegin',\n      edgeGuards[0] ?? createFocusGuard(),\n    )\n    document.body.insertAdjacentElement(\n      'beforeend',\n      edgeGuards[1] ?? createFocusGuard(),\n    )\n    count++\n\n    cleanupFn(() => {\n      if (count === 1) {\n        document\n          .querySelectorAll('[data-reka-focus-guard]')\n          .forEach(node => node.remove())\n      }\n      count--\n    })\n  })\n}\n\nfunction createFocusGuard() {\n  const element = document.createElement('span')\n  element.setAttribute('data-reka-focus-guard', '')\n  element.tabIndex = 0\n  element.style.outline = 'none'\n  element.style.opacity = '0'\n  element.style.position = 'fixed'\n  element.style.pointerEvents = 'none'\n  return element\n}\n","import type { MaybeElementRef } from '@vueuse/core'\nimport { unrefElement } from '@vueuse/core'\nimport { computed, toValue } from 'vue'\n\nexport function useFormControl(el: MaybeElementRef) {\n  // We set this to true by default so that events bubble to forms without JS (SSR)\n  return computed(() => toValue(el) ? Boolean(unrefElement(el)?.closest('form')) : true)\n}\n","import type { MaybeElement } from '@vueuse/core'\nimport type { ComponentPublicInstance } from 'vue'\n// reference: https://github.com/vuejs/rfcs/issues/258#issuecomment-1068697672\nimport { unrefElement } from '@vueuse/core'\nimport { computed, getCurrentInstance, onUpdated, ref, triggerRef } from 'vue'\n\nexport function useForwardExpose<T extends ComponentPublicInstance>() {\n  const instance = getCurrentInstance()!\n\n  const currentRef = ref<Element | T | null>()\n  const currentElement = computed(() => resolveCurrentElement())\n\n  // When using as-child with conditional rendering (v-if/v-else), the underlying\n  // DOM element ($el) changes but currentRef (component instance) stays the same.\n  // Since $el is not reactive, we sync currentElement after DOM updates.\n  onUpdated(() => {\n    if (currentElement.value !== resolveCurrentElement()) {\n      triggerRef(currentRef)\n    }\n  })\n\n  function resolveCurrentElement() {\n    // $el could be text/comment for non-single root normal or text root, thus we retrieve the nextElementSibling\n    return currentRef.value\n      && '$el' in currentRef.value\n      && ['#text', '#comment'].includes(currentRef.value.$el.nodeName)\n      ? currentRef.value.$el.nextElementSibling as HTMLElement\n      : unrefElement(currentRef as unknown as MaybeElement) as HTMLElement\n  }\n\n  // Do give us credit if you reference our code :D\n  // localExpose should only be assigned once else will create infinite loop\n  const localExpose: Record<string, any> | null = Object.assign({}, instance.exposed)\n  const ret: Record<string, any> = {}\n\n  // retrieve props for current instance\n  for (const key in instance.props) {\n    Object.defineProperty(ret, key, {\n      enumerable: true,\n      configurable: true,\n      get: () => instance.props[key],\n    })\n  }\n\n  // retrieve default exposed value\n  if (Object.keys(localExpose).length > 0) {\n    for (const key in localExpose) {\n      Object.defineProperty(ret, key, {\n        enumerable: true,\n        configurable: true,\n        get: () => localExpose![key],\n      })\n    }\n  }\n\n  // retrieve original first root element\n  Object.defineProperty(ret, '$el', {\n    enumerable: true,\n    configurable: true,\n    get: () => instance.vnode.el,\n  })\n  instance.exposed = ret\n\n  function forwardRef(ref: Element | T | null) {\n    currentRef.value = ref\n\n    if (!ref)\n      return\n\n    // retrieve the forwarded element\n    Object.defineProperty(ret, '$el', {\n      enumerable: true,\n      configurable: true,\n      get: () => (ref instanceof Element ? ref : ref.$el),\n    })\n\n    // ref not is Element\n    // and `useForwardExpose.test.ts > useForwardRef > should forward plain DOM element ref - 2` Passing in `$el`\n    if (!(ref instanceof Element) && !Object.hasOwn(ref, '$el')) {\n      // Retrieves the `exposed` data that has not been unwrapped by `vue` from `$.exposed`.\n      const childExposed = ref.$.exposed\n      const merged = Object.assign({}, ret)\n\n      for (const key in childExposed) {\n        Object.defineProperty(merged, key, {\n          enumerable: true,\n          configurable: true,\n          get: () => childExposed[key],\n        })\n      }\n\n      instance.exposed = merged\n    }\n  }\n\n  return { forwardRef, currentRef, currentElement }\n}\n","import type { MaybeRefOrGetter } from 'vue'\nimport { camelize, computed, getCurrentInstance, toRef } from 'vue'\n\ninterface PropOptions {\n  type?: any\n  required?: boolean\n  default?: any\n}\n\n/**\n * Vue coerces optional boolean props (e.g. `foo?: boolean`) to non-optional (`foo: boolean`)\n * in the `defineProps` return type. Since `useForwardProps` only returns props that were\n * explicitly assigned, boolean-typed props should remain optional in the return type.\n */\ntype WithOptionalBooleans<T> = {\n  [K in keyof T as [T[K]] extends [boolean] ? K : never]?: T[K]\n} & {\n  [K in keyof T as [T[K]] extends [boolean] ? never : K]: T[K]\n}\n\n/**\n * The `useForwardProps` function in TypeScript takes in a set of props and returns a computed value\n * that combines default props with assigned props from the current instance.\n * @param {T} props - The `props` parameter is an object that represents the props passed to a\n * component.\n * @returns computed value that combines the default props, preserved props, and assigned props.\n */\nexport function useForwardProps<T extends Record<string, any>>(props: MaybeRefOrGetter<T>) {\n  const vm = getCurrentInstance()\n  // Default value for declared props\n  const defaultProps = Object.keys(vm?.type.props ?? {}).reduce((prev, curr) => {\n    const defaultValue = (vm?.type.props[curr] as PropOptions).default\n    if (defaultValue !== undefined)\n      prev[curr as keyof T] = defaultValue\n    return prev\n  }, {} as T)\n\n  const refProps = toRef(props)\n  return computed(() => {\n    const preservedProps = {} as T\n    const assignedProps = vm?.vnode.props ?? {}\n\n    Object.keys(assignedProps).forEach((key) => {\n      preservedProps[camelize(key) as keyof T] = assignedProps[key]\n    })\n\n    // Only return value from the props parameter\n    return Object.keys({ ...defaultProps, ...preservedProps }).reduce((prev, curr) => {\n      if (refProps.value[curr] !== undefined)\n        (prev as Record<string, any>)[curr] = refProps.value[curr]\n      return prev\n    }, {} as WithOptionalBooleans<T>)\n  })\n}\n","import type { MaybeRefOrGetter } from 'vue'\nimport { computed } from 'vue'\nimport { useEmitAsProps } from './useEmitAsProps'\nimport { useForwardProps } from './useForwardProps'\n\n/**\n * The function `useForwardPropsEmits` takes in props and an optional emit function, and returns a\n * computed object that combines the parsed props and emits as props.\n * @param {T} props - The `props` parameter is of type `T`, which is a generic type that extends the\n * parameters of the `useForwardProps` function. It represents the props object that is passed to the\n * `useForwardProps` function.\n * @param [emit] - The `emit` parameter is a function that can be used to emit events. It takes two\n * arguments: `name`, which is the name of the event to be emitted, and `args`, which are the arguments\n * to be passed along with the event.\n * @returns a computed property that combines the parsed\n * props and emits as props.\n */\nexport function useForwardPropsEmits<T extends Record<string, any>, Name extends string>(props: MaybeRefOrGetter<T>, emit?: (name: Name, ...args: any[]) => void) {\n  const parsedProps = useForwardProps(props)\n  const emitsAsProps = emit ? useEmitAsProps(emit) : {}\n\n  return computed(() => ({\n    ...parsedProps.value,\n    ...emitsAsProps,\n  }))\n}\n","import type { ComponentPublicInstance } from 'vue'\n// reference: https://github.com/vuejs/rfcs/issues/258#issuecomment-1068697672\nimport { getCurrentInstance } from 'vue'\n\nexport function useForwardRef() {\n  const instance = getCurrentInstance()!\n  function handleRefChange(ref: Element | ComponentPublicInstance | null) {\n    if (typeof ref === 'object') {\n      instance.exposed = ref\n      instance.exposeProxy = ref\n    }\n  }\n  return handleRefChange\n}\n","import type { Ref } from 'vue'\nimport type { Side } from '@/Popper/utils'\nimport { createEventHook, refAutoReset, tryOnScopeDispose } from '@vueuse/shared'\nimport { ref, watchEffect } from 'vue'\n\nexport function useGraceArea(triggerElement: Ref<HTMLElement | undefined>, containerElement: Ref<HTMLElement | undefined>) {\n// Reset the inTransit state if idle/scrolled.\n  const isPointerInTransit = refAutoReset(false, 300)\n  // `refAutoReset` will clear timeout-based resets on scope dispose (e.g., component unmount),\n  // thus leaving the state as-is without resetting it.\n  // So we need to manually reset it in such cases.\n  tryOnScopeDispose(() => {\n    isPointerInTransit.value = false\n  })\n\n  const pointerGraceArea = ref<Polygon | null>(null)\n  const pointerExit = createEventHook<void>()\n\n  function handleRemoveGraceArea() {\n    pointerGraceArea.value = null\n    isPointerInTransit.value = false\n  }\n\n  function handleCreateGraceArea(event: PointerEvent, hoverTarget: HTMLElement | undefined) {\n    if (!hoverTarget)\n      return\n    const currentTarget = event.currentTarget as HTMLElement\n    const exitPoint = { x: event.clientX, y: event.clientY }\n    const exitSide = getExitSideFromRect(exitPoint, currentTarget.getBoundingClientRect())\n    const paddedExitPoints = getPaddedExitPoints(exitPoint, exitSide, 1)\n    const hoverTargetPoints = getPointsFromRect(hoverTarget.getBoundingClientRect())\n    const graceArea = getHull([...paddedExitPoints, ...hoverTargetPoints])\n    pointerGraceArea.value = graceArea\n    isPointerInTransit.value = true\n  }\n\n  watchEffect((cleanupFn) => {\n    if (triggerElement.value && containerElement.value) {\n      const handleTriggerLeave = (event: PointerEvent) => handleCreateGraceArea(event, containerElement.value)\n      const handleContentLeave = (event: PointerEvent) => handleCreateGraceArea(event, triggerElement.value)\n\n      triggerElement.value.addEventListener('pointerleave', handleTriggerLeave)\n      containerElement.value.addEventListener('pointerleave', handleContentLeave)\n\n      cleanupFn(() => {\n        triggerElement.value?.removeEventListener('pointerleave', handleTriggerLeave)\n        containerElement.value?.removeEventListener('pointerleave', handleContentLeave)\n      })\n    }\n  })\n\n  watchEffect((cleanupFn) => {\n    if (pointerGraceArea.value) {\n      const handleTrackPointerGrace = (event: PointerEvent) => {\n        if (!pointerGraceArea.value || !(event.target instanceof Element))\n          return\n\n        const target = event.target\n        const pointerPosition = { x: event.clientX, y: event.clientY }\n        const hasEnteredTarget = triggerElement.value?.contains(target) || containerElement.value?.contains(target)\n        const isPointerOutsideGraceArea = !isPointInPolygon(pointerPosition, pointerGraceArea.value)\n        const isAnotherGraceAreaTrigger = !!target.closest('[data-grace-area-trigger]')\n\n        if (hasEnteredTarget) {\n          handleRemoveGraceArea()\n        }\n        else if (isPointerOutsideGraceArea || isAnotherGraceAreaTrigger) {\n          handleRemoveGraceArea()\n          pointerExit.trigger()\n        }\n      }\n      triggerElement.value?.ownerDocument.addEventListener('pointermove', handleTrackPointerGrace)\n\n      cleanupFn(() => triggerElement.value?.ownerDocument.removeEventListener('pointermove', handleTrackPointerGrace))\n    }\n  })\n\n  return {\n    isPointerInTransit,\n    onPointerExit: pointerExit.on,\n  }\n}\n\ninterface Point { x: number, y: number }\ntype Polygon = Point[]\n\nfunction getExitSideFromRect(point: Point, rect: DOMRect): Side {\n  const top = Math.abs(rect.top - point.y)\n  const bottom = Math.abs(rect.bottom - point.y)\n  const right = Math.abs(rect.right - point.x)\n  const left = Math.abs(rect.left - point.x)\n\n  switch (Math.min(top, bottom, right, left)) {\n    case left:\n      return 'left'\n    case right:\n      return 'right'\n    case top:\n      return 'top'\n    case bottom:\n      return 'bottom'\n    default:\n      throw new Error('unreachable')\n  }\n}\n\nfunction getPaddedExitPoints(exitPoint: Point, exitSide: Side, padding = 5) {\n  const paddedExitPoints: Point[] = []\n  switch (exitSide) {\n    case 'top':\n      paddedExitPoints.push(\n        { x: exitPoint.x - padding, y: exitPoint.y + padding },\n        { x: exitPoint.x + padding, y: exitPoint.y + padding },\n      )\n      break\n    case 'bottom':\n      paddedExitPoints.push(\n        { x: exitPoint.x - padding, y: exitPoint.y - padding },\n        { x: exitPoint.x + padding, y: exitPoint.y - padding },\n      )\n      break\n    case 'left':\n      paddedExitPoints.push(\n        { x: exitPoint.x + padding, y: exitPoint.y - padding },\n        { x: exitPoint.x + padding, y: exitPoint.y + padding },\n      )\n      break\n    case 'right':\n      paddedExitPoints.push(\n        { x: exitPoint.x - padding, y: exitPoint.y - padding },\n        { x: exitPoint.x - padding, y: exitPoint.y + padding },\n      )\n      break\n  }\n  return paddedExitPoints\n}\n\nfunction getPointsFromRect(rect: DOMRect) {\n  const { top, right, bottom, left } = rect\n  return [\n    { x: left, y: top },\n    { x: right, y: top },\n    { x: right, y: bottom },\n    { x: left, y: bottom },\n  ]\n}\n\n// Determine if a point is inside of a polygon.\n// Based on https://github.com/substack/point-in-polygon\nfunction isPointInPolygon(point: Point, polygon: Polygon) {\n  const { x, y } = point\n  let inside = false\n  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n    const xi = polygon[i].x\n    const yi = polygon[i].y\n    const xj = polygon[j].x\n    const yj = polygon[j].y\n\n    // prettier-ignore\n    const intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)\n    if (intersect)\n      inside = !inside\n  }\n\n  return inside\n}\n\n// Returns a new array of points representing the convex hull of the given set of points.\n// https://www.nayuki.io/page/convex-hull-algorithm\nfunction getHull<P extends Point>(points: Readonly<Array<P>>): Array<P> {\n  const newPoints: Array<P> = points.slice()\n  newPoints.sort((a: Point, b: Point) => {\n    if (a.x < b.x)\n      return -1\n    else if (a.x > b.x)\n      return +1\n    else if (a.y < b.y)\n      return -1\n    else if (a.y > b.y)\n      return +1\n    else return 0\n  })\n  return getHullPresorted(newPoints)\n}\n\n// Returns the convex hull, assuming that each points[i] <= points[i + 1]. Runs in O(n) time.\nfunction getHullPresorted<P extends Point>(points: Readonly<Array<P>>): Array<P> {\n  if (points.length <= 1)\n    return points.slice()\n\n  const upperHull: Array<P> = []\n  for (let i = 0; i < points.length; i++) {\n    const p = points[i]\n    while (upperHull.length >= 2) {\n      const q = upperHull.at(-1)!\n      const r = upperHull[upperHull.length - 2]\n      if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x))\n        upperHull.pop()\n      else break\n    }\n    upperHull.push(p)\n  }\n  upperHull.pop()\n\n  const lowerHull: Array<P> = []\n  for (let i = points.length - 1; i >= 0; i--) {\n    const p = points[i]\n    while (lowerHull.length >= 2) {\n      const q = lowerHull.at(-1)!\n      const r = lowerHull[lowerHull.length - 2]\n      if ((q.x - r.x) * (p.y - r.y) >= (q.y - r.y) * (p.x - r.x))\n        lowerHull.pop()\n      else break\n    }\n    lowerHull.push(p)\n  }\n  lowerHull.pop()\n\n  if (\n    upperHull.length === 1\n    && lowerHull.length === 1\n    && upperHull[0].x === lowerHull[0].x\n    && upperHull[0].y === lowerHull[0].y\n  ) {\n    return upperHull\n  }\n\n  else {\n    return upperHull.concat(lowerHull)\n  }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.suppressOthers = exports.supportsInert = exports.inertOthers = exports.hideOthers = void 0;\nvar getDefaultParent = function (originalTarget) {\n    if (typeof document === 'undefined') {\n        return null;\n    }\n    var sampleTarget = Array.isArray(originalTarget) ? originalTarget[0] : originalTarget;\n    return sampleTarget.ownerDocument.body;\n};\nvar counterMap = new WeakMap();\nvar uncontrolledNodes = new WeakMap();\nvar markerMap = {};\nvar lockCount = 0;\nvar unwrapHost = function (node) {\n    return node && (node.host || unwrapHost(node.parentNode));\n};\nvar correctTargets = function (parent, targets) {\n    return targets\n        .map(function (target) {\n        if (parent.contains(target)) {\n            return target;\n        }\n        var correctedTarget = unwrapHost(target);\n        if (correctedTarget && parent.contains(correctedTarget)) {\n            return correctedTarget;\n        }\n        console.error('aria-hidden', target, 'in not contained inside', parent, '. Doing nothing');\n        return null;\n    })\n        .filter(function (x) { return Boolean(x); });\n};\n/**\n * Marks everything except given node(or nodes) as aria-hidden\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @param {String} [controlAttribute] - html Attribute to control\n * @return {Undo} undo command\n */\nvar applyAttributeToOthers = function (originalTarget, parentNode, markerName, controlAttribute) {\n    var targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]);\n    if (!markerMap[markerName]) {\n        markerMap[markerName] = new WeakMap();\n    }\n    var markerCounter = markerMap[markerName];\n    var hiddenNodes = [];\n    var elementsToKeep = new Set();\n    var elementsToStop = new Set(targets);\n    var keep = function (el) {\n        if (!el || elementsToKeep.has(el)) {\n            return;\n        }\n        elementsToKeep.add(el);\n        keep(el.parentNode);\n    };\n    targets.forEach(keep);\n    var deep = function (parent) {\n        if (!parent || elementsToStop.has(parent)) {\n            return;\n        }\n        Array.prototype.forEach.call(parent.children, function (node) {\n            if (elementsToKeep.has(node)) {\n                deep(node);\n            }\n            else {\n                try {\n                    var attr = node.getAttribute(controlAttribute);\n                    var alreadyHidden = attr !== null && attr !== 'false';\n                    var counterValue = (counterMap.get(node) || 0) + 1;\n                    var markerValue = (markerCounter.get(node) || 0) + 1;\n                    counterMap.set(node, counterValue);\n                    markerCounter.set(node, markerValue);\n                    hiddenNodes.push(node);\n                    if (counterValue === 1 && alreadyHidden) {\n                        uncontrolledNodes.set(node, true);\n                    }\n                    if (markerValue === 1) {\n                        node.setAttribute(markerName, 'true');\n                    }\n                    if (!alreadyHidden) {\n                        node.setAttribute(controlAttribute, 'true');\n                    }\n                }\n                catch (e) {\n                    console.error('aria-hidden: cannot operate on ', node, e);\n                }\n            }\n        });\n    };\n    deep(parentNode);\n    elementsToKeep.clear();\n    lockCount++;\n    return function () {\n        hiddenNodes.forEach(function (node) {\n            var counterValue = counterMap.get(node) - 1;\n            var markerValue = markerCounter.get(node) - 1;\n            counterMap.set(node, counterValue);\n            markerCounter.set(node, markerValue);\n            if (!counterValue) {\n                if (!uncontrolledNodes.has(node)) {\n                    node.removeAttribute(controlAttribute);\n                }\n                uncontrolledNodes.delete(node);\n            }\n            if (!markerValue) {\n                node.removeAttribute(markerName);\n            }\n        });\n        lockCount--;\n        if (!lockCount) {\n            // clear\n            counterMap = new WeakMap();\n            counterMap = new WeakMap();\n            uncontrolledNodes = new WeakMap();\n            markerMap = {};\n        }\n    };\n};\n/**\n * Marks everything except given node(or nodes) as aria-hidden\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @return {Undo} undo command\n */\nvar hideOthers = function (originalTarget, parentNode, markerName) {\n    if (markerName === void 0) { markerName = 'data-aria-hidden'; }\n    var targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]);\n    var activeParentNode = parentNode || getDefaultParent(originalTarget);\n    if (!activeParentNode) {\n        return function () { return null; };\n    }\n    // we should not hide aria-live elements - https://github.com/theKashey/aria-hidden/issues/10\n    // and script elements, as they have no impact on accessibility.\n    targets.push.apply(targets, Array.from(activeParentNode.querySelectorAll('[aria-live], script')));\n    return applyAttributeToOthers(targets, activeParentNode, markerName, 'aria-hidden');\n};\nexports.hideOthers = hideOthers;\n/**\n * Marks everything except given node(or nodes) as inert\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @return {Undo} undo command\n */\nvar inertOthers = function (originalTarget, parentNode, markerName) {\n    if (markerName === void 0) { markerName = 'data-inert-ed'; }\n    var activeParentNode = parentNode || getDefaultParent(originalTarget);\n    if (!activeParentNode) {\n        return function () { return null; };\n    }\n    return applyAttributeToOthers(originalTarget, activeParentNode, markerName, 'inert');\n};\nexports.inertOthers = inertOthers;\n/**\n * @returns if current browser supports inert\n */\nvar supportsInert = function () {\n    return typeof HTMLElement !== 'undefined' && HTMLElement.prototype.hasOwnProperty('inert');\n};\nexports.supportsInert = supportsInert;\n/**\n * Automatic function to \"suppress\" DOM elements - _hide_ or _inert_ in the best possible way\n * @param {Element | Element[]} originalTarget - elements to keep on the page\n * @param [parentNode] - top element, defaults to document.body\n * @param {String} [markerName] - a special attribute to mark every node\n * @return {Undo} undo command\n */\nvar suppressOthers = function (originalTarget, parentNode, markerName) {\n    if (markerName === void 0) { markerName = 'data-suppressed'; }\n    return ((0, exports.supportsInert)() ? exports.inertOthers : exports.hideOthers)(originalTarget, parentNode, markerName);\n};\nexports.suppressOthers = suppressOthers;\n","import type { MaybeElementRef } from '@vueuse/core'\nimport { unrefElement } from '@vueuse/core'\nimport { hideOthers } from 'aria-hidden'\nimport { onUnmounted, watch } from 'vue'\n\n/**\n * The `useHideOthers` function is a TypeScript function that takes a target element reference and\n * hides all other elements in ARIA when the target element is present, and restores the visibility of the\n * hidden elements when the target element is removed.\n * @param {MaybeElementRef} target - The `target` parameter is a reference to the element that you want\n * to hide other elements when it is clicked or focused.\n */\nexport function useHideOthers(target: MaybeElementRef) {\n  let undo: ReturnType<typeof hideOthers>\n  watch(() => unrefElement(target), (el) => {\n    // disable hideOthers on test mode\n    if (import.meta.env.MODE === 'test')\n      return\n    // Skip if inside a closed native popover\n    // Use try/catch as `:popover-open` pseudo-class is not supported in all browsers (e.g. Safari 18)\n    let isInsideClosedPopover = false\n    try {\n      isInsideClosedPopover = !!el?.closest('[popover]:not(:popover-open)')\n    }\n    catch {}\n    if (el && !isInsideClosedPopover)\n      undo = hideOthers(el)\n    else if (undo)\n      undo()\n  })\n\n  onUnmounted(() => {\n    if (undo)\n      undo()\n  })\n}\n","import * as vue from 'vue'\n// Inspired from https://github.com/tailwindlabs/headlessui/issues/2913\n// as the alternative, and a fallback for Vue version < 3.5\nimport { injectConfigProviderContext } from '@/ConfigProvider/ConfigProvider.vue'\n\nlet count = 0\n/**\n * The `useId` function generates a unique identifier using a provided deterministic ID,\n * a configured `<ConfigProvider>` ID source, Vue's native `useId`, or a fallback counter.\n * @param {string | null | undefined} [deterministicId] - The `useId` function you provided takes an\n * optional parameter `deterministicId`, which can be a string, null, or undefined. If\n * `deterministicId` is provided, the function will return it. Otherwise, it will generate an id using\n * the configured ID source.\n */\nexport function useId(deterministicId?: string | null | undefined, prefix = 'reka') {\n  if (deterministicId)\n    return deterministicId\n\n  let id: string\n  const configProviderContext = injectConfigProviderContext({ useId: undefined })\n\n  // Keep the app-provided ID source authoritative. Frameworks such as Nuxt can\n  // prerender with a different Vue app ID prefix than the hydrating client, so\n  // falling through to Vue's native useId would bypass the stable source that\n  // ConfigProvider was explicitly given.\n  if (configProviderContext.useId) {\n    id = configProviderContext.useId()\n  }\n  else if ('useId' in vue) {\n    id = vue.useId?.()\n  }\n  else {\n    id = `${++count}`\n  }\n\n  return prefix ? `${prefix}-${id}` : id\n}\n","export function useKbd() {\n  return {\n    ALT: 'Alt',\n    ARROW_DOWN: 'ArrowDown',\n    ARROW_LEFT: 'ArrowLeft',\n    ARROW_RIGHT: 'ArrowRight',\n    ARROW_UP: 'ArrowUp',\n    BACKSPACE: 'Backspace',\n    CAPS_LOCK: 'CapsLock',\n    CONTROL: 'Control',\n    DELETE: 'Delete',\n    END: 'End',\n    ENTER: 'Enter',\n    ESCAPE: 'Escape',\n    F1: 'F1',\n    F10: 'F10',\n    F11: 'F11',\n    F12: 'F12',\n    F2: 'F2',\n    F3: 'F3',\n    F4: 'F4',\n    F5: 'F5',\n    F6: 'F6',\n    F7: 'F7',\n    F8: 'F8',\n    F9: 'F9',\n    HOME: 'Home',\n    META: 'Meta',\n    PAGE_DOWN: 'PageDown',\n    PAGE_UP: 'PageUp',\n    SHIFT: 'Shift',\n    SPACE: ' ',\n    TAB: 'Tab',\n    CTRL: 'Control',\n    ASTERISK: '*',\n    SPACE_CODE: 'Space',\n  }\n}\n\n/**\n * A wrapper around the internal kbd object to make it easier to use in tests\n * which require the key names to be wrapped in curly braces.\n */\nexport type KbdKeys = keyof ReturnType<typeof useKbd>\n\nexport function useTestKbd() {\n  const kbd = useKbd()\n\n  const initTestKbd: Record<KbdKeys, string> = Object.entries(kbd).reduce((acc, [key, value]) => {\n    acc[key as KbdKeys] = `{${value}}`\n    return acc\n  }, {} as Record<KbdKeys, string>)\n\n  return {\n    ...initTestKbd,\n    SHIFT_TAB: `{Shift>}{${kbd.TAB}}`,\n  }\n}\n","import type { Ref } from 'vue'\nimport { computed, ref } from 'vue'\nimport { injectConfigProviderContext } from '@/ConfigProvider/ConfigProvider.vue'\n\n/**\n * The `useLocale` function provides a way to access the current locale in your application.\n * @param {Ref<string | undefined>} [locale] - An optional ref containing the locale.\n * @returns A computed ref holding the resolved locale.\n */\nexport function useLocale(locale?: Ref<string | undefined>) {\n  const context = injectConfigProviderContext({\n    locale: ref('en'),\n  })\n  return computed(() => locale?.value || context.locale?.value || 'en')\n}\n","import type { Ref, UnwrapNestedRefs } from 'vue'\nimport { ref } from 'vue'\nimport { findValuesBetween } from './arrays'\n\nexport function useSelectionBehavior<T>(\n  modelValue: Ref<T | T[]>,\n  props: UnwrapNestedRefs<{ multiple?: boolean, selectionBehavior?: 'toggle' | 'replace' }>,\n) {\n  const firstValue = ref()\n\n  const onSelectItem = (val: T, condition: (existingValue: T) => boolean) => {\n    // multiple select\n    if (props.multiple && Array.isArray(modelValue.value)) {\n      if (props.selectionBehavior === 'replace') {\n        modelValue.value = [val]\n        firstValue.value = val\n      }\n      else {\n        const index = modelValue.value.findIndex(v => condition(v))\n        if (index !== -1)\n          modelValue.value = modelValue.value.filter((_, i) => i !== index)\n        else\n          modelValue.value = [...modelValue.value, val]\n      }\n    }\n    // single select\n    else {\n      if (props.selectionBehavior === 'replace') {\n        modelValue.value = { ...val }\n      }\n      else {\n        if (!Array.isArray(modelValue.value) && condition(modelValue.value))\n          modelValue.value = undefined as any\n        else\n          modelValue.value = { ...val }\n      }\n    }\n    return modelValue.value\n  }\n\n  function handleMultipleReplace(intent: 'first' | 'last' | 'prev' | 'next', currentElement: HTMLElement | Element | null, getItems: () => { ref: HTMLElement, value?: any }[], options: any[]) {\n    if (!firstValue?.value || !props.multiple || !Array.isArray(modelValue.value))\n      return\n\n    const collection = getItems().filter(i => i.ref.dataset.disabled !== '')\n    const lastValue = collection.find(i => i.ref === currentElement)?.value\n    if (!lastValue)\n      return\n\n    let value: T[] | null = null\n    switch (intent) {\n      case 'prev':\n      case 'next': {\n        value = findValuesBetween(options, firstValue.value, lastValue)\n        break\n      }\n      case 'first': {\n        value = findValuesBetween(options, firstValue.value, options?.[0])\n        break\n      }\n      case 'last': {\n        value = findValuesBetween(options, firstValue.value, options.at(-1))\n        break\n      }\n    }\n\n    modelValue.value = value\n  }\n\n  return {\n    firstValue,\n    onSelectItem,\n    handleMultipleReplace,\n  }\n}\n","import type { MaybeElementRef } from '@vueuse/core'\nimport { unrefElement } from '@vueuse/core'\nimport { computed, onMounted, ref } from 'vue'\n\nexport function useSize(element: MaybeElementRef) {\n  const size = ref<{ width: number, height: number }>()\n  const width = computed(() => size.value?.width ?? 0)\n  const height = computed(() => size.value?.height ?? 0)\n\n  onMounted(() => {\n    const el = unrefElement(element) as HTMLElement\n    if (el) {\n      // provide size as early as possible\n      size.value = { width: el.offsetWidth, height: el.offsetHeight }\n\n      const resizeObserver = new ResizeObserver((entries) => {\n        if (!Array.isArray(entries))\n          return\n\n        // Since we only observe the one element, we don't need to loop over the\n        // array\n        if (!entries.length)\n          return\n\n        const entry = entries[0]\n        let width: number\n        let height: number\n\n        if ('borderBoxSize' in entry) {\n          const borderSizeEntry = entry.borderBoxSize\n          // iron out differences between browsers\n          const borderSize = Array.isArray(borderSizeEntry)\n            ? borderSizeEntry[0]\n            : borderSizeEntry\n          width = borderSize.inlineSize\n          height = borderSize.blockSize\n        }\n        else {\n          // for browsers that don't support `borderBoxSize`\n          // we calculate it ourselves to get the correct border box.\n          width = el.offsetWidth\n          height = el.offsetHeight\n        }\n\n        // temporary disable width/height from resize observer. borderSizeEntry seems to be incorrect\n        size.value = { width, height }\n      })\n\n      resizeObserver.observe(el, { box: 'border-box' })\n\n      return () => resizeObserver.unobserve(el)\n    }\n    else {\n      // We only want to reset to `undefined` when the element becomes `null`,\n      // not if it changes to another element.\n      size.value = undefined\n    }\n  })\n\n  return {\n    width,\n    height,\n  }\n}\n","import type { Ref } from 'vue'\nimport { ref } from 'vue'\n\ninterface Machine<S> {\n  [k: string]: { [k: string]: S }\n}\ntype MachineState<T> = keyof T\ntype MachineEvent<T> = keyof UnionToIntersection<T[keyof T]>\n\n// 🤯 https://fettblog.eu/typescript-union-to-intersection/\ntype UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (\n  x: infer R,\n) => any\n  ? R\n  : never\n\n/**\n * The `useStateMachine` function is a TypeScript function that creates a state machine and returns the\n * current state and a dispatch function to update the state based on events.\n * @param initialState - The `initialState` parameter is the initial state of the state machine. It\n * represents the starting point of the state machine's state.\n * @param machine - The `machine` parameter is an object that represents a state machine. It should\n * have keys that correspond to the possible states of the machine, and the values should be objects\n * that represent the possible events and their corresponding next states.\n * @returns The `useStateMachine` function returns an object with two properties: `state` and\n * `dispatch`.\n */\nexport function useStateMachine<M>(\n  initialState: MachineState<M>,\n  machine: M & Machine<MachineState<M>>,\n) {\n  const state = ref(initialState) as Ref<MachineState<M>>\n\n  function reducer(event: MachineEvent<M>) {\n    // @ts-expect-error  state.value is keyof M\n    const nextState = machine[state.value][event]\n    return nextState ?? state.value\n  }\n\n  const dispatch = (event: MachineEvent<M>) => {\n    state.value = reducer(event)\n  }\n\n  return {\n    state,\n    dispatch,\n  }\n}\n","import { refAutoReset } from '@vueuse/shared'\nimport { getActiveElement } from './getActiveElement'\n\nexport function useTypeahead(callback?: (search: string) => void) {\n  // Reset `search` 1 second after it was last updated\n  const search = refAutoReset('', 1000)\n\n  const handleTypeaheadSearch = (key: string, items: { ref: HTMLElement, value?: any }[]) => {\n    search.value = search.value + key\n\n    if (callback) {\n      callback(key)\n    }\n    else {\n      const currentItem = getActiveElement()\n      const itemsWithTextValue = items.map(item => ({\n        ...item,\n        textValue: item.value?.textValue ?? item.ref.textContent?.trim() ?? '',\n      }))\n      const currentMatch = itemsWithTextValue.find(item => item.ref === currentItem)\n      const values = itemsWithTextValue.map(item => item.textValue)\n      const nextMatch = getNextMatch(values, search.value, currentMatch?.textValue)\n\n      const newItem = itemsWithTextValue.find(item => item.textValue === nextMatch)\n\n      if (newItem)\n        (newItem.ref as HTMLElement).focus()\n      return newItem?.ref\n    }\n  }\n\n  const resetTypeahead = () => {\n    search.value = ''\n  }\n\n  return {\n    search,\n    handleTypeaheadSearch,\n    resetTypeahead,\n  }\n}\n\n/**\n * Wraps an array around itself at a given start index\n * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']`\n */\nexport function wrapArray<T>(array: T[], startIndex: number) {\n  return array.map((_, index) => array[(startIndex + index) % array.length])\n}\n\n/**\n * This is the \"meat\" of the typeahead matching logic. It takes in all the values,\n * the search and the current match, and returns the next match (or `undefined`).\n *\n * We normalize the search because if a user has repeatedly pressed a character,\n * we want the exact same behavior as if we only had that one character\n * (ie. cycle through options starting with that character)\n *\n * We also reorder the values by wrapping the array around the current match.\n * This is so we always look forward from the current match, and picking the first\n * match will always be the correct one.\n *\n * Finally, if the normalized search is exactly one character, we exclude the\n * current match from the values because otherwise it would be the first to match always\n * and focus would never move. This is as opposed to the regular case, where we\n * don't want focus to move if the current match still matches.\n */\nexport function getNextMatch(\n  values: string[],\n  search: string,\n  currentMatch?: string,\n) {\n  const isRepeated\n    = search.length > 1 && Array.from(search).every(char => char === search[0])\n  const normalizedSearch = isRepeated ? search[0] : search\n  const currentMatchIndex = currentMatch ? values.indexOf(currentMatch) : -1\n  let wrappedValues = wrapArray(values, Math.max(currentMatchIndex, 0))\n  const excludeCurrentMatch = normalizedSearch.length === 1\n  if (excludeCurrentMatch)\n    wrappedValues = wrappedValues.filter(v => v !== currentMatch)\n  const nextMatch = wrappedValues.find(value =>\n    value.toLowerCase().startsWith(normalizedSearch.toLowerCase()),\n  )\n  return nextMatch !== currentMatch ? nextMatch : undefined\n}\n","import type { ComponentOptionsBase, DefineComponent, VNodeProps } from 'vue'\nimport type { ComponentProps } from 'vue-component-type-helpers'\nimport { h, mergeProps } from 'vue'\nimport { useForwardExpose } from './useForwardExpose'\n\n// TODO: TEST\n\n// From vue next\n// https://github.com/vuejs/core/blob/1f2a652a9d2e3bec472fb1786a4c16d6ccfa1fb1/packages/runtime-core/src/h.ts#L53-L58\ntype RawProps = VNodeProps & {\n  // used to differ from a single VNode object as children\n  __v_isVNode?: never\n  // used to differ from Array children\n  [Symbol.iterator]?: never\n} & Record<string, any>\n\n// types inspired from vue-test-utils\n// https://github.com/vuejs/test-utils/blob/main/src/mount.ts#L36\ninterface MountingOptions<Props> {\n  /**\n   * Default props for the component\n   */\n  props?: (RawProps & Props) | ({} extends Props ? null : never) | ((attrs: Record<string, any>) => (RawProps & Props))\n  /**\n   * Pass attributes into the component\n   */\n  attrs?: Record<string, unknown>\n}\n\nexport function withDefault<\n  T,\n  C = T extends ((...args: any) => any) | (new (...args: any) => any)\n    ? T\n    : T extends { props?: infer Props }\n      ? DefineComponent<\n        Props extends Readonly<(infer PropNames)[]> | (infer PropNames)[]\n          ? { [key in PropNames extends string ? PropNames : string]?: any }\n          : Props\n      >\n      : DefineComponent,\n  P extends ComponentProps<C> = ComponentProps<C>,\n>(\n  originalComponent: T,\n  options?: MountingOptions<P>,\n): T\n\nexport function withDefault<T extends ComponentOptionsBase<{}, {}, {}, any, any, any, any, any>>(WrappedComponent: T, options?: MountingOptions<any>) {\n  return ({\n    inheritAttrs: false,\n    name: `${WrappedComponent.__name ?? ''}Wrapper`,\n    setup(_, ctx) {\n      return () => {\n        const optionProps = typeof options?.props === 'function' ? options?.props(ctx.attrs) : options?.props\n        const { forwardRef } = useForwardExpose()\n\n        const mergedProps = mergeProps(optionProps, ctx.attrs)\n        return h(WrappedComponent, { ...mergedProps, ref: forwardRef }, ctx.slots)\n      }\n    },\n  }) as T\n}\n","","import type { Ref } from 'vue'\nimport { defaultWindow } from '@vueuse/core'\nimport { isClient } from '@vueuse/shared'\nimport { computed, nextTick, onUnmounted, ref, watch } from 'vue'\nimport { useStateMachine } from '@/shared'\n\nexport function usePresence(\n  present: Ref<boolean>,\n  node: Ref<HTMLElement | undefined>,\n) {\n  const stylesRef = ref<CSSStyleDeclaration>({} as any)\n  const prevAnimationNameRef = ref<string>('none')\n  const prevPresentRef = ref(present)\n  const initialState = present.value ? 'mounted' : 'unmounted'\n  let timeoutId: number | undefined\n  const ownerWindow = node.value?.ownerDocument.defaultView ?? defaultWindow\n\n  const { state, dispatch } = useStateMachine(initialState, {\n    mounted: {\n      UNMOUNT: 'unmounted',\n      ANIMATION_OUT: 'unmountSuspended',\n    },\n    unmountSuspended: {\n      MOUNT: 'mounted',\n      ANIMATION_END: 'unmounted',\n    },\n    unmounted: {\n      MOUNT: 'mounted',\n    },\n  })\n\n  const dispatchCustomEvent = (name: 'enter' | 'after-enter' | 'leave' | 'after-leave') => {\n    // We only dispatch this event because CustomEvent is not available in Node18\n    // https://github.com/unovue/reka-ui/issues/930\n    if (isClient) {\n      const customEvent = new CustomEvent(name, { bubbles: false, cancelable: false })\n      node.value?.dispatchEvent(customEvent)\n    }\n  }\n\n  watch(\n    present,\n    async (currentPresent, prevPresent) => {\n      const hasPresentChanged = prevPresent !== currentPresent\n      await nextTick()\n      if (hasPresentChanged) {\n        const prevAnimationName = prevAnimationNameRef.value\n        const currentAnimationName = getAnimationName(node.value)\n\n        if (currentPresent) {\n          dispatch('MOUNT')\n          dispatchCustomEvent('enter')\n          if (currentAnimationName === 'none')\n            dispatchCustomEvent('after-enter')\n        }\n        else if (\n          currentAnimationName === 'none' || currentAnimationName === 'undefined'\n          || stylesRef.value?.display === 'none'\n        ) {\n          // If there is no exit animation or the element is hidden, animations won't run\n          // so we unmount instantly rv\n          dispatch('UNMOUNT')\n          dispatchCustomEvent('leave')\n          dispatchCustomEvent('after-leave')\n        }\n        else {\n          /**\n           * When `present` changes to `false`, we check changes to animation-name to\n           * determine whether an animation has started. We chose this approach (reading\n           * computed styles) because there is no `animationrun` event and `animationstart`\n           * fires after `animation-delay` has expired which would be too late.\n           */\n          const isAnimating = prevAnimationName !== currentAnimationName\n          if (prevPresent && isAnimating) {\n            dispatch('ANIMATION_OUT')\n            dispatchCustomEvent('leave')\n          }\n          else {\n            dispatch('UNMOUNT')\n            dispatchCustomEvent('after-leave')\n          }\n        }\n      }\n    },\n    { immediate: true },\n  )\n\n  /**\n   * Triggering an ANIMATION_OUT during an ANIMATION_IN will fire an `animationcancel`\n   * event for ANIMATION_IN after we have entered `unmountSuspended` state. So, we\n   * make sure we only trigger ANIMATION_END for the currently active animation.\n   */\n  const handleAnimationEnd = (event: AnimationEvent) => {\n    const currentAnimationName = getAnimationName(node.value)\n    const isCurrentAnimation = currentAnimationName.includes(\n      CSS.escape(event.animationName),\n    )\n    const directionName = state.value === 'mounted' ? 'enter' : 'leave'\n    if (event.target === node.value && isCurrentAnimation) {\n      dispatchCustomEvent(`after-${directionName}`)\n      dispatch('ANIMATION_END')\n\n      if (!prevPresentRef.value) {\n        const currentFillMode = node.value.style.animationFillMode\n        node.value.style.animationFillMode = 'forwards'\n        // Reset the style after the node had time to unmount (for cases\n        // where the component chooses not to unmount). Doing this any\n        // sooner than `setTimeout` (e.g. with `requestAnimationFrame`)\n        // still causes a flash.\n        timeoutId = ownerWindow?.setTimeout(() => {\n          if (node.value?.style.animationFillMode === 'forwards') {\n            node.value.style.animationFillMode = currentFillMode\n          }\n        })\n      }\n    }\n    // if no animation, immediately trigger 'ANIMATION_END'\n    if (event.target === node.value && currentAnimationName === 'none')\n      dispatch('ANIMATION_END')\n  }\n  const handleAnimationStart = (event: AnimationEvent) => {\n    if (event.target === node.value) {\n      // if animation occurred, store its name as the previous animation.\n      prevAnimationNameRef.value = getAnimationName(node.value)\n    }\n  }\n\n  const watcher = watch(\n    node,\n    (newNode, oldNode) => {\n      if (newNode) {\n        stylesRef.value = getComputedStyle(newNode)\n        newNode.addEventListener('animationstart', handleAnimationStart)\n        newNode.addEventListener('animationcancel', handleAnimationEnd)\n        newNode.addEventListener('animationend', handleAnimationEnd)\n      }\n      else {\n        // Transition to the unmounted state if the node is removed prematurely.\n        // We avoid doing so during cleanup as the node may change but still exist.\n        dispatch('ANIMATION_END')\n\n        if (timeoutId !== undefined)\n          ownerWindow?.clearTimeout(timeoutId)\n        oldNode?.removeEventListener('animationstart', handleAnimationStart)\n        oldNode?.removeEventListener('animationcancel', handleAnimationEnd)\n        oldNode?.removeEventListener('animationend', handleAnimationEnd)\n      }\n    },\n    { immediate: true },\n  )\n\n  const stateWatcher = watch(state, () => {\n    const currentAnimationName = getAnimationName(node.value)\n    prevAnimationNameRef.value\n      = state.value === 'mounted' ? currentAnimationName : 'none'\n  })\n\n  onUnmounted(() => {\n    watcher()\n    stateWatcher()\n  })\n\n  const isPresent = computed(() =>\n    ['mounted', 'unmountSuspended'].includes(state.value),\n  )\n\n  return {\n    isPresent,\n  }\n}\n\nfunction getAnimationName(node?: HTMLElement) {\n  return node ? getComputedStyle(node).animationName || 'none' : 'none'\n}\n","import type {\n  SlotsType,\n  VNode,\n} from 'vue'\nimport { unrefElement } from '@vueuse/core'\nimport {\n  defineComponent,\n  getCurrentInstance,\n  h,\n  ref,\n  toRefs,\n} from 'vue'\nimport { renderSlotFragments } from '@/shared'\nimport { usePresence } from './usePresence'\n\nexport interface PresenceProps {\n  /**\n   * Conditional to mount or unmount the child element. Similar to `v-if`\n   *\n   * @required true\n   */\n  present: boolean\n  /**\n   * Force the element to render all the time.\n   *\n   * Useful for programmatically render grandchild component with the exposed `present`\n   *\n   * @defaultValue false\n   */\n  forceMount?: boolean\n}\n\nexport default defineComponent({\n  name: 'Presence',\n  props: {\n    present: {\n      type: Boolean,\n      required: true,\n    },\n    forceMount: {\n      type: Boolean,\n    },\n  },\n  slots: {} as SlotsType<{\n    default: (opts: { present: boolean }) => any\n  }>,\n  setup(props, { slots, expose }) {\n    const { present, forceMount } = toRefs(props)\n\n    const node = ref<HTMLElement>()\n    // Mount composables once to prevent duplicated eventListener\n    const { isPresent } = usePresence(present, node)\n    expose({ present: isPresent })\n\n    let children = slots.default({ present: isPresent.value })\n    children = renderSlotFragments(children || [])\n    const instance = getCurrentInstance()\n\n    if (children && children?.length > 1) {\n      const componentName = instance?.parent?.type.name\n        ? `<${instance.parent.type.name} />`\n        : 'component'\n\n      throw new Error(\n        [\n          `Detected an invalid children for \\`${componentName}\\` for  \\`Presence\\` component.`,\n          '',\n          'Note: Presence works similarly to `v-if` directly, but it waits for animation/transition to finished before unmounting. So it expect only one direct child of valid VNode type.',\n          'You can apply a few solutions:',\n          [\n            'Provide a single child element so that `presence` directive attach correctly.',\n            'Ensure the first child is an actual element instead of a raw text node or comment node.',\n          ]\n            .map(line => `  - ${line}`)\n            .join('\\n'),\n        ].join('\\n'),\n      )\n    }\n\n    return () => {\n      if (forceMount.value || present.value || isPresent.value) {\n        return h(slots.default({ present: isPresent.value })[0] as VNode, {\n          ref: (v) => {\n            const el = unrefElement(v as HTMLElement)\n            if (typeof el?.hasAttribute === 'undefined')\n              return el\n\n            // special case to handle animation for PopperContent\n            if (el?.hasAttribute('data-reka-popper-content-wrapper'))\n              node.value = el.firstElementChild as HTMLElement\n            else\n              node.value = el\n\n            return el\n          },\n        })\n      }\n      else { return null }\n    }\n  },\n})\n","import { cloneVNode, Comment, defineComponent, mergeProps } from 'vue'\nimport { renderSlotFragments } from '@/shared'\n\nexport const Slot = defineComponent({\n  name: 'PrimitiveSlot',\n  inheritAttrs: false,\n  setup(_, { attrs, slots }) {\n    return () => {\n      if (!slots.default)\n        return null\n\n      const children = renderSlotFragments(slots.default())\n      const firstNonCommentChildrenIndex = children.findIndex(child => child.type !== Comment)\n      if (firstNonCommentChildrenIndex === -1)\n        return children\n\n      const firstNonCommentChildren = children[firstNonCommentChildrenIndex]\n\n      // Remove props ref from being inferred\n      delete firstNonCommentChildren.props?.ref\n\n      // Manually merge props to ensure `firstNonCommentChildren.props`\n      // has higher priority than `attrs` and can override `attrs`.\n      // Otherwise `cloneVNode(firstNonCommentChildren, attrs)` will\n      // prioritize `attrs` and override `firstNonCommentChildren.props`.\n      const mergedProps = firstNonCommentChildren.props\n        ? mergeProps(attrs, firstNonCommentChildren.props)\n        : attrs\n      const cloned = cloneVNode({ ...firstNonCommentChildren, props: {} }, mergedProps)\n\n      if (children.length === 1)\n        return cloned\n\n      children[firstNonCommentChildrenIndex] = cloned\n      return children\n    }\n  },\n})\n","import type { Component, PropType } from 'vue'\nimport { defineComponent, h } from 'vue'\nimport { Slot } from './Slot'\n\nexport type AsTag\n  = | 'a'\n    | 'button'\n    | 'div'\n    | 'form'\n    | 'h2'\n    | 'h3'\n    | 'img'\n    | 'input'\n    | 'label'\n    | 'li'\n    | 'nav'\n    | 'ol'\n    | 'p'\n    | 'span'\n    | 'svg'\n    | 'ul'\n    | 'template'\n    | ({} & string) // any other string\n\nexport interface PrimitiveProps {\n  /**\n   * Change the default rendered element for the one passed as a child, merging their props and behavior.\n   *\n   * Read our [Composition](https://www.reka-ui.com/docs/guides/composition) guide for more details.\n   */\n  asChild?: boolean\n  /**\n   * The element or component this component should render as. Can be overwritten by `asChild`.\n   * @defaultValue \"div\"\n   */\n  as?: AsTag | Component\n}\n\n// For self closing tags, don't provide default slots because of hydration issue\nconst SELF_CLOSING_TAGS = ['area', 'img', 'input']\n\nexport const Primitive = defineComponent({\n  name: 'Primitive',\n  inheritAttrs: false,\n  props: {\n    asChild: {\n      type: Boolean,\n      default: false,\n    },\n    as: {\n      type: [String, Object] as PropType<AsTag | Component>,\n      default: 'div',\n    },\n  },\n  setup(props, { attrs, slots }) {\n    const asTag = props.asChild ? 'template' : props.as\n\n    if (typeof asTag === 'string' && SELF_CLOSING_TAGS.includes(asTag))\n      return () => h(asTag, attrs)\n\n    if (asTag !== 'template')\n      return () => h(props.as, attrs, { default: slots.default })\n\n    return () => h(Slot, attrs, { default: slots.default })\n  },\n})\n","import type { ComponentPublicInstance } from 'vue'\nimport { unrefElement } from '@vueuse/core'\nimport { computed, ref } from 'vue'\n\nexport function usePrimitiveElement<T extends ComponentPublicInstance>() {\n  const primitiveElement = ref<T>()\n  const currentElement = computed<HTMLElement>(() => ['#text', '#comment'].includes(primitiveElement.value?.$el.nodeName) ? primitiveElement.value?.$el.nextElementSibling : unrefElement(primitiveElement))\n\n  return {\n    primitiveElement,\n    currentElement,\n  }\n}\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { toRefs } from 'vue'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface CollapsibleRootProps extends PrimitiveProps {\n  /** The open state of the collapsible when it is initially rendered. <br> Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /** The controlled open state of the collapsible. Can be binded with `v-model`. */\n  open?: boolean\n  /** When `true`, prevents the user from interacting with the collapsible. */\n  disabled?: boolean\n  /** When `true`, the element will be unmounted on closed state. */\n  unmountOnHide?: boolean\n}\n\nexport type CollapsibleRootEmits = {\n  /** Event handler called when the open state of the collapsible changes. */\n  'update:open': [value: boolean]\n}\n\ninterface CollapsibleRootContext {\n  contentId: string\n  disabled?: Ref<boolean>\n  open: Ref<boolean>\n  unmountOnHide: Ref<boolean>\n  onOpenToggle: () => void\n}\n\nexport const [injectCollapsibleRootContext, provideCollapsibleRootContext]\n  = createContext<CollapsibleRootContext>('CollapsibleRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CollapsibleRootProps>(), {\n  open: undefined,\n  defaultOpen: false,\n  unmountOnHide: true,\n})\n\nconst emit = defineEmits<CollapsibleRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst { disabled, unmountOnHide } = toRefs(props)\n\nprovideCollapsibleRootContext({\n  contentId: '',\n  disabled,\n  open,\n  unmountOnHide,\n  onOpenToggle: () => {\n    if (disabled.value)\n      return\n\n    open.value = !open.value\n  },\n})\n\ndefineExpose({ open })\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"props.asChild\"\n    :data-state=\"open ? 'open' : 'closed'\"\n    :data-disabled=\"disabled ? '' : undefined\"\n  >\n    <slot :open=\"open\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { toRefs } from 'vue'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface CollapsibleRootProps extends PrimitiveProps {\n  /** The open state of the collapsible when it is initially rendered. <br> Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /** The controlled open state of the collapsible. Can be binded with `v-model`. */\n  open?: boolean\n  /** When `true`, prevents the user from interacting with the collapsible. */\n  disabled?: boolean\n  /** When `true`, the element will be unmounted on closed state. */\n  unmountOnHide?: boolean\n}\n\nexport type CollapsibleRootEmits = {\n  /** Event handler called when the open state of the collapsible changes. */\n  'update:open': [value: boolean]\n}\n\ninterface CollapsibleRootContext {\n  contentId: string\n  disabled?: Ref<boolean>\n  open: Ref<boolean>\n  unmountOnHide: Ref<boolean>\n  onOpenToggle: () => void\n}\n\nexport const [injectCollapsibleRootContext, provideCollapsibleRootContext]\n  = createContext<CollapsibleRootContext>('CollapsibleRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CollapsibleRootProps>(), {\n  open: undefined,\n  defaultOpen: false,\n  unmountOnHide: true,\n})\n\nconst emit = defineEmits<CollapsibleRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst { disabled, unmountOnHide } = toRefs(props)\n\nprovideCollapsibleRootContext({\n  contentId: '',\n  disabled,\n  open,\n  unmountOnHide,\n  onOpenToggle: () => {\n    if (disabled.value)\n      return\n\n    open.value = !open.value\n  },\n})\n\ndefineExpose({ open })\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"props.asChild\"\n    :data-state=\"open ? 'open' : 'closed'\"\n    :data-disabled=\"disabled ? '' : undefined\"\n  >\n    <slot :open=\"open\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CollapsibleContentProps extends PrimitiveProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n\nexport type CollapsibleContentEmits = {\n  contentFound: [void]\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener } from '@vueuse/core'\nimport { computed, nextTick, onMounted, ref, watch } from 'vue'\nimport { Presence } from '@/Presence'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { useForwardExpose, useId } from '@/shared'\nimport { injectCollapsibleRootContext } from './CollapsibleRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<CollapsibleContentProps>()\nconst emits = defineEmits<CollapsibleContentEmits>()\n\nconst rootContext = injectCollapsibleRootContext()\nrootContext.contentId ||= useId(undefined, 'reka-collapsible-content')\n\nconst presentRef = ref<InstanceType<typeof Presence>>()\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst width = ref(0)\nconst height = ref(0)\n\n// when opening we want it to immediately open to retrieve dimensions\n// when closing we delay `present` to retrieve dimensions before closing\nconst isOpen = computed(() => rootContext.open.value)\nconst isMountAnimationPrevented = ref(isOpen.value)\nconst currentStyle = ref<Record<string, string>>()\n\nwatch(\n  () => [isOpen.value, presentRef.value?.present],\n  async () => {\n    await nextTick()\n    const node = currentElement.value\n    if (!node)\n      return\n    currentStyle.value = currentStyle.value || {\n      transitionDuration: node.style.transitionDuration,\n      animationName: node.style.animationName,\n    }\n    // block any animations/transitions so the element renders at its full dimensions\n    node.style.transitionDuration = '0s'\n    node.style.animationName = 'none'\n\n    // get width and height from full dimensions\n    const rect = node.getBoundingClientRect()\n    height.value = rect.height\n    width.value = rect.width\n\n    // kick off any animations/transitions that were originally set up if it isn't the initial mount\n    if (!isMountAnimationPrevented.value) {\n      node.style.transitionDuration = currentStyle.value.transitionDuration\n      node.style.animationName = currentStyle.value.animationName\n    }\n  },\n  {\n    immediate: true,\n  },\n)\n\nconst skipAnimation = computed(() => isMountAnimationPrevented.value && rootContext.open.value)\n\nonMounted(() => {\n  requestAnimationFrame(() => {\n    isMountAnimationPrevented.value = false\n  })\n})\n\nuseEventListener(currentElement, 'beforematch', (ev) => {\n  requestAnimationFrame(() => {\n    rootContext.onOpenToggle()\n    emits('contentFound')\n  })\n})\n</script>\n\n<template>\n  <Presence\n    v-slot=\"{ present }\"\n    ref=\"presentRef\"\n    :present=\"forceMount || rootContext.open.value\"\n    :force-mount=\"true\"\n  >\n    <Primitive\n      v-bind=\"$attrs\"\n      :id=\"rootContext.contentId\"\n      :ref=\"forwardRef\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n      :hidden=\"!present ? rootContext.unmountOnHide.value ? '' : 'until-found' : undefined\"\n      :data-state=\"skipAnimation ? undefined : rootContext.open.value ? 'open' : 'closed'\"\n      :data-disabled=\"rootContext.disabled?.value ? '' : undefined\"\n      :style=\"{\n        [`--reka-collapsible-content-height`]: `${height}px`,\n        [`--reka-collapsible-content-width`]: `${width}px`,\n      }\"\n    >\n      <slot v-if=\"rootContext.unmountOnHide.value ? present : true\" />\n    </Primitive>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CollapsibleContentProps extends PrimitiveProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n\nexport type CollapsibleContentEmits = {\n  contentFound: [void]\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener } from '@vueuse/core'\nimport { computed, nextTick, onMounted, ref, watch } from 'vue'\nimport { Presence } from '@/Presence'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { useForwardExpose, useId } from '@/shared'\nimport { injectCollapsibleRootContext } from './CollapsibleRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<CollapsibleContentProps>()\nconst emits = defineEmits<CollapsibleContentEmits>()\n\nconst rootContext = injectCollapsibleRootContext()\nrootContext.contentId ||= useId(undefined, 'reka-collapsible-content')\n\nconst presentRef = ref<InstanceType<typeof Presence>>()\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst width = ref(0)\nconst height = ref(0)\n\n// when opening we want it to immediately open to retrieve dimensions\n// when closing we delay `present` to retrieve dimensions before closing\nconst isOpen = computed(() => rootContext.open.value)\nconst isMountAnimationPrevented = ref(isOpen.value)\nconst currentStyle = ref<Record<string, string>>()\n\nwatch(\n  () => [isOpen.value, presentRef.value?.present],\n  async () => {\n    await nextTick()\n    const node = currentElement.value\n    if (!node)\n      return\n    currentStyle.value = currentStyle.value || {\n      transitionDuration: node.style.transitionDuration,\n      animationName: node.style.animationName,\n    }\n    // block any animations/transitions so the element renders at its full dimensions\n    node.style.transitionDuration = '0s'\n    node.style.animationName = 'none'\n\n    // get width and height from full dimensions\n    const rect = node.getBoundingClientRect()\n    height.value = rect.height\n    width.value = rect.width\n\n    // kick off any animations/transitions that were originally set up if it isn't the initial mount\n    if (!isMountAnimationPrevented.value) {\n      node.style.transitionDuration = currentStyle.value.transitionDuration\n      node.style.animationName = currentStyle.value.animationName\n    }\n  },\n  {\n    immediate: true,\n  },\n)\n\nconst skipAnimation = computed(() => isMountAnimationPrevented.value && rootContext.open.value)\n\nonMounted(() => {\n  requestAnimationFrame(() => {\n    isMountAnimationPrevented.value = false\n  })\n})\n\nuseEventListener(currentElement, 'beforematch', (ev) => {\n  requestAnimationFrame(() => {\n    rootContext.onOpenToggle()\n    emits('contentFound')\n  })\n})\n</script>\n\n<template>\n  <Presence\n    v-slot=\"{ present }\"\n    ref=\"presentRef\"\n    :present=\"forceMount || rootContext.open.value\"\n    :force-mount=\"true\"\n  >\n    <Primitive\n      v-bind=\"$attrs\"\n      :id=\"rootContext.contentId\"\n      :ref=\"forwardRef\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n      :hidden=\"!present ? rootContext.unmountOnHide.value ? '' : 'until-found' : undefined\"\n      :data-state=\"skipAnimation ? undefined : rootContext.open.value ? 'open' : 'closed'\"\n      :data-disabled=\"rootContext.disabled?.value ? '' : undefined\"\n      :style=\"{\n        [`--reka-collapsible-content-height`]: `${height}px`,\n        [`--reka-collapsible-content-width`]: `${width}px`,\n      }\"\n    >\n      <slot v-if=\"rootContext.unmountOnHide.value ? present : true\" />\n    </Primitive>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface CollapsibleTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectCollapsibleRootContext } from './CollapsibleRoot.vue'\n\nconst props = withDefaults(defineProps<CollapsibleTriggerProps>(), {\n  as: 'button',\n})\n\nuseForwardExpose()\nconst rootContext = injectCollapsibleRootContext()\n</script>\n\n<template>\n  <Primitive\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :as=\"as\"\n    :as-child=\"props.asChild\"\n    :aria-controls=\"rootContext.contentId\"\n    :aria-expanded=\"rootContext.open.value\"\n    :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n    :data-disabled=\"rootContext.disabled?.value ? '' : undefined\"\n    :disabled=\"rootContext.disabled?.value\"\n    @click=\"rootContext.onOpenToggle\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface CollapsibleTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectCollapsibleRootContext } from './CollapsibleRoot.vue'\n\nconst props = withDefaults(defineProps<CollapsibleTriggerProps>(), {\n  as: 'button',\n})\n\nuseForwardExpose()\nconst rootContext = injectCollapsibleRootContext()\n</script>\n\n<template>\n  <Primitive\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :as=\"as\"\n    :as-child=\"props.asChild\"\n    :aria-controls=\"rootContext.contentId\"\n    :aria-expanded=\"rootContext.open.value\"\n    :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n    :data-disabled=\"rootContext.disabled?.value ? '' : undefined\"\n    :disabled=\"rootContext.disabled?.value\"\n    @click=\"rootContext.onOpenToggle\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","import type { Ref } from 'vue'\nimport type { AcceptableValue, SingleOrMultipleProps } from './types'\nimport { useVModel } from '@vueuse/core'\nimport { isEqual } from 'ohash'\nimport { computed } from 'vue'\nimport { isValueEqualOrExist } from './isValueEqualOrExist'\n\n/**\n * Validates the props and it makes sure that the types are coherent with each other\n *\n * 1. If type, defaultValue, and modelValue are all undefined, throw an error.\n * 2. If modelValue and defaultValue are defined and not of the same type, throw an error.\n * 3. If type is defined:\n *    a. If type is 'single' and either modelValue or defaultValue is an array, log an error and return 'multiple'.\n *    b. If type is 'multiple' and neither modelValue nor defaultValue is an array, log an error and return 'single'.\n * 4. Return 'multiple' if modelValue is an array, else return 'single'.\n */\nfunction validateProps({ type, defaultValue, modelValue }: SingleOrMultipleProps) {\n  const value = modelValue || defaultValue\n  const canTypeBeInferred = modelValue !== undefined || defaultValue !== undefined\n\n  if (canTypeBeInferred)\n    return Array.isArray(value) ? 'multiple' : 'single'\n  else\n    return type ?? 'single' // always fallback to `single`\n}\n\nfunction getDefaultType({ type, defaultValue, modelValue }: SingleOrMultipleProps) {\n  if (type)\n    return type\n\n  return validateProps({ type, defaultValue, modelValue })\n}\n\nfunction getDefaultValue({ type, defaultValue }: SingleOrMultipleProps) {\n  if (defaultValue !== undefined)\n    return defaultValue\n\n  return (type === 'single') ? undefined : []\n}\n\nexport function useSingleOrMultipleValue<P extends SingleOrMultipleProps, Name extends string>(\n  props: P,\n  emits: (name: Name, ...args: any[]) => void,\n) {\n  const type = computed(() => getDefaultType(props))\n  const modelValue = useVModel(props, 'modelValue', emits, {\n    defaultValue: getDefaultValue(props),\n    passive: (props.modelValue === undefined) as false,\n    deep: true,\n  }) as Ref<AcceptableValue | AcceptableValue[] | undefined>\n\n  function changeModelValue(value: AcceptableValue) {\n    if (type.value === 'single') {\n      modelValue.value = isEqual(value, modelValue.value) ? undefined : value\n    }\n    else {\n      const modelValueArray = Array.isArray(modelValue.value) ? [...(modelValue.value as AcceptableValue[] || [])] : [modelValue.value].filter(Boolean)\n      if (isValueEqualOrExist(modelValueArray, value)) {\n        const index = modelValueArray.findIndex(i => isEqual(i, value))\n        modelValueArray.splice(index, 1)\n      }\n      else {\n        modelValueArray.push(value)\n      }\n      modelValue.value = modelValueArray\n    }\n  }\n\n  const isSingle = computed(() => type.value === 'single')\n\n  return {\n    modelValue,\n    changeModelValue,\n    isSingle,\n  }\n}\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue, DataOrientation, Direction, SingleOrMultipleProps, SingleOrMultipleType } from '@/shared/types'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\nexport interface AccordionRootProps<T = string | string[]>\n  extends PrimitiveProps, SingleOrMultipleProps<T> {\n  /**\n   * When type is \"single\", allows closing content when clicking trigger for an open item.\n   * When type is \"multiple\", this prop has no effect.\n   *\n   * @defaultValue false\n   */\n  collapsible?: boolean\n\n  /**\n   * When `true`, prevents the user from interacting with the accordion and all its items\n   *\n   * @defaultValue false\n   */\n  disabled?: boolean\n\n  /**\n   * The reading direction of the accordion when applicable. If omitted, assumes LTR (left-to-right) reading mode.\n   *\n   * @defaultValue \"ltr\"\n   */\n  dir?: Direction\n\n  /**\n   * The orientation of the accordion.\n   *\n   * @defaultValue \"vertical\"\n   */\n  orientation?: DataOrientation\n\n  /**\n   * When `true`, the element will be unmounted on closed state.\n   *\n   * @defaultValue `true`\n   */\n  unmountOnHide?: boolean\n}\n\nexport type AccordionRootEmits<T extends SingleOrMultipleType = SingleOrMultipleType> = {\n  /**\n   * Event handler called when the expanded state of an item changes\n   */\n  'update:modelValue': [value: (T extends 'single' ? string : string[]) | undefined]\n}\n\nexport type AccordionRootContext<P extends AccordionRootProps> = {\n  disabled: Ref<P['disabled']>\n  direction: Ref<P['dir']>\n  orientation: P['orientation']\n  parentElement: Ref<HTMLElement | undefined>\n  changeModelValue: (value: string) => void\n  isSingle: ComputedRef<boolean>\n  modelValue: Ref<AcceptableValue | AcceptableValue[] | undefined>\n  collapsible: boolean\n  unmountOnHide: Ref<boolean>\n}\n\nexport const [injectAccordionRootContext, provideAccordionRootContext]\n  = createContext<AccordionRootContext<AccordionRootProps>>('AccordionRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends (string | string[]), ExplicitType extends SingleOrMultipleType\">\nimport { toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useSingleOrMultipleValue } from '@/shared/useSingleOrMultipleValue'\n\nconst props = withDefaults(defineProps<AccordionRootProps<T>>(), {\n  disabled: false,\n  orientation: 'vertical',\n  collapsible: false,\n  unmountOnHide: true,\n})\n\nconst emits = defineEmits<AccordionRootEmits<ExplicitType>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current active value */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { dir, disabled, unmountOnHide } = toRefs(props)\nconst direction = useDirection(dir)\n\nconst { modelValue, changeModelValue, isSingle } = useSingleOrMultipleValue(props, emits)\n\nconst { forwardRef, currentElement: parentElement } = useForwardExpose()\n\nprovideAccordionRootContext({\n  disabled,\n  direction,\n  orientation: props.orientation,\n  parentElement,\n  isSingle,\n  collapsible: props.collapsible,\n  modelValue,\n  changeModelValue,\n  unmountOnHide,\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n  >\n    <slot :model-value=\"modelValue\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue, DataOrientation, Direction, SingleOrMultipleProps, SingleOrMultipleType } from '@/shared/types'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\nexport interface AccordionRootProps<T = string | string[]>\n  extends PrimitiveProps, SingleOrMultipleProps<T> {\n  /**\n   * When type is \"single\", allows closing content when clicking trigger for an open item.\n   * When type is \"multiple\", this prop has no effect.\n   *\n   * @defaultValue false\n   */\n  collapsible?: boolean\n\n  /**\n   * When `true`, prevents the user from interacting with the accordion and all its items\n   *\n   * @defaultValue false\n   */\n  disabled?: boolean\n\n  /**\n   * The reading direction of the accordion when applicable. If omitted, assumes LTR (left-to-right) reading mode.\n   *\n   * @defaultValue \"ltr\"\n   */\n  dir?: Direction\n\n  /**\n   * The orientation of the accordion.\n   *\n   * @defaultValue \"vertical\"\n   */\n  orientation?: DataOrientation\n\n  /**\n   * When `true`, the element will be unmounted on closed state.\n   *\n   * @defaultValue `true`\n   */\n  unmountOnHide?: boolean\n}\n\nexport type AccordionRootEmits<T extends SingleOrMultipleType = SingleOrMultipleType> = {\n  /**\n   * Event handler called when the expanded state of an item changes\n   */\n  'update:modelValue': [value: (T extends 'single' ? string : string[]) | undefined]\n}\n\nexport type AccordionRootContext<P extends AccordionRootProps> = {\n  disabled: Ref<P['disabled']>\n  direction: Ref<P['dir']>\n  orientation: P['orientation']\n  parentElement: Ref<HTMLElement | undefined>\n  changeModelValue: (value: string) => void\n  isSingle: ComputedRef<boolean>\n  modelValue: Ref<AcceptableValue | AcceptableValue[] | undefined>\n  collapsible: boolean\n  unmountOnHide: Ref<boolean>\n}\n\nexport const [injectAccordionRootContext, provideAccordionRootContext]\n  = createContext<AccordionRootContext<AccordionRootProps>>('AccordionRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends (string | string[]), ExplicitType extends SingleOrMultipleType\">\nimport { toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useSingleOrMultipleValue } from '@/shared/useSingleOrMultipleValue'\n\nconst props = withDefaults(defineProps<AccordionRootProps<T>>(), {\n  disabled: false,\n  orientation: 'vertical',\n  collapsible: false,\n  unmountOnHide: true,\n})\n\nconst emits = defineEmits<AccordionRootEmits<ExplicitType>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current active value */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { dir, disabled, unmountOnHide } = toRefs(props)\nconst direction = useDirection(dir)\n\nconst { modelValue, changeModelValue, isSingle } = useSingleOrMultipleValue(props, emits)\n\nconst { forwardRef, currentElement: parentElement } = useForwardExpose()\n\nprovideAccordionRootContext({\n  disabled,\n  direction,\n  orientation: props.orientation,\n  parentElement,\n  isSingle,\n  collapsible: props.collapsible,\n  modelValue,\n  changeModelValue,\n  unmountOnHide,\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n  >\n    <slot :model-value=\"modelValue\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, VNodeRef } from 'vue'\nimport type { CollapsibleRootProps } from '../Collapsible'\nimport { createContext, useArrowNavigation, useForwardExpose } from '@/shared'\nimport { injectAccordionRootContext } from './AccordionRoot.vue'\n\nenum AccordionItemState {\n  Open = 'open',\n  Closed = 'closed',\n}\n\nexport interface AccordionItemProps\n  extends Omit<CollapsibleRootProps, 'open' | 'defaultOpen' | 'onOpenChange'> {\n  /**\n   * Whether or not an accordion item is disabled from user interaction.\n   * When `true`, prevents the user from interacting with the item.\n   *\n   * @defaultValue false\n   */\n  disabled?: boolean\n  /**\n   * A string value for the accordion item. All items within an accordion should use a unique value.\n   */\n  value: string\n}\n\ninterface AccordionItemContext {\n  open: ComputedRef<boolean>\n  dataState: ComputedRef<AccordionItemState>\n  disabled: ComputedRef<boolean>\n  dataDisabled: ComputedRef<'' | undefined>\n  triggerId: string\n  currentRef: VNodeRef\n  currentElement: ComputedRef<HTMLElement | undefined>\n  value: ComputedRef<string>\n}\n\nexport const [injectAccordionItemContext, provideAccordionItemContext]\n  = createContext<AccordionItemContext>('AccordionItem')\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { CollapsibleRoot } from '@/Collapsible'\n\nconst props = withDefaults(\n  defineProps<AccordionItemProps>(),\n  {\n    unmountOnHide: undefined,\n  },\n)\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nconst rootContext = injectAccordionRootContext()\n\nconst open = computed(() =>\n  rootContext.isSingle.value\n    ? props.value === rootContext.modelValue.value\n    : Array.isArray(rootContext.modelValue.value)\n      && rootContext.modelValue.value.includes(props.value),\n)\n\nconst disabled = computed(() => {\n  return (rootContext.disabled.value || props.disabled)\n})\n\nconst dataDisabled = computed(() => (disabled.value ? '' : undefined))\n\nconst dataState = computed(() =>\n  open.value ? AccordionItemState.Open : AccordionItemState.Closed,\n)\n\ndefineExpose({ open, dataDisabled })\nconst { currentRef, currentElement } = useForwardExpose()\n\nprovideAccordionItemContext({\n  open,\n  dataState,\n  disabled,\n  dataDisabled,\n  triggerId: '',\n  currentRef,\n  currentElement,\n  value: computed(() => props.value),\n})\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  const target = e.target as HTMLElement\n  const allCollectionItems: HTMLElement[] = Array.from(rootContext.parentElement.value?.querySelectorAll('[data-reka-collection-item]') ?? [])\n\n  const collectionItemIndex = allCollectionItems.findIndex(item => item === target)\n  if (collectionItemIndex === -1)\n    return null\n\n  useArrowNavigation(\n    e,\n    target,\n    rootContext.parentElement.value!,\n    {\n      arrowKeyOptions: rootContext.orientation,\n      dir: rootContext.direction.value,\n      focus: true,\n    },\n  )\n}\n</script>\n\n<template>\n  <CollapsibleRoot\n    :data-orientation=\"rootContext.orientation\"\n    :data-disabled=\"dataDisabled\"\n    :data-state=\"dataState\"\n    :disabled=\"disabled\"\n    :open=\"open\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :unmount-on-hide=\"props.unmountOnHide ?? rootContext.unmountOnHide.value\"\n    @keydown.up.down.left.right.home.end=\"handleArrowKey\"\n  >\n    <slot :open=\"open\" />\n  </CollapsibleRoot>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, VNodeRef } from 'vue'\nimport type { CollapsibleRootProps } from '../Collapsible'\nimport { createContext, useArrowNavigation, useForwardExpose } from '@/shared'\nimport { injectAccordionRootContext } from './AccordionRoot.vue'\n\nenum AccordionItemState {\n  Open = 'open',\n  Closed = 'closed',\n}\n\nexport interface AccordionItemProps\n  extends Omit<CollapsibleRootProps, 'open' | 'defaultOpen' | 'onOpenChange'> {\n  /**\n   * Whether or not an accordion item is disabled from user interaction.\n   * When `true`, prevents the user from interacting with the item.\n   *\n   * @defaultValue false\n   */\n  disabled?: boolean\n  /**\n   * A string value for the accordion item. All items within an accordion should use a unique value.\n   */\n  value: string\n}\n\ninterface AccordionItemContext {\n  open: ComputedRef<boolean>\n  dataState: ComputedRef<AccordionItemState>\n  disabled: ComputedRef<boolean>\n  dataDisabled: ComputedRef<'' | undefined>\n  triggerId: string\n  currentRef: VNodeRef\n  currentElement: ComputedRef<HTMLElement | undefined>\n  value: ComputedRef<string>\n}\n\nexport const [injectAccordionItemContext, provideAccordionItemContext]\n  = createContext<AccordionItemContext>('AccordionItem')\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { CollapsibleRoot } from '@/Collapsible'\n\nconst props = withDefaults(\n  defineProps<AccordionItemProps>(),\n  {\n    unmountOnHide: undefined,\n  },\n)\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nconst rootContext = injectAccordionRootContext()\n\nconst open = computed(() =>\n  rootContext.isSingle.value\n    ? props.value === rootContext.modelValue.value\n    : Array.isArray(rootContext.modelValue.value)\n      && rootContext.modelValue.value.includes(props.value),\n)\n\nconst disabled = computed(() => {\n  return (rootContext.disabled.value || props.disabled)\n})\n\nconst dataDisabled = computed(() => (disabled.value ? '' : undefined))\n\nconst dataState = computed(() =>\n  open.value ? AccordionItemState.Open : AccordionItemState.Closed,\n)\n\ndefineExpose({ open, dataDisabled })\nconst { currentRef, currentElement } = useForwardExpose()\n\nprovideAccordionItemContext({\n  open,\n  dataState,\n  disabled,\n  dataDisabled,\n  triggerId: '',\n  currentRef,\n  currentElement,\n  value: computed(() => props.value),\n})\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  const target = e.target as HTMLElement\n  const allCollectionItems: HTMLElement[] = Array.from(rootContext.parentElement.value?.querySelectorAll('[data-reka-collection-item]') ?? [])\n\n  const collectionItemIndex = allCollectionItems.findIndex(item => item === target)\n  if (collectionItemIndex === -1)\n    return null\n\n  useArrowNavigation(\n    e,\n    target,\n    rootContext.parentElement.value!,\n    {\n      arrowKeyOptions: rootContext.orientation,\n      dir: rootContext.direction.value,\n      focus: true,\n    },\n  )\n}\n</script>\n\n<template>\n  <CollapsibleRoot\n    :data-orientation=\"rootContext.orientation\"\n    :data-disabled=\"dataDisabled\"\n    :data-state=\"dataState\"\n    :disabled=\"disabled\"\n    :open=\"open\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :unmount-on-hide=\"props.unmountOnHide ?? rootContext.unmountOnHide.value\"\n    @keydown.up.down.left.right.home.end=\"handleArrowKey\"\n  >\n    <slot :open=\"open\" />\n  </CollapsibleRoot>\n</template>\n","<script lang=\"ts\">\nimport type { CollapsibleContentProps } from '../Collapsible'\n\nexport interface AccordionContentProps extends CollapsibleContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useForwardExpose } from '@/shared'\nimport { CollapsibleContent } from '../Collapsible'\nimport { injectAccordionItemContext } from './AccordionItem.vue'\nimport { injectAccordionRootContext } from './AccordionRoot.vue'\n\nconst props = defineProps<AccordionContentProps>()\n\nconst rootContext = injectAccordionRootContext()\nconst itemContext = injectAccordionItemContext()\n\nuseForwardExpose()\n</script>\n\n<template>\n  <CollapsibleContent\n    role=\"region\"\n    :as-child=\"props.asChild\"\n    :as=\"as\"\n    :force-mount=\"props.forceMount\"\n    :aria-labelledby=\"itemContext.triggerId\"\n    :data-state=\"itemContext.dataState.value\"\n    :data-disabled=\"itemContext.dataDisabled.value\"\n    :data-orientation=\"rootContext.orientation\"\n    style=\"\n      --reka-accordion-content-width: var(--reka-collapsible-content-width);\n      --reka-accordion-content-height: var(--reka-collapsible-content-height);\n    \"\n    @content-found=\"rootContext.changeModelValue(itemContext.value.value)\"\n  >\n    <slot />\n  </CollapsibleContent>\n</template>\n","<script lang=\"ts\">\nimport type { CollapsibleContentProps } from '../Collapsible'\n\nexport interface AccordionContentProps extends CollapsibleContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useForwardExpose } from '@/shared'\nimport { CollapsibleContent } from '../Collapsible'\nimport { injectAccordionItemContext } from './AccordionItem.vue'\nimport { injectAccordionRootContext } from './AccordionRoot.vue'\n\nconst props = defineProps<AccordionContentProps>()\n\nconst rootContext = injectAccordionRootContext()\nconst itemContext = injectAccordionItemContext()\n\nuseForwardExpose()\n</script>\n\n<template>\n  <CollapsibleContent\n    role=\"region\"\n    :as-child=\"props.asChild\"\n    :as=\"as\"\n    :force-mount=\"props.forceMount\"\n    :aria-labelledby=\"itemContext.triggerId\"\n    :data-state=\"itemContext.dataState.value\"\n    :data-disabled=\"itemContext.dataDisabled.value\"\n    :data-orientation=\"rootContext.orientation\"\n    style=\"\n      --reka-accordion-content-width: var(--reka-collapsible-content-width);\n      --reka-accordion-content-height: var(--reka-collapsible-content-height);\n    \"\n    @content-found=\"rootContext.changeModelValue(itemContext.value.value)\"\n  >\n    <slot />\n  </CollapsibleContent>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface AccordionHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectAccordionItemContext } from './AccordionItem.vue'\nimport { injectAccordionRootContext } from './AccordionRoot.vue'\n\nconst props = withDefaults(defineProps<AccordionHeaderProps>(), {\n  as: 'h3',\n})\n\nconst rootContext = injectAccordionRootContext()\nconst itemContext = injectAccordionItemContext()\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :data-orientation=\"rootContext.orientation\"\n    :data-state=\"itemContext.dataState.value\"\n    :data-disabled=\"itemContext.dataDisabled.value\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface AccordionHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectAccordionItemContext } from './AccordionItem.vue'\nimport { injectAccordionRootContext } from './AccordionRoot.vue'\n\nconst props = withDefaults(defineProps<AccordionHeaderProps>(), {\n  as: 'h3',\n})\n\nconst rootContext = injectAccordionRootContext()\nconst itemContext = injectAccordionItemContext()\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :data-orientation=\"rootContext.orientation\"\n    :data-state=\"itemContext.dataState.value\"\n    :data-disabled=\"itemContext.dataDisabled.value\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface AccordionTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { CollapsibleTrigger } from '@/Collapsible'\nimport { useId } from '@/shared'\nimport { injectAccordionItemContext } from './AccordionItem.vue'\n\nimport { injectAccordionRootContext } from './AccordionRoot.vue'\n\nconst props = defineProps<AccordionTriggerProps>()\n\nconst rootContext = injectAccordionRootContext()\nconst itemContext = injectAccordionItemContext()\n\nitemContext.triggerId ||= useId(undefined, 'reka-accordion-trigger')\nfunction changeItem() {\n  const triggerDisabled = rootContext.isSingle.value && itemContext.open.value && !rootContext.collapsible\n  if (itemContext.disabled.value || triggerDisabled)\n    return\n\n  rootContext.changeModelValue(itemContext.value.value)\n}\n</script>\n\n<template>\n  <CollapsibleTrigger\n    :id=\"itemContext.triggerId\"\n    :ref=\"itemContext.currentRef\"\n    data-reka-collection-item\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :aria-disabled=\"itemContext.disabled.value || undefined\"\n    :aria-expanded=\"itemContext.open.value || false\"\n    :data-disabled=\"itemContext.dataDisabled.value\"\n    :data-orientation=\"rootContext.orientation\"\n    :data-state=\"itemContext.dataState.value\"\n    :disabled=\"itemContext.disabled.value\"\n    @click=\"changeItem\"\n  >\n    <slot />\n  </CollapsibleTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface AccordionTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { CollapsibleTrigger } from '@/Collapsible'\nimport { useId } from '@/shared'\nimport { injectAccordionItemContext } from './AccordionItem.vue'\n\nimport { injectAccordionRootContext } from './AccordionRoot.vue'\n\nconst props = defineProps<AccordionTriggerProps>()\n\nconst rootContext = injectAccordionRootContext()\nconst itemContext = injectAccordionItemContext()\n\nitemContext.triggerId ||= useId(undefined, 'reka-accordion-trigger')\nfunction changeItem() {\n  const triggerDisabled = rootContext.isSingle.value && itemContext.open.value && !rootContext.collapsible\n  if (itemContext.disabled.value || triggerDisabled)\n    return\n\n  rootContext.changeModelValue(itemContext.value.value)\n}\n</script>\n\n<template>\n  <CollapsibleTrigger\n    :id=\"itemContext.triggerId\"\n    :ref=\"itemContext.currentRef\"\n    data-reka-collection-item\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :aria-disabled=\"itemContext.disabled.value || undefined\"\n    :aria-expanded=\"itemContext.open.value || false\"\n    :data-disabled=\"itemContext.dataDisabled.value\"\n    :data-orientation=\"rootContext.orientation\"\n    :data-state=\"itemContext.dataState.value\"\n    :disabled=\"itemContext.disabled.value\"\n    @click=\"changeItem\"\n  >\n    <slot />\n  </CollapsibleTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { createContext } from '@/shared'\n\nexport interface DialogRootProps {\n  /** The controlled open state of the dialog. Can be binded as `v-model:open`. */\n  open?: boolean\n  /** The open state of the dialog when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /**\n   * The modality of the dialog When set to `true`, <br>\n   * interaction with outside elements will be disabled and only dialog content will be visible to screen readers.\n   */\n  modal?: boolean\n}\n\nexport type DialogRootEmits = {\n  /** Event handler called when the open state of the dialog changes. */\n  'update:open': [value: boolean]\n}\n\nexport interface DialogRootContext {\n  open: Readonly<Ref<boolean>>\n  modal: Ref<boolean>\n  openModal: () => void\n  onOpenChange: (value: boolean) => void\n  onOpenToggle: () => void\n  triggerElement: Ref<HTMLElement | undefined>\n  contentElement: Ref<HTMLElement | undefined>\n  contentId: string\n  titleId: string\n  descriptionId: string\n}\n\nexport const [injectDialogRootContext, provideDialogRootContext]\n  = createContext<DialogRootContext>('DialogRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, toRefs } from 'vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<DialogRootProps>(), {\n  open: undefined,\n  defaultOpen: false,\n  modal: true,\n})\nconst emit = defineEmits<DialogRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n    /** Close the dialog */\n    close: () => void\n  }) => any\n}>()\n\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst triggerElement = ref<HTMLElement>()\nconst contentElement = ref<HTMLElement>()\nconst { modal } = toRefs(props)\n\nprovideDialogRootContext({\n  open,\n  modal,\n  openModal: () => {\n    open.value = true\n  },\n  onOpenChange: (value) => {\n    open.value = value\n  },\n  onOpenToggle: () => {\n    open.value = !open.value\n  },\n  contentId: '',\n  titleId: '',\n  descriptionId: '',\n  triggerElement,\n  contentElement,\n})\n</script>\n\n<template>\n  <slot\n    :open=\"open\"\n    :close=\"() => open = false\"\n  />\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { createContext } from '@/shared'\n\nexport interface DialogRootProps {\n  /** The controlled open state of the dialog. Can be binded as `v-model:open`. */\n  open?: boolean\n  /** The open state of the dialog when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /**\n   * The modality of the dialog When set to `true`, <br>\n   * interaction with outside elements will be disabled and only dialog content will be visible to screen readers.\n   */\n  modal?: boolean\n}\n\nexport type DialogRootEmits = {\n  /** Event handler called when the open state of the dialog changes. */\n  'update:open': [value: boolean]\n}\n\nexport interface DialogRootContext {\n  open: Readonly<Ref<boolean>>\n  modal: Ref<boolean>\n  openModal: () => void\n  onOpenChange: (value: boolean) => void\n  onOpenToggle: () => void\n  triggerElement: Ref<HTMLElement | undefined>\n  contentElement: Ref<HTMLElement | undefined>\n  contentId: string\n  titleId: string\n  descriptionId: string\n}\n\nexport const [injectDialogRootContext, provideDialogRootContext]\n  = createContext<DialogRootContext>('DialogRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, toRefs } from 'vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<DialogRootProps>(), {\n  open: undefined,\n  defaultOpen: false,\n  modal: true,\n})\nconst emit = defineEmits<DialogRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n    /** Close the dialog */\n    close: () => void\n  }) => any\n}>()\n\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst triggerElement = ref<HTMLElement>()\nconst contentElement = ref<HTMLElement>()\nconst { modal } = toRefs(props)\n\nprovideDialogRootContext({\n  open,\n  modal,\n  openModal: () => {\n    open.value = true\n  },\n  onOpenChange: (value) => {\n    open.value = value\n  },\n  onOpenToggle: () => {\n    open.value = !open.value\n  },\n  contentId: '',\n  titleId: '',\n  descriptionId: '',\n  triggerElement,\n  contentElement,\n})\n</script>\n\n<template>\n  <slot\n    :open=\"open\"\n    :close=\"() => open = false\"\n  />\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface DialogCloseProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = withDefaults(defineProps<DialogCloseProps>(), {\n  as: 'button',\n})\n\nuseForwardExpose()\nconst rootContext = injectDialogRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    @click=\"rootContext.onOpenChange(false)\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface DialogCloseProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = withDefaults(defineProps<DialogCloseProps>(), {\n  as: 'button',\n})\n\nuseForwardExpose()\nconst rootContext = injectDialogRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    @click=\"rootContext.onOpenChange(false)\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","import type { MaybeRefOrGetter, Ref } from 'vue'\nimport { isClient } from '@vueuse/shared'\nimport { nextTick, ref, toValue, watchEffect } from 'vue'\nimport { handleAndDispatchCustomEvent } from '@/shared'\n\nexport type PointerDownOutsideEvent = CustomEvent<{\n  originalEvent: PointerEvent\n}>\nexport type FocusOutsideEvent = CustomEvent<{ originalEvent: FocusEvent }>\n\nexport const DISMISSABLE_LAYER_NAME = 'DismissableLayer'\nexport const CONTEXT_UPDATE = 'dismissableLayer.update'\nexport const POINTER_DOWN_OUTSIDE = 'dismissableLayer.pointerDownOutside'\nexport const FOCUS_OUTSIDE = 'dismissableLayer.focusOutside'\n\nexport function isLayerExist(layerElement: HTMLElement, targetElement: HTMLElement) {\n  if (!(targetElement instanceof Element))\n    return false\n\n  const targetLayer = targetElement.closest(\n    '[data-dismissable-layer]',\n  )\n\n  const mainLayer = layerElement.dataset.dismissableLayer === ''\n    ? layerElement\n    : layerElement.querySelector(\n      '[data-dismissable-layer]',\n    ) as HTMLElement\n\n  const nodeList = Array.from(\n    layerElement.ownerDocument.querySelectorAll('[data-dismissable-layer]'),\n  )\n\n  if (targetLayer && (mainLayer === targetLayer || nodeList.indexOf(mainLayer) < nodeList.indexOf(targetLayer))) {\n    return true\n  }\n  else {\n    return false\n  }\n}\n\n/**\n * Listens for `pointerdown` outside a DOM subtree. We use `pointerdown` rather than `pointerup`\n * to mimic layer dismissing behaviour present in OS.\n * Returns props to pass to the node we want to check for outside events.\n */\nexport function usePointerDownOutside(\n  onPointerDownOutside?: (event: PointerDownOutsideEvent) => void,\n  element?: Ref<HTMLElement | undefined>,\n  enabled: MaybeRefOrGetter<boolean> = true,\n) {\n  const ownerDocument: Document\n    = element?.value?.ownerDocument ?? globalThis?.document\n\n  const isPointerInsideDOMTree = ref(false)\n  const handleClickRef = ref(() => {})\n\n  watchEffect((cleanupFn) => {\n    if (!isClient || !toValue(enabled))\n      return\n    const handlePointerDown = async (event: PointerEvent) => {\n      const target = event.target as HTMLElement | undefined\n\n      if (!element?.value || !target)\n        return\n\n      if (isLayerExist(element.value, target)) {\n        isPointerInsideDOMTree.value = false\n        return\n      }\n\n      if (event.target && !isPointerInsideDOMTree.value) {\n        const eventDetail = { originalEvent: event }\n\n        function handleAndDispatchPointerDownOutsideEvent() {\n          handleAndDispatchCustomEvent(\n            POINTER_DOWN_OUTSIDE,\n            onPointerDownOutside,\n            eventDetail,\n          )\n        }\n\n        /**\n         * On touch devices, we need to wait for a click event because browsers implement\n         * a ~350ms delay between the time the user stops touching the display and when the\n         * browser executes events. We need to ensure we don't reactivate pointer-events within\n         * this timeframe otherwise the browser may execute events that should have been prevented.\n         *\n         * Additionally, this also lets us deal automatically with cancellations when a click event\n         * isn't raised because the page was considered scrolled/drag-scrolled, long-pressed, etc.\n         *\n         * This is why we also continuously remove the previous listener, because we cannot be\n         * certain that it was raised, and therefore cleaned-up.\n         */\n        if (event.pointerType === 'touch') {\n          ownerDocument.removeEventListener('click', handleClickRef.value)\n          handleClickRef.value = handleAndDispatchPointerDownOutsideEvent\n          ownerDocument.addEventListener('click', handleClickRef.value, {\n            once: true,\n          })\n        }\n        else {\n          handleAndDispatchPointerDownOutsideEvent()\n        }\n      }\n      else {\n        // We need to remove the event listener in case the outside click has been canceled.\n        // See: https://github.com/radix-ui/primitives/issues/2171\n        ownerDocument.removeEventListener('click', handleClickRef.value)\n      }\n      isPointerInsideDOMTree.value = false\n    }\n    /**\n     * if this hook executes in a component that mounts via a `pointerdown` event, the event\n     * would bubble up to the document and trigger a `pointerDownOutside` event. We avoid\n     * this by delaying the event listener registration on the document.\n     * This is how the DOM works, ie:\n     * ```\n     * button.addEventListener('pointerdown', () => {\n     *   console.log('I will log');\n     *   document.addEventListener('pointerdown', () => {\n     *     console.log('I will also log');\n     *   })\n     * });\n     */\n    const timerId = window.setTimeout(() => {\n      ownerDocument.addEventListener('pointerdown', handlePointerDown)\n    }, 0)\n\n    cleanupFn(() => {\n      window.clearTimeout(timerId)\n      ownerDocument.removeEventListener('pointerdown', handlePointerDown)\n      ownerDocument.removeEventListener('click', handleClickRef.value)\n    })\n  })\n\n  return {\n    onPointerDownCapture: () => {\n      if (!toValue(enabled))\n        return\n      isPointerInsideDOMTree.value = true\n    },\n  }\n}\n\n/**\n * Listens for when focus happens outside a DOM subtree.\n * Returns props to pass to the root (node) of the subtree we want to check.\n */\nexport function useFocusOutside(\n  onFocusOutside?: (event: FocusOutsideEvent) => void,\n  element?: Ref<HTMLElement | undefined>,\n  enabled: MaybeRefOrGetter<boolean> = true,\n) {\n  const ownerDocument: Document\n    = element?.value?.ownerDocument ?? globalThis?.document\n\n  const isFocusInsideDOMTree = ref(false)\n  watchEffect((cleanupFn) => {\n    if (!isClient || !toValue(enabled))\n      return\n    const handleFocus = async (event: FocusEvent) => {\n      if (!element?.value)\n        return\n\n      await nextTick()\n      await nextTick()\n      const target = event.target as HTMLElement | undefined\n      if (!element.value || !target || isLayerExist(element.value, target))\n        return\n\n      if (event.target && !isFocusInsideDOMTree.value) {\n        const eventDetail = { originalEvent: event }\n        handleAndDispatchCustomEvent(\n          FOCUS_OUTSIDE,\n          onFocusOutside,\n          eventDetail,\n        )\n      }\n    }\n\n    ownerDocument.addEventListener('focusin', handleFocus)\n\n    cleanupFn(() => ownerDocument.removeEventListener('focusin', handleFocus))\n  })\n\n  return {\n    onFocusCapture: () => {\n      if (!toValue(enabled))\n        return\n\n      isFocusInsideDOMTree.value = true\n    },\n    onBlurCapture: () => {\n      if (!toValue(enabled))\n        return\n\n      isFocusInsideDOMTree.value = false\n    },\n  }\n}\n\nexport function dispatchUpdate() {\n  const event = new CustomEvent(CONTEXT_UPDATE)\n  document.dispatchEvent(event)\n}\n","<script lang=\"ts\">\nimport type {\n  FocusOutsideEvent,\n  PointerDownOutsideEvent,\n} from './utils'\n\nimport type { PrimitiveProps } from '@/Primitive'\nimport {\n  computed,\n  nextTick,\n  reactive,\n  watch,\n  watchEffect,\n} from 'vue'\nimport { isNullish, useForwardExpose } from '@/shared'\n\nexport interface DismissableLayerProps extends PrimitiveProps {\n  /**\n   * When `true`, hover/focus/click interactions will be disabled on elements outside\n   * the `DismissableLayer`. Users will need to click twice on outside elements to\n   * interact with them: once to close the `DismissableLayer`, and again to trigger the element.\n   */\n  disableOutsidePointerEvents?: boolean\n}\n\nexport type DismissableLayerEmits = {\n  /**\n   * Event handler called when the escape key is down.\n   * Can be prevented.\n   */\n  escapeKeyDown: [event: KeyboardEvent]\n  /**\n   * Event handler called when a `pointerdown` event happens outside of the `DismissableLayer`.\n   * Can be prevented.\n   */\n  pointerDownOutside: [event: PointerDownOutsideEvent]\n  /**\n   * Event handler called when the focus moves outside of the `DismissableLayer`.\n   * Can be prevented.\n   */\n  focusOutside: [ event: FocusOutsideEvent]\n  /**\n   * Event handler called when an interaction happens outside the `DismissableLayer`.\n   * Specifically, when a `pointerdown` event happens outside or focus moves outside of it.\n   * Can be prevented.\n   */\n  interactOutside: [ event: PointerDownOutsideEvent | FocusOutsideEvent]\n}\n\nexport type DismissableLayerPrivateEmits = DismissableLayerEmits & {\n  /**\n   * Handler called when the `DismissableLayer` should be dismissed\n   */\n  dismiss: []\n}\n\nexport const context = reactive({\n  layersRoot: new Set<HTMLElement>(),\n  layersWithOutsidePointerEventsDisabled: new Set<HTMLElement>(),\n  originalBodyPointerEvents: undefined as string | undefined,\n  branches: new Set<HTMLElement>(),\n})\n</script>\n\n<script setup lang=\"ts\">\nimport { onKeyStroke } from '@vueuse/core'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport {\n  useFocusOutside,\n  usePointerDownOutside,\n} from './utils'\n\nconst props = withDefaults(defineProps<DismissableLayerProps>(), {\n  disableOutsidePointerEvents: false,\n})\n\nconst emits = defineEmits<DismissableLayerPrivateEmits>()\n\nconst { forwardRef, currentElement: layerElement } = useForwardExpose()\nconst ownerDocument = computed(\n  () => layerElement.value?.ownerDocument ?? globalThis.document,\n)\n\nconst layers = computed(() => context.layersRoot)\n\nconst index = computed(() => {\n  return layerElement.value\n    ? Array.from(layers.value).indexOf(layerElement.value)\n    : -1\n})\n\nconst isBodyPointerEventsDisabled = computed(() => {\n  return context.layersWithOutsidePointerEventsDisabled.size > 0\n})\n\nconst isPointerEventsEnabled = computed(() => {\n  const localLayers = Array.from(layers.value)\n  const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1)\n  const highestLayerWithOutsidePointerEventsDisabledIndex = localLayers.indexOf(highestLayerWithOutsidePointerEventsDisabled)\n\n  return index.value >= highestLayerWithOutsidePointerEventsDisabledIndex\n})\n\nconst pointerDownOutside = usePointerDownOutside(async (event) => {\n  const isPointerDownOnBranch = [...context.branches].some(branch =>\n    branch?.contains(event.target as HTMLElement),\n  )\n\n  if (!isPointerEventsEnabled.value || isPointerDownOnBranch)\n    return\n  emits('pointerDownOutside', event)\n  emits('interactOutside', event)\n  await nextTick()\n  if (!event.defaultPrevented)\n    emits('dismiss')\n}, layerElement)\n\nconst focusOutside = useFocusOutside((event) => {\n  const isFocusInBranch = [...context.branches].some(branch =>\n    branch?.contains(event.target as HTMLElement),\n  )\n\n  if (isFocusInBranch)\n    return\n  emits('focusOutside', event)\n  emits('interactOutside', event)\n  if (!event.defaultPrevented)\n    emits('dismiss')\n}, layerElement)\n\nonKeyStroke('Escape', (event) => {\n  const isHighestLayer = index.value === layers.value.size - 1\n  if (!isHighestLayer)\n    return\n  emits('escapeKeyDown', event)\n  if (!event.defaultPrevented)\n    emits('dismiss')\n})\n\n// Use `watch` with explicit sources (instead of `watchEffect`) so this effect\n// only re-runs when `layerElement` or `disableOutsidePointerEvents` change.\n// Reading `context.layersWithOutsidePointerEventsDisabled.size` inside the\n// callback must NOT make it reactive: otherwise adding/removing any other\n// layer would re-run this effect and its cleanup could prematurely restore the\n// body's `pointer-events` while an ancestor layer is still open (#2674).\nwatch(\n  [layerElement, () => props.disableOutsidePointerEvents],\n  ([element, disableOutsidePointerEvents], _, onCleanup) => {\n    if (!element)\n      return\n    if (disableOutsidePointerEvents) {\n      if (context.layersWithOutsidePointerEventsDisabled.size === 0) {\n        context.originalBodyPointerEvents = ownerDocument.value.body.style.pointerEvents\n        ownerDocument.value.body.style.pointerEvents = 'none'\n      }\n      context.layersWithOutsidePointerEventsDisabled.add(element)\n\n      // Remove this layer from the set on cleanup (re-run via prop toggle, or\n      // unmount) and restore the body's `pointer-events` only once the last\n      // disabling layer is gone. Removing here — rather than relying solely on\n      // the unmount-only effect below — keeps the set accurate when\n      // `disableOutsidePointerEvents` toggles `true -> false` while still\n      // mounted (e.g. a modal Menu closing). Checking `size === 0` *after*\n      // deletion makes the restore independent of cleanup ordering (#2674).\n      onCleanup(() => {\n        context.layersWithOutsidePointerEventsDisabled.delete(element)\n        if (\n          context.layersWithOutsidePointerEventsDisabled.size === 0\n          && !isNullish(context.originalBodyPointerEvents)\n        ) {\n          ownerDocument.value.body.style.pointerEvents = context.originalBodyPointerEvents\n        }\n      })\n    }\n    layers.value.add(element)\n  },\n  { immediate: true },\n)\n\nwatchEffect((cleanupFn) => {\n  cleanupFn(() => {\n    if (!layerElement.value)\n      return\n    layers.value.delete(layerElement.value)\n    context.layersWithOutsidePointerEventsDisabled.delete(layerElement.value)\n  })\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    data-dismissable-layer\n    :style=\"{\n      pointerEvents: isBodyPointerEventsDisabled\n        ? isPointerEventsEnabled\n          ? 'auto'\n          : 'none'\n        : undefined,\n    }\"\n    @focus.capture=\"focusOutside.onFocusCapture\"\n    @blur.capture=\"focusOutside.onBlurCapture\"\n    @pointerdown.capture=\"pointerDownOutside.onPointerDownCapture\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type {\n  FocusOutsideEvent,\n  PointerDownOutsideEvent,\n} from './utils'\n\nimport type { PrimitiveProps } from '@/Primitive'\nimport {\n  computed,\n  nextTick,\n  reactive,\n  watch,\n  watchEffect,\n} from 'vue'\nimport { isNullish, useForwardExpose } from '@/shared'\n\nexport interface DismissableLayerProps extends PrimitiveProps {\n  /**\n   * When `true`, hover/focus/click interactions will be disabled on elements outside\n   * the `DismissableLayer`. Users will need to click twice on outside elements to\n   * interact with them: once to close the `DismissableLayer`, and again to trigger the element.\n   */\n  disableOutsidePointerEvents?: boolean\n}\n\nexport type DismissableLayerEmits = {\n  /**\n   * Event handler called when the escape key is down.\n   * Can be prevented.\n   */\n  escapeKeyDown: [event: KeyboardEvent]\n  /**\n   * Event handler called when a `pointerdown` event happens outside of the `DismissableLayer`.\n   * Can be prevented.\n   */\n  pointerDownOutside: [event: PointerDownOutsideEvent]\n  /**\n   * Event handler called when the focus moves outside of the `DismissableLayer`.\n   * Can be prevented.\n   */\n  focusOutside: [ event: FocusOutsideEvent]\n  /**\n   * Event handler called when an interaction happens outside the `DismissableLayer`.\n   * Specifically, when a `pointerdown` event happens outside or focus moves outside of it.\n   * Can be prevented.\n   */\n  interactOutside: [ event: PointerDownOutsideEvent | FocusOutsideEvent]\n}\n\nexport type DismissableLayerPrivateEmits = DismissableLayerEmits & {\n  /**\n   * Handler called when the `DismissableLayer` should be dismissed\n   */\n  dismiss: []\n}\n\nexport const context = reactive({\n  layersRoot: new Set<HTMLElement>(),\n  layersWithOutsidePointerEventsDisabled: new Set<HTMLElement>(),\n  originalBodyPointerEvents: undefined as string | undefined,\n  branches: new Set<HTMLElement>(),\n})\n</script>\n\n<script setup lang=\"ts\">\nimport { onKeyStroke } from '@vueuse/core'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport {\n  useFocusOutside,\n  usePointerDownOutside,\n} from './utils'\n\nconst props = withDefaults(defineProps<DismissableLayerProps>(), {\n  disableOutsidePointerEvents: false,\n})\n\nconst emits = defineEmits<DismissableLayerPrivateEmits>()\n\nconst { forwardRef, currentElement: layerElement } = useForwardExpose()\nconst ownerDocument = computed(\n  () => layerElement.value?.ownerDocument ?? globalThis.document,\n)\n\nconst layers = computed(() => context.layersRoot)\n\nconst index = computed(() => {\n  return layerElement.value\n    ? Array.from(layers.value).indexOf(layerElement.value)\n    : -1\n})\n\nconst isBodyPointerEventsDisabled = computed(() => {\n  return context.layersWithOutsidePointerEventsDisabled.size > 0\n})\n\nconst isPointerEventsEnabled = computed(() => {\n  const localLayers = Array.from(layers.value)\n  const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1)\n  const highestLayerWithOutsidePointerEventsDisabledIndex = localLayers.indexOf(highestLayerWithOutsidePointerEventsDisabled)\n\n  return index.value >= highestLayerWithOutsidePointerEventsDisabledIndex\n})\n\nconst pointerDownOutside = usePointerDownOutside(async (event) => {\n  const isPointerDownOnBranch = [...context.branches].some(branch =>\n    branch?.contains(event.target as HTMLElement),\n  )\n\n  if (!isPointerEventsEnabled.value || isPointerDownOnBranch)\n    return\n  emits('pointerDownOutside', event)\n  emits('interactOutside', event)\n  await nextTick()\n  if (!event.defaultPrevented)\n    emits('dismiss')\n}, layerElement)\n\nconst focusOutside = useFocusOutside((event) => {\n  const isFocusInBranch = [...context.branches].some(branch =>\n    branch?.contains(event.target as HTMLElement),\n  )\n\n  if (isFocusInBranch)\n    return\n  emits('focusOutside', event)\n  emits('interactOutside', event)\n  if (!event.defaultPrevented)\n    emits('dismiss')\n}, layerElement)\n\nonKeyStroke('Escape', (event) => {\n  const isHighestLayer = index.value === layers.value.size - 1\n  if (!isHighestLayer)\n    return\n  emits('escapeKeyDown', event)\n  if (!event.defaultPrevented)\n    emits('dismiss')\n})\n\n// Use `watch` with explicit sources (instead of `watchEffect`) so this effect\n// only re-runs when `layerElement` or `disableOutsidePointerEvents` change.\n// Reading `context.layersWithOutsidePointerEventsDisabled.size` inside the\n// callback must NOT make it reactive: otherwise adding/removing any other\n// layer would re-run this effect and its cleanup could prematurely restore the\n// body's `pointer-events` while an ancestor layer is still open (#2674).\nwatch(\n  [layerElement, () => props.disableOutsidePointerEvents],\n  ([element, disableOutsidePointerEvents], _, onCleanup) => {\n    if (!element)\n      return\n    if (disableOutsidePointerEvents) {\n      if (context.layersWithOutsidePointerEventsDisabled.size === 0) {\n        context.originalBodyPointerEvents = ownerDocument.value.body.style.pointerEvents\n        ownerDocument.value.body.style.pointerEvents = 'none'\n      }\n      context.layersWithOutsidePointerEventsDisabled.add(element)\n\n      // Remove this layer from the set on cleanup (re-run via prop toggle, or\n      // unmount) and restore the body's `pointer-events` only once the last\n      // disabling layer is gone. Removing here — rather than relying solely on\n      // the unmount-only effect below — keeps the set accurate when\n      // `disableOutsidePointerEvents` toggles `true -> false` while still\n      // mounted (e.g. a modal Menu closing). Checking `size === 0` *after*\n      // deletion makes the restore independent of cleanup ordering (#2674).\n      onCleanup(() => {\n        context.layersWithOutsidePointerEventsDisabled.delete(element)\n        if (\n          context.layersWithOutsidePointerEventsDisabled.size === 0\n          && !isNullish(context.originalBodyPointerEvents)\n        ) {\n          ownerDocument.value.body.style.pointerEvents = context.originalBodyPointerEvents\n        }\n      })\n    }\n    layers.value.add(element)\n  },\n  { immediate: true },\n)\n\nwatchEffect((cleanupFn) => {\n  cleanupFn(() => {\n    if (!layerElement.value)\n      return\n    layers.value.delete(layerElement.value)\n    context.layersWithOutsidePointerEventsDisabled.delete(layerElement.value)\n  })\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    data-dismissable-layer\n    :style=\"{\n      pointerEvents: isBodyPointerEventsDisabled\n        ? isPointerEventsEnabled\n          ? 'auto'\n          : 'none'\n        : undefined,\n    }\"\n    @focus.capture=\"focusOutside.onFocusCapture\"\n    @blur.capture=\"focusOutside.onBlurCapture\"\n    @pointerdown.capture=\"pointerDownOutside.onPointerDownCapture\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DismissableLayerBranchProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted, onUnmounted } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { context } from './DismissableLayer.vue'\n\nconst props = defineProps<DismissableLayerBranchProps>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nonMounted(() => {\n  context.branches.add(currentElement.value)\n})\nonUnmounted(() => {\n  context.branches.delete(currentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    v-bind=\"props\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DismissableLayerBranchProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted, onUnmounted } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { context } from './DismissableLayer.vue'\n\nconst props = defineProps<DismissableLayerBranchProps>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nonMounted(() => {\n  context.branches.add(currentElement.value)\n})\nonUnmounted(() => {\n  context.branches.delete(currentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    v-bind=\"props\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","import { createGlobalState } from '@vueuse/core'\nimport { ref } from 'vue'\n\ninterface FocusScopeAPI {\n  paused: boolean\n  pause: () => void\n  resume: () => void\n}\n\nconst useFocusStackState = createGlobalState(() => {\n  const stack = ref<FocusScopeAPI[]>([])\n  return stack\n})\n\nexport function createFocusScopesStack() {\n  /** A stack of focus scopes, with the active one at the top */\n  const stack = useFocusStackState()\n\n  return {\n    add(focusScope: FocusScopeAPI) {\n      // pause the currently active focus scope (at the top of the stack)\n      const activeFocusScope = stack.value[0]\n      if (focusScope !== activeFocusScope)\n        activeFocusScope?.pause()\n\n      // remove in case it already exists (because we'll re-add it at the top of the stack)\n      stack.value = arrayRemove(stack.value, focusScope)\n      stack.value.unshift(focusScope)\n    },\n\n    remove(focusScope: FocusScopeAPI) {\n      stack.value = arrayRemove(stack.value, focusScope)\n      stack.value[0]?.resume()\n    },\n  }\n}\n\nexport function arrayRemove<T>(array: T[], item: T) {\n  const updatedArray = [...array]\n  const index = updatedArray.indexOf(item)\n  if (index !== -1)\n    updatedArray.splice(index, 1)\n\n  return updatedArray\n}\n\nexport function removeLinks(items: HTMLElement[]) {\n  return items.filter(item => item.tagName !== 'A')\n}\n","import { getActiveElement } from '@/shared'\n\nexport const AUTOFOCUS_ON_MOUNT = 'focusScope.autoFocusOnMount'\nexport const AUTOFOCUS_ON_UNMOUNT = 'focusScope.autoFocusOnUnmount'\nexport const EVENT_OPTIONS = { bubbles: false, cancelable: true }\n\ntype FocusableTarget = HTMLElement | { focus: () => void }\n\n/**\n * Attempts focusing the first element in a list of candidates.\n * Stops when focus has actually moved.\n */\nexport function focusFirst(candidates: HTMLElement[], { select = false } = {}) {\n  const previouslyFocusedElement = getActiveElement()\n  for (const candidate of candidates) {\n    focus(candidate, { select })\n    if (getActiveElement() !== previouslyFocusedElement)\n      return true\n  }\n}\n\n/**\n * Returns the first and last tabbable elements inside a container.\n */\nexport function getTabbableEdges(container: HTMLElement) {\n  const candidates = getTabbableCandidates(container)\n  const first = findVisible(candidates, container)\n  const last = findVisible(candidates.reverse(), container)\n  return [first, last] as const\n}\n\n/**\n * Returns a list of potential tabbable candidates.\n *\n * NOTE: This is only a close approximation. For example it doesn't take into account cases like when\n * elements are not visible. This cannot be worked out easily by just reading a property, but rather\n * necessitate runtime knowledge (computed styles, etc). We deal with these cases separately.\n *\n * See: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker\n * Credit: https://github.com/discord/focus-layers/blob/master/src/util/wrapFocus.tsx#L1\n */\nexport function getTabbableCandidates(container: HTMLElement) {\n  const nodes: HTMLElement[] = []\n  const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {\n    acceptNode: (node: any) => {\n      const isHiddenInput = node.tagName === 'INPUT' && node.type === 'hidden'\n      if (node.disabled || node.hidden || isHiddenInput)\n        return NodeFilter.FILTER_SKIP\n      // `.tabIndex` is not the same as the `tabindex` attribute. It works on the\n      // runtime's understanding of tabbability, so this automatically accounts\n      // for any kind of element that could be tabbed to.\n      return node.tabIndex >= 0\n        ? NodeFilter.FILTER_ACCEPT\n        : NodeFilter.FILTER_SKIP\n    },\n  })\n  while (walker.nextNode()) nodes.push(walker.currentNode as HTMLElement)\n  // we do not take into account the order of nodes with positive `tabIndex` as it\n  // hinders accessibility to have tab order different from visual order.\n  return nodes\n}\n\n/**\n * Returns the first visible element in a list.\n * NOTE: Only checks visibility up to the `container`.\n */\nexport function findVisible(elements: HTMLElement[], container: HTMLElement) {\n  for (const element of elements) {\n    // we stop checking if it's hidden at the `container` level (excluding)\n    if (!isHidden(element, { upTo: container }))\n      return element\n  }\n}\n\nexport function isHidden(node: HTMLElement, { upTo }: { upTo?: HTMLElement }) {\n  if (getComputedStyle(node).visibility === 'hidden')\n    return true\n  while (node) {\n    // we stop at `upTo` (excluding it)\n    if (upTo !== undefined && node === upTo)\n      return false\n    if (getComputedStyle(node).display === 'none')\n      return true\n    node = node.parentElement as HTMLElement\n  }\n  return false\n}\n\nexport function isSelectableInput(\n  element: any,\n): element is FocusableTarget & { select: () => void } {\n  return element instanceof HTMLInputElement && 'select' in element\n}\n\nexport function focus(\n  element?: FocusableTarget | null,\n  { select = false } = {},\n) {\n  // only focus if that element is focusable\n  if (element && element.focus) {\n    const previouslyFocusedElement = getActiveElement()\n    // NOTE: we prevent scrolling on focus, to minimize jarring transitions for users\n    element.focus({ preventScroll: true })\n    // only select if its not the same element, it supports selection and we need to select\n    if (\n      element !== previouslyFocusedElement\n      && isSelectableInput(element)\n      && select\n    ) {\n      element.select()\n    }\n  }\n}\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { getActiveElement, useForwardExpose } from '@/shared'\n\nexport type FocusScopeEmits = {\n  /**\n   * Event handler called when auto-focusing on mount.\n   * Can be prevented.\n   */\n  mountAutoFocus: [event: Event]\n\n  /**\n   * Event handler called when auto-focusing on unmount.\n   * Can be prevented.\n   */\n  unmountAutoFocus: [event: Event]\n}\n\nexport interface FocusScopeProps extends PrimitiveProps {\n  /**\n   * When `true`, tabbing from last item will focus first tabbable\n   * and shift+tab from first item will focus last tababble.\n   * @defaultValue false\n   */\n  loop?: boolean\n\n  /**\n   * When `true`, focus cannot escape the focus scope via keyboard,\n   * pointer, or a programmatic focus.\n   * @defaultValue false\n   */\n  trapped?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { isClient } from '@vueuse/shared'\nimport { nextTick, reactive, ref, watchEffect } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { createFocusScopesStack } from './stack'\nimport {\n  AUTOFOCUS_ON_MOUNT,\n  AUTOFOCUS_ON_UNMOUNT,\n  EVENT_OPTIONS,\n  focus,\n  focusFirst,\n  getTabbableCandidates,\n  getTabbableEdges,\n} from './utils'\n\nconst props = withDefaults(defineProps<FocusScopeProps>(), {\n  loop: false,\n  trapped: false,\n})\nconst emits = defineEmits<FocusScopeEmits>()\n\nconst { currentRef, currentElement } = useForwardExpose()\nconst lastFocusedElementRef = ref<HTMLElement | null>(null)\nconst focusScopesStack = createFocusScopesStack()\n\nconst focusScope = reactive({\n  paused: false,\n  pause() {\n    this.paused = true\n  },\n  resume() {\n    this.paused = false\n  },\n})\n\nwatchEffect((cleanupFn) => {\n  if (!isClient)\n    return\n  const container = currentElement.value\n  if (!props.trapped)\n    return\n\n  function handleFocusIn(event: FocusEvent) {\n    if (focusScope.paused || !container)\n      return\n    const target = event.target as HTMLElement | null\n    if (container.contains(target))\n      lastFocusedElementRef.value = target\n    else focus(lastFocusedElementRef.value, { select: true })\n  }\n\n  function handleFocusOut(event: FocusEvent) {\n    if (focusScope.paused || !container)\n      return\n    const relatedTarget = event.relatedTarget as HTMLElement | null\n\n    // A `focusout` event with a `null` `relatedTarget` will happen in at least two cases:\n    //\n    // 1. When the user switches app/tabs/windows/the browser itself loses focus.\n    // 2. In Google Chrome, when the focused element is removed from the DOM.\n    //\n    // We let the browser do its thing here because:\n    //\n    // 1. The browser already keeps a memory of what's focused for when the page gets refocused.\n    // 2. In Google Chrome, if we try to focus the deleted focused element (as per below), it\n    //    throws the CPU to 100%, so we avoid doing anything for this reason here too.\n    if (relatedTarget === null)\n      return\n\n    // If the focus has moved to an actual legitimate element (`relatedTarget !== null`)\n    // that is outside the container, we move focus to the last valid focused element inside.\n    if (!container.contains(relatedTarget))\n      focus(lastFocusedElementRef.value, { select: true })\n  }\n\n  // When the focused element gets removed from the DOM, browsers move focus\n  // back to the document.body. In this case, we move focus to the container\n  // to keep focus trapped correctly.\n  // -- related: https://github.com/unovue/reka-ui/issues/518\n  // Reka UI tentative solution:\n  // instead of leaning on document.activeElement, we use lastFocusedElementRef.value to check\n  // if the element still exist inside the container,\n  // if not then we focus to the container\n  function handleMutations(mutations: MutationRecord[]) {\n    const lastFocusedElement = lastFocusedElementRef.value\n\n    // Mutation may be triggered by something unrelated to focus, e.g. class is set on an element\n    // so we first check if we even have a previously focused element.\n    if (lastFocusedElement === null) {\n      return\n    }\n\n    // Ensure mutations removed nodes from the DOM at all.\n    const anyNodesRemoved = mutations.some(m => m.removedNodes.length > 0)\n    if (!anyNodesRemoved) {\n      return\n    }\n\n    const isLastFocusedElementExist = container.contains(lastFocusedElement)\n    if (!isLastFocusedElementExist)\n      focus(container)\n  }\n\n  document.addEventListener('focusin', handleFocusIn)\n  document.addEventListener('focusout', handleFocusOut)\n  const mutationObserver = new MutationObserver(handleMutations)\n  if (container)\n    mutationObserver.observe(container, { childList: true, subtree: true })\n\n  cleanupFn(() => {\n    document.removeEventListener('focusin', handleFocusIn)\n    document.removeEventListener('focusout', handleFocusOut)\n    mutationObserver.disconnect()\n  })\n})\n\nwatchEffect(async (cleanupFn) => {\n  const container = currentElement.value\n\n  await nextTick()\n  if (!container)\n    return\n  focusScopesStack.add(focusScope)\n  const previouslyFocusedElement = getActiveElement() as HTMLElement | null\n  const hasFocusedCandidate = container.contains(previouslyFocusedElement)\n\n  if (!hasFocusedCandidate) {\n    const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS)\n    container.addEventListener(AUTOFOCUS_ON_MOUNT, (ev: Event) =>\n      emits('mountAutoFocus', ev))\n    container.dispatchEvent(mountEvent)\n\n    if (!mountEvent.defaultPrevented) {\n      focusFirst(getTabbableCandidates(container), {\n        select: true,\n      })\n      if (getActiveElement() === previouslyFocusedElement)\n        focus(container)\n    }\n  }\n\n  cleanupFn(() => {\n    container.removeEventListener(AUTOFOCUS_ON_MOUNT, (ev: Event) =>\n      emits('mountAutoFocus', ev))\n\n    const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS)\n    const unmountEventHandler = (ev: Event) => {\n      emits('unmountAutoFocus', ev)\n    }\n    container.addEventListener(AUTOFOCUS_ON_UNMOUNT, unmountEventHandler)\n    container.dispatchEvent(unmountEvent)\n\n    // Signal that blur events fired below are system-initiated (focus trap\n    // cleanup), not user-initiated. Consumers can use this to skip validation.\n    container.setAttribute('data-focus-scope-unmounting', '')\n\n    setTimeout(() => {\n      if (!unmountEvent.defaultPrevented)\n        focus(previouslyFocusedElement ?? document.body, { select: true })\n\n      // we need to remove the listener after we `dispatchEvent`\n      container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, unmountEventHandler)\n\n      focusScopesStack.remove(focusScope)\n      container.removeAttribute('data-focus-scope-unmounting')\n    }, 0)\n  })\n})\n\nfunction handleKeyDown(event: KeyboardEvent) {\n  if (!props.loop && !props.trapped)\n    return\n  if (focusScope.paused)\n    return\n\n  const isTabKey\n    = event.key === 'Tab' && !event.altKey && !event.ctrlKey && !event.metaKey\n  const focusedElement = getActiveElement() as HTMLElement | null\n\n  if (isTabKey && focusedElement) {\n    const container = event.currentTarget as HTMLElement\n    const [first, last] = getTabbableEdges(container)\n    const hasTabbableElementsInside = first && last\n\n    // we can only wrap focus if we have tabbable edges\n    if (!hasTabbableElementsInside) {\n      if (focusedElement === container)\n        event.preventDefault()\n    }\n    else {\n      if (!event.shiftKey && focusedElement === last) {\n        event.preventDefault()\n        if (props.loop)\n          focus(first, { select: true })\n      }\n      else if (event.shiftKey && focusedElement === first) {\n        event.preventDefault()\n        if (props.loop)\n          focus(last, { select: true })\n      }\n    }\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"currentRef\"\n    tabindex=\"-1\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    @keydown=\"handleKeyDown\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { getActiveElement, useForwardExpose } from '@/shared'\n\nexport type FocusScopeEmits = {\n  /**\n   * Event handler called when auto-focusing on mount.\n   * Can be prevented.\n   */\n  mountAutoFocus: [event: Event]\n\n  /**\n   * Event handler called when auto-focusing on unmount.\n   * Can be prevented.\n   */\n  unmountAutoFocus: [event: Event]\n}\n\nexport interface FocusScopeProps extends PrimitiveProps {\n  /**\n   * When `true`, tabbing from last item will focus first tabbable\n   * and shift+tab from first item will focus last tababble.\n   * @defaultValue false\n   */\n  loop?: boolean\n\n  /**\n   * When `true`, focus cannot escape the focus scope via keyboard,\n   * pointer, or a programmatic focus.\n   * @defaultValue false\n   */\n  trapped?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { isClient } from '@vueuse/shared'\nimport { nextTick, reactive, ref, watchEffect } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { createFocusScopesStack } from './stack'\nimport {\n  AUTOFOCUS_ON_MOUNT,\n  AUTOFOCUS_ON_UNMOUNT,\n  EVENT_OPTIONS,\n  focus,\n  focusFirst,\n  getTabbableCandidates,\n  getTabbableEdges,\n} from './utils'\n\nconst props = withDefaults(defineProps<FocusScopeProps>(), {\n  loop: false,\n  trapped: false,\n})\nconst emits = defineEmits<FocusScopeEmits>()\n\nconst { currentRef, currentElement } = useForwardExpose()\nconst lastFocusedElementRef = ref<HTMLElement | null>(null)\nconst focusScopesStack = createFocusScopesStack()\n\nconst focusScope = reactive({\n  paused: false,\n  pause() {\n    this.paused = true\n  },\n  resume() {\n    this.paused = false\n  },\n})\n\nwatchEffect((cleanupFn) => {\n  if (!isClient)\n    return\n  const container = currentElement.value\n  if (!props.trapped)\n    return\n\n  function handleFocusIn(event: FocusEvent) {\n    if (focusScope.paused || !container)\n      return\n    const target = event.target as HTMLElement | null\n    if (container.contains(target))\n      lastFocusedElementRef.value = target\n    else focus(lastFocusedElementRef.value, { select: true })\n  }\n\n  function handleFocusOut(event: FocusEvent) {\n    if (focusScope.paused || !container)\n      return\n    const relatedTarget = event.relatedTarget as HTMLElement | null\n\n    // A `focusout` event with a `null` `relatedTarget` will happen in at least two cases:\n    //\n    // 1. When the user switches app/tabs/windows/the browser itself loses focus.\n    // 2. In Google Chrome, when the focused element is removed from the DOM.\n    //\n    // We let the browser do its thing here because:\n    //\n    // 1. The browser already keeps a memory of what's focused for when the page gets refocused.\n    // 2. In Google Chrome, if we try to focus the deleted focused element (as per below), it\n    //    throws the CPU to 100%, so we avoid doing anything for this reason here too.\n    if (relatedTarget === null)\n      return\n\n    // If the focus has moved to an actual legitimate element (`relatedTarget !== null`)\n    // that is outside the container, we move focus to the last valid focused element inside.\n    if (!container.contains(relatedTarget))\n      focus(lastFocusedElementRef.value, { select: true })\n  }\n\n  // When the focused element gets removed from the DOM, browsers move focus\n  // back to the document.body. In this case, we move focus to the container\n  // to keep focus trapped correctly.\n  // -- related: https://github.com/unovue/reka-ui/issues/518\n  // Reka UI tentative solution:\n  // instead of leaning on document.activeElement, we use lastFocusedElementRef.value to check\n  // if the element still exist inside the container,\n  // if not then we focus to the container\n  function handleMutations(mutations: MutationRecord[]) {\n    const lastFocusedElement = lastFocusedElementRef.value\n\n    // Mutation may be triggered by something unrelated to focus, e.g. class is set on an element\n    // so we first check if we even have a previously focused element.\n    if (lastFocusedElement === null) {\n      return\n    }\n\n    // Ensure mutations removed nodes from the DOM at all.\n    const anyNodesRemoved = mutations.some(m => m.removedNodes.length > 0)\n    if (!anyNodesRemoved) {\n      return\n    }\n\n    const isLastFocusedElementExist = container.contains(lastFocusedElement)\n    if (!isLastFocusedElementExist)\n      focus(container)\n  }\n\n  document.addEventListener('focusin', handleFocusIn)\n  document.addEventListener('focusout', handleFocusOut)\n  const mutationObserver = new MutationObserver(handleMutations)\n  if (container)\n    mutationObserver.observe(container, { childList: true, subtree: true })\n\n  cleanupFn(() => {\n    document.removeEventListener('focusin', handleFocusIn)\n    document.removeEventListener('focusout', handleFocusOut)\n    mutationObserver.disconnect()\n  })\n})\n\nwatchEffect(async (cleanupFn) => {\n  const container = currentElement.value\n\n  await nextTick()\n  if (!container)\n    return\n  focusScopesStack.add(focusScope)\n  const previouslyFocusedElement = getActiveElement() as HTMLElement | null\n  const hasFocusedCandidate = container.contains(previouslyFocusedElement)\n\n  if (!hasFocusedCandidate) {\n    const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS)\n    container.addEventListener(AUTOFOCUS_ON_MOUNT, (ev: Event) =>\n      emits('mountAutoFocus', ev))\n    container.dispatchEvent(mountEvent)\n\n    if (!mountEvent.defaultPrevented) {\n      focusFirst(getTabbableCandidates(container), {\n        select: true,\n      })\n      if (getActiveElement() === previouslyFocusedElement)\n        focus(container)\n    }\n  }\n\n  cleanupFn(() => {\n    container.removeEventListener(AUTOFOCUS_ON_MOUNT, (ev: Event) =>\n      emits('mountAutoFocus', ev))\n\n    const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS)\n    const unmountEventHandler = (ev: Event) => {\n      emits('unmountAutoFocus', ev)\n    }\n    container.addEventListener(AUTOFOCUS_ON_UNMOUNT, unmountEventHandler)\n    container.dispatchEvent(unmountEvent)\n\n    // Signal that blur events fired below are system-initiated (focus trap\n    // cleanup), not user-initiated. Consumers can use this to skip validation.\n    container.setAttribute('data-focus-scope-unmounting', '')\n\n    setTimeout(() => {\n      if (!unmountEvent.defaultPrevented)\n        focus(previouslyFocusedElement ?? document.body, { select: true })\n\n      // we need to remove the listener after we `dispatchEvent`\n      container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, unmountEventHandler)\n\n      focusScopesStack.remove(focusScope)\n      container.removeAttribute('data-focus-scope-unmounting')\n    }, 0)\n  })\n})\n\nfunction handleKeyDown(event: KeyboardEvent) {\n  if (!props.loop && !props.trapped)\n    return\n  if (focusScope.paused)\n    return\n\n  const isTabKey\n    = event.key === 'Tab' && !event.altKey && !event.ctrlKey && !event.metaKey\n  const focusedElement = getActiveElement() as HTMLElement | null\n\n  if (isTabKey && focusedElement) {\n    const container = event.currentTarget as HTMLElement\n    const [first, last] = getTabbableEdges(container)\n    const hasTabbableElementsInside = first && last\n\n    // we can only wrap focus if we have tabbable edges\n    if (!hasTabbableElementsInside) {\n      if (focusedElement === container)\n        event.preventDefault()\n    }\n    else {\n      if (!event.shiftKey && focusedElement === last) {\n        event.preventDefault()\n        if (props.loop)\n          focus(first, { select: true })\n      }\n      else if (event.shiftKey && focusedElement === first) {\n        event.preventDefault()\n        if (props.loop)\n          focus(last, { select: true })\n      }\n    }\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"currentRef\"\n    tabindex=\"-1\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    @keydown=\"handleKeyDown\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","import { getActiveElement } from '@/shared'\n\nexport type CheckedState = boolean | 'indeterminate'\nexport type Direction = 'ltr' | 'rtl'\n\nexport const ITEM_NAME = 'MenuItem'\nexport const ITEM_SELECT = 'menu.itemSelect'\nexport const SELECTION_KEYS = ['Enter', ' ']\nexport const FIRST_KEYS = ['ArrowDown', 'PageUp', 'Home']\nexport const LAST_KEYS = ['ArrowUp', 'PageDown', 'End']\nexport const FIRST_LAST_KEYS = [...FIRST_KEYS, ...LAST_KEYS]\nexport const SUB_OPEN_KEYS: Record<Direction, string[]> = {\n  ltr: [...SELECTION_KEYS, 'ArrowRight'],\n  rtl: [...SELECTION_KEYS, 'ArrowLeft'],\n}\nexport const SUB_CLOSE_KEYS: Record<Direction, string[]> = {\n  ltr: ['ArrowLeft'],\n  rtl: ['ArrowRight'],\n}\n\nexport function getOpenState(open: boolean) {\n  return open ? 'open' : 'closed'\n}\n\nexport function isIndeterminate(\n  checked?: CheckedState,\n): checked is 'indeterminate' {\n  return checked === 'indeterminate'\n}\n\nexport function getCheckedState(checked: CheckedState) {\n  return isIndeterminate(checked)\n    ? 'indeterminate'\n    : checked\n      ? 'checked'\n      : 'unchecked'\n}\n\nexport function focusFirst(candidates: HTMLElement[]) {\n  const PREVIOUSLY_FOCUSED_ELEMENT = getActiveElement()\n  for (const candidate of candidates) {\n    // if focus is already where we want to go, we don't want to keep going through the candidates\n    if (candidate === PREVIOUSLY_FOCUSED_ELEMENT)\n      return\n    candidate.focus()\n    if (getActiveElement() !== PREVIOUSLY_FOCUSED_ELEMENT)\n      return\n  }\n}\n\nexport interface Point {\n  x: number\n  y: number\n}\nexport type Polygon = Point[]\nexport type Side = 'left' | 'right'\nexport interface GraceIntent {\n  area: Polygon\n  side: Side\n}\n\n// Determine if a point is inside of a polygon.\n// Based on https://github.com/substack/point-in-polygon\nexport function isPointInPolygon(point: Point, polygon: Polygon) {\n  const { x, y } = point\n  let inside = false\n  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n    const xi = polygon[i].x\n    const yi = polygon[i].y\n    const xj = polygon[j].x\n    const yj = polygon[j].y\n\n    const intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)\n    if (intersect)\n      inside = !inside\n  }\n\n  return inside\n}\n\nexport function isPointerInGraceArea(event: PointerEvent, area?: Polygon) {\n  if (!area)\n    return false\n  const cursorPos = { x: event.clientX, y: event.clientY }\n  return isPointInPolygon(cursorPos, area)\n}\n\nexport function isMouseEvent(event: PointerEvent) {\n  return event.pointerType === 'mouse'\n}\n","import type { Ref } from 'vue'\nimport { onMounted } from 'vue'\n\nconst DEFAULT_TITLE_NAME = 'DialogTitle'\nconst DEFAULT_CONTENT_NAME = 'DialogContent'\n\nexport type WarningProps = {\n  titleName?: string\n  contentName?: string\n  componentLink?: string\n  titleId: string\n  descriptionId: string\n  contentElement: Ref<HTMLElement | undefined>\n}\n\nexport function useWarning({\n  titleName = DEFAULT_TITLE_NAME,\n  contentName = DEFAULT_CONTENT_NAME,\n  componentLink = 'dialog.html#title',\n  titleId,\n  descriptionId,\n  contentElement,\n}: WarningProps) {\n  const TITLE_MESSAGE = `Warning: \\`${contentName}\\` requires a \\`${titleName}\\` for the component to be accessible for screen reader users.\n\nIf you want to hide the \\`${titleName}\\`, you can wrap it with our VisuallyHidden component.\n\nFor more information, see https://www.reka-ui.com/docs/components/${componentLink}`\n\n  const DESCRIPTION_MESSAGE = `Warning: Missing \\`Description\\` or \\`aria-describedby=\"undefined\"\\` for ${contentName}.`\n\n  onMounted(() => {\n    const hasTitle = document.getElementById(titleId)\n    if (!hasTitle)\n      console.warn(TITLE_MESSAGE)\n\n    const describedById = contentElement.value?.getAttribute('aria-describedby')\n    // if we have an id and the user hasn't set aria-describedby=\"undefined\"\n    if (descriptionId && describedById) {\n      const hasDescription = document.getElementById(descriptionId)\n      if (!hasDescription)\n        console.warn(DESCRIPTION_MESSAGE)\n    }\n  })\n}\n","<script lang=\"ts\">\nimport type {\n  DismissableLayerEmits,\n  DismissableLayerProps,\n} from '@/DismissableLayer'\nimport { getActiveElement, useForwardExpose, useId } from '@/shared'\n\nexport type DialogContentImplEmits = DismissableLayerEmits & {\n  /**\n   * Event handler called when auto-focusing on open.\n   * Can be prevented.\n   */\n  openAutoFocus: [event: Event]\n  /**\n   * Event handler called when auto-focusing on close.\n   * Can be prevented.\n   */\n  closeAutoFocus: [event: Event]\n}\n\nexport interface DialogContentImplProps extends DismissableLayerProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling transntion with Vue native transition or other animation libraries.\n   */\n  forceMount?: boolean\n  /**\n   * When `true`, focus cannot escape the `Content` via keyboard,\n   * pointer, or a programmatic focus.\n   * @defaultValue false\n   */\n  trapFocus?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted } from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { FocusScope } from '@/FocusScope'\nimport { getOpenState } from '@/Menu/utils'\nimport { injectDialogRootContext } from './DialogRoot.vue'\nimport { useWarning } from './utils'\n\nconst props = defineProps<DialogContentImplProps>()\nconst emits = defineEmits<DialogContentImplEmits>()\n\nconst rootContext = injectDialogRootContext()\nconst { forwardRef, currentElement: contentElement } = useForwardExpose()\n\nrootContext.titleId ||= useId(undefined, 'reka-dialog-title')\nrootContext.descriptionId ||= useId(undefined, 'reka-dialog-description')\n\nonMounted(() => {\n  rootContext.contentElement = contentElement\n\n  // Preserve the `DialogTrigger` element in case it was triggered programmatically\n  if (getActiveElement() !== document.body)\n    rootContext.triggerElement.value = getActiveElement() as HTMLElement\n})\n\nif (process.env.NODE_ENV !== 'production') {\n  useWarning({\n    titleName: 'DialogTitle',\n    contentName: 'DialogContent',\n    componentLink: 'dialog.html#title',\n    titleId: rootContext.titleId,\n    descriptionId: rootContext.descriptionId,\n    contentElement,\n  })\n}\n</script>\n\n<template>\n  <FocusScope\n    as-child\n    loop\n    :trapped=\"props.trapFocus\"\n    @mount-auto-focus=\"emits('openAutoFocus', $event)\"\n    @unmount-auto-focus=\"emits('closeAutoFocus', $event)\"\n  >\n    <DismissableLayer\n      :id=\"rootContext.contentId\"\n      :ref=\"forwardRef\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :disable-outside-pointer-events=\"disableOutsidePointerEvents\"\n      role=\"dialog\"\n      :aria-describedby=\"rootContext.descriptionId\"\n      :aria-labelledby=\"rootContext.titleId\"\n      :data-state=\"getOpenState(rootContext.open.value)\"\n      v-bind=\"$attrs\"\n      @dismiss=\"rootContext.onOpenChange(false)\"\n      @escape-key-down=\"emits('escapeKeyDown', $event)\"\n      @focus-outside=\"emits('focusOutside', $event)\"\n      @interact-outside=\"emits('interactOutside', $event)\"\n      @pointer-down-outside=\"emits('pointerDownOutside', $event)\"\n    >\n      <slot />\n    </DismissableLayer>\n  </FocusScope>\n</template>\n","<script lang=\"ts\">\nimport type {\n  DismissableLayerEmits,\n  DismissableLayerProps,\n} from '@/DismissableLayer'\nimport { getActiveElement, useForwardExpose, useId } from '@/shared'\n\nexport type DialogContentImplEmits = DismissableLayerEmits & {\n  /**\n   * Event handler called when auto-focusing on open.\n   * Can be prevented.\n   */\n  openAutoFocus: [event: Event]\n  /**\n   * Event handler called when auto-focusing on close.\n   * Can be prevented.\n   */\n  closeAutoFocus: [event: Event]\n}\n\nexport interface DialogContentImplProps extends DismissableLayerProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling transntion with Vue native transition or other animation libraries.\n   */\n  forceMount?: boolean\n  /**\n   * When `true`, focus cannot escape the `Content` via keyboard,\n   * pointer, or a programmatic focus.\n   * @defaultValue false\n   */\n  trapFocus?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted } from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { FocusScope } from '@/FocusScope'\nimport { getOpenState } from '@/Menu/utils'\nimport { injectDialogRootContext } from './DialogRoot.vue'\nimport { useWarning } from './utils'\n\nconst props = defineProps<DialogContentImplProps>()\nconst emits = defineEmits<DialogContentImplEmits>()\n\nconst rootContext = injectDialogRootContext()\nconst { forwardRef, currentElement: contentElement } = useForwardExpose()\n\nrootContext.titleId ||= useId(undefined, 'reka-dialog-title')\nrootContext.descriptionId ||= useId(undefined, 'reka-dialog-description')\n\nonMounted(() => {\n  rootContext.contentElement = contentElement\n\n  // Preserve the `DialogTrigger` element in case it was triggered programmatically\n  if (getActiveElement() !== document.body)\n    rootContext.triggerElement.value = getActiveElement() as HTMLElement\n})\n\nif (process.env.NODE_ENV !== 'production') {\n  useWarning({\n    titleName: 'DialogTitle',\n    contentName: 'DialogContent',\n    componentLink: 'dialog.html#title',\n    titleId: rootContext.titleId,\n    descriptionId: rootContext.descriptionId,\n    contentElement,\n  })\n}\n</script>\n\n<template>\n  <FocusScope\n    as-child\n    loop\n    :trapped=\"props.trapFocus\"\n    @mount-auto-focus=\"emits('openAutoFocus', $event)\"\n    @unmount-auto-focus=\"emits('closeAutoFocus', $event)\"\n  >\n    <DismissableLayer\n      :id=\"rootContext.contentId\"\n      :ref=\"forwardRef\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :disable-outside-pointer-events=\"disableOutsidePointerEvents\"\n      role=\"dialog\"\n      :aria-describedby=\"rootContext.descriptionId\"\n      :aria-labelledby=\"rootContext.titleId\"\n      :data-state=\"getOpenState(rootContext.open.value)\"\n      v-bind=\"$attrs\"\n      @dismiss=\"rootContext.onOpenChange(false)\"\n      @escape-key-down=\"emits('escapeKeyDown', $event)\"\n      @focus-outside=\"emits('focusOutside', $event)\"\n      @interact-outside=\"emits('interactOutside', $event)\"\n      @pointer-down-outside=\"emits('pointerDownOutside', $event)\"\n    >\n      <slot />\n    </DismissableLayer>\n  </FocusScope>\n</template>\n","<script setup lang=\"ts\">\nimport type { DialogContentImplEmits, DialogContentImplProps } from './DialogContentImpl.vue'\nimport { useEmitAsProps, useForwardExpose, useHideOthers } from '@/shared'\nimport DialogContentImpl from './DialogContentImpl.vue'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = withDefaults(defineProps<DialogContentImplProps>(), {\n  disableOutsidePointerEvents: true,\n})\nconst emits = defineEmits<DialogContentImplEmits>()\n\nconst rootContext = injectDialogRootContext()\n\nconst emitsAsProps = useEmitAsProps(emits)\n\nconst { forwardRef, currentElement } = useForwardExpose()\nuseHideOthers(currentElement)\n</script>\n\n<template>\n  <DialogContentImpl\n    v-bind=\"{ ...props, ...emitsAsProps }\"\n    :ref=\"forwardRef\"\n    :trap-focus=\"rootContext.open.value\"\n    :disable-outside-pointer-events=\"props.disableOutsidePointerEvents\"\n    @close-auto-focus=\"\n      (event) => {\n        if (!event.defaultPrevented) {\n          event.preventDefault();\n          rootContext.triggerElement.value?.focus();\n        }\n      }\n    \"\n    @pointer-down-outside=\"\n      (event) => {\n        const originalEvent = event.detail.originalEvent;\n        const ctrlLeftClick\n          = originalEvent.button === 0 && originalEvent.ctrlKey === true;\n        const isRightClick = originalEvent.button === 2 || ctrlLeftClick;\n\n        // If the event is a right-click, we shouldn't close because\n        // it is effectively as if we right-clicked the `Overlay`.\n        if (isRightClick) event.preventDefault();\n      }\n    \"\n    @focus-outside=\"\n      (event) => {\n        // When focus is trapped, a `focusout` event may still happen.\n        // We make sure we don't trigger our `onDismiss` in such case.\n        event.preventDefault();\n      }\n    \"\n  >\n    <slot />\n  </DialogContentImpl>\n</template>\n","<script setup lang=\"ts\">\nimport type { DialogContentImplEmits, DialogContentImplProps } from './DialogContentImpl.vue'\nimport { useEmitAsProps, useForwardExpose, useHideOthers } from '@/shared'\nimport DialogContentImpl from './DialogContentImpl.vue'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = withDefaults(defineProps<DialogContentImplProps>(), {\n  disableOutsidePointerEvents: true,\n})\nconst emits = defineEmits<DialogContentImplEmits>()\n\nconst rootContext = injectDialogRootContext()\n\nconst emitsAsProps = useEmitAsProps(emits)\n\nconst { forwardRef, currentElement } = useForwardExpose()\nuseHideOthers(currentElement)\n</script>\n\n<template>\n  <DialogContentImpl\n    v-bind=\"{ ...props, ...emitsAsProps }\"\n    :ref=\"forwardRef\"\n    :trap-focus=\"rootContext.open.value\"\n    :disable-outside-pointer-events=\"props.disableOutsidePointerEvents\"\n    @close-auto-focus=\"\n      (event) => {\n        if (!event.defaultPrevented) {\n          event.preventDefault();\n          rootContext.triggerElement.value?.focus();\n        }\n      }\n    \"\n    @pointer-down-outside=\"\n      (event) => {\n        const originalEvent = event.detail.originalEvent;\n        const ctrlLeftClick\n          = originalEvent.button === 0 && originalEvent.ctrlKey === true;\n        const isRightClick = originalEvent.button === 2 || ctrlLeftClick;\n\n        // If the event is a right-click, we shouldn't close because\n        // it is effectively as if we right-clicked the `Overlay`.\n        if (isRightClick) event.preventDefault();\n      }\n    \"\n    @focus-outside=\"\n      (event) => {\n        // When focus is trapped, a `focusout` event may still happen.\n        // We make sure we don't trigger our `onDismiss` in such case.\n        event.preventDefault();\n      }\n    \"\n  >\n    <slot />\n  </DialogContentImpl>\n</template>\n","<script setup lang=\"ts\">\nimport type { DialogContentImplEmits, DialogContentImplProps } from './DialogContentImpl.vue'\nimport { ref } from 'vue'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\nimport DialogContentImpl from './DialogContentImpl.vue'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = defineProps<DialogContentImplProps>()\nconst emits = defineEmits<DialogContentImplEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n\nconst rootContext = injectDialogRootContext()\nconst hasInteractedOutsideRef = ref(false)\nconst hasPointerDownOutsideRef = ref(false)\n</script>\n\n<template>\n  <DialogContentImpl\n    v-bind=\"{ ...props, ...emitsAsProps }\"\n    :trap-focus=\"false\"\n    :disable-outside-pointer-events=\"false\"\n    @close-auto-focus=\"\n      (event) => {\n        if (!event.defaultPrevented) {\n          if (!hasInteractedOutsideRef) rootContext.triggerElement.value?.focus();\n          // Always prevent auto focus because we either focus manually or want user agent focus\n          event.preventDefault();\n        }\n\n        hasInteractedOutsideRef = false;\n        hasPointerDownOutsideRef = false;\n      }\n    \"\n    @interact-outside=\"(event) => {\n      if (!event.defaultPrevented) {\n        hasInteractedOutsideRef = true;\n        if (event.detail.originalEvent.type === 'pointerdown') {\n          hasPointerDownOutsideRef = true;\n        }\n      }\n\n      // Prevent dismissing when clicking the trigger.\n      // As the trigger is already setup to close, without doing so would\n      // cause it to close and immediately open.\n      const target = event.target as HTMLElement;\n      const targetIsTrigger = rootContext.triggerElement.value?.contains(target);\n      if (targetIsTrigger) event.preventDefault();\n\n      // On Safari if the trigger is inside a container with tabIndex={0}, when clicked\n      // we will get the pointer down outside event on the trigger, but then a subsequent\n      // focus outside event on the container, we ignore any focus outside event when we've\n      // already had a pointer down outside event.\n      if (event.detail.originalEvent.type === 'focusin' && hasPointerDownOutsideRef) {\n        event.preventDefault();\n      }\n    }\"\n  >\n    <slot />\n  </DialogContentImpl>\n</template>\n","<script setup lang=\"ts\">\nimport type { DialogContentImplEmits, DialogContentImplProps } from './DialogContentImpl.vue'\nimport { ref } from 'vue'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\nimport DialogContentImpl from './DialogContentImpl.vue'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = defineProps<DialogContentImplProps>()\nconst emits = defineEmits<DialogContentImplEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n\nconst rootContext = injectDialogRootContext()\nconst hasInteractedOutsideRef = ref(false)\nconst hasPointerDownOutsideRef = ref(false)\n</script>\n\n<template>\n  <DialogContentImpl\n    v-bind=\"{ ...props, ...emitsAsProps }\"\n    :trap-focus=\"false\"\n    :disable-outside-pointer-events=\"false\"\n    @close-auto-focus=\"\n      (event) => {\n        if (!event.defaultPrevented) {\n          if (!hasInteractedOutsideRef) rootContext.triggerElement.value?.focus();\n          // Always prevent auto focus because we either focus manually or want user agent focus\n          event.preventDefault();\n        }\n\n        hasInteractedOutsideRef = false;\n        hasPointerDownOutsideRef = false;\n      }\n    \"\n    @interact-outside=\"(event) => {\n      if (!event.defaultPrevented) {\n        hasInteractedOutsideRef = true;\n        if (event.detail.originalEvent.type === 'pointerdown') {\n          hasPointerDownOutsideRef = true;\n        }\n      }\n\n      // Prevent dismissing when clicking the trigger.\n      // As the trigger is already setup to close, without doing so would\n      // cause it to close and immediately open.\n      const target = event.target as HTMLElement;\n      const targetIsTrigger = rootContext.triggerElement.value?.contains(target);\n      if (targetIsTrigger) event.preventDefault();\n\n      // On Safari if the trigger is inside a container with tabIndex={0}, when clicked\n      // we will get the pointer down outside event on the trigger, but then a subsequent\n      // focus outside event on the container, we ignore any focus outside event when we've\n      // already had a pointer down outside event.\n      if (event.detail.originalEvent.type === 'focusin' && hasPointerDownOutsideRef) {\n        event.preventDefault();\n      }\n    }\"\n  >\n    <slot />\n  </DialogContentImpl>\n</template>\n","<script lang=\"ts\">\nimport type {\n  DialogContentImplEmits,\n  DialogContentImplProps,\n} from './DialogContentImpl.vue'\n\nexport type DialogContentEmits = DialogContentImplEmits\n\nexport interface DialogContentProps extends Omit<DialogContentImplProps, 'trapFocus'> {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\nimport DialogContentModal from './DialogContentModal.vue'\nimport DialogContentNonModal from './DialogContentNonModal.vue'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = withDefaults(defineProps<DialogContentProps>(), {\n  // Keep `undefined` (instead of Vue's boolean coercion to `false`) so the\n  // modal/non-modal child can apply its own default. This lets a modal\n  // `DialogContent` stay locked by default while still honoring an explicit\n  // `:disable-outside-pointer-events=\"false\"` (#2677).\n  disableOutsidePointerEvents: undefined,\n})\nconst emits = defineEmits<DialogContentEmits>()\n\nconst rootContext = injectDialogRootContext()\n\nconst emitsAsProps = useEmitAsProps(emits)\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <Presence :present=\"forceMount || rootContext.open.value\">\n    <DialogContentModal\n      v-if=\"rootContext.modal.value\"\n      :ref=\"forwardRef\"\n      v-bind=\"{ ...props, ...emitsAsProps, ...$attrs }\"\n    >\n      <slot />\n    </DialogContentModal>\n    <DialogContentNonModal\n      v-else\n      :ref=\"forwardRef\"\n      v-bind=\"{ ...props, ...emitsAsProps, ...$attrs }\"\n    >\n      <slot />\n    </DialogContentNonModal>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type {\n  DialogContentImplEmits,\n  DialogContentImplProps,\n} from './DialogContentImpl.vue'\n\nexport type DialogContentEmits = DialogContentImplEmits\n\nexport interface DialogContentProps extends Omit<DialogContentImplProps, 'trapFocus'> {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\nimport DialogContentModal from './DialogContentModal.vue'\nimport DialogContentNonModal from './DialogContentNonModal.vue'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = withDefaults(defineProps<DialogContentProps>(), {\n  // Keep `undefined` (instead of Vue's boolean coercion to `false`) so the\n  // modal/non-modal child can apply its own default. This lets a modal\n  // `DialogContent` stay locked by default while still honoring an explicit\n  // `:disable-outside-pointer-events=\"false\"` (#2677).\n  disableOutsidePointerEvents: undefined,\n})\nconst emits = defineEmits<DialogContentEmits>()\n\nconst rootContext = injectDialogRootContext()\n\nconst emitsAsProps = useEmitAsProps(emits)\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <Presence :present=\"forceMount || rootContext.open.value\">\n    <DialogContentModal\n      v-if=\"rootContext.modal.value\"\n      :ref=\"forwardRef\"\n      v-bind=\"{ ...props, ...emitsAsProps, ...$attrs }\"\n    >\n      <slot />\n    </DialogContentModal>\n    <DialogContentNonModal\n      v-else\n      :ref=\"forwardRef\"\n      v-bind=\"{ ...props, ...emitsAsProps, ...$attrs }\"\n    >\n      <slot />\n    </DialogContentNonModal>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DialogDescriptionProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = withDefaults(defineProps<DialogDescriptionProps>(), { as: 'p' })\n\nuseForwardExpose()\nconst rootContext = injectDialogRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.descriptionId\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DialogDescriptionProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = withDefaults(defineProps<DialogDescriptionProps>(), { as: 'p' })\n\nuseForwardExpose()\nconst rootContext = injectDialogRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.descriptionId\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface DialogOverlayImplProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { useBodyScrollLock } from '@/shared/useBodyScrollLock'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\ndefineProps<DialogOverlayImplProps>()\nconst rootContext = injectDialogRootContext()\n\nuseBodyScrollLock(true)\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n    style=\"pointer-events: auto\"\n    @pointerdown.left.self.prevent\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface DialogOverlayImplProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { useBodyScrollLock } from '@/shared/useBodyScrollLock'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\ndefineProps<DialogOverlayImplProps>()\nconst rootContext = injectDialogRootContext()\n\nuseBodyScrollLock(true)\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n    style=\"pointer-events: auto\"\n    @pointerdown.left.self.prevent\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DialogOverlayImplProps } from './DialogOverlayImpl.vue'\nimport { useForwardExpose } from '@/shared'\nimport DialogOverlayImpl from './DialogOverlayImpl.vue'\n\nexport interface DialogOverlayProps extends DialogOverlayImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\ndefineProps<DialogOverlayProps>()\nconst rootContext = injectDialogRootContext()\n\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <Presence\n    v-if=\"rootContext?.modal.value\"\n    :present=\"forceMount || rootContext.open.value\"\n  >\n    <DialogOverlayImpl\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n    >\n      <slot />\n    </DialogOverlayImpl>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { DialogOverlayImplProps } from './DialogOverlayImpl.vue'\nimport { useForwardExpose } from '@/shared'\nimport DialogOverlayImpl from './DialogOverlayImpl.vue'\n\nexport interface DialogOverlayProps extends DialogOverlayImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\ndefineProps<DialogOverlayProps>()\nconst rootContext = injectDialogRootContext()\n\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <Presence\n    v-if=\"rootContext?.modal.value\"\n    :present=\"forceMount || rootContext.open.value\"\n  >\n    <DialogOverlayImpl\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n    >\n      <slot />\n    </DialogOverlayImpl>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nexport interface TeleportProps {\n  /**\n   * Vue native teleport component prop `:to`\n   *\n   * {@link https://vuejs.org/guide/built-ins/teleport.html#basic-usage}\n   */\n  to?: string | HTMLElement\n  /**\n   * Disable teleport and render the component inline\n   *\n   * {@link https://vuejs.org/guide/built-ins/teleport.html#disabling-teleport}\n   */\n  disabled?: boolean\n  /**\n   * Defer the resolving of a Teleport target until other parts of the\n   * application have mounted (requires Vue 3.5.0+)\n   *\n   * {@link https://vuejs.org/guide/built-ins/teleport.html#deferred-teleport}\n   */\n  defer?: boolean\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useMounted } from '@vueuse/core'\n\nwithDefaults(defineProps<TeleportProps>(), {\n  to: 'body',\n})\n\nconst isMounted = useMounted()\n</script>\n\n<template>\n  <Teleport\n    v-if=\"isMounted || forceMount\"\n    :to=\"to\"\n    :disabled=\"disabled\"\n    :defer=\"defer\"\n  >\n    <slot />\n  </Teleport>\n</template>\n","<script lang=\"ts\">\nexport interface TeleportProps {\n  /**\n   * Vue native teleport component prop `:to`\n   *\n   * {@link https://vuejs.org/guide/built-ins/teleport.html#basic-usage}\n   */\n  to?: string | HTMLElement\n  /**\n   * Disable teleport and render the component inline\n   *\n   * {@link https://vuejs.org/guide/built-ins/teleport.html#disabling-teleport}\n   */\n  disabled?: boolean\n  /**\n   * Defer the resolving of a Teleport target until other parts of the\n   * application have mounted (requires Vue 3.5.0+)\n   *\n   * {@link https://vuejs.org/guide/built-ins/teleport.html#deferred-teleport}\n   */\n  defer?: boolean\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useMounted } from '@vueuse/core'\n\nwithDefaults(defineProps<TeleportProps>(), {\n  to: 'body',\n})\n\nconst isMounted = useMounted()\n</script>\n\n<template>\n  <Teleport\n    v-if=\"isMounted || forceMount\"\n    :to=\"to\"\n    :disabled=\"disabled\"\n    :defer=\"defer\"\n  >\n    <slot />\n  </Teleport>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface DialogPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<DialogPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface DialogPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<DialogPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DialogTitleProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = withDefaults(defineProps<DialogTitleProps>(), { as: 'h2' })\nconst rootContext = injectDialogRootContext()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.titleId\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DialogTitleProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = withDefaults(defineProps<DialogTitleProps>(), { as: 'h2' })\nconst rootContext = injectDialogRootContext()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.titleId\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface DialogTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose, useId } from '@/shared'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = withDefaults(defineProps<DialogTriggerProps>(), {\n  as: 'button',\n})\nconst rootContext = injectDialogRootContext()\nconst { forwardRef, currentElement } = useForwardExpose()\n\nrootContext.contentId ||= useId(undefined, 'reka-dialog-content')\nonMounted(() => {\n  rootContext.triggerElement.value = currentElement.value\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :ref=\"forwardRef\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    aria-haspopup=\"dialog\"\n    :aria-expanded=\"rootContext.open.value || false\"\n    :aria-controls=\"rootContext.open.value ? rootContext.contentId : undefined\"\n    :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n    @click=\"rootContext.onOpenToggle\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface DialogTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose, useId } from '@/shared'\nimport { injectDialogRootContext } from './DialogRoot.vue'\n\nconst props = withDefaults(defineProps<DialogTriggerProps>(), {\n  as: 'button',\n})\nconst rootContext = injectDialogRootContext()\nconst { forwardRef, currentElement } = useForwardExpose()\n\nrootContext.contentId ||= useId(undefined, 'reka-dialog-content')\nonMounted(() => {\n  rootContext.triggerElement.value = currentElement.value\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :ref=\"forwardRef\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    aria-haspopup=\"dialog\"\n    :aria-expanded=\"rootContext.open.value || false\"\n    :aria-controls=\"rootContext.open.value ? rootContext.contentId : undefined\"\n    :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n    @click=\"rootContext.onOpenToggle\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DialogCloseProps } from '@/Dialog'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AlertDialogActionProps extends DialogCloseProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { DialogClose } from '@/Dialog'\n\nconst props = withDefaults(defineProps<AlertDialogActionProps>(), { as: 'button' })\nuseForwardExpose()\n</script>\n\n<template>\n  <DialogClose v-bind=\"props\">\n    <slot />\n  </DialogClose>\n</template>\n","<script lang=\"ts\">\nimport type { DialogCloseProps } from '@/Dialog'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AlertDialogActionProps extends DialogCloseProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { DialogClose } from '@/Dialog'\n\nconst props = withDefaults(defineProps<AlertDialogActionProps>(), { as: 'button' })\nuseForwardExpose()\n</script>\n\n<template>\n  <DialogClose v-bind=\"props\">\n    <slot />\n  </DialogClose>\n</template>\n","<script lang=\"ts\">\nimport type {\n  DialogContentEmits,\n  DialogContentProps,\n} from '@/Dialog'\nimport { createContext, useEmitAsProps, useForwardExpose } from '@/shared'\n\ninterface AlertDialogContentContext {\n  onCancelElementChange: (el: HTMLElement | undefined) => void\n}\n\nexport const [injectAlertDialogContentContext, provideAlertDialogContentContext]\n  = createContext<AlertDialogContentContext>('AlertDialogContent')\n\nexport type AlertDialogContentEmits = DialogContentEmits\nexport interface AlertDialogContentProps extends DialogContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { nextTick, ref } from 'vue'\nimport { DialogContent } from '@/Dialog'\n\nconst props = defineProps<AlertDialogContentProps>()\nconst emits = defineEmits<AlertDialogContentEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n\nconst cancelElement = ref<HTMLElement | undefined>()\n\nprovideAlertDialogContentContext({\n  onCancelElementChange: (el) => {\n    cancelElement.value = el\n  },\n})\n</script>\n\n<template>\n  <DialogContent\n    v-bind=\"{ ...props, ...emitsAsProps }\"\n    role=\"alertdialog\"\n    @pointer-down-outside.prevent\n    @interact-outside.prevent\n    @open-auto-focus=\"\n      () => {\n        nextTick(() => {\n          cancelElement?.focus({\n            preventScroll: true,\n          });\n        });\n      }\n    \"\n  >\n    <slot />\n  </DialogContent>\n</template>\n","<script lang=\"ts\">\nimport type {\n  DialogContentEmits,\n  DialogContentProps,\n} from '@/Dialog'\nimport { createContext, useEmitAsProps, useForwardExpose } from '@/shared'\n\ninterface AlertDialogContentContext {\n  onCancelElementChange: (el: HTMLElement | undefined) => void\n}\n\nexport const [injectAlertDialogContentContext, provideAlertDialogContentContext]\n  = createContext<AlertDialogContentContext>('AlertDialogContent')\n\nexport type AlertDialogContentEmits = DialogContentEmits\nexport interface AlertDialogContentProps extends DialogContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { nextTick, ref } from 'vue'\nimport { DialogContent } from '@/Dialog'\n\nconst props = defineProps<AlertDialogContentProps>()\nconst emits = defineEmits<AlertDialogContentEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n\nconst cancelElement = ref<HTMLElement | undefined>()\n\nprovideAlertDialogContentContext({\n  onCancelElementChange: (el) => {\n    cancelElement.value = el\n  },\n})\n</script>\n\n<template>\n  <DialogContent\n    v-bind=\"{ ...props, ...emitsAsProps }\"\n    role=\"alertdialog\"\n    @pointer-down-outside.prevent\n    @interact-outside.prevent\n    @open-auto-focus=\"\n      () => {\n        nextTick(() => {\n          cancelElement?.focus({\n            preventScroll: true,\n          });\n        });\n      }\n    \"\n  >\n    <slot />\n  </DialogContent>\n</template>\n","<script lang=\"ts\">\nimport type { DialogCloseProps } from '@/Dialog'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AlertDialogCancelProps extends DialogCloseProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted } from 'vue'\nimport { DialogClose } from '@/Dialog'\nimport { injectAlertDialogContentContext } from './AlertDialogContent.vue'\n\nconst props = withDefaults(defineProps<AlertDialogCancelProps>(), { as: 'button' })\nconst contentContext = injectAlertDialogContentContext()\nconst { forwardRef, currentElement } = useForwardExpose()\n\nonMounted(() => {\n  contentContext.onCancelElementChange(currentElement.value)\n})\n</script>\n\n<template>\n  <DialogClose\n    v-bind=\"props\"\n    :ref=\"forwardRef\"\n  >\n    <slot />\n  </DialogClose>\n</template>\n","<script lang=\"ts\">\nimport type { DialogCloseProps } from '@/Dialog'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AlertDialogCancelProps extends DialogCloseProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted } from 'vue'\nimport { DialogClose } from '@/Dialog'\nimport { injectAlertDialogContentContext } from './AlertDialogContent.vue'\n\nconst props = withDefaults(defineProps<AlertDialogCancelProps>(), { as: 'button' })\nconst contentContext = injectAlertDialogContentContext()\nconst { forwardRef, currentElement } = useForwardExpose()\n\nonMounted(() => {\n  contentContext.onCancelElementChange(currentElement.value)\n})\n</script>\n\n<template>\n  <DialogClose\n    v-bind=\"props\"\n    :ref=\"forwardRef\"\n  >\n    <slot />\n  </DialogClose>\n</template>\n","<script lang=\"ts\">\nimport type { DialogDescriptionProps } from '@/Dialog'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AlertDialogDescriptionProps extends DialogDescriptionProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { DialogDescription } from '@/Dialog'\n\nconst props = withDefaults(defineProps<AlertDialogDescriptionProps>(), { as: 'p' })\nuseForwardExpose()\n</script>\n\n<template>\n  <DialogDescription v-bind=\"props\">\n    <slot />\n  </DialogDescription>\n</template>\n","<script lang=\"ts\">\nimport type { DialogDescriptionProps } from '@/Dialog'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AlertDialogDescriptionProps extends DialogDescriptionProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { DialogDescription } from '@/Dialog'\n\nconst props = withDefaults(defineProps<AlertDialogDescriptionProps>(), { as: 'p' })\nuseForwardExpose()\n</script>\n\n<template>\n  <DialogDescription v-bind=\"props\">\n    <slot />\n  </DialogDescription>\n</template>\n","<script lang=\"ts\">\nimport type { DialogOverlayProps } from '@/Dialog'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AlertDialogOverlayProps extends DialogOverlayProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { DialogOverlay } from '@/Dialog'\n\nconst props = defineProps<AlertDialogOverlayProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <DialogOverlay v-bind=\"props\">\n    <slot />\n  </DialogOverlay>\n</template>\n","<script lang=\"ts\">\nimport type { DialogOverlayProps } from '@/Dialog'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AlertDialogOverlayProps extends DialogOverlayProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { DialogOverlay } from '@/Dialog'\n\nconst props = defineProps<AlertDialogOverlayProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <DialogOverlay v-bind=\"props\">\n    <slot />\n  </DialogOverlay>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface AlertDialogPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<AlertDialogPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface AlertDialogPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<AlertDialogPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type {\n  DialogRootEmits,\n  DialogRootProps,\n} from '@/Dialog'\n\nexport type AlertDialogEmits = DialogRootEmits\nexport interface AlertDialogProps extends Omit<DialogRootProps, 'modal'> {}\n</script>\n\n<script setup lang=\"ts\">\nimport { DialogRoot } from '@/Dialog'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\n\nconst props = defineProps<AlertDialogProps>()\nconst emits = defineEmits<AlertDialogEmits>()\n\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <DialogRoot\n    v-slot=\"slotProps\"\n    v-bind=\"forwarded\"\n    :modal=\"true\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </DialogRoot>\n</template>\n","<script lang=\"ts\">\nimport type {\n  DialogRootEmits,\n  DialogRootProps,\n} from '@/Dialog'\n\nexport type AlertDialogEmits = DialogRootEmits\nexport interface AlertDialogProps extends Omit<DialogRootProps, 'modal'> {}\n</script>\n\n<script setup lang=\"ts\">\nimport { DialogRoot } from '@/Dialog'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\n\nconst props = defineProps<AlertDialogProps>()\nconst emits = defineEmits<AlertDialogEmits>()\n\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <DialogRoot\n    v-slot=\"slotProps\"\n    v-bind=\"forwarded\"\n    :modal=\"true\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </DialogRoot>\n</template>\n","<script lang=\"ts\">\nimport type { DialogTitleProps } from '@/Dialog'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AlertDialogTitleProps extends DialogTitleProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { DialogTitle } from '@/Dialog'\n\nconst props = withDefaults(defineProps<AlertDialogTitleProps>(), { as: 'h2' })\nuseForwardExpose()\n</script>\n\n<template>\n  <DialogTitle v-bind=\"props\">\n    <slot />\n  </DialogTitle>\n</template>\n","<script lang=\"ts\">\nimport type { DialogTitleProps } from '@/Dialog'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AlertDialogTitleProps extends DialogTitleProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { DialogTitle } from '@/Dialog'\n\nconst props = withDefaults(defineProps<AlertDialogTitleProps>(), { as: 'h2' })\nuseForwardExpose()\n</script>\n\n<template>\n  <DialogTitle v-bind=\"props\">\n    <slot />\n  </DialogTitle>\n</template>\n","<script lang=\"ts\">\nimport type { DialogTriggerProps } from '@/Dialog'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AlertDialogTriggerProps extends DialogTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { DialogTrigger } from '@/Dialog'\n\nconst props = withDefaults(defineProps<AlertDialogTriggerProps>(), { as: 'button' })\nuseForwardExpose()\n</script>\n\n<template>\n  <DialogTrigger v-bind=\"props\">\n    <slot />\n  </DialogTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { DialogTriggerProps } from '@/Dialog'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AlertDialogTriggerProps extends DialogTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { DialogTrigger } from '@/Dialog'\n\nconst props = withDefaults(defineProps<AlertDialogTriggerProps>(), { as: 'button' })\nuseForwardExpose()\n</script>\n\n<template>\n  <DialogTrigger v-bind=\"props\">\n    <slot />\n  </DialogTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AspectRatioProps extends PrimitiveProps {\n  /**\n   * The desired ratio. Eg: 16/9\n   * @defaultValue 1\n   */\n  ratio?: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<AspectRatioProps>(), {\n  ratio: 1,\n})\ndefineSlots<{\n  default?: (props: {\n    /** Current aspect ratio (in %) */\n    aspect: typeof aspect.value\n  }) => any\n}>()\n\nconst { forwardRef } = useForwardExpose()\n\nconst aspect = computed(() => {\n  return (1 / props.ratio) * 100\n})\n</script>\n\n<template>\n  <div\n    :style=\"`position: relative; width: 100%; padding-bottom: ${aspect}%`\"\n    data-reka-aspect-ratio-wrapper\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      style=\"position: absolute; inset: 0px\"\n      v-bind=\"$attrs\"\n    >\n      <slot :aspect=\"aspect\" />\n    </Primitive>\n  </div>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AspectRatioProps extends PrimitiveProps {\n  /**\n   * The desired ratio. Eg: 16/9\n   * @defaultValue 1\n   */\n  ratio?: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<AspectRatioProps>(), {\n  ratio: 1,\n})\ndefineSlots<{\n  default?: (props: {\n    /** Current aspect ratio (in %) */\n    aspect: typeof aspect.value\n  }) => any\n}>()\n\nconst { forwardRef } = useForwardExpose()\n\nconst aspect = computed(() => {\n  return (1 / props.ratio) * 100\n})\n</script>\n\n<template>\n  <div\n    :style=\"`position: relative; width: 100%; padding-bottom: ${aspect}%`\"\n    data-reka-aspect-ratio-wrapper\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      style=\"position: absolute; inset: 0px\"\n      v-bind=\"$attrs\"\n    >\n      <slot :aspect=\"aspect\" />\n    </Primitive>\n  </div>\n</template>\n","import type { Ref } from 'vue'\nimport { computed, defineComponent, h, inject, markRaw, provide, ref, watch, watchEffect } from 'vue'\nimport { Slot, usePrimitiveElement } from '@/Primitive'\n\ninterface CollectionContext<ItemData = {}> {\n  collectionRef: Ref<HTMLElement | undefined>\n  itemMap: Ref<Map<HTMLElement, { ref: HTMLElement, value?: any } & ItemData>>\n}\n\nconst ITEM_DATA_ATTR = 'data-reka-collection-item'\n\nexport function useCollection<ItemData = {}>(options: { key?: string, isProvider?: boolean } = {}) {\n  const { key = '', isProvider = false } = options\n  const injectionKey = `${key}CollectionProvider`\n  let context: CollectionContext<ItemData>\n\n  if (isProvider) {\n    const itemMap = ref<Map<HTMLElement, { ref: HTMLElement } & ItemData>>(new Map())\n    const collectionRef = ref<HTMLElement>()\n\n    context = {\n      collectionRef,\n      itemMap,\n    } as CollectionContext<ItemData>\n    provide(injectionKey, context)\n  }\n  else {\n    context = inject(injectionKey) as CollectionContext<ItemData>\n  }\n\n  const getItems = (includeDisabledItem = false) => {\n    const collectionNode = context.collectionRef.value\n    if (!collectionNode)\n      return []\n    const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`))\n    const items = Array.from(context.itemMap.value.values())\n    const orderedItems = items.sort(\n      (a, b) => orderedNodes.indexOf(a.ref) - orderedNodes.indexOf(b.ref),\n    )\n\n    if (includeDisabledItem)\n      return orderedItems\n    else\n      return orderedItems.filter(i => i.ref.dataset.disabled !== '')\n  }\n\n  const CollectionSlot = defineComponent({\n    name: 'CollectionSlot',\n    inheritAttrs: false,\n    setup(_, { slots, attrs }) {\n      const { primitiveElement, currentElement } = usePrimitiveElement()\n      watch(currentElement, () => {\n        context.collectionRef.value = currentElement.value\n      })\n      return () => h(Slot, { ref: primitiveElement, ...attrs }, slots)\n    },\n  })\n\n  const CollectionItem = defineComponent({\n    name: 'CollectionItem',\n    inheritAttrs: false,\n    props: {\n      value: {\n        // It accepts any value\n        validator: () => true,\n      },\n    },\n    setup(props, { slots, attrs }) {\n      const { primitiveElement, currentElement } = usePrimitiveElement()\n\n      watchEffect((cleanupFn) => {\n        if (currentElement.value) {\n          const key = markRaw(currentElement.value)\n          // @ts-expect-error ignore assignment of unknown to any\n          context.itemMap.value.set(key, { ref: currentElement.value!, value: props.value })\n          cleanupFn(() => context.itemMap.value.delete(key))\n        }\n      })\n\n      return () => h(Slot, { ...attrs, [ITEM_DATA_ATTR]: '', ref: primitiveElement }, slots)\n    },\n  })\n\n  const reactiveItems = computed(() => Array.from(context.itemMap.value.values()))\n  const itemMapSize = computed(() => context.itemMap.value.size)\n\n  return { getItems, reactiveItems, itemMapSize, CollectionSlot, CollectionItem }\n}\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface VisuallyHiddenProps extends PrimitiveProps {\n  feature?: 'focusable' | 'fully-hidden'\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nwithDefaults(defineProps<VisuallyHiddenProps>(), { as: 'span', feature: 'focusable' })\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-hidden=\"feature === 'focusable' ? 'true' : undefined\"\n    :data-hidden=\"feature === 'fully-hidden' ? '' : undefined\"\n    :tabindex=\"feature === 'fully-hidden' ? '-1' : undefined\"\n    :style=\"{\n      // See: https://github.com/twbs/bootstrap/blob/a360960b8dfdb4bf48f87539c2243458fa0366f7/scss/mixins/_visually-hidden.scss\n      position: 'absolute',\n      border: 0,\n      width: '1px',\n      height: '1px',\n      padding: 0,\n      margin: '-1px',\n      overflow: 'hidden',\n      clip: 'rect(0, 0, 0, 0)',\n      clipPath: 'inset(50%)',\n      whiteSpace: 'nowrap',\n      wordWrap: 'normal',\n\n      // Prevent causing unnecessary container scroll\n      // @see https://github.com/unovue/reka-ui/issues/2127\n      top: '-1px',\n      left: '-1px',\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface VisuallyHiddenProps extends PrimitiveProps {\n  feature?: 'focusable' | 'fully-hidden'\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nwithDefaults(defineProps<VisuallyHiddenProps>(), { as: 'span', feature: 'focusable' })\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-hidden=\"feature === 'focusable' ? 'true' : undefined\"\n    :data-hidden=\"feature === 'fully-hidden' ? '' : undefined\"\n    :tabindex=\"feature === 'fully-hidden' ? '-1' : undefined\"\n    :style=\"{\n      // See: https://github.com/twbs/bootstrap/blob/a360960b8dfdb4bf48f87539c2243458fa0366f7/scss/mixins/_visually-hidden.scss\n      position: 'absolute',\n      border: 0,\n      width: '1px',\n      height: '1px',\n      padding: 0,\n      margin: '-1px',\n      overflow: 'hidden',\n      clip: 'rect(0, 0, 0, 0)',\n      clipPath: 'inset(50%)',\n      whiteSpace: 'nowrap',\n      wordWrap: 'normal',\n\n      // Prevent causing unnecessary container scroll\n      // @see https://github.com/unovue/reka-ui/issues/2127\n      top: '-1px',\n      left: '-1px',\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nexport interface VisuallyHiddenInputBubbleProps<T> {\n  name: string\n  value: T\n  checked?: boolean\n  required?: boolean\n  disabled?: boolean\n  feature?: VisuallyHiddenProps['feature']\n}\n</script>\n\n<script setup lang=\"ts\" generic=\"T\">\nimport type { VisuallyHiddenProps } from './VisuallyHidden.vue'\nimport { computed, watch } from 'vue'\nimport { usePrimitiveElement } from '@/Primitive'\nimport VisuallyHidden from './VisuallyHidden.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<VisuallyHiddenInputBubbleProps<T>>(), {\n  feature: 'fully-hidden',\n  checked: undefined,\n})\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst valueState = computed(() => props.checked ?? props.value)\n\nwatch(valueState, (cur, prev) => {\n  if (!currentElement.value)\n    return\n\n  const input = currentElement.value as HTMLInputElement\n  const inputProto = window.HTMLInputElement.prototype\n  const descriptor = Object.getOwnPropertyDescriptor(inputProto, 'value') as PropertyDescriptor\n  const setValue = descriptor.set\n  if (setValue && cur !== prev) {\n    const inputEvent = new Event('input', { bubbles: true })\n    const changeEvent = new Event('change', { bubbles: true })\n    setValue.call(input, cur)\n    input.dispatchEvent(inputEvent)\n    input.dispatchEvent(changeEvent)\n  }\n})\n</script>\n\n<template>\n  <VisuallyHidden\n    ref=\"primitiveElement\"\n    v-bind=\"{ ...props, ...$attrs }\"\n    as=\"input\"\n  />\n</template>\n","<script lang=\"ts\">\nexport interface VisuallyHiddenInputBubbleProps<T> {\n  name: string\n  value: T\n  checked?: boolean\n  required?: boolean\n  disabled?: boolean\n  feature?: VisuallyHiddenProps['feature']\n}\n</script>\n\n<script setup lang=\"ts\" generic=\"T\">\nimport type { VisuallyHiddenProps } from './VisuallyHidden.vue'\nimport { computed, watch } from 'vue'\nimport { usePrimitiveElement } from '@/Primitive'\nimport VisuallyHidden from './VisuallyHidden.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<VisuallyHiddenInputBubbleProps<T>>(), {\n  feature: 'fully-hidden',\n  checked: undefined,\n})\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst valueState = computed(() => props.checked ?? props.value)\n\nwatch(valueState, (cur, prev) => {\n  if (!currentElement.value)\n    return\n\n  const input = currentElement.value as HTMLInputElement\n  const inputProto = window.HTMLInputElement.prototype\n  const descriptor = Object.getOwnPropertyDescriptor(inputProto, 'value') as PropertyDescriptor\n  const setValue = descriptor.set\n  if (setValue && cur !== prev) {\n    const inputEvent = new Event('input', { bubbles: true })\n    const changeEvent = new Event('change', { bubbles: true })\n    setValue.call(input, cur)\n    input.dispatchEvent(inputEvent)\n    input.dispatchEvent(changeEvent)\n  }\n})\n</script>\n\n<template>\n  <VisuallyHidden\n    ref=\"primitiveElement\"\n    v-bind=\"{ ...props, ...$attrs }\"\n    as=\"input\"\n  />\n</template>\n","<script setup lang=\"ts\" generic=\"T\">\nimport type { VisuallyHiddenInputBubbleProps } from './VisuallyHiddenInputBubble.vue'\nimport { computed } from 'vue'\nimport VisuallyHiddenInputBubble from './VisuallyHiddenInputBubble.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<VisuallyHiddenInputBubbleProps<T>>(), {\n  feature: 'fully-hidden',\n  checked: undefined,\n})\n\nconst isFormArrayEmptyAndRequired = computed(() =>\n  typeof props.value === 'object'\n  && Array.isArray(props.value)\n  && props.value.length === 0\n  && props.required,\n)\n\nconst parsedValue = computed(() => {\n  // if primitive value\n  if (typeof props.value === 'string' || typeof props.value === 'number' || typeof props.value === 'boolean' || props.value === null || props.value === undefined) {\n    return [{ name: props.name, value: props.value }]\n  }\n\n  // if array value\n  else if (typeof props.value === 'object' && Array.isArray(props.value)) {\n    return props.value.flatMap((obj, index) => {\n      // if item in array is object\n      if (typeof obj === 'object')\n        return Object.entries(obj).map(([key, value]) => ({ name: `${props.name}[${index}][${key}]`, value }))\n      // if item in array is not object, may be primitive\n      else\n        return ({ name: `${props.name}[${index}]`, value: obj })\n    })\n  }\n\n  // if object value\n  else if (props.value !== null && typeof props.value === 'object' && !Array.isArray(props.value)) {\n    return Object.entries(props.value as object).map(([key, value]) => ({ name: `${props.name}[${key}]`, value }))\n  }\n\n  return []\n})\n</script>\n\n<template>\n  <!-- We render single input if it's required -->\n  <VisuallyHiddenInputBubble\n    v-if=\"isFormArrayEmptyAndRequired\"\n    :key=\"name\"\n    v-bind=\"{ ...props, ...$attrs }\"\n    :name=\"name\"\n    :value=\"value\"\n  />\n\n  <VisuallyHiddenInputBubble\n    v-for=\"parsed in parsedValue\"\n    v-else\n    :key=\"parsed.name\"\n    v-bind=\"{ ...props, ...$attrs }\"\n    :name=\"parsed.name\"\n    :value=\"parsed.value\"\n  />\n</template>\n","<script setup lang=\"ts\" generic=\"T\">\nimport type { VisuallyHiddenInputBubbleProps } from './VisuallyHiddenInputBubble.vue'\nimport { computed } from 'vue'\nimport VisuallyHiddenInputBubble from './VisuallyHiddenInputBubble.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<VisuallyHiddenInputBubbleProps<T>>(), {\n  feature: 'fully-hidden',\n  checked: undefined,\n})\n\nconst isFormArrayEmptyAndRequired = computed(() =>\n  typeof props.value === 'object'\n  && Array.isArray(props.value)\n  && props.value.length === 0\n  && props.required,\n)\n\nconst parsedValue = computed(() => {\n  // if primitive value\n  if (typeof props.value === 'string' || typeof props.value === 'number' || typeof props.value === 'boolean' || props.value === null || props.value === undefined) {\n    return [{ name: props.name, value: props.value }]\n  }\n\n  // if array value\n  else if (typeof props.value === 'object' && Array.isArray(props.value)) {\n    return props.value.flatMap((obj, index) => {\n      // if item in array is object\n      if (typeof obj === 'object')\n        return Object.entries(obj).map(([key, value]) => ({ name: `${props.name}[${index}][${key}]`, value }))\n      // if item in array is not object, may be primitive\n      else\n        return ({ name: `${props.name}[${index}]`, value: obj })\n    })\n  }\n\n  // if object value\n  else if (props.value !== null && typeof props.value === 'object' && !Array.isArray(props.value)) {\n    return Object.entries(props.value as object).map(([key, value]) => ({ name: `${props.name}[${key}]`, value }))\n  }\n\n  return []\n})\n</script>\n\n<template>\n  <!-- We render single input if it's required -->\n  <VisuallyHiddenInputBubble\n    v-if=\"isFormArrayEmptyAndRequired\"\n    :key=\"name\"\n    v-bind=\"{ ...props, ...$attrs }\"\n    :name=\"name\"\n    :value=\"value\"\n  />\n\n  <VisuallyHiddenInputBubble\n    v-for=\"parsed in parsedValue\"\n    v-else\n    :key=\"parsed.name\"\n    v-bind=\"{ ...props, ...$attrs }\"\n    :name=\"parsed.name\"\n    :value=\"parsed.value\"\n  />\n</template>\n","import { isEqual } from 'ohash'\n\nexport function queryCheckedElement(parentEl: HTMLElement | null) {\n  return parentEl?.querySelector('[data-state=checked]') as HTMLElement | null\n}\n\nexport function valueComparator<T>(value: T | T[] | undefined, currentValue: T, comparator?: string | ((a: T, b: T) => boolean)) {\n  if (value === undefined)\n    return false\n  else if (Array.isArray(value))\n    return value.some(val => compare(val, currentValue, comparator))\n  else\n    return compare(value, currentValue, comparator)\n}\n\nexport function compare<T>(value?: T, currentValue?: T, comparator?: string | ((a: T, b: T) => boolean)) {\n  if (value === undefined || currentValue === undefined)\n    return false\n\n  if (typeof value === 'string')\n    return value === currentValue\n\n  if (typeof comparator === 'function')\n    return comparator(value, currentValue)\n\n  if (typeof comparator === 'string')\n    return value?.[comparator as keyof T] === currentValue?.[comparator as keyof T]\n\n  return isEqual(value, currentValue)\n}\n","import { getActiveElement } from '@/shared'\n\nexport type Orientation = 'horizontal' | 'vertical'\nexport type Direction = 'ltr' | 'rtl'\n\nexport const ENTRY_FOCUS = 'rovingFocusGroup.onEntryFocus'\nexport const EVENT_OPTIONS = { bubbles: false, cancelable: true }\n\nexport const MAP_KEY_TO_FOCUS_INTENT: Record<string, FocusIntent> = {\n  ArrowLeft: 'prev',\n  ArrowUp: 'prev',\n  ArrowRight: 'next',\n  ArrowDown: 'next',\n  PageUp: 'first',\n  Home: 'first',\n  PageDown: 'last',\n  End: 'last',\n}\n\nexport function getDirectionAwareKey(key: string, dir?: Direction) {\n  if (dir !== 'rtl')\n    return key\n  return key === 'ArrowLeft'\n    ? 'ArrowRight'\n    : key === 'ArrowRight'\n      ? 'ArrowLeft'\n      : key\n}\n\ntype FocusIntent = 'first' | 'last' | 'prev' | 'next'\n\nexport function getFocusIntent(\n  event: KeyboardEvent,\n  orientation?: Orientation,\n  dir?: Direction,\n) {\n  const key = getDirectionAwareKey(event.key, dir)\n  if (orientation === 'vertical' && ['ArrowLeft', 'ArrowRight'].includes(key))\n    return undefined\n  if (orientation === 'horizontal' && ['ArrowUp', 'ArrowDown'].includes(key))\n    return undefined\n  return MAP_KEY_TO_FOCUS_INTENT[key]\n}\n\nexport function focusFirst(candidates: HTMLElement[], preventScroll = false) {\n  const PREVIOUSLY_FOCUSED_ELEMENT = getActiveElement()\n  for (const candidate of candidates) {\n    // if focus is already where we want to go, we don't want to keep going through the candidates\n    if (candidate === PREVIOUSLY_FOCUSED_ELEMENT)\n      return\n    candidate.focus({ preventScroll })\n    if (getActiveElement() !== PREVIOUSLY_FOCUSED_ELEMENT)\n      return\n  }\n}\n\n/**\n * Wraps an array around itself at a given start index\n * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']`\n */\nexport function wrapArray<T>(array: T[], startIndex: number) {\n  return array.map((_, index) => array[(startIndex + index) % array.length])\n}\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue, DataOrientation, Direction, FormFieldProps } from '@/shared/types'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { getFocusIntent } from '@/RovingFocus/utils'\nimport { createContext, findValuesBetween, useDirection, useFormControl, useKbd, useTypeahead } from '@/shared'\nimport { Primitive } from '..'\n\ntype ListboxRootContext<T> = {\n  modelValue: Ref<T | Array<T> | undefined>\n  onValueChange: (val: T) => void\n  multiple: Ref<boolean>\n  orientation: Ref<DataOrientation>\n  dir: Ref<Direction>\n  disabled: Ref<boolean>\n  highlightOnHover: Ref<boolean>\n  highlightedElement: Ref<HTMLElement | null>\n  isVirtual: Ref<boolean>\n  virtualFocusHook: EventHook<{ event?: Event, scroll: boolean }>\n  virtualKeydownHook: EventHook<KeyboardEvent>\n  virtualHighlightHook: EventHook<any>\n  by?: string | ((a: T, b: T) => boolean)\n  firstValue?: Ref<T | undefined>\n  selectionBehavior?: Ref<'toggle' | 'replace'>\n\n  focusable: Ref<boolean>\n\n  onLeave: (event: Event) => void\n  onEnter: (event: Event) => void\n  changeHighlight: (el: HTMLElement, scrollIntoView?: boolean, focus?: boolean) => void\n  onKeydownNavigation: (event: KeyboardEvent) => void\n  onKeydownEnter: (event: KeyboardEvent) => void\n  onKeydownTypeAhead: (event: KeyboardEvent) => void\n  onCompositionStart: () => void\n  onCompositionEnd: () => void\n  highlightFirstItem: () => void\n}\n\nexport const [injectListboxRootContext, provideListboxRootContext]\n  = createContext<ListboxRootContext<AcceptableValue>>('ListboxRoot')\n\nexport interface ListboxRootProps<T = AcceptableValue> extends PrimitiveProps, FormFieldProps {\n  /** The controlled value of the listbox. Can be binded with `v-model`. */\n  modelValue?: T | Array<T>\n  /** The value of the listbox when initially rendered. Use when you do not need to control the state of the Listbox */\n  defaultValue?: T | Array<T>\n  /** Whether multiple options can be selected or not. */\n  multiple?: boolean\n  /** The orientation of the listbox. <br>Mainly so arrow navigation is done accordingly (left & right vs. up & down) */\n  orientation?: DataOrientation\n  /** The reading direction of the listbox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** When `true`, prevents the user from interacting with listbox */\n  disabled?: boolean\n  /**\n   * How multiple selection should behave in the collection.\n   * @defaultValue 'toggle'\n   */\n  selectionBehavior?: 'toggle' | 'replace'\n  /** When `true`, hover over item will trigger highlight */\n  highlightOnHover?: boolean\n  /** Use this to compare objects by a particular field, or pass your own comparison function for complete control over how objects are compared. */\n  by?: string | ((a: T, b: T) => boolean)\n}\n\nexport type ListboxRootEmits<T = AcceptableValue> = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: T]\n  /** Event handler when highlighted element changes. */\n  'highlight': [payload: { ref: HTMLElement, value: T } | undefined]\n  /** Event handler called when container is being focused. Can be prevented. */\n  'entryFocus': [event: CustomEvent]\n  /** Event handler called when the mouse leave the container */\n  'leave': [event: Event]\n}\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport type { EventHook } from '@vueuse/core'\nimport type { Ref } from 'vue'\nimport { createEventHook, useVModel } from '@vueuse/core'\nimport { isClient } from '@vueuse/shared'\nimport { nextTick, ref, toRefs, watch } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\nimport { compare } from './utils'\n\nconst props = withDefaults(defineProps<ListboxRootProps>(), {\n  selectionBehavior: 'toggle',\n  orientation: 'vertical',\n})\nconst emits = defineEmits<ListboxRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current active value */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { multiple, highlightOnHover, orientation, disabled, selectionBehavior, dir: propDir } = toRefs(props)\nconst { getItems } = useCollection<{ value: T }>({ isProvider: true })\nconst { handleTypeaheadSearch } = useTypeahead()\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst kbd = useKbd()\nconst dir = useDirection(propDir)\n\nconst isFormControl = useFormControl(currentElement)\n\nconst firstValue = ref<T>()\nconst isUserAction = ref(false)\nconst focusable = ref(true)\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? (multiple.value ? [] : undefined),\n  passive: (props.modelValue === undefined) as false,\n  deep: true,\n}) as Ref<T | T[] | undefined>\n\nfunction onValueChange(val: T) {\n  isUserAction.value = true\n  if (props.multiple) {\n    const modelArray = Array.isArray(modelValue.value) ? [...modelValue.value] : []\n    const index = modelArray.findIndex(i => compare(i, val, props.by))\n    if (props.selectionBehavior === 'toggle') {\n      index === -1 ? modelArray.push(val) : modelArray.splice(index, 1)\n      modelValue.value = modelArray\n    }\n    else {\n      modelValue.value = [val]\n      firstValue.value = val\n    }\n  }\n  else {\n    if (props.selectionBehavior === 'toggle') {\n      if (compare(modelValue.value, val, props.by))\n        modelValue.value = undefined\n      else\n        modelValue.value = val\n    }\n    else {\n      modelValue.value = val\n    }\n  }\n  setTimeout(() => {\n    isUserAction.value = false\n  }, 1)\n}\n\nconst highlightedElement = ref<HTMLElement | null>(null)\nconst previousElement = ref<HTMLElement | null>(null)\nconst isVirtual = ref(false)\nconst isComposing = ref(false)\nconst virtualFocusHook = createEventHook<{ event?: Event, scroll: boolean }>()\nconst virtualKeydownHook = createEventHook<KeyboardEvent>()\nconst virtualHighlightHook = createEventHook<T>()\n\nfunction getCollectionItem() {\n  return getItems().map(i => i.ref).filter(i => i.dataset.disabled !== '')\n}\n\nfunction changeHighlight(el: HTMLElement, scrollIntoView = true, focus?: boolean) {\n  if (!el)\n    return\n\n  highlightedElement.value = el\n  if (focus ?? focusable.value)\n    highlightedElement.value.focus()\n  if (scrollIntoView)\n    highlightedElement.value.scrollIntoView({ block: 'nearest' })\n\n  const highlightedItem = getItems().find(i => i.ref === el)\n  emits('highlight', highlightedItem)\n}\n\nfunction highlightItem(value: T) {\n  if (isVirtual.value) {\n    // @ts-expect-error known type issue https://github.com/vueuse/vueuse/issues/4610\n    virtualHighlightHook.trigger(value)\n  }\n  else {\n    const item = getItems().find(i => compare(i.value, value, props.by))\n    if (item) {\n      highlightedElement.value = item.ref\n      changeHighlight(item.ref)\n    }\n  }\n}\n\nfunction onKeydownEnter(event: KeyboardEvent) {\n  if (highlightedElement.value && highlightedElement.value.isConnected) {\n    event.preventDefault()\n    event.stopPropagation()\n\n    if (!isComposing.value) {\n      highlightedElement.value.click()\n    }\n  }\n}\n\nfunction onKeydownTypeAhead(event: KeyboardEvent) {\n  if (!focusable.value)\n    return\n  isUserAction.value = true\n  if (isVirtual.value) {\n    virtualKeydownHook.trigger(event)\n  }\n  else {\n    const isMetaKey = event.altKey || event.ctrlKey || event.metaKey\n\n    if (isMetaKey && event.key === 'a' && multiple.value) {\n      const collection = getItems()\n      const values = collection.map(i => i.value)\n      modelValue.value = [...values]\n      event.preventDefault()\n      const lastItem = collection.at(-1)\n      if (lastItem)\n        changeHighlight(lastItem.ref)\n    }\n    else if (!isMetaKey) {\n      const el = handleTypeaheadSearch(event.key, getItems())\n      if (el)\n        changeHighlight(el)\n    }\n  }\n  setTimeout(() => {\n    isUserAction.value = false\n  }, 1)\n}\n\nfunction onCompositionStart() {\n  isComposing.value = true\n}\nfunction onCompositionEnd() {\n  nextTick(() => {\n    isComposing.value = false\n  })\n}\n\nfunction highlightFirstItem() {\n  nextTick(() => {\n    const event = new KeyboardEvent('keydown', { key: 'PageUp' })\n    onKeydownNavigation(event)\n  })\n}\n\nfunction onLeave(event: Event) {\n  const el = highlightedElement.value\n\n  if ((el as Node)?.isConnected) {\n    previousElement.value = el\n  }\n\n  highlightedElement.value = null\n  emits('leave', event)\n}\n\nfunction onEnter(event: Event) {\n  const entryFocusEvent = new CustomEvent('listbox.entryFocus', { bubbles: false, cancelable: true })\n  event.currentTarget?.dispatchEvent(entryFocusEvent)\n  emits('entryFocus', entryFocusEvent)\n\n  if (entryFocusEvent.defaultPrevented)\n    return\n\n  if (previousElement.value) {\n    changeHighlight(previousElement.value)\n  }\n  else {\n    const el = getCollectionItem()?.[0]\n    changeHighlight(el)\n  }\n}\n\nfunction onKeydownNavigation(event: KeyboardEvent) {\n  const intent = getFocusIntent(event, orientation.value, dir.value)\n  if (!intent)\n    return\n\n  let collection = getCollectionItem()\n  if (highlightedElement.value) {\n    if (intent === 'last') {\n      collection.reverse()\n    }\n    else if (intent === 'prev' || intent === 'next') {\n      if (intent === 'prev')\n        collection.reverse()\n\n      const currentIndex = collection.indexOf(highlightedElement.value)\n      collection = collection.slice(currentIndex + 1)\n    }\n    handleMultipleReplace(event, collection[0])\n  }\n\n  if (collection.length) {\n    const index = !highlightedElement.value && intent === 'prev' ? collection.length - 1 : 0\n    changeHighlight(collection[index])\n  }\n\n  if (isVirtual.value)\n    return virtualKeydownHook.trigger(event)\n}\n\nfunction handleMultipleReplace(event: KeyboardEvent, targetEl: HTMLElement) {\n  if (isVirtual.value || props.selectionBehavior !== 'replace' || !multiple.value || !Array.isArray(modelValue.value))\n    return\n  const isMetaKey = event.altKey || event.ctrlKey || event.metaKey\n  if (isMetaKey && !event.shiftKey)\n    return\n\n  if (event.shiftKey) {\n    const collection = getItems().filter(i => i.ref.dataset.disabled !== '')\n    let lastValue = collection.find(i => i.ref === targetEl)?.value\n\n    if (event.key === kbd.END)\n      lastValue = collection.at(-1)?.value\n    else if (event.key === kbd.HOME)\n      lastValue = collection[0]?.value\n\n    if (!lastValue || !firstValue.value)\n      return\n\n    const values = findValuesBetween(collection.map(i => i.value), firstValue.value, lastValue)\n    modelValue.value = values\n  }\n}\n\nasync function highlightSelected(event?: Event, scroll = true) {\n  // highlightSelected is called inside a watch with immediate set to true.\n  // This results in code execution during SSR.\n  // Ensure this code only runs in a browser environment, since it performs\n  // DOM-only side effects (focus, scrollIntoView, synthetic KeyboardEvent).\n  if (!isClient)\n    return\n  await nextTick()\n  if (isVirtual.value) {\n    // Trigger on nextTick for Virtualizer to be mounted.\n    // `scroll` is `false` on the initial mount highlight, so the virtualizer sets\n    // its roving-tabindex target without focusing/scrolling — otherwise a\n    // virtualized Listbox below the fold would pull the page to it on load.\n    virtualFocusHook.trigger({ event, scroll })\n  }\n  else {\n    const collection = getCollectionItem()\n    const item = collection.find(i => i.dataset.state === 'checked')\n    // On the initial (mount) highlight we only set the roving-tabindex target.\n    // Focusing/scrolling here would scroll the page to a Listbox the user never\n    // interacted with (e.g. one below the fold). Later highlights scroll as before.\n    const focus = scroll ? undefined : false\n    if (item)\n      changeHighlight(item, scroll, focus)\n    else if (collection.length)\n      changeHighlight(collection[0], scroll, focus)\n  }\n}\n\n// `false` until the initial (mount) modelValue highlight has been queued.\n// Flipped synchronously in the watcher so the \"is this the mount highlight?\"\n// decision never depends on nextTick ordering, which differs between a client\n// mount and SSR hydration. The intent travels with the call as an argument\n// rather than via a shared flag released on a later tick.\nlet hasHighlightedOnMount = false\n\n// watch for only programmatic changes\nwatch(modelValue, () => {\n  if (!isUserAction.value) {\n    const scroll = hasHighlightedOnMount\n    hasHighlightedOnMount = true\n    nextTick(() => {\n      highlightSelected(undefined, scroll)\n    })\n  }\n}, { immediate: true, deep: true })\n\ndefineExpose({\n  highlightedElement,\n  highlightItem,\n  highlightFirstItem,\n  highlightSelected,\n  getItems,\n})\n\nprovideListboxRootContext({\n  modelValue,\n  // @ts-expect-error ignoring\n  onValueChange,\n  multiple,\n  orientation,\n  dir,\n  disabled,\n  highlightOnHover,\n  highlightedElement,\n  isVirtual,\n  virtualFocusHook,\n  virtualKeydownHook,\n  virtualHighlightHook,\n  by: props.by,\n  firstValue,\n  selectionBehavior,\n\n  focusable,\n  onLeave,\n  onEnter,\n  changeHighlight,\n  onKeydownEnter,\n  onKeydownNavigation,\n  onKeydownTypeAhead,\n  onCompositionStart,\n  onCompositionEnd,\n  highlightFirstItem,\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :dir=\"dir\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    @pointerleave=\"onLeave\"\n    @focusout=\"async (event: FocusEvent) => {\n      const target = (event.relatedTarget || event.target) as HTMLElement | null\n      await nextTick()\n      if (highlightedElement && currentElement && !currentElement.contains(target)) {\n        onLeave(event)\n      }\n    }\"\n  >\n    <slot :model-value=\"modelValue\" />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      :name=\"name\"\n      :value=\"modelValue\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue, DataOrientation, Direction, FormFieldProps } from '@/shared/types'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { getFocusIntent } from '@/RovingFocus/utils'\nimport { createContext, findValuesBetween, useDirection, useFormControl, useKbd, useTypeahead } from '@/shared'\nimport { Primitive } from '..'\n\ntype ListboxRootContext<T> = {\n  modelValue: Ref<T | Array<T> | undefined>\n  onValueChange: (val: T) => void\n  multiple: Ref<boolean>\n  orientation: Ref<DataOrientation>\n  dir: Ref<Direction>\n  disabled: Ref<boolean>\n  highlightOnHover: Ref<boolean>\n  highlightedElement: Ref<HTMLElement | null>\n  isVirtual: Ref<boolean>\n  virtualFocusHook: EventHook<{ event?: Event, scroll: boolean }>\n  virtualKeydownHook: EventHook<KeyboardEvent>\n  virtualHighlightHook: EventHook<any>\n  by?: string | ((a: T, b: T) => boolean)\n  firstValue?: Ref<T | undefined>\n  selectionBehavior?: Ref<'toggle' | 'replace'>\n\n  focusable: Ref<boolean>\n\n  onLeave: (event: Event) => void\n  onEnter: (event: Event) => void\n  changeHighlight: (el: HTMLElement, scrollIntoView?: boolean, focus?: boolean) => void\n  onKeydownNavigation: (event: KeyboardEvent) => void\n  onKeydownEnter: (event: KeyboardEvent) => void\n  onKeydownTypeAhead: (event: KeyboardEvent) => void\n  onCompositionStart: () => void\n  onCompositionEnd: () => void\n  highlightFirstItem: () => void\n}\n\nexport const [injectListboxRootContext, provideListboxRootContext]\n  = createContext<ListboxRootContext<AcceptableValue>>('ListboxRoot')\n\nexport interface ListboxRootProps<T = AcceptableValue> extends PrimitiveProps, FormFieldProps {\n  /** The controlled value of the listbox. Can be binded with `v-model`. */\n  modelValue?: T | Array<T>\n  /** The value of the listbox when initially rendered. Use when you do not need to control the state of the Listbox */\n  defaultValue?: T | Array<T>\n  /** Whether multiple options can be selected or not. */\n  multiple?: boolean\n  /** The orientation of the listbox. <br>Mainly so arrow navigation is done accordingly (left & right vs. up & down) */\n  orientation?: DataOrientation\n  /** The reading direction of the listbox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** When `true`, prevents the user from interacting with listbox */\n  disabled?: boolean\n  /**\n   * How multiple selection should behave in the collection.\n   * @defaultValue 'toggle'\n   */\n  selectionBehavior?: 'toggle' | 'replace'\n  /** When `true`, hover over item will trigger highlight */\n  highlightOnHover?: boolean\n  /** Use this to compare objects by a particular field, or pass your own comparison function for complete control over how objects are compared. */\n  by?: string | ((a: T, b: T) => boolean)\n}\n\nexport type ListboxRootEmits<T = AcceptableValue> = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: T]\n  /** Event handler when highlighted element changes. */\n  'highlight': [payload: { ref: HTMLElement, value: T } | undefined]\n  /** Event handler called when container is being focused. Can be prevented. */\n  'entryFocus': [event: CustomEvent]\n  /** Event handler called when the mouse leave the container */\n  'leave': [event: Event]\n}\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport type { EventHook } from '@vueuse/core'\nimport type { Ref } from 'vue'\nimport { createEventHook, useVModel } from '@vueuse/core'\nimport { isClient } from '@vueuse/shared'\nimport { nextTick, ref, toRefs, watch } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\nimport { compare } from './utils'\n\nconst props = withDefaults(defineProps<ListboxRootProps>(), {\n  selectionBehavior: 'toggle',\n  orientation: 'vertical',\n})\nconst emits = defineEmits<ListboxRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current active value */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { multiple, highlightOnHover, orientation, disabled, selectionBehavior, dir: propDir } = toRefs(props)\nconst { getItems } = useCollection<{ value: T }>({ isProvider: true })\nconst { handleTypeaheadSearch } = useTypeahead()\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst kbd = useKbd()\nconst dir = useDirection(propDir)\n\nconst isFormControl = useFormControl(currentElement)\n\nconst firstValue = ref<T>()\nconst isUserAction = ref(false)\nconst focusable = ref(true)\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? (multiple.value ? [] : undefined),\n  passive: (props.modelValue === undefined) as false,\n  deep: true,\n}) as Ref<T | T[] | undefined>\n\nfunction onValueChange(val: T) {\n  isUserAction.value = true\n  if (props.multiple) {\n    const modelArray = Array.isArray(modelValue.value) ? [...modelValue.value] : []\n    const index = modelArray.findIndex(i => compare(i, val, props.by))\n    if (props.selectionBehavior === 'toggle') {\n      index === -1 ? modelArray.push(val) : modelArray.splice(index, 1)\n      modelValue.value = modelArray\n    }\n    else {\n      modelValue.value = [val]\n      firstValue.value = val\n    }\n  }\n  else {\n    if (props.selectionBehavior === 'toggle') {\n      if (compare(modelValue.value, val, props.by))\n        modelValue.value = undefined\n      else\n        modelValue.value = val\n    }\n    else {\n      modelValue.value = val\n    }\n  }\n  setTimeout(() => {\n    isUserAction.value = false\n  }, 1)\n}\n\nconst highlightedElement = ref<HTMLElement | null>(null)\nconst previousElement = ref<HTMLElement | null>(null)\nconst isVirtual = ref(false)\nconst isComposing = ref(false)\nconst virtualFocusHook = createEventHook<{ event?: Event, scroll: boolean }>()\nconst virtualKeydownHook = createEventHook<KeyboardEvent>()\nconst virtualHighlightHook = createEventHook<T>()\n\nfunction getCollectionItem() {\n  return getItems().map(i => i.ref).filter(i => i.dataset.disabled !== '')\n}\n\nfunction changeHighlight(el: HTMLElement, scrollIntoView = true, focus?: boolean) {\n  if (!el)\n    return\n\n  highlightedElement.value = el\n  if (focus ?? focusable.value)\n    highlightedElement.value.focus()\n  if (scrollIntoView)\n    highlightedElement.value.scrollIntoView({ block: 'nearest' })\n\n  const highlightedItem = getItems().find(i => i.ref === el)\n  emits('highlight', highlightedItem)\n}\n\nfunction highlightItem(value: T) {\n  if (isVirtual.value) {\n    // @ts-expect-error known type issue https://github.com/vueuse/vueuse/issues/4610\n    virtualHighlightHook.trigger(value)\n  }\n  else {\n    const item = getItems().find(i => compare(i.value, value, props.by))\n    if (item) {\n      highlightedElement.value = item.ref\n      changeHighlight(item.ref)\n    }\n  }\n}\n\nfunction onKeydownEnter(event: KeyboardEvent) {\n  if (highlightedElement.value && highlightedElement.value.isConnected) {\n    event.preventDefault()\n    event.stopPropagation()\n\n    if (!isComposing.value) {\n      highlightedElement.value.click()\n    }\n  }\n}\n\nfunction onKeydownTypeAhead(event: KeyboardEvent) {\n  if (!focusable.value)\n    return\n  isUserAction.value = true\n  if (isVirtual.value) {\n    virtualKeydownHook.trigger(event)\n  }\n  else {\n    const isMetaKey = event.altKey || event.ctrlKey || event.metaKey\n\n    if (isMetaKey && event.key === 'a' && multiple.value) {\n      const collection = getItems()\n      const values = collection.map(i => i.value)\n      modelValue.value = [...values]\n      event.preventDefault()\n      const lastItem = collection.at(-1)\n      if (lastItem)\n        changeHighlight(lastItem.ref)\n    }\n    else if (!isMetaKey) {\n      const el = handleTypeaheadSearch(event.key, getItems())\n      if (el)\n        changeHighlight(el)\n    }\n  }\n  setTimeout(() => {\n    isUserAction.value = false\n  }, 1)\n}\n\nfunction onCompositionStart() {\n  isComposing.value = true\n}\nfunction onCompositionEnd() {\n  nextTick(() => {\n    isComposing.value = false\n  })\n}\n\nfunction highlightFirstItem() {\n  nextTick(() => {\n    const event = new KeyboardEvent('keydown', { key: 'PageUp' })\n    onKeydownNavigation(event)\n  })\n}\n\nfunction onLeave(event: Event) {\n  const el = highlightedElement.value\n\n  if ((el as Node)?.isConnected) {\n    previousElement.value = el\n  }\n\n  highlightedElement.value = null\n  emits('leave', event)\n}\n\nfunction onEnter(event: Event) {\n  const entryFocusEvent = new CustomEvent('listbox.entryFocus', { bubbles: false, cancelable: true })\n  event.currentTarget?.dispatchEvent(entryFocusEvent)\n  emits('entryFocus', entryFocusEvent)\n\n  if (entryFocusEvent.defaultPrevented)\n    return\n\n  if (previousElement.value) {\n    changeHighlight(previousElement.value)\n  }\n  else {\n    const el = getCollectionItem()?.[0]\n    changeHighlight(el)\n  }\n}\n\nfunction onKeydownNavigation(event: KeyboardEvent) {\n  const intent = getFocusIntent(event, orientation.value, dir.value)\n  if (!intent)\n    return\n\n  let collection = getCollectionItem()\n  if (highlightedElement.value) {\n    if (intent === 'last') {\n      collection.reverse()\n    }\n    else if (intent === 'prev' || intent === 'next') {\n      if (intent === 'prev')\n        collection.reverse()\n\n      const currentIndex = collection.indexOf(highlightedElement.value)\n      collection = collection.slice(currentIndex + 1)\n    }\n    handleMultipleReplace(event, collection[0])\n  }\n\n  if (collection.length) {\n    const index = !highlightedElement.value && intent === 'prev' ? collection.length - 1 : 0\n    changeHighlight(collection[index])\n  }\n\n  if (isVirtual.value)\n    return virtualKeydownHook.trigger(event)\n}\n\nfunction handleMultipleReplace(event: KeyboardEvent, targetEl: HTMLElement) {\n  if (isVirtual.value || props.selectionBehavior !== 'replace' || !multiple.value || !Array.isArray(modelValue.value))\n    return\n  const isMetaKey = event.altKey || event.ctrlKey || event.metaKey\n  if (isMetaKey && !event.shiftKey)\n    return\n\n  if (event.shiftKey) {\n    const collection = getItems().filter(i => i.ref.dataset.disabled !== '')\n    let lastValue = collection.find(i => i.ref === targetEl)?.value\n\n    if (event.key === kbd.END)\n      lastValue = collection.at(-1)?.value\n    else if (event.key === kbd.HOME)\n      lastValue = collection[0]?.value\n\n    if (!lastValue || !firstValue.value)\n      return\n\n    const values = findValuesBetween(collection.map(i => i.value), firstValue.value, lastValue)\n    modelValue.value = values\n  }\n}\n\nasync function highlightSelected(event?: Event, scroll = true) {\n  // highlightSelected is called inside a watch with immediate set to true.\n  // This results in code execution during SSR.\n  // Ensure this code only runs in a browser environment, since it performs\n  // DOM-only side effects (focus, scrollIntoView, synthetic KeyboardEvent).\n  if (!isClient)\n    return\n  await nextTick()\n  if (isVirtual.value) {\n    // Trigger on nextTick for Virtualizer to be mounted.\n    // `scroll` is `false` on the initial mount highlight, so the virtualizer sets\n    // its roving-tabindex target without focusing/scrolling — otherwise a\n    // virtualized Listbox below the fold would pull the page to it on load.\n    virtualFocusHook.trigger({ event, scroll })\n  }\n  else {\n    const collection = getCollectionItem()\n    const item = collection.find(i => i.dataset.state === 'checked')\n    // On the initial (mount) highlight we only set the roving-tabindex target.\n    // Focusing/scrolling here would scroll the page to a Listbox the user never\n    // interacted with (e.g. one below the fold). Later highlights scroll as before.\n    const focus = scroll ? undefined : false\n    if (item)\n      changeHighlight(item, scroll, focus)\n    else if (collection.length)\n      changeHighlight(collection[0], scroll, focus)\n  }\n}\n\n// `false` until the initial (mount) modelValue highlight has been queued.\n// Flipped synchronously in the watcher so the \"is this the mount highlight?\"\n// decision never depends on nextTick ordering, which differs between a client\n// mount and SSR hydration. The intent travels with the call as an argument\n// rather than via a shared flag released on a later tick.\nlet hasHighlightedOnMount = false\n\n// watch for only programmatic changes\nwatch(modelValue, () => {\n  if (!isUserAction.value) {\n    const scroll = hasHighlightedOnMount\n    hasHighlightedOnMount = true\n    nextTick(() => {\n      highlightSelected(undefined, scroll)\n    })\n  }\n}, { immediate: true, deep: true })\n\ndefineExpose({\n  highlightedElement,\n  highlightItem,\n  highlightFirstItem,\n  highlightSelected,\n  getItems,\n})\n\nprovideListboxRootContext({\n  modelValue,\n  // @ts-expect-error ignoring\n  onValueChange,\n  multiple,\n  orientation,\n  dir,\n  disabled,\n  highlightOnHover,\n  highlightedElement,\n  isVirtual,\n  virtualFocusHook,\n  virtualKeydownHook,\n  virtualHighlightHook,\n  by: props.by,\n  firstValue,\n  selectionBehavior,\n\n  focusable,\n  onLeave,\n  onEnter,\n  changeHighlight,\n  onKeydownEnter,\n  onKeydownNavigation,\n  onKeydownTypeAhead,\n  onCompositionStart,\n  onCompositionEnd,\n  highlightFirstItem,\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :dir=\"dir\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    @pointerleave=\"onLeave\"\n    @focusout=\"async (event: FocusEvent) => {\n      const target = (event.relatedTarget || event.target) as HTMLElement | null\n      await nextTick()\n      if (highlightedElement && currentElement && !currentElement.contains(target)) {\n        onLeave(event)\n      }\n    }\"\n  >\n    <slot :model-value=\"modelValue\" />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      :name=\"name\"\n      :value=\"modelValue\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '..'\nimport { refAutoReset } from '@vueuse/shared'\nimport { Primitive } from '..'\nimport { injectListboxRootContext } from './ListboxRoot.vue'\n\nexport interface ListboxContentProps extends PrimitiveProps { }\n</script>\n\n<script setup lang=\"ts\">\nimport { useCollection } from '@/Collection'\n\ndefineProps<ListboxContentProps>()\n\nconst { CollectionSlot } = useCollection()\nconst rootContext = injectListboxRootContext()\n\nconst isClickFocus = refAutoReset(false, 10)\n</script>\n\n<template>\n  <CollectionSlot>\n    <Primitive\n      role=\"listbox\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :tabindex=\"rootContext.focusable.value ? rootContext.highlightedElement.value ? '-1' : '0' : '-1'\"\n      :aria-orientation=\"rootContext.orientation.value\"\n      :aria-multiselectable=\"!!rootContext.multiple.value\"\n      :data-orientation=\"rootContext.orientation.value\"\n      @mousedown.left=\"isClickFocus = true\"\n      @focus=\"(ev: FocusEvent) => {\n        if (isClickFocus)\n          return\n        rootContext.onEnter(ev)\n      }\"\n      @keydown.down.up.left.right.home.end=\"(event: KeyboardEvent) => {\n        if (\n          // when orientation is vertical, ignore left/right\n          (\n            rootContext.orientation.value === 'vertical'\n            && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')\n          )\n          // when orientation is horizontal, ignore up/down\n          || (\n            rootContext.orientation.value === 'horizontal'\n            && (event.key === 'ArrowUp' || event.key === 'ArrowDown')\n          )\n        ) {\n          return\n        }\n\n        event.preventDefault()\n        rootContext.focusable.value ? rootContext.onKeydownNavigation(event) : undefined\n      }\"\n      @keydown.enter=\"rootContext.onKeydownEnter\"\n      @keydown=\"rootContext.onKeydownTypeAhead\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '..'\nimport { refAutoReset } from '@vueuse/shared'\nimport { Primitive } from '..'\nimport { injectListboxRootContext } from './ListboxRoot.vue'\n\nexport interface ListboxContentProps extends PrimitiveProps { }\n</script>\n\n<script setup lang=\"ts\">\nimport { useCollection } from '@/Collection'\n\ndefineProps<ListboxContentProps>()\n\nconst { CollectionSlot } = useCollection()\nconst rootContext = injectListboxRootContext()\n\nconst isClickFocus = refAutoReset(false, 10)\n</script>\n\n<template>\n  <CollectionSlot>\n    <Primitive\n      role=\"listbox\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :tabindex=\"rootContext.focusable.value ? rootContext.highlightedElement.value ? '-1' : '0' : '-1'\"\n      :aria-orientation=\"rootContext.orientation.value\"\n      :aria-multiselectable=\"!!rootContext.multiple.value\"\n      :data-orientation=\"rootContext.orientation.value\"\n      @mousedown.left=\"isClickFocus = true\"\n      @focus=\"(ev: FocusEvent) => {\n        if (isClickFocus)\n          return\n        rootContext.onEnter(ev)\n      }\"\n      @keydown.down.up.left.right.home.end=\"(event: KeyboardEvent) => {\n        if (\n          // when orientation is vertical, ignore left/right\n          (\n            rootContext.orientation.value === 'vertical'\n            && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')\n          )\n          // when orientation is horizontal, ignore up/down\n          || (\n            rootContext.orientation.value === 'horizontal'\n            && (event.key === 'ArrowUp' || event.key === 'ArrowDown')\n          )\n        ) {\n          return\n        }\n\n        event.preventDefault()\n        rootContext.focusable.value ? rootContext.onKeydownNavigation(event) : undefined\n      }\"\n      @keydown.enter=\"rootContext.onKeydownEnter\"\n      @keydown=\"rootContext.onKeydownTypeAhead\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '..'\nimport { useVModel } from '@vueuse/core'\nimport { computed, onMounted, onUnmounted, ref, watchSyncEffect } from 'vue'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { useComposing } from '@/shared'\nimport { Primitive } from '..'\nimport { injectListboxRootContext } from './ListboxRoot.vue'\n\nexport interface ListboxFilterProps extends PrimitiveProps {\n  /** The controlled value of the filter. Can be binded with v-model. */\n  modelValue?: string\n  /** Focus on element when mounted. */\n  autoFocus?: boolean\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n}\n\nexport type ListboxFilterEmits = {\n  'update:modelValue': [string]\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = withDefaults(defineProps<ListboxFilterProps>(), {\n  as: 'input',\n})\nconst emits = defineEmits<ListboxFilterEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: '',\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst rootContext = injectListboxRootContext()\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst disabled = computed(() => props.disabled || rootContext.disabled.value || false)\n\nconst activedescendant = ref<string | undefined>()\nwatchSyncEffect(() => activedescendant.value = rootContext.highlightedElement.value?.id)\n\nonMounted(() => {\n  rootContext.focusable.value = false\n\n  setTimeout(() => {\n    // make sure all DOM was flush then only capture the focus\n    if (props.autoFocus)\n      currentElement.value?.focus()\n  }, 1)\n})\n\nonUnmounted(() => {\n  rootContext.focusable.value = true\n})\n\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing((event) => {\n  modelValue.value = (event.target as HTMLInputElement).value\n  rootContext.onCompositionEnd()\n  rootContext.highlightFirstItem()\n})\n\nfunction onCompositionStart() {\n  rootContext.onCompositionStart()\n  handleCompositionStart()\n}\n\nfunction handleInput(event: InputEvent) {\n  if (isComposing.value)\n    return\n  modelValue.value = (event.target as HTMLInputElement).value\n  rootContext.highlightFirstItem()\n}\n\nfunction handleKeydownNavigation(event: KeyboardEvent) {\n  // Don't navigate mid-composition, arrow keys are used for IME candidate navigation\n  if (isComposing.value)\n    return\n  event.preventDefault()\n  rootContext.onKeydownNavigation(event)\n}\n\nfunction handleKeydownEnter(event: KeyboardEvent) {\n  // Don't select mid-composition, Enter commits the IME candidate\n  if (isComposing.value)\n    return\n  rootContext.onKeydownEnter(event)\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :value=\"modelValue\"\n    :disabled=\"disabled ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :aria-disabled=\"disabled ?? undefined\"\n    :aria-activedescendant=\"activedescendant\"\n    type=\"text\"\n    @keydown.down.up.home.end=\"handleKeydownNavigation\"\n    @keydown.enter=\"handleKeydownEnter\"\n    @input=\"handleInput\"\n    @compositionstart=\"onCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot :model-value=\"modelValue\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '..'\nimport { useVModel } from '@vueuse/core'\nimport { computed, onMounted, onUnmounted, ref, watchSyncEffect } from 'vue'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { useComposing } from '@/shared'\nimport { Primitive } from '..'\nimport { injectListboxRootContext } from './ListboxRoot.vue'\n\nexport interface ListboxFilterProps extends PrimitiveProps {\n  /** The controlled value of the filter. Can be binded with v-model. */\n  modelValue?: string\n  /** Focus on element when mounted. */\n  autoFocus?: boolean\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n}\n\nexport type ListboxFilterEmits = {\n  'update:modelValue': [string]\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = withDefaults(defineProps<ListboxFilterProps>(), {\n  as: 'input',\n})\nconst emits = defineEmits<ListboxFilterEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: '',\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst rootContext = injectListboxRootContext()\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst disabled = computed(() => props.disabled || rootContext.disabled.value || false)\n\nconst activedescendant = ref<string | undefined>()\nwatchSyncEffect(() => activedescendant.value = rootContext.highlightedElement.value?.id)\n\nonMounted(() => {\n  rootContext.focusable.value = false\n\n  setTimeout(() => {\n    // make sure all DOM was flush then only capture the focus\n    if (props.autoFocus)\n      currentElement.value?.focus()\n  }, 1)\n})\n\nonUnmounted(() => {\n  rootContext.focusable.value = true\n})\n\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing((event) => {\n  modelValue.value = (event.target as HTMLInputElement).value\n  rootContext.onCompositionEnd()\n  rootContext.highlightFirstItem()\n})\n\nfunction onCompositionStart() {\n  rootContext.onCompositionStart()\n  handleCompositionStart()\n}\n\nfunction handleInput(event: InputEvent) {\n  if (isComposing.value)\n    return\n  modelValue.value = (event.target as HTMLInputElement).value\n  rootContext.highlightFirstItem()\n}\n\nfunction handleKeydownNavigation(event: KeyboardEvent) {\n  // Don't navigate mid-composition, arrow keys are used for IME candidate navigation\n  if (isComposing.value)\n    return\n  event.preventDefault()\n  rootContext.onKeydownNavigation(event)\n}\n\nfunction handleKeydownEnter(event: KeyboardEvent) {\n  // Don't select mid-composition, Enter commits the IME candidate\n  if (isComposing.value)\n    return\n  rootContext.onKeydownEnter(event)\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :value=\"modelValue\"\n    :disabled=\"disabled ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :aria-disabled=\"disabled ?? undefined\"\n    :aria-activedescendant=\"activedescendant\"\n    type=\"text\"\n    @keydown.down.up.home.end=\"handleKeydownNavigation\"\n    @keydown.enter=\"handleKeydownEnter\"\n    @input=\"handleInput\"\n    @compositionstart=\"onCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot :model-value=\"modelValue\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useId } from '@/shared'\n\nexport interface ListboxGroupProps extends PrimitiveProps {}\n\ninterface ListboxGroupContext {\n  id: string\n}\n\nexport const [injectListboxGroupContext, provideListboxGroupContext]\n  = createContext<ListboxGroupContext>('ListboxGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<ListboxGroupProps>()\n\nconst id = useId(undefined, 'reka-listbox-group')\nprovideListboxGroupContext({ id })\n</script>\n\n<template>\n  <Primitive\n    role=\"group\"\n    v-bind=\"props\"\n    :aria-labelledby=\"id\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useId } from '@/shared'\n\nexport interface ListboxGroupProps extends PrimitiveProps {}\n\ninterface ListboxGroupContext {\n  id: string\n}\n\nexport const [injectListboxGroupContext, provideListboxGroupContext]\n  = createContext<ListboxGroupContext>('ListboxGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<ListboxGroupProps>()\n\nconst id = useId(undefined, 'reka-listbox-group')\nprovideListboxGroupContext({ id })\n</script>\n\n<template>\n  <Primitive\n    role=\"group\"\n    v-bind=\"props\"\n    :aria-labelledby=\"id\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ListboxGroupLabelProps extends PrimitiveProps {\n  for?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectListboxGroupContext } from './ListboxGroup.vue'\n\nconst props = withDefaults(defineProps<ListboxGroupLabelProps>(), {\n  as: 'div',\n})\n\nconst groupContext = injectListboxGroupContext({ id: '' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"groupContext.id\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ListboxGroupLabelProps extends PrimitiveProps {\n  for?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectListboxGroupContext } from './ListboxGroup.vue'\n\nconst props = withDefaults(defineProps<ListboxGroupLabelProps>(), {\n  as: 'div',\n})\n\nconst groupContext = injectListboxGroupContext({ id: '' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"groupContext.id\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport { createContext, handleAndDispatchCustomEvent, useForwardExpose, useId } from '@/shared'\n\nexport interface ListboxItemProps<T = AcceptableValue> extends PrimitiveProps {\n  /** The value given as data when submitted with a `name`. */\n  value: T\n  /** When `true`, prevents the user from interacting with the item. */\n  disabled?: boolean\n}\nexport type SelectEvent<T> = CustomEvent<{ originalEvent: PointerEvent, value?: T }>\n\nexport type ListboxItemEmits<T = AcceptableValue> = {\n  /** Event handler called when the selecting item. <br> It can be prevented by calling `event.preventDefault`. */\n  select: [event: SelectEvent<T>]\n}\n\nconst LISTBOX_SELECT = 'listbox.select'\n\ninterface ListboxItemContext {\n  isSelected: Ref<boolean>\n}\n\nexport const [injectListboxItemContext, provideListboxItemContext]\n  = createContext<ListboxItemContext>('ListboxItem')\n</script>\n\n<script setup lang=\"ts\"  generic=\"T extends AcceptableValue = AcceptableValue\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '..'\nimport type { AcceptableValue } from '@/shared/types'\nimport { computed } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '..'\nimport { injectListboxRootContext } from './ListboxRoot.vue'\nimport { valueComparator } from './utils'\n\nconst props = withDefaults(defineProps<ListboxItemProps<T>>(), {\n  as: 'div',\n})\nconst emits = defineEmits<ListboxItemEmits<T>>()\n\nconst id = useId(undefined, 'reka-listbox-item')\nconst { CollectionItem } = useCollection()\nconst { forwardRef, currentElement } = useForwardExpose()\nconst rootContext = injectListboxRootContext()\n\nconst isHighlighted = computed(() => currentElement.value != null && currentElement.value === rootContext.highlightedElement.value)\nconst isSelected = computed(() => valueComparator(rootContext.modelValue.value, props.value, rootContext.by))\n\nconst disabled = computed(() => rootContext.disabled.value || props.disabled)\n\nasync function handleSelect(ev: SelectEvent<T>) {\n  emits('select', ev)\n  if (ev?.defaultPrevented)\n    return\n\n  if (!disabled.value && ev) {\n    rootContext.onValueChange(props.value)\n    rootContext.changeHighlight(currentElement.value)\n  }\n}\n\nfunction handleSelectCustomEvent(ev: PointerEvent) {\n  const eventDetail = { originalEvent: ev, value: props.value as T }\n  handleAndDispatchCustomEvent(LISTBOX_SELECT, handleSelect, eventDetail)\n}\n\nprovideListboxItemContext({\n  isSelected,\n})\n</script>\n\n<template>\n  <CollectionItem :value=\"value\">\n    <Primitive\n      :id=\"id\"\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      v-memo=\"[isHighlighted, isSelected, disabled, rootContext.focusable.value]\"\n      role=\"option\"\n      :tabindex=\"rootContext.focusable.value ? isHighlighted ? '0' : '-1' : -1\"\n      :aria-selected=\"isSelected\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :disabled=\"disabled ? '' : undefined\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :data-highlighted=\"isHighlighted ? '' : undefined\"\n      :data-state=\"isSelected ? 'checked' : 'unchecked'\"\n      @click=\"handleSelectCustomEvent\"\n      @keydown.space.prevent=\"handleSelectCustomEvent\"\n      @pointermove=\"() => {\n        if (rootContext.highlightedElement.value === currentElement)\n          return\n\n        if (rootContext.highlightOnHover.value)\n          rootContext.changeHighlight(currentElement, false, false)\n      }\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport { createContext, handleAndDispatchCustomEvent, useForwardExpose, useId } from '@/shared'\n\nexport interface ListboxItemProps<T = AcceptableValue> extends PrimitiveProps {\n  /** The value given as data when submitted with a `name`. */\n  value: T\n  /** When `true`, prevents the user from interacting with the item. */\n  disabled?: boolean\n}\nexport type SelectEvent<T> = CustomEvent<{ originalEvent: PointerEvent, value?: T }>\n\nexport type ListboxItemEmits<T = AcceptableValue> = {\n  /** Event handler called when the selecting item. <br> It can be prevented by calling `event.preventDefault`. */\n  select: [event: SelectEvent<T>]\n}\n\nconst LISTBOX_SELECT = 'listbox.select'\n\ninterface ListboxItemContext {\n  isSelected: Ref<boolean>\n}\n\nexport const [injectListboxItemContext, provideListboxItemContext]\n  = createContext<ListboxItemContext>('ListboxItem')\n</script>\n\n<script setup lang=\"ts\"  generic=\"T extends AcceptableValue = AcceptableValue\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '..'\nimport type { AcceptableValue } from '@/shared/types'\nimport { computed } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '..'\nimport { injectListboxRootContext } from './ListboxRoot.vue'\nimport { valueComparator } from './utils'\n\nconst props = withDefaults(defineProps<ListboxItemProps<T>>(), {\n  as: 'div',\n})\nconst emits = defineEmits<ListboxItemEmits<T>>()\n\nconst id = useId(undefined, 'reka-listbox-item')\nconst { CollectionItem } = useCollection()\nconst { forwardRef, currentElement } = useForwardExpose()\nconst rootContext = injectListboxRootContext()\n\nconst isHighlighted = computed(() => currentElement.value != null && currentElement.value === rootContext.highlightedElement.value)\nconst isSelected = computed(() => valueComparator(rootContext.modelValue.value, props.value, rootContext.by))\n\nconst disabled = computed(() => rootContext.disabled.value || props.disabled)\n\nasync function handleSelect(ev: SelectEvent<T>) {\n  emits('select', ev)\n  if (ev?.defaultPrevented)\n    return\n\n  if (!disabled.value && ev) {\n    rootContext.onValueChange(props.value)\n    rootContext.changeHighlight(currentElement.value)\n  }\n}\n\nfunction handleSelectCustomEvent(ev: PointerEvent) {\n  const eventDetail = { originalEvent: ev, value: props.value as T }\n  handleAndDispatchCustomEvent(LISTBOX_SELECT, handleSelect, eventDetail)\n}\n\nprovideListboxItemContext({\n  isSelected,\n})\n</script>\n\n<template>\n  <CollectionItem :value=\"value\">\n    <Primitive\n      :id=\"id\"\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      v-memo=\"[isHighlighted, isSelected, disabled, rootContext.focusable.value]\"\n      role=\"option\"\n      :tabindex=\"rootContext.focusable.value ? isHighlighted ? '0' : '-1' : -1\"\n      :aria-selected=\"isSelected\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :disabled=\"disabled ? '' : undefined\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :data-highlighted=\"isHighlighted ? '' : undefined\"\n      :data-state=\"isSelected ? 'checked' : 'unchecked'\"\n      @click=\"handleSelectCustomEvent\"\n      @keydown.space.prevent=\"handleSelectCustomEvent\"\n      @pointermove=\"() => {\n        if (rootContext.highlightedElement.value === currentElement)\n          return\n\n        if (rootContext.highlightOnHover.value)\n          rootContext.changeHighlight(currentElement, false, false)\n      }\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ListboxItemIndicatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectListboxItemContext } from './ListboxItem.vue'\n\nconst props = withDefaults(defineProps<ListboxItemIndicatorProps>(), {\n  as: 'span',\n})\n\nuseForwardExpose()\nconst itemContext = injectListboxItemContext()\n</script>\n\n<template>\n  <Primitive\n    v-if=\"itemContext.isSelected.value\"\n    aria-hidden=\"true\"\n    v-bind=\"props\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ListboxItemIndicatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectListboxItemContext } from './ListboxItem.vue'\n\nconst props = withDefaults(defineProps<ListboxItemIndicatorProps>(), {\n  as: 'span',\n})\n\nuseForwardExpose()\nconst itemContext = injectListboxItemContext()\n</script>\n\n<template>\n  <Primitive\n    v-if=\"itemContext.isSelected.value\"\n    aria-hidden=\"true\"\n    v-bind=\"props\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","// Lazy materialization for the lanes===1 fast path. Backed by a\n// Float64Array (stride 2: start, size, …); VirtualItems are constructed on\n// first indexed read and cached. Saves the per-item object allocation at\n// large list counts where most items are never visible.\n\nimport type { VirtualItem } from './index'\n\ntype Key = number | string | bigint\n\nexport function createLazyMeasurementsView(\n  count: number,\n  flat: Float64Array,\n  getItemKey: (i: number) => Key,\n): Array<VirtualItem> {\n  const cache: Array<VirtualItem | undefined> = new Array(count)\n  return new Proxy(cache as any, {\n    get(target, prop, receiver) {\n      if (typeof prop === 'string') {\n        // Cheap digit-prefix sniff before number coerce.\n        const c = prop.charCodeAt(0)\n        if (c >= 48 && c <= 57) {\n          const i = +prop\n          if (Number.isInteger(i) && i >= 0 && i < count) {\n            let v = target[i]\n            if (!v) {\n              const s = flat[i * 2]!\n              v = target[i] = {\n                index: i,\n                key: getItemKey(i),\n                start: s,\n                size: flat[i * 2 + 1]!,\n                end: s + flat[i * 2 + 1]!,\n                lane: 0,\n              }\n            }\n            return v\n          }\n        }\n        if (prop === 'length') return count\n      }\n      return Reflect.get(target, prop, receiver)\n    },\n  }) as Array<VirtualItem>\n}\n","export type NoInfer<A extends any> = [A][A extends any ? 0 : never]\n\nexport type PartialKeys<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>\n\nexport function memo<TDeps extends ReadonlyArray<any>, TResult>(\n  getDeps: () => [...TDeps],\n  fn: (...args: NoInfer<[...TDeps]>) => TResult,\n  opts: {\n    key: false | string\n    debug?: () => boolean\n    onChange?: (result: TResult) => void\n    initialDeps?: TDeps\n    skipInitialOnChange?: boolean\n  },\n) {\n  let deps = opts.initialDeps ?? []\n  let result: TResult | undefined\n  let isInitial = true\n\n  function memoizedFunction(): TResult {\n    // Debug-only timing. In production builds, `process.env.NODE_ENV !==\n    // 'production'` is constant-folded to `false` by downstream minifiers\n    // (Terser/esbuild/swc with `define`), which DCEs the entire block.\n    const debugEnabled =\n      process.env.NODE_ENV !== 'production' && !!opts.key && !!opts.debug?.()\n    let depTime = 0\n    if (debugEnabled) depTime = Date.now()\n\n    const newDeps = getDeps()\n\n    const depsChanged =\n      newDeps.length !== deps.length ||\n      newDeps.some((dep: any, index: number) => deps[index] !== dep)\n\n    if (!depsChanged) {\n      return result!\n    }\n\n    deps = newDeps\n\n    let resultTime = 0\n    if (debugEnabled) resultTime = Date.now()\n\n    result = fn(...newDeps)\n\n    if (debugEnabled) {\n      const depEndTime = Math.round((Date.now() - depTime) * 100) / 100\n      const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100\n      const resultFpsPercentage = resultEndTime / 16\n\n      const pad = (str: number | string, num: number) => {\n        str = String(str)\n        while (str.length < num) {\n          str = ' ' + str\n        }\n        return str\n      }\n\n      console.info(\n        `%c⏱ ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`,\n        `\n            font-size: .6rem;\n            font-weight: bold;\n            color: hsl(${Math.max(\n              0,\n              Math.min(120 - 120 * resultFpsPercentage, 120),\n            )}deg 100% 31%);`,\n        opts?.key,\n      )\n    }\n\n    if (opts?.onChange && !(isInitial && opts.skipInitialOnChange)) {\n      opts.onChange(result)\n    }\n\n    isInitial = false\n\n    return result\n  }\n\n  // Attach updateDeps to the function itself\n  memoizedFunction.updateDeps = (newDeps: [...TDeps]) => {\n    deps = newDeps\n  }\n\n  return memoizedFunction\n}\n\nexport function notUndefined<T>(value: T | undefined, msg?: string): T {\n  if (value === undefined) {\n    throw new Error(`Unexpected undefined${msg ? `: ${msg}` : ''}`)\n  } else {\n    return value\n  }\n}\n\nexport const approxEqual = (a: number, b: number) => Math.abs(a - b) < 1.01\n\nexport const debounce = (\n  targetWindow: Window & typeof globalThis,\n  fn: Function,\n  ms: number,\n) => {\n  let timeoutId: number\n  return function (this: any, ...args: Array<any>) {\n    targetWindow.clearTimeout(timeoutId)\n    timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms)\n  }\n}\n","import { createLazyMeasurementsView } from './lazy-measurements'\nimport { approxEqual, debounce, memo, notUndefined } from './utils'\n\n// Browser-aware iOS detection. Programmatic `scrollTo`/`scrollTop` writes\n// during a momentum-scroll cancel the momentum on iOS WebKit, so we defer\n// scroll-position adjustments triggered by mid-scroll resizes until the\n// scroll settles. SSR-safe (returns false when navigator is unavailable).\nlet _isIOSResult: boolean | undefined\nconst isIOSWebKit = (): boolean => {\n  if (_isIOSResult !== undefined) return _isIOSResult\n  if (typeof navigator === 'undefined') return (_isIOSResult = false)\n  if (/iP(hone|od|ad)/.test(navigator.userAgent)) return (_isIOSResult = true)\n  // iPadOS 13+ reports as MacIntel; touch-points distinguishes it from desktop.\n  const mtp = (navigator as Navigator & { maxTouchPoints?: number })\n    .maxTouchPoints\n  return (_isIOSResult =\n    navigator.platform === 'MacIntel' && mtp !== undefined && mtp > 0)\n}\n\n// Test hook: reset the iOS detection cache. Not exported.\nexport const _resetIOSDetectionForTests = () => {\n  _isIOSResult = undefined\n}\n\nexport { approxEqual, debounce, memo, notUndefined } from './utils'\nexport type { NoInfer, PartialKeys } from './utils'\n\n//\n\ntype ScrollDirection = 'forward' | 'backward'\n\ntype ScrollAlignment = 'start' | 'center' | 'end' | 'auto'\n\ntype ScrollBehavior = 'auto' | 'smooth' | 'instant'\n\ntype ScrollAnchor = 'start' | 'end'\n\ntype FollowOnAppend = boolean | ScrollBehavior\n\nexport interface ScrollToOptions {\n  align?: ScrollAlignment\n  behavior?: ScrollBehavior\n}\n\ntype ScrollToOffsetOptions = ScrollToOptions\n\ntype ScrollToIndexOptions = ScrollToOptions\n\ntype ScrollToEndOptions = Pick<ScrollToOptions, 'behavior'>\n\nexport interface Range {\n  startIndex: number\n  endIndex: number\n  overscan: number\n  count: number\n}\n\ntype Key = number | string | bigint\n\nexport interface VirtualItem {\n  key: Key\n  index: number\n  start: number\n  end: number\n  size: number\n  lane: number\n}\n\nexport interface Rect {\n  width: number\n  height: number\n}\n\n//\n\nconst getRect = (element: HTMLElement): Rect => {\n  const { offsetWidth, offsetHeight } = element\n  return { width: offsetWidth, height: offsetHeight }\n}\n\nexport const defaultKeyExtractor = (index: number) => index\n\nexport const defaultRangeExtractor = (range: Range) => {\n  const start = Math.max(range.startIndex - range.overscan, 0)\n  const end = Math.min(range.endIndex + range.overscan, range.count - 1)\n  const len = end - start + 1\n\n  const arr = new Array<number>(len)\n  for (let i = 0; i < len; i++) {\n    arr[i] = start + i\n  }\n  return arr\n}\n\nexport const observeElementRect = <T extends Element>(\n  instance: Virtualizer<T, any>,\n  cb: (rect: Rect) => void,\n) => {\n  const element = instance.scrollElement\n  if (!element) {\n    return\n  }\n  const targetWindow = instance.targetWindow\n  if (!targetWindow) {\n    return\n  }\n\n  const handler = (rect: Rect) => {\n    const { width, height } = rect\n    cb({ width: Math.round(width), height: Math.round(height) })\n  }\n\n  handler(getRect(element as unknown as HTMLElement))\n\n  if (!targetWindow.ResizeObserver) {\n    return () => {}\n  }\n\n  const observer = new targetWindow.ResizeObserver((entries) => {\n    const run = () => {\n      const entry = entries[0]\n      if (entry?.borderBoxSize) {\n        const box = entry.borderBoxSize[0]\n        if (box) {\n          handler({ width: box.inlineSize, height: box.blockSize })\n          return\n        }\n      }\n      handler(getRect(element as unknown as HTMLElement))\n    }\n\n    instance.options.useAnimationFrameWithResizeObserver\n      ? requestAnimationFrame(run)\n      : run()\n  })\n\n  observer.observe(element, { box: 'border-box' })\n\n  return () => {\n    observer.unobserve(element)\n  }\n}\n\nconst addEventListenerOptions = {\n  passive: true,\n}\n\nexport const observeWindowRect = (\n  instance: Virtualizer<Window, any>,\n  cb: (rect: Rect) => void,\n) => {\n  const element = instance.scrollElement\n  if (!element) {\n    return\n  }\n\n  const handler = () => {\n    cb({ width: element.innerWidth, height: element.innerHeight })\n  }\n  handler()\n\n  element.addEventListener('resize', handler, addEventListenerOptions)\n\n  return () => {\n    element.removeEventListener('resize', handler)\n  }\n}\n\nconst supportsScrollend =\n  typeof window == 'undefined' ? true : 'onscrollend' in window\n\ntype ObserveOffsetCallBack = (offset: number, isScrolling: boolean) => void\n\n// Shared core: both element and window variants attach scroll/scrollend\n// listeners with the same lifecycle; they only differ in how to read the\n// current offset from the scroll target.\nconst observeOffset = <T extends Element | Window>(\n  instance: Virtualizer<T, any>,\n  cb: ObserveOffsetCallBack,\n  readOffset: (target: T) => number,\n) => {\n  const element = instance.scrollElement\n  if (!element) {\n    return\n  }\n  const targetWindow = instance.targetWindow\n  if (!targetWindow) {\n    return\n  }\n\n  const registerScrollendEvent =\n    instance.options.useScrollendEvent && supportsScrollend\n\n  let offset = 0\n  const fallback = registerScrollendEvent\n    ? null\n    : debounce(\n        targetWindow,\n        () => cb(offset, false),\n        instance.options.isScrollingResetDelay,\n      )\n\n  const createHandler = (isScrolling: boolean) => () => {\n    offset = readOffset(element)\n    fallback?.()\n    cb(offset, isScrolling)\n  }\n  const handler = createHandler(true)\n  const endHandler = createHandler(false)\n\n  element.addEventListener('scroll', handler, addEventListenerOptions)\n  if (registerScrollendEvent) {\n    element.addEventListener('scrollend', endHandler, addEventListenerOptions)\n  }\n  return () => {\n    element.removeEventListener('scroll', handler)\n    if (registerScrollendEvent) {\n      element.removeEventListener('scrollend', endHandler)\n    }\n  }\n}\n\nexport const observeElementOffset = <T extends Element>(\n  instance: Virtualizer<T, any>,\n  cb: ObserveOffsetCallBack,\n) =>\n  observeOffset(instance, cb, (el) => {\n    const { horizontal, isRtl } = instance.options\n    return horizontal ? el.scrollLeft * ((isRtl && -1) || 1) : el.scrollTop\n  })\n\nexport const observeWindowOffset = (\n  instance: Virtualizer<Window, any>,\n  cb: ObserveOffsetCallBack,\n) =>\n  observeOffset(instance, cb, (win) =>\n    instance.options.horizontal ? win.scrollX : win.scrollY,\n  )\n\nexport const measureElement = <TItemElement extends Element>(\n  element: TItemElement,\n  entry: ResizeObserverEntry | undefined,\n  instance: Virtualizer<any, TItemElement>,\n) => {\n  // When useCachedMeasurements is enabled, return the cached size\n  // (or estimateSize as fallback) instead of measuring the DOM.\n  if (instance.options.useCachedMeasurements) {\n    const index = instance.indexFromElement(element)\n    const key = instance.options.getItemKey(index)\n    return (\n      instance.itemSizeCache.get(key) ?? instance.options.estimateSize(index)\n    )\n  }\n\n  if (entry?.borderBoxSize) {\n    const box = entry.borderBoxSize[0]\n    if (box) {\n      const size = Math.round(\n        box[instance.options.horizontal ? 'inlineSize' : 'blockSize'],\n      )\n      return size\n    }\n  }\n\n  // When called without a ResizeObserverEntry (sync measurement path),\n  // return the previously measured size if available. This avoids a\n  // synchronous layout read (offsetWidth/offsetHeight) on re-renders.\n  // The ResizeObserver is already observing the element and will deliver\n  // the accurate size asynchronously if it changed.\n  // Users who need synchronous DOM reads can provide a custom measureElement.\n  if (!entry) {\n    const index = instance.indexFromElement(element)\n    const key = instance.options.getItemKey(index)\n    const cachedSize = instance.itemSizeCache.get(key)\n    if (cachedSize !== undefined) {\n      return cachedSize\n    }\n  }\n\n  return (element as unknown as HTMLElement)[\n    instance.options.horizontal ? 'offsetWidth' : 'offsetHeight'\n  ]\n}\n\nconst scrollWithAdjustments = (\n  offset: number,\n  {\n    adjustments = 0,\n    behavior,\n  }: { adjustments?: number; behavior?: ScrollBehavior },\n  instance: Virtualizer<any, any>,\n) => {\n  instance.scrollElement?.scrollTo?.({\n    [instance.options.horizontal ? 'left' : 'top']: offset + adjustments,\n    behavior,\n  })\n}\n\nexport const windowScroll: <T extends Window>(\n  offset: number,\n  options: { adjustments?: number; behavior?: ScrollBehavior },\n  instance: Virtualizer<T, any>,\n) => void = scrollWithAdjustments\n\nexport const elementScroll: <T extends Element>(\n  offset: number,\n  options: { adjustments?: number; behavior?: ScrollBehavior },\n  instance: Virtualizer<T, any>,\n) => void = scrollWithAdjustments\n\ntype LaneAssignmentMode = 'estimate' | 'measured'\n\nexport interface VirtualizerOptions<\n  TScrollElement extends Element | Window,\n  TItemElement extends Element,\n> {\n  // Required from the user\n  count: number\n  getScrollElement: () => TScrollElement | null\n  estimateSize: (index: number) => number\n\n  // Required from the framework adapter (but can be overridden)\n  scrollToFn: (\n    offset: number,\n    options: { adjustments?: number; behavior?: ScrollBehavior },\n    instance: Virtualizer<TScrollElement, TItemElement>,\n  ) => void\n  observeElementRect: (\n    instance: Virtualizer<TScrollElement, TItemElement>,\n    cb: (rect: Rect) => void,\n  ) => void | (() => void)\n  observeElementOffset: (\n    instance: Virtualizer<TScrollElement, TItemElement>,\n    cb: ObserveOffsetCallBack,\n  ) => void | (() => void)\n  // Optional\n  debug?: boolean\n  initialRect?: Rect\n  onChange?: (\n    instance: Virtualizer<TScrollElement, TItemElement>,\n    sync: boolean,\n  ) => void\n  measureElement?: (\n    element: TItemElement,\n    entry: ResizeObserverEntry | undefined,\n    instance: Virtualizer<TScrollElement, TItemElement>,\n  ) => number\n  overscan?: number\n  horizontal?: boolean\n  paddingStart?: number\n  paddingEnd?: number\n  scrollPaddingStart?: number\n  scrollPaddingEnd?: number\n  initialOffset?: number | (() => number)\n  getItemKey?: (index: number) => Key\n  rangeExtractor?: (range: Range) => Array<number>\n  scrollMargin?: number\n  gap?: number\n  indexAttribute?: string\n  initialMeasurementsCache?: Array<VirtualItem>\n  lanes?: number\n  anchorTo?: ScrollAnchor\n  followOnAppend?: FollowOnAppend\n  scrollEndThreshold?: number\n  isScrollingResetDelay?: number\n  useScrollendEvent?: boolean\n  enabled?: boolean\n  isRtl?: boolean\n  useAnimationFrameWithResizeObserver?: boolean\n  laneAssignmentMode?: LaneAssignmentMode\n  useCachedMeasurements?: boolean\n}\n\ntype ScrollState = {\n  // what we want\n  index: number | null\n  align: ScrollAlignment\n  behavior: ScrollBehavior\n\n  // lifecycle\n  startedAt: number\n\n  // target tracking\n  lastTargetOffset: number\n\n  // settling\n  stableFrames: number\n}\n\ntype PendingScrollAnchor = [\n  key: Key | null,\n  offset: number,\n  followOnAppend: ScrollBehavior | null,\n  anchorDelta: number,\n]\n\nexport class Virtualizer<\n  TScrollElement extends Element | Window,\n  TItemElement extends Element,\n> {\n  private unsubs: Array<void | (() => void)> = []\n  options!: Required<VirtualizerOptions<TScrollElement, TItemElement>>\n  scrollElement: TScrollElement | null = null\n  targetWindow: (Window & typeof globalThis) | null = null\n  isScrolling = false\n  private scrollState: ScrollState | null = null\n  measurementsCache: Array<VirtualItem> = []\n  // Flat backing store for the lanes===1 fast path: [start_0, size_0, start_1, size_1, ...].\n  // null until the first single-lane build; reused (and grown) across rebuilds.\n  private _flatMeasurements: Float64Array | null = null\n  itemSizeCache = new Map<Key, number>()\n  private itemSizeCacheVersion = 0\n  private laneAssignments = new Map<number, number>() // index → lane cache\n  // Earliest index dirtied since last getMeasurements() rebuild, or null.\n  private pendingMin: number | null = null\n  private prevLanes: number | undefined = undefined\n  private lanesChangedFlag = false\n  private lanesSettling = false\n  private pendingScrollAnchor: PendingScrollAnchor | null = null\n  scrollRect: Rect | null = null\n  scrollOffset: number | null = null\n  scrollDirection: ScrollDirection | null = null\n  private scrollAdjustments = 0\n  // Sum of size-change deltas above-viewport that were skipped during\n  // iOS momentum scroll (writing scrollTop mid-momentum cancels it).\n  // Flushed in a single scrollTo when iOS is fully settled.\n  private _iosDeferredAdjustment = 0\n  // Touch state. iOS WebKit cancels momentum when scrollTop is written, so\n  // we defer adjustments not only during `isScrolling` but also through the\n  // touchstart→touchend window (active drag) and a short tail after\n  // touchend (early-momentum window — iOS only fires touch events once at\n  // the start of momentum, so we use a timer rather than another event).\n  private _iosTouching = false\n  private _iosJustTouchEnded = false\n  private _iosTouchEndTimerId: number | null = null\n  // Subpixel reconciliation. Safari (and Chrome/Firefox under certain DPRs)\n  // round scrollTop/scrollLeft writes to integer pixels. If we wrote 12345.5\n  // but the browser reports back 12346, the next reconcileScroll sees a\n  // \"target changed\" and re-fires scrollTo — a feedback loop that the\n  // approxEqual(<1.01) tolerance otherwise absorbs as a workaround.\n  // By remembering the intended value of our most-recent self-driven\n  // scrollTo, we can match the browser's rounded read back to the intended\n  // value when the diff is < 1.5 px, distinguishing it from a real user\n  // scroll. The +0.5 over Math.abs lets us also absorb the +1 / -1 cases.\n  private _intendedScrollOffset: number | null = null\n  shouldAdjustScrollPositionOnItemSizeChange:\n    | undefined\n    | ((\n        item: VirtualItem,\n        delta: number,\n        instance: Virtualizer<TScrollElement, TItemElement>,\n      ) => boolean)\n  elementsCache = new Map<Key, TItemElement>()\n  private now = () => this.targetWindow?.performance?.now?.() ?? Date.now()\n  private observer = (() => {\n    let _ro: ResizeObserver | null = null\n\n    const get = () => {\n      if (_ro) {\n        return _ro\n      }\n\n      if (!this.targetWindow || !this.targetWindow.ResizeObserver) {\n        return null\n      }\n\n      return (_ro = new this.targetWindow.ResizeObserver((entries) => {\n        entries.forEach((entry) => {\n          const run = () => {\n            const node = entry.target as TItemElement\n            const index = this.indexFromElement(node)\n\n            if (!node.isConnected) {\n              this.observer.unobserve(node)\n              // Find the cache entry pointing to this exact node and remove\n              // it. We can't call getItemKey(index) here because items may\n              // have been removed since this node was rendered — the index\n              // could be stale and out-of-bounds in the user's data array\n              // (regression test in e2e/.../stale-index.spec.ts, fix #1148).\n              // The === comparison naturally handles the React-replaced-\n              // a-node-for-the-same-key case: that entry now points to a\n              // different node, so this loop won't match.\n              for (const [cacheKey, cachedNode] of this.elementsCache) {\n                if (cachedNode === node) {\n                  this.elementsCache.delete(cacheKey)\n                  break\n                }\n              }\n              return\n            }\n\n            if (this.shouldMeasureDuringScroll(index)) {\n              this.resizeItem(\n                index,\n                this.options.measureElement(node, entry, this),\n              )\n            }\n          }\n          this.options.useAnimationFrameWithResizeObserver\n            ? requestAnimationFrame(run)\n            : run()\n        })\n      }))\n    }\n\n    return {\n      disconnect: () => {\n        get()?.disconnect()\n        _ro = null\n      },\n      observe: (target: Element) =>\n        get()?.observe(target, { box: 'border-box' }),\n      unobserve: (target: Element) => get()?.unobserve(target),\n    }\n  })()\n  range: { startIndex: number; endIndex: number } | null = null\n\n  constructor(opts: VirtualizerOptions<TScrollElement, TItemElement>) {\n    this.setOptions(opts)\n  }\n\n  setOptions = (opts: VirtualizerOptions<TScrollElement, TItemElement>) => {\n    // Skip `{...defaults, ...opts}` because explicit `undefined` values in\n    // opts would override defaults with `undefined`.\n    const merged = {\n      debug: false,\n      initialOffset: 0,\n      overscan: 1,\n      paddingStart: 0,\n      paddingEnd: 0,\n      scrollPaddingStart: 0,\n      scrollPaddingEnd: 0,\n      horizontal: false,\n      getItemKey: defaultKeyExtractor,\n      rangeExtractor: defaultRangeExtractor,\n      onChange: () => {},\n      measureElement,\n      initialRect: { width: 0, height: 0 },\n      scrollMargin: 0,\n      gap: 0,\n      indexAttribute: 'data-index',\n      initialMeasurementsCache: [],\n      lanes: 1,\n      anchorTo: 'start',\n      followOnAppend: false,\n      scrollEndThreshold: 1,\n      isScrollingResetDelay: 150,\n      enabled: true,\n      isRtl: false,\n      useScrollendEvent: false,\n      useAnimationFrameWithResizeObserver: false,\n      laneAssignmentMode: 'estimate',\n      useCachedMeasurements: false,\n    } as unknown as Required<VirtualizerOptions<TScrollElement, TItemElement>>\n\n    for (const key in opts) {\n      const v = (opts as any)[key]\n      if (v !== undefined) (merged as any)[key] = v\n    }\n\n    const prevOptions = this.options as\n      | Required<VirtualizerOptions<TScrollElement, TItemElement>>\n      | undefined\n    let anchor: [Key, number] | null = null\n    let followOnAppend: ScrollBehavior | null = null\n    let edgeKeysChanged = false\n\n    if (\n      prevOptions !== undefined &&\n      prevOptions.enabled &&\n      merged.enabled &&\n      merged.anchorTo === 'end' &&\n      this.scrollElement !== null\n    ) {\n      const prevCount = prevOptions.count\n      const nextCount = merged.count\n      const measurements = this.getMeasurements()\n      const prevFirstKey =\n        prevCount > 0\n          ? (measurements[0]?.key ?? prevOptions.getItemKey(0))\n          : null\n      const prevLastKey =\n        prevCount > 0\n          ? (measurements[prevCount - 1]?.key ??\n            prevOptions.getItemKey(prevCount - 1))\n          : null\n      const didCountChange = nextCount !== prevCount\n      const didEdgeKeysChange =\n        didCountChange ||\n        (prevCount > 0 &&\n          nextCount > 0 &&\n          (merged.getItemKey(0) !== prevFirstKey ||\n            merged.getItemKey(nextCount - 1) !== prevLastKey))\n\n      if (didEdgeKeysChange) {\n        edgeKeysChanged = true\n        const item =\n          prevCount > 0\n            ? (this.getVirtualItemForOffset(this.getScrollOffset()) ??\n              measurements[0])\n            : null\n\n        if (item) {\n          anchor = [item.key, this.getScrollOffset() - item.start]\n        }\n\n        const behavior =\n          merged.followOnAppend === true\n            ? 'auto'\n            : merged.followOnAppend || null\n\n        if (\n          behavior &&\n          nextCount > prevCount &&\n          this.isAtEnd(prevOptions.scrollEndThreshold) &&\n          (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)\n        ) {\n          followOnAppend = behavior\n        }\n      }\n    }\n\n    this.options = merged\n\n    // When edge keys changed (prepend, trim, reorder, etc.) the key→index\n    // mapping has shifted. Force a full measurement rebuild so the anchor\n    // resolution below reads positions from the new layout, not the stale\n    // memoised cache. Without this, a stable `getItemKey` reference +\n    // unchanged `count` would let getMeasurements() return the old layout.\n    if (edgeKeysChanged) {\n      this.pendingMin = 0\n      this.itemSizeCacheVersion++\n    }\n\n    // Eagerly adjust scrollOffset so the virtualizer computes the correct\n    // visible range during the current render pass — before _willUpdate\n    // syncs the DOM scroll position in a layout effect. Without this,\n    // the virtualizer would render the wrong items for one frame (the\n    // estimate-based positions are stale) and then correct in the next\n    // frame, producing a visible \"jump\" on prepend with dynamic sizes.\n    let anchorResolved = false\n    let anchorDelta = 0\n    if (anchor && this.scrollOffset !== null) {\n      const [anchorKey, anchorOffset] = anchor\n      const newMeasurements = this.getMeasurements()\n      const { count, getItemKey } = this.options\n      let idx = 0\n      while (idx < count && getItemKey(idx) !== anchorKey) {\n        idx++\n      }\n      if (idx < count) {\n        const anchorItem = newMeasurements[idx]\n        if (anchorItem) {\n          const newOffset = anchorItem.start + anchorOffset\n          if (newOffset !== this.scrollOffset) {\n            anchorDelta = newOffset - this.scrollOffset\n            this.scrollOffset = newOffset\n            anchorResolved = true\n          }\n        }\n      }\n    }\n\n    if (anchorResolved || followOnAppend) {\n      this.pendingScrollAnchor = [\n        anchorResolved ? anchor![0] : null,\n        anchorResolved ? anchor![1] : 0,\n        followOnAppend,\n        anchorDelta,\n      ]\n    }\n  }\n\n  private notify = (sync: boolean) => {\n    this.options.onChange?.(this, sync)\n  }\n\n  private applyScrollAdjustment(delta: number, behavior?: ScrollBehavior) {\n    if (delta === 0) return\n\n    if (process.env.NODE_ENV !== 'production' && this.options.debug) {\n      console.info('correction', delta)\n    }\n\n    if (\n      isIOSWebKit() &&\n      (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)\n    ) {\n      this._iosDeferredAdjustment += delta\n    } else {\n      this._scrollToOffset(this.getScrollOffset(), {\n        adjustments: (this.scrollAdjustments += delta),\n        behavior,\n      })\n    }\n  }\n\n  private maybeNotify = memo(\n    () => {\n      this.calculateRange()\n\n      return [\n        this.isScrolling,\n        this.range ? this.range.startIndex : null,\n        this.range ? this.range.endIndex : null,\n      ]\n    },\n    (isScrolling) => {\n      this.notify(isScrolling)\n    },\n    {\n      key: process.env.NODE_ENV !== 'production' && 'maybeNotify',\n      debug: () => this.options.debug,\n      initialDeps: [\n        this.isScrolling,\n        this.range ? this.range.startIndex : null,\n        this.range ? this.range.endIndex : null,\n      ] as [boolean, number | null, number | null],\n    },\n  )\n\n  private cleanup = () => {\n    this.unsubs.filter(Boolean).forEach((d) => d!())\n    this.unsubs = []\n    this.observer.disconnect()\n    if (this.rafId != null && this.targetWindow) {\n      this.targetWindow.cancelAnimationFrame(this.rafId)\n      this.rafId = null\n    }\n    this.scrollState = null\n    this.scrollElement = null\n    this.targetWindow = null\n  }\n\n  _didMount = () => {\n    return () => {\n      this.cleanup()\n    }\n  }\n\n  _willUpdate = () => {\n    const scrollElement = this.options.enabled\n      ? this.options.getScrollElement()\n      : null\n\n    if (this.scrollElement !== scrollElement) {\n      this.cleanup()\n\n      if (!scrollElement) {\n        this.maybeNotify()\n        return\n      }\n\n      this.scrollElement = scrollElement\n\n      if (this.scrollElement && 'ownerDocument' in this.scrollElement) {\n        this.targetWindow = this.scrollElement.ownerDocument.defaultView\n      } else {\n        this.targetWindow = this.scrollElement?.window ?? null\n      }\n\n      this.elementsCache.forEach((cached) => {\n        this.observer.observe(cached)\n      })\n\n      this.unsubs.push(\n        this.options.observeElementRect(this, (rect) => {\n          this.scrollRect = rect\n          this.maybeNotify()\n        }),\n      )\n\n      this.unsubs.push(\n        this.options.observeElementOffset(this, (offset, isScrolling) => {\n          // If this scroll event looks like the browser's read-back of a\n          // value we just wrote, prefer our intended (sub-pixel-accurate)\n          // value over the browser's rounded one. The 1.5 px tolerance is\n          // tight enough to avoid mistaking a real user scroll for a\n          // self-write — by the time the user has moved 1.5 px, the\n          // intended value will already have been consumed by a prior\n          // scroll event and cleared.\n          if (\n            this._intendedScrollOffset !== null &&\n            Math.abs(offset - this._intendedScrollOffset) < 1.5\n          ) {\n            offset = this._intendedScrollOffset\n          }\n          this._intendedScrollOffset = null\n\n          this.scrollAdjustments = 0\n          this.scrollDirection = isScrolling\n            ? this.getScrollOffset() < offset\n              ? 'forward'\n              : 'backward'\n            : null\n          this.scrollOffset = offset\n          this.isScrolling = isScrolling\n\n          // Flush deferred iOS adjustments if we're now fully settled.\n          // \"Fully settled\" means: not actively scrolling, no finger on\n          // screen, and the post-touchend grace window has expired.\n          this._flushIosDeferredIfReady()\n\n          if (this.scrollState) {\n            this.scheduleScrollReconcile()\n          }\n          this.maybeNotify()\n        }),\n      )\n\n      // Touch event listeners (iOS-aware deferral). We attach unconditionally\n      // — the listeners are passive and cheap; on non-touch devices they\n      // simply never fire. The gating by isIOSWebKit() lives in resizeItem\n      // and _flushIosDeferredIfReady so we only burn the path on iOS.\n      if ('addEventListener' in this.scrollElement) {\n        const scrollEl = this.scrollElement as unknown as EventTarget\n        const onTouchStart = () => {\n          this._iosTouching = true\n          this._iosJustTouchEnded = false\n          if (this._iosTouchEndTimerId !== null && this.targetWindow != null) {\n            this.targetWindow.clearTimeout(this._iosTouchEndTimerId)\n            this._iosTouchEndTimerId = null\n          }\n        }\n        const onTouchEnd = () => {\n          this._iosTouching = false\n          if (!isIOSWebKit() || this.targetWindow == null) {\n            // Non-iOS: nothing more to track. Just clear the touching flag.\n            return\n          }\n          this._iosJustTouchEnded = true\n          // After ~150 ms with no scroll/touch events, momentum is done.\n          this._iosTouchEndTimerId = this.targetWindow.setTimeout(() => {\n            this._iosJustTouchEnded = false\n            this._iosTouchEndTimerId = null\n            // After the grace window, attempt to flush. The scroll event\n            // for momentum decay may have already fired before our timer.\n            this._flushIosDeferredIfReady()\n          }, 150)\n        }\n        scrollEl.addEventListener(\n          'touchstart',\n          onTouchStart,\n          addEventListenerOptions,\n        )\n        scrollEl.addEventListener(\n          'touchend',\n          onTouchEnd,\n          addEventListenerOptions,\n        )\n        this.unsubs.push(() => {\n          scrollEl.removeEventListener('touchstart', onTouchStart)\n          scrollEl.removeEventListener('touchend', onTouchEnd)\n          if (this._iosTouchEndTimerId !== null && this.targetWindow != null) {\n            this.targetWindow.clearTimeout(this._iosTouchEndTimerId)\n            this._iosTouchEndTimerId = null\n          }\n        })\n      }\n\n      this._scrollToOffset(this.getScrollOffset(), {\n        adjustments: undefined,\n        behavior: undefined,\n      })\n    }\n\n    const anchor = this.pendingScrollAnchor\n    this.pendingScrollAnchor = null\n\n    if (anchor && this.scrollElement && this.options.enabled) {\n      const [key, _offset, followOnAppend, anchorDelta] = anchor\n\n      if (key !== null && !followOnAppend) {\n        // scrollOffset was eagerly adjusted in setOptions so the\n        // virtualizer already computed the correct range during render.\n        // Now sync the browser's actual scroll position to match.\n        // Skip when followOnAppend is set — scrollToEnd will handle it.\n        //\n        // On iOS WebKit, writing scrollTop during touch/momentum cancels\n        // the in-flight scroll. Defer the DOM sync the same way\n        // applyScrollAdjustment does — accumulate the delta and let\n        // _flushIosDeferredIfReady handle it once the scroll settles.\n        if (\n          isIOSWebKit() &&\n          (this.isScrolling || this._iosTouching || this._iosJustTouchEnded)\n        ) {\n          if (anchorDelta !== 0) {\n            this._iosDeferredAdjustment += anchorDelta\n          }\n        } else {\n          this._scrollToOffset(this.getScrollOffset(), {\n            adjustments: undefined,\n            behavior: undefined,\n          })\n        }\n      }\n\n      if (followOnAppend) {\n        this.scrollToEnd({ behavior: followOnAppend })\n      }\n    }\n  }\n\n  // Apply any accumulated iOS-deferred scroll adjustment, but only when we're\n  // truly settled — not actively scrolling, not under an active touch, and\n  // past the post-touchend grace window. Called from the scroll callback\n  // and the touchend grace-timer.\n  private _flushIosDeferredIfReady = () => {\n    if (this._iosDeferredAdjustment === 0) return\n    if (this.isScrolling) return\n    if (this._iosTouching) return\n    if (this._iosJustTouchEnded) return\n    // Phase 2b: Safari elastic-overscroll (rubber-band) lets scrollTop go\n    // negative or beyond scrollHeight - clientHeight. Writing scrollTop\n    // while in that zone snaps the page back to the clamped value at the\n    // end of the bounce, often discarding the user's intent. Skip the\n    // flush; the next in-bounds scroll event will retry.\n    const cur = this.getScrollOffset()\n    const max = this.getMaxScrollOffset()\n    if (cur < 0 || cur > max) return\n    const delta = this._iosDeferredAdjustment\n    this._iosDeferredAdjustment = 0\n    // Roll the deferred delta into the running accumulator so any resize\n    // landing between now and the resulting scroll event computes from the\n    // post-flush offset rather than the stale one.\n    this._scrollToOffset(cur, {\n      adjustments: (this.scrollAdjustments += delta),\n      behavior: undefined,\n    })\n  }\n\n  private rafId: number | null = null\n  private scheduleScrollReconcile() {\n    if (!this.targetWindow) {\n      this.scrollState = null\n      return\n    }\n    if (this.rafId != null) return\n    this.rafId = this.targetWindow.requestAnimationFrame(() => {\n      this.rafId = null\n      this.reconcileScroll()\n    })\n  }\n  private reconcileScroll() {\n    if (!this.scrollState) return\n\n    const el = this.scrollElement\n    if (!el) return\n\n    // Safety valve: bail out if reconciliation has been running too long\n    const MAX_RECONCILE_MS = 5000\n    if (this.now() - this.scrollState.startedAt > MAX_RECONCILE_MS) {\n      this.scrollState = null\n      return\n    }\n\n    const offsetInfo =\n      this.scrollState.index != null\n        ? this.getOffsetForIndex(this.scrollState.index, this.scrollState.align)\n        : undefined\n    const targetOffset = offsetInfo\n      ? offsetInfo[0]\n      : this.scrollState.lastTargetOffset\n\n    // Require one stable frame where target matches scroll offset.\n    // approxEqual() already tolerates minor fluctuations, so one frame is sufficient\n    // to confirm scroll has reached its target without premature cleanup.\n    const STABLE_FRAMES = 1\n\n    const targetChanged = targetOffset !== this.scrollState.lastTargetOffset\n\n    if (!targetChanged && approxEqual(targetOffset, this.getScrollOffset())) {\n      this.scrollState.stableFrames++\n      if (this.scrollState.stableFrames >= STABLE_FRAMES) {\n        // Final-pass exact landing. The reconcile-stable check uses a 1.01px\n        // tolerance (approxEqual) so we don't fight subpixel browser rounding\n        // during the converging phase. Once we're definitively settled,\n        // commit the exact target so consumers calling scrollToIndex(N)\n        // end up at the EXACT computed position of item N — matching\n        // virtuoso's 0px landing accuracy rather than our prior 0.5-1px.\n        if (this.getScrollOffset() !== targetOffset) {\n          this._scrollToOffset(targetOffset, {\n            adjustments: undefined,\n            behavior: 'auto',\n          })\n        }\n        this.scrollState = null\n        return\n      }\n    } else {\n      this.scrollState.stableFrames = 0\n\n      if (targetChanged) {\n        // When the target moves during smooth scroll (because items came into\n        // view and got measured, shifting positions), the original logic was\n        // to immediately snap to 'auto' — visibly jarring on long\n        // scroll-to-index calls. Now: keep smooth while we're still far\n        // (more than a viewport) from the new target. Only fall back to\n        // 'auto' for the final approach, so the user sees one continuous\n        // motion that smoothly adjusts its endpoint as measurements arrive.\n        const viewport = this.getSize() || 600\n        const distance = Math.abs(targetOffset - this.getScrollOffset())\n        const keepSmooth =\n          this.scrollState.behavior === 'smooth' && distance > viewport\n\n        this.scrollState.lastTargetOffset = targetOffset\n        if (!keepSmooth) {\n          this.scrollState.behavior = 'auto'\n        }\n\n        this._scrollToOffset(targetOffset, {\n          adjustments: undefined,\n          behavior: keepSmooth ? 'smooth' : 'auto',\n        })\n      }\n    }\n\n    // Always reschedule while scrollState is active to guarantee\n    // the safety valve timeout runs even if no scroll events fire\n    // (e.g. no-op scrollToFn, detached element)\n    this.scheduleScrollReconcile()\n  }\n\n  private getSize = () => {\n    if (!this.options.enabled) {\n      this.scrollRect = null\n      return 0\n    }\n\n    this.scrollRect = this.scrollRect ?? this.options.initialRect\n\n    return this.scrollRect[this.options.horizontal ? 'width' : 'height']\n  }\n\n  private getScrollOffset = () => {\n    if (!this.options.enabled) {\n      this.scrollOffset = null\n      return 0\n    }\n\n    this.scrollOffset =\n      this.scrollOffset ??\n      (typeof this.options.initialOffset === 'function'\n        ? this.options.initialOffset()\n        : this.options.initialOffset)\n\n    return this.scrollOffset\n  }\n\n  private getFurthestMeasurement = (\n    measurements: Array<VirtualItem>,\n    index: number,\n  ) => {\n    const furthestMeasurementsFound = new Map<number, true>()\n    const furthestMeasurements = new Map<number, VirtualItem>()\n    for (let m = index - 1; m >= 0; m--) {\n      const measurement = measurements[m]!\n\n      if (furthestMeasurementsFound.has(measurement.lane)) {\n        continue\n      }\n\n      const previousFurthestMeasurement = furthestMeasurements.get(\n        measurement.lane,\n      )\n      if (\n        previousFurthestMeasurement == null ||\n        measurement.end > previousFurthestMeasurement.end\n      ) {\n        furthestMeasurements.set(measurement.lane, measurement)\n      } else if (measurement.end < previousFurthestMeasurement.end) {\n        furthestMeasurementsFound.set(measurement.lane, true)\n      }\n\n      if (furthestMeasurementsFound.size === this.options.lanes) {\n        break\n      }\n    }\n\n    return furthestMeasurements.size === this.options.lanes\n      ? Array.from(furthestMeasurements.values()).sort((a, b) => {\n          if (a.end === b.end) {\n            return a.index - b.index\n          }\n\n          return a.end - b.end\n        })[0]\n      : undefined\n  }\n\n  private getMeasurementOptions = memo(\n    () => [\n      this.options.count,\n      this.options.paddingStart,\n      this.options.scrollMargin,\n      this.options.getItemKey,\n      this.options.enabled,\n      this.options.lanes,\n      this.options.laneAssignmentMode,\n    ],\n    (\n      count,\n      paddingStart,\n      scrollMargin,\n      getItemKey,\n      enabled,\n      lanes,\n      laneAssignmentMode,\n    ) => {\n      const lanesChanged =\n        this.prevLanes !== undefined && this.prevLanes !== lanes\n\n      if (lanesChanged) {\n        // Set flag for getMeasurements to handle\n        this.lanesChangedFlag = true\n      }\n\n      this.prevLanes = lanes\n      this.pendingMin = null\n\n      return {\n        count,\n        paddingStart,\n        scrollMargin,\n        getItemKey,\n        enabled,\n        lanes,\n        laneAssignmentMode,\n      }\n    },\n    {\n      key: false,\n    },\n  )\n\n  private getMeasurements = memo(\n    () => [this.getMeasurementOptions(), this.itemSizeCacheVersion],\n    (\n      {\n        count,\n        paddingStart,\n        scrollMargin,\n        getItemKey,\n        enabled,\n        lanes,\n        laneAssignmentMode,\n      },\n      _itemSizeCacheVersion,\n    ) => {\n      const itemSizeCache = this.itemSizeCache\n      if (!enabled) {\n        this.measurementsCache = []\n        this.itemSizeCache.clear()\n        this.laneAssignments.clear()\n        return []\n      }\n\n      // Clean up stale lane cache entries when count decreases\n      if (this.laneAssignments.size > count) {\n        for (const index of this.laneAssignments.keys()) {\n          if (index >= count) {\n            this.laneAssignments.delete(index)\n          }\n        }\n      }\n\n      // ✅ Force complete recalculation when lanes change\n      if (this.lanesChangedFlag) {\n        this.lanesChangedFlag = false // Reset immediately\n        this.lanesSettling = true // Start settling period\n        this.measurementsCache = []\n        this.itemSizeCache.clear()\n        this.laneAssignments.clear() // Clear lane cache for new lane count\n        // Force min = 0 on the rebuild\n        this.pendingMin = null\n      }\n\n      // Don't restore from initialMeasurementsCache during lane changes\n      // as it contains stale lane assignments from the previous lane count\n      if (this.measurementsCache.length === 0 && !this.lanesSettling) {\n        this.measurementsCache = this.options.initialMeasurementsCache\n        this.measurementsCache.forEach((item) => {\n          this.itemSizeCache.set(item.key, item.size)\n        })\n      }\n\n      // During lanes settling, ignore pendingMin to prevent repositioning\n      const min = this.lanesSettling ? 0 : (this.pendingMin ?? 0)\n      this.pendingMin = null\n\n      // ✅ End settling period when cache is fully built\n      if (this.lanesSettling && this.measurementsCache.length === count) {\n        this.lanesSettling = false\n      }\n\n      // ─── Fast path: single-lane lazy materialization ────────────────────\n      // For lanes === 1 (the default and most common case), skip the\n      // per-item VirtualItem object allocation. We write start/size pairs\n      // into a Float64Array and return a Proxy that builds VirtualItem\n      // objects on demand (only the indices a consumer actually reads).\n      //\n      // At n=100k this drops cold-mount cost from ~2.5ms (eager object\n      // allocation) to roughly the cost of a single typed-array fill.\n      if (lanes === 1) {\n        const gap = this.options.gap\n        // Reuse flat backing if large enough; else grow (preserving data\n        // before `min` to mirror the slice-and-rebuild contract).\n        const need = count * 2\n        let flat = this._flatMeasurements\n        if (!flat || flat.length < need) {\n          const next = new Float64Array(need)\n          if (flat && min > 0) next.set(flat.subarray(0, min * 2))\n          flat = next\n          this._flatMeasurements = flat\n        }\n\n        let runningStart: number\n        if (min === 0) {\n          runningStart = paddingStart + scrollMargin\n        } else {\n          // Continue from where we left off\n          const prevIdx = min - 1\n          runningStart = flat[prevIdx * 2]! + flat[prevIdx * 2 + 1]! + gap\n        }\n\n        for (let i = min; i < count; i++) {\n          const key = getItemKey(i)\n          const measuredSize = itemSizeCache.get(key)\n          const size =\n            typeof measuredSize === 'number'\n              ? measuredSize\n              : this.options.estimateSize(i)\n          flat[i * 2] = runningStart\n          flat[i * 2 + 1] = size\n          runningStart += size + gap\n        }\n\n        const view = createLazyMeasurementsView(count, flat, getItemKey)\n        this.measurementsCache = view\n        return view\n      }\n\n      const measurements = this.measurementsCache.slice(0, min)\n\n      // ✅ Performance: Track last item index per lane for O(1) lookup\n      const laneLastIndex: Array<number | undefined> = new Array(lanes).fill(\n        undefined,\n      )\n\n      // Initialize from existing measurements (before min)\n      for (let m = 0; m < min; m++) {\n        const item = measurements[m]\n        if (item) {\n          laneLastIndex[item.lane] = m\n        }\n      }\n\n      for (let i = min; i < count; i++) {\n        const key = getItemKey(i)\n\n        // Check for cached lane assignment\n        const cachedLane = this.laneAssignments.get(i)\n        let lane: number\n        let start: number\n\n        const shouldCacheLane =\n          laneAssignmentMode === 'estimate' || itemSizeCache.has(key)\n\n        if (cachedLane !== undefined && this.options.lanes > 1) {\n          // Use cached lane - O(1) lookup for previous item in same lane\n          lane = cachedLane\n          const prevIndex = laneLastIndex[lane]\n          const prevInLane =\n            prevIndex !== undefined ? measurements[prevIndex] : undefined\n          start = prevInLane\n            ? prevInLane.end + this.options.gap\n            : paddingStart + scrollMargin\n        } else {\n          // No cache - use original logic (find shortest lane)\n          const furthestMeasurement =\n            this.options.lanes === 1\n              ? measurements[i - 1]\n              : this.getFurthestMeasurement(measurements, i)\n\n          start = furthestMeasurement\n            ? furthestMeasurement.end + this.options.gap\n            : paddingStart + scrollMargin\n\n          lane = furthestMeasurement\n            ? furthestMeasurement.lane\n            : i % this.options.lanes\n\n          if (this.options.lanes > 1 && shouldCacheLane) {\n            this.laneAssignments.set(i, lane)\n          }\n        }\n\n        const measuredSize = itemSizeCache.get(key)\n        const size =\n          typeof measuredSize === 'number'\n            ? measuredSize\n            : this.options.estimateSize(i)\n\n        const end = start + size\n\n        measurements[i] = {\n          index: i,\n          start,\n          size,\n          end,\n          key,\n          lane,\n        }\n\n        // ✅ Performance: Update lane's last item index\n        laneLastIndex[lane] = i\n      }\n\n      this.measurementsCache = measurements\n\n      return measurements\n    },\n    {\n      key: process.env.NODE_ENV !== 'production' && 'getMeasurements',\n      debug: () => this.options.debug,\n    },\n  )\n\n  calculateRange = memo(\n    () => [\n      this.getMeasurements(),\n      this.getSize(),\n      this.getScrollOffset(),\n      this.options.lanes,\n    ],\n    (measurements, outerSize, scrollOffset, lanes) => {\n      return (this.range =\n        measurements.length > 0 && outerSize > 0\n          ? calculateRange({\n              measurements,\n              outerSize,\n              scrollOffset,\n              lanes,\n              // Pass the typed array so binary search + forward-walk can\n              // read start/end directly from Float64Array, skipping the\n              // Proxy traps that materialize a full VirtualItem per probe.\n              flat:\n                lanes === 1 && this._flatMeasurements != null\n                  ? this._flatMeasurements\n                  : null,\n            })\n          : null)\n    },\n    {\n      key: process.env.NODE_ENV !== 'production' && 'calculateRange',\n      debug: () => this.options.debug,\n    },\n  )\n\n  getVirtualIndexes = memo(\n    () => {\n      let startIndex: number | null = null\n      let endIndex: number | null = null\n      const range = this.calculateRange()\n      if (range) {\n        startIndex = range.startIndex\n        endIndex = range.endIndex\n      }\n      this.maybeNotify.updateDeps([this.isScrolling, startIndex, endIndex])\n      return [\n        this.options.rangeExtractor,\n        this.options.overscan,\n        this.options.count,\n        startIndex,\n        endIndex,\n      ]\n    },\n    (rangeExtractor, overscan, count, startIndex, endIndex) => {\n      return startIndex === null || endIndex === null\n        ? []\n        : rangeExtractor({\n            startIndex,\n            endIndex,\n            overscan,\n            count,\n          })\n    },\n    {\n      key: process.env.NODE_ENV !== 'production' && 'getVirtualIndexes',\n      debug: () => this.options.debug,\n    },\n  )\n\n  indexFromElement = (node: TItemElement) => {\n    const attributeName = this.options.indexAttribute\n    const indexStr = node.getAttribute(attributeName)\n\n    if (!indexStr) {\n      console.warn(\n        `Missing attribute name '${attributeName}={index}' on measured element.`,\n      )\n      return -1\n    }\n\n    return parseInt(indexStr, 10)\n  }\n\n  /**\n   * Determines if an item at the given index should be measured during smooth scroll.\n   * During smooth scroll, only items within a buffer range around the target are measured\n   * to prevent items far from the target from pushing it away.\n   */\n  private shouldMeasureDuringScroll = (index: number): boolean => {\n    // No scroll state or not smooth scroll - always allow measurements\n    if (!this.scrollState || this.scrollState.behavior !== 'smooth') {\n      return true\n    }\n\n    const scrollIndex =\n      this.scrollState.index ??\n      this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index\n\n    if (scrollIndex !== undefined && this.range) {\n      // Allow measurements within a buffer range around the scroll target\n      const bufferSize = Math.max(\n        this.options.overscan,\n        Math.ceil((this.range.endIndex - this.range.startIndex) / 2),\n      )\n      const minIndex = Math.max(0, scrollIndex - bufferSize)\n      const maxIndex = Math.min(\n        this.options.count - 1,\n        scrollIndex + bufferSize,\n      )\n      return index >= minIndex && index <= maxIndex\n    }\n\n    return true\n  }\n\n  measureElement = (node: TItemElement | null) => {\n    if (!node) {\n      this.elementsCache.forEach((cached, key) => {\n        if (!cached.isConnected) {\n          this.observer.unobserve(cached)\n          this.elementsCache.delete(key)\n        }\n      })\n      return\n    }\n\n    const index = this.indexFromElement(node)\n    const key = this.options.getItemKey(index)\n    const prevNode = this.elementsCache.get(key)\n\n    if (prevNode !== node) {\n      if (prevNode) {\n        this.observer.unobserve(prevNode)\n      }\n      this.observer.observe(node)\n      this.elementsCache.set(key, node)\n    }\n\n    // Sync-measure when idle (initial render) or during programmatic scrolling\n    // (scrollToIndex/scrollToOffset) where reconcileScroll needs sizes in the same frame.\n    // During normal user scrolling, skip sync measurement — the RO callback handles it async.\n    if (\n      (!this.isScrolling || this.scrollState) &&\n      this.shouldMeasureDuringScroll(index)\n    ) {\n      this.resizeItem(index, this.options.measureElement(node, undefined, this))\n    }\n  }\n\n  resizeItem = (index: number, size: number) => {\n    if (index < 0 || index >= this.options.count) return\n\n    // Fast field reads. For lanes===1 we read raw start/size from the flat\n    // typed array, avoiding a Proxy.get + VirtualItem allocation per call.\n    // For lanes>1 we fall back to the cached VirtualItem array.\n    let cachedSize: number\n    let itemStart: number\n    let key: Key\n    const flat = this._flatMeasurements\n    if (this.options.lanes === 1 && flat !== null) {\n      key = this.options.getItemKey(index)\n      itemStart = flat[index * 2]!\n      cachedSize = flat[index * 2 + 1]!\n    } else {\n      const item = this.measurementsCache[index]\n      if (!item) return\n      key = item.key\n      itemStart = item.start\n      cachedSize = item.size\n    }\n\n    const itemSize = this.itemSizeCache.get(key) ?? cachedSize\n    const delta = size - itemSize\n\n    if (delta !== 0) {\n      const wasAtEnd =\n        this.options.anchorTo === 'end' &&\n        this.scrollState?.behavior !== 'smooth' &&\n        this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold\n      const prevTotalSize = wasAtEnd ? this.getTotalSize() : 0\n      const shouldAdjustScroll =\n        this.scrollState?.behavior !== 'smooth' &&\n        (this.shouldAdjustScrollPositionOnItemSizeChange !== undefined\n          ? this.shouldAdjustScrollPositionOnItemSizeChange(\n              // The callback expects a VirtualItem; build one lazily only\n              // when the consumer actually supplied a custom predicate.\n              this.measurementsCache[index] ?? {\n                index,\n                key,\n                start: itemStart,\n                size: cachedSize,\n                end: itemStart + cachedSize,\n                lane: 0,\n              },\n              delta,\n              this,\n            )\n          : // Default: adjust when the resize is an above-viewport item.\n            // First measurement (!has(key)): always adjust — the item\n            // has never been sized, so the estimate→actual delta must\n            // be compensated regardless of scroll direction.\n            // Re-measurement (has(key)): skip during backward scroll\n            // to avoid the \"items jump while scrolling up\" cascade.\n            itemStart < this.getScrollOffset() + this.scrollAdjustments &&\n            (!this.itemSizeCache.has(key) ||\n              this.scrollDirection !== 'backward'))\n\n      if (this.pendingMin === null || index < this.pendingMin) {\n        this.pendingMin = index\n      }\n      this.itemSizeCache.set(key, size)\n      this.itemSizeCacheVersion++\n\n      if (wasAtEnd) {\n        this.applyScrollAdjustment(this.getTotalSize() - prevTotalSize)\n      } else if (shouldAdjustScroll) {\n        this.applyScrollAdjustment(delta)\n      }\n\n      this.notify(false)\n    }\n  }\n\n  getVirtualItems = memo(\n    () => [this.getVirtualIndexes(), this.getMeasurements()],\n    (indexes, measurements) => {\n      const virtualItems: Array<VirtualItem> = []\n\n      for (let k = 0, len = indexes.length; k < len; k++) {\n        const i = indexes[k]!\n        const measurement = measurements[i]!\n\n        virtualItems.push(measurement)\n      }\n\n      return virtualItems\n    },\n    {\n      key: process.env.NODE_ENV !== 'production' && 'getVirtualItems',\n      debug: () => this.options.debug,\n    },\n  )\n\n  getVirtualItemForOffset = (offset: number) => {\n    const measurements = this.getMeasurements()\n    if (measurements.length === 0) {\n      return undefined\n    }\n    // Same fast-path as calculateRange: read start values directly from the\n    // typed array during binary search to skip the Proxy.get materialization\n    // per probe.\n    const flat = this._flatMeasurements\n    const useFlat = this.options.lanes === 1 && flat != null\n    const idx = findNearestBinarySearch(\n      0,\n      measurements.length - 1,\n      useFlat\n        ? (i: number) => flat[i * 2]!\n        : (i: number) => notUndefined(measurements[i]).start,\n      offset,\n    )\n    return notUndefined(measurements[idx])\n  }\n\n  private getMaxScrollOffset = () => {\n    if (!this.scrollElement) return 0\n\n    if ('scrollHeight' in this.scrollElement) {\n      // Element\n      return this.options.horizontal\n        ? this.scrollElement.scrollWidth - this.scrollElement.clientWidth\n        : this.scrollElement.scrollHeight - this.scrollElement.clientHeight\n    } else {\n      // Window\n      const doc = this.scrollElement.document.documentElement\n      return this.options.horizontal\n        ? doc.scrollWidth - this.scrollElement.innerWidth\n        : doc.scrollHeight - this.scrollElement.innerHeight\n    }\n  }\n\n  private getVirtualDistanceFromEnd = () => {\n    return Math.max(\n      this.getTotalSize() - this.getSize() - this.getScrollOffset(),\n      0,\n    )\n  }\n\n  getDistanceFromEnd = () => {\n    return Math.max(this.getMaxScrollOffset() - this.getScrollOffset(), 0)\n  }\n\n  isAtEnd = (threshold = this.options.scrollEndThreshold) => {\n    return this.getDistanceFromEnd() <= threshold\n  }\n\n  getOffsetForAlignment = (\n    toOffset: number,\n    align: ScrollAlignment,\n    itemSize = 0,\n  ) => {\n    if (!this.scrollElement) return 0\n\n    const size = this.getSize()\n    const scrollOffset = this.getScrollOffset()\n\n    if (align === 'auto') {\n      align = toOffset >= scrollOffset + size ? 'end' : 'start'\n    }\n\n    if (align === 'center') {\n      // When aligning to a particular item (e.g. with scrollToIndex),\n      // adjust offset by the size of the item to center on the item\n      toOffset += (itemSize - size) / 2\n    } else if (align === 'end') {\n      toOffset -= size\n    }\n\n    const maxOffset = this.getMaxScrollOffset()\n\n    return Math.max(Math.min(maxOffset, toOffset), 0)\n  }\n\n  getOffsetForIndex = (index: number, align: ScrollAlignment = 'auto') => {\n    index = Math.max(0, Math.min(index, this.options.count - 1))\n\n    const size = this.getSize()\n    const scrollOffset = this.getScrollOffset()\n\n    const item = this.measurementsCache[index]\n    if (!item) return\n\n    if (align === 'auto') {\n      if (item.end >= scrollOffset + size - this.options.scrollPaddingEnd) {\n        align = 'end'\n      } else if (item.start <= scrollOffset + this.options.scrollPaddingStart) {\n        align = 'start'\n      } else {\n        return [scrollOffset, align] as const\n      }\n    }\n\n    // For the last item with 'end' alignment, use browser's actual max scroll\n    // to account for borders/padding that aren't in our measurements\n    if (align === 'end' && index === this.options.count - 1) {\n      return [this.getMaxScrollOffset(), align] as const\n    }\n\n    const toOffset =\n      align === 'end'\n        ? item.end + this.options.scrollPaddingEnd\n        : item.start - this.options.scrollPaddingStart\n\n    return [\n      this.getOffsetForAlignment(toOffset, align, item.size),\n      align,\n    ] as const\n  }\n\n  scrollToOffset = (\n    toOffset: number,\n    { align = 'start', behavior = 'auto' }: ScrollToOffsetOptions = {},\n  ) => {\n    const offset = this.getOffsetForAlignment(toOffset, align)\n\n    const now = this.now()\n    this.scrollState = {\n      index: null,\n      align,\n      behavior,\n      startedAt: now,\n      lastTargetOffset: offset,\n      stableFrames: 0,\n    }\n\n    this._scrollToOffset(offset, { adjustments: undefined, behavior })\n\n    this.scheduleScrollReconcile()\n  }\n\n  scrollToIndex = (\n    index: number,\n    {\n      align: initialAlign = 'auto',\n      behavior = 'auto',\n    }: ScrollToIndexOptions = {},\n  ) => {\n    index = Math.max(0, Math.min(index, this.options.count - 1))\n\n    const offsetInfo = this.getOffsetForIndex(index, initialAlign)\n    if (!offsetInfo) {\n      return\n    }\n    const [offset, align] = offsetInfo\n\n    const now = this.now()\n    this.scrollState = {\n      index,\n      align,\n      behavior,\n      startedAt: now,\n      lastTargetOffset: offset,\n      stableFrames: 0,\n    }\n\n    this._scrollToOffset(offset, { adjustments: undefined, behavior })\n\n    this.scheduleScrollReconcile()\n  }\n\n  scrollBy = (\n    delta: number,\n    { behavior = 'auto' }: ScrollToOffsetOptions = {},\n  ) => {\n    const offset = this.getScrollOffset() + delta\n    const now = this.now()\n\n    this.scrollState = {\n      index: null,\n      align: 'start',\n      behavior,\n      startedAt: now,\n      lastTargetOffset: offset,\n      stableFrames: 0,\n    }\n\n    this._scrollToOffset(offset, { adjustments: undefined, behavior })\n\n    this.scheduleScrollReconcile()\n  }\n\n  scrollToEnd = ({ behavior = 'auto' }: ScrollToEndOptions = {}) => {\n    if (this.options.count > 0) {\n      this.scrollToIndex(this.options.count - 1, {\n        align: 'end',\n        behavior,\n      })\n      return\n    }\n\n    this.scrollToOffset(Math.max(this.getTotalSize() - this.getSize(), 0), {\n      behavior,\n    })\n  }\n\n  getTotalSize = () => {\n    const measurements = this.getMeasurements()\n\n    let end: number\n    // If there are no measurements, set the end to paddingStart\n    // If there is only one lane, use the last measurement's end\n    // Otherwise find the maximum end value among all measurements\n    if (measurements.length === 0) {\n      end = this.options.paddingStart\n    } else if (this.options.lanes === 1) {\n      // Fast path: read last item's end directly from the flat typed array\n      // when available; avoids a Proxy.get + VirtualItem materialization\n      // just to call getTotalSize (which React renders trigger every commit).\n      const lastIdx = measurements.length - 1\n      const flat = this._flatMeasurements\n      if (flat != null) {\n        end = flat[lastIdx * 2]! + flat[lastIdx * 2 + 1]!\n      } else {\n        end = measurements[lastIdx]?.end ?? 0\n      }\n    } else {\n      const endByLane = Array<number | null>(this.options.lanes).fill(null)\n      let endIndex = measurements.length - 1\n      while (endIndex >= 0 && endByLane.some((val) => val === null)) {\n        const item = measurements[endIndex]!\n        if (endByLane[item.lane] === null) {\n          endByLane[item.lane] = item.end\n        }\n\n        endIndex--\n      }\n\n      end = Math.max(...endByLane.filter((val): val is number => val !== null))\n    }\n\n    return Math.max(\n      end - this.options.scrollMargin + this.options.paddingEnd,\n      0,\n    )\n  }\n\n  /**\n   * Returns a snapshot of currently-measured items suitable for round-\n   * tripping through state storage (sessionStorage, history, etc.) and\n   * passing back as `initialMeasurementsCache` on remount. Pair with the\n   * current `scrollOffset` to restore exact scroll position after navigation.\n   *\n   * Only items the consumer has actually rendered (and thus measured) appear\n   * in the snapshot; unmeasured items will fall back to `estimateSize` on\n   * restore. Returns an empty array if no items have been measured.\n   */\n  takeSnapshot = (): Array<VirtualItem> => {\n    const snapshot: Array<VirtualItem> = []\n    if (this.itemSizeCache.size === 0) return snapshot\n    // Iterate measurementsCache only for indices whose key is in itemSizeCache\n    // (i.e., have been measured). We build VirtualItem objects with the\n    // current start/size/end so they can be persisted as plain data.\n    const m = this.getMeasurements()\n    for (const item of m) {\n      if (item && this.itemSizeCache.has(item.key)) {\n        // Force materialization (lazy path) and copy plain fields.\n        snapshot.push({\n          index: item.index,\n          key: item.key,\n          start: item.start,\n          size: item.size,\n          end: item.end,\n          lane: item.lane,\n        })\n      }\n    }\n    return snapshot\n  }\n\n  private _scrollToOffset = (\n    offset: number,\n    {\n      adjustments,\n      behavior,\n    }: {\n      adjustments: number | undefined\n      behavior: ScrollBehavior | undefined\n    },\n  ) => {\n    // Record the intended logical scroll target so the next scroll event\n    // can reconcile against subpixel rounding by the browser.\n    this._intendedScrollOffset = offset + (adjustments ?? 0)\n    this.options.scrollToFn(offset, { behavior, adjustments }, this)\n  }\n\n  measure = () => {\n    // Reset pendingMin so the next getMeasurements rebuilds from index 0.\n    // Without this, a prior resizeItem() that left pendingMin > 0 would\n    // cause the rebuild to preserve stale items before that index.\n    this.pendingMin = null\n    this.itemSizeCache.clear()\n    this.laneAssignments.clear() // Clear lane cache for full re-layout\n    this.itemSizeCacheVersion++\n    this.notify(false)\n  }\n}\n\nconst findNearestBinarySearch = (\n  low: number,\n  high: number,\n  getCurrentValue: (i: number) => number,\n  value: number,\n) => {\n  while (low <= high) {\n    const middle = ((low + high) / 2) | 0\n    const currentValue = getCurrentValue(middle)\n\n    if (currentValue < value) {\n      low = middle + 1\n    } else if (currentValue > value) {\n      high = middle - 1\n    } else {\n      return middle\n    }\n  }\n\n  if (low > 0) {\n    return low - 1\n  } else {\n    return 0\n  }\n}\n\nfunction calculateRange({\n  measurements,\n  outerSize,\n  scrollOffset,\n  lanes,\n  flat,\n}: {\n  measurements: Array<VirtualItem>\n  outerSize: number\n  scrollOffset: number\n  lanes: number\n  flat: Float64Array | null\n}) {\n  const lastIndex = measurements.length - 1\n  // When the lanes===1 fast-path is active, read start/end directly from the\n  // flat Float64Array instead of going through the lazy-view Proxy. Cuts\n  // ~17 Proxy.get traps per scroll for the binary search alone.\n  const getStart = flat\n    ? (index: number) => flat[index * 2]!\n    : (index: number) => measurements[index]!.start\n  const getEnd = flat\n    ? (index: number) => flat[index * 2]! + flat[index * 2 + 1]!\n    : (index: number) => measurements[index]!.end\n\n  // handle case when item count is less than or equal to lanes\n  if (measurements.length <= lanes) {\n    return {\n      startIndex: 0,\n      endIndex: lastIndex,\n    }\n  }\n\n  let startIndex = findNearestBinarySearch(0, lastIndex, getStart, scrollOffset)\n  let endIndex = startIndex\n\n  if (lanes === 1) {\n    while (\n      endIndex < lastIndex &&\n      getEnd(endIndex) < scrollOffset + outerSize\n    ) {\n      endIndex++\n    }\n  } else if (lanes > 1) {\n    // Expand forward until we include the visible items from all lanes\n    // which are closer to the end of the virtualizer window\n    const endPerLane = Array(lanes).fill(0)\n    while (\n      endIndex < lastIndex &&\n      endPerLane.some((pos) => pos < scrollOffset + outerSize)\n    ) {\n      const item = measurements[endIndex]!\n      endPerLane[item.lane] = item.end\n      endIndex++\n    }\n\n    // Expand backward until we include all lanes' visible items\n    // closer to the top\n    const startPerLane = Array(lanes).fill(scrollOffset + outerSize)\n    while (startIndex >= 0 && startPerLane.some((pos) => pos >= scrollOffset)) {\n      const item = measurements[startIndex]!\n      startPerLane[item.lane] = item.start\n      startIndex--\n    }\n\n    // Align startIndex to the beginning of its lane\n    startIndex = Math.max(0, startIndex - (startIndex % lanes))\n    // Align endIndex to the end of its lane\n    endIndex = Math.min(lastIndex, endIndex + (lanes - 1 - (endIndex % lanes)))\n  }\n\n  return { startIndex, endIndex }\n}\n","import {\n  Virtualizer,\n  elementScroll,\n  observeElementOffset,\n  observeElementRect,\n  observeWindowOffset,\n  observeWindowRect,\n  windowScroll,\n} from '@tanstack/virtual-core'\nimport {\n  computed,\n  onScopeDispose,\n  shallowRef,\n  triggerRef,\n  unref,\n  watch,\n} from 'vue'\nimport type { PartialKeys, VirtualizerOptions } from '@tanstack/virtual-core'\nimport type { Ref } from 'vue'\n\nexport * from '@tanstack/virtual-core'\n\ntype MaybeRef<T> = T | Ref<T>\n\nfunction useVirtualizerBase<\n  TScrollElement extends Element | Window,\n  TItemElement extends Element,\n>(\n  options: MaybeRef<VirtualizerOptions<TScrollElement, TItemElement>>,\n): Ref<Virtualizer<TScrollElement, TItemElement>> {\n  const virtualizer = new Virtualizer(unref(options))\n  const state = shallowRef(virtualizer)\n\n  const cleanup = virtualizer._didMount()\n\n  watch(\n    () => unref(options).getScrollElement(),\n    (el) => {\n      if (el) {\n        virtualizer._willUpdate()\n      }\n    },\n    {\n      immediate: true,\n    },\n  )\n\n  watch(\n    () => unref(options),\n    (options) => {\n      virtualizer.setOptions({\n        ...options,\n        onChange: (instance, sync) => {\n          triggerRef(state)\n          options.onChange?.(instance, sync)\n        },\n      })\n\n      virtualizer._willUpdate()\n      triggerRef(state)\n    },\n    {\n      immediate: true,\n    },\n  )\n\n  onScopeDispose(cleanup)\n\n  return state\n}\n\nexport function useVirtualizer<\n  TScrollElement extends Element,\n  TItemElement extends Element,\n>(\n  options: MaybeRef<\n    PartialKeys<\n      VirtualizerOptions<TScrollElement, TItemElement>,\n      'observeElementRect' | 'observeElementOffset' | 'scrollToFn'\n    >\n  >,\n): Ref<Virtualizer<TScrollElement, TItemElement>> {\n  return useVirtualizerBase<TScrollElement, TItemElement>(\n    computed(() => ({\n      observeElementRect: observeElementRect,\n      observeElementOffset: observeElementOffset,\n      scrollToFn: elementScroll,\n      ...unref(options),\n    })),\n  )\n}\n\nexport function useWindowVirtualizer<TItemElement extends Element>(\n  options: MaybeRef<\n    PartialKeys<\n      VirtualizerOptions<Window, TItemElement>,\n      | 'observeElementRect'\n      | 'observeElementOffset'\n      | 'scrollToFn'\n      | 'getScrollElement'\n    >\n  >,\n): Ref<Virtualizer<Window, TItemElement>> {\n  return useVirtualizerBase<Window, TItemElement>(\n    computed(() => ({\n      getScrollElement: () => (typeof document !== 'undefined' ? window : null),\n      observeElementRect: observeWindowRect,\n      observeElementOffset: observeWindowOffset,\n      scrollToFn: windowScroll,\n      initialOffset: () =>\n        typeof document !== 'undefined' ? window.scrollY : 0,\n      ...unref(options),\n    })),\n  )\n}\n","<script lang=\"ts\">\nexport interface ListboxVirtualizerProps<T extends AcceptableValue = AcceptableValue> {\n  /** List of items */\n  options: T[]\n  /** Number of items rendered outside the visible area */\n  overscan?: number\n  /** Estimated size (in px) of each item */\n  estimateSize?: number | ((index: number) => number)\n  /** Text content for each item to achieve type-ahead feature */\n  textContent?: (option: T) => string\n}\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport type { VirtualItem, Virtualizer } from '@tanstack/vue-virtual'\nimport type { Ref, VNode } from 'vue'\nimport type { AcceptableValue } from '@/shared/types'\nimport { useVirtualizer } from '@tanstack/vue-virtual'\nimport { useParentElement } from '@vueuse/core'\nimport { refAutoReset } from '@vueuse/shared'\nimport { cloneVNode, computed, Fragment, useSlots } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { MAP_KEY_TO_FOCUS_INTENT } from '@/RovingFocus/utils'\nimport { findValuesBetween, getActiveElement } from '@/shared'\nimport { getNextMatch } from '@/shared/useTypeahead'\nimport { injectListboxRootContext } from './ListboxRoot.vue'\nimport { compare, queryCheckedElement } from './utils'\n\nconst props = defineProps<ListboxVirtualizerProps<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    option: T\n    virtualizer: Virtualizer<HTMLElement, Element>\n    virtualItem: VirtualItem\n  }) => any\n}>()\n\nconst slots = useSlots()\nconst rootContext = injectListboxRootContext()\nconst parentEl = useParentElement() as Ref<HTMLElement>\nconst { getItems } = useCollection<{ value: T }>()\n\n// set virtual true when this component mounted\nrootContext.isVirtual.value = true\n\nconst padding = computed(() => {\n  const el = parentEl.value\n  if (!el) {\n    return { start: 0, end: 0 }\n  }\n  else {\n    const styles = window.getComputedStyle(el)\n    return {\n      start: Number.parseFloat(styles.paddingBlockStart || styles.paddingTop),\n      end: Number.parseFloat(styles.paddingBlockEnd || styles.paddingBottom),\n    }\n  }\n})\n\nconst virtualizer = useVirtualizer(\n  {\n    get scrollPaddingStart() { return padding.value.start },\n    get scrollPaddingEnd() { return padding.value.end },\n    get count() { return props.options.length },\n    get horizontal() { return rootContext.orientation.value === 'horizontal' },\n    estimateSize(index) {\n      if (typeof props.estimateSize === 'function')\n        return props.estimateSize(index)\n\n      return props.estimateSize ?? 28\n    },\n    getScrollElement() { return parentEl.value },\n    overscan: props.overscan ?? 12,\n  },\n)\n\nconst virtualizedItems = computed(() => virtualizer.value.getVirtualItems().map((item) => {\n  const defaultNode = slots.default!({\n    option: props.options[item.index],\n    virtualizer: virtualizer.value,\n    virtualItem: item,\n  })[0]\n\n  const targetNode = defaultNode.type === Fragment && Array.isArray(defaultNode.children)\n    ? defaultNode.children.find(child => typeof (child as VNode).type !== 'symbol') as VNode\n    : defaultNode\n\n  return {\n    item,\n    is: cloneVNode(targetNode, {\n      'key': `${item.key}`,\n      'data-index': item.index,\n      'aria-setsize': props.options.length,\n      'aria-posinset': item.index + 1,\n      'style': {\n        position: 'absolute',\n        top: 0,\n        left: 0,\n        transform: `translateY(${item.start}px)`,\n        overflowAnchor: 'none',\n      },\n    }),\n  }\n}))\n\nrootContext.virtualFocusHook.on(({ event, scroll }) => {\n  // `scroll` is `false` only for the initial mount highlight. There we set the\n  // roving-tabindex target without focusing or scrolling, so a virtualized\n  // Listbox below the fold doesn't pull the page to it on load. User-driven\n  // highlights (keyboard, typeahead, select) keep scrolling as before.\n  const index = props.options.findIndex((option) => {\n    if (Array.isArray(rootContext.modelValue.value))\n      return compare(option, rootContext.modelValue.value[0], rootContext.by)\n    else\n      return compare(option, rootContext.modelValue.value!, rootContext.by)\n  })\n  if (index !== -1) {\n    event?.preventDefault()\n\n    // Bringing the checked item into the (internal) scroll viewport is safe — it\n    // only scrolls the listbox container, never the page.\n    virtualizer.value.scrollToIndex(index, { align: 'start' })\n    requestAnimationFrame(() => {\n      const item = queryCheckedElement(parentEl.value)\n      if (item) {\n        rootContext.changeHighlight(item, scroll, scroll ? undefined : false)\n        if (event)\n          item?.focus()\n      }\n    })\n  }\n  else if (scroll) {\n    rootContext.highlightFirstItem()\n  }\n  else {\n    // Mount highlight with no checked item: highlight the first enabled item only,\n    // mirroring the non-virtual path. `highlightFirstItem` is reserved for\n    // user-driven PageUp/Home navigation, which focuses and scrolls.\n    requestAnimationFrame(() => {\n      const item = getItems().find(i => i.ref.dataset.disabled !== '')?.ref\n      if (item)\n        rootContext.changeHighlight(item, false, false)\n    })\n  }\n})\n\nrootContext.virtualHighlightHook.on((value) => {\n  const index = props.options.findIndex((option) => {\n    return compare(option, value, rootContext.by)\n  })\n  virtualizer.value.scrollToIndex(index, { align: 'start' })\n  requestAnimationFrame(() => {\n    const item = queryCheckedElement(parentEl.value)\n    if (item)\n      rootContext.changeHighlight(item)\n  })\n})\n\n// Reset `search` 1 second after it was last updated\nconst search = refAutoReset('', 1000)\nconst optionsWithMetadata = computed(() => {\n  const parseTextContent = (option: T) => {\n    if (props.textContent)\n      return props.textContent(option)\n    else\n      return option?.toString().toLowerCase()\n  }\n\n  return props.options.map((option, index) => ({\n    index,\n    textContent: parseTextContent(option),\n  }))\n})\n\nfunction handleMultipleReplace(event: Event, intent: 'first' | 'last' | 'prev' | 'next') {\n  if (!rootContext.firstValue?.value || !rootContext.multiple.value || !Array.isArray(rootContext.modelValue.value))\n    return\n\n  const collection = getItems().filter(i => i.ref.dataset.disabled !== '')\n  const lastValue = collection.find(i => i.ref === rootContext.highlightedElement.value)?.value\n  if (!lastValue)\n    return\n\n  let value: T[] | null = null\n  switch (intent) {\n    case 'prev':\n    case 'next': {\n      value = findValuesBetween(props.options, rootContext.firstValue.value as T, lastValue)\n      break\n    }\n    case 'first': {\n      value = findValuesBetween(props.options, rootContext.firstValue.value as T, props.options?.[0])\n      break\n    }\n    case 'last': {\n      value = findValuesBetween(props.options, rootContext.firstValue.value as T, props.options.at(-1)!)\n      break\n    }\n  }\n  rootContext.modelValue.value = value\n}\n\nrootContext.virtualKeydownHook.on((event) => {\n  const isMetaKey = event.altKey || event.ctrlKey || event.metaKey\n  const isTabKey = event.key === 'Tab' && !isMetaKey\n  if (isTabKey)\n    return\n\n  let intent = MAP_KEY_TO_FOCUS_INTENT[event.key]\n\n  // Meta + A, select all feature\n  if (isMetaKey && event.key === 'a' && rootContext.multiple.value) {\n    event.preventDefault()\n    rootContext.modelValue.value = [...props.options]\n    // purposely make the focus to last\n    intent = 'last'\n  }\n  else if (event.shiftKey && intent) {\n    handleMultipleReplace(event, intent)\n  }\n\n  if (['first', 'last'].includes(intent)) {\n    event.preventDefault()\n\n    const index = intent === 'first' ? 0 : props.options.length - 1\n    virtualizer.value.scrollToIndex(index)\n    requestAnimationFrame(() => {\n      const items = getItems()\n      const item = intent === 'first' ? items[0] : items.at(-1)\n      if (item)\n        rootContext.changeHighlight(item.ref)\n    })\n  }\n  else if (!intent && !isMetaKey) {\n    search.value += event.key\n    const currentIndex = Number(getActiveElement()?.getAttribute('data-index'))\n    const currentMatch = optionsWithMetadata.value[currentIndex].textContent\n    const filteredOptions = optionsWithMetadata.value.map(i => i.textContent ?? '')\n    const next = getNextMatch(filteredOptions, search.value, currentMatch)\n\n    const nextMatch = optionsWithMetadata.value.find(option => option.textContent === next)\n    if (nextMatch) {\n      virtualizer.value.scrollToIndex(nextMatch.index, { align: 'start' })\n      requestAnimationFrame(() => {\n        const item = parentEl.value.querySelector(`[data-index=\"${nextMatch.index}\"]`)\n        if (item instanceof HTMLElement)\n          rootContext.changeHighlight(item)\n      })\n    }\n  }\n})\n</script>\n\n<template>\n  <div\n    data-reka-virtualizer\n    :style=\"{\n      position: 'relative',\n      width: '100%',\n      height: `${virtualizer.getTotalSize()}px`,\n    }\"\n  >\n    <component\n      :is=\"is\"\n      v-for=\"{ is, item } in virtualizedItems\"\n      :key=\"item.index\"\n    />\n  </div>\n</template>\n","<script lang=\"ts\">\nexport interface ListboxVirtualizerProps<T extends AcceptableValue = AcceptableValue> {\n  /** List of items */\n  options: T[]\n  /** Number of items rendered outside the visible area */\n  overscan?: number\n  /** Estimated size (in px) of each item */\n  estimateSize?: number | ((index: number) => number)\n  /** Text content for each item to achieve type-ahead feature */\n  textContent?: (option: T) => string\n}\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport type { VirtualItem, Virtualizer } from '@tanstack/vue-virtual'\nimport type { Ref, VNode } from 'vue'\nimport type { AcceptableValue } from '@/shared/types'\nimport { useVirtualizer } from '@tanstack/vue-virtual'\nimport { useParentElement } from '@vueuse/core'\nimport { refAutoReset } from '@vueuse/shared'\nimport { cloneVNode, computed, Fragment, useSlots } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { MAP_KEY_TO_FOCUS_INTENT } from '@/RovingFocus/utils'\nimport { findValuesBetween, getActiveElement } from '@/shared'\nimport { getNextMatch } from '@/shared/useTypeahead'\nimport { injectListboxRootContext } from './ListboxRoot.vue'\nimport { compare, queryCheckedElement } from './utils'\n\nconst props = defineProps<ListboxVirtualizerProps<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    option: T\n    virtualizer: Virtualizer<HTMLElement, Element>\n    virtualItem: VirtualItem\n  }) => any\n}>()\n\nconst slots = useSlots()\nconst rootContext = injectListboxRootContext()\nconst parentEl = useParentElement() as Ref<HTMLElement>\nconst { getItems } = useCollection<{ value: T }>()\n\n// set virtual true when this component mounted\nrootContext.isVirtual.value = true\n\nconst padding = computed(() => {\n  const el = parentEl.value\n  if (!el) {\n    return { start: 0, end: 0 }\n  }\n  else {\n    const styles = window.getComputedStyle(el)\n    return {\n      start: Number.parseFloat(styles.paddingBlockStart || styles.paddingTop),\n      end: Number.parseFloat(styles.paddingBlockEnd || styles.paddingBottom),\n    }\n  }\n})\n\nconst virtualizer = useVirtualizer(\n  {\n    get scrollPaddingStart() { return padding.value.start },\n    get scrollPaddingEnd() { return padding.value.end },\n    get count() { return props.options.length },\n    get horizontal() { return rootContext.orientation.value === 'horizontal' },\n    estimateSize(index) {\n      if (typeof props.estimateSize === 'function')\n        return props.estimateSize(index)\n\n      return props.estimateSize ?? 28\n    },\n    getScrollElement() { return parentEl.value },\n    overscan: props.overscan ?? 12,\n  },\n)\n\nconst virtualizedItems = computed(() => virtualizer.value.getVirtualItems().map((item) => {\n  const defaultNode = slots.default!({\n    option: props.options[item.index],\n    virtualizer: virtualizer.value,\n    virtualItem: item,\n  })[0]\n\n  const targetNode = defaultNode.type === Fragment && Array.isArray(defaultNode.children)\n    ? defaultNode.children.find(child => typeof (child as VNode).type !== 'symbol') as VNode\n    : defaultNode\n\n  return {\n    item,\n    is: cloneVNode(targetNode, {\n      'key': `${item.key}`,\n      'data-index': item.index,\n      'aria-setsize': props.options.length,\n      'aria-posinset': item.index + 1,\n      'style': {\n        position: 'absolute',\n        top: 0,\n        left: 0,\n        transform: `translateY(${item.start}px)`,\n        overflowAnchor: 'none',\n      },\n    }),\n  }\n}))\n\nrootContext.virtualFocusHook.on(({ event, scroll }) => {\n  // `scroll` is `false` only for the initial mount highlight. There we set the\n  // roving-tabindex target without focusing or scrolling, so a virtualized\n  // Listbox below the fold doesn't pull the page to it on load. User-driven\n  // highlights (keyboard, typeahead, select) keep scrolling as before.\n  const index = props.options.findIndex((option) => {\n    if (Array.isArray(rootContext.modelValue.value))\n      return compare(option, rootContext.modelValue.value[0], rootContext.by)\n    else\n      return compare(option, rootContext.modelValue.value!, rootContext.by)\n  })\n  if (index !== -1) {\n    event?.preventDefault()\n\n    // Bringing the checked item into the (internal) scroll viewport is safe — it\n    // only scrolls the listbox container, never the page.\n    virtualizer.value.scrollToIndex(index, { align: 'start' })\n    requestAnimationFrame(() => {\n      const item = queryCheckedElement(parentEl.value)\n      if (item) {\n        rootContext.changeHighlight(item, scroll, scroll ? undefined : false)\n        if (event)\n          item?.focus()\n      }\n    })\n  }\n  else if (scroll) {\n    rootContext.highlightFirstItem()\n  }\n  else {\n    // Mount highlight with no checked item: highlight the first enabled item only,\n    // mirroring the non-virtual path. `highlightFirstItem` is reserved for\n    // user-driven PageUp/Home navigation, which focuses and scrolls.\n    requestAnimationFrame(() => {\n      const item = getItems().find(i => i.ref.dataset.disabled !== '')?.ref\n      if (item)\n        rootContext.changeHighlight(item, false, false)\n    })\n  }\n})\n\nrootContext.virtualHighlightHook.on((value) => {\n  const index = props.options.findIndex((option) => {\n    return compare(option, value, rootContext.by)\n  })\n  virtualizer.value.scrollToIndex(index, { align: 'start' })\n  requestAnimationFrame(() => {\n    const item = queryCheckedElement(parentEl.value)\n    if (item)\n      rootContext.changeHighlight(item)\n  })\n})\n\n// Reset `search` 1 second after it was last updated\nconst search = refAutoReset('', 1000)\nconst optionsWithMetadata = computed(() => {\n  const parseTextContent = (option: T) => {\n    if (props.textContent)\n      return props.textContent(option)\n    else\n      return option?.toString().toLowerCase()\n  }\n\n  return props.options.map((option, index) => ({\n    index,\n    textContent: parseTextContent(option),\n  }))\n})\n\nfunction handleMultipleReplace(event: Event, intent: 'first' | 'last' | 'prev' | 'next') {\n  if (!rootContext.firstValue?.value || !rootContext.multiple.value || !Array.isArray(rootContext.modelValue.value))\n    return\n\n  const collection = getItems().filter(i => i.ref.dataset.disabled !== '')\n  const lastValue = collection.find(i => i.ref === rootContext.highlightedElement.value)?.value\n  if (!lastValue)\n    return\n\n  let value: T[] | null = null\n  switch (intent) {\n    case 'prev':\n    case 'next': {\n      value = findValuesBetween(props.options, rootContext.firstValue.value as T, lastValue)\n      break\n    }\n    case 'first': {\n      value = findValuesBetween(props.options, rootContext.firstValue.value as T, props.options?.[0])\n      break\n    }\n    case 'last': {\n      value = findValuesBetween(props.options, rootContext.firstValue.value as T, props.options.at(-1)!)\n      break\n    }\n  }\n  rootContext.modelValue.value = value\n}\n\nrootContext.virtualKeydownHook.on((event) => {\n  const isMetaKey = event.altKey || event.ctrlKey || event.metaKey\n  const isTabKey = event.key === 'Tab' && !isMetaKey\n  if (isTabKey)\n    return\n\n  let intent = MAP_KEY_TO_FOCUS_INTENT[event.key]\n\n  // Meta + A, select all feature\n  if (isMetaKey && event.key === 'a' && rootContext.multiple.value) {\n    event.preventDefault()\n    rootContext.modelValue.value = [...props.options]\n    // purposely make the focus to last\n    intent = 'last'\n  }\n  else if (event.shiftKey && intent) {\n    handleMultipleReplace(event, intent)\n  }\n\n  if (['first', 'last'].includes(intent)) {\n    event.preventDefault()\n\n    const index = intent === 'first' ? 0 : props.options.length - 1\n    virtualizer.value.scrollToIndex(index)\n    requestAnimationFrame(() => {\n      const items = getItems()\n      const item = intent === 'first' ? items[0] : items.at(-1)\n      if (item)\n        rootContext.changeHighlight(item.ref)\n    })\n  }\n  else if (!intent && !isMetaKey) {\n    search.value += event.key\n    const currentIndex = Number(getActiveElement()?.getAttribute('data-index'))\n    const currentMatch = optionsWithMetadata.value[currentIndex].textContent\n    const filteredOptions = optionsWithMetadata.value.map(i => i.textContent ?? '')\n    const next = getNextMatch(filteredOptions, search.value, currentMatch)\n\n    const nextMatch = optionsWithMetadata.value.find(option => option.textContent === next)\n    if (nextMatch) {\n      virtualizer.value.scrollToIndex(nextMatch.index, { align: 'start' })\n      requestAnimationFrame(() => {\n        const item = parentEl.value.querySelector(`[data-index=\"${nextMatch.index}\"]`)\n        if (item instanceof HTMLElement)\n          rootContext.changeHighlight(item)\n      })\n    }\n  }\n})\n</script>\n\n<template>\n  <div\n    data-reka-virtualizer\n    :style=\"{\n      position: 'relative',\n      width: '100%',\n      height: `${virtualizer.getTotalSize()}px`,\n    }\"\n  >\n    <component\n      :is=\"is\"\n      v-for=\"{ is, item } in virtualizedItems\"\n      :key=\"item.index\"\n    />\n  </div>\n</template>\n","<script lang=\"ts\">\nimport type { ReferenceElement } from '@floating-ui/vue'\nimport type { Ref } from 'vue'\nimport { createContext } from '@/shared'\n\nexport interface Measurable {\n  getBoundingClientRect: () => DOMRect\n}\n\ninterface PopperRootContext {\n  anchor: Ref<ReferenceElement | undefined>\n  onAnchorChange: (element: ReferenceElement | undefined) => void\n}\n\nexport const [injectPopperRootContext, providePopperRootContext]\n  = createContext<PopperRootContext>('PopperRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst anchor = ref<ReferenceElement>()\n\nprovidePopperRootContext({\n  anchor,\n  onAnchorChange: element => anchor.value = element,\n})\n</script>\n\n<template>\n  <slot />\n</template>\n","<script lang=\"ts\">\nimport type { ReferenceElement } from '@floating-ui/vue'\nimport type { Ref } from 'vue'\nimport { createContext } from '@/shared'\n\nexport interface Measurable {\n  getBoundingClientRect: () => DOMRect\n}\n\ninterface PopperRootContext {\n  anchor: Ref<ReferenceElement | undefined>\n  onAnchorChange: (element: ReferenceElement | undefined) => void\n}\n\nexport const [injectPopperRootContext, providePopperRootContext]\n  = createContext<PopperRootContext>('PopperRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst anchor = ref<ReferenceElement>()\n\nprovidePopperRootContext({\n  anchor,\n  onAnchorChange: element => anchor.value = element,\n})\n</script>\n\n<template>\n  <slot />\n</template>\n","<script lang=\"ts\">\nimport type { ReferenceElement } from '@floating-ui/vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PopperAnchorProps extends PrimitiveProps {\n  /**\n   *  The reference (or anchor) element that is being referred to for positioning.\n   *\n   *  If not provided will use the current component as anchor.\n   */\n  reference?: ReferenceElement\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { watchPostEffect } from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectPopperRootContext } from './PopperRoot.vue'\n\nconst props = defineProps<PopperAnchorProps>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst rootContext = injectPopperRootContext()\n\nwatchPostEffect(() => {\n  rootContext.onAnchorChange(props.reference ?? currentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ReferenceElement } from '@floating-ui/vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PopperAnchorProps extends PrimitiveProps {\n  /**\n   *  The reference (or anchor) element that is being referred to for positioning.\n   *\n   *  If not provided will use the current component as anchor.\n   */\n  reference?: ReferenceElement\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { watchPostEffect } from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectPopperRootContext } from './PopperRoot.vue'\n\nconst props = defineProps<PopperAnchorProps>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst rootContext = injectPopperRootContext()\n\nwatchPostEffect(() => {\n  rootContext.onAnchorChange(props.reference ?? currentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '../useForwardExpose'\n\nexport interface ArrowProps extends PrimitiveProps {\n  /**\n   * The width of the arrow in pixels.\n   *\n   * @defaultValue 10\n   */\n  width?: number\n  /**\n   * The height of the arrow in pixels.\n   *\n   * @defaultValue 5\n   */\n  height?: number\n  /**\n   * When `true`, render the rounded version of arrow. Do not work with `as`/`asChild`\n   *\n   * @defaultValue false\n   */\n  rounded?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<ArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :width=\"width\"\n    :height=\"height\"\n    :viewBox=\"asChild ? undefined : '0 0 12 6'\"\n    :preserveAspectRatio=\"asChild ? undefined : 'none'\"\n  >\n    <slot>\n      <path\n        v-if=\"!rounded\"\n        d=\"M0 0L6 6L12 0\"\n      />\n      <path\n        v-else\n        d=\"M0 0L4.58579 4.58579C5.36683 5.36683 6.63316 5.36684 7.41421 4.58579L12 0\"\n      />\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '../useForwardExpose'\n\nexport interface ArrowProps extends PrimitiveProps {\n  /**\n   * The width of the arrow in pixels.\n   *\n   * @defaultValue 10\n   */\n  width?: number\n  /**\n   * The height of the arrow in pixels.\n   *\n   * @defaultValue 5\n   */\n  height?: number\n  /**\n   * When `true`, render the rounded version of arrow. Do not work with `as`/`asChild`\n   *\n   * @defaultValue false\n   */\n  rounded?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<ArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :width=\"width\"\n    :height=\"height\"\n    :viewBox=\"asChild ? undefined : '0 0 12 6'\"\n    :preserveAspectRatio=\"asChild ? undefined : 'none'\"\n  >\n    <slot>\n      <path\n        v-if=\"!rounded\"\n        d=\"M0 0L6 6L12 0\"\n      />\n      <path\n        v-else\n        d=\"M0 0L4.58579 4.58579C5.36683 5.36683 6.63316 5.36684 7.41421 4.58579L12 0\"\n      />\n    </slot>\n  </Primitive>\n</template>\n","import type { Middleware, Placement } from '@floating-ui/vue'\n\nconst SIDE_OPTIONS = ['top', 'right', 'bottom', 'left'] as const\nconst ALIGN_OPTIONS = ['start', 'center', 'end'] as const\n\nexport type Side = (typeof SIDE_OPTIONS)[number]\nexport type Align = (typeof ALIGN_OPTIONS)[number]\n\nexport function isNotNull<T>(value: T | null): value is T {\n  return value !== null\n}\n\nexport function transformOrigin(options: {\n  arrowWidth: number\n  arrowHeight: number\n}): Middleware {\n  return {\n    name: 'transformOrigin',\n    options,\n    fn(data) {\n      const { placement, rects, middlewareData } = data\n\n      const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0\n      const isArrowHidden = cannotCenterArrow\n      const arrowWidth = isArrowHidden ? 0 : options.arrowWidth\n      const arrowHeight = isArrowHidden ? 0 : options.arrowHeight\n\n      const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement)\n      const noArrowAlign = { start: '0%', center: '50%', end: '100%' }[\n        placedAlign\n      ]\n\n      const arrowXCenter = (middlewareData.arrow?.x ?? 0) + arrowWidth / 2\n      const arrowYCenter = (middlewareData.arrow?.y ?? 0) + arrowHeight / 2\n\n      let x = ''\n      let y = ''\n\n      if (placedSide === 'bottom') {\n        x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`\n        y = `${-arrowHeight}px`\n      }\n      else if (placedSide === 'top') {\n        x = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`\n        y = `${rects.floating.height + arrowHeight}px`\n      }\n      else if (placedSide === 'right') {\n        x = `${-arrowHeight}px`\n        y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`\n      }\n      else if (placedSide === 'left') {\n        x = `${rects.floating.width + arrowHeight}px`\n        y = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`\n      }\n      return { data: { x, y } }\n    },\n  }\n}\n\nexport function getSideAndAlignFromPlacement(placement: Placement) {\n  const [side, align = 'center'] = placement.split('-')\n  return [side as Side, align as Align] as const\n}\n","/**\n * Custom positioning reference element.\n * @see https://floating-ui.com/docs/virtual-elements\n */\n\nconst sides = ['top', 'right', 'bottom', 'left'];\nconst alignments = ['start', 'end'];\nconst placements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + \"-\" + alignments[0], side + \"-\" + alignments[1]), []);\nconst min = Math.min;\nconst max = Math.max;\nconst round = Math.round;\nconst floor = Math.floor;\nconst createCoords = v => ({\n  x: v,\n  y: v\n});\nconst oppositeSideMap = {\n  left: 'right',\n  right: 'left',\n  bottom: 'top',\n  top: 'bottom'\n};\nfunction clamp(start, value, end) {\n  return max(start, min(value, end));\n}\nfunction evaluate(value, param) {\n  return typeof value === 'function' ? value(param) : value;\n}\nfunction getSide(placement) {\n  return placement.split('-')[0];\n}\nfunction getAlignment(placement) {\n  return placement.split('-')[1];\n}\nfunction getOppositeAxis(axis) {\n  return axis === 'x' ? 'y' : 'x';\n}\nfunction getAxisLength(axis) {\n  return axis === 'y' ? 'height' : 'width';\n}\nfunction getSideAxis(placement) {\n  const firstChar = placement[0];\n  return firstChar === 't' || firstChar === 'b' ? 'y' : 'x';\n}\nfunction getAlignmentAxis(placement) {\n  return getOppositeAxis(getSideAxis(placement));\n}\nfunction getAlignmentSides(placement, rects, rtl) {\n  if (rtl === void 0) {\n    rtl = false;\n  }\n  const alignment = getAlignment(placement);\n  const alignmentAxis = getAlignmentAxis(placement);\n  const length = getAxisLength(alignmentAxis);\n  let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top';\n  if (rects.reference[length] > rects.floating[length]) {\n    mainAlignmentSide = getOppositePlacement(mainAlignmentSide);\n  }\n  return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];\n}\nfunction getExpandedPlacements(placement) {\n  const oppositePlacement = getOppositePlacement(placement);\n  return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];\n}\nfunction getOppositeAlignmentPlacement(placement) {\n  return placement.includes('start') ? placement.replace('start', 'end') : placement.replace('end', 'start');\n}\nconst lrPlacement = ['left', 'right'];\nconst rlPlacement = ['right', 'left'];\nconst tbPlacement = ['top', 'bottom'];\nconst btPlacement = ['bottom', 'top'];\nfunction getSideList(side, isStart, rtl) {\n  switch (side) {\n    case 'top':\n    case 'bottom':\n      if (rtl) return isStart ? rlPlacement : lrPlacement;\n      return isStart ? lrPlacement : rlPlacement;\n    case 'left':\n    case 'right':\n      return isStart ? tbPlacement : btPlacement;\n    default:\n      return [];\n  }\n}\nfunction getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {\n  const alignment = getAlignment(placement);\n  let list = getSideList(getSide(placement), direction === 'start', rtl);\n  if (alignment) {\n    list = list.map(side => side + \"-\" + alignment);\n    if (flipAlignment) {\n      list = list.concat(list.map(getOppositeAlignmentPlacement));\n    }\n  }\n  return list;\n}\nfunction getOppositePlacement(placement) {\n  const side = getSide(placement);\n  return oppositeSideMap[side] + placement.slice(side.length);\n}\nfunction expandPaddingObject(padding) {\n  return {\n    top: 0,\n    right: 0,\n    bottom: 0,\n    left: 0,\n    ...padding\n  };\n}\nfunction getPaddingObject(padding) {\n  return typeof padding !== 'number' ? expandPaddingObject(padding) : {\n    top: padding,\n    right: padding,\n    bottom: padding,\n    left: padding\n  };\n}\nfunction rectToClientRect(rect) {\n  const {\n    x,\n    y,\n    width,\n    height\n  } = rect;\n  return {\n    width,\n    height,\n    top: y,\n    left: x,\n    right: x + width,\n    bottom: y + height,\n    x,\n    y\n  };\n}\n\nexport { alignments, clamp, createCoords, evaluate, expandPaddingObject, floor, getAlignment, getAlignmentAxis, getAlignmentSides, getAxisLength, getExpandedPlacements, getOppositeAlignmentPlacement, getOppositeAxis, getOppositeAxisPlacements, getOppositePlacement, getPaddingObject, getSide, getSideAxis, max, min, placements, rectToClientRect, round, sides };\n","import { getSideAxis, getAlignmentAxis, getAxisLength, getSide, getAlignment, evaluate, getPaddingObject, rectToClientRect, min, clamp, placements, getAlignmentSides, getOppositeAlignmentPlacement, getOppositePlacement, getExpandedPlacements, getOppositeAxisPlacements, sides, max, getOppositeAxis } from '@floating-ui/utils';\nexport { rectToClientRect } from '@floating-ui/utils';\n\nfunction computeCoordsFromPlacement(_ref, placement, rtl) {\n  let {\n    reference,\n    floating\n  } = _ref;\n  const sideAxis = getSideAxis(placement);\n  const alignmentAxis = getAlignmentAxis(placement);\n  const alignLength = getAxisLength(alignmentAxis);\n  const side = getSide(placement);\n  const isVertical = sideAxis === 'y';\n  const commonX = reference.x + reference.width / 2 - floating.width / 2;\n  const commonY = reference.y + reference.height / 2 - floating.height / 2;\n  const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;\n  let coords;\n  switch (side) {\n    case 'top':\n      coords = {\n        x: commonX,\n        y: reference.y - floating.height\n      };\n      break;\n    case 'bottom':\n      coords = {\n        x: commonX,\n        y: reference.y + reference.height\n      };\n      break;\n    case 'right':\n      coords = {\n        x: reference.x + reference.width,\n        y: commonY\n      };\n      break;\n    case 'left':\n      coords = {\n        x: reference.x - floating.width,\n        y: commonY\n      };\n      break;\n    default:\n      coords = {\n        x: reference.x,\n        y: reference.y\n      };\n  }\n  switch (getAlignment(placement)) {\n    case 'start':\n      coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);\n      break;\n    case 'end':\n      coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);\n      break;\n  }\n  return coords;\n}\n\n/**\n * Resolves with an object of overflow side offsets that determine how much the\n * element is overflowing a given clipping boundary on each side.\n * - positive = overflowing the boundary by that number of pixels\n * - negative = how many pixels left before it will overflow\n * - 0 = lies flush with the boundary\n * @see https://floating-ui.com/docs/detectOverflow\n */\nasync function detectOverflow(state, options) {\n  var _await$platform$isEle;\n  if (options === void 0) {\n    options = {};\n  }\n  const {\n    x,\n    y,\n    platform,\n    rects,\n    elements,\n    strategy\n  } = state;\n  const {\n    boundary = 'clippingAncestors',\n    rootBoundary = 'viewport',\n    elementContext = 'floating',\n    altBoundary = false,\n    padding = 0\n  } = evaluate(options, state);\n  const paddingObject = getPaddingObject(padding);\n  const altContext = elementContext === 'floating' ? 'reference' : 'floating';\n  const element = elements[altBoundary ? altContext : elementContext];\n  const clippingClientRect = rectToClientRect(await platform.getClippingRect({\n    element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))),\n    boundary,\n    rootBoundary,\n    strategy\n  }));\n  const rect = elementContext === 'floating' ? {\n    x,\n    y,\n    width: rects.floating.width,\n    height: rects.floating.height\n  } : rects.reference;\n  const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating));\n  const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || {\n    x: 1,\n    y: 1\n  } : {\n    x: 1,\n    y: 1\n  };\n  const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({\n    elements,\n    rect,\n    offsetParent,\n    strategy\n  }) : rect);\n  return {\n    top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,\n    bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,\n    left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,\n    right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x\n  };\n}\n\n// Maximum number of resets that can occur before bailing to avoid infinite reset loops.\nconst MAX_RESET_COUNT = 50;\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element\n * next to a given reference element.\n *\n * This export does not have any `platform` interface logic. You will need to\n * write one for the platform you are using Floating UI with.\n */\nconst computePosition = async (reference, floating, config) => {\n  const {\n    placement = 'bottom',\n    strategy = 'absolute',\n    middleware = [],\n    platform\n  } = config;\n  const platformWithDetectOverflow = platform.detectOverflow ? platform : {\n    ...platform,\n    detectOverflow\n  };\n  const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating));\n  let rects = await platform.getElementRects({\n    reference,\n    floating,\n    strategy\n  });\n  let {\n    x,\n    y\n  } = computeCoordsFromPlacement(rects, placement, rtl);\n  let statefulPlacement = placement;\n  let resetCount = 0;\n  const middlewareData = {};\n  for (let i = 0; i < middleware.length; i++) {\n    const currentMiddleware = middleware[i];\n    if (!currentMiddleware) {\n      continue;\n    }\n    const {\n      name,\n      fn\n    } = currentMiddleware;\n    const {\n      x: nextX,\n      y: nextY,\n      data,\n      reset\n    } = await fn({\n      x,\n      y,\n      initialPlacement: placement,\n      placement: statefulPlacement,\n      strategy,\n      middlewareData,\n      rects,\n      platform: platformWithDetectOverflow,\n      elements: {\n        reference,\n        floating\n      }\n    });\n    x = nextX != null ? nextX : x;\n    y = nextY != null ? nextY : y;\n    middlewareData[name] = {\n      ...middlewareData[name],\n      ...data\n    };\n    if (reset && resetCount < MAX_RESET_COUNT) {\n      resetCount++;\n      if (typeof reset === 'object') {\n        if (reset.placement) {\n          statefulPlacement = reset.placement;\n        }\n        if (reset.rects) {\n          rects = reset.rects === true ? await platform.getElementRects({\n            reference,\n            floating,\n            strategy\n          }) : reset.rects;\n        }\n        ({\n          x,\n          y\n        } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));\n      }\n      i = -1;\n    }\n  }\n  return {\n    x,\n    y,\n    placement: statefulPlacement,\n    strategy,\n    middlewareData\n  };\n};\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = options => ({\n  name: 'arrow',\n  options,\n  async fn(state) {\n    const {\n      x,\n      y,\n      placement,\n      rects,\n      platform,\n      elements,\n      middlewareData\n    } = state;\n    // Since `element` is required, we don't Partial<> the type.\n    const {\n      element,\n      padding = 0\n    } = evaluate(options, state) || {};\n    if (element == null) {\n      return {};\n    }\n    const paddingObject = getPaddingObject(padding);\n    const coords = {\n      x,\n      y\n    };\n    const axis = getAlignmentAxis(placement);\n    const length = getAxisLength(axis);\n    const arrowDimensions = await platform.getDimensions(element);\n    const isYAxis = axis === 'y';\n    const minProp = isYAxis ? 'top' : 'left';\n    const maxProp = isYAxis ? 'bottom' : 'right';\n    const clientProp = isYAxis ? 'clientHeight' : 'clientWidth';\n    const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];\n    const startDiff = coords[axis] - rects.reference[axis];\n    const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element));\n    let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;\n\n    // DOM platform can return `window` as the `offsetParent`.\n    if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) {\n      clientSize = elements.floating[clientProp] || rects.floating[length];\n    }\n    const centerToReference = endDiff / 2 - startDiff / 2;\n\n    // If the padding is large enough that it causes the arrow to no longer be\n    // centered, modify the padding so that it is centered.\n    const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;\n    const minPadding = min(paddingObject[minProp], largestPossiblePadding);\n    const maxPadding = min(paddingObject[maxProp], largestPossiblePadding);\n\n    // Make sure the arrow doesn't overflow the floating element if the center\n    // point is outside the floating element's bounds.\n    const min$1 = minPadding;\n    const max = clientSize - arrowDimensions[length] - maxPadding;\n    const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;\n    const offset = clamp(min$1, center, max);\n\n    // If the reference is small enough that the arrow's padding causes it to\n    // to point to nothing for an aligned placement, adjust the offset of the\n    // floating element itself. To ensure `shift()` continues to take action,\n    // a single reset is performed when this is true.\n    const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;\n    const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0;\n    return {\n      [axis]: coords[axis] + alignmentOffset,\n      data: {\n        [axis]: offset,\n        centerOffset: center - offset - alignmentOffset,\n        ...(shouldAddOffset && {\n          alignmentOffset\n        })\n      },\n      reset: shouldAddOffset\n    };\n  }\n});\n\nfunction getPlacementList(alignment, autoAlignment, allowedPlacements) {\n  const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement);\n  return allowedPlacementsSortedByAlignment.filter(placement => {\n    if (alignment) {\n      return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false);\n    }\n    return true;\n  });\n}\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    name: 'autoPlacement',\n    options,\n    async fn(state) {\n      var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE;\n      const {\n        rects,\n        middlewareData,\n        placement,\n        platform,\n        elements\n      } = state;\n      const {\n        crossAxis = false,\n        alignment,\n        allowedPlacements = placements,\n        autoAlignment = true,\n        ...detectOverflowOptions\n      } = evaluate(options, state);\n      const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements;\n      const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n      const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0;\n      const currentPlacement = placements$1[currentIndex];\n      if (currentPlacement == null) {\n        return {};\n      }\n      const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)));\n\n      // Make `computeCoords` start from the right place.\n      if (placement !== currentPlacement) {\n        return {\n          reset: {\n            placement: placements$1[0]\n          }\n        };\n      }\n      const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]];\n      const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), {\n        placement: currentPlacement,\n        overflows: currentOverflows\n      }];\n      const nextPlacement = placements$1[currentIndex + 1];\n\n      // There are more placements to check.\n      if (nextPlacement) {\n        return {\n          data: {\n            index: currentIndex + 1,\n            overflows: allOverflows\n          },\n          reset: {\n            placement: nextPlacement\n          }\n        };\n      }\n      const placementsSortedByMostSpace = allOverflows.map(d => {\n        const alignment = getAlignment(d.placement);\n        return [d.placement, alignment && crossAxis ?\n        // Check along the mainAxis and main crossAxis side.\n        d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) :\n        // Check only the mainAxis.\n        d.overflows[0], d.overflows];\n      }).sort((a, b) => a[1] - b[1]);\n      const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0,\n      // Aligned placements should not check their opposite crossAxis\n      // side.\n      getAlignment(d[0]) ? 2 : 3).every(v => v <= 0));\n      const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0];\n      if (resetPlacement !== placement) {\n        return {\n          data: {\n            index: currentIndex + 1,\n            overflows: allOverflows\n          },\n          reset: {\n            placement: resetPlacement\n          }\n        };\n      }\n      return {};\n    }\n  };\n};\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    name: 'flip',\n    options,\n    async fn(state) {\n      var _middlewareData$arrow, _middlewareData$flip;\n      const {\n        placement,\n        middlewareData,\n        rects,\n        initialPlacement,\n        platform,\n        elements\n      } = state;\n      const {\n        mainAxis: checkMainAxis = true,\n        crossAxis: checkCrossAxis = true,\n        fallbackPlacements: specifiedFallbackPlacements,\n        fallbackStrategy = 'bestFit',\n        fallbackAxisSideDirection = 'none',\n        flipAlignment = true,\n        ...detectOverflowOptions\n      } = evaluate(options, state);\n\n      // If a reset by the arrow was caused due to an alignment offset being\n      // added, we should skip any logic now since `flip()` has already done its\n      // work.\n      // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643\n      if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n        return {};\n      }\n      const side = getSide(placement);\n      const initialSideAxis = getSideAxis(initialPlacement);\n      const isBasePlacement = getSide(initialPlacement) === initialPlacement;\n      const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n      const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));\n      const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none';\n      if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) {\n        fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));\n      }\n      const placements = [initialPlacement, ...fallbackPlacements];\n      const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n      const overflows = [];\n      let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];\n      if (checkMainAxis) {\n        overflows.push(overflow[side]);\n      }\n      if (checkCrossAxis) {\n        const sides = getAlignmentSides(placement, rects, rtl);\n        overflows.push(overflow[sides[0]], overflow[sides[1]]);\n      }\n      overflowsData = [...overflowsData, {\n        placement,\n        overflows\n      }];\n\n      // One or more sides is overflowing.\n      if (!overflows.every(side => side <= 0)) {\n        var _middlewareData$flip2, _overflowsData$filter;\n        const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;\n        const nextPlacement = placements[nextIndex];\n        if (nextPlacement) {\n          const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false;\n          if (!ignoreCrossAxisOverflow ||\n          // We leave the current main axis only if every placement on that axis\n          // overflows the main axis.\n          overflowsData.every(d => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) {\n            // Try next placement and re-run the lifecycle.\n            return {\n              data: {\n                index: nextIndex,\n                overflows: overflowsData\n              },\n              reset: {\n                placement: nextPlacement\n              }\n            };\n          }\n        }\n\n        // First, find the candidates that fit on the mainAxis side of overflow,\n        // then find the placement that fits the best on the main crossAxis side.\n        let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;\n\n        // Otherwise fallback.\n        if (!resetPlacement) {\n          switch (fallbackStrategy) {\n            case 'bestFit':\n              {\n                var _overflowsData$filter2;\n                const placement = (_overflowsData$filter2 = overflowsData.filter(d => {\n                  if (hasFallbackAxisSideDirection) {\n                    const currentSideAxis = getSideAxis(d.placement);\n                    return currentSideAxis === initialSideAxis ||\n                    // Create a bias to the `y` side axis due to horizontal\n                    // reading directions favoring greater width.\n                    currentSideAxis === 'y';\n                  }\n                  return true;\n                }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0];\n                if (placement) {\n                  resetPlacement = placement;\n                }\n                break;\n              }\n            case 'initialPlacement':\n              resetPlacement = initialPlacement;\n              break;\n          }\n        }\n        if (placement !== resetPlacement) {\n          return {\n            reset: {\n              placement: resetPlacement\n            }\n          };\n        }\n      }\n      return {};\n    }\n  };\n};\n\nfunction getSideOffsets(overflow, rect) {\n  return {\n    top: overflow.top - rect.height,\n    right: overflow.right - rect.width,\n    bottom: overflow.bottom - rect.height,\n    left: overflow.left - rect.width\n  };\n}\nfunction isAnySideFullyClipped(overflow) {\n  return sides.some(side => overflow[side] >= 0);\n}\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    name: 'hide',\n    options,\n    async fn(state) {\n      const {\n        rects,\n        platform\n      } = state;\n      const {\n        strategy = 'referenceHidden',\n        ...detectOverflowOptions\n      } = evaluate(options, state);\n      switch (strategy) {\n        case 'referenceHidden':\n          {\n            const overflow = await platform.detectOverflow(state, {\n              ...detectOverflowOptions,\n              elementContext: 'reference'\n            });\n            const offsets = getSideOffsets(overflow, rects.reference);\n            return {\n              data: {\n                referenceHiddenOffsets: offsets,\n                referenceHidden: isAnySideFullyClipped(offsets)\n              }\n            };\n          }\n        case 'escaped':\n          {\n            const overflow = await platform.detectOverflow(state, {\n              ...detectOverflowOptions,\n              altBoundary: true\n            });\n            const offsets = getSideOffsets(overflow, rects.floating);\n            return {\n              data: {\n                escapedOffsets: offsets,\n                escaped: isAnySideFullyClipped(offsets)\n              }\n            };\n          }\n        default:\n          {\n            return {};\n          }\n      }\n    }\n  };\n};\n\nfunction getBoundingRect(rects) {\n  const minX = min(...rects.map(rect => rect.left));\n  const minY = min(...rects.map(rect => rect.top));\n  const maxX = max(...rects.map(rect => rect.right));\n  const maxY = max(...rects.map(rect => rect.bottom));\n  return {\n    x: minX,\n    y: minY,\n    width: maxX - minX,\n    height: maxY - minY\n  };\n}\nfunction getRectsByLine(rects) {\n  const sortedRects = rects.slice().sort((a, b) => a.y - b.y);\n  const groups = [];\n  let prevRect = null;\n  for (let i = 0; i < sortedRects.length; i++) {\n    const rect = sortedRects[i];\n    if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) {\n      groups.push([rect]);\n    } else {\n      groups[groups.length - 1].push(rect);\n    }\n    prevRect = rect;\n  }\n  return groups.map(rect => rectToClientRect(getBoundingRect(rect)));\n}\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    name: 'inline',\n    options,\n    async fn(state) {\n      const {\n        placement,\n        elements,\n        rects,\n        platform,\n        strategy\n      } = state;\n      // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a\n      // ClientRect's bounds, despite the event listener being triggered. A\n      // padding of 2 seems to handle this issue.\n      const {\n        padding = 2,\n        x,\n        y\n      } = evaluate(options, state);\n      const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []);\n      const clientRects = getRectsByLine(nativeClientRects);\n      const fallback = rectToClientRect(getBoundingRect(nativeClientRects));\n      const paddingObject = getPaddingObject(padding);\n      function getBoundingClientRect() {\n        // There are two rects and they are disjoined.\n        if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) {\n          // Find the first rect in which the point is fully inside.\n          return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback;\n        }\n\n        // There are 2 or more connected rects.\n        if (clientRects.length >= 2) {\n          if (getSideAxis(placement) === 'y') {\n            const firstRect = clientRects[0];\n            const lastRect = clientRects[clientRects.length - 1];\n            const isTop = getSide(placement) === 'top';\n            const top = firstRect.top;\n            const bottom = lastRect.bottom;\n            const left = isTop ? firstRect.left : lastRect.left;\n            const right = isTop ? firstRect.right : lastRect.right;\n            const width = right - left;\n            const height = bottom - top;\n            return {\n              top,\n              bottom,\n              left,\n              right,\n              width,\n              height,\n              x: left,\n              y: top\n            };\n          }\n          const isLeftSide = getSide(placement) === 'left';\n          const maxRight = max(...clientRects.map(rect => rect.right));\n          const minLeft = min(...clientRects.map(rect => rect.left));\n          const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight);\n          const top = measureRects[0].top;\n          const bottom = measureRects[measureRects.length - 1].bottom;\n          const left = minLeft;\n          const right = maxRight;\n          const width = right - left;\n          const height = bottom - top;\n          return {\n            top,\n            bottom,\n            left,\n            right,\n            width,\n            height,\n            x: left,\n            y: top\n          };\n        }\n        return fallback;\n      }\n      const resetRects = await platform.getElementRects({\n        reference: {\n          getBoundingClientRect\n        },\n        floating: elements.floating,\n        strategy\n      });\n      if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) {\n        return {\n          reset: {\n            rects: resetRects\n          }\n        };\n      }\n      return {};\n    }\n  };\n};\n\nconst originSides = /*#__PURE__*/new Set(['left', 'top']);\n\n// For type backwards-compatibility, the `OffsetOptions` type was also\n// Derivable.\n\nasync function convertValueToCoords(state, options) {\n  const {\n    placement,\n    platform,\n    elements\n  } = state;\n  const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n  const side = getSide(placement);\n  const alignment = getAlignment(placement);\n  const isVertical = getSideAxis(placement) === 'y';\n  const mainAxisMulti = originSides.has(side) ? -1 : 1;\n  const crossAxisMulti = rtl && isVertical ? -1 : 1;\n  const rawValue = evaluate(options, state);\n\n  // eslint-disable-next-line prefer-const\n  let {\n    mainAxis,\n    crossAxis,\n    alignmentAxis\n  } = typeof rawValue === 'number' ? {\n    mainAxis: rawValue,\n    crossAxis: 0,\n    alignmentAxis: null\n  } : {\n    mainAxis: rawValue.mainAxis || 0,\n    crossAxis: rawValue.crossAxis || 0,\n    alignmentAxis: rawValue.alignmentAxis\n  };\n  if (alignment && typeof alignmentAxis === 'number') {\n    crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis;\n  }\n  return isVertical ? {\n    x: crossAxis * crossAxisMulti,\n    y: mainAxis * mainAxisMulti\n  } : {\n    x: mainAxis * mainAxisMulti,\n    y: crossAxis * crossAxisMulti\n  };\n}\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = function (options) {\n  if (options === void 0) {\n    options = 0;\n  }\n  return {\n    name: 'offset',\n    options,\n    async fn(state) {\n      var _middlewareData$offse, _middlewareData$arrow;\n      const {\n        x,\n        y,\n        placement,\n        middlewareData\n      } = state;\n      const diffCoords = await convertValueToCoords(state, options);\n\n      // If the placement is the same and the arrow caused an alignment offset\n      // then we don't need to change the positioning coordinates.\n      if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n        return {};\n      }\n      return {\n        x: x + diffCoords.x,\n        y: y + diffCoords.y,\n        data: {\n          ...diffCoords,\n          placement\n        }\n      };\n    }\n  };\n};\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    name: 'shift',\n    options,\n    async fn(state) {\n      const {\n        x,\n        y,\n        placement,\n        platform\n      } = state;\n      const {\n        mainAxis: checkMainAxis = true,\n        crossAxis: checkCrossAxis = false,\n        limiter = {\n          fn: _ref => {\n            let {\n              x,\n              y\n            } = _ref;\n            return {\n              x,\n              y\n            };\n          }\n        },\n        ...detectOverflowOptions\n      } = evaluate(options, state);\n      const coords = {\n        x,\n        y\n      };\n      const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n      const crossAxis = getSideAxis(getSide(placement));\n      const mainAxis = getOppositeAxis(crossAxis);\n      let mainAxisCoord = coords[mainAxis];\n      let crossAxisCoord = coords[crossAxis];\n      if (checkMainAxis) {\n        const minSide = mainAxis === 'y' ? 'top' : 'left';\n        const maxSide = mainAxis === 'y' ? 'bottom' : 'right';\n        const min = mainAxisCoord + overflow[minSide];\n        const max = mainAxisCoord - overflow[maxSide];\n        mainAxisCoord = clamp(min, mainAxisCoord, max);\n      }\n      if (checkCrossAxis) {\n        const minSide = crossAxis === 'y' ? 'top' : 'left';\n        const maxSide = crossAxis === 'y' ? 'bottom' : 'right';\n        const min = crossAxisCoord + overflow[minSide];\n        const max = crossAxisCoord - overflow[maxSide];\n        crossAxisCoord = clamp(min, crossAxisCoord, max);\n      }\n      const limitedCoords = limiter.fn({\n        ...state,\n        [mainAxis]: mainAxisCoord,\n        [crossAxis]: crossAxisCoord\n      });\n      return {\n        ...limitedCoords,\n        data: {\n          x: limitedCoords.x - x,\n          y: limitedCoords.y - y,\n          enabled: {\n            [mainAxis]: checkMainAxis,\n            [crossAxis]: checkCrossAxis\n          }\n        }\n      };\n    }\n  };\n};\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    options,\n    fn(state) {\n      const {\n        x,\n        y,\n        placement,\n        rects,\n        middlewareData\n      } = state;\n      const {\n        offset = 0,\n        mainAxis: checkMainAxis = true,\n        crossAxis: checkCrossAxis = true\n      } = evaluate(options, state);\n      const coords = {\n        x,\n        y\n      };\n      const crossAxis = getSideAxis(placement);\n      const mainAxis = getOppositeAxis(crossAxis);\n      let mainAxisCoord = coords[mainAxis];\n      let crossAxisCoord = coords[crossAxis];\n      const rawOffset = evaluate(offset, state);\n      const computedOffset = typeof rawOffset === 'number' ? {\n        mainAxis: rawOffset,\n        crossAxis: 0\n      } : {\n        mainAxis: 0,\n        crossAxis: 0,\n        ...rawOffset\n      };\n      if (checkMainAxis) {\n        const len = mainAxis === 'y' ? 'height' : 'width';\n        const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;\n        const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;\n        if (mainAxisCoord < limitMin) {\n          mainAxisCoord = limitMin;\n        } else if (mainAxisCoord > limitMax) {\n          mainAxisCoord = limitMax;\n        }\n      }\n      if (checkCrossAxis) {\n        var _middlewareData$offse, _middlewareData$offse2;\n        const len = mainAxis === 'y' ? 'width' : 'height';\n        const isOriginSide = originSides.has(getSide(placement));\n        const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);\n        const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);\n        if (crossAxisCoord < limitMin) {\n          crossAxisCoord = limitMin;\n        } else if (crossAxisCoord > limitMax) {\n          crossAxisCoord = limitMax;\n        }\n      }\n      return {\n        [mainAxis]: mainAxisCoord,\n        [crossAxis]: crossAxisCoord\n      };\n    }\n  };\n};\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = function (options) {\n  if (options === void 0) {\n    options = {};\n  }\n  return {\n    name: 'size',\n    options,\n    async fn(state) {\n      var _state$middlewareData, _state$middlewareData2;\n      const {\n        placement,\n        rects,\n        platform,\n        elements\n      } = state;\n      const {\n        apply = () => {},\n        ...detectOverflowOptions\n      } = evaluate(options, state);\n      const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n      const side = getSide(placement);\n      const alignment = getAlignment(placement);\n      const isYAxis = getSideAxis(placement) === 'y';\n      const {\n        width,\n        height\n      } = rects.floating;\n      let heightSide;\n      let widthSide;\n      if (side === 'top' || side === 'bottom') {\n        heightSide = side;\n        widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right';\n      } else {\n        widthSide = side;\n        heightSide = alignment === 'end' ? 'top' : 'bottom';\n      }\n      const maximumClippingHeight = height - overflow.top - overflow.bottom;\n      const maximumClippingWidth = width - overflow.left - overflow.right;\n      const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight);\n      const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth);\n      const noShift = !state.middlewareData.shift;\n      let availableHeight = overflowAvailableHeight;\n      let availableWidth = overflowAvailableWidth;\n      if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) {\n        availableWidth = maximumClippingWidth;\n      }\n      if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) {\n        availableHeight = maximumClippingHeight;\n      }\n      if (noShift && !alignment) {\n        const xMin = max(overflow.left, 0);\n        const xMax = max(overflow.right, 0);\n        const yMin = max(overflow.top, 0);\n        const yMax = max(overflow.bottom, 0);\n        if (isYAxis) {\n          availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));\n        } else {\n          availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));\n        }\n      }\n      await apply({\n        ...state,\n        availableWidth,\n        availableHeight\n      });\n      const nextDimensions = await platform.getDimensions(elements.floating);\n      if (width !== nextDimensions.width || height !== nextDimensions.height) {\n        return {\n          reset: {\n            rects: true\n          }\n        };\n      }\n      return {};\n    }\n  };\n};\n\nexport { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, shift, size };\n","function hasWindow() {\n  return typeof window !== 'undefined';\n}\nfunction getNodeName(node) {\n  if (isNode(node)) {\n    return (node.nodeName || '').toLowerCase();\n  }\n  // Mocked nodes in testing environments may not be instances of Node. By\n  // returning `#document` an infinite loop won't occur.\n  // https://github.com/floating-ui/floating-ui/issues/2317\n  return '#document';\n}\nfunction getWindow(node) {\n  var _node$ownerDocument;\n  return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;\n}\nfunction getDocumentElement(node) {\n  var _ref;\n  return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;\n}\nfunction isNode(value) {\n  if (!hasWindow()) {\n    return false;\n  }\n  return value instanceof Node || value instanceof getWindow(value).Node;\n}\nfunction isElement(value) {\n  if (!hasWindow()) {\n    return false;\n  }\n  return value instanceof Element || value instanceof getWindow(value).Element;\n}\nfunction isHTMLElement(value) {\n  if (!hasWindow()) {\n    return false;\n  }\n  return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;\n}\nfunction isShadowRoot(value) {\n  if (!hasWindow() || typeof ShadowRoot === 'undefined') {\n    return false;\n  }\n  return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;\n}\nfunction isOverflowElement(element) {\n  const {\n    overflow,\n    overflowX,\n    overflowY,\n    display\n  } = getComputedStyle(element);\n  return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && display !== 'inline' && display !== 'contents';\n}\nfunction isTableElement(element) {\n  return /^(table|td|th)$/.test(getNodeName(element));\n}\nfunction isTopLayer(element) {\n  try {\n    if (element.matches(':popover-open')) {\n      return true;\n    }\n  } catch (_e) {\n    // no-op\n  }\n  try {\n    return element.matches(':modal');\n  } catch (_e) {\n    return false;\n  }\n}\nconst willChangeRe = /transform|translate|scale|rotate|perspective|filter/;\nconst containRe = /paint|layout|strict|content/;\nconst isNotNone = value => !!value && value !== 'none';\nlet isWebKitValue;\nfunction isContainingBlock(elementOrCss) {\n  const css = isElement(elementOrCss) ? getComputedStyle(elementOrCss) : elementOrCss;\n\n  // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n  // https://drafts.csswg.org/css-transforms-2/#individual-transforms\n  return isNotNone(css.transform) || isNotNone(css.translate) || isNotNone(css.scale) || isNotNone(css.rotate) || isNotNone(css.perspective) || !isWebKit() && (isNotNone(css.backdropFilter) || isNotNone(css.filter)) || willChangeRe.test(css.willChange || '') || containRe.test(css.contain || '');\n}\nfunction getContainingBlock(element) {\n  let currentNode = getParentNode(element);\n  while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {\n    if (isContainingBlock(currentNode)) {\n      return currentNode;\n    } else if (isTopLayer(currentNode)) {\n      return null;\n    }\n    currentNode = getParentNode(currentNode);\n  }\n  return null;\n}\nfunction isWebKit() {\n  if (isWebKitValue == null) {\n    isWebKitValue = typeof CSS !== 'undefined' && CSS.supports && CSS.supports('-webkit-backdrop-filter', 'none');\n  }\n  return isWebKitValue;\n}\nfunction isLastTraversableNode(node) {\n  return /^(html|body|#document)$/.test(getNodeName(node));\n}\nfunction getComputedStyle(element) {\n  return getWindow(element).getComputedStyle(element);\n}\nfunction getNodeScroll(element) {\n  if (isElement(element)) {\n    return {\n      scrollLeft: element.scrollLeft,\n      scrollTop: element.scrollTop\n    };\n  }\n  return {\n    scrollLeft: element.scrollX,\n    scrollTop: element.scrollY\n  };\n}\nfunction getParentNode(node) {\n  if (getNodeName(node) === 'html') {\n    return node;\n  }\n  const result =\n  // Step into the shadow DOM of the parent of a slotted node.\n  node.assignedSlot ||\n  // DOM Element detected.\n  node.parentNode ||\n  // ShadowRoot detected.\n  isShadowRoot(node) && node.host ||\n  // Fallback.\n  getDocumentElement(node);\n  return isShadowRoot(result) ? result.host : result;\n}\nfunction getNearestOverflowAncestor(node) {\n  const parentNode = getParentNode(node);\n  if (isLastTraversableNode(parentNode)) {\n    return node.ownerDocument ? node.ownerDocument.body : node.body;\n  }\n  if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {\n    return parentNode;\n  }\n  return getNearestOverflowAncestor(parentNode);\n}\nfunction getOverflowAncestors(node, list, traverseIframes) {\n  var _node$ownerDocument2;\n  if (list === void 0) {\n    list = [];\n  }\n  if (traverseIframes === void 0) {\n    traverseIframes = true;\n  }\n  const scrollableAncestor = getNearestOverflowAncestor(node);\n  const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);\n  const win = getWindow(scrollableAncestor);\n  if (isBody) {\n    const frameElement = getFrameElement(win);\n    return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);\n  } else {\n    return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));\n  }\n}\nfunction getFrameElement(win) {\n  return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;\n}\n\nexport { getComputedStyle, getContainingBlock, getDocumentElement, getFrameElement, getNearestOverflowAncestor, getNodeName, getNodeScroll, getOverflowAncestors, getParentNode, getWindow, isContainingBlock, isElement, isHTMLElement, isLastTraversableNode, isNode, isOverflowElement, isShadowRoot, isTableElement, isTopLayer, isWebKit };\n","import { rectToClientRect, arrow as arrow$1, autoPlacement as autoPlacement$1, detectOverflow as detectOverflow$1, flip as flip$1, hide as hide$1, inline as inline$1, limitShift as limitShift$1, offset as offset$1, shift as shift$1, size as size$1, computePosition as computePosition$1 } from '@floating-ui/core';\nimport { round, createCoords, max, min, floor } from '@floating-ui/utils';\nimport { getComputedStyle as getComputedStyle$1, isHTMLElement, isElement, getWindow, isWebKit, getFrameElement, getNodeScroll, getDocumentElement, isTopLayer, getNodeName, isOverflowElement, getOverflowAncestors, getParentNode, isLastTraversableNode, isContainingBlock, isTableElement, getContainingBlock } from '@floating-ui/utils/dom';\nexport { getOverflowAncestors } from '@floating-ui/utils/dom';\n\nfunction getCssDimensions(element) {\n  const css = getComputedStyle$1(element);\n  // In testing environments, the `width` and `height` properties are empty\n  // strings for SVG elements, returning NaN. Fallback to `0` in this case.\n  let width = parseFloat(css.width) || 0;\n  let height = parseFloat(css.height) || 0;\n  const hasOffset = isHTMLElement(element);\n  const offsetWidth = hasOffset ? element.offsetWidth : width;\n  const offsetHeight = hasOffset ? element.offsetHeight : height;\n  const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;\n  if (shouldFallback) {\n    width = offsetWidth;\n    height = offsetHeight;\n  }\n  return {\n    width,\n    height,\n    $: shouldFallback\n  };\n}\n\nfunction unwrapElement(element) {\n  return !isElement(element) ? element.contextElement : element;\n}\n\nfunction getScale(element) {\n  const domElement = unwrapElement(element);\n  if (!isHTMLElement(domElement)) {\n    return createCoords(1);\n  }\n  const rect = domElement.getBoundingClientRect();\n  const {\n    width,\n    height,\n    $\n  } = getCssDimensions(domElement);\n  let x = ($ ? round(rect.width) : rect.width) / width;\n  let y = ($ ? round(rect.height) : rect.height) / height;\n\n  // 0, NaN, or Infinity should always fallback to 1.\n\n  if (!x || !Number.isFinite(x)) {\n    x = 1;\n  }\n  if (!y || !Number.isFinite(y)) {\n    y = 1;\n  }\n  return {\n    x,\n    y\n  };\n}\n\nconst noOffsets = /*#__PURE__*/createCoords(0);\nfunction getVisualOffsets(element) {\n  const win = getWindow(element);\n  if (!isWebKit() || !win.visualViewport) {\n    return noOffsets;\n  }\n  return {\n    x: win.visualViewport.offsetLeft,\n    y: win.visualViewport.offsetTop\n  };\n}\nfunction shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {\n  if (isFixed === void 0) {\n    isFixed = false;\n  }\n  if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {\n    return false;\n  }\n  return isFixed;\n}\n\nfunction getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {\n  if (includeScale === void 0) {\n    includeScale = false;\n  }\n  if (isFixedStrategy === void 0) {\n    isFixedStrategy = false;\n  }\n  const clientRect = element.getBoundingClientRect();\n  const domElement = unwrapElement(element);\n  let scale = createCoords(1);\n  if (includeScale) {\n    if (offsetParent) {\n      if (isElement(offsetParent)) {\n        scale = getScale(offsetParent);\n      }\n    } else {\n      scale = getScale(element);\n    }\n  }\n  const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);\n  let x = (clientRect.left + visualOffsets.x) / scale.x;\n  let y = (clientRect.top + visualOffsets.y) / scale.y;\n  let width = clientRect.width / scale.x;\n  let height = clientRect.height / scale.y;\n  if (domElement) {\n    const win = getWindow(domElement);\n    const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;\n    let currentWin = win;\n    let currentIFrame = getFrameElement(currentWin);\n    while (currentIFrame && offsetParent && offsetWin !== currentWin) {\n      const iframeScale = getScale(currentIFrame);\n      const iframeRect = currentIFrame.getBoundingClientRect();\n      const css = getComputedStyle$1(currentIFrame);\n      const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;\n      const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;\n      x *= iframeScale.x;\n      y *= iframeScale.y;\n      width *= iframeScale.x;\n      height *= iframeScale.y;\n      x += left;\n      y += top;\n      currentWin = getWindow(currentIFrame);\n      currentIFrame = getFrameElement(currentWin);\n    }\n  }\n  return rectToClientRect({\n    width,\n    height,\n    x,\n    y\n  });\n}\n\n// If <html> has a CSS width greater than the viewport, then this will be\n// incorrect for RTL.\nfunction getWindowScrollBarX(element, rect) {\n  const leftScroll = getNodeScroll(element).scrollLeft;\n  if (!rect) {\n    return getBoundingClientRect(getDocumentElement(element)).left + leftScroll;\n  }\n  return rect.left + leftScroll;\n}\n\nfunction getHTMLOffset(documentElement, scroll) {\n  const htmlRect = documentElement.getBoundingClientRect();\n  const x = htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect);\n  const y = htmlRect.top + scroll.scrollTop;\n  return {\n    x,\n    y\n  };\n}\n\nfunction convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {\n  let {\n    elements,\n    rect,\n    offsetParent,\n    strategy\n  } = _ref;\n  const isFixed = strategy === 'fixed';\n  const documentElement = getDocumentElement(offsetParent);\n  const topLayer = elements ? isTopLayer(elements.floating) : false;\n  if (offsetParent === documentElement || topLayer && isFixed) {\n    return rect;\n  }\n  let scroll = {\n    scrollLeft: 0,\n    scrollTop: 0\n  };\n  let scale = createCoords(1);\n  const offsets = createCoords(0);\n  const isOffsetParentAnElement = isHTMLElement(offsetParent);\n  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n    if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n      scroll = getNodeScroll(offsetParent);\n    }\n    if (isOffsetParentAnElement) {\n      const offsetRect = getBoundingClientRect(offsetParent);\n      scale = getScale(offsetParent);\n      offsets.x = offsetRect.x + offsetParent.clientLeft;\n      offsets.y = offsetRect.y + offsetParent.clientTop;\n    }\n  }\n  const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);\n  return {\n    width: rect.width * scale.x,\n    height: rect.height * scale.y,\n    x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,\n    y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y\n  };\n}\n\nfunction getClientRects(element) {\n  return Array.from(element.getClientRects());\n}\n\n// Gets the entire size of the scrollable document area, even extending outside\n// of the `<html>` and `<body>` rect bounds if horizontally scrollable.\nfunction getDocumentRect(element) {\n  const html = getDocumentElement(element);\n  const scroll = getNodeScroll(element);\n  const body = element.ownerDocument.body;\n  const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);\n  const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);\n  let x = -scroll.scrollLeft + getWindowScrollBarX(element);\n  const y = -scroll.scrollTop;\n  if (getComputedStyle$1(body).direction === 'rtl') {\n    x += max(html.clientWidth, body.clientWidth) - width;\n  }\n  return {\n    width,\n    height,\n    x,\n    y\n  };\n}\n\n// Safety check: ensure the scrollbar space is reasonable in case this\n// calculation is affected by unusual styles.\n// Most scrollbars leave 15-18px of space.\nconst SCROLLBAR_MAX = 25;\nfunction getViewportRect(element, strategy) {\n  const win = getWindow(element);\n  const html = getDocumentElement(element);\n  const visualViewport = win.visualViewport;\n  let width = html.clientWidth;\n  let height = html.clientHeight;\n  let x = 0;\n  let y = 0;\n  if (visualViewport) {\n    width = visualViewport.width;\n    height = visualViewport.height;\n    const visualViewportBased = isWebKit();\n    if (!visualViewportBased || visualViewportBased && strategy === 'fixed') {\n      x = visualViewport.offsetLeft;\n      y = visualViewport.offsetTop;\n    }\n  }\n  const windowScrollbarX = getWindowScrollBarX(html);\n  // <html> `overflow: hidden` + `scrollbar-gutter: stable` reduces the\n  // visual width of the <html> but this is not considered in the size\n  // of `html.clientWidth`.\n  if (windowScrollbarX <= 0) {\n    const doc = html.ownerDocument;\n    const body = doc.body;\n    const bodyStyles = getComputedStyle(body);\n    const bodyMarginInline = doc.compatMode === 'CSS1Compat' ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0;\n    const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline);\n    if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) {\n      width -= clippingStableScrollbarWidth;\n    }\n  } else if (windowScrollbarX <= SCROLLBAR_MAX) {\n    // If the <body> scrollbar is on the left, the width needs to be extended\n    // by the scrollbar amount so there isn't extra space on the right.\n    width += windowScrollbarX;\n  }\n  return {\n    width,\n    height,\n    x,\n    y\n  };\n}\n\n// Returns the inner client rect, subtracting scrollbars if present.\nfunction getInnerBoundingClientRect(element, strategy) {\n  const clientRect = getBoundingClientRect(element, true, strategy === 'fixed');\n  const top = clientRect.top + element.clientTop;\n  const left = clientRect.left + element.clientLeft;\n  const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);\n  const width = element.clientWidth * scale.x;\n  const height = element.clientHeight * scale.y;\n  const x = left * scale.x;\n  const y = top * scale.y;\n  return {\n    width,\n    height,\n    x,\n    y\n  };\n}\nfunction getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {\n  let rect;\n  if (clippingAncestor === 'viewport') {\n    rect = getViewportRect(element, strategy);\n  } else if (clippingAncestor === 'document') {\n    rect = getDocumentRect(getDocumentElement(element));\n  } else if (isElement(clippingAncestor)) {\n    rect = getInnerBoundingClientRect(clippingAncestor, strategy);\n  } else {\n    const visualOffsets = getVisualOffsets(element);\n    rect = {\n      x: clippingAncestor.x - visualOffsets.x,\n      y: clippingAncestor.y - visualOffsets.y,\n      width: clippingAncestor.width,\n      height: clippingAncestor.height\n    };\n  }\n  return rectToClientRect(rect);\n}\nfunction hasFixedPositionAncestor(element, stopNode) {\n  const parentNode = getParentNode(element);\n  if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {\n    return false;\n  }\n  return getComputedStyle$1(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode);\n}\n\n// A \"clipping ancestor\" is an `overflow` element with the characteristic of\n// clipping (or hiding) child elements. This returns all clipping ancestors\n// of the given element up the tree.\nfunction getClippingElementAncestors(element, cache) {\n  const cachedResult = cache.get(element);\n  if (cachedResult) {\n    return cachedResult;\n  }\n  let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body');\n  let currentContainingBlockComputedStyle = null;\n  const elementIsFixed = getComputedStyle$1(element).position === 'fixed';\n  let currentNode = elementIsFixed ? getParentNode(element) : element;\n\n  // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n  while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {\n    const computedStyle = getComputedStyle$1(currentNode);\n    const currentNodeIsContaining = isContainingBlock(currentNode);\n    if (!currentNodeIsContaining && computedStyle.position === 'fixed') {\n      currentContainingBlockComputedStyle = null;\n    }\n    const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && (currentContainingBlockComputedStyle.position === 'absolute' || currentContainingBlockComputedStyle.position === 'fixed') || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);\n    if (shouldDropCurrentNode) {\n      // Drop non-containing blocks.\n      result = result.filter(ancestor => ancestor !== currentNode);\n    } else {\n      // Record last containing block for next iteration.\n      currentContainingBlockComputedStyle = computedStyle;\n    }\n    currentNode = getParentNode(currentNode);\n  }\n  cache.set(element, result);\n  return result;\n}\n\n// Gets the maximum area that the element is visible in due to any number of\n// clipping ancestors.\nfunction getClippingRect(_ref) {\n  let {\n    element,\n    boundary,\n    rootBoundary,\n    strategy\n  } = _ref;\n  const elementClippingAncestors = boundary === 'clippingAncestors' ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);\n  const clippingAncestors = [...elementClippingAncestors, rootBoundary];\n  const firstRect = getClientRectFromClippingAncestor(element, clippingAncestors[0], strategy);\n  let top = firstRect.top;\n  let right = firstRect.right;\n  let bottom = firstRect.bottom;\n  let left = firstRect.left;\n  for (let i = 1; i < clippingAncestors.length; i++) {\n    const rect = getClientRectFromClippingAncestor(element, clippingAncestors[i], strategy);\n    top = max(rect.top, top);\n    right = min(rect.right, right);\n    bottom = min(rect.bottom, bottom);\n    left = max(rect.left, left);\n  }\n  return {\n    width: right - left,\n    height: bottom - top,\n    x: left,\n    y: top\n  };\n}\n\nfunction getDimensions(element) {\n  const {\n    width,\n    height\n  } = getCssDimensions(element);\n  return {\n    width,\n    height\n  };\n}\n\nfunction getRectRelativeToOffsetParent(element, offsetParent, strategy) {\n  const isOffsetParentAnElement = isHTMLElement(offsetParent);\n  const documentElement = getDocumentElement(offsetParent);\n  const isFixed = strategy === 'fixed';\n  const rect = getBoundingClientRect(element, true, isFixed, offsetParent);\n  let scroll = {\n    scrollLeft: 0,\n    scrollTop: 0\n  };\n  const offsets = createCoords(0);\n\n  // If the <body> scrollbar appears on the left (e.g. RTL systems). Use\n  // Firefox with layout.scrollbar.side = 3 in about:config to test this.\n  function setLeftRTLScrollbarOffset() {\n    offsets.x = getWindowScrollBarX(documentElement);\n  }\n  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n    if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n      scroll = getNodeScroll(offsetParent);\n    }\n    if (isOffsetParentAnElement) {\n      const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);\n      offsets.x = offsetRect.x + offsetParent.clientLeft;\n      offsets.y = offsetRect.y + offsetParent.clientTop;\n    } else if (documentElement) {\n      setLeftRTLScrollbarOffset();\n    }\n  }\n  if (isFixed && !isOffsetParentAnElement && documentElement) {\n    setLeftRTLScrollbarOffset();\n  }\n  const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);\n  const x = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x;\n  const y = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;\n  return {\n    x,\n    y,\n    width: rect.width,\n    height: rect.height\n  };\n}\n\nfunction isStaticPositioned(element) {\n  return getComputedStyle$1(element).position === 'static';\n}\n\nfunction getTrueOffsetParent(element, polyfill) {\n  if (!isHTMLElement(element) || getComputedStyle$1(element).position === 'fixed') {\n    return null;\n  }\n  if (polyfill) {\n    return polyfill(element);\n  }\n  let rawOffsetParent = element.offsetParent;\n\n  // Firefox returns the <html> element as the offsetParent if it's non-static,\n  // while Chrome and Safari return the <body> element. The <body> element must\n  // be used to perform the correct calculations even if the <html> element is\n  // non-static.\n  if (getDocumentElement(element) === rawOffsetParent) {\n    rawOffsetParent = rawOffsetParent.ownerDocument.body;\n  }\n  return rawOffsetParent;\n}\n\n// Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\nfunction getOffsetParent(element, polyfill) {\n  const win = getWindow(element);\n  if (isTopLayer(element)) {\n    return win;\n  }\n  if (!isHTMLElement(element)) {\n    let svgOffsetParent = getParentNode(element);\n    while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {\n      if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {\n        return svgOffsetParent;\n      }\n      svgOffsetParent = getParentNode(svgOffsetParent);\n    }\n    return win;\n  }\n  let offsetParent = getTrueOffsetParent(element, polyfill);\n  while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {\n    offsetParent = getTrueOffsetParent(offsetParent, polyfill);\n  }\n  if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {\n    return win;\n  }\n  return offsetParent || getContainingBlock(element) || win;\n}\n\nconst getElementRects = async function (data) {\n  const getOffsetParentFn = this.getOffsetParent || getOffsetParent;\n  const getDimensionsFn = this.getDimensions;\n  const floatingDimensions = await getDimensionsFn(data.floating);\n  return {\n    reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),\n    floating: {\n      x: 0,\n      y: 0,\n      width: floatingDimensions.width,\n      height: floatingDimensions.height\n    }\n  };\n};\n\nfunction isRTL(element) {\n  return getComputedStyle$1(element).direction === 'rtl';\n}\n\nconst platform = {\n  convertOffsetParentRelativeRectToViewportRelativeRect,\n  getDocumentElement,\n  getClippingRect,\n  getOffsetParent,\n  getElementRects,\n  getClientRects,\n  getDimensions,\n  getScale,\n  isElement,\n  isRTL\n};\n\nfunction rectsAreEqual(a, b) {\n  return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;\n}\n\n// https://samthor.au/2021/observing-dom/\nfunction observeMove(element, onMove) {\n  let io = null;\n  let timeoutId;\n  const root = getDocumentElement(element);\n  function cleanup() {\n    var _io;\n    clearTimeout(timeoutId);\n    (_io = io) == null || _io.disconnect();\n    io = null;\n  }\n  function refresh(skip, threshold) {\n    if (skip === void 0) {\n      skip = false;\n    }\n    if (threshold === void 0) {\n      threshold = 1;\n    }\n    cleanup();\n    const elementRectForRootMargin = element.getBoundingClientRect();\n    const {\n      left,\n      top,\n      width,\n      height\n    } = elementRectForRootMargin;\n    if (!skip) {\n      onMove();\n    }\n    if (!width || !height) {\n      return;\n    }\n    const insetTop = floor(top);\n    const insetRight = floor(root.clientWidth - (left + width));\n    const insetBottom = floor(root.clientHeight - (top + height));\n    const insetLeft = floor(left);\n    const rootMargin = -insetTop + \"px \" + -insetRight + \"px \" + -insetBottom + \"px \" + -insetLeft + \"px\";\n    const options = {\n      rootMargin,\n      threshold: max(0, min(1, threshold)) || 1\n    };\n    let isFirstUpdate = true;\n    function handleObserve(entries) {\n      const ratio = entries[0].intersectionRatio;\n      if (ratio !== threshold) {\n        if (!isFirstUpdate) {\n          return refresh();\n        }\n        if (!ratio) {\n          // If the reference is clipped, the ratio is 0. Throttle the refresh\n          // to prevent an infinite loop of updates.\n          timeoutId = setTimeout(() => {\n            refresh(false, 1e-7);\n          }, 1000);\n        } else {\n          refresh(false, ratio);\n        }\n      }\n      if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) {\n        // It's possible that even though the ratio is reported as 1, the\n        // element is not actually fully within the IntersectionObserver's root\n        // area anymore. This can happen under performance constraints. This may\n        // be a bug in the browser's IntersectionObserver implementation. To\n        // work around this, we compare the element's bounding rect now with\n        // what it was at the time we created the IntersectionObserver. If they\n        // are not equal then the element moved, so we refresh.\n        refresh();\n      }\n      isFirstUpdate = false;\n    }\n\n    // Older browsers don't support a `document` as the root and will throw an\n    // error.\n    try {\n      io = new IntersectionObserver(handleObserve, {\n        ...options,\n        // Handle <iframe>s\n        root: root.ownerDocument\n      });\n    } catch (_e) {\n      io = new IntersectionObserver(handleObserve, options);\n    }\n    io.observe(element);\n  }\n  refresh(true);\n  return cleanup;\n}\n\n/**\n * Automatically updates the position of the floating element when necessary.\n * Should only be called when the floating element is mounted on the DOM or\n * visible on the screen.\n * @returns cleanup function that should be invoked when the floating element is\n * removed from the DOM or hidden from the screen.\n * @see https://floating-ui.com/docs/autoUpdate\n */\nfunction autoUpdate(reference, floating, update, options) {\n  if (options === void 0) {\n    options = {};\n  }\n  const {\n    ancestorScroll = true,\n    ancestorResize = true,\n    elementResize = typeof ResizeObserver === 'function',\n    layoutShift = typeof IntersectionObserver === 'function',\n    animationFrame = false\n  } = options;\n  const referenceEl = unwrapElement(reference);\n  const ancestors = ancestorScroll || ancestorResize ? [...(referenceEl ? getOverflowAncestors(referenceEl) : []), ...(floating ? getOverflowAncestors(floating) : [])] : [];\n  ancestors.forEach(ancestor => {\n    ancestorScroll && ancestor.addEventListener('scroll', update, {\n      passive: true\n    });\n    ancestorResize && ancestor.addEventListener('resize', update);\n  });\n  const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null;\n  let reobserveFrame = -1;\n  let resizeObserver = null;\n  if (elementResize) {\n    resizeObserver = new ResizeObserver(_ref => {\n      let [firstEntry] = _ref;\n      if (firstEntry && firstEntry.target === referenceEl && resizeObserver && floating) {\n        // Prevent update loops when using the `size` middleware.\n        // https://github.com/floating-ui/floating-ui/issues/1740\n        resizeObserver.unobserve(floating);\n        cancelAnimationFrame(reobserveFrame);\n        reobserveFrame = requestAnimationFrame(() => {\n          var _resizeObserver;\n          (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);\n        });\n      }\n      update();\n    });\n    if (referenceEl && !animationFrame) {\n      resizeObserver.observe(referenceEl);\n    }\n    if (floating) {\n      resizeObserver.observe(floating);\n    }\n  }\n  let frameId;\n  let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;\n  if (animationFrame) {\n    frameLoop();\n  }\n  function frameLoop() {\n    const nextRefRect = getBoundingClientRect(reference);\n    if (prevRefRect && !rectsAreEqual(prevRefRect, nextRefRect)) {\n      update();\n    }\n    prevRefRect = nextRefRect;\n    frameId = requestAnimationFrame(frameLoop);\n  }\n  update();\n  return () => {\n    var _resizeObserver2;\n    ancestors.forEach(ancestor => {\n      ancestorScroll && ancestor.removeEventListener('scroll', update);\n      ancestorResize && ancestor.removeEventListener('resize', update);\n    });\n    cleanupIo == null || cleanupIo();\n    (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();\n    resizeObserver = null;\n    if (animationFrame) {\n      cancelAnimationFrame(frameId);\n    }\n  };\n}\n\n/**\n * Resolves with an object of overflow side offsets that determine how much the\n * element is overflowing a given clipping boundary on each side.\n * - positive = overflowing the boundary by that number of pixels\n * - negative = how many pixels left before it will overflow\n * - 0 = lies flush with the boundary\n * @see https://floating-ui.com/docs/detectOverflow\n */\nconst detectOverflow = detectOverflow$1;\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = offset$1;\n\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = autoPlacement$1;\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = shift$1;\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = flip$1;\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = size$1;\n\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = hide$1;\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = arrow$1;\n\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = inline$1;\n\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = limitShift$1;\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element\n * next to a given reference element.\n */\nconst computePosition = (reference, floating, options) => {\n  // This caches the expensive `getClippingElementAncestors` function so that\n  // multiple lifecycle resets re-use the same result. It only lives for a\n  // single call. If other functions become expensive, we can add them as well.\n  const cache = new Map();\n  const mergedOptions = {\n    platform,\n    ...options\n  };\n  const platformWithCache = {\n    ...mergedOptions.platform,\n    _c: cache\n  };\n  return computePosition$1(reference, floating, {\n    ...mergedOptions,\n    platform: platformWithCache\n  });\n};\n\nexport { arrow, autoPlacement, autoUpdate, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, platform, shift, size };\n","var Vue = require('vue')\n\nObject.keys(Vue).forEach(function(key) {\n  exports[key] = Vue[key]\n})\n\nexports.set = function(target, key, val) {\n  if (Array.isArray(target)) {\n    target.length = Math.max(target.length, key)\n    target.splice(key, 1, val)\n    return val\n  }\n  target[key] = val\n  return val\n}\n\nexports.del = function(target, key) {\n  if (Array.isArray(target)) {\n    target.splice(key, 1)\n    return\n  }\n  delete target[key]\n}\n\nexports.Vue = Vue\nexports.Vue2 = undefined\nexports.isVue2 = false\nexports.isVue3 = true\nexports.install = function(){}\n","import { arrow as arrow$1, computePosition } from '@floating-ui/dom';\nexport { autoPlacement, autoUpdate, computePosition, detectOverflow, flip, getOverflowAncestors, hide, inline, limitShift, offset, platform, shift, size } from '@floating-ui/dom';\nimport { isNode, getNodeName } from '@floating-ui/utils/dom';\nimport { unref, computed, ref, shallowRef, watch, getCurrentScope, onScopeDispose, shallowReadonly } from 'vue-demi';\n\nfunction isComponentPublicInstance(target) {\n  return target != null && typeof target === 'object' && '$el' in target;\n}\nfunction unwrapElement(target) {\n  if (isComponentPublicInstance(target)) {\n    const element = target.$el;\n    return isNode(element) && getNodeName(element) === '#comment' ? null : element;\n  }\n  return target;\n}\n\nfunction toValue(source) {\n  return typeof source === 'function' ? source() : unref(source);\n}\n\n/**\n * Positions an inner element of the floating element such that it is centered to the reference element.\n * @param options The arrow options.\n * @see https://floating-ui.com/docs/arrow\n */\nfunction arrow(options) {\n  return {\n    name: 'arrow',\n    options,\n    fn(args) {\n      const element = unwrapElement(toValue(options.element));\n      if (element == null) {\n        return {};\n      }\n      return arrow$1({\n        element,\n        padding: options.padding\n      }).fn(args);\n    }\n  };\n}\n\nfunction getDPR(element) {\n  if (typeof window === 'undefined') {\n    return 1;\n  }\n  const win = element.ownerDocument.defaultView || window;\n  return win.devicePixelRatio || 1;\n}\n\nfunction roundByDPR(element, value) {\n  const dpr = getDPR(element);\n  return Math.round(value * dpr) / dpr;\n}\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element next to a reference element when it is given a certain CSS positioning strategy.\n * @param reference The reference template ref.\n * @param floating The floating template ref.\n * @param options The floating options.\n * @see https://floating-ui.com/docs/vue\n */\nfunction useFloating(reference, floating, options) {\n  if (options === void 0) {\n    options = {};\n  }\n  const whileElementsMountedOption = options.whileElementsMounted;\n  const openOption = computed(() => {\n    var _toValue;\n    return (_toValue = toValue(options.open)) != null ? _toValue : true;\n  });\n  const middlewareOption = computed(() => toValue(options.middleware));\n  const placementOption = computed(() => {\n    var _toValue2;\n    return (_toValue2 = toValue(options.placement)) != null ? _toValue2 : 'bottom';\n  });\n  const strategyOption = computed(() => {\n    var _toValue3;\n    return (_toValue3 = toValue(options.strategy)) != null ? _toValue3 : 'absolute';\n  });\n  const transformOption = computed(() => {\n    var _toValue4;\n    return (_toValue4 = toValue(options.transform)) != null ? _toValue4 : true;\n  });\n  const referenceElement = computed(() => unwrapElement(reference.value));\n  const floatingElement = computed(() => unwrapElement(floating.value));\n  const x = ref(0);\n  const y = ref(0);\n  const strategy = ref(strategyOption.value);\n  const placement = ref(placementOption.value);\n  const middlewareData = shallowRef({});\n  const isPositioned = ref(false);\n  const floatingStyles = computed(() => {\n    const initialStyles = {\n      position: strategy.value,\n      left: '0',\n      top: '0'\n    };\n    if (!floatingElement.value) {\n      return initialStyles;\n    }\n    const xVal = roundByDPR(floatingElement.value, x.value);\n    const yVal = roundByDPR(floatingElement.value, y.value);\n    if (transformOption.value) {\n      return {\n        ...initialStyles,\n        transform: \"translate(\" + xVal + \"px, \" + yVal + \"px)\",\n        ...(getDPR(floatingElement.value) >= 1.5 && {\n          willChange: 'transform'\n        })\n      };\n    }\n    return {\n      position: strategy.value,\n      left: xVal + \"px\",\n      top: yVal + \"px\"\n    };\n  });\n  let whileElementsMountedCleanup;\n  function update() {\n    if (referenceElement.value == null || floatingElement.value == null) {\n      return;\n    }\n    const open = openOption.value;\n    computePosition(referenceElement.value, floatingElement.value, {\n      middleware: middlewareOption.value,\n      placement: placementOption.value,\n      strategy: strategyOption.value\n    }).then(position => {\n      x.value = position.x;\n      y.value = position.y;\n      strategy.value = position.strategy;\n      placement.value = position.placement;\n      middlewareData.value = position.middlewareData;\n      /**\n       * The floating element's position may be recomputed while it's closed\n       * but still mounted (such as when transitioning out). To ensure\n       * `isPositioned` will be `false` initially on the next open, avoid\n       * setting it to `true` when `open === false` (must be specified).\n       */\n      isPositioned.value = open !== false;\n    });\n  }\n  function cleanup() {\n    if (typeof whileElementsMountedCleanup === 'function') {\n      whileElementsMountedCleanup();\n      whileElementsMountedCleanup = undefined;\n    }\n  }\n  function attach() {\n    cleanup();\n    if (whileElementsMountedOption === undefined) {\n      update();\n      return;\n    }\n    if (referenceElement.value != null && floatingElement.value != null) {\n      whileElementsMountedCleanup = whileElementsMountedOption(referenceElement.value, floatingElement.value, update);\n      return;\n    }\n  }\n  function reset() {\n    if (!openOption.value) {\n      isPositioned.value = false;\n    }\n  }\n  watch([middlewareOption, placementOption, strategyOption, openOption], update, {\n    flush: 'sync'\n  });\n  watch([referenceElement, floatingElement], attach, {\n    flush: 'sync'\n  });\n  watch(openOption, reset, {\n    flush: 'sync'\n  });\n  if (getCurrentScope()) {\n    onScopeDispose(cleanup);\n  }\n  return {\n    x: shallowReadonly(x),\n    y: shallowReadonly(y),\n    strategy: shallowReadonly(strategy),\n    placement: shallowReadonly(placement),\n    middlewareData: shallowReadonly(middlewareData),\n    isPositioned: shallowReadonly(isPositioned),\n    floatingStyles,\n    update\n  };\n}\n\nexport { arrow, useFloating };\n","<script lang=\"ts\">\nimport type {\n  Middleware,\n  Placement,\n  ReferenceElement,\n} from '@floating-ui/vue'\nimport type { Ref } from 'vue'\nimport type {\n  Align,\n  Side,\n} from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useForwardExpose, useSize } from '@/shared'\n\nexport const PopperContentPropsDefaultValue = {\n  side: 'bottom' as Side,\n  sideOffset: 0,\n  sideFlip: true,\n  align: 'center' as Align,\n  alignOffset: 0,\n  alignFlip: true,\n  arrowPadding: 0,\n  hideShiftedArrow: true,\n  avoidCollisions: true,\n  collisionBoundary: () => [],\n  collisionPadding: 0,\n  sticky: 'partial' as 'partial' | 'always',\n  hideWhenDetached: false,\n  positionStrategy: 'fixed' as 'absolute' | 'fixed',\n  updatePositionStrategy: 'optimized' as 'optimized' | 'always',\n  prioritizePosition: false,\n}\n\nexport interface PopperContentProps extends PrimitiveProps {\n  /**\n   * The preferred side of the trigger to render against when open.\n   * Will be reversed when collisions occur and avoidCollisions\n   * is enabled.\n   *\n   * @defaultValue \"bottom\"\n   */\n  side?: Side\n\n  /**\n   * The distance in pixels from the trigger.\n   *\n   * @defaultValue 0\n   */\n  sideOffset?: number\n\n  /**\n   * Flip to the opposite side when colliding with boundary.\n   *\n   * @defaultValue true\n   */\n  sideFlip?: boolean\n\n  /**\n   * The preferred alignment against the trigger.\n   * May change when collisions occur.\n   *\n   * @defaultValue \"center\"\n   */\n  align?: Align\n\n  /**\n   * An offset in pixels from the `start` or `end` alignment options.\n   *\n   * @defaultValue 0\n   */\n  alignOffset?: number\n\n  /**\n   * Flip alignment when colliding with boundary.\n   * May only occur when `prioritizePosition` is true.\n   *\n   * @defaultValue true\n   */\n  alignFlip?: boolean\n\n  /**\n   * When `true`, overrides the side and align preferences\n   * to prevent collisions with boundary edges.\n   *\n   * @defaultValue true\n   */\n  avoidCollisions?: boolean\n\n  /**\n   * The element used as the collision boundary. By default\n   * this is the viewport, though you can provide additional\n   * element(s) to be included in this check.\n   *\n   * @defaultValue []\n   */\n  collisionBoundary?: Element | null | Array<Element | null>\n\n  /**\n   * The distance in pixels from the boundary edges where collision\n   * detection should occur. Accepts a number (same for all sides),\n   * or a partial padding object, for example: { top: 20, left: 20 }.\n   *\n   * @defaultValue 0\n   */\n  collisionPadding?: number | Partial<Record<Side, number>>\n\n  /**\n   * The padding between the arrow and the edges of the content.\n   * If your content has border-radius, this will prevent it from\n   * overflowing the corners.\n   *\n   * @defaultValue 0\n   */\n  arrowPadding?: number\n\n  /**\n   * When `true`, hides the arrow when it cannot be centered\n   * to the reference element.\n   *\n   * @defaultValue true\n   */\n  hideShiftedArrow?: boolean\n\n  /**\n   * The sticky behavior on the align axis. `partial` will keep the\n   * content in the boundary as long as the trigger is at least partially\n   * in the boundary whilst \"always\" will keep the content in the boundary\n   * regardless.\n   *\n   * @defaultValue \"partial\"\n   */\n  sticky?: 'partial' | 'always'\n\n  /**\n   * Whether to hide the content when the trigger becomes fully occluded.\n   *\n   * @defaultValue false\n   */\n  hideWhenDetached?: boolean\n\n  /**\n   *  The type of CSS position property to use.\n   */\n  positionStrategy?: 'absolute' | 'fixed'\n\n  /**\n   * Strategy to update the position of the floating element on every animation frame.\n   *\n   * @defaultValue 'optimized'\n   */\n  updatePositionStrategy?: 'optimized' | 'always'\n\n  /**\n   * Whether to disable the update position for the content when the layout shifted.\n   *\n   * @defaultValue false\n   */\n  disableUpdateOnLayoutShift?: boolean\n\n  /**\n   * Force content to be position within the viewport.\n   *\n   * Might overlap the reference element, which may not be desired.\n   *\n   * @defaultValue false\n   */\n  prioritizePosition?: boolean\n\n  /**\n   *  The custom element or virtual element that will be set as the reference\n   *  to position the floating element.\n   *\n   *  If provided, it will replace the default anchor element.\n   */\n  reference?: ReferenceElement\n}\n\nexport interface PopperContentContext {\n  placedSide: Ref<Side>\n  onArrowChange: (arrow: HTMLElement | undefined) => void\n  arrowX?: Ref<number>\n  arrowY?: Ref<number>\n  shouldHideArrow: Ref<boolean>\n}\n\nexport const [injectPopperContentContext, providePopperContentContext]\n  = createContext<PopperContentContext>('PopperContent')\n</script>\n\n<script setup lang=\"ts\">\nimport {\n  autoUpdate,\n  flip,\n  arrow as floatingUIarrow,\n  hide,\n  limitShift,\n  offset,\n  shift,\n  size,\n  useFloating,\n} from '@floating-ui/vue'\nimport { computedEager } from '@vueuse/core'\nimport { computed, ref, watchEffect, watchPostEffect } from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectPopperRootContext } from './PopperRoot.vue'\nimport {\n  getSideAndAlignFromPlacement,\n  isNotNull,\n  transformOrigin,\n} from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<PopperContentProps>(), {\n  ...PopperContentPropsDefaultValue,\n})\nconst emits = defineEmits<{\n  placed: [void]\n}>()\n\nconst rootContext = injectPopperRootContext()\nconst { forwardRef, currentElement: contentElement } = useForwardExpose()\n\nconst floatingRef = ref<HTMLElement>()\n\nconst arrow = ref<HTMLElement>()\nconst { width: arrowWidth, height: arrowHeight } = useSize(arrow)\n\nconst desiredPlacement = computed(\n  () =>\n    (props.side\n      + (props.align !== 'center' ? `-${props.align}` : '')) as Placement,\n)\n\nconst collisionPadding = computed(() => {\n  return typeof props.collisionPadding === 'number'\n    ? props.collisionPadding\n    : { top: 0, right: 0, bottom: 0, left: 0, ...props.collisionPadding }\n})\n\nconst boundary = computed(() => {\n  return Array.isArray(props.collisionBoundary)\n    ? props.collisionBoundary\n    : [props.collisionBoundary]\n})\n\nconst detectOverflowOptions = computed(() => {\n  return {\n    padding: collisionPadding.value,\n    boundary: boundary.value.filter(isNotNull),\n    // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries\n    altBoundary: boundary.value.length > 0,\n  }\n})\n\nconst flipOptions = computed(() => {\n  return {\n    mainAxis: props.sideFlip,\n    crossAxis: props.alignFlip,\n  }\n})\n\nconst computedMiddleware = computedEager(() => {\n  return [\n    offset({\n      mainAxis: props.sideOffset + arrowHeight.value,\n      alignmentAxis: props.alignOffset,\n    }),\n    props.prioritizePosition\n    && props.avoidCollisions\n    && flip({\n      ...detectOverflowOptions.value,\n      ...flipOptions.value,\n    }),\n    props.avoidCollisions\n    && shift({\n      mainAxis: true,\n      crossAxis: !!props.prioritizePosition,\n      limiter: props.sticky === 'partial' ? limitShift() : undefined,\n      ...detectOverflowOptions.value,\n    }),\n    !props.prioritizePosition\n    && props.avoidCollisions\n    && flip({\n      ...detectOverflowOptions.value,\n      ...flipOptions.value,\n    }),\n    size({\n      ...detectOverflowOptions.value,\n      apply: ({ elements, rects, availableWidth, availableHeight }) => {\n        const { width: anchorWidth, height: anchorHeight } = rects.reference\n        const contentStyle = elements.floating.style\n        contentStyle.setProperty(\n          '--reka-popper-available-width',\n          `${availableWidth}px`,\n        )\n        contentStyle.setProperty(\n          '--reka-popper-available-height',\n          `${availableHeight}px`,\n        )\n        contentStyle.setProperty(\n          '--reka-popper-anchor-width',\n          `${anchorWidth}px`,\n        )\n        contentStyle.setProperty(\n          '--reka-popper-anchor-height',\n          `${anchorHeight}px`,\n        )\n      },\n    }),\n    arrow.value\n    && floatingUIarrow({ element: arrow.value, padding: props.arrowPadding }),\n    transformOrigin({\n      arrowWidth: arrowWidth.value,\n      arrowHeight: arrowHeight.value,\n    }),\n    props.hideWhenDetached\n    && hide({ strategy: 'referenceHidden', ...detectOverflowOptions.value }),\n  ] as Middleware[]\n})\n\n// If provided custom reference, it will overwrite the default anchor element\nconst reference = computed(() => props.reference ?? rootContext.anchor.value)\n\nconst { floatingStyles, placement, isPositioned, middlewareData, update } = useFloating(\n  reference,\n  floatingRef,\n  {\n    strategy: props.positionStrategy,\n    placement: desiredPlacement,\n    whileElementsMounted: (...args) => {\n      const cleanup = autoUpdate(...args, {\n        layoutShift: !props.disableUpdateOnLayoutShift,\n        animationFrame: props.updatePositionStrategy === 'always',\n      })\n      return cleanup\n    },\n    middleware: computedMiddleware,\n  },\n)\n\nconst placedSide = computed(\n  () => getSideAndAlignFromPlacement(placement.value)[0],\n)\nconst placedAlign = computed(\n  () => getSideAndAlignFromPlacement(placement.value)[1],\n)\n\nwatchPostEffect(() => {\n  if (isPositioned.value)\n    emits('placed')\n})\n\nconst shouldHideArrow = computed(() => {\n  const cannotCenterArrow = middlewareData.value.arrow?.centerOffset !== 0\n  return props.hideShiftedArrow && cannotCenterArrow\n})\n\nconst contentZIndex = ref('')\nwatchEffect(() => {\n  if (contentElement.value)\n    contentZIndex.value = window.getComputedStyle(contentElement.value).zIndex\n})\n\nconst arrowX = computed(() => middlewareData.value.arrow?.x ?? 0)\nconst arrowY = computed(() => middlewareData.value.arrow?.y ?? 0)\n\nprovidePopperContentContext({\n  placedSide,\n  onArrowChange: element => arrow.value = element,\n  arrowX,\n  arrowY,\n  shouldHideArrow,\n})\n</script>\n\n<template>\n  <div\n    ref=\"floatingRef\"\n    data-reka-popper-content-wrapper=\"\"\n    :style=\"{\n      ...floatingStyles,\n      transform: isPositioned ? floatingStyles.transform : 'translate(0, -200%)', // keep off the page when measuring\n      minWidth: 'max-content',\n      zIndex: contentZIndex,\n      ['--reka-popper-transform-origin' as any]: [\n        middlewareData.transformOrigin?.x,\n        middlewareData.transformOrigin?.y,\n      ].join(' '),\n\n      // hide the content if using the hide middleware and should be hidden\n      // set visibility to hidden and disable pointer events so the UI behaves\n      // as if the PopperContent isn't there at all\n      ...(middlewareData.hide?.referenceHidden && {\n        visibility: 'hidden',\n        pointerEvents: 'none',\n      }),\n    }\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      v-bind=\"$attrs\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n      :data-side=\"placedSide\"\n      :data-align=\"placedAlign\"\n      :style=\"{\n        // if the PopperContent hasn't been placed yet (not all measurements done)\n        // we prevent animations so that users's animation don't kick in too early referring wrong sides\n        animation: !isPositioned ? 'none' : undefined,\n      }\"\n    >\n      <slot />\n    </Primitive>\n  </div>\n</template>\n","<script lang=\"ts\">\nimport type {\n  Middleware,\n  Placement,\n  ReferenceElement,\n} from '@floating-ui/vue'\nimport type { Ref } from 'vue'\nimport type {\n  Align,\n  Side,\n} from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useForwardExpose, useSize } from '@/shared'\n\nexport const PopperContentPropsDefaultValue = {\n  side: 'bottom' as Side,\n  sideOffset: 0,\n  sideFlip: true,\n  align: 'center' as Align,\n  alignOffset: 0,\n  alignFlip: true,\n  arrowPadding: 0,\n  hideShiftedArrow: true,\n  avoidCollisions: true,\n  collisionBoundary: () => [],\n  collisionPadding: 0,\n  sticky: 'partial' as 'partial' | 'always',\n  hideWhenDetached: false,\n  positionStrategy: 'fixed' as 'absolute' | 'fixed',\n  updatePositionStrategy: 'optimized' as 'optimized' | 'always',\n  prioritizePosition: false,\n}\n\nexport interface PopperContentProps extends PrimitiveProps {\n  /**\n   * The preferred side of the trigger to render against when open.\n   * Will be reversed when collisions occur and avoidCollisions\n   * is enabled.\n   *\n   * @defaultValue \"bottom\"\n   */\n  side?: Side\n\n  /**\n   * The distance in pixels from the trigger.\n   *\n   * @defaultValue 0\n   */\n  sideOffset?: number\n\n  /**\n   * Flip to the opposite side when colliding with boundary.\n   *\n   * @defaultValue true\n   */\n  sideFlip?: boolean\n\n  /**\n   * The preferred alignment against the trigger.\n   * May change when collisions occur.\n   *\n   * @defaultValue \"center\"\n   */\n  align?: Align\n\n  /**\n   * An offset in pixels from the `start` or `end` alignment options.\n   *\n   * @defaultValue 0\n   */\n  alignOffset?: number\n\n  /**\n   * Flip alignment when colliding with boundary.\n   * May only occur when `prioritizePosition` is true.\n   *\n   * @defaultValue true\n   */\n  alignFlip?: boolean\n\n  /**\n   * When `true`, overrides the side and align preferences\n   * to prevent collisions with boundary edges.\n   *\n   * @defaultValue true\n   */\n  avoidCollisions?: boolean\n\n  /**\n   * The element used as the collision boundary. By default\n   * this is the viewport, though you can provide additional\n   * element(s) to be included in this check.\n   *\n   * @defaultValue []\n   */\n  collisionBoundary?: Element | null | Array<Element | null>\n\n  /**\n   * The distance in pixels from the boundary edges where collision\n   * detection should occur. Accepts a number (same for all sides),\n   * or a partial padding object, for example: { top: 20, left: 20 }.\n   *\n   * @defaultValue 0\n   */\n  collisionPadding?: number | Partial<Record<Side, number>>\n\n  /**\n   * The padding between the arrow and the edges of the content.\n   * If your content has border-radius, this will prevent it from\n   * overflowing the corners.\n   *\n   * @defaultValue 0\n   */\n  arrowPadding?: number\n\n  /**\n   * When `true`, hides the arrow when it cannot be centered\n   * to the reference element.\n   *\n   * @defaultValue true\n   */\n  hideShiftedArrow?: boolean\n\n  /**\n   * The sticky behavior on the align axis. `partial` will keep the\n   * content in the boundary as long as the trigger is at least partially\n   * in the boundary whilst \"always\" will keep the content in the boundary\n   * regardless.\n   *\n   * @defaultValue \"partial\"\n   */\n  sticky?: 'partial' | 'always'\n\n  /**\n   * Whether to hide the content when the trigger becomes fully occluded.\n   *\n   * @defaultValue false\n   */\n  hideWhenDetached?: boolean\n\n  /**\n   *  The type of CSS position property to use.\n   */\n  positionStrategy?: 'absolute' | 'fixed'\n\n  /**\n   * Strategy to update the position of the floating element on every animation frame.\n   *\n   * @defaultValue 'optimized'\n   */\n  updatePositionStrategy?: 'optimized' | 'always'\n\n  /**\n   * Whether to disable the update position for the content when the layout shifted.\n   *\n   * @defaultValue false\n   */\n  disableUpdateOnLayoutShift?: boolean\n\n  /**\n   * Force content to be position within the viewport.\n   *\n   * Might overlap the reference element, which may not be desired.\n   *\n   * @defaultValue false\n   */\n  prioritizePosition?: boolean\n\n  /**\n   *  The custom element or virtual element that will be set as the reference\n   *  to position the floating element.\n   *\n   *  If provided, it will replace the default anchor element.\n   */\n  reference?: ReferenceElement\n}\n\nexport interface PopperContentContext {\n  placedSide: Ref<Side>\n  onArrowChange: (arrow: HTMLElement | undefined) => void\n  arrowX?: Ref<number>\n  arrowY?: Ref<number>\n  shouldHideArrow: Ref<boolean>\n}\n\nexport const [injectPopperContentContext, providePopperContentContext]\n  = createContext<PopperContentContext>('PopperContent')\n</script>\n\n<script setup lang=\"ts\">\nimport {\n  autoUpdate,\n  flip,\n  arrow as floatingUIarrow,\n  hide,\n  limitShift,\n  offset,\n  shift,\n  size,\n  useFloating,\n} from '@floating-ui/vue'\nimport { computedEager } from '@vueuse/core'\nimport { computed, ref, watchEffect, watchPostEffect } from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectPopperRootContext } from './PopperRoot.vue'\nimport {\n  getSideAndAlignFromPlacement,\n  isNotNull,\n  transformOrigin,\n} from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<PopperContentProps>(), {\n  ...PopperContentPropsDefaultValue,\n})\nconst emits = defineEmits<{\n  placed: [void]\n}>()\n\nconst rootContext = injectPopperRootContext()\nconst { forwardRef, currentElement: contentElement } = useForwardExpose()\n\nconst floatingRef = ref<HTMLElement>()\n\nconst arrow = ref<HTMLElement>()\nconst { width: arrowWidth, height: arrowHeight } = useSize(arrow)\n\nconst desiredPlacement = computed(\n  () =>\n    (props.side\n      + (props.align !== 'center' ? `-${props.align}` : '')) as Placement,\n)\n\nconst collisionPadding = computed(() => {\n  return typeof props.collisionPadding === 'number'\n    ? props.collisionPadding\n    : { top: 0, right: 0, bottom: 0, left: 0, ...props.collisionPadding }\n})\n\nconst boundary = computed(() => {\n  return Array.isArray(props.collisionBoundary)\n    ? props.collisionBoundary\n    : [props.collisionBoundary]\n})\n\nconst detectOverflowOptions = computed(() => {\n  return {\n    padding: collisionPadding.value,\n    boundary: boundary.value.filter(isNotNull),\n    // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries\n    altBoundary: boundary.value.length > 0,\n  }\n})\n\nconst flipOptions = computed(() => {\n  return {\n    mainAxis: props.sideFlip,\n    crossAxis: props.alignFlip,\n  }\n})\n\nconst computedMiddleware = computedEager(() => {\n  return [\n    offset({\n      mainAxis: props.sideOffset + arrowHeight.value,\n      alignmentAxis: props.alignOffset,\n    }),\n    props.prioritizePosition\n    && props.avoidCollisions\n    && flip({\n      ...detectOverflowOptions.value,\n      ...flipOptions.value,\n    }),\n    props.avoidCollisions\n    && shift({\n      mainAxis: true,\n      crossAxis: !!props.prioritizePosition,\n      limiter: props.sticky === 'partial' ? limitShift() : undefined,\n      ...detectOverflowOptions.value,\n    }),\n    !props.prioritizePosition\n    && props.avoidCollisions\n    && flip({\n      ...detectOverflowOptions.value,\n      ...flipOptions.value,\n    }),\n    size({\n      ...detectOverflowOptions.value,\n      apply: ({ elements, rects, availableWidth, availableHeight }) => {\n        const { width: anchorWidth, height: anchorHeight } = rects.reference\n        const contentStyle = elements.floating.style\n        contentStyle.setProperty(\n          '--reka-popper-available-width',\n          `${availableWidth}px`,\n        )\n        contentStyle.setProperty(\n          '--reka-popper-available-height',\n          `${availableHeight}px`,\n        )\n        contentStyle.setProperty(\n          '--reka-popper-anchor-width',\n          `${anchorWidth}px`,\n        )\n        contentStyle.setProperty(\n          '--reka-popper-anchor-height',\n          `${anchorHeight}px`,\n        )\n      },\n    }),\n    arrow.value\n    && floatingUIarrow({ element: arrow.value, padding: props.arrowPadding }),\n    transformOrigin({\n      arrowWidth: arrowWidth.value,\n      arrowHeight: arrowHeight.value,\n    }),\n    props.hideWhenDetached\n    && hide({ strategy: 'referenceHidden', ...detectOverflowOptions.value }),\n  ] as Middleware[]\n})\n\n// If provided custom reference, it will overwrite the default anchor element\nconst reference = computed(() => props.reference ?? rootContext.anchor.value)\n\nconst { floatingStyles, placement, isPositioned, middlewareData, update } = useFloating(\n  reference,\n  floatingRef,\n  {\n    strategy: props.positionStrategy,\n    placement: desiredPlacement,\n    whileElementsMounted: (...args) => {\n      const cleanup = autoUpdate(...args, {\n        layoutShift: !props.disableUpdateOnLayoutShift,\n        animationFrame: props.updatePositionStrategy === 'always',\n      })\n      return cleanup\n    },\n    middleware: computedMiddleware,\n  },\n)\n\nconst placedSide = computed(\n  () => getSideAndAlignFromPlacement(placement.value)[0],\n)\nconst placedAlign = computed(\n  () => getSideAndAlignFromPlacement(placement.value)[1],\n)\n\nwatchPostEffect(() => {\n  if (isPositioned.value)\n    emits('placed')\n})\n\nconst shouldHideArrow = computed(() => {\n  const cannotCenterArrow = middlewareData.value.arrow?.centerOffset !== 0\n  return props.hideShiftedArrow && cannotCenterArrow\n})\n\nconst contentZIndex = ref('')\nwatchEffect(() => {\n  if (contentElement.value)\n    contentZIndex.value = window.getComputedStyle(contentElement.value).zIndex\n})\n\nconst arrowX = computed(() => middlewareData.value.arrow?.x ?? 0)\nconst arrowY = computed(() => middlewareData.value.arrow?.y ?? 0)\n\nprovidePopperContentContext({\n  placedSide,\n  onArrowChange: element => arrow.value = element,\n  arrowX,\n  arrowY,\n  shouldHideArrow,\n})\n</script>\n\n<template>\n  <div\n    ref=\"floatingRef\"\n    data-reka-popper-content-wrapper=\"\"\n    :style=\"{\n      ...floatingStyles,\n      transform: isPositioned ? floatingStyles.transform : 'translate(0, -200%)', // keep off the page when measuring\n      minWidth: 'max-content',\n      zIndex: contentZIndex,\n      ['--reka-popper-transform-origin' as any]: [\n        middlewareData.transformOrigin?.x,\n        middlewareData.transformOrigin?.y,\n      ].join(' '),\n\n      // hide the content if using the hide middleware and should be hidden\n      // set visibility to hidden and disable pointer events so the UI behaves\n      // as if the PopperContent isn't there at all\n      ...(middlewareData.hide?.referenceHidden && {\n        visibility: 'hidden',\n        pointerEvents: 'none',\n      }),\n    }\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      v-bind=\"$attrs\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n      :data-side=\"placedSide\"\n      :data-align=\"placedAlign\"\n      :style=\"{\n        // if the PopperContent hasn't been placed yet (not all measurements done)\n        // we prevent animations so that users's animation don't kick in too early referring wrong sides\n        animation: !isPositioned ? 'none' : undefined,\n      }\"\n    >\n      <slot />\n    </Primitive>\n  </div>\n</template>\n","<script lang=\"ts\">\nimport type { Side } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { ArrowProps } from '@/shared/component/Arrow.vue'\n\nconst OPPOSITE_SIDE: Record<Side, Side> = {\n  top: 'bottom',\n  right: 'left',\n  bottom: 'top',\n  left: 'right',\n}\n\nexport interface PopperArrowProps extends ArrowProps, PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport type { ComponentPublicInstance } from 'vue'\nimport { computed } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport Arrow from '@/shared/component/Arrow.vue'\nimport { injectPopperContentContext } from './PopperContent.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nwithDefaults(\n  defineProps<PopperArrowProps>(),\n  { as: 'svg' },\n)\n\nconst { forwardRef } = useForwardExpose()\nconst contentContext = injectPopperContentContext()\n\nconst baseSide = computed(() => OPPOSITE_SIDE[contentContext.placedSide.value])\n</script>\n\n<template>\n  <span\n    :ref=\"(el: Element | ComponentPublicInstance | null) => {\n      contentContext.onArrowChange((el as HTMLElement) ?? undefined)\n      return undefined\n    }\"\n    :style=\"{\n      position: 'absolute',\n      left: contentContext.arrowX?.value ? `${contentContext.arrowX?.value}px` : undefined,\n      top: contentContext.arrowY?.value ? `${contentContext.arrowY?.value}px` : undefined,\n      [baseSide]: 0,\n      transformOrigin: {\n        top: '',\n        right: '0 0',\n        bottom: 'center 0',\n        left: '100% 0',\n      }[contentContext.placedSide.value],\n      transform: {\n        top: 'translateY(100%)',\n        right: 'translateY(50%) rotate(90deg) translateX(-50%)',\n        bottom: `rotate(180deg)`,\n        left: 'translateY(50%) rotate(-90deg) translateX(50%)',\n      }[contentContext.placedSide.value],\n      visibility: contentContext.shouldHideArrow.value ? 'hidden' : undefined,\n    }\"\n  >\n    <Arrow\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :style=\"{\n        display: 'block',\n      }\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :rounded=\"rounded\"\n      :width=\"width\"\n      :height=\"height\"\n    >\n      <slot />\n    </Arrow>\n  </span>\n</template>\n","<script lang=\"ts\">\nimport type { Side } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { ArrowProps } from '@/shared/component/Arrow.vue'\n\nconst OPPOSITE_SIDE: Record<Side, Side> = {\n  top: 'bottom',\n  right: 'left',\n  bottom: 'top',\n  left: 'right',\n}\n\nexport interface PopperArrowProps extends ArrowProps, PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport type { ComponentPublicInstance } from 'vue'\nimport { computed } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport Arrow from '@/shared/component/Arrow.vue'\nimport { injectPopperContentContext } from './PopperContent.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nwithDefaults(\n  defineProps<PopperArrowProps>(),\n  { as: 'svg' },\n)\n\nconst { forwardRef } = useForwardExpose()\nconst contentContext = injectPopperContentContext()\n\nconst baseSide = computed(() => OPPOSITE_SIDE[contentContext.placedSide.value])\n</script>\n\n<template>\n  <span\n    :ref=\"(el: Element | ComponentPublicInstance | null) => {\n      contentContext.onArrowChange((el as HTMLElement) ?? undefined)\n      return undefined\n    }\"\n    :style=\"{\n      position: 'absolute',\n      left: contentContext.arrowX?.value ? `${contentContext.arrowX?.value}px` : undefined,\n      top: contentContext.arrowY?.value ? `${contentContext.arrowY?.value}px` : undefined,\n      [baseSide]: 0,\n      transformOrigin: {\n        top: '',\n        right: '0 0',\n        bottom: 'center 0',\n        left: '100% 0',\n      }[contentContext.placedSide.value],\n      transform: {\n        top: 'translateY(100%)',\n        right: 'translateY(50%) rotate(90deg) translateX(-50%)',\n        bottom: `rotate(180deg)`,\n        left: 'translateY(50%) rotate(-90deg) translateX(50%)',\n      }[contentContext.placedSide.value],\n      visibility: contentContext.shouldHideArrow.value ? 'hidden' : undefined,\n    }\"\n  >\n    <Arrow\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :style=\"{\n        display: 'block',\n      }\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :rounded=\"rounded\"\n      :width=\"width\"\n      :height=\"height\"\n    >\n      <slot />\n    </Arrow>\n  </span>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { ListboxRootProps } from '@/Listbox'\nimport type { AcceptableValue, GenericComponentInstance } from '@/shared/types'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { createContext, useDirection, useFilter } from '@/shared'\n\ntype ComboboxRootContext<T> = {\n  modelValue: Ref<T | Array<T>>\n  multiple: Ref<boolean>\n  disabled: Ref<boolean>\n  open: Ref<boolean>\n  onOpenChange: (value: boolean) => void\n  isUserInputted: Ref<boolean>\n  isVirtual: Ref<boolean>\n  contentId: string\n  inputElement: Ref<HTMLInputElement | undefined>\n  onInputElementChange: (el: HTMLInputElement) => void\n  triggerElement: Ref<HTMLElement | undefined>\n  onTriggerElementChange: (el: HTMLElement) => void\n  highlightedElement: Ref<HTMLElement | undefined>\n  parentElement: Ref<HTMLElement | undefined>\n  resetSearchTermOnSelect: Ref<boolean>\n  onResetSearchTerm: EventHookOn\n  allItems: Ref<Map<string, string>>\n  allGroups: Ref<Map<string, Set<string>>>\n  filterSearch: Ref<string>\n  filterState: ComputedRef<{ count: number, items: Map<string, number>, groups: Set<string> }>\n  ignoreFilter: Ref<boolean>\n  openOnFocus: Ref<boolean>\n  openOnClick: Ref<boolean>\n  resetModelValueOnClear: Ref<boolean>\n}\n\nexport const [injectComboboxRootContext, provideComboboxRootContext]\n  = createContext<ComboboxRootContext<AcceptableValue>>('ComboboxRoot')\n\nexport type ComboboxRootEmits<T = AcceptableValue> = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: T]\n  /** Event handler when highlighted element changes. */\n  'highlight': [payload: { ref: HTMLElement, value: T } | undefined]\n  /** Event handler called when the open state of the combobox changes. */\n  'update:open': [value: boolean]\n}\n\nexport interface ComboboxRootProps<T = AcceptableValue> extends Omit<ListboxRootProps<T>, 'orientation' | 'selectionBehavior'> {\n  /** The controlled open state of the Combobox. Can be binded with `v-model:open`. */\n  open?: boolean\n  /** The open state of the combobox when it is initially rendered. <br> Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /**\n   * Whether to reset the searchTerm when the Combobox input blurred\n   * @defaultValue `true`\n   */\n  resetSearchTermOnBlur?: boolean\n  /**\n   * Whether to reset the searchTerm when the Combobox value is selected\n   * @defaultValue `true`\n   */\n  resetSearchTermOnSelect?: boolean\n  /**\n   * Whether to open the combobox when the input is focused\n   * @defaultValue `false`\n   */\n  openOnFocus?: boolean\n  /**\n   * Whether to open the combobox when the input is clicked\n   * @defaultValue `false`\n   */\n  openOnClick?: boolean\n  /**\n   * When `true`, disable the default filters\n   */\n  ignoreFilter?: boolean\n  /**\n   * When `true` the `modelValue` will be reset to `null` (or `[]` if `multiple`)\n   */\n  resetModelValueOnClear?: boolean\n}\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport type { EventHookOn } from '@vueuse/core'\nimport { createEventHook, useVModel } from '@vueuse/core'\nimport { computed, getCurrentInstance, nextTick, onMounted, ref, toRefs } from 'vue'\nimport { ListboxRoot } from '@/Listbox'\nimport { PopperRoot } from '@/Popper'\n\nconst props = withDefaults(defineProps<ComboboxRootProps<T>>(), {\n  open: undefined,\n  resetSearchTermOnBlur: true,\n  resetSearchTermOnSelect: true,\n  openOnFocus: false,\n  openOnClick: false,\n  resetModelValueOnClear: false,\n  highlightOnHover: true,\n})\nconst emits = defineEmits<ComboboxRootEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n    /** Current active value */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { primitiveElement, currentElement: parentElement } = usePrimitiveElement<GenericComponentInstance<typeof ListboxRoot>>()\nconst { multiple, disabled, ignoreFilter, resetSearchTermOnSelect, openOnFocus, openOnClick, dir: propDir, resetModelValueOnClear, highlightOnHover } = toRefs(props)\n\nconst dir = useDirection(propDir)\n\nconst modelValue = useVModel(props as ComboboxRootProps<T>, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? (multiple.value ? [] : undefined),\n  passive: (props.modelValue === undefined) as false,\n  deep: true,\n}) as Ref<T | T[]>\n\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nasync function onOpenChange(val: boolean) {\n  open.value = val\n  filterSearch.value = ''\n\n  if (val) {\n    // make sure dom is ready then only highlight the selected\n    await nextTick()\n    primitiveElement.value?.highlightSelected()\n    isUserInputted.value = true\n    inputElement.value?.focus()\n  }\n  else {\n    isUserInputted.value = false\n    setTimeout(() => {\n      if (!val && props.resetSearchTermOnBlur)\n        resetSearchTerm.trigger()\n    }, 1)\n  }\n}\n\nconst resetSearchTerm = createEventHook()\nconst isUserInputted = ref(false)\nconst isVirtual = ref(false)\nconst inputElement = ref<HTMLInputElement>()\nconst triggerElement = ref<HTMLElement>()\n\nconst highlightedElement = computed(() => primitiveElement.value?.highlightedElement ?? undefined)\n\nconst allItems = ref<Map<string, string>>(new Map())\nconst allGroups = ref<Map<string, Set<string>>>(new Map())\n\nconst { contains } = useFilter({ sensitivity: 'base' })\n\nconst filterSearch = ref('')\n\nconst filterState = computed<{\n  count: number\n  items: Map<string, number>\n  groups: Set<string>\n}>((oldValue) => {\n  if (!filterSearch.value || props.ignoreFilter || isVirtual.value) {\n    // Do nothing, each item will know to show itself because search is empty\n    return {\n      count: allItems.value.size,\n      items: oldValue?.items ?? new Map(),\n      groups: oldValue?.groups ?? new Set(allGroups.value.keys()),\n    }\n  }\n\n  let itemCount = 0\n  const filteredItems = new Map<string, number>()\n  const filteredGroups = new Set<string>()\n\n  // Check which items should be included\n  for (const [id, value] of allItems.value) {\n    const score = contains(value, filterSearch.value)\n    filteredItems.set(id, score ? 1 : 0)\n    if (score)\n      itemCount++\n  }\n\n  // Check which groups have at least 1 item shown\n  for (const [groupId, group] of allGroups.value) {\n    for (const itemId of group) {\n      if (filteredItems.get(itemId)! > 0) {\n        filteredGroups.add(groupId)\n        break\n      }\n    }\n  }\n\n  return {\n    count: itemCount,\n    items: filteredItems,\n    groups: filteredGroups,\n  }\n})\n\nconst inst = getCurrentInstance()\nonMounted(() => {\n  if (inst?.exposed) {\n    inst.exposed.highlightItem = primitiveElement.value?.highlightItem\n    inst.exposed.highlightFirstItem = primitiveElement.value?.highlightFirstItem\n    inst.exposed.highlightSelected = primitiveElement.value?.highlightSelected\n  }\n})\n\ndefineExpose({\n  filtered: filterState,\n  highlightedElement,\n  highlightItem: primitiveElement.value?.highlightItem,\n  highlightFirstItem: primitiveElement.value?.highlightFirstItem,\n  highlightSelected: primitiveElement.value?.highlightSelected,\n})\n\nprovideComboboxRootContext({\n  modelValue,\n  multiple,\n  disabled,\n  open,\n  onOpenChange,\n  contentId: '',\n  isUserInputted,\n  isVirtual,\n  inputElement,\n  highlightedElement,\n  onInputElementChange: val => inputElement.value = val,\n  triggerElement,\n  onTriggerElementChange: val => triggerElement.value = val,\n  parentElement,\n  resetSearchTermOnSelect,\n  onResetSearchTerm: resetSearchTerm.on,\n  allItems,\n  allGroups,\n  filterSearch,\n  filterState,\n  ignoreFilter,\n  openOnFocus,\n  openOnClick,\n  resetModelValueOnClear,\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <ListboxRoot\n      ref=\"primitiveElement\"\n      v-bind=\"$attrs\"\n      v-model=\"modelValue\"\n      :style=\"{\n        pointerEvents: open ? 'auto' : undefined,\n      }\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :dir=\"dir\"\n      :multiple=\"multiple\"\n      :name=\"name\"\n      :required=\"required\"\n      :disabled=\"disabled\"\n      :highlight-on-hover=\"highlightOnHover\"\n      :by=\"props.by as any\"\n      @highlight=\"emits('highlight', $event as any)\"\n    >\n      <slot\n        :open=\"open\"\n        :model-value=\"modelValue\"\n      />\n    </ListboxRoot>\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { ListboxRootProps } from '@/Listbox'\nimport type { AcceptableValue, GenericComponentInstance } from '@/shared/types'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { createContext, useDirection, useFilter } from '@/shared'\n\ntype ComboboxRootContext<T> = {\n  modelValue: Ref<T | Array<T>>\n  multiple: Ref<boolean>\n  disabled: Ref<boolean>\n  open: Ref<boolean>\n  onOpenChange: (value: boolean) => void\n  isUserInputted: Ref<boolean>\n  isVirtual: Ref<boolean>\n  contentId: string\n  inputElement: Ref<HTMLInputElement | undefined>\n  onInputElementChange: (el: HTMLInputElement) => void\n  triggerElement: Ref<HTMLElement | undefined>\n  onTriggerElementChange: (el: HTMLElement) => void\n  highlightedElement: Ref<HTMLElement | undefined>\n  parentElement: Ref<HTMLElement | undefined>\n  resetSearchTermOnSelect: Ref<boolean>\n  onResetSearchTerm: EventHookOn\n  allItems: Ref<Map<string, string>>\n  allGroups: Ref<Map<string, Set<string>>>\n  filterSearch: Ref<string>\n  filterState: ComputedRef<{ count: number, items: Map<string, number>, groups: Set<string> }>\n  ignoreFilter: Ref<boolean>\n  openOnFocus: Ref<boolean>\n  openOnClick: Ref<boolean>\n  resetModelValueOnClear: Ref<boolean>\n}\n\nexport const [injectComboboxRootContext, provideComboboxRootContext]\n  = createContext<ComboboxRootContext<AcceptableValue>>('ComboboxRoot')\n\nexport type ComboboxRootEmits<T = AcceptableValue> = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: T]\n  /** Event handler when highlighted element changes. */\n  'highlight': [payload: { ref: HTMLElement, value: T } | undefined]\n  /** Event handler called when the open state of the combobox changes. */\n  'update:open': [value: boolean]\n}\n\nexport interface ComboboxRootProps<T = AcceptableValue> extends Omit<ListboxRootProps<T>, 'orientation' | 'selectionBehavior'> {\n  /** The controlled open state of the Combobox. Can be binded with `v-model:open`. */\n  open?: boolean\n  /** The open state of the combobox when it is initially rendered. <br> Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /**\n   * Whether to reset the searchTerm when the Combobox input blurred\n   * @defaultValue `true`\n   */\n  resetSearchTermOnBlur?: boolean\n  /**\n   * Whether to reset the searchTerm when the Combobox value is selected\n   * @defaultValue `true`\n   */\n  resetSearchTermOnSelect?: boolean\n  /**\n   * Whether to open the combobox when the input is focused\n   * @defaultValue `false`\n   */\n  openOnFocus?: boolean\n  /**\n   * Whether to open the combobox when the input is clicked\n   * @defaultValue `false`\n   */\n  openOnClick?: boolean\n  /**\n   * When `true`, disable the default filters\n   */\n  ignoreFilter?: boolean\n  /**\n   * When `true` the `modelValue` will be reset to `null` (or `[]` if `multiple`)\n   */\n  resetModelValueOnClear?: boolean\n}\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport type { EventHookOn } from '@vueuse/core'\nimport { createEventHook, useVModel } from '@vueuse/core'\nimport { computed, getCurrentInstance, nextTick, onMounted, ref, toRefs } from 'vue'\nimport { ListboxRoot } from '@/Listbox'\nimport { PopperRoot } from '@/Popper'\n\nconst props = withDefaults(defineProps<ComboboxRootProps<T>>(), {\n  open: undefined,\n  resetSearchTermOnBlur: true,\n  resetSearchTermOnSelect: true,\n  openOnFocus: false,\n  openOnClick: false,\n  resetModelValueOnClear: false,\n  highlightOnHover: true,\n})\nconst emits = defineEmits<ComboboxRootEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n    /** Current active value */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { primitiveElement, currentElement: parentElement } = usePrimitiveElement<GenericComponentInstance<typeof ListboxRoot>>()\nconst { multiple, disabled, ignoreFilter, resetSearchTermOnSelect, openOnFocus, openOnClick, dir: propDir, resetModelValueOnClear, highlightOnHover } = toRefs(props)\n\nconst dir = useDirection(propDir)\n\nconst modelValue = useVModel(props as ComboboxRootProps<T>, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? (multiple.value ? [] : undefined),\n  passive: (props.modelValue === undefined) as false,\n  deep: true,\n}) as Ref<T | T[]>\n\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nasync function onOpenChange(val: boolean) {\n  open.value = val\n  filterSearch.value = ''\n\n  if (val) {\n    // make sure dom is ready then only highlight the selected\n    await nextTick()\n    primitiveElement.value?.highlightSelected()\n    isUserInputted.value = true\n    inputElement.value?.focus()\n  }\n  else {\n    isUserInputted.value = false\n    setTimeout(() => {\n      if (!val && props.resetSearchTermOnBlur)\n        resetSearchTerm.trigger()\n    }, 1)\n  }\n}\n\nconst resetSearchTerm = createEventHook()\nconst isUserInputted = ref(false)\nconst isVirtual = ref(false)\nconst inputElement = ref<HTMLInputElement>()\nconst triggerElement = ref<HTMLElement>()\n\nconst highlightedElement = computed(() => primitiveElement.value?.highlightedElement ?? undefined)\n\nconst allItems = ref<Map<string, string>>(new Map())\nconst allGroups = ref<Map<string, Set<string>>>(new Map())\n\nconst { contains } = useFilter({ sensitivity: 'base' })\n\nconst filterSearch = ref('')\n\nconst filterState = computed<{\n  count: number\n  items: Map<string, number>\n  groups: Set<string>\n}>((oldValue) => {\n  if (!filterSearch.value || props.ignoreFilter || isVirtual.value) {\n    // Do nothing, each item will know to show itself because search is empty\n    return {\n      count: allItems.value.size,\n      items: oldValue?.items ?? new Map(),\n      groups: oldValue?.groups ?? new Set(allGroups.value.keys()),\n    }\n  }\n\n  let itemCount = 0\n  const filteredItems = new Map<string, number>()\n  const filteredGroups = new Set<string>()\n\n  // Check which items should be included\n  for (const [id, value] of allItems.value) {\n    const score = contains(value, filterSearch.value)\n    filteredItems.set(id, score ? 1 : 0)\n    if (score)\n      itemCount++\n  }\n\n  // Check which groups have at least 1 item shown\n  for (const [groupId, group] of allGroups.value) {\n    for (const itemId of group) {\n      if (filteredItems.get(itemId)! > 0) {\n        filteredGroups.add(groupId)\n        break\n      }\n    }\n  }\n\n  return {\n    count: itemCount,\n    items: filteredItems,\n    groups: filteredGroups,\n  }\n})\n\nconst inst = getCurrentInstance()\nonMounted(() => {\n  if (inst?.exposed) {\n    inst.exposed.highlightItem = primitiveElement.value?.highlightItem\n    inst.exposed.highlightFirstItem = primitiveElement.value?.highlightFirstItem\n    inst.exposed.highlightSelected = primitiveElement.value?.highlightSelected\n  }\n})\n\ndefineExpose({\n  filtered: filterState,\n  highlightedElement,\n  highlightItem: primitiveElement.value?.highlightItem,\n  highlightFirstItem: primitiveElement.value?.highlightFirstItem,\n  highlightSelected: primitiveElement.value?.highlightSelected,\n})\n\nprovideComboboxRootContext({\n  modelValue,\n  multiple,\n  disabled,\n  open,\n  onOpenChange,\n  contentId: '',\n  isUserInputted,\n  isVirtual,\n  inputElement,\n  highlightedElement,\n  onInputElementChange: val => inputElement.value = val,\n  triggerElement,\n  onTriggerElementChange: val => triggerElement.value = val,\n  parentElement,\n  resetSearchTermOnSelect,\n  onResetSearchTerm: resetSearchTerm.on,\n  allItems,\n  allGroups,\n  filterSearch,\n  filterState,\n  ignoreFilter,\n  openOnFocus,\n  openOnClick,\n  resetModelValueOnClear,\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <ListboxRoot\n      ref=\"primitiveElement\"\n      v-bind=\"$attrs\"\n      v-model=\"modelValue\"\n      :style=\"{\n        pointerEvents: open ? 'auto' : undefined,\n      }\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :dir=\"dir\"\n      :multiple=\"multiple\"\n      :name=\"name\"\n      :required=\"required\"\n      :disabled=\"disabled\"\n      :highlight-on-hover=\"highlightOnHover\"\n      :by=\"props.by as any\"\n      @highlight=\"emits('highlight', $event as any)\"\n    >\n      <slot\n        :open=\"open\"\n        :model-value=\"modelValue\"\n      />\n    </ListboxRoot>\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Direction, GenericComponentInstance } from '@/shared/types'\nimport { provideComboboxRootContext } from '@/Combobox/ComboboxRoot.vue'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { createContext, useDirection, useFilter } from '@/shared'\n\nexport interface AutocompleteRootProps extends PrimitiveProps {\n  /** The controlled value of the Autocomplete (the input text). Can be bound with `v-model`. */\n  modelValue?: string\n  /** The value of the autocomplete when initially rendered. Use when you do not need to control the state. */\n  defaultValue?: string\n  /** The controlled open state of the Autocomplete. Can be bound with `v-model:open`. */\n  open?: boolean\n  /** The open state of the autocomplete when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /** When `true`, prevents the user from interacting with autocomplete */\n  disabled?: boolean\n  /** The reading direction of the autocomplete when applicable. */\n  dir?: Direction\n  /** The name of the field. Submitted with its owning form as part of a name/value pair. */\n  name?: string\n  /** When `true`, indicates that the user must set the value before the owning form can be submitted. */\n  required?: boolean\n  /**\n   * Whether to reset the searchTerm when the Autocomplete input blurred\n   * @defaultValue `false`\n   */\n  resetSearchTermOnBlur?: boolean\n  /**\n   * Whether to open the autocomplete when the input is focused\n   * @defaultValue `false`\n   */\n  openOnFocus?: boolean\n  /**\n   * Whether to open the autocomplete when the input is clicked\n   * @defaultValue `false`\n   */\n  openOnClick?: boolean\n  /**\n   * When `true`, disable the default filters\n   */\n  ignoreFilter?: boolean\n  /** When `true`, hover over item will trigger highlight */\n  highlightOnHover?: boolean\n}\n\nexport type AutocompleteRootEmits = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: string]\n  /** Event handler when highlighted element changes. */\n  'highlight': [payload: { ref: HTMLElement, value: string } | undefined]\n  /** Event handler called when the open state of the autocomplete changes. */\n  'update:open': [value: boolean]\n}\n\nexport type AutocompleteRootContext = {\n  modelValue: Ref<string>\n}\n\nexport const [injectAutocompleteRootContext, provideAutocompleteRootContext]\n  = createContext<AutocompleteRootContext>('AutocompleteRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { createEventHook, useVModel } from '@vueuse/core'\nimport { computed, getCurrentInstance, nextTick, onMounted, ref, toRefs } from 'vue'\nimport { ListboxRoot } from '@/Listbox'\nimport { PopperRoot } from '@/Popper'\n\nconst props = withDefaults(defineProps<AutocompleteRootProps>(), {\n  open: undefined,\n  resetSearchTermOnBlur: false,\n  openOnFocus: false,\n  openOnClick: false,\n  highlightOnHover: true,\n})\nconst emits = defineEmits<AutocompleteRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n    /** Current active value */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { primitiveElement, currentElement: parentElement } = usePrimitiveElement<GenericComponentInstance<typeof ListboxRoot>>()\nconst { disabled, ignoreFilter, openOnFocus, openOnClick, dir: propDir, highlightOnHover } = toRefs(props)\n\nconst dir = useDirection(propDir)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? '',\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<string>\n\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\n// Writable computed that converts any value to string for the ComboboxRootContext.\n// This handles the case when ComboboxItem sets modelValue to a non-string value,\n// or when ComboboxCancel resets modelValue to null.\nconst contextModelValue = computed({\n  get: () => modelValue.value,\n  set: (val: any) => {\n    if (val === null || val === undefined) {\n      modelValue.value = ''\n    }\n    else {\n      modelValue.value = String(val)\n    }\n  },\n})\n\nasync function onOpenChange(val: boolean) {\n  open.value = val\n\n  if (val) {\n    // When opening, set filter to current text so items are filtered by what's in the input\n    filterSearch.value = modelValue.value || ''\n\n    await nextTick()\n    primitiveElement.value?.highlightSelected()\n    isUserInputted.value = true\n    inputElement.value?.focus()\n  }\n  else {\n    isUserInputted.value = false\n    filterSearch.value = ''\n    setTimeout(() => {\n      if (!val && props.resetSearchTermOnBlur)\n        resetSearchTerm.trigger()\n    }, 1)\n  }\n}\n\nconst resetSearchTerm = createEventHook()\nconst isUserInputted = ref(false)\nconst isVirtual = ref(false)\nconst inputElement = ref<HTMLInputElement>()\nconst triggerElement = ref<HTMLElement>()\n\nconst highlightedElement = computed(() => primitiveElement.value?.highlightedElement ?? undefined)\n\nconst allItems = ref<Map<string, string>>(new Map())\nconst allGroups = ref<Map<string, Set<string>>>(new Map())\n\nconst { contains } = useFilter({ sensitivity: 'base' })\n\nconst filterSearch = ref('')\n\nconst filterState = computed<{\n  count: number\n  items: Map<string, number>\n  groups: Set<string>\n}>((oldValue) => {\n  if (!filterSearch.value || props.ignoreFilter || isVirtual.value) {\n    return {\n      count: allItems.value.size,\n      items: oldValue?.items ?? new Map(),\n      groups: oldValue?.groups ?? new Set(allGroups.value.keys()),\n    }\n  }\n\n  let itemCount = 0\n  const filteredItems = new Map<string, number>()\n  const filteredGroups = new Set<string>()\n\n  for (const [id, value] of allItems.value) {\n    const score = contains(value, filterSearch.value)\n    filteredItems.set(id, score ? 1 : 0)\n    if (score)\n      itemCount++\n  }\n\n  for (const [groupId, group] of allGroups.value) {\n    for (const itemId of group) {\n      if (filteredItems.get(itemId)! > 0) {\n        filteredGroups.add(groupId)\n        break\n      }\n    }\n  }\n\n  return {\n    count: itemCount,\n    items: filteredItems,\n    groups: filteredGroups,\n  }\n})\n\nconst inst = getCurrentInstance()\nonMounted(() => {\n  if (inst?.exposed) {\n    inst.exposed.highlightItem = primitiveElement.value?.highlightItem\n    inst.exposed.highlightFirstItem = primitiveElement.value?.highlightFirstItem\n    inst.exposed.highlightSelected = primitiveElement.value?.highlightSelected\n  }\n})\n\ndefineExpose({\n  filtered: filterState,\n  highlightedElement,\n  highlightItem: primitiveElement.value?.highlightItem,\n  highlightFirstItem: primitiveElement.value?.highlightFirstItem,\n  highlightSelected: primitiveElement.value?.highlightSelected,\n})\n\n// Provide the Combobox context so all Combobox sub-components work inside Autocomplete\nprovideComboboxRootContext({\n  modelValue: contextModelValue as any,\n  multiple: ref(false),\n  disabled,\n  open,\n  onOpenChange,\n  contentId: '',\n  isUserInputted,\n  isVirtual,\n  inputElement,\n  highlightedElement,\n  onInputElementChange: val => inputElement.value = val,\n  triggerElement,\n  onTriggerElementChange: val => triggerElement.value = val,\n  parentElement,\n  resetSearchTermOnSelect: ref(false),\n  onResetSearchTerm: resetSearchTerm.on,\n  allItems,\n  allGroups,\n  filterSearch,\n  filterState,\n  ignoreFilter,\n  openOnFocus,\n  openOnClick,\n  resetModelValueOnClear: ref(true),\n})\n\n// Provide autocomplete-specific context\nprovideAutocompleteRootContext({\n  modelValue,\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <ListboxRoot\n      ref=\"primitiveElement\"\n      v-bind=\"$attrs\"\n      v-model=\"(contextModelValue as any)\"\n      :style=\"{\n        pointerEvents: open ? 'auto' : undefined,\n      }\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :dir=\"dir\"\n      :name=\"name\"\n      :required=\"required\"\n      :disabled=\"disabled\"\n      :highlight-on-hover=\"highlightOnHover\"\n      @highlight=\"emits('highlight', $event as any)\"\n    >\n      <slot\n        :open=\"open\"\n        :model-value=\"modelValue\"\n      />\n    </ListboxRoot>\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Direction, GenericComponentInstance } from '@/shared/types'\nimport { provideComboboxRootContext } from '@/Combobox/ComboboxRoot.vue'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { createContext, useDirection, useFilter } from '@/shared'\n\nexport interface AutocompleteRootProps extends PrimitiveProps {\n  /** The controlled value of the Autocomplete (the input text). Can be bound with `v-model`. */\n  modelValue?: string\n  /** The value of the autocomplete when initially rendered. Use when you do not need to control the state. */\n  defaultValue?: string\n  /** The controlled open state of the Autocomplete. Can be bound with `v-model:open`. */\n  open?: boolean\n  /** The open state of the autocomplete when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /** When `true`, prevents the user from interacting with autocomplete */\n  disabled?: boolean\n  /** The reading direction of the autocomplete when applicable. */\n  dir?: Direction\n  /** The name of the field. Submitted with its owning form as part of a name/value pair. */\n  name?: string\n  /** When `true`, indicates that the user must set the value before the owning form can be submitted. */\n  required?: boolean\n  /**\n   * Whether to reset the searchTerm when the Autocomplete input blurred\n   * @defaultValue `false`\n   */\n  resetSearchTermOnBlur?: boolean\n  /**\n   * Whether to open the autocomplete when the input is focused\n   * @defaultValue `false`\n   */\n  openOnFocus?: boolean\n  /**\n   * Whether to open the autocomplete when the input is clicked\n   * @defaultValue `false`\n   */\n  openOnClick?: boolean\n  /**\n   * When `true`, disable the default filters\n   */\n  ignoreFilter?: boolean\n  /** When `true`, hover over item will trigger highlight */\n  highlightOnHover?: boolean\n}\n\nexport type AutocompleteRootEmits = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: string]\n  /** Event handler when highlighted element changes. */\n  'highlight': [payload: { ref: HTMLElement, value: string } | undefined]\n  /** Event handler called when the open state of the autocomplete changes. */\n  'update:open': [value: boolean]\n}\n\nexport type AutocompleteRootContext = {\n  modelValue: Ref<string>\n}\n\nexport const [injectAutocompleteRootContext, provideAutocompleteRootContext]\n  = createContext<AutocompleteRootContext>('AutocompleteRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { createEventHook, useVModel } from '@vueuse/core'\nimport { computed, getCurrentInstance, nextTick, onMounted, ref, toRefs } from 'vue'\nimport { ListboxRoot } from '@/Listbox'\nimport { PopperRoot } from '@/Popper'\n\nconst props = withDefaults(defineProps<AutocompleteRootProps>(), {\n  open: undefined,\n  resetSearchTermOnBlur: false,\n  openOnFocus: false,\n  openOnClick: false,\n  highlightOnHover: true,\n})\nconst emits = defineEmits<AutocompleteRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n    /** Current active value */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { primitiveElement, currentElement: parentElement } = usePrimitiveElement<GenericComponentInstance<typeof ListboxRoot>>()\nconst { disabled, ignoreFilter, openOnFocus, openOnClick, dir: propDir, highlightOnHover } = toRefs(props)\n\nconst dir = useDirection(propDir)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? '',\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<string>\n\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\n// Writable computed that converts any value to string for the ComboboxRootContext.\n// This handles the case when ComboboxItem sets modelValue to a non-string value,\n// or when ComboboxCancel resets modelValue to null.\nconst contextModelValue = computed({\n  get: () => modelValue.value,\n  set: (val: any) => {\n    if (val === null || val === undefined) {\n      modelValue.value = ''\n    }\n    else {\n      modelValue.value = String(val)\n    }\n  },\n})\n\nasync function onOpenChange(val: boolean) {\n  open.value = val\n\n  if (val) {\n    // When opening, set filter to current text so items are filtered by what's in the input\n    filterSearch.value = modelValue.value || ''\n\n    await nextTick()\n    primitiveElement.value?.highlightSelected()\n    isUserInputted.value = true\n    inputElement.value?.focus()\n  }\n  else {\n    isUserInputted.value = false\n    filterSearch.value = ''\n    setTimeout(() => {\n      if (!val && props.resetSearchTermOnBlur)\n        resetSearchTerm.trigger()\n    }, 1)\n  }\n}\n\nconst resetSearchTerm = createEventHook()\nconst isUserInputted = ref(false)\nconst isVirtual = ref(false)\nconst inputElement = ref<HTMLInputElement>()\nconst triggerElement = ref<HTMLElement>()\n\nconst highlightedElement = computed(() => primitiveElement.value?.highlightedElement ?? undefined)\n\nconst allItems = ref<Map<string, string>>(new Map())\nconst allGroups = ref<Map<string, Set<string>>>(new Map())\n\nconst { contains } = useFilter({ sensitivity: 'base' })\n\nconst filterSearch = ref('')\n\nconst filterState = computed<{\n  count: number\n  items: Map<string, number>\n  groups: Set<string>\n}>((oldValue) => {\n  if (!filterSearch.value || props.ignoreFilter || isVirtual.value) {\n    return {\n      count: allItems.value.size,\n      items: oldValue?.items ?? new Map(),\n      groups: oldValue?.groups ?? new Set(allGroups.value.keys()),\n    }\n  }\n\n  let itemCount = 0\n  const filteredItems = new Map<string, number>()\n  const filteredGroups = new Set<string>()\n\n  for (const [id, value] of allItems.value) {\n    const score = contains(value, filterSearch.value)\n    filteredItems.set(id, score ? 1 : 0)\n    if (score)\n      itemCount++\n  }\n\n  for (const [groupId, group] of allGroups.value) {\n    for (const itemId of group) {\n      if (filteredItems.get(itemId)! > 0) {\n        filteredGroups.add(groupId)\n        break\n      }\n    }\n  }\n\n  return {\n    count: itemCount,\n    items: filteredItems,\n    groups: filteredGroups,\n  }\n})\n\nconst inst = getCurrentInstance()\nonMounted(() => {\n  if (inst?.exposed) {\n    inst.exposed.highlightItem = primitiveElement.value?.highlightItem\n    inst.exposed.highlightFirstItem = primitiveElement.value?.highlightFirstItem\n    inst.exposed.highlightSelected = primitiveElement.value?.highlightSelected\n  }\n})\n\ndefineExpose({\n  filtered: filterState,\n  highlightedElement,\n  highlightItem: primitiveElement.value?.highlightItem,\n  highlightFirstItem: primitiveElement.value?.highlightFirstItem,\n  highlightSelected: primitiveElement.value?.highlightSelected,\n})\n\n// Provide the Combobox context so all Combobox sub-components work inside Autocomplete\nprovideComboboxRootContext({\n  modelValue: contextModelValue as any,\n  multiple: ref(false),\n  disabled,\n  open,\n  onOpenChange,\n  contentId: '',\n  isUserInputted,\n  isVirtual,\n  inputElement,\n  highlightedElement,\n  onInputElementChange: val => inputElement.value = val,\n  triggerElement,\n  onTriggerElementChange: val => triggerElement.value = val,\n  parentElement,\n  resetSearchTermOnSelect: ref(false),\n  onResetSearchTerm: resetSearchTerm.on,\n  allItems,\n  allGroups,\n  filterSearch,\n  filterState,\n  ignoreFilter,\n  openOnFocus,\n  openOnClick,\n  resetModelValueOnClear: ref(true),\n})\n\n// Provide autocomplete-specific context\nprovideAutocompleteRootContext({\n  modelValue,\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <ListboxRoot\n      ref=\"primitiveElement\"\n      v-bind=\"$attrs\"\n      v-model=\"(contextModelValue as any)\"\n      :style=\"{\n        pointerEvents: open ? 'auto' : undefined,\n      }\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :dir=\"dir\"\n      :name=\"name\"\n      :required=\"required\"\n      :disabled=\"disabled\"\n      :highlight-on-hover=\"highlightOnHover\"\n      @highlight=\"emits('highlight', $event as any)\"\n    >\n      <slot\n        :open=\"open\"\n        :model-value=\"modelValue\"\n      />\n    </ListboxRoot>\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type { ListboxFilterEmits, ListboxFilterProps } from '@/Listbox'\n\nexport type AutocompleteInputEmits = ListboxFilterEmits\nexport interface AutocompleteInputProps extends ListboxFilterProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { nextTick, onMounted, watch } from 'vue'\nimport { injectComboboxRootContext } from '@/Combobox/ComboboxRoot.vue'\nimport { ListboxFilter } from '@/Listbox'\nimport { injectListboxRootContext } from '@/Listbox/ListboxRoot.vue'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { useComposing } from '@/shared'\nimport { injectAutocompleteRootContext } from './AutocompleteRoot.vue'\n\nconst props = withDefaults(defineProps<AutocompleteInputProps>(), {\n  as: 'input',\n})\nconst emits = defineEmits<AutocompleteInputEmits>()\n\nconst rootContext = injectComboboxRootContext()\nconst autocompleteContext = injectAutocompleteRootContext()\nconst listboxContext = injectListboxRootContext()\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  passive: (props.modelValue === undefined) as false,\n})\n\nif (autocompleteContext.modelValue.value) {\n  modelValue.value = autocompleteContext.modelValue.value\n}\n\nonMounted(() => {\n  if (currentElement.value)\n    rootContext.onInputElementChange(currentElement.value as HTMLInputElement)\n})\n\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing((event) => {\n  const el = event.target as HTMLInputElement\n  if (el)\n    processInputValue(el.value)\n})\n\nfunction handleKeyDown(ev: KeyboardEvent) {\n  // Don't swallow arrow keys mid-composition, they're used for IME candidate navigation\n  if (isComposing.value)\n    return\n  ev.preventDefault()\n  if (!rootContext.open.value)\n    rootContext.onOpenChange(true)\n}\n\nfunction processInputValue(value: string) {\n  if (!rootContext.open.value) {\n    rootContext.onOpenChange(true)\n    nextTick(() => {\n      if (value) {\n        rootContext.filterSearch.value = value\n        listboxContext.highlightFirstItem()\n      }\n    })\n  }\n  else {\n    rootContext.filterSearch.value = value\n  }\n  // Autocomplete-specific: update root's modelValue with the typed text\n  autocompleteContext.modelValue.value = value\n}\n\nfunction handleInput(event: InputEvent) {\n  if (isComposing.value)\n    return\n  processInputValue((event.target as HTMLInputElement).value)\n}\n\nfunction handleFocus() {\n  if (rootContext.openOnFocus.value && !rootContext.open.value)\n    rootContext.onOpenChange(true)\n}\n\nfunction handleClick() {\n  if (rootContext.openOnClick.value && !rootContext.open.value)\n    rootContext.onOpenChange(true)\n}\n\n// When root's modelValue changes externally (e.g. item click, programmatic), sync the input display\nwatch(autocompleteContext.modelValue, (newVal) => {\n  const text = newVal ?? ''\n  if (modelValue.value !== text)\n    modelValue.value = text\n})\n\n// Restore input text when root triggers resetSearchTerm (e.g. on blur with resetSearchTermOnBlur)\nrootContext.onResetSearchTerm(() => {\n  modelValue.value = autocompleteContext.modelValue.value ?? ''\n})\n\nwatch(rootContext.filterState, (_newValue, oldValue) => {\n  if (!rootContext.isVirtual.value && (oldValue.count === 0)) {\n    listboxContext.highlightFirstItem()\n  }\n})\n</script>\n\n<template>\n  <ListboxFilter\n    ref=\"primitiveElement\"\n    v-model=\"modelValue\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :auto-focus=\"autoFocus\"\n    :disabled=\"disabled\"\n    :aria-expanded=\"rootContext.open.value\"\n    :aria-controls=\"rootContext.contentId\"\n    aria-autocomplete=\"list\"\n    role=\"combobox\"\n    autocomplete=\"off\"\n    @click=\"handleClick\"\n    @input=\"handleInput\"\n    @keydown.down.up=\"handleKeyDown\"\n    @focus=\"handleFocus\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot />\n  </ListboxFilter>\n</template>\n","<script lang=\"ts\">\nimport type { ListboxFilterEmits, ListboxFilterProps } from '@/Listbox'\n\nexport type AutocompleteInputEmits = ListboxFilterEmits\nexport interface AutocompleteInputProps extends ListboxFilterProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { nextTick, onMounted, watch } from 'vue'\nimport { injectComboboxRootContext } from '@/Combobox/ComboboxRoot.vue'\nimport { ListboxFilter } from '@/Listbox'\nimport { injectListboxRootContext } from '@/Listbox/ListboxRoot.vue'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { useComposing } from '@/shared'\nimport { injectAutocompleteRootContext } from './AutocompleteRoot.vue'\n\nconst props = withDefaults(defineProps<AutocompleteInputProps>(), {\n  as: 'input',\n})\nconst emits = defineEmits<AutocompleteInputEmits>()\n\nconst rootContext = injectComboboxRootContext()\nconst autocompleteContext = injectAutocompleteRootContext()\nconst listboxContext = injectListboxRootContext()\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  passive: (props.modelValue === undefined) as false,\n})\n\nif (autocompleteContext.modelValue.value) {\n  modelValue.value = autocompleteContext.modelValue.value\n}\n\nonMounted(() => {\n  if (currentElement.value)\n    rootContext.onInputElementChange(currentElement.value as HTMLInputElement)\n})\n\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing((event) => {\n  const el = event.target as HTMLInputElement\n  if (el)\n    processInputValue(el.value)\n})\n\nfunction handleKeyDown(ev: KeyboardEvent) {\n  // Don't swallow arrow keys mid-composition, they're used for IME candidate navigation\n  if (isComposing.value)\n    return\n  ev.preventDefault()\n  if (!rootContext.open.value)\n    rootContext.onOpenChange(true)\n}\n\nfunction processInputValue(value: string) {\n  if (!rootContext.open.value) {\n    rootContext.onOpenChange(true)\n    nextTick(() => {\n      if (value) {\n        rootContext.filterSearch.value = value\n        listboxContext.highlightFirstItem()\n      }\n    })\n  }\n  else {\n    rootContext.filterSearch.value = value\n  }\n  // Autocomplete-specific: update root's modelValue with the typed text\n  autocompleteContext.modelValue.value = value\n}\n\nfunction handleInput(event: InputEvent) {\n  if (isComposing.value)\n    return\n  processInputValue((event.target as HTMLInputElement).value)\n}\n\nfunction handleFocus() {\n  if (rootContext.openOnFocus.value && !rootContext.open.value)\n    rootContext.onOpenChange(true)\n}\n\nfunction handleClick() {\n  if (rootContext.openOnClick.value && !rootContext.open.value)\n    rootContext.onOpenChange(true)\n}\n\n// When root's modelValue changes externally (e.g. item click, programmatic), sync the input display\nwatch(autocompleteContext.modelValue, (newVal) => {\n  const text = newVal ?? ''\n  if (modelValue.value !== text)\n    modelValue.value = text\n})\n\n// Restore input text when root triggers resetSearchTerm (e.g. on blur with resetSearchTermOnBlur)\nrootContext.onResetSearchTerm(() => {\n  modelValue.value = autocompleteContext.modelValue.value ?? ''\n})\n\nwatch(rootContext.filterState, (_newValue, oldValue) => {\n  if (!rootContext.isVirtual.value && (oldValue.count === 0)) {\n    listboxContext.highlightFirstItem()\n  }\n})\n</script>\n\n<template>\n  <ListboxFilter\n    ref=\"primitiveElement\"\n    v-model=\"modelValue\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :auto-focus=\"autoFocus\"\n    :disabled=\"disabled\"\n    :aria-expanded=\"rootContext.open.value\"\n    :aria-controls=\"rootContext.contentId\"\n    aria-autocomplete=\"list\"\n    role=\"combobox\"\n    autocomplete=\"off\"\n    @click=\"handleClick\"\n    @input=\"handleInput\"\n    @keydown.down.up=\"handleKeyDown\"\n    @focus=\"handleFocus\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot />\n  </ListboxFilter>\n</template>\n","<script lang=\"ts\">\nexport interface ComboboxAnchorProps extends PopperAnchorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport type { PopperAnchorProps } from '@/Popper'\nimport { PopperAnchor } from '@/Popper'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\ndefineProps<ComboboxAnchorProps>()\n\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <PopperAnchor\n    as-child\n    :reference=\"reference\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      v-bind=\"$attrs\"\n    >\n      <slot />\n    </Primitive>\n  </PopperAnchor>\n</template>\n","<script lang=\"ts\">\nexport interface ComboboxAnchorProps extends PopperAnchorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport type { PopperAnchorProps } from '@/Popper'\nimport { PopperAnchor } from '@/Popper'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\ndefineProps<ComboboxAnchorProps>()\n\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <PopperAnchor\n    as-child\n    :reference=\"reference\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      v-bind=\"$attrs\"\n    >\n      <slot />\n    </Primitive>\n  </PopperAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { DismissableLayerEmits, DismissableLayerProps } from '@/DismissableLayer'\nimport type { PopperContentProps } from '@/Popper'\n\nimport { createContext, getActiveElement, useFocusGuards, useForwardExpose, useForwardProps, useHideOthers } from '@/shared'\nimport { useBodyScrollLock } from '@/shared/useBodyScrollLock'\n\nexport type ComboboxContentImplEmits = DismissableLayerEmits\n\nexport interface ComboboxContentImplProps extends PopperContentProps, DismissableLayerProps {\n  /**\n   * The positioning mode to use, <br>\n   * `inline` is the default and you can control the position using CSS. <br>\n   * `popper` positions content in the same way as our other primitives, for example `Popover` or `DropdownMenu`.\n   */\n  position?: 'inline' | 'popper'\n  /** The document.body will be lock, and scrolling will be disabled. */\n  bodyLock?: boolean\n  /**\n   * When `true`, hides the content when there are no items matching the filter.\n   * @defaultValue false\n   */\n  hideWhenEmpty?: boolean\n}\n\nexport const [injectComboboxContentContext, provideComboboxContentContext]\n  = createContext<{\n    position: Ref<'inline' | 'popper'>\n  }>('ComboboxContent')\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted, onUnmounted, ref, toRefs } from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { FocusScope } from '@/FocusScope'\nimport { ListboxContent } from '@/Listbox'\nimport { PopperContent } from '@/Popper'\nimport { Primitive } from '@/Primitive'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = withDefaults(defineProps<ComboboxContentImplProps>(), {\n  position: 'inline',\n})\nconst emits = defineEmits<ComboboxContentImplEmits>()\n\nconst { position } = toRefs(props)\nconst rootContext = injectComboboxRootContext()\n\nconst isEmpty = computed(() => rootContext.ignoreFilter.value\n  ? rootContext.allItems.value.size === 0\n  : rootContext.filterState.value.count === 0,\n)\n\nconst { forwardRef, currentElement } = useForwardExpose()\nuseBodyScrollLock(props.bodyLock)\nuseFocusGuards()\nuseHideOthers(rootContext.parentElement)\n\nconst pickedProps = computed(() => {\n  if (props.position === 'popper')\n    return props\n  else return {}\n})\n\nconst forwardedProps = useForwardProps(pickedProps.value)\n\nconst popperStyle = {\n  // Ensure border-box for floating-ui calculations\n  'boxSizing': 'border-box',\n  '--reka-combobox-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n  '--reka-combobox-content-available-width':\n        'var(--reka-popper-available-width)',\n  '--reka-combobox-content-available-height':\n        'var(--reka-popper-available-height)',\n  '--reka-combobox-trigger-width': 'var(--reka-popper-anchor-width)',\n  '--reka-combobox-trigger-height': 'var(--reka-popper-anchor-height)',\n}\n\nprovideComboboxContentContext({ position })\n\n// Handle case where input position within the content\nconst isInputWithinContent = ref(false)\nonMounted(() => {\n  if (rootContext.inputElement.value) {\n    isInputWithinContent.value = currentElement.value.contains(rootContext.inputElement.value)\n    if (isInputWithinContent.value) {\n      rootContext.inputElement.value.focus()\n    }\n  }\n})\n\nonUnmounted(() => {\n  const activeElement = getActiveElement()\n  if (isInputWithinContent.value && (!activeElement || activeElement === document.body)) {\n    rootContext.triggerElement.value?.focus()\n  }\n})\n\nfunction isEventTargetWithinCombobox(target: EventTarget | null) {\n  if (rootContext.parentElement.value?.contains(target as Node))\n    return true\n\n  // A `<label>` associated (via `for`) with an element inside the combobox forwards its\n  // click/focus to that control, so interacting with it should not dismiss the content.\n  // Without this, clicking such a label while open dismisses on `pointerdown` and the\n  // forwarded click/focus immediately re-opens it.\n  const label = target instanceof Element ? target.closest('label') : null\n  const control = label?.control\n  return !!control && !!rootContext.parentElement.value?.contains(control)\n}\n</script>\n\n<template>\n  <ListboxContent as-child>\n    <FocusScope\n      as-child\n      @mount-auto-focus.prevent\n      @unmount-auto-focus.prevent\n    >\n      <DismissableLayer\n        as-child\n        :disable-outside-pointer-events=\"disableOutsidePointerEvents\"\n        @dismiss=\"rootContext.onOpenChange(false)\"\n        @focus-outside=\"(ev) => {\n          // if focusing inside the combobox (or a label tied to it), prevent dismiss\n          if (isEventTargetWithinCombobox(ev.target)) ev.preventDefault()\n          emits('focusOutside', ev)\n        }\"\n        @interact-outside=\"emits('interactOutside', $event)\"\n        @escape-key-down=\"emits('escapeKeyDown', $event)\"\n        @pointer-down-outside=\"(ev) => {\n          // if clicking inside the combobox (or a label tied to it), prevent dismiss\n          if (isEventTargetWithinCombobox(ev.target)) ev.preventDefault()\n          emits('pointerDownOutside', ev)\n        }\"\n      >\n        <component\n          :is=\"position === 'popper' ? PopperContent : Primitive\"\n          v-bind=\"{ ...$attrs, ...forwardedProps }\"\n          :id=\"rootContext.contentId\"\n          :ref=\"forwardRef\"\n          :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n          :data-empty=\"isEmpty ? '' : undefined\"\n          :style=\"{\n            // flex layout so we can place the scroll buttons properly\n            // When hideWhenEmpty is true, hide the content when no items match\n            display: (props.hideWhenEmpty && isEmpty) ? 'none' : 'flex',\n            flexDirection: 'column',\n            // reset the outline by default as the content MAY get focused\n            outline: 'none',\n            ...(position === 'popper' ? popperStyle : {}),\n          }\"\n        >\n          <slot />\n        </component>\n      </DismissableLayer>\n    </FocusScope>\n  </ListboxContent>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { DismissableLayerEmits, DismissableLayerProps } from '@/DismissableLayer'\nimport type { PopperContentProps } from '@/Popper'\n\nimport { createContext, getActiveElement, useFocusGuards, useForwardExpose, useForwardProps, useHideOthers } from '@/shared'\nimport { useBodyScrollLock } from '@/shared/useBodyScrollLock'\n\nexport type ComboboxContentImplEmits = DismissableLayerEmits\n\nexport interface ComboboxContentImplProps extends PopperContentProps, DismissableLayerProps {\n  /**\n   * The positioning mode to use, <br>\n   * `inline` is the default and you can control the position using CSS. <br>\n   * `popper` positions content in the same way as our other primitives, for example `Popover` or `DropdownMenu`.\n   */\n  position?: 'inline' | 'popper'\n  /** The document.body will be lock, and scrolling will be disabled. */\n  bodyLock?: boolean\n  /**\n   * When `true`, hides the content when there are no items matching the filter.\n   * @defaultValue false\n   */\n  hideWhenEmpty?: boolean\n}\n\nexport const [injectComboboxContentContext, provideComboboxContentContext]\n  = createContext<{\n    position: Ref<'inline' | 'popper'>\n  }>('ComboboxContent')\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted, onUnmounted, ref, toRefs } from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { FocusScope } from '@/FocusScope'\nimport { ListboxContent } from '@/Listbox'\nimport { PopperContent } from '@/Popper'\nimport { Primitive } from '@/Primitive'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = withDefaults(defineProps<ComboboxContentImplProps>(), {\n  position: 'inline',\n})\nconst emits = defineEmits<ComboboxContentImplEmits>()\n\nconst { position } = toRefs(props)\nconst rootContext = injectComboboxRootContext()\n\nconst isEmpty = computed(() => rootContext.ignoreFilter.value\n  ? rootContext.allItems.value.size === 0\n  : rootContext.filterState.value.count === 0,\n)\n\nconst { forwardRef, currentElement } = useForwardExpose()\nuseBodyScrollLock(props.bodyLock)\nuseFocusGuards()\nuseHideOthers(rootContext.parentElement)\n\nconst pickedProps = computed(() => {\n  if (props.position === 'popper')\n    return props\n  else return {}\n})\n\nconst forwardedProps = useForwardProps(pickedProps.value)\n\nconst popperStyle = {\n  // Ensure border-box for floating-ui calculations\n  'boxSizing': 'border-box',\n  '--reka-combobox-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n  '--reka-combobox-content-available-width':\n        'var(--reka-popper-available-width)',\n  '--reka-combobox-content-available-height':\n        'var(--reka-popper-available-height)',\n  '--reka-combobox-trigger-width': 'var(--reka-popper-anchor-width)',\n  '--reka-combobox-trigger-height': 'var(--reka-popper-anchor-height)',\n}\n\nprovideComboboxContentContext({ position })\n\n// Handle case where input position within the content\nconst isInputWithinContent = ref(false)\nonMounted(() => {\n  if (rootContext.inputElement.value) {\n    isInputWithinContent.value = currentElement.value.contains(rootContext.inputElement.value)\n    if (isInputWithinContent.value) {\n      rootContext.inputElement.value.focus()\n    }\n  }\n})\n\nonUnmounted(() => {\n  const activeElement = getActiveElement()\n  if (isInputWithinContent.value && (!activeElement || activeElement === document.body)) {\n    rootContext.triggerElement.value?.focus()\n  }\n})\n\nfunction isEventTargetWithinCombobox(target: EventTarget | null) {\n  if (rootContext.parentElement.value?.contains(target as Node))\n    return true\n\n  // A `<label>` associated (via `for`) with an element inside the combobox forwards its\n  // click/focus to that control, so interacting with it should not dismiss the content.\n  // Without this, clicking such a label while open dismisses on `pointerdown` and the\n  // forwarded click/focus immediately re-opens it.\n  const label = target instanceof Element ? target.closest('label') : null\n  const control = label?.control\n  return !!control && !!rootContext.parentElement.value?.contains(control)\n}\n</script>\n\n<template>\n  <ListboxContent as-child>\n    <FocusScope\n      as-child\n      @mount-auto-focus.prevent\n      @unmount-auto-focus.prevent\n    >\n      <DismissableLayer\n        as-child\n        :disable-outside-pointer-events=\"disableOutsidePointerEvents\"\n        @dismiss=\"rootContext.onOpenChange(false)\"\n        @focus-outside=\"(ev) => {\n          // if focusing inside the combobox (or a label tied to it), prevent dismiss\n          if (isEventTargetWithinCombobox(ev.target)) ev.preventDefault()\n          emits('focusOutside', ev)\n        }\"\n        @interact-outside=\"emits('interactOutside', $event)\"\n        @escape-key-down=\"emits('escapeKeyDown', $event)\"\n        @pointer-down-outside=\"(ev) => {\n          // if clicking inside the combobox (or a label tied to it), prevent dismiss\n          if (isEventTargetWithinCombobox(ev.target)) ev.preventDefault()\n          emits('pointerDownOutside', ev)\n        }\"\n      >\n        <component\n          :is=\"position === 'popper' ? PopperContent : Primitive\"\n          v-bind=\"{ ...$attrs, ...forwardedProps }\"\n          :id=\"rootContext.contentId\"\n          :ref=\"forwardRef\"\n          :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n          :data-empty=\"isEmpty ? '' : undefined\"\n          :style=\"{\n            // flex layout so we can place the scroll buttons properly\n            // When hideWhenEmpty is true, hide the content when no items match\n            display: (props.hideWhenEmpty && isEmpty) ? 'none' : 'flex',\n            flexDirection: 'column',\n            // reset the outline by default as the content MAY get focused\n            outline: 'none',\n            ...(position === 'popper' ? popperStyle : {}),\n          }\"\n        >\n          <slot />\n        </component>\n      </DismissableLayer>\n    </FocusScope>\n  </ListboxContent>\n</template>\n","<script lang=\"ts\">\nimport type { PopperArrowProps } from '@/Popper'\n\nexport interface ComboboxArrowProps extends PopperArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperArrow } from '@/Popper'\nimport { useForwardExpose } from '@/shared'\nimport { injectComboboxContentContext } from './ComboboxContentImpl.vue'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = withDefaults(defineProps<ComboboxArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nconst rootContext = injectComboboxRootContext()\nconst contentContext = injectComboboxContentContext()\n\nuseForwardExpose()\n</script>\n\n<template>\n  <PopperArrow\n    v-if=\"rootContext.open.value && contentContext.position.value === 'popper'\"\n    v-bind=\"props\"\n  >\n    <slot />\n  </PopperArrow>\n</template>\n","<script lang=\"ts\">\nimport type { PopperArrowProps } from '@/Popper'\n\nexport interface ComboboxArrowProps extends PopperArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperArrow } from '@/Popper'\nimport { useForwardExpose } from '@/shared'\nimport { injectComboboxContentContext } from './ComboboxContentImpl.vue'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = withDefaults(defineProps<ComboboxArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nconst rootContext = injectComboboxRootContext()\nconst contentContext = injectComboboxContentContext()\n\nuseForwardExpose()\n</script>\n\n<template>\n  <PopperArrow\n    v-if=\"rootContext.open.value && contentContext.position.value === 'popper'\"\n    v-bind=\"props\"\n  >\n    <slot />\n  </PopperArrow>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ComboboxCancelProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = withDefaults(defineProps<ComboboxCancelProps>(), {\n  as: 'button',\n})\n\nuseForwardExpose()\nconst rootContext = injectComboboxRootContext()\n\nfunction handleClick() {\n  // Reset the search to show all options.\n  rootContext.filterSearch.value = ''\n\n  if (rootContext.inputElement.value) {\n    rootContext.inputElement.value.value = ''\n    rootContext.inputElement.value.focus()\n  }\n\n  if (rootContext.resetModelValueOnClear?.value) {\n    rootContext.modelValue.value = rootContext.multiple.value ? [] : null\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    :type=\"as === 'button' ? 'button' : undefined\"\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    @click=\"handleClick\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ComboboxCancelProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = withDefaults(defineProps<ComboboxCancelProps>(), {\n  as: 'button',\n})\n\nuseForwardExpose()\nconst rootContext = injectComboboxRootContext()\n\nfunction handleClick() {\n  // Reset the search to show all options.\n  rootContext.filterSearch.value = ''\n\n  if (rootContext.inputElement.value) {\n    rootContext.inputElement.value.value = ''\n    rootContext.inputElement.value.focus()\n  }\n\n  if (rootContext.resetModelValueOnClear?.value) {\n    rootContext.modelValue.value = rootContext.multiple.value ? [] : null\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    :type=\"as === 'button' ? 'button' : undefined\"\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    @click=\"handleClick\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ComboboxContentImplEmits, ComboboxContentImplProps } from './ComboboxContentImpl.vue'\n\nexport type ComboboxContentEmits = ComboboxContentImplEmits\nexport interface ComboboxContentProps extends ComboboxContentImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardExpose, useForwardPropsEmits, useId } from '@/shared'\nimport ComboboxContentImpl from './ComboboxContentImpl.vue'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = defineProps<ComboboxContentProps>()\nconst emits = defineEmits<ComboboxContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nconst { forwardRef } = useForwardExpose()\n\nconst rootContext = injectComboboxRootContext()\n\nrootContext.contentId ||= useId(undefined, 'reka-combobox-content')\n</script>\n\n<template>\n  <Presence :present=\"forceMount || rootContext.open.value\">\n    <ComboboxContentImpl\n      v-bind=\"{ ...forwarded, ...$attrs }\"\n      :ref=\"forwardRef\"\n    >\n      <slot />\n    </ComboboxContentImpl>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { ComboboxContentImplEmits, ComboboxContentImplProps } from './ComboboxContentImpl.vue'\n\nexport type ComboboxContentEmits = ComboboxContentImplEmits\nexport interface ComboboxContentProps extends ComboboxContentImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardExpose, useForwardPropsEmits, useId } from '@/shared'\nimport ComboboxContentImpl from './ComboboxContentImpl.vue'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = defineProps<ComboboxContentProps>()\nconst emits = defineEmits<ComboboxContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nconst { forwardRef } = useForwardExpose()\n\nconst rootContext = injectComboboxRootContext()\n\nrootContext.contentId ||= useId(undefined, 'reka-combobox-content')\n</script>\n\n<template>\n  <Presence :present=\"forceMount || rootContext.open.value\">\n    <ComboboxContentImpl\n      v-bind=\"{ ...forwarded, ...$attrs }\"\n      :ref=\"forwardRef\"\n    >\n      <slot />\n    </ComboboxContentImpl>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed } from 'vue'\n\nexport interface ComboboxEmptyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = defineProps<ComboboxEmptyProps>()\nconst rootContext = injectComboboxRootContext()\n\nconst isRender = computed(() => rootContext.ignoreFilter.value\n  ? rootContext.allItems.value.size === 0\n  : rootContext.filterState.value.count === 0,\n)\n</script>\n\n<template>\n  <Primitive\n    v-if=\"isRender\"\n    v-bind=\"props\"\n  >\n    <slot>No options</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed } from 'vue'\n\nexport interface ComboboxEmptyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = defineProps<ComboboxEmptyProps>()\nconst rootContext = injectComboboxRootContext()\n\nconst isRender = computed(() => rootContext.ignoreFilter.value\n  ? rootContext.allItems.value.size === 0\n  : rootContext.filterState.value.count === 0,\n)\n</script>\n\n<template>\n  <Primitive\n    v-if=\"isRender\"\n    v-bind=\"props\"\n  >\n    <slot>No options</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ListboxGroupProps } from '@/Listbox'\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { createContext, useId } from '@/shared'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nexport interface ComboboxGroupProps extends ListboxGroupProps {}\n\ntype ComboboxGroupContext = {\n  id: string\n  labelId: string\n}\n\nexport const [injectComboboxGroupContext, provideComboboxGroupContext]\n  = createContext<ComboboxGroupContext>('ComboboxGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport { ListboxGroup } from '@/Listbox'\n\nconst props = defineProps<ComboboxGroupProps>()\nconst id = useId(undefined, 'reka-combobox-group')\nconst rootContext = injectComboboxRootContext()\n\nconst isRender = computed(() => rootContext.ignoreFilter.value ? true : !rootContext.filterSearch.value ? true : rootContext.filterState.value.groups.has(id))\n\nconst context = provideComboboxGroupContext({\n  id,\n  labelId: '',\n})\n\nonMounted(() => {\n  if (!rootContext.allGroups.value.has(id))\n    rootContext.allGroups.value.set(id, new Set())\n})\nonUnmounted(() => {\n  rootContext.allGroups.value.delete(id)\n})\n</script>\n\n<template>\n  <ListboxGroup\n    :id=\"id\"\n    :aria-labelledby=\"context.labelId\"\n    v-bind=\"props\"\n    :hidden=\"isRender ? undefined : true\"\n  >\n    <slot />\n  </ListboxGroup>\n</template>\n","<script lang=\"ts\">\nimport type { ListboxGroupProps } from '@/Listbox'\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { createContext, useId } from '@/shared'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nexport interface ComboboxGroupProps extends ListboxGroupProps {}\n\ntype ComboboxGroupContext = {\n  id: string\n  labelId: string\n}\n\nexport const [injectComboboxGroupContext, provideComboboxGroupContext]\n  = createContext<ComboboxGroupContext>('ComboboxGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport { ListboxGroup } from '@/Listbox'\n\nconst props = defineProps<ComboboxGroupProps>()\nconst id = useId(undefined, 'reka-combobox-group')\nconst rootContext = injectComboboxRootContext()\n\nconst isRender = computed(() => rootContext.ignoreFilter.value ? true : !rootContext.filterSearch.value ? true : rootContext.filterState.value.groups.has(id))\n\nconst context = provideComboboxGroupContext({\n  id,\n  labelId: '',\n})\n\nonMounted(() => {\n  if (!rootContext.allGroups.value.has(id))\n    rootContext.allGroups.value.set(id, new Set())\n})\nonUnmounted(() => {\n  rootContext.allGroups.value.delete(id)\n})\n</script>\n\n<template>\n  <ListboxGroup\n    :id=\"id\"\n    :aria-labelledby=\"context.labelId\"\n    v-bind=\"props\"\n    :hidden=\"isRender ? undefined : true\"\n  >\n    <slot />\n  </ListboxGroup>\n</template>\n","<script lang=\"ts\">\nimport type { ListboxFilterEmits, ListboxFilterProps } from '@/Listbox'\nimport { useVModel } from '@vueuse/core'\nimport { nextTick, onMounted, watch } from 'vue'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { useComposing } from '@/shared'\n\nexport type ComboboxInputEmits = ListboxFilterEmits\nexport interface ComboboxInputProps extends ListboxFilterProps {\n  /** The display value of input for selected item. Does not work with `multiple`. */\n  displayValue?: (val: any) => string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { ListboxFilter } from '@/Listbox'\nimport { injectListboxRootContext } from '@/Listbox/ListboxRoot.vue'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = withDefaults(defineProps<ComboboxInputProps>(), {\n  as: 'input',\n})\nconst emits = defineEmits<ComboboxInputEmits>()\n\nconst rootContext = injectComboboxRootContext()\nconst listboxContext = injectListboxRootContext()\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  passive: (props.modelValue === undefined) as false,\n})\n\nonMounted(() => {\n  if (currentElement.value)\n    rootContext.onInputElementChange(currentElement.value as HTMLInputElement)\n})\n\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing((event) => {\n  const el = event.target as HTMLInputElement\n  if (el)\n    processInputValue(el.value)\n})\n\nfunction handleKeyDown(ev: KeyboardEvent) {\n  // Don't swallow arrow keys mid-composition, they're used for IME candidate navigation\n  if (isComposing.value)\n    return\n  ev.preventDefault()\n  if (!rootContext.open.value)\n    rootContext.onOpenChange(true)\n}\n\nfunction processInputValue(value: string) {\n  if (!rootContext.open.value) {\n    rootContext.onOpenChange(true)\n    nextTick(() => {\n      if (value) {\n        rootContext.filterSearch.value = value\n        listboxContext.highlightFirstItem()\n      }\n    })\n  }\n  else {\n    rootContext.filterSearch.value = value\n  }\n}\n\nfunction handleInput(event: InputEvent) {\n  if (isComposing.value)\n    return\n  processInputValue((event.target as HTMLInputElement).value)\n}\n\nfunction handleFocus() {\n  if (rootContext.openOnFocus.value && !rootContext.open.value)\n    rootContext.onOpenChange(true)\n}\n\nfunction handleBlur(ev: FocusEvent) {\n  if (!rootContext.open.value)\n    return\n\n  const nextFocus = ev.relatedTarget as Element | null\n\n  // If focus moves to nothing (e.g. click on non-focusable area), let DismissableLayer handle it\n  if (!nextFocus)\n    return\n\n  const isInsideRoot = rootContext.parentElement.value?.contains(nextFocus)\n  const isInsideContent = document.getElementById(rootContext.contentId)?.contains(nextFocus)\n\n  if (!isInsideRoot && !isInsideContent) {\n    // Delay to let FocusScope's focus-restoration (handleFocusOut) run first.\n    // Without this, closing fires before FocusScope can pull focus back inside,\n    // causing a second combobox to immediately close when switching between two.\n    requestAnimationFrame(() => {\n      if (!rootContext.open.value)\n        return\n      const active = document.activeElement\n      const isStillOutside = !rootContext.parentElement.value?.contains(active)\n        && !document.getElementById(rootContext.contentId)?.contains(active)\n      if (isStillOutside) {\n        rootContext.onOpenChange(false)\n      }\n    })\n  }\n}\n\nfunction handleClick() {\n  if (rootContext.openOnClick.value && !rootContext.open.value)\n    rootContext.onOpenChange(true)\n}\n\nfunction resetSearchTerm() {\n  const rootModelValue = rootContext.modelValue.value\n\n  if (props.displayValue) {\n    modelValue.value = props.displayValue(rootModelValue)\n  }\n  else if (!rootContext.multiple.value && rootModelValue && !Array.isArray(rootModelValue)) {\n    if (typeof rootModelValue !== 'object')\n      modelValue.value = rootModelValue.toString()\n    else modelValue.value = ''\n  }\n  else {\n    modelValue.value = ''\n  }\n\n  nextTick(() => {\n    // Temporary force reassign\n    // eslint-disable-next-line no-self-assign\n    modelValue.value = modelValue.value\n  })\n}\n\nrootContext.onResetSearchTerm(() => {\n  resetSearchTerm()\n})\n\nwatch(rootContext.modelValue, async () => {\n  if (!rootContext.isUserInputted.value && rootContext.resetSearchTermOnSelect.value)\n    resetSearchTerm()\n}, { immediate: true, deep: true })\n\nwatch(rootContext.filterState, (_newValue, oldValue) => {\n  // we exclude virtualized list as the state would be constantly updated,\n  // and only change highlight when previously there were no items displayed\n  if (!rootContext.isVirtual.value && (oldValue.count === 0)) {\n    listboxContext.highlightFirstItem()\n  }\n})\n</script>\n\n<template>\n  <ListboxFilter\n    ref=\"primitiveElement\"\n    v-model=\"modelValue\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :auto-focus=\"autoFocus\"\n    :disabled=\"disabled\"\n    :aria-expanded=\"rootContext.open.value\"\n    :aria-controls=\"rootContext.contentId\"\n    aria-autocomplete=\"list\"\n    role=\"combobox\"\n    autocomplete=\"off\"\n    @click=\"handleClick\"\n    @input=\"handleInput\"\n    @keydown.down.up=\"handleKeyDown\"\n    @focus=\"handleFocus\"\n    @blur=\"handleBlur\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot />\n  </ListboxFilter>\n</template>\n","<script lang=\"ts\">\nimport type { ListboxFilterEmits, ListboxFilterProps } from '@/Listbox'\nimport { useVModel } from '@vueuse/core'\nimport { nextTick, onMounted, watch } from 'vue'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { useComposing } from '@/shared'\n\nexport type ComboboxInputEmits = ListboxFilterEmits\nexport interface ComboboxInputProps extends ListboxFilterProps {\n  /** The display value of input for selected item. Does not work with `multiple`. */\n  displayValue?: (val: any) => string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { ListboxFilter } from '@/Listbox'\nimport { injectListboxRootContext } from '@/Listbox/ListboxRoot.vue'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = withDefaults(defineProps<ComboboxInputProps>(), {\n  as: 'input',\n})\nconst emits = defineEmits<ComboboxInputEmits>()\n\nconst rootContext = injectComboboxRootContext()\nconst listboxContext = injectListboxRootContext()\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  passive: (props.modelValue === undefined) as false,\n})\n\nonMounted(() => {\n  if (currentElement.value)\n    rootContext.onInputElementChange(currentElement.value as HTMLInputElement)\n})\n\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing((event) => {\n  const el = event.target as HTMLInputElement\n  if (el)\n    processInputValue(el.value)\n})\n\nfunction handleKeyDown(ev: KeyboardEvent) {\n  // Don't swallow arrow keys mid-composition, they're used for IME candidate navigation\n  if (isComposing.value)\n    return\n  ev.preventDefault()\n  if (!rootContext.open.value)\n    rootContext.onOpenChange(true)\n}\n\nfunction processInputValue(value: string) {\n  if (!rootContext.open.value) {\n    rootContext.onOpenChange(true)\n    nextTick(() => {\n      if (value) {\n        rootContext.filterSearch.value = value\n        listboxContext.highlightFirstItem()\n      }\n    })\n  }\n  else {\n    rootContext.filterSearch.value = value\n  }\n}\n\nfunction handleInput(event: InputEvent) {\n  if (isComposing.value)\n    return\n  processInputValue((event.target as HTMLInputElement).value)\n}\n\nfunction handleFocus() {\n  if (rootContext.openOnFocus.value && !rootContext.open.value)\n    rootContext.onOpenChange(true)\n}\n\nfunction handleBlur(ev: FocusEvent) {\n  if (!rootContext.open.value)\n    return\n\n  const nextFocus = ev.relatedTarget as Element | null\n\n  // If focus moves to nothing (e.g. click on non-focusable area), let DismissableLayer handle it\n  if (!nextFocus)\n    return\n\n  const isInsideRoot = rootContext.parentElement.value?.contains(nextFocus)\n  const isInsideContent = document.getElementById(rootContext.contentId)?.contains(nextFocus)\n\n  if (!isInsideRoot && !isInsideContent) {\n    // Delay to let FocusScope's focus-restoration (handleFocusOut) run first.\n    // Without this, closing fires before FocusScope can pull focus back inside,\n    // causing a second combobox to immediately close when switching between two.\n    requestAnimationFrame(() => {\n      if (!rootContext.open.value)\n        return\n      const active = document.activeElement\n      const isStillOutside = !rootContext.parentElement.value?.contains(active)\n        && !document.getElementById(rootContext.contentId)?.contains(active)\n      if (isStillOutside) {\n        rootContext.onOpenChange(false)\n      }\n    })\n  }\n}\n\nfunction handleClick() {\n  if (rootContext.openOnClick.value && !rootContext.open.value)\n    rootContext.onOpenChange(true)\n}\n\nfunction resetSearchTerm() {\n  const rootModelValue = rootContext.modelValue.value\n\n  if (props.displayValue) {\n    modelValue.value = props.displayValue(rootModelValue)\n  }\n  else if (!rootContext.multiple.value && rootModelValue && !Array.isArray(rootModelValue)) {\n    if (typeof rootModelValue !== 'object')\n      modelValue.value = rootModelValue.toString()\n    else modelValue.value = ''\n  }\n  else {\n    modelValue.value = ''\n  }\n\n  nextTick(() => {\n    // Temporary force reassign\n    // eslint-disable-next-line no-self-assign\n    modelValue.value = modelValue.value\n  })\n}\n\nrootContext.onResetSearchTerm(() => {\n  resetSearchTerm()\n})\n\nwatch(rootContext.modelValue, async () => {\n  if (!rootContext.isUserInputted.value && rootContext.resetSearchTermOnSelect.value)\n    resetSearchTerm()\n}, { immediate: true, deep: true })\n\nwatch(rootContext.filterState, (_newValue, oldValue) => {\n  // we exclude virtualized list as the state would be constantly updated,\n  // and only change highlight when previously there were no items displayed\n  if (!rootContext.isVirtual.value && (oldValue.count === 0)) {\n    listboxContext.highlightFirstItem()\n  }\n})\n</script>\n\n<template>\n  <ListboxFilter\n    ref=\"primitiveElement\"\n    v-model=\"modelValue\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :auto-focus=\"autoFocus\"\n    :disabled=\"disabled\"\n    :aria-expanded=\"rootContext.open.value\"\n    :aria-controls=\"rootContext.contentId\"\n    aria-autocomplete=\"list\"\n    role=\"combobox\"\n    autocomplete=\"off\"\n    @click=\"handleClick\"\n    @input=\"handleInput\"\n    @keydown.down.up=\"handleKeyDown\"\n    @focus=\"handleFocus\"\n    @blur=\"handleBlur\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot />\n  </ListboxFilter>\n</template>\n","<script lang=\"ts\">\nimport type { ListboxItemEmits, ListboxItemProps } from '@/Listbox'\nimport type { AcceptableValue } from '@/shared/types'\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { useId } from '@/shared'\nimport { injectComboboxGroupContext } from './ComboboxGroup.vue'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nexport { injectListboxItemContext as injectComboboxItemContext } from '@/Listbox'\n\nexport type ComboboxItemEmits<T = AcceptableValue> = ListboxItemEmits<T>\nexport interface ComboboxItemProps<T = AcceptableValue> extends ListboxItemProps<T> {\n  /**\n   * A string representation of the item contents.\n   *\n   * If the children are not plain text, then the `textValue` prop must also be set to a plain text representation, which will be used for autocomplete in the ComboBox.\n   */\n  textValue?: string\n}\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport { ListboxItem } from '@/Listbox'\n\nconst props = defineProps<ComboboxItemProps<T>>()\nconst emits = defineEmits<ComboboxItemEmits<T>>()\n\nconst id = useId(undefined, 'reka-combobox-item')\nconst rootContext = injectComboboxRootContext()\nconst groupContext = injectComboboxGroupContext(null)\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nif (props.value === '') {\n  throw new Error(\n    'A <ComboboxItem /> must have a value prop that is not an empty string. This is because the Combobox value can be set to an empty string to clear the selection and show the placeholder.',\n  )\n}\n\nconst isRender = computed(() => {\n  if (rootContext.isVirtual.value || rootContext.ignoreFilter.value || !rootContext.filterSearch.value) {\n    return true\n  }\n  else {\n    const filteredCurrentItem = rootContext.filterState.value.items.get(id)\n    // If the filtered items is undefined means not in the all times map yet\n    // Do the first render to add into the map\n    if (filteredCurrentItem === undefined) {\n      return true\n    }\n\n    // Check with filter\n    return filteredCurrentItem > 0\n  }\n})\n\nonMounted(() => {\n  // textValue to perform filter\n  rootContext.allItems.value.set(id, props.textValue || currentElement.value.textContent || currentElement.value.innerText)\n\n  const groupId = groupContext?.id\n  if (groupId) {\n    if (!rootContext.allGroups.value.has(groupId)) {\n      rootContext.allGroups.value.set(groupId, new Set([id]))\n    }\n    else {\n      rootContext.allGroups.value.get(groupId)?.add(id)\n    }\n  }\n})\nonUnmounted(() => {\n  rootContext.allItems.value.delete(id)\n})\n</script>\n\n<template>\n  <ListboxItem\n    v-if=\"isRender\"\n    v-bind=\"props\"\n    :id=\"id\"\n    ref=\"primitiveElement\"\n    :disabled=\"rootContext.disabled.value || disabled\"\n    @select=\"(event) => {\n      emits('select', event as any)\n      if (event.defaultPrevented)\n        return\n\n      if (!rootContext.multiple.value && !disabled && !rootContext.disabled.value) {\n        event.preventDefault()\n        rootContext.onOpenChange(false)\n        rootContext.modelValue.value = props.value\n      }\n      else if (rootContext.multiple.value) {\n        rootContext.inputElement.value?.focus()\n      }\n    }\"\n  >\n    <slot>{{ value }}</slot>\n  </ListboxItem>\n</template>\n","<script lang=\"ts\">\nimport type { ListboxItemEmits, ListboxItemProps } from '@/Listbox'\nimport type { AcceptableValue } from '@/shared/types'\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { usePrimitiveElement } from '@/Primitive'\nimport { useId } from '@/shared'\nimport { injectComboboxGroupContext } from './ComboboxGroup.vue'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nexport { injectListboxItemContext as injectComboboxItemContext } from '@/Listbox'\n\nexport type ComboboxItemEmits<T = AcceptableValue> = ListboxItemEmits<T>\nexport interface ComboboxItemProps<T = AcceptableValue> extends ListboxItemProps<T> {\n  /**\n   * A string representation of the item contents.\n   *\n   * If the children are not plain text, then the `textValue` prop must also be set to a plain text representation, which will be used for autocomplete in the ComboBox.\n   */\n  textValue?: string\n}\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport { ListboxItem } from '@/Listbox'\n\nconst props = defineProps<ComboboxItemProps<T>>()\nconst emits = defineEmits<ComboboxItemEmits<T>>()\n\nconst id = useId(undefined, 'reka-combobox-item')\nconst rootContext = injectComboboxRootContext()\nconst groupContext = injectComboboxGroupContext(null)\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nif (props.value === '') {\n  throw new Error(\n    'A <ComboboxItem /> must have a value prop that is not an empty string. This is because the Combobox value can be set to an empty string to clear the selection and show the placeholder.',\n  )\n}\n\nconst isRender = computed(() => {\n  if (rootContext.isVirtual.value || rootContext.ignoreFilter.value || !rootContext.filterSearch.value) {\n    return true\n  }\n  else {\n    const filteredCurrentItem = rootContext.filterState.value.items.get(id)\n    // If the filtered items is undefined means not in the all times map yet\n    // Do the first render to add into the map\n    if (filteredCurrentItem === undefined) {\n      return true\n    }\n\n    // Check with filter\n    return filteredCurrentItem > 0\n  }\n})\n\nonMounted(() => {\n  // textValue to perform filter\n  rootContext.allItems.value.set(id, props.textValue || currentElement.value.textContent || currentElement.value.innerText)\n\n  const groupId = groupContext?.id\n  if (groupId) {\n    if (!rootContext.allGroups.value.has(groupId)) {\n      rootContext.allGroups.value.set(groupId, new Set([id]))\n    }\n    else {\n      rootContext.allGroups.value.get(groupId)?.add(id)\n    }\n  }\n})\nonUnmounted(() => {\n  rootContext.allItems.value.delete(id)\n})\n</script>\n\n<template>\n  <ListboxItem\n    v-if=\"isRender\"\n    v-bind=\"props\"\n    :id=\"id\"\n    ref=\"primitiveElement\"\n    :disabled=\"rootContext.disabled.value || disabled\"\n    @select=\"(event) => {\n      emits('select', event as any)\n      if (event.defaultPrevented)\n        return\n\n      if (!rootContext.multiple.value && !disabled && !rootContext.disabled.value) {\n        event.preventDefault()\n        rootContext.onOpenChange(false)\n        rootContext.modelValue.value = props.value\n      }\n      else if (rootContext.multiple.value) {\n        rootContext.inputElement.value?.focus()\n      }\n    }\"\n  >\n    <slot>{{ value }}</slot>\n  </ListboxItem>\n</template>\n","<script lang=\"ts\">\nimport type { ListboxItemIndicatorProps } from '@/Listbox'\n\nexport interface ComboboxItemIndicatorProps extends ListboxItemIndicatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ListboxItemIndicator } from '@/Listbox'\n\nconst props = withDefaults(defineProps<ComboboxItemIndicatorProps>(), {\n  as: 'span',\n})\n</script>\n\n<template>\n  <ListboxItemIndicator\n    v-bind=\"props\"\n  >\n    <slot />\n  </ListboxItemIndicator>\n</template>\n","<script lang=\"ts\">\nimport type { ListboxItemIndicatorProps } from '@/Listbox'\n\nexport interface ComboboxItemIndicatorProps extends ListboxItemIndicatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ListboxItemIndicator } from '@/Listbox'\n\nconst props = withDefaults(defineProps<ComboboxItemIndicatorProps>(), {\n  as: 'span',\n})\n</script>\n\n<template>\n  <ListboxItemIndicator\n    v-bind=\"props\"\n  >\n    <slot />\n  </ListboxItemIndicator>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ComboboxLabelProps extends PrimitiveProps {\n  for?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose, useId } from '@/shared'\nimport { injectComboboxGroupContext } from './ComboboxGroup.vue'\n\nconst props = withDefaults(defineProps<ComboboxLabelProps>(), {\n  as: 'div',\n})\n\nuseForwardExpose()\nconst groupContext = injectComboboxGroupContext({ id: '', labelId: '' })\n\ngroupContext.labelId ||= useId(undefined, 'reka-combobox-group-label')\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"groupContext.labelId\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ComboboxLabelProps extends PrimitiveProps {\n  for?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose, useId } from '@/shared'\nimport { injectComboboxGroupContext } from './ComboboxGroup.vue'\n\nconst props = withDefaults(defineProps<ComboboxLabelProps>(), {\n  as: 'div',\n})\n\nuseForwardExpose()\nconst groupContext = injectComboboxGroupContext({ id: '', labelId: '' })\n\ngroupContext.labelId ||= useId(undefined, 'reka-combobox-group-label')\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"groupContext.labelId\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface ComboboxPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<ComboboxPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface ComboboxPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<ComboboxPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ComboboxSeparatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<ComboboxSeparatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-hidden=\"true\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ComboboxSeparatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<ComboboxSeparatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-hidden=\"true\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ComboboxTriggerProps extends PrimitiveProps {\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = withDefaults(defineProps<ComboboxTriggerProps>(), {\n  as: 'button',\n})\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst rootContext = injectComboboxRootContext()\nconst disabled = computed(() => props.disabled || rootContext.disabled.value || false)\n\nonMounted(() => {\n  if (currentElement.value)\n    rootContext.onTriggerElementChange(currentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :ref=\"forwardRef\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    tabindex=\"-1\"\n    aria-label=\"Show popup\"\n    aria-haspopup=\"listbox\"\n    :aria-expanded=\"rootContext.open.value\"\n    :aria-controls=\"rootContext.contentId\"\n    :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n    :disabled=\"disabled\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :aria-disabled=\"disabled ?? undefined\"\n    @click=\"rootContext.onOpenChange(!rootContext.open.value)\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ComboboxTriggerProps extends PrimitiveProps {\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = withDefaults(defineProps<ComboboxTriggerProps>(), {\n  as: 'button',\n})\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst rootContext = injectComboboxRootContext()\nconst disabled = computed(() => props.disabled || rootContext.disabled.value || false)\n\nonMounted(() => {\n  if (currentElement.value)\n    rootContext.onTriggerElementChange(currentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :ref=\"forwardRef\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    tabindex=\"-1\"\n    aria-label=\"Show popup\"\n    aria-haspopup=\"listbox\"\n    :aria-expanded=\"rootContext.open.value\"\n    :aria-controls=\"rootContext.contentId\"\n    :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n    :disabled=\"disabled\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :aria-disabled=\"disabled ?? undefined\"\n    @click=\"rootContext.onOpenChange(!rootContext.open.value)\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","import type { Ref } from 'vue'\nimport { computed, ref } from 'vue'\nimport { injectConfigProviderContext } from '@/ConfigProvider/ConfigProvider.vue'\n\nexport function useNonce(nonce?: Ref<string | undefined>) {\n  const context = injectConfigProviderContext({\n    nonce: ref(),\n  })\n  return computed(() => nonce?.value || context.nonce?.value)\n}\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { toRefs } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport { useNonce } from '@/shared/useNonce'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nexport interface ComboboxViewportProps extends PrimitiveProps {\n  /**\n   * Will add `nonce` attribute to the style tag which can be used by Content Security Policy. <br> If omitted, inherits globally from `ConfigProvider`.\n   */\n  nonce?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<ComboboxViewportProps>()\nconst { forwardRef } = useForwardExpose()\n\nconst { nonce: propNonce } = toRefs(props)\nconst nonce = useNonce(propNonce)\n\nconst rootContext = injectComboboxRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"{ ...$attrs, ...props }\"\n    :ref=\"forwardRef\"\n    data-reka-combobox-viewport\n    role=\"presentation\"\n    :style=\"{\n      // we use position: 'relative' here on the `viewport` so that when we call\n      // `selectedItem.offsetTop` in calculations, the offset is relative to the viewport\n      // (independent of the scrollUpButton).\n      position: 'relative',\n      flex: rootContext.isVirtual.value ? undefined : 1,\n      overflow: 'auto',\n    }\"\n  >\n    <slot />\n  </Primitive>\n  <Primitive\n    as=\"style\"\n    :nonce=\"nonce\"\n  >\n    /* Hide scrollbars cross-browser and enable momentum scroll for touch\n    devices */ [data-reka-combobox-viewport] { scrollbar-width:none; -ms-overflow-style: none;\n    -webkit-overflow-scrolling: touch; }\n    [data-reka-combobox-viewport]::-webkit-scrollbar { display: none; }\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { toRefs } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport { useNonce } from '@/shared/useNonce'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nexport interface ComboboxViewportProps extends PrimitiveProps {\n  /**\n   * Will add `nonce` attribute to the style tag which can be used by Content Security Policy. <br> If omitted, inherits globally from `ConfigProvider`.\n   */\n  nonce?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<ComboboxViewportProps>()\nconst { forwardRef } = useForwardExpose()\n\nconst { nonce: propNonce } = toRefs(props)\nconst nonce = useNonce(propNonce)\n\nconst rootContext = injectComboboxRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"{ ...$attrs, ...props }\"\n    :ref=\"forwardRef\"\n    data-reka-combobox-viewport\n    role=\"presentation\"\n    :style=\"{\n      // we use position: 'relative' here on the `viewport` so that when we call\n      // `selectedItem.offsetTop` in calculations, the offset is relative to the viewport\n      // (independent of the scrollUpButton).\n      position: 'relative',\n      flex: rootContext.isVirtual.value ? undefined : 1,\n      overflow: 'auto',\n    }\"\n  >\n    <slot />\n  </Primitive>\n  <Primitive\n    as=\"style\"\n    :nonce=\"nonce\"\n  >\n    /* Hide scrollbars cross-browser and enable momentum scroll for touch\n    devices */ [data-reka-combobox-viewport] { scrollbar-width:none; -ms-overflow-style: none;\n    -webkit-overflow-scrolling: touch; }\n    [data-reka-combobox-viewport]::-webkit-scrollbar { display: none; }\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nexport interface ComboboxVirtualizerProps<T extends AcceptableValue = AcceptableValue> extends ListboxVirtualizerProps<T> {}\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport type { VirtualItem, Virtualizer } from '@tanstack/vue-virtual'\nimport type { ListboxVirtualizerProps } from '@/Listbox/ListboxVirtualizer.vue'\nimport type { AcceptableValue } from '@/shared/types'\nimport ListboxVirtualizer from '@/Listbox/ListboxVirtualizer.vue'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = defineProps<ComboboxVirtualizerProps<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    option: T\n    virtualizer: Virtualizer<HTMLElement, Element>\n    virtualItem: VirtualItem\n  }) => any\n}>()\n\nconst rootContext = injectComboboxRootContext()\n// set virtual true when this component mounted\nrootContext.isVirtual.value = true\n</script>\n\n<template>\n  <ListboxVirtualizer\n    v-slot=\"slotProps\"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </ListboxVirtualizer>\n</template>\n","<script lang=\"ts\">\nexport interface ComboboxVirtualizerProps<T extends AcceptableValue = AcceptableValue> extends ListboxVirtualizerProps<T> {}\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport type { VirtualItem, Virtualizer } from '@tanstack/vue-virtual'\nimport type { ListboxVirtualizerProps } from '@/Listbox/ListboxVirtualizer.vue'\nimport type { AcceptableValue } from '@/shared/types'\nimport ListboxVirtualizer from '@/Listbox/ListboxVirtualizer.vue'\nimport { injectComboboxRootContext } from './ComboboxRoot.vue'\n\nconst props = defineProps<ComboboxVirtualizerProps<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    option: T\n    virtualizer: Virtualizer<HTMLElement, Element>\n    virtualItem: VirtualItem\n  }) => any\n}>()\n\nconst rootContext = injectComboboxRootContext()\n// set virtual true when this component mounted\nrootContext.isVirtual.value = true\n</script>\n\n<template>\n  <ListboxVirtualizer\n    v-slot=\"slotProps\"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </ListboxVirtualizer>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { ImageLoadingStatus } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface AvatarRootProps extends PrimitiveProps {}\n\nexport type AvatarRootContext = {\n  imageLoadingStatus: Ref<ImageLoadingStatus>\n}\n\nexport const [injectAvatarRootContext, provideAvatarRootContext]\n  = createContext<AvatarRootContext>('AvatarRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nwithDefaults(defineProps<AvatarRootProps>(), {\n  as: 'span',\n})\n\nuseForwardExpose()\n\nprovideAvatarRootContext({\n  imageLoadingStatus: ref<ImageLoadingStatus>('idle'),\n})\n</script>\n\n<template>\n  <Primitive\n    :as-child=\"asChild\"\n    :as=\"as\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { ImageLoadingStatus } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface AvatarRootProps extends PrimitiveProps {}\n\nexport type AvatarRootContext = {\n  imageLoadingStatus: Ref<ImageLoadingStatus>\n}\n\nexport const [injectAvatarRootContext, provideAvatarRootContext]\n  = createContext<AvatarRootContext>('AvatarRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nwithDefaults(defineProps<AvatarRootProps>(), {\n  as: 'span',\n})\n\nuseForwardExpose()\n\nprovideAvatarRootContext({\n  imageLoadingStatus: ref<ImageLoadingStatus>('idle'),\n})\n</script>\n\n<template>\n  <Primitive\n    :as-child=\"asChild\"\n    :as=\"as\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { isClient } from '@vueuse/shared'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AvatarFallbackProps extends PrimitiveProps {\n  /** Useful for delaying rendering so it only appears for those with slower connections. */\n  delayMs?: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref, watchEffect } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectAvatarRootContext } from './AvatarRoot.vue'\n\nconst props = withDefaults(defineProps<AvatarFallbackProps>(), {\n  as: 'span',\n})\n\nconst rootContext = injectAvatarRootContext()\nuseForwardExpose()\n\nconst canRender = ref(props.delayMs === undefined)\n\nwatchEffect((onCleanup) => {\n  if (props.delayMs && isClient) {\n    const timerId = window.setTimeout(() => {\n      canRender.value = true\n    }, props.delayMs)\n\n    onCleanup(() => {\n      window.clearTimeout(timerId)\n    })\n  }\n})\n</script>\n\n<template>\n  <Primitive\n    v-if=\"canRender && rootContext.imageLoadingStatus.value !== 'loaded'\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { isClient } from '@vueuse/shared'\nimport { useForwardExpose } from '@/shared'\n\nexport interface AvatarFallbackProps extends PrimitiveProps {\n  /** Useful for delaying rendering so it only appears for those with slower connections. */\n  delayMs?: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref, watchEffect } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectAvatarRootContext } from './AvatarRoot.vue'\n\nconst props = withDefaults(defineProps<AvatarFallbackProps>(), {\n  as: 'span',\n})\n\nconst rootContext = injectAvatarRootContext()\nuseForwardExpose()\n\nconst canRender = ref(props.delayMs === undefined)\n\nwatchEffect((onCleanup) => {\n  if (props.delayMs && isClient) {\n    const timerId = window.setTimeout(() => {\n      canRender.value = true\n    }, props.delayMs)\n\n    onCleanup(() => {\n      window.clearTimeout(timerId)\n    })\n  }\n})\n</script>\n\n<template>\n  <Primitive\n    v-if=\"canRender && rootContext.imageLoadingStatus.value !== 'loaded'\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","import type { ImgHTMLAttributes, Ref } from 'vue'\nimport { isClient } from '@vueuse/shared'\nimport { computed, onMounted, onUnmounted, ref, watchEffect } from 'vue'\n\nexport type ImageLoadingStatus = 'idle' | 'loading' | 'loaded' | 'error'\n\nfunction resolveLoadingStatus(image: HTMLImageElement | null, src?: string): ImageLoadingStatus {\n  if (!image) {\n    return 'idle'\n  }\n  if (!src) {\n    return 'error'\n  }\n  if (image.src !== src) {\n    image.src = src\n  }\n  return image.complete && image.naturalWidth > 0 ? 'loaded' : 'loading'\n}\n\nexport function useImageLoadingStatus(src: Ref<string>, { referrerPolicy, crossOrigin }: { referrerPolicy?: Ref<ImgHTMLAttributes['referrerpolicy']>, crossOrigin?: Ref<ImgHTMLAttributes['crossorigin']> } = {}) {\n  const isMounted = ref(false)\n  const imageRef = ref<HTMLImageElement | null>(null)\n  const image = computed(() => {\n    if (!isMounted.value) {\n      return null\n    }\n    if (!imageRef.value && isClient) {\n      imageRef.value = new window.Image()\n    }\n    return imageRef.value\n  })\n\n  const loadingStatus = ref<ImageLoadingStatus>(resolveLoadingStatus(image.value, src.value))\n\n  const updateStatus = (status: ImageLoadingStatus) => () => {\n    if (isMounted.value)\n      loadingStatus.value = status\n  }\n\n  onMounted(() => {\n    isMounted.value = true\n\n    watchEffect((onCleanup) => {\n      const img = image.value\n      if (!img)\n        return\n\n      loadingStatus.value = resolveLoadingStatus(img, src.value)\n\n      const handleLoad = updateStatus('loaded')\n      const handleError = updateStatus('error')\n\n      img.addEventListener('load', handleLoad)\n      img.addEventListener('error', handleError)\n\n      if (referrerPolicy?.value)\n        img.referrerPolicy = referrerPolicy.value\n      if (typeof crossOrigin?.value === 'string')\n        img.crossOrigin = crossOrigin.value\n\n      onCleanup(() => {\n        img.removeEventListener('load', handleLoad)\n        img.removeEventListener('error', handleError)\n      })\n    })\n  })\n\n  onUnmounted(() => {\n    isMounted.value = false\n  })\n\n  return loadingStatus\n}\n","<script lang=\"ts\">\nimport type { ImageLoadingStatus } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport type AvatarImageEmits = {\n  /**\n   * A callback providing information about the loading status of the image. <br>\n   * This is useful in case you want to control more precisely what to render as the image is loading.\n   */\n  loadingStatusChange: [value: ImageLoadingStatus]\n}\nexport interface AvatarImageProps extends PrimitiveProps {\n  src: string\n  referrerPolicy?: ImgHTMLAttributes['referrerpolicy']\n  crossOrigin?: ImgHTMLAttributes['crossorigin']\n}\n</script>\n\n<script setup lang=\"ts\">\nimport type { ImgHTMLAttributes } from 'vue'\nimport { toRefs, watch } from 'vue'\nimport { Primitive } from '../Primitive'\nimport { injectAvatarRootContext } from './AvatarRoot.vue'\nimport { useImageLoadingStatus } from './utils'\n\nconst props = withDefaults(defineProps<AvatarImageProps>(), { as: 'img' })\nconst emits = defineEmits<AvatarImageEmits>()\n\nconst { src, referrerPolicy, crossOrigin } = toRefs(props)\nuseForwardExpose()\nconst rootContext = injectAvatarRootContext()\n\nconst imageLoadingStatus = useImageLoadingStatus(src, { referrerPolicy, crossOrigin })\n\nwatch(\n  imageLoadingStatus,\n  (newValue) => {\n    emits('loadingStatusChange', newValue)\n    if (newValue !== 'idle')\n      rootContext.imageLoadingStatus.value = newValue\n  },\n  { immediate: true },\n)\n</script>\n\n<template>\n  <Primitive\n    v-show=\"imageLoadingStatus === 'loaded'\"\n    role=\"img\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :src=\"src\"\n    :referrerpolicy=\"referrerPolicy\"\n    :crossorigin=\"crossOrigin\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ImageLoadingStatus } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport type AvatarImageEmits = {\n  /**\n   * A callback providing information about the loading status of the image. <br>\n   * This is useful in case you want to control more precisely what to render as the image is loading.\n   */\n  loadingStatusChange: [value: ImageLoadingStatus]\n}\nexport interface AvatarImageProps extends PrimitiveProps {\n  src: string\n  referrerPolicy?: ImgHTMLAttributes['referrerpolicy']\n  crossOrigin?: ImgHTMLAttributes['crossorigin']\n}\n</script>\n\n<script setup lang=\"ts\">\nimport type { ImgHTMLAttributes } from 'vue'\nimport { toRefs, watch } from 'vue'\nimport { Primitive } from '../Primitive'\nimport { injectAvatarRootContext } from './AvatarRoot.vue'\nimport { useImageLoadingStatus } from './utils'\n\nconst props = withDefaults(defineProps<AvatarImageProps>(), { as: 'img' })\nconst emits = defineEmits<AvatarImageEmits>()\n\nconst { src, referrerPolicy, crossOrigin } = toRefs(props)\nuseForwardExpose()\nconst rootContext = injectAvatarRootContext()\n\nconst imageLoadingStatus = useImageLoadingStatus(src, { referrerPolicy, crossOrigin })\n\nwatch(\n  imageLoadingStatus,\n  (newValue) => {\n    emits('loadingStatusChange', newValue)\n    if (newValue !== 'idle')\n      rootContext.imageLoadingStatus.value = newValue\n  },\n  { immediate: true },\n)\n</script>\n\n<template>\n  <Primitive\n    v-show=\"imageLoadingStatus === 'loaded'\"\n    role=\"img\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :src=\"src\"\n    :referrerpolicy=\"referrerPolicy\"\n    :crossorigin=\"crossOrigin\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","/*\n  * Implementation ported from https://github.com/melt-ui/melt-ui/blob/develop/src/lib/builders/date-field/_internal/helpers.ts\n*/\n\nimport type { DateSegmentPart, EditableSegmentPart, SegmentPart, TimeSegmentPart } from './types'\n\nexport const DATE_SEGMENT_PARTS = ['day', 'month', 'year'] as const\nexport const TIME_SEGMENT_PARTS = ['hour', 'minute', 'second', 'dayPeriod'] as const\nexport const NON_EDITABLE_SEGMENT_PARTS = ['literal', 'timeZoneName'] as const\nexport const EDITABLE_SEGMENT_PARTS = [...DATE_SEGMENT_PARTS, ...TIME_SEGMENT_PARTS] as const\nexport const EDITABLE_TIME_SEGMENT_PARTS = [...TIME_SEGMENT_PARTS] as const\nexport const ALL_SEGMENT_PARTS = [\n  ...EDITABLE_SEGMENT_PARTS,\n  ...NON_EDITABLE_SEGMENT_PARTS,\n] as const\nexport const ALL_EXCEPT_LITERAL_PARTS = ALL_SEGMENT_PARTS.filter(part => part !== 'literal')\n\nexport function isDateSegmentPart(part: unknown): part is DateSegmentPart {\n  return DATE_SEGMENT_PARTS.includes(part as DateSegmentPart)\n}\n\nexport function isTimeSegmentPart(part: unknown): part is TimeSegmentPart {\n  return TIME_SEGMENT_PARTS.includes(part as TimeSegmentPart)\n}\n\nexport function isSegmentPart(part: string): part is EditableSegmentPart {\n  return EDITABLE_SEGMENT_PARTS.includes(part as EditableSegmentPart)\n}\n\nexport function isAnySegmentPart(part: unknown): part is SegmentPart {\n  return ALL_SEGMENT_PARTS.includes(part as EditableSegmentPart)\n}\n","/*\n * Implementation ported from from from https://github.com/melt-ui/melt-ui/blob/develop/src/lib/internal/helpers/date/placeholders.ts\n*/\n\nconst supportedLocales = [\n  'ach',\n  'af',\n  'am',\n  'an',\n  'ar',\n  'ast',\n  'az',\n  'be',\n  'bg',\n  'bn',\n  'br',\n  'bs',\n  'ca',\n  'cak',\n  'ckb',\n  'cs',\n  'cy',\n  'da',\n  'de',\n  'dsb',\n  'el',\n  'en',\n  'eo',\n  'es',\n  'et',\n  'eu',\n  'fa',\n  'ff',\n  'fi',\n  'fr',\n  'fy',\n  'ga',\n  'gd',\n  'gl',\n  'he',\n  'hr',\n  'hsb',\n  'hu',\n  'ia',\n  'id',\n  'it',\n  'ja',\n  'ka',\n  'kk',\n  'kn',\n  'ko',\n  'lb',\n  'lo',\n  'lt',\n  'lv',\n  'meh',\n  'ml',\n  'ms',\n  'nl',\n  'nn',\n  'no',\n  'oc',\n  'pl',\n  'pt',\n  'rm',\n  'ro',\n  'ru',\n  'sc',\n  'scn',\n  'sk',\n  'sl',\n  'sr',\n  'sv',\n  'szl',\n  'tg',\n  'th',\n  'tr',\n  'uk',\n  'zh-CN',\n  'zh-TW',\n] as const\n\nconst placeholderFields = ['year', 'month', 'day'] as const\n\ntype PlaceholderField = (typeof placeholderFields)[number]\nexport type SupportedLocale = (typeof supportedLocales)[number]\nexport type PlaceholderMap = Record<SupportedLocale, Record<PlaceholderField, string>>\n\nconst placeholders: PlaceholderMap = {\n  'ach': { year: 'mwaka', month: 'dwe', day: 'nino' },\n  'af': { year: 'jjjj', month: 'mm', day: 'dd' },\n  'am': { year: 'ዓዓዓዓ', month: 'ሚሜ', day: 'ቀቀ' },\n  'an': { year: 'aaaa', month: 'mm', day: 'dd' },\n  'ar': { year: 'سنة', month: 'شهر', day: 'يوم' },\n  'ast': { year: 'aaaa', month: 'mm', day: 'dd' },\n  'az': { year: 'iiii', month: 'aa', day: 'gg' },\n  'be': { year: 'гггг', month: 'мм', day: 'дд' },\n  'bg': { year: 'гггг', month: 'мм', day: 'дд' },\n  'bn': { year: 'yyyy', month: 'মিমি', day: 'dd' },\n  'br': { year: 'bbbb', month: 'mm', day: 'dd' },\n  'bs': { year: 'gggg', month: 'mm', day: 'dd' },\n  'ca': { year: 'aaaa', month: 'mm', day: 'dd' },\n  'cak': { year: 'jjjj', month: 'ii', day: 'q\\'q\\'' },\n  'ckb': { year: 'ساڵ', month: 'مانگ', day: 'ڕۆژ' },\n  'cs': { year: 'rrrr', month: 'mm', day: 'dd' },\n  'cy': { year: 'bbbb', month: 'mm', day: 'dd' },\n  'da': { year: 'åååå', month: 'mm', day: 'dd' },\n  'de': { year: 'jjjj', month: 'mm', day: 'tt' },\n  'dsb': { year: 'llll', month: 'mm', day: 'źź' },\n  'el': { year: 'εεεε', month: 'μμ', day: 'ηη' },\n  'en': { year: 'yyyy', month: 'mm', day: 'dd' },\n  'eo': { year: 'jjjj', month: 'mm', day: 'tt' },\n  'es': { year: 'aaaa', month: 'mm', day: 'dd' },\n  'et': { year: 'aaaa', month: 'kk', day: 'pp' },\n  'eu': { year: 'uuuu', month: 'hh', day: 'ee' },\n  'fa': { year: 'سال', month: 'ماه', day: 'روز' },\n  'ff': { year: 'hhhh', month: 'll', day: 'ññ' },\n  'fi': { year: 'vvvv', month: 'kk', day: 'pp' },\n  'fr': { year: 'aaaa', month: 'mm', day: 'jj' },\n  'fy': { year: 'jjjj', month: 'mm', day: 'dd' },\n  'ga': { year: 'bbbb', month: 'mm', day: 'll' },\n  'gd': { year: 'bbbb', month: 'mm', day: 'll' },\n  'gl': { year: 'aaaa', month: 'mm', day: 'dd' },\n  'he': { year: 'שנה', month: 'חודש', day: 'יום' },\n  'hr': { year: 'gggg', month: 'mm', day: 'dd' },\n  'hsb': { year: 'llll', month: 'mm', day: 'dd' },\n  'hu': { year: 'éééé', month: 'hh', day: 'nn' },\n  'ia': { year: 'aaaa', month: 'mm', day: 'dd' },\n  'id': { year: 'tttt', month: 'bb', day: 'hh' },\n  'it': { year: 'aaaa', month: 'mm', day: 'gg' },\n  'ja': { year: ' 年 ', month: '月', day: '日' },\n  'ka': { year: 'წწწწ', month: 'თთ', day: 'რრ' },\n  'kk': { year: 'жжжж', month: 'аа', day: 'кк' },\n  'kn': { year: 'ವವವವ', month: 'ಮಿಮೀ', day: 'ದಿದಿ' },\n  'ko': { year: '연도', month: '월', day: '일' },\n  'lb': { year: 'jjjj', month: 'mm', day: 'dd' },\n  'lo': { year: 'ປປປປ', month: 'ດດ', day: 'ວວ' },\n  'lt': { year: 'mmmm', month: 'mm', day: 'dd' },\n  'lv': { year: 'gggg', month: 'mm', day: 'dd' },\n  'meh': { year: 'aaaa', month: 'mm', day: 'dd' },\n  'ml': { year: 'വർഷം', month: 'മാസം', day: 'തീയതി' },\n  'ms': { year: 'tttt', month: 'mm', day: 'hh' },\n  'nl': { year: 'jjjj', month: 'mm', day: 'dd' },\n  'nn': { year: 'åååå', month: 'mm', day: 'dd' },\n  'no': { year: 'åååå', month: 'mm', day: 'dd' },\n  'oc': { year: 'aaaa', month: 'mm', day: 'jj' },\n  'pl': { year: 'rrrr', month: 'mm', day: 'dd' },\n  'pt': { year: 'aaaa', month: 'mm', day: 'dd' },\n  'rm': { year: 'oooo', month: 'mm', day: 'dd' },\n  'ro': { year: 'aaaa', month: 'll', day: 'zz' },\n  'ru': { year: 'гггг', month: 'мм', day: 'дд' },\n  'sc': { year: 'aaaa', month: 'mm', day: 'dd' },\n  'scn': { year: 'aaaa', month: 'mm', day: 'jj' },\n  'sk': { year: 'rrrr', month: 'mm', day: 'dd' },\n  'sl': { year: 'llll', month: 'mm', day: 'dd' },\n  'sr': { year: 'гггг', month: 'мм', day: 'дд' },\n  'sv': { year: 'åååå', month: 'mm', day: 'dd' },\n  'szl': { year: 'rrrr', month: 'mm', day: 'dd' },\n  'tg': { year: 'сссс', month: 'мм', day: 'рр' },\n  'th': { year: 'ปปปป', month: 'ดด', day: 'วว' },\n  'tr': { year: 'yyyy', month: 'aa', day: 'gg' },\n  'uk': { year: 'рррр', month: 'мм', day: 'дд' },\n  'zh-CN': { year: '年', month: '月', day: '日' },\n  'zh-TW': { year: '年', month: '月', day: '日' },\n}\n\nfunction getPlaceholderObj(locale: SupportedLocale | (string & {})) {\n  if (!isSupportedLocale(locale)) {\n    const localeLanguage = getLocaleLanguage(locale)\n    if (!isSupportedLocale(localeLanguage))\n      return placeholders.en\n\n    else\n      return placeholders[localeLanguage]\n  }\n  else {\n    return placeholders[locale]\n  }\n}\n\ntype Field = 'era' | 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second' | 'dayPeriod'\n\nexport function getPlaceholder(\n  field: Field,\n  value: string,\n  locale: SupportedLocale | (string & {}),\n) {\n  if (isPlaceholderField(field))\n    return getPlaceholderObj(locale)[field]\n\n  if (isDefaultField(field))\n    return value\n\n  if (isTimeField(field))\n    return '––'\n\n  return ''\n}\n\nfunction isSupportedLocale(locale: string): locale is SupportedLocale {\n  return supportedLocales.includes(locale as SupportedLocale)\n}\n\nfunction isPlaceholderField(field: unknown): field is PlaceholderField {\n  return placeholderFields.includes(field as PlaceholderField)\n}\n\nfunction isTimeField(field: unknown): field is 'hour' | 'minute' | 'second' {\n  return field === 'hour' || field === 'minute' || field === 'second'\n}\n\nfunction isDefaultField(field: unknown): field is 'era' | 'dayPeriod' {\n  return field === 'era' || field === 'dayPeriod'\n}\n\nfunction getLocaleLanguage(locale: string) {\n  if (Intl.Locale)\n    return new Intl.Locale(locale).language\n\n  return locale.split('-')[0]\n}\n","import type { DateFields, DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Formatter } from '@/shared'\nimport type { DateSegmentPart, Granularity, HourCycle, SegmentContentObj, SegmentPart, SegmentValueObj, TimeSegmentPart } from '@/shared/date'\nimport { isZonedDateTime, toDate } from '@/date'\nimport { DATE_SEGMENT_PARTS, EDITABLE_SEGMENT_PARTS, getOptsByGranularity, getPlaceholder, isDateSegmentPart, isSegmentPart, normalizeHourCycle, TIME_SEGMENT_PARTS } from '@/shared/date'\n\nconst calendarDateTimeGranularities = ['hour', 'minute', 'second']\n\ntype SyncDateSegmentValuesProps = {\n  value: DateValue\n  formatter: Formatter\n}\n\ntype SyncTimeSegmentValuesProps = {\n  value: DateValue\n  formatter: Formatter\n}\n\nexport function syncTimeSegmentValues(props: SyncTimeSegmentValuesProps) {\n  return Object.fromEntries(TIME_SEGMENT_PARTS.map((part) => {\n    if (part === 'dayPeriod')\n      return [part, props.formatter.dayPeriod(toDate(props.value))]\n    return [part, props.value[part as keyof DateValue]]\n  })) as SegmentValueObj\n}\n\nexport function syncSegmentValues(props: SyncDateSegmentValuesProps) {\n  const { formatter } = props\n\n  const dateValues = DATE_SEGMENT_PARTS.map((part) => {\n    return [part, props.value[part]]\n  })\n  if ('hour' in props.value) {\n    const timeValues = syncTimeSegmentValues({ value: props.value, formatter })\n\n    return { ...Object.fromEntries(dateValues), ...timeValues } as SegmentValueObj\n  }\n\n  return Object.fromEntries(dateValues) as SegmentValueObj\n}\n\nexport function initializeTimeSegmentValues(granularity: 'hour' | 'minute' | 'second'): SegmentValueObj {\n  return Object.fromEntries(\n    TIME_SEGMENT_PARTS.map((part) => {\n      if (part === 'dayPeriod')\n        return [part, 'AM']\n      return [part, null]\n    }).filter(([key]) => {\n      if (key === 'literal' || key === null)\n        return false\n      if (granularity === 'minute' && key === 'second')\n        return false\n      if (granularity === 'hour' && (key === 'second' || key === 'minute'))\n        return false\n      else return true\n    }),\n  )\n}\n\nexport function initializeSegmentValues(granularity: Granularity): SegmentValueObj {\n  const initialParts = EDITABLE_SEGMENT_PARTS.map((part) => {\n    if (part === 'dayPeriod')\n      return [part, 'AM']\n\n    return [part, null]\n  }).filter(([key]) => {\n    if (key === 'literal' || key === null)\n      return false\n    if (granularity === 'minute' && key === 'second')\n      return false\n    if (granularity === 'hour' && (key === 'second' || key === 'minute'))\n      return false\n    if (granularity === 'day')\n      return !calendarDateTimeGranularities.includes(key) && key !== 'dayPeriod'\n    else return true\n  })\n\n  return Object.fromEntries(initialParts)\n}\n\ntype SharedContentProps = {\n  granularity: Granularity\n  dateRef: DateValue\n  formatter: Formatter\n  hideTimeZone: boolean\n  hourCycle: HourCycle\n  isTimeValue?: boolean\n}\n\ntype CreateContentObjProps = SharedContentProps & {\n  segmentValues: SegmentValueObj\n  locale: Ref<string>\n}\n\ntype CreateContentArrProps = SharedContentProps & {\n  contentObj: SegmentContentObj\n}\n\nfunction createContentObj(props: CreateContentObjProps) {\n  const { segmentValues, formatter, locale } = props\n  function getPartContent(part: DateSegmentPart | TimeSegmentPart) {\n    if ('hour' in segmentValues) {\n      const value = segmentValues[part]\n      if (value !== null) {\n        if (part === 'day') {\n          return formatter.part(props.dateRef.set({\n            [part as keyof DateFields]: value,\n            /**\n             * Edge case for the day field:\n             *\n             * 1. If the month is filled,\n             *   we need to ensure that the day snaps to the maximum value of that month.\n             * 2. If the month is not filled,\n             *   we default to the month with the maximum number of days (here just using January, 31 days),\n             *   so that user can input any possible day.\n             */\n            month: segmentValues.month ?? 1,\n          }), part, { hourCycle: normalizeHourCycle(props.hourCycle) })\n        }\n        return formatter.part(props.dateRef.set({ [part]: value }), part, {\n          hourCycle: normalizeHourCycle(props.hourCycle),\n        })\n      }\n      else {\n        return getPlaceholder(part, '', locale.value)\n      }\n    }\n    else {\n      if (isDateSegmentPart(part)) {\n        const value = segmentValues[part]\n        if (value !== null) {\n          if (part === 'day') {\n            return formatter.part(props.dateRef.set({\n              [part]: value,\n              // Same logic as above for the day field\n              month: segmentValues.month ?? 1,\n            }), part)\n          }\n\n          return formatter.part(props.dateRef.set({ [part]: value }), part)\n        }\n\n        else {\n          return getPlaceholder(part, '', locale.value)\n        }\n      }\n      return ''\n    }\n  }\n\n  const content = Object.keys(segmentValues).reduce((obj, part) => {\n    if (!isSegmentPart(part))\n      return obj\n    if ('hour' in segmentValues && part === 'dayPeriod') {\n      const value = segmentValues[part]\n\n      if (value !== null)\n        obj[part] = value\n\n      else\n        obj[part] = getPlaceholder(part, 'AM', locale.value)\n    }\n    else {\n      obj[part] = getPartContent(part)\n    }\n\n    return obj\n  }, {} as SegmentContentObj)\n\n  return content\n}\n\nfunction createContentArr(props: CreateContentArrProps) {\n  const { granularity, formatter, contentObj, hideTimeZone, hourCycle, isTimeValue } = props\n  const parts = formatter.toParts(props.dateRef, getOptsByGranularity(granularity, hourCycle, isTimeValue))\n\n  const segmentContentArr = parts\n    .map((part) => {\n      const defaultParts = ['literal', 'timeZoneName', null]\n\n      if (defaultParts.includes(part.type) || !isSegmentPart(part.type)) {\n        return {\n          part: part.type,\n          value: part.value,\n        }\n      }\n\n      return {\n        part: part.type,\n        value: contentObj[part.type],\n      }\n    })\n    .filter((segment): segment is { part: SegmentPart, value: string } => {\n      if (segment.part === null || segment.value === null)\n        return false\n      if (segment.part === 'timeZoneName' && (!isZonedDateTime(props.dateRef) || hideTimeZone))\n        return false\n\n      // In some locales (e.g., zh-TW), the time zone is represented with square brackets.\n      // We also filter out these literals that are just brackets.\n      // @see https://github.com/unovue/reka-ui/issues/1670\n      if (\n        (!isZonedDateTime(props.dateRef) || hideTimeZone)\n        && segment.part === 'literal' && ['[', ']'].includes(segment.value.trim())\n      ) {\n        return false\n      }\n\n      return true\n    })\n\n  return segmentContentArr\n}\n\ntype CreateContentProps = CreateContentObjProps\n\nexport function createContent(props: CreateContentProps) {\n  const contentObj = createContentObj(props)\n\n  const contentArr = createContentArr({\n    contentObj,\n    ...props,\n  })\n\n  return {\n    obj: contentObj,\n    arr: contentArr,\n  }\n}\n","import { useKbd } from '@/shared'\n\nexport function isSegmentNavigationKey(key: string) {\n  const kbd = useKbd()\n  if (key === kbd.ARROW_RIGHT || key === kbd.ARROW_LEFT)\n    return true\n  return false\n}\n\nexport function isNumberString(value: string) {\n  if (Number.isNaN(Number.parseInt(value)))\n    return false\n  return true\n}\n\nexport function isAcceptableSegmentKey(key: string) {\n  const kbd = useKbd()\n  const acceptableSegmentKeys = [\n    kbd.ENTER,\n    kbd.ARROW_UP,\n    kbd.ARROW_DOWN,\n    kbd.ARROW_LEFT,\n    kbd.ARROW_RIGHT,\n    kbd.BACKSPACE,\n    kbd.SPACE,\n    'a',\n    'A',\n    'p',\n    'P',\n  ]\n  if (acceptableSegmentKeys.includes(key))\n    return true\n  if (isNumberString(key))\n    return true\n  return false\n}\n\nexport function getSegmentElements(parentElement: HTMLElement): Element[] {\n  return Array.from(parentElement.querySelectorAll('[data-reka-date-field-segment]')).filter(item => item.getAttribute('data-reka-date-field-segment') !== 'literal')\n}\n\nexport function getTimeFieldSegmentElements(parentElement: HTMLElement): Element[] {\n  return Array.from(parentElement.querySelectorAll('[data-reka-time-field-segment]')).filter(item => item.getAttribute('data-reka-time-field-segment') !== 'literal')\n}\n","import type { CalendarDateTime, DateFields, DateValue, TimeFields } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { AnyExceptLiteral, DateStep, HourCycle, SegmentPart, SegmentValueObj } from './types'\nimport type { Formatter } from '@/shared'\nimport {\n  DateFormatter,\n} from '@internationalized/date'\nimport { computed } from 'vue'\nimport { getDaysInMonth, toDate } from '@/date'\nimport { getActiveElement, snapValueToStep, useKbd } from '@/shared'\nimport { isAcceptableSegmentKey, isNumberString, isSegmentNavigationKey } from './segment'\n\nconst DIGIT_REG = /^\\d$/\n\ntype MinuteSecondIncrementProps = {\n  e: KeyboardEvent\n  part: keyof TimeFields\n  dateRef: DateValue\n  prevValue: number | null\n}\n\ntype DateTimeValueIncrementation = {\n  e: KeyboardEvent\n  part: keyof Omit<DateFields, 'era'> | keyof TimeFields\n  dateRef: DateValue\n  prevValue: number | null\n}\n\ntype SegmentAttrProps = {\n  disabled: boolean\n  segmentValues: SegmentValueObj\n  hourCycle: HourCycle\n  placeholder: DateValue\n  formatter: Formatter\n}\n\nfunction commonSegmentAttrs(props: SegmentAttrProps) {\n  return {\n    role: 'spinbutton',\n    contenteditable: true,\n    tabindex: props.disabled ? undefined : 0,\n    spellcheck: false,\n    inputmode: 'numeric',\n    autocorrect: 'off',\n    enterkeyhint: 'next',\n    style: 'caret-color: transparent;',\n  }\n}\n\nfunction daySegmentAttrs(props: SegmentAttrProps) {\n  const { segmentValues, placeholder } = props\n  const isEmpty = segmentValues.day === null\n\n  // Include month from segmentValues to ensure correct max days calculation\n  const dateFields: { day?: number, month?: number } = {}\n  if (segmentValues.day)\n    dateFields.day = segmentValues.day\n  if (segmentValues.month)\n    dateFields.month = segmentValues.month\n\n  const date = Object.keys(dateFields).length > 0 ? placeholder.set(dateFields) : placeholder\n\n  const valueNow = date.day\n  const valueMin = 1\n  const valueMax = getDaysInMonth(date)\n  const valueText = isEmpty ? 'Empty' : `${valueNow}`\n\n  return {\n    ...commonSegmentAttrs(props),\n    'aria-label': 'day,',\n    'aria-valuemin': valueMin,\n    'aria-valuemax': valueMax,\n    'aria-valuenow': valueNow,\n    'aria-valuetext': valueText,\n    'data-placeholder': isEmpty ? '' : undefined,\n  }\n}\n\nfunction monthSegmentAttrs(props: SegmentAttrProps) {\n  const { segmentValues, placeholder, formatter } = props\n  const isEmpty = segmentValues.month === null\n  const date = segmentValues.month\n    ? placeholder.set({ month: segmentValues.month })\n    : placeholder\n  const valueNow = date.month\n  const valueMin = 1\n  const valueMax = 12\n  const valueText = isEmpty ? 'Empty' : `${valueNow} - ${formatter.fullMonth(toDate(date))}`\n\n  return {\n    ...commonSegmentAttrs(props),\n    'aria-label': 'month, ',\n    'contenteditable': true,\n    'aria-valuemin': valueMin,\n    'aria-valuemax': valueMax,\n    'aria-valuenow': valueNow,\n    'aria-valuetext': valueText,\n    'data-placeholder': isEmpty ? '' : undefined,\n  }\n}\n\nfunction yearSegmentAttrs(props: SegmentAttrProps) {\n  const { segmentValues, placeholder } = props\n  const isEmpty = segmentValues.year === null\n  const date = segmentValues.year ? placeholder.set({ year: segmentValues.year }) : placeholder\n  const valueMin = 1\n  const valueMax = 9999\n  const valueNow = date.year\n  const valueText = isEmpty ? 'Empty' : `${valueNow}`\n\n  return {\n    ...commonSegmentAttrs(props),\n    'aria-label': 'year, ',\n    'aria-valuemin': valueMin,\n    'aria-valuemax': valueMax,\n    'aria-valuenow': valueNow,\n    'aria-valuetext': valueText,\n    'data-placeholder': isEmpty ? '' : undefined,\n  }\n}\n\nfunction hourSegmentAttrs(props: SegmentAttrProps) {\n  const { segmentValues, hourCycle, placeholder } = props\n\n  if (!('hour' in segmentValues) || !('hour' in placeholder))\n    return {}\n  const isEmpty = segmentValues.hour === null\n  const date = segmentValues.hour ? placeholder.set({ hour: segmentValues.hour }) : placeholder\n  const valueMin = hourCycle === 12 ? 1 : 0\n  const valueMax = hourCycle === 12 ? 12 : 23\n  const valueNow = date.hour\n  const valueText = isEmpty ? 'Empty' : `${valueNow} ${segmentValues.dayPeriod ?? ''}`\n\n  return {\n    ...commonSegmentAttrs(props),\n    'aria-label': 'hour, ',\n    'aria-valuemin': valueMin,\n    'aria-valuemax': valueMax,\n    'aria-valuenow': valueNow,\n    'aria-valuetext': valueText,\n    'data-placeholder': isEmpty ? '' : undefined,\n  }\n}\n\nfunction minuteSegmentAttrs(props: SegmentAttrProps) {\n  const { segmentValues, placeholder } = props\n  if (!('minute' in segmentValues) || !('minute' in placeholder))\n    return {}\n  const isEmpty = segmentValues.minute === null\n  const date = segmentValues.minute\n    ? placeholder.set({ minute: segmentValues.minute })\n    : placeholder\n  const valueNow = date.minute\n  const valueMin = 0\n  const valueMax = 59\n  const valueText = isEmpty ? 'Empty' : `${valueNow}`\n\n  return {\n    ...commonSegmentAttrs(props),\n    'aria-label': 'minute, ',\n    'aria-valuemin': valueMin,\n    'aria-valuemax': valueMax,\n    'aria-valuenow': valueNow,\n    'aria-valuetext': valueText,\n    'data-placeholder': isEmpty ? '' : undefined,\n  }\n}\n\nfunction secondSegmentAttrs(props: SegmentAttrProps) {\n  const { segmentValues, placeholder } = props\n  if (!('second' in segmentValues) || !('second' in placeholder))\n    return {}\n  const isEmpty = segmentValues.second === null\n  const date = segmentValues.second\n    ? placeholder.set({ second: segmentValues.second })\n    : placeholder\n  const valueNow = date.second\n  const valueMin = 0\n  const valueMax = 59\n  const valueText = isEmpty ? 'Empty' : `${valueNow}`\n\n  return {\n    ...commonSegmentAttrs(props),\n    'aria-label': 'second, ',\n    'aria-valuemin': valueMin,\n    'aria-valuemax': valueMax,\n    'aria-valuenow': valueNow,\n    'aria-valuetext': valueText,\n    'data-placeholder': isEmpty ? '' : undefined,\n  }\n}\n\nfunction dayPeriodSegmentAttrs(props: SegmentAttrProps) {\n  const { segmentValues } = props\n  if (!('dayPeriod' in segmentValues))\n    return {}\n\n  const valueMin = 0\n  const valueMax = 12\n  const valueNow = segmentValues.hour ? (segmentValues.hour > 12 ? segmentValues.hour - 12 : segmentValues.hour) : 0\n  const valueText = segmentValues.dayPeriod ?? 'AM'\n\n  return {\n    ...commonSegmentAttrs(props),\n    'inputmode': 'text',\n    'aria-label': 'AM/PM',\n    'aria-valuemin': valueMin,\n    'aria-valuemax': valueMax,\n    'aria-valuenow': valueNow,\n    'aria-valuetext': valueText,\n  }\n}\n\nfunction literalSegmentAttrs(_props: SegmentAttrProps) {\n  return {\n    'aria-hidden': true,\n    'data-segment': 'literal',\n  }\n}\n\nfunction timeZoneSegmentAttrs(props: SegmentAttrProps) {\n  return {\n    'role': 'textbox',\n    'aria-label': 'timezone, ',\n    'data-readonly': true,\n    'data-segment': 'timeZoneName',\n    'tabindex': props.disabled ? undefined : 0,\n    'style': 'caret-color: transparent;',\n  }\n}\n\nfunction eraSegmentAttrs(props: SegmentAttrProps) {\n  const { segmentValues, placeholder } = props\n\n  const valueMin = 0\n  const valueMax = 0\n  const valueNow = 0\n  const valueText = 'era' in segmentValues ? segmentValues.era : placeholder.era\n\n  return {\n    ...commonSegmentAttrs(props),\n    'aria-label': 'era',\n    'aria-valuemin': valueMin,\n    'aria-valuemax': valueMax,\n    'aria-valuenow': valueNow,\n    'aria-valuetext': valueText,\n  }\n}\n\nexport const segmentBuilders = {\n  day: {\n    attrs: daySegmentAttrs,\n  },\n  month: {\n    attrs: monthSegmentAttrs,\n  },\n  year: {\n    attrs: yearSegmentAttrs,\n  },\n  hour: {\n    attrs: hourSegmentAttrs,\n  },\n  minute: {\n    attrs: minuteSegmentAttrs,\n  },\n  second: {\n    attrs: secondSegmentAttrs,\n  },\n  dayPeriod: {\n    attrs: dayPeriodSegmentAttrs,\n  },\n  literal: {\n    attrs: literalSegmentAttrs,\n  },\n  timeZoneName: {\n    attrs: timeZoneSegmentAttrs,\n  },\n  era: {\n    attrs: eraSegmentAttrs,\n  },\n}\n\nexport type UseDateFieldProps = {\n  hasLeftFocus: Ref<boolean>\n  lastKeyZero: Ref<boolean>\n  placeholder: Ref<DateValue>\n  hourCycle: HourCycle\n  step: Ref<DateStep>\n  stepSnapping?: Ref<boolean>\n  formatter: Formatter\n  segmentValues: Ref<SegmentValueObj>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  part: SegmentPart\n  modelValue: Ref<DateValue | undefined>\n  focusNext: () => void\n}\n\nexport function useDateField(props: UseDateFieldProps) {\n  const kbd = useKbd()\n\n  function minuteSecondIncrementation({ e, part, dateRef, prevValue }: MinuteSecondIncrementProps): number {\n    const step = props.step.value[part] ?? 1\n    const sign = e.key === kbd.ARROW_UP ? step : -step\n    const min = 0\n    const max = 59\n\n    if (prevValue === null)\n      return sign > 0 ? min : max\n\n    const cycleArgs: [keyof TimeFields, number] = [part, sign]\n    return (dateRef as CalendarDateTime).set({ [part]: prevValue }).cycle(...cycleArgs)[part]\n  }\n\n  function deleteValue(prevValue: number | null) {\n    props.hasLeftFocus.value = false\n    if (prevValue === null)\n      return prevValue\n\n    const str = prevValue.toString()\n    if (str.length === 1) {\n      props.modelValue.value = undefined\n      return null\n    }\n\n    return Number.parseInt(str.slice(0, -1))\n  }\n  function dateTimeValueIncrementation({ e, part, dateRef, prevValue }: DateTimeValueIncrementation): number {\n    const step = props.step.value[part] ?? 1\n    const sign = e.key === kbd.ARROW_UP ? step : -step\n\n    if (prevValue === null)\n      return dateRef[part as keyof Omit<DateFields, 'era'>]\n\n    if (part === 'hour' && 'hour' in dateRef) {\n      // Don't pass hourCycle to cycle - internal representation is always 24-hour\n      // The hourCycle prop only affects display, not internal cycling\n      const cycleArgs: [keyof DateFields | keyof TimeFields, number] = [part, sign]\n      return dateRef.set({ [part as keyof DateValue]: prevValue }).cycle(...cycleArgs)[part]\n    }\n\n    const cycleArgs: [keyof DateFields, number] = [part as keyof DateFields, sign]\n    if (part === 'day') {\n      return dateRef.set({\n        [part as keyof DateValue]: prevValue,\n        /**\n         * Edge case for the day field:\n         *\n         * 1. If the month is filled,\n         *   we need to ensure that the day snaps to the maximum value of that month.\n         * 2. If the month is not filled,\n         *   we default to the month with the maximum number of days (here just using January, 31 days),\n         *   so that user can input any possible day.\n         */\n        month: props.segmentValues.value.month ?? 1,\n      }).cycle(...cycleArgs)[part as keyof Omit<DateFields, 'era'>]\n    }\n\n    return dateRef.set({ [part as keyof DateValue]: prevValue }).cycle(...cycleArgs)[part as keyof Omit<DateFields, 'era'>]\n  }\n  function updateDayOrMonth(max: number, num: number, prev: number | null) {\n    let moveToNext = false\n    const maxStart = Math.floor(max / 10)\n\n    /**\n     * If the user has left the segment, we want to reset the\n     * `prev` value so that we can start the segment over again\n     * when the user types a number.\n     */\n    if (props.hasLeftFocus.value) {\n      props.hasLeftFocus.value = false\n      props.lastKeyZero.value = false\n      prev = null\n    }\n\n    if (prev === null) {\n      /**\n       * If the user types a 0 as the first number, we want\n       * to keep track of that so that when they type the next\n       * number, we can move to the next segment.\n       */\n\n      if (num === 0) {\n        props.lastKeyZero.value = true\n        return { value: null, moveToNext }\n      }\n      /**\n       * If the last key was a 0, or if the first number is\n       * greater than the max start digit (0-3 in most cases), then\n       * we want to move to the next segment, since it's not possible\n       * to continue typing a valid number in this segment.\n       */\n\n      if (props.lastKeyZero.value || num > maxStart) {\n        // move to next\n        moveToNext = true\n      }\n      props.lastKeyZero.value = false\n      /**\n       * If none of the above conditions are met, then we can just\n       * return the number as the segment value and continue typing\n       * in this segment.\n       */\n      return { value: num, moveToNext }\n    }\n\n    /**\n     * If the number of digits is 2, or if the total with the existing digit\n     * and the pressed digit is greater than the maximum value for this\n     * month, then we will reset the segment as if the user had pressed the\n     * backspace key and then typed the number.\n     */\n    const digits = prev.toString().length\n    const total = Number.parseInt(prev.toString() + num.toString())\n    /**\n     * If the number of digits is 2, or if the total with the existing digit\n     * and the pressed digit is greater than the maximum value for this\n     * month, then we will reset the segment as if the user had pressed the\n     * backspace key and then typed the number.\n     */\n\n    if (digits === 2 || total > max) {\n      /**\n       * As we're doing elsewhere, we're checking if the number is greater\n       * than the max start digit (0-3 in most months), and if so, we're\n       * going to move to the next segment.\n       */\n      if (num > maxStart || total > max) {\n        // move to next\n        moveToNext = true\n      }\n      return { value: num, moveToNext }\n    }\n    // move to next\n    moveToNext = true\n    return { value: total, moveToNext }\n  }\n\n  function updateMinuteOrSecond(num: number, prev: number | null) {\n    const max = 59\n    let moveToNext = false\n    const maxStart = Math.floor(max / 10)\n\n    /**\n     * If the user has left the segment, we want to reset the\n     * `prev` value so that we can start the segment over again\n     * when the user types a number.\n     */\n    if (props.hasLeftFocus.value) {\n      props.hasLeftFocus.value = false\n      props.lastKeyZero.value = false\n      prev = null\n    }\n\n    if (prev === null) {\n      /**\n       * If the user types a 0 as the first number, we want\n       * to keep track of that so that when they type the next\n       * number, we can move to the next segment.\n       */\n\n      if (num === 0) {\n        props.lastKeyZero.value = true\n        return { value: 0, moveToNext }\n      }\n      /**\n       * If the last key was a 0, or if the first number is\n       * greater than the max start digit (0-3 in most cases), then\n       * we want to move to the next segment, since it's not possible\n       * to continue typing a valid number in this segment.\n       */\n\n      if (props.lastKeyZero.value || num > maxStart) {\n        // move to next\n        moveToNext = true\n      }\n      props.lastKeyZero.value = false\n      /**\n       * If none of the above conditions are met, then we can just\n       * return the number as the segment value and continue typing\n       * in this segment.\n       */\n      return { value: num, moveToNext }\n    }\n\n    /**\n     * If the number of digits is 2, or if the total with the existing digit\n     * and the pressed digit is greater than the maximum value for this\n     * month, then we will reset the segment as if the user had pressed the\n     * backspace key and then typed the number.\n     */\n    const digits = prev.toString().length\n    const total = Number.parseInt(prev.toString() + num.toString())\n\n    /**\n     * If the number of digits is 2, or if the total with the existing digit\n     * and the pressed digit is greater than the maximum value for this\n     * month, then we will reset the segment as if the user had pressed the\n     * backspace key and then typed the number.\n     */\n\n    if (digits === 2 || total > max) {\n      /**\n       * As we're doing elsewhere, we're checking if the number is greater\n       * than the max start digit (0-3 in most months), and if so, we're\n       * going to move to the next segment.\n       */\n      if (num > maxStart) {\n        // move to next\n        moveToNext = true\n      }\n      return { value: num, moveToNext }\n    }\n    // move to next\n    moveToNext = true\n    return { value: total, moveToNext }\n  }\n\n  function updateHour(max: number, num: number, prev: number | null) {\n    let moveToNext = false\n    const maxStart = Math.floor(max / 10)\n\n    /**\n     * If the user has left the segment, we want to reset the\n     * `prev` value so that we can start the segment over again\n     * when the user types a number.\n     */\n    // probably not implement, kind of weird\n    if (props.hasLeftFocus.value) {\n      props.hasLeftFocus.value = false\n      props.lastKeyZero.value = false\n      prev = null\n    }\n\n    if (prev === null) {\n      /**\n       * If the user types a 0 as the first number, we want\n       * to keep track of that so that when they type the next\n       * number, we can move to the next segment.\n       */\n\n      if (num === 0) {\n        props.lastKeyZero.value = true\n        return { value: 0, moveToNext }\n      }\n      /**\n       * If the last key was a 0, or if the first number is\n       * greater than the max start digit (0-3 in most cases), then\n       * we want to move to the next segment, since it's not possible\n       * to continue typing a valid number in this segment.\n       */\n\n      if (props.lastKeyZero.value || num > maxStart) {\n        // move to next\n        moveToNext = true\n      }\n      props.lastKeyZero.value = false\n      /**\n       * If none of the above conditions are met, then we can just\n       * return the number as the segment value and continue typing\n       * in this segment.\n       */\n      return { value: num, moveToNext }\n    }\n\n    /**\n     * If the number of digits is 2, or if the total with the existing digit\n     * and the pressed digit is greater than the maximum value for this\n     * month, then we will reset the segment as if the user had pressed the\n     * backspace key and then typed the number.\n     */\n    const digits = prev.toString().length\n    const total = Number.parseInt(prev.toString() + num.toString())\n\n    /**\n     * If the number of digits is 2, or if the total with the existing digit\n     * and the pressed digit is greater than the maximum value for this\n     * month, then we will reset the segment as if the user had pressed the\n     * backspace key and then typed the number.\n     */\n\n    if (digits === 2 || total > max) {\n      /**\n       * As we're doing elsewhere, we're checking if the number is greater\n       * than the max start digit (0-3 in most months), and if so, we're\n       * going to move to the next segment.\n       */\n      if (num > maxStart) {\n        // move to next\n        moveToNext = true\n      }\n      return { value: num, moveToNext }\n    }\n    // move to next\n    moveToNext = true\n    return { value: total, moveToNext }\n  }\n\n  function updateYear(num: number, prev: number | null) {\n    let moveToNext = false\n\n    /**\n     * If the user has left the segment, we want to reset the\n     * `prev` value so that we can start the segment over again\n     * when the user types a number.\n     */\n    // probably not implement, kind of weird\n    if (props.hasLeftFocus.value) {\n      props.hasLeftFocus.value = false\n      prev = null\n    }\n\n    if (prev === null)\n      return { value: num === 0 ? 1 : num, moveToNext }\n\n    const str = prev.toString() + num.toString()\n\n    if (str.length > 4)\n      return { value: num === 0 ? 1 : num, moveToNext }\n\n    if (str.length === 4)\n      moveToNext = true\n\n    const int = Number.parseInt(str)\n    return { value: int, moveToNext }\n  }\n\n  const attributes = computed(() => segmentBuilders[props.part]?.attrs({\n    disabled: props.disabled.value,\n    placeholder: props.placeholder.value,\n    hourCycle: props.hourCycle,\n    segmentValues: props.segmentValues.value,\n    formatter: props.formatter,\n  }) ?? {})\n\n  // TODO: look into abstracting segment keydown functions since they have the same structure (checks -> arrow_up, arrow_down update -> number string update -> move to next -> backspace update)\n  function handleDaySegmentKeydown(e: KeyboardEvent) {\n    if (!isAcceptableSegmentKey(e.key) || isSegmentNavigationKey(e.key))\n      return\n\n    const prevValue = props.segmentValues.value.day\n\n    if (e.key === kbd.ARROW_DOWN || e.key === kbd.ARROW_UP) {\n      props.segmentValues.value.day = dateTimeValueIncrementation({ e, part: 'day', dateRef: props.placeholder.value, prevValue })\n      return\n    }\n\n    if (isNumberString(e.key)) {\n      const num = Number.parseInt(e.key)\n      const segmentMonthValue = props.segmentValues.value.month\n\n      const daysInMonth = segmentMonthValue\n        ? getDaysInMonth(props.placeholder.value.set({ month: segmentMonthValue }))\n        // if the month is not set, we default to the maximum number of days in a month\n        // so that user can input any possible day\n        : 31\n\n      const { value, moveToNext } = updateDayOrMonth(daysInMonth, num, prevValue)\n\n      props.segmentValues.value.day = value\n\n      if (moveToNext)\n        props.focusNext()\n    }\n\n    if (e.key === kbd.BACKSPACE) {\n      props.hasLeftFocus.value = false\n      props.segmentValues.value.day = deleteValue(prevValue)\n    }\n  }\n\n  function handleMonthSegmentKeydown(e: KeyboardEvent) {\n    if (!isAcceptableSegmentKey(e.key) || isSegmentNavigationKey(e.key))\n      return\n\n    const prevValue = props.segmentValues.value.month\n\n    if (e.key === kbd.ARROW_DOWN || e.key === kbd.ARROW_UP) {\n      props.segmentValues.value.month = dateTimeValueIncrementation({ e, part: 'month', dateRef: props.placeholder.value, prevValue })\n      return\n    }\n\n    if (isNumberString(e.key)) {\n      const num = Number.parseInt(e.key)\n      const { value, moveToNext } = updateDayOrMonth(12, num, prevValue)\n\n      props.segmentValues.value.month = value\n\n      if (moveToNext)\n        props.focusNext()\n    }\n\n    if (e.key === kbd.BACKSPACE) {\n      props.hasLeftFocus.value = false\n      props.segmentValues.value.month = deleteValue(prevValue)\n    }\n  }\n\n  function handleYearSegmentKeydown(e: KeyboardEvent) {\n    if (!isAcceptableSegmentKey(e.key) || isSegmentNavigationKey(e.key))\n      return\n\n    const prevValue = props.segmentValues.value.year\n\n    if (e.key === kbd.ARROW_DOWN || e.key === kbd.ARROW_UP) {\n      props.segmentValues.value.year = dateTimeValueIncrementation({ e, part: 'year', dateRef: props.placeholder.value, prevValue })\n      return\n    }\n\n    if (isNumberString(e.key)) {\n      const num = Number.parseInt(e.key)\n      const { value, moveToNext } = updateYear(num, prevValue)\n\n      props.segmentValues.value.year = value\n\n      if (moveToNext)\n        props.focusNext()\n    }\n\n    if (e.key === kbd.BACKSPACE) {\n      props.hasLeftFocus.value = false\n      props.segmentValues.value.year = deleteValue(prevValue)\n    }\n  }\n\n  function uses12HourFormat(locale: string): boolean {\n    const hourCycle = new DateFormatter(locale, { hour: 'numeric' }).resolvedOptions().hourCycle\n    return hourCycle === 'h11' || hourCycle === 'h12'\n  }\n\n  function handleHourSegmentKeydown(e: KeyboardEvent) {\n    const dateRef = props.placeholder.value\n    if (!isAcceptableSegmentKey(e.key) || isSegmentNavigationKey(e.key) || !('hour' in dateRef) || !('hour' in props.segmentValues.value))\n      return\n\n    const prevValue = props.segmentValues.value.hour\n\n    if (e.key === kbd.ARROW_UP || e.key === kbd.ARROW_DOWN) {\n      const newHour = dateTimeValueIncrementation({ e, part: 'hour', dateRef: props.placeholder.value, prevValue })\n      props.segmentValues.value.hour = newHour\n\n      if ('dayPeriod' in props.segmentValues.value && newHour !== null) {\n        // Determine AM/PM based on internal 24-hour value\n        // Hour 0-11 = AM, Hour 12-23 = PM\n        props.segmentValues.value.dayPeriod = newHour >= 12 ? 'PM' : 'AM'\n      }\n\n      return\n    }\n\n    if (isNumberString(e.key)) {\n      const num = Number.parseInt(e.key)\n      const is12Hour = props.hourCycle !== undefined\n        ? props.hourCycle === 12\n        : uses12HourFormat(props.formatter.getLocale())\n      const max = is12Hour ? 12 : 24\n\n      let displayPrev = prevValue\n      if (is12Hour && prevValue !== null) {\n        // 12 AM/PM should be treated as 0 internally even if it doesn't match the display\n        // otherwise repeatedly typing 0 will not advance to the next segment\n        displayPrev = prevValue % 12 === 0 ? 0 : (prevValue > 12 ? prevValue - 12 : prevValue)\n      }\n\n      const { value, moveToNext } = updateHour(max, num, displayPrev)\n\n      // Convert display hour back to internal 24-hour format\n      let internalValue = value\n      if (is12Hour && value !== null) {\n        const period = props.segmentValues.value.dayPeriod || 'AM'\n        if (value === 12) {\n          internalValue = period === 'AM' ? 0 : 12\n        }\n        else {\n          internalValue = period === 'PM' ? value + 12 : value\n        }\n      }\n\n      props.segmentValues.value.hour = internalValue\n\n      if (moveToNext)\n        props.focusNext()\n    }\n\n    if (e.key === kbd.BACKSPACE) {\n      props.hasLeftFocus.value = false\n      props.segmentValues.value.hour = deleteValue(prevValue)\n    }\n  }\n\n  function handleMinuteSegmentKeydown(e: KeyboardEvent) {\n    const dateRef = props.placeholder.value\n\n    if (!isAcceptableSegmentKey(e.key) || isSegmentNavigationKey(e.key) || !('minute' in dateRef) || !('minute' in props.segmentValues.value))\n      return\n\n    const prevValue = props.segmentValues.value.minute\n\n    if (e.key === kbd.ARROW_UP || e.key === kbd.ARROW_DOWN) {\n      props.segmentValues.value.minute = minuteSecondIncrementation({ e, part: 'minute', dateRef: props.placeholder.value, prevValue })\n    }\n\n    if (isNumberString(e.key)) {\n      const num = Number.parseInt(e.key)\n\n      const { value, moveToNext } = updateMinuteOrSecond(num, prevValue)\n\n      props.segmentValues.value.minute = value\n\n      if (moveToNext)\n        props.focusNext()\n    }\n\n    if (e.key === kbd.BACKSPACE) {\n      props.hasLeftFocus.value = false\n      props.segmentValues.value.minute = deleteValue(prevValue)\n    }\n  }\n\n  function handleSecondSegmentKeydown(e: KeyboardEvent) {\n    const dateRef = props.placeholder.value\n\n    if (!isAcceptableSegmentKey(e.key) || isSegmentNavigationKey(e.key) || !('second' in dateRef) || !('second' in props.segmentValues.value))\n      return\n\n    const prevValue = props.segmentValues.value.second\n\n    if (e.key === kbd.ARROW_UP || e.key === kbd.ARROW_DOWN) {\n      props.segmentValues.value.second = minuteSecondIncrementation({ e, part: 'second', dateRef: props.placeholder.value, prevValue })\n    }\n\n    if (isNumberString(e.key)) {\n      const num = Number.parseInt(e.key)\n      const { value, moveToNext } = updateMinuteOrSecond(num, prevValue)\n\n      props.segmentValues.value.second = value\n\n      if (moveToNext)\n        props.focusNext()\n    }\n\n    if (e.key === kbd.BACKSPACE) {\n      props.hasLeftFocus.value = false\n      props.segmentValues.value.second = deleteValue(prevValue)\n    }\n  }\n\n  function handleDayPeriodSegmentKeydown(e: KeyboardEvent) {\n    if (((!isAcceptableSegmentKey(e.key) || isSegmentNavigationKey(e.key)) && e.key !== 'a' && e.key !== 'p') || !('hour' in props.placeholder.value) || !('dayPeriod' in props.segmentValues.value))\n      return\n\n    if (e.key === kbd.ARROW_UP || e.key === kbd.ARROW_DOWN) {\n      if (props.segmentValues.value.dayPeriod === 'AM') {\n        props.segmentValues.value.dayPeriod = 'PM'\n        props.segmentValues.value.hour = props.segmentValues.value.hour! + 12\n        return\n      }\n      props.segmentValues.value.dayPeriod = 'AM'\n      props.segmentValues.value.hour = props.segmentValues.value.hour! - 12\n      return\n    }\n\n    if (['a', 'A'].includes(e.key) && props.segmentValues.value.dayPeriod !== 'AM') {\n      props.segmentValues.value.dayPeriod = 'AM'\n      props.segmentValues.value.hour = props.segmentValues.value.hour! - 12\n      return\n    }\n\n    if (['p', 'P'].includes(e.key) && props.segmentValues.value.dayPeriod !== 'PM') {\n      props.segmentValues.value.dayPeriod = 'PM'\n      props.segmentValues.value.hour = props.segmentValues.value.hour! + 12\n    }\n  }\n\n  function handleSegmentClick(e: MouseEvent) {\n    const disabled = props.disabled.value\n    if (disabled)\n      e.preventDefault()\n  }\n\n  function handleSegmentKeydown(e: KeyboardEvent) {\n    // A genuine composition keydown sets `isComposing` or reports `key === 'Process'`.\n    // Don't use `keyCode === 229` alone: a CJK IME (e.g. Pinyin) keeps that flag set\n    // while passing a directly-typed key through, so a real digit (`key === '1'`)\n    // would be dropped and leak into the contenteditable as raw text.\n    if (e.isComposing || e.key === 'Process')\n      return\n\n    const disabled = props.disabled.value\n    const readonly = props.readonly.value\n    if (disabled || readonly)\n      return\n    if (e.key !== kbd.TAB)\n      e.preventDefault()\n    const segmentKeydownHandlers = {\n      day: handleDaySegmentKeydown,\n      month: handleMonthSegmentKeydown,\n      year: handleYearSegmentKeydown,\n      hour: handleHourSegmentKeydown,\n      minute: handleMinuteSegmentKeydown,\n      second: handleSecondSegmentKeydown,\n      dayPeriod: handleDayPeriodSegmentKeydown,\n      timeZoneName: () => { },\n    } as const\n\n    segmentKeydownHandlers[props.part as keyof typeof segmentKeydownHandlers](e)\n\n    if (![kbd.ARROW_LEFT, kbd.ARROW_RIGHT].includes(e.key) && e.key !== kbd.TAB && e.key !== kbd.SHIFT && isAcceptableSegmentKey(e.key)) {\n      if (Object.values(props.segmentValues.value).every(item => item !== null)) {\n        const updateObject = { ...props.segmentValues.value as Record<AnyExceptLiteral, number> }\n\n        // Set all date fields at once to avoid order-dependent constraints\n        // (e.g., setting day: 31 before month: 3 would incorrectly constrain the day)\n        const dateRef = props.placeholder.value.set(updateObject)\n\n        props.modelValue.value = dateRef.copy()\n      }\n    }\n  }\n\n  function handleSegmentFocusOut() {\n    if (!props.stepSnapping?.value)\n      return\n\n    if (props.part === 'hour' && 'hour' in props.segmentValues.value && props.segmentValues.value.hour !== null && props.step.value.hour && props.step.value.hour > 1) {\n      props.segmentValues.value.hour = snapValueToStep(props.segmentValues.value.hour, 0, 23, props.step.value.hour)\n      if ('dayPeriod' in props.segmentValues.value) {\n        if (props.segmentValues.value.hour < 12)\n          props.segmentValues.value.dayPeriod = 'AM'\n        else if (props.segmentValues.value.hour)\n          props.segmentValues.value.dayPeriod = 'PM'\n      }\n    }\n    else if (props.part === 'minute' && 'minute' in props.segmentValues.value && props.segmentValues.value.minute !== null && props.step.value.minute && props.step.value.minute > 1) {\n      props.segmentValues.value.minute = snapValueToStep(props.segmentValues.value.minute, 0, 59, props.step.value.minute)\n    }\n    else if (props.part === 'second' && 'second' in props.segmentValues.value && props.segmentValues.value.second !== null && props.step.value.second && props.step.value.second > 1) {\n      props.segmentValues.value.second = snapValueToStep(props.segmentValues.value.second, 0, 59, props.step.value.second)\n    }\n\n    if (Object.values(props.segmentValues.value).every(item => item !== null)) {\n      const dateRef = props.placeholder.value.set({ ...props.segmentValues.value as Record<AnyExceptLiteral, number> })\n      props.modelValue.value = dateRef.copy()\n    }\n  }\n\n  // Snapshot of the segment's child nodes (and their text) before the IME mutates\n  // the contenteditable. Vue renders the value into one text node but may keep\n  // empty sibling text nodes around it, so we must preserve EVERY node it owns and\n  // restore them verbatim on `compositionend`. Recreating nodes (textContent) would\n  // detach Vue's binding and freeze the segment; recreating the element isn't an\n  // option either, since the root captures segment elements once via\n  // `getSegmentElements` and a fresh node would break navigation.\n  let preCompositionNodes: { node: ChildNode, value: string | null }[] | null = null\n\n  function handleSegmentBeforeInput(e: InputEvent) {\n    // The segment's text is driven programmatically (keydown -> segmentValues ->\n    // Vue render), so the contenteditable must never be edited directly. Safari\n    // dispatches `beforeinput`/`input` BEFORE `keydown` while an IME is active,\n    // so a passed-through key (e.g. a digit typed while Pinyin is selected) would\n    // leak into the DOM as raw text before `handleSegmentKeydown` can prevent it.\n    // Composition input keeps `isComposing` true, so let it through and reconcile\n    // on `compositionend`.\n    if (!e.isComposing)\n      e.preventDefault()\n  }\n\n  function handleSegmentCompositionStart(e: CompositionEvent) {\n    const el = e.target as HTMLElement\n    preCompositionNodes = Array.from(el.childNodes, node => ({ node, value: node.nodeValue }))\n  }\n\n  function handleSegmentCompositionEnd(e: CompositionEvent) {\n    const el = e.target as HTMLElement\n    const original = preCompositionNodes\n    preCompositionNodes = null\n\n    // Restore Vue's original nodes (with their text) and drop anything the IME\n    // inserted, keeping Vue's bindings intact so later renders still patch the DOM.\n    // When no composition was tracked (e.g. synthetic events in tests) leave it be.\n    if (original) {\n      for (const { node, value } of original)\n        node.nodeValue = value\n      el.replaceChildren(...original.map(o => o.node))\n    }\n\n    const data = e.data\n    if (!data)\n      return\n\n    for (const char of data) {\n      if (!DIGIT_REG.test(char))\n        continue\n\n      // Dispatch to the focused segment so subsequent digits follow focus\n      // after `focusNext()` advances to the next segment (e.g. \"34\" → 3 in day, 4 in month).\n      const target = getActiveElement()\n      if (!(target instanceof HTMLElement))\n        break\n\n      target.dispatchEvent(new KeyboardEvent('keydown', {\n        key: char,\n        bubbles: true,\n        cancelable: true,\n      }))\n    }\n  }\n\n  return {\n    handleSegmentClick,\n    handleSegmentKeydown,\n    handleSegmentBeforeInput,\n    handleSegmentCompositionStart,\n    handleSegmentCompositionEnd,\n    handleSegmentFocusOut,\n    attributes,\n  }\n}\n","/*\n  * Adapted from https://github.com/melt-ui/melt-ui/blob/develop/src/lib/builders/calendar/create.ts\n*/\n\nimport type { DateFields, DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher, WeekDayFormat, WeekStartsOn } from '@/date'\nimport type { DateFormatterOptions } from '@/shared/useDateFormatter'\nimport { isEqualMonth, isSameDay, isSameMonth } from '@internationalized/date'\nimport { computed, ref, watch } from 'vue'\nimport { createMonths, getDaysInMonth, isAfter, isBefore, toDate } from '@/date'\nimport { useDateFormatter } from '@/shared'\n\nexport type UseCalendarProps = {\n  locale: Ref<string>\n  placeholder: Ref<DateValue>\n  weekStartsOn: Ref<WeekStartsOn>\n  fixedWeeks: Ref<boolean>\n  numberOfMonths: Ref<number>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  disabled: Ref<boolean>\n  weekdayFormat: Ref<WeekDayFormat>\n  pagedNavigation: Ref<boolean>\n  isDateDisabled?: Matcher\n  isDateUnavailable?: Matcher\n  calendarLabel: Ref<string | undefined>\n  nextPage: Ref<((placeholder: DateValue) => DateValue) | undefined>\n  prevPage: Ref<((placeholder: DateValue) => DateValue) | undefined>\n}\n\nexport type UseCalendarStateProps = {\n  isDateDisabled: Matcher\n  isDateUnavailable: Matcher\n  date: Ref<DateValue | DateValue[] | undefined>\n}\n\nexport function useCalendarState(props: UseCalendarStateProps) {\n  function isDateSelected(dateObj: DateValue) {\n    if (Array.isArray(props.date.value))\n      return props.date.value.some(d => isSameDay(d, dateObj))\n\n    else if (!props.date.value)\n      return false\n\n    else\n      return isSameDay(props.date.value, dateObj)\n  }\n\n  const isInvalid = computed(\n    () => {\n      if (Array.isArray(props.date.value)) {\n        if (!props.date.value.length)\n          return false\n        for (const dateObj of props.date.value) {\n          if (props.isDateDisabled?.(dateObj))\n            return true\n          if (props.isDateUnavailable?.(dateObj))\n            return true\n        }\n      }\n      else {\n        if (!props.date.value)\n          return false\n        if (props.isDateDisabled?.(props.date.value))\n          return true\n        if (props.isDateUnavailable?.(props.date.value))\n          return true\n      }\n      return false\n    },\n  )\n\n  const hasSelectedDate = computed(() => {\n    return Array.isArray(props.date.value) ? props.date.value.length > 0 : !!props.date.value\n  })\n\n  const isSelectedDateDisabled = computed(() => {\n    if (Array.isArray(props.date.value)) {\n      if (!props.date.value.length)\n        return false\n      return props.date.value.some(dateObj => props.isDateDisabled?.(dateObj))\n    }\n    if (!props.date.value)\n      return false\n    return !!props.isDateDisabled?.(props.date.value)\n  })\n\n  return {\n    isDateSelected,\n    isInvalid,\n    hasSelectedDate,\n    isSelectedDateDisabled,\n  }\n}\n\nfunction handleNextDisabled(lastPeriodInView: DateValue, nextPageFunc: (date: DateValue) => DateValue): DateValue {\n  const firstPeriodOfNextPage = nextPageFunc(lastPeriodInView)\n  const diff = firstPeriodOfNextPage.compare(lastPeriodInView)\n  const duration: DateFields = {}\n  if (diff >= 7)\n    duration.day = 1\n  if (diff >= getDaysInMonth(lastPeriodInView))\n    duration.month = 1\n  return firstPeriodOfNextPage.set({ ...duration })\n}\nfunction handlePrevDisabled(firstPeriodInView: DateValue, prevPageFunc: (date: DateValue) => DateValue): DateValue {\n  const lastPeriodOfPrevPage = prevPageFunc(firstPeriodInView)\n  const diff = firstPeriodInView.compare(lastPeriodOfPrevPage)\n  const duration: DateFields = {}\n  if (diff >= 7)\n    duration.day = 35\n  if (diff >= getDaysInMonth(firstPeriodInView))\n    duration.month = 13\n  return lastPeriodOfPrevPage.set({ ...duration })\n}\nfunction handleNextPage(date: DateValue, nextPageFunc: (date: DateValue) => DateValue): DateValue {\n  return nextPageFunc(date)\n}\n\nfunction handlePrevPage(date: DateValue, prevPageFunc: (date: DateValue) => DateValue): DateValue {\n  return prevPageFunc(date)\n}\n\nexport function useCalendar(props: UseCalendarProps) {\n  const formatter = useDateFormatter(props.locale.value)\n\n  const headingFormatOptions = computed(() => {\n    const options: DateFormatterOptions = {\n      calendar: props.placeholder.value.calendar.identifier,\n    }\n\n    if (props.placeholder.value.calendar.identifier === 'gregory' && props.placeholder.value.era === 'BC')\n      options.era = 'short'\n\n    return options\n  })\n\n  const grid = ref<Grid<DateValue>[]>(createMonths({\n    dateObj: props.placeholder.value,\n    weekStartsOn: props.weekStartsOn.value,\n    locale: props.locale.value,\n    fixedWeeks: props.fixedWeeks.value,\n    numberOfMonths: props.numberOfMonths.value,\n  })) as Ref<Grid<DateValue>[]>\n\n  const visibleView = computed(() => {\n    return grid.value.map(month => month.value)\n  })\n\n  function isOutsideVisibleView(date: DateValue) {\n    return !visibleView.value.some(month => isEqualMonth(date, month))\n  }\n\n  const isNextButtonDisabled = (nextPageFunc?: (date: DateValue) => DateValue) => {\n    if (!props.maxValue.value || !grid.value.length)\n      return false\n    if (props.disabled.value)\n      return true\n\n    const lastPeriodInView = grid.value.at(-1)!.value\n\n    if (!nextPageFunc && !props.nextPage.value) {\n      const firstPeriodOfNextPage = lastPeriodInView.add({ months: 1 }).set({ day: 1 })\n      return isAfter(firstPeriodOfNextPage, props.maxValue.value)\n    }\n\n    const firstPeriodOfNextPage = handleNextDisabled(lastPeriodInView, nextPageFunc || props.nextPage.value!)\n    return isAfter(firstPeriodOfNextPage, props.maxValue.value)\n  }\n\n  const isPrevButtonDisabled = (prevPageFunc?: (date: DateValue) => DateValue) => {\n    if (!props.minValue.value || !grid.value.length)\n      return false\n    if (props.disabled.value)\n      return true\n    const firstPeriodInView = grid.value[0].value\n\n    if (!prevPageFunc && !props.prevPage.value) {\n      const lastPeriodOfPrevPage = firstPeriodInView.subtract({ months: 1 }).set({ day: 35 })\n      return isBefore(lastPeriodOfPrevPage, props.minValue.value)\n    }\n\n    const lastPeriodOfPrevPage = handlePrevDisabled(firstPeriodInView, prevPageFunc || props.prevPage.value!)\n    return isBefore(lastPeriodOfPrevPage, props.minValue.value)\n  }\n\n  function isDateDisabled(dateObj: DateValue) {\n    if (props.isDateDisabled?.(dateObj) || props.disabled.value)\n      return true\n    if (props.maxValue.value && isAfter(dateObj, props.maxValue.value))\n      return true\n    if (props.minValue.value && isBefore(dateObj, props.minValue.value))\n      return true\n    return false\n  }\n\n  const isDateUnavailable = (date: DateValue) => {\n    if (props.isDateUnavailable?.(date))\n      return true\n    return false\n  }\n\n  const weekdays = computed(() => {\n    if (!grid.value.length)\n      return []\n    return grid.value[0].rows[0].map((date) => {\n      return formatter.dayOfWeek(toDate(date), props.weekdayFormat.value)\n    })\n  })\n\n  const nextPage = (nextPageFunc?: (date: DateValue) => DateValue) => {\n    const firstDate = grid.value[0].value\n\n    if (!nextPageFunc && !props.nextPage.value) {\n      const newDate = firstDate.add({ months: props.pagedNavigation.value ? props.numberOfMonths.value : 1 })\n\n      const newGrid = createMonths({\n        dateObj: newDate,\n        weekStartsOn: props.weekStartsOn.value,\n        locale: props.locale.value,\n        fixedWeeks: props.fixedWeeks.value,\n        numberOfMonths: props.numberOfMonths.value,\n      })\n\n      grid.value = newGrid\n\n      props.placeholder.value = newGrid[0].value.set({ day: 1 })\n      return\n    }\n\n    const newDate = handleNextPage(firstDate, nextPageFunc || props.nextPage.value!)\n    const newGrid = createMonths({\n      dateObj: newDate,\n      weekStartsOn: props.weekStartsOn.value,\n      locale: props.locale.value,\n      fixedWeeks: props.fixedWeeks.value,\n      numberOfMonths: props.numberOfMonths.value,\n    })\n\n    grid.value = newGrid\n\n    const duration: DateFields = {}\n\n    // Do not adjust the placeholder if the nextPageFunc is defined (overwrite)\n    if (!nextPageFunc) {\n      const diff = newGrid[0].value.compare(firstDate)\n      if (diff >= getDaysInMonth(firstDate))\n        duration.day = 1\n\n      if (diff >= 365)\n        duration.month = 1\n    }\n\n    props.placeholder.value = newGrid[0].value.set({ ...duration })\n  }\n\n  const prevPage = (prevPageFunc?: (date: DateValue) => DateValue) => {\n    const firstDate = grid.value[0].value\n\n    if (!prevPageFunc && !props.prevPage.value) {\n      const newDate = firstDate.subtract({ months: props.pagedNavigation.value ? props.numberOfMonths.value : 1 })\n\n      const newGrid = createMonths({\n        dateObj: newDate,\n        weekStartsOn: props.weekStartsOn.value,\n        locale: props.locale.value,\n        fixedWeeks: props.fixedWeeks.value,\n        numberOfMonths: props.numberOfMonths.value,\n      })\n\n      grid.value = newGrid\n\n      props.placeholder.value = newGrid[0].value.set({ day: 1 })\n      return\n    }\n\n    const newDate = handlePrevPage(firstDate, prevPageFunc || props.prevPage.value!)\n    const newGrid = createMonths({\n      dateObj: newDate,\n      weekStartsOn: props.weekStartsOn.value,\n      locale: props.locale.value,\n      fixedWeeks: props.fixedWeeks.value,\n      numberOfMonths: props.numberOfMonths.value,\n    })\n\n    grid.value = newGrid\n\n    const duration: DateFields = {}\n\n    // Do not adjust the placeholder if the prevPageFunc is defined (overwrite)\n    if (!prevPageFunc) {\n      const diff = firstDate.compare(newGrid[0].value)\n      if (diff >= getDaysInMonth(firstDate))\n        duration.day = 1\n\n      if (diff >= 365)\n        duration.month = 1\n    }\n\n    props.placeholder.value = newGrid[0].value.set({ ...duration })\n  }\n\n  watch(props.placeholder, (value) => {\n    if (visibleView.value.some(month => isEqualMonth(month, value)))\n      return\n    grid.value = createMonths({\n      dateObj: value,\n      weekStartsOn: props.weekStartsOn.value,\n      locale: props.locale.value,\n      fixedWeeks: props.fixedWeeks.value,\n      numberOfMonths: props.numberOfMonths.value,\n    })\n  })\n\n  watch([props.locale, props.weekStartsOn, props.fixedWeeks, props.numberOfMonths], () => {\n    grid.value = createMonths({\n      dateObj: props.placeholder.value,\n      weekStartsOn: props.weekStartsOn.value,\n      locale: props.locale.value,\n      fixedWeeks: props.fixedWeeks.value,\n      numberOfMonths: props.numberOfMonths.value,\n    })\n  })\n\n  const headingValue = computed(() => {\n    if (!grid.value.length)\n      return ''\n\n    if (props.locale.value !== formatter.getLocale())\n      formatter.setLocale(props.locale.value)\n\n    if (grid.value.length === 1) {\n      const month = grid.value[0].value\n      return `${formatter.fullMonthAndYear(toDate(month), headingFormatOptions.value)}`\n    }\n\n    const startMonth = toDate(grid.value[0].value)\n    const endMonth = toDate(grid.value.at(-1)!.value)\n\n    const startMonthName = formatter.fullMonth(startMonth, headingFormatOptions.value)\n    const endMonthName = formatter.fullMonth(endMonth, headingFormatOptions.value)\n    const startMonthYear = formatter.fullYear(startMonth, headingFormatOptions.value)\n    const endMonthYear = formatter.fullYear(endMonth, headingFormatOptions.value)\n\n    const content\n      = startMonthYear === endMonthYear\n        ? `${startMonthName} - ${endMonthName} ${endMonthYear}`\n        : `${startMonthName} ${startMonthYear} - ${endMonthName} ${endMonthYear}`\n\n    return content\n  })\n\n  const fullCalendarLabel = computed(() => `${props.calendarLabel.value ?? 'Event Date'}, ${headingValue.value}`)\n\n  const isPlaceholderFocusable = computed(() => {\n    return !(isDateDisabled(props.placeholder.value) || isDateUnavailable(props.placeholder.value) || isOutsideVisibleView(props.placeholder.value))\n  })\n\n  const firstFocusableDate = computed(() => {\n    for (const month of grid.value) {\n      if (props.minValue.value && isBefore(month.value, props.minValue.value))\n        continue\n\n      const daysInMonth = getDaysInMonth(month.value)\n      const startDay = props.minValue.value && isSameMonth(props.minValue.value, month.value) ? props.minValue.value.day : 1\n\n      for (let day = startDay; day <= daysInMonth; day++) {\n        const date = month.value.set({ day })\n        if (isDateDisabled(date) || isDateUnavailable(date))\n          continue\n        return date\n      }\n    }\n  })\n\n  return {\n    isDateDisabled,\n    isDateUnavailable,\n    isNextButtonDisabled,\n    isPrevButtonDisabled,\n    grid,\n    weekdays,\n    visibleView,\n    isOutsideVisibleView,\n    formatter,\n    nextPage,\n    prevPage,\n    headingValue,\n    fullCalendarLabel,\n    isPlaceholderFocusable,\n    firstFocusableDate,\n  }\n}\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\n\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher, WeekDayFormat, WeekStartsOn } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nimport type { Formatter } from '@/shared'\nimport type { Direction } from '@/shared/types'\nimport { isEqualDay, isSameDay } from '@internationalized/date'\nimport { getWeekStartsOn } from '@/date'\nimport { createContext, useDirection, useLocale } from '@/shared'\nimport { getDefaultDate, handleCalendarInitialFocus } from '@/shared/date'\nimport { useCalendar, useCalendarState } from './useCalendar'\n\ntype CalendarRootContext = {\n  locale: Ref<string>\n  modelValue: Ref<DateValue | DateValue[] | undefined>\n  placeholder: Ref<DateValue>\n  pagedNavigation: Ref<boolean>\n  preventDeselect: Ref<boolean>\n  grid: Ref<Grid<DateValue>[]>\n  weekDays: Ref<string[]>\n  weekStartsOn: Ref<WeekStartsOn>\n  weekdayFormat: Ref<WeekDayFormat>\n  fixedWeeks: Ref<boolean>\n  multiple: Ref<boolean>\n  numberOfMonths: Ref<number>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  initialFocus: Ref<boolean>\n  onDateChange: (date: DateValue) => void\n  onPlaceholderChange: (date: DateValue) => void\n  fullCalendarLabel: Ref<string>\n  parentElement: Ref<HTMLElement | undefined>\n  headingValue: Ref<string>\n  isInvalid: Ref<boolean>\n  isDateDisabled: Matcher\n  isDateSelected: Matcher\n  isDateUnavailable?: Matcher\n  isOutsideVisibleView: (date: DateValue) => boolean\n  prevPage: (prevPageFunc?: (date: DateValue) => DateValue) => void\n  nextPage: (nextPageFunc?: (date: DateValue) => DateValue) => void\n  isNextButtonDisabled: (nextPageFunc?: (date: DateValue) => DateValue) => boolean\n  isPrevButtonDisabled: (prevPageFunc?: (date: DateValue) => DateValue) => boolean\n  formatter: Formatter\n  dir: Ref<Direction>\n  disableDaysOutsideCurrentView: Ref<boolean>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  isPlaceholderFocusable: Ref<boolean>\n  firstFocusableDate: Ref<DateValue | undefined>\n  hasSelectedDate: Ref<boolean>\n  isSelectedDateDisabled: Ref<boolean>\n}\n\nexport interface CalendarRootProps extends PrimitiveProps {\n  /** The default value for the calendar */\n  defaultValue?: DateValue\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The placeholder date, which is used to determine what month to display when no date is selected */\n  placeholder?: DateValue\n  /** This property causes the previous and next buttons to navigate by the number of months displayed at once, rather than one month */\n  pagedNavigation?: boolean\n  /** Whether or not to prevent the user from deselecting a date without selecting another date first */\n  preventDeselect?: boolean\n  /** The day of the week to start the calendar on */\n  weekStartsOn?: WeekStartsOn\n  /** The format to use for the weekday strings provided via the weekdays slot prop */\n  weekdayFormat?: WeekDayFormat\n  /** The accessible label for the calendar */\n  calendarLabel?: string\n  /** Whether or not to always display 6 weeks in the calendar */\n  fixedWeeks?: boolean\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** The number of months to display at once */\n  numberOfMonths?: number\n  /** Whether the calendar is disabled */\n  disabled?: boolean\n  /** Whether the calendar is readonly */\n  readonly?: boolean\n  /** If true, the calendar will focus the selected day, today, or the first day of the month depending on what is visible when the calendar is mounted */\n  initialFocus?: boolean\n  /** A function that returns whether or not a date is disabled */\n  isDateDisabled?: Matcher\n  /** A function that returns whether or not a date is unavailable */\n  isDateUnavailable?: Matcher\n  /** The reading direction of the calendar when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** A function that returns the next page of the calendar. It receives the current placeholder as an argument inside the component. */\n  nextPage?: (placeholder: DateValue) => DateValue\n  /** A function that returns the previous page of the calendar. It receives the current placeholder as an argument inside the component. */\n  prevPage?: (placeholder: DateValue) => DateValue\n  /** The controlled selected date value of the calendar. Can be bound as `v-model`. */\n  modelValue?: DateValue | DateValue[] | null\n  /** Whether multiple dates can be selected */\n  multiple?: boolean\n  /** Whether or not to disable days outside the current view. */\n  disableDaysOutsideCurrentView?: boolean\n}\n\nexport type CalendarRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateValue | undefined]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n}\n\nexport const [injectCalendarRootContext, provideCalendarRootContext]\n  = createContext<CalendarRootContext>('CalendarRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, onMounted, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CalendarRootProps>(), {\n  defaultValue: undefined,\n  as: 'div',\n  pagedNavigation: false,\n  preventDeselect: false,\n  weekdayFormat: 'narrow',\n  fixedWeeks: false,\n  multiple: false,\n  numberOfMonths: 1,\n  disabled: false,\n  readonly: false,\n  initialFocus: false,\n  placeholder: undefined,\n  isDateDisabled: undefined,\n  isDateUnavailable: undefined,\n  disableDaysOutsideCurrentView: false,\n})\nconst emits = defineEmits<CalendarRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the placeholder */\n    date: DateValue\n    /** The grid of dates */\n    grid: Grid<DateValue>[]\n    /** The days of the week */\n    weekDays: string[]\n    /** The start of the week */\n    weekStartsOn: WeekStartsOn\n    /** The calendar locale */\n    locale: string\n    /** Whether or not to always display 6 weeks in the calendar */\n    fixedWeeks: boolean\n    /** The current date of the calendar */\n    modelValue: DateValue | DateValue[] | undefined\n  }) => any\n}>()\n\nconst {\n  disabled,\n  readonly,\n  initialFocus,\n  pagedNavigation,\n  weekdayFormat,\n  fixedWeeks,\n  multiple,\n  minValue,\n  maxValue,\n  numberOfMonths,\n  preventDeselect,\n  isDateDisabled: propsIsDateDisabled,\n  isDateUnavailable: propsIsDateUnavailable,\n  calendarLabel,\n  defaultValue,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n  dir: propDir,\n  locale: propLocale,\n  disableDaysOutsideCurrentView,\n} = toRefs(props)\n\nconst { primitiveElement, currentElement: parentElement }\n  = usePrimitiveElement()\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\nconst weekStartsOn = computed(() => props.weekStartsOn ?? getWeekStartsOn(locale.value))\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateValue | DateValue[] | undefined>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: modelValue.value,\n  locale: props.locale,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nfunction onPlaceholderChange(value: DateValue) {\n  placeholder.value = value.copy()\n}\n\nconst {\n  fullCalendarLabel,\n  headingValue,\n  isDateDisabled,\n  isDateUnavailable,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  weekdays,\n  isOutsideVisibleView,\n  nextPage,\n  prevPage,\n  formatter,\n  grid,\n  isPlaceholderFocusable,\n  firstFocusableDate,\n} = useCalendar({\n  locale,\n  placeholder,\n  weekStartsOn,\n  fixedWeeks,\n  numberOfMonths,\n  minValue,\n  maxValue,\n  disabled,\n  weekdayFormat,\n  pagedNavigation,\n  isDateDisabled: propsIsDateDisabled.value,\n  isDateUnavailable: propsIsDateUnavailable.value,\n  calendarLabel,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n})\n\nconst {\n  isInvalid,\n  isDateSelected,\n  hasSelectedDate,\n  isSelectedDateDisabled,\n} = useCalendarState({\n  date: modelValue,\n  isDateDisabled,\n  isDateUnavailable,\n})\n\nwatch(modelValue, (_modelValue) => {\n  if (Array.isArray(_modelValue) && _modelValue.length) {\n    const lastValue = _modelValue.at(-1)\n    if (lastValue && !isEqualDay(placeholder.value, lastValue))\n      onPlaceholderChange(lastValue)\n  }\n  else if (!Array.isArray(_modelValue) && _modelValue && !isEqualDay(placeholder.value, _modelValue)) {\n    onPlaceholderChange(_modelValue)\n  }\n})\n\nfunction onDateChange(value: DateValue) {\n  if (!multiple.value) {\n    if (!modelValue.value) {\n      modelValue.value = value.copy()\n      return\n    }\n\n    if (!preventDeselect.value && isEqualDay(modelValue.value as DateValue, value)) {\n      placeholder.value = value.copy()\n      modelValue.value = undefined\n    }\n    else { modelValue.value = value.copy() }\n  }\n  else if (!modelValue.value) {\n    modelValue.value = [value.copy()]\n  }\n  else if (Array.isArray(modelValue.value)) {\n    const index = modelValue.value.findIndex(date => isSameDay(date, value))\n    if (index === -1) {\n      modelValue.value = [...modelValue.value, value]\n    }\n    else if (!preventDeselect.value) {\n      const next = modelValue.value.filter(date => !isSameDay(date, value))\n      if (!next.length) {\n        placeholder.value = value.copy()\n        modelValue.value = undefined\n        return\n      }\n      modelValue.value = next.map(date => date.copy())\n    }\n  }\n}\n\nonMounted(() => {\n  if (initialFocus.value)\n    handleCalendarInitialFocus(parentElement.value)\n})\n\nprovideCalendarRootContext({\n  isDateUnavailable,\n  dir,\n  isDateDisabled,\n  locale,\n  formatter,\n  modelValue,\n  placeholder,\n  disabled,\n  initialFocus,\n  pagedNavigation,\n  grid,\n  weekDays: weekdays,\n  weekStartsOn,\n  weekdayFormat,\n  fixedWeeks,\n  multiple,\n  numberOfMonths,\n  readonly,\n  preventDeselect,\n  fullCalendarLabel,\n  headingValue,\n  isInvalid,\n  isDateSelected,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  isOutsideVisibleView,\n  nextPage,\n  prevPage,\n  parentElement,\n  onPlaceholderChange,\n  onDateChange,\n  disableDaysOutsideCurrentView,\n  minValue,\n  maxValue,\n  isPlaceholderFocusable,\n  firstFocusableDate,\n  hasSelectedDate,\n  isSelectedDateDisabled,\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"fullCalendarLabel\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n  >\n    <slot\n      :date=\"placeholder\"\n      :grid=\"grid\"\n      :week-days=\"weekdays\"\n      :week-starts-on=\"weekStartsOn\"\n      :locale=\"locale\"\n      :fixed-weeks=\"fixedWeeks\"\n      :model-value=\"modelValue\"\n    />\n    <div\n      style=\"border: 0px; clip: rect(0px, 0px, 0px, 0px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; white-space: nowrap; width: 1px;\"\n    >\n      <div\n        role=\"heading\"\n        aria-level=\"2\"\n      >\n        {{ fullCalendarLabel }}\n      </div>\n    </div>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\n\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher, WeekDayFormat, WeekStartsOn } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nimport type { Formatter } from '@/shared'\nimport type { Direction } from '@/shared/types'\nimport { isEqualDay, isSameDay } from '@internationalized/date'\nimport { getWeekStartsOn } from '@/date'\nimport { createContext, useDirection, useLocale } from '@/shared'\nimport { getDefaultDate, handleCalendarInitialFocus } from '@/shared/date'\nimport { useCalendar, useCalendarState } from './useCalendar'\n\ntype CalendarRootContext = {\n  locale: Ref<string>\n  modelValue: Ref<DateValue | DateValue[] | undefined>\n  placeholder: Ref<DateValue>\n  pagedNavigation: Ref<boolean>\n  preventDeselect: Ref<boolean>\n  grid: Ref<Grid<DateValue>[]>\n  weekDays: Ref<string[]>\n  weekStartsOn: Ref<WeekStartsOn>\n  weekdayFormat: Ref<WeekDayFormat>\n  fixedWeeks: Ref<boolean>\n  multiple: Ref<boolean>\n  numberOfMonths: Ref<number>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  initialFocus: Ref<boolean>\n  onDateChange: (date: DateValue) => void\n  onPlaceholderChange: (date: DateValue) => void\n  fullCalendarLabel: Ref<string>\n  parentElement: Ref<HTMLElement | undefined>\n  headingValue: Ref<string>\n  isInvalid: Ref<boolean>\n  isDateDisabled: Matcher\n  isDateSelected: Matcher\n  isDateUnavailable?: Matcher\n  isOutsideVisibleView: (date: DateValue) => boolean\n  prevPage: (prevPageFunc?: (date: DateValue) => DateValue) => void\n  nextPage: (nextPageFunc?: (date: DateValue) => DateValue) => void\n  isNextButtonDisabled: (nextPageFunc?: (date: DateValue) => DateValue) => boolean\n  isPrevButtonDisabled: (prevPageFunc?: (date: DateValue) => DateValue) => boolean\n  formatter: Formatter\n  dir: Ref<Direction>\n  disableDaysOutsideCurrentView: Ref<boolean>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  isPlaceholderFocusable: Ref<boolean>\n  firstFocusableDate: Ref<DateValue | undefined>\n  hasSelectedDate: Ref<boolean>\n  isSelectedDateDisabled: Ref<boolean>\n}\n\nexport interface CalendarRootProps extends PrimitiveProps {\n  /** The default value for the calendar */\n  defaultValue?: DateValue\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The placeholder date, which is used to determine what month to display when no date is selected */\n  placeholder?: DateValue\n  /** This property causes the previous and next buttons to navigate by the number of months displayed at once, rather than one month */\n  pagedNavigation?: boolean\n  /** Whether or not to prevent the user from deselecting a date without selecting another date first */\n  preventDeselect?: boolean\n  /** The day of the week to start the calendar on */\n  weekStartsOn?: WeekStartsOn\n  /** The format to use for the weekday strings provided via the weekdays slot prop */\n  weekdayFormat?: WeekDayFormat\n  /** The accessible label for the calendar */\n  calendarLabel?: string\n  /** Whether or not to always display 6 weeks in the calendar */\n  fixedWeeks?: boolean\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** The number of months to display at once */\n  numberOfMonths?: number\n  /** Whether the calendar is disabled */\n  disabled?: boolean\n  /** Whether the calendar is readonly */\n  readonly?: boolean\n  /** If true, the calendar will focus the selected day, today, or the first day of the month depending on what is visible when the calendar is mounted */\n  initialFocus?: boolean\n  /** A function that returns whether or not a date is disabled */\n  isDateDisabled?: Matcher\n  /** A function that returns whether or not a date is unavailable */\n  isDateUnavailable?: Matcher\n  /** The reading direction of the calendar when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** A function that returns the next page of the calendar. It receives the current placeholder as an argument inside the component. */\n  nextPage?: (placeholder: DateValue) => DateValue\n  /** A function that returns the previous page of the calendar. It receives the current placeholder as an argument inside the component. */\n  prevPage?: (placeholder: DateValue) => DateValue\n  /** The controlled selected date value of the calendar. Can be bound as `v-model`. */\n  modelValue?: DateValue | DateValue[] | null\n  /** Whether multiple dates can be selected */\n  multiple?: boolean\n  /** Whether or not to disable days outside the current view. */\n  disableDaysOutsideCurrentView?: boolean\n}\n\nexport type CalendarRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateValue | undefined]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n}\n\nexport const [injectCalendarRootContext, provideCalendarRootContext]\n  = createContext<CalendarRootContext>('CalendarRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, onMounted, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CalendarRootProps>(), {\n  defaultValue: undefined,\n  as: 'div',\n  pagedNavigation: false,\n  preventDeselect: false,\n  weekdayFormat: 'narrow',\n  fixedWeeks: false,\n  multiple: false,\n  numberOfMonths: 1,\n  disabled: false,\n  readonly: false,\n  initialFocus: false,\n  placeholder: undefined,\n  isDateDisabled: undefined,\n  isDateUnavailable: undefined,\n  disableDaysOutsideCurrentView: false,\n})\nconst emits = defineEmits<CalendarRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the placeholder */\n    date: DateValue\n    /** The grid of dates */\n    grid: Grid<DateValue>[]\n    /** The days of the week */\n    weekDays: string[]\n    /** The start of the week */\n    weekStartsOn: WeekStartsOn\n    /** The calendar locale */\n    locale: string\n    /** Whether or not to always display 6 weeks in the calendar */\n    fixedWeeks: boolean\n    /** The current date of the calendar */\n    modelValue: DateValue | DateValue[] | undefined\n  }) => any\n}>()\n\nconst {\n  disabled,\n  readonly,\n  initialFocus,\n  pagedNavigation,\n  weekdayFormat,\n  fixedWeeks,\n  multiple,\n  minValue,\n  maxValue,\n  numberOfMonths,\n  preventDeselect,\n  isDateDisabled: propsIsDateDisabled,\n  isDateUnavailable: propsIsDateUnavailable,\n  calendarLabel,\n  defaultValue,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n  dir: propDir,\n  locale: propLocale,\n  disableDaysOutsideCurrentView,\n} = toRefs(props)\n\nconst { primitiveElement, currentElement: parentElement }\n  = usePrimitiveElement()\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\nconst weekStartsOn = computed(() => props.weekStartsOn ?? getWeekStartsOn(locale.value))\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateValue | DateValue[] | undefined>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: modelValue.value,\n  locale: props.locale,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nfunction onPlaceholderChange(value: DateValue) {\n  placeholder.value = value.copy()\n}\n\nconst {\n  fullCalendarLabel,\n  headingValue,\n  isDateDisabled,\n  isDateUnavailable,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  weekdays,\n  isOutsideVisibleView,\n  nextPage,\n  prevPage,\n  formatter,\n  grid,\n  isPlaceholderFocusable,\n  firstFocusableDate,\n} = useCalendar({\n  locale,\n  placeholder,\n  weekStartsOn,\n  fixedWeeks,\n  numberOfMonths,\n  minValue,\n  maxValue,\n  disabled,\n  weekdayFormat,\n  pagedNavigation,\n  isDateDisabled: propsIsDateDisabled.value,\n  isDateUnavailable: propsIsDateUnavailable.value,\n  calendarLabel,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n})\n\nconst {\n  isInvalid,\n  isDateSelected,\n  hasSelectedDate,\n  isSelectedDateDisabled,\n} = useCalendarState({\n  date: modelValue,\n  isDateDisabled,\n  isDateUnavailable,\n})\n\nwatch(modelValue, (_modelValue) => {\n  if (Array.isArray(_modelValue) && _modelValue.length) {\n    const lastValue = _modelValue.at(-1)\n    if (lastValue && !isEqualDay(placeholder.value, lastValue))\n      onPlaceholderChange(lastValue)\n  }\n  else if (!Array.isArray(_modelValue) && _modelValue && !isEqualDay(placeholder.value, _modelValue)) {\n    onPlaceholderChange(_modelValue)\n  }\n})\n\nfunction onDateChange(value: DateValue) {\n  if (!multiple.value) {\n    if (!modelValue.value) {\n      modelValue.value = value.copy()\n      return\n    }\n\n    if (!preventDeselect.value && isEqualDay(modelValue.value as DateValue, value)) {\n      placeholder.value = value.copy()\n      modelValue.value = undefined\n    }\n    else { modelValue.value = value.copy() }\n  }\n  else if (!modelValue.value) {\n    modelValue.value = [value.copy()]\n  }\n  else if (Array.isArray(modelValue.value)) {\n    const index = modelValue.value.findIndex(date => isSameDay(date, value))\n    if (index === -1) {\n      modelValue.value = [...modelValue.value, value]\n    }\n    else if (!preventDeselect.value) {\n      const next = modelValue.value.filter(date => !isSameDay(date, value))\n      if (!next.length) {\n        placeholder.value = value.copy()\n        modelValue.value = undefined\n        return\n      }\n      modelValue.value = next.map(date => date.copy())\n    }\n  }\n}\n\nonMounted(() => {\n  if (initialFocus.value)\n    handleCalendarInitialFocus(parentElement.value)\n})\n\nprovideCalendarRootContext({\n  isDateUnavailable,\n  dir,\n  isDateDisabled,\n  locale,\n  formatter,\n  modelValue,\n  placeholder,\n  disabled,\n  initialFocus,\n  pagedNavigation,\n  grid,\n  weekDays: weekdays,\n  weekStartsOn,\n  weekdayFormat,\n  fixedWeeks,\n  multiple,\n  numberOfMonths,\n  readonly,\n  preventDeselect,\n  fullCalendarLabel,\n  headingValue,\n  isInvalid,\n  isDateSelected,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  isOutsideVisibleView,\n  nextPage,\n  prevPage,\n  parentElement,\n  onPlaceholderChange,\n  onDateChange,\n  disableDaysOutsideCurrentView,\n  minValue,\n  maxValue,\n  isPlaceholderFocusable,\n  firstFocusableDate,\n  hasSelectedDate,\n  isSelectedDateDisabled,\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"fullCalendarLabel\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n  >\n    <slot\n      :date=\"placeholder\"\n      :grid=\"grid\"\n      :week-days=\"weekdays\"\n      :week-starts-on=\"weekStartsOn\"\n      :locale=\"locale\"\n      :fixed-weeks=\"fixedWeeks\"\n      :model-value=\"modelValue\"\n    />\n    <div\n      style=\"border: 0px; clip: rect(0px, 0px, 0px, 0px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; white-space: nowrap; width: 1px;\"\n    >\n      <div\n        role=\"heading\"\n        aria-level=\"2\"\n      >\n        {{ fullCalendarLabel }}\n      </div>\n    </div>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarCellProps extends PrimitiveProps {\n  /** The date value for the cell */\n  date: DateValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectCalendarRootContext } from './CalendarRoot.vue'\n\nwithDefaults(defineProps<CalendarCellProps>(), { as: 'td' })\nconst rootContext = injectCalendarRootContext()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"gridcell\"\n    :aria-selected=\"rootContext.isDateSelected(date) ? true : undefined\"\n    :aria-disabled=\"rootContext.isDateDisabled(date) || rootContext.isDateUnavailable?.(date) || rootContext.disableDaysOutsideCurrentView.value\"\n    :data-disabled=\"rootContext.isDateDisabled(date) || rootContext.disableDaysOutsideCurrentView.value ? '' : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarCellProps extends PrimitiveProps {\n  /** The date value for the cell */\n  date: DateValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectCalendarRootContext } from './CalendarRoot.vue'\n\nwithDefaults(defineProps<CalendarCellProps>(), { as: 'td' })\nconst rootContext = injectCalendarRootContext()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"gridcell\"\n    :aria-selected=\"rootContext.isDateSelected(date) ? true : undefined\"\n    :aria-disabled=\"rootContext.isDateDisabled(date) || rootContext.isDateUnavailable?.(date) || rootContext.disableDaysOutsideCurrentView.value\"\n    :data-disabled=\"rootContext.isDateDisabled(date) || rootContext.disableDaysOutsideCurrentView.value ? '' : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport {\n\n  getLocalTimeZone,\n  isSameDay,\n  isSameMonth,\n  isToday,\n} from '@internationalized/date'\nimport { computed, nextTick } from 'vue'\nimport { toDate } from '@/date'\nimport { useKbd } from '@/shared'\n\nexport interface CalendarCellTriggerProps extends PrimitiveProps {\n  /** The date value provided to the cell trigger */\n  day: DateValue\n  /** The month in which the cell is rendered */\n  month: DateValue\n}\n\nexport interface CalendarCellTriggerSlot {\n  default?: (props: {\n    /** Current day */\n    dayValue: string\n    /** Current disable state */\n    disabled: boolean\n    /** Current selected state */\n    selected: boolean\n    /** Current today state */\n    today: boolean\n    /** Current outside view state */\n    outsideView: boolean\n    /** Current outside visible view state */\n    outsideVisibleView: boolean\n    /** Current unavailable state */\n    unavailable: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectCalendarRootContext } from './CalendarRoot.vue'\n\nconst props = withDefaults(defineProps<CalendarCellTriggerProps>(), {\n  as: 'div',\n})\n\ndefineSlots<CalendarCellTriggerSlot>()\n\nconst kbd = useKbd()\nconst rootContext = injectCalendarRootContext()\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst dayValue = computed(() => props.day.day.toLocaleString(rootContext.locale.value))\n\nconst labelText = computed(() => {\n  return rootContext.formatter.custom(toDate(props.day), {\n    weekday: 'long',\n    month: 'long',\n    day: 'numeric',\n    year: 'numeric',\n  })\n})\n\nconst isUnavailable = computed(() =>\n  rootContext.isDateUnavailable?.(props.day) ?? false,\n)\nconst isDateToday = computed(() => {\n  return isToday(props.day, getLocalTimeZone())\n})\nconst isOutsideView = computed(() => {\n  return !isSameMonth(props.day, props.month)\n})\n\nconst isOutsideVisibleView = computed(() =>\n  rootContext.isOutsideVisibleView(props.day),\n)\n\nconst isDisabled = computed(() => rootContext.isDateDisabled(props.day) || (rootContext.disableDaysOutsideCurrentView.value && isOutsideView.value))\n\nconst isFocusedDate = computed(() => {\n  if (isOutsideView.value || isDisabled.value)\n    return false\n  if (!rootContext.disabled.value && rootContext.isPlaceholderFocusable.value && isSameDay(props.day, rootContext.placeholder.value))\n    return true\n  if ((!rootContext.hasSelectedDate.value || rootContext.isSelectedDateDisabled.value) && !rootContext.isPlaceholderFocusable.value)\n    return rootContext.firstFocusableDate.value && isSameDay(props.day, rootContext.firstFocusableDate.value)\n  return false\n})\n\nconst isSelectedDate = computed(() => rootContext.isDateSelected(props.day))\n\nfunction changeDate(date: DateValue) {\n  if (rootContext.readonly.value)\n    return\n  if (rootContext.isDateDisabled(date) || rootContext.isDateUnavailable?.(date))\n    return\n\n  rootContext.onDateChange(date)\n}\n\nfunction handleClick() {\n  if (isDisabled.value)\n    return\n  changeDate(props.day)\n}\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  if (isDisabled.value)\n    return\n  e.preventDefault()\n  e.stopPropagation()\n  const parentElement = rootContext.parentElement.value!\n  const indexIncrementation = 7\n  const sign = rootContext.dir.value === 'rtl' ? -1 : 1\n  switch (e.code) {\n    case kbd.ARROW_RIGHT:\n      shiftFocus(props.day, sign)\n      break\n    case kbd.ARROW_LEFT:\n      shiftFocus(props.day, -sign)\n      break\n    case kbd.ARROW_UP:\n      shiftFocus(props.day, -indexIncrementation)\n      break\n    case kbd.ARROW_DOWN:\n      shiftFocus(props.day, indexIncrementation)\n      break\n    case kbd.ENTER:\n    case kbd.SPACE_CODE:\n      changeDate(props.day)\n  }\n\n  function shiftFocus(day: DateValue, add: number) {\n    const candidateDayValue = day.add({ days: add })\n\n    if ((rootContext.minValue.value && candidateDayValue.compare(rootContext.minValue.value) < 0) || (rootContext.maxValue.value && candidateDayValue.compare(rootContext.maxValue.value) > 0))\n      return\n\n    const candidateDay = parentElement.querySelector<HTMLElement>(`[data-value='${candidateDayValue.toString()}']:not([data-outside-view])`)\n    // If the date is not found it means we must change the page\n    if (!candidateDay) {\n      if (add > 0) {\n        if (rootContext.isNextButtonDisabled())\n          return\n        rootContext.nextPage()\n      }\n      else {\n        if (rootContext.isPrevButtonDisabled())\n          return\n        rootContext.prevPage()\n      }\n      nextTick(() => {\n        shiftFocus(day, add)\n      })\n      return\n    }\n\n    if (candidateDay && candidateDay.hasAttribute('data-disabled')) {\n      return shiftFocus(candidateDayValue, add)\n    }\n    rootContext.onPlaceholderChange(candidateDayValue)\n    candidateDay?.focus()\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    role=\"button\"\n    :aria-label=\"labelText\"\n    data-reka-calendar-cell-trigger\n    :aria-disabled=\"isDisabled || isUnavailable ? true : undefined\"\n    :data-selected=\"isSelectedDate ? true : undefined\"\n    :data-value=\"day.toString()\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-unavailable=\"isUnavailable ? '' : undefined\"\n    :data-today=\"isDateToday ? '' : undefined\"\n    :data-outside-view=\"isOutsideView ? '' : undefined\"\n    :data-outside-visible-view=\"isOutsideVisibleView ? '' : undefined\"\n    :data-focused=\"isFocusedDate ? '' : undefined\"\n    :tabindex=\"isFocusedDate ? 0 : isOutsideView || isDisabled ? undefined : -1\"\n    @click=\"handleClick\"\n    @keydown.up.down.left.right.space.enter=\"handleArrowKey\"\n    @keydown.enter.prevent\n  >\n    <slot\n      :day-value=\"dayValue\"\n      :disabled=\"isDisabled\"\n      :today=\"isDateToday\"\n      :selected=\"isSelectedDate\"\n      :outside-view=\"isOutsideView\"\n      :outside-visible-view=\"isOutsideVisibleView\"\n      :unavailable=\"isUnavailable\"\n    >\n      {{ dayValue }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport {\n\n  getLocalTimeZone,\n  isSameDay,\n  isSameMonth,\n  isToday,\n} from '@internationalized/date'\nimport { computed, nextTick } from 'vue'\nimport { toDate } from '@/date'\nimport { useKbd } from '@/shared'\n\nexport interface CalendarCellTriggerProps extends PrimitiveProps {\n  /** The date value provided to the cell trigger */\n  day: DateValue\n  /** The month in which the cell is rendered */\n  month: DateValue\n}\n\nexport interface CalendarCellTriggerSlot {\n  default?: (props: {\n    /** Current day */\n    dayValue: string\n    /** Current disable state */\n    disabled: boolean\n    /** Current selected state */\n    selected: boolean\n    /** Current today state */\n    today: boolean\n    /** Current outside view state */\n    outsideView: boolean\n    /** Current outside visible view state */\n    outsideVisibleView: boolean\n    /** Current unavailable state */\n    unavailable: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectCalendarRootContext } from './CalendarRoot.vue'\n\nconst props = withDefaults(defineProps<CalendarCellTriggerProps>(), {\n  as: 'div',\n})\n\ndefineSlots<CalendarCellTriggerSlot>()\n\nconst kbd = useKbd()\nconst rootContext = injectCalendarRootContext()\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst dayValue = computed(() => props.day.day.toLocaleString(rootContext.locale.value))\n\nconst labelText = computed(() => {\n  return rootContext.formatter.custom(toDate(props.day), {\n    weekday: 'long',\n    month: 'long',\n    day: 'numeric',\n    year: 'numeric',\n  })\n})\n\nconst isUnavailable = computed(() =>\n  rootContext.isDateUnavailable?.(props.day) ?? false,\n)\nconst isDateToday = computed(() => {\n  return isToday(props.day, getLocalTimeZone())\n})\nconst isOutsideView = computed(() => {\n  return !isSameMonth(props.day, props.month)\n})\n\nconst isOutsideVisibleView = computed(() =>\n  rootContext.isOutsideVisibleView(props.day),\n)\n\nconst isDisabled = computed(() => rootContext.isDateDisabled(props.day) || (rootContext.disableDaysOutsideCurrentView.value && isOutsideView.value))\n\nconst isFocusedDate = computed(() => {\n  if (isOutsideView.value || isDisabled.value)\n    return false\n  if (!rootContext.disabled.value && rootContext.isPlaceholderFocusable.value && isSameDay(props.day, rootContext.placeholder.value))\n    return true\n  if ((!rootContext.hasSelectedDate.value || rootContext.isSelectedDateDisabled.value) && !rootContext.isPlaceholderFocusable.value)\n    return rootContext.firstFocusableDate.value && isSameDay(props.day, rootContext.firstFocusableDate.value)\n  return false\n})\n\nconst isSelectedDate = computed(() => rootContext.isDateSelected(props.day))\n\nfunction changeDate(date: DateValue) {\n  if (rootContext.readonly.value)\n    return\n  if (rootContext.isDateDisabled(date) || rootContext.isDateUnavailable?.(date))\n    return\n\n  rootContext.onDateChange(date)\n}\n\nfunction handleClick() {\n  if (isDisabled.value)\n    return\n  changeDate(props.day)\n}\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  if (isDisabled.value)\n    return\n  e.preventDefault()\n  e.stopPropagation()\n  const parentElement = rootContext.parentElement.value!\n  const indexIncrementation = 7\n  const sign = rootContext.dir.value === 'rtl' ? -1 : 1\n  switch (e.code) {\n    case kbd.ARROW_RIGHT:\n      shiftFocus(props.day, sign)\n      break\n    case kbd.ARROW_LEFT:\n      shiftFocus(props.day, -sign)\n      break\n    case kbd.ARROW_UP:\n      shiftFocus(props.day, -indexIncrementation)\n      break\n    case kbd.ARROW_DOWN:\n      shiftFocus(props.day, indexIncrementation)\n      break\n    case kbd.ENTER:\n    case kbd.SPACE_CODE:\n      changeDate(props.day)\n  }\n\n  function shiftFocus(day: DateValue, add: number) {\n    const candidateDayValue = day.add({ days: add })\n\n    if ((rootContext.minValue.value && candidateDayValue.compare(rootContext.minValue.value) < 0) || (rootContext.maxValue.value && candidateDayValue.compare(rootContext.maxValue.value) > 0))\n      return\n\n    const candidateDay = parentElement.querySelector<HTMLElement>(`[data-value='${candidateDayValue.toString()}']:not([data-outside-view])`)\n    // If the date is not found it means we must change the page\n    if (!candidateDay) {\n      if (add > 0) {\n        if (rootContext.isNextButtonDisabled())\n          return\n        rootContext.nextPage()\n      }\n      else {\n        if (rootContext.isPrevButtonDisabled())\n          return\n        rootContext.prevPage()\n      }\n      nextTick(() => {\n        shiftFocus(day, add)\n      })\n      return\n    }\n\n    if (candidateDay && candidateDay.hasAttribute('data-disabled')) {\n      return shiftFocus(candidateDayValue, add)\n    }\n    rootContext.onPlaceholderChange(candidateDayValue)\n    candidateDay?.focus()\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    role=\"button\"\n    :aria-label=\"labelText\"\n    data-reka-calendar-cell-trigger\n    :aria-disabled=\"isDisabled || isUnavailable ? true : undefined\"\n    :data-selected=\"isSelectedDate ? true : undefined\"\n    :data-value=\"day.toString()\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-unavailable=\"isUnavailable ? '' : undefined\"\n    :data-today=\"isDateToday ? '' : undefined\"\n    :data-outside-view=\"isOutsideView ? '' : undefined\"\n    :data-outside-visible-view=\"isOutsideVisibleView ? '' : undefined\"\n    :data-focused=\"isFocusedDate ? '' : undefined\"\n    :tabindex=\"isFocusedDate ? 0 : isOutsideView || isDisabled ? undefined : -1\"\n    @click=\"handleClick\"\n    @keydown.up.down.left.right.space.enter=\"handleArrowKey\"\n    @keydown.enter.prevent\n  >\n    <slot\n      :day-value=\"dayValue\"\n      :disabled=\"isDisabled\"\n      :today=\"isDateToday\"\n      :selected=\"isSelectedDate\"\n      :outside-view=\"isOutsideView\"\n      :outside-visible-view=\"isOutsideVisibleView\"\n      :unavailable=\"isUnavailable\"\n    >\n      {{ dayValue }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarGridProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectCalendarRootContext } from './CalendarRoot.vue'\n\nconst props = withDefaults(defineProps<CalendarGridProps>(), { as: 'table' })\n\nconst rootContext = injectCalendarRootContext()\nconst disabled = computed(() => rootContext.disabled.value ? true : undefined)\nconst readonly = computed(() => rootContext.readonly.value ? true : undefined)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    role=\"application\"\n    :aria-readonly=\"readonly\"\n    :aria-disabled=\"disabled\"\n    :data-readonly=\"readonly && ''\"\n    :data-disabled=\"disabled && ''\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarGridProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectCalendarRootContext } from './CalendarRoot.vue'\n\nconst props = withDefaults(defineProps<CalendarGridProps>(), { as: 'table' })\n\nconst rootContext = injectCalendarRootContext()\nconst disabled = computed(() => rootContext.disabled.value ? true : undefined)\nconst readonly = computed(() => rootContext.readonly.value ? true : undefined)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    role=\"application\"\n    :aria-readonly=\"readonly\"\n    :aria-disabled=\"disabled\"\n    :data-readonly=\"readonly && ''\"\n    :data-disabled=\"disabled && ''\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarGridBodyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CalendarGridBodyProps>(), { as: 'tbody' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarGridBodyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CalendarGridBodyProps>(), { as: 'tbody' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarGridHeadProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CalendarGridHeadProps>(), { as: 'thead' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-hidden=\"true\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarGridHeadProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CalendarGridHeadProps>(), { as: 'thead' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-hidden=\"true\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarGridRowProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CalendarGridRowProps>(), { as: 'tr' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarGridRowProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CalendarGridRowProps>(), { as: 'tr' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarHeadCellProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CalendarHeadCellProps>(), { as: 'th' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarHeadCellProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CalendarHeadCellProps>(), { as: 'th' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CalendarHeaderProps>(), { as: 'div' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<CalendarHeaderProps>(), { as: 'div' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarHeadingProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectCalendarRootContext } from './CalendarRoot.vue'\n\nconst props = withDefaults(defineProps<CalendarHeadingProps>(), { as: 'div' })\n\ndefineSlots<{\n  default?: (props: {\n    /** Current month and year */\n    headingValue: string\n  }) => any\n}>()\n\nconst rootContext = injectCalendarRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n  >\n    <slot :heading-value=\"rootContext.headingValue.value\">\n      {{ rootContext.headingValue.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarHeadingProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectCalendarRootContext } from './CalendarRoot.vue'\n\nconst props = withDefaults(defineProps<CalendarHeadingProps>(), { as: 'div' })\n\ndefineSlots<{\n  default?: (props: {\n    /** Current month and year */\n    headingValue: string\n  }) => any\n}>()\n\nconst rootContext = injectCalendarRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n  >\n    <slot :heading-value=\"rootContext.headingValue.value\">\n      {{ rootContext.headingValue.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarNextProps extends PrimitiveProps {\n  /** The function to be used for the next page. Overwrites the `nextPage` function set on the `CalendarRoot`. */\n  nextPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface CalendarNextSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectCalendarRootContext } from './CalendarRoot.vue'\n\nconst props = withDefaults(defineProps<CalendarNextProps>(), { as: 'button', step: 'month' })\ndefineSlots<CalendarNextSlot>()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isNextButtonDisabled(props.nextPage))\n\nconst rootContext = injectCalendarRootContext()\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.nextPage(props.nextPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Next page\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Next page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarNextProps extends PrimitiveProps {\n  /** The function to be used for the next page. Overwrites the `nextPage` function set on the `CalendarRoot`. */\n  nextPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface CalendarNextSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectCalendarRootContext } from './CalendarRoot.vue'\n\nconst props = withDefaults(defineProps<CalendarNextProps>(), { as: 'button', step: 'month' })\ndefineSlots<CalendarNextSlot>()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isNextButtonDisabled(props.nextPage))\n\nconst rootContext = injectCalendarRootContext()\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.nextPage(props.nextPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Next page\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Next page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarPrevProps extends PrimitiveProps {\n  /** The function to be used for the prev page. Overwrites the `prevPage` function set on the `CalendarRoot`. */\n  prevPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface CalendarPrevSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectCalendarRootContext } from './CalendarRoot.vue'\n\nconst props = withDefaults(defineProps<CalendarPrevProps>(), { as: 'button', step: 'month' })\ndefineSlots<CalendarPrevSlot>()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isPrevButtonDisabled(props.prevPage))\n\nconst rootContext = injectCalendarRootContext()\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.prevPage(props.prevPage)\n}\n</script>\n\n<template>\n  <Primitive\n    aria-label=\"Previous page\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Prev page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface CalendarPrevProps extends PrimitiveProps {\n  /** The function to be used for the prev page. Overwrites the `prevPage` function set on the `CalendarRoot`. */\n  prevPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface CalendarPrevSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectCalendarRootContext } from './CalendarRoot.vue'\n\nconst props = withDefaults(defineProps<CalendarPrevProps>(), { as: 'button', step: 'month' })\ndefineSlots<CalendarPrevSlot>()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isPrevButtonDisabled(props.prevPage))\n\nconst rootContext = injectCalendarRootContext()\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.prevPage(props.prevPage)\n}\n</script>\n\n<template>\n  <Primitive\n    aria-label=\"Previous page\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Prev page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type {\n  Direction,\n  Orientation,\n} from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useDirection } from '@/shared'\n\nexport interface RovingFocusGroupProps extends PrimitiveProps {\n  /**\n   * The orientation of the group.\n   * Mainly so arrow navigation is done accordingly (left & right vs. up & down)\n   */\n  orientation?: Orientation\n  /**\n   * The direction of navigation between items.\n   */\n  dir?: Direction\n  /**\n   * Whether keyboard navigation should loop around\n   * @defaultValue false\n   */\n  loop?: boolean\n  /** The controlled value of the current stop item. Can be binded as `v-model`. */\n  currentTabStopId?: string | null\n  /**\n   * The value of the current stop item.\n   *\n   * Use when you do not need to control the state of the stop item.\n   */\n  defaultCurrentTabStopId?: string\n  /**\n   * When `true`, will prevent scrolling to the focus item when focused.\n   */\n  preventScrollOnEntryFocus?: boolean\n}\n\nexport type RovingFocusGroupEmits = {\n  'entryFocus': [event: Event]\n  'update:currentTabStopId': [value: string | null | undefined]\n}\n\ninterface RovingContext {\n  orientation: Ref<Orientation | undefined>\n  dir: Ref<Direction>\n  loop: Ref<boolean>\n  currentTabStopId: Ref<string | null | undefined>\n  onItemFocus: (tabStopId: string) => void\n  onItemShiftTab: () => void\n  onFocusableItemAdd: () => void\n  onFocusableItemRemove: () => void\n}\n\nexport const [injectRovingFocusGroupContext, provideRovingFocusGroupContext]\n  = createContext<RovingContext>('RovingFocusGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, toRefs } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\nimport { ENTRY_FOCUS, EVENT_OPTIONS, focusFirst } from './utils'\n\nconst props = withDefaults(defineProps<RovingFocusGroupProps>(), {\n  loop: false,\n  orientation: undefined,\n  preventScrollOnEntryFocus: false,\n})\nconst emits = defineEmits<RovingFocusGroupEmits>()\n\nconst { loop, orientation, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nconst currentTabStopId = useVModel(props, 'currentTabStopId', emits, {\n  defaultValue: props.defaultCurrentTabStopId,\n  passive: (props.currentTabStopId === undefined) as false,\n})\nconst isTabbingBackOut = ref(false)\nconst isClickFocus = ref(false)\nconst focusableItemsCount = ref(0)\n\nconst { getItems, CollectionSlot } = useCollection({ isProvider: true })\n\nfunction handleFocus(event: FocusEvent) {\n  // We normally wouldn't need this check, because we already check\n  // that the focus is on the current target and not bubbling to it.\n  // We do this because Safari doesn't focus buttons when clicked, and\n  // instead, the wrapper will get focused and not through a bubbling event.\n  const isKeyboardFocus = !isClickFocus.value\n\n  if (\n    event.currentTarget\n    && event.target === event.currentTarget\n    && isKeyboardFocus\n    && !isTabbingBackOut.value\n  ) {\n    const entryFocusEvent = new CustomEvent(ENTRY_FOCUS, EVENT_OPTIONS)\n    event.currentTarget.dispatchEvent(entryFocusEvent)\n    emits('entryFocus', entryFocusEvent)\n\n    if (!entryFocusEvent.defaultPrevented) {\n      const items = getItems().map(i => i.ref).filter(i => i.dataset.disabled !== '')\n      const activeItem = items.find(item => item.getAttribute('data-active') === '')\n      const highlightedItem = items.find(item => item.getAttribute('data-highlighted') === '')\n      const currentItem = items.find(\n        item => item.id === currentTabStopId.value,\n      )\n      const candidateItems = [activeItem, highlightedItem, currentItem, ...items].filter(\n        Boolean,\n      ) as typeof items\n      focusFirst(candidateItems, props.preventScrollOnEntryFocus)\n    }\n  }\n  isClickFocus.value = false\n}\n\nfunction handleMouseUp() {\n  // reset `isClickFocus` after 1 tick because handleFocus might not triggered due to focused element\n  setTimeout(() => {\n    isClickFocus.value = false\n  }, 1)\n}\n\ndefineExpose({\n  getItems,\n})\n\nprovideRovingFocusGroupContext({\n  loop,\n  dir,\n  orientation,\n  currentTabStopId,\n  onItemFocus: (tabStopId) => {\n    currentTabStopId.value = tabStopId\n  },\n  onItemShiftTab: () => {\n    isTabbingBackOut.value = true\n  },\n  onFocusableItemAdd: () => {\n    focusableItemsCount.value++\n  },\n  onFocusableItemRemove: () => {\n    focusableItemsCount.value--\n  },\n})\n</script>\n\n<template>\n  <CollectionSlot>\n    <Primitive\n      :tabindex=\"isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0\"\n      :data-orientation=\"orientation\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :dir=\"dir\"\n      style=\"outline: none\"\n      @mousedown=\"isClickFocus = true\"\n      @mouseup=\"handleMouseUp\"\n      @focus=\"handleFocus\"\n      @blur=\"isTabbingBackOut = false\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type {\n  Direction,\n  Orientation,\n} from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useDirection } from '@/shared'\n\nexport interface RovingFocusGroupProps extends PrimitiveProps {\n  /**\n   * The orientation of the group.\n   * Mainly so arrow navigation is done accordingly (left & right vs. up & down)\n   */\n  orientation?: Orientation\n  /**\n   * The direction of navigation between items.\n   */\n  dir?: Direction\n  /**\n   * Whether keyboard navigation should loop around\n   * @defaultValue false\n   */\n  loop?: boolean\n  /** The controlled value of the current stop item. Can be binded as `v-model`. */\n  currentTabStopId?: string | null\n  /**\n   * The value of the current stop item.\n   *\n   * Use when you do not need to control the state of the stop item.\n   */\n  defaultCurrentTabStopId?: string\n  /**\n   * When `true`, will prevent scrolling to the focus item when focused.\n   */\n  preventScrollOnEntryFocus?: boolean\n}\n\nexport type RovingFocusGroupEmits = {\n  'entryFocus': [event: Event]\n  'update:currentTabStopId': [value: string | null | undefined]\n}\n\ninterface RovingContext {\n  orientation: Ref<Orientation | undefined>\n  dir: Ref<Direction>\n  loop: Ref<boolean>\n  currentTabStopId: Ref<string | null | undefined>\n  onItemFocus: (tabStopId: string) => void\n  onItemShiftTab: () => void\n  onFocusableItemAdd: () => void\n  onFocusableItemRemove: () => void\n}\n\nexport const [injectRovingFocusGroupContext, provideRovingFocusGroupContext]\n  = createContext<RovingContext>('RovingFocusGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, toRefs } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\nimport { ENTRY_FOCUS, EVENT_OPTIONS, focusFirst } from './utils'\n\nconst props = withDefaults(defineProps<RovingFocusGroupProps>(), {\n  loop: false,\n  orientation: undefined,\n  preventScrollOnEntryFocus: false,\n})\nconst emits = defineEmits<RovingFocusGroupEmits>()\n\nconst { loop, orientation, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nconst currentTabStopId = useVModel(props, 'currentTabStopId', emits, {\n  defaultValue: props.defaultCurrentTabStopId,\n  passive: (props.currentTabStopId === undefined) as false,\n})\nconst isTabbingBackOut = ref(false)\nconst isClickFocus = ref(false)\nconst focusableItemsCount = ref(0)\n\nconst { getItems, CollectionSlot } = useCollection({ isProvider: true })\n\nfunction handleFocus(event: FocusEvent) {\n  // We normally wouldn't need this check, because we already check\n  // that the focus is on the current target and not bubbling to it.\n  // We do this because Safari doesn't focus buttons when clicked, and\n  // instead, the wrapper will get focused and not through a bubbling event.\n  const isKeyboardFocus = !isClickFocus.value\n\n  if (\n    event.currentTarget\n    && event.target === event.currentTarget\n    && isKeyboardFocus\n    && !isTabbingBackOut.value\n  ) {\n    const entryFocusEvent = new CustomEvent(ENTRY_FOCUS, EVENT_OPTIONS)\n    event.currentTarget.dispatchEvent(entryFocusEvent)\n    emits('entryFocus', entryFocusEvent)\n\n    if (!entryFocusEvent.defaultPrevented) {\n      const items = getItems().map(i => i.ref).filter(i => i.dataset.disabled !== '')\n      const activeItem = items.find(item => item.getAttribute('data-active') === '')\n      const highlightedItem = items.find(item => item.getAttribute('data-highlighted') === '')\n      const currentItem = items.find(\n        item => item.id === currentTabStopId.value,\n      )\n      const candidateItems = [activeItem, highlightedItem, currentItem, ...items].filter(\n        Boolean,\n      ) as typeof items\n      focusFirst(candidateItems, props.preventScrollOnEntryFocus)\n    }\n  }\n  isClickFocus.value = false\n}\n\nfunction handleMouseUp() {\n  // reset `isClickFocus` after 1 tick because handleFocus might not triggered due to focused element\n  setTimeout(() => {\n    isClickFocus.value = false\n  }, 1)\n}\n\ndefineExpose({\n  getItems,\n})\n\nprovideRovingFocusGroupContext({\n  loop,\n  dir,\n  orientation,\n  currentTabStopId,\n  onItemFocus: (tabStopId) => {\n    currentTabStopId.value = tabStopId\n  },\n  onItemShiftTab: () => {\n    isTabbingBackOut.value = true\n  },\n  onFocusableItemAdd: () => {\n    focusableItemsCount.value++\n  },\n  onFocusableItemRemove: () => {\n    focusableItemsCount.value--\n  },\n})\n</script>\n\n<template>\n  <CollectionSlot>\n    <Primitive\n      :tabindex=\"isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0\"\n      :data-orientation=\"orientation\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :dir=\"dir\"\n      style=\"outline: none\"\n      @mousedown=\"isClickFocus = true\"\n      @mouseup=\"handleMouseUp\"\n      @focus=\"handleFocus\"\n      @blur=\"isTabbingBackOut = false\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RovingFocusItemProps extends PrimitiveProps {\n  tabStopId?: string\n  /**\n   * When `false`, item will not be focusable.\n   * @defaultValue `true`\n   */\n  focusable?: boolean\n  /** When `true`, item will be initially focused. */\n  active?: boolean\n  /** When `true`, shift + arrow key will allow focusing on next/previous item. */\n  allowShiftKey?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, nextTick, onMounted, onUnmounted } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\nimport { useId } from '@/shared'\nimport { injectRovingFocusGroupContext } from './RovingFocusGroup.vue'\nimport { focusFirst, getFocusIntent, wrapArray } from './utils'\n\nconst props = withDefaults(defineProps<RovingFocusItemProps>(), {\n  focusable: true,\n  as: 'span',\n})\n\nconst context = injectRovingFocusGroupContext()\nconst randomId = useId()\nconst id = computed(() => props.tabStopId || randomId)\nconst isCurrentTabStop = computed(\n  () => context.currentTabStopId.value === id.value,\n)\n\nconst { getItems, CollectionItem } = useCollection()\n\nonMounted(() => {\n  if (props.focusable)\n    context.onFocusableItemAdd()\n})\nonUnmounted(() => {\n  if (props.focusable)\n    context.onFocusableItemRemove()\n})\n\nfunction handleKeydown(event: KeyboardEvent) {\n  if (event.key === 'Tab' && event.shiftKey) {\n    context.onItemShiftTab()\n    return\n  }\n\n  if (event.target !== event.currentTarget)\n    return\n\n  const focusIntent = getFocusIntent(\n    event,\n    context.orientation.value,\n    context.dir.value,\n  )\n\n  if (focusIntent !== undefined) {\n    if (event.metaKey || event.ctrlKey || event.altKey || (props.allowShiftKey ? false : event.shiftKey))\n      return\n    event.preventDefault()\n    let candidateNodes = [...getItems().map(i => i.ref).filter(i => i.dataset.disabled !== '')]\n\n    if (focusIntent === 'last') {\n      candidateNodes.reverse()\n    }\n    else if (focusIntent === 'prev' || focusIntent === 'next') {\n      if (focusIntent === 'prev')\n        candidateNodes.reverse()\n      const currentIndex = candidateNodes.indexOf(\n        event.currentTarget as HTMLElement,\n      )\n\n      candidateNodes = context.loop.value\n        ? wrapArray(candidateNodes, currentIndex + 1)\n        : candidateNodes.slice(currentIndex + 1)\n    }\n\n    nextTick(() => focusFirst(candidateNodes))\n  }\n}\n</script>\n\n<template>\n  <CollectionItem>\n    <Primitive\n      :tabindex=\"isCurrentTabStop ? 0 : -1\"\n      :data-orientation=\"context.orientation.value\"\n      :data-active=\"active ? '' : undefined\"\n      :data-disabled=\"!focusable ? '' : undefined\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      @mousedown=\"\n        (event: MouseEvent) => {\n          // We prevent focusing non-focusable items on `mousedown`.\n          // Even though the item has tabIndex={-1}, that only means take it out of the tab order.\n          if (!focusable) event.preventDefault();\n          // Safari doesn't focus a button when clicked so we run our logic on mousedown also\n          else context.onItemFocus(id);\n        }\n      \"\n      @focus=\"context.onItemFocus(id)\"\n      @keydown=\"handleKeydown\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RovingFocusItemProps extends PrimitiveProps {\n  tabStopId?: string\n  /**\n   * When `false`, item will not be focusable.\n   * @defaultValue `true`\n   */\n  focusable?: boolean\n  /** When `true`, item will be initially focused. */\n  active?: boolean\n  /** When `true`, shift + arrow key will allow focusing on next/previous item. */\n  allowShiftKey?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, nextTick, onMounted, onUnmounted } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\nimport { useId } from '@/shared'\nimport { injectRovingFocusGroupContext } from './RovingFocusGroup.vue'\nimport { focusFirst, getFocusIntent, wrapArray } from './utils'\n\nconst props = withDefaults(defineProps<RovingFocusItemProps>(), {\n  focusable: true,\n  as: 'span',\n})\n\nconst context = injectRovingFocusGroupContext()\nconst randomId = useId()\nconst id = computed(() => props.tabStopId || randomId)\nconst isCurrentTabStop = computed(\n  () => context.currentTabStopId.value === id.value,\n)\n\nconst { getItems, CollectionItem } = useCollection()\n\nonMounted(() => {\n  if (props.focusable)\n    context.onFocusableItemAdd()\n})\nonUnmounted(() => {\n  if (props.focusable)\n    context.onFocusableItemRemove()\n})\n\nfunction handleKeydown(event: KeyboardEvent) {\n  if (event.key === 'Tab' && event.shiftKey) {\n    context.onItemShiftTab()\n    return\n  }\n\n  if (event.target !== event.currentTarget)\n    return\n\n  const focusIntent = getFocusIntent(\n    event,\n    context.orientation.value,\n    context.dir.value,\n  )\n\n  if (focusIntent !== undefined) {\n    if (event.metaKey || event.ctrlKey || event.altKey || (props.allowShiftKey ? false : event.shiftKey))\n      return\n    event.preventDefault()\n    let candidateNodes = [...getItems().map(i => i.ref).filter(i => i.dataset.disabled !== '')]\n\n    if (focusIntent === 'last') {\n      candidateNodes.reverse()\n    }\n    else if (focusIntent === 'prev' || focusIntent === 'next') {\n      if (focusIntent === 'prev')\n        candidateNodes.reverse()\n      const currentIndex = candidateNodes.indexOf(\n        event.currentTarget as HTMLElement,\n      )\n\n      candidateNodes = context.loop.value\n        ? wrapArray(candidateNodes, currentIndex + 1)\n        : candidateNodes.slice(currentIndex + 1)\n    }\n\n    nextTick(() => focusFirst(candidateNodes))\n  }\n}\n</script>\n\n<template>\n  <CollectionItem>\n    <Primitive\n      :tabindex=\"isCurrentTabStop ? 0 : -1\"\n      :data-orientation=\"context.orientation.value\"\n      :data-active=\"active ? '' : undefined\"\n      :data-disabled=\"!focusable ? '' : undefined\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      @mousedown=\"\n        (event: MouseEvent) => {\n          // We prevent focusing non-focusable items on `mousedown`.\n          // Even though the item has tabIndex={-1}, that only means take it out of the tab order.\n          if (!focusable) event.preventDefault();\n          // Safari doesn't focus a button when clicked so we run our logic on mousedown also\n          else context.onItemFocus(id);\n        }\n      \"\n      @focus=\"context.onItemFocus(id)\"\n      @keydown=\"handleKeydown\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { RovingFocusGroupProps } from '@/RovingFocus'\nimport type { AcceptableValue, FormFieldProps } from '@/shared/types'\nimport { useVModel } from '@vueuse/core'\nimport { computed, toRefs } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { createContext, useDirection, useFormControl } from '@/shared'\n\nexport interface CheckboxGroupRootProps<T = AcceptableValue> extends Pick<RovingFocusGroupProps, 'as' | 'asChild' | 'dir' | 'orientation' | 'loop'>, FormFieldProps {\n  /** The value of the checkbox when it is initially rendered. Use when you do not need to control its value. */\n  defaultValue?: T[]\n  /** The controlled value of the checkbox. Can be binded with v-model. */\n  modelValue?: T[]\n  /** When `false`, navigating through the items using arrow keys will be disabled. */\n  rovingFocus?: boolean\n  /** When `true`, prevents the user from interacting with the checkboxes */\n  disabled?: boolean\n}\n\nexport type CheckboxGroupRootEmits<T = AcceptableValue> = {\n  /** Event handler called when the value of the checkbox changes. */\n  'update:modelValue': [value: T[]]\n}\n\ninterface CheckboxGroupRootContext {\n  modelValue: Ref<AcceptableValue[]>\n  rovingFocus: Ref<boolean>\n  disabled: Ref<boolean>\n}\n\nexport const [injectCheckboxGroupRootContext, provideCheckboxGroupRootContext]\n  = createContext<CheckboxGroupRootContext>('CheckboxGroupRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport { RovingFocusGroup } from '@/RovingFocus'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\nconst props = withDefaults(defineProps<CheckboxGroupRootProps<T>>(), {\n  rovingFocus: true,\n})\nconst emits = defineEmits<CheckboxGroupRootEmits<T>>()\n\nconst { disabled, rovingFocus, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst isFormControl = useFormControl(currentElement)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? [],\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<T[]>\n\nconst rovingFocusProps = computed(() => {\n  return rovingFocus.value ? { loop: props.loop, dir: dir.value, orientation: props.orientation } : {}\n})\n\nprovideCheckboxGroupRootContext({\n  modelValue,\n  rovingFocus,\n  disabled,\n})\n</script>\n\n<template>\n  <component\n    :is=\"rovingFocus ? RovingFocusGroup : Primitive\"\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    v-bind=\"rovingFocusProps\"\n  >\n    <slot />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      :name=\"name\"\n      :value=\"modelValue\"\n      :required=\"required\"\n    />\n  </component>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { RovingFocusGroupProps } from '@/RovingFocus'\nimport type { AcceptableValue, FormFieldProps } from '@/shared/types'\nimport { useVModel } from '@vueuse/core'\nimport { computed, toRefs } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { createContext, useDirection, useFormControl } from '@/shared'\n\nexport interface CheckboxGroupRootProps<T = AcceptableValue> extends Pick<RovingFocusGroupProps, 'as' | 'asChild' | 'dir' | 'orientation' | 'loop'>, FormFieldProps {\n  /** The value of the checkbox when it is initially rendered. Use when you do not need to control its value. */\n  defaultValue?: T[]\n  /** The controlled value of the checkbox. Can be binded with v-model. */\n  modelValue?: T[]\n  /** When `false`, navigating through the items using arrow keys will be disabled. */\n  rovingFocus?: boolean\n  /** When `true`, prevents the user from interacting with the checkboxes */\n  disabled?: boolean\n}\n\nexport type CheckboxGroupRootEmits<T = AcceptableValue> = {\n  /** Event handler called when the value of the checkbox changes. */\n  'update:modelValue': [value: T[]]\n}\n\ninterface CheckboxGroupRootContext {\n  modelValue: Ref<AcceptableValue[]>\n  rovingFocus: Ref<boolean>\n  disabled: Ref<boolean>\n}\n\nexport const [injectCheckboxGroupRootContext, provideCheckboxGroupRootContext]\n  = createContext<CheckboxGroupRootContext>('CheckboxGroupRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport { RovingFocusGroup } from '@/RovingFocus'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\nconst props = withDefaults(defineProps<CheckboxGroupRootProps<T>>(), {\n  rovingFocus: true,\n})\nconst emits = defineEmits<CheckboxGroupRootEmits<T>>()\n\nconst { disabled, rovingFocus, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst isFormControl = useFormControl(currentElement)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? [],\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<T[]>\n\nconst rovingFocusProps = computed(() => {\n  return rovingFocus.value ? { loop: props.loop, dir: dir.value, orientation: props.orientation } : {}\n})\n\nprovideCheckboxGroupRootContext({\n  modelValue,\n  rovingFocus,\n  disabled,\n})\n</script>\n\n<template>\n  <component\n    :is=\"rovingFocus ? RovingFocusGroup : Primitive\"\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    v-bind=\"rovingFocusProps\"\n  >\n    <slot />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      :name=\"name\"\n      :value=\"modelValue\"\n      :required=\"required\"\n    />\n  </component>\n</template>\n","export type CheckedState = boolean | 'indeterminate'\n\nexport function isIndeterminate(checked?: CheckedState): checked is 'indeterminate' {\n  return checked === 'indeterminate'\n}\n\nexport function getState(checked: CheckedState) {\n  return isIndeterminate(checked) ? 'indeterminate' : checked ? 'checked' : 'unchecked'\n}\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { CheckedState } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue, FormFieldProps } from '@/shared/types'\nimport { useVModel } from '@vueuse/core'\nimport { createContext, isNullish, isValueEqualOrExist, useFormControl, useForwardExpose } from '@/shared'\nimport { injectCheckboxGroupRootContext } from './CheckboxGroupRoot.vue'\n\nexport interface CheckboxRootProps<T = boolean> extends PrimitiveProps, FormFieldProps {\n  /** The value of the checkbox when it is initially rendered. Use when you do not need to control its value. */\n  defaultValue?: T | 'indeterminate'\n  /** The controlled value of the checkbox. Can be binded with v-model. */\n  modelValue?: T | 'indeterminate' | null\n  /** When `true`, prevents the user from interacting with the checkbox */\n  disabled?: boolean\n  /**\n   * The value given as data when submitted with a `name`.\n   *  @defaultValue \"on\"\n   */\n  value?: AcceptableValue\n  /** Id of the element */\n  id?: string\n  /**\n   * The value used when the checkbox is checked. Defaults to `true`.\n   */\n  trueValue?: T\n  /**\n   * The value used when the checkbox is unchecked. Defaults to `false`.\n   */\n  falseValue?: T\n}\n\nexport type CheckboxRootEmits<T = boolean> = {\n  /** Event handler called when the value of the checkbox changes. */\n  'update:modelValue': [value: T | 'indeterminate']\n}\n\ninterface CheckboxRootContext {\n  disabled: Ref<boolean>\n  state: Ref<CheckedState>\n}\n\nexport const [injectCheckboxRootContext, provideCheckboxRootContext]\n  = createContext<CheckboxRootContext>('CheckboxRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T = boolean\">\nimport { isEqual } from 'ohash'\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\nimport { getState, isIndeterminate } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<CheckboxRootProps<T>>(), {\n  modelValue: undefined,\n  value: 'on',\n  as: 'button',\n  trueValue: (() => true) as unknown as undefined,\n  falseValue: (() => false) as unknown as undefined,\n})\nconst emits = defineEmits<CheckboxRootEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current value */\n    modelValue: typeof modelValue.value\n    /** Current state */\n    state: typeof checkboxState.value\n  }) => any\n}>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst checkboxGroupContext = injectCheckboxGroupRootContext(null)\n\nconst modelValue = useVModel(props as any, 'modelValue', emits as any, {\n  defaultValue: props.defaultValue ?? props.falseValue,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<T | 'indeterminate'>\n\nconst disabled = computed(() => checkboxGroupContext?.disabled.value || props.disabled)\n\nconst isChecked = computed(() => isEqual(modelValue.value, props.trueValue))\n\nconst checkboxState = computed<CheckedState>(() => {\n  if (!isNullish(checkboxGroupContext?.modelValue.value)) {\n    return isValueEqualOrExist(checkboxGroupContext.modelValue.value, props.value)\n  }\n  else {\n    if (modelValue.value === 'indeterminate')\n      return 'indeterminate'\n    return isChecked.value\n  }\n})\n\nfunction handleClick() {\n  if (!isNullish(checkboxGroupContext?.modelValue.value)) {\n    const modelValueArray = [...(checkboxGroupContext.modelValue.value || [])]\n    if (isValueEqualOrExist(modelValueArray, props.value)) {\n      const index = modelValueArray.findIndex(i => isEqual(i, props.value))\n      modelValueArray.splice(index, 1)\n    }\n    else {\n      modelValueArray.push(props.value)\n    }\n    checkboxGroupContext.modelValue.value = modelValueArray\n  }\n  else {\n    if (modelValue.value === 'indeterminate') {\n      modelValue.value = props.trueValue as T\n    }\n    else {\n      modelValue.value = isChecked.value ? props.falseValue as T : props.trueValue as T\n    }\n  }\n}\n\nconst isFormControl = useFormControl(currentElement)\nconst ariaLabel = computed(() => props.id && currentElement.value\n  ? (document.querySelector(`[for=\"${props.id}\"]`) as HTMLLabelElement)?.innerText\n  : undefined)\n\nprovideCheckboxRootContext({\n  disabled,\n  state: checkboxState,\n})\n</script>\n\n<template>\n  <component\n    v-bind=\"$attrs\"\n    :is=\"checkboxGroupContext?.rovingFocus.value ? RovingFocusItem : Primitive\"\n    :id=\"id\"\n    :ref=\"forwardRef\"\n    role=\"checkbox\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :aria-checked=\"isIndeterminate(checkboxState) ? 'mixed' : checkboxState\"\n    :aria-required=\"required\"\n    :aria-label=\"$attrs['aria-label'] || ariaLabel\"\n    :data-state=\"getState(checkboxState)\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :disabled=\"disabled\"\n    :focusable=\"checkboxGroupContext?.rovingFocus.value ? !disabled : undefined\"\n    @keydown.enter.prevent=\"() => {\n      // According to WAI ARIA, Checkboxes don't activate on enter keypress\n    }\"\n    @click=\"handleClick\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :state=\"checkboxState\"\n    />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name && !checkboxGroupContext\"\n      type=\"checkbox\"\n      :checked=\"!!checkboxState\"\n      :name=\"name\"\n      :value=\"value\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n    />\n  </component>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { CheckedState } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue, FormFieldProps } from '@/shared/types'\nimport { useVModel } from '@vueuse/core'\nimport { createContext, isNullish, isValueEqualOrExist, useFormControl, useForwardExpose } from '@/shared'\nimport { injectCheckboxGroupRootContext } from './CheckboxGroupRoot.vue'\n\nexport interface CheckboxRootProps<T = boolean> extends PrimitiveProps, FormFieldProps {\n  /** The value of the checkbox when it is initially rendered. Use when you do not need to control its value. */\n  defaultValue?: T | 'indeterminate'\n  /** The controlled value of the checkbox. Can be binded with v-model. */\n  modelValue?: T | 'indeterminate' | null\n  /** When `true`, prevents the user from interacting with the checkbox */\n  disabled?: boolean\n  /**\n   * The value given as data when submitted with a `name`.\n   *  @defaultValue \"on\"\n   */\n  value?: AcceptableValue\n  /** Id of the element */\n  id?: string\n  /**\n   * The value used when the checkbox is checked. Defaults to `true`.\n   */\n  trueValue?: T\n  /**\n   * The value used when the checkbox is unchecked. Defaults to `false`.\n   */\n  falseValue?: T\n}\n\nexport type CheckboxRootEmits<T = boolean> = {\n  /** Event handler called when the value of the checkbox changes. */\n  'update:modelValue': [value: T | 'indeterminate']\n}\n\ninterface CheckboxRootContext {\n  disabled: Ref<boolean>\n  state: Ref<CheckedState>\n}\n\nexport const [injectCheckboxRootContext, provideCheckboxRootContext]\n  = createContext<CheckboxRootContext>('CheckboxRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T = boolean\">\nimport { isEqual } from 'ohash'\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\nimport { getState, isIndeterminate } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<CheckboxRootProps<T>>(), {\n  modelValue: undefined,\n  value: 'on',\n  as: 'button',\n  trueValue: (() => true) as unknown as undefined,\n  falseValue: (() => false) as unknown as undefined,\n})\nconst emits = defineEmits<CheckboxRootEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current value */\n    modelValue: typeof modelValue.value\n    /** Current state */\n    state: typeof checkboxState.value\n  }) => any\n}>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst checkboxGroupContext = injectCheckboxGroupRootContext(null)\n\nconst modelValue = useVModel(props as any, 'modelValue', emits as any, {\n  defaultValue: props.defaultValue ?? props.falseValue,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<T | 'indeterminate'>\n\nconst disabled = computed(() => checkboxGroupContext?.disabled.value || props.disabled)\n\nconst isChecked = computed(() => isEqual(modelValue.value, props.trueValue))\n\nconst checkboxState = computed<CheckedState>(() => {\n  if (!isNullish(checkboxGroupContext?.modelValue.value)) {\n    return isValueEqualOrExist(checkboxGroupContext.modelValue.value, props.value)\n  }\n  else {\n    if (modelValue.value === 'indeterminate')\n      return 'indeterminate'\n    return isChecked.value\n  }\n})\n\nfunction handleClick() {\n  if (!isNullish(checkboxGroupContext?.modelValue.value)) {\n    const modelValueArray = [...(checkboxGroupContext.modelValue.value || [])]\n    if (isValueEqualOrExist(modelValueArray, props.value)) {\n      const index = modelValueArray.findIndex(i => isEqual(i, props.value))\n      modelValueArray.splice(index, 1)\n    }\n    else {\n      modelValueArray.push(props.value)\n    }\n    checkboxGroupContext.modelValue.value = modelValueArray\n  }\n  else {\n    if (modelValue.value === 'indeterminate') {\n      modelValue.value = props.trueValue as T\n    }\n    else {\n      modelValue.value = isChecked.value ? props.falseValue as T : props.trueValue as T\n    }\n  }\n}\n\nconst isFormControl = useFormControl(currentElement)\nconst ariaLabel = computed(() => props.id && currentElement.value\n  ? (document.querySelector(`[for=\"${props.id}\"]`) as HTMLLabelElement)?.innerText\n  : undefined)\n\nprovideCheckboxRootContext({\n  disabled,\n  state: checkboxState,\n})\n</script>\n\n<template>\n  <component\n    v-bind=\"$attrs\"\n    :is=\"checkboxGroupContext?.rovingFocus.value ? RovingFocusItem : Primitive\"\n    :id=\"id\"\n    :ref=\"forwardRef\"\n    role=\"checkbox\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :aria-checked=\"isIndeterminate(checkboxState) ? 'mixed' : checkboxState\"\n    :aria-required=\"required\"\n    :aria-label=\"$attrs['aria-label'] || ariaLabel\"\n    :data-state=\"getState(checkboxState)\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :disabled=\"disabled\"\n    :focusable=\"checkboxGroupContext?.rovingFocus.value ? !disabled : undefined\"\n    @keydown.enter.prevent=\"() => {\n      // According to WAI ARIA, Checkboxes don't activate on enter keypress\n    }\"\n    @click=\"handleClick\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :state=\"checkboxState\"\n    />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name && !checkboxGroupContext\"\n      type=\"checkbox\"\n      :checked=\"!!checkboxState\"\n      :name=\"name\"\n      :value=\"value\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n    />\n  </component>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface CheckboxIndicatorProps extends PrimitiveProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { Primitive } from '@/Primitive'\nimport { injectCheckboxRootContext } from './CheckboxRoot.vue'\nimport { getState, isIndeterminate } from './utils'\n\nwithDefaults(defineProps<CheckboxIndicatorProps>(), {\n  as: 'span',\n})\nconst { forwardRef } = useForwardExpose()\n\nconst rootContext = injectCheckboxRootContext()\n</script>\n\n<template>\n  <Presence\n    :present=\"forceMount || isIndeterminate(rootContext.state.value) || rootContext.state.value === true\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :data-state=\"getState(rootContext.state.value)\"\n      :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n      :style=\"{ pointerEvents: 'none' }\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      v-bind=\"$attrs\"\n    >\n      <slot />\n    </Primitive>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface CheckboxIndicatorProps extends PrimitiveProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { Primitive } from '@/Primitive'\nimport { injectCheckboxRootContext } from './CheckboxRoot.vue'\nimport { getState, isIndeterminate } from './utils'\n\nwithDefaults(defineProps<CheckboxIndicatorProps>(), {\n  as: 'span',\n})\nconst { forwardRef } = useForwardExpose()\n\nconst rootContext = injectCheckboxRootContext()\n</script>\n\n<template>\n  <Presence\n    :present=\"forceMount || isIndeterminate(rootContext.state.value) || rootContext.state.value === true\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :data-state=\"getState(rootContext.state.value)\"\n      :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n      :style=\"{ pointerEvents: 'none' }\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      v-bind=\"$attrs\"\n    >\n      <slot />\n    </Primitive>\n  </Presence>\n</template>\n","import type { Color, ColorFormat, HSBColor, HSLColor, RGBColor } from './types'\n\n/**\n * Converts a Color object to a string representation.\n */\nexport function colorToString(color: Color, format: ColorFormat = 'hex'): string {\n  switch (format) {\n    case 'hex':\n      return colorToHex(color)\n    case 'rgb':\n      return colorToRgb(color)\n    case 'hsl':\n      return colorToHsl(color)\n    case 'hsb':\n      return colorToHsb(color)\n    default:\n      throw new Error(`Unknown format: ${format}`)\n  }\n}\n\n/**\n * Converts any color to hex string.\n */\nexport function colorToHex(color: Color): string {\n  const rgb = color.space === 'rgb' ? color : convertToRgb(color)\n  const toHex = (n: number) => Math.round(n).toString(16).padStart(2, '0')\n\n  if (rgb.alpha < 1) {\n    const alpha = Math.round(rgb.alpha * 255).toString(16).padStart(2, '0')\n    return `#${toHex(rgb.r)}${toHex(rgb.g)}${toHex(rgb.b)}${alpha}`\n  }\n\n  return `#${toHex(rgb.r)}${toHex(rgb.g)}${toHex(rgb.b)}`\n}\n\n/**\n * Converts any color to rgb() string.\n */\nexport function colorToRgb(color: Color): string {\n  const rgb = color.space === 'rgb' ? color : convertToRgb(color)\n  const { r, g, b, alpha } = rgb\n\n  if (alpha < 1) {\n    return `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${alpha})`\n  }\n  return `rgb(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)})`\n}\n\n/**\n * Converts any color to hsl() string.\n */\nexport function colorToHsl(color: Color): string {\n  const hsl = color.space === 'hsl' ? color : convertToHsl(color)\n  const { h, s, l, alpha } = hsl\n\n  if (alpha < 1) {\n    return `hsla(${Math.round(h)}, ${Math.round(s)}%, ${Math.round(l)}%, ${alpha})`\n  }\n  return `hsl(${Math.round(h)}, ${Math.round(s)}%, ${Math.round(l)}%)`\n}\n\n/**\n * Converts any color to hsb() string.\n */\nexport function colorToHsb(color: Color): string {\n  const hsb = color.space === 'hsb' ? color : convertToHsb(color)\n  const { h, s, b, alpha } = hsb\n\n  if (alpha < 1) {\n    return `hsba(${Math.round(h)}, ${Math.round(s)}%, ${Math.round(b)}%, ${alpha})`\n  }\n  return `hsb(${Math.round(h)}, ${Math.round(s)}%, ${Math.round(b)}%)`\n}\n\n/**\n * Converts any color to RGB color space.\n */\nexport function convertToRgb(color: Color): RGBColor {\n  if (color.space === 'rgb') {\n    return color\n  }\n  if (color.space === 'hsl') {\n    return hslToRgb(color)\n  }\n  if (color.space === 'hsb') {\n    return hsbToRgb(color)\n  }\n  throw new Error(`Unknown color space: ${(color as Color).space}`)\n}\n\n/**\n * Converts any color to HSL color space.\n */\nexport function convertToHsl(color: Color): HSLColor {\n  if (color.space === 'hsl') {\n    return color\n  }\n  return rgbToHsl(convertToRgb(color))\n}\n\n/**\n * Converts any color to HSB color space.\n */\nexport function convertToHsb(color: Color): HSBColor {\n  if (color.space === 'hsb') {\n    return color\n  }\n  return rgbToHsb(convertToRgb(color))\n}\n\n/**\n * Converts RGB to HSL.\n */\nfunction rgbToHsl(rgb: RGBColor): HSLColor {\n  const r = rgb.r / 255\n  const g = rgb.g / 255\n  const b = rgb.b / 255\n\n  const max = Math.max(r, g, b)\n  const min = Math.min(r, g, b)\n  let h = 0\n  let s = 0\n  const l = (max + min) / 2\n\n  if (max !== min) {\n    const d = max - min\n    s = l > 0.5 ? d / (2 - max - min) : d / (max + min)\n    switch (max) {\n      case r:\n        h = (g - b) / d + (g < b ? 6 : 0)\n        break\n      case g:\n        h = (b - r) / d + 2\n        break\n      case b:\n        h = (r - g) / d + 4\n        break\n    }\n    h /= 6\n  }\n\n  return {\n    space: 'hsl',\n    h: h * 360,\n    s: s * 100,\n    l: l * 100,\n    alpha: rgb.alpha,\n  }\n}\n\n/**\n * Converts HSL to RGB.\n */\nfunction hslToRgb(hsl: HSLColor): RGBColor {\n  const h = hsl.h / 360\n  const s = hsl.s / 100\n  const l = hsl.l / 100\n\n  let r: number, g: number, b: number\n\n  if (s === 0) {\n    r = g = b = l\n  }\n  else {\n    const hue2rgb = (p: number, q: number, t: number) => {\n      if (t < 0)\n        t += 1\n      if (t > 1)\n        t -= 1\n      if (t < 1 / 6)\n        return p + (q - p) * 6 * t\n      if (t < 1 / 2)\n        return q\n      if (t < 2 / 3)\n        return p + (q - p) * (2 / 3 - t) * 6\n      return p\n    }\n\n    const q = l < 0.5 ? l * (1 + s) : l + s - l * s\n    const p = 2 * l - q\n    r = hue2rgb(p, q, h + 1 / 3)\n    g = hue2rgb(p, q, h)\n    b = hue2rgb(p, q, h - 1 / 3)\n  }\n\n  return {\n    space: 'rgb',\n    r: r * 255,\n    g: g * 255,\n    b: b * 255,\n    alpha: hsl.alpha,\n  }\n}\n\n/**\n * Converts RGB to HSB.\n */\nfunction rgbToHsb(rgb: RGBColor): HSBColor {\n  const r = rgb.r / 255\n  const g = rgb.g / 255\n  const b = rgb.b / 255\n\n  const max = Math.max(r, g, b)\n  const min = Math.min(r, g, b)\n  const d = max - min\n\n  let h = 0\n  const s = max === 0 ? 0 : d / max\n  const v = max\n\n  if (max !== min) {\n    switch (max) {\n      case r:\n        h = (g - b) / d + (g < b ? 6 : 0)\n        break\n      case g:\n        h = (b - r) / d + 2\n        break\n      case b:\n        h = (r - g) / d + 4\n        break\n    }\n    h /= 6\n  }\n\n  return {\n    space: 'hsb',\n    h: h * 360,\n    s: s * 100,\n    b: v * 100,\n    alpha: rgb.alpha,\n  }\n}\n\n/**\n * Converts HSB to RGB.\n */\nfunction hsbToRgb(hsb: HSBColor): RGBColor {\n  const h = hsb.h / 360\n  const s = hsb.s / 100\n  const v = hsb.b / 100\n\n  let r = 0\n  let g = 0\n  let b = 0\n\n  const i = Math.floor(h * 6)\n  const f = h * 6 - i\n  const p = v * (1 - s)\n  const q = v * (1 - f * s)\n  const t = v * (1 - (1 - f) * s)\n\n  switch (i % 6) {\n    case 0:\n      r = v\n      g = t\n      b = p\n      break\n    case 1:\n      r = q\n      g = v\n      b = p\n      break\n    case 2:\n      r = p\n      g = v\n      b = t\n      break\n    case 3:\n      r = p\n      g = q\n      b = v\n      break\n    case 4:\n      r = t\n      g = p\n      b = v\n      break\n    case 5:\n      r = v\n      g = p\n      b = q\n      break\n  }\n\n  return {\n    space: 'rgb',\n    r: r * 255,\n    g: g * 255,\n    b: b * 255,\n    alpha: hsb.alpha,\n  }\n}\n","import type { ChannelRange, Color, ColorChannel, ColorSpace, HSBColor, HSLColor, RGBColor } from './types'\nimport { convertToHsb, convertToHsl, convertToRgb } from './convert'\n\n/**\n * Gets the range (min, max, step) for a color channel.\n */\nexport function getChannelRange(channel: ColorChannel): ChannelRange {\n  switch (channel) {\n    case 'hue':\n      return { min: 0, max: 360, step: 1 }\n    case 'saturation':\n    case 'lightness':\n    case 'brightness':\n    case 'alpha':\n      return { min: 0, max: 100, step: 1 }\n    case 'red':\n    case 'green':\n    case 'blue':\n      return { min: 0, max: 255, step: 1 }\n    default:\n      throw new Error(`Unknown channel: ${channel}`)\n  }\n}\n\n/**\n * Gets the display name for a channel.\n */\nexport function getChannelName(channel: ColorChannel): string {\n  const names: Record<ColorChannel, string> = {\n    red: 'Red',\n    green: 'Green',\n    blue: 'Blue',\n    hue: 'Hue',\n    saturation: 'Saturation',\n    lightness: 'Lightness',\n    brightness: 'Brightness',\n    alpha: 'Alpha',\n  }\n  return names[channel] ?? channel\n}\n\n/**\n * Gets the value of a specific channel from a color.\n * Avoids conversion if the color is already in the target color space.\n */\nexport function getChannelValue(color: Color, channel: ColorChannel): number {\n  switch (channel) {\n    case 'red':\n      return color.space === 'rgb' ? (color as RGBColor).r : convertToRgb(color).r\n    case 'green':\n      return color.space === 'rgb' ? (color as RGBColor).g : convertToRgb(color).g\n    case 'blue':\n      return color.space === 'rgb' ? (color as RGBColor).b : convertToRgb(color).b\n    case 'hue':\n      return color.space === 'hsl' ? (color as HSLColor).h : convertToHsl(color).h\n    case 'saturation':\n      if (color.space === 'hsl')\n        return (color as HSLColor).s\n      if (color.space === 'hsb')\n        return (color as HSBColor).s\n      return convertToHsl(color).s\n    case 'lightness':\n      return color.space === 'hsl' ? (color as HSLColor).l : convertToHsl(color).l\n    case 'brightness':\n      return color.space === 'hsb' ? (color as HSBColor).b : convertToHsb(color).b\n    case 'alpha':\n      return color.alpha * 100\n    default:\n      throw new Error(`Unknown channel: ${channel}`)\n  }\n}\n\n/**\n * Sets a channel value on a color, returning a new color.\n * The returned color maintains the original color space.\n */\nexport function setChannelValue(color: Color, channel: ColorChannel, value: number): Color {\n  const range = getChannelRange(channel)\n  const clamped = Math.max(range.min, Math.min(range.max, value))\n\n  // Alpha is handled the same across all spaces\n  if (channel === 'alpha') {\n    return { ...color, alpha: clamped / 100 } as Color\n  }\n\n  // For RGB channels, convert to RGB, set, then convert back\n  if (channel === 'red' || channel === 'green' || channel === 'blue') {\n    const rgb = convertToRgb(color)\n    const newRgb: RGBColor = {\n      ...rgb,\n      [channel === 'red' ? 'r' : channel === 'green' ? 'g' : 'b']: clamped,\n    }\n    return convertFromRgb(newRgb, color.space)\n  }\n\n  // For HSL channels\n  if (channel === 'hue' || channel === 'lightness') {\n    const hsl = convertToHsl(color)\n    const newHsl: HSLColor = {\n      ...hsl,\n      [channel === 'hue' ? 'h' : 'l']: clamped,\n    }\n    return convertFromHsl(newHsl, color.space)\n  }\n\n  // For saturation, respect the color's native space (HSB vs HSL)\n  if (channel === 'saturation') {\n    if (color.space === 'hsb') {\n      const hsb = convertToHsb(color)\n      const newHsb: HSBColor = { ...hsb, s: clamped }\n      return convertFromHsb(newHsb, color.space)\n    }\n    const hsl = convertToHsl(color)\n    const newHsl: HSLColor = { ...hsl, s: clamped }\n    return convertFromHsl(newHsl, color.space)\n  }\n\n  // For brightness (HSB-only)\n  if (channel === 'brightness') {\n    const hsb = convertToHsb(color)\n    const newHsb: HSBColor = { ...hsb, b: clamped }\n    return convertFromHsb(newHsb, color.space)\n  }\n\n  throw new Error(`Unknown channel: ${channel}`)\n}\n\n/**\n * Sets multiple channel values at once, preserving exact values.\n * Useful when updating 2D color areas where both channels change simultaneously.\n */\nexport function setChannelValues(\n  color: Color,\n  channels: Array<{ channel: ColorChannel, value: number }>,\n): Color {\n  if (channels.length === 0)\n    return color\n  if (channels.length === 1) {\n    return setChannelValue(color, channels[0].channel, channels[0].value)\n  }\n\n  // Determine the target color space based on all channels\n  const channelNames = channels.map(c => c.channel)\n  const hasBrightness = channelNames.includes('brightness')\n  const hasLightness = channelNames.includes('lightness')\n  const hasRgb = channelNames.some(c => c === 'red' || c === 'green' || c === 'blue')\n\n  let workingColor: Color\n\n  if (hasRgb) {\n    workingColor = convertToRgb(color)\n  }\n  else if (hasBrightness) {\n    // HSB mode\n    workingColor = convertToHsb(color)\n  }\n  else if (hasLightness) {\n    // HSL mode\n    workingColor = convertToHsl(color)\n  }\n  else {\n    // Default to HSL for hue/saturation\n    workingColor = convertToHsl(color)\n  }\n\n  // Apply all channel values\n  for (const { channel, value } of channels) {\n    const range = getChannelRange(channel)\n    const clamped = Math.max(range.min, Math.min(range.max, value))\n\n    if (channel === 'alpha') {\n      workingColor = { ...workingColor, alpha: clamped / 100 }\n    }\n    else if (workingColor.space === 'rgb' && (channel === 'red' || channel === 'green' || channel === 'blue')) {\n      const key = channel === 'red' ? 'r' : channel === 'green' ? 'g' : 'b'\n      workingColor = { ...workingColor, [key]: clamped } as RGBColor\n    }\n    else if (workingColor.space === 'hsl' && (channel === 'hue' || channel === 'saturation' || channel === 'lightness')) {\n      const key = channel === 'hue' ? 'h' : channel === 'saturation' ? 's' : 'l'\n      workingColor = { ...workingColor, [key]: clamped } as HSLColor\n    }\n    else if (workingColor.space === 'hsb' && (channel === 'hue' || channel === 'saturation' || channel === 'brightness')) {\n      const key = channel === 'hue' ? 'h' : channel === 'saturation' ? 's' : 'b'\n      workingColor = { ...workingColor, [key]: clamped } as HSBColor\n    }\n  }\n\n  // For color areas, keep the working color space to preserve precision\n  // Only convert back if we're in single-channel mode (channels.length === 1)\n  // In multi-channel mode (like 2D color area), the working color space is more appropriate\n  if (channels.length === 1 && workingColor.space !== color.space) {\n    if (color.space === 'rgb')\n      return convertToRgb(workingColor)\n    if (color.space === 'hsl')\n      return convertToHsl(workingColor)\n    if (color.space === 'hsb')\n      return convertToHsb(workingColor)\n  }\n\n  return workingColor\n}\n\n/**\n * Converts an RGB color to a specific color space.\n */\nfunction convertFromRgb(rgb: RGBColor, targetSpace: ColorSpace): Color {\n  if (targetSpace === 'rgb') {\n    return rgb\n  }\n  if (targetSpace === 'hsl') {\n    return rgbToHsl(rgb)\n  }\n  if (targetSpace === 'hsb') {\n    return rgbToHsb(rgb)\n  }\n  throw new Error(`Unknown color space: ${targetSpace}`)\n}\n\n/**\n * Converts an HSL color to a specific color space.\n */\nfunction convertFromHsl(hsl: HSLColor, targetSpace: ColorSpace): Color {\n  if (targetSpace === 'hsl') {\n    return hsl\n  }\n  const rgb = hslToRgb(hsl)\n  if (targetSpace === 'rgb') {\n    return rgb\n  }\n  if (targetSpace === 'hsb') {\n    return rgbToHsb(rgb)\n  }\n  throw new Error(`Unknown color space: ${targetSpace}`)\n}\n\n/**\n * Converts an HSB color to a specific color space.\n */\nfunction convertFromHsb(hsb: HSBColor, targetSpace: ColorSpace): Color {\n  if (targetSpace === 'hsb') {\n    return hsb\n  }\n  const rgb = hsbToRgb(hsb)\n  if (targetSpace === 'rgb') {\n    return rgb\n  }\n  if (targetSpace === 'hsl') {\n    return rgbToHsl(rgb)\n  }\n  throw new Error(`Unknown color space: ${targetSpace}`)\n}\n\n// Conversion helpers (duplicated from convert.ts to avoid circular deps)\nfunction rgbToHsl(rgb: RGBColor): HSLColor {\n  const r = rgb.r / 255\n  const g = rgb.g / 255\n  const b = rgb.b / 255\n\n  const max = Math.max(r, g, b)\n  const min = Math.min(r, g, b)\n  let h = 0\n  let s = 0\n  const l = (max + min) / 2\n\n  if (max !== min) {\n    const d = max - min\n    s = l > 0.5 ? d / (2 - max - min) : d / (max + min)\n    switch (max) {\n      case r:\n        h = (g - b) / d + (g < b ? 6 : 0)\n        break\n      case g:\n        h = (b - r) / d + 2\n        break\n      case b:\n        h = (r - g) / d + 4\n        break\n    }\n    h /= 6\n  }\n\n  return {\n    space: 'hsl',\n    h: h * 360,\n    s: s * 100,\n    l: l * 100,\n    alpha: rgb.alpha,\n  }\n}\n\nfunction hslToRgb(hsl: HSLColor): RGBColor {\n  const h = hsl.h / 360\n  const s = hsl.s / 100\n  const l = hsl.l / 100\n\n  let r: number, g: number, b: number\n\n  if (s === 0) {\n    r = g = b = l\n  }\n  else {\n    const hue2rgb = (p: number, q: number, t: number) => {\n      if (t < 0)\n        t += 1\n      if (t > 1)\n        t -= 1\n      if (t < 1 / 6)\n        return p + (q - p) * 6 * t\n      if (t < 1 / 2)\n        return q\n      if (t < 2 / 3)\n        return p + (q - p) * (2 / 3 - t) * 6\n      return p\n    }\n\n    const q = l < 0.5 ? l * (1 + s) : l + s - l * s\n    const p = 2 * l - q\n    r = hue2rgb(p, q, h + 1 / 3)\n    g = hue2rgb(p, q, h)\n    b = hue2rgb(p, q, h - 1 / 3)\n  }\n\n  return {\n    space: 'rgb',\n    r: r * 255,\n    g: g * 255,\n    b: b * 255,\n    alpha: hsl.alpha,\n  }\n}\n\nfunction rgbToHsb(rgb: RGBColor): HSBColor {\n  const r = rgb.r / 255\n  const g = rgb.g / 255\n  const b = rgb.b / 255\n\n  const max = Math.max(r, g, b)\n  const min = Math.min(r, g, b)\n  const d = max - min\n\n  let h = 0\n  const s = max === 0 ? 0 : d / max\n  const v = max\n\n  if (max !== min) {\n    switch (max) {\n      case r:\n        h = (g - b) / d + (g < b ? 6 : 0)\n        break\n      case g:\n        h = (b - r) / d + 2\n        break\n      case b:\n        h = (r - g) / d + 4\n        break\n    }\n    h /= 6\n  }\n\n  return {\n    space: 'hsb',\n    h: h * 360,\n    s: s * 100,\n    b: v * 100,\n    alpha: rgb.alpha,\n  }\n}\n\nfunction hsbToRgb(hsb: HSBColor): RGBColor {\n  const h = hsb.h / 360\n  const s = hsb.s / 100\n  const v = hsb.b / 100\n\n  let r = 0\n  let g = 0\n  let b = 0\n\n  const i = Math.floor(h * 6)\n  const f = h * 6 - i\n  const p = v * (1 - s)\n  const q = v * (1 - f * s)\n  const t = v * (1 - (1 - f) * s)\n\n  switch (i % 6) {\n    case 0:\n      r = v\n      g = t\n      b = p\n      break\n    case 1:\n      r = q\n      g = v\n      b = p\n      break\n    case 2:\n      r = p\n      g = v\n      b = t\n      break\n    case 3:\n      r = p\n      g = q\n      b = v\n      break\n    case 4:\n      r = t\n      g = p\n      b = v\n      break\n    case 5:\n      r = v\n      g = p\n      b = q\n      break\n  }\n\n  return {\n    space: 'rgb',\n    r: r * 255,\n    g: g * 255,\n    b: b * 255,\n    alpha: hsb.alpha,\n  }\n}\n","import type { Color, ColorChannel, ColorSpace, RGBColor } from './types'\nimport { colorToString, convertToHsb, convertToHsl, convertToRgb } from './convert'\n\n/**\n * Generates a CSS gradient for a color slider track.\n */\nexport function getSliderGradient(\n  color: Color,\n  channel: ColorChannel,\n  colorSpace: ColorSpace = color.space as ColorSpace,\n): string {\n  const hsl = convertToHsl(color)\n  const hsb = convertToHsb(color)\n\n  switch (channel) {\n    case 'hue':\n      return getHueGradient()\n    case 'saturation':\n      return getSaturationGradient(hsl, colorSpace)\n    case 'lightness':\n      return getLightnessGradient(hsl)\n    case 'brightness':\n      return getBrightnessGradient(hsb)\n    case 'red':\n      return getRedGradient(color)\n    case 'green':\n      return getGreenGradient(color)\n    case 'blue':\n      return getBlueGradient(color)\n    case 'alpha':\n      return getAlphaGradient(color)\n    default:\n      return ''\n  }\n}\n\n/**\n * Generates a CSS gradient for a color area (2D picker).\n */\nexport function getAreaGradient(\n  color: Color,\n  xChannel: ColorChannel,\n  yChannel: ColorChannel,\n  colorSpace: ColorSpace = color.space as ColorSpace,\n): { background: string, gradientX: string, gradientY: string } {\n  const hsl = convertToHsl(color)\n  const hsb = convertToHsb(color)\n\n  // Determine which gradient layers to apply based on channels\n  const gradientX = getChannelGradientForArea(color, xChannel, colorSpace, 'x')\n  const gradientY = getChannelGradientForArea(color, yChannel, colorSpace, 'y')\n\n  // Background is the color with both channels at max\n  const bgColor = getAreaBackgroundColor(color, xChannel, yChannel, colorSpace)\n\n  return {\n    background: bgColor,\n    gradientX,\n    gradientY,\n  }\n}\n\nfunction getHueGradient(): string {\n  return 'linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)'\n}\n\nfunction getSaturationGradient(hsl: { h: number, s: number, l: number, alpha: number }, colorSpace: ColorSpace): string {\n  const start = colorToString({ space: 'hsl', h: hsl.h, s: 0, l: colorSpace === 'hsl' ? hsl.l : 50, alpha: 1 }, 'hsl')\n  const end = colorToString({ space: 'hsl', h: hsl.h, s: 100, l: colorSpace === 'hsl' ? hsl.l : 50, alpha: 1 }, 'hsl')\n  return `linear-gradient(to right, ${start}, ${end})`\n}\n\nfunction getLightnessGradient(hsl: { h: number, s: number, l: number, alpha: number }): string {\n  const start = colorToString({ space: 'hsl', h: hsl.h, s: hsl.s, l: 0, alpha: 1 }, 'hsl')\n  const mid = colorToString({ space: 'hsl', h: hsl.h, s: hsl.s, l: 50, alpha: 1 }, 'hsl')\n  const end = colorToString({ space: 'hsl', h: hsl.h, s: hsl.s, l: 100, alpha: 1 }, 'hsl')\n  return `linear-gradient(to right, ${start}, ${mid}, ${end})`\n}\n\nfunction getBrightnessGradient(hsb: { h: number, s: number, b: number, alpha: number }): string {\n  const start = colorToString({ space: 'hsb', h: hsb.h, s: hsb.s, b: 0, alpha: 1 }, 'rgb')\n  const end = colorToString({ space: 'hsb', h: hsb.h, s: hsb.s, b: 100, alpha: 1 }, 'rgb')\n  return `linear-gradient(to right, ${start}, ${end})`\n}\n\nfunction getRedGradient(color: Color): string {\n  const { g, b, alpha } = color.space === 'rgb' ? color : { g: 128, b: 128, alpha: 1 }\n  const start = colorToString({ space: 'rgb', r: 0, g, b, alpha: 1 }, 'rgb')\n  const end = colorToString({ space: 'rgb', r: 255, g, b, alpha: 1 }, 'rgb')\n  return `linear-gradient(to right, ${start}, ${end})`\n}\n\nfunction getGreenGradient(color: Color): string {\n  const { r, b, alpha } = color.space === 'rgb' ? color : { r: 128, b: 128, alpha: 1 }\n  const start = colorToString({ space: 'rgb', r, g: 0, b, alpha: 1 }, 'rgb')\n  const end = colorToString({ space: 'rgb', r, g: 255, b, alpha: 1 }, 'rgb')\n  return `linear-gradient(to right, ${start}, ${end})`\n}\n\nfunction getBlueGradient(color: Color): string {\n  const { r, g, alpha } = color.space === 'rgb' ? color : { r: 128, g: 128, alpha: 1 }\n  const start = colorToString({ space: 'rgb', r, g, b: 0, alpha: 1 }, 'rgb')\n  const end = colorToString({ space: 'rgb', r, g, b: 255, alpha: 1 }, 'rgb')\n  return `linear-gradient(to right, ${start}, ${end})`\n}\n\n// Checkerboard pattern used behind alpha gradients to visualize transparency\nconst CHECKERBOARD_LAYERS = [\n  'linear-gradient(45deg, #ccc 25%, transparent 25%)',\n  'linear-gradient(-45deg, #ccc 25%, transparent 25%)',\n  'linear-gradient(45deg, transparent 75%, #ccc 75%)',\n  'linear-gradient(-45deg, transparent 75%, #ccc 75%)',\n].join(', ')\n\nfunction getAlphaGradient(color: Color): string {\n  const { r, g, b } = color.space === 'rgb' ? color : convertToRgb(color)\n  const solidRgb = `rgb(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)})`\n  return `linear-gradient(to right, transparent, ${solidRgb}), ${CHECKERBOARD_LAYERS}`\n}\n\nfunction getChannelGradientForArea(\n  color: Color,\n  channel: ColorChannel,\n  colorSpace: ColorSpace,\n  axis: 'x' | 'y',\n): string {\n  const direction = axis === 'x' ? 'to right' : 'to top'\n  const hsl = convertToHsl(color)\n  const hsb = convertToHsb(color)\n\n  switch (channel) {\n    case 'saturation': {\n      if (colorSpace === 'hsb') {\n        // For HSB: White to transparent (overlay on pure hue)\n        // Left side (0% sat) = white, Right side (100% sat) = transparent (shows pure hue)\n        return `linear-gradient(${direction}, rgba(255, 255, 255, 1), rgba(255, 255, 255, 0))`\n      }\n      // For HSL: White to full color\n      const fullColor = colorToString({ space: 'hsl', h: hsl.h, s: 100, l: 50, alpha: 1 }, 'rgb')\n      return `linear-gradient(${direction}, #ffffff, ${fullColor})`\n    }\n    case 'lightness': {\n      // White -> color -> black\n      const mid = colorToString({ space: 'hsl', h: hsl.h, s: hsl.s, l: 50, alpha: 1 }, 'rgb')\n      return `linear-gradient(${direction}, #000000, ${mid}, #ffffff)`\n    }\n    case 'brightness': {\n      // For HSB: Transparent to black (overlay on pure hue)\n      // Top (100% brightness) = transparent (shows pure hue), Bottom (0% brightness) = black\n      return `linear-gradient(${direction}, rgba(0, 0, 0, 0), rgba(0, 0, 0, 1))`\n    }\n    default:\n      return ''\n  }\n}\n\nfunction getAreaBackgroundColor(\n  color: Color,\n  xChannel: ColorChannel,\n  yChannel: ColorChannel,\n  colorSpace: ColorSpace,\n): string {\n  const hsl = convertToHsl(color)\n  const hsb = convertToHsb(color)\n\n  // For HSL saturation/lightness area, show pure hue\n  if (colorSpace === 'hsl' && xChannel === 'saturation' && yChannel === 'lightness') {\n    return colorToString({ space: 'hsl', h: hsl.h, s: 100, l: 50, alpha: 1 }, 'rgb')\n  }\n\n  // For HSB saturation/brightness area, show pure hue\n  if (colorSpace === 'hsb' && xChannel === 'saturation' && yChannel === 'brightness') {\n    return colorToString({ space: 'hsb', h: hsb.h, s: 100, b: 100, alpha: 1 }, 'rgb')\n  }\n\n  // Default to white\n  return '#ffffff'\n}\n\n/**\n * Gets the CSS background style for a color area.\n */\nexport function getAreaBackgroundStyle(\n  color: Color,\n  xChannel: ColorChannel,\n  yChannel: ColorChannel,\n  colorSpace: ColorSpace = color.space as ColorSpace,\n): Record<string, string> {\n  const hsl = convertToHsl(color)\n  const hsb = convertToHsb(color)\n\n  // Hue-based color picker (Hue/Saturation, Hue/Lightness, Hue/Brightness)\n  // Shows full rainbow spectrum horizontally\n  if (xChannel === 'hue') {\n    // Full hue gradient as background (rainbow spectrum)\n    const hueGradient = 'linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)'\n\n    if (yChannel === 'saturation') {\n      // Vertical: gray at bottom (0% sat) fading to transparent at top (100% sat shows hue)\n      // No blend mode needed — transparent stacking is correct\n      const desatColor = colorToString({ space: 'hsl', h: hsl.h, s: 0, l: hsl.l, alpha: 1 }, 'rgb')\n      return {\n        backgroundImage: `linear-gradient(to bottom, transparent, ${desatColor}), ${hueGradient}`,\n      }\n    }\n\n    if (yChannel === 'lightness') {\n      // Vertical: black at bottom (L=0) → transparent at middle (L=50, shows hue) → white at top (L=100)\n      return {\n        backgroundImage: `linear-gradient(to top, #000000, transparent, #ffffff), ${hueGradient}`,\n      }\n    }\n\n    if (yChannel === 'brightness') {\n      // Vertical: black at bottom (B=0) → transparent at top (B=100, shows hue)\n      return {\n        backgroundImage: `linear-gradient(to top, #000000, transparent), ${hueGradient}`,\n      }\n    }\n  }\n\n  // Classic color picker gradients for saturation-based pickers\n  if (xChannel === 'saturation' && (yChannel === 'lightness' || yChannel === 'brightness')) {\n    if (colorSpace === 'hsl') {\n      // HSL: Base is pure hue at 50% lightness\n      // Saturation x-axis: gray (S=0) at left fading to transparent (shows pure hue at S=100)\n      // Lightness y-axis: black at bottom (L=0), transparent at middle (L=50), white at top (L=100)\n      const hueColor = colorToString({ space: 'hsl', h: hsl.h, s: 100, l: 50, alpha: 1 }, 'rgb')\n      const grayColor = colorToString({ space: 'hsl', h: hsl.h, s: 0, l: 50, alpha: 1 }, 'rgb')\n      const satGradient = `linear-gradient(to right, ${grayColor}, transparent)`\n      const lightGradient = `linear-gradient(to top, #000000, transparent, #ffffff)`\n\n      return {\n        backgroundColor: hueColor,\n        backgroundImage: `${lightGradient}, ${satGradient}`,\n      }\n    }\n\n    if (colorSpace === 'hsb') {\n      // HSB: Base is pure hue (full sat, full brightness)\n      // Top edge: white (0% sat) → pure hue (100% sat)\n      // Bottom edge: always black (0% brightness)\n      const hueColor = colorToString({ space: 'hsb', h: hsb.h, s: 100, b: 100, alpha: 1 }, 'rgb')\n      // White to transparent (left to right)\n      const satGradient = `linear-gradient(to right, #ffffff, transparent)`\n      // Black gradient from bottom up\n      const brightGradient = `linear-gradient(to top, #000000, transparent)`\n\n      return {\n        backgroundColor: hueColor,\n        backgroundImage: `${brightGradient}, ${satGradient}`,\n      }\n    }\n  }\n\n  // RGB color picker (Red/Green, Red/Blue, Green/Blue)\n  // Uses screen blend mode to combine gradients additively (like React Spectrum)\n  // Formula: 1 - (1 - a) * (1 - b), effectively adds RGB values\n  if (colorSpace === 'rgb'\n    && (xChannel === 'red' || xChannel === 'green' || xChannel === 'blue')\n    && (yChannel === 'red' || yChannel === 'green' || yChannel === 'blue')) {\n    const rgb = convertToRgb(color)\n\n    // Get the constant channel (z-channel - the one NOT x or y)\n    const allChannels = ['red', 'green', 'blue'] as const\n    const varyingChannels = [xChannel, yChannel]\n    const constantChannel = allChannels.find(c => !varyingChannels.includes(c))!\n    const constantValue = rgb[constantChannel === 'red' ? 'r' : constantChannel === 'green' ? 'g' : 'b']\n\n    // Create the three layers for screen blend mode:\n    // 1. X gradient: black to full-X-color\n    // 2. Y gradient: black to full-Y-color\n    // 3. Background: black with Z channel set\n\n    // X gradient: black (0,0,0) → full X (255,0,0) for red, etc.\n    const xColorStart: RGBColor = { space: 'rgb', r: 0, g: 0, b: 0, alpha: 1 }\n    const xColorEnd: RGBColor = {\n      space: 'rgb',\n      r: xChannel === 'red' ? 255 : 0,\n      g: xChannel === 'green' ? 255 : 0,\n      b: xChannel === 'blue' ? 255 : 0,\n      alpha: 1,\n    }\n    const xGradient = `linear-gradient(to right, ${colorToString(xColorStart, 'rgb')}, ${colorToString(xColorEnd, 'rgb')})`\n\n    // Y gradient: black (0,0,0) → full Y (0,255,0) for green, etc.\n    const yColorEnd: RGBColor = {\n      space: 'rgb',\n      r: yChannel === 'red' ? 255 : 0,\n      g: yChannel === 'green' ? 255 : 0,\n      b: yChannel === 'blue' ? 255 : 0,\n      alpha: 1,\n    }\n    const yGradient = `linear-gradient(to top, ${colorToString(xColorStart, 'rgb')}, ${colorToString(yColorEnd, 'rgb')})`\n\n    // Background: black with constant Z channel value\n    const bgColor: RGBColor = {\n      space: 'rgb',\n      r: constantChannel === 'red' ? constantValue : 0,\n      g: constantChannel === 'green' ? constantValue : 0,\n      b: constantChannel === 'blue' ? constantValue : 0,\n      alpha: 1,\n    }\n\n    return {\n      backgroundColor: colorToString(bgColor, 'rgb'),\n      backgroundImage: `${yGradient}, ${xGradient}`,\n      backgroundBlendMode: 'screen',\n    }\n  }\n\n  // Fallback for other combinations\n  const { background, gradientX, gradientY } = getAreaGradient(color, xChannel, yChannel, colorSpace)\n  const gradients: string[] = []\n  if (gradientY)\n    gradients.push(gradientY)\n  if (gradientX)\n    gradients.push(gradientX)\n\n  return {\n    backgroundColor: background,\n    backgroundImage: gradients.join(', '),\n  }\n}\n\n/**\n * Gets the CSS background for a slider track.\n */\nexport function getSliderBackgroundStyle(\n  color: Color,\n  channel: ColorChannel,\n  colorSpace: ColorSpace = color.space as ColorSpace,\n): Record<string, string> {\n  const gradient = getSliderGradient(color, channel, colorSpace)\n\n  if (channel === 'alpha') {\n    return {\n      background: gradient,\n      backgroundSize: '100% 100%, 8px 8px, 8px 8px, 8px 8px, 8px 8px',\n      backgroundPosition: '0 0, 0 0, 0 4px, 4px -4px, -4px 0px',\n    }\n  }\n\n  return {\n    background: gradient,\n  }\n}\n","import type { Color, HSBColor, HSLColor, RGBColor } from './types'\n\nconst HEX3_RE = /^[0-9A-F]{3}$/i\nconst HEX6_RE = /^[0-9A-F]{6}$/i\nconst HEX8_RE = /^[0-9A-F]{8}$/i\nconst RGB_RE = /rgba?\\(\\s*([\\d.]+)\\s*,\\s*([\\d.]+)\\s*,\\s*([\\d.]+)\\s*(?:,\\s*([\\d.]+)\\s*)?\\)/\nconst HSL_RE = /hsla?\\(\\s*([\\d.]+)\\s*,\\s*([\\d.]+)%\\s*,\\s*([\\d.]+)%\\s*(?:,\\s*([\\d.]+)\\s*)?\\)/\nconst HSB_RE = /hsb[av]?\\(\\s*([\\d.]+)\\s*,\\s*([\\d.]+)%?\\s*,\\s*([\\d.]+)%?\\s*(?:,\\s*([\\d.]+)\\s*)?\\)/\n\n/**\n * Parses a color string into a Color object.\n * Supports hex (#rrggbb, #rgb), rgb(), hsl(), and hsb()/hsv() formats.\n */\nexport function parseColor(value: string): Color {\n  const trimmed = value.trim().toLowerCase()\n\n  // Hex format\n  if (trimmed.startsWith('#')) {\n    return parseHex(trimmed)\n  }\n\n  // rgb() format\n  if (trimmed.startsWith('rgb')) {\n    return parseRgb(trimmed)\n  }\n\n  // hsl() format\n  if (trimmed.startsWith('hsl')) {\n    return parseHsl(trimmed)\n  }\n\n  // hsb() or hsv() format\n  if (trimmed.startsWith('hsb') || trimmed.startsWith('hsv')) {\n    return parseHsb(trimmed)\n  }\n\n  throw new Error(`Unable to parse color: ${value}`)\n}\n\nfunction parseHex(hex: string): RGBColor {\n  let normalized = hex.slice(1)\n\n  // Validate hex format (3, 6, or 8 hex digits)\n  if (!HEX3_RE.test(normalized) && !HEX6_RE.test(normalized) && !HEX8_RE.test(normalized)) {\n    throw new Error(`Invalid hex color: ${hex}. Expected format: #RGB, #RRGGBB, or #RRGGBBAA`)\n  }\n\n  // Expand shorthand (e.g., #f00 -> #ff0000)\n  if (normalized.length === 3) {\n    normalized = normalized.split('').map(c => c + c).join('')\n  }\n\n  // Handle 6-digit hex\n  if (normalized.length === 6) {\n    const bigint = parseInt(normalized, 16)\n    return {\n      space: 'rgb',\n      r: (bigint >> 16) & 255,\n      g: (bigint >> 8) & 255,\n      b: bigint & 255,\n      alpha: 1,\n    }\n  }\n\n  // Handle 8-digit hex (with alpha)\n  if (normalized.length === 8) {\n    const bigint = parseInt(normalized, 16)\n    return {\n      space: 'rgb',\n      r: (bigint >> 24) & 255,\n      g: (bigint >> 16) & 255,\n      b: (bigint >> 8) & 255,\n      alpha: (bigint & 255) / 255,\n    }\n  }\n\n  throw new Error(`Invalid hex color: ${hex}`)\n}\n\nfunction parseRgb(rgb: string): RGBColor {\n  const match = rgb.match(RGB_RE)\n  if (!match) {\n    throw new Error(`Invalid RGB color: ${rgb}`)\n  }\n\n  return {\n    space: 'rgb',\n    r: parseFloat(match[1]),\n    g: parseFloat(match[2]),\n    b: parseFloat(match[3]),\n    alpha: match[4] ? parseFloat(match[4]) : 1,\n  }\n}\n\nfunction parseHsl(hsl: string): HSLColor {\n  const match = hsl.match(HSL_RE)\n  if (!match) {\n    throw new Error(`Invalid HSL color: ${hsl}`)\n  }\n\n  return {\n    space: 'hsl',\n    h: parseFloat(match[1]),\n    s: parseFloat(match[2]),\n    l: parseFloat(match[3]),\n    alpha: match[4] ? parseFloat(match[4]) : 1,\n  }\n}\n\nfunction parseHsb(hsb: string): HSBColor {\n  const match = hsb.match(HSB_RE)\n  if (!match) {\n    throw new Error(`Invalid HSB color: ${hsb}`)\n  }\n\n  return {\n    space: 'hsb',\n    h: parseFloat(match[1]),\n    s: parseFloat(match[2]),\n    b: parseFloat(match[3]),\n    alpha: match[4] ? parseFloat(match[4]) : 1,\n  }\n}\n\n/**\n * Normalizes a value to a Color object.\n * If already a Color, returns it. If a string, parses it.\n */\nexport function normalizeColor(value: string | Color): Color {\n  if (typeof value === 'string') {\n    return parseColor(value)\n  }\n  return value\n}\n\n/**\n * Checks if a string is a valid color.\n */\nexport function isValidColor(value: string): boolean {\n  try {\n    parseColor(value)\n    return true\n  }\n  catch {\n    return false\n  }\n}\n","/**\n * Converts a hex color string to RGB (Red, Green, Blue).\n * @param hex Hex color string (e.g., \"#ff5733\" or \"#f53\")\n * @returns An object containing red, green, and blue values (0-255).\n */\nconst HASH_PREFIX_RE = /^#/\nconst HEX6_RE = /^[0-9A-F]{6}$/i\nconst HEX3_RE = /^[0-9A-F]{3}$/i\n\nexport function hexToRGB(hex: string): { r: number, g: number, b: number } {\n  hex = hex.replace(HASH_PREFIX_RE, '')\n\n  // Validate hex format (3 or 6 hex digits)\n  if (!HEX6_RE.test(hex) && !HEX3_RE.test(hex)) {\n    throw new Error(`Invalid hex color: ${hex}. Expected format: #RGB or #RRGGBB`)\n  }\n\n  // Handle shorthand hex (e.g., \"#FFF\" -> \"#FFFFFF\")\n  if (hex.length === 3) {\n    hex = hex.split('').map(c => c + c).join('')\n  }\n\n  const bigint = parseInt(hex, 16)\n  const r = (bigint >> 16) & 255\n  const g = (bigint >> 8) & 255\n  const b = bigint & 255\n  return { r, g, b }\n}\n\n/**\n * Converts a hex color string to HSL (Hue, Saturation, Lightness).\n * @param hex Hex color string (e.g., \"#ff5733\")\n * @returns An object containing hue (0-360), saturation (0-100), and lightness (0-100) values.\n */\nexport function hexToHSL(hex: string): { h: number, s: number, l: number } {\n  let { r, g, b } = hexToRGB(hex)\n\n  r /= 255\n  g /= 255\n  b /= 255\n\n  const max = Math.max(r, g, b)\n  const min = Math.min(r, g, b)\n  let h: number\n  let s: number\n  let l: number = (max + min) / 2\n\n  if (max === min) {\n    h = s = 0 // achromatic\n    l *= 100 // Scale l to 0-100 for consistency with chromatic case\n  }\n  else {\n    const d = max - min\n    s = l > 0.5 ? d / (2 - max - min) : d / (max + min)\n    if (max === r) {\n      h = (g - b) / d + (g < b ? 6 : 0)\n    }\n    else if (max === g) {\n      h = (b - r) / d + 2\n    }\n    else {\n      h = (r - g) / d + 4\n    }\n    h /= 6\n    h *= 360\n    s *= 100\n    l *= 100\n  }\n\n  return { h, s, l }\n}\n\n/**\n * Converts a hex color string to a human-readable color name.\n * @param hex Hex color string (e.g., \"#ff5733\")\n * @returns A human-readable color name based on the hue, saturation, and lightness.\n */\nexport function getColorName(hex: string) {\n  const { h, s, l } = hexToHSL(hex)\n\n  // Handle achromatic colors (low saturation)\n  // Using 0-100 scale for all comparisons\n  if (s < 10) {\n    if (l < 10)\n      return 'black'\n    if (l > 95)\n      return 'white'\n    if (l < 20)\n      return 'very dark gray'\n    if (l < 35)\n      return 'dark gray'\n    if (l < 65)\n      return 'gray'\n    if (l < 80)\n      return 'light gray'\n    return 'very light gray'\n  }\n\n  // Determine base color by hue\n  let baseName\n  if (h < 15 || h >= 345)\n    baseName = 'red'\n  else if (h < 45)\n    baseName = 'orange'\n  else if (h < 75)\n    baseName = 'yellow'\n  else if (h < 105)\n    baseName = 'yellow-green'\n  else if (h < 135)\n    baseName = 'green'\n  else if (h < 165)\n    baseName = 'green-cyan'\n  else if (h < 195)\n    baseName = 'cyan'\n  else if (h < 225)\n    baseName = 'blue'\n  else if (h < 255)\n    baseName = 'blue-violet'\n  else if (h < 285)\n    baseName = 'violet'\n  else if (h < 315)\n    baseName = 'magenta'\n  else baseName = 'red-magenta'\n\n  // Add descriptors based on saturation and lightness\n  // Using 0-100 scale for all comparisons\n  const descriptors = []\n  if (s > 80)\n    descriptors.push('vibrant')\n  else if (s < 30)\n    descriptors.push('muted')\n\n  if (l > 80)\n    descriptors.push('light')\n  else if (l < 30)\n    descriptors.push('dark')\n\n  return descriptors.length > 0\n    ? `${descriptors.join(' ')} ${baseName}`\n    : baseName\n}\n\nexport function getColorContrast(hex: string): 'light' | 'dark' {\n  const { r, g, b } = hexToRGB(hex)\n  const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255\n  return luminance > 0.5 ? 'dark' : 'light'\n}\n","<script lang=\"ts\">\nimport type { ComputedRef, CSSProperties, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Color, ColorChannel, ColorSpace } from '@/shared/color'\nimport type { FormFieldProps } from '@/shared/types'\nimport { createContext, useFormControl, useForwardExpose } from '@/shared'\n\nexport interface ColorAreaRootProps extends PrimitiveProps, FormFieldProps {\n  /** The color value (controlled). Can be a hex string or Color object. */\n  modelValue?: string | Color\n  /** The default color value (uncontrolled). */\n  defaultValue?: string | Color\n  /** The color space to operate in. */\n  colorSpace?: ColorSpace\n  /** Color channel for the horizontal (x) axis. */\n  xChannel?: ColorChannel\n  /** Color channel for the vertical (y) axis. */\n  yChannel?: ColorChannel\n  /** When `true`, prevents the user from interacting with the area. */\n  disabled?: boolean\n  /** The name of the x channel input element for form submission. */\n  xName?: string\n  /** The name of the y channel input element for form submission. */\n  yName?: string\n}\n\nexport type ColorAreaRootEmits = {\n  'update:modelValue': [value: string]\n  'update:color': [value: Color]\n  'change': [value: string]\n  'changeEnd': [value: string]\n}\n\nexport interface ColorAreaRootContext {\n  color: Ref<Color>\n  xValue: Ref<number>\n  yValue: Ref<number>\n  xChannel: Ref<ColorChannel>\n  yChannel: Ref<ColorChannel>\n  colorSpace: Ref<ColorSpace>\n  disabled: Ref<boolean>\n  xRange: ComputedRef<{ min: number, max: number, step: number }>\n  yRange: ComputedRef<{ min: number, max: number, step: number }>\n  thumbRef: Ref<HTMLElement | undefined>\n  updateValues: (x: number, y: number) => void\n  commitValues: () => void\n}\n\nexport const [injectColorAreaRootContext, provideColorAreaRootContext]\n  = createContext<ColorAreaRootContext>('ColorAreaRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, ref, toRefs, watch } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport {\n  colorToString,\n  convertToHsb,\n  convertToHsl,\n  getAreaBackgroundStyle,\n  getChannelRange,\n  getChannelValue,\n  normalizeColor,\n  setChannelValues,\n} from '@/shared/color'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\nconst props = withDefaults(defineProps<ColorAreaRootProps>(), {\n  colorSpace: 'hsl',\n  xChannel: 'hue',\n  yChannel: 'saturation',\n  disabled: false,\n  defaultValue: '#ff0000',\n  as: 'div',\n})\n\nconst emits = defineEmits<ColorAreaRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** CSS styles for the color area background gradient */\n    style: CSSProperties\n  }) => any\n}>()\n\nconst { colorSpace, xChannel, yChannel, disabled } = toRefs(props)\nconst { forwardRef, currentElement } = useForwardExpose()\nconst isFormControl = useFormControl(currentElement)\n\n// Normalize the model value to a Color object\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n})\n\n// The actual color object for rendering\nconst color = computed({\n  get: () => normalizeColor(modelValue.value ?? '#000000'),\n  set: (newColor: Color) => {\n    const hexString = colorToString(newColor, 'hex')\n    modelValue.value = hexString\n    emits('update:color', newColor)\n  },\n})\n\n// Get channel ranges\nconst xRange = computed(() => getChannelRange(xChannel.value))\nconst yRange = computed(() => getChannelRange(yChannel.value))\n\n// Store exact channel values as refs to avoid floating-point drift\n// Initialize from the color value (rounded to nearest integer)\nconst xValue = ref(Math.round(getChannelValue(color.value, xChannel.value)))\nconst yValue = ref(Math.round(getChannelValue(color.value, yChannel.value)))\n\n// Store the hue separately to preserve it when saturation is 0 (grayscale)\nconst hueValue = ref(colorSpace.value === 'hsl'\n  ? convertToHsl(color.value).h\n  : colorSpace.value === 'hsb'\n    ? convertToHsb(color.value).h\n    : 0)\n\n// Track when we're in the middle of an update to prevent circular sync\nlet isUpdating = false\n\n// Sync channel values when color changes externally\nwatch(() => color.value, (newColor) => {\n  // Skip if we just triggered this update ourselves\n  if (isUpdating)\n    return\n\n  const newX = Math.round(getChannelValue(newColor, xChannel.value))\n  const newY = Math.round(getChannelValue(newColor, yChannel.value))\n\n  // Only update if the rounded value meaningfully changed.\n  // During drag, xValue/yValue store exact floats (e.g. 80.45).\n  // External updates (e.g. hue slider) should not snap these to integers.\n  if (Math.round(xValue.value) !== newX)\n    xValue.value = newX\n  if (Math.round(yValue.value) !== newY)\n    yValue.value = newY\n\n  // Update hue if saturation is not 0 (to preserve hue for grayscale colors)\n  if (colorSpace.value === 'hsl') {\n    const hsl = convertToHsl(newColor)\n    if (hsl.s > 0)\n      hueValue.value = hsl.h\n  }\n  else if (colorSpace.value === 'hsb') {\n    const hsb = convertToHsb(newColor)\n    if (hsb.s > 0)\n      hueValue.value = hsb.h\n  }\n}, { immediate: true })\n\n// Background styles for the color area\n// Use preserved hue to ensure background doesn't change when saturation is 0\nconst areaStyles = computed(() => {\n  // Create a color with the preserved hue for background computation\n  let bgColor = color.value\n  if (colorSpace.value === 'hsl' || colorSpace.value === 'hsb') {\n    if (colorSpace.value === 'hsl') {\n      bgColor = { space: 'hsl', h: hueValue.value, s: 100, l: 50, alpha: 1 }\n    }\n    else {\n      bgColor = { space: 'hsb', h: hueValue.value, s: 100, b: 100, alpha: 1 }\n    }\n  }\n  return getAreaBackgroundStyle(bgColor, xChannel.value, yChannel.value, colorSpace.value)\n})\n\nfunction updateValues(x: number, y: number) {\n  const clampedX = Math.max(xRange.value.min, Math.min(xRange.value.max, x))\n  const clampedY = Math.max(yRange.value.min, Math.min(yRange.value.max, y))\n\n  // Update exact values\n  xValue.value = clampedX\n  yValue.value = clampedY\n\n  // Prevent watch from syncing back to xValue/yValue\n  isUpdating = true\n\n  // Update color from exact values (with preserved hue)\n  const channels: Array<{ channel: ColorChannel, value: number }> = [\n    { channel: xChannel.value, value: clampedX },\n    { channel: yChannel.value, value: clampedY },\n  ]\n\n  // Preserve hue only when it is NOT directly controlled by an axis\n  const usesHueAxis = xChannel.value === 'hue' || yChannel.value === 'hue'\n  if (!usesHueAxis && (colorSpace.value === 'hsl' || colorSpace.value === 'hsb')) {\n    channels.push({ channel: 'hue', value: hueValue.value })\n  }\n\n  color.value = setChannelValues(color.value, channels)\n\n  // Re-enable watch sync after Vue has processed the update\n  nextTick(() => {\n    isUpdating = false\n  })\n}\n\nfunction commitValues() {\n  emits('changeEnd', colorToString(color.value, 'hex'))\n}\n\nconst thumbRef = ref<HTMLElement>()\n\nprovideColorAreaRootContext({\n  color: computed(() => color.value) as Ref<Color>,\n  xValue,\n  yValue,\n  xChannel,\n  yChannel,\n  colorSpace,\n  disabled,\n  xRange,\n  yRange,\n  thumbRef,\n  updateValues,\n  commitValues,\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"group\"\n    :aria-disabled=\"disabled ? 'true' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n  >\n    <slot :style=\"areaStyles\" />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && xName\"\n      type=\"text\"\n      :value=\"xValue\"\n      :name=\"xName\"\n      :disabled=\"disabled\"\n    />\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && yName\"\n      type=\"text\"\n      :value=\"yValue\"\n      :name=\"yName\"\n      :disabled=\"disabled\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, CSSProperties, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Color, ColorChannel, ColorSpace } from '@/shared/color'\nimport type { FormFieldProps } from '@/shared/types'\nimport { createContext, useFormControl, useForwardExpose } from '@/shared'\n\nexport interface ColorAreaRootProps extends PrimitiveProps, FormFieldProps {\n  /** The color value (controlled). Can be a hex string or Color object. */\n  modelValue?: string | Color\n  /** The default color value (uncontrolled). */\n  defaultValue?: string | Color\n  /** The color space to operate in. */\n  colorSpace?: ColorSpace\n  /** Color channel for the horizontal (x) axis. */\n  xChannel?: ColorChannel\n  /** Color channel for the vertical (y) axis. */\n  yChannel?: ColorChannel\n  /** When `true`, prevents the user from interacting with the area. */\n  disabled?: boolean\n  /** The name of the x channel input element for form submission. */\n  xName?: string\n  /** The name of the y channel input element for form submission. */\n  yName?: string\n}\n\nexport type ColorAreaRootEmits = {\n  'update:modelValue': [value: string]\n  'update:color': [value: Color]\n  'change': [value: string]\n  'changeEnd': [value: string]\n}\n\nexport interface ColorAreaRootContext {\n  color: Ref<Color>\n  xValue: Ref<number>\n  yValue: Ref<number>\n  xChannel: Ref<ColorChannel>\n  yChannel: Ref<ColorChannel>\n  colorSpace: Ref<ColorSpace>\n  disabled: Ref<boolean>\n  xRange: ComputedRef<{ min: number, max: number, step: number }>\n  yRange: ComputedRef<{ min: number, max: number, step: number }>\n  thumbRef: Ref<HTMLElement | undefined>\n  updateValues: (x: number, y: number) => void\n  commitValues: () => void\n}\n\nexport const [injectColorAreaRootContext, provideColorAreaRootContext]\n  = createContext<ColorAreaRootContext>('ColorAreaRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, ref, toRefs, watch } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport {\n  colorToString,\n  convertToHsb,\n  convertToHsl,\n  getAreaBackgroundStyle,\n  getChannelRange,\n  getChannelValue,\n  normalizeColor,\n  setChannelValues,\n} from '@/shared/color'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\nconst props = withDefaults(defineProps<ColorAreaRootProps>(), {\n  colorSpace: 'hsl',\n  xChannel: 'hue',\n  yChannel: 'saturation',\n  disabled: false,\n  defaultValue: '#ff0000',\n  as: 'div',\n})\n\nconst emits = defineEmits<ColorAreaRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** CSS styles for the color area background gradient */\n    style: CSSProperties\n  }) => any\n}>()\n\nconst { colorSpace, xChannel, yChannel, disabled } = toRefs(props)\nconst { forwardRef, currentElement } = useForwardExpose()\nconst isFormControl = useFormControl(currentElement)\n\n// Normalize the model value to a Color object\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n})\n\n// The actual color object for rendering\nconst color = computed({\n  get: () => normalizeColor(modelValue.value ?? '#000000'),\n  set: (newColor: Color) => {\n    const hexString = colorToString(newColor, 'hex')\n    modelValue.value = hexString\n    emits('update:color', newColor)\n  },\n})\n\n// Get channel ranges\nconst xRange = computed(() => getChannelRange(xChannel.value))\nconst yRange = computed(() => getChannelRange(yChannel.value))\n\n// Store exact channel values as refs to avoid floating-point drift\n// Initialize from the color value (rounded to nearest integer)\nconst xValue = ref(Math.round(getChannelValue(color.value, xChannel.value)))\nconst yValue = ref(Math.round(getChannelValue(color.value, yChannel.value)))\n\n// Store the hue separately to preserve it when saturation is 0 (grayscale)\nconst hueValue = ref(colorSpace.value === 'hsl'\n  ? convertToHsl(color.value).h\n  : colorSpace.value === 'hsb'\n    ? convertToHsb(color.value).h\n    : 0)\n\n// Track when we're in the middle of an update to prevent circular sync\nlet isUpdating = false\n\n// Sync channel values when color changes externally\nwatch(() => color.value, (newColor) => {\n  // Skip if we just triggered this update ourselves\n  if (isUpdating)\n    return\n\n  const newX = Math.round(getChannelValue(newColor, xChannel.value))\n  const newY = Math.round(getChannelValue(newColor, yChannel.value))\n\n  // Only update if the rounded value meaningfully changed.\n  // During drag, xValue/yValue store exact floats (e.g. 80.45).\n  // External updates (e.g. hue slider) should not snap these to integers.\n  if (Math.round(xValue.value) !== newX)\n    xValue.value = newX\n  if (Math.round(yValue.value) !== newY)\n    yValue.value = newY\n\n  // Update hue if saturation is not 0 (to preserve hue for grayscale colors)\n  if (colorSpace.value === 'hsl') {\n    const hsl = convertToHsl(newColor)\n    if (hsl.s > 0)\n      hueValue.value = hsl.h\n  }\n  else if (colorSpace.value === 'hsb') {\n    const hsb = convertToHsb(newColor)\n    if (hsb.s > 0)\n      hueValue.value = hsb.h\n  }\n}, { immediate: true })\n\n// Background styles for the color area\n// Use preserved hue to ensure background doesn't change when saturation is 0\nconst areaStyles = computed(() => {\n  // Create a color with the preserved hue for background computation\n  let bgColor = color.value\n  if (colorSpace.value === 'hsl' || colorSpace.value === 'hsb') {\n    if (colorSpace.value === 'hsl') {\n      bgColor = { space: 'hsl', h: hueValue.value, s: 100, l: 50, alpha: 1 }\n    }\n    else {\n      bgColor = { space: 'hsb', h: hueValue.value, s: 100, b: 100, alpha: 1 }\n    }\n  }\n  return getAreaBackgroundStyle(bgColor, xChannel.value, yChannel.value, colorSpace.value)\n})\n\nfunction updateValues(x: number, y: number) {\n  const clampedX = Math.max(xRange.value.min, Math.min(xRange.value.max, x))\n  const clampedY = Math.max(yRange.value.min, Math.min(yRange.value.max, y))\n\n  // Update exact values\n  xValue.value = clampedX\n  yValue.value = clampedY\n\n  // Prevent watch from syncing back to xValue/yValue\n  isUpdating = true\n\n  // Update color from exact values (with preserved hue)\n  const channels: Array<{ channel: ColorChannel, value: number }> = [\n    { channel: xChannel.value, value: clampedX },\n    { channel: yChannel.value, value: clampedY },\n  ]\n\n  // Preserve hue only when it is NOT directly controlled by an axis\n  const usesHueAxis = xChannel.value === 'hue' || yChannel.value === 'hue'\n  if (!usesHueAxis && (colorSpace.value === 'hsl' || colorSpace.value === 'hsb')) {\n    channels.push({ channel: 'hue', value: hueValue.value })\n  }\n\n  color.value = setChannelValues(color.value, channels)\n\n  // Re-enable watch sync after Vue has processed the update\n  nextTick(() => {\n    isUpdating = false\n  })\n}\n\nfunction commitValues() {\n  emits('changeEnd', colorToString(color.value, 'hex'))\n}\n\nconst thumbRef = ref<HTMLElement>()\n\nprovideColorAreaRootContext({\n  color: computed(() => color.value) as Ref<Color>,\n  xValue,\n  yValue,\n  xChannel,\n  yChannel,\n  colorSpace,\n  disabled,\n  xRange,\n  yRange,\n  thumbRef,\n  updateValues,\n  commitValues,\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"group\"\n    :aria-disabled=\"disabled ? 'true' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n  >\n    <slot :style=\"areaStyles\" />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && xName\"\n      type=\"text\"\n      :value=\"xValue\"\n      :name=\"xName\"\n      :disabled=\"disabled\"\n    />\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && yName\"\n      type=\"text\"\n      :value=\"yValue\"\n      :name=\"yName\"\n      :disabled=\"disabled\"\n    />\n  </Primitive>\n</template>\n","import { clamp } from '@/shared'\n\n// https://github.com/tmcw-up-for-adoption/simple-linear-scale/blob/master/index.js\nexport function linearScale(input: readonly [number, number], output: readonly [number, number]) {\n  return (value: number) => {\n    if (input[0] === input[1] || output[0] === output[1])\n      return output[0]\n    const ratio = (output[1] - output[0]) / (input[1] - input[0])\n    return output[0] + ratio * (value - input[0])\n  }\n}\n\nexport function convertValueToPercentage(value: number, min: number, max: number) {\n  if (max === min)\n    return 0\n  const maxSteps = max - min\n  const percentPerStep = 100 / maxSteps\n  const percentage = percentPerStep * (value - min)\n  return clamp(percentage, 0, 100)\n}\n\nexport function getThumbPosition(percentage: number): string {\n  return `${percentage}%`\n}\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ColorAreaAreaProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectColorAreaRootContext } from './ColorAreaRoot.vue'\nimport { linearScale } from './utils'\n\nconst props = withDefaults(defineProps<ColorAreaAreaProps>(), {\n  as: 'div',\n})\n\nconst rootContext = injectColorAreaRootContext()\nconst { primitiveElement, currentElement: areaElement } = usePrimitiveElement()\n\nconst isDragging = ref(false)\n\n// Convert pointer position to channel values\nfunction getValuesFromPointer(event: PointerEvent) {\n  const rect = areaElement.value!.getBoundingClientRect()\n\n  const xInput: [number, number] = [0, rect.width]\n  const xOutput: [number, number] = [rootContext.xRange.value.min, rootContext.xRange.value.max]\n  const xScale = linearScale(xInput, xOutput)\n  const xValue = xScale(event.clientX - rect.left)\n\n  // Y is inverted (top is max, bottom is min for most channels)\n  const yInput: [number, number] = [0, rect.height]\n  const yOutput: [number, number] = [rootContext.yRange.value.max, rootContext.yRange.value.min]\n  const yScale = linearScale(yInput, yOutput)\n  const yValue = yScale(event.clientY - rect.top)\n\n  return { x: xValue, y: yValue }\n}\n\nfunction handlePointerDown(event: PointerEvent) {\n  if (rootContext.disabled.value)\n    return\n\n  const target = event.target as HTMLElement\n  target.setPointerCapture(event.pointerId)\n  event.preventDefault()\n\n  isDragging.value = true\n  const { x, y } = getValuesFromPointer(event)\n  rootContext.updateValues(x, y)\n\n  // Focus the thumb when dragging starts\n  rootContext.thumbRef.value?.focus()\n}\n\nfunction handlePointerMove(event: PointerEvent) {\n  if (!isDragging.value || rootContext.disabled.value)\n    return\n\n  const target = event.target as HTMLElement\n  if (target.hasPointerCapture(event.pointerId)) {\n    const { x, y } = getValuesFromPointer(event)\n    rootContext.updateValues(x, y)\n  }\n}\n\nfunction handlePointerUp(event: PointerEvent) {\n  if (!isDragging.value)\n    return\n\n  const target = event.target as HTMLElement\n  target.releasePointerCapture(event.pointerId)\n  isDragging.value = false\n  rootContext.commitValues()\n}\n\n// Keyboard navigation\nfunction handleKeyDown(event: KeyboardEvent) {\n  if (rootContext.disabled.value)\n    return\n\n  const stepMultiplier = event.shiftKey ? 10 : 1\n  const xStepSize = rootContext.xRange.value.step * stepMultiplier\n  const yStepSize = rootContext.yRange.value.step * stepMultiplier\n\n  let xDelta = 0\n  let yDelta = 0\n\n  switch (event.key) {\n    case 'ArrowLeft':\n      xDelta = -xStepSize\n      break\n    case 'ArrowRight':\n      xDelta = xStepSize\n      break\n    case 'ArrowUp':\n      yDelta = yStepSize\n      break\n    case 'ArrowDown':\n      yDelta = -yStepSize\n      break\n    case 'PageUp':\n      yDelta = yStepSize * 10\n      break\n    case 'PageDown':\n      yDelta = -yStepSize * 10\n      break\n    case 'Home':\n      xDelta = -xStepSize * 10\n      break\n    case 'End':\n      xDelta = xStepSize * 10\n      break\n    default:\n      return\n  }\n\n  event.preventDefault()\n  rootContext.updateValues(\n    rootContext.xValue.value + xDelta,\n    rootContext.yValue.value + yDelta,\n  )\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    role=\"application\"\n    aria-roledescription=\"Color picker\"\n    :aria-disabled=\"rootContext.disabled.value ? 'true' : undefined\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :style=\"{\n      touchAction: 'none',\n    }\"\n    @keydown=\"handleKeyDown\"\n    @pointerdown=\"handlePointerDown\"\n    @pointermove=\"handlePointerMove\"\n    @pointerup=\"handlePointerUp\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ColorAreaAreaProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectColorAreaRootContext } from './ColorAreaRoot.vue'\nimport { linearScale } from './utils'\n\nconst props = withDefaults(defineProps<ColorAreaAreaProps>(), {\n  as: 'div',\n})\n\nconst rootContext = injectColorAreaRootContext()\nconst { primitiveElement, currentElement: areaElement } = usePrimitiveElement()\n\nconst isDragging = ref(false)\n\n// Convert pointer position to channel values\nfunction getValuesFromPointer(event: PointerEvent) {\n  const rect = areaElement.value!.getBoundingClientRect()\n\n  const xInput: [number, number] = [0, rect.width]\n  const xOutput: [number, number] = [rootContext.xRange.value.min, rootContext.xRange.value.max]\n  const xScale = linearScale(xInput, xOutput)\n  const xValue = xScale(event.clientX - rect.left)\n\n  // Y is inverted (top is max, bottom is min for most channels)\n  const yInput: [number, number] = [0, rect.height]\n  const yOutput: [number, number] = [rootContext.yRange.value.max, rootContext.yRange.value.min]\n  const yScale = linearScale(yInput, yOutput)\n  const yValue = yScale(event.clientY - rect.top)\n\n  return { x: xValue, y: yValue }\n}\n\nfunction handlePointerDown(event: PointerEvent) {\n  if (rootContext.disabled.value)\n    return\n\n  const target = event.target as HTMLElement\n  target.setPointerCapture(event.pointerId)\n  event.preventDefault()\n\n  isDragging.value = true\n  const { x, y } = getValuesFromPointer(event)\n  rootContext.updateValues(x, y)\n\n  // Focus the thumb when dragging starts\n  rootContext.thumbRef.value?.focus()\n}\n\nfunction handlePointerMove(event: PointerEvent) {\n  if (!isDragging.value || rootContext.disabled.value)\n    return\n\n  const target = event.target as HTMLElement\n  if (target.hasPointerCapture(event.pointerId)) {\n    const { x, y } = getValuesFromPointer(event)\n    rootContext.updateValues(x, y)\n  }\n}\n\nfunction handlePointerUp(event: PointerEvent) {\n  if (!isDragging.value)\n    return\n\n  const target = event.target as HTMLElement\n  target.releasePointerCapture(event.pointerId)\n  isDragging.value = false\n  rootContext.commitValues()\n}\n\n// Keyboard navigation\nfunction handleKeyDown(event: KeyboardEvent) {\n  if (rootContext.disabled.value)\n    return\n\n  const stepMultiplier = event.shiftKey ? 10 : 1\n  const xStepSize = rootContext.xRange.value.step * stepMultiplier\n  const yStepSize = rootContext.yRange.value.step * stepMultiplier\n\n  let xDelta = 0\n  let yDelta = 0\n\n  switch (event.key) {\n    case 'ArrowLeft':\n      xDelta = -xStepSize\n      break\n    case 'ArrowRight':\n      xDelta = xStepSize\n      break\n    case 'ArrowUp':\n      yDelta = yStepSize\n      break\n    case 'ArrowDown':\n      yDelta = -yStepSize\n      break\n    case 'PageUp':\n      yDelta = yStepSize * 10\n      break\n    case 'PageDown':\n      yDelta = -yStepSize * 10\n      break\n    case 'Home':\n      xDelta = -xStepSize * 10\n      break\n    case 'End':\n      xDelta = xStepSize * 10\n      break\n    default:\n      return\n  }\n\n  event.preventDefault()\n  rootContext.updateValues(\n    rootContext.xValue.value + xDelta,\n    rootContext.yValue.value + yDelta,\n  )\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    role=\"application\"\n    aria-roledescription=\"Color picker\"\n    :aria-disabled=\"rootContext.disabled.value ? 'true' : undefined\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :style=\"{\n      touchAction: 'none',\n    }\"\n    @keydown=\"handleKeyDown\"\n    @pointerdown=\"handlePointerDown\"\n    @pointermove=\"handlePointerMove\"\n    @pointerup=\"handlePointerUp\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ColorAreaThumbProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { getChannelName } from '@/shared/color'\nimport { injectColorAreaRootContext } from './ColorAreaRoot.vue'\nimport { convertValueToPercentage } from './utils'\n\nconst props = withDefaults(defineProps<ColorAreaThumbProps>(), {\n  as: 'span',\n})\n\nconst rootContext = injectColorAreaRootContext()\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nonMounted(() => {\n  rootContext.thumbRef.value = currentElement.value\n})\n\nconst xPercent = computed(() =>\n  convertValueToPercentage(\n    rootContext.xValue.value,\n    rootContext.xRange.value.min,\n    rootContext.xRange.value.max,\n  ),\n)\n\nconst yPercent = computed(() =>\n  convertValueToPercentage(\n    rootContext.yValue.value,\n    rootContext.yRange.value.min,\n    rootContext.yRange.value.max,\n  ),\n)\n\nconst ariaLabel = computed(() => {\n  return `${getChannelName(rootContext.xChannel.value)}, ${getChannelName(rootContext.yChannel.value)}`\n})\n\nconst ariaValueText = computed(() => {\n  return `${getChannelName(rootContext.xChannel.value)} ${Math.round(rootContext.xValue.value)}, ${getChannelName(rootContext.yChannel.value)} ${Math.round(rootContext.yValue.value)}`\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    role=\"slider\"\n    :tabindex=\"rootContext.disabled.value ? undefined : 0\"\n    :aria-label=\"ariaLabel\"\n    aria-roledescription=\"Color thumb\"\n    :aria-valuemin=\"rootContext.xRange.value.min\"\n    :aria-valuemax=\"rootContext.xRange.value.max\"\n    :aria-valuenow=\"rootContext.xValue.value\"\n    :aria-valuetext=\"ariaValueText\"\n    aria-orientation=\"horizontal\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :style=\"{\n      position: 'absolute',\n      left: `${xPercent}%`,\n      top: `${100 - yPercent}%`,\n      transform: 'translate(-50%, -50%)',\n      touchAction: 'none',\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ColorAreaThumbProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { getChannelName } from '@/shared/color'\nimport { injectColorAreaRootContext } from './ColorAreaRoot.vue'\nimport { convertValueToPercentage } from './utils'\n\nconst props = withDefaults(defineProps<ColorAreaThumbProps>(), {\n  as: 'span',\n})\n\nconst rootContext = injectColorAreaRootContext()\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nonMounted(() => {\n  rootContext.thumbRef.value = currentElement.value\n})\n\nconst xPercent = computed(() =>\n  convertValueToPercentage(\n    rootContext.xValue.value,\n    rootContext.xRange.value.min,\n    rootContext.xRange.value.max,\n  ),\n)\n\nconst yPercent = computed(() =>\n  convertValueToPercentage(\n    rootContext.yValue.value,\n    rootContext.yRange.value.min,\n    rootContext.yRange.value.max,\n  ),\n)\n\nconst ariaLabel = computed(() => {\n  return `${getChannelName(rootContext.xChannel.value)}, ${getChannelName(rootContext.yChannel.value)}`\n})\n\nconst ariaValueText = computed(() => {\n  return `${getChannelName(rootContext.xChannel.value)} ${Math.round(rootContext.xValue.value)}, ${getChannelName(rootContext.yChannel.value)} ${Math.round(rootContext.yValue.value)}`\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    role=\"slider\"\n    :tabindex=\"rootContext.disabled.value ? undefined : 0\"\n    :aria-label=\"ariaLabel\"\n    aria-roledescription=\"Color thumb\"\n    :aria-valuemin=\"rootContext.xRange.value.min\"\n    :aria-valuemax=\"rootContext.xRange.value.max\"\n    :aria-valuenow=\"rootContext.xValue.value\"\n    :aria-valuetext=\"ariaValueText\"\n    aria-orientation=\"horizontal\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :style=\"{\n      position: 'absolute',\n      left: `${xPercent}%`,\n      top: `${100 - yPercent}%`,\n      transform: 'translate(-50%, -50%)',\n      touchAction: 'none',\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Color, ColorChannel, ColorSpace } from '@/shared/color'\nimport type { FormFieldProps } from '@/shared/types'\nimport { createContext, useFormControl, useForwardExpose, useLocale } from '@/shared'\n\nexport interface ColorFieldRootProps extends PrimitiveProps, FormFieldProps {\n  /** The color value (controlled). Can be a hex string or Color object. */\n  modelValue?: string | Color\n  /** The default color value (uncontrolled). */\n  defaultValue?: string | Color\n  /** The color space to operate in when displaying a channel. */\n  colorSpace?: ColorSpace\n  /** The color channel to display. If not provided, displays hex value. */\n  channel?: ColorChannel\n  /** Placeholder text when the field is empty. */\n  placeholder?: string\n  /** When `true`, prevents the user from interacting with the field. */\n  disabled?: boolean\n  /** When `true`, the field is read-only. */\n  readonly?: boolean\n  /** When `true`, prevents the value from changing on wheel scroll. */\n  disableWheelChange?: boolean\n  /** The locale to use for number formatting. */\n  locale?: string\n  /** Custom step value for increment/decrement. Defaults to channel step or 1 for hex. */\n  step?: number\n}\n\nexport type ColorFieldRootEmits = {\n  'update:modelValue': [value: string]\n  'update:color': [value: Color]\n}\n\nexport interface ColorFieldRootContext {\n  color: Ref<Color>\n  inputValue: Ref<string>\n  channel: Ref<ColorChannel | undefined>\n  colorSpace: Ref<ColorSpace>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  disableWheelChange: Ref<boolean>\n  placeholder: Ref<string | undefined>\n  updateValue: (value: string) => void\n  commit: () => void\n  increment: () => void\n  decrement: () => void\n  incrementToMax: () => void\n  decrementToMin: () => void\n  incrementPage: () => void\n  decrementPage: () => void\n  handleWheel: (event: WheelEvent) => void\n}\n\nexport const [injectColorFieldRootContext, provideColorFieldRootContext]\n  = createContext<ColorFieldRootContext>('ColorFieldRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRefs, watch } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport {\n  colorToString,\n  convertToRgb,\n  getChannelRange,\n  getChannelValue,\n  isValidColor,\n  normalizeColor,\n  parseColor,\n  setChannelValue,\n} from '@/shared/color'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\nconst props = withDefaults(defineProps<ColorFieldRootProps>(), {\n  colorSpace: 'hsl',\n  disabled: false,\n  readonly: false,\n  disableWheelChange: false,\n  defaultValue: '#000000',\n  as: 'div',\n})\n\nconst emits = defineEmits<ColorFieldRootEmits>()\n\nconst { colorSpace, channel, disabled, readonly, disableWheelChange, placeholder, locale: propLocale, step: stepProp } = toRefs(props)\nconst { forwardRef, currentElement } = useForwardExpose()\nconst isFormControl = useFormControl(currentElement)\nconst locale = useLocale(propLocale)\n\n// Normalize the model value\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst color = computed({\n  get: () => normalizeColor(modelValue.value ?? '#000000'),\n  set: (newColor: Color) => {\n    const hexString = colorToString(newColor, 'hex')\n    modelValue.value = hexString\n    emits('update:color', newColor)\n  },\n})\n\n// Input value for the text field\nconst inputValue = ref('')\nconst isEditing = ref(false)\n\n// Update input value when color changes (unless user is editing)\nwatch(() => color.value, (newColor) => {\n  if (!isEditing.value) {\n    inputValue.value = formatValue(newColor)\n  }\n}, { immediate: true })\n\nfunction formatValue(c: Color): string {\n  if (channel.value) {\n    const value = getChannelValue(c, channel.value)\n    if (channel.value === 'alpha') {\n      return String(Math.round(value))\n    }\n    return String(Math.round(value))\n  }\n  // Hex mode\n  return colorToString(c, 'hex')\n}\n\n// The effective step size\nconst MIN_HEX_INT = 0x000000\nconst MAX_HEX_INT = 0xFFFFFF\nconst PAGE_STEP_MULTIPLIER = 10\n\nfunction getStep(): number {\n  if (stepProp.value != null)\n    return stepProp.value\n  if (channel.value)\n    return getChannelRange(channel.value).step\n  // Hex mode: step by 1 in the integer space (like react-spectrum)\n  return 1\n}\n\nfunction updateValue(value: string) {\n  inputValue.value = value\n}\n\nfunction commit() {\n  isEditing.value = false\n\n  if (channel.value) {\n    // Channel mode - parse as number\n    const numValue = parseFloat(inputValue.value)\n    if (!isNaN(numValue)) {\n      const range = getChannelRange(channel.value)\n      const clamped = Math.max(range.min, Math.min(range.max, numValue))\n      color.value = setChannelValue(color.value, channel.value, clamped)\n    }\n    // Reset to formatted value\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    // Hex mode - parse as color\n    const trimmed = inputValue.value.trim()\n    if (isValidColor(trimmed)) {\n      color.value = parseColor(trimmed)\n    }\n    // Reset to formatted value\n    inputValue.value = formatValue(color.value)\n  }\n}\n\nfunction addHexValue(delta: number) {\n  const intDelta = Math.trunc(delta)\n  const hexInt = color.value.space === 'rgb'\n    ? ((Math.round((color.value as any).r) << 16) | (Math.round((color.value as any).g) << 8) | Math.round((color.value as any).b))\n    : (() => {\n        const rgb = convertToRgb(color.value)\n        return (Math.round(rgb.r) << 16) | (Math.round(rgb.g) << 8) | Math.round(rgb.b)\n      })()\n  const clamped = Math.min(Math.max(hexInt + intDelta, MIN_HEX_INT), MAX_HEX_INT)\n  const hex = `#${clamped.toString(16).padStart(6, '0')}`\n  color.value = parseColor(hex)\n  inputValue.value = formatValue(color.value)\n}\n\nfunction increment() {\n  if (disabled.value || readonly.value)\n    return\n  const step = getStep()\n  if (channel.value) {\n    const currentValue = getChannelValue(color.value, channel.value)\n    color.value = setChannelValue(color.value, channel.value, currentValue + step)\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    addHexValue(step)\n  }\n}\n\nfunction decrement() {\n  if (disabled.value || readonly.value)\n    return\n  const step = getStep()\n  if (channel.value) {\n    const currentValue = getChannelValue(color.value, channel.value)\n    color.value = setChannelValue(color.value, channel.value, currentValue - step)\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    addHexValue(-step)\n  }\n}\n\nfunction incrementPage() {\n  if (disabled.value || readonly.value)\n    return\n  const step = getStep() * PAGE_STEP_MULTIPLIER\n  if (channel.value) {\n    const currentValue = getChannelValue(color.value, channel.value)\n    color.value = setChannelValue(color.value, channel.value, currentValue + step)\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    addHexValue(step)\n  }\n}\n\nfunction decrementPage() {\n  if (disabled.value || readonly.value)\n    return\n  const step = getStep() * PAGE_STEP_MULTIPLIER\n  if (channel.value) {\n    const currentValue = getChannelValue(color.value, channel.value)\n    color.value = setChannelValue(color.value, channel.value, currentValue - step)\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    addHexValue(-step)\n  }\n}\n\nfunction incrementToMax() {\n  if (disabled.value || readonly.value)\n    return\n  if (channel.value) {\n    const range = getChannelRange(channel.value)\n    color.value = setChannelValue(color.value, channel.value, range.max)\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    addHexValue(MAX_HEX_INT)\n  }\n}\n\nfunction decrementToMin() {\n  if (disabled.value || readonly.value)\n    return\n  if (channel.value) {\n    const range = getChannelRange(channel.value)\n    color.value = setChannelValue(color.value, channel.value, range.min)\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    addHexValue(-MAX_HEX_INT)\n  }\n}\n\nfunction handleWheel(event: WheelEvent) {\n  if (disableWheelChange.value || disabled.value || readonly.value)\n    return\n\n  event.preventDefault()\n\n  if (event.deltaY > 0)\n    decrement()\n  else\n    increment()\n}\n\nprovideColorFieldRootContext({\n  color: computed(() => color.value) as Ref<Color>,\n  inputValue,\n  channel,\n  colorSpace,\n  disabled,\n  readonly,\n  disableWheelChange,\n  placeholder,\n  updateValue,\n  commit,\n  increment,\n  decrement,\n  incrementToMax,\n  decrementToMin,\n  incrementPage,\n  decrementPage,\n  handleWheel,\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"group\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"readonly ? '' : undefined\"\n  >\n    <slot />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      type=\"text\"\n      :value=\"colorToString(color, 'hex')\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Color, ColorChannel, ColorSpace } from '@/shared/color'\nimport type { FormFieldProps } from '@/shared/types'\nimport { createContext, useFormControl, useForwardExpose, useLocale } from '@/shared'\n\nexport interface ColorFieldRootProps extends PrimitiveProps, FormFieldProps {\n  /** The color value (controlled). Can be a hex string or Color object. */\n  modelValue?: string | Color\n  /** The default color value (uncontrolled). */\n  defaultValue?: string | Color\n  /** The color space to operate in when displaying a channel. */\n  colorSpace?: ColorSpace\n  /** The color channel to display. If not provided, displays hex value. */\n  channel?: ColorChannel\n  /** Placeholder text when the field is empty. */\n  placeholder?: string\n  /** When `true`, prevents the user from interacting with the field. */\n  disabled?: boolean\n  /** When `true`, the field is read-only. */\n  readonly?: boolean\n  /** When `true`, prevents the value from changing on wheel scroll. */\n  disableWheelChange?: boolean\n  /** The locale to use for number formatting. */\n  locale?: string\n  /** Custom step value for increment/decrement. Defaults to channel step or 1 for hex. */\n  step?: number\n}\n\nexport type ColorFieldRootEmits = {\n  'update:modelValue': [value: string]\n  'update:color': [value: Color]\n}\n\nexport interface ColorFieldRootContext {\n  color: Ref<Color>\n  inputValue: Ref<string>\n  channel: Ref<ColorChannel | undefined>\n  colorSpace: Ref<ColorSpace>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  disableWheelChange: Ref<boolean>\n  placeholder: Ref<string | undefined>\n  updateValue: (value: string) => void\n  commit: () => void\n  increment: () => void\n  decrement: () => void\n  incrementToMax: () => void\n  decrementToMin: () => void\n  incrementPage: () => void\n  decrementPage: () => void\n  handleWheel: (event: WheelEvent) => void\n}\n\nexport const [injectColorFieldRootContext, provideColorFieldRootContext]\n  = createContext<ColorFieldRootContext>('ColorFieldRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRefs, watch } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport {\n  colorToString,\n  convertToRgb,\n  getChannelRange,\n  getChannelValue,\n  isValidColor,\n  normalizeColor,\n  parseColor,\n  setChannelValue,\n} from '@/shared/color'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\nconst props = withDefaults(defineProps<ColorFieldRootProps>(), {\n  colorSpace: 'hsl',\n  disabled: false,\n  readonly: false,\n  disableWheelChange: false,\n  defaultValue: '#000000',\n  as: 'div',\n})\n\nconst emits = defineEmits<ColorFieldRootEmits>()\n\nconst { colorSpace, channel, disabled, readonly, disableWheelChange, placeholder, locale: propLocale, step: stepProp } = toRefs(props)\nconst { forwardRef, currentElement } = useForwardExpose()\nconst isFormControl = useFormControl(currentElement)\nconst locale = useLocale(propLocale)\n\n// Normalize the model value\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst color = computed({\n  get: () => normalizeColor(modelValue.value ?? '#000000'),\n  set: (newColor: Color) => {\n    const hexString = colorToString(newColor, 'hex')\n    modelValue.value = hexString\n    emits('update:color', newColor)\n  },\n})\n\n// Input value for the text field\nconst inputValue = ref('')\nconst isEditing = ref(false)\n\n// Update input value when color changes (unless user is editing)\nwatch(() => color.value, (newColor) => {\n  if (!isEditing.value) {\n    inputValue.value = formatValue(newColor)\n  }\n}, { immediate: true })\n\nfunction formatValue(c: Color): string {\n  if (channel.value) {\n    const value = getChannelValue(c, channel.value)\n    if (channel.value === 'alpha') {\n      return String(Math.round(value))\n    }\n    return String(Math.round(value))\n  }\n  // Hex mode\n  return colorToString(c, 'hex')\n}\n\n// The effective step size\nconst MIN_HEX_INT = 0x000000\nconst MAX_HEX_INT = 0xFFFFFF\nconst PAGE_STEP_MULTIPLIER = 10\n\nfunction getStep(): number {\n  if (stepProp.value != null)\n    return stepProp.value\n  if (channel.value)\n    return getChannelRange(channel.value).step\n  // Hex mode: step by 1 in the integer space (like react-spectrum)\n  return 1\n}\n\nfunction updateValue(value: string) {\n  inputValue.value = value\n}\n\nfunction commit() {\n  isEditing.value = false\n\n  if (channel.value) {\n    // Channel mode - parse as number\n    const numValue = parseFloat(inputValue.value)\n    if (!isNaN(numValue)) {\n      const range = getChannelRange(channel.value)\n      const clamped = Math.max(range.min, Math.min(range.max, numValue))\n      color.value = setChannelValue(color.value, channel.value, clamped)\n    }\n    // Reset to formatted value\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    // Hex mode - parse as color\n    const trimmed = inputValue.value.trim()\n    if (isValidColor(trimmed)) {\n      color.value = parseColor(trimmed)\n    }\n    // Reset to formatted value\n    inputValue.value = formatValue(color.value)\n  }\n}\n\nfunction addHexValue(delta: number) {\n  const intDelta = Math.trunc(delta)\n  const hexInt = color.value.space === 'rgb'\n    ? ((Math.round((color.value as any).r) << 16) | (Math.round((color.value as any).g) << 8) | Math.round((color.value as any).b))\n    : (() => {\n        const rgb = convertToRgb(color.value)\n        return (Math.round(rgb.r) << 16) | (Math.round(rgb.g) << 8) | Math.round(rgb.b)\n      })()\n  const clamped = Math.min(Math.max(hexInt + intDelta, MIN_HEX_INT), MAX_HEX_INT)\n  const hex = `#${clamped.toString(16).padStart(6, '0')}`\n  color.value = parseColor(hex)\n  inputValue.value = formatValue(color.value)\n}\n\nfunction increment() {\n  if (disabled.value || readonly.value)\n    return\n  const step = getStep()\n  if (channel.value) {\n    const currentValue = getChannelValue(color.value, channel.value)\n    color.value = setChannelValue(color.value, channel.value, currentValue + step)\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    addHexValue(step)\n  }\n}\n\nfunction decrement() {\n  if (disabled.value || readonly.value)\n    return\n  const step = getStep()\n  if (channel.value) {\n    const currentValue = getChannelValue(color.value, channel.value)\n    color.value = setChannelValue(color.value, channel.value, currentValue - step)\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    addHexValue(-step)\n  }\n}\n\nfunction incrementPage() {\n  if (disabled.value || readonly.value)\n    return\n  const step = getStep() * PAGE_STEP_MULTIPLIER\n  if (channel.value) {\n    const currentValue = getChannelValue(color.value, channel.value)\n    color.value = setChannelValue(color.value, channel.value, currentValue + step)\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    addHexValue(step)\n  }\n}\n\nfunction decrementPage() {\n  if (disabled.value || readonly.value)\n    return\n  const step = getStep() * PAGE_STEP_MULTIPLIER\n  if (channel.value) {\n    const currentValue = getChannelValue(color.value, channel.value)\n    color.value = setChannelValue(color.value, channel.value, currentValue - step)\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    addHexValue(-step)\n  }\n}\n\nfunction incrementToMax() {\n  if (disabled.value || readonly.value)\n    return\n  if (channel.value) {\n    const range = getChannelRange(channel.value)\n    color.value = setChannelValue(color.value, channel.value, range.max)\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    addHexValue(MAX_HEX_INT)\n  }\n}\n\nfunction decrementToMin() {\n  if (disabled.value || readonly.value)\n    return\n  if (channel.value) {\n    const range = getChannelRange(channel.value)\n    color.value = setChannelValue(color.value, channel.value, range.min)\n    inputValue.value = formatValue(color.value)\n  }\n  else {\n    addHexValue(-MAX_HEX_INT)\n  }\n}\n\nfunction handleWheel(event: WheelEvent) {\n  if (disableWheelChange.value || disabled.value || readonly.value)\n    return\n\n  event.preventDefault()\n\n  if (event.deltaY > 0)\n    decrement()\n  else\n    increment()\n}\n\nprovideColorFieldRootContext({\n  color: computed(() => color.value) as Ref<Color>,\n  inputValue,\n  channel,\n  colorSpace,\n  disabled,\n  readonly,\n  disableWheelChange,\n  placeholder,\n  updateValue,\n  commit,\n  increment,\n  decrement,\n  incrementToMax,\n  decrementToMin,\n  incrementPage,\n  decrementPage,\n  handleWheel,\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"group\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"readonly ? '' : undefined\"\n  >\n    <slot />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      type=\"text\"\n      :value=\"colorToString(color, 'hex')\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nconst ALLOWED_INPUT_RE = /[\\d.-]/\n\nexport interface ColorFieldInputProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useComposing } from '@/shared'\nimport { injectColorFieldRootContext } from './ColorFieldRoot.vue'\n\nconst props = withDefaults(defineProps<ColorFieldInputProps>(), {\n  as: 'input',\n})\n\nconst rootContext = injectColorFieldRootContext()\n\nconst isFocused = ref(false)\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing()\n\nconst inputType = computed(() => {\n  return rootContext.channel.value ? 'text' : 'text'\n})\n\nconst inputMode = computed(() => {\n  return rootContext.channel.value ? 'numeric' : 'text'\n})\n\nfunction handleInput(event: Event) {\n  const target = event.target as HTMLInputElement\n  rootContext.updateValue(target.value)\n}\n\nfunction handleBlur() {\n  isFocused.value = false\n  rootContext.commit()\n}\n\nfunction handleFocus() {\n  isFocused.value = true\n}\n\nfunction handleWheel(event: WheelEvent) {\n  if (!isFocused.value)\n    return\n  rootContext.handleWheel(event)\n}\n\nfunction handleKeydown(event: KeyboardEvent) {\n  // Don't step/commit mid-composition, keys are used for IME candidate navigation and commit.\n  // `isComposing` stays true until the tick after `compositionend`, so the commit keydown\n  // (which can report `event.isComposing === false`) is still skipped.\n  if (isComposing.value || event.isComposing)\n    return\n  switch (event.key) {\n    case 'ArrowUp':\n      event.preventDefault()\n      rootContext.increment()\n      break\n    case 'ArrowDown':\n      event.preventDefault()\n      rootContext.decrement()\n      break\n    case 'PageUp':\n      event.preventDefault()\n      rootContext.incrementPage()\n      break\n    case 'PageDown':\n      event.preventDefault()\n      rootContext.decrementPage()\n      break\n    case 'Home':\n      event.preventDefault()\n      rootContext.decrementToMin()\n      break\n    case 'End':\n      event.preventDefault()\n      rootContext.incrementToMax()\n      break\n    case 'Enter':\n      event.preventDefault()\n      rootContext.commit()\n      break\n  }\n}\n\n// Handle numeric key validation for channel mode\nfunction handleBeforeInput(event: InputEvent) {\n  if (event.isComposing)\n    return\n  if (!rootContext.channel.value)\n    return // No validation for hex mode\n\n  const target = event.target as HTMLInputElement\n  const data = event.data\n\n  // Allow numbers, decimal point, minus sign\n  if (data && !ALLOWED_INPUT_RE.test(data)) {\n    event.preventDefault()\n    return\n  }\n\n  // Check the resulting value would be valid\n  const nextValue = target.value.slice(0, target.selectionStart ?? undefined)\n    + (data ?? '')\n    + target.value.slice(target.selectionEnd ?? undefined)\n\n  // Allow empty or partial values while typing\n  if (nextValue === '-' || nextValue === '.' || nextValue === '-.')\n    return\n\n  const numValue = parseFloat(nextValue)\n  if (isNaN(numValue)) {\n    event.preventDefault()\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :type=\"inputType\"\n    :inputmode=\"inputMode\"\n    :value=\"rootContext.inputValue.value\"\n    :placeholder=\"rootContext.placeholder.value\"\n    :disabled=\"rootContext.disabled.value\"\n    :readonly=\"rootContext.readonly.value\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :data-readonly=\"rootContext.readonly.value ? '' : undefined\"\n    :aria-invalid=\"!rootContext.channel.value ? undefined : undefined\"\n    @input=\"handleInput\"\n    @blur=\"handleBlur\"\n    @focus=\"handleFocus\"\n    @keydown=\"handleKeydown\"\n    @wheel=\"handleWheel\"\n    @beforeinput=\"handleBeforeInput\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nconst ALLOWED_INPUT_RE = /[\\d.-]/\n\nexport interface ColorFieldInputProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useComposing } from '@/shared'\nimport { injectColorFieldRootContext } from './ColorFieldRoot.vue'\n\nconst props = withDefaults(defineProps<ColorFieldInputProps>(), {\n  as: 'input',\n})\n\nconst rootContext = injectColorFieldRootContext()\n\nconst isFocused = ref(false)\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing()\n\nconst inputType = computed(() => {\n  return rootContext.channel.value ? 'text' : 'text'\n})\n\nconst inputMode = computed(() => {\n  return rootContext.channel.value ? 'numeric' : 'text'\n})\n\nfunction handleInput(event: Event) {\n  const target = event.target as HTMLInputElement\n  rootContext.updateValue(target.value)\n}\n\nfunction handleBlur() {\n  isFocused.value = false\n  rootContext.commit()\n}\n\nfunction handleFocus() {\n  isFocused.value = true\n}\n\nfunction handleWheel(event: WheelEvent) {\n  if (!isFocused.value)\n    return\n  rootContext.handleWheel(event)\n}\n\nfunction handleKeydown(event: KeyboardEvent) {\n  // Don't step/commit mid-composition, keys are used for IME candidate navigation and commit.\n  // `isComposing` stays true until the tick after `compositionend`, so the commit keydown\n  // (which can report `event.isComposing === false`) is still skipped.\n  if (isComposing.value || event.isComposing)\n    return\n  switch (event.key) {\n    case 'ArrowUp':\n      event.preventDefault()\n      rootContext.increment()\n      break\n    case 'ArrowDown':\n      event.preventDefault()\n      rootContext.decrement()\n      break\n    case 'PageUp':\n      event.preventDefault()\n      rootContext.incrementPage()\n      break\n    case 'PageDown':\n      event.preventDefault()\n      rootContext.decrementPage()\n      break\n    case 'Home':\n      event.preventDefault()\n      rootContext.decrementToMin()\n      break\n    case 'End':\n      event.preventDefault()\n      rootContext.incrementToMax()\n      break\n    case 'Enter':\n      event.preventDefault()\n      rootContext.commit()\n      break\n  }\n}\n\n// Handle numeric key validation for channel mode\nfunction handleBeforeInput(event: InputEvent) {\n  if (event.isComposing)\n    return\n  if (!rootContext.channel.value)\n    return // No validation for hex mode\n\n  const target = event.target as HTMLInputElement\n  const data = event.data\n\n  // Allow numbers, decimal point, minus sign\n  if (data && !ALLOWED_INPUT_RE.test(data)) {\n    event.preventDefault()\n    return\n  }\n\n  // Check the resulting value would be valid\n  const nextValue = target.value.slice(0, target.selectionStart ?? undefined)\n    + (data ?? '')\n    + target.value.slice(target.selectionEnd ?? undefined)\n\n  // Allow empty or partial values while typing\n  if (nextValue === '-' || nextValue === '.' || nextValue === '-.')\n    return\n\n  const numValue = parseFloat(nextValue)\n  if (isNaN(numValue)) {\n    event.preventDefault()\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :type=\"inputType\"\n    :inputmode=\"inputMode\"\n    :value=\"rootContext.inputValue.value\"\n    :placeholder=\"rootContext.placeholder.value\"\n    :disabled=\"rootContext.disabled.value\"\n    :readonly=\"rootContext.readonly.value\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :data-readonly=\"rootContext.readonly.value ? '' : undefined\"\n    :aria-invalid=\"!rootContext.channel.value ? undefined : undefined\"\n    @input=\"handleInput\"\n    @blur=\"handleBlur\"\n    @focus=\"handleFocus\"\n    @keydown=\"handleKeydown\"\n    @wheel=\"handleWheel\"\n    @beforeinput=\"handleBeforeInput\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","import type { ComputedRef } from 'vue'\nimport { clamp, createContext } from '@/shared'\n\nexport interface SliderOrientationPrivateProps {\n  min: number\n  max: number\n  inverted: boolean\n}\n\nexport type SliderOrientationPrivateEmits = {\n  slideEnd: []\n  slideStart: [value: number]\n  slideMove: [value: number]\n  homeKeyDown: [event: KeyboardEvent]\n  endKeyDown: [event: KeyboardEvent]\n  stepKeyDown: [event: KeyboardEvent, direction: number]\n}\n\nexport function getNextSortedValues(prevValues: number[] = [], nextValue: number, atIndex: number) {\n  const nextValues = [...prevValues]\n  nextValues[atIndex] = nextValue\n  return nextValues.sort((a, b) => a - b)\n}\n\nexport function convertValueToPercentage(value: number, min: number, max: number) {\n  const maxSteps = max - min\n  const percentPerStep = 100 / maxSteps\n  const percentage = percentPerStep * (value - min)\n  return clamp(percentage, 0, 100)\n}\n\n/**\n * Returns a label for each thumb when there are two or more thumbs\n */\nexport function getLabel(index: number, totalValues: number) {\n  if (totalValues > 2)\n    return `Value ${index + 1} of ${totalValues}`\n\n  else if (totalValues === 2)\n    return ['Minimum', 'Maximum'][index]\n\n  else\n    return undefined\n}\n\n/**\n * Given a `values` array and a `nextValue`, determine which value in\n * the array is closest to `nextValue` and return its index.\n *\n * @example\n * // returns 1\n * getClosestValueIndex([10, 30], 25);\n */\nexport function getClosestValueIndex(values: number[], nextValue: number) {\n  if (values.length === 1)\n    return 0\n  const distances = values.map(value => Math.abs(value - nextValue))\n  const closestDistance = Math.min(...distances)\n  return distances.indexOf(closestDistance)\n}\n\n/**\n * Offsets the thumb centre point while sliding to ensure it remains\n * within the bounds of the slider when reaching the edges\n */\nexport function getThumbInBoundsOffset(width: number, left: number, direction: number) {\n  const halfWidth = width / 2\n  const halfPercent = 50\n  const offset = linearScale([0, halfPercent], [0, halfWidth])\n  return (halfWidth - offset(left) * direction) * direction\n}\n\n/**\n * Gets an array of steps between each value.\n *\n * @example\n * // returns [1, 9]\n * getStepsBetweenValues([10, 11, 20]);\n */\nexport function getStepsBetweenValues(values: number[]) {\n  return values.slice(0, -1).map((value, index) => values[index + 1] - value)\n}\n\n/**\n * Verifies the minimum steps between all values is greater than or equal\n * to the expected minimum steps.\n *\n * @example\n * // returns false\n * hasMinStepsBetweenValues([1,2,3], 2);\n *\n * @example\n * // returns true\n * hasMinStepsBetweenValues([1,2,3], 1);\n */\nexport function hasMinStepsBetweenValues(values: number[], minStepsBetweenValues: number) {\n  if (minStepsBetweenValues > 0) {\n    const stepsBetweenValues = getStepsBetweenValues(values)\n    const actualMinStepsBetweenValues = Math.min(...stepsBetweenValues)\n    return actualMinStepsBetweenValues >= minStepsBetweenValues\n  }\n  return true\n}\n\n// https://github.com/tmcw-up-for-adoption/simple-linear-scale/blob/master/index.js\nexport function linearScale(input: readonly [number, number], output: readonly [number, number]) {\n  return (value: number) => {\n    if (input[0] === input[1] || output[0] === output[1])\n      return output[0]\n    const ratio = (output[1] - output[0]) / (input[1] - input[0])\n    return output[0] + ratio * (value - input[0])\n  }\n}\n\nexport function getDecimalCount(value: number) {\n  return (String(value).split('.')[1] || '').length\n}\n\nexport function roundValue(value: number, decimalCount: number) {\n  const rounder = 10 ** decimalCount\n  return Math.round(value * rounder) / rounder\n}\n\nexport type Direction = 'ltr' | 'rtl'\n\nexport const PAGE_KEYS = ['PageUp', 'PageDown']\nexport const ARROW_KEYS = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']\n\ntype SlideDirection = 'from-left' | 'from-right' | 'from-bottom' | 'from-top'\nexport const BACK_KEYS: Record<SlideDirection, string[]> = {\n  'from-left': ['Home', 'PageDown', 'ArrowDown', 'ArrowLeft'],\n  'from-right': ['Home', 'PageDown', 'ArrowDown', 'ArrowRight'],\n  'from-bottom': ['Home', 'PageDown', 'ArrowDown', 'ArrowLeft'],\n  'from-top': ['Home', 'PageUp', 'ArrowUp', 'ArrowLeft'],\n}\n\ntype Side = 'top' | 'right' | 'bottom' | 'left'\ninterface SliderOrientation {\n  startEdge: ComputedRef<Side>\n  endEdge: ComputedRef<Side>\n  direction: ComputedRef<1 | -1>\n  size: 'width' | 'height'\n}\n\nexport const [injectSliderOrientationContext, provideSliderOrientationContext]\n  = createContext<SliderOrientation>(['SliderVertical', 'SliderHorizontal'])\n","<script setup lang=\"ts\">\nimport type { Direction, SliderOrientationPrivateEmits, SliderOrientationPrivateProps } from './utils'\nimport { computed, ref, toRefs } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport SliderImpl from './SliderImpl.vue'\nimport { injectSliderRootContext } from './SliderRoot.vue'\nimport { BACK_KEYS, linearScale, provideSliderOrientationContext } from './utils'\n\ninterface SliderHorizontalProps extends SliderOrientationPrivateProps {\n  dir?: Direction\n}\n\nconst props = defineProps<SliderHorizontalProps>()\nconst emits = defineEmits<SliderOrientationPrivateEmits>()\nconst { max, min, dir, inverted } = toRefs(props)\n\nconst { forwardRef, currentElement: sliderElement } = useForwardExpose()\nconst rootContext = injectSliderRootContext()\n\nconst offsetPosition = ref<number>()\nconst rectRef = ref<DOMRect>()\nconst isSlidingFromLeft = computed(() => (dir?.value !== 'rtl' && !inverted.value) || (dir?.value !== 'ltr' && inverted.value))\n\nfunction getValueFromPointerEvent(event: PointerEvent, slideStart?: boolean) {\n  const rect = rectRef.value || sliderElement.value!.getBoundingClientRect()\n\n  // Get the currently active thumb element\n  const thumb = [...rootContext.thumbElements.value][rootContext.valueIndexToChangeRef.value]\n  const thumbWidth = rootContext.thumbAlignment.value === 'contain' ? thumb.clientWidth : 0\n\n  // Calculate offset for dragging, but only when needed\n  if (!offsetPosition.value && !slideStart && rootContext.thumbAlignment.value === 'contain') {\n    offsetPosition.value = event.clientX - thumb.getBoundingClientRect().left\n  }\n\n  // Define the input range (slider track width minus thumb width)\n  const input: [number, number] = [0, rect.width - thumbWidth]\n  const output: [number, number] = isSlidingFromLeft.value ? [min.value, max.value] : [max.value, min.value]\n  const value = linearScale(input, output)\n\n  rectRef.value = rect\n  const position = slideStart\n    ? event.clientX - rect.left - thumbWidth / 2\n    : event.clientX - rect.left - (offsetPosition.value ?? 0)\n\n  return value(position)\n}\n\nconst startEdge = computed(() => isSlidingFromLeft.value ? 'left' : 'right')\nconst endEdge = computed(() => isSlidingFromLeft.value ? 'right' : 'left')\nconst direction = computed(() => isSlidingFromLeft.value ? 1 : -1)\n\nprovideSliderOrientationContext({\n  startEdge,\n  endEdge,\n  direction,\n  size: 'width',\n})\n</script>\n\n<template>\n  <SliderImpl\n    :ref=\"forwardRef\"\n    :dir=\"dir\"\n    data-orientation=\"horizontal\"\n    :style=\"{\n      ['--reka-slider-thumb-transform' as any]:\n        !isSlidingFromLeft && rootContext.thumbAlignment.value === 'overflow' ? 'translateX(50%)' : 'translateX(-50%)',\n    }\"\n    @slide-start=\"(event) => {\n      const value = getValueFromPointerEvent(event, true);\n      emits('slideStart', value)\n    }\"\n    @slide-move=\"(event) => {\n      const value = getValueFromPointerEvent(event);\n      emits('slideMove', value)\n    }\"\n    @slide-end=\"() => {\n      rectRef = undefined;\n      offsetPosition = undefined\n      emits('slideEnd')\n    }\"\n    @step-key-down=\"(event) => {\n      const slideDirection = isSlidingFromLeft ? 'from-left' : 'from-right';\n      const isBackKey = BACK_KEYS[slideDirection].includes(event.key);\n      emits('stepKeyDown', event, isBackKey ? -1 : 1)\n    }\"\n    @end-key-down=\"emits('endKeyDown', $event)\"\n    @home-key-down=\"emits('homeKeyDown', $event)\"\n  >\n    <slot />\n  </SliderImpl>\n</template>\n","<script setup lang=\"ts\">\nimport type { Direction, SliderOrientationPrivateEmits, SliderOrientationPrivateProps } from './utils'\nimport { computed, ref, toRefs } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport SliderImpl from './SliderImpl.vue'\nimport { injectSliderRootContext } from './SliderRoot.vue'\nimport { BACK_KEYS, linearScale, provideSliderOrientationContext } from './utils'\n\ninterface SliderHorizontalProps extends SliderOrientationPrivateProps {\n  dir?: Direction\n}\n\nconst props = defineProps<SliderHorizontalProps>()\nconst emits = defineEmits<SliderOrientationPrivateEmits>()\nconst { max, min, dir, inverted } = toRefs(props)\n\nconst { forwardRef, currentElement: sliderElement } = useForwardExpose()\nconst rootContext = injectSliderRootContext()\n\nconst offsetPosition = ref<number>()\nconst rectRef = ref<DOMRect>()\nconst isSlidingFromLeft = computed(() => (dir?.value !== 'rtl' && !inverted.value) || (dir?.value !== 'ltr' && inverted.value))\n\nfunction getValueFromPointerEvent(event: PointerEvent, slideStart?: boolean) {\n  const rect = rectRef.value || sliderElement.value!.getBoundingClientRect()\n\n  // Get the currently active thumb element\n  const thumb = [...rootContext.thumbElements.value][rootContext.valueIndexToChangeRef.value]\n  const thumbWidth = rootContext.thumbAlignment.value === 'contain' ? thumb.clientWidth : 0\n\n  // Calculate offset for dragging, but only when needed\n  if (!offsetPosition.value && !slideStart && rootContext.thumbAlignment.value === 'contain') {\n    offsetPosition.value = event.clientX - thumb.getBoundingClientRect().left\n  }\n\n  // Define the input range (slider track width minus thumb width)\n  const input: [number, number] = [0, rect.width - thumbWidth]\n  const output: [number, number] = isSlidingFromLeft.value ? [min.value, max.value] : [max.value, min.value]\n  const value = linearScale(input, output)\n\n  rectRef.value = rect\n  const position = slideStart\n    ? event.clientX - rect.left - thumbWidth / 2\n    : event.clientX - rect.left - (offsetPosition.value ?? 0)\n\n  return value(position)\n}\n\nconst startEdge = computed(() => isSlidingFromLeft.value ? 'left' : 'right')\nconst endEdge = computed(() => isSlidingFromLeft.value ? 'right' : 'left')\nconst direction = computed(() => isSlidingFromLeft.value ? 1 : -1)\n\nprovideSliderOrientationContext({\n  startEdge,\n  endEdge,\n  direction,\n  size: 'width',\n})\n</script>\n\n<template>\n  <SliderImpl\n    :ref=\"forwardRef\"\n    :dir=\"dir\"\n    data-orientation=\"horizontal\"\n    :style=\"{\n      ['--reka-slider-thumb-transform' as any]:\n        !isSlidingFromLeft && rootContext.thumbAlignment.value === 'overflow' ? 'translateX(50%)' : 'translateX(-50%)',\n    }\"\n    @slide-start=\"(event) => {\n      const value = getValueFromPointerEvent(event, true);\n      emits('slideStart', value)\n    }\"\n    @slide-move=\"(event) => {\n      const value = getValueFromPointerEvent(event);\n      emits('slideMove', value)\n    }\"\n    @slide-end=\"() => {\n      rectRef = undefined;\n      offsetPosition = undefined\n      emits('slideEnd')\n    }\"\n    @step-key-down=\"(event) => {\n      const slideDirection = isSlidingFromLeft ? 'from-left' : 'from-right';\n      const isBackKey = BACK_KEYS[slideDirection].includes(event.key);\n      emits('stepKeyDown', event, isBackKey ? -1 : 1)\n    }\"\n    @end-key-down=\"emits('endKeyDown', $event)\"\n    @home-key-down=\"emits('homeKeyDown', $event)\"\n  >\n    <slot />\n  </SliderImpl>\n</template>\n","<script setup lang=\"ts\">\nimport type { SliderOrientationPrivateEmits, SliderOrientationPrivateProps } from './utils'\nimport { computed, ref, toRefs } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport SliderImpl from './SliderImpl.vue'\nimport { injectSliderRootContext } from './SliderRoot.vue'\nimport { BACK_KEYS, linearScale, provideSliderOrientationContext } from './utils'\n\ninterface SliderVerticalProps extends SliderOrientationPrivateProps {}\nconst props = defineProps<SliderVerticalProps>()\nconst emits = defineEmits<SliderOrientationPrivateEmits>()\nconst { max, min, inverted } = toRefs(props)\n\nconst rootContext = injectSliderRootContext()\nconst { forwardRef, currentElement: sliderElement } = useForwardExpose()\n\nconst offsetPosition = ref<number>()\nconst rectRef = ref<DOMRect>()\nconst isSlidingFromBottom = computed(() => !inverted.value)\n\nfunction getValueFromPointerEvent(event: PointerEvent, slideStart?: boolean) {\n  const rect = rectRef.value || sliderElement.value!.getBoundingClientRect()\n\n  // Get the currently active thumb element\n  const thumb = [...rootContext.thumbElements.value][rootContext.valueIndexToChangeRef.value]\n  const thumbHeight = rootContext.thumbAlignment.value === 'contain' ? thumb.clientHeight : 0\n\n  // Calculate offset for dragging, but only when needed\n  if (!offsetPosition.value && !slideStart && rootContext.thumbAlignment.value === 'contain') {\n    offsetPosition.value = event.clientY - thumb.getBoundingClientRect().top\n  }\n\n  // Define the input range (slider track width minus thumb width)\n  const input: [number, number] = [0, rect.height - thumbHeight]\n  const output: [number, number] = isSlidingFromBottom.value ? [max.value, min.value] : [min.value, max.value]\n  const value = linearScale(input, output)\n\n  const position = slideStart\n    ? event.clientY - rect.top - thumbHeight / 2\n    : event.clientY - rect.top - (offsetPosition.value ?? 0)\n\n  rectRef.value = rect\n  return value(position)\n}\n\nconst startEdge = computed(() => isSlidingFromBottom.value ? 'bottom' : 'top')\nconst endEdge = computed(() => isSlidingFromBottom.value ? 'top' : 'bottom')\nconst direction = computed(() => isSlidingFromBottom.value ? 1 : -1)\n\nprovideSliderOrientationContext({\n  startEdge,\n  endEdge,\n  direction,\n  size: 'height',\n})\n</script>\n\n<template>\n  <SliderImpl\n    :ref=\"forwardRef\"\n    data-orientation=\"vertical\"\n    :style=\"{\n      ['--reka-slider-thumb-transform' as any]:\n        !isSlidingFromBottom && rootContext.thumbAlignment.value === 'overflow' ? 'translateY(-50%)' : 'translateY(50%)',\n    }\"\n    @slide-start=\"(event) => {\n      const value = getValueFromPointerEvent(event, true);\n      emits('slideStart', value)\n    }\"\n    @slide-move=\"(event) => {\n      const value = getValueFromPointerEvent(event);\n      emits('slideMove', value)\n    }\"\n    @slide-end=\"() => {\n      rectRef = undefined;\n      offsetPosition = undefined\n      emits('slideEnd')\n    }\"\n    @step-key-down=\"(event) => {\n      const slideDirection = isSlidingFromBottom ? 'from-bottom' : 'from-top';\n      const isBackKey = BACK_KEYS[slideDirection].includes(event.key);\n      emits('stepKeyDown', event, isBackKey ? -1 : 1)\n    }\"\n    @end-key-down=\"emits('endKeyDown', $event)\"\n    @home-key-down=\"emits('homeKeyDown', $event)\"\n  >\n    <slot />\n  </SliderImpl>\n</template>\n","<script setup lang=\"ts\">\nimport type { SliderOrientationPrivateEmits, SliderOrientationPrivateProps } from './utils'\nimport { computed, ref, toRefs } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport SliderImpl from './SliderImpl.vue'\nimport { injectSliderRootContext } from './SliderRoot.vue'\nimport { BACK_KEYS, linearScale, provideSliderOrientationContext } from './utils'\n\ninterface SliderVerticalProps extends SliderOrientationPrivateProps {}\nconst props = defineProps<SliderVerticalProps>()\nconst emits = defineEmits<SliderOrientationPrivateEmits>()\nconst { max, min, inverted } = toRefs(props)\n\nconst rootContext = injectSliderRootContext()\nconst { forwardRef, currentElement: sliderElement } = useForwardExpose()\n\nconst offsetPosition = ref<number>()\nconst rectRef = ref<DOMRect>()\nconst isSlidingFromBottom = computed(() => !inverted.value)\n\nfunction getValueFromPointerEvent(event: PointerEvent, slideStart?: boolean) {\n  const rect = rectRef.value || sliderElement.value!.getBoundingClientRect()\n\n  // Get the currently active thumb element\n  const thumb = [...rootContext.thumbElements.value][rootContext.valueIndexToChangeRef.value]\n  const thumbHeight = rootContext.thumbAlignment.value === 'contain' ? thumb.clientHeight : 0\n\n  // Calculate offset for dragging, but only when needed\n  if (!offsetPosition.value && !slideStart && rootContext.thumbAlignment.value === 'contain') {\n    offsetPosition.value = event.clientY - thumb.getBoundingClientRect().top\n  }\n\n  // Define the input range (slider track width minus thumb width)\n  const input: [number, number] = [0, rect.height - thumbHeight]\n  const output: [number, number] = isSlidingFromBottom.value ? [max.value, min.value] : [min.value, max.value]\n  const value = linearScale(input, output)\n\n  const position = slideStart\n    ? event.clientY - rect.top - thumbHeight / 2\n    : event.clientY - rect.top - (offsetPosition.value ?? 0)\n\n  rectRef.value = rect\n  return value(position)\n}\n\nconst startEdge = computed(() => isSlidingFromBottom.value ? 'bottom' : 'top')\nconst endEdge = computed(() => isSlidingFromBottom.value ? 'top' : 'bottom')\nconst direction = computed(() => isSlidingFromBottom.value ? 1 : -1)\n\nprovideSliderOrientationContext({\n  startEdge,\n  endEdge,\n  direction,\n  size: 'height',\n})\n</script>\n\n<template>\n  <SliderImpl\n    :ref=\"forwardRef\"\n    data-orientation=\"vertical\"\n    :style=\"{\n      ['--reka-slider-thumb-transform' as any]:\n        !isSlidingFromBottom && rootContext.thumbAlignment.value === 'overflow' ? 'translateY(-50%)' : 'translateY(50%)',\n    }\"\n    @slide-start=\"(event) => {\n      const value = getValueFromPointerEvent(event, true);\n      emits('slideStart', value)\n    }\"\n    @slide-move=\"(event) => {\n      const value = getValueFromPointerEvent(event);\n      emits('slideMove', value)\n    }\"\n    @slide-end=\"() => {\n      rectRef = undefined;\n      offsetPosition = undefined\n      emits('slideEnd')\n    }\"\n    @step-key-down=\"(event) => {\n      const slideDirection = isSlidingFromBottom ? 'from-bottom' : 'from-top';\n      const isBackKey = BACK_KEYS[slideDirection].includes(event.key);\n      emits('stepKeyDown', event, isBackKey ? -1 : 1)\n    }\"\n    @end-key-down=\"emits('endKeyDown', $event)\"\n    @home-key-down=\"emits('homeKeyDown', $event)\"\n  >\n    <slot />\n  </SliderImpl>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { DataOrientation, Direction, FormFieldProps } from '../shared/types'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { clamp, createContext, useDirection, useFormControl, useForwardExpose } from '@/shared'\n\ntype ThumbAlignment = 'contain' | 'overflow'\n\nexport interface SliderRootProps extends PrimitiveProps, FormFieldProps {\n  /** The value of the slider when initially rendered. Use when you do not need to control the state of the slider. */\n  defaultValue?: number[]\n  /** The controlled value of the slider. Can be bind as `v-model`. */\n  modelValue?: number[] | null\n  /** When `true`, prevents the user from interacting with the slider. */\n  disabled?: boolean\n  /** The orientation of the slider. */\n  orientation?: DataOrientation\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** Whether the slider is visually inverted. */\n  inverted?: boolean\n  /** The minimum value for the range. */\n  min?: number\n  /** The maximum value for the range. */\n  max?: number\n  /** The stepping interval. */\n  step?: number\n  /** The minimum permitted steps between multiple thumbs. */\n  minStepsBetweenThumbs?: number\n  /**\n   * The alignment of the slider thumb.\n   * - `contain`: thumbs will be contained within the bounds of the track.\n   * - `overflow`: thumbs will not be bound by the track. No extra offset will be added.\n   * @defaultValue 'contain'\n   */\n  thumbAlignment?: ThumbAlignment\n}\n\nexport type SliderRootEmits = {\n  /**\n   * Event handler called when the slider value changes\n   */\n  'update:modelValue': [payload: number[] | undefined]\n  /**\n   * Event handler called when the value changes at the end of an interaction.\n   *\n   * Useful when you only need to capture a final value e.g. to update a backend service.\n   */\n  'valueCommit': [payload: number[]]\n}\n\nexport interface SliderRootContext {\n  orientation: Ref<DataOrientation>\n  disabled: Ref<boolean>\n  min: Ref<number>\n  max: Ref<number>\n  modelValue?: Readonly<Ref<number[] | null | undefined>>\n  currentModelValue: ComputedRef<number[]>\n  valueIndexToChangeRef: Ref<number>\n  thumbElements: Ref<HTMLElement[]>\n  thumbAlignment: Ref<ThumbAlignment>\n}\n\nexport const [injectSliderRootContext, provideSliderRootContext]\n  = createContext<SliderRootContext>('SliderRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRaw, toRefs } from 'vue'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\nimport SliderHorizontal from './SliderHorizontal.vue'\nimport SliderVertical from './SliderVertical.vue'\nimport { ARROW_KEYS, getClosestValueIndex, getDecimalCount, getNextSortedValues, hasMinStepsBetweenValues, PAGE_KEYS, roundValue } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<SliderRootProps>(), {\n  min: 0,\n  max: 100,\n  step: 1,\n  orientation: 'horizontal',\n  disabled: false,\n  minStepsBetweenThumbs: 0,\n  defaultValue: () => [0],\n  inverted: false,\n  thumbAlignment: 'contain',\n  as: 'span',\n})\nconst emits = defineEmits<SliderRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current slider values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { min, max, step, minStepsBetweenThumbs, orientation, disabled, thumbAlignment, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nconst { forwardRef, currentElement } = useForwardExpose()\nconst isFormControl = useFormControl(currentElement)\n\nconst { CollectionSlot } = useCollection({ isProvider: true })\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<number[] | null>\n\nconst currentModelValue = computed(() => Array.isArray(modelValue.value) ? [...modelValue.value] : [])\n\nconst valueIndexToChangeRef = ref(0)\nconst valuesBeforeSlideStartRef = ref(currentModelValue.value)\n\nfunction handleSlideStart(value: number) {\n  const closestIndex = getClosestValueIndex(currentModelValue.value, value)\n  updateValues(value, closestIndex)\n}\n\nfunction handleSlideMove(value: number) {\n  updateValues(value, valueIndexToChangeRef.value)\n}\n\nfunction handleSlideEnd() {\n  const prevValue = valuesBeforeSlideStartRef.value[valueIndexToChangeRef.value]\n  const nextValue = currentModelValue.value[valueIndexToChangeRef.value]\n  const hasChanged = nextValue !== prevValue\n  if (hasChanged)\n    emits('valueCommit', toRaw(currentModelValue.value))\n}\n\nfunction updateValues(value: number, atIndex: number, { commit } = { commit: false }) {\n  const decimalCount = getDecimalCount(step.value)\n  const snapToStep = roundValue(Math.round((value - min.value) / step.value) * step.value + min.value, decimalCount)\n  const nextValue = clamp(snapToStep, min.value, max.value)\n\n  const nextValues = getNextSortedValues(currentModelValue.value, nextValue, atIndex)\n\n  if (hasMinStepsBetweenValues(nextValues, minStepsBetweenThumbs.value * step.value)) {\n    valueIndexToChangeRef.value = nextValues.indexOf(nextValue)\n    const hasChanged = String(nextValues) !== String(modelValue.value)\n    if (hasChanged && commit)\n      emits('valueCommit', nextValues)\n\n    if (hasChanged) {\n      thumbElements.value[valueIndexToChangeRef.value]?.focus()\n      modelValue.value = nextValues\n    }\n  }\n}\n\nconst thumbElements = ref<HTMLElement[]>([])\nprovideSliderRootContext({\n  modelValue,\n  currentModelValue,\n  valueIndexToChangeRef,\n  thumbElements,\n  orientation,\n  min,\n  max,\n  disabled,\n  thumbAlignment,\n})\n</script>\n\n<template>\n  <CollectionSlot>\n    <component\n      :is=\"orientation === 'horizontal' ? SliderHorizontal : SliderVertical\"\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      :min=\"min\"\n      :max=\"max\"\n      :dir=\"dir\"\n      :inverted=\"inverted\"\n      :aria-disabled=\"disabled\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      @pointerdown=\"() => {\n        if (!disabled) valuesBeforeSlideStartRef = currentModelValue\n      }\"\n      @slide-start=\"!disabled && handleSlideStart($event)\"\n      @slide-move=\"!disabled && handleSlideMove($event)\"\n      @slide-end=\"!disabled && handleSlideEnd()\"\n      @home-key-down=\"!disabled && updateValues(min, 0, { commit: true })\"\n      @end-key-down=\"!disabled && updateValues(max, currentModelValue.length - 1, { commit: true })\"\n      @step-key-down=\"(event, direction) => {\n        if (!disabled) {\n          const isPageKey = PAGE_KEYS.includes(event.key);\n          const isSkipKey = isPageKey || (event.shiftKey && ARROW_KEYS.includes(event.key));\n          const multiplier = isSkipKey ? 10 : 1;\n          const atIndex = valueIndexToChangeRef;\n          const value = currentModelValue[atIndex];\n          const stepInDirection = step * multiplier * direction;\n          updateValues(value + stepInDirection, atIndex, { commit: true });\n        }\n      }\"\n    >\n      <slot :model-value=\"modelValue\" />\n\n      <VisuallyHiddenInput\n        v-if=\"isFormControl && name\"\n        type=\"number\"\n        :value=\"modelValue\"\n        :name=\"name\"\n        :required=\"required\"\n        :disabled=\"disabled\"\n        :step=\"step\"\n      />\n    </component>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { DataOrientation, Direction, FormFieldProps } from '../shared/types'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { clamp, createContext, useDirection, useFormControl, useForwardExpose } from '@/shared'\n\ntype ThumbAlignment = 'contain' | 'overflow'\n\nexport interface SliderRootProps extends PrimitiveProps, FormFieldProps {\n  /** The value of the slider when initially rendered. Use when you do not need to control the state of the slider. */\n  defaultValue?: number[]\n  /** The controlled value of the slider. Can be bind as `v-model`. */\n  modelValue?: number[] | null\n  /** When `true`, prevents the user from interacting with the slider. */\n  disabled?: boolean\n  /** The orientation of the slider. */\n  orientation?: DataOrientation\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** Whether the slider is visually inverted. */\n  inverted?: boolean\n  /** The minimum value for the range. */\n  min?: number\n  /** The maximum value for the range. */\n  max?: number\n  /** The stepping interval. */\n  step?: number\n  /** The minimum permitted steps between multiple thumbs. */\n  minStepsBetweenThumbs?: number\n  /**\n   * The alignment of the slider thumb.\n   * - `contain`: thumbs will be contained within the bounds of the track.\n   * - `overflow`: thumbs will not be bound by the track. No extra offset will be added.\n   * @defaultValue 'contain'\n   */\n  thumbAlignment?: ThumbAlignment\n}\n\nexport type SliderRootEmits = {\n  /**\n   * Event handler called when the slider value changes\n   */\n  'update:modelValue': [payload: number[] | undefined]\n  /**\n   * Event handler called when the value changes at the end of an interaction.\n   *\n   * Useful when you only need to capture a final value e.g. to update a backend service.\n   */\n  'valueCommit': [payload: number[]]\n}\n\nexport interface SliderRootContext {\n  orientation: Ref<DataOrientation>\n  disabled: Ref<boolean>\n  min: Ref<number>\n  max: Ref<number>\n  modelValue?: Readonly<Ref<number[] | null | undefined>>\n  currentModelValue: ComputedRef<number[]>\n  valueIndexToChangeRef: Ref<number>\n  thumbElements: Ref<HTMLElement[]>\n  thumbAlignment: Ref<ThumbAlignment>\n}\n\nexport const [injectSliderRootContext, provideSliderRootContext]\n  = createContext<SliderRootContext>('SliderRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRaw, toRefs } from 'vue'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\nimport SliderHorizontal from './SliderHorizontal.vue'\nimport SliderVertical from './SliderVertical.vue'\nimport { ARROW_KEYS, getClosestValueIndex, getDecimalCount, getNextSortedValues, hasMinStepsBetweenValues, PAGE_KEYS, roundValue } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<SliderRootProps>(), {\n  min: 0,\n  max: 100,\n  step: 1,\n  orientation: 'horizontal',\n  disabled: false,\n  minStepsBetweenThumbs: 0,\n  defaultValue: () => [0],\n  inverted: false,\n  thumbAlignment: 'contain',\n  as: 'span',\n})\nconst emits = defineEmits<SliderRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current slider values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { min, max, step, minStepsBetweenThumbs, orientation, disabled, thumbAlignment, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nconst { forwardRef, currentElement } = useForwardExpose()\nconst isFormControl = useFormControl(currentElement)\n\nconst { CollectionSlot } = useCollection({ isProvider: true })\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<number[] | null>\n\nconst currentModelValue = computed(() => Array.isArray(modelValue.value) ? [...modelValue.value] : [])\n\nconst valueIndexToChangeRef = ref(0)\nconst valuesBeforeSlideStartRef = ref(currentModelValue.value)\n\nfunction handleSlideStart(value: number) {\n  const closestIndex = getClosestValueIndex(currentModelValue.value, value)\n  updateValues(value, closestIndex)\n}\n\nfunction handleSlideMove(value: number) {\n  updateValues(value, valueIndexToChangeRef.value)\n}\n\nfunction handleSlideEnd() {\n  const prevValue = valuesBeforeSlideStartRef.value[valueIndexToChangeRef.value]\n  const nextValue = currentModelValue.value[valueIndexToChangeRef.value]\n  const hasChanged = nextValue !== prevValue\n  if (hasChanged)\n    emits('valueCommit', toRaw(currentModelValue.value))\n}\n\nfunction updateValues(value: number, atIndex: number, { commit } = { commit: false }) {\n  const decimalCount = getDecimalCount(step.value)\n  const snapToStep = roundValue(Math.round((value - min.value) / step.value) * step.value + min.value, decimalCount)\n  const nextValue = clamp(snapToStep, min.value, max.value)\n\n  const nextValues = getNextSortedValues(currentModelValue.value, nextValue, atIndex)\n\n  if (hasMinStepsBetweenValues(nextValues, minStepsBetweenThumbs.value * step.value)) {\n    valueIndexToChangeRef.value = nextValues.indexOf(nextValue)\n    const hasChanged = String(nextValues) !== String(modelValue.value)\n    if (hasChanged && commit)\n      emits('valueCommit', nextValues)\n\n    if (hasChanged) {\n      thumbElements.value[valueIndexToChangeRef.value]?.focus()\n      modelValue.value = nextValues\n    }\n  }\n}\n\nconst thumbElements = ref<HTMLElement[]>([])\nprovideSliderRootContext({\n  modelValue,\n  currentModelValue,\n  valueIndexToChangeRef,\n  thumbElements,\n  orientation,\n  min,\n  max,\n  disabled,\n  thumbAlignment,\n})\n</script>\n\n<template>\n  <CollectionSlot>\n    <component\n      :is=\"orientation === 'horizontal' ? SliderHorizontal : SliderVertical\"\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      :min=\"min\"\n      :max=\"max\"\n      :dir=\"dir\"\n      :inverted=\"inverted\"\n      :aria-disabled=\"disabled\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      @pointerdown=\"() => {\n        if (!disabled) valuesBeforeSlideStartRef = currentModelValue\n      }\"\n      @slide-start=\"!disabled && handleSlideStart($event)\"\n      @slide-move=\"!disabled && handleSlideMove($event)\"\n      @slide-end=\"!disabled && handleSlideEnd()\"\n      @home-key-down=\"!disabled && updateValues(min, 0, { commit: true })\"\n      @end-key-down=\"!disabled && updateValues(max, currentModelValue.length - 1, { commit: true })\"\n      @step-key-down=\"(event, direction) => {\n        if (!disabled) {\n          const isPageKey = PAGE_KEYS.includes(event.key);\n          const isSkipKey = isPageKey || (event.shiftKey && ARROW_KEYS.includes(event.key));\n          const multiplier = isSkipKey ? 10 : 1;\n          const atIndex = valueIndexToChangeRef;\n          const value = currentModelValue[atIndex];\n          const stepInDirection = step * multiplier * direction;\n          updateValues(value + stepInDirection, atIndex, { commit: true });\n        }\n      }\"\n    >\n      <slot :model-value=\"modelValue\" />\n\n      <VisuallyHiddenInput\n        v-if=\"isFormControl && name\"\n        type=\"number\"\n        :value=\"modelValue\"\n        :name=\"name\"\n        :required=\"required\"\n        :disabled=\"disabled\"\n        :step=\"step\"\n      />\n    </component>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport type SliderImplEmits = {\n  slideStart: [event: PointerEvent]\n  slideMove: [event: PointerEvent]\n  slideEnd: [event: PointerEvent]\n  homeKeyDown: [event: KeyboardEvent]\n  endKeyDown: [event: KeyboardEvent]\n  stepKeyDown: [event: KeyboardEvent]\n}\n\nexport interface SliderImplProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectSliderRootContext } from './SliderRoot.vue'\nimport { ARROW_KEYS, PAGE_KEYS } from './utils'\n\nconst props = withDefaults(defineProps<SliderImplProps>(), {\n  as: 'span',\n})\nconst emits = defineEmits<SliderImplEmits>()\nconst rootContext = injectSliderRootContext()\n</script>\n\n<template>\n  <Primitive\n    data-slider-impl\n    v-bind=\"props\"\n    @keydown=\"(event: KeyboardEvent) => {\n      if (event.key === 'Home') {\n        emits('homeKeyDown', event)\n        // Prevent scrolling to page start\n        event.preventDefault();\n      }\n      else if (event.key === 'End') {\n        emits('endKeyDown', event)\n        // Prevent scrolling to page end\n        event.preventDefault();\n      }\n      else if (PAGE_KEYS.concat(ARROW_KEYS).includes(event.key)) {\n        emits('stepKeyDown', event)\n        // Prevent scrolling for directional key presses\n        event.preventDefault();\n      }\n    }\"\n    @pointerdown=\"(event: PointerEvent) => {\n      const target = event.target as HTMLElement;\n      target.setPointerCapture(event.pointerId);\n      // Prevent browser focus behaviour because we focus a thumb manually when values change.\n      event.preventDefault();\n      // Touch devices have a delay before focusing so won't focus if touch immediately moves\n      // away from target (sliding). We want thumb to focus regardless.\n      if (rootContext.thumbElements.value.includes(target)) {\n        target.focus();\n      }\n      else {\n        emits('slideStart', event)\n      }\n    }\"\n    @pointermove=\"(event: PointerEvent) => {\n      const target = event.target as HTMLElement;\n      if (target.hasPointerCapture(event.pointerId)) emits('slideMove', event);\n    }\"\n    @pointerup=\"(event: PointerEvent) => {\n      const target = event.target as HTMLElement;\n      if (target.hasPointerCapture(event.pointerId)) {\n        target.releasePointerCapture(event.pointerId);\n        emits('slideEnd', event)\n      }\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport type SliderImplEmits = {\n  slideStart: [event: PointerEvent]\n  slideMove: [event: PointerEvent]\n  slideEnd: [event: PointerEvent]\n  homeKeyDown: [event: KeyboardEvent]\n  endKeyDown: [event: KeyboardEvent]\n  stepKeyDown: [event: KeyboardEvent]\n}\n\nexport interface SliderImplProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectSliderRootContext } from './SliderRoot.vue'\nimport { ARROW_KEYS, PAGE_KEYS } from './utils'\n\nconst props = withDefaults(defineProps<SliderImplProps>(), {\n  as: 'span',\n})\nconst emits = defineEmits<SliderImplEmits>()\nconst rootContext = injectSliderRootContext()\n</script>\n\n<template>\n  <Primitive\n    data-slider-impl\n    v-bind=\"props\"\n    @keydown=\"(event: KeyboardEvent) => {\n      if (event.key === 'Home') {\n        emits('homeKeyDown', event)\n        // Prevent scrolling to page start\n        event.preventDefault();\n      }\n      else if (event.key === 'End') {\n        emits('endKeyDown', event)\n        // Prevent scrolling to page end\n        event.preventDefault();\n      }\n      else if (PAGE_KEYS.concat(ARROW_KEYS).includes(event.key)) {\n        emits('stepKeyDown', event)\n        // Prevent scrolling for directional key presses\n        event.preventDefault();\n      }\n    }\"\n    @pointerdown=\"(event: PointerEvent) => {\n      const target = event.target as HTMLElement;\n      target.setPointerCapture(event.pointerId);\n      // Prevent browser focus behaviour because we focus a thumb manually when values change.\n      event.preventDefault();\n      // Touch devices have a delay before focusing so won't focus if touch immediately moves\n      // away from target (sliding). We want thumb to focus regardless.\n      if (rootContext.thumbElements.value.includes(target)) {\n        target.focus();\n      }\n      else {\n        emits('slideStart', event)\n      }\n    }\"\n    @pointermove=\"(event: PointerEvent) => {\n      const target = event.target as HTMLElement;\n      if (target.hasPointerCapture(event.pointerId)) emits('slideMove', event);\n    }\"\n    @pointerup=\"(event: PointerEvent) => {\n      const target = event.target as HTMLElement;\n      if (target.hasPointerCapture(event.pointerId)) {\n        target.releasePointerCapture(event.pointerId);\n        emits('slideEnd', event)\n      }\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface SliderRangeProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectSliderRootContext } from './SliderRoot.vue'\nimport { convertValueToPercentage, injectSliderOrientationContext } from './utils'\n\nwithDefaults(defineProps<SliderRangeProps>(), { as: 'span' })\nconst rootContext = injectSliderRootContext()\nconst orientation = injectSliderOrientationContext()\n\nuseForwardExpose()\nconst percentages = computed(() => rootContext.currentModelValue.value.map(value =>\n  convertValueToPercentage(value, rootContext.min.value, rootContext.max.value),\n))\n\nconst offsetStart = computed(() => rootContext.currentModelValue.value.length > 1 ? Math.min(...percentages.value!) : 0)\nconst offsetEnd = computed(() => 100 - Math.max(...percentages.value, 0))\n</script>\n\n<template>\n  <Primitive\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :data-orientation=\"rootContext.orientation.value\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :style=\"{\n      [orientation!.startEdge.value]: `${offsetStart}%`,\n      [orientation!.endEdge.value]: `${offsetEnd}%`,\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface SliderRangeProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectSliderRootContext } from './SliderRoot.vue'\nimport { convertValueToPercentage, injectSliderOrientationContext } from './utils'\n\nwithDefaults(defineProps<SliderRangeProps>(), { as: 'span' })\nconst rootContext = injectSliderRootContext()\nconst orientation = injectSliderOrientationContext()\n\nuseForwardExpose()\nconst percentages = computed(() => rootContext.currentModelValue.value.map(value =>\n  convertValueToPercentage(value, rootContext.min.value, rootContext.max.value),\n))\n\nconst offsetStart = computed(() => rootContext.currentModelValue.value.length > 1 ? Math.min(...percentages.value!) : 0)\nconst offsetEnd = computed(() => 100 - Math.max(...percentages.value, 0))\n</script>\n\n<template>\n  <Primitive\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :data-orientation=\"rootContext.orientation.value\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :style=\"{\n      [orientation!.startEdge.value]: `${offsetStart}%`,\n      [orientation!.endEdge.value]: `${offsetEnd}%`,\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface SliderThumbImplProps extends PrimitiveProps {\n  index: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useMounted } from '@vueuse/core'\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose, useSize } from '@/shared'\nimport { injectSliderRootContext } from './SliderRoot.vue'\nimport { convertValueToPercentage, getLabel, getThumbInBoundsOffset, injectSliderOrientationContext } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<SliderThumbImplProps>()\n\nconst rootContext = injectSliderRootContext()\nconst orientation = injectSliderOrientationContext()\n\nconst { forwardRef, currentElement: thumbElement } = useForwardExpose()\nconst { CollectionItem } = useCollection()\n\nconst value = computed(() => rootContext.modelValue?.value?.[props.index])\nconst percent = computed(() => value.value === undefined ? 0 : convertValueToPercentage(value.value, rootContext.min.value ?? 0, rootContext.max.value ?? 100))\nconst label = computed(() => getLabel(props.index, rootContext.modelValue?.value?.length ?? 0))\nconst size = useSize(thumbElement)\nconst orientationSize = computed(() => size[orientation!.size].value)\nconst thumbInBoundsOffset = computed(() => {\n  if (rootContext.thumbAlignment.value === 'overflow' || !orientationSize.value) {\n    return 0\n  }\n  else {\n    return getThumbInBoundsOffset(orientationSize.value, percent.value, orientation!.direction.value)\n  }\n})\n\nconst isMounted = useMounted()\nonMounted(() => {\n  rootContext.thumbElements.value.push(thumbElement.value)\n})\nonUnmounted(() => {\n  const i = rootContext.thumbElements.value.findIndex(i => i === thumbElement.value) ?? -1\n  rootContext.thumbElements.value.splice(i, 1)\n})\n</script>\n\n<template>\n  <CollectionItem>\n    <Primitive\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      role=\"slider\"\n      :tabindex=\"rootContext.disabled.value ? undefined : 0\"\n      :aria-label=\"$attrs['aria-label'] || label\"\n      :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n      :data-orientation=\"rootContext.orientation.value\"\n      :aria-valuenow=\"value\"\n      :aria-valuemin=\"rootContext.min.value\"\n      :aria-valuemax=\"rootContext.max.value\"\n      :aria-orientation=\"rootContext.orientation.value\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      :style=\"{\n        transform: 'var(--reka-slider-thumb-transform)',\n        position: 'absolute',\n        [orientation!.startEdge.value]: `calc(${percent}% + ${thumbInBoundsOffset}px)`,\n        /**\n         * There will be no value on initial render while we work out the index so we hide thumbs\n         * without a value, otherwise SSR will render them in the wrong position before they\n         * snap into the correct position during hydration which would be visually jarring for\n         * slower connections.\n         */\n        display: !isMounted && value === undefined ? 'none' : undefined,\n      }\"\n      @focus=\"() => {\n        rootContext.valueIndexToChangeRef.value = index\n      }\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface SliderThumbImplProps extends PrimitiveProps {\n  index: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useMounted } from '@vueuse/core'\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose, useSize } from '@/shared'\nimport { injectSliderRootContext } from './SliderRoot.vue'\nimport { convertValueToPercentage, getLabel, getThumbInBoundsOffset, injectSliderOrientationContext } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<SliderThumbImplProps>()\n\nconst rootContext = injectSliderRootContext()\nconst orientation = injectSliderOrientationContext()\n\nconst { forwardRef, currentElement: thumbElement } = useForwardExpose()\nconst { CollectionItem } = useCollection()\n\nconst value = computed(() => rootContext.modelValue?.value?.[props.index])\nconst percent = computed(() => value.value === undefined ? 0 : convertValueToPercentage(value.value, rootContext.min.value ?? 0, rootContext.max.value ?? 100))\nconst label = computed(() => getLabel(props.index, rootContext.modelValue?.value?.length ?? 0))\nconst size = useSize(thumbElement)\nconst orientationSize = computed(() => size[orientation!.size].value)\nconst thumbInBoundsOffset = computed(() => {\n  if (rootContext.thumbAlignment.value === 'overflow' || !orientationSize.value) {\n    return 0\n  }\n  else {\n    return getThumbInBoundsOffset(orientationSize.value, percent.value, orientation!.direction.value)\n  }\n})\n\nconst isMounted = useMounted()\nonMounted(() => {\n  rootContext.thumbElements.value.push(thumbElement.value)\n})\nonUnmounted(() => {\n  const i = rootContext.thumbElements.value.findIndex(i => i === thumbElement.value) ?? -1\n  rootContext.thumbElements.value.splice(i, 1)\n})\n</script>\n\n<template>\n  <CollectionItem>\n    <Primitive\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      role=\"slider\"\n      :tabindex=\"rootContext.disabled.value ? undefined : 0\"\n      :aria-label=\"$attrs['aria-label'] || label\"\n      :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n      :data-orientation=\"rootContext.orientation.value\"\n      :aria-valuenow=\"value\"\n      :aria-valuemin=\"rootContext.min.value\"\n      :aria-valuemax=\"rootContext.max.value\"\n      :aria-orientation=\"rootContext.orientation.value\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      :style=\"{\n        transform: 'var(--reka-slider-thumb-transform)',\n        position: 'absolute',\n        [orientation!.startEdge.value]: `calc(${percent}% + ${thumbInBoundsOffset}px)`,\n        /**\n         * There will be no value on initial render while we work out the index so we hide thumbs\n         * without a value, otherwise SSR will render them in the wrong position before they\n         * snap into the correct position during hydration which would be visually jarring for\n         * slower connections.\n         */\n        display: !isMounted && value === undefined ? 'none' : undefined,\n      }\"\n      @focus=\"() => {\n        rootContext.valueIndexToChangeRef.value = index\n      }\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface SliderThumbProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { useCollection } from '@/Collection'\nimport SliderThumbImpl from './SliderThumbImpl.vue'\n\nconst props = withDefaults(defineProps<SliderThumbProps>(), {\n  as: 'span',\n})\nconst { getItems } = useCollection()\n\nconst { forwardRef, currentElement: thumbElement } = useForwardExpose()\n\nconst index = computed(() => thumbElement.value ? getItems(true).findIndex(i => i.ref === thumbElement.value) : -1)\n</script>\n\n<template>\n  <SliderThumbImpl\n    :ref=\"forwardRef\"\n    v-bind=\"props\"\n    :index=\"index\"\n  >\n    <slot />\n  </SliderThumbImpl>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface SliderThumbProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { useCollection } from '@/Collection'\nimport SliderThumbImpl from './SliderThumbImpl.vue'\n\nconst props = withDefaults(defineProps<SliderThumbProps>(), {\n  as: 'span',\n})\nconst { getItems } = useCollection()\n\nconst { forwardRef, currentElement: thumbElement } = useForwardExpose()\n\nconst index = computed(() => thumbElement.value ? getItems(true).findIndex(i => i.ref === thumbElement.value) : -1)\n</script>\n\n<template>\n  <SliderThumbImpl\n    :ref=\"forwardRef\"\n    v-bind=\"props\"\n    :index=\"index\"\n  >\n    <slot />\n  </SliderThumbImpl>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface SliderTrackProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectSliderRootContext } from './SliderRoot.vue'\n\nwithDefaults(defineProps<SliderTrackProps>(), { as: 'span' })\n\nconst rootContext = injectSliderRootContext()\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :data-orientation=\"rootContext.orientation.value\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface SliderTrackProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectSliderRootContext } from './SliderRoot.vue'\n\nwithDefaults(defineProps<SliderTrackProps>(), { as: 'span' })\n\nconst rootContext = injectSliderRootContext()\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :data-orientation=\"rootContext.orientation.value\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Color, ColorChannel, ColorChannel as ColorChannelType, ColorSpace } from '@/shared/color'\nimport type { DataOrientation, Direction, FormFieldProps } from '@/shared/types'\nimport { createContext, useDirection, useFormControl, useForwardExpose } from '@/shared'\n\nexport interface ColorSliderRootProps extends PrimitiveProps, FormFieldProps {\n  /** The color value (controlled). Can be a hex string or Color object. */\n  modelValue?: string | Color\n  /** The default color value (uncontrolled). */\n  defaultValue?: string | Color\n  /** The color space to operate in. */\n  colorSpace?: ColorSpace\n  /** The color channel that this slider manipulates. */\n  channel: ColorChannel\n  /** The orientation of the slider. */\n  orientation?: DataOrientation\n  /** The reading direction of the slider. */\n  dir?: Direction\n  /** Whether the slider is visually inverted. */\n  inverted?: boolean\n  /** When `true`, prevents the user from interacting with the slider. */\n  disabled?: boolean\n  /** Custom step value for increment/decrement. Defaults to the channel's natural step. */\n  step?: number\n}\n\nexport type ColorSliderRootEmits = {\n  'update:modelValue': [value: string | Color]\n  'update:color': [value: Color]\n  'change': [value: string]\n  'changeEnd': [value: string]\n}\n\nexport interface ColorSliderRootContext {\n  color: Ref<Color>\n  channelValue: ComputedRef<number>\n  channel: Ref<ColorChannel>\n  colorSpace: Ref<ColorSpace>\n  orientation: Ref<DataOrientation>\n  disabled: Ref<boolean>\n  inverted: Ref<boolean>\n  min: ComputedRef<number>\n  max: ComputedRef<number>\n  step: ComputedRef<number>\n}\n\nexport const [injectColorSliderRootContext, provideColorSliderRootContext]\n  = createContext<ColorSliderRootContext>('ColorSliderRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRefs, watch } from 'vue'\nimport { colorToString, convertToHsb, convertToHsl, convertToRgb, getChannelRange, getChannelValue, normalizeColor, setChannelValue } from '@/shared/color'\nimport { SliderRoot } from '@/Slider'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ColorSliderRootProps>(), {\n  colorSpace: 'hsl',\n  orientation: 'horizontal',\n  disabled: false,\n  inverted: false,\n  defaultValue: '#000000',\n  as: 'span',\n})\n\nconst emits = defineEmits<ColorSliderRootEmits>()\n\nconst { orientation, disabled, inverted, dir: propDir, channel, colorSpace, step: stepProp } = toRefs(props)\nconst dir = useDirection(propDir)\nconst { forwardRef, currentElement } = useForwardExpose()\nconst isFormControl = useFormControl(currentElement)\n\n// Normalize the model value to a Color object\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n})\n\n// Convert a color to the native color space for the given channel.\n// This ensures setChannelValue/getChannelValue operate without cross-space round-trips.\nfunction toNativeSpace(color: Color, ch: ColorChannelType, space: ColorSpace): Color {\n  switch (ch) {\n    case 'hue':\n    case 'lightness':\n      return convertToHsl(color)\n    case 'saturation':\n      return space === 'hsb' ? convertToHsb(color) : convertToHsl(color)\n    case 'brightness':\n      return convertToHsb(color)\n    case 'red':\n    case 'green':\n    case 'blue':\n      return convertToRgb(color)\n    case 'alpha':\n      return color\n    default:\n      return color\n  }\n}\n\n// Internal color ref that preserves color space precision.\n// Convert to the channel's native space to avoid cross-space round-trips during drag.\nconst internalColor = ref<Color>(toNativeSpace(normalizeColor(modelValue.value ?? props.defaultValue ?? '#000000'), channel.value, colorSpace.value))\n\n// Check if a color is achromatic (hue information is lost in hex round-trips)\nfunction isAchromatic(color: Color): boolean {\n  const hsl = convertToHsl(color)\n  return hsl.s === 0 || hsl.l === 0 || hsl.l >= 100\n}\n\n// Sync internal color from external modelValue changes (e.g. parent updates)\nwatch(() => modelValue.value, (newVal) => {\n  if (newVal == null)\n    return\n  const parsed = normalizeColor(newVal)\n  const currentHex = colorToString(internalColor.value, 'hex')\n  const newHex = colorToString(parsed, 'hex')\n  // Only update if the external value actually changed (avoid overwriting\n  // precision during our own drag updates)\n  if (currentHex !== newHex) {\n    const nativeColor = toNativeSpace(parsed, channel.value, colorSpace.value)\n    const currentChannelVal = getChannelValue(internalColor.value, channel.value)\n    const newChannelVal = getChannelValue(nativeColor, channel.value)\n\n    // Preserve this slider's channel value when:\n    // 1. Color is achromatic (hue completely lost in hex round-trip)\n    // 2. Channel value diff is within 2% of range (8-bit RGB quantization drift)\n    // We still update the rest of the color so the track gradient stays correct.\n    const range = channelRange.value.max - channelRange.value.min\n    const shouldPreserve = (channel.value === 'hue' && isAchromatic(parsed))\n      || Math.abs(currentChannelVal - newChannelVal) < range * 0.02\n\n    if (shouldPreserve) {\n      internalColor.value = setChannelValue(nativeColor, channel.value, currentChannelVal)\n    }\n    else {\n      internalColor.value = nativeColor\n    }\n  }\n})\n\nconst color = computed({\n  get: () => internalColor.value,\n  set: (newColor: Color) => {\n    internalColor.value = newColor\n    const hexString = colorToString(newColor, 'hex')\n    modelValue.value = hexString\n    emits('update:color', newColor)\n  },\n})\n\n// Get channel range\nconst channelRange = computed(() => getChannelRange(channel.value))\nconst min = computed(() => channelRange.value.min)\nconst max = computed(() => channelRange.value.max)\nconst step = computed(() => stepProp.value ?? channelRange.value.step)\n\n// Current channel value\nconst channelValue = computed(() => getChannelValue(color.value, channel.value))\n\n// Convert channel value to array format for SliderRoot\nconst sliderValue = computed({\n  get: () => [channelValue.value],\n  set: (newValue: number[]) => {\n    const clamped = Math.max(min.value, Math.min(max.value, newValue[0]))\n    const newColor = setChannelValue(color.value, channel.value, clamped)\n    color.value = newColor\n    emits('change', colorToString(newColor, 'hex'))\n  },\n})\n\nfunction handleValueCommit(values: number[]) {\n  emits('changeEnd', colorToString(color.value, 'hex'))\n}\n\nprovideColorSliderRootContext({\n  color: computed(() => color.value) as Ref<Color>,\n  channelValue,\n  channel,\n  colorSpace,\n  orientation,\n  disabled,\n  inverted,\n  min,\n  max,\n  step,\n})\n</script>\n\n<template>\n  <SliderRoot\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    v-model=\"sliderValue\"\n    :orientation=\"orientation\"\n    :dir=\"dir\"\n    :disabled=\"disabled\"\n    :inverted=\"inverted\"\n    :min=\"min\"\n    :max=\"max\"\n    :step=\"step\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    @value-commit=\"handleValueCommit\"\n  >\n    <slot />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      type=\"text\"\n      :value=\"colorToString(color, 'hex')\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n    />\n  </SliderRoot>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Color, ColorChannel, ColorChannel as ColorChannelType, ColorSpace } from '@/shared/color'\nimport type { DataOrientation, Direction, FormFieldProps } from '@/shared/types'\nimport { createContext, useDirection, useFormControl, useForwardExpose } from '@/shared'\n\nexport interface ColorSliderRootProps extends PrimitiveProps, FormFieldProps {\n  /** The color value (controlled). Can be a hex string or Color object. */\n  modelValue?: string | Color\n  /** The default color value (uncontrolled). */\n  defaultValue?: string | Color\n  /** The color space to operate in. */\n  colorSpace?: ColorSpace\n  /** The color channel that this slider manipulates. */\n  channel: ColorChannel\n  /** The orientation of the slider. */\n  orientation?: DataOrientation\n  /** The reading direction of the slider. */\n  dir?: Direction\n  /** Whether the slider is visually inverted. */\n  inverted?: boolean\n  /** When `true`, prevents the user from interacting with the slider. */\n  disabled?: boolean\n  /** Custom step value for increment/decrement. Defaults to the channel's natural step. */\n  step?: number\n}\n\nexport type ColorSliderRootEmits = {\n  'update:modelValue': [value: string | Color]\n  'update:color': [value: Color]\n  'change': [value: string]\n  'changeEnd': [value: string]\n}\n\nexport interface ColorSliderRootContext {\n  color: Ref<Color>\n  channelValue: ComputedRef<number>\n  channel: Ref<ColorChannel>\n  colorSpace: Ref<ColorSpace>\n  orientation: Ref<DataOrientation>\n  disabled: Ref<boolean>\n  inverted: Ref<boolean>\n  min: ComputedRef<number>\n  max: ComputedRef<number>\n  step: ComputedRef<number>\n}\n\nexport const [injectColorSliderRootContext, provideColorSliderRootContext]\n  = createContext<ColorSliderRootContext>('ColorSliderRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRefs, watch } from 'vue'\nimport { colorToString, convertToHsb, convertToHsl, convertToRgb, getChannelRange, getChannelValue, normalizeColor, setChannelValue } from '@/shared/color'\nimport { SliderRoot } from '@/Slider'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ColorSliderRootProps>(), {\n  colorSpace: 'hsl',\n  orientation: 'horizontal',\n  disabled: false,\n  inverted: false,\n  defaultValue: '#000000',\n  as: 'span',\n})\n\nconst emits = defineEmits<ColorSliderRootEmits>()\n\nconst { orientation, disabled, inverted, dir: propDir, channel, colorSpace, step: stepProp } = toRefs(props)\nconst dir = useDirection(propDir)\nconst { forwardRef, currentElement } = useForwardExpose()\nconst isFormControl = useFormControl(currentElement)\n\n// Normalize the model value to a Color object\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n})\n\n// Convert a color to the native color space for the given channel.\n// This ensures setChannelValue/getChannelValue operate without cross-space round-trips.\nfunction toNativeSpace(color: Color, ch: ColorChannelType, space: ColorSpace): Color {\n  switch (ch) {\n    case 'hue':\n    case 'lightness':\n      return convertToHsl(color)\n    case 'saturation':\n      return space === 'hsb' ? convertToHsb(color) : convertToHsl(color)\n    case 'brightness':\n      return convertToHsb(color)\n    case 'red':\n    case 'green':\n    case 'blue':\n      return convertToRgb(color)\n    case 'alpha':\n      return color\n    default:\n      return color\n  }\n}\n\n// Internal color ref that preserves color space precision.\n// Convert to the channel's native space to avoid cross-space round-trips during drag.\nconst internalColor = ref<Color>(toNativeSpace(normalizeColor(modelValue.value ?? props.defaultValue ?? '#000000'), channel.value, colorSpace.value))\n\n// Check if a color is achromatic (hue information is lost in hex round-trips)\nfunction isAchromatic(color: Color): boolean {\n  const hsl = convertToHsl(color)\n  return hsl.s === 0 || hsl.l === 0 || hsl.l >= 100\n}\n\n// Sync internal color from external modelValue changes (e.g. parent updates)\nwatch(() => modelValue.value, (newVal) => {\n  if (newVal == null)\n    return\n  const parsed = normalizeColor(newVal)\n  const currentHex = colorToString(internalColor.value, 'hex')\n  const newHex = colorToString(parsed, 'hex')\n  // Only update if the external value actually changed (avoid overwriting\n  // precision during our own drag updates)\n  if (currentHex !== newHex) {\n    const nativeColor = toNativeSpace(parsed, channel.value, colorSpace.value)\n    const currentChannelVal = getChannelValue(internalColor.value, channel.value)\n    const newChannelVal = getChannelValue(nativeColor, channel.value)\n\n    // Preserve this slider's channel value when:\n    // 1. Color is achromatic (hue completely lost in hex round-trip)\n    // 2. Channel value diff is within 2% of range (8-bit RGB quantization drift)\n    // We still update the rest of the color so the track gradient stays correct.\n    const range = channelRange.value.max - channelRange.value.min\n    const shouldPreserve = (channel.value === 'hue' && isAchromatic(parsed))\n      || Math.abs(currentChannelVal - newChannelVal) < range * 0.02\n\n    if (shouldPreserve) {\n      internalColor.value = setChannelValue(nativeColor, channel.value, currentChannelVal)\n    }\n    else {\n      internalColor.value = nativeColor\n    }\n  }\n})\n\nconst color = computed({\n  get: () => internalColor.value,\n  set: (newColor: Color) => {\n    internalColor.value = newColor\n    const hexString = colorToString(newColor, 'hex')\n    modelValue.value = hexString\n    emits('update:color', newColor)\n  },\n})\n\n// Get channel range\nconst channelRange = computed(() => getChannelRange(channel.value))\nconst min = computed(() => channelRange.value.min)\nconst max = computed(() => channelRange.value.max)\nconst step = computed(() => stepProp.value ?? channelRange.value.step)\n\n// Current channel value\nconst channelValue = computed(() => getChannelValue(color.value, channel.value))\n\n// Convert channel value to array format for SliderRoot\nconst sliderValue = computed({\n  get: () => [channelValue.value],\n  set: (newValue: number[]) => {\n    const clamped = Math.max(min.value, Math.min(max.value, newValue[0]))\n    const newColor = setChannelValue(color.value, channel.value, clamped)\n    color.value = newColor\n    emits('change', colorToString(newColor, 'hex'))\n  },\n})\n\nfunction handleValueCommit(values: number[]) {\n  emits('changeEnd', colorToString(color.value, 'hex'))\n}\n\nprovideColorSliderRootContext({\n  color: computed(() => color.value) as Ref<Color>,\n  channelValue,\n  channel,\n  colorSpace,\n  orientation,\n  disabled,\n  inverted,\n  min,\n  max,\n  step,\n})\n</script>\n\n<template>\n  <SliderRoot\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    v-model=\"sliderValue\"\n    :orientation=\"orientation\"\n    :dir=\"dir\"\n    :disabled=\"disabled\"\n    :inverted=\"inverted\"\n    :min=\"min\"\n    :max=\"max\"\n    :step=\"step\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    @value-commit=\"handleValueCommit\"\n  >\n    <slot />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      type=\"text\"\n      :value=\"colorToString(color, 'hex')\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n    />\n  </SliderRoot>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ColorSliderThumbProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { getChannelName } from '@/shared/color'\nimport { SliderThumb } from '@/Slider'\nimport { injectColorSliderRootContext } from './ColorSliderRoot.vue'\n\nconst props = withDefaults(defineProps<ColorSliderThumbProps>(), {\n  as: 'span',\n})\n\ndefineSlots<{\n  default?: (props: {\n    /** The display name of the current channel */\n    channelName: string\n    /** The current numeric value of the channel */\n    channelValue: number\n  }) => any\n}>()\n\nconst rootContext = injectColorSliderRootContext()\n\nconst ariaLabel = computed(() => {\n  return getChannelName(rootContext.channel.value)\n})\n\nconst ariaValueText = computed(() => {\n  const value = rootContext.channelValue.value\n  const channel = rootContext.channel.value\n  if (channel === 'alpha') {\n    return `${Math.round(value)}%`\n  }\n  return String(Math.round(value))\n})\n</script>\n\n<template>\n  <SliderThumb\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"ariaLabel\"\n    :aria-valuetext=\"ariaValueText\"\n  >\n    <slot\n      :channel-name=\"ariaLabel\"\n      :channel-value=\"rootContext.channelValue.value\"\n    />\n  </SliderThumb>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ColorSliderThumbProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { getChannelName } from '@/shared/color'\nimport { SliderThumb } from '@/Slider'\nimport { injectColorSliderRootContext } from './ColorSliderRoot.vue'\n\nconst props = withDefaults(defineProps<ColorSliderThumbProps>(), {\n  as: 'span',\n})\n\ndefineSlots<{\n  default?: (props: {\n    /** The display name of the current channel */\n    channelName: string\n    /** The current numeric value of the channel */\n    channelValue: number\n  }) => any\n}>()\n\nconst rootContext = injectColorSliderRootContext()\n\nconst ariaLabel = computed(() => {\n  return getChannelName(rootContext.channel.value)\n})\n\nconst ariaValueText = computed(() => {\n  const value = rootContext.channelValue.value\n  const channel = rootContext.channel.value\n  if (channel === 'alpha') {\n    return `${Math.round(value)}%`\n  }\n  return String(Math.round(value))\n})\n</script>\n\n<template>\n  <SliderThumb\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"ariaLabel\"\n    :aria-valuetext=\"ariaValueText\"\n  >\n    <slot\n      :channel-name=\"ariaLabel\"\n      :channel-value=\"rootContext.channelValue.value\"\n    />\n  </SliderThumb>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ColorSliderTrackProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { getSliderBackgroundStyle } from '@/shared/color'\nimport { SliderTrack } from '@/Slider'\nimport { injectColorSliderRootContext } from './ColorSliderRoot.vue'\n\nconst props = withDefaults(defineProps<ColorSliderTrackProps>(), {\n  as: 'span',\n})\n\nconst rootContext = injectColorSliderRootContext()\n\nconst backgroundStyle = computed(() => {\n  return getSliderBackgroundStyle(\n    rootContext.color.value,\n    rootContext.channel.value,\n    rootContext.colorSpace.value,\n  )\n})\n</script>\n\n<template>\n  <SliderTrack\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :style=\"backgroundStyle\"\n  >\n    <slot />\n  </SliderTrack>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ColorSliderTrackProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { getSliderBackgroundStyle } from '@/shared/color'\nimport { SliderTrack } from '@/Slider'\nimport { injectColorSliderRootContext } from './ColorSliderRoot.vue'\n\nconst props = withDefaults(defineProps<ColorSliderTrackProps>(), {\n  as: 'span',\n})\n\nconst rootContext = injectColorSliderRootContext()\n\nconst backgroundStyle = computed(() => {\n  return getSliderBackgroundStyle(\n    rootContext.color.value,\n    rootContext.channel.value,\n    rootContext.colorSpace.value,\n  )\n})\n</script>\n\n<template>\n  <SliderTrack\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :style=\"backgroundStyle\"\n  >\n    <slot />\n  </SliderTrack>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Color } from '@/shared/color'\n\nexport interface ColorSwatchProps extends PrimitiveProps {\n  /**\n   * The color to display in the swatch as a hex string or Color object.\n   * Example: `#16a372`, `#ff5733`, or `{ space: 'hsl', h: 120, s: 100, l: 50, alpha: 1 }`.\n   */\n  color?: string | Color\n  /**\n   * Optional accessible label for the color. If omitted, the color name will be derived from the color value.\n   */\n  label?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { colorToString, getColorContrast, getColorName, normalizeColor } from '@/shared/color'\n\nconst props = withDefaults(defineProps<ColorSwatchProps>(), { as: 'div', color: '' })\n\nconst colorString = computed(() => {\n  if (!props.color)\n    return ''\n  if (typeof props.color === 'string') {\n    return props.color\n  }\n  return colorToString(props.color, 'hex')\n})\n\nconst colorObj = computed(() => {\n  if (!props.color)\n    return null\n  try {\n    return normalizeColor(props.color)\n  }\n  catch {\n    return null\n  }\n})\n\nconst alpha = computed(() => colorObj.value?.alpha ?? 0)\nconst isNoColor = computed(() => !props.color || alpha.value <= 0)\n\nconst label = computed(() => {\n  if (props.label)\n    return props.label\n\n  // Match React Aria: transparent colors get \"transparent\" label\n  if (!colorObj.value || colorObj.value.alpha === 0)\n    return 'transparent'\n\n  try {\n    return getColorName(colorString.value)\n  }\n  catch {\n    return colorString.value || 'transparent'\n  }\n})\n\nconst colorContrast = computed(() => {\n  try {\n    return getColorContrast(colorString.value)\n  }\n  catch {\n    if (import.meta.env.DEV) {\n      console.warn(`WARNING: Unable to resolve contrast color for \"${colorString.value}\".\n           Please check that the color provided is a valid hex color.`)\n    }\n    return undefined\n  }\n})\n</script>\n\n<template>\n  <Primitive\n    role=\"img\"\n    :aria-label=\"label\"\n    aria-roledescription=\"color swatch\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :data-color-contrast=\"colorContrast\"\n    :data-no-color=\"isNoColor ? '' : undefined\"\n    :style=\"{\n      '--reka-color-swatch-color': colorString,\n      '--reka-color-swatch-alpha': String(alpha),\n    }\"\n  >\n    <slot\n      :color=\"colorString\"\n      :alpha=\"alpha\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Color } from '@/shared/color'\n\nexport interface ColorSwatchProps extends PrimitiveProps {\n  /**\n   * The color to display in the swatch as a hex string or Color object.\n   * Example: `#16a372`, `#ff5733`, or `{ space: 'hsl', h: 120, s: 100, l: 50, alpha: 1 }`.\n   */\n  color?: string | Color\n  /**\n   * Optional accessible label for the color. If omitted, the color name will be derived from the color value.\n   */\n  label?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { colorToString, getColorContrast, getColorName, normalizeColor } from '@/shared/color'\n\nconst props = withDefaults(defineProps<ColorSwatchProps>(), { as: 'div', color: '' })\n\nconst colorString = computed(() => {\n  if (!props.color)\n    return ''\n  if (typeof props.color === 'string') {\n    return props.color\n  }\n  return colorToString(props.color, 'hex')\n})\n\nconst colorObj = computed(() => {\n  if (!props.color)\n    return null\n  try {\n    return normalizeColor(props.color)\n  }\n  catch {\n    return null\n  }\n})\n\nconst alpha = computed(() => colorObj.value?.alpha ?? 0)\nconst isNoColor = computed(() => !props.color || alpha.value <= 0)\n\nconst label = computed(() => {\n  if (props.label)\n    return props.label\n\n  // Match React Aria: transparent colors get \"transparent\" label\n  if (!colorObj.value || colorObj.value.alpha === 0)\n    return 'transparent'\n\n  try {\n    return getColorName(colorString.value)\n  }\n  catch {\n    return colorString.value || 'transparent'\n  }\n})\n\nconst colorContrast = computed(() => {\n  try {\n    return getColorContrast(colorString.value)\n  }\n  catch {\n    if (import.meta.env.DEV) {\n      console.warn(`WARNING: Unable to resolve contrast color for \"${colorString.value}\".\n           Please check that the color provided is a valid hex color.`)\n    }\n    return undefined\n  }\n})\n</script>\n\n<template>\n  <Primitive\n    role=\"img\"\n    :aria-label=\"label\"\n    aria-roledescription=\"color swatch\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :data-color-contrast=\"colorContrast\"\n    :data-no-color=\"isNoColor ? '' : undefined\"\n    :style=\"{\n      '--reka-color-swatch-color': colorString,\n      '--reka-color-swatch-alpha': String(alpha),\n    }\"\n  >\n    <slot\n      :color=\"colorString\"\n      :alpha=\"alpha\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { ListboxItemEmits, ListboxItemProps } from '@/Listbox'\nimport { createContext, useForwardPropsEmits } from '@/shared'\n\nexport interface ColorSwatchPickerItemProps extends ListboxItemProps {\n/**\n * The color to display in the swatch as a hex string.\n * Example: `#16a372` or `#ff5733`.\n */\n  value: string\n}\n\nexport type ColorSwatchPickerItemEmits = ListboxItemEmits\n\nexport interface ColorSwatchPickerItemContext {\n  color: Ref<string>\n}\n\nexport const [injectColorSwatchPickerItemContext, provideColorSwatchPickerItemContext]\n  = createContext<ColorSwatchPickerItemContext>('ColorSwatchPickerItem', 'ColorSwatchPickerItemContext')\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, toRefs } from 'vue'\nimport { ListboxItem } from '@/Listbox'\nimport { getColorName } from '@/shared/color'\n\nconst props = defineProps<ColorSwatchPickerItemProps>()\n\nconst emits = defineEmits<ColorSwatchPickerItemEmits>()\n\nconst { value } = toRefs(props)\n\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst colorLabel = computed(() => {\n  try {\n    return getColorName(value.value)\n  }\n  catch {\n    return value.value\n  }\n})\n\nprovideColorSwatchPickerItemContext({\n  color: value,\n})\n</script>\n\n<template>\n  <ListboxItem\n    v-bind=\"forwarded\"\n    :aria-label=\"colorLabel\"\n    :data-color=\"value\"\n    :style=\"{ '--reka-color-swatch-picker-item-color': value }\"\n  >\n    <slot />\n  </ListboxItem>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { ListboxItemEmits, ListboxItemProps } from '@/Listbox'\nimport { createContext, useForwardPropsEmits } from '@/shared'\n\nexport interface ColorSwatchPickerItemProps extends ListboxItemProps {\n/**\n * The color to display in the swatch as a hex string.\n * Example: `#16a372` or `#ff5733`.\n */\n  value: string\n}\n\nexport type ColorSwatchPickerItemEmits = ListboxItemEmits\n\nexport interface ColorSwatchPickerItemContext {\n  color: Ref<string>\n}\n\nexport const [injectColorSwatchPickerItemContext, provideColorSwatchPickerItemContext]\n  = createContext<ColorSwatchPickerItemContext>('ColorSwatchPickerItem', 'ColorSwatchPickerItemContext')\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, toRefs } from 'vue'\nimport { ListboxItem } from '@/Listbox'\nimport { getColorName } from '@/shared/color'\n\nconst props = defineProps<ColorSwatchPickerItemProps>()\n\nconst emits = defineEmits<ColorSwatchPickerItemEmits>()\n\nconst { value } = toRefs(props)\n\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst colorLabel = computed(() => {\n  try {\n    return getColorName(value.value)\n  }\n  catch {\n    return value.value\n  }\n})\n\nprovideColorSwatchPickerItemContext({\n  color: value,\n})\n</script>\n\n<template>\n  <ListboxItem\n    v-bind=\"forwarded\"\n    :aria-label=\"colorLabel\"\n    :data-color=\"value\"\n    :style=\"{ '--reka-color-swatch-picker-item-color': value }\"\n  >\n    <slot />\n  </ListboxItem>\n</template>\n","<script lang=\"ts\">\nimport type { ListboxItemIndicatorProps } from '@/Listbox'\n\nexport interface ColorSwatchPickerItemIndicatorProps extends ListboxItemIndicatorProps { }\n</script>\n\n<script setup lang=\"ts\">\nimport { ListboxItemIndicator } from '@/Listbox'\n\nconst props = defineProps<ColorSwatchPickerItemIndicatorProps>()\n</script>\n\n<template>\n  <ListboxItemIndicator v-bind=\"props\">\n    <slot />\n  </ListboxItemIndicator>\n</template>\n","<script lang=\"ts\">\nimport type { ListboxItemIndicatorProps } from '@/Listbox'\n\nexport interface ColorSwatchPickerItemIndicatorProps extends ListboxItemIndicatorProps { }\n</script>\n\n<script setup lang=\"ts\">\nimport { ListboxItemIndicator } from '@/Listbox'\n\nconst props = defineProps<ColorSwatchPickerItemIndicatorProps>()\n</script>\n\n<template>\n  <ListboxItemIndicator v-bind=\"props\">\n    <slot />\n  </ListboxItemIndicator>\n</template>\n","<script lang=\"ts\">\nimport type { ColorSwatchProps } from '@/ColorSwatch/ColorSwatch.vue'\n\nexport interface ColorSwatchPickerItemSwatchProps extends Omit<ColorSwatchProps, 'color'> { }\n</script>\n\n<script setup lang=\"ts\">\nimport { ColorSwatch } from '@/ColorSwatch'\nimport { injectColorSwatchPickerItemContext } from './ColorSwatchPickerItem.vue'\n\nconst props = defineProps<ColorSwatchPickerItemSwatchProps>()\n\nconst colorSwatchPickerItemContext = injectColorSwatchPickerItemContext()\n</script>\n\n<template>\n  <ColorSwatch\n    v-bind=\"props\"\n    :color=\"colorSwatchPickerItemContext.color.value\"\n  />\n</template>\n","<script lang=\"ts\">\nimport type { ColorSwatchProps } from '@/ColorSwatch/ColorSwatch.vue'\n\nexport interface ColorSwatchPickerItemSwatchProps extends Omit<ColorSwatchProps, 'color'> { }\n</script>\n\n<script setup lang=\"ts\">\nimport { ColorSwatch } from '@/ColorSwatch'\nimport { injectColorSwatchPickerItemContext } from './ColorSwatchPickerItem.vue'\n\nconst props = defineProps<ColorSwatchPickerItemSwatchProps>()\n\nconst colorSwatchPickerItemContext = injectColorSwatchPickerItemContext()\n</script>\n\n<template>\n  <ColorSwatch\n    v-bind=\"props\"\n    :color=\"colorSwatchPickerItemContext.color.value\"\n  />\n</template>\n","<script lang=\"ts\">\nimport type { ListboxRootEmits, ListboxRootProps } from '@/Listbox'\nimport { useVModel } from '@vueuse/core'\nimport { useForwardPropsEmits } from '@/shared'\n\nexport interface ColorSwatchPickerRootProps extends Omit<ListboxRootProps, 'by'> {\n  defaultValue?: string | string[]\n  modelValue?: string | string[]\n}\n\nexport type ColorSwatchPickerRootEmits = ListboxRootEmits\n</script>\n\n<script setup lang=\"ts\">\nimport { ListboxContent, ListboxRoot } from '@/Listbox'\n\nconst props = withDefaults(defineProps<ColorSwatchPickerRootProps>(), {\n  as: 'div',\n  defaultValue: undefined,\n  dir: 'ltr',\n  disabled: false,\n  loop: false,\n  orientation: 'horizontal',\n})\n\nconst emits = defineEmits<ColorSwatchPickerRootEmits>()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? (props.multiple ? [] : ''),\n  // Cast required for VueUse's passive option type; enables passive sync when modelValue is undefined\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst forwarded = useForwardPropsEmits(props, emits)\n</script>\n\n<template>\n  <ListboxRoot\n    v-bind=\"forwarded\"\n    v-model=\"modelValue\"\n    as-child\n  >\n    <ListboxContent\n      :as-child=\"asChild\"\n      :as=\"as\"\n    >\n      <slot :model-value=\"modelValue\" />\n    </ListboxContent>\n  </ListboxRoot>\n</template>\n","<script lang=\"ts\">\nimport type { ListboxRootEmits, ListboxRootProps } from '@/Listbox'\nimport { useVModel } from '@vueuse/core'\nimport { useForwardPropsEmits } from '@/shared'\n\nexport interface ColorSwatchPickerRootProps extends Omit<ListboxRootProps, 'by'> {\n  defaultValue?: string | string[]\n  modelValue?: string | string[]\n}\n\nexport type ColorSwatchPickerRootEmits = ListboxRootEmits\n</script>\n\n<script setup lang=\"ts\">\nimport { ListboxContent, ListboxRoot } from '@/Listbox'\n\nconst props = withDefaults(defineProps<ColorSwatchPickerRootProps>(), {\n  as: 'div',\n  defaultValue: undefined,\n  dir: 'ltr',\n  disabled: false,\n  loop: false,\n  orientation: 'horizontal',\n})\n\nconst emits = defineEmits<ColorSwatchPickerRootEmits>()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? (props.multiple ? [] : ''),\n  // Cast required for VueUse's passive option type; enables passive sync when modelValue is undefined\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst forwarded = useForwardPropsEmits(props, emits)\n</script>\n\n<template>\n  <ListboxRoot\n    v-bind=\"forwarded\"\n    v-model=\"modelValue\"\n    as-child\n  >\n    <ListboxContent\n      :as-child=\"asChild\"\n      :as=\"as\"\n    >\n      <slot :model-value=\"modelValue\" />\n    </ListboxContent>\n  </ListboxRoot>\n</template>\n","<script setup lang=\"ts\">\nimport type { PopperAnchorProps } from '@/Popper'\nimport { PopperAnchor } from '@/Popper'\n\ninterface MenuAnchorProps extends PopperAnchorProps {}\n\nconst props = defineProps<MenuAnchorProps>()\n</script>\n\n<template>\n  <PopperAnchor v-bind=\"props\">\n    <slot />\n  </PopperAnchor>\n</template>\n","<script setup lang=\"ts\">\nimport type { PopperAnchorProps } from '@/Popper'\nimport { PopperAnchor } from '@/Popper'\n\ninterface MenuAnchorProps extends PopperAnchorProps {}\n\nconst props = defineProps<MenuAnchorProps>()\n</script>\n\n<template>\n  <PopperAnchor v-bind=\"props\">\n    <slot />\n  </PopperAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { PopperArrowProps } from '@/Popper'\n\nexport interface MenuArrowProps extends PopperArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperArrow } from '@/Popper'\n\nconst props = defineProps<MenuArrowProps>()\n</script>\n\n<template>\n  <PopperArrow v-bind=\"props\">\n    <slot />\n  </PopperArrow>\n</template>\n","<script lang=\"ts\">\nimport type { PopperArrowProps } from '@/Popper'\n\nexport interface MenuArrowProps extends PopperArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperArrow } from '@/Popper'\n\nconst props = defineProps<MenuArrowProps>()\n</script>\n\n<template>\n  <PopperArrow v-bind=\"props\">\n    <slot />\n  </PopperArrow>\n</template>\n","import { createSharedComposable, useEventListener } from '@vueuse/core'\nimport { onMounted, ref } from 'vue'\n\nfunction useIsUsingKeyboardImpl() {\n  const isUsingKeyboard = ref(false)\n\n  onMounted(() => {\n    // Capture phase ensures we set the boolean before any side effects execute\n    // in response to the key or pointer event as they might depend on this value.\n    useEventListener('keydown', () => {\n      isUsingKeyboard.value = true\n    }, { capture: true, passive: true })\n\n    useEventListener(['pointerdown', 'pointermove'], () => {\n      isUsingKeyboard.value = false\n    }, { capture: true, passive: true })\n  })\n\n  return isUsingKeyboard\n}\n\nexport const useIsUsingKeyboard = createSharedComposable(useIsUsingKeyboardImpl)\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Direction } from './utils'\nimport { createContext, useDirection } from '@/shared'\nimport { useIsUsingKeyboard } from '@/shared/useIsUsingKeyboard'\n\nexport interface MenuContext {\n  open: Ref<boolean>\n  onOpenChange: (open: boolean) => void\n  content: Ref<HTMLElement | undefined>\n  onContentChange: (content: HTMLElement | undefined) => void\n}\n\nexport interface MenuRootContext {\n  onClose: () => void\n  dir: Ref<Direction>\n  isUsingKeyboardRef: Ref<boolean>\n  modal: Ref<boolean>\n}\n\nexport interface MenuProps {\n  /** The controlled open state of the menu. Can be used as `v-model:open`. */\n  open?: boolean\n  /**\n   * The reading direction of the combobox when applicable.\n   *\n   * If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode.\n   */\n  dir?: Direction\n  /**\n   * The modality of the dropdown menu.\n   *\n   * When set to `true`, interaction with outside elements will be disabled and only menu content will be visible to screen readers.\n   */\n  modal?: boolean\n}\n\nexport type MenuEmits = {\n  'update:open': [payload: boolean]\n}\n\nexport const [injectMenuContext, provideMenuContext]\n  = createContext<MenuContext>(['MenuRoot', 'MenuSub'], 'MenuContext')\n\nexport const [injectMenuRootContext, provideMenuRootContext]\n  = createContext<MenuRootContext>('MenuRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport {\n  ref,\n  toRefs,\n} from 'vue'\nimport { PopperRoot } from '@/Popper'\n\nconst props = withDefaults(defineProps<MenuProps>(), {\n  open: false,\n  modal: true,\n})\nconst emits = defineEmits<MenuEmits>()\nconst { modal, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\n\nconst open = useVModel(props, 'open', emits)\n\nconst content = ref<HTMLElement>()\nconst isUsingKeyboardRef = useIsUsingKeyboard()\n\nprovideMenuContext({\n  open,\n  onOpenChange: (value) => {\n    open.value = value\n  },\n  content,\n  onContentChange: (element) => {\n    content.value = element\n  },\n})\n\nprovideMenuRootContext({\n  onClose: () => {\n    open.value = false\n  },\n  isUsingKeyboardRef,\n  dir,\n  modal,\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <slot />\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Direction } from './utils'\nimport { createContext, useDirection } from '@/shared'\nimport { useIsUsingKeyboard } from '@/shared/useIsUsingKeyboard'\n\nexport interface MenuContext {\n  open: Ref<boolean>\n  onOpenChange: (open: boolean) => void\n  content: Ref<HTMLElement | undefined>\n  onContentChange: (content: HTMLElement | undefined) => void\n}\n\nexport interface MenuRootContext {\n  onClose: () => void\n  dir: Ref<Direction>\n  isUsingKeyboardRef: Ref<boolean>\n  modal: Ref<boolean>\n}\n\nexport interface MenuProps {\n  /** The controlled open state of the menu. Can be used as `v-model:open`. */\n  open?: boolean\n  /**\n   * The reading direction of the combobox when applicable.\n   *\n   * If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode.\n   */\n  dir?: Direction\n  /**\n   * The modality of the dropdown menu.\n   *\n   * When set to `true`, interaction with outside elements will be disabled and only menu content will be visible to screen readers.\n   */\n  modal?: boolean\n}\n\nexport type MenuEmits = {\n  'update:open': [payload: boolean]\n}\n\nexport const [injectMenuContext, provideMenuContext]\n  = createContext<MenuContext>(['MenuRoot', 'MenuSub'], 'MenuContext')\n\nexport const [injectMenuRootContext, provideMenuRootContext]\n  = createContext<MenuRootContext>('MenuRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport {\n  ref,\n  toRefs,\n} from 'vue'\nimport { PopperRoot } from '@/Popper'\n\nconst props = withDefaults(defineProps<MenuProps>(), {\n  open: false,\n  modal: true,\n})\nconst emits = defineEmits<MenuEmits>()\nconst { modal, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\n\nconst open = useVModel(props, 'open', emits)\n\nconst content = ref<HTMLElement>()\nconst isUsingKeyboardRef = useIsUsingKeyboard()\n\nprovideMenuContext({\n  open,\n  onOpenChange: (value) => {\n    open.value = value\n  },\n  content,\n  onContentChange: (element) => {\n    content.value = element\n  },\n})\n\nprovideMenuRootContext({\n  onClose: () => {\n    open.value = false\n  },\n  isUsingKeyboardRef,\n  dir,\n  modal,\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <slot />\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type {\n  GraceIntent,\n  Side,\n} from './utils'\nimport type {\n  DismissableLayerEmits,\n  DismissableLayerProps,\n} from '@/DismissableLayer'\nimport type { FocusScopeProps } from '@/FocusScope'\nimport type { PopperContentProps } from '@/Popper'\nimport type { RovingFocusGroupEmits } from '@/RovingFocus'\n\nimport {\n  createContext,\n  getActiveElement,\n  useArrowNavigation,\n  useFocusGuards,\n  useForwardExpose,\n  useTypeahead,\n} from '@/shared'\nimport { useBodyScrollLock } from '@/shared/useBodyScrollLock'\n\nexport interface MenuContentContext {\n  onItemEnter: (event: PointerEvent) => boolean\n  onItemLeave: (event: PointerEvent) => boolean\n  onTriggerLeave: (event: PointerEvent) => boolean\n  searchRef: Ref<string>\n  highlightedElement: Ref<HTMLElement | undefined>\n  onKeydownNavigation: (event: KeyboardEvent) => void\n  onKeydownEnter: (event: KeyboardEvent) => void\n  filterElement: Ref<HTMLElement | undefined>\n  onFilterElementChange: (el: HTMLElement | undefined) => void\n  activeSubmenuContext: Ref<{ onOpenChange: (open: boolean) => void, trigger: Ref<HTMLElement | undefined> } | undefined>\n  pointerGraceTimerRef: Ref<number>\n  onPointerGraceIntentChange: (intent: GraceIntent | null) => void\n}\n\nexport const [injectMenuContentContext, provideMenuContentContext]\n  = createContext<MenuContentContext>('MenuContent')\n\nexport interface MenuContentImplPrivateProps {\n  /**\n   * When `true`, hover/focus/click interactions will be disabled on elements outside\n   * the `DismissableLayer`. Users will need to click twice on outside elements to\n   * interact with them: once to close the `DismissableLayer`, and again to trigger the element.\n   */\n  disableOutsidePointerEvents?: DismissableLayerProps['disableOutsidePointerEvents']\n  /**\n   * Whether scrolling outside the `MenuContent` should be prevented\n   * @defaultValue false\n   */\n  disableOutsideScroll?: boolean\n\n  /**\n   * Whether focus should be trapped within the `MenuContent`\n   * @defaultValue also\n   */\n  trapFocus?: FocusScopeProps['trapped']\n}\n\nexport type MenuContentImplEmits = DismissableLayerEmits & Omit<RovingFocusGroupEmits, 'update:currentTabStopId'> & {\n  openAutoFocus: [event: Event]\n  /**\n   * Event handler called when auto-focusing on close.\n   * Can be prevented.\n   */\n  closeAutoFocus: [event: Event]\n}\n\ntype MenuContentImplPrivateEmits = MenuContentImplEmits & {\n  /**\n   * Handler called when the `DismissableLayer` should be dismissed\n   */\n  dismiss: []\n}\n\nexport interface MenuContentImplProps\n  extends MenuContentImplPrivateProps,\n  Omit<PopperContentProps, 'dir'> {\n  /**\n   * When `true`, keyboard navigation will loop from last item to first, and vice versa.\n   * @defaultValue false\n   */\n  loop?: boolean\n}\n\nexport interface MenuRootContentTypeProps\n  extends Omit<MenuContentImplProps, 'disableOutsidePointerEvents' | 'disableOutsideScroll' | 'trapFocus'> {}\n</script>\n\n<script setup lang=\"ts\">\nimport {\n  onUnmounted,\n  ref,\n  toRefs,\n  watch,\n} from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { FocusScope } from '@/FocusScope'\nimport {\n  PopperContent,\n  PopperContentPropsDefaultValue,\n} from '@/Popper'\nimport { RovingFocusGroup } from '@/RovingFocus'\nimport { injectMenuContext, injectMenuRootContext } from './MenuRoot.vue'\nimport {\n  FIRST_LAST_KEYS,\n  focusFirst,\n  getOpenState,\n  isMouseEvent,\n  isPointerInGraceArea,\n  LAST_KEYS,\n} from './utils'\n\nconst props = withDefaults(defineProps<MenuContentImplProps>(), {\n  ...PopperContentPropsDefaultValue,\n})\nconst emits = defineEmits<MenuContentImplPrivateEmits>()\nconst menuContext = injectMenuContext()\nconst rootContext = injectMenuRootContext()\n\nconst { trapFocus, disableOutsidePointerEvents, loop } = toRefs(props)\n\nuseFocusGuards()\nuseBodyScrollLock(disableOutsidePointerEvents.value)\n\nconst searchRef = ref('')\nconst timerRef = ref(0)\nconst pointerGraceTimerRef = ref(0)\nconst pointerGraceIntentRef = ref<GraceIntent | null>(null)\nconst pointerDirRef = ref<Side>('right')\nconst lastPointerXRef = ref(0)\nconst currentItemId = ref<string | null>(null)\n\nconst rovingFocusGroupRef = ref<InstanceType<typeof RovingFocusGroup>>()\nconst { forwardRef, currentElement: contentElement } = useForwardExpose()\nconst { handleTypeaheadSearch } = useTypeahead()\n\nconst highlightedElement = ref<HTMLElement>()\n\nfunction onKeydownNavigation(event: KeyboardEvent) {\n  const el = useArrowNavigation(\n    event,\n    (highlightedElement.value || getActiveElement()) as HTMLElement,\n    contentElement.value,\n    {\n      loop: loop.value,\n      arrowKeyOptions: 'vertical',\n      dir: rootContext?.dir.value,\n      focus: false,\n      attributeName: '[data-reka-collection-item]:not([data-disabled])',\n    },\n  )\n  if (el) {\n    highlightedElement.value = el\n    el.scrollIntoView({ block: 'nearest' })\n  }\n}\n\nfunction onKeydownEnter() {\n  if (highlightedElement.value) {\n    highlightedElement.value.click()\n  }\n}\n\nconst filterElement = ref<HTMLElement>()\nconst activeSubmenuContext = ref<{ onOpenChange: (open: boolean) => void, trigger: Ref<HTMLElement | undefined> }>()\n\nwatch(highlightedElement, (el) => {\n  if (activeSubmenuContext.value && (el === undefined || el !== activeSubmenuContext.value.trigger.value)) {\n    activeSubmenuContext.value.onOpenChange(false)\n    activeSubmenuContext.value = undefined\n  }\n})\n\nwatch(contentElement, (el) => {\n  menuContext!.onContentChange(el)\n})\n\nonUnmounted(() => {\n  window.clearTimeout(timerRef.value)\n})\n\nfunction isPointerMovingToSubmenu(event: PointerEvent) {\n  const isMovingTowards\n    = pointerDirRef.value === pointerGraceIntentRef.value?.side\n\n  return (\n    isMovingTowards\n    && isPointerInGraceArea(event, pointerGraceIntentRef.value?.area)\n  )\n}\n\nasync function handleMountAutoFocus(event: Event) {\n  emits('openAutoFocus', event)\n  if (event.defaultPrevented)\n    return\n  // when opening, explicitly focus the content area only and leave\n  // `onEntryFocus` in  control of focusing first item\n  event.preventDefault()\n  contentElement.value?.focus({\n    preventScroll: true,\n  })\n}\n\nfunction handleKeyDown(event: KeyboardEvent) {\n  if (event.defaultPrevented)\n    return\n  // submenu key events bubble through portals. We only care about keys in this menu.\n  const target = event.target as HTMLElement\n  const isKeyDownInside\n    = target.closest('[data-reka-menu-content]') === event.currentTarget\n  const isKeyDownInTextField = ['input', 'textarea'].includes(target.tagName.toLowerCase())\n  const isModifierKey = event.ctrlKey || event.altKey || event.metaKey\n  const isCharacterKey = event.key.length === 1\n\n  const el = useArrowNavigation(\n    event,\n    getActiveElement() as HTMLElement,\n    contentElement.value,\n    {\n      loop: loop.value,\n      arrowKeyOptions: 'vertical',\n      dir: rootContext?.dir.value,\n      focus: true,\n      attributeName: '[data-reka-collection-item]:not([data-disabled])',\n    },\n  )\n  if (el)\n    return el?.focus()\n\n  // prevent \"Space\" taken account into handleTypeahead\n  if (event.code === 'Space')\n    return\n\n  const collectionItems = rovingFocusGroupRef.value?.getItems() ?? []\n\n  if (isKeyDownInside) {\n    // menus should not be navigated using tab key so we prevent it\n    if (event.key === 'Tab')\n      event.preventDefault()\n    if (!isModifierKey && isCharacterKey && !isKeyDownInTextField)\n      handleTypeaheadSearch(event.key, collectionItems)\n  }\n\n  // focus first/last item based on key pressed\n  if (event.target !== contentElement.value)\n    return\n  if (!FIRST_LAST_KEYS.includes(event.key))\n    return\n  event.preventDefault()\n  const candidateNodes = [...collectionItems.map(item => item.ref)]\n  if (LAST_KEYS.includes(event.key))\n    candidateNodes.reverse()\n  focusFirst(candidateNodes)\n}\n\nfunction handleBlur(event: FocusEvent) {\n  // clear search buffer when leaving the menu\n  // @ts-expect-error the provided currentTarget and target should be HTMLElement\n  if (!event?.currentTarget?.contains?.(event.target)) {\n    window.clearTimeout(timerRef.value)\n    searchRef.value = ''\n  }\n}\n\nfunction handlePointerMove(event: PointerEvent) {\n  if (!isMouseEvent(event))\n    return\n  const target = event.target as HTMLElement\n  const pointerXHasChanged = lastPointerXRef.value !== event.clientX\n\n  // We don't use `event.movementX` for this check because Safari will\n  // always return `0` on a pointer event.\n  if (\n    (event?.currentTarget as HTMLElement)?.contains(target)\n    && pointerXHasChanged\n  ) {\n    const newDir = event.clientX > lastPointerXRef.value ? 'right' : 'left'\n    pointerDirRef.value = newDir\n    lastPointerXRef.value = event.clientX\n  }\n}\n\nfunction handlePointerEnter(event: PointerEvent) {\n  if (!isMouseEvent(event))\n    return\n  // When hovering over a menu content (main or sub), focus its filter element if it exists\n  if (filterElement.value) {\n    filterElement.value.focus()\n  }\n}\n\nprovideMenuContentContext({\n  onItemEnter: (event) => {\n    // event.preventDefault() we can't prevent pointerMove event\n    if (isPointerMovingToSubmenu(event))\n      return true\n    else\n      return false\n  },\n  onItemLeave: (event) => {\n    if (isPointerMovingToSubmenu(event))\n      return true\n\n    const isInputFocused = ['INPUT', 'TEXTAREA'].includes(getActiveElement()?.tagName || '')\n    if (!isInputFocused)\n      contentElement.value?.focus()\n\n    currentItemId.value = null\n    return false\n  },\n  onTriggerLeave: (event) => {\n    // event.preventDefault() we can't prevent pointerLeave event\n    if (isPointerMovingToSubmenu(event))\n      return true\n    else\n      return false\n  },\n  searchRef,\n  highlightedElement,\n  onKeydownNavigation,\n  onKeydownEnter,\n  filterElement,\n  onFilterElementChange: (el) => {\n    filterElement.value = el\n  },\n  activeSubmenuContext,\n  pointerGraceTimerRef,\n  onPointerGraceIntentChange: (intent) => {\n    pointerGraceIntentRef.value = intent\n  },\n})\n</script>\n\n<template>\n  <FocusScope\n    as-child\n    :trapped=\"trapFocus\"\n    @mount-auto-focus=\"handleMountAutoFocus\"\n    @unmount-auto-focus=\"emits('closeAutoFocus', $event)\"\n  >\n    <DismissableLayer\n      as-child\n      :disable-outside-pointer-events=\"disableOutsidePointerEvents\"\n      @escape-key-down=\"emits('escapeKeyDown', $event)\"\n      @pointer-down-outside=\"emits('pointerDownOutside', $event)\"\n      @focus-outside=\"emits('focusOutside', $event)\"\n      @interact-outside=\"emits('interactOutside', $event)\"\n      @dismiss=\"emits('dismiss')\"\n    >\n      <RovingFocusGroup\n        ref=\"rovingFocusGroupRef\"\n        v-model:current-tab-stop-id=\"currentItemId\"\n        as-child\n        orientation=\"vertical\"\n        :dir=\"rootContext.dir.value\"\n        :loop=\"loop\"\n        @entry-focus=\"(event) => {\n          emits('entryFocus', event)\n          // only focus first item when using keyboard\n          if (!rootContext.isUsingKeyboardRef.value) event.preventDefault();\n        }\"\n      >\n        <PopperContent\n          :ref=\"forwardRef\"\n          role=\"menu\"\n          :as=\"as\"\n          :as-child=\"asChild\"\n          aria-orientation=\"vertical\"\n          data-reka-menu-content\n          :data-state=\"getOpenState(menuContext.open.value)\"\n          :dir=\"rootContext.dir.value\"\n          :side=\"side\"\n          :side-offset=\"sideOffset\"\n          :align=\"align\"\n          :align-offset=\"alignOffset\"\n          :avoid-collisions=\"avoidCollisions\"\n          :collision-boundary=\"collisionBoundary\"\n          :collision-padding=\"collisionPadding\"\n          :arrow-padding=\"arrowPadding\"\n          :prioritize-position=\"prioritizePosition\"\n          :position-strategy=\"positionStrategy\"\n          :update-position-strategy=\"updatePositionStrategy\"\n          :sticky=\"sticky\"\n          :hide-when-detached=\"hideWhenDetached\"\n          :reference=\"reference\"\n          @keydown=\"handleKeyDown\"\n          @blur=\"handleBlur\"\n          @pointermove=\"handlePointerMove\"\n          @pointerenter=\"handlePointerEnter\"\n        >\n          <slot />\n        </PopperContent>\n      </RovingFocusGroup>\n    </DismissableLayer>\n  </FocusScope>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type {\n  GraceIntent,\n  Side,\n} from './utils'\nimport type {\n  DismissableLayerEmits,\n  DismissableLayerProps,\n} from '@/DismissableLayer'\nimport type { FocusScopeProps } from '@/FocusScope'\nimport type { PopperContentProps } from '@/Popper'\nimport type { RovingFocusGroupEmits } from '@/RovingFocus'\n\nimport {\n  createContext,\n  getActiveElement,\n  useArrowNavigation,\n  useFocusGuards,\n  useForwardExpose,\n  useTypeahead,\n} from '@/shared'\nimport { useBodyScrollLock } from '@/shared/useBodyScrollLock'\n\nexport interface MenuContentContext {\n  onItemEnter: (event: PointerEvent) => boolean\n  onItemLeave: (event: PointerEvent) => boolean\n  onTriggerLeave: (event: PointerEvent) => boolean\n  searchRef: Ref<string>\n  highlightedElement: Ref<HTMLElement | undefined>\n  onKeydownNavigation: (event: KeyboardEvent) => void\n  onKeydownEnter: (event: KeyboardEvent) => void\n  filterElement: Ref<HTMLElement | undefined>\n  onFilterElementChange: (el: HTMLElement | undefined) => void\n  activeSubmenuContext: Ref<{ onOpenChange: (open: boolean) => void, trigger: Ref<HTMLElement | undefined> } | undefined>\n  pointerGraceTimerRef: Ref<number>\n  onPointerGraceIntentChange: (intent: GraceIntent | null) => void\n}\n\nexport const [injectMenuContentContext, provideMenuContentContext]\n  = createContext<MenuContentContext>('MenuContent')\n\nexport interface MenuContentImplPrivateProps {\n  /**\n   * When `true`, hover/focus/click interactions will be disabled on elements outside\n   * the `DismissableLayer`. Users will need to click twice on outside elements to\n   * interact with them: once to close the `DismissableLayer`, and again to trigger the element.\n   */\n  disableOutsidePointerEvents?: DismissableLayerProps['disableOutsidePointerEvents']\n  /**\n   * Whether scrolling outside the `MenuContent` should be prevented\n   * @defaultValue false\n   */\n  disableOutsideScroll?: boolean\n\n  /**\n   * Whether focus should be trapped within the `MenuContent`\n   * @defaultValue also\n   */\n  trapFocus?: FocusScopeProps['trapped']\n}\n\nexport type MenuContentImplEmits = DismissableLayerEmits & Omit<RovingFocusGroupEmits, 'update:currentTabStopId'> & {\n  openAutoFocus: [event: Event]\n  /**\n   * Event handler called when auto-focusing on close.\n   * Can be prevented.\n   */\n  closeAutoFocus: [event: Event]\n}\n\ntype MenuContentImplPrivateEmits = MenuContentImplEmits & {\n  /**\n   * Handler called when the `DismissableLayer` should be dismissed\n   */\n  dismiss: []\n}\n\nexport interface MenuContentImplProps\n  extends MenuContentImplPrivateProps,\n  Omit<PopperContentProps, 'dir'> {\n  /**\n   * When `true`, keyboard navigation will loop from last item to first, and vice versa.\n   * @defaultValue false\n   */\n  loop?: boolean\n}\n\nexport interface MenuRootContentTypeProps\n  extends Omit<MenuContentImplProps, 'disableOutsidePointerEvents' | 'disableOutsideScroll' | 'trapFocus'> {}\n</script>\n\n<script setup lang=\"ts\">\nimport {\n  onUnmounted,\n  ref,\n  toRefs,\n  watch,\n} from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { FocusScope } from '@/FocusScope'\nimport {\n  PopperContent,\n  PopperContentPropsDefaultValue,\n} from '@/Popper'\nimport { RovingFocusGroup } from '@/RovingFocus'\nimport { injectMenuContext, injectMenuRootContext } from './MenuRoot.vue'\nimport {\n  FIRST_LAST_KEYS,\n  focusFirst,\n  getOpenState,\n  isMouseEvent,\n  isPointerInGraceArea,\n  LAST_KEYS,\n} from './utils'\n\nconst props = withDefaults(defineProps<MenuContentImplProps>(), {\n  ...PopperContentPropsDefaultValue,\n})\nconst emits = defineEmits<MenuContentImplPrivateEmits>()\nconst menuContext = injectMenuContext()\nconst rootContext = injectMenuRootContext()\n\nconst { trapFocus, disableOutsidePointerEvents, loop } = toRefs(props)\n\nuseFocusGuards()\nuseBodyScrollLock(disableOutsidePointerEvents.value)\n\nconst searchRef = ref('')\nconst timerRef = ref(0)\nconst pointerGraceTimerRef = ref(0)\nconst pointerGraceIntentRef = ref<GraceIntent | null>(null)\nconst pointerDirRef = ref<Side>('right')\nconst lastPointerXRef = ref(0)\nconst currentItemId = ref<string | null>(null)\n\nconst rovingFocusGroupRef = ref<InstanceType<typeof RovingFocusGroup>>()\nconst { forwardRef, currentElement: contentElement } = useForwardExpose()\nconst { handleTypeaheadSearch } = useTypeahead()\n\nconst highlightedElement = ref<HTMLElement>()\n\nfunction onKeydownNavigation(event: KeyboardEvent) {\n  const el = useArrowNavigation(\n    event,\n    (highlightedElement.value || getActiveElement()) as HTMLElement,\n    contentElement.value,\n    {\n      loop: loop.value,\n      arrowKeyOptions: 'vertical',\n      dir: rootContext?.dir.value,\n      focus: false,\n      attributeName: '[data-reka-collection-item]:not([data-disabled])',\n    },\n  )\n  if (el) {\n    highlightedElement.value = el\n    el.scrollIntoView({ block: 'nearest' })\n  }\n}\n\nfunction onKeydownEnter() {\n  if (highlightedElement.value) {\n    highlightedElement.value.click()\n  }\n}\n\nconst filterElement = ref<HTMLElement>()\nconst activeSubmenuContext = ref<{ onOpenChange: (open: boolean) => void, trigger: Ref<HTMLElement | undefined> }>()\n\nwatch(highlightedElement, (el) => {\n  if (activeSubmenuContext.value && (el === undefined || el !== activeSubmenuContext.value.trigger.value)) {\n    activeSubmenuContext.value.onOpenChange(false)\n    activeSubmenuContext.value = undefined\n  }\n})\n\nwatch(contentElement, (el) => {\n  menuContext!.onContentChange(el)\n})\n\nonUnmounted(() => {\n  window.clearTimeout(timerRef.value)\n})\n\nfunction isPointerMovingToSubmenu(event: PointerEvent) {\n  const isMovingTowards\n    = pointerDirRef.value === pointerGraceIntentRef.value?.side\n\n  return (\n    isMovingTowards\n    && isPointerInGraceArea(event, pointerGraceIntentRef.value?.area)\n  )\n}\n\nasync function handleMountAutoFocus(event: Event) {\n  emits('openAutoFocus', event)\n  if (event.defaultPrevented)\n    return\n  // when opening, explicitly focus the content area only and leave\n  // `onEntryFocus` in  control of focusing first item\n  event.preventDefault()\n  contentElement.value?.focus({\n    preventScroll: true,\n  })\n}\n\nfunction handleKeyDown(event: KeyboardEvent) {\n  if (event.defaultPrevented)\n    return\n  // submenu key events bubble through portals. We only care about keys in this menu.\n  const target = event.target as HTMLElement\n  const isKeyDownInside\n    = target.closest('[data-reka-menu-content]') === event.currentTarget\n  const isKeyDownInTextField = ['input', 'textarea'].includes(target.tagName.toLowerCase())\n  const isModifierKey = event.ctrlKey || event.altKey || event.metaKey\n  const isCharacterKey = event.key.length === 1\n\n  const el = useArrowNavigation(\n    event,\n    getActiveElement() as HTMLElement,\n    contentElement.value,\n    {\n      loop: loop.value,\n      arrowKeyOptions: 'vertical',\n      dir: rootContext?.dir.value,\n      focus: true,\n      attributeName: '[data-reka-collection-item]:not([data-disabled])',\n    },\n  )\n  if (el)\n    return el?.focus()\n\n  // prevent \"Space\" taken account into handleTypeahead\n  if (event.code === 'Space')\n    return\n\n  const collectionItems = rovingFocusGroupRef.value?.getItems() ?? []\n\n  if (isKeyDownInside) {\n    // menus should not be navigated using tab key so we prevent it\n    if (event.key === 'Tab')\n      event.preventDefault()\n    if (!isModifierKey && isCharacterKey && !isKeyDownInTextField)\n      handleTypeaheadSearch(event.key, collectionItems)\n  }\n\n  // focus first/last item based on key pressed\n  if (event.target !== contentElement.value)\n    return\n  if (!FIRST_LAST_KEYS.includes(event.key))\n    return\n  event.preventDefault()\n  const candidateNodes = [...collectionItems.map(item => item.ref)]\n  if (LAST_KEYS.includes(event.key))\n    candidateNodes.reverse()\n  focusFirst(candidateNodes)\n}\n\nfunction handleBlur(event: FocusEvent) {\n  // clear search buffer when leaving the menu\n  // @ts-expect-error the provided currentTarget and target should be HTMLElement\n  if (!event?.currentTarget?.contains?.(event.target)) {\n    window.clearTimeout(timerRef.value)\n    searchRef.value = ''\n  }\n}\n\nfunction handlePointerMove(event: PointerEvent) {\n  if (!isMouseEvent(event))\n    return\n  const target = event.target as HTMLElement\n  const pointerXHasChanged = lastPointerXRef.value !== event.clientX\n\n  // We don't use `event.movementX` for this check because Safari will\n  // always return `0` on a pointer event.\n  if (\n    (event?.currentTarget as HTMLElement)?.contains(target)\n    && pointerXHasChanged\n  ) {\n    const newDir = event.clientX > lastPointerXRef.value ? 'right' : 'left'\n    pointerDirRef.value = newDir\n    lastPointerXRef.value = event.clientX\n  }\n}\n\nfunction handlePointerEnter(event: PointerEvent) {\n  if (!isMouseEvent(event))\n    return\n  // When hovering over a menu content (main or sub), focus its filter element if it exists\n  if (filterElement.value) {\n    filterElement.value.focus()\n  }\n}\n\nprovideMenuContentContext({\n  onItemEnter: (event) => {\n    // event.preventDefault() we can't prevent pointerMove event\n    if (isPointerMovingToSubmenu(event))\n      return true\n    else\n      return false\n  },\n  onItemLeave: (event) => {\n    if (isPointerMovingToSubmenu(event))\n      return true\n\n    const isInputFocused = ['INPUT', 'TEXTAREA'].includes(getActiveElement()?.tagName || '')\n    if (!isInputFocused)\n      contentElement.value?.focus()\n\n    currentItemId.value = null\n    return false\n  },\n  onTriggerLeave: (event) => {\n    // event.preventDefault() we can't prevent pointerLeave event\n    if (isPointerMovingToSubmenu(event))\n      return true\n    else\n      return false\n  },\n  searchRef,\n  highlightedElement,\n  onKeydownNavigation,\n  onKeydownEnter,\n  filterElement,\n  onFilterElementChange: (el) => {\n    filterElement.value = el\n  },\n  activeSubmenuContext,\n  pointerGraceTimerRef,\n  onPointerGraceIntentChange: (intent) => {\n    pointerGraceIntentRef.value = intent\n  },\n})\n</script>\n\n<template>\n  <FocusScope\n    as-child\n    :trapped=\"trapFocus\"\n    @mount-auto-focus=\"handleMountAutoFocus\"\n    @unmount-auto-focus=\"emits('closeAutoFocus', $event)\"\n  >\n    <DismissableLayer\n      as-child\n      :disable-outside-pointer-events=\"disableOutsidePointerEvents\"\n      @escape-key-down=\"emits('escapeKeyDown', $event)\"\n      @pointer-down-outside=\"emits('pointerDownOutside', $event)\"\n      @focus-outside=\"emits('focusOutside', $event)\"\n      @interact-outside=\"emits('interactOutside', $event)\"\n      @dismiss=\"emits('dismiss')\"\n    >\n      <RovingFocusGroup\n        ref=\"rovingFocusGroupRef\"\n        v-model:current-tab-stop-id=\"currentItemId\"\n        as-child\n        orientation=\"vertical\"\n        :dir=\"rootContext.dir.value\"\n        :loop=\"loop\"\n        @entry-focus=\"(event) => {\n          emits('entryFocus', event)\n          // only focus first item when using keyboard\n          if (!rootContext.isUsingKeyboardRef.value) event.preventDefault();\n        }\"\n      >\n        <PopperContent\n          :ref=\"forwardRef\"\n          role=\"menu\"\n          :as=\"as\"\n          :as-child=\"asChild\"\n          aria-orientation=\"vertical\"\n          data-reka-menu-content\n          :data-state=\"getOpenState(menuContext.open.value)\"\n          :dir=\"rootContext.dir.value\"\n          :side=\"side\"\n          :side-offset=\"sideOffset\"\n          :align=\"align\"\n          :align-offset=\"alignOffset\"\n          :avoid-collisions=\"avoidCollisions\"\n          :collision-boundary=\"collisionBoundary\"\n          :collision-padding=\"collisionPadding\"\n          :arrow-padding=\"arrowPadding\"\n          :prioritize-position=\"prioritizePosition\"\n          :position-strategy=\"positionStrategy\"\n          :update-position-strategy=\"updatePositionStrategy\"\n          :sticky=\"sticky\"\n          :hide-when-detached=\"hideWhenDetached\"\n          :reference=\"reference\"\n          @keydown=\"handleKeyDown\"\n          @blur=\"handleBlur\"\n          @pointermove=\"handlePointerMove\"\n          @pointerenter=\"handlePointerEnter\"\n        >\n          <slot />\n        </PopperContent>\n      </RovingFocusGroup>\n    </DismissableLayer>\n  </FocusScope>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MenuItemImplProps extends PrimitiveProps {\n  /** When `true`, prevents the user from interacting with the item. */\n  disabled?: boolean\n  /**\n   * Optional text used for typeahead purposes. By default the typeahead behavior will use the `.textContent` of the item. <br>\n   *  Use this when the content is complex, or you have non-textual content inside.\n   */\n  textValue?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, nextTick, ref } from 'vue'\nimport { useCollection } from '@/Collection'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { getActiveElement, useForwardExpose } from '@/shared'\nimport { injectMenuContentContext } from './MenuContentImpl.vue'\nimport { isMouseEvent } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<MenuItemImplProps>()\n\nconst contentContext = injectMenuContentContext()\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { CollectionItem } = useCollection()\n\nconst isFocused = ref(false)\nconst isHighlighted = computed(() => isFocused.value || (currentElement.value != null && contentContext.highlightedElement.value === currentElement.value))\n\nasync function handlePointerMove(event: PointerEvent) {\n  if (event.defaultPrevented || !isMouseEvent(event))\n    return\n  if (props.disabled) {\n    contentContext.onItemLeave(event)\n  }\n  else {\n    const defaultPrevented = contentContext.onItemEnter(event)\n    if (!defaultPrevented) {\n      const item = event.currentTarget as HTMLElement\n      contentContext.highlightedElement.value = item\n      const isInputFocused = ['INPUT', 'TEXTAREA'].includes(getActiveElement()?.tagName || '')\n      if (!isInputFocused)\n        item.focus({ preventScroll: true })\n    }\n  }\n}\n\nasync function handlePointerLeave(event: PointerEvent) {\n  await nextTick()\n  if (event.defaultPrevented)\n    return\n  if (!isMouseEvent(event))\n    return\n\n  // If the highlight was already claimed by another element (e.g. the pointer moved\n  // directly onto another item, whose synchronous `pointermove` ran before this\n  // `nextTick` resolved), this leave is stale and must not reset focus/roving state.\n  if (contentContext.highlightedElement.value !== currentElement.value)\n    return\n\n  const isMovingToSubmenu = contentContext.onItemLeave(event)\n  if (!isMovingToSubmenu && contentContext.highlightedElement.value === currentElement.value)\n    contentContext.highlightedElement.value = undefined\n}\n</script>\n\n<template>\n  <CollectionItem :value=\"{ textValue }\">\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"menuitem\"\n      tabindex=\"-1\"\n      v-bind=\"$attrs\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :aria-disabled=\"disabled || undefined\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :data-highlighted=\"isHighlighted ? '' : undefined\"\n      @pointermove=\"handlePointerMove\"\n      @pointerleave=\"handlePointerLeave\"\n      @focus=\"\n        async (event: FocusEvent) => {\n          await nextTick();\n          if (event.defaultPrevented || disabled) return;\n          isFocused = true;\n          contentContext.highlightedElement.value = event.currentTarget as HTMLElement\n        }\n      \"\n      @blur=\"\n        async (event: FocusEvent) => {\n          await nextTick();\n          if (event.defaultPrevented) return;\n          isFocused = false;\n        }\n      \"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MenuItemImplProps extends PrimitiveProps {\n  /** When `true`, prevents the user from interacting with the item. */\n  disabled?: boolean\n  /**\n   * Optional text used for typeahead purposes. By default the typeahead behavior will use the `.textContent` of the item. <br>\n   *  Use this when the content is complex, or you have non-textual content inside.\n   */\n  textValue?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, nextTick, ref } from 'vue'\nimport { useCollection } from '@/Collection'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { getActiveElement, useForwardExpose } from '@/shared'\nimport { injectMenuContentContext } from './MenuContentImpl.vue'\nimport { isMouseEvent } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<MenuItemImplProps>()\n\nconst contentContext = injectMenuContentContext()\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { CollectionItem } = useCollection()\n\nconst isFocused = ref(false)\nconst isHighlighted = computed(() => isFocused.value || (currentElement.value != null && contentContext.highlightedElement.value === currentElement.value))\n\nasync function handlePointerMove(event: PointerEvent) {\n  if (event.defaultPrevented || !isMouseEvent(event))\n    return\n  if (props.disabled) {\n    contentContext.onItemLeave(event)\n  }\n  else {\n    const defaultPrevented = contentContext.onItemEnter(event)\n    if (!defaultPrevented) {\n      const item = event.currentTarget as HTMLElement\n      contentContext.highlightedElement.value = item\n      const isInputFocused = ['INPUT', 'TEXTAREA'].includes(getActiveElement()?.tagName || '')\n      if (!isInputFocused)\n        item.focus({ preventScroll: true })\n    }\n  }\n}\n\nasync function handlePointerLeave(event: PointerEvent) {\n  await nextTick()\n  if (event.defaultPrevented)\n    return\n  if (!isMouseEvent(event))\n    return\n\n  // If the highlight was already claimed by another element (e.g. the pointer moved\n  // directly onto another item, whose synchronous `pointermove` ran before this\n  // `nextTick` resolved), this leave is stale and must not reset focus/roving state.\n  if (contentContext.highlightedElement.value !== currentElement.value)\n    return\n\n  const isMovingToSubmenu = contentContext.onItemLeave(event)\n  if (!isMovingToSubmenu && contentContext.highlightedElement.value === currentElement.value)\n    contentContext.highlightedElement.value = undefined\n}\n</script>\n\n<template>\n  <CollectionItem :value=\"{ textValue }\">\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"menuitem\"\n      tabindex=\"-1\"\n      v-bind=\"$attrs\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :aria-disabled=\"disabled || undefined\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :data-highlighted=\"isHighlighted ? '' : undefined\"\n      @pointermove=\"handlePointerMove\"\n      @pointerleave=\"handlePointerLeave\"\n      @focus=\"\n        async (event: FocusEvent) => {\n          await nextTick();\n          if (event.defaultPrevented || disabled) return;\n          isFocused = true;\n          contentContext.highlightedElement.value = event.currentTarget as HTMLElement\n        }\n      \"\n      @blur=\"\n        async (event: FocusEvent) => {\n          await nextTick();\n          if (event.defaultPrevented) return;\n          isFocused = false;\n        }\n      \"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemImplProps } from './MenuItemImpl.vue'\nimport { useForwardExpose } from '@/shared'\n\nexport type MenuItemEmits = {\n  /**\n   * Event handler called when the user selects an item (via mouse or keyboard). <br>\n   *  Calling `event.preventDefault` in this handler will prevent the menu from closing when selecting that item.\n   */\n  select: [event: Event]\n}\n\nexport interface MenuItemProps extends MenuItemImplProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { nextTick, ref } from 'vue'\nimport { injectMenuContentContext } from './MenuContentImpl.vue'\nimport MenuItemImpl from './MenuItemImpl.vue'\nimport { injectMenuRootContext } from './MenuRoot.vue'\nimport { ITEM_SELECT, SELECTION_KEYS } from './utils'\n\nconst props = defineProps<MenuItemProps>()\nconst emits = defineEmits<MenuItemEmits>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst rootContext = injectMenuRootContext()\nconst contentContext = injectMenuContentContext()\n\nconst isPointerDownRef = ref(false)\n\nasync function handleSelect() {\n  const menuItem = currentElement.value\n  if (!props.disabled && menuItem) {\n    const itemSelectEvent = new CustomEvent(ITEM_SELECT, {\n      bubbles: true,\n      cancelable: true,\n    })\n    emits('select', itemSelectEvent)\n    // let select event finish\n    await nextTick()\n    if (itemSelectEvent.defaultPrevented)\n      isPointerDownRef.value = false\n    else rootContext.onClose()\n  }\n}\n</script>\n\n<template>\n  <MenuItemImpl\n    v-bind=\"props\"\n    :ref=\"forwardRef\"\n    @click=\"handleSelect\"\n    @pointerdown=\"\n      () => {\n        isPointerDownRef = true;\n      }\n    \"\n    @pointerup=\"\n      async (event: PointerEvent) => {\n        await nextTick();\n        if (event.defaultPrevented) return;\n        // Pointer down can move to a different menu item which should activate it on pointer up.\n        // We dispatch a click for selection to allow composition with click based triggers and to\n        // prevent Firefox from getting stuck in text selection mode when the menu closes.\n        if (!isPointerDownRef) (event.currentTarget as HTMLElement)?.click();\n      }\n    \"\n    @keydown=\"\n      async (event: KeyboardEvent) => {\n        const isTypingAhead = contentContext.searchRef.value !== '';\n        if (disabled || (isTypingAhead && event.key === ' ')) return;\n        if (SELECTION_KEYS.includes(event.key)) {\n          (event.currentTarget as HTMLElement)?.click();\n          /**\n           * We prevent default browser behaviour for selection keys as they should trigger\n           * a selection only:\n           * - prevents space from scrolling the page.\n           * - if keydown causes focus to move, prevents keydown from firing on the new target.\n           */\n          event.preventDefault();\n        }\n      }\n    \"\n  >\n    <slot />\n  </MenuItemImpl>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemImplProps } from './MenuItemImpl.vue'\nimport { useForwardExpose } from '@/shared'\n\nexport type MenuItemEmits = {\n  /**\n   * Event handler called when the user selects an item (via mouse or keyboard). <br>\n   *  Calling `event.preventDefault` in this handler will prevent the menu from closing when selecting that item.\n   */\n  select: [event: Event]\n}\n\nexport interface MenuItemProps extends MenuItemImplProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { nextTick, ref } from 'vue'\nimport { injectMenuContentContext } from './MenuContentImpl.vue'\nimport MenuItemImpl from './MenuItemImpl.vue'\nimport { injectMenuRootContext } from './MenuRoot.vue'\nimport { ITEM_SELECT, SELECTION_KEYS } from './utils'\n\nconst props = defineProps<MenuItemProps>()\nconst emits = defineEmits<MenuItemEmits>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst rootContext = injectMenuRootContext()\nconst contentContext = injectMenuContentContext()\n\nconst isPointerDownRef = ref(false)\n\nasync function handleSelect() {\n  const menuItem = currentElement.value\n  if (!props.disabled && menuItem) {\n    const itemSelectEvent = new CustomEvent(ITEM_SELECT, {\n      bubbles: true,\n      cancelable: true,\n    })\n    emits('select', itemSelectEvent)\n    // let select event finish\n    await nextTick()\n    if (itemSelectEvent.defaultPrevented)\n      isPointerDownRef.value = false\n    else rootContext.onClose()\n  }\n}\n</script>\n\n<template>\n  <MenuItemImpl\n    v-bind=\"props\"\n    :ref=\"forwardRef\"\n    @click=\"handleSelect\"\n    @pointerdown=\"\n      () => {\n        isPointerDownRef = true;\n      }\n    \"\n    @pointerup=\"\n      async (event: PointerEvent) => {\n        await nextTick();\n        if (event.defaultPrevented) return;\n        // Pointer down can move to a different menu item which should activate it on pointer up.\n        // We dispatch a click for selection to allow composition with click based triggers and to\n        // prevent Firefox from getting stuck in text selection mode when the menu closes.\n        if (!isPointerDownRef) (event.currentTarget as HTMLElement)?.click();\n      }\n    \"\n    @keydown=\"\n      async (event: KeyboardEvent) => {\n        const isTypingAhead = contentContext.searchRef.value !== '';\n        if (disabled || (isTypingAhead && event.key === ' ')) return;\n        if (SELECTION_KEYS.includes(event.key)) {\n          (event.currentTarget as HTMLElement)?.click();\n          /**\n           * We prevent default browser behaviour for selection keys as they should trigger\n           * a selection only:\n           * - prevents space from scrolling the page.\n           * - if keydown causes focus to move, prevents keydown from firing on the new target.\n           */\n          event.preventDefault();\n        }\n      }\n    \"\n  >\n    <slot />\n  </MenuItemImpl>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { CheckedState } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext } from '@/shared'\n\ninterface MenuItemIndicatorContext {\n  modelValue: Ref<CheckedState>\n}\n\nexport interface MenuItemIndicatorProps extends PrimitiveProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n\nexport const [injectMenuItemIndicatorContext, provideMenuItemIndicatorContext]\n  = createContext<MenuItemIndicatorContext>(\n    ['MenuCheckboxItem', 'MenuRadioItem'],\n    'MenuItemIndicatorContext',\n  )\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { Presence } from '@/Presence'\nimport { Primitive } from '@/Primitive'\nimport { getCheckedState, isIndeterminate } from './utils'\n\nwithDefaults(defineProps<MenuItemIndicatorProps>(), {\n  as: 'span',\n})\n\nconst indicatorContext = injectMenuItemIndicatorContext({\n  modelValue: ref(false),\n})\n</script>\n\n<template>\n  <Presence\n    :present=\"\n      forceMount\n        || isIndeterminate(indicatorContext.modelValue.value)\n        || indicatorContext.modelValue.value === true\n    \"\n  >\n    <Primitive\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :data-state=\"getCheckedState(indicatorContext.modelValue.value)\"\n    >\n      <slot />\n    </Primitive>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { CheckedState } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext } from '@/shared'\n\ninterface MenuItemIndicatorContext {\n  modelValue: Ref<CheckedState>\n}\n\nexport interface MenuItemIndicatorProps extends PrimitiveProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n\nexport const [injectMenuItemIndicatorContext, provideMenuItemIndicatorContext]\n  = createContext<MenuItemIndicatorContext>(\n    ['MenuCheckboxItem', 'MenuRadioItem'],\n    'MenuItemIndicatorContext',\n  )\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { Presence } from '@/Presence'\nimport { Primitive } from '@/Primitive'\nimport { getCheckedState, isIndeterminate } from './utils'\n\nwithDefaults(defineProps<MenuItemIndicatorProps>(), {\n  as: 'span',\n})\n\nconst indicatorContext = injectMenuItemIndicatorContext({\n  modelValue: ref(false),\n})\n</script>\n\n<template>\n  <Presence\n    :present=\"\n      forceMount\n        || isIndeterminate(indicatorContext.modelValue.value)\n        || indicatorContext.modelValue.value === true\n    \"\n  >\n    <Primitive\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :data-state=\"getCheckedState(indicatorContext.modelValue.value)\"\n    >\n      <slot />\n    </Primitive>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuItemEmits,\n  MenuItemProps,\n} from './MenuItem.vue'\nimport type { CheckedState } from './utils'\nimport { useForwardProps } from '@/shared'\n\nexport type MenuCheckboxItemEmits = MenuItemEmits & {\n  /** Event handler called when the checked state changes. */\n  'update:modelValue': [payload: boolean]\n}\n\nexport interface MenuCheckboxItemProps extends MenuItemProps {\n  /** The controlled checked state of the item. Can be used as `v-model`. */\n  modelValue?: CheckedState\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { reactiveOmit, useVModel } from '@vueuse/core'\nimport MenuItem from './MenuItem.vue'\nimport { provideMenuItemIndicatorContext } from './MenuItemIndicator.vue'\nimport { getCheckedState, isIndeterminate } from './utils'\n\nconst props = withDefaults(defineProps<MenuCheckboxItemProps>(), {\n  modelValue: false,\n})\nconst emits = defineEmits<MenuCheckboxItemEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current modelValue state */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst delegatedProps = reactiveOmit(props, ['modelValue'])\nconst forwarded = useForwardProps(delegatedProps)\n\nconst modelValue = useVModel(props, 'modelValue', emits)\n\nprovideMenuItemIndicatorContext({ modelValue })\n</script>\n\n<template>\n  <MenuItem\n    role=\"menuitemcheckbox\"\n    v-bind=\"forwarded\"\n    :aria-checked=\"isIndeterminate(modelValue) ? 'mixed' : modelValue\"\n    :data-state=\"getCheckedState(modelValue)\"\n    @select=\"\n      async (event) => {\n        emits('select', event);\n        if (isIndeterminate(modelValue)) {\n          modelValue = true;\n        }\n        else {\n          modelValue = !modelValue;\n        }\n      }\n    \"\n  >\n    <slot :model-value=\"modelValue\" />\n  </MenuItem>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuItemEmits,\n  MenuItemProps,\n} from './MenuItem.vue'\nimport type { CheckedState } from './utils'\nimport { useForwardProps } from '@/shared'\n\nexport type MenuCheckboxItemEmits = MenuItemEmits & {\n  /** Event handler called when the checked state changes. */\n  'update:modelValue': [payload: boolean]\n}\n\nexport interface MenuCheckboxItemProps extends MenuItemProps {\n  /** The controlled checked state of the item. Can be used as `v-model`. */\n  modelValue?: CheckedState\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { reactiveOmit, useVModel } from '@vueuse/core'\nimport MenuItem from './MenuItem.vue'\nimport { provideMenuItemIndicatorContext } from './MenuItemIndicator.vue'\nimport { getCheckedState, isIndeterminate } from './utils'\n\nconst props = withDefaults(defineProps<MenuCheckboxItemProps>(), {\n  modelValue: false,\n})\nconst emits = defineEmits<MenuCheckboxItemEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current modelValue state */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst delegatedProps = reactiveOmit(props, ['modelValue'])\nconst forwarded = useForwardProps(delegatedProps)\n\nconst modelValue = useVModel(props, 'modelValue', emits)\n\nprovideMenuItemIndicatorContext({ modelValue })\n</script>\n\n<template>\n  <MenuItem\n    role=\"menuitemcheckbox\"\n    v-bind=\"forwarded\"\n    :aria-checked=\"isIndeterminate(modelValue) ? 'mixed' : modelValue\"\n    :data-state=\"getCheckedState(modelValue)\"\n    @select=\"\n      async (event) => {\n        emits('select', event);\n        if (isIndeterminate(modelValue)) {\n          modelValue = true;\n        }\n        else {\n          modelValue = !modelValue;\n        }\n      }\n    \"\n  >\n    <slot :model-value=\"modelValue\" />\n  </MenuItem>\n</template>\n","<script setup lang=\"ts\">\nimport type { MenuContentImplEmits, MenuRootContentTypeProps } from './MenuContentImpl.vue'\nimport { useForwardExpose, useForwardPropsEmits, useHideOthers } from '@/shared'\nimport MenuContentImpl from './MenuContentImpl.vue'\nimport { injectMenuContext } from './MenuRoot.vue'\n\nconst props = defineProps<MenuRootContentModalProps>()\nconst emits = defineEmits<MenuRootContentModalEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst menuContext = injectMenuContext()\n\ninterface MenuRootContentModalProps extends MenuRootContentTypeProps {}\ntype MenuRootContentModalEmits = MenuContentImplEmits\n\nconst { forwardRef, currentElement } = useForwardExpose()\nuseHideOthers(currentElement)\n</script>\n\n<template>\n  <MenuContentImpl\n    v-bind=\"forwarded\"\n    :ref=\"forwardRef\"\n    :trap-focus=\"menuContext.open.value\"\n    :disable-outside-pointer-events=\"menuContext.open.value\"\n    :disable-outside-scroll=\"true\"\n    @dismiss=\"menuContext.onOpenChange(false)\"\n    @focus-outside.prevent=\"emits('focusOutside', $event)\"\n  >\n    <slot />\n  </MenuContentImpl>\n</template>\n","<script setup lang=\"ts\">\nimport type { MenuContentImplEmits, MenuRootContentTypeProps } from './MenuContentImpl.vue'\nimport { useForwardExpose, useForwardPropsEmits, useHideOthers } from '@/shared'\nimport MenuContentImpl from './MenuContentImpl.vue'\nimport { injectMenuContext } from './MenuRoot.vue'\n\nconst props = defineProps<MenuRootContentModalProps>()\nconst emits = defineEmits<MenuRootContentModalEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst menuContext = injectMenuContext()\n\ninterface MenuRootContentModalProps extends MenuRootContentTypeProps {}\ntype MenuRootContentModalEmits = MenuContentImplEmits\n\nconst { forwardRef, currentElement } = useForwardExpose()\nuseHideOthers(currentElement)\n</script>\n\n<template>\n  <MenuContentImpl\n    v-bind=\"forwarded\"\n    :ref=\"forwardRef\"\n    :trap-focus=\"menuContext.open.value\"\n    :disable-outside-pointer-events=\"menuContext.open.value\"\n    :disable-outside-scroll=\"true\"\n    @dismiss=\"menuContext.onOpenChange(false)\"\n    @focus-outside.prevent=\"emits('focusOutside', $event)\"\n  >\n    <slot />\n  </MenuContentImpl>\n</template>\n","<script setup lang=\"ts\">\nimport type { MenuContentImplEmits, MenuRootContentTypeProps } from './MenuContentImpl.vue'\nimport { useForwardPropsEmits } from '@/shared'\nimport MenuContentImpl from './MenuContentImpl.vue'\nimport { injectMenuContext } from './MenuRoot.vue'\n\nconst props = defineProps<MenuRootContentNonModalProps>()\nconst emits = defineEmits<MenuRootContentModalEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst menuContext = injectMenuContext()\n\ninterface MenuRootContentNonModalProps extends MenuRootContentTypeProps {}\ntype MenuRootContentModalEmits = MenuContentImplEmits\n</script>\n\n<template>\n  <MenuContentImpl\n    v-bind=\"forwarded\"\n    :trap-focus=\"false\"\n    :disable-outside-pointer-events=\"false\"\n    :disable-outside-scroll=\"false\"\n    @dismiss=\"menuContext.onOpenChange(false)\"\n  >\n    <slot />\n  </MenuContentImpl>\n</template>\n","<script setup lang=\"ts\">\nimport type { MenuContentImplEmits, MenuRootContentTypeProps } from './MenuContentImpl.vue'\nimport { useForwardPropsEmits } from '@/shared'\nimport MenuContentImpl from './MenuContentImpl.vue'\nimport { injectMenuContext } from './MenuRoot.vue'\n\nconst props = defineProps<MenuRootContentNonModalProps>()\nconst emits = defineEmits<MenuRootContentModalEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst menuContext = injectMenuContext()\n\ninterface MenuRootContentNonModalProps extends MenuRootContentTypeProps {}\ntype MenuRootContentModalEmits = MenuContentImplEmits\n</script>\n\n<template>\n  <MenuContentImpl\n    v-bind=\"forwarded\"\n    :trap-focus=\"false\"\n    :disable-outside-pointer-events=\"false\"\n    :disable-outside-scroll=\"false\"\n    @dismiss=\"menuContext.onOpenChange(false)\"\n  >\n    <slot />\n  </MenuContentImpl>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuContentImplEmits,\n  MenuRootContentTypeProps,\n} from './MenuContentImpl.vue'\n\nexport type MenuContentEmits = Omit<MenuContentImplEmits, 'entryFocus' | 'openAutoFocus'>\n\nexport interface MenuContentProps extends MenuRootContentTypeProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardPropsEmits } from '@/shared'\nimport { injectMenuContext, injectMenuRootContext } from './MenuRoot.vue'\nimport MenuRootContentModal from './MenuRootContentModal.vue'\nimport MenuRootContentNonModal from './MenuRootContentNonModal.vue'\n\nconst props = defineProps<MenuContentProps>()\nconst emits = defineEmits<MenuContentImplEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst menuContext = injectMenuContext()\nconst rootContext = injectMenuRootContext()\n</script>\n\n<template>\n  <Presence :present=\"forceMount || menuContext.open.value\">\n    <MenuRootContentModal\n      v-if=\"rootContext.modal.value\"\n      v-bind=\"{ ...$attrs, ...forwarded }\"\n    >\n      <slot />\n    </MenuRootContentModal>\n    <MenuRootContentNonModal\n      v-else\n      v-bind=\"{ ...$attrs, ...forwarded }\"\n    >\n      <slot />\n    </MenuRootContentNonModal>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuContentImplEmits,\n  MenuRootContentTypeProps,\n} from './MenuContentImpl.vue'\n\nexport type MenuContentEmits = Omit<MenuContentImplEmits, 'entryFocus' | 'openAutoFocus'>\n\nexport interface MenuContentProps extends MenuRootContentTypeProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardPropsEmits } from '@/shared'\nimport { injectMenuContext, injectMenuRootContext } from './MenuRoot.vue'\nimport MenuRootContentModal from './MenuRootContentModal.vue'\nimport MenuRootContentNonModal from './MenuRootContentNonModal.vue'\n\nconst props = defineProps<MenuContentProps>()\nconst emits = defineEmits<MenuContentImplEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst menuContext = injectMenuContext()\nconst rootContext = injectMenuRootContext()\n</script>\n\n<template>\n  <Presence :present=\"forceMount || menuContext.open.value\">\n    <MenuRootContentModal\n      v-if=\"rootContext.modal.value\"\n      v-bind=\"{ ...$attrs, ...forwarded }\"\n    >\n      <slot />\n    </MenuRootContentModal>\n    <MenuRootContentNonModal\n      v-else\n      v-bind=\"{ ...$attrs, ...forwarded }\"\n    >\n      <slot />\n    </MenuRootContentNonModal>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useId } from '@/shared'\n\nexport interface MenuGroupProps extends PrimitiveProps {}\n\ninterface MenuGroupContext {\n  id: string\n}\n\nexport const [injectMenuGroupContext, provideMenuGroupContext]\n  = createContext<MenuGroupContext>('MenuGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<MenuGroupProps>()\n\nconst id = useId(undefined, 'reka-menu-group')\nprovideMenuGroupContext({ id })\n</script>\n\n<template>\n  <Primitive\n    role=\"group\"\n    v-bind=\"props\"\n    :aria-labelledby=\"id\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useId } from '@/shared'\n\nexport interface MenuGroupProps extends PrimitiveProps {}\n\ninterface MenuGroupContext {\n  id: string\n}\n\nexport const [injectMenuGroupContext, provideMenuGroupContext]\n  = createContext<MenuGroupContext>('MenuGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<MenuGroupProps>()\n\nconst id = useId(undefined, 'reka-menu-group')\nprovideMenuGroupContext({ id })\n</script>\n\n<template>\n  <Primitive\n    role=\"group\"\n    v-bind=\"props\"\n    :aria-labelledby=\"id\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { injectMenuGroupContext } from './MenuGroup.vue'\n\nexport interface MenuLabelProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MenuLabelProps>(), {\n  as: 'div',\n})\n\nconst groupContext = injectMenuGroupContext({ id: '' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"groupContext.id || undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { injectMenuGroupContext } from './MenuGroup.vue'\n\nexport interface MenuLabelProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MenuLabelProps>(), {\n  as: 'div',\n})\n\nconst groupContext = injectMenuGroupContext({ id: '' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"groupContext.id || undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface MenuPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<MenuPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface MenuPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<MenuPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { MenuGroupProps } from './MenuGroup.vue'\nimport type { AcceptableValue } from '@/shared/types'\nimport { createContext, useForwardProps } from '@/shared'\n\ninterface MenuRadioGroupContext {\n  modelValue: Ref<AcceptableValue>\n  onValueChange: (payload: AcceptableValue) => void\n}\n\nexport interface MenuRadioGroupProps extends MenuGroupProps {\n  /** The value of the selected item in the group. */\n  modelValue?: AcceptableValue\n}\n\nexport type MenuRadioGroupEmits = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [payload: AcceptableValue]\n}\n\nexport const [injectMenuRadioGroupContext, provideMenuRadioGroupContext]\n  = createContext<MenuRadioGroupContext>('MenuRadioGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport { reactiveOmit, useVModel } from '@vueuse/core'\nimport MenuGroup from './MenuGroup.vue'\n\nconst props = withDefaults(defineProps<MenuRadioGroupProps>(), {\n  modelValue: '',\n})\nconst emits = defineEmits<MenuRadioGroupEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst delegatedProps = reactiveOmit(props, ['modelValue'])\nconst forwarded = useForwardProps(delegatedProps)\n\nconst modelValue = useVModel(props, 'modelValue', emits)\n\nprovideMenuRadioGroupContext({\n  modelValue,\n  onValueChange: (payload) => {\n    modelValue.value = payload\n  },\n})\n</script>\n\n<template>\n  <MenuGroup v-bind=\"forwarded\">\n    <slot :model-value=\"modelValue\" />\n  </MenuGroup>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { MenuGroupProps } from './MenuGroup.vue'\nimport type { AcceptableValue } from '@/shared/types'\nimport { createContext, useForwardProps } from '@/shared'\n\ninterface MenuRadioGroupContext {\n  modelValue: Ref<AcceptableValue>\n  onValueChange: (payload: AcceptableValue) => void\n}\n\nexport interface MenuRadioGroupProps extends MenuGroupProps {\n  /** The value of the selected item in the group. */\n  modelValue?: AcceptableValue\n}\n\nexport type MenuRadioGroupEmits = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [payload: AcceptableValue]\n}\n\nexport const [injectMenuRadioGroupContext, provideMenuRadioGroupContext]\n  = createContext<MenuRadioGroupContext>('MenuRadioGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport { reactiveOmit, useVModel } from '@vueuse/core'\nimport MenuGroup from './MenuGroup.vue'\n\nconst props = withDefaults(defineProps<MenuRadioGroupProps>(), {\n  modelValue: '',\n})\nconst emits = defineEmits<MenuRadioGroupEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst delegatedProps = reactiveOmit(props, ['modelValue'])\nconst forwarded = useForwardProps(delegatedProps)\n\nconst modelValue = useVModel(props, 'modelValue', emits)\n\nprovideMenuRadioGroupContext({\n  modelValue,\n  onValueChange: (payload) => {\n    modelValue.value = payload\n  },\n})\n</script>\n\n<template>\n  <MenuGroup v-bind=\"forwarded\">\n    <slot :model-value=\"modelValue\" />\n  </MenuGroup>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuItemEmits,\n  MenuItemProps,\n} from './MenuItem.vue'\nimport type { AcceptableValue } from '@/shared/types'\nimport { reactiveOmit } from '@vueuse/shared'\nimport { useForwardProps } from '@/shared'\n\nexport type MenuRadioItemEmits = MenuItemEmits\n\nexport interface MenuRadioItemProps extends MenuItemProps {\n  /** The unique value of the item. */\n  value: AcceptableValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, toRefs } from 'vue'\nimport MenuItem from './MenuItem.vue'\nimport { provideMenuItemIndicatorContext } from './MenuItemIndicator.vue'\nimport { injectMenuRadioGroupContext } from './MenuRadioGroup.vue'\nimport { getCheckedState } from './utils'\n\nconst props = defineProps<MenuRadioItemProps>()\nconst emits = defineEmits<MenuRadioItemEmits>()\n\nconst delegatedProps = reactiveOmit(props, ['value'])\nconst forwarded = useForwardProps(delegatedProps)\n\nconst { value } = toRefs(props)\nconst radioGroupContext = injectMenuRadioGroupContext()\nconst modelValue = computed(\n  () => radioGroupContext.modelValue.value === value?.value,\n)\n\nprovideMenuItemIndicatorContext({ modelValue })\n</script>\n\n<template>\n  <MenuItem\n    role=\"menuitemradio\"\n    v-bind=\"forwarded\"\n    :aria-checked=\"modelValue\"\n    :data-state=\"getCheckedState(modelValue)\"\n    @select=\"\n      async (event) => {\n        emits('select', event);\n        radioGroupContext.onValueChange(value);\n      }\n    \"\n  >\n    <slot />\n  </MenuItem>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuItemEmits,\n  MenuItemProps,\n} from './MenuItem.vue'\nimport type { AcceptableValue } from '@/shared/types'\nimport { reactiveOmit } from '@vueuse/shared'\nimport { useForwardProps } from '@/shared'\n\nexport type MenuRadioItemEmits = MenuItemEmits\n\nexport interface MenuRadioItemProps extends MenuItemProps {\n  /** The unique value of the item. */\n  value: AcceptableValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, toRefs } from 'vue'\nimport MenuItem from './MenuItem.vue'\nimport { provideMenuItemIndicatorContext } from './MenuItemIndicator.vue'\nimport { injectMenuRadioGroupContext } from './MenuRadioGroup.vue'\nimport { getCheckedState } from './utils'\n\nconst props = defineProps<MenuRadioItemProps>()\nconst emits = defineEmits<MenuRadioItemEmits>()\n\nconst delegatedProps = reactiveOmit(props, ['value'])\nconst forwarded = useForwardProps(delegatedProps)\n\nconst { value } = toRefs(props)\nconst radioGroupContext = injectMenuRadioGroupContext()\nconst modelValue = computed(\n  () => radioGroupContext.modelValue.value === value?.value,\n)\n\nprovideMenuItemIndicatorContext({ modelValue })\n</script>\n\n<template>\n  <MenuItem\n    role=\"menuitemradio\"\n    v-bind=\"forwarded\"\n    :aria-checked=\"modelValue\"\n    :data-state=\"getCheckedState(modelValue)\"\n    @select=\"\n      async (event) => {\n        emits('select', event);\n        radioGroupContext.onValueChange(value);\n      }\n    \"\n  >\n    <slot />\n  </MenuItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MenuSeparatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<MenuSeparatorProps>()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    role=\"separator\"\n    aria-orientation=\"horizontal\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MenuSeparatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<MenuSeparatorProps>()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    role=\"separator\"\n    aria-orientation=\"horizontal\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { MenuContext } from './MenuRoot.vue'\nimport { createContext } from '@/shared'\n\nexport interface MenuSubContext {\n  contentId: string\n  triggerId: string\n  trigger: Ref<HTMLElement | undefined>\n  onTriggerChange: (trigger: HTMLElement | undefined) => void\n  parentMenuContext?: MenuContext\n}\n\nexport const [injectMenuSubContext, provideMenuSubContext]\n  = createContext<MenuSubContext>('MenuSub')\n\nexport interface MenuSubProps {\n  /** The controlled open state of the menu. Can be used as `v-model:open`. */\n  open?: boolean\n}\n\nexport type MenuSubEmits = {\n  /** Event handler called when the open state of the submenu changes. */\n  'update:open': [payload: boolean]\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport {\n  ref,\n  watchEffect,\n} from 'vue'\nimport { PopperRoot } from '@/Popper'\nimport { injectMenuContext, provideMenuContext } from './MenuRoot.vue'\n\nconst props = withDefaults(defineProps<MenuSubProps>(), {\n  open: undefined,\n})\nconst emits = defineEmits<MenuSubEmits>()\n\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: false,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst parentMenuContext = injectMenuContext()\nconst trigger = ref<HTMLElement>()\nconst content = ref<HTMLElement>()\n\n// Prevent the parent menu from reopening with open submenus.\nwatchEffect((cleanupFn) => {\n  if (parentMenuContext?.open.value === false)\n    open.value = false\n  cleanupFn(() => (open.value = false))\n})\n\nprovideMenuContext({\n  open,\n  onOpenChange: (value) => {\n    open.value = value\n  },\n  content,\n  onContentChange: (element) => {\n    content.value = element\n  },\n})\n\nprovideMenuSubContext({\n  triggerId: '',\n  contentId: '',\n  trigger,\n  onTriggerChange: (element) => {\n    trigger.value = element\n  },\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <slot />\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { MenuContext } from './MenuRoot.vue'\nimport { createContext } from '@/shared'\n\nexport interface MenuSubContext {\n  contentId: string\n  triggerId: string\n  trigger: Ref<HTMLElement | undefined>\n  onTriggerChange: (trigger: HTMLElement | undefined) => void\n  parentMenuContext?: MenuContext\n}\n\nexport const [injectMenuSubContext, provideMenuSubContext]\n  = createContext<MenuSubContext>('MenuSub')\n\nexport interface MenuSubProps {\n  /** The controlled open state of the menu. Can be used as `v-model:open`. */\n  open?: boolean\n}\n\nexport type MenuSubEmits = {\n  /** Event handler called when the open state of the submenu changes. */\n  'update:open': [payload: boolean]\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport {\n  ref,\n  watchEffect,\n} from 'vue'\nimport { PopperRoot } from '@/Popper'\nimport { injectMenuContext, provideMenuContext } from './MenuRoot.vue'\n\nconst props = withDefaults(defineProps<MenuSubProps>(), {\n  open: undefined,\n})\nconst emits = defineEmits<MenuSubEmits>()\n\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: false,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst parentMenuContext = injectMenuContext()\nconst trigger = ref<HTMLElement>()\nconst content = ref<HTMLElement>()\n\n// Prevent the parent menu from reopening with open submenus.\nwatchEffect((cleanupFn) => {\n  if (parentMenuContext?.open.value === false)\n    open.value = false\n  cleanupFn(() => (open.value = false))\n})\n\nprovideMenuContext({\n  open,\n  onOpenChange: (value) => {\n    open.value = value\n  },\n  content,\n  onContentChange: (element) => {\n    content.value = element\n  },\n})\n\nprovideMenuSubContext({\n  triggerId: '',\n  contentId: '',\n  trigger,\n  onTriggerChange: (element) => {\n    trigger.value = element\n  },\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <slot />\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuContentImplEmits,\n  MenuContentImplProps,\n} from './MenuContentImpl.vue'\n\nexport type MenuSubContentEmits = MenuContentImplEmits\n\n// reference: https://github.com/radix-ui/primitives/blob/main/packages/react/menu/src/Menu.tsx#L1152\nexport interface MenuSubContentProps extends Omit<MenuContentImplProps, 'disableOutsidePointerEvents' | 'disableOutsideScroll' | 'trapFocus' | 'side' | 'align'> {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardExpose, useForwardPropsEmits, useId } from '@/shared'\nimport MenuContentImpl, { injectMenuContentContext } from './MenuContentImpl.vue'\nimport { injectMenuContext, injectMenuRootContext } from './MenuRoot.vue'\nimport { injectMenuSubContext } from './MenuSub.vue'\nimport { SUB_CLOSE_KEYS } from './utils'\n\nconst props = withDefaults(defineProps<MenuSubContentProps>(), {\n  prioritizePosition: true,\n})\nconst emits = defineEmits<MenuSubContentEmits>()\n\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst menuContext = injectMenuContext()\nconst rootContext = injectMenuRootContext()\nconst menuSubContext = injectMenuSubContext()\nconst parentContentContext = injectMenuContentContext()\n\nconst { forwardRef, currentElement: subContentElement } = useForwardExpose()\n\nmenuSubContext.contentId ||= useId(undefined, 'reka-menu-sub-content')\n</script>\n\n<template>\n  <Presence :present=\"forceMount || menuContext.open.value\">\n    <MenuContentImpl\n      v-bind=\"forwarded\"\n      :id=\"menuSubContext.contentId\"\n      :ref=\"forwardRef\"\n      :aria-labelledby=\"menuSubContext.triggerId\"\n      align=\"start\"\n      :side=\"rootContext.dir.value === 'rtl' ? 'left' : 'right'\"\n      :disable-outside-pointer-events=\"false\"\n      :disable-outside-scroll=\"false\"\n      :trap-focus=\"false\"\n      @open-auto-focus.prevent=\"(event) => {\n        // when opening a submenu, focus content for keyboard users only\n        if (rootContext.isUsingKeyboardRef.value) subContentElement?.focus();\n      }\"\n      @close-auto-focus.prevent\n      @focus-outside=\"\n        (event) => {\n          if (event.defaultPrevented) return;\n          // We prevent closing when the trigger is focused to avoid triggering a re-open animation\n          // on pointer interaction.\n          // Also check if focus is moving to the parent content's filter to avoid closing when\n          // hovering between submenu and parent menu\n          const isMovingToParentContent = parentContentContext.filterElement.value?.contains(event.target as Node);\n          if (event.target !== menuSubContext.trigger.value && !isMovingToParentContent)\n            menuContext.onOpenChange(false);\n        }\n      \"\n      @escape-key-down=\"\n        (event) => {\n          rootContext.onClose();\n          // ensure pressing escape in submenu doesn't escape full screen mode\n          event.preventDefault();\n        }\n      \"\n      @keydown=\"(event: KeyboardEvent) => {\n        // Submenu key events bubble through portals. We only care about keys in this menu.\n        const isKeyDownInside = (event.currentTarget as HTMLElement)?.contains(event.target as HTMLElement);\n        const isCloseKey = SUB_CLOSE_KEYS[rootContext.dir.value].includes(event.key);\n        if (isKeyDownInside && isCloseKey) {\n          menuContext.onOpenChange(false);\n          // We focus manually because we prevented it in `onCloseAutoFocus`\n          if (parentContentContext.filterElement.value) {\n            parentContentContext.filterElement.value.focus();\n            parentContentContext.highlightedElement.value = menuSubContext.trigger.value;\n            menuSubContext.trigger.value?.scrollIntoView({ block: 'nearest' });\n          }\n          else {\n            menuSubContext.trigger.value?.focus();\n          }\n          // prevent window from scrolling\n          event.preventDefault();\n        }\n      }\"\n    >\n      <slot />\n    </MenuContentImpl>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuContentImplEmits,\n  MenuContentImplProps,\n} from './MenuContentImpl.vue'\n\nexport type MenuSubContentEmits = MenuContentImplEmits\n\n// reference: https://github.com/radix-ui/primitives/blob/main/packages/react/menu/src/Menu.tsx#L1152\nexport interface MenuSubContentProps extends Omit<MenuContentImplProps, 'disableOutsidePointerEvents' | 'disableOutsideScroll' | 'trapFocus' | 'side' | 'align'> {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardExpose, useForwardPropsEmits, useId } from '@/shared'\nimport MenuContentImpl, { injectMenuContentContext } from './MenuContentImpl.vue'\nimport { injectMenuContext, injectMenuRootContext } from './MenuRoot.vue'\nimport { injectMenuSubContext } from './MenuSub.vue'\nimport { SUB_CLOSE_KEYS } from './utils'\n\nconst props = withDefaults(defineProps<MenuSubContentProps>(), {\n  prioritizePosition: true,\n})\nconst emits = defineEmits<MenuSubContentEmits>()\n\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst menuContext = injectMenuContext()\nconst rootContext = injectMenuRootContext()\nconst menuSubContext = injectMenuSubContext()\nconst parentContentContext = injectMenuContentContext()\n\nconst { forwardRef, currentElement: subContentElement } = useForwardExpose()\n\nmenuSubContext.contentId ||= useId(undefined, 'reka-menu-sub-content')\n</script>\n\n<template>\n  <Presence :present=\"forceMount || menuContext.open.value\">\n    <MenuContentImpl\n      v-bind=\"forwarded\"\n      :id=\"menuSubContext.contentId\"\n      :ref=\"forwardRef\"\n      :aria-labelledby=\"menuSubContext.triggerId\"\n      align=\"start\"\n      :side=\"rootContext.dir.value === 'rtl' ? 'left' : 'right'\"\n      :disable-outside-pointer-events=\"false\"\n      :disable-outside-scroll=\"false\"\n      :trap-focus=\"false\"\n      @open-auto-focus.prevent=\"(event) => {\n        // when opening a submenu, focus content for keyboard users only\n        if (rootContext.isUsingKeyboardRef.value) subContentElement?.focus();\n      }\"\n      @close-auto-focus.prevent\n      @focus-outside=\"\n        (event) => {\n          if (event.defaultPrevented) return;\n          // We prevent closing when the trigger is focused to avoid triggering a re-open animation\n          // on pointer interaction.\n          // Also check if focus is moving to the parent content's filter to avoid closing when\n          // hovering between submenu and parent menu\n          const isMovingToParentContent = parentContentContext.filterElement.value?.contains(event.target as Node);\n          if (event.target !== menuSubContext.trigger.value && !isMovingToParentContent)\n            menuContext.onOpenChange(false);\n        }\n      \"\n      @escape-key-down=\"\n        (event) => {\n          rootContext.onClose();\n          // ensure pressing escape in submenu doesn't escape full screen mode\n          event.preventDefault();\n        }\n      \"\n      @keydown=\"(event: KeyboardEvent) => {\n        // Submenu key events bubble through portals. We only care about keys in this menu.\n        const isKeyDownInside = (event.currentTarget as HTMLElement)?.contains(event.target as HTMLElement);\n        const isCloseKey = SUB_CLOSE_KEYS[rootContext.dir.value].includes(event.key);\n        if (isKeyDownInside && isCloseKey) {\n          menuContext.onOpenChange(false);\n          // We focus manually because we prevented it in `onCloseAutoFocus`\n          if (parentContentContext.filterElement.value) {\n            parentContentContext.filterElement.value.focus();\n            parentContentContext.highlightedElement.value = menuSubContext.trigger.value;\n            menuSubContext.trigger.value?.scrollIntoView({ block: 'nearest' });\n          }\n          else {\n            menuSubContext.trigger.value?.focus();\n          }\n          // prevent window from scrolling\n          event.preventDefault();\n        }\n      }\"\n    >\n      <slot />\n    </MenuContentImpl>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemImplProps } from './MenuItemImpl.vue'\nimport type { Side } from './utils'\n\nexport interface MenuSubTriggerProps extends MenuItemImplProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport type { ComponentPublicInstance } from 'vue'\nimport { nextTick, onUnmounted, ref, watch } from 'vue'\nimport { useId } from '@/shared'\nimport MenuAnchor from './MenuAnchor.vue'\nimport { injectMenuContentContext } from './MenuContentImpl.vue'\nimport MenuItemImpl from './MenuItemImpl.vue'\nimport { injectMenuContext, injectMenuRootContext } from './MenuRoot.vue'\nimport { injectMenuSubContext } from './MenuSub.vue'\nimport { getOpenState, isMouseEvent, SUB_OPEN_KEYS } from './utils'\n\nconst props = defineProps<MenuSubTriggerProps>()\n\nconst menuContext = injectMenuContext()\nconst rootContext = injectMenuRootContext()\nconst subContext = injectMenuSubContext()\nconst contentContext = injectMenuContentContext()\n\nwatch(menuContext.open, (open) => {\n  if (open) {\n    contentContext.activeSubmenuContext.value = {\n      onOpenChange: menuContext.onOpenChange,\n      trigger: subContext.trigger,\n    }\n  }\n  else if (contentContext.activeSubmenuContext.value?.trigger.value === subContext.trigger.value) {\n    contentContext.activeSubmenuContext.value = undefined\n  }\n})\n\nconst openTimerRef = ref<number | null>(null)\n\nsubContext.triggerId ||= useId(undefined, 'reka-menu-sub-trigger')\n\nfunction clearOpenTimer() {\n  if (openTimerRef.value)\n    window.clearTimeout(openTimerRef.value)\n  openTimerRef.value = null\n}\n\nonUnmounted(() => {\n  clearOpenTimer()\n})\n\nfunction handlePointerMove(event: PointerEvent) {\n  if (!isMouseEvent(event))\n    return\n  const defaultPrevented = contentContext.onItemEnter(event)\n  if (defaultPrevented)\n    return\n\n  if (!props.disabled && !menuContext.open.value && !openTimerRef.value) {\n    contentContext.onPointerGraceIntentChange(null)\n    openTimerRef.value = window.setTimeout(() => {\n      menuContext.onOpenChange(true)\n      clearOpenTimer()\n    }, 100)\n  }\n}\n\nasync function handlePointerLeave(event: PointerEvent) {\n  if (!isMouseEvent(event))\n    return\n  clearOpenTimer()\n\n  const contentRect = menuContext.content.value?.getBoundingClientRect()\n  if (contentRect?.width) {\n    // TODO (Radix UI): make sure to update this when we change positioning logic\n    // https://github.com/radix-ui/primitives/blob/main/packages/react/menu/src/Menu.tsx#L1088\n    const side = menuContext.content.value?.dataset.side as Side\n\n    const rightSide = side === 'right'\n    const bleed = rightSide ? -5 : +5\n    const contentNearEdge = contentRect[rightSide ? 'left' : 'right']\n    const contentFarEdge = contentRect[rightSide ? 'right' : 'left']\n\n    contentContext.onPointerGraceIntentChange({\n      area: [\n        // Apply a bleed on clientX to ensure that our exit point is\n        // consistently within polygon bounds\n        { x: event.clientX + bleed, y: event.clientY },\n        { x: contentNearEdge, y: contentRect.top },\n        { x: contentFarEdge, y: contentRect.top },\n        { x: contentFarEdge, y: contentRect.bottom },\n        { x: contentNearEdge, y: contentRect.bottom },\n      ],\n      side,\n    })\n\n    window.clearTimeout(contentContext.pointerGraceTimerRef.value)\n    contentContext.pointerGraceTimerRef.value = window.setTimeout(\n      () => contentContext.onPointerGraceIntentChange(null),\n      300,\n    )\n  }\n  else {\n    const defaultPrevented = contentContext.onTriggerLeave(event)\n    if (defaultPrevented)\n      return\n\n    // There's 100ms where the user may leave an item before the submenu was opened.\n    contentContext.onPointerGraceIntentChange(null)\n  }\n}\n\nasync function handleKeyDown(event: KeyboardEvent) {\n  const isTypingAhead = contentContext.searchRef.value !== ''\n  if (props.disabled || (isTypingAhead && event.key === ' '))\n    return\n  if (SUB_OPEN_KEYS[rootContext.dir.value].includes(event.key)) {\n    menuContext.onOpenChange(true)\n\n    await nextTick()\n    // The trigger may hold focus if opened via pointer interaction\n    // so we ensure content is given focus again when switching to keyboard.\n    menuContext.content.value?.focus()\n    // prevent window from scrolling\n    event.preventDefault()\n  }\n}\n</script>\n\n<template>\n  <MenuAnchor as-child>\n    <MenuItemImpl\n      v-bind=\"props\"\n      :id=\"subContext.triggerId\"\n      :ref=\"\n        (vnode: Element | ComponentPublicInstance | null) => {\n          if (!vnode) return undefined\n          // @ts-ignore\n          subContext?.onTriggerChange(vnode?.$el);\n          return undefined\n        }\n      \"\n      aria-haspopup=\"menu\"\n      :aria-expanded=\"menuContext.open.value\"\n      :aria-controls=\"subContext.contentId\"\n      :data-state=\"getOpenState(menuContext.open.value)\"\n      @click=\"\n        async (event: MouseEvent) => {\n          if (props.disabled || event.defaultPrevented) return;\n          /**\n           * We manually focus because iOS Safari doesn't always focus on click (e.g. buttons)\n           * and we rely heavily on `onFocusOutside` for submenus to close when switching\n           * between separate submenus.\n           */\n          (event.currentTarget as HTMLElement)?.focus();\n          if (!menuContext.open.value) menuContext.onOpenChange(true);\n        }\n      \"\n      @pointermove=\"handlePointerMove\"\n      @pointerleave=\"handlePointerLeave\"\n      @keydown=\"handleKeyDown\"\n    >\n      <slot />\n    </MenuItemImpl>\n  </MenuAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemImplProps } from './MenuItemImpl.vue'\nimport type { Side } from './utils'\n\nexport interface MenuSubTriggerProps extends MenuItemImplProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport type { ComponentPublicInstance } from 'vue'\nimport { nextTick, onUnmounted, ref, watch } from 'vue'\nimport { useId } from '@/shared'\nimport MenuAnchor from './MenuAnchor.vue'\nimport { injectMenuContentContext } from './MenuContentImpl.vue'\nimport MenuItemImpl from './MenuItemImpl.vue'\nimport { injectMenuContext, injectMenuRootContext } from './MenuRoot.vue'\nimport { injectMenuSubContext } from './MenuSub.vue'\nimport { getOpenState, isMouseEvent, SUB_OPEN_KEYS } from './utils'\n\nconst props = defineProps<MenuSubTriggerProps>()\n\nconst menuContext = injectMenuContext()\nconst rootContext = injectMenuRootContext()\nconst subContext = injectMenuSubContext()\nconst contentContext = injectMenuContentContext()\n\nwatch(menuContext.open, (open) => {\n  if (open) {\n    contentContext.activeSubmenuContext.value = {\n      onOpenChange: menuContext.onOpenChange,\n      trigger: subContext.trigger,\n    }\n  }\n  else if (contentContext.activeSubmenuContext.value?.trigger.value === subContext.trigger.value) {\n    contentContext.activeSubmenuContext.value = undefined\n  }\n})\n\nconst openTimerRef = ref<number | null>(null)\n\nsubContext.triggerId ||= useId(undefined, 'reka-menu-sub-trigger')\n\nfunction clearOpenTimer() {\n  if (openTimerRef.value)\n    window.clearTimeout(openTimerRef.value)\n  openTimerRef.value = null\n}\n\nonUnmounted(() => {\n  clearOpenTimer()\n})\n\nfunction handlePointerMove(event: PointerEvent) {\n  if (!isMouseEvent(event))\n    return\n  const defaultPrevented = contentContext.onItemEnter(event)\n  if (defaultPrevented)\n    return\n\n  if (!props.disabled && !menuContext.open.value && !openTimerRef.value) {\n    contentContext.onPointerGraceIntentChange(null)\n    openTimerRef.value = window.setTimeout(() => {\n      menuContext.onOpenChange(true)\n      clearOpenTimer()\n    }, 100)\n  }\n}\n\nasync function handlePointerLeave(event: PointerEvent) {\n  if (!isMouseEvent(event))\n    return\n  clearOpenTimer()\n\n  const contentRect = menuContext.content.value?.getBoundingClientRect()\n  if (contentRect?.width) {\n    // TODO (Radix UI): make sure to update this when we change positioning logic\n    // https://github.com/radix-ui/primitives/blob/main/packages/react/menu/src/Menu.tsx#L1088\n    const side = menuContext.content.value?.dataset.side as Side\n\n    const rightSide = side === 'right'\n    const bleed = rightSide ? -5 : +5\n    const contentNearEdge = contentRect[rightSide ? 'left' : 'right']\n    const contentFarEdge = contentRect[rightSide ? 'right' : 'left']\n\n    contentContext.onPointerGraceIntentChange({\n      area: [\n        // Apply a bleed on clientX to ensure that our exit point is\n        // consistently within polygon bounds\n        { x: event.clientX + bleed, y: event.clientY },\n        { x: contentNearEdge, y: contentRect.top },\n        { x: contentFarEdge, y: contentRect.top },\n        { x: contentFarEdge, y: contentRect.bottom },\n        { x: contentNearEdge, y: contentRect.bottom },\n      ],\n      side,\n    })\n\n    window.clearTimeout(contentContext.pointerGraceTimerRef.value)\n    contentContext.pointerGraceTimerRef.value = window.setTimeout(\n      () => contentContext.onPointerGraceIntentChange(null),\n      300,\n    )\n  }\n  else {\n    const defaultPrevented = contentContext.onTriggerLeave(event)\n    if (defaultPrevented)\n      return\n\n    // There's 100ms where the user may leave an item before the submenu was opened.\n    contentContext.onPointerGraceIntentChange(null)\n  }\n}\n\nasync function handleKeyDown(event: KeyboardEvent) {\n  const isTypingAhead = contentContext.searchRef.value !== ''\n  if (props.disabled || (isTypingAhead && event.key === ' '))\n    return\n  if (SUB_OPEN_KEYS[rootContext.dir.value].includes(event.key)) {\n    menuContext.onOpenChange(true)\n\n    await nextTick()\n    // The trigger may hold focus if opened via pointer interaction\n    // so we ensure content is given focus again when switching to keyboard.\n    menuContext.content.value?.focus()\n    // prevent window from scrolling\n    event.preventDefault()\n  }\n}\n</script>\n\n<template>\n  <MenuAnchor as-child>\n    <MenuItemImpl\n      v-bind=\"props\"\n      :id=\"subContext.triggerId\"\n      :ref=\"\n        (vnode: Element | ComponentPublicInstance | null) => {\n          if (!vnode) return undefined\n          // @ts-ignore\n          subContext?.onTriggerChange(vnode?.$el);\n          return undefined\n        }\n      \"\n      aria-haspopup=\"menu\"\n      :aria-expanded=\"menuContext.open.value\"\n      :aria-controls=\"subContext.contentId\"\n      :data-state=\"getOpenState(menuContext.open.value)\"\n      @click=\"\n        async (event: MouseEvent) => {\n          if (props.disabled || event.defaultPrevented) return;\n          /**\n           * We manually focus because iOS Safari doesn't always focus on click (e.g. buttons)\n           * and we rely heavily on `onFocusOutside` for submenus to close when switching\n           * between separate submenus.\n           */\n          (event.currentTarget as HTMLElement)?.focus();\n          if (!menuContext.open.value) menuContext.onOpenChange(true);\n        }\n      \"\n      @pointermove=\"handlePointerMove\"\n      @pointerleave=\"handlePointerLeave\"\n      @keydown=\"handleKeyDown\"\n    >\n      <slot />\n    </MenuItemImpl>\n  </MenuAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { MenuArrowProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ContextMenuArrowProps extends MenuArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuArrow } from '@/Menu'\n\nconst props = withDefaults(defineProps<ContextMenuArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\n\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuArrow v-bind=\"props\">\n    <slot />\n  </MenuArrow>\n</template>\n","<script lang=\"ts\">\nimport type { MenuArrowProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ContextMenuArrowProps extends MenuArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuArrow } from '@/Menu'\n\nconst props = withDefaults(defineProps<ContextMenuArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\n\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuArrow v-bind=\"props\">\n    <slot />\n  </MenuArrow>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuCheckboxItemEmits,\n  MenuCheckboxItemProps,\n} from '@/Menu'\n\nexport type ContextMenuCheckboxItemEmits = MenuCheckboxItemEmits\n\nexport interface ContextMenuCheckboxItemProps extends MenuCheckboxItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuCheckboxItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<ContextMenuCheckboxItemProps>()\nconst emits = defineEmits<ContextMenuCheckboxItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuCheckboxItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuCheckboxItem>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuCheckboxItemEmits,\n  MenuCheckboxItemProps,\n} from '@/Menu'\n\nexport type ContextMenuCheckboxItemEmits = MenuCheckboxItemEmits\n\nexport interface ContextMenuCheckboxItemProps extends MenuCheckboxItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuCheckboxItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<ContextMenuCheckboxItemProps>()\nconst emits = defineEmits<ContextMenuCheckboxItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuCheckboxItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuCheckboxItem>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { MenuEmits, MenuProps } from '@/Menu'\nimport type { Direction } from '@/shared/types'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\ntype ContextMenuRootContext = {\n  open: Ref<boolean>\n  onOpenChange: (open: boolean) => void\n  modal: Ref<boolean>\n  dir: Ref<Direction>\n  triggerElement: Ref<HTMLElement | undefined>\n  pressOpenDelay: Ref<number>\n}\n\nexport interface ContextMenuRootProps extends Omit<MenuProps, 'open'> {\n  /**\n   * The duration from when the trigger is pressed until the menu opens.\n   *\n   * @defaultValue 700\n   */\n  pressOpenDelay?: number\n}\nexport type ContextMenuRootEmits = MenuEmits\n\nexport const [injectContextMenuRootContext, provideContextMenuRootContext]\n  = createContext<ContextMenuRootContext>('ContextMenuRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { ref, toRefs, watch } from 'vue'\nimport { MenuRoot } from '@/Menu'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ContextMenuRootProps>(), {\n  modal: true,\n  pressOpenDelay: 700,\n})\nconst emits = defineEmits<ContextMenuRootEmits>()\nconst { dir: propDir, modal, pressOpenDelay } = toRefs(props)\nuseForwardExpose()\nconst dir = useDirection(propDir)\n\nconst open = ref(false)\nconst triggerElement = ref<HTMLElement>()\n\nprovideContextMenuRootContext({\n  open,\n  onOpenChange: (value: boolean) => {\n    open.value = value\n  },\n  dir,\n  modal,\n  triggerElement,\n  pressOpenDelay,\n})\n\nwatch(open, (value) => {\n  emits('update:open', value)\n})\n</script>\n\n<template>\n  <MenuRoot\n    v-model:open=\"open\"\n    :dir=\"dir\"\n    :modal=\"modal\"\n  >\n    <slot />\n  </MenuRoot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { MenuEmits, MenuProps } from '@/Menu'\nimport type { Direction } from '@/shared/types'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\ntype ContextMenuRootContext = {\n  open: Ref<boolean>\n  onOpenChange: (open: boolean) => void\n  modal: Ref<boolean>\n  dir: Ref<Direction>\n  triggerElement: Ref<HTMLElement | undefined>\n  pressOpenDelay: Ref<number>\n}\n\nexport interface ContextMenuRootProps extends Omit<MenuProps, 'open'> {\n  /**\n   * The duration from when the trigger is pressed until the menu opens.\n   *\n   * @defaultValue 700\n   */\n  pressOpenDelay?: number\n}\nexport type ContextMenuRootEmits = MenuEmits\n\nexport const [injectContextMenuRootContext, provideContextMenuRootContext]\n  = createContext<ContextMenuRootContext>('ContextMenuRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { ref, toRefs, watch } from 'vue'\nimport { MenuRoot } from '@/Menu'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ContextMenuRootProps>(), {\n  modal: true,\n  pressOpenDelay: 700,\n})\nconst emits = defineEmits<ContextMenuRootEmits>()\nconst { dir: propDir, modal, pressOpenDelay } = toRefs(props)\nuseForwardExpose()\nconst dir = useDirection(propDir)\n\nconst open = ref(false)\nconst triggerElement = ref<HTMLElement>()\n\nprovideContextMenuRootContext({\n  open,\n  onOpenChange: (value: boolean) => {\n    open.value = value\n  },\n  dir,\n  modal,\n  triggerElement,\n  pressOpenDelay,\n})\n\nwatch(open, (value) => {\n  emits('update:open', value)\n})\n</script>\n\n<template>\n  <MenuRoot\n    v-model:open=\"open\"\n    :dir=\"dir\"\n    :modal=\"modal\"\n  >\n    <slot />\n  </MenuRoot>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuContentEmits,\n  MenuContentProps,\n} from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\n\nexport type ContextMenuContentEmits = MenuContentEmits\n\nexport interface ContextMenuContentProps\n  extends Omit<\n    MenuContentProps,\n    | 'side'\n    | 'sideOffset'\n    | 'align'\n    | 'arrowPadding'\n    | 'updatePositionStrategy'\n  > {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { MenuContent } from '@/Menu'\nimport { injectContextMenuRootContext } from './ContextMenuRoot.vue'\n\nconst props = withDefaults(defineProps<ContextMenuContentProps>(), {\n  alignOffset: 0,\n  avoidCollisions: true,\n  collisionBoundary: () => [],\n  collisionPadding: 0,\n  sticky: 'partial',\n  hideWhenDetached: false,\n})\nconst emits = defineEmits<ContextMenuContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\n\nuseForwardExpose()\nconst rootContext = injectContextMenuRootContext()\nconst hasInteractedOutside = ref(false)\n</script>\n\n<template>\n  <MenuContent\n    v-bind=\"forwarded\"\n    side=\"right\"\n    :side-offset=\"2\"\n    align=\"start\"\n    update-position-strategy=\"always\"\n    :style=\"{\n      '--reka-context-menu-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-context-menu-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-context-menu-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-context-menu-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-context-menu-trigger-height':\n        'var(--reka-popper-anchor-height)',\n    }\"\n    @close-auto-focus=\"\n      (event) => {\n        if (!event.defaultPrevented && hasInteractedOutside) {\n          event.preventDefault();\n        }\n        hasInteractedOutside = false;\n      }\n    \"\n    @interact-outside=\"\n      (event) => {\n        const originalEvent = event.detail.originalEvent as PointerEvent\n        // Prevent closing when right click (button=2) with the trigger element\n        if (originalEvent.button === 2 && event.target === rootContext.triggerElement.value) {\n          event.preventDefault()\n        }\n        if (!event.defaultPrevented && !rootContext.modal.value)\n          hasInteractedOutside = true;\n      }\n    \"\n  >\n    <slot />\n  </MenuContent>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuContentEmits,\n  MenuContentProps,\n} from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\n\nexport type ContextMenuContentEmits = MenuContentEmits\n\nexport interface ContextMenuContentProps\n  extends Omit<\n    MenuContentProps,\n    | 'side'\n    | 'sideOffset'\n    | 'align'\n    | 'arrowPadding'\n    | 'updatePositionStrategy'\n  > {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { MenuContent } from '@/Menu'\nimport { injectContextMenuRootContext } from './ContextMenuRoot.vue'\n\nconst props = withDefaults(defineProps<ContextMenuContentProps>(), {\n  alignOffset: 0,\n  avoidCollisions: true,\n  collisionBoundary: () => [],\n  collisionPadding: 0,\n  sticky: 'partial',\n  hideWhenDetached: false,\n})\nconst emits = defineEmits<ContextMenuContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\n\nuseForwardExpose()\nconst rootContext = injectContextMenuRootContext()\nconst hasInteractedOutside = ref(false)\n</script>\n\n<template>\n  <MenuContent\n    v-bind=\"forwarded\"\n    side=\"right\"\n    :side-offset=\"2\"\n    align=\"start\"\n    update-position-strategy=\"always\"\n    :style=\"{\n      '--reka-context-menu-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-context-menu-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-context-menu-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-context-menu-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-context-menu-trigger-height':\n        'var(--reka-popper-anchor-height)',\n    }\"\n    @close-auto-focus=\"\n      (event) => {\n        if (!event.defaultPrevented && hasInteractedOutside) {\n          event.preventDefault();\n        }\n        hasInteractedOutside = false;\n      }\n    \"\n    @interact-outside=\"\n      (event) => {\n        const originalEvent = event.detail.originalEvent as PointerEvent\n        // Prevent closing when right click (button=2) with the trigger element\n        if (originalEvent.button === 2 && event.target === rootContext.triggerElement.value) {\n          event.preventDefault()\n        }\n        if (!event.defaultPrevented && !rootContext.modal.value)\n          hasInteractedOutside = true;\n      }\n    \"\n  >\n    <slot />\n  </MenuContent>\n</template>\n","<script lang=\"ts\">\nimport type { MenuGroupProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ContextMenuGroupProps extends MenuGroupProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuGroup } from '@/Menu'\n\nconst props = defineProps<ContextMenuGroupProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuGroup v-bind=\"props\">\n    <slot />\n  </MenuGroup>\n</template>\n","<script lang=\"ts\">\nimport type { MenuGroupProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ContextMenuGroupProps extends MenuGroupProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuGroup } from '@/Menu'\n\nconst props = defineProps<ContextMenuGroupProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuGroup v-bind=\"props\">\n    <slot />\n  </MenuGroup>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemEmits, MenuItemProps } from '@/Menu'\n\nexport type ContextMenuItemEmits = MenuItemEmits\n\nexport interface ContextMenuItemProps extends MenuItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<MenuItemProps>()\nconst emits = defineEmits<MenuItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuItem>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemEmits, MenuItemProps } from '@/Menu'\n\nexport type ContextMenuItemEmits = MenuItemEmits\n\nexport interface ContextMenuItemProps extends MenuItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<MenuItemProps>()\nconst emits = defineEmits<MenuItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuItem>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemIndicatorProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ContextMenuItemIndicatorProps extends MenuItemIndicatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuItemIndicator } from '@/Menu'\n\nconst props = defineProps<ContextMenuItemIndicatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuItemIndicator v-bind=\"props\">\n    <slot />\n  </MenuItemIndicator>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemIndicatorProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ContextMenuItemIndicatorProps extends MenuItemIndicatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuItemIndicator } from '@/Menu'\n\nconst props = defineProps<ContextMenuItemIndicatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuItemIndicator v-bind=\"props\">\n    <slot />\n  </MenuItemIndicator>\n</template>\n","<script lang=\"ts\">\nimport type { MenuLabelProps } from '@/Menu'\n\nexport interface ContextMenuLabelProps extends MenuLabelProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuLabel } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = defineProps<ContextMenuLabelProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuLabel v-bind=\"props\">\n    <slot />\n  </MenuLabel>\n</template>\n","<script lang=\"ts\">\nimport type { MenuLabelProps } from '@/Menu'\n\nexport interface ContextMenuLabelProps extends MenuLabelProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuLabel } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = defineProps<ContextMenuLabelProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuLabel v-bind=\"props\">\n    <slot />\n  </MenuLabel>\n</template>\n","<script setup lang=\"ts\">\nimport type { MenuPortalProps } from '@/Menu'\nimport { MenuPortal } from '@/Menu'\n\nexport interface ContextMenuPortalProps extends MenuPortalProps {}\nconst props = defineProps<ContextMenuPortalProps>()\n</script>\n\n<template>\n  <MenuPortal v-bind=\"props\">\n    <slot />\n  </MenuPortal>\n</template>\n","<script setup lang=\"ts\">\nimport type { MenuPortalProps } from '@/Menu'\nimport { MenuPortal } from '@/Menu'\n\nexport interface ContextMenuPortalProps extends MenuPortalProps {}\nconst props = defineProps<ContextMenuPortalProps>()\n</script>\n\n<template>\n  <MenuPortal v-bind=\"props\">\n    <slot />\n  </MenuPortal>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuRadioGroupEmits,\n  MenuRadioGroupProps,\n} from '@/Menu'\n\nexport type ContextMenuRadioGroupEmits = MenuRadioGroupEmits\n\nexport interface ContextMenuRadioGroupProps extends MenuRadioGroupProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuRadioGroup } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<ContextMenuRadioGroupProps>()\nconst emits = defineEmits<ContextMenuRadioGroupEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuRadioGroup v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuRadioGroup>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuRadioGroupEmits,\n  MenuRadioGroupProps,\n} from '@/Menu'\n\nexport type ContextMenuRadioGroupEmits = MenuRadioGroupEmits\n\nexport interface ContextMenuRadioGroupProps extends MenuRadioGroupProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuRadioGroup } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<ContextMenuRadioGroupProps>()\nconst emits = defineEmits<ContextMenuRadioGroupEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuRadioGroup v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuRadioGroup>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuItemEmits,\n  MenuRadioItemProps,\n} from '@/Menu'\n\nexport type ContextMenuRadioItemEmits = MenuItemEmits\n\nexport interface ContextMenuRadioItemProps extends MenuRadioItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuRadioItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<ContextMenuRadioItemProps>()\nconst emits = defineEmits<ContextMenuRadioItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuRadioItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuRadioItem>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuItemEmits,\n  MenuRadioItemProps,\n} from '@/Menu'\n\nexport type ContextMenuRadioItemEmits = MenuItemEmits\n\nexport interface ContextMenuRadioItemProps extends MenuRadioItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuRadioItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<ContextMenuRadioItemProps>()\nconst emits = defineEmits<ContextMenuRadioItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuRadioItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuRadioItem>\n</template>\n","<script lang=\"ts\">\nimport type { MenuSeparatorProps } from '@/Menu'\n\nexport interface ContextMenuSeparatorProps extends MenuSeparatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSeparator } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = defineProps<ContextMenuSeparatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSeparator v-bind=\"props\">\n    <slot />\n  </MenuSeparator>\n</template>\n","<script lang=\"ts\">\nimport type { MenuSeparatorProps } from '@/Menu'\n\nexport interface ContextMenuSeparatorProps extends MenuSeparatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSeparator } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = defineProps<ContextMenuSeparatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSeparator v-bind=\"props\">\n    <slot />\n  </MenuSeparator>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { MenuSubEmits, MenuSubProps } from '@/Menu'\n\nexport type ContextMenuSubEmits = MenuSubEmits\nexport interface ContextMenuSubProps extends MenuSubProps {\n  /** The open state of the submenu when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { MenuSub } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = withDefaults(defineProps<ContextMenuSubProps>(), {\n  open: undefined,\n})\nconst emit = defineEmits<ContextMenuSubEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nuseForwardExpose()\n\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n</script>\n\n<template>\n  <MenuSub v-model:open=\"open\">\n    <slot :open=\"open\" />\n  </MenuSub>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { MenuSubEmits, MenuSubProps } from '@/Menu'\n\nexport type ContextMenuSubEmits = MenuSubEmits\nexport interface ContextMenuSubProps extends MenuSubProps {\n  /** The open state of the submenu when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { MenuSub } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = withDefaults(defineProps<ContextMenuSubProps>(), {\n  open: undefined,\n})\nconst emit = defineEmits<ContextMenuSubEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nuseForwardExpose()\n\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n</script>\n\n<template>\n  <MenuSub v-model:open=\"open\">\n    <slot :open=\"open\" />\n  </MenuSub>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuSubContentEmits,\n  MenuSubContentProps,\n} from '@/Menu'\n\nexport type ContextMenuSubContentEmits = MenuSubContentEmits\nexport interface ContextMenuSubContentProps extends MenuSubContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSubContent } from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\n\nconst props = defineProps<ContextMenuSubContentProps>()\n\nconst emits = defineEmits<ContextMenuSubContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSubContent\n    v-bind=\"forwarded\"\n    :style=\"{\n      '--reka-context-menu-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-context-menu-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-context-menu-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-context-menu-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-context-menu-trigger-height':\n        'var(--reka-popper-anchor-height)',\n    }\"\n  >\n    <slot />\n  </MenuSubContent>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuSubContentEmits,\n  MenuSubContentProps,\n} from '@/Menu'\n\nexport type ContextMenuSubContentEmits = MenuSubContentEmits\nexport interface ContextMenuSubContentProps extends MenuSubContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSubContent } from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\n\nconst props = defineProps<ContextMenuSubContentProps>()\n\nconst emits = defineEmits<ContextMenuSubContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSubContent\n    v-bind=\"forwarded\"\n    :style=\"{\n      '--reka-context-menu-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-context-menu-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-context-menu-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-context-menu-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-context-menu-trigger-height':\n        'var(--reka-popper-anchor-height)',\n    }\"\n  >\n    <slot />\n  </MenuSubContent>\n</template>\n","<script lang=\"ts\">\nimport type { MenuSubTriggerProps } from '@/Menu'\n\nexport interface ContextMenuSubTriggerProps extends MenuSubTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSubTrigger } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = defineProps<ContextMenuSubTriggerProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSubTrigger v-bind=\"props\">\n    <slot />\n  </MenuSubTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { MenuSubTriggerProps } from '@/Menu'\n\nexport interface ContextMenuSubTriggerProps extends MenuSubTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSubTrigger } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = defineProps<ContextMenuSubTriggerProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSubTrigger v-bind=\"props\">\n    <slot />\n  </MenuSubTrigger>\n</template>\n","export function isTouchOrPen(event: PointerEvent) {\n  return event.pointerType !== 'mouse'\n}\n","<script lang=\"ts\">\nimport type { Point } from '@/Menu/utils'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ContextMenuTriggerProps extends PrimitiveProps {\n  /**\n   * When `true`, the context menu would not open when right-clicking.\n   *\n   * Note that this will also restore the native context menu.\n   */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, nextTick, onMounted, ref, toRefs } from 'vue'\nimport { MenuAnchor } from '@/Menu'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectContextMenuRootContext } from './ContextMenuRoot.vue'\nimport { isTouchOrPen } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ContextMenuTriggerProps>(), {\n  as: 'span',\n  disabled: false,\n})\nconst { disabled } = toRefs(props)\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst rootContext = injectContextMenuRootContext()\nconst point = ref<Point>({ x: 0, y: 0 })\nconst virtualEl = computed(() => ({\n  getBoundingClientRect: () =>\n    ({\n      width: 0,\n      height: 0,\n      left: point.value.x,\n      right: point.value.x,\n      top: point.value.y,\n      bottom: point.value.y,\n      ...point.value,\n    } as DOMRect),\n}))\n\nconst longPressTimer = ref(0)\nfunction clearLongPress() {\n  window.clearTimeout(longPressTimer.value)\n}\n\nfunction handleOpen(event: MouseEvent | PointerEvent) {\n  point.value = { x: event.clientX, y: event.clientY }\n  rootContext.onOpenChange(true)\n}\n\nasync function handleContextMenu(event: PointerEvent) {\n  if (!disabled.value) {\n    await nextTick()\n    if (!event.defaultPrevented) {\n      clearLongPress()\n      handleOpen(event)\n      event.preventDefault()\n    }\n  }\n}\n\nasync function handlePointerDown(event: PointerEvent) {\n  if (!disabled.value) {\n    await nextTick()\n\n    if (isTouchOrPen(event) && !event.defaultPrevented) {\n      // clear the long press here in case there's multiple touch points\n      clearLongPress()\n      longPressTimer.value = window.setTimeout(handleOpen, rootContext.pressOpenDelay.value, event)\n    }\n  }\n}\n\nasync function handlePointerEvent(event: PointerEvent) {\n  if (!disabled.value) {\n    await nextTick()\n    if (isTouchOrPen(event) && !event.defaultPrevented)\n      clearLongPress()\n  }\n}\n\nonMounted(() => {\n  if (currentElement.value) {\n    rootContext.triggerElement.value = currentElement.value\n  }\n})\n</script>\n\n<template>\n  <MenuAnchor\n    as=\"template\"\n    :reference=\"virtualEl\"\n  />\n\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :style=\"{\n      WebkitTouchCallout: 'none',\n      pointerEvents: 'auto',\n    }\"\n    v-bind=\"$attrs\"\n    @contextmenu=\"handleContextMenu\"\n    @pointerdown=\"handlePointerDown\"\n    @pointermove=\"handlePointerEvent\"\n    @pointercancel=\"handlePointerEvent\"\n    @pointerup=\"handlePointerEvent\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Point } from '@/Menu/utils'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ContextMenuTriggerProps extends PrimitiveProps {\n  /**\n   * When `true`, the context menu would not open when right-clicking.\n   *\n   * Note that this will also restore the native context menu.\n   */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, nextTick, onMounted, ref, toRefs } from 'vue'\nimport { MenuAnchor } from '@/Menu'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectContextMenuRootContext } from './ContextMenuRoot.vue'\nimport { isTouchOrPen } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ContextMenuTriggerProps>(), {\n  as: 'span',\n  disabled: false,\n})\nconst { disabled } = toRefs(props)\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst rootContext = injectContextMenuRootContext()\nconst point = ref<Point>({ x: 0, y: 0 })\nconst virtualEl = computed(() => ({\n  getBoundingClientRect: () =>\n    ({\n      width: 0,\n      height: 0,\n      left: point.value.x,\n      right: point.value.x,\n      top: point.value.y,\n      bottom: point.value.y,\n      ...point.value,\n    } as DOMRect),\n}))\n\nconst longPressTimer = ref(0)\nfunction clearLongPress() {\n  window.clearTimeout(longPressTimer.value)\n}\n\nfunction handleOpen(event: MouseEvent | PointerEvent) {\n  point.value = { x: event.clientX, y: event.clientY }\n  rootContext.onOpenChange(true)\n}\n\nasync function handleContextMenu(event: PointerEvent) {\n  if (!disabled.value) {\n    await nextTick()\n    if (!event.defaultPrevented) {\n      clearLongPress()\n      handleOpen(event)\n      event.preventDefault()\n    }\n  }\n}\n\nasync function handlePointerDown(event: PointerEvent) {\n  if (!disabled.value) {\n    await nextTick()\n\n    if (isTouchOrPen(event) && !event.defaultPrevented) {\n      // clear the long press here in case there's multiple touch points\n      clearLongPress()\n      longPressTimer.value = window.setTimeout(handleOpen, rootContext.pressOpenDelay.value, event)\n    }\n  }\n}\n\nasync function handlePointerEvent(event: PointerEvent) {\n  if (!disabled.value) {\n    await nextTick()\n    if (isTouchOrPen(event) && !event.defaultPrevented)\n      clearLongPress()\n  }\n}\n\nonMounted(() => {\n  if (currentElement.value) {\n    rootContext.triggerElement.value = currentElement.value\n  }\n})\n</script>\n\n<template>\n  <MenuAnchor\n    as=\"template\"\n    :reference=\"virtualEl\"\n  />\n\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :style=\"{\n      WebkitTouchCallout: 'none',\n      pointerEvents: 'auto',\n    }\"\n    v-bind=\"$attrs\"\n    @contextmenu=\"handleContextMenu\"\n    @pointerdown=\"handlePointerDown\"\n    @pointermove=\"handlePointerEvent\"\n    @pointercancel=\"handlePointerEvent\"\n    @pointerup=\"handlePointerEvent\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Matcher } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { DateStep, Formatter } from '@/shared'\nimport type { Granularity, HourCycle, SegmentPart, SegmentValueObj } from '@/shared/date'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport { hasTime, isBefore } from '@/date'\nimport { createContext, isNullish, useDateFormatter, useDirection, useKbd, useLocale } from '@/shared'\nimport {\n  createContent,\n  getDefaultDate,\n  getInputType,\n  getSegmentElements,\n  initializeSegmentValues,\n  isSegmentNavigationKey,\n  normalizeDateStep,\n  normalizeHourCycle,\n  normalizeInputValue,\n  syncSegmentValues,\n} from '@/shared/date'\n\ntype DateFieldRootContext = {\n  locale: Ref<string>\n  modelValue: Ref<DateValue | undefined>\n  placeholder: Ref<DateValue>\n  isDateUnavailable?: Matcher\n  isInvalid: Ref<boolean>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  formatter: Formatter\n  hourCycle: HourCycle\n  step: Ref<DateStep>\n  segmentValues: Ref<SegmentValueObj>\n  segmentContents: Ref<{ part: SegmentPart, value: string }[]>\n  elements: Ref<Set<HTMLElement>>\n  focusNext: () => void\n  setFocusedElement: (el: HTMLElement) => void\n}\n\nexport interface DateFieldRootProps extends PrimitiveProps, FormFieldProps {\n  /** The default value for the calendar */\n  defaultValue?: DateValue\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The placeholder date, which is used to determine what month to display when no date is selected. This updates as the user navigates the calendar and can be used to programmatically control the calendar view */\n  placeholder?: DateValue\n  /** The controlled value of the field. Can be bound as `v-model`. */\n  modelValue?: DateValue | null\n  /** The hour cycle used for formatting times. Defaults to the local preference */\n  hourCycle?: HourCycle\n  /** The stepping interval for the time fields. Defaults to `1`. */\n  step?: DateStep\n  /** The granularity to use for formatting times. Defaults to day if a CalendarDate is provided, otherwise defaults to minute. The field will render segments for each part of the date up to and including the specified granularity */\n  granularity?: Granularity\n  /** Whether or not to hide the time zone segment of the field */\n  hideTimeZone?: boolean\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether or not the date field is disabled */\n  disabled?: boolean\n  /** Whether or not the date field is readonly */\n  readonly?: boolean\n  /** A function that returns whether or not a date is unavailable */\n  isDateUnavailable?: Matcher\n  /** Id of the element */\n  id?: string\n  /** The reading direction of the date field when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n}\n\nexport type DateFieldRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateValue | undefined]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n}\n\nexport const [injectDateFieldRootContext, provideDateFieldRootContext]\n  = createContext<DateFieldRootContext>('DateFieldRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { VisuallyHidden } from '@/VisuallyHidden'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<DateFieldRootProps>(), {\n  defaultValue: undefined,\n  disabled: false,\n  readonly: false,\n  placeholder: undefined,\n  isDateUnavailable: undefined,\n})\nconst emits = defineEmits<DateFieldRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the field */\n    modelValue: DateValue | undefined\n    /** The date field segment contents */\n    segments: { part: SegmentPart, value: string }[]\n    /** Value if the input is invalid */\n    isInvalid: boolean\n  }) => any\n}>()\n\nconst { disabled, readonly, isDateUnavailable: propsIsDateUnavailable, granularity, defaultValue, dir: propDir, locale: propLocale } = toRefs(props)\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\n\nconst formatter = useDateFormatter(locale.value, {\n  hourCycle: normalizeHourCycle(props.hourCycle),\n})\nconst { primitiveElement, currentElement: parentElement }\n  = usePrimitiveElement()\nconst segmentElements = ref<Set<HTMLElement>>(new Set())\n\nonMounted(() => {\n  getSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n})\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateValue>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  granularity: granularity.value,\n  defaultValue: modelValue.value,\n  locale: props.locale,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nconst step = computed(() => normalizeDateStep(props))\n\nconst inferredGranularity = computed(() => {\n  if (props.granularity)\n    return !hasTime(placeholder.value) ? 'day' : props.granularity\n\n  return hasTime(placeholder.value) ? 'minute' : 'day'\n})\n\nconst isInvalid = computed(() => {\n  if (!modelValue.value)\n    return false\n\n  if (propsIsDateUnavailable.value?.(modelValue.value))\n    return true\n\n  if (props.minValue && isBefore(modelValue.value, props.minValue))\n    return true\n\n  if (props.maxValue && isBefore(props.maxValue, modelValue.value))\n    return true\n\n  return false\n})\n\nconst initialSegments = initializeSegmentValues(inferredGranularity.value)\n\nconst segmentValues = ref<SegmentValueObj>(modelValue.value ? { ...syncSegmentValues({ value: modelValue.value, formatter }) } : { ...initialSegments })\n\nconst allSegmentContent = computed(() => createContent({\n  granularity: inferredGranularity.value,\n  dateRef: placeholder.value,\n  formatter,\n  hideTimeZone: props.hideTimeZone,\n  hourCycle: props.hourCycle,\n  segmentValues: segmentValues.value,\n  locale,\n}))\n\nconst segmentContents = computed(() => allSegmentContent.value.arr)\n\nconst editableSegmentContents = computed(() => segmentContents.value.filter(({ part }) => part !== 'literal'))\n\nwatch(locale, (value) => {\n  if (formatter.getLocale() !== value) {\n    formatter.setLocale(value)\n    // Locale changed, so we need to clear the segment elements and re-get them (different order)\n    // Get the focusable elements again on the next tick\n    nextTick(() => {\n      segmentElements.value.clear()\n      getSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n    })\n  }\n})\n\nwatch(modelValue, (_modelValue) => {\n  if (!isNullish(_modelValue) && placeholder.value.compare(_modelValue) !== 0) {\n    placeholder.value = _modelValue.copy()\n  }\n})\n\nwatch([modelValue, locale], ([_modelValue]) => {\n  if (!isNullish(_modelValue)) {\n    segmentValues.value = { ...syncSegmentValues({ value: _modelValue, formatter }) }\n  }\n  // If segment has null value, means that user modified it, thus do not reset the segmentValues\n  else if (Object.values(segmentValues.value).every(value => value !== null) && isNullish(_modelValue)) {\n    segmentValues.value = { ...initialSegments }\n  }\n})\n\nconst currentFocusedElement = ref<HTMLElement | null>(null)\n\nconst currentSegmentIndex = computed(() =>\n  Array.from(segmentElements.value).findIndex(el =>\n    el.getAttribute('data-reka-date-field-segment')\n    === currentFocusedElement.value?.getAttribute('data-reka-date-field-segment')))\n\nconst nextFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const nextCondition = sign < 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (nextCondition)\n    return null\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value + sign]\n  return segmentToFocus\n})\n\nconst prevFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const prevCondition = sign > 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (prevCondition)\n    return null\n\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value - sign]\n  return segmentToFocus\n})\n\nconst inputType = computed(() => getInputType(inferredGranularity.value))\nconst inputValue = computed(() => normalizeInputValue(modelValue.value, inferredGranularity.value))\nconst inputMaxValue = computed(() => props.maxValue ? normalizeInputValue(props.maxValue, inferredGranularity.value) : undefined)\nconst inputMinValue = computed(() => props.minValue ? normalizeInputValue(props.minValue, inferredGranularity.value) : undefined)\n\nconst kbd = useKbd()\n\nfunction handleKeydown(e: KeyboardEvent) {\n  // Don't navigate between segments mid-composition, arrow keys are used for IME candidate navigation\n  if (e.isComposing)\n    return\n  if (!isSegmentNavigationKey(e.key))\n    return\n  if (e.key === kbd.ARROW_LEFT)\n    prevFocusableSegment.value?.focus()\n  if (e.key === kbd.ARROW_RIGHT)\n    nextFocusableSegment.value?.focus()\n}\n\nfunction setFocusedElement(el: HTMLElement) {\n  currentFocusedElement.value = el\n}\n\nprovideDateFieldRootContext({\n  isDateUnavailable: propsIsDateUnavailable.value,\n  locale,\n  modelValue,\n  placeholder,\n  disabled,\n  formatter,\n  hourCycle: props.hourCycle,\n  step,\n  readonly,\n  segmentValues,\n  isInvalid,\n  segmentContents: editableSegmentContents,\n  elements: segmentElements,\n  setFocusedElement,\n  focusNext() {\n    nextFocusableSegment.value?.focus()\n  },\n})\n\ndefineExpose({\n  /** Helper to set the focused element inside the DateField */\n  setFocusedElement,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    ref=\"primitiveElement\"\n    role=\"group\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n    @keydown.left.right=\"handleKeydown\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :segments=\"segmentContents\"\n      :is-invalid=\"isInvalid\"\n    />\n\n    <VisuallyHidden\n      :id=\"id\"\n      as=\"input\"\n      :type=\"inputType\"\n      feature=\"focusable\"\n      tabindex=\"-1\"\n      :value=\"inputValue\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n      :max=\"inputMaxValue\"\n      :min=\"inputMinValue\"\n      @focus=\"Array.from(segmentElements)?.[0]?.focus()\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Matcher } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { DateStep, Formatter } from '@/shared'\nimport type { Granularity, HourCycle, SegmentPart, SegmentValueObj } from '@/shared/date'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport { hasTime, isBefore } from '@/date'\nimport { createContext, isNullish, useDateFormatter, useDirection, useKbd, useLocale } from '@/shared'\nimport {\n  createContent,\n  getDefaultDate,\n  getInputType,\n  getSegmentElements,\n  initializeSegmentValues,\n  isSegmentNavigationKey,\n  normalizeDateStep,\n  normalizeHourCycle,\n  normalizeInputValue,\n  syncSegmentValues,\n} from '@/shared/date'\n\ntype DateFieldRootContext = {\n  locale: Ref<string>\n  modelValue: Ref<DateValue | undefined>\n  placeholder: Ref<DateValue>\n  isDateUnavailable?: Matcher\n  isInvalid: Ref<boolean>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  formatter: Formatter\n  hourCycle: HourCycle\n  step: Ref<DateStep>\n  segmentValues: Ref<SegmentValueObj>\n  segmentContents: Ref<{ part: SegmentPart, value: string }[]>\n  elements: Ref<Set<HTMLElement>>\n  focusNext: () => void\n  setFocusedElement: (el: HTMLElement) => void\n}\n\nexport interface DateFieldRootProps extends PrimitiveProps, FormFieldProps {\n  /** The default value for the calendar */\n  defaultValue?: DateValue\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The placeholder date, which is used to determine what month to display when no date is selected. This updates as the user navigates the calendar and can be used to programmatically control the calendar view */\n  placeholder?: DateValue\n  /** The controlled value of the field. Can be bound as `v-model`. */\n  modelValue?: DateValue | null\n  /** The hour cycle used for formatting times. Defaults to the local preference */\n  hourCycle?: HourCycle\n  /** The stepping interval for the time fields. Defaults to `1`. */\n  step?: DateStep\n  /** The granularity to use for formatting times. Defaults to day if a CalendarDate is provided, otherwise defaults to minute. The field will render segments for each part of the date up to and including the specified granularity */\n  granularity?: Granularity\n  /** Whether or not to hide the time zone segment of the field */\n  hideTimeZone?: boolean\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether or not the date field is disabled */\n  disabled?: boolean\n  /** Whether or not the date field is readonly */\n  readonly?: boolean\n  /** A function that returns whether or not a date is unavailable */\n  isDateUnavailable?: Matcher\n  /** Id of the element */\n  id?: string\n  /** The reading direction of the date field when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n}\n\nexport type DateFieldRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateValue | undefined]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n}\n\nexport const [injectDateFieldRootContext, provideDateFieldRootContext]\n  = createContext<DateFieldRootContext>('DateFieldRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { VisuallyHidden } from '@/VisuallyHidden'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<DateFieldRootProps>(), {\n  defaultValue: undefined,\n  disabled: false,\n  readonly: false,\n  placeholder: undefined,\n  isDateUnavailable: undefined,\n})\nconst emits = defineEmits<DateFieldRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the field */\n    modelValue: DateValue | undefined\n    /** The date field segment contents */\n    segments: { part: SegmentPart, value: string }[]\n    /** Value if the input is invalid */\n    isInvalid: boolean\n  }) => any\n}>()\n\nconst { disabled, readonly, isDateUnavailable: propsIsDateUnavailable, granularity, defaultValue, dir: propDir, locale: propLocale } = toRefs(props)\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\n\nconst formatter = useDateFormatter(locale.value, {\n  hourCycle: normalizeHourCycle(props.hourCycle),\n})\nconst { primitiveElement, currentElement: parentElement }\n  = usePrimitiveElement()\nconst segmentElements = ref<Set<HTMLElement>>(new Set())\n\nonMounted(() => {\n  getSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n})\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateValue>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  granularity: granularity.value,\n  defaultValue: modelValue.value,\n  locale: props.locale,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nconst step = computed(() => normalizeDateStep(props))\n\nconst inferredGranularity = computed(() => {\n  if (props.granularity)\n    return !hasTime(placeholder.value) ? 'day' : props.granularity\n\n  return hasTime(placeholder.value) ? 'minute' : 'day'\n})\n\nconst isInvalid = computed(() => {\n  if (!modelValue.value)\n    return false\n\n  if (propsIsDateUnavailable.value?.(modelValue.value))\n    return true\n\n  if (props.minValue && isBefore(modelValue.value, props.minValue))\n    return true\n\n  if (props.maxValue && isBefore(props.maxValue, modelValue.value))\n    return true\n\n  return false\n})\n\nconst initialSegments = initializeSegmentValues(inferredGranularity.value)\n\nconst segmentValues = ref<SegmentValueObj>(modelValue.value ? { ...syncSegmentValues({ value: modelValue.value, formatter }) } : { ...initialSegments })\n\nconst allSegmentContent = computed(() => createContent({\n  granularity: inferredGranularity.value,\n  dateRef: placeholder.value,\n  formatter,\n  hideTimeZone: props.hideTimeZone,\n  hourCycle: props.hourCycle,\n  segmentValues: segmentValues.value,\n  locale,\n}))\n\nconst segmentContents = computed(() => allSegmentContent.value.arr)\n\nconst editableSegmentContents = computed(() => segmentContents.value.filter(({ part }) => part !== 'literal'))\n\nwatch(locale, (value) => {\n  if (formatter.getLocale() !== value) {\n    formatter.setLocale(value)\n    // Locale changed, so we need to clear the segment elements and re-get them (different order)\n    // Get the focusable elements again on the next tick\n    nextTick(() => {\n      segmentElements.value.clear()\n      getSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n    })\n  }\n})\n\nwatch(modelValue, (_modelValue) => {\n  if (!isNullish(_modelValue) && placeholder.value.compare(_modelValue) !== 0) {\n    placeholder.value = _modelValue.copy()\n  }\n})\n\nwatch([modelValue, locale], ([_modelValue]) => {\n  if (!isNullish(_modelValue)) {\n    segmentValues.value = { ...syncSegmentValues({ value: _modelValue, formatter }) }\n  }\n  // If segment has null value, means that user modified it, thus do not reset the segmentValues\n  else if (Object.values(segmentValues.value).every(value => value !== null) && isNullish(_modelValue)) {\n    segmentValues.value = { ...initialSegments }\n  }\n})\n\nconst currentFocusedElement = ref<HTMLElement | null>(null)\n\nconst currentSegmentIndex = computed(() =>\n  Array.from(segmentElements.value).findIndex(el =>\n    el.getAttribute('data-reka-date-field-segment')\n    === currentFocusedElement.value?.getAttribute('data-reka-date-field-segment')))\n\nconst nextFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const nextCondition = sign < 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (nextCondition)\n    return null\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value + sign]\n  return segmentToFocus\n})\n\nconst prevFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const prevCondition = sign > 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (prevCondition)\n    return null\n\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value - sign]\n  return segmentToFocus\n})\n\nconst inputType = computed(() => getInputType(inferredGranularity.value))\nconst inputValue = computed(() => normalizeInputValue(modelValue.value, inferredGranularity.value))\nconst inputMaxValue = computed(() => props.maxValue ? normalizeInputValue(props.maxValue, inferredGranularity.value) : undefined)\nconst inputMinValue = computed(() => props.minValue ? normalizeInputValue(props.minValue, inferredGranularity.value) : undefined)\n\nconst kbd = useKbd()\n\nfunction handleKeydown(e: KeyboardEvent) {\n  // Don't navigate between segments mid-composition, arrow keys are used for IME candidate navigation\n  if (e.isComposing)\n    return\n  if (!isSegmentNavigationKey(e.key))\n    return\n  if (e.key === kbd.ARROW_LEFT)\n    prevFocusableSegment.value?.focus()\n  if (e.key === kbd.ARROW_RIGHT)\n    nextFocusableSegment.value?.focus()\n}\n\nfunction setFocusedElement(el: HTMLElement) {\n  currentFocusedElement.value = el\n}\n\nprovideDateFieldRootContext({\n  isDateUnavailable: propsIsDateUnavailable.value,\n  locale,\n  modelValue,\n  placeholder,\n  disabled,\n  formatter,\n  hourCycle: props.hourCycle,\n  step,\n  readonly,\n  segmentValues,\n  isInvalid,\n  segmentContents: editableSegmentContents,\n  elements: segmentElements,\n  setFocusedElement,\n  focusNext() {\n    nextFocusableSegment.value?.focus()\n  },\n})\n\ndefineExpose({\n  /** Helper to set the focused element inside the DateField */\n  setFocusedElement,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    ref=\"primitiveElement\"\n    role=\"group\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n    @keydown.left.right=\"handleKeydown\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :segments=\"segmentContents\"\n      :is-invalid=\"isInvalid\"\n    />\n\n    <VisuallyHidden\n      :id=\"id\"\n      as=\"input\"\n      :type=\"inputType\"\n      feature=\"focusable\"\n      tabindex=\"-1\"\n      :value=\"inputValue\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n      :max=\"inputMaxValue\"\n      :min=\"inputMinValue\"\n      @focus=\"Array.from(segmentElements)?.[0]?.focus()\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { SegmentPart } from '@/shared/date'\nimport { computed, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useDateField } from '@/shared/date/useDateField'\nimport { injectDateFieldRootContext } from './DateFieldRoot.vue'\n\nexport interface DateFieldInputProps extends PrimitiveProps {\n  /** The part of the date to render */\n  part: SegmentPart\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateFieldInputProps>()\n\nconst rootContext = injectDateFieldRootContext()\n\nconst hasLeftFocus = ref(true)\nconst lastKeyZero = ref(false)\n\nconst {\n  handleSegmentClick,\n  handleSegmentKeydown,\n  handleSegmentBeforeInput,\n  handleSegmentCompositionStart,\n  handleSegmentCompositionEnd,\n  attributes,\n} = useDateField({\n  hasLeftFocus,\n  lastKeyZero,\n  placeholder: rootContext.placeholder,\n  hourCycle: rootContext.hourCycle,\n  step: rootContext.step,\n  segmentValues: rootContext.segmentValues,\n  formatter: rootContext.formatter,\n  part: props.part,\n  disabled: rootContext.disabled,\n  readonly: rootContext.readonly,\n  focusNext: rootContext.focusNext,\n  modelValue: rootContext.modelValue,\n})\n\nconst disabled = computed(() => rootContext.disabled.value)\nconst readonly = computed(() => rootContext.readonly.value)\nconst isInvalid = computed(() => rootContext.isInvalid.value)\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    v-bind=\"attributes\"\n    :contenteditable=\"disabled || readonly ? false : part !== 'literal'\"\n    :data-reka-date-field-segment=\"part\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :aria-readonly=\"readonly ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :aria-invalid=\"isInvalid ? true : undefined\"\n    v-on=\"part !== 'literal' ? {\n      mousedown: handleSegmentClick,\n      keydown: handleSegmentKeydown,\n      beforeinput: handleSegmentBeforeInput,\n      compositionstart: handleSegmentCompositionStart,\n      compositionend: handleSegmentCompositionEnd,\n      focusout: () => { hasLeftFocus = true },\n      focusin: (e: FocusEvent) => {\n        rootContext.setFocusedElement(e.target as HTMLElement)\n      },\n    } : {}\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { SegmentPart } from '@/shared/date'\nimport { computed, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useDateField } from '@/shared/date/useDateField'\nimport { injectDateFieldRootContext } from './DateFieldRoot.vue'\n\nexport interface DateFieldInputProps extends PrimitiveProps {\n  /** The part of the date to render */\n  part: SegmentPart\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateFieldInputProps>()\n\nconst rootContext = injectDateFieldRootContext()\n\nconst hasLeftFocus = ref(true)\nconst lastKeyZero = ref(false)\n\nconst {\n  handleSegmentClick,\n  handleSegmentKeydown,\n  handleSegmentBeforeInput,\n  handleSegmentCompositionStart,\n  handleSegmentCompositionEnd,\n  attributes,\n} = useDateField({\n  hasLeftFocus,\n  lastKeyZero,\n  placeholder: rootContext.placeholder,\n  hourCycle: rootContext.hourCycle,\n  step: rootContext.step,\n  segmentValues: rootContext.segmentValues,\n  formatter: rootContext.formatter,\n  part: props.part,\n  disabled: rootContext.disabled,\n  readonly: rootContext.readonly,\n  focusNext: rootContext.focusNext,\n  modelValue: rootContext.modelValue,\n})\n\nconst disabled = computed(() => rootContext.disabled.value)\nconst readonly = computed(() => rootContext.readonly.value)\nconst isInvalid = computed(() => rootContext.isInvalid.value)\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    v-bind=\"attributes\"\n    :contenteditable=\"disabled || readonly ? false : part !== 'literal'\"\n    :data-reka-date-field-segment=\"part\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :aria-readonly=\"readonly ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :aria-invalid=\"isInvalid ? true : undefined\"\n    v-on=\"part !== 'literal' ? {\n      mousedown: handleSegmentClick,\n      keydown: handleSegmentKeydown,\n      beforeinput: handleSegmentBeforeInput,\n      compositionstart: handleSegmentCompositionStart,\n      compositionend: handleSegmentCompositionEnd,\n      focusout: () => { hasLeftFocus = true },\n      focusin: (e: FocusEvent) => {\n        rootContext.setFocusedElement(e.target as HTMLElement)\n      },\n    } : {}\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { createContext } from '@/shared'\n\nexport interface PopoverRootProps {\n  /**\n   * The open state of the popover when it is initially rendered. Use when you do not need to control its open state.\n   */\n  defaultOpen?: boolean\n  /**\n   * The controlled open state of the popover.\n   */\n  open?: boolean\n  /**\n   * The modality of the popover. When set to true, interaction with outside elements will be disabled and only popover content will be visible to screen readers.\n   *\n   * @defaultValue false\n   */\n  modal?: boolean\n}\nexport type PopoverRootEmits = {\n  /**\n   * Event handler called when the open state of the popover changes.\n   */\n  'update:open': [value: boolean]\n}\n\nexport interface PopoverRootContext {\n  triggerElement: Ref<HTMLElement | undefined>\n  triggerId: string\n  contentId: string\n  open: Ref<boolean>\n  modal: Ref<boolean>\n  onOpenChange: (value: boolean) => void\n  onOpenToggle: () => void\n  hasCustomAnchor: Ref<boolean>\n}\n\nexport const [injectPopoverRootContext, providePopoverRootContext]\n  = createContext<PopoverRootContext>('PopoverRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, toRefs } from 'vue'\nimport { PopperRoot } from '@/Popper'\n\nconst props = withDefaults(defineProps<PopoverRootProps>(), {\n  defaultOpen: false,\n  open: undefined,\n  modal: false,\n})\nconst emit = defineEmits<PopoverRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n    /** Close the popover */\n    close: () => void\n  }) => any\n}>()\n\nconst { modal } = toRefs(props)\n\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst triggerElement = ref<HTMLElement>()\nconst hasCustomAnchor = ref(false)\n\nprovidePopoverRootContext({\n  contentId: '',\n  triggerId: '',\n  modal,\n  open,\n  onOpenChange: (value) => {\n    open.value = value\n  },\n  onOpenToggle: () => {\n    open.value = !open.value\n  },\n  triggerElement,\n  hasCustomAnchor,\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <slot\n      :open=\"open\"\n      :close=\"() => open = false\"\n    />\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { createContext } from '@/shared'\n\nexport interface PopoverRootProps {\n  /**\n   * The open state of the popover when it is initially rendered. Use when you do not need to control its open state.\n   */\n  defaultOpen?: boolean\n  /**\n   * The controlled open state of the popover.\n   */\n  open?: boolean\n  /**\n   * The modality of the popover. When set to true, interaction with outside elements will be disabled and only popover content will be visible to screen readers.\n   *\n   * @defaultValue false\n   */\n  modal?: boolean\n}\nexport type PopoverRootEmits = {\n  /**\n   * Event handler called when the open state of the popover changes.\n   */\n  'update:open': [value: boolean]\n}\n\nexport interface PopoverRootContext {\n  triggerElement: Ref<HTMLElement | undefined>\n  triggerId: string\n  contentId: string\n  open: Ref<boolean>\n  modal: Ref<boolean>\n  onOpenChange: (value: boolean) => void\n  onOpenToggle: () => void\n  hasCustomAnchor: Ref<boolean>\n}\n\nexport const [injectPopoverRootContext, providePopoverRootContext]\n  = createContext<PopoverRootContext>('PopoverRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, toRefs } from 'vue'\nimport { PopperRoot } from '@/Popper'\n\nconst props = withDefaults(defineProps<PopoverRootProps>(), {\n  defaultOpen: false,\n  open: undefined,\n  modal: false,\n})\nconst emit = defineEmits<PopoverRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n    /** Close the popover */\n    close: () => void\n  }) => any\n}>()\n\nconst { modal } = toRefs(props)\n\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst triggerElement = ref<HTMLElement>()\nconst hasCustomAnchor = ref(false)\n\nprovidePopoverRootContext({\n  contentId: '',\n  triggerId: '',\n  modal,\n  open,\n  onOpenChange: (value) => {\n    open.value = value\n  },\n  onOpenToggle: () => {\n    open.value = !open.value\n  },\n  triggerElement,\n  hasCustomAnchor,\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <slot\n      :open=\"open\"\n      :close=\"() => open = false\"\n    />\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type { PopperAnchorProps } from '@/Popper'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PopoverAnchorProps extends PopperAnchorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onBeforeMount, onUnmounted } from 'vue'\nimport { PopperAnchor } from '@/Popper'\nimport { injectPopoverRootContext } from './PopoverRoot.vue'\n\nconst props = defineProps<PopoverAnchorProps>()\n\nuseForwardExpose()\nconst rootContext = injectPopoverRootContext()\n\nonBeforeMount(() => {\n  rootContext.hasCustomAnchor.value = true\n})\nonUnmounted(() => {\n  rootContext.hasCustomAnchor.value = false\n})\n</script>\n\n<template>\n  <PopperAnchor v-bind=\"props\">\n    <slot />\n  </PopperAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { PopperAnchorProps } from '@/Popper'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PopoverAnchorProps extends PopperAnchorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onBeforeMount, onUnmounted } from 'vue'\nimport { PopperAnchor } from '@/Popper'\nimport { injectPopoverRootContext } from './PopoverRoot.vue'\n\nconst props = defineProps<PopoverAnchorProps>()\n\nuseForwardExpose()\nconst rootContext = injectPopoverRootContext()\n\nonBeforeMount(() => {\n  rootContext.hasCustomAnchor.value = true\n})\nonUnmounted(() => {\n  rootContext.hasCustomAnchor.value = false\n})\n</script>\n\n<template>\n  <PopperAnchor v-bind=\"props\">\n    <slot />\n  </PopperAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverAnchorProps } from '..'\nimport { PopoverAnchor } from '..'\n\nexport interface DatePickerAnchorProps extends PopoverAnchorProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerAnchorProps>()\n</script>\n\n<template>\n  <PopoverAnchor v-bind=\"props\">\n    <slot />\n  </PopoverAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverAnchorProps } from '..'\nimport { PopoverAnchor } from '..'\n\nexport interface DatePickerAnchorProps extends PopoverAnchorProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerAnchorProps>()\n</script>\n\n<template>\n  <PopoverAnchor v-bind=\"props\">\n    <slot />\n  </PopoverAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { PopperArrowProps } from '@/Popper'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PopoverArrowProps extends PopperArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperArrow } from '@/Popper'\n\nconst props = withDefaults(defineProps<PopoverArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nuseForwardExpose()\n</script>\n\n<template>\n  <PopperArrow v-bind=\"props\">\n    <slot />\n  </PopperArrow>\n</template>\n","<script lang=\"ts\">\nimport type { PopperArrowProps } from '@/Popper'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PopoverArrowProps extends PopperArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperArrow } from '@/Popper'\n\nconst props = withDefaults(defineProps<PopoverArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nuseForwardExpose()\n</script>\n\n<template>\n  <PopperArrow v-bind=\"props\">\n    <slot />\n  </PopperArrow>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverArrowProps } from '..'\nimport { PopoverArrow } from '..'\n\nexport interface DatePickerArrowProps extends PopoverArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerArrowProps>()\n</script>\n\n<template>\n  <PopoverArrow v-bind=\"props\">\n    <slot />\n  </PopoverArrow>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverArrowProps } from '..'\nimport { PopoverArrow } from '..'\n\nexport interface DatePickerArrowProps extends PopoverArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerArrowProps>()\n</script>\n\n<template>\n  <PopoverArrow v-bind=\"props\">\n    <slot />\n  </PopoverArrow>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\n\nimport type { Ref } from 'vue'\nimport type { CalendarRootProps, DateFieldRoot, DateFieldRootProps, PopoverRootEmits, PopoverRootProps } from '..'\nimport type { Matcher, WeekDayFormat, WeekStartsOn } from '@/date'\nimport type { DateStep, Granularity, HourCycle } from '@/shared/date'\nimport type { Direction } from '@/shared/types'\nimport { computed, ref, toRefs, watch } from 'vue'\nimport { getWeekStartsOn } from '@/date'\nimport { createContext, useDirection, useLocale } from '@/shared'\nimport { getDefaultDate } from '@/shared/date'\nimport { PopoverRoot } from '..'\n\ntype DatePickerRootContext = {\n  id: Ref<string | undefined>\n  name: Ref<string | undefined>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  hourCycle: Ref<HourCycle | undefined>\n  granularity: Ref<Granularity | undefined>\n  hideTimeZone: Ref<boolean>\n  required: Ref<boolean>\n  locale: Ref<string>\n  dateFieldRef: Ref<InstanceType<typeof DateFieldRoot> | undefined>\n  modelValue: Ref<DateValue | undefined>\n  placeholder: Ref<DateValue>\n  pagedNavigation: Ref<boolean>\n  preventDeselect: Ref<boolean>\n  weekStartsOn: Ref<WeekStartsOn>\n  weekdayFormat: Ref<WeekDayFormat>\n  fixedWeeks: Ref<boolean>\n  numberOfMonths: Ref<number>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  isDateDisabled?: Matcher\n  isDateUnavailable?: Matcher\n  defaultOpen: Ref<boolean>\n  open: Ref<boolean>\n  modal: Ref<boolean>\n  onDateChange: (date: DateValue | undefined) => void\n  onPlaceholderChange: (date: DateValue) => void\n  dir: Ref<Direction>\n  step: Ref<DateStep | undefined>\n  closeOnSelect: Ref<boolean>\n}\n\nexport type DatePickerRootProps = Omit<DateFieldRootProps, 'as' | 'asChild'> & PopoverRootProps & Pick<CalendarRootProps, 'isDateDisabled' | 'pagedNavigation' | 'weekStartsOn' | 'weekdayFormat' | 'fixedWeeks' | 'numberOfMonths' | 'preventDeselect'> & {\n  /** Whether or not to close the popover on date select */\n  closeOnSelect?: boolean\n}\n\nexport type DatePickerRootEmits = PopoverRootEmits & {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateValue | undefined]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n}\n\nexport const [injectDatePickerRootContext, provideDatePickerRootContext]\n  = createContext<DatePickerRootContext>('DatePickerRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\n\ndefineOptions({\n  inheritAttrs: false,\n})\nconst props = withDefaults(defineProps<DatePickerRootProps>(), {\n  defaultValue: undefined,\n  defaultOpen: false,\n  open: undefined,\n  modal: false,\n  pagedNavigation: false,\n  preventDeselect: false,\n  weekdayFormat: 'narrow',\n  fixedWeeks: false,\n  numberOfMonths: 1,\n  disabled: false,\n  readonly: false,\n  placeholder: undefined,\n  isDateDisabled: undefined,\n  isDateUnavailable: undefined,\n  closeOnSelect: false,\n})\nconst emits = defineEmits<DatePickerRootEmits>()\nconst {\n  locale: propLocale,\n  disabled,\n  readonly,\n  pagedNavigation,\n  weekdayFormat,\n  fixedWeeks,\n  numberOfMonths,\n  preventDeselect,\n  isDateDisabled: propsIsDateDisabled,\n  isDateUnavailable: propsIsDateUnavailable,\n  defaultOpen,\n  modal,\n  id,\n  name,\n  required,\n  minValue,\n  maxValue,\n  granularity,\n  hideTimeZone,\n  hourCycle,\n  defaultValue,\n  dir: propDir,\n  step,\n  closeOnSelect,\n} = toRefs(props)\n\nconst dir = useDirection(propDir)\nconst locale = useLocale(propLocale)\nconst weekStartsOn = computed(() => props.weekStartsOn ?? getWeekStartsOn(locale.value))\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateValue | undefined>\n\nconst defaultDate = computed(() => getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  granularity: props.granularity,\n  defaultValue: modelValue.value,\n  locale: locale.value,\n}))\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.value.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: defaultOpen.value,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst dateFieldRef = ref<InstanceType<typeof DateFieldRoot> | undefined>()\n\n/**\n * Reset time fields on DateValue instances that support time granularity.\n */\nfunction resetTime(date: DateValue) {\n  if (!('hour' in date))\n    return date\n\n  return date.set({ hour: 0, minute: 0, second: 0, millisecond: 0 })\n}\n\nwatch(modelValue, (value) => {\n  if (value && value.compare(placeholder.value) !== 0) {\n    placeholder.value = value.copy()\n  }\n  else if (!value && 'hour' in placeholder.value) {\n    placeholder.value = resetTime(placeholder.value)\n  }\n  if (closeOnSelect.value) {\n    open.value = false\n  }\n})\n\nprovideDatePickerRootContext({\n  isDateUnavailable: propsIsDateUnavailable.value,\n  isDateDisabled: propsIsDateDisabled.value,\n  locale,\n  disabled,\n  pagedNavigation,\n  weekStartsOn,\n  weekdayFormat,\n  fixedWeeks,\n  numberOfMonths,\n  readonly,\n  preventDeselect,\n  modelValue,\n  placeholder,\n  defaultOpen,\n  modal,\n  open,\n  id,\n  name,\n  required,\n  minValue,\n  maxValue,\n  granularity,\n  hideTimeZone,\n  hourCycle,\n  dateFieldRef,\n  dir,\n  step,\n  onDateChange(date: DateValue | undefined) {\n    if (!date) {\n      modelValue.value = undefined\n    }\n    else if (!modelValue.value) {\n      modelValue.value = date.copy()\n    }\n    else if (!preventDeselect.value && date && modelValue.value.compare(date) === 0) {\n      modelValue.value = undefined\n    }\n    else {\n      modelValue.value = date.copy()\n    }\n  },\n  onPlaceholderChange(date: DateValue) {\n    placeholder.value = date.copy()\n  },\n  closeOnSelect,\n})\n</script>\n\n<template>\n  <PopoverRoot\n    v-model:open=\"open\"\n    :default-open=\"defaultOpen\"\n    :modal=\"modal\"\n  >\n    <slot />\n  </PopoverRoot>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\n\nimport type { Ref } from 'vue'\nimport type { CalendarRootProps, DateFieldRoot, DateFieldRootProps, PopoverRootEmits, PopoverRootProps } from '..'\nimport type { Matcher, WeekDayFormat, WeekStartsOn } from '@/date'\nimport type { DateStep, Granularity, HourCycle } from '@/shared/date'\nimport type { Direction } from '@/shared/types'\nimport { computed, ref, toRefs, watch } from 'vue'\nimport { getWeekStartsOn } from '@/date'\nimport { createContext, useDirection, useLocale } from '@/shared'\nimport { getDefaultDate } from '@/shared/date'\nimport { PopoverRoot } from '..'\n\ntype DatePickerRootContext = {\n  id: Ref<string | undefined>\n  name: Ref<string | undefined>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  hourCycle: Ref<HourCycle | undefined>\n  granularity: Ref<Granularity | undefined>\n  hideTimeZone: Ref<boolean>\n  required: Ref<boolean>\n  locale: Ref<string>\n  dateFieldRef: Ref<InstanceType<typeof DateFieldRoot> | undefined>\n  modelValue: Ref<DateValue | undefined>\n  placeholder: Ref<DateValue>\n  pagedNavigation: Ref<boolean>\n  preventDeselect: Ref<boolean>\n  weekStartsOn: Ref<WeekStartsOn>\n  weekdayFormat: Ref<WeekDayFormat>\n  fixedWeeks: Ref<boolean>\n  numberOfMonths: Ref<number>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  isDateDisabled?: Matcher\n  isDateUnavailable?: Matcher\n  defaultOpen: Ref<boolean>\n  open: Ref<boolean>\n  modal: Ref<boolean>\n  onDateChange: (date: DateValue | undefined) => void\n  onPlaceholderChange: (date: DateValue) => void\n  dir: Ref<Direction>\n  step: Ref<DateStep | undefined>\n  closeOnSelect: Ref<boolean>\n}\n\nexport type DatePickerRootProps = Omit<DateFieldRootProps, 'as' | 'asChild'> & PopoverRootProps & Pick<CalendarRootProps, 'isDateDisabled' | 'pagedNavigation' | 'weekStartsOn' | 'weekdayFormat' | 'fixedWeeks' | 'numberOfMonths' | 'preventDeselect'> & {\n  /** Whether or not to close the popover on date select */\n  closeOnSelect?: boolean\n}\n\nexport type DatePickerRootEmits = PopoverRootEmits & {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateValue | undefined]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n}\n\nexport const [injectDatePickerRootContext, provideDatePickerRootContext]\n  = createContext<DatePickerRootContext>('DatePickerRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\n\ndefineOptions({\n  inheritAttrs: false,\n})\nconst props = withDefaults(defineProps<DatePickerRootProps>(), {\n  defaultValue: undefined,\n  defaultOpen: false,\n  open: undefined,\n  modal: false,\n  pagedNavigation: false,\n  preventDeselect: false,\n  weekdayFormat: 'narrow',\n  fixedWeeks: false,\n  numberOfMonths: 1,\n  disabled: false,\n  readonly: false,\n  placeholder: undefined,\n  isDateDisabled: undefined,\n  isDateUnavailable: undefined,\n  closeOnSelect: false,\n})\nconst emits = defineEmits<DatePickerRootEmits>()\nconst {\n  locale: propLocale,\n  disabled,\n  readonly,\n  pagedNavigation,\n  weekdayFormat,\n  fixedWeeks,\n  numberOfMonths,\n  preventDeselect,\n  isDateDisabled: propsIsDateDisabled,\n  isDateUnavailable: propsIsDateUnavailable,\n  defaultOpen,\n  modal,\n  id,\n  name,\n  required,\n  minValue,\n  maxValue,\n  granularity,\n  hideTimeZone,\n  hourCycle,\n  defaultValue,\n  dir: propDir,\n  step,\n  closeOnSelect,\n} = toRefs(props)\n\nconst dir = useDirection(propDir)\nconst locale = useLocale(propLocale)\nconst weekStartsOn = computed(() => props.weekStartsOn ?? getWeekStartsOn(locale.value))\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateValue | undefined>\n\nconst defaultDate = computed(() => getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  granularity: props.granularity,\n  defaultValue: modelValue.value,\n  locale: locale.value,\n}))\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.value.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: defaultOpen.value,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst dateFieldRef = ref<InstanceType<typeof DateFieldRoot> | undefined>()\n\n/**\n * Reset time fields on DateValue instances that support time granularity.\n */\nfunction resetTime(date: DateValue) {\n  if (!('hour' in date))\n    return date\n\n  return date.set({ hour: 0, minute: 0, second: 0, millisecond: 0 })\n}\n\nwatch(modelValue, (value) => {\n  if (value && value.compare(placeholder.value) !== 0) {\n    placeholder.value = value.copy()\n  }\n  else if (!value && 'hour' in placeholder.value) {\n    placeholder.value = resetTime(placeholder.value)\n  }\n  if (closeOnSelect.value) {\n    open.value = false\n  }\n})\n\nprovideDatePickerRootContext({\n  isDateUnavailable: propsIsDateUnavailable.value,\n  isDateDisabled: propsIsDateDisabled.value,\n  locale,\n  disabled,\n  pagedNavigation,\n  weekStartsOn,\n  weekdayFormat,\n  fixedWeeks,\n  numberOfMonths,\n  readonly,\n  preventDeselect,\n  modelValue,\n  placeholder,\n  defaultOpen,\n  modal,\n  open,\n  id,\n  name,\n  required,\n  minValue,\n  maxValue,\n  granularity,\n  hideTimeZone,\n  hourCycle,\n  dateFieldRef,\n  dir,\n  step,\n  onDateChange(date: DateValue | undefined) {\n    if (!date) {\n      modelValue.value = undefined\n    }\n    else if (!modelValue.value) {\n      modelValue.value = date.copy()\n    }\n    else if (!preventDeselect.value && date && modelValue.value.compare(date) === 0) {\n      modelValue.value = undefined\n    }\n    else {\n      modelValue.value = date.copy()\n    }\n  },\n  onPlaceholderChange(date: DateValue) {\n    placeholder.value = date.copy()\n  },\n  closeOnSelect,\n})\n</script>\n\n<template>\n  <PopoverRoot\n    v-model:open=\"open\"\n    :default-open=\"defaultOpen\"\n    :modal=\"modal\"\n  >\n    <slot />\n  </PopoverRoot>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport { isEqualDay } from '@internationalized/date'\nimport { CalendarRoot } from '..'\nimport { injectDatePickerRootContext } from './DatePickerRoot.vue'\n</script>\n\n<script setup lang=\"ts\">\nconst rootContext = injectDatePickerRootContext()\n</script>\n\n<template>\n  <CalendarRoot\n    v-slot=\"{ weekDays, grid, date, weekStartsOn, locale, fixedWeeks }\"\n    v-bind=\"{\n      isDateDisabled: rootContext.isDateDisabled,\n      isDateUnavailable: rootContext.isDateUnavailable,\n      minValue: rootContext.minValue.value,\n      maxValue: rootContext.maxValue.value,\n      locale: rootContext.locale.value,\n      disabled: rootContext.disabled.value,\n      pagedNavigation: rootContext.pagedNavigation.value,\n      weekStartsOn: rootContext.weekStartsOn.value,\n      weekdayFormat: rootContext.weekdayFormat.value,\n      fixedWeeks: rootContext.fixedWeeks.value,\n      numberOfMonths: rootContext.numberOfMonths.value,\n      readonly: rootContext.readonly.value,\n      preventDeselect: rootContext.preventDeselect.value,\n      dir: rootContext.dir.value,\n    }\"\n    :model-value=\"rootContext.modelValue.value\"\n    :placeholder=\"rootContext.placeholder.value\"\n    :multiple=\"false\"\n    @update:model-value=\"(date: DateValue | undefined) => {\n      if (date && rootContext.modelValue.value && isEqualDay(date, rootContext.modelValue.value)) return\n      rootContext.onDateChange(date)\n    }\"\n    @update:placeholder=\"(date: DateValue) => {\n      if (isEqualDay(date, rootContext.placeholder.value)) return\n      rootContext.onPlaceholderChange(date)\n    }\"\n  >\n    <slot\n      :date=\"date\"\n      :grid=\"grid\"\n      :week-days=\"weekDays\"\n      :week-starts-on=\"weekStartsOn\"\n      :locale=\"locale\"\n      :fixed-weeks=\"fixedWeeks\"\n    />\n  </CalendarRoot>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport { isEqualDay } from '@internationalized/date'\nimport { CalendarRoot } from '..'\nimport { injectDatePickerRootContext } from './DatePickerRoot.vue'\n</script>\n\n<script setup lang=\"ts\">\nconst rootContext = injectDatePickerRootContext()\n</script>\n\n<template>\n  <CalendarRoot\n    v-slot=\"{ weekDays, grid, date, weekStartsOn, locale, fixedWeeks }\"\n    v-bind=\"{\n      isDateDisabled: rootContext.isDateDisabled,\n      isDateUnavailable: rootContext.isDateUnavailable,\n      minValue: rootContext.minValue.value,\n      maxValue: rootContext.maxValue.value,\n      locale: rootContext.locale.value,\n      disabled: rootContext.disabled.value,\n      pagedNavigation: rootContext.pagedNavigation.value,\n      weekStartsOn: rootContext.weekStartsOn.value,\n      weekdayFormat: rootContext.weekdayFormat.value,\n      fixedWeeks: rootContext.fixedWeeks.value,\n      numberOfMonths: rootContext.numberOfMonths.value,\n      readonly: rootContext.readonly.value,\n      preventDeselect: rootContext.preventDeselect.value,\n      dir: rootContext.dir.value,\n    }\"\n    :model-value=\"rootContext.modelValue.value\"\n    :placeholder=\"rootContext.placeholder.value\"\n    :multiple=\"false\"\n    @update:model-value=\"(date: DateValue | undefined) => {\n      if (date && rootContext.modelValue.value && isEqualDay(date, rootContext.modelValue.value)) return\n      rootContext.onDateChange(date)\n    }\"\n    @update:placeholder=\"(date: DateValue) => {\n      if (isEqualDay(date, rootContext.placeholder.value)) return\n      rootContext.onPlaceholderChange(date)\n    }\"\n  >\n    <slot\n      :date=\"date\"\n      :grid=\"grid\"\n      :week-days=\"weekDays\"\n      :week-starts-on=\"weekStartsOn\"\n      :locale=\"locale\"\n      :fixed-weeks=\"fixedWeeks\"\n    />\n  </CalendarRoot>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarCellProps } from '..'\nimport { CalendarCell } from '..'\n\nexport interface DatePickerCellProps extends CalendarCellProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerCellProps>()\n</script>\n\n<template>\n  <CalendarCell v-bind=\"props\">\n    <slot />\n  </CalendarCell>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarCellProps } from '..'\nimport { CalendarCell } from '..'\n\nexport interface DatePickerCellProps extends CalendarCellProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerCellProps>()\n</script>\n\n<template>\n  <CalendarCell v-bind=\"props\">\n    <slot />\n  </CalendarCell>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarCellTriggerProps } from '..'\nimport type { CalendarCellTriggerSlot } from '@/Calendar/CalendarCellTrigger.vue'\nimport { CalendarCellTrigger } from '..'\n\nexport interface DatePickerCellTriggerProps extends CalendarCellTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerCellTriggerProps>()\ndefineSlots<CalendarCellTriggerSlot>()\n</script>\n\n<template>\n  <CalendarCellTrigger\n    v-slot=\"slotProps\"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </CalendarCellTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarCellTriggerProps } from '..'\nimport type { CalendarCellTriggerSlot } from '@/Calendar/CalendarCellTrigger.vue'\nimport { CalendarCellTrigger } from '..'\n\nexport interface DatePickerCellTriggerProps extends CalendarCellTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerCellTriggerProps>()\ndefineSlots<CalendarCellTriggerSlot>()\n</script>\n\n<template>\n  <CalendarCellTrigger\n    v-slot=\"slotProps\"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </CalendarCellTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PopoverCloseProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport {\n  injectPopoverRootContext,\n} from './PopoverRoot.vue'\n\nconst props = withDefaults(defineProps<PopoverCloseProps>(), {\n  as: 'button',\n})\n\nuseForwardExpose()\nconst rootContext = injectPopoverRootContext()\n</script>\n\n<template>\n  <Primitive\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :as=\"as\"\n    :as-child=\"props.asChild\"\n    @click=\"rootContext.onOpenChange(false)\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PopoverCloseProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport {\n  injectPopoverRootContext,\n} from './PopoverRoot.vue'\n\nconst props = withDefaults(defineProps<PopoverCloseProps>(), {\n  as: 'button',\n})\n\nuseForwardExpose()\nconst rootContext = injectPopoverRootContext()\n</script>\n\n<template>\n  <Primitive\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :as=\"as\"\n    :as-child=\"props.asChild\"\n    @click=\"rootContext.onOpenChange(false)\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverCloseProps } from '..'\nimport { PopoverClose } from '..'\n\nexport interface DatePickerCloseProps extends PopoverCloseProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerCloseProps>()\n</script>\n\n<template>\n  <PopoverClose v-bind=\"props\">\n    <slot />\n  </PopoverClose>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverCloseProps } from '..'\nimport { PopoverClose } from '..'\n\nexport interface DatePickerCloseProps extends PopoverCloseProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerCloseProps>()\n</script>\n\n<template>\n  <PopoverClose v-bind=\"props\">\n    <slot />\n  </PopoverClose>\n</template>\n","<script lang=\"ts\">\nimport type {\n  DismissableLayerEmits,\n  DismissableLayerProps,\n} from '@/DismissableLayer'\nimport type { FocusScopeProps } from '@/FocusScope'\nimport type { PopperContentProps } from '@/Popper'\nimport { reactiveOmit } from '@vueuse/shared'\n\nexport type PopoverContentImplEmits = DismissableLayerEmits & {\n  /**\n   * Event handler called when auto-focusing on open.\n   * Can be prevented.\n   */\n  openAutoFocus: [event: Event]\n  /**\n   * Event handler called when auto-focusing on close.\n   * Can be prevented.\n   */\n  closeAutoFocus: [event: Event]\n}\n\nexport interface PopoverContentImplProps extends PopperContentProps, DismissableLayerProps {}\n\ninterface PopoverContentImplPrivateProps extends PopoverContentImplProps {\n  /**\n   * Whether focus should be trapped within the `MenuContent`\n   * @defaultValue false\n   */\n  trapFocus?: FocusScopeProps['trapped']\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { FocusScope } from '@/FocusScope'\nimport { PopperContent } from '@/Popper'\nimport { useFocusGuards, useForwardExpose, useForwardProps } from '@/shared'\nimport { injectPopoverRootContext } from './PopoverRoot.vue'\n\nconst props = defineProps<PopoverContentImplPrivateProps>()\nconst emits = defineEmits<PopoverContentImplEmits>()\n\nconst forwarded = useForwardProps(reactiveOmit(props, 'trapFocus', 'disableOutsidePointerEvents'))\nconst { forwardRef } = useForwardExpose()\n\nconst rootContext = injectPopoverRootContext()\nuseFocusGuards()\n</script>\n\n<template>\n  <FocusScope\n    as-child\n    loop\n    :trapped=\"trapFocus\"\n    @mount-auto-focus=\"emits('openAutoFocus', $event)\"\n    @unmount-auto-focus=\"emits('closeAutoFocus', $event)\"\n  >\n    <DismissableLayer\n      as-child\n      :disable-outside-pointer-events=\"disableOutsidePointerEvents\"\n      @pointer-down-outside=\"emits('pointerDownOutside', $event)\"\n      @interact-outside=\"emits('interactOutside', $event)\"\n      @escape-key-down=\"emits('escapeKeyDown', $event)\"\n      @focus-outside=\"emits('focusOutside', $event)\"\n      @dismiss=\"rootContext.onOpenChange(false)\"\n    >\n      <PopperContent\n        v-bind=\"forwarded\"\n        :id=\"rootContext.contentId\"\n        :ref=\"forwardRef\"\n        :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n        :aria-labelledby=\"rootContext.triggerId\"\n        :style=\"{\n          '--reka-popover-content-transform-origin':\n            'var(--reka-popper-transform-origin)',\n          '--reka-popover-content-available-width':\n            'var(--reka-popper-available-width)',\n          '--reka-popover-content-available-height':\n            'var(--reka-popper-available-height)',\n          '--reka-popover-trigger-width': 'var(--reka-popper-anchor-width)',\n          '--reka-popover-trigger-height': 'var(--reka-popper-anchor-height)',\n        }\"\n        role=\"dialog\"\n      >\n        <slot />\n      </PopperContent>\n    </DismissableLayer>\n  </FocusScope>\n</template>\n","<script lang=\"ts\">\nimport type {\n  DismissableLayerEmits,\n  DismissableLayerProps,\n} from '@/DismissableLayer'\nimport type { FocusScopeProps } from '@/FocusScope'\nimport type { PopperContentProps } from '@/Popper'\nimport { reactiveOmit } from '@vueuse/shared'\n\nexport type PopoverContentImplEmits = DismissableLayerEmits & {\n  /**\n   * Event handler called when auto-focusing on open.\n   * Can be prevented.\n   */\n  openAutoFocus: [event: Event]\n  /**\n   * Event handler called when auto-focusing on close.\n   * Can be prevented.\n   */\n  closeAutoFocus: [event: Event]\n}\n\nexport interface PopoverContentImplProps extends PopperContentProps, DismissableLayerProps {}\n\ninterface PopoverContentImplPrivateProps extends PopoverContentImplProps {\n  /**\n   * Whether focus should be trapped within the `MenuContent`\n   * @defaultValue false\n   */\n  trapFocus?: FocusScopeProps['trapped']\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { FocusScope } from '@/FocusScope'\nimport { PopperContent } from '@/Popper'\nimport { useFocusGuards, useForwardExpose, useForwardProps } from '@/shared'\nimport { injectPopoverRootContext } from './PopoverRoot.vue'\n\nconst props = defineProps<PopoverContentImplPrivateProps>()\nconst emits = defineEmits<PopoverContentImplEmits>()\n\nconst forwarded = useForwardProps(reactiveOmit(props, 'trapFocus', 'disableOutsidePointerEvents'))\nconst { forwardRef } = useForwardExpose()\n\nconst rootContext = injectPopoverRootContext()\nuseFocusGuards()\n</script>\n\n<template>\n  <FocusScope\n    as-child\n    loop\n    :trapped=\"trapFocus\"\n    @mount-auto-focus=\"emits('openAutoFocus', $event)\"\n    @unmount-auto-focus=\"emits('closeAutoFocus', $event)\"\n  >\n    <DismissableLayer\n      as-child\n      :disable-outside-pointer-events=\"disableOutsidePointerEvents\"\n      @pointer-down-outside=\"emits('pointerDownOutside', $event)\"\n      @interact-outside=\"emits('interactOutside', $event)\"\n      @escape-key-down=\"emits('escapeKeyDown', $event)\"\n      @focus-outside=\"emits('focusOutside', $event)\"\n      @dismiss=\"rootContext.onOpenChange(false)\"\n    >\n      <PopperContent\n        v-bind=\"forwarded\"\n        :id=\"rootContext.contentId\"\n        :ref=\"forwardRef\"\n        :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n        :aria-labelledby=\"rootContext.triggerId\"\n        :style=\"{\n          '--reka-popover-content-transform-origin':\n            'var(--reka-popper-transform-origin)',\n          '--reka-popover-content-available-width':\n            'var(--reka-popper-available-width)',\n          '--reka-popover-content-available-height':\n            'var(--reka-popper-available-height)',\n          '--reka-popover-trigger-width': 'var(--reka-popper-anchor-width)',\n          '--reka-popover-trigger-height': 'var(--reka-popper-anchor-height)',\n        }\"\n        role=\"dialog\"\n      >\n        <slot />\n      </PopperContent>\n    </DismissableLayer>\n  </FocusScope>\n</template>\n","<script setup lang=\"ts\">\nimport type { PopoverContentImplEmits, PopoverContentImplProps } from './PopoverContentImpl.vue'\nimport { ref } from 'vue'\nimport { useForwardExpose, useForwardPropsEmits, useHideOthers } from '@/shared'\nimport { useBodyScrollLock } from '@/shared/useBodyScrollLock'\nimport PopoverContentImpl from './PopoverContentImpl.vue'\nimport { injectPopoverRootContext } from './PopoverRoot.vue'\n\nconst props = defineProps<PopoverContentImplProps>()\nconst emits = defineEmits<PopoverContentImplEmits>()\nconst rootContext = injectPopoverRootContext()\nconst isRightClickOutsideRef = ref(false)\n\nuseBodyScrollLock(true)\n\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst { forwardRef, currentElement } = useForwardExpose()\nuseHideOthers(currentElement)\n</script>\n\n<template>\n  <PopoverContentImpl\n    v-bind=\"forwarded\"\n    :ref=\"forwardRef\"\n    :trap-focus=\"rootContext.open.value\"\n    disable-outside-pointer-events\n    @close-auto-focus.prevent=\"\n      (event) => {\n        emits('closeAutoFocus', event);\n\n        if (!isRightClickOutsideRef) rootContext.triggerElement.value?.focus();\n      }\n    \"\n    @pointer-down-outside=\"\n      (event) => {\n        emits('pointerDownOutside', event);\n\n        const originalEvent = event.detail.originalEvent;\n        const ctrlLeftClick\n          = originalEvent.button === 0 && originalEvent.ctrlKey === true;\n        const isRightClick = originalEvent.button === 2 || ctrlLeftClick;\n\n        isRightClickOutsideRef = isRightClick;\n      }\n    \"\n    @focus-outside.prevent\n  >\n    <slot />\n  </PopoverContentImpl>\n</template>\n","<script setup lang=\"ts\">\nimport type { PopoverContentImplEmits, PopoverContentImplProps } from './PopoverContentImpl.vue'\nimport { ref } from 'vue'\nimport { useForwardExpose, useForwardPropsEmits, useHideOthers } from '@/shared'\nimport { useBodyScrollLock } from '@/shared/useBodyScrollLock'\nimport PopoverContentImpl from './PopoverContentImpl.vue'\nimport { injectPopoverRootContext } from './PopoverRoot.vue'\n\nconst props = defineProps<PopoverContentImplProps>()\nconst emits = defineEmits<PopoverContentImplEmits>()\nconst rootContext = injectPopoverRootContext()\nconst isRightClickOutsideRef = ref(false)\n\nuseBodyScrollLock(true)\n\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst { forwardRef, currentElement } = useForwardExpose()\nuseHideOthers(currentElement)\n</script>\n\n<template>\n  <PopoverContentImpl\n    v-bind=\"forwarded\"\n    :ref=\"forwardRef\"\n    :trap-focus=\"rootContext.open.value\"\n    disable-outside-pointer-events\n    @close-auto-focus.prevent=\"\n      (event) => {\n        emits('closeAutoFocus', event);\n\n        if (!isRightClickOutsideRef) rootContext.triggerElement.value?.focus();\n      }\n    \"\n    @pointer-down-outside=\"\n      (event) => {\n        emits('pointerDownOutside', event);\n\n        const originalEvent = event.detail.originalEvent;\n        const ctrlLeftClick\n          = originalEvent.button === 0 && originalEvent.ctrlKey === true;\n        const isRightClick = originalEvent.button === 2 || ctrlLeftClick;\n\n        isRightClickOutsideRef = isRightClick;\n      }\n    \"\n    @focus-outside.prevent\n  >\n    <slot />\n  </PopoverContentImpl>\n</template>\n","<script setup lang=\"ts\">\nimport type { PopoverContentImplEmits, PopoverContentImplProps } from './PopoverContentImpl.vue'\nimport { ref } from 'vue'\nimport { useForwardPropsEmits } from '@/shared'\nimport PopoverContentImpl from './PopoverContentImpl.vue'\nimport { injectPopoverRootContext } from './PopoverRoot.vue'\n\nconst props = defineProps<PopoverContentImplProps>()\nconst emits = defineEmits<PopoverContentImplEmits>()\nconst rootContext = injectPopoverRootContext()\nconst hasInteractedOutsideRef = ref(false)\nconst hasPointerDownOutsideRef = ref(false)\n\nconst forwarded = useForwardPropsEmits(props, emits)\n</script>\n\n<template>\n  <PopoverContentImpl\n    v-bind=\"forwarded\"\n    :trap-focus=\"false\"\n    :disable-outside-pointer-events=\"false\"\n    @close-auto-focus=\"\n      (event) => {\n        emits('closeAutoFocus', event);\n\n        if (!event.defaultPrevented) {\n          if (!hasInteractedOutsideRef) rootContext.triggerElement.value?.focus();\n          // Always prevent auto focus because we either focus manually or want user agent focus\n          event.preventDefault();\n        }\n\n        hasInteractedOutsideRef = false;\n        hasPointerDownOutsideRef = false;\n      }\n    \"\n    @interact-outside=\"\n      async (event) => {\n        emits('interactOutside', event);\n\n        if (!event.defaultPrevented) {\n          hasInteractedOutsideRef = true;\n          if (event.detail.originalEvent.type === 'pointerdown') {\n            hasPointerDownOutsideRef = true;\n          }\n        }\n\n        // Prevent dismissing when clicking the trigger.\n        // As the trigger is already setup to close, without doing so would\n        // cause it to close and immediately open.\n        const target = event.target as HTMLElement;\n        const targetIsTrigger = rootContext.triggerElement.value?.contains(target);\n        if (targetIsTrigger) event.preventDefault();\n\n        // On Safari if the trigger is inside a container with tabIndex={0}, when clicked\n        // we will get the pointer down outside event on the trigger, but then a subsequent\n        // focus outside event on the container, we ignore any focus outside event when we've\n        // already had a pointer down outside event.\n        if (\n          event.detail.originalEvent.type === 'focusin'\n          && hasPointerDownOutsideRef\n        ) {\n          event.preventDefault();\n        }\n      }\n    \"\n  >\n    <slot />\n  </PopoverContentImpl>\n</template>\n","<script setup lang=\"ts\">\nimport type { PopoverContentImplEmits, PopoverContentImplProps } from './PopoverContentImpl.vue'\nimport { ref } from 'vue'\nimport { useForwardPropsEmits } from '@/shared'\nimport PopoverContentImpl from './PopoverContentImpl.vue'\nimport { injectPopoverRootContext } from './PopoverRoot.vue'\n\nconst props = defineProps<PopoverContentImplProps>()\nconst emits = defineEmits<PopoverContentImplEmits>()\nconst rootContext = injectPopoverRootContext()\nconst hasInteractedOutsideRef = ref(false)\nconst hasPointerDownOutsideRef = ref(false)\n\nconst forwarded = useForwardPropsEmits(props, emits)\n</script>\n\n<template>\n  <PopoverContentImpl\n    v-bind=\"forwarded\"\n    :trap-focus=\"false\"\n    :disable-outside-pointer-events=\"false\"\n    @close-auto-focus=\"\n      (event) => {\n        emits('closeAutoFocus', event);\n\n        if (!event.defaultPrevented) {\n          if (!hasInteractedOutsideRef) rootContext.triggerElement.value?.focus();\n          // Always prevent auto focus because we either focus manually or want user agent focus\n          event.preventDefault();\n        }\n\n        hasInteractedOutsideRef = false;\n        hasPointerDownOutsideRef = false;\n      }\n    \"\n    @interact-outside=\"\n      async (event) => {\n        emits('interactOutside', event);\n\n        if (!event.defaultPrevented) {\n          hasInteractedOutsideRef = true;\n          if (event.detail.originalEvent.type === 'pointerdown') {\n            hasPointerDownOutsideRef = true;\n          }\n        }\n\n        // Prevent dismissing when clicking the trigger.\n        // As the trigger is already setup to close, without doing so would\n        // cause it to close and immediately open.\n        const target = event.target as HTMLElement;\n        const targetIsTrigger = rootContext.triggerElement.value?.contains(target);\n        if (targetIsTrigger) event.preventDefault();\n\n        // On Safari if the trigger is inside a container with tabIndex={0}, when clicked\n        // we will get the pointer down outside event on the trigger, but then a subsequent\n        // focus outside event on the container, we ignore any focus outside event when we've\n        // already had a pointer down outside event.\n        if (\n          event.detail.originalEvent.type === 'focusin'\n          && hasPointerDownOutsideRef\n        ) {\n          event.preventDefault();\n        }\n      }\n    \"\n  >\n    <slot />\n  </PopoverContentImpl>\n</template>\n","<script lang=\"ts\">\nimport type {\n  PopoverContentImplEmits,\n  PopoverContentImplProps,\n} from './PopoverContentImpl.vue'\n\nexport type PopoverContentEmits = PopoverContentImplEmits\n\nexport interface PopoverContentProps extends PopoverContentImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardExpose, useForwardPropsEmits, useId } from '@/shared'\nimport PopoverContentModal from './PopoverContentModal.vue'\nimport PopoverContentNonModal from './PopoverContentNonModal.vue'\nimport { injectPopoverRootContext } from './PopoverRoot.vue'\n\nconst props = defineProps<PopoverContentProps>()\nconst emits = defineEmits<PopoverContentEmits>()\n\nconst rootContext = injectPopoverRootContext()\n\nconst forwarded = useForwardPropsEmits(props, emits)\nconst { forwardRef } = useForwardExpose()\n\nrootContext.contentId ||= useId(undefined, 'reka-popover-content')\n</script>\n\n<template>\n  <Presence :present=\"forceMount || rootContext.open.value\">\n    <PopoverContentModal\n      v-if=\"rootContext.modal.value\"\n      v-bind=\"forwarded\"\n      :ref=\"forwardRef\"\n    >\n      <slot />\n    </PopoverContentModal>\n    <PopoverContentNonModal\n      v-else\n      v-bind=\"forwarded\"\n      :ref=\"forwardRef\"\n    >\n      <slot />\n    </PopoverContentNonModal>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type {\n  PopoverContentImplEmits,\n  PopoverContentImplProps,\n} from './PopoverContentImpl.vue'\n\nexport type PopoverContentEmits = PopoverContentImplEmits\n\nexport interface PopoverContentProps extends PopoverContentImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardExpose, useForwardPropsEmits, useId } from '@/shared'\nimport PopoverContentModal from './PopoverContentModal.vue'\nimport PopoverContentNonModal from './PopoverContentNonModal.vue'\nimport { injectPopoverRootContext } from './PopoverRoot.vue'\n\nconst props = defineProps<PopoverContentProps>()\nconst emits = defineEmits<PopoverContentEmits>()\n\nconst rootContext = injectPopoverRootContext()\n\nconst forwarded = useForwardPropsEmits(props, emits)\nconst { forwardRef } = useForwardExpose()\n\nrootContext.contentId ||= useId(undefined, 'reka-popover-content')\n</script>\n\n<template>\n  <Presence :present=\"forceMount || rootContext.open.value\">\n    <PopoverContentModal\n      v-if=\"rootContext.modal.value\"\n      v-bind=\"forwarded\"\n      :ref=\"forwardRef\"\n    >\n      <slot />\n    </PopoverContentModal>\n    <PopoverContentNonModal\n      v-else\n      v-bind=\"forwarded\"\n      :ref=\"forwardRef\"\n    >\n      <slot />\n    </PopoverContentNonModal>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface PopoverPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<PopoverPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface PopoverPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<PopoverPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverContentEmits, PopoverContentProps, PopoverPortalProps } from '..'\nimport { computed } from 'vue'\nimport { handleCalendarInitialFocus } from '@/shared/date'\nimport { PopoverContent, PopoverPortal, useForwardPropsEmits } from '..'\n\nexport interface DatePickerContentProps extends PopoverContentProps {\n  /**\n   * Props to control the portal wrapped around the content.\n   */\n  portal?: PopoverPortalProps\n}\nexport interface DatePickerContentEmits extends PopoverContentEmits {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerContentProps>()\nconst emits = defineEmits<DatePickerContentEmits>()\n\nconst propsToForward = computed(() => ({\n  ...props,\n  portal: undefined,\n}))\nconst forwarded = useForwardPropsEmits(propsToForward, emits)\n</script>\n\n<template>\n  <PopoverPortal v-bind=\"portal\">\n    <PopoverContent\n      v-bind=\"{ ...forwarded, ...$attrs }\"\n      @open-auto-focus=\"event => {\n        emits('openAutoFocus', event)\n\n        if (!event.defaultPrevented && event.target) {\n          handleCalendarInitialFocus(event.target as HTMLElement)\n          event.preventDefault()\n        }\n      }\"\n    >\n      <slot />\n    </PopoverContent>\n  </PopoverPortal>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverContentEmits, PopoverContentProps, PopoverPortalProps } from '..'\nimport { computed } from 'vue'\nimport { handleCalendarInitialFocus } from '@/shared/date'\nimport { PopoverContent, PopoverPortal, useForwardPropsEmits } from '..'\n\nexport interface DatePickerContentProps extends PopoverContentProps {\n  /**\n   * Props to control the portal wrapped around the content.\n   */\n  portal?: PopoverPortalProps\n}\nexport interface DatePickerContentEmits extends PopoverContentEmits {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerContentProps>()\nconst emits = defineEmits<DatePickerContentEmits>()\n\nconst propsToForward = computed(() => ({\n  ...props,\n  portal: undefined,\n}))\nconst forwarded = useForwardPropsEmits(propsToForward, emits)\n</script>\n\n<template>\n  <PopoverPortal v-bind=\"portal\">\n    <PopoverContent\n      v-bind=\"{ ...forwarded, ...$attrs }\"\n      @open-auto-focus=\"event => {\n        emits('openAutoFocus', event)\n\n        if (!event.defaultPrevented && event.target) {\n          handleCalendarInitialFocus(event.target as HTMLElement)\n          event.preventDefault()\n        }\n      }\"\n    >\n      <slot />\n    </PopoverContent>\n  </PopoverPortal>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport { DateFieldRoot } from '..'\nimport { injectDatePickerRootContext } from './DatePickerRoot.vue'\n</script>\n\n<script setup lang=\"ts\">\nconst rootContext = injectDatePickerRootContext()\n</script>\n\n<template>\n  <DateFieldRoot\n    v-slot=\"{ segments, modelValue }\"\n    :ref=\"rootContext.dateFieldRef\"\n    :model-value=\"rootContext.modelValue.value\"\n    :placeholder=\"rootContext.placeholder.value\"\n    v-bind=\"{\n      id: rootContext.id.value,\n      name: rootContext.name.value,\n      disabled: rootContext.disabled.value,\n      minValue: rootContext.minValue.value,\n      maxValue: rootContext.maxValue.value,\n      readonly: rootContext.readonly.value,\n      hourCycle: rootContext.hourCycle.value,\n      granularity: rootContext.granularity.value,\n      hideTimeZone: rootContext.hideTimeZone.value,\n      locale: rootContext.locale.value,\n      isDateUnavailable: rootContext.isDateUnavailable,\n      required: rootContext.required.value,\n      dir: rootContext.dir.value,\n      step: rootContext.step.value,\n    }\"\n    @update:model-value=\"(date: DateValue | undefined) => {\n      if (date && rootContext.modelValue.value && date.compare(rootContext.modelValue.value) === 0) return\n      rootContext.onDateChange(date)\n    }\"\n    @update:placeholder=\"(date: DateValue) => {\n      if (date.compare(rootContext.placeholder.value) === 0) return\n      rootContext.onPlaceholderChange(date)\n    }\"\n  >\n    <slot\n      :segments=\"segments\"\n      :model-value=\"modelValue\"\n    />\n  </DateFieldRoot>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport { DateFieldRoot } from '..'\nimport { injectDatePickerRootContext } from './DatePickerRoot.vue'\n</script>\n\n<script setup lang=\"ts\">\nconst rootContext = injectDatePickerRootContext()\n</script>\n\n<template>\n  <DateFieldRoot\n    v-slot=\"{ segments, modelValue }\"\n    :ref=\"rootContext.dateFieldRef\"\n    :model-value=\"rootContext.modelValue.value\"\n    :placeholder=\"rootContext.placeholder.value\"\n    v-bind=\"{\n      id: rootContext.id.value,\n      name: rootContext.name.value,\n      disabled: rootContext.disabled.value,\n      minValue: rootContext.minValue.value,\n      maxValue: rootContext.maxValue.value,\n      readonly: rootContext.readonly.value,\n      hourCycle: rootContext.hourCycle.value,\n      granularity: rootContext.granularity.value,\n      hideTimeZone: rootContext.hideTimeZone.value,\n      locale: rootContext.locale.value,\n      isDateUnavailable: rootContext.isDateUnavailable,\n      required: rootContext.required.value,\n      dir: rootContext.dir.value,\n      step: rootContext.step.value,\n    }\"\n    @update:model-value=\"(date: DateValue | undefined) => {\n      if (date && rootContext.modelValue.value && date.compare(rootContext.modelValue.value) === 0) return\n      rootContext.onDateChange(date)\n    }\"\n    @update:placeholder=\"(date: DateValue) => {\n      if (date.compare(rootContext.placeholder.value) === 0) return\n      rootContext.onPlaceholderChange(date)\n    }\"\n  >\n    <slot\n      :segments=\"segments\"\n      :model-value=\"modelValue\"\n    />\n  </DateFieldRoot>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarGridProps } from '..'\nimport { CalendarGrid } from '..'\n\nexport interface DatePickerGridProps extends CalendarGridProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerGridProps>()\n</script>\n\n<template>\n  <CalendarGrid v-bind=\"props\">\n    <slot />\n  </CalendarGrid>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarGridProps } from '..'\nimport { CalendarGrid } from '..'\n\nexport interface DatePickerGridProps extends CalendarGridProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerGridProps>()\n</script>\n\n<template>\n  <CalendarGrid v-bind=\"props\">\n    <slot />\n  </CalendarGrid>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarGridBodyProps } from '..'\nimport { CalendarGridBody } from '..'\n\nexport interface DatePickerGridBodyProps extends CalendarGridBodyProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerGridBodyProps>()\n</script>\n\n<template>\n  <CalendarGridBody v-bind=\"props\">\n    <slot />\n  </CalendarGridBody>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarGridBodyProps } from '..'\nimport { CalendarGridBody } from '..'\n\nexport interface DatePickerGridBodyProps extends CalendarGridBodyProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerGridBodyProps>()\n</script>\n\n<template>\n  <CalendarGridBody v-bind=\"props\">\n    <slot />\n  </CalendarGridBody>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarGridHeadProps } from '..'\nimport { CalendarGridHead } from '..'\n\nexport interface DatePickerGridHeadProps extends CalendarGridHeadProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerGridHeadProps>()\n</script>\n\n<template>\n  <CalendarGridHead v-bind=\"props\">\n    <slot />\n  </CalendarGridHead>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarGridHeadProps } from '..'\nimport { CalendarGridHead } from '..'\n\nexport interface DatePickerGridHeadProps extends CalendarGridHeadProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerGridHeadProps>()\n</script>\n\n<template>\n  <CalendarGridHead v-bind=\"props\">\n    <slot />\n  </CalendarGridHead>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarGridRowProps } from '..'\nimport { CalendarGridRow } from '..'\n\nexport interface DatePickerGridRowProps extends CalendarGridRowProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerGridRowProps>()\n</script>\n\n<template>\n  <CalendarGridRow v-bind=\"props\">\n    <slot />\n  </CalendarGridRow>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarGridRowProps } from '..'\nimport { CalendarGridRow } from '..'\n\nexport interface DatePickerGridRowProps extends CalendarGridRowProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerGridRowProps>()\n</script>\n\n<template>\n  <CalendarGridRow v-bind=\"props\">\n    <slot />\n  </CalendarGridRow>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarHeadCellProps } from '..'\nimport { CalendarHeadCell } from '..'\n\nexport interface DatePickerHeadCellProps extends CalendarHeadCellProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerHeadCellProps>()\n</script>\n\n<template>\n  <CalendarHeadCell v-bind=\"props\">\n    <slot />\n  </CalendarHeadCell>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarHeadCellProps } from '..'\nimport { CalendarHeadCell } from '..'\n\nexport interface DatePickerHeadCellProps extends CalendarHeadCellProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerHeadCellProps>()\n</script>\n\n<template>\n  <CalendarHeadCell v-bind=\"props\">\n    <slot />\n  </CalendarHeadCell>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarHeaderProps } from '..'\nimport { CalendarHeader } from '..'\n\nexport interface DatePickerHeaderProps extends CalendarHeaderProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerHeaderProps>()\n</script>\n\n<template>\n  <CalendarHeader v-bind=\"props\">\n    <slot />\n  </CalendarHeader>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarHeaderProps } from '..'\nimport { CalendarHeader } from '..'\n\nexport interface DatePickerHeaderProps extends CalendarHeaderProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerHeaderProps>()\n</script>\n\n<template>\n  <CalendarHeader v-bind=\"props\">\n    <slot />\n  </CalendarHeader>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarHeadingProps } from '..'\nimport { CalendarHeading } from '..'\n\nexport interface DatePickerHeadingProps extends CalendarHeadingProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerHeadingProps>()\ndefineSlots<{\n  default?: (props: {\n    /** Current month and year */\n    headingValue: string\n  }) => any\n}>()\n</script>\n\n<template>\n  <CalendarHeading\n    v-slot=\"{ headingValue }\"\n    v-bind=\"props\"\n  >\n    <slot :heading-value=\"headingValue\">\n      {{ headingValue }}\n    </slot>\n  </CalendarHeading>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarHeadingProps } from '..'\nimport { CalendarHeading } from '..'\n\nexport interface DatePickerHeadingProps extends CalendarHeadingProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerHeadingProps>()\ndefineSlots<{\n  default?: (props: {\n    /** Current month and year */\n    headingValue: string\n  }) => any\n}>()\n</script>\n\n<template>\n  <CalendarHeading\n    v-slot=\"{ headingValue }\"\n    v-bind=\"props\"\n  >\n    <slot :heading-value=\"headingValue\">\n      {{ headingValue }}\n    </slot>\n  </CalendarHeading>\n</template>\n","<script lang=\"ts\">\nimport type { DateFieldInputProps } from '..'\nimport { DateFieldInput } from '..'\n\nexport interface DatePickerInputProps extends DateFieldInputProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerInputProps>()\n</script>\n\n<template>\n  <DateFieldInput v-bind=\"props\">\n    <slot />\n  </DateFieldInput>\n</template>\n","<script lang=\"ts\">\nimport type { DateFieldInputProps } from '..'\nimport { DateFieldInput } from '..'\n\nexport interface DatePickerInputProps extends DateFieldInputProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerInputProps>()\n</script>\n\n<template>\n  <DateFieldInput v-bind=\"props\">\n    <slot />\n  </DateFieldInput>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarNextProps } from '..'\nimport type { CalendarNextSlot } from '@/Calendar/CalendarNext.vue'\nimport { CalendarNext } from '..'\n\nexport interface DatePickerNextProps extends CalendarNextProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerNextProps>()\n\ndefineSlots<CalendarNextSlot>()\n</script>\n\n<template>\n  <CalendarNext\n    v-slot=\"slotProps\"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </CalendarNext>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarNextProps } from '..'\nimport type { CalendarNextSlot } from '@/Calendar/CalendarNext.vue'\nimport { CalendarNext } from '..'\n\nexport interface DatePickerNextProps extends CalendarNextProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerNextProps>()\n\ndefineSlots<CalendarNextSlot>()\n</script>\n\n<template>\n  <CalendarNext\n    v-slot=\"slotProps\"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </CalendarNext>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarPrevProps } from '..'\nimport type { CalendarPrevSlot } from '@/Calendar/CalendarPrev.vue'\nimport { CalendarPrev } from '..'\n\nexport interface DatePickerPrevProps extends CalendarPrevProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerPrevProps>()\ndefineSlots<CalendarPrevSlot>()\n</script>\n\n<template>\n  <CalendarPrev\n    v-slot=\"slotProps\"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </CalendarPrev>\n</template>\n","<script lang=\"ts\">\nimport type { CalendarPrevProps } from '..'\nimport type { CalendarPrevSlot } from '@/Calendar/CalendarPrev.vue'\nimport { CalendarPrev } from '..'\n\nexport interface DatePickerPrevProps extends CalendarPrevProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerPrevProps>()\ndefineSlots<CalendarPrevSlot>()\n</script>\n\n<template>\n  <CalendarPrev\n    v-slot=\"slotProps\"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </CalendarPrev>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose, useId } from '@/shared'\n\nexport interface PopoverTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted } from 'vue'\nimport { PopperAnchor } from '@/Popper'\nimport { Primitive } from '@/Primitive'\nimport { injectPopoverRootContext } from './PopoverRoot.vue'\n\nconst props = withDefaults(defineProps<PopoverTriggerProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectPopoverRootContext()\n\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\n\nrootContext.triggerId ||= useId(undefined, 'reka-popover-trigger')\nonMounted(() => {\n  rootContext.triggerElement.value = triggerElement.value\n})\n</script>\n\n<template>\n  <component\n    :is=\"rootContext.hasCustomAnchor.value ? Primitive : PopperAnchor\"\n    as-child\n  >\n    <Primitive\n      :id=\"rootContext.triggerId\"\n      :ref=\"forwardRef\"\n      :type=\"as === 'button' ? 'button' : undefined\"\n      aria-haspopup=\"dialog\"\n      :aria-expanded=\"rootContext.open.value\"\n      :aria-controls=\"rootContext.contentId\"\n      :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n      :as=\"as\"\n      :as-child=\"props.asChild\"\n      @click=\"rootContext.onOpenToggle\"\n    >\n      <slot />\n    </Primitive>\n  </component>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose, useId } from '@/shared'\n\nexport interface PopoverTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted } from 'vue'\nimport { PopperAnchor } from '@/Popper'\nimport { Primitive } from '@/Primitive'\nimport { injectPopoverRootContext } from './PopoverRoot.vue'\n\nconst props = withDefaults(defineProps<PopoverTriggerProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectPopoverRootContext()\n\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\n\nrootContext.triggerId ||= useId(undefined, 'reka-popover-trigger')\nonMounted(() => {\n  rootContext.triggerElement.value = triggerElement.value\n})\n</script>\n\n<template>\n  <component\n    :is=\"rootContext.hasCustomAnchor.value ? Primitive : PopperAnchor\"\n    as-child\n  >\n    <Primitive\n      :id=\"rootContext.triggerId\"\n      :ref=\"forwardRef\"\n      :type=\"as === 'button' ? 'button' : undefined\"\n      aria-haspopup=\"dialog\"\n      :aria-expanded=\"rootContext.open.value\"\n      :aria-controls=\"rootContext.contentId\"\n      :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n      :as=\"as\"\n      :as-child=\"props.asChild\"\n      @click=\"rootContext.onOpenToggle\"\n    >\n      <slot />\n    </Primitive>\n  </component>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverTriggerProps } from '..'\nimport { PopoverTrigger } from '..'\nimport { injectDatePickerRootContext } from './DatePickerRoot.vue'\n\nexport interface DatePickerTriggerProps extends PopoverTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerTriggerProps>()\nconst rootContext = injectDatePickerRootContext()\n</script>\n\n<template>\n  <PopoverTrigger\n    data-reka-date-field-segment=\"trigger\"\n    v-bind=\"props\"\n    :disabled=\"rootContext.disabled.value\"\n    @focusin=\"(e: FocusEvent) => {\n      rootContext.dateFieldRef.value?.setFocusedElement(e.target as HTMLElement)\n    }\"\n  >\n    <slot />\n  </PopoverTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverTriggerProps } from '..'\nimport { PopoverTrigger } from '..'\nimport { injectDatePickerRootContext } from './DatePickerRoot.vue'\n\nexport interface DatePickerTriggerProps extends PopoverTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DatePickerTriggerProps>()\nconst rootContext = injectDatePickerRootContext()\n</script>\n\n<template>\n  <PopoverTrigger\n    data-reka-date-field-segment=\"trigger\"\n    v-bind=\"props\"\n    :disabled=\"rootContext.disabled.value\"\n    @focusin=\"(e: FocusEvent) => {\n      rootContext.dateFieldRef.value?.setFocusedElement(e.target as HTMLElement)\n    }\"\n  >\n    <slot />\n  </PopoverTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\n\nimport type { Ref } from 'vue'\nimport type { Matcher } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { DateRange, DateStep, Granularity, HourCycle, SegmentPart, SegmentValueObj } from '@/shared/date'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport {\n  areAllDaysBetweenValid,\n  hasTime,\n  isBefore,\n  isBeforeOrSame,\n} from '@/date'\nimport { createContext, useDateFormatter, useDirection, useKbd, useLocale } from '@/shared'\nimport {\n  createContent,\n  getDefaultDate,\n  getSegmentElements,\n  initializeSegmentValues,\n  isSegmentNavigationKey,\n  normalizeDateStep,\n  normalizeHourCycle,\n\n  syncSegmentValues,\n} from '@/shared/date'\n\nexport type DateRangeType = 'start' | 'end'\n\ntype DateRangeFieldRootContext = {\n  locale: Ref<string>\n  startValue: Ref<DateValue | undefined>\n  endValue: Ref<DateValue | undefined>\n  placeholder: Ref<DateValue>\n  isDateUnavailable?: Matcher\n  isInvalid: Ref<boolean>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  formatter: Formatter\n  hourCycle: HourCycle\n  step: Ref<DateStep>\n  segmentValues: Record<DateRangeType, Ref<SegmentValueObj>>\n  segmentContents: Ref<{ start: { part: SegmentPart, value: string }[], end: { part: SegmentPart, value: string }[] }>\n  elements: Ref<Set<HTMLElement>>\n  focusNext: () => void\n  setFocusedElement: (el: HTMLElement) => void\n}\n\nexport interface DateRangeFieldRootProps extends PrimitiveProps, FormFieldProps {\n  /** The default value for the calendar */\n  defaultValue?: DateRange\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The placeholder date, which is used to determine what month to display when no date is selected. This updates as the user navigates the calendar and can be used to programmatically control the calendar view */\n  placeholder?: DateValue\n  /** The controlled value of the field. Can be bound as `v-model`. */\n  modelValue?: DateRange | null\n  /** The hour cycle used for formatting times. Defaults to the local preference */\n  hourCycle?: HourCycle\n  /** The stepping interval for the time fields. Defaults to `1`. */\n  step?: DateStep\n  /** The granularity to use for formatting times. Defaults to day if a CalendarDate is provided, otherwise defaults to minute. The field will render segments for each part of the date up to and including the specified granularity */\n  granularity?: Granularity\n  /** Whether or not to hide the time zone segment of the field */\n  hideTimeZone?: boolean\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether or not the date field is disabled */\n  disabled?: boolean\n  /** Whether or not the date field is readonly */\n  readonly?: boolean\n  /** A function that returns whether or not a date is unavailable */\n  isDateUnavailable?: Matcher\n  /** Id of the element */\n  id?: string\n  /** The reading direction of the date field when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n}\n\nexport type DateRangeFieldRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateRange]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n}\n\nexport const [injectDateRangeFieldRootContext, provideDateRangeFieldRootContext]\n  = createContext<DateRangeFieldRootContext>('DateRangeFieldRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { VisuallyHidden } from '@/VisuallyHidden'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<DateRangeFieldRootProps>(), {\n  defaultValue: undefined,\n  disabled: false,\n  readonly: false,\n  placeholder: undefined,\n  isDateUnavailable: undefined,\n})\nconst emits = defineEmits<DateRangeFieldRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current date range of the field */\n    modelValue: DateRange | null\n    /** The date field segment contents */\n    segments: { start: { part: SegmentPart, value: string }[], end: { part: SegmentPart, value: string }[] }\n    /** Value if the input is invalid */\n    isInvalid: boolean\n  }) => any\n}>()\nconst { disabled, readonly, isDateUnavailable: propsIsDateUnavailable, dir: propDir, locale: propLocale } = toRefs(props)\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\n\nconst formatter = useDateFormatter(locale.value, {\n  hourCycle: normalizeHourCycle(props.hourCycle),\n})\nconst { primitiveElement, currentElement: parentElement }\n  = usePrimitiveElement()\nconst segmentElements = ref<Set<HTMLElement>>(new Set())\n\nonMounted(() => {\n  getSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n})\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? { start: undefined, end: undefined },\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateRange | null>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  granularity: props.granularity,\n  defaultValue: modelValue.value?.start,\n  locale: props.locale,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nconst step = computed(() => normalizeDateStep(props))\n\nconst inferredGranularity = computed(() => {\n  if (props.granularity)\n    return !hasTime(placeholder.value) ? 'day' : props.granularity\n\n  return hasTime(placeholder.value) ? 'minute' : 'day'\n})\n\nconst isStartInvalid = computed(() => {\n  if (!modelValue.value?.start)\n    return false\n\n  if (propsIsDateUnavailable.value?.(modelValue.value.start))\n    return true\n\n  if (props.minValue && isBefore(modelValue.value.start, props.minValue))\n    return true\n\n  if (props.maxValue && isBefore(props.maxValue, modelValue.value.start))\n    return true\n\n  return false\n})\n\nconst isEndInvalid = computed(() => {\n  if (!modelValue.value?.end)\n    return false\n\n  if (propsIsDateUnavailable.value?.(modelValue.value.end))\n    return true\n\n  if (props.minValue && isBefore(modelValue.value.end, props.minValue))\n    return true\n\n  if (props.maxValue && isBefore(props.maxValue, modelValue.value.end))\n    return true\n\n  return false\n})\n\nconst isInvalid = computed(() => {\n  if (isStartInvalid.value || isEndInvalid.value)\n    return true\n\n  if (!modelValue.value?.start || !modelValue.value?.end)\n    return false\n\n  if (!isBeforeOrSame(modelValue.value.start, modelValue.value.end))\n    return true\n\n  if (propsIsDateUnavailable.value !== undefined) {\n    const allValid = areAllDaysBetweenValid(\n      modelValue.value.start,\n      modelValue.value.end,\n      propsIsDateUnavailable.value,\n      undefined,\n    )\n    if (!allValid)\n      return true\n  }\n  return false\n})\n\nconst initialSegments = initializeSegmentValues(inferredGranularity.value)\n\nconst startSegmentValues = ref<SegmentValueObj>(modelValue.value?.start ? { ...syncSegmentValues({ value: modelValue.value.start, formatter }) } : { ...initialSegments })\nconst endSegmentValues = ref<SegmentValueObj>(modelValue.value?.end ? { ...syncSegmentValues({ value: modelValue.value.end, formatter }) } : { ...initialSegments })\n\nconst startSegmentContent = computed(() => createContent({\n  granularity: inferredGranularity.value,\n  dateRef: placeholder.value,\n  formatter,\n  hideTimeZone: props.hideTimeZone,\n  hourCycle: props.hourCycle,\n  segmentValues: startSegmentValues.value,\n  locale,\n}))\n\nconst endSegmentContent = computed(() => createContent({\n  granularity: inferredGranularity.value,\n  dateRef: placeholder.value,\n  formatter,\n  hideTimeZone: props.hideTimeZone,\n  hourCycle: props.hourCycle,\n  segmentValues: endSegmentValues.value,\n  locale,\n}))\n\nconst segmentContents = computed(() => ({\n  start: startSegmentContent.value.arr,\n  end: endSegmentContent.value.arr,\n}))\n\nconst editableSegmentContents = computed(() => ({ start: segmentContents.value.start.filter(({ part }) => part !== 'literal'), end: segmentContents.value.end.filter(({ part }) => part !== 'literal') }))\n\nconst startValue = ref(modelValue.value?.start?.copy()) as Ref<DateValue | undefined>\nconst endValue = ref(modelValue.value?.end?.copy()) as Ref<DateValue | undefined>\n\nwatch([startValue, endValue], ([_startValue, _endValue]) => {\n  modelValue.value = { start: _startValue?.copy(), end: _endValue?.copy() }\n})\n\nwatch(modelValue, (_modelValue) => {\n  const isStartChanged = _modelValue?.start && startValue.value\n    ? _modelValue.start.compare(startValue.value) !== 0\n    : _modelValue?.start !== startValue.value\n  if (isStartChanged) {\n    startValue.value = _modelValue?.start?.copy()\n  }\n\n  const isEndChanged = _modelValue?.end && endValue.value\n    ? _modelValue.end.compare(endValue.value) !== 0\n    : _modelValue?.end !== endValue.value\n  if (isEndChanged) {\n    endValue.value = _modelValue?.end?.copy()\n  }\n})\n\nwatch([startValue, locale], ([_startValue]) => {\n  if (_startValue !== undefined) {\n    startSegmentValues.value = { ...syncSegmentValues({ value: _startValue, formatter }) }\n  }\n  // If segment has null value, means that user modified it, thus do not reset the segmentValues\n  else if (Object.values(startSegmentValues.value).every(value => value !== null) && _startValue === undefined) {\n    startSegmentValues.value = { ...initialSegments }\n  }\n})\n\nwatch(locale, (value) => {\n  if (formatter.getLocale() !== value) {\n    formatter.setLocale(value)\n    // Locale changed, so we need to clear the segment elements and re-get them (different order)\n    // Get the focusable elements again on the next tick\n    nextTick(() => {\n      segmentElements.value.clear()\n      getSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n    })\n  }\n})\n\nwatch(modelValue, (_modelValue) => {\n  if (_modelValue && _modelValue.start !== undefined && placeholder.value.compare(_modelValue.start) !== 0)\n    placeholder.value = _modelValue.start.copy()\n})\n\nwatch([endValue, locale], ([_endValue]) => {\n  if (_endValue !== undefined) {\n    endSegmentValues.value = { ...syncSegmentValues({ value: _endValue, formatter }) }\n  }\n  // If segment has null value, means that user modified it, thus do not reset the segmentValues\n  else if (Object.values(endSegmentValues.value).every(value => value !== null) && _endValue === undefined) {\n    endSegmentValues.value = { ...initialSegments }\n  }\n})\n\nconst currentFocusedElement = ref<HTMLElement | null>(null)\n\nconst currentSegmentIndex = computed(() => Array.from(segmentElements.value).findIndex(el =>\n  el.getAttribute('data-reka-date-field-segment') === currentFocusedElement.value?.getAttribute('data-reka-date-field-segment')\n  && el.getAttribute('data-reka-date-range-field-segment-type') === currentFocusedElement.value?.getAttribute('data-reka-date-range-field-segment-type')))\n\nconst nextFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const nextCondition = sign < 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (nextCondition)\n    return null\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value + sign]\n  return segmentToFocus\n})\n\nconst prevFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const prevCondition = sign > 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (prevCondition)\n    return null\n\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value - sign]\n  return segmentToFocus\n})\n\nconst kbd = useKbd()\n\nfunction handleKeydown(e: KeyboardEvent) {\n  // Don't navigate between segments mid-composition, arrow keys are used for IME candidate navigation\n  if (e.isComposing)\n    return\n  if (!isSegmentNavigationKey(e.key))\n    return\n  if (e.key === kbd.ARROW_LEFT)\n    prevFocusableSegment.value?.focus()\n  if (e.key === kbd.ARROW_RIGHT)\n    nextFocusableSegment.value?.focus()\n}\n\nfunction setFocusedElement(el: HTMLElement) {\n  currentFocusedElement.value = el\n}\n\nprovideDateRangeFieldRootContext({\n  isDateUnavailable: propsIsDateUnavailable.value,\n  locale,\n  startValue,\n  endValue,\n  placeholder,\n  disabled,\n  formatter,\n  hourCycle: props.hourCycle,\n  step,\n  readonly,\n  segmentValues: { start: startSegmentValues, end: endSegmentValues },\n  isInvalid,\n  segmentContents: editableSegmentContents,\n  elements: segmentElements,\n  setFocusedElement,\n  focusNext() {\n    nextFocusableSegment.value?.focus()\n  },\n})\n\ndefineExpose({\n  setFocusedElement,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    ref=\"primitiveElement\"\n    role=\"group\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n    @keydown.left.right=\"handleKeydown\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :segments=\"segmentContents\"\n      :is-invalid=\"isInvalid\"\n    />\n\n    <VisuallyHidden\n      :id=\"id\"\n      as=\"input\"\n      feature=\"focusable\"\n      tabindex=\"-1\"\n      :value=\"`${modelValue?.start?.toString()} - ${modelValue?.end?.toString()}`\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n      @focus=\"Array.from(segmentElements)?.[0]?.focus()\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\n\nimport type { Ref } from 'vue'\nimport type { Matcher } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { DateRange, DateStep, Granularity, HourCycle, SegmentPart, SegmentValueObj } from '@/shared/date'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport {\n  areAllDaysBetweenValid,\n  hasTime,\n  isBefore,\n  isBeforeOrSame,\n} from '@/date'\nimport { createContext, useDateFormatter, useDirection, useKbd, useLocale } from '@/shared'\nimport {\n  createContent,\n  getDefaultDate,\n  getSegmentElements,\n  initializeSegmentValues,\n  isSegmentNavigationKey,\n  normalizeDateStep,\n  normalizeHourCycle,\n\n  syncSegmentValues,\n} from '@/shared/date'\n\nexport type DateRangeType = 'start' | 'end'\n\ntype DateRangeFieldRootContext = {\n  locale: Ref<string>\n  startValue: Ref<DateValue | undefined>\n  endValue: Ref<DateValue | undefined>\n  placeholder: Ref<DateValue>\n  isDateUnavailable?: Matcher\n  isInvalid: Ref<boolean>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  formatter: Formatter\n  hourCycle: HourCycle\n  step: Ref<DateStep>\n  segmentValues: Record<DateRangeType, Ref<SegmentValueObj>>\n  segmentContents: Ref<{ start: { part: SegmentPart, value: string }[], end: { part: SegmentPart, value: string }[] }>\n  elements: Ref<Set<HTMLElement>>\n  focusNext: () => void\n  setFocusedElement: (el: HTMLElement) => void\n}\n\nexport interface DateRangeFieldRootProps extends PrimitiveProps, FormFieldProps {\n  /** The default value for the calendar */\n  defaultValue?: DateRange\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The placeholder date, which is used to determine what month to display when no date is selected. This updates as the user navigates the calendar and can be used to programmatically control the calendar view */\n  placeholder?: DateValue\n  /** The controlled value of the field. Can be bound as `v-model`. */\n  modelValue?: DateRange | null\n  /** The hour cycle used for formatting times. Defaults to the local preference */\n  hourCycle?: HourCycle\n  /** The stepping interval for the time fields. Defaults to `1`. */\n  step?: DateStep\n  /** The granularity to use for formatting times. Defaults to day if a CalendarDate is provided, otherwise defaults to minute. The field will render segments for each part of the date up to and including the specified granularity */\n  granularity?: Granularity\n  /** Whether or not to hide the time zone segment of the field */\n  hideTimeZone?: boolean\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether or not the date field is disabled */\n  disabled?: boolean\n  /** Whether or not the date field is readonly */\n  readonly?: boolean\n  /** A function that returns whether or not a date is unavailable */\n  isDateUnavailable?: Matcher\n  /** Id of the element */\n  id?: string\n  /** The reading direction of the date field when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n}\n\nexport type DateRangeFieldRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateRange]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n}\n\nexport const [injectDateRangeFieldRootContext, provideDateRangeFieldRootContext]\n  = createContext<DateRangeFieldRootContext>('DateRangeFieldRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { VisuallyHidden } from '@/VisuallyHidden'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<DateRangeFieldRootProps>(), {\n  defaultValue: undefined,\n  disabled: false,\n  readonly: false,\n  placeholder: undefined,\n  isDateUnavailable: undefined,\n})\nconst emits = defineEmits<DateRangeFieldRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current date range of the field */\n    modelValue: DateRange | null\n    /** The date field segment contents */\n    segments: { start: { part: SegmentPart, value: string }[], end: { part: SegmentPart, value: string }[] }\n    /** Value if the input is invalid */\n    isInvalid: boolean\n  }) => any\n}>()\nconst { disabled, readonly, isDateUnavailable: propsIsDateUnavailable, dir: propDir, locale: propLocale } = toRefs(props)\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\n\nconst formatter = useDateFormatter(locale.value, {\n  hourCycle: normalizeHourCycle(props.hourCycle),\n})\nconst { primitiveElement, currentElement: parentElement }\n  = usePrimitiveElement()\nconst segmentElements = ref<Set<HTMLElement>>(new Set())\n\nonMounted(() => {\n  getSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n})\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? { start: undefined, end: undefined },\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateRange | null>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  granularity: props.granularity,\n  defaultValue: modelValue.value?.start,\n  locale: props.locale,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nconst step = computed(() => normalizeDateStep(props))\n\nconst inferredGranularity = computed(() => {\n  if (props.granularity)\n    return !hasTime(placeholder.value) ? 'day' : props.granularity\n\n  return hasTime(placeholder.value) ? 'minute' : 'day'\n})\n\nconst isStartInvalid = computed(() => {\n  if (!modelValue.value?.start)\n    return false\n\n  if (propsIsDateUnavailable.value?.(modelValue.value.start))\n    return true\n\n  if (props.minValue && isBefore(modelValue.value.start, props.minValue))\n    return true\n\n  if (props.maxValue && isBefore(props.maxValue, modelValue.value.start))\n    return true\n\n  return false\n})\n\nconst isEndInvalid = computed(() => {\n  if (!modelValue.value?.end)\n    return false\n\n  if (propsIsDateUnavailable.value?.(modelValue.value.end))\n    return true\n\n  if (props.minValue && isBefore(modelValue.value.end, props.minValue))\n    return true\n\n  if (props.maxValue && isBefore(props.maxValue, modelValue.value.end))\n    return true\n\n  return false\n})\n\nconst isInvalid = computed(() => {\n  if (isStartInvalid.value || isEndInvalid.value)\n    return true\n\n  if (!modelValue.value?.start || !modelValue.value?.end)\n    return false\n\n  if (!isBeforeOrSame(modelValue.value.start, modelValue.value.end))\n    return true\n\n  if (propsIsDateUnavailable.value !== undefined) {\n    const allValid = areAllDaysBetweenValid(\n      modelValue.value.start,\n      modelValue.value.end,\n      propsIsDateUnavailable.value,\n      undefined,\n    )\n    if (!allValid)\n      return true\n  }\n  return false\n})\n\nconst initialSegments = initializeSegmentValues(inferredGranularity.value)\n\nconst startSegmentValues = ref<SegmentValueObj>(modelValue.value?.start ? { ...syncSegmentValues({ value: modelValue.value.start, formatter }) } : { ...initialSegments })\nconst endSegmentValues = ref<SegmentValueObj>(modelValue.value?.end ? { ...syncSegmentValues({ value: modelValue.value.end, formatter }) } : { ...initialSegments })\n\nconst startSegmentContent = computed(() => createContent({\n  granularity: inferredGranularity.value,\n  dateRef: placeholder.value,\n  formatter,\n  hideTimeZone: props.hideTimeZone,\n  hourCycle: props.hourCycle,\n  segmentValues: startSegmentValues.value,\n  locale,\n}))\n\nconst endSegmentContent = computed(() => createContent({\n  granularity: inferredGranularity.value,\n  dateRef: placeholder.value,\n  formatter,\n  hideTimeZone: props.hideTimeZone,\n  hourCycle: props.hourCycle,\n  segmentValues: endSegmentValues.value,\n  locale,\n}))\n\nconst segmentContents = computed(() => ({\n  start: startSegmentContent.value.arr,\n  end: endSegmentContent.value.arr,\n}))\n\nconst editableSegmentContents = computed(() => ({ start: segmentContents.value.start.filter(({ part }) => part !== 'literal'), end: segmentContents.value.end.filter(({ part }) => part !== 'literal') }))\n\nconst startValue = ref(modelValue.value?.start?.copy()) as Ref<DateValue | undefined>\nconst endValue = ref(modelValue.value?.end?.copy()) as Ref<DateValue | undefined>\n\nwatch([startValue, endValue], ([_startValue, _endValue]) => {\n  modelValue.value = { start: _startValue?.copy(), end: _endValue?.copy() }\n})\n\nwatch(modelValue, (_modelValue) => {\n  const isStartChanged = _modelValue?.start && startValue.value\n    ? _modelValue.start.compare(startValue.value) !== 0\n    : _modelValue?.start !== startValue.value\n  if (isStartChanged) {\n    startValue.value = _modelValue?.start?.copy()\n  }\n\n  const isEndChanged = _modelValue?.end && endValue.value\n    ? _modelValue.end.compare(endValue.value) !== 0\n    : _modelValue?.end !== endValue.value\n  if (isEndChanged) {\n    endValue.value = _modelValue?.end?.copy()\n  }\n})\n\nwatch([startValue, locale], ([_startValue]) => {\n  if (_startValue !== undefined) {\n    startSegmentValues.value = { ...syncSegmentValues({ value: _startValue, formatter }) }\n  }\n  // If segment has null value, means that user modified it, thus do not reset the segmentValues\n  else if (Object.values(startSegmentValues.value).every(value => value !== null) && _startValue === undefined) {\n    startSegmentValues.value = { ...initialSegments }\n  }\n})\n\nwatch(locale, (value) => {\n  if (formatter.getLocale() !== value) {\n    formatter.setLocale(value)\n    // Locale changed, so we need to clear the segment elements and re-get them (different order)\n    // Get the focusable elements again on the next tick\n    nextTick(() => {\n      segmentElements.value.clear()\n      getSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n    })\n  }\n})\n\nwatch(modelValue, (_modelValue) => {\n  if (_modelValue && _modelValue.start !== undefined && placeholder.value.compare(_modelValue.start) !== 0)\n    placeholder.value = _modelValue.start.copy()\n})\n\nwatch([endValue, locale], ([_endValue]) => {\n  if (_endValue !== undefined) {\n    endSegmentValues.value = { ...syncSegmentValues({ value: _endValue, formatter }) }\n  }\n  // If segment has null value, means that user modified it, thus do not reset the segmentValues\n  else if (Object.values(endSegmentValues.value).every(value => value !== null) && _endValue === undefined) {\n    endSegmentValues.value = { ...initialSegments }\n  }\n})\n\nconst currentFocusedElement = ref<HTMLElement | null>(null)\n\nconst currentSegmentIndex = computed(() => Array.from(segmentElements.value).findIndex(el =>\n  el.getAttribute('data-reka-date-field-segment') === currentFocusedElement.value?.getAttribute('data-reka-date-field-segment')\n  && el.getAttribute('data-reka-date-range-field-segment-type') === currentFocusedElement.value?.getAttribute('data-reka-date-range-field-segment-type')))\n\nconst nextFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const nextCondition = sign < 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (nextCondition)\n    return null\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value + sign]\n  return segmentToFocus\n})\n\nconst prevFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const prevCondition = sign > 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (prevCondition)\n    return null\n\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value - sign]\n  return segmentToFocus\n})\n\nconst kbd = useKbd()\n\nfunction handleKeydown(e: KeyboardEvent) {\n  // Don't navigate between segments mid-composition, arrow keys are used for IME candidate navigation\n  if (e.isComposing)\n    return\n  if (!isSegmentNavigationKey(e.key))\n    return\n  if (e.key === kbd.ARROW_LEFT)\n    prevFocusableSegment.value?.focus()\n  if (e.key === kbd.ARROW_RIGHT)\n    nextFocusableSegment.value?.focus()\n}\n\nfunction setFocusedElement(el: HTMLElement) {\n  currentFocusedElement.value = el\n}\n\nprovideDateRangeFieldRootContext({\n  isDateUnavailable: propsIsDateUnavailable.value,\n  locale,\n  startValue,\n  endValue,\n  placeholder,\n  disabled,\n  formatter,\n  hourCycle: props.hourCycle,\n  step,\n  readonly,\n  segmentValues: { start: startSegmentValues, end: endSegmentValues },\n  isInvalid,\n  segmentContents: editableSegmentContents,\n  elements: segmentElements,\n  setFocusedElement,\n  focusNext() {\n    nextFocusableSegment.value?.focus()\n  },\n})\n\ndefineExpose({\n  setFocusedElement,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    ref=\"primitiveElement\"\n    role=\"group\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n    @keydown.left.right=\"handleKeydown\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :segments=\"segmentContents\"\n      :is-invalid=\"isInvalid\"\n    />\n\n    <VisuallyHidden\n      :id=\"id\"\n      as=\"input\"\n      feature=\"focusable\"\n      tabindex=\"-1\"\n      :value=\"`${modelValue?.start?.toString()} - ${modelValue?.end?.toString()}`\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n      @focus=\"Array.from(segmentElements)?.[0]?.focus()\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateRangeType } from './DateRangeFieldRoot.vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { SegmentPart } from '@/shared/date'\nimport { computed, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useDateField } from '@/shared/date/useDateField'\nimport { injectDateRangeFieldRootContext } from './DateRangeFieldRoot.vue'\n\nexport interface DateRangeFieldInputProps extends PrimitiveProps {\n  /** The part of the date to render */\n  part: SegmentPart\n  /** The type of field to render (start or end) */\n  type: DateRangeType\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangeFieldInputProps>()\n\nconst rootContext = injectDateRangeFieldRootContext()\n\nconst hasLeftFocus = ref(true)\nconst lastKeyZero = ref(false)\n\nconst {\n  handleSegmentClick,\n  handleSegmentKeydown,\n  handleSegmentBeforeInput,\n  handleSegmentCompositionStart,\n  handleSegmentCompositionEnd,\n  attributes,\n} = useDateField({\n  hasLeftFocus,\n  lastKeyZero,\n  placeholder: rootContext.placeholder,\n  hourCycle: rootContext.hourCycle,\n  step: rootContext.step,\n  segmentValues: rootContext.segmentValues[props.type],\n  formatter: rootContext.formatter,\n  part: props.part,\n  disabled: rootContext.disabled,\n  readonly: rootContext.readonly,\n  focusNext: rootContext.focusNext,\n  modelValue: props.type === 'start' ? rootContext.startValue : rootContext.endValue,\n})\n\nconst disabled = computed(() => rootContext.disabled.value)\nconst readonly = computed(() => rootContext.readonly.value)\nconst isInvalid = computed(() => rootContext.isInvalid.value)\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    v-bind=\"attributes\"\n    :contenteditable=\"disabled || readonly ? false : part !== 'literal'\"\n    :data-reka-date-field-segment=\"part\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :aria-readonly=\"readonly ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-reka-date-range-field-segment-type=\"type\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :aria-invalid=\"isInvalid ? true : undefined\"\n    v-on=\"part !== 'literal' ? {\n      mousedown: handleSegmentClick,\n      keydown: handleSegmentKeydown,\n      beforeinput: handleSegmentBeforeInput,\n      compositionstart: handleSegmentCompositionStart,\n      compositionend: handleSegmentCompositionEnd,\n      focusout: () => { hasLeftFocus = true },\n      focusin: (e: FocusEvent) => {\n        rootContext.setFocusedElement(e.target as HTMLElement)\n      },\n    } : {}\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateRangeType } from './DateRangeFieldRoot.vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { SegmentPart } from '@/shared/date'\nimport { computed, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useDateField } from '@/shared/date/useDateField'\nimport { injectDateRangeFieldRootContext } from './DateRangeFieldRoot.vue'\n\nexport interface DateRangeFieldInputProps extends PrimitiveProps {\n  /** The part of the date to render */\n  part: SegmentPart\n  /** The type of field to render (start or end) */\n  type: DateRangeType\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangeFieldInputProps>()\n\nconst rootContext = injectDateRangeFieldRootContext()\n\nconst hasLeftFocus = ref(true)\nconst lastKeyZero = ref(false)\n\nconst {\n  handleSegmentClick,\n  handleSegmentKeydown,\n  handleSegmentBeforeInput,\n  handleSegmentCompositionStart,\n  handleSegmentCompositionEnd,\n  attributes,\n} = useDateField({\n  hasLeftFocus,\n  lastKeyZero,\n  placeholder: rootContext.placeholder,\n  hourCycle: rootContext.hourCycle,\n  step: rootContext.step,\n  segmentValues: rootContext.segmentValues[props.type],\n  formatter: rootContext.formatter,\n  part: props.part,\n  disabled: rootContext.disabled,\n  readonly: rootContext.readonly,\n  focusNext: rootContext.focusNext,\n  modelValue: props.type === 'start' ? rootContext.startValue : rootContext.endValue,\n})\n\nconst disabled = computed(() => rootContext.disabled.value)\nconst readonly = computed(() => rootContext.readonly.value)\nconst isInvalid = computed(() => rootContext.isInvalid.value)\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    v-bind=\"attributes\"\n    :contenteditable=\"disabled || readonly ? false : part !== 'literal'\"\n    :data-reka-date-field-segment=\"part\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :aria-readonly=\"readonly ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-reka-date-range-field-segment-type=\"type\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :aria-invalid=\"isInvalid ? true : undefined\"\n    v-on=\"part !== 'literal' ? {\n      mousedown: handleSegmentClick,\n      keydown: handleSegmentKeydown,\n      beforeinput: handleSegmentBeforeInput,\n      compositionstart: handleSegmentCompositionStart,\n      compositionend: handleSegmentCompositionEnd,\n      focusout: () => { hasLeftFocus = true },\n      focusin: (e: FocusEvent) => {\n        rootContext.setFocusedElement(e.target as HTMLElement)\n      },\n    } : {}\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverAnchorProps } from '..'\nimport { PopoverAnchor } from '..'\n\nexport interface DateRangePickerAnchorProps extends PopoverAnchorProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerAnchorProps>()\n</script>\n\n<template>\n  <PopoverAnchor v-bind=\"props\">\n    <slot />\n  </PopoverAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverAnchorProps } from '..'\nimport { PopoverAnchor } from '..'\n\nexport interface DateRangePickerAnchorProps extends PopoverAnchorProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerAnchorProps>()\n</script>\n\n<template>\n  <PopoverAnchor v-bind=\"props\">\n    <slot />\n  </PopoverAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverArrowProps } from '..'\nimport { PopoverArrow } from '..'\n\nexport interface DateRangePickerArrowProps extends PopoverArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerArrowProps>()\n</script>\n\n<template>\n  <PopoverArrow v-bind=\"props\">\n    <slot />\n  </PopoverArrow>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverArrowProps } from '..'\nimport { PopoverArrow } from '..'\n\nexport interface DateRangePickerArrowProps extends PopoverArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerArrowProps>()\n</script>\n\n<template>\n  <PopoverArrow v-bind=\"props\">\n    <slot />\n  </PopoverArrow>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\n\nimport type { Ref } from 'vue'\nimport type { DateRangeFieldRoot, DateRangeFieldRootProps, PopoverRootEmits, PopoverRootProps, RangeCalendarRootProps } from '..'\nimport type { Matcher, WeekDayFormat, WeekStartsOn } from '@/date'\nimport type { DateRange, DateStep, Granularity, HourCycle } from '@/shared/date'\n\nimport type { Direction } from '@/shared/types'\nimport { getWeekStartsOn } from '@/date'\nimport { createContext, useDirection, useLocale } from '@/shared'\nimport { getDefaultDate } from '@/shared/date'\nimport { PopoverRoot } from '..'\n\ntype DateRangePickerRootContext = {\n  id: Ref<string | undefined>\n  name: Ref<string | undefined>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  hourCycle: Ref<HourCycle | undefined>\n  granularity: Ref<Granularity | undefined>\n  hideTimeZone: Ref<boolean>\n  required: Ref<boolean>\n  locale: Ref<string>\n  dateFieldRef: Ref<InstanceType<typeof DateRangeFieldRoot> | undefined>\n  modelValue: Ref<{ start: DateValue | undefined, end: DateValue | undefined }>\n  placeholder: Ref<DateValue>\n  pagedNavigation: Ref<boolean>\n  preventDeselect: Ref<boolean>\n  weekStartsOn: Ref<WeekStartsOn>\n  weekdayFormat: Ref<WeekDayFormat>\n  fixedWeeks: Ref<boolean>\n  numberOfMonths: Ref<number>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  isDateDisabled?: Matcher\n  isDateUnavailable?: Matcher\n  isDateHighlightable?: Matcher\n  defaultOpen: Ref<boolean>\n  open: Ref<boolean>\n  modal: Ref<boolean>\n  onDateChange: (date: DateRange) => void\n  onPlaceholderChange: (date: DateValue) => void\n  onStartValueChange: (date: DateValue | undefined) => void\n  dir: Ref<Direction>\n  allowNonContiguousRanges: Ref<boolean>\n  fixedDate: Ref<'start' | 'end' | undefined>\n  maximumDays?: Ref<number | undefined>\n  step: Ref<DateStep | undefined>\n  closeOnSelect?: Ref<boolean>\n}\n\nexport type DateRangePickerRootProps = Omit<DateRangeFieldRootProps, 'as' | 'asChild'> & PopoverRootProps & Pick<RangeCalendarRootProps, 'isDateDisabled' | 'pagedNavigation' | 'weekStartsOn' | 'weekdayFormat' | 'fixedWeeks' | 'numberOfMonths' | 'preventDeselect' | 'isDateUnavailable' | 'isDateHighlightable' | 'allowNonContiguousRanges' | 'fixedDate' | 'maximumDays'> & {\n  /** Whether or not to close the popover on range select */\n  closeOnSelect?: boolean\n}\n\nexport type DateRangePickerRootEmits = PopoverRootEmits & {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateRange]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n  /** Event handler called whenever the start value changes */\n  'update:startValue': [date: DateValue | undefined]\n}\n\nexport const [injectDateRangePickerRootContext, provideDateRangePickerRootContext]\n  = createContext<DateRangePickerRootContext>('DateRangePickerRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRefs, watch } from 'vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\nconst props = withDefaults(defineProps<DateRangePickerRootProps>(), {\n  defaultValue: () => ({ start: undefined, end: undefined }),\n  defaultOpen: false,\n  open: undefined,\n  modal: false,\n  pagedNavigation: false,\n  preventDeselect: false,\n  weekdayFormat: 'narrow',\n  fixedWeeks: false,\n  numberOfMonths: 1,\n  disabled: false,\n  readonly: false,\n  placeholder: undefined,\n  isDateDisabled: undefined,\n  isDateUnavailable: undefined,\n  isDateHighlightable: undefined,\n  allowNonContiguousRanges: false,\n  maximumDays: undefined,\n  closeOnSelect: false,\n})\nconst emits = defineEmits<DateRangePickerRootEmits>()\nconst {\n  locale: propLocale,\n  disabled,\n  readonly,\n  pagedNavigation,\n  weekdayFormat,\n  fixedWeeks,\n  numberOfMonths,\n  preventDeselect,\n  isDateDisabled: propsIsDateDisabled,\n  isDateUnavailable: propsIsDateUnavailable,\n  isDateHighlightable: propsIsDateHighlightable,\n  defaultOpen,\n  modal,\n  id,\n  name,\n  required,\n  minValue,\n  maxValue,\n  granularity,\n  hideTimeZone,\n  hourCycle,\n  dir: propsDir,\n  allowNonContiguousRanges,\n  fixedDate,\n  maximumDays,\n  step,\n  closeOnSelect,\n} = toRefs(props)\n\nconst dir = useDirection(propsDir)\nconst locale = useLocale(propLocale)\nconst weekStartsOn = computed(() => props.weekStartsOn ?? getWeekStartsOn(locale.value))\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? { start: undefined, end: undefined },\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateRange>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  granularity: props.granularity,\n  defaultValue: modelValue.value?.start,\n  locale: locale.value,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: defaultOpen.value,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst dateFieldRef = ref<InstanceType<typeof DateRangeFieldRoot> | undefined>()\n\nwatch(modelValue, (value) => {\n  if (value && value.start && value.start.compare(placeholder.value) !== 0) {\n    placeholder.value = value.start.copy()\n  }\n\n  if (value.start && value.end) {\n    if (closeOnSelect.value) {\n      open.value = false\n    }\n  }\n})\n\nprovideDateRangePickerRootContext({\n  allowNonContiguousRanges,\n  isDateUnavailable: propsIsDateUnavailable.value,\n  isDateDisabled: propsIsDateDisabled.value,\n  isDateHighlightable: propsIsDateHighlightable.value,\n  locale,\n  disabled,\n  pagedNavigation,\n  weekStartsOn,\n  weekdayFormat,\n  fixedWeeks,\n  numberOfMonths,\n  readonly,\n  preventDeselect,\n  modelValue,\n  placeholder,\n  defaultOpen,\n  modal,\n  open,\n  id,\n  name,\n  required,\n  minValue,\n  maxValue,\n  granularity,\n  hideTimeZone,\n  hourCycle,\n  dateFieldRef,\n  dir,\n  fixedDate,\n  maximumDays,\n  step,\n  onStartValueChange(date: DateValue | undefined) {\n    emits('update:startValue', date)\n  },\n  onDateChange(date: DateRange) {\n    modelValue.value = { start: date.start?.copy(), end: date.end?.copy() }\n  },\n  onPlaceholderChange(date: DateValue) {\n    placeholder.value = date.copy()\n  },\n  closeOnSelect,\n})\n</script>\n\n<template>\n  <PopoverRoot\n    v-model:open=\"open\"\n    :default-open=\"defaultOpen\"\n    :modal=\"modal\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :open=\"open\"\n    />\n  </PopoverRoot>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\n\nimport type { Ref } from 'vue'\nimport type { DateRangeFieldRoot, DateRangeFieldRootProps, PopoverRootEmits, PopoverRootProps, RangeCalendarRootProps } from '..'\nimport type { Matcher, WeekDayFormat, WeekStartsOn } from '@/date'\nimport type { DateRange, DateStep, Granularity, HourCycle } from '@/shared/date'\n\nimport type { Direction } from '@/shared/types'\nimport { getWeekStartsOn } from '@/date'\nimport { createContext, useDirection, useLocale } from '@/shared'\nimport { getDefaultDate } from '@/shared/date'\nimport { PopoverRoot } from '..'\n\ntype DateRangePickerRootContext = {\n  id: Ref<string | undefined>\n  name: Ref<string | undefined>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  hourCycle: Ref<HourCycle | undefined>\n  granularity: Ref<Granularity | undefined>\n  hideTimeZone: Ref<boolean>\n  required: Ref<boolean>\n  locale: Ref<string>\n  dateFieldRef: Ref<InstanceType<typeof DateRangeFieldRoot> | undefined>\n  modelValue: Ref<{ start: DateValue | undefined, end: DateValue | undefined }>\n  placeholder: Ref<DateValue>\n  pagedNavigation: Ref<boolean>\n  preventDeselect: Ref<boolean>\n  weekStartsOn: Ref<WeekStartsOn>\n  weekdayFormat: Ref<WeekDayFormat>\n  fixedWeeks: Ref<boolean>\n  numberOfMonths: Ref<number>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  isDateDisabled?: Matcher\n  isDateUnavailable?: Matcher\n  isDateHighlightable?: Matcher\n  defaultOpen: Ref<boolean>\n  open: Ref<boolean>\n  modal: Ref<boolean>\n  onDateChange: (date: DateRange) => void\n  onPlaceholderChange: (date: DateValue) => void\n  onStartValueChange: (date: DateValue | undefined) => void\n  dir: Ref<Direction>\n  allowNonContiguousRanges: Ref<boolean>\n  fixedDate: Ref<'start' | 'end' | undefined>\n  maximumDays?: Ref<number | undefined>\n  step: Ref<DateStep | undefined>\n  closeOnSelect?: Ref<boolean>\n}\n\nexport type DateRangePickerRootProps = Omit<DateRangeFieldRootProps, 'as' | 'asChild'> & PopoverRootProps & Pick<RangeCalendarRootProps, 'isDateDisabled' | 'pagedNavigation' | 'weekStartsOn' | 'weekdayFormat' | 'fixedWeeks' | 'numberOfMonths' | 'preventDeselect' | 'isDateUnavailable' | 'isDateHighlightable' | 'allowNonContiguousRanges' | 'fixedDate' | 'maximumDays'> & {\n  /** Whether or not to close the popover on range select */\n  closeOnSelect?: boolean\n}\n\nexport type DateRangePickerRootEmits = PopoverRootEmits & {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateRange]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n  /** Event handler called whenever the start value changes */\n  'update:startValue': [date: DateValue | undefined]\n}\n\nexport const [injectDateRangePickerRootContext, provideDateRangePickerRootContext]\n  = createContext<DateRangePickerRootContext>('DateRangePickerRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRefs, watch } from 'vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\nconst props = withDefaults(defineProps<DateRangePickerRootProps>(), {\n  defaultValue: () => ({ start: undefined, end: undefined }),\n  defaultOpen: false,\n  open: undefined,\n  modal: false,\n  pagedNavigation: false,\n  preventDeselect: false,\n  weekdayFormat: 'narrow',\n  fixedWeeks: false,\n  numberOfMonths: 1,\n  disabled: false,\n  readonly: false,\n  placeholder: undefined,\n  isDateDisabled: undefined,\n  isDateUnavailable: undefined,\n  isDateHighlightable: undefined,\n  allowNonContiguousRanges: false,\n  maximumDays: undefined,\n  closeOnSelect: false,\n})\nconst emits = defineEmits<DateRangePickerRootEmits>()\nconst {\n  locale: propLocale,\n  disabled,\n  readonly,\n  pagedNavigation,\n  weekdayFormat,\n  fixedWeeks,\n  numberOfMonths,\n  preventDeselect,\n  isDateDisabled: propsIsDateDisabled,\n  isDateUnavailable: propsIsDateUnavailable,\n  isDateHighlightable: propsIsDateHighlightable,\n  defaultOpen,\n  modal,\n  id,\n  name,\n  required,\n  minValue,\n  maxValue,\n  granularity,\n  hideTimeZone,\n  hourCycle,\n  dir: propsDir,\n  allowNonContiguousRanges,\n  fixedDate,\n  maximumDays,\n  step,\n  closeOnSelect,\n} = toRefs(props)\n\nconst dir = useDirection(propsDir)\nconst locale = useLocale(propLocale)\nconst weekStartsOn = computed(() => props.weekStartsOn ?? getWeekStartsOn(locale.value))\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? { start: undefined, end: undefined },\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateRange>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  granularity: props.granularity,\n  defaultValue: modelValue.value?.start,\n  locale: locale.value,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: defaultOpen.value,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst dateFieldRef = ref<InstanceType<typeof DateRangeFieldRoot> | undefined>()\n\nwatch(modelValue, (value) => {\n  if (value && value.start && value.start.compare(placeholder.value) !== 0) {\n    placeholder.value = value.start.copy()\n  }\n\n  if (value.start && value.end) {\n    if (closeOnSelect.value) {\n      open.value = false\n    }\n  }\n})\n\nprovideDateRangePickerRootContext({\n  allowNonContiguousRanges,\n  isDateUnavailable: propsIsDateUnavailable.value,\n  isDateDisabled: propsIsDateDisabled.value,\n  isDateHighlightable: propsIsDateHighlightable.value,\n  locale,\n  disabled,\n  pagedNavigation,\n  weekStartsOn,\n  weekdayFormat,\n  fixedWeeks,\n  numberOfMonths,\n  readonly,\n  preventDeselect,\n  modelValue,\n  placeholder,\n  defaultOpen,\n  modal,\n  open,\n  id,\n  name,\n  required,\n  minValue,\n  maxValue,\n  granularity,\n  hideTimeZone,\n  hourCycle,\n  dateFieldRef,\n  dir,\n  fixedDate,\n  maximumDays,\n  step,\n  onStartValueChange(date: DateValue | undefined) {\n    emits('update:startValue', date)\n  },\n  onDateChange(date: DateRange) {\n    modelValue.value = { start: date.start?.copy(), end: date.end?.copy() }\n  },\n  onPlaceholderChange(date: DateValue) {\n    placeholder.value = date.copy()\n  },\n  closeOnSelect,\n})\n</script>\n\n<template>\n  <PopoverRoot\n    v-model:open=\"open\"\n    :default-open=\"defaultOpen\"\n    :modal=\"modal\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :open=\"open\"\n    />\n  </PopoverRoot>\n</template>\n","/*\n  * Adapted from https://github.com/melt-ui/melt-ui/blob/develop/src/lib/builders/range-calendar/create.ts\n*/\n\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Matcher } from '@/date'\nimport { isSameDay } from '@internationalized/date'\nimport { computed } from 'vue'\nimport { areAllDaysBetweenValid, getDaysBetween, isBefore, isBetween } from '@/date'\n\nexport type UseRangeCalendarProps = {\n  start: Ref<DateValue | undefined>\n  end: Ref<DateValue | undefined>\n  isDateDisabled: Matcher\n  isDateUnavailable: Matcher\n  isDateHighlightable?: Matcher\n  focusedValue: Ref<DateValue | undefined>\n  allowNonContiguousRanges: Ref<boolean>\n  fixedDate: Ref<'start' | 'end' | undefined>\n  maximumDays?: Ref<number | undefined>\n}\n\nexport function useRangeCalendarState(props: UseRangeCalendarProps) {\n  const isStartInvalid = computed(() => {\n    if (!props.start.value)\n      return false\n    if (props.isDateDisabled(props.start.value))\n      return true\n    return false\n  })\n\n  const isEndInvalid = computed(() => {\n    if (!props.end.value)\n      return false\n    if (props.isDateDisabled(props.end.value))\n      return true\n    return false\n  })\n\n  const isInvalid = computed(\n    () => {\n      if (isStartInvalid.value || isEndInvalid.value)\n        return true\n      if (props.start.value && props.end.value && isBefore(props.end.value, props.start.value))\n        return true\n      return false\n    },\n  )\n\n  const isSelectionStart = (date: DateValue) => {\n    if (!props.start.value)\n      return false\n    return isSameDay(props.start.value, date)\n  }\n\n  const isSelectionEnd = (date: DateValue) => {\n    if (!props.end.value)\n      return false\n    return isSameDay(props.end.value, date)\n  }\n\n  const isSelected = (date: DateValue) => {\n    if (props.start.value && isSameDay(props.start.value, date))\n      return true\n    if (props.end.value && isSameDay(props.end.value, date))\n      return true\n    if (props.end.value && props.start.value)\n      return isBetween(date, props.start.value, props.end.value)\n\n    return false\n  }\n\n  const rangeIsDateDisabled = (date: DateValue) => {\n    if (props.isDateDisabled(date))\n      return true\n\n    if (props.maximumDays?.value) {\n      if (props.start.value && props.end.value) {\n        if (props.fixedDate.value) {\n          const diff = getDaysBetween(props.start.value, props.end.value).length\n          if (diff <= props.maximumDays.value) {\n            const daysLeft = props.maximumDays.value - diff - 1\n            const startLimit = props.start.value.subtract({ days: daysLeft })\n            const endLimit = props.end.value.add({ days: daysLeft })\n            return !isBetween(date, startLimit, endLimit)\n          }\n        }\n        return false\n      }\n      if (props.start.value) {\n        const maxDate = props.start.value.add({ days: props.maximumDays.value })\n        const minDate = props.start.value.subtract({ days: props.maximumDays.value })\n        return !isBetween(date, minDate, maxDate)\n      }\n    }\n\n    return false\n  }\n\n  const isDateHighlightable = (date: DateValue) => {\n    if (props.isDateHighlightable?.(date))\n      return true\n    return false\n  }\n\n  const highlightedRange = computed(() => {\n    if (props.start.value && props.end.value && !props.fixedDate.value)\n      return null\n    if (!props.start.value || !props.focusedValue.value)\n      return null\n\n    const isStartBeforeFocused = isBefore(props.start.value, props.focusedValue.value)\n    const start = isStartBeforeFocused ? props.start.value : props.focusedValue.value\n    const end = isStartBeforeFocused ? props.focusedValue.value : props.start.value\n\n    if (isSameDay(start, end)) {\n      return {\n        start,\n        end,\n      }\n    }\n\n    if (props.maximumDays?.value && !props.end.value) {\n      const maximumDays = props.maximumDays.value\n      const anchor = props.start.value\n      const focused = props.focusedValue.value\n\n      if (!isBefore(focused, anchor))\n        return { start: anchor, end: anchor.add({ days: maximumDays - 1 }) }\n\n      return { start: anchor.subtract({ days: maximumDays - 1 }), end: anchor }\n    }\n\n    const isValid = areAllDaysBetweenValid(start, end, props.allowNonContiguousRanges.value ? () => false : props.isDateUnavailable, rangeIsDateDisabled, props.isDateHighlightable)\n    if (isValid) {\n      return {\n        start,\n        end,\n      }\n    }\n    return null\n  })\n\n  const isHighlightedStart = (date: DateValue) => {\n    if (!highlightedRange.value || !highlightedRange.value.start)\n      return false\n    return isSameDay(highlightedRange.value.start, date)\n  }\n\n  const isHighlightedEnd = (date: DateValue) => {\n    if (!highlightedRange.value || !highlightedRange.value.end)\n      return false\n    return isSameDay(highlightedRange.value.end, date)\n  }\n\n  const hasSelectedDate = computed(() => {\n    return !!(props.start.value || props.end.value)\n  })\n\n  const isStartDateDisabled = computed(() => {\n    return !!(props.start.value && props.isDateDisabled(props.start.value))\n  })\n\n  const isEndDateDisabled = computed(() => {\n    return !!(props.end.value && props.isDateDisabled(props.end.value))\n  })\n\n  const isSelectedDisabled = computed(() => {\n    const hasStart = !!props.start.value\n    const hasEnd = !!props.end.value\n    if (!hasStart && !hasEnd)\n      return false\n    if (hasStart && hasEnd)\n      return isStartDateDisabled.value && isEndDateDisabled.value\n    return (hasStart && isStartDateDisabled.value) || (hasEnd && isEndDateDisabled.value)\n  })\n\n  const selectedFocusableDate = computed(() => {\n    if (props.start.value && !isStartDateDisabled.value)\n      return props.start.value\n    if (props.end.value && !isEndDateDisabled.value)\n      return props.end.value\n    return undefined\n  })\n\n  return {\n    isInvalid,\n    isSelected,\n    isDateHighlightable,\n    highlightedRange,\n    isSelectionStart,\n    isSelectionEnd,\n    isHighlightedStart,\n    isHighlightedEnd,\n    isDateDisabled: rangeIsDateDisabled,\n    hasSelectedDate,\n    isSelectedDisabled,\n    selectedFocusableDate,\n  }\n}\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher, WeekDayFormat, WeekStartsOn } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { DateRange } from '@/shared/date'\nimport type { Direction } from '@/shared/types'\nimport { isEqualDay } from '@internationalized/date'\nimport { useCalendar } from '@/Calendar/useCalendar'\nimport { getWeekStartsOn, isBefore } from '@/date'\nimport {\n  createContext,\n  useDirection,\n  useKbd,\n  useLocale,\n} from '@/shared'\nimport { getDefaultDate, handleCalendarInitialFocus } from '@/shared/date'\nimport { useRangeCalendarState } from './useRangeCalendar'\n\ntype RangeCalendarRootContext = {\n  modelValue: Ref<DateRange>\n  startValue: Ref<DateValue | undefined>\n  endValue: Ref<DateValue | undefined>\n  locale: Ref<string>\n  placeholder: Ref<DateValue>\n  pagedNavigation: Ref<boolean>\n  preventDeselect: Ref<boolean>\n  grid: Ref<Grid<DateValue>[]>\n  weekDays: Ref<string[]>\n  weekStartsOn: Ref<WeekStartsOn>\n  weekdayFormat: Ref<WeekDayFormat>\n  fixedWeeks: Ref<boolean>\n  numberOfMonths: Ref<number>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  initialFocus: Ref<boolean>\n  onPlaceholderChange: (date: DateValue) => void\n  fullCalendarLabel: Ref<string>\n  parentElement: Ref<HTMLElement | undefined>\n  headingValue: Ref<string>\n  isInvalid: Ref<boolean>\n  isDateDisabled: Matcher\n  isDateUnavailable?: Matcher\n  isDateHighlightable?: Matcher\n  isOutsideVisibleView: (date: DateValue) => boolean\n  allowNonContiguousRanges: Ref<boolean>\n  highlightedRange: Ref<{ start: DateValue, end: DateValue } | null>\n  focusedValue: Ref<DateValue | undefined>\n  lastPressedDateValue: Ref<DateValue | undefined>\n  isSelected: (date: DateValue) => boolean\n  isSelectionEnd: (date: DateValue) => boolean\n  isSelectionStart: (date: DateValue) => boolean\n  isHighlightedStart: (date: DateValue) => boolean\n  isHighlightedEnd: (date: DateValue) => boolean\n  prevPage: (prevPageFunc?: (date: DateValue) => DateValue) => void\n  nextPage: (nextPageFunc?: (date: DateValue) => DateValue) => void\n  isNextButtonDisabled: (\n    nextPageFunc?: (date: DateValue) => DateValue,\n  ) => boolean\n  isPrevButtonDisabled: (\n    prevPageFunc?: (date: DateValue) => DateValue,\n  ) => boolean\n  formatter: Formatter\n  dir: Ref<Direction>\n  disableDaysOutsideCurrentView: Ref<boolean>\n  fixedDate: Ref<'start' | 'end' | undefined>\n  maximumDays: Ref<number | undefined>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  isPlaceholderFocusable: Ref<boolean>\n  firstFocusableDate: Ref<DateValue | undefined>\n  hasSelectedDate: Ref<boolean>\n  isSelectedDisabled: Ref<boolean>\n  selectedFocusableDate: Ref<DateValue | undefined>\n}\n\nexport interface RangeCalendarRootProps extends PrimitiveProps {\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The default value for the calendar */\n  defaultValue?: DateRange\n  /** The controlled selected date range of the calendar. Can be bound as `v-model`. */\n  modelValue?: DateRange | null\n  /** The placeholder date, which is used to determine what month to display when no date is selected. This updates as the user navigates the calendar and can be used to programmatically control the calendar view */\n  placeholder?: DateValue\n  /** When combined with `isDateUnavailable`, determines whether non-contiguous ranges, i.e. ranges containing unavailable dates, may be selected. */\n  allowNonContiguousRanges?: boolean\n  /** This property causes the previous and next buttons to navigate by the number of months displayed at once, rather than one month */\n  pagedNavigation?: boolean\n  /** Whether or not to prevent the user from deselecting a date without selecting another date first */\n  preventDeselect?: boolean\n  /** The maximum number of days that can be selected in a range */\n  maximumDays?: number\n  /** The day of the week to start the calendar on */\n  weekStartsOn?: WeekStartsOn\n  /** The format to use for the weekday strings provided via the weekdays slot prop */\n  weekdayFormat?: WeekDayFormat\n  /** The accessible label for the calendar */\n  calendarLabel?: string\n  /** Whether or not to always display 6 weeks in the calendar */\n  fixedWeeks?: boolean\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** The number of months to display at once */\n  numberOfMonths?: number\n  /** Whether or not the calendar is disabled */\n  disabled?: boolean\n  /** Whether or not the calendar is readonly */\n  readonly?: boolean\n  /** If true, the calendar will focus the selected day, today, or the first day of the month depending on what is visible when the calendar is mounted */\n  initialFocus?: boolean\n  /** A function that returns whether or not a date is disabled */\n  isDateDisabled?: Matcher\n  /** A function that returns whether or not a date is unavailable */\n  isDateUnavailable?: Matcher\n  /** A function that returns whether or not a date is hightable */\n  isDateHighlightable?: Matcher\n  /** The reading direction of the calendar when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** A function that returns the next page of the calendar. It receives the current placeholder as an argument inside the component. */\n  nextPage?: (placeholder: DateValue) => DateValue\n  /** A function that returns the previous page of the calendar. It receives the current placeholder as an argument inside the component. */\n  prevPage?: (placeholder: DateValue) => DateValue\n  /** Whether or not to disable days outside the current view. */\n  disableDaysOutsideCurrentView?: boolean\n  /** Which part of the range should be fixed */\n  fixedDate?: 'start' | 'end'\n\n}\n\nexport type RangeCalendarRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateRange]\n  /** Event handler called whenever there is a new validModel */\n  'update:validModelValue': [date: DateRange]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n  /** Event handler called whenever the start value changes */\n  'update:startValue': [date: DateValue | undefined]\n}\n\nexport const [injectRangeCalendarRootContext, provideRangeCalendarRootContext]\n  = createContext<RangeCalendarRootContext>('RangeCalendarRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener, useVModel } from '@vueuse/core'\nimport { computed, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<RangeCalendarRootProps>(), {\n  defaultValue: () => ({ start: undefined, end: undefined }),\n  as: 'div',\n  pagedNavigation: false,\n  preventDeselect: false,\n  weekdayFormat: 'narrow',\n  fixedWeeks: false,\n  numberOfMonths: 1,\n  disabled: false,\n  readonly: false,\n  initialFocus: false,\n  placeholder: undefined,\n  isDateDisabled: undefined,\n  isDateUnavailable: undefined,\n  isDateHighlightable: undefined,\n  allowNonContiguousRanges: false,\n  maximumDays: undefined,\n  disableDaysOutsideCurrentView: false,\n\n})\nconst emits = defineEmits<RangeCalendarRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the placeholder */\n    date: DateValue\n    /** The grid of dates */\n    grid: Grid<DateValue>[]\n    /** The days of the week */\n    weekDays: string[]\n    /** The start of the week */\n    weekStartsOn: WeekStartsOn\n    /** The calendar locale */\n    locale: string\n    /** Whether or not to always display 6 weeks in the calendar */\n    fixedWeeks: boolean\n    /** The current date range */\n    modelValue: DateRange\n  }) => any\n}>()\n\nconst {\n  disabled,\n  readonly,\n  initialFocus,\n  pagedNavigation,\n  weekdayFormat,\n  fixedWeeks,\n  numberOfMonths,\n  preventDeselect,\n  isDateUnavailable: propsIsDateUnavailable,\n  isDateHighlightable: propsIsDateHighlightable,\n  isDateDisabled: propsIsDateDisabled,\n  calendarLabel,\n  maxValue,\n  minValue,\n  dir: propDir,\n  locale: propLocale,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n  allowNonContiguousRanges,\n  disableDaysOutsideCurrentView,\n  fixedDate,\n  maximumDays,\n} = toRefs(props)\n\nconst { primitiveElement, currentElement: parentElement }\n  = usePrimitiveElement()\nconst dir = useDirection(propDir)\nconst locale = useLocale(propLocale)\nconst weekStartsOn = computed(() => props.weekStartsOn ?? getWeekStartsOn(locale.value))\n\nconst lastPressedDateValue = ref() as Ref<DateValue | undefined>\nconst focusedValue = ref() as Ref<DateValue | undefined>\nconst isEditing = ref(false)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? { start: undefined, end: undefined },\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateRange | null>\n\nconst normalizeRange = (value?: DateRange | null): DateRange => value ?? { start: undefined, end: undefined }\nconst normalizedModelValue = computed(() => normalizeRange(modelValue.value))\n\nconst validModelValue = ref(normalizeRange(modelValue.value)) as Ref<DateRange>\n\nwatch(validModelValue, (value) => {\n  emits('update:validModelValue', value)\n})\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: normalizeRange(modelValue.value).start,\n  locale: props.locale,\n})\n\nconst startValue = ref(normalizeRange(modelValue.value).start) as Ref<\n  DateValue | undefined\n>\nconst endValue = ref(normalizeRange(modelValue.value).end) as Ref<DateValue | undefined>\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nfunction onPlaceholderChange(value: DateValue) {\n  placeholder.value = value.copy()\n}\n\nconst {\n  fullCalendarLabel,\n  headingValue,\n  isDateDisabled,\n  isDateUnavailable,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  grid,\n  weekdays,\n  isOutsideVisibleView,\n  nextPage,\n  prevPage,\n  formatter,\n  isPlaceholderFocusable,\n  firstFocusableDate,\n} = useCalendar({\n  locale,\n  placeholder,\n  weekStartsOn,\n  fixedWeeks,\n  numberOfMonths,\n  minValue,\n  maxValue,\n  disabled,\n  weekdayFormat,\n  pagedNavigation,\n  isDateDisabled: propsIsDateDisabled.value,\n  isDateUnavailable: propsIsDateUnavailable.value,\n  calendarLabel,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n})\n\nconst {\n  isInvalid,\n  isSelected,\n  isDateHighlightable,\n  highlightedRange,\n  isSelectionStart,\n  isSelectionEnd,\n  isHighlightedStart,\n  isHighlightedEnd,\n  isDateDisabled: rangeIsDateDisabled,\n  hasSelectedDate,\n  isSelectedDisabled,\n  selectedFocusableDate,\n} = useRangeCalendarState({\n  start: startValue,\n  end: endValue,\n  isDateDisabled,\n  isDateUnavailable,\n  isDateHighlightable: propsIsDateHighlightable.value,\n  focusedValue,\n  allowNonContiguousRanges,\n  fixedDate,\n  maximumDays,\n})\n\nwatch(modelValue, (_modelValue) => {\n  const next = normalizeRange(_modelValue)\n\n  const isStartSynced = (!next.start && !startValue.value)\n    || (!!next.start && !!startValue.value && isEqualDay(next.start, startValue.value))\n\n  if (!isStartSynced) {\n    startValue.value = next.start?.copy?.()\n  }\n\n  const isEndSynced = (!next.end && !endValue.value)\n    || (!!next.end && !!endValue.value && isEqualDay(next.end, endValue.value))\n\n  if (!isEndSynced) {\n    endValue.value = next.end?.copy?.()\n  }\n})\n\nwatch(startValue, (_startValue) => {\n  if (_startValue && !isEqualDay(_startValue, placeholder.value))\n    onPlaceholderChange(_startValue)\n\n  emits('update:startValue', _startValue)\n})\n\nwatch([startValue, endValue], ([_startValue, _endValue]) => {\n  const value = modelValue.value\n\n  if (\n    value\n    && value.start\n    && value.end\n    && _startValue\n    && _endValue\n    && isEqualDay(value.start, _startValue)\n    && isEqualDay(value.end, _endValue)\n  ) {\n    return\n  }\n\n  isEditing.value = true\n  if (_endValue && _startValue) {\n    const nextValue = isBefore(_endValue, _startValue)\n      ? { start: _endValue.copy(), end: _startValue.copy() }\n      : { start: _startValue.copy(), end: _endValue.copy() }\n\n    modelValue.value = { start: nextValue.start, end: nextValue.end }\n    isEditing.value = false\n    validModelValue.value = { start: nextValue.start.copy(), end: nextValue.end.copy() }\n  }\n  else {\n    modelValue.value = _startValue\n      ? { start: _startValue.copy(), end: undefined }\n      : { start: _endValue?.copy(), end: undefined }\n  }\n})\n\nconst kbd = useKbd()\nuseEventListener(parentElement, 'keydown', (ev) => {\n  if (ev.key === kbd.ESCAPE && isEditing.value) {\n    // Abort start and end selection\n    startValue.value = validModelValue.value.start?.copy()\n    endValue.value = validModelValue.value.end?.copy()\n  }\n})\n\nprovideRangeCalendarRootContext({\n  isDateUnavailable,\n  isDateHighlightable,\n  startValue,\n  endValue,\n  formatter,\n  modelValue: normalizedModelValue,\n  placeholder,\n  disabled,\n  initialFocus,\n  pagedNavigation,\n  grid,\n  weekDays: weekdays,\n  weekStartsOn,\n  weekdayFormat,\n  fixedWeeks,\n  numberOfMonths,\n  readonly,\n  preventDeselect,\n  fullCalendarLabel,\n  headingValue,\n  isInvalid,\n  isDateDisabled: rangeIsDateDisabled,\n  allowNonContiguousRanges,\n  highlightedRange,\n  focusedValue,\n  lastPressedDateValue,\n  isSelected,\n  isSelectionEnd,\n  isSelectionStart,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  isOutsideVisibleView,\n  nextPage,\n  prevPage,\n  parentElement,\n  onPlaceholderChange,\n  locale,\n  dir,\n  isHighlightedStart,\n  isHighlightedEnd,\n  disableDaysOutsideCurrentView,\n  fixedDate,\n  maximumDays,\n  minValue,\n  maxValue,\n  isPlaceholderFocusable,\n  firstFocusableDate,\n  hasSelectedDate,\n  isSelectedDisabled,\n  selectedFocusableDate,\n})\n\nonMounted(() => {\n  if (initialFocus.value)\n    handleCalendarInitialFocus(parentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"fullCalendarLabel\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n  >\n    <div\n      style=\"\n        border: 0px;\n        clip: rect(0px, 0px, 0px, 0px);\n        clip-path: inset(50%);\n        height: 1px;\n        margin: -1px;\n        overflow: hidden;\n        padding: 0px;\n        position: absolute;\n        white-space: nowrap;\n        width: 1px;\n      \"\n    >\n      <div\n        role=\"heading\"\n        aria-level=\"2\"\n      >\n        {{ fullCalendarLabel }}\n      </div>\n    </div>\n\n    <slot\n      :date=\"placeholder\"\n      :grid=\"grid\"\n      :week-days=\"weekdays\"\n      :week-starts-on=\"weekStartsOn\"\n      :locale=\"locale\"\n      :fixed-weeks=\"fixedWeeks\"\n      :model-value=\"normalizedModelValue\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher, WeekDayFormat, WeekStartsOn } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { DateRange } from '@/shared/date'\nimport type { Direction } from '@/shared/types'\nimport { isEqualDay } from '@internationalized/date'\nimport { useCalendar } from '@/Calendar/useCalendar'\nimport { getWeekStartsOn, isBefore } from '@/date'\nimport {\n  createContext,\n  useDirection,\n  useKbd,\n  useLocale,\n} from '@/shared'\nimport { getDefaultDate, handleCalendarInitialFocus } from '@/shared/date'\nimport { useRangeCalendarState } from './useRangeCalendar'\n\ntype RangeCalendarRootContext = {\n  modelValue: Ref<DateRange>\n  startValue: Ref<DateValue | undefined>\n  endValue: Ref<DateValue | undefined>\n  locale: Ref<string>\n  placeholder: Ref<DateValue>\n  pagedNavigation: Ref<boolean>\n  preventDeselect: Ref<boolean>\n  grid: Ref<Grid<DateValue>[]>\n  weekDays: Ref<string[]>\n  weekStartsOn: Ref<WeekStartsOn>\n  weekdayFormat: Ref<WeekDayFormat>\n  fixedWeeks: Ref<boolean>\n  numberOfMonths: Ref<number>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  initialFocus: Ref<boolean>\n  onPlaceholderChange: (date: DateValue) => void\n  fullCalendarLabel: Ref<string>\n  parentElement: Ref<HTMLElement | undefined>\n  headingValue: Ref<string>\n  isInvalid: Ref<boolean>\n  isDateDisabled: Matcher\n  isDateUnavailable?: Matcher\n  isDateHighlightable?: Matcher\n  isOutsideVisibleView: (date: DateValue) => boolean\n  allowNonContiguousRanges: Ref<boolean>\n  highlightedRange: Ref<{ start: DateValue, end: DateValue } | null>\n  focusedValue: Ref<DateValue | undefined>\n  lastPressedDateValue: Ref<DateValue | undefined>\n  isSelected: (date: DateValue) => boolean\n  isSelectionEnd: (date: DateValue) => boolean\n  isSelectionStart: (date: DateValue) => boolean\n  isHighlightedStart: (date: DateValue) => boolean\n  isHighlightedEnd: (date: DateValue) => boolean\n  prevPage: (prevPageFunc?: (date: DateValue) => DateValue) => void\n  nextPage: (nextPageFunc?: (date: DateValue) => DateValue) => void\n  isNextButtonDisabled: (\n    nextPageFunc?: (date: DateValue) => DateValue,\n  ) => boolean\n  isPrevButtonDisabled: (\n    prevPageFunc?: (date: DateValue) => DateValue,\n  ) => boolean\n  formatter: Formatter\n  dir: Ref<Direction>\n  disableDaysOutsideCurrentView: Ref<boolean>\n  fixedDate: Ref<'start' | 'end' | undefined>\n  maximumDays: Ref<number | undefined>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  isPlaceholderFocusable: Ref<boolean>\n  firstFocusableDate: Ref<DateValue | undefined>\n  hasSelectedDate: Ref<boolean>\n  isSelectedDisabled: Ref<boolean>\n  selectedFocusableDate: Ref<DateValue | undefined>\n}\n\nexport interface RangeCalendarRootProps extends PrimitiveProps {\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The default value for the calendar */\n  defaultValue?: DateRange\n  /** The controlled selected date range of the calendar. Can be bound as `v-model`. */\n  modelValue?: DateRange | null\n  /** The placeholder date, which is used to determine what month to display when no date is selected. This updates as the user navigates the calendar and can be used to programmatically control the calendar view */\n  placeholder?: DateValue\n  /** When combined with `isDateUnavailable`, determines whether non-contiguous ranges, i.e. ranges containing unavailable dates, may be selected. */\n  allowNonContiguousRanges?: boolean\n  /** This property causes the previous and next buttons to navigate by the number of months displayed at once, rather than one month */\n  pagedNavigation?: boolean\n  /** Whether or not to prevent the user from deselecting a date without selecting another date first */\n  preventDeselect?: boolean\n  /** The maximum number of days that can be selected in a range */\n  maximumDays?: number\n  /** The day of the week to start the calendar on */\n  weekStartsOn?: WeekStartsOn\n  /** The format to use for the weekday strings provided via the weekdays slot prop */\n  weekdayFormat?: WeekDayFormat\n  /** The accessible label for the calendar */\n  calendarLabel?: string\n  /** Whether or not to always display 6 weeks in the calendar */\n  fixedWeeks?: boolean\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** The number of months to display at once */\n  numberOfMonths?: number\n  /** Whether or not the calendar is disabled */\n  disabled?: boolean\n  /** Whether or not the calendar is readonly */\n  readonly?: boolean\n  /** If true, the calendar will focus the selected day, today, or the first day of the month depending on what is visible when the calendar is mounted */\n  initialFocus?: boolean\n  /** A function that returns whether or not a date is disabled */\n  isDateDisabled?: Matcher\n  /** A function that returns whether or not a date is unavailable */\n  isDateUnavailable?: Matcher\n  /** A function that returns whether or not a date is hightable */\n  isDateHighlightable?: Matcher\n  /** The reading direction of the calendar when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** A function that returns the next page of the calendar. It receives the current placeholder as an argument inside the component. */\n  nextPage?: (placeholder: DateValue) => DateValue\n  /** A function that returns the previous page of the calendar. It receives the current placeholder as an argument inside the component. */\n  prevPage?: (placeholder: DateValue) => DateValue\n  /** Whether or not to disable days outside the current view. */\n  disableDaysOutsideCurrentView?: boolean\n  /** Which part of the range should be fixed */\n  fixedDate?: 'start' | 'end'\n\n}\n\nexport type RangeCalendarRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateRange]\n  /** Event handler called whenever there is a new validModel */\n  'update:validModelValue': [date: DateRange]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n  /** Event handler called whenever the start value changes */\n  'update:startValue': [date: DateValue | undefined]\n}\n\nexport const [injectRangeCalendarRootContext, provideRangeCalendarRootContext]\n  = createContext<RangeCalendarRootContext>('RangeCalendarRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener, useVModel } from '@vueuse/core'\nimport { computed, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<RangeCalendarRootProps>(), {\n  defaultValue: () => ({ start: undefined, end: undefined }),\n  as: 'div',\n  pagedNavigation: false,\n  preventDeselect: false,\n  weekdayFormat: 'narrow',\n  fixedWeeks: false,\n  numberOfMonths: 1,\n  disabled: false,\n  readonly: false,\n  initialFocus: false,\n  placeholder: undefined,\n  isDateDisabled: undefined,\n  isDateUnavailable: undefined,\n  isDateHighlightable: undefined,\n  allowNonContiguousRanges: false,\n  maximumDays: undefined,\n  disableDaysOutsideCurrentView: false,\n\n})\nconst emits = defineEmits<RangeCalendarRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the placeholder */\n    date: DateValue\n    /** The grid of dates */\n    grid: Grid<DateValue>[]\n    /** The days of the week */\n    weekDays: string[]\n    /** The start of the week */\n    weekStartsOn: WeekStartsOn\n    /** The calendar locale */\n    locale: string\n    /** Whether or not to always display 6 weeks in the calendar */\n    fixedWeeks: boolean\n    /** The current date range */\n    modelValue: DateRange\n  }) => any\n}>()\n\nconst {\n  disabled,\n  readonly,\n  initialFocus,\n  pagedNavigation,\n  weekdayFormat,\n  fixedWeeks,\n  numberOfMonths,\n  preventDeselect,\n  isDateUnavailable: propsIsDateUnavailable,\n  isDateHighlightable: propsIsDateHighlightable,\n  isDateDisabled: propsIsDateDisabled,\n  calendarLabel,\n  maxValue,\n  minValue,\n  dir: propDir,\n  locale: propLocale,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n  allowNonContiguousRanges,\n  disableDaysOutsideCurrentView,\n  fixedDate,\n  maximumDays,\n} = toRefs(props)\n\nconst { primitiveElement, currentElement: parentElement }\n  = usePrimitiveElement()\nconst dir = useDirection(propDir)\nconst locale = useLocale(propLocale)\nconst weekStartsOn = computed(() => props.weekStartsOn ?? getWeekStartsOn(locale.value))\n\nconst lastPressedDateValue = ref() as Ref<DateValue | undefined>\nconst focusedValue = ref() as Ref<DateValue | undefined>\nconst isEditing = ref(false)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? { start: undefined, end: undefined },\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateRange | null>\n\nconst normalizeRange = (value?: DateRange | null): DateRange => value ?? { start: undefined, end: undefined }\nconst normalizedModelValue = computed(() => normalizeRange(modelValue.value))\n\nconst validModelValue = ref(normalizeRange(modelValue.value)) as Ref<DateRange>\n\nwatch(validModelValue, (value) => {\n  emits('update:validModelValue', value)\n})\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: normalizeRange(modelValue.value).start,\n  locale: props.locale,\n})\n\nconst startValue = ref(normalizeRange(modelValue.value).start) as Ref<\n  DateValue | undefined\n>\nconst endValue = ref(normalizeRange(modelValue.value).end) as Ref<DateValue | undefined>\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nfunction onPlaceholderChange(value: DateValue) {\n  placeholder.value = value.copy()\n}\n\nconst {\n  fullCalendarLabel,\n  headingValue,\n  isDateDisabled,\n  isDateUnavailable,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  grid,\n  weekdays,\n  isOutsideVisibleView,\n  nextPage,\n  prevPage,\n  formatter,\n  isPlaceholderFocusable,\n  firstFocusableDate,\n} = useCalendar({\n  locale,\n  placeholder,\n  weekStartsOn,\n  fixedWeeks,\n  numberOfMonths,\n  minValue,\n  maxValue,\n  disabled,\n  weekdayFormat,\n  pagedNavigation,\n  isDateDisabled: propsIsDateDisabled.value,\n  isDateUnavailable: propsIsDateUnavailable.value,\n  calendarLabel,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n})\n\nconst {\n  isInvalid,\n  isSelected,\n  isDateHighlightable,\n  highlightedRange,\n  isSelectionStart,\n  isSelectionEnd,\n  isHighlightedStart,\n  isHighlightedEnd,\n  isDateDisabled: rangeIsDateDisabled,\n  hasSelectedDate,\n  isSelectedDisabled,\n  selectedFocusableDate,\n} = useRangeCalendarState({\n  start: startValue,\n  end: endValue,\n  isDateDisabled,\n  isDateUnavailable,\n  isDateHighlightable: propsIsDateHighlightable.value,\n  focusedValue,\n  allowNonContiguousRanges,\n  fixedDate,\n  maximumDays,\n})\n\nwatch(modelValue, (_modelValue) => {\n  const next = normalizeRange(_modelValue)\n\n  const isStartSynced = (!next.start && !startValue.value)\n    || (!!next.start && !!startValue.value && isEqualDay(next.start, startValue.value))\n\n  if (!isStartSynced) {\n    startValue.value = next.start?.copy?.()\n  }\n\n  const isEndSynced = (!next.end && !endValue.value)\n    || (!!next.end && !!endValue.value && isEqualDay(next.end, endValue.value))\n\n  if (!isEndSynced) {\n    endValue.value = next.end?.copy?.()\n  }\n})\n\nwatch(startValue, (_startValue) => {\n  if (_startValue && !isEqualDay(_startValue, placeholder.value))\n    onPlaceholderChange(_startValue)\n\n  emits('update:startValue', _startValue)\n})\n\nwatch([startValue, endValue], ([_startValue, _endValue]) => {\n  const value = modelValue.value\n\n  if (\n    value\n    && value.start\n    && value.end\n    && _startValue\n    && _endValue\n    && isEqualDay(value.start, _startValue)\n    && isEqualDay(value.end, _endValue)\n  ) {\n    return\n  }\n\n  isEditing.value = true\n  if (_endValue && _startValue) {\n    const nextValue = isBefore(_endValue, _startValue)\n      ? { start: _endValue.copy(), end: _startValue.copy() }\n      : { start: _startValue.copy(), end: _endValue.copy() }\n\n    modelValue.value = { start: nextValue.start, end: nextValue.end }\n    isEditing.value = false\n    validModelValue.value = { start: nextValue.start.copy(), end: nextValue.end.copy() }\n  }\n  else {\n    modelValue.value = _startValue\n      ? { start: _startValue.copy(), end: undefined }\n      : { start: _endValue?.copy(), end: undefined }\n  }\n})\n\nconst kbd = useKbd()\nuseEventListener(parentElement, 'keydown', (ev) => {\n  if (ev.key === kbd.ESCAPE && isEditing.value) {\n    // Abort start and end selection\n    startValue.value = validModelValue.value.start?.copy()\n    endValue.value = validModelValue.value.end?.copy()\n  }\n})\n\nprovideRangeCalendarRootContext({\n  isDateUnavailable,\n  isDateHighlightable,\n  startValue,\n  endValue,\n  formatter,\n  modelValue: normalizedModelValue,\n  placeholder,\n  disabled,\n  initialFocus,\n  pagedNavigation,\n  grid,\n  weekDays: weekdays,\n  weekStartsOn,\n  weekdayFormat,\n  fixedWeeks,\n  numberOfMonths,\n  readonly,\n  preventDeselect,\n  fullCalendarLabel,\n  headingValue,\n  isInvalid,\n  isDateDisabled: rangeIsDateDisabled,\n  allowNonContiguousRanges,\n  highlightedRange,\n  focusedValue,\n  lastPressedDateValue,\n  isSelected,\n  isSelectionEnd,\n  isSelectionStart,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  isOutsideVisibleView,\n  nextPage,\n  prevPage,\n  parentElement,\n  onPlaceholderChange,\n  locale,\n  dir,\n  isHighlightedStart,\n  isHighlightedEnd,\n  disableDaysOutsideCurrentView,\n  fixedDate,\n  maximumDays,\n  minValue,\n  maxValue,\n  isPlaceholderFocusable,\n  firstFocusableDate,\n  hasSelectedDate,\n  isSelectedDisabled,\n  selectedFocusableDate,\n})\n\nonMounted(() => {\n  if (initialFocus.value)\n    handleCalendarInitialFocus(parentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"fullCalendarLabel\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n  >\n    <div\n      style=\"\n        border: 0px;\n        clip: rect(0px, 0px, 0px, 0px);\n        clip-path: inset(50%);\n        height: 1px;\n        margin: -1px;\n        overflow: hidden;\n        padding: 0px;\n        position: absolute;\n        white-space: nowrap;\n        width: 1px;\n      \"\n    >\n      <div\n        role=\"heading\"\n        aria-level=\"2\"\n      >\n        {{ fullCalendarLabel }}\n      </div>\n    </div>\n\n    <slot\n      :date=\"placeholder\"\n      :grid=\"grid\"\n      :week-days=\"weekdays\"\n      :week-starts-on=\"weekStartsOn\"\n      :locale=\"locale\"\n      :fixed-weeks=\"fixedWeeks\"\n      :model-value=\"normalizedModelValue\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport { isEqualDay } from '@internationalized/date'\nimport { RangeCalendarRoot } from '..'\nimport { injectDateRangePickerRootContext } from './DateRangePickerRoot.vue'\n</script>\n\n<script setup lang=\"ts\">\nconst rootContext = injectDateRangePickerRootContext()\n</script>\n\n<template>\n  <RangeCalendarRoot\n    v-slot=\"{ weekDays, grid, date, weekStartsOn, locale, fixedWeeks }\"\n    v-bind=\"{\n      allowNonContiguousRanges: rootContext.allowNonContiguousRanges.value,\n      isDateDisabled: rootContext.isDateDisabled,\n      isDateUnavailable: rootContext.isDateUnavailable,\n      isDateHighlightable: rootContext.isDateHighlightable,\n      locale: rootContext.locale.value,\n      disabled: rootContext.disabled.value,\n      pagedNavigation: rootContext.pagedNavigation.value,\n      weekStartsOn: rootContext.weekStartsOn.value,\n      weekdayFormat: rootContext.weekdayFormat.value,\n      fixedWeeks: rootContext.fixedWeeks.value,\n      numberOfMonths: rootContext.numberOfMonths.value,\n      readonly: rootContext.readonly.value,\n      preventDeselect: rootContext.preventDeselect.value,\n      minValue: rootContext.minValue.value,\n      maxValue: rootContext.maxValue.value,\n      dir: rootContext.dir.value,\n      fixedDate: rootContext.fixedDate.value,\n      maximumDays: rootContext.maximumDays?.value,\n    }\"\n    :model-value=\"rootContext.modelValue.value\"\n    :placeholder=\"rootContext.placeholder.value\"\n    @update:start-value=\"(date) => {\n      rootContext.onStartValueChange(date)\n    }\"\n    @update:model-value=\"(date) => {\n      if (date.start && rootContext.modelValue.value?.start && date.end && rootContext.modelValue.value?.end && isEqualDay(date.start, rootContext.modelValue.value?.start) && isEqualDay(date.end, rootContext.modelValue.value?.end)) return\n      rootContext.onDateChange(date)\n    }\"\n    @update:placeholder=\"(date) => {\n      if (isEqualDay(date, rootContext.placeholder.value)) return\n      rootContext.onPlaceholderChange(date)\n    }\"\n  >\n    <slot\n      :date=\"date\"\n      :grid=\"grid\"\n      :week-days=\"weekDays\"\n      :week-starts-on=\"weekStartsOn\"\n      :locale=\"locale\"\n      :fixed-weeks=\"fixedWeeks\"\n    />\n  </RangeCalendarRoot>\n</template>\n","<script lang=\"ts\">\nimport { isEqualDay } from '@internationalized/date'\nimport { RangeCalendarRoot } from '..'\nimport { injectDateRangePickerRootContext } from './DateRangePickerRoot.vue'\n</script>\n\n<script setup lang=\"ts\">\nconst rootContext = injectDateRangePickerRootContext()\n</script>\n\n<template>\n  <RangeCalendarRoot\n    v-slot=\"{ weekDays, grid, date, weekStartsOn, locale, fixedWeeks }\"\n    v-bind=\"{\n      allowNonContiguousRanges: rootContext.allowNonContiguousRanges.value,\n      isDateDisabled: rootContext.isDateDisabled,\n      isDateUnavailable: rootContext.isDateUnavailable,\n      isDateHighlightable: rootContext.isDateHighlightable,\n      locale: rootContext.locale.value,\n      disabled: rootContext.disabled.value,\n      pagedNavigation: rootContext.pagedNavigation.value,\n      weekStartsOn: rootContext.weekStartsOn.value,\n      weekdayFormat: rootContext.weekdayFormat.value,\n      fixedWeeks: rootContext.fixedWeeks.value,\n      numberOfMonths: rootContext.numberOfMonths.value,\n      readonly: rootContext.readonly.value,\n      preventDeselect: rootContext.preventDeselect.value,\n      minValue: rootContext.minValue.value,\n      maxValue: rootContext.maxValue.value,\n      dir: rootContext.dir.value,\n      fixedDate: rootContext.fixedDate.value,\n      maximumDays: rootContext.maximumDays?.value,\n    }\"\n    :model-value=\"rootContext.modelValue.value\"\n    :placeholder=\"rootContext.placeholder.value\"\n    @update:start-value=\"(date) => {\n      rootContext.onStartValueChange(date)\n    }\"\n    @update:model-value=\"(date) => {\n      if (date.start && rootContext.modelValue.value?.start && date.end && rootContext.modelValue.value?.end && isEqualDay(date.start, rootContext.modelValue.value?.start) && isEqualDay(date.end, rootContext.modelValue.value?.end)) return\n      rootContext.onDateChange(date)\n    }\"\n    @update:placeholder=\"(date) => {\n      if (isEqualDay(date, rootContext.placeholder.value)) return\n      rootContext.onPlaceholderChange(date)\n    }\"\n  >\n    <slot\n      :date=\"date\"\n      :grid=\"grid\"\n      :week-days=\"weekDays\"\n      :week-starts-on=\"weekStartsOn\"\n      :locale=\"locale\"\n      :fixed-weeks=\"fixedWeeks\"\n    />\n  </RangeCalendarRoot>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarCellProps extends PrimitiveProps {\n  date: DateValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectRangeCalendarRootContext } from './RangeCalendarRoot.vue'\n\nwithDefaults(defineProps<RangeCalendarCellProps>(), { as: 'td' })\nconst rootContext = injectRangeCalendarRootContext()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"gridcell\"\n    :aria-selected=\"rootContext.isSelected(date) ? true : undefined\"\n    :aria-disabled=\"rootContext.isDateDisabled(date) || rootContext.isDateUnavailable?.(date) || rootContext.disableDaysOutsideCurrentView.value\"\n    :data-disabled=\"rootContext.isDateDisabled(date) || rootContext.disableDaysOutsideCurrentView.value ? '' : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarCellProps extends PrimitiveProps {\n  date: DateValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectRangeCalendarRootContext } from './RangeCalendarRoot.vue'\n\nwithDefaults(defineProps<RangeCalendarCellProps>(), { as: 'td' })\nconst rootContext = injectRangeCalendarRootContext()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"gridcell\"\n    :aria-selected=\"rootContext.isSelected(date) ? true : undefined\"\n    :aria-disabled=\"rootContext.isDateDisabled(date) || rootContext.isDateUnavailable?.(date) || rootContext.disableDaysOutsideCurrentView.value\"\n    :data-disabled=\"rootContext.isDateDisabled(date) || rootContext.disableDaysOutsideCurrentView.value ? '' : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarCellProps } from '..'\nimport { RangeCalendarCell } from '..'\n\nexport interface DateRangePickerCellProps extends RangeCalendarCellProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerCellProps>()\n</script>\n\n<template>\n  <RangeCalendarCell v-bind=\"props\">\n    <slot />\n  </RangeCalendarCell>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarCellProps } from '..'\nimport { RangeCalendarCell } from '..'\n\nexport interface DateRangePickerCellProps extends RangeCalendarCellProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerCellProps>()\n</script>\n\n<template>\n  <RangeCalendarCell v-bind=\"props\">\n    <slot />\n  </RangeCalendarCell>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport {\n\n  getLocalTimeZone,\n  isSameDay,\n  isSameMonth,\n  isToday,\n} from '@internationalized/date'\nimport { computed, nextTick } from 'vue'\nimport { isBetweenInclusive, toDate } from '@/date'\nimport { useKbd } from '@/shared'\n\nexport interface RangeCalendarCellTriggerProps extends PrimitiveProps {\n  day: DateValue\n  month: DateValue\n}\n\nexport interface RangeCalendarCellTriggerSlot {\n  default?: (props: {\n    /** Current day */\n    dayValue: string\n    /** Current disable state */\n    disabled: boolean\n    /** Current selected state */\n    selected: boolean\n    /** Current today state */\n    today: boolean\n    /** Current outside view state */\n    outsideView: boolean\n    /** Current outside visible view state */\n    outsideVisibleView: boolean\n    /** Current unavailable state */\n    unavailable: boolean\n    /** Current highlighted state */\n    highlighted: boolean\n    /** Current highlighted start state */\n    highlightedStart: boolean\n    /** Current highlighted end state */\n    highlightedEnd: boolean\n    /** Current selection start state */\n    selectionStart: boolean\n    /** Current selection end state */\n    selectionEnd: boolean\n\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectRangeCalendarRootContext } from './RangeCalendarRoot.vue'\n\nconst props = withDefaults(defineProps<RangeCalendarCellTriggerProps>(), { as: 'div' })\ndefineSlots<RangeCalendarCellTriggerSlot>()\n\nconst rootContext = injectRangeCalendarRootContext()\n\nconst kbd = useKbd()\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst labelText = computed(() => rootContext.formatter.custom(toDate(props.day), {\n  weekday: 'long',\n  month: 'long',\n  day: 'numeric',\n  year: 'numeric',\n}))\n\nconst isUnavailable = computed(() => rootContext.isDateUnavailable?.(props.day) ?? false)\nconst isSelectedDate = computed(() => rootContext.isSelected(props.day))\nconst isSelectionStart = computed(() => rootContext.isSelectionStart(props.day))\nconst isSelectionEnd = computed(() => rootContext.isSelectionEnd(props.day))\nconst isHighlightStart = computed(() => rootContext.isHighlightedStart(props.day))\nconst isHighlightEnd = computed(() => rootContext.isHighlightedEnd(props.day))\nconst isHighlighted = computed(() => rootContext.highlightedRange.value\n  ? isBetweenInclusive(props.day, rootContext.highlightedRange.value.start, rootContext.highlightedRange.value.end)\n  : false)\nconst allowNonContiguousRanges = computed(() => rootContext.allowNonContiguousRanges.value)\n\nconst isDateToday = computed(() => {\n  return isToday(props.day, getLocalTimeZone())\n})\nconst isOutsideView = computed(() => {\n  return !isSameMonth(props.day, props.month)\n})\nconst isOutsideVisibleView = computed(() =>\n  rootContext.isOutsideVisibleView(props.day),\n)\n\nconst isDisabled = computed(() => rootContext.isDateDisabled(props.day) || (rootContext.disableDaysOutsideCurrentView.value && isOutsideView.value))\n\nconst dayValue = computed(() => props.day.day.toLocaleString(rootContext.locale.value))\n\nconst isFocusedDate = computed(() => {\n  if (isOutsideView.value || isDisabled.value)\n    return false\n  if (!rootContext.disabled.value && rootContext.isPlaceholderFocusable.value && isSameDay(props.day, rootContext.placeholder.value))\n    return true\n  if (!rootContext.disabled.value && rootContext.selectedFocusableDate.value && !rootContext.isPlaceholderFocusable.value)\n    return isSameDay(props.day, rootContext.selectedFocusableDate.value)\n  if (!rootContext.disabled.value && (!rootContext.hasSelectedDate.value || rootContext.isSelectedDisabled.value) && !rootContext.isPlaceholderFocusable.value)\n    return rootContext.firstFocusableDate.value && isSameDay(props.day, rootContext.firstFocusableDate.value)\n  return false\n})\n\nfunction changeDate(e: MouseEvent | KeyboardEvent, date: DateValue) {\n  if (rootContext.readonly.value)\n    return\n  if (rootContext.isDateDisabled(date) || rootContext.isDateUnavailable?.(date))\n    return\n\n  if (rootContext.startValue.value && rootContext.highlightedRange.value === null) {\n    if (isSameDay(date, rootContext.startValue.value) && !rootContext.preventDeselect.value && !rootContext.endValue.value) {\n      rootContext.startValue.value = undefined\n      rootContext.onPlaceholderChange(date)\n      rootContext.lastPressedDateValue.value = date.copy()\n      return\n    }\n    else if (!rootContext.endValue.value) {\n      e.preventDefault()\n      if (rootContext.lastPressedDateValue.value && isSameDay(rootContext.lastPressedDateValue.value, date))\n        rootContext.startValue.value = date.copy()\n      rootContext.lastPressedDateValue.value = date.copy()\n      return\n    }\n  }\n\n  rootContext.lastPressedDateValue.value = date.copy()\n\n  if (\n    rootContext.startValue.value\n    && rootContext.endValue.value\n    && isSameDay(rootContext.startValue.value, rootContext.endValue.value)\n    && isSameDay(rootContext.startValue.value, date)\n    && !rootContext.preventDeselect.value\n  ) {\n    rootContext.startValue.value = undefined\n    rootContext.endValue.value = undefined\n    rootContext.onPlaceholderChange(date)\n    return\n  }\n\n  if (!rootContext.startValue.value) {\n    rootContext.startValue.value = date.copy()\n  }\n  else if (!rootContext.endValue.value) {\n    rootContext.endValue.value = date.copy()\n  }\n  else if (rootContext.endValue.value && rootContext.startValue.value) {\n    if (!rootContext.fixedDate.value) {\n      rootContext.endValue.value = undefined\n      rootContext.startValue.value = date.copy()\n    }\n    else if (rootContext.fixedDate.value === 'start') {\n      if (date.compare(rootContext.startValue.value) < 0) {\n        rootContext.startValue.value = date.copy()\n      }\n      else {\n        rootContext.endValue.value = date.copy()\n      }\n    }\n    else if (rootContext.fixedDate.value === 'end') {\n      if (date.compare(rootContext.endValue.value) > 0) {\n        rootContext.endValue.value = date.copy()\n      }\n      else {\n        rootContext.startValue.value = date.copy()\n      }\n    }\n  }\n}\n\nfunction handleClick(e: MouseEvent) {\n  if (isDisabled.value)\n    return\n  changeDate(e, props.day)\n}\n\nfunction handleFocus() {\n  if (isDisabled.value || rootContext.isDateUnavailable?.(props.day))\n    return\n  rootContext.focusedValue.value = props.day.copy()\n}\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  if (isDisabled.value)\n    return\n  e.preventDefault()\n  e.stopPropagation()\n  const parentElement = rootContext.parentElement.value!\n  const indexIncrementation = 7\n  const sign = rootContext.dir.value === 'rtl' ? -1 : 1\n  switch (e.code) {\n    case kbd.ARROW_RIGHT:\n      shiftFocus(props.day, sign)\n      break\n    case kbd.ARROW_LEFT:\n      shiftFocus(props.day, -sign)\n      break\n    case kbd.ARROW_UP:\n      shiftFocus(props.day, -indexIncrementation)\n      break\n    case kbd.ARROW_DOWN:\n      shiftFocus(props.day, indexIncrementation)\n      break\n    case kbd.ENTER:\n    case kbd.SPACE_CODE:\n      changeDate(e, props.day)\n  }\n\n  function shiftFocus(day: DateValue, add: number) {\n    const candidateDayValue = day.add({ days: add })\n\n    if ((rootContext.minValue.value && candidateDayValue.compare(rootContext.minValue.value) < 0) || (rootContext.maxValue.value && candidateDayValue.compare(rootContext.maxValue.value) > 0))\n      return\n\n    const candidateDay = parentElement.querySelector<HTMLElement>(`[data-value='${candidateDayValue.toString()}']:not([data-outside-view])`)\n    // If the date is not found it means we must change the page\n    if (!candidateDay) {\n      if (add > 0) {\n        if (rootContext.isNextButtonDisabled())\n          return\n        rootContext.nextPage()\n      }\n      else {\n        if (rootContext.isPrevButtonDisabled())\n          return\n        rootContext.prevPage()\n      }\n      nextTick(() => {\n        shiftFocus(day, add)\n      })\n      return\n    }\n\n    if (candidateDay && candidateDay.hasAttribute('data-disabled')) {\n      return shiftFocus(candidateDayValue, add)\n    }\n    rootContext.onPlaceholderChange(candidateDayValue)\n    candidateDay?.focus()\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"button\"\n    :aria-label=\"labelText\"\n    data-reka-calendar-cell-trigger\n    :aria-pressed=\"isSelectedDate && (allowNonContiguousRanges || !isUnavailable) ? true : undefined\"\n    :aria-disabled=\"isDisabled || isUnavailable ? true : undefined\"\n    :data-highlighted=\"isHighlighted && (allowNonContiguousRanges || !isUnavailable) ? '' : undefined\"\n    :data-selection-start=\"isSelectionStart ? true : undefined\"\n    :data-selection-end=\"isSelectionEnd ? true : undefined\"\n    :data-highlighted-start=\"isHighlightStart ? true : undefined\"\n    :data-highlighted-end=\"isHighlightEnd ? true : undefined\"\n    :data-selected=\"isSelectedDate && (allowNonContiguousRanges || !isUnavailable) ? true : undefined\"\n    :data-outside-visible-view=\"isOutsideVisibleView ? '' : undefined\"\n    :data-value=\"day.toString()\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-unavailable=\"isUnavailable ? '' : undefined\"\n    :data-today=\"isDateToday ? '' : undefined\"\n    :data-outside-view=\"isOutsideView ? '' : undefined\"\n    :data-focused=\"isFocusedDate ? '' : undefined\"\n    :tabindex=\"isFocusedDate ? 0 : isOutsideView || isDisabled ? undefined : -1\"\n    @click=\"handleClick\"\n    @focusin=\"handleFocus\"\n    @mouseenter=\"handleFocus\"\n    @keydown.up.down.left.right.enter.space=\"handleArrowKey\"\n  >\n    <slot\n      :day-value=\"dayValue\"\n      :disabled=\"isDisabled\"\n      :today=\"isDateToday\"\n      :selected=\"isSelectedDate\"\n      :outside-view=\"isOutsideView\"\n      :outside-visible-view=\"isOutsideVisibleView\"\n      :unavailable=\"isUnavailable\"\n      :highlighted=\"isHighlighted && (allowNonContiguousRanges || !isUnavailable)\"\n      :highlighted-start=\"isHighlightStart\"\n      :highlighted-end=\"isHighlightEnd\"\n      :selection-start=\"isSelectionStart\"\n      :selection-end=\"isSelectionEnd\"\n    >\n      {{ dayValue }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport {\n\n  getLocalTimeZone,\n  isSameDay,\n  isSameMonth,\n  isToday,\n} from '@internationalized/date'\nimport { computed, nextTick } from 'vue'\nimport { isBetweenInclusive, toDate } from '@/date'\nimport { useKbd } from '@/shared'\n\nexport interface RangeCalendarCellTriggerProps extends PrimitiveProps {\n  day: DateValue\n  month: DateValue\n}\n\nexport interface RangeCalendarCellTriggerSlot {\n  default?: (props: {\n    /** Current day */\n    dayValue: string\n    /** Current disable state */\n    disabled: boolean\n    /** Current selected state */\n    selected: boolean\n    /** Current today state */\n    today: boolean\n    /** Current outside view state */\n    outsideView: boolean\n    /** Current outside visible view state */\n    outsideVisibleView: boolean\n    /** Current unavailable state */\n    unavailable: boolean\n    /** Current highlighted state */\n    highlighted: boolean\n    /** Current highlighted start state */\n    highlightedStart: boolean\n    /** Current highlighted end state */\n    highlightedEnd: boolean\n    /** Current selection start state */\n    selectionStart: boolean\n    /** Current selection end state */\n    selectionEnd: boolean\n\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectRangeCalendarRootContext } from './RangeCalendarRoot.vue'\n\nconst props = withDefaults(defineProps<RangeCalendarCellTriggerProps>(), { as: 'div' })\ndefineSlots<RangeCalendarCellTriggerSlot>()\n\nconst rootContext = injectRangeCalendarRootContext()\n\nconst kbd = useKbd()\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst labelText = computed(() => rootContext.formatter.custom(toDate(props.day), {\n  weekday: 'long',\n  month: 'long',\n  day: 'numeric',\n  year: 'numeric',\n}))\n\nconst isUnavailable = computed(() => rootContext.isDateUnavailable?.(props.day) ?? false)\nconst isSelectedDate = computed(() => rootContext.isSelected(props.day))\nconst isSelectionStart = computed(() => rootContext.isSelectionStart(props.day))\nconst isSelectionEnd = computed(() => rootContext.isSelectionEnd(props.day))\nconst isHighlightStart = computed(() => rootContext.isHighlightedStart(props.day))\nconst isHighlightEnd = computed(() => rootContext.isHighlightedEnd(props.day))\nconst isHighlighted = computed(() => rootContext.highlightedRange.value\n  ? isBetweenInclusive(props.day, rootContext.highlightedRange.value.start, rootContext.highlightedRange.value.end)\n  : false)\nconst allowNonContiguousRanges = computed(() => rootContext.allowNonContiguousRanges.value)\n\nconst isDateToday = computed(() => {\n  return isToday(props.day, getLocalTimeZone())\n})\nconst isOutsideView = computed(() => {\n  return !isSameMonth(props.day, props.month)\n})\nconst isOutsideVisibleView = computed(() =>\n  rootContext.isOutsideVisibleView(props.day),\n)\n\nconst isDisabled = computed(() => rootContext.isDateDisabled(props.day) || (rootContext.disableDaysOutsideCurrentView.value && isOutsideView.value))\n\nconst dayValue = computed(() => props.day.day.toLocaleString(rootContext.locale.value))\n\nconst isFocusedDate = computed(() => {\n  if (isOutsideView.value || isDisabled.value)\n    return false\n  if (!rootContext.disabled.value && rootContext.isPlaceholderFocusable.value && isSameDay(props.day, rootContext.placeholder.value))\n    return true\n  if (!rootContext.disabled.value && rootContext.selectedFocusableDate.value && !rootContext.isPlaceholderFocusable.value)\n    return isSameDay(props.day, rootContext.selectedFocusableDate.value)\n  if (!rootContext.disabled.value && (!rootContext.hasSelectedDate.value || rootContext.isSelectedDisabled.value) && !rootContext.isPlaceholderFocusable.value)\n    return rootContext.firstFocusableDate.value && isSameDay(props.day, rootContext.firstFocusableDate.value)\n  return false\n})\n\nfunction changeDate(e: MouseEvent | KeyboardEvent, date: DateValue) {\n  if (rootContext.readonly.value)\n    return\n  if (rootContext.isDateDisabled(date) || rootContext.isDateUnavailable?.(date))\n    return\n\n  if (rootContext.startValue.value && rootContext.highlightedRange.value === null) {\n    if (isSameDay(date, rootContext.startValue.value) && !rootContext.preventDeselect.value && !rootContext.endValue.value) {\n      rootContext.startValue.value = undefined\n      rootContext.onPlaceholderChange(date)\n      rootContext.lastPressedDateValue.value = date.copy()\n      return\n    }\n    else if (!rootContext.endValue.value) {\n      e.preventDefault()\n      if (rootContext.lastPressedDateValue.value && isSameDay(rootContext.lastPressedDateValue.value, date))\n        rootContext.startValue.value = date.copy()\n      rootContext.lastPressedDateValue.value = date.copy()\n      return\n    }\n  }\n\n  rootContext.lastPressedDateValue.value = date.copy()\n\n  if (\n    rootContext.startValue.value\n    && rootContext.endValue.value\n    && isSameDay(rootContext.startValue.value, rootContext.endValue.value)\n    && isSameDay(rootContext.startValue.value, date)\n    && !rootContext.preventDeselect.value\n  ) {\n    rootContext.startValue.value = undefined\n    rootContext.endValue.value = undefined\n    rootContext.onPlaceholderChange(date)\n    return\n  }\n\n  if (!rootContext.startValue.value) {\n    rootContext.startValue.value = date.copy()\n  }\n  else if (!rootContext.endValue.value) {\n    rootContext.endValue.value = date.copy()\n  }\n  else if (rootContext.endValue.value && rootContext.startValue.value) {\n    if (!rootContext.fixedDate.value) {\n      rootContext.endValue.value = undefined\n      rootContext.startValue.value = date.copy()\n    }\n    else if (rootContext.fixedDate.value === 'start') {\n      if (date.compare(rootContext.startValue.value) < 0) {\n        rootContext.startValue.value = date.copy()\n      }\n      else {\n        rootContext.endValue.value = date.copy()\n      }\n    }\n    else if (rootContext.fixedDate.value === 'end') {\n      if (date.compare(rootContext.endValue.value) > 0) {\n        rootContext.endValue.value = date.copy()\n      }\n      else {\n        rootContext.startValue.value = date.copy()\n      }\n    }\n  }\n}\n\nfunction handleClick(e: MouseEvent) {\n  if (isDisabled.value)\n    return\n  changeDate(e, props.day)\n}\n\nfunction handleFocus() {\n  if (isDisabled.value || rootContext.isDateUnavailable?.(props.day))\n    return\n  rootContext.focusedValue.value = props.day.copy()\n}\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  if (isDisabled.value)\n    return\n  e.preventDefault()\n  e.stopPropagation()\n  const parentElement = rootContext.parentElement.value!\n  const indexIncrementation = 7\n  const sign = rootContext.dir.value === 'rtl' ? -1 : 1\n  switch (e.code) {\n    case kbd.ARROW_RIGHT:\n      shiftFocus(props.day, sign)\n      break\n    case kbd.ARROW_LEFT:\n      shiftFocus(props.day, -sign)\n      break\n    case kbd.ARROW_UP:\n      shiftFocus(props.day, -indexIncrementation)\n      break\n    case kbd.ARROW_DOWN:\n      shiftFocus(props.day, indexIncrementation)\n      break\n    case kbd.ENTER:\n    case kbd.SPACE_CODE:\n      changeDate(e, props.day)\n  }\n\n  function shiftFocus(day: DateValue, add: number) {\n    const candidateDayValue = day.add({ days: add })\n\n    if ((rootContext.minValue.value && candidateDayValue.compare(rootContext.minValue.value) < 0) || (rootContext.maxValue.value && candidateDayValue.compare(rootContext.maxValue.value) > 0))\n      return\n\n    const candidateDay = parentElement.querySelector<HTMLElement>(`[data-value='${candidateDayValue.toString()}']:not([data-outside-view])`)\n    // If the date is not found it means we must change the page\n    if (!candidateDay) {\n      if (add > 0) {\n        if (rootContext.isNextButtonDisabled())\n          return\n        rootContext.nextPage()\n      }\n      else {\n        if (rootContext.isPrevButtonDisabled())\n          return\n        rootContext.prevPage()\n      }\n      nextTick(() => {\n        shiftFocus(day, add)\n      })\n      return\n    }\n\n    if (candidateDay && candidateDay.hasAttribute('data-disabled')) {\n      return shiftFocus(candidateDayValue, add)\n    }\n    rootContext.onPlaceholderChange(candidateDayValue)\n    candidateDay?.focus()\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"button\"\n    :aria-label=\"labelText\"\n    data-reka-calendar-cell-trigger\n    :aria-pressed=\"isSelectedDate && (allowNonContiguousRanges || !isUnavailable) ? true : undefined\"\n    :aria-disabled=\"isDisabled || isUnavailable ? true : undefined\"\n    :data-highlighted=\"isHighlighted && (allowNonContiguousRanges || !isUnavailable) ? '' : undefined\"\n    :data-selection-start=\"isSelectionStart ? true : undefined\"\n    :data-selection-end=\"isSelectionEnd ? true : undefined\"\n    :data-highlighted-start=\"isHighlightStart ? true : undefined\"\n    :data-highlighted-end=\"isHighlightEnd ? true : undefined\"\n    :data-selected=\"isSelectedDate && (allowNonContiguousRanges || !isUnavailable) ? true : undefined\"\n    :data-outside-visible-view=\"isOutsideVisibleView ? '' : undefined\"\n    :data-value=\"day.toString()\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-unavailable=\"isUnavailable ? '' : undefined\"\n    :data-today=\"isDateToday ? '' : undefined\"\n    :data-outside-view=\"isOutsideView ? '' : undefined\"\n    :data-focused=\"isFocusedDate ? '' : undefined\"\n    :tabindex=\"isFocusedDate ? 0 : isOutsideView || isDisabled ? undefined : -1\"\n    @click=\"handleClick\"\n    @focusin=\"handleFocus\"\n    @mouseenter=\"handleFocus\"\n    @keydown.up.down.left.right.enter.space=\"handleArrowKey\"\n  >\n    <slot\n      :day-value=\"dayValue\"\n      :disabled=\"isDisabled\"\n      :today=\"isDateToday\"\n      :selected=\"isSelectedDate\"\n      :outside-view=\"isOutsideView\"\n      :outside-visible-view=\"isOutsideVisibleView\"\n      :unavailable=\"isUnavailable\"\n      :highlighted=\"isHighlighted && (allowNonContiguousRanges || !isUnavailable)\"\n      :highlighted-start=\"isHighlightStart\"\n      :highlighted-end=\"isHighlightEnd\"\n      :selection-start=\"isSelectionStart\"\n      :selection-end=\"isSelectionEnd\"\n    >\n      {{ dayValue }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarCellTriggerProps, RangeCalendarCellTriggerSlot } from '@/RangeCalendar/RangeCalendarCellTrigger.vue'\nimport { RangeCalendarCellTrigger } from '..'\n\nexport interface DateRangePickerCellTriggerProps extends RangeCalendarCellTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerCellTriggerProps>()\n\ndefineSlots<RangeCalendarCellTriggerSlot>()\n</script>\n\n<template>\n  <RangeCalendarCellTrigger\n    v-slot=\"slotProps\"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </RangeCalendarCellTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarCellTriggerProps, RangeCalendarCellTriggerSlot } from '@/RangeCalendar/RangeCalendarCellTrigger.vue'\nimport { RangeCalendarCellTrigger } from '..'\n\nexport interface DateRangePickerCellTriggerProps extends RangeCalendarCellTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerCellTriggerProps>()\n\ndefineSlots<RangeCalendarCellTriggerSlot>()\n</script>\n\n<template>\n  <RangeCalendarCellTrigger\n    v-slot=\"slotProps\"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </RangeCalendarCellTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverCloseProps } from '..'\nimport { PopoverClose } from '..'\n\nexport interface DateRangePickerCloseProps extends PopoverCloseProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerCloseProps>()\n</script>\n\n<template>\n  <PopoverClose v-bind=\"props\">\n    <slot />\n  </PopoverClose>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverCloseProps } from '..'\nimport { PopoverClose } from '..'\n\nexport interface DateRangePickerCloseProps extends PopoverCloseProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerCloseProps>()\n</script>\n\n<template>\n  <PopoverClose v-bind=\"props\">\n    <slot />\n  </PopoverClose>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverContentEmits, PopoverContentProps, PopoverPortalProps } from '..'\nimport { computed } from 'vue'\nimport { handleCalendarInitialFocus } from '@/shared/date'\nimport { PopoverContent, PopoverPortal, useForwardPropsEmits } from '..'\n\nexport interface DateRangePickerContentProps extends PopoverContentProps {\n  /**\n   * Props to control the portal wrapped around the content.\n   */\n  portal?: PopoverPortalProps\n}\nexport interface DateRangePickerContentEmits extends PopoverContentEmits {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerContentProps>()\nconst emits = defineEmits<DateRangePickerContentEmits>()\n\nconst propsToForward = computed(() => ({\n  ...props,\n  portal: undefined,\n}))\nconst forwarded = useForwardPropsEmits(propsToForward, emits)\n</script>\n\n<template>\n  <PopoverPortal v-bind=\"portal\">\n    <PopoverContent\n      v-bind=\"{ ...forwarded, ...$attrs }\"\n      @open-auto-focus=\"event => {\n        emits('openAutoFocus', event)\n\n        if (!event.defaultPrevented && event.target) {\n          handleCalendarInitialFocus(event.target as HTMLElement)\n          event.preventDefault()\n        }\n      }\"\n    >\n      <slot />\n    </PopoverContent>\n  </PopoverPortal>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverContentEmits, PopoverContentProps, PopoverPortalProps } from '..'\nimport { computed } from 'vue'\nimport { handleCalendarInitialFocus } from '@/shared/date'\nimport { PopoverContent, PopoverPortal, useForwardPropsEmits } from '..'\n\nexport interface DateRangePickerContentProps extends PopoverContentProps {\n  /**\n   * Props to control the portal wrapped around the content.\n   */\n  portal?: PopoverPortalProps\n}\nexport interface DateRangePickerContentEmits extends PopoverContentEmits {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerContentProps>()\nconst emits = defineEmits<DateRangePickerContentEmits>()\n\nconst propsToForward = computed(() => ({\n  ...props,\n  portal: undefined,\n}))\nconst forwarded = useForwardPropsEmits(propsToForward, emits)\n</script>\n\n<template>\n  <PopoverPortal v-bind=\"portal\">\n    <PopoverContent\n      v-bind=\"{ ...forwarded, ...$attrs }\"\n      @open-auto-focus=\"event => {\n        emits('openAutoFocus', event)\n\n        if (!event.defaultPrevented && event.target) {\n          handleCalendarInitialFocus(event.target as HTMLElement)\n          event.preventDefault()\n        }\n      }\"\n    >\n      <slot />\n    </PopoverContent>\n  </PopoverPortal>\n</template>\n","<script lang=\"ts\">\nimport { isEqualDay } from '@internationalized/date'\nimport { DateRangeFieldRoot } from '..'\nimport { injectDateRangePickerRootContext } from './DateRangePickerRoot.vue'\n</script>\n\n<script setup lang=\"ts\">\nconst rootContext = injectDateRangePickerRootContext()\n</script>\n\n<template>\n  <DateRangeFieldRoot\n    v-slot=\"{ segments, modelValue }\"\n    :ref=\"rootContext.dateFieldRef\"\n    :model-value=\"rootContext.modelValue.value\"\n    :placeholder=\"rootContext.placeholder.value\"\n    v-bind=\"{\n      id: rootContext.id.value,\n      name: rootContext.name.value,\n      disabled: rootContext.disabled.value,\n      minValue: rootContext.minValue.value,\n      maxValue: rootContext.maxValue.value,\n      readonly: rootContext.readonly.value,\n      hourCycle: rootContext.hourCycle.value,\n      granularity: rootContext.granularity.value,\n      hideTimeZone: rootContext.hideTimeZone.value,\n      locale: rootContext.locale.value,\n      isDateUnavailable: rootContext.isDateUnavailable,\n      required: rootContext.required.value,\n      dir: rootContext.dir.value,\n      step: rootContext.step.value,\n    }\"\n    @update:model-value=\"(date) => {\n      if (date.start && rootContext.modelValue.value.start && date.end && rootContext.modelValue.value.end && date.start.compare(rootContext.modelValue.value.start) === 0 && date.end.compare(rootContext.modelValue.value.end) === 0) return\n      rootContext.onDateChange(date)\n    }\"\n    @update:placeholder=\"(date) => {\n      if (isEqualDay(date, rootContext.placeholder.value) && date.compare(rootContext.placeholder.value) === 0) return\n      rootContext.onPlaceholderChange(date)\n    }\"\n  >\n    <slot\n      :segments=\"segments\"\n      :model-value=\"modelValue\"\n    />\n  </DateRangeFieldRoot>\n</template>\n","<script lang=\"ts\">\nimport { isEqualDay } from '@internationalized/date'\nimport { DateRangeFieldRoot } from '..'\nimport { injectDateRangePickerRootContext } from './DateRangePickerRoot.vue'\n</script>\n\n<script setup lang=\"ts\">\nconst rootContext = injectDateRangePickerRootContext()\n</script>\n\n<template>\n  <DateRangeFieldRoot\n    v-slot=\"{ segments, modelValue }\"\n    :ref=\"rootContext.dateFieldRef\"\n    :model-value=\"rootContext.modelValue.value\"\n    :placeholder=\"rootContext.placeholder.value\"\n    v-bind=\"{\n      id: rootContext.id.value,\n      name: rootContext.name.value,\n      disabled: rootContext.disabled.value,\n      minValue: rootContext.minValue.value,\n      maxValue: rootContext.maxValue.value,\n      readonly: rootContext.readonly.value,\n      hourCycle: rootContext.hourCycle.value,\n      granularity: rootContext.granularity.value,\n      hideTimeZone: rootContext.hideTimeZone.value,\n      locale: rootContext.locale.value,\n      isDateUnavailable: rootContext.isDateUnavailable,\n      required: rootContext.required.value,\n      dir: rootContext.dir.value,\n      step: rootContext.step.value,\n    }\"\n    @update:model-value=\"(date) => {\n      if (date.start && rootContext.modelValue.value.start && date.end && rootContext.modelValue.value.end && date.start.compare(rootContext.modelValue.value.start) === 0 && date.end.compare(rootContext.modelValue.value.end) === 0) return\n      rootContext.onDateChange(date)\n    }\"\n    @update:placeholder=\"(date) => {\n      if (isEqualDay(date, rootContext.placeholder.value) && date.compare(rootContext.placeholder.value) === 0) return\n      rootContext.onPlaceholderChange(date)\n    }\"\n  >\n    <slot\n      :segments=\"segments\"\n      :model-value=\"modelValue\"\n    />\n  </DateRangeFieldRoot>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarGridProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectRangeCalendarRootContext } from './RangeCalendarRoot.vue'\n\nconst props = withDefaults(defineProps<RangeCalendarGridProps>(), { as: 'table' })\n\nconst rootContext = injectRangeCalendarRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value ? true : undefined)\nconst readonly = computed(() => rootContext.readonly.value ? true : undefined)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    role=\"application\"\n    :aria-readonly=\"readonly\"\n    :aria-disabled=\"disabled\"\n    :data-readonly=\"readonly && ''\"\n    :data-disabled=\"disabled && ''\"\n    @mouseleave=\"rootContext.focusedValue.value = undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarGridProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectRangeCalendarRootContext } from './RangeCalendarRoot.vue'\n\nconst props = withDefaults(defineProps<RangeCalendarGridProps>(), { as: 'table' })\n\nconst rootContext = injectRangeCalendarRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value ? true : undefined)\nconst readonly = computed(() => rootContext.readonly.value ? true : undefined)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    role=\"application\"\n    :aria-readonly=\"readonly\"\n    :aria-disabled=\"disabled\"\n    :data-readonly=\"readonly && ''\"\n    :data-disabled=\"disabled && ''\"\n    @mouseleave=\"rootContext.focusedValue.value = undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarGridProps } from '..'\nimport { RangeCalendarGrid } from '..'\n\nexport interface DateRangePickerGridProps extends RangeCalendarGridProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerGridProps>()\n</script>\n\n<template>\n  <RangeCalendarGrid v-bind=\"props\">\n    <slot />\n  </RangeCalendarGrid>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarGridProps } from '..'\nimport { RangeCalendarGrid } from '..'\n\nexport interface DateRangePickerGridProps extends RangeCalendarGridProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerGridProps>()\n</script>\n\n<template>\n  <RangeCalendarGrid v-bind=\"props\">\n    <slot />\n  </RangeCalendarGrid>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarGridBodyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<RangeCalendarGridBodyProps>(), { as: 'tbody' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarGridBodyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<RangeCalendarGridBodyProps>(), { as: 'tbody' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarGridBodyProps } from '..'\nimport { RangeCalendarGridBody } from '..'\n\nexport interface DateRangePickerGridBodyProps extends RangeCalendarGridBodyProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerGridBodyProps>()\n</script>\n\n<template>\n  <RangeCalendarGridBody v-bind=\"props\">\n    <slot />\n  </RangeCalendarGridBody>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarGridBodyProps } from '..'\nimport { RangeCalendarGridBody } from '..'\n\nexport interface DateRangePickerGridBodyProps extends RangeCalendarGridBodyProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerGridBodyProps>()\n</script>\n\n<template>\n  <RangeCalendarGridBody v-bind=\"props\">\n    <slot />\n  </RangeCalendarGridBody>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarGridHeadProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<RangeCalendarGridHeadProps>(), { as: 'thead' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-hidden=\"true\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarGridHeadProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<RangeCalendarGridHeadProps>(), { as: 'thead' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-hidden=\"true\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarGridHeadProps } from '..'\nimport { RangeCalendarGridHead } from '..'\n\nexport interface DateRangePickerGridHeadProps extends RangeCalendarGridHeadProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerGridHeadProps>()\n</script>\n\n<template>\n  <RangeCalendarGridHead v-bind=\"props\">\n    <slot />\n  </RangeCalendarGridHead>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarGridHeadProps } from '..'\nimport { RangeCalendarGridHead } from '..'\n\nexport interface DateRangePickerGridHeadProps extends RangeCalendarGridHeadProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerGridHeadProps>()\n</script>\n\n<template>\n  <RangeCalendarGridHead v-bind=\"props\">\n    <slot />\n  </RangeCalendarGridHead>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarGridRowProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<RangeCalendarGridRowProps>(), { as: 'tr' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarGridRowProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<RangeCalendarGridRowProps>(), { as: 'tr' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarGridRowProps } from '..'\nimport { RangeCalendarGridRow } from '..'\n\nexport interface DateRangePickerGridRowProps extends RangeCalendarGridRowProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerGridRowProps>()\n</script>\n\n<template>\n  <RangeCalendarGridRow v-bind=\"props\">\n    <slot />\n  </RangeCalendarGridRow>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarGridRowProps } from '..'\nimport { RangeCalendarGridRow } from '..'\n\nexport interface DateRangePickerGridRowProps extends RangeCalendarGridRowProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerGridRowProps>()\n</script>\n\n<template>\n  <RangeCalendarGridRow v-bind=\"props\">\n    <slot />\n  </RangeCalendarGridRow>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarHeadCellProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<RangeCalendarHeadCellProps>(), { as: 'th' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarHeadCellProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<RangeCalendarHeadCellProps>(), { as: 'th' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarHeadCellProps } from '..'\nimport { RangeCalendarHeadCell } from '..'\n\nexport interface DateRangePickerHeadCellProps extends RangeCalendarHeadCellProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerHeadCellProps>()\n</script>\n\n<template>\n  <RangeCalendarHeadCell v-bind=\"props\">\n    <slot />\n  </RangeCalendarHeadCell>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarHeadCellProps } from '..'\nimport { RangeCalendarHeadCell } from '..'\n\nexport interface DateRangePickerHeadCellProps extends RangeCalendarHeadCellProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerHeadCellProps>()\n</script>\n\n<template>\n  <RangeCalendarHeadCell v-bind=\"props\">\n    <slot />\n  </RangeCalendarHeadCell>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<RangeCalendarHeaderProps>(), { as: 'div' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<RangeCalendarHeaderProps>(), { as: 'div' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarHeaderProps } from '..'\nimport { RangeCalendarHeader } from '..'\n\nexport interface DateRangePickerHeaderProps extends RangeCalendarHeaderProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerHeaderProps>()\n</script>\n\n<template>\n  <RangeCalendarHeader v-bind=\"props\">\n    <slot />\n  </RangeCalendarHeader>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarHeaderProps } from '..'\nimport { RangeCalendarHeader } from '..'\n\nexport interface DateRangePickerHeaderProps extends RangeCalendarHeaderProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerHeaderProps>()\n</script>\n\n<template>\n  <RangeCalendarHeader v-bind=\"props\">\n    <slot />\n  </RangeCalendarHeader>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarHeadingProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectRangeCalendarRootContext } from './RangeCalendarRoot.vue'\n\nconst props = withDefaults(defineProps<RangeCalendarHeadingProps>(), { as: 'div' })\ndefineSlots<{\n  default?: (props: {\n    /** Current month and year */\n    headingValue: string\n  }) => any\n}>()\nconst rootContext = injectRangeCalendarRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n  >\n    <slot :heading-value=\"rootContext.headingValue.value\">\n      {{ rootContext.headingValue.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarHeadingProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectRangeCalendarRootContext } from './RangeCalendarRoot.vue'\n\nconst props = withDefaults(defineProps<RangeCalendarHeadingProps>(), { as: 'div' })\ndefineSlots<{\n  default?: (props: {\n    /** Current month and year */\n    headingValue: string\n  }) => any\n}>()\nconst rootContext = injectRangeCalendarRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n  >\n    <slot :heading-value=\"rootContext.headingValue.value\">\n      {{ rootContext.headingValue.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarHeadingProps } from '..'\nimport { RangeCalendarHeading } from '..'\n\nexport interface DateRangePickerHeadingProps extends RangeCalendarHeadingProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerHeadingProps>()\ndefineSlots<{\n  default?: (props: {\n    /** Current month and year */\n    headingValue: string\n  }) => any\n}>()\n</script>\n\n<template>\n  <RangeCalendarHeading\n    v-slot=\"{ headingValue }\"\n    v-bind=\"props\"\n  >\n    <slot :heading-value=\"headingValue\">\n      {{ headingValue }}\n    </slot>\n  </RangeCalendarHeading>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarHeadingProps } from '..'\nimport { RangeCalendarHeading } from '..'\n\nexport interface DateRangePickerHeadingProps extends RangeCalendarHeadingProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerHeadingProps>()\ndefineSlots<{\n  default?: (props: {\n    /** Current month and year */\n    headingValue: string\n  }) => any\n}>()\n</script>\n\n<template>\n  <RangeCalendarHeading\n    v-slot=\"{ headingValue }\"\n    v-bind=\"props\"\n  >\n    <slot :heading-value=\"headingValue\">\n      {{ headingValue }}\n    </slot>\n  </RangeCalendarHeading>\n</template>\n","<script lang=\"ts\">\nimport type { DateRangeFieldInputProps } from '..'\nimport { DateRangeFieldInput } from '..'\n\nexport interface DateRangePickerInputProps extends DateRangeFieldInputProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerInputProps>()\n</script>\n\n<template>\n  <DateRangeFieldInput v-bind=\"props\">\n    <slot />\n  </DateRangeFieldInput>\n</template>\n","<script lang=\"ts\">\nimport type { DateRangeFieldInputProps } from '..'\nimport { DateRangeFieldInput } from '..'\n\nexport interface DateRangePickerInputProps extends DateRangeFieldInputProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerInputProps>()\n</script>\n\n<template>\n  <DateRangeFieldInput v-bind=\"props\">\n    <slot />\n  </DateRangeFieldInput>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarNextProps extends PrimitiveProps {\n  /** The function to be used for the next page. Overwrites the `nextPage` function set on the `RangeCalendarRoot`. */\n  nextPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface RangeCalendarNextSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectRangeCalendarRootContext } from './RangeCalendarRoot.vue'\n\nconst props = withDefaults(defineProps<RangeCalendarNextProps>(), { as: 'button' })\ndefineSlots<RangeCalendarNextSlot>()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isNextButtonDisabled(props.nextPage))\n\nconst rootContext = injectRangeCalendarRootContext()\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.nextPage(props.nextPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Next page\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Next page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarNextProps extends PrimitiveProps {\n  /** The function to be used for the next page. Overwrites the `nextPage` function set on the `RangeCalendarRoot`. */\n  nextPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface RangeCalendarNextSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectRangeCalendarRootContext } from './RangeCalendarRoot.vue'\n\nconst props = withDefaults(defineProps<RangeCalendarNextProps>(), { as: 'button' })\ndefineSlots<RangeCalendarNextSlot>()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isNextButtonDisabled(props.nextPage))\n\nconst rootContext = injectRangeCalendarRootContext()\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.nextPage(props.nextPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Next page\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Next page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarNextProps } from '..'\nimport type { RangeCalendarNextSlot } from '@/RangeCalendar/RangeCalendarNext.vue'\nimport { RangeCalendarNext } from '..'\n\nexport interface DateRangePickerNextProps extends RangeCalendarNextProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerNextProps>()\ndefineSlots<RangeCalendarNextSlot>()\n</script>\n\n<template>\n  <RangeCalendarNext\n    v-slot=\"slotProps \"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </RangeCalendarNext>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarNextProps } from '..'\nimport type { RangeCalendarNextSlot } from '@/RangeCalendar/RangeCalendarNext.vue'\nimport { RangeCalendarNext } from '..'\n\nexport interface DateRangePickerNextProps extends RangeCalendarNextProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerNextProps>()\ndefineSlots<RangeCalendarNextSlot>()\n</script>\n\n<template>\n  <RangeCalendarNext\n    v-slot=\"slotProps \"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </RangeCalendarNext>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarPrevProps extends PrimitiveProps {\n  /** The function to be used for the prev page. Overwrites the `prevPage` function set on the `RangeCalendarRoot`. */\n  prevPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface RangeCalendarPrevSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectRangeCalendarRootContext } from './RangeCalendarRoot.vue'\n\nconst props = withDefaults(defineProps<RangeCalendarPrevProps>(), { as: 'button' })\ndefineSlots<RangeCalendarPrevSlot>()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isPrevButtonDisabled(props.prevPage))\n\nconst rootContext = injectRangeCalendarRootContext()\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.prevPage(props.prevPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Previous page\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Prev page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface RangeCalendarPrevProps extends PrimitiveProps {\n  /** The function to be used for the prev page. Overwrites the `prevPage` function set on the `RangeCalendarRoot`. */\n  prevPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface RangeCalendarPrevSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectRangeCalendarRootContext } from './RangeCalendarRoot.vue'\n\nconst props = withDefaults(defineProps<RangeCalendarPrevProps>(), { as: 'button' })\ndefineSlots<RangeCalendarPrevSlot>()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isPrevButtonDisabled(props.prevPage))\n\nconst rootContext = injectRangeCalendarRootContext()\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.prevPage(props.prevPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Previous page\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Prev page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarPrevProps } from '..'\nimport type { RangeCalendarPrevSlot } from '@/RangeCalendar/RangeCalendarPrev.vue'\nimport { RangeCalendarPrev } from '..'\n\nexport interface DateRangePickerPrevProps extends RangeCalendarPrevProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerPrevProps>()\ndefineSlots<RangeCalendarPrevSlot>()\n</script>\n\n<template>\n  <RangeCalendarPrev\n    v-slot=\"slotProps \"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </RangeCalendarPrev>\n</template>\n","<script lang=\"ts\">\nimport type { RangeCalendarPrevProps } from '..'\nimport type { RangeCalendarPrevSlot } from '@/RangeCalendar/RangeCalendarPrev.vue'\nimport { RangeCalendarPrev } from '..'\n\nexport interface DateRangePickerPrevProps extends RangeCalendarPrevProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerPrevProps>()\ndefineSlots<RangeCalendarPrevSlot>()\n</script>\n\n<template>\n  <RangeCalendarPrev\n    v-slot=\"slotProps \"\n    v-bind=\"props\"\n  >\n    <slot v-bind=\"slotProps\" />\n  </RangeCalendarPrev>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverTriggerProps } from '..'\nimport { PopoverTrigger } from '..'\nimport { injectDateRangePickerRootContext } from './DateRangePickerRoot.vue'\n\nexport interface DateRangePickerTriggerProps extends PopoverTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerTriggerProps>()\nconst rootContext = injectDateRangePickerRootContext()\n</script>\n\n<template>\n  <PopoverTrigger\n    data-reka-date-field-segment=\"trigger\"\n    v-bind=\"props\"\n    :disabled=\"rootContext.disabled.value\"\n    @focusin=\"(e: FocusEvent) => {\n      rootContext.dateFieldRef.value?.setFocusedElement(e.target as HTMLElement)\n    }\"\n  >\n    <slot />\n  </PopoverTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { PopoverTriggerProps } from '..'\nimport { PopoverTrigger } from '..'\nimport { injectDateRangePickerRootContext } from './DateRangePickerRoot.vue'\n\nexport interface DateRangePickerTriggerProps extends PopoverTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<DateRangePickerTriggerProps>()\nconst rootContext = injectDateRangePickerRootContext()\n</script>\n\n<template>\n  <PopoverTrigger\n    data-reka-date-field-segment=\"trigger\"\n    v-bind=\"props\"\n    :disabled=\"rootContext.disabled.value\"\n    @focusin=\"(e: FocusEvent) => {\n      rootContext.dateFieldRef.value?.setFocusedElement(e.target as HTMLElement)\n    }\"\n  >\n    <slot />\n  </PopoverTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { MenuArrowProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuArrowProps extends MenuArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuArrow } from '@/Menu'\n\nconst props = withDefaults(defineProps<DropdownMenuArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuArrow v-bind=\"props\">\n    <slot />\n  </MenuArrow>\n</template>\n","<script lang=\"ts\">\nimport type { MenuArrowProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuArrowProps extends MenuArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuArrow } from '@/Menu'\n\nconst props = withDefaults(defineProps<DropdownMenuArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuArrow v-bind=\"props\">\n    <slot />\n  </MenuArrow>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuCheckboxItemEmits,\n  MenuCheckboxItemProps,\n} from '@/Menu'\n\nexport type DropdownMenuCheckboxItemEmits = MenuCheckboxItemEmits\n\nexport interface DropdownMenuCheckboxItemProps extends MenuCheckboxItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuCheckboxItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<DropdownMenuCheckboxItemProps>()\nconst emits = defineEmits<DropdownMenuCheckboxItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuCheckboxItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuCheckboxItem>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuCheckboxItemEmits,\n  MenuCheckboxItemProps,\n} from '@/Menu'\n\nexport type DropdownMenuCheckboxItemEmits = MenuCheckboxItemEmits\n\nexport interface DropdownMenuCheckboxItemProps extends MenuCheckboxItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuCheckboxItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<DropdownMenuCheckboxItemProps>()\nconst emits = defineEmits<DropdownMenuCheckboxItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuCheckboxItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuCheckboxItem>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Direction } from '../shared/types'\nimport type { MenuEmits, MenuProps } from '@/Menu'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuRootProps extends MenuProps {\n  /** The open state of the dropdown menu when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n}\nexport type DropdownMenuRootEmits = MenuEmits\n\nexport interface DropdownMenuRootContext {\n  open: Readonly<Ref<boolean>>\n  onOpenChange: (open: boolean) => void\n  onOpenToggle: () => void\n  triggerId: string\n  triggerElement: Ref<HTMLElement | undefined>\n  contentId: string\n  modal: Ref<boolean>\n  dir: Ref<Direction>\n}\n\nexport const [injectDropdownMenuRootContext, provideDropdownMenuRootContext]\n  = createContext<DropdownMenuRootContext>('DropdownMenuRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, toRefs } from 'vue'\nimport { MenuRoot } from '@/Menu'\n\nconst props = withDefaults(defineProps<DropdownMenuRootProps>(), {\n  modal: true,\n  open: undefined,\n})\nconst emit = defineEmits<DropdownMenuRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nuseForwardExpose()\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst triggerElement = ref<HTMLElement>()\n\nconst { modal, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nprovideDropdownMenuRootContext({\n  open,\n  onOpenChange: (value) => {\n    open.value = value\n  },\n  onOpenToggle: () => {\n    open.value = !open.value\n  },\n  triggerId: '',\n  triggerElement,\n  contentId: '',\n  modal,\n  dir,\n})\n</script>\n\n<template>\n  <MenuRoot\n    v-model:open=\"open\"\n    :dir=\"dir\"\n    :modal=\"modal\"\n  >\n    <slot :open=\"open\" />\n  </MenuRoot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Direction } from '../shared/types'\nimport type { MenuEmits, MenuProps } from '@/Menu'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuRootProps extends MenuProps {\n  /** The open state of the dropdown menu when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n}\nexport type DropdownMenuRootEmits = MenuEmits\n\nexport interface DropdownMenuRootContext {\n  open: Readonly<Ref<boolean>>\n  onOpenChange: (open: boolean) => void\n  onOpenToggle: () => void\n  triggerId: string\n  triggerElement: Ref<HTMLElement | undefined>\n  contentId: string\n  modal: Ref<boolean>\n  dir: Ref<Direction>\n}\n\nexport const [injectDropdownMenuRootContext, provideDropdownMenuRootContext]\n  = createContext<DropdownMenuRootContext>('DropdownMenuRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, toRefs } from 'vue'\nimport { MenuRoot } from '@/Menu'\n\nconst props = withDefaults(defineProps<DropdownMenuRootProps>(), {\n  modal: true,\n  open: undefined,\n})\nconst emit = defineEmits<DropdownMenuRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nuseForwardExpose()\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst triggerElement = ref<HTMLElement>()\n\nconst { modal, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nprovideDropdownMenuRootContext({\n  open,\n  onOpenChange: (value) => {\n    open.value = value\n  },\n  onOpenToggle: () => {\n    open.value = !open.value\n  },\n  triggerId: '',\n  triggerElement,\n  contentId: '',\n  modal,\n  dir,\n})\n</script>\n\n<template>\n  <MenuRoot\n    v-model:open=\"open\"\n    :dir=\"dir\"\n    :modal=\"modal\"\n  >\n    <slot :open=\"open\" />\n  </MenuRoot>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuContentEmits,\n  MenuContentProps,\n} from '@/Menu'\n\nexport type DropdownMenuContentEmits = MenuContentEmits\n\nexport interface DropdownMenuContentProps extends MenuContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { MenuContent } from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits, useId } from '@/shared'\nimport { injectDropdownMenuRootContext } from './DropdownMenuRoot.vue'\n\nconst props = defineProps<DropdownMenuContentProps>()\nconst emits = defineEmits<DropdownMenuContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n\nconst rootContext = injectDropdownMenuRootContext()\n\nconst hasInteractedOutsideRef = ref(false)\n\nfunction handleCloseAutoFocus(event: Event) {\n  if (event.defaultPrevented)\n    return\n  if (!hasInteractedOutsideRef.value) {\n    setTimeout(() => {\n      rootContext.triggerElement.value?.focus()\n    }, 0)\n  }\n  hasInteractedOutsideRef.value = false\n\n  // Always prevent auto focus because we either focus manually or want user agent focus\n  event.preventDefault()\n}\n\nrootContext.contentId ||= useId(undefined, 'reka-dropdown-menu-content')\n</script>\n\n<template>\n  <MenuContent\n    v-bind=\"forwarded\"\n    :id=\"rootContext.contentId\"\n    :aria-labelledby=\"rootContext?.triggerId\"\n    :style=\"{\n      '--reka-dropdown-menu-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-dropdown-menu-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-dropdown-menu-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-dropdown-menu-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-dropdown-menu-trigger-height':\n        'var(--reka-popper-anchor-height)',\n    }\"\n    @close-auto-focus=\"handleCloseAutoFocus\"\n    @interact-outside=\"(event) => {\n      if (event.defaultPrevented) return\n\n      const originalEvent = event.detail.originalEvent as PointerEvent;\n      const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;\n      const isRightClick = originalEvent.button === 2 || ctrlLeftClick;\n      if (!rootContext.modal.value || isRightClick) hasInteractedOutsideRef = true;\n      if (rootContext.triggerElement.value?.contains(event.target as HTMLElement)) event.preventDefault()\n    }\"\n  >\n    <slot />\n  </MenuContent>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuContentEmits,\n  MenuContentProps,\n} from '@/Menu'\n\nexport type DropdownMenuContentEmits = MenuContentEmits\n\nexport interface DropdownMenuContentProps extends MenuContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { MenuContent } from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits, useId } from '@/shared'\nimport { injectDropdownMenuRootContext } from './DropdownMenuRoot.vue'\n\nconst props = defineProps<DropdownMenuContentProps>()\nconst emits = defineEmits<DropdownMenuContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n\nconst rootContext = injectDropdownMenuRootContext()\n\nconst hasInteractedOutsideRef = ref(false)\n\nfunction handleCloseAutoFocus(event: Event) {\n  if (event.defaultPrevented)\n    return\n  if (!hasInteractedOutsideRef.value) {\n    setTimeout(() => {\n      rootContext.triggerElement.value?.focus()\n    }, 0)\n  }\n  hasInteractedOutsideRef.value = false\n\n  // Always prevent auto focus because we either focus manually or want user agent focus\n  event.preventDefault()\n}\n\nrootContext.contentId ||= useId(undefined, 'reka-dropdown-menu-content')\n</script>\n\n<template>\n  <MenuContent\n    v-bind=\"forwarded\"\n    :id=\"rootContext.contentId\"\n    :aria-labelledby=\"rootContext?.triggerId\"\n    :style=\"{\n      '--reka-dropdown-menu-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-dropdown-menu-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-dropdown-menu-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-dropdown-menu-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-dropdown-menu-trigger-height':\n        'var(--reka-popper-anchor-height)',\n    }\"\n    @close-auto-focus=\"handleCloseAutoFocus\"\n    @interact-outside=\"(event) => {\n      if (event.defaultPrevented) return\n\n      const originalEvent = event.detail.originalEvent as PointerEvent;\n      const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;\n      const isRightClick = originalEvent.button === 2 || ctrlLeftClick;\n      if (!rootContext.modal.value || isRightClick) hasInteractedOutsideRef = true;\n      if (rootContext.triggerElement.value?.contains(event.target as HTMLElement)) event.preventDefault()\n    }\"\n  >\n    <slot />\n  </MenuContent>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useVModel } from '@vueuse/core'\nimport { computed, onMounted, onUnmounted, ref, watch, watchSyncEffect } from 'vue'\nimport { injectMenuContentContext } from '@/Menu/MenuContentImpl.vue'\nimport { injectMenuRootContext } from '@/Menu/MenuRoot.vue'\nimport { injectMenuSubContext } from '@/Menu/MenuSub.vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { useComposing } from '@/shared'\n\nexport interface DropdownMenuFilterProps extends PrimitiveProps {\n  /** The controlled value of the filter. Can be binded with v-model. */\n  modelValue?: string\n  /** Focus on element when mounted. */\n  autoFocus?: boolean\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n}\n\nexport type DropdownMenuFilterEmits = {\n  'update:modelValue': [string]\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = withDefaults(defineProps<DropdownMenuFilterProps>(), {\n  as: 'input',\n})\nconst emits = defineEmits<DropdownMenuFilterEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: '',\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst rootContext = injectMenuRootContext()\nconst contentContext = injectMenuContentContext()\nconst subContext = injectMenuSubContext(null)\n\n// Keep searchRef in sync with modelValue changes\nwatch(modelValue, (v) => { contentContext.searchRef.value = v ?? '' }, { immediate: true })\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst disabled = computed(() => props.disabled || false)\n\nconst activedescendant = ref<string | undefined>()\nwatchSyncEffect(() => activedescendant.value = contentContext.highlightedElement.value?.id)\n\nonMounted(() => {\n  contentContext.onFilterElementChange(currentElement.value)\n  setTimeout(() => {\n    // make sure all DOM was flush then only capture the focus\n    if (props.autoFocus) {\n      const isSubmenu = !!subContext\n      if (!isSubmenu || rootContext.isUsingKeyboardRef.value)\n        currentElement.value?.focus()\n    }\n  }, 1)\n})\n\nonUnmounted(() => {\n  contentContext.onFilterElementChange(undefined)\n  // Clean up search when unmounting\n  contentContext.searchRef.value = ''\n})\n\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing((event) => {\n  const el = event.target as HTMLInputElement\n  if (el) {\n    modelValue.value = el.value\n    contentContext.searchRef.value = el.value\n  }\n})\n\nfunction handleInput(event: InputEvent) {\n  if (disabled.value)\n    return\n  if (isComposing.value)\n    return\n  const target = event.target as HTMLInputElement\n  modelValue.value = target.value\n  contentContext.searchRef.value = target.value\n}\n\nfunction handleKeyDown(event: KeyboardEvent) {\n  if (disabled.value)\n    return\n  // During composition the keys belong to the IME (candidate navigation/commit).\n  // Stop them from bubbling to the menu content's keydown handler (which would\n  // navigate/typeahead) without calling preventDefault, so the IME still works.\n  if (isComposing.value) {\n    event.stopPropagation()\n    return\n  }\n  if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {\n    event.preventDefault()\n    contentContext.onKeydownNavigation(event)\n  }\n  else if (event.key === 'Enter') {\n    event.preventDefault()\n    contentContext.onKeydownEnter(event)\n  }\n  // Prevent Escape from bubbling to avoid closing the menu when clearing the filter\n  else if (event.key === 'Escape' && modelValue.value) {\n    event.stopPropagation()\n    modelValue.value = ''\n    contentContext.searchRef.value = ''\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :value=\"modelValue\"\n    :disabled=\"disabled ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :aria-activedescendant=\"activedescendant\"\n    type=\"text\"\n    role=\"searchbox\"\n    @input=\"handleInput\"\n    @keydown=\"handleKeyDown\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot :model-value=\"modelValue\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useVModel } from '@vueuse/core'\nimport { computed, onMounted, onUnmounted, ref, watch, watchSyncEffect } from 'vue'\nimport { injectMenuContentContext } from '@/Menu/MenuContentImpl.vue'\nimport { injectMenuRootContext } from '@/Menu/MenuRoot.vue'\nimport { injectMenuSubContext } from '@/Menu/MenuSub.vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { useComposing } from '@/shared'\n\nexport interface DropdownMenuFilterProps extends PrimitiveProps {\n  /** The controlled value of the filter. Can be binded with v-model. */\n  modelValue?: string\n  /** Focus on element when mounted. */\n  autoFocus?: boolean\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n}\n\nexport type DropdownMenuFilterEmits = {\n  'update:modelValue': [string]\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = withDefaults(defineProps<DropdownMenuFilterProps>(), {\n  as: 'input',\n})\nconst emits = defineEmits<DropdownMenuFilterEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: '',\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst rootContext = injectMenuRootContext()\nconst contentContext = injectMenuContentContext()\nconst subContext = injectMenuSubContext(null)\n\n// Keep searchRef in sync with modelValue changes\nwatch(modelValue, (v) => { contentContext.searchRef.value = v ?? '' }, { immediate: true })\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst disabled = computed(() => props.disabled || false)\n\nconst activedescendant = ref<string | undefined>()\nwatchSyncEffect(() => activedescendant.value = contentContext.highlightedElement.value?.id)\n\nonMounted(() => {\n  contentContext.onFilterElementChange(currentElement.value)\n  setTimeout(() => {\n    // make sure all DOM was flush then only capture the focus\n    if (props.autoFocus) {\n      const isSubmenu = !!subContext\n      if (!isSubmenu || rootContext.isUsingKeyboardRef.value)\n        currentElement.value?.focus()\n    }\n  }, 1)\n})\n\nonUnmounted(() => {\n  contentContext.onFilterElementChange(undefined)\n  // Clean up search when unmounting\n  contentContext.searchRef.value = ''\n})\n\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing((event) => {\n  const el = event.target as HTMLInputElement\n  if (el) {\n    modelValue.value = el.value\n    contentContext.searchRef.value = el.value\n  }\n})\n\nfunction handleInput(event: InputEvent) {\n  if (disabled.value)\n    return\n  if (isComposing.value)\n    return\n  const target = event.target as HTMLInputElement\n  modelValue.value = target.value\n  contentContext.searchRef.value = target.value\n}\n\nfunction handleKeyDown(event: KeyboardEvent) {\n  if (disabled.value)\n    return\n  // During composition the keys belong to the IME (candidate navigation/commit).\n  // Stop them from bubbling to the menu content's keydown handler (which would\n  // navigate/typeahead) without calling preventDefault, so the IME still works.\n  if (isComposing.value) {\n    event.stopPropagation()\n    return\n  }\n  if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {\n    event.preventDefault()\n    contentContext.onKeydownNavigation(event)\n  }\n  else if (event.key === 'Enter') {\n    event.preventDefault()\n    contentContext.onKeydownEnter(event)\n  }\n  // Prevent Escape from bubbling to avoid closing the menu when clearing the filter\n  else if (event.key === 'Escape' && modelValue.value) {\n    event.stopPropagation()\n    modelValue.value = ''\n    contentContext.searchRef.value = ''\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :value=\"modelValue\"\n    :disabled=\"disabled ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :aria-activedescendant=\"activedescendant\"\n    type=\"text\"\n    role=\"searchbox\"\n    @input=\"handleInput\"\n    @keydown=\"handleKeyDown\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot :model-value=\"modelValue\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { MenuGroupProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuGroupProps extends MenuGroupProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuGroup } from '@/Menu'\n\nconst props = defineProps<DropdownMenuGroupProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuGroup v-bind=\"props\">\n    <slot />\n  </MenuGroup>\n</template>\n","<script lang=\"ts\">\nimport type { MenuGroupProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuGroupProps extends MenuGroupProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuGroup } from '@/Menu'\n\nconst props = defineProps<DropdownMenuGroupProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuGroup v-bind=\"props\">\n    <slot />\n  </MenuGroup>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemEmits, MenuItemProps } from '@/Menu'\n\nexport type DropdownMenuItemEmits = MenuItemEmits\n\nexport interface DropdownMenuItemProps extends MenuItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<DropdownMenuItemProps>()\nconst emits = defineEmits<DropdownMenuItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuItem>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemEmits, MenuItemProps } from '@/Menu'\n\nexport type DropdownMenuItemEmits = MenuItemEmits\n\nexport interface DropdownMenuItemProps extends MenuItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<DropdownMenuItemProps>()\nconst emits = defineEmits<DropdownMenuItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuItem>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemIndicatorProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuItemIndicatorProps extends MenuItemIndicatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuItemIndicator } from '@/Menu'\n\nconst props = defineProps<DropdownMenuItemIndicatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuItemIndicator v-bind=\"props\">\n    <slot />\n  </MenuItemIndicator>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemIndicatorProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuItemIndicatorProps extends MenuItemIndicatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuItemIndicator } from '@/Menu'\n\nconst props = defineProps<DropdownMenuItemIndicatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuItemIndicator v-bind=\"props\">\n    <slot />\n  </MenuItemIndicator>\n</template>\n","<script lang=\"ts\">\nimport type { MenuLabelProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuLabelProps extends MenuLabelProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuLabel } from '@/Menu'\n\nconst props = defineProps<DropdownMenuLabelProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuLabel v-bind=\"props\">\n    <slot />\n  </MenuLabel>\n</template>\n","<script lang=\"ts\">\nimport type { MenuLabelProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuLabelProps extends MenuLabelProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuLabel } from '@/Menu'\n\nconst props = defineProps<DropdownMenuLabelProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuLabel v-bind=\"props\">\n    <slot />\n  </MenuLabel>\n</template>\n","<script lang=\"ts\">\nimport type { MenuPortalProps } from '@/Menu'\n\nexport interface DropdownMenuPortalProps extends MenuPortalProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuPortal } from '@/Menu'\n\nconst props = defineProps<DropdownMenuPortalProps>()\n</script>\n\n<template>\n  <MenuPortal v-bind=\"props\">\n    <slot />\n  </MenuPortal>\n</template>\n","<script lang=\"ts\">\nimport type { MenuPortalProps } from '@/Menu'\n\nexport interface DropdownMenuPortalProps extends MenuPortalProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuPortal } from '@/Menu'\n\nconst props = defineProps<DropdownMenuPortalProps>()\n</script>\n\n<template>\n  <MenuPortal v-bind=\"props\">\n    <slot />\n  </MenuPortal>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuRadioGroupEmits,\n  MenuRadioGroupProps,\n} from '@/Menu'\n\nexport type DropdownMenuRadioGroupEmits = MenuRadioGroupEmits\n\nexport interface DropdownMenuRadioGroupProps extends MenuRadioGroupProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuRadioGroup } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<MenuRadioGroupProps>()\nconst emits = defineEmits<MenuRadioGroupEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuRadioGroup v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuRadioGroup>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuRadioGroupEmits,\n  MenuRadioGroupProps,\n} from '@/Menu'\n\nexport type DropdownMenuRadioGroupEmits = MenuRadioGroupEmits\n\nexport interface DropdownMenuRadioGroupProps extends MenuRadioGroupProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuRadioGroup } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<MenuRadioGroupProps>()\nconst emits = defineEmits<MenuRadioGroupEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuRadioGroup v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuRadioGroup>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuRadioItemEmits,\n  MenuRadioItemProps,\n} from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\n\nexport type DropdownMenuRadioItemEmits = MenuRadioItemEmits\n\nexport interface DropdownMenuRadioItemProps extends MenuRadioItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuRadioItem } from '@/Menu'\n\nconst props = defineProps<DropdownMenuRadioItemProps>()\nconst emits = defineEmits<DropdownMenuRadioItemEmits>()\n\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuRadioItem v-bind=\"forwarded\">\n    <slot />\n  </MenuRadioItem>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuRadioItemEmits,\n  MenuRadioItemProps,\n} from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\n\nexport type DropdownMenuRadioItemEmits = MenuRadioItemEmits\n\nexport interface DropdownMenuRadioItemProps extends MenuRadioItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuRadioItem } from '@/Menu'\n\nconst props = defineProps<DropdownMenuRadioItemProps>()\nconst emits = defineEmits<DropdownMenuRadioItemEmits>()\n\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuRadioItem v-bind=\"forwarded\">\n    <slot />\n  </MenuRadioItem>\n</template>\n","<script lang=\"ts\">\nimport type { MenuSeparatorProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuSeparatorProps extends MenuSeparatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSeparator } from '@/Menu'\n\nconst props = defineProps<DropdownMenuSeparatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSeparator v-bind=\"props\">\n    <slot />\n  </MenuSeparator>\n</template>\n","<script lang=\"ts\">\nimport type { MenuSeparatorProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuSeparatorProps extends MenuSeparatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSeparator } from '@/Menu'\n\nconst props = defineProps<DropdownMenuSeparatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSeparator v-bind=\"props\">\n    <slot />\n  </MenuSeparator>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { MenuSubEmits, MenuSubProps } from '@/Menu'\n\nexport type DropdownMenuSubEmits = MenuSubEmits\nexport interface DropdownMenuSubProps extends MenuSubProps {\n  /** The open state of the dropdown menu when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { MenuSub } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = withDefaults(defineProps<DropdownMenuSubProps>(), {\n  open: undefined,\n})\nconst emit = defineEmits<DropdownMenuSubEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nconst open = useVModel(props, 'open', emit, {\n  passive: (props.open === undefined) as false,\n  defaultValue: props.defaultOpen ?? false,\n}) as Ref<boolean>\n\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSub v-model:open=\"open\">\n    <slot :open=\"open\" />\n  </MenuSub>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { MenuSubEmits, MenuSubProps } from '@/Menu'\n\nexport type DropdownMenuSubEmits = MenuSubEmits\nexport interface DropdownMenuSubProps extends MenuSubProps {\n  /** The open state of the dropdown menu when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { MenuSub } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = withDefaults(defineProps<DropdownMenuSubProps>(), {\n  open: undefined,\n})\nconst emit = defineEmits<DropdownMenuSubEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nconst open = useVModel(props, 'open', emit, {\n  passive: (props.open === undefined) as false,\n  defaultValue: props.defaultOpen ?? false,\n}) as Ref<boolean>\n\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSub v-model:open=\"open\">\n    <slot :open=\"open\" />\n  </MenuSub>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuSubContentEmits,\n  MenuSubContentProps,\n} from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport type DropdownMenuSubContentEmits = MenuSubContentEmits\n\nexport interface DropdownMenuSubContentProps extends MenuSubContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSubContent } from '@/Menu'\nimport { useForwardPropsEmits } from '..'\n\nconst props = defineProps<DropdownMenuSubContentProps>()\nconst emits = defineEmits<DropdownMenuSubContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSubContent\n    v-bind=\"forwarded\"\n    :style=\"{\n      '--reka-dropdown-menu-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-dropdown-menu-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-dropdown-menu-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-dropdown-menu-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-dropdown-menu-trigger-height':\n        'var(--reka-popper-anchor-height)',\n    }\"\n  >\n    <slot />\n  </MenuSubContent>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuSubContentEmits,\n  MenuSubContentProps,\n} from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport type DropdownMenuSubContentEmits = MenuSubContentEmits\n\nexport interface DropdownMenuSubContentProps extends MenuSubContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSubContent } from '@/Menu'\nimport { useForwardPropsEmits } from '..'\n\nconst props = defineProps<DropdownMenuSubContentProps>()\nconst emits = defineEmits<DropdownMenuSubContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSubContent\n    v-bind=\"forwarded\"\n    :style=\"{\n      '--reka-dropdown-menu-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-dropdown-menu-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-dropdown-menu-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-dropdown-menu-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-dropdown-menu-trigger-height':\n        'var(--reka-popper-anchor-height)',\n    }\"\n  >\n    <slot />\n  </MenuSubContent>\n</template>\n","<script lang=\"ts\">\nimport type { MenuSubTriggerProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuSubTriggerProps extends MenuSubTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSubTrigger } from '@/Menu'\n\nconst props = defineProps<DropdownMenuSubTriggerProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSubTrigger v-bind=\"props\">\n    <slot />\n  </MenuSubTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { MenuSubTriggerProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface DropdownMenuSubTriggerProps extends MenuSubTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSubTrigger } from '@/Menu'\n\nconst props = defineProps<DropdownMenuSubTriggerProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSubTrigger v-bind=\"props\">\n    <slot />\n  </MenuSubTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose, useId } from '@/shared'\n\nexport interface DropdownMenuTriggerProps extends PrimitiveProps {\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { nextTick, onMounted } from 'vue'\nimport { MenuAnchor } from '@/Menu'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectDropdownMenuRootContext } from './DropdownMenuRoot.vue'\n\nconst props = withDefaults(defineProps<DropdownMenuTriggerProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectDropdownMenuRootContext()\n\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\n\nonMounted(() => {\n  rootContext.triggerElement = triggerElement\n})\n\nrootContext.triggerId ||= useId(undefined, 'reka-dropdown-menu-trigger')\n</script>\n\n<template>\n  <MenuAnchor as-child>\n    <Primitive\n      :id=\"rootContext.triggerId\"\n      :ref=\"forwardRef\"\n      :type=\"as === 'button' ? 'button' : undefined\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n      aria-haspopup=\"menu\"\n      :aria-expanded=\"rootContext.open.value\"\n      :aria-controls=\"rootContext.open.value ? rootContext.contentId : undefined\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :disabled=\"disabled\"\n      :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n      @click=\"\n        async (event: MouseEvent) => {\n          // only call handler if it's the left button (mousedown gets triggered by all mouse buttons)\n          // but not when the control key is pressed (avoiding MacOS right click)\n          if (!disabled && event.button === 0 && event.ctrlKey === false) {\n            rootContext?.onOpenToggle();\n            await nextTick()\n            // prevent trigger focusing when opening\n            // this allows the content to be given focus without competition\n            if (rootContext.open.value) event.preventDefault();\n          }\n        }\n      \"\n      @keydown.enter.space.arrow-down=\"\n        (event: KeyboardEvent) => {\n          if (disabled) return;\n          if (['Enter', ' '].includes(event.key)) rootContext.onOpenToggle();\n          if (event.key === 'ArrowDown') rootContext.onOpenChange(true);\n          // prevent keydown from scrolling window / first focused item to execute\n          // that keydown (inadvertently closing the menu)\n          if (['Enter', ' ', 'ArrowDown'].includes(event.key))\n            event.preventDefault();\n        }\n      \"\n    >\n      <slot />\n    </Primitive>\n  </MenuAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose, useId } from '@/shared'\n\nexport interface DropdownMenuTriggerProps extends PrimitiveProps {\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { nextTick, onMounted } from 'vue'\nimport { MenuAnchor } from '@/Menu'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectDropdownMenuRootContext } from './DropdownMenuRoot.vue'\n\nconst props = withDefaults(defineProps<DropdownMenuTriggerProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectDropdownMenuRootContext()\n\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\n\nonMounted(() => {\n  rootContext.triggerElement = triggerElement\n})\n\nrootContext.triggerId ||= useId(undefined, 'reka-dropdown-menu-trigger')\n</script>\n\n<template>\n  <MenuAnchor as-child>\n    <Primitive\n      :id=\"rootContext.triggerId\"\n      :ref=\"forwardRef\"\n      :type=\"as === 'button' ? 'button' : undefined\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n      aria-haspopup=\"menu\"\n      :aria-expanded=\"rootContext.open.value\"\n      :aria-controls=\"rootContext.open.value ? rootContext.contentId : undefined\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :disabled=\"disabled\"\n      :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n      @click=\"\n        async (event: MouseEvent) => {\n          // only call handler if it's the left button (mousedown gets triggered by all mouse buttons)\n          // but not when the control key is pressed (avoiding MacOS right click)\n          if (!disabled && event.button === 0 && event.ctrlKey === false) {\n            rootContext?.onOpenToggle();\n            await nextTick()\n            // prevent trigger focusing when opening\n            // this allows the content to be given focus without competition\n            if (rootContext.open.value) event.preventDefault();\n          }\n        }\n      \"\n      @keydown.enter.space.arrow-down=\"\n        (event: KeyboardEvent) => {\n          if (disabled) return;\n          if (['Enter', ' '].includes(event.key)) rootContext.onOpenToggle();\n          if (event.key === 'ArrowDown') rootContext.onOpenChange(true);\n          // prevent keydown from scrolling window / first focused item to execute\n          // that keydown (inadvertently closing the menu)\n          if (['Enter', ' ', 'ArrowDown'].includes(event.key))\n            event.preventDefault();\n        }\n      \"\n    >\n      <slot />\n    </Primitive>\n  </MenuAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport { useFocusOutside, usePointerDownOutside } from '@/DismissableLayer'\nimport { createContext, useDirection, useFormControl } from '@/shared'\n\ntype ActivationMode = 'focus' | 'dblclick' | 'none'\ntype SubmitMode = 'blur' | 'enter' | 'none' | 'both'\n\ntype EditableRootContext = {\n  id: Ref<string | undefined>\n  name: Ref<string | undefined>\n  maxLength: Ref<number | undefined>\n  disabled: Ref<boolean>\n  modelValue: Ref<string | null | undefined>\n  inputValue: Ref<string | null | undefined>\n  placeholder: Ref<{ edit: string, preview: string }>\n  isEditing: Ref<boolean>\n  submitMode: Ref<SubmitMode>\n  activationMode: Ref<ActivationMode>\n  selectOnFocus: Ref<boolean>\n  edit: () => void\n  cancel: () => void\n  submit: () => void\n  inputRef: Ref<HTMLInputElement | undefined>\n  startWithEditMode: Ref<boolean>\n  isEmpty: Ref<boolean>\n  readonly: Ref<boolean>\n  autoResize: Ref<boolean>\n}\n\nexport interface EditableRootProps extends PrimitiveProps, FormFieldProps {\n  /** The default value of the editable field */\n  defaultValue?: string\n  /** The value of the editable field */\n  modelValue?: string | null\n  /** The placeholder for the editable field */\n  placeholder?: string | { edit: string, preview: string }\n  /** The reading direction of the calendar when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** Whether the editable field is disabled */\n  disabled?: boolean\n  /** Whether the editable field is read-only */\n  readonly?: boolean\n  /** The activation event of the editable field */\n  activationMode?: ActivationMode\n  /** Whether to select the text in the input when it is focused. */\n  selectOnFocus?: boolean\n  /** The submit event of the editable field */\n  submitMode?: SubmitMode\n  /** Whether to start with the edit mode active */\n  startWithEditMode?: boolean\n  /** The maximum number of characters allowed */\n  maxLength?: number\n  /** Whether the editable field should auto resize */\n  autoResize?: boolean\n  /** The id of the field */\n  id?: string\n}\n\nexport type EditableRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [value: string]\n  /** Event handler called when a value is submitted */\n  'submit': [value: string | null | undefined]\n  /** Event handler called when the editable field changes state */\n  'update:state': [state: 'edit' | 'submit' | 'cancel']\n}\n\nexport const [injectEditableRootContext, provideEditableRootContext]\n  = createContext<EditableRootContext>('EditableRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<EditableRootProps>(), {\n  as: 'div',\n  disabled: false,\n  submitMode: 'blur',\n  activationMode: 'focus',\n  selectOnFocus: false,\n  placeholder: 'Enter text...',\n  autoResize: false,\n  required: false,\n})\n\nconst emits = defineEmits<EditableRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** Whether the editable field is in edit mode */\n    isEditing: boolean\n    /** The value of the editable field */\n    modelValue: typeof modelValue.value\n    /** Whether the editable field is empty */\n    isEmpty: boolean\n    /** Function to submit the value of the editable */\n    submit: () => void\n    /** Function to cancel the value of the editable */\n    cancel: () => void\n    /** Function to set the editable in edit mode */\n    edit: () => void\n  }) => any\n}>()\n\nconst {\n  id,\n  name,\n  defaultValue,\n  startWithEditMode,\n  placeholder: propPlaceholder,\n  maxLength,\n  disabled,\n  dir: propDir,\n  submitMode,\n  activationMode,\n  selectOnFocus,\n  readonly,\n  autoResize,\n  required,\n} = toRefs(props)\n\nconst inputRef = ref<HTMLInputElement | undefined>()\nconst dir = useDirection(propDir)\nconst isEditing = ref(startWithEditMode.value ?? false)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value ?? '',\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst isFormControl = useFormControl(currentElement)\n\nconst placeholder = computed(() => {\n  return typeof propPlaceholder.value === 'string' ? { edit: propPlaceholder.value, preview: propPlaceholder.value } : propPlaceholder.value\n})\n\nconst inputValue = ref(modelValue.value)\n\nwatch(() => modelValue.value, () => {\n  inputValue.value = modelValue.value\n}, { immediate: true, deep: true })\n\nfunction cancel() {\n  isEditing.value = false\n  emits('update:state', 'cancel')\n}\n\nfunction edit() {\n  isEditing.value = true\n  inputValue.value = modelValue.value\n\n  emits('update:state', 'edit')\n}\n\nfunction submit() {\n  modelValue.value = inputValue.value\n  isEditing.value = false\n\n  emits('update:state', 'submit')\n  emits('submit', inputValue.value)\n}\n\nfunction handleDismiss() {\n  if (isEditing.value) {\n    if (submitMode.value === 'blur' || submitMode.value === 'both')\n      submit()\n    else\n      cancel()\n  }\n}\n\nconst pointerDownOutside = usePointerDownOutside(() => handleDismiss(), currentElement, isEditing)\nconst focusOutside = useFocusOutside(() => handleDismiss(), currentElement, isEditing)\n\nconst isEmpty = computed(() => modelValue.value === '')\n\ndefineExpose({\n  /** Function to submit the value of the editable */\n  submit,\n  /** Function to cancel the value of the editable */\n  cancel,\n  /** Function to set the editable in edit mode */\n  edit,\n})\n\nprovideEditableRootContext({\n  id,\n  name,\n  disabled,\n  isEditing,\n  maxLength,\n  modelValue,\n  inputValue,\n  placeholder,\n  edit,\n  cancel,\n  submit,\n  activationMode,\n  submitMode,\n  selectOnFocus,\n  inputRef,\n  startWithEditMode,\n  isEmpty,\n  readonly,\n  autoResize,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :dir=\"dir\"\n    data-dismissable-layer\n    @focus.capture=\"focusOutside.onFocusCapture\"\n    @blur.capture=\"focusOutside.onBlurCapture\"\n    @pointerdown.capture=\"pointerDownOutside.onPointerDownCapture\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :is-editing=\"isEditing\"\n      :is-empty=\"isEmpty\"\n      :submit=\"submit\"\n      :cancel=\"cancel\"\n      :edit=\"edit\"\n    />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      type=\"text\"\n      :value=\"modelValue\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport { useFocusOutside, usePointerDownOutside } from '@/DismissableLayer'\nimport { createContext, useDirection, useFormControl } from '@/shared'\n\ntype ActivationMode = 'focus' | 'dblclick' | 'none'\ntype SubmitMode = 'blur' | 'enter' | 'none' | 'both'\n\ntype EditableRootContext = {\n  id: Ref<string | undefined>\n  name: Ref<string | undefined>\n  maxLength: Ref<number | undefined>\n  disabled: Ref<boolean>\n  modelValue: Ref<string | null | undefined>\n  inputValue: Ref<string | null | undefined>\n  placeholder: Ref<{ edit: string, preview: string }>\n  isEditing: Ref<boolean>\n  submitMode: Ref<SubmitMode>\n  activationMode: Ref<ActivationMode>\n  selectOnFocus: Ref<boolean>\n  edit: () => void\n  cancel: () => void\n  submit: () => void\n  inputRef: Ref<HTMLInputElement | undefined>\n  startWithEditMode: Ref<boolean>\n  isEmpty: Ref<boolean>\n  readonly: Ref<boolean>\n  autoResize: Ref<boolean>\n}\n\nexport interface EditableRootProps extends PrimitiveProps, FormFieldProps {\n  /** The default value of the editable field */\n  defaultValue?: string\n  /** The value of the editable field */\n  modelValue?: string | null\n  /** The placeholder for the editable field */\n  placeholder?: string | { edit: string, preview: string }\n  /** The reading direction of the calendar when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** Whether the editable field is disabled */\n  disabled?: boolean\n  /** Whether the editable field is read-only */\n  readonly?: boolean\n  /** The activation event of the editable field */\n  activationMode?: ActivationMode\n  /** Whether to select the text in the input when it is focused. */\n  selectOnFocus?: boolean\n  /** The submit event of the editable field */\n  submitMode?: SubmitMode\n  /** Whether to start with the edit mode active */\n  startWithEditMode?: boolean\n  /** The maximum number of characters allowed */\n  maxLength?: number\n  /** Whether the editable field should auto resize */\n  autoResize?: boolean\n  /** The id of the field */\n  id?: string\n}\n\nexport type EditableRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [value: string]\n  /** Event handler called when a value is submitted */\n  'submit': [value: string | null | undefined]\n  /** Event handler called when the editable field changes state */\n  'update:state': [state: 'edit' | 'submit' | 'cancel']\n}\n\nexport const [injectEditableRootContext, provideEditableRootContext]\n  = createContext<EditableRootContext>('EditableRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<EditableRootProps>(), {\n  as: 'div',\n  disabled: false,\n  submitMode: 'blur',\n  activationMode: 'focus',\n  selectOnFocus: false,\n  placeholder: 'Enter text...',\n  autoResize: false,\n  required: false,\n})\n\nconst emits = defineEmits<EditableRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** Whether the editable field is in edit mode */\n    isEditing: boolean\n    /** The value of the editable field */\n    modelValue: typeof modelValue.value\n    /** Whether the editable field is empty */\n    isEmpty: boolean\n    /** Function to submit the value of the editable */\n    submit: () => void\n    /** Function to cancel the value of the editable */\n    cancel: () => void\n    /** Function to set the editable in edit mode */\n    edit: () => void\n  }) => any\n}>()\n\nconst {\n  id,\n  name,\n  defaultValue,\n  startWithEditMode,\n  placeholder: propPlaceholder,\n  maxLength,\n  disabled,\n  dir: propDir,\n  submitMode,\n  activationMode,\n  selectOnFocus,\n  readonly,\n  autoResize,\n  required,\n} = toRefs(props)\n\nconst inputRef = ref<HTMLInputElement | undefined>()\nconst dir = useDirection(propDir)\nconst isEditing = ref(startWithEditMode.value ?? false)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value ?? '',\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst isFormControl = useFormControl(currentElement)\n\nconst placeholder = computed(() => {\n  return typeof propPlaceholder.value === 'string' ? { edit: propPlaceholder.value, preview: propPlaceholder.value } : propPlaceholder.value\n})\n\nconst inputValue = ref(modelValue.value)\n\nwatch(() => modelValue.value, () => {\n  inputValue.value = modelValue.value\n}, { immediate: true, deep: true })\n\nfunction cancel() {\n  isEditing.value = false\n  emits('update:state', 'cancel')\n}\n\nfunction edit() {\n  isEditing.value = true\n  inputValue.value = modelValue.value\n\n  emits('update:state', 'edit')\n}\n\nfunction submit() {\n  modelValue.value = inputValue.value\n  isEditing.value = false\n\n  emits('update:state', 'submit')\n  emits('submit', inputValue.value)\n}\n\nfunction handleDismiss() {\n  if (isEditing.value) {\n    if (submitMode.value === 'blur' || submitMode.value === 'both')\n      submit()\n    else\n      cancel()\n  }\n}\n\nconst pointerDownOutside = usePointerDownOutside(() => handleDismiss(), currentElement, isEditing)\nconst focusOutside = useFocusOutside(() => handleDismiss(), currentElement, isEditing)\n\nconst isEmpty = computed(() => modelValue.value === '')\n\ndefineExpose({\n  /** Function to submit the value of the editable */\n  submit,\n  /** Function to cancel the value of the editable */\n  cancel,\n  /** Function to set the editable in edit mode */\n  edit,\n})\n\nprovideEditableRootContext({\n  id,\n  name,\n  disabled,\n  isEditing,\n  maxLength,\n  modelValue,\n  inputValue,\n  placeholder,\n  edit,\n  cancel,\n  submit,\n  activationMode,\n  submitMode,\n  selectOnFocus,\n  inputRef,\n  startWithEditMode,\n  isEmpty,\n  readonly,\n  autoResize,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :dir=\"dir\"\n    data-dismissable-layer\n    @focus.capture=\"focusOutside.onFocusCapture\"\n    @blur.capture=\"focusOutside.onBlurCapture\"\n    @pointerdown.capture=\"pointerDownOutside.onPointerDownCapture\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :is-editing=\"isEditing\"\n      :is-empty=\"isEmpty\"\n      :submit=\"submit\"\n      :cancel=\"cancel\"\n      :edit=\"edit\"\n    />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      type=\"text\"\n      :value=\"modelValue\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { injectEditableRootContext } from './EditableRoot.vue'\n\nexport interface EditableAreaProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<EditableAreaProps>(), { as: 'div' })\n\nconst context = injectEditableRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :data-placeholder-shown=\"context.isEditing.value ? undefined : ''\"\n    :data-focus=\"context.isEditing.value ? '' : undefined\"\n    :data-focused=\"context.isEditing.value ? '' : undefined\"\n    :data-empty=\"context.isEmpty.value ? '' : undefined\"\n    :data-readonly=\"context.readonly.value ? '' : undefined\"\n    :data-disabled=\"context.disabled.value ? '' : undefined\"\n    :style=\"context.autoResize.value ? { display: 'inline-grid' } : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { injectEditableRootContext } from './EditableRoot.vue'\n\nexport interface EditableAreaProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<EditableAreaProps>(), { as: 'div' })\n\nconst context = injectEditableRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :data-placeholder-shown=\"context.isEditing.value ? undefined : ''\"\n    :data-focus=\"context.isEditing.value ? '' : undefined\"\n    :data-focused=\"context.isEditing.value ? '' : undefined\"\n    :data-empty=\"context.isEmpty.value ? '' : undefined\"\n    :data-readonly=\"context.readonly.value ? '' : undefined\"\n    :data-disabled=\"context.disabled.value ? '' : undefined\"\n    :style=\"context.autoResize.value ? { display: 'inline-grid' } : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface EditableCancelTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectEditableRootContext } from './EditableRoot.vue'\n\nconst props = withDefaults(defineProps<EditableCancelTriggerProps>(), { as: 'button' })\n\nconst context = injectEditableRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"cancel\"\n    :aria-disabled=\"context.disabled.value ? '' : undefined\"\n    :data-disabled=\"context.disabled.value ? '' : undefined\"\n    :disabled=\"context.disabled.value\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :hidden=\"context.isEditing.value ? undefined : ''\"\n    @click=\"context.cancel\"\n  >\n    <slot>Cancel</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface EditableCancelTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectEditableRootContext } from './EditableRoot.vue'\n\nconst props = withDefaults(defineProps<EditableCancelTriggerProps>(), { as: 'button' })\n\nconst context = injectEditableRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"cancel\"\n    :aria-disabled=\"context.disabled.value ? '' : undefined\"\n    :data-disabled=\"context.disabled.value ? '' : undefined\"\n    :disabled=\"context.disabled.value\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :hidden=\"context.isEditing.value ? undefined : ''\"\n    @click=\"context.cancel\"\n  >\n    <slot>Cancel</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface EditableEditTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectEditableRootContext } from './EditableRoot.vue'\n\nconst props = withDefaults(defineProps<EditableEditTriggerProps>(), { as: 'button' })\n\nconst context = injectEditableRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"edit\"\n    :aria-disabled=\"context.disabled.value ? '' : undefined\"\n    :data-disabled=\"context.disabled.value ? '' : undefined\"\n    :disabled=\"context.disabled.value\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :hidden=\"context.isEditing.value ? '' : undefined\"\n    @click=\"context.edit\"\n  >\n    <slot>Edit</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface EditableEditTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectEditableRootContext } from './EditableRoot.vue'\n\nconst props = withDefaults(defineProps<EditableEditTriggerProps>(), { as: 'button' })\n\nconst context = injectEditableRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"edit\"\n    :aria-disabled=\"context.disabled.value ? '' : undefined\"\n    :data-disabled=\"context.disabled.value ? '' : undefined\"\n    :disabled=\"context.disabled.value\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :hidden=\"context.isEditing.value ? '' : undefined\"\n    @click=\"context.edit\"\n  >\n    <slot>Edit</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nexport interface EditableInputProps extends PrimitiveProps {\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, nextTick, onMounted, watch } from 'vue'\nimport { useKbd } from '@/shared'\nimport { injectEditableRootContext } from './EditableRoot.vue'\n\nconst props = withDefaults(defineProps<EditableInputProps>(), {\n  as: 'input',\n})\n\nconst kbd = useKbd()\n\nconst context = injectEditableRootContext()\n\nconst disabled = computed(() => context.disabled.value)\n\nconst placeholder = computed(() => context.placeholder.value?.edit)\n\nconst { primitiveElement, currentElement: inputRef } = usePrimitiveElement()\n\nonMounted(() => {\n  context.inputRef.value = inputRef.value as HTMLInputElement\n  if (context.startWithEditMode.value) {\n    context.inputRef.value?.focus({ preventScroll: true })\n    if (context.selectOnFocus.value)\n      context.inputRef.value?.select()\n  }\n})\n\nwatch(context.isEditing, (value) => {\n  if (value) {\n    nextTick(() => {\n      context.inputRef.value?.focus({ preventScroll: true })\n      if (context.selectOnFocus.value)\n        context.inputRef.value?.select()\n    })\n  }\n})\n\nfunction handleSubmitKeyDown(event: KeyboardEvent) {\n  if ((context.submitMode.value === 'enter' || context.submitMode.value === 'both') && event.key === kbd.ENTER && !event.shiftKey && !event.metaKey && !event.isComposing)\n    context.submit()\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    v-bind=\"props\"\n    :value=\"context.inputValue.value\"\n    :placeholder=\"placeholder\"\n    :disabled=\"disabled\"\n    :maxlength=\"context.maxLength.value\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"context.readonly.value ? '' : undefined\"\n    :readonly=\"context.readonly.value\"\n    aria-label=\"editable input\"\n    :hidden=\"context.autoResize.value ? undefined : !context.isEditing.value\"\n    :style=\"context.autoResize.value ? { all: 'unset', gridArea: '1 / 1 / auto / auto', visibility: !context.isEditing.value ? 'hidden' : undefined } : undefined\"\n    @input=\"context.inputValue.value = $event.target.value\"\n    @keydown.enter.space=\"handleSubmitKeyDown\"\n    @keydown.esc=\"context.cancel\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nexport interface EditableInputProps extends PrimitiveProps {\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, nextTick, onMounted, watch } from 'vue'\nimport { useKbd } from '@/shared'\nimport { injectEditableRootContext } from './EditableRoot.vue'\n\nconst props = withDefaults(defineProps<EditableInputProps>(), {\n  as: 'input',\n})\n\nconst kbd = useKbd()\n\nconst context = injectEditableRootContext()\n\nconst disabled = computed(() => context.disabled.value)\n\nconst placeholder = computed(() => context.placeholder.value?.edit)\n\nconst { primitiveElement, currentElement: inputRef } = usePrimitiveElement()\n\nonMounted(() => {\n  context.inputRef.value = inputRef.value as HTMLInputElement\n  if (context.startWithEditMode.value) {\n    context.inputRef.value?.focus({ preventScroll: true })\n    if (context.selectOnFocus.value)\n      context.inputRef.value?.select()\n  }\n})\n\nwatch(context.isEditing, (value) => {\n  if (value) {\n    nextTick(() => {\n      context.inputRef.value?.focus({ preventScroll: true })\n      if (context.selectOnFocus.value)\n        context.inputRef.value?.select()\n    })\n  }\n})\n\nfunction handleSubmitKeyDown(event: KeyboardEvent) {\n  if ((context.submitMode.value === 'enter' || context.submitMode.value === 'both') && event.key === kbd.ENTER && !event.shiftKey && !event.metaKey && !event.isComposing)\n    context.submit()\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    v-bind=\"props\"\n    :value=\"context.inputValue.value\"\n    :placeholder=\"placeholder\"\n    :disabled=\"disabled\"\n    :maxlength=\"context.maxLength.value\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"context.readonly.value ? '' : undefined\"\n    :readonly=\"context.readonly.value\"\n    aria-label=\"editable input\"\n    :hidden=\"context.autoResize.value ? undefined : !context.isEditing.value\"\n    :style=\"context.autoResize.value ? { all: 'unset', gridArea: '1 / 1 / auto / auto', visibility: !context.isEditing.value ? 'hidden' : undefined } : undefined\"\n    @input=\"context.inputValue.value = $event.target.value\"\n    @keydown.enter.space=\"handleSubmitKeyDown\"\n    @keydown.esc=\"context.cancel\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed } from 'vue'\nimport { injectEditableRootContext } from './EditableRoot.vue'\n\nexport interface EditablePreviewProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<EditablePreviewProps>(), { as: 'span' })\n\nconst context = injectEditableRootContext()\n\nconst placeholder = computed(() => context.placeholder.value?.preview)\n\nfunction handleFocus() {\n  if (context.activationMode.value === 'focus')\n    context.edit()\n}\nfunction handleDoubleClick() {\n  if (context.activationMode.value === 'dblclick')\n    context.edit()\n}\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"0\"\n    :data-placeholder-shown=\"context.isEditing.value ? undefined : ''\"\n    :hidden=\"context.autoResize.value ? undefined : context.isEditing.value\"\n    :style=\"context.autoResize.value ? {\n      whiteSpace: 'pre',\n      userSelect: 'none',\n      gridArea: '1 / 1 / auto / auto',\n      visibility: context.isEditing.value ? 'hidden' : undefined,\n      overflow: 'hidden',\n      textOverflow: 'ellipsis',\n    } : undefined\"\n    @focusin=\"handleFocus\"\n    @dblclick=\"handleDoubleClick\"\n  >\n    <slot>\n      {{ context.modelValue.value || placeholder }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed } from 'vue'\nimport { injectEditableRootContext } from './EditableRoot.vue'\n\nexport interface EditablePreviewProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<EditablePreviewProps>(), { as: 'span' })\n\nconst context = injectEditableRootContext()\n\nconst placeholder = computed(() => context.placeholder.value?.preview)\n\nfunction handleFocus() {\n  if (context.activationMode.value === 'focus')\n    context.edit()\n}\nfunction handleDoubleClick() {\n  if (context.activationMode.value === 'dblclick')\n    context.edit()\n}\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"0\"\n    :data-placeholder-shown=\"context.isEditing.value ? undefined : ''\"\n    :hidden=\"context.autoResize.value ? undefined : context.isEditing.value\"\n    :style=\"context.autoResize.value ? {\n      whiteSpace: 'pre',\n      userSelect: 'none',\n      gridArea: '1 / 1 / auto / auto',\n      visibility: context.isEditing.value ? 'hidden' : undefined,\n      overflow: 'hidden',\n      textOverflow: 'ellipsis',\n    } : undefined\"\n    @focusin=\"handleFocus\"\n    @dblclick=\"handleDoubleClick\"\n  >\n    <slot>\n      {{ context.modelValue.value || placeholder }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface EditableSubmitTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectEditableRootContext } from './EditableRoot.vue'\n\nconst props = withDefaults(defineProps<EditableSubmitTriggerProps>(), { as: 'button' })\n\nconst context = injectEditableRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"submit\"\n    :aria-disabled=\"context.disabled.value ? '' : undefined\"\n    :data-disabled=\"context.disabled.value ? '' : undefined\"\n    :disabled=\"context.disabled.value\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :hidden=\"context.isEditing.value ? undefined : ''\"\n    @click=\"context.submit\"\n  >\n    <slot>Submit</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface EditableSubmitTriggerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectEditableRootContext } from './EditableRoot.vue'\n\nconst props = withDefaults(defineProps<EditableSubmitTriggerProps>(), { as: 'button' })\n\nconst context = injectEditableRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"submit\"\n    :aria-disabled=\"context.disabled.value ? '' : undefined\"\n    :data-disabled=\"context.disabled.value ? '' : undefined\"\n    :disabled=\"context.disabled.value\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :hidden=\"context.isEditing.value ? undefined : ''\"\n    @click=\"context.submit\"\n  >\n    <slot>Submit</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PopperArrowProps } from '@/Popper'\nimport { useForwardExpose } from '@/shared'\n\nexport interface HoverCardArrowProps extends PopperArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperArrow } from '@/Popper'\n\nconst props = withDefaults(defineProps<HoverCardArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nuseForwardExpose()\n</script>\n\n<template>\n  <PopperArrow v-bind=\"props\">\n    <slot />\n  </PopperArrow>\n</template>\n","<script lang=\"ts\">\nimport type { PopperArrowProps } from '@/Popper'\nimport { useForwardExpose } from '@/shared'\n\nexport interface HoverCardArrowProps extends PopperArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperArrow } from '@/Popper'\n\nconst props = withDefaults(defineProps<HoverCardArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nuseForwardExpose()\n</script>\n\n<template>\n  <PopperArrow v-bind=\"props\">\n    <slot />\n  </PopperArrow>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface HoverCardRootProps {\n  /** The open state of the hover card when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /** The controlled open state of the hover card. Can be binded as `v-model:open`. */\n  open?: boolean\n  /** The duration from when the mouse enters the trigger until the hover card opens. */\n  openDelay?: number\n  /** The duration from when the mouse leaves the trigger or content until the hover card closes. */\n  closeDelay?: number\n}\nexport type HoverCardRootEmits = {\n  /** Event handler called when the open state of the hover card changes. */\n  'update:open': [value: boolean]\n}\n\nexport interface HoverCardRootContext {\n  open: Ref<boolean>\n  onOpenChange: (open: boolean) => void\n  onOpen: () => void\n  onClose: () => void\n  onDismiss: () => void\n  hasSelectionRef: Ref<boolean>\n  isPointerDownOnContentRef: Ref<boolean>\n  isPointerInTransitRef: Ref<boolean>\n  triggerElement: Ref<HTMLElement | undefined>\n}\n\nexport const [injectHoverCardRootContext, provideHoverCardRootContext]\n  = createContext<HoverCardRootContext>('HoverCardRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, toRefs } from 'vue'\nimport { PopperRoot } from '@/Popper'\n\nconst props = withDefaults(defineProps<HoverCardRootProps>(), {\n  defaultOpen: false,\n  open: undefined,\n  openDelay: 700,\n  closeDelay: 300,\n})\nconst emit = defineEmits<HoverCardRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nconst { openDelay, closeDelay } = toRefs(props)\n\nuseForwardExpose()\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst openTimerRef = ref(0)\nconst closeTimerRef = ref(0)\nconst hasSelectionRef = ref(false)\nconst isPointerDownOnContentRef = ref(false)\nconst isPointerInTransitRef = ref(false)\nconst triggerElement = ref<HTMLElement>()\n\nfunction handleOpen() {\n  clearTimeout(closeTimerRef.value)\n  openTimerRef.value = window.setTimeout(() => open.value = true, openDelay.value)\n}\n\nfunction handleClose() {\n  clearTimeout(openTimerRef.value)\n  if (!hasSelectionRef.value && !isPointerDownOnContentRef.value)\n    closeTimerRef.value = window.setTimeout(() => open.value = false, closeDelay.value)\n}\n\nfunction handleDismiss() {\n  open.value = false\n}\n\nprovideHoverCardRootContext({\n  open,\n  onOpenChange(value) {\n    open.value = value\n  },\n  onOpen: handleOpen,\n  onClose: handleClose,\n  onDismiss: handleDismiss,\n  hasSelectionRef,\n  isPointerDownOnContentRef,\n  isPointerInTransitRef,\n  triggerElement,\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <slot :open=\"open\" />\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface HoverCardRootProps {\n  /** The open state of the hover card when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /** The controlled open state of the hover card. Can be binded as `v-model:open`. */\n  open?: boolean\n  /** The duration from when the mouse enters the trigger until the hover card opens. */\n  openDelay?: number\n  /** The duration from when the mouse leaves the trigger or content until the hover card closes. */\n  closeDelay?: number\n}\nexport type HoverCardRootEmits = {\n  /** Event handler called when the open state of the hover card changes. */\n  'update:open': [value: boolean]\n}\n\nexport interface HoverCardRootContext {\n  open: Ref<boolean>\n  onOpenChange: (open: boolean) => void\n  onOpen: () => void\n  onClose: () => void\n  onDismiss: () => void\n  hasSelectionRef: Ref<boolean>\n  isPointerDownOnContentRef: Ref<boolean>\n  isPointerInTransitRef: Ref<boolean>\n  triggerElement: Ref<HTMLElement | undefined>\n}\n\nexport const [injectHoverCardRootContext, provideHoverCardRootContext]\n  = createContext<HoverCardRootContext>('HoverCardRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, toRefs } from 'vue'\nimport { PopperRoot } from '@/Popper'\n\nconst props = withDefaults(defineProps<HoverCardRootProps>(), {\n  defaultOpen: false,\n  open: undefined,\n  openDelay: 700,\n  closeDelay: 300,\n})\nconst emit = defineEmits<HoverCardRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nconst { openDelay, closeDelay } = toRefs(props)\n\nuseForwardExpose()\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst openTimerRef = ref(0)\nconst closeTimerRef = ref(0)\nconst hasSelectionRef = ref(false)\nconst isPointerDownOnContentRef = ref(false)\nconst isPointerInTransitRef = ref(false)\nconst triggerElement = ref<HTMLElement>()\n\nfunction handleOpen() {\n  clearTimeout(closeTimerRef.value)\n  openTimerRef.value = window.setTimeout(() => open.value = true, openDelay.value)\n}\n\nfunction handleClose() {\n  clearTimeout(openTimerRef.value)\n  if (!hasSelectionRef.value && !isPointerDownOnContentRef.value)\n    closeTimerRef.value = window.setTimeout(() => open.value = false, closeDelay.value)\n}\n\nfunction handleDismiss() {\n  open.value = false\n}\n\nprovideHoverCardRootContext({\n  open,\n  onOpenChange(value) {\n    open.value = value\n  },\n  onOpen: handleOpen,\n  onClose: handleClose,\n  onDismiss: handleDismiss,\n  hasSelectionRef,\n  isPointerDownOnContentRef,\n  isPointerInTransitRef,\n  triggerElement,\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <slot :open=\"open\" />\n  </PopperRoot>\n</template>\n","export function excludeTouch(eventHandler: () => void) {\n  return (event: PointerEvent) => event.pointerType === 'touch' ? undefined : eventHandler()\n}\n\n/**\n * Returns a list of nodes that can be in the tab sequence.\n * @see: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker\n */\nexport function getTabbableNodes(container: HTMLElement) {\n  const nodes: HTMLElement[] = []\n  const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {\n    acceptNode: (node: any) => {\n      // `.tabIndex` is not the same as the `tabindex` attribute. It works on the\n      // runtime's understanding of tabbability, so this automatically accounts\n      // for any kind of element that could be tabbed to.\n      return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP\n    },\n  })\n  while (walker.nextNode()) nodes.push(walker.currentNode as HTMLElement)\n  return nodes\n}\n","<script lang=\"ts\">\nimport type { DismissableLayerEmits } from '@/DismissableLayer'\nimport type { PopperContentProps } from '@/Popper'\nimport { syncRef } from '@vueuse/shared'\nimport { useForwardExpose, useGraceArea } from '@/shared'\n\nexport type HoverCardContentImplEmits = DismissableLayerEmits\nexport interface HoverCardContentImplProps extends PopperContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener } from '@vueuse/core'\nimport { nextTick, onMounted, onUnmounted, ref, watchEffect } from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { PopperContent } from '@/Popper'\nimport { useForwardProps } from '..'\nimport { injectHoverCardRootContext } from './HoverCardRoot.vue'\nimport { getTabbableNodes } from './utils'\n\nconst props = defineProps<HoverCardContentImplProps>()\nconst emits = defineEmits<HoverCardContentImplEmits>()\nconst forwarded = useForwardProps(props)\n\nconst { forwardRef, currentElement: contentElement } = useForwardExpose()\nconst rootContext = injectHoverCardRootContext()\nconst { isPointerInTransit, onPointerExit } = useGraceArea(rootContext.triggerElement, contentElement)\n\nsyncRef(rootContext.isPointerInTransitRef, isPointerInTransit, { direction: 'rtl' })\n\nonPointerExit(() => {\n  rootContext.onClose()\n})\n\nconst containSelection = ref(false)\n\nlet originalBodyUserSelect: string\nwatchEffect((cleanupFn) => {\n  if (containSelection.value) {\n    const body = document.body\n\n    // Safari requires prefix\n    originalBodyUserSelect = body.style.userSelect || body.style.webkitUserSelect\n\n    body.style.userSelect = 'none'\n    body.style.webkitUserSelect = 'none'\n\n    cleanupFn(() => {\n      body.style.userSelect = originalBodyUserSelect\n      body.style.webkitUserSelect = originalBodyUserSelect\n    })\n  }\n})\n\nfunction handlePointerUp() {\n  containSelection.value = false\n  rootContext.isPointerDownOnContentRef.value = false\n\n  // Delay a frame to ensure we always access the latest selection\n  nextTick(() => {\n    const hasSelection = document.getSelection()?.toString() !== ''\n    if (hasSelection)\n      rootContext.hasSelectionRef.value = true\n  })\n}\nonMounted(() => {\n  if (contentElement.value) {\n    document.addEventListener('pointerup', handlePointerUp)\n\n    const tabbables = getTabbableNodes(contentElement.value)\n    tabbables.forEach(tabbable => tabbable.setAttribute('tabindex', '-1'))\n  }\n\n  useEventListener(window, 'scroll', (event: Event) => {\n    const target = event.target as HTMLElement\n    if (target?.contains(rootContext.triggerElement.value!))\n      rootContext.onDismiss()\n  }, { capture: true })\n})\n\nonUnmounted(() => {\n  document.removeEventListener('pointerup', handlePointerUp)\n  rootContext.hasSelectionRef.value = false\n  rootContext.isPointerDownOnContentRef.value = false\n})\n</script>\n\n<template>\n  <DismissableLayer\n    as-child\n    :disable-outside-pointer-events=\"false\"\n    @escape-key-down=\"emits('escapeKeyDown', $event)\"\n    @pointer-down-outside=\"emits('pointerDownOutside', $event)\"\n    @focus-outside.prevent=\"emits('focusOutside', $event)\"\n    @dismiss=\"rootContext.onDismiss\"\n  >\n    <PopperContent\n      v-bind=\"{ ...forwarded, ...$attrs }\"\n      :ref=\"forwardRef\"\n      :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n      :style=\"{\n        'userSelect': containSelection ? 'text' : undefined,\n        // Safari requires prefix\n        'WebkitUserSelect': containSelection ? 'text' : undefined,\n        // re-namespace exposed content custom properties\n        '--reka-hover-card-content-transform-origin': 'var(--reka-popper-transform-origin)',\n        '--reka-hover-card-content-available-width': 'var(--reka-popper-available-width)',\n        '--reka-hover-card-content-available-height': 'var(--reka-popper-available-height)',\n        '--reka-hover-card-trigger-width': 'var(--reka-popper-anchor-width)',\n        '--reka-hover-card-trigger-height': 'var(--reka-popper-anchor-height)',\n      }\"\n      @pointerdown=\"(event: PointerEvent) => {\n        // Contain selection to current layer\n        if ((event.currentTarget as HTMLElement).contains(event.target as HTMLElement)) {\n          containSelection = true\n        }\n        rootContext.hasSelectionRef.value = false;\n        rootContext.isPointerDownOnContentRef.value = true;\n      }\"\n    >\n      <slot />\n    </PopperContent>\n  </DismissableLayer>\n</template>\n","<script lang=\"ts\">\nimport type { DismissableLayerEmits } from '@/DismissableLayer'\nimport type { PopperContentProps } from '@/Popper'\nimport { syncRef } from '@vueuse/shared'\nimport { useForwardExpose, useGraceArea } from '@/shared'\n\nexport type HoverCardContentImplEmits = DismissableLayerEmits\nexport interface HoverCardContentImplProps extends PopperContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener } from '@vueuse/core'\nimport { nextTick, onMounted, onUnmounted, ref, watchEffect } from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { PopperContent } from '@/Popper'\nimport { useForwardProps } from '..'\nimport { injectHoverCardRootContext } from './HoverCardRoot.vue'\nimport { getTabbableNodes } from './utils'\n\nconst props = defineProps<HoverCardContentImplProps>()\nconst emits = defineEmits<HoverCardContentImplEmits>()\nconst forwarded = useForwardProps(props)\n\nconst { forwardRef, currentElement: contentElement } = useForwardExpose()\nconst rootContext = injectHoverCardRootContext()\nconst { isPointerInTransit, onPointerExit } = useGraceArea(rootContext.triggerElement, contentElement)\n\nsyncRef(rootContext.isPointerInTransitRef, isPointerInTransit, { direction: 'rtl' })\n\nonPointerExit(() => {\n  rootContext.onClose()\n})\n\nconst containSelection = ref(false)\n\nlet originalBodyUserSelect: string\nwatchEffect((cleanupFn) => {\n  if (containSelection.value) {\n    const body = document.body\n\n    // Safari requires prefix\n    originalBodyUserSelect = body.style.userSelect || body.style.webkitUserSelect\n\n    body.style.userSelect = 'none'\n    body.style.webkitUserSelect = 'none'\n\n    cleanupFn(() => {\n      body.style.userSelect = originalBodyUserSelect\n      body.style.webkitUserSelect = originalBodyUserSelect\n    })\n  }\n})\n\nfunction handlePointerUp() {\n  containSelection.value = false\n  rootContext.isPointerDownOnContentRef.value = false\n\n  // Delay a frame to ensure we always access the latest selection\n  nextTick(() => {\n    const hasSelection = document.getSelection()?.toString() !== ''\n    if (hasSelection)\n      rootContext.hasSelectionRef.value = true\n  })\n}\nonMounted(() => {\n  if (contentElement.value) {\n    document.addEventListener('pointerup', handlePointerUp)\n\n    const tabbables = getTabbableNodes(contentElement.value)\n    tabbables.forEach(tabbable => tabbable.setAttribute('tabindex', '-1'))\n  }\n\n  useEventListener(window, 'scroll', (event: Event) => {\n    const target = event.target as HTMLElement\n    if (target?.contains(rootContext.triggerElement.value!))\n      rootContext.onDismiss()\n  }, { capture: true })\n})\n\nonUnmounted(() => {\n  document.removeEventListener('pointerup', handlePointerUp)\n  rootContext.hasSelectionRef.value = false\n  rootContext.isPointerDownOnContentRef.value = false\n})\n</script>\n\n<template>\n  <DismissableLayer\n    as-child\n    :disable-outside-pointer-events=\"false\"\n    @escape-key-down=\"emits('escapeKeyDown', $event)\"\n    @pointer-down-outside=\"emits('pointerDownOutside', $event)\"\n    @focus-outside.prevent=\"emits('focusOutside', $event)\"\n    @dismiss=\"rootContext.onDismiss\"\n  >\n    <PopperContent\n      v-bind=\"{ ...forwarded, ...$attrs }\"\n      :ref=\"forwardRef\"\n      :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n      :style=\"{\n        'userSelect': containSelection ? 'text' : undefined,\n        // Safari requires prefix\n        'WebkitUserSelect': containSelection ? 'text' : undefined,\n        // re-namespace exposed content custom properties\n        '--reka-hover-card-content-transform-origin': 'var(--reka-popper-transform-origin)',\n        '--reka-hover-card-content-available-width': 'var(--reka-popper-available-width)',\n        '--reka-hover-card-content-available-height': 'var(--reka-popper-available-height)',\n        '--reka-hover-card-trigger-width': 'var(--reka-popper-anchor-width)',\n        '--reka-hover-card-trigger-height': 'var(--reka-popper-anchor-height)',\n      }\"\n      @pointerdown=\"(event: PointerEvent) => {\n        // Contain selection to current layer\n        if ((event.currentTarget as HTMLElement).contains(event.target as HTMLElement)) {\n          containSelection = true\n        }\n        rootContext.hasSelectionRef.value = false;\n        rootContext.isPointerDownOnContentRef.value = true;\n      }\"\n    >\n      <slot />\n    </PopperContent>\n  </DismissableLayer>\n</template>\n","<script lang=\"ts\">\nimport type { HoverCardContentImplEmits, HoverCardContentImplProps } from './HoverCardContentImpl.vue'\n\nexport type HoverCardContentEmits = HoverCardContentImplEmits\n\nexport interface HoverCardContentProps extends HoverCardContentImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\nimport HoverCardContentImpl from './HoverCardContentImpl.vue'\nimport { injectHoverCardRootContext } from './HoverCardRoot.vue'\nimport { excludeTouch } from './utils'\n\nconst props = defineProps<HoverCardContentProps>()\nconst emits = defineEmits<HoverCardContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nconst { forwardRef } = useForwardExpose()\n\nconst rootContext = injectHoverCardRootContext()\n</script>\n\n<template>\n  <Presence\n    :present=\"forceMount || rootContext.open.value\"\n  >\n    <HoverCardContentImpl\n      v-bind=\"forwarded\"\n      :ref=\"forwardRef\"\n      @pointerenter=\"excludeTouch(rootContext.onOpen)($event)\"\n    >\n      <slot />\n    </HoverCardContentImpl>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { HoverCardContentImplEmits, HoverCardContentImplProps } from './HoverCardContentImpl.vue'\n\nexport type HoverCardContentEmits = HoverCardContentImplEmits\n\nexport interface HoverCardContentProps extends HoverCardContentImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\nimport HoverCardContentImpl from './HoverCardContentImpl.vue'\nimport { injectHoverCardRootContext } from './HoverCardRoot.vue'\nimport { excludeTouch } from './utils'\n\nconst props = defineProps<HoverCardContentProps>()\nconst emits = defineEmits<HoverCardContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nconst { forwardRef } = useForwardExpose()\n\nconst rootContext = injectHoverCardRootContext()\n</script>\n\n<template>\n  <Presence\n    :present=\"forceMount || rootContext.open.value\"\n  >\n    <HoverCardContentImpl\n      v-bind=\"forwarded\"\n      :ref=\"forwardRef\"\n      @pointerenter=\"excludeTouch(rootContext.onOpen)($event)\"\n    >\n      <slot />\n    </HoverCardContentImpl>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface HoverCardPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<HoverCardPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface HoverCardPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<HoverCardPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nexport interface HoverCardTriggerProps extends PopperAnchorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport type { PopperAnchorProps } from '@/Popper'\nimport { PopperAnchor } from '@/Popper'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectHoverCardRootContext } from './HoverCardRoot.vue'\nimport { excludeTouch } from './utils'\n\nwithDefaults(defineProps<HoverCardTriggerProps>(), {\n  as: 'a',\n})\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst rootContext = injectHoverCardRootContext()\nrootContext.triggerElement = currentElement\n\nfunction handleLeave() {\n  setTimeout(() => {\n    if (!rootContext.isPointerInTransitRef.value && !rootContext.open.value) {\n      rootContext.onClose()\n    }\n  }, 0)\n}\n</script>\n\n<template>\n  <PopperAnchor\n    as-child\n    :reference=\"reference\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n      data-grace-area-trigger\n      @pointerenter=\"excludeTouch(rootContext.onOpen)($event)\"\n      @pointerleave=\"excludeTouch(handleLeave)($event)\"\n      @focus=\"rootContext.onOpen()\"\n      @blur=\"rootContext.onClose()\"\n    >\n      <slot />\n    </Primitive>\n  </PopperAnchor>\n</template>\n","<script lang=\"ts\">\nexport interface HoverCardTriggerProps extends PopperAnchorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport type { PopperAnchorProps } from '@/Popper'\nimport { PopperAnchor } from '@/Popper'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectHoverCardRootContext } from './HoverCardRoot.vue'\nimport { excludeTouch } from './utils'\n\nwithDefaults(defineProps<HoverCardTriggerProps>(), {\n  as: 'a',\n})\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst rootContext = injectHoverCardRootContext()\nrootContext.triggerElement = currentElement\n\nfunction handleLeave() {\n  setTimeout(() => {\n    if (!rootContext.isPointerInTransitRef.value && !rootContext.open.value) {\n      rootContext.onClose()\n    }\n  }, 0)\n}\n</script>\n\n<template>\n  <PopperAnchor\n    as-child\n    :reference=\"reference\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n      data-grace-area-trigger\n      @pointerenter=\"excludeTouch(rootContext.onOpen)($event)\"\n      @pointerleave=\"excludeTouch(handleLeave)($event)\"\n      @focus=\"rootContext.onOpen()\"\n      @blur=\"rootContext.onClose()\"\n    >\n      <slot />\n    </Primitive>\n  </PopperAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface LabelProps extends PrimitiveProps {\n  /** The id of the element the label is associated with. */\n  for?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<LabelProps>(), {\n  as: 'label',\n})\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    @mousedown=\"(event: MouseEvent) => {\n      // prevent text selection when double clicking label\n      if (!event.defaultPrevented && event.detail > 1) event.preventDefault();\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface LabelProps extends PrimitiveProps {\n  /** The id of the element the label is associated with. */\n  for?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<LabelProps>(), {\n  as: 'label',\n})\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    @mousedown=\"(event: MouseEvent) => {\n      // prevent text selection when double clicking label\n      if (!event.defaultPrevented && event.detail > 1) event.preventDefault();\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { MenuArrowProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface MenubarArrowProps extends MenuArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuArrow } from '@/Menu'\n\nconst props = withDefaults(defineProps<MenubarArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuArrow v-bind=\"props\">\n    <slot />\n  </MenuArrow>\n</template>\n","<script lang=\"ts\">\nimport type { MenuArrowProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface MenubarArrowProps extends MenuArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuArrow } from '@/Menu'\n\nconst props = withDefaults(defineProps<MenubarArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuArrow v-bind=\"props\">\n    <slot />\n  </MenuArrow>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuCheckboxItemEmits,\n  MenuCheckboxItemProps,\n} from '@/Menu'\n\nexport type MenubarCheckboxItemEmits = MenuCheckboxItemEmits\n\nexport interface MenubarCheckboxItemProps extends MenuCheckboxItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuCheckboxItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<MenubarCheckboxItemProps>()\nconst emits = defineEmits<MenubarCheckboxItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuCheckboxItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuCheckboxItem>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuCheckboxItemEmits,\n  MenuCheckboxItemProps,\n} from '@/Menu'\n\nexport type MenubarCheckboxItemEmits = MenuCheckboxItemEmits\n\nexport interface MenubarCheckboxItemProps extends MenuCheckboxItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuCheckboxItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<MenubarCheckboxItemProps>()\nconst emits = defineEmits<MenubarCheckboxItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuCheckboxItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuCheckboxItem>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Direction } from '../shared/types'\nimport { useCollection } from '@/Collection'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\nexport interface MenubarRootProps {\n  /** The controlled value of the menu to open. Can be used as `v-model`. */\n  modelValue?: string\n  /** The value of the menu that should be open when initially rendered. Use when you do not need to control the value state. */\n  defaultValue?: string\n  /**\n   * The reading direction of the combobox when applicable.\n   *\n   *  If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode.\n   */\n  dir?: Direction\n  /** When `true`, keyboard navigation will loop from last item to first, and vice versa. */\n  loop?: boolean\n}\nexport type MenubarRootEmits = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: boolean]\n}\n\nexport interface MenubarRootContext {\n  modelValue: Ref<string>\n  dir: Ref<Direction>\n  loop: Ref<boolean>\n  onMenuOpen: (value: string) => void\n  onMenuClose: () => void\n  onMenuToggle: (value: string) => void\n}\n\nexport const [injectMenubarRootContext, provideMenubarRootContext]\n  = createContext<MenubarRootContext>('MenubarRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusGroup } from '@/RovingFocus'\n\nconst props = withDefaults(defineProps<MenubarRootProps>(), {\n  loop: false,\n})\nconst emit = defineEmits<MenubarRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { forwardRef } = useForwardExpose()\nconst { CollectionSlot } = useCollection({ key: 'Menubar', isProvider: true })\n\nconst modelValue = useVModel(props, 'modelValue', emit, {\n  defaultValue: props.defaultValue ?? '',\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<string>\n\nconst currentTabStopId = ref<string | null>(null)\n\nconst { dir: propDir, loop } = toRefs(props)\nconst dir = useDirection(propDir)\nprovideMenubarRootContext({\n  modelValue,\n  dir,\n  loop,\n  onMenuOpen: (value) => {\n    modelValue.value = value\n    currentTabStopId.value = value\n  },\n  onMenuClose: () => {\n    modelValue.value = ''\n  },\n  onMenuToggle: (value) => {\n    modelValue.value = modelValue.value ? '' : value\n    // `openMenuOpen` and `onMenuToggle` are called exclusively so we\n    // need to update the id in either case.\n    currentTabStopId.value = value\n  },\n})\n</script>\n\n<template>\n  <CollectionSlot>\n    <RovingFocusGroup\n      v-model:current-tab-stop-id=\"currentTabStopId\"\n      orientation=\"horizontal\"\n      :loop=\"loop\"\n      :dir=\"dir\"\n      as-child\n    >\n      <Primitive\n        :ref=\"forwardRef\"\n        role=\"menubar\"\n      >\n        <slot :model-value=\"modelValue\" />\n      </Primitive>\n    </RovingFocusGroup>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Direction } from '../shared/types'\nimport { useCollection } from '@/Collection'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\nexport interface MenubarRootProps {\n  /** The controlled value of the menu to open. Can be used as `v-model`. */\n  modelValue?: string\n  /** The value of the menu that should be open when initially rendered. Use when you do not need to control the value state. */\n  defaultValue?: string\n  /**\n   * The reading direction of the combobox when applicable.\n   *\n   *  If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode.\n   */\n  dir?: Direction\n  /** When `true`, keyboard navigation will loop from last item to first, and vice versa. */\n  loop?: boolean\n}\nexport type MenubarRootEmits = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: boolean]\n}\n\nexport interface MenubarRootContext {\n  modelValue: Ref<string>\n  dir: Ref<Direction>\n  loop: Ref<boolean>\n  onMenuOpen: (value: string) => void\n  onMenuClose: () => void\n  onMenuToggle: (value: string) => void\n}\n\nexport const [injectMenubarRootContext, provideMenubarRootContext]\n  = createContext<MenubarRootContext>('MenubarRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusGroup } from '@/RovingFocus'\n\nconst props = withDefaults(defineProps<MenubarRootProps>(), {\n  loop: false,\n})\nconst emit = defineEmits<MenubarRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { forwardRef } = useForwardExpose()\nconst { CollectionSlot } = useCollection({ key: 'Menubar', isProvider: true })\n\nconst modelValue = useVModel(props, 'modelValue', emit, {\n  defaultValue: props.defaultValue ?? '',\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<string>\n\nconst currentTabStopId = ref<string | null>(null)\n\nconst { dir: propDir, loop } = toRefs(props)\nconst dir = useDirection(propDir)\nprovideMenubarRootContext({\n  modelValue,\n  dir,\n  loop,\n  onMenuOpen: (value) => {\n    modelValue.value = value\n    currentTabStopId.value = value\n  },\n  onMenuClose: () => {\n    modelValue.value = ''\n  },\n  onMenuToggle: (value) => {\n    modelValue.value = modelValue.value ? '' : value\n    // `openMenuOpen` and `onMenuToggle` are called exclusively so we\n    // need to update the id in either case.\n    currentTabStopId.value = value\n  },\n})\n</script>\n\n<template>\n  <CollectionSlot>\n    <RovingFocusGroup\n      v-model:current-tab-stop-id=\"currentTabStopId\"\n      orientation=\"horizontal\"\n      :loop=\"loop\"\n      :dir=\"dir\"\n      as-child\n    >\n      <Primitive\n        :ref=\"forwardRef\"\n        role=\"menubar\"\n      >\n        <slot :model-value=\"modelValue\" />\n      </Primitive>\n    </RovingFocusGroup>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { createContext, useForwardExpose, useId } from '@/shared'\n\nexport interface MenubarMenuProps {\n  /**\n   * A unique value that associates the item with an active value when the navigation menu is controlled.\n   *\n   * This prop is managed automatically when uncontrolled.\n   */\n  value?: string\n}\n\ntype MenubarMenuContext = {\n  value: string\n  triggerId: string\n  triggerElement: Ref<HTMLElement | undefined>\n  contentId: string\n  wasKeyboardTriggerOpenRef: Ref<boolean>\n}\n\nexport const [injectMenubarMenuContext, provideMenubarMenuContext]\n  = createContext<MenubarMenuContext>('MenubarMenu')\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, ref, watch } from 'vue'\nimport { MenuRoot } from '@/Menu'\nimport { injectMenubarRootContext } from './MenubarRoot.vue'\n\nconst props = defineProps<MenubarMenuProps>()\n\nconst value = useId(props.value)\nconst rootContext = injectMenubarRootContext()\nuseForwardExpose()\n\nconst triggerElement = ref<HTMLElement>()\nconst wasKeyboardTriggerOpenRef = ref(false)\n\nconst open = computed(() => rootContext.modelValue.value === value)\n\nwatch(open, () => {\n  if (!open.value)\n    wasKeyboardTriggerOpenRef.value = false\n})\n\nprovideMenubarMenuContext({\n  value,\n  triggerElement,\n  triggerId: value,\n  contentId: '',\n  wasKeyboardTriggerOpenRef,\n})\n</script>\n\n<template>\n  <MenuRoot\n    :open=\"open\"\n    :modal=\"false\"\n    :dir=\"rootContext.dir.value\"\n    @update:open=\"\n      (value) => {\n        // Menu only calls `@update:open` when dismissing so we\n        // want to close our MenuBar based on the same events.\n        if (!value) rootContext.onMenuClose();\n      }\n    \"\n  >\n    <slot />\n  </MenuRoot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { createContext, useForwardExpose, useId } from '@/shared'\n\nexport interface MenubarMenuProps {\n  /**\n   * A unique value that associates the item with an active value when the navigation menu is controlled.\n   *\n   * This prop is managed automatically when uncontrolled.\n   */\n  value?: string\n}\n\ntype MenubarMenuContext = {\n  value: string\n  triggerId: string\n  triggerElement: Ref<HTMLElement | undefined>\n  contentId: string\n  wasKeyboardTriggerOpenRef: Ref<boolean>\n}\n\nexport const [injectMenubarMenuContext, provideMenubarMenuContext]\n  = createContext<MenubarMenuContext>('MenubarMenu')\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, ref, watch } from 'vue'\nimport { MenuRoot } from '@/Menu'\nimport { injectMenubarRootContext } from './MenubarRoot.vue'\n\nconst props = defineProps<MenubarMenuProps>()\n\nconst value = useId(props.value)\nconst rootContext = injectMenubarRootContext()\nuseForwardExpose()\n\nconst triggerElement = ref<HTMLElement>()\nconst wasKeyboardTriggerOpenRef = ref(false)\n\nconst open = computed(() => rootContext.modelValue.value === value)\n\nwatch(open, () => {\n  if (!open.value)\n    wasKeyboardTriggerOpenRef.value = false\n})\n\nprovideMenubarMenuContext({\n  value,\n  triggerElement,\n  triggerId: value,\n  contentId: '',\n  wasKeyboardTriggerOpenRef,\n})\n</script>\n\n<template>\n  <MenuRoot\n    :open=\"open\"\n    :modal=\"false\"\n    :dir=\"rootContext.dir.value\"\n    @update:open=\"\n      (value) => {\n        // Menu only calls `@update:open` when dismissing so we\n        // want to close our MenuBar based on the same events.\n        if (!value) rootContext.onMenuClose();\n      }\n    \"\n  >\n    <slot />\n  </MenuRoot>\n</template>\n","<script lang=\"ts\">\nimport type { MenuContentEmits, MenuContentProps } from '@/Menu'\nimport { useCollection } from '@/Collection'\n\nexport type MenubarContentEmits = MenuContentEmits\n\nexport interface MenubarContentProps extends MenuContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { MenuContent } from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits, useId } from '@/shared'\nimport { wrapArray } from '@/shared/useTypeahead'\nimport { injectMenubarMenuContext } from './MenubarMenu.vue'\nimport { injectMenubarRootContext } from './MenubarRoot.vue'\n\nconst props = withDefaults(defineProps<MenubarContentProps>(), {\n  align: 'start',\n})\nconst emits = defineEmits<MenubarContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n\nconst rootContext = injectMenubarRootContext()\nconst menuContext = injectMenubarMenuContext()\n\nmenuContext.contentId ||= useId(undefined, 'reka-menubar-content')\n\nconst { getItems } = useCollection({ key: 'Menubar' })\n\nconst hasInteractedOutsideRef = ref(false)\n\nfunction handleArrowNavigation(event: KeyboardEvent) {\n  const target = event.target as HTMLElement\n  const targetIsSubTrigger = target.hasAttribute(\n    'data-reka-menubar-subtrigger',\n  )\n\n  const prevMenuKey = rootContext.dir.value === 'rtl' ? 'ArrowRight' : 'ArrowLeft'\n  const isPrevKey = prevMenuKey === event.key\n  const isNextKey = !isPrevKey\n\n  // Prevent navigation when we're opening a submenu\n  if (isNextKey && targetIsSubTrigger)\n    return\n\n  let candidateValues = getItems().filter(i => i.ref.dataset.disabled !== '').map(i => i.ref.dataset.value)\n  if (isPrevKey)\n    candidateValues.reverse()\n\n  const currentIndex = candidateValues.indexOf(menuContext.value)\n\n  candidateValues = rootContext.loop.value\n    ? wrapArray(candidateValues, currentIndex + 1)\n    : candidateValues.slice(currentIndex + 1)\n\n  const [nextValue] = candidateValues\n  if (nextValue)\n    rootContext.onMenuOpen(nextValue)\n}\n</script>\n\n<template>\n  <MenuContent\n    v-bind=\"forwarded\"\n    :id=\"menuContext.contentId\"\n    data-reka-menubar-content=\"\"\n    :aria-labelledby=\"menuContext.triggerId\"\n    :style=\"{\n      '--reka-menubar-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-menubar-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-menubar-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-menubar-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-menubar-trigger-height': 'var(--reka-popper-anchor-height)',\n    }\"\n    @close-auto-focus=\"(event) => {\n      const menubarOpen = Boolean(rootContext.modelValue.value);\n      if (!menubarOpen && !hasInteractedOutsideRef) {\n        menuContext.triggerElement.value?.focus();\n      }\n\n      hasInteractedOutsideRef = false;\n      // Always prevent auto focus because we either focus manually or want user agent focus\n      event.preventDefault();\n    }\"\n    @focus-outside=\"(event) => {\n      const target = event.target as HTMLElement;\n      const isMenubarTrigger = getItems().filter(i => i.ref.dataset.disabled !== '').some((i) => i.ref.contains(target));\n      if (isMenubarTrigger) event.preventDefault();\n    }\"\n    @interact-outside=\"\n      (event) => {\n        hasInteractedOutsideRef = true;\n      }\n    \"\n    @entry-focus=\"(event) => {\n      if (!menuContext.wasKeyboardTriggerOpenRef.value) event.preventDefault()\n    }\"\n    @keydown.arrow-right.arrow-left=\"handleArrowNavigation\"\n  >\n    <slot />\n  </MenuContent>\n</template>\n","<script lang=\"ts\">\nimport type { MenuContentEmits, MenuContentProps } from '@/Menu'\nimport { useCollection } from '@/Collection'\n\nexport type MenubarContentEmits = MenuContentEmits\n\nexport interface MenubarContentProps extends MenuContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { MenuContent } from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits, useId } from '@/shared'\nimport { wrapArray } from '@/shared/useTypeahead'\nimport { injectMenubarMenuContext } from './MenubarMenu.vue'\nimport { injectMenubarRootContext } from './MenubarRoot.vue'\n\nconst props = withDefaults(defineProps<MenubarContentProps>(), {\n  align: 'start',\n})\nconst emits = defineEmits<MenubarContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n\nconst rootContext = injectMenubarRootContext()\nconst menuContext = injectMenubarMenuContext()\n\nmenuContext.contentId ||= useId(undefined, 'reka-menubar-content')\n\nconst { getItems } = useCollection({ key: 'Menubar' })\n\nconst hasInteractedOutsideRef = ref(false)\n\nfunction handleArrowNavigation(event: KeyboardEvent) {\n  const target = event.target as HTMLElement\n  const targetIsSubTrigger = target.hasAttribute(\n    'data-reka-menubar-subtrigger',\n  )\n\n  const prevMenuKey = rootContext.dir.value === 'rtl' ? 'ArrowRight' : 'ArrowLeft'\n  const isPrevKey = prevMenuKey === event.key\n  const isNextKey = !isPrevKey\n\n  // Prevent navigation when we're opening a submenu\n  if (isNextKey && targetIsSubTrigger)\n    return\n\n  let candidateValues = getItems().filter(i => i.ref.dataset.disabled !== '').map(i => i.ref.dataset.value)\n  if (isPrevKey)\n    candidateValues.reverse()\n\n  const currentIndex = candidateValues.indexOf(menuContext.value)\n\n  candidateValues = rootContext.loop.value\n    ? wrapArray(candidateValues, currentIndex + 1)\n    : candidateValues.slice(currentIndex + 1)\n\n  const [nextValue] = candidateValues\n  if (nextValue)\n    rootContext.onMenuOpen(nextValue)\n}\n</script>\n\n<template>\n  <MenuContent\n    v-bind=\"forwarded\"\n    :id=\"menuContext.contentId\"\n    data-reka-menubar-content=\"\"\n    :aria-labelledby=\"menuContext.triggerId\"\n    :style=\"{\n      '--reka-menubar-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-menubar-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-menubar-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-menubar-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-menubar-trigger-height': 'var(--reka-popper-anchor-height)',\n    }\"\n    @close-auto-focus=\"(event) => {\n      const menubarOpen = Boolean(rootContext.modelValue.value);\n      if (!menubarOpen && !hasInteractedOutsideRef) {\n        menuContext.triggerElement.value?.focus();\n      }\n\n      hasInteractedOutsideRef = false;\n      // Always prevent auto focus because we either focus manually or want user agent focus\n      event.preventDefault();\n    }\"\n    @focus-outside=\"(event) => {\n      const target = event.target as HTMLElement;\n      const isMenubarTrigger = getItems().filter(i => i.ref.dataset.disabled !== '').some((i) => i.ref.contains(target));\n      if (isMenubarTrigger) event.preventDefault();\n    }\"\n    @interact-outside=\"\n      (event) => {\n        hasInteractedOutsideRef = true;\n      }\n    \"\n    @entry-focus=\"(event) => {\n      if (!menuContext.wasKeyboardTriggerOpenRef.value) event.preventDefault()\n    }\"\n    @keydown.arrow-right.arrow-left=\"handleArrowNavigation\"\n  >\n    <slot />\n  </MenuContent>\n</template>\n","<script lang=\"ts\">\nimport type { MenuGroupProps } from '@/Menu'\n\nexport interface MenubarGroupProps extends MenuGroupProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuGroup } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = defineProps<MenubarGroupProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuGroup v-bind=\"props\">\n    <slot />\n  </MenuGroup>\n</template>\n","<script lang=\"ts\">\nimport type { MenuGroupProps } from '@/Menu'\n\nexport interface MenubarGroupProps extends MenuGroupProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuGroup } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = defineProps<MenubarGroupProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuGroup v-bind=\"props\">\n    <slot />\n  </MenuGroup>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemEmits, MenuItemProps } from '@/Menu'\n\nexport type MenubarItemEmits = MenuItemEmits\n\nexport interface MenubarItemProps extends MenuItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<MenubarItemProps>()\nconst emits = defineEmits<MenubarItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuItem>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemEmits, MenuItemProps } from '@/Menu'\n\nexport type MenubarItemEmits = MenuItemEmits\n\nexport interface MenubarItemProps extends MenuItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuItem } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<MenubarItemProps>()\nconst emits = defineEmits<MenubarItemEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuItem v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuItem>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemIndicatorProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface MenubarItemIndicatorProps extends MenuItemIndicatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuItemIndicator } from '@/Menu'\n\nconst props = defineProps<MenubarItemIndicatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuItemIndicator v-bind=\"props\">\n    <slot />\n  </MenuItemIndicator>\n</template>\n","<script lang=\"ts\">\nimport type { MenuItemIndicatorProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface MenubarItemIndicatorProps extends MenuItemIndicatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuItemIndicator } from '@/Menu'\n\nconst props = defineProps<MenubarItemIndicatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuItemIndicator v-bind=\"props\">\n    <slot />\n  </MenuItemIndicator>\n</template>\n","<script lang=\"ts\">\nimport type { MenuLabelProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface MenubarLabelProps extends MenuLabelProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuLabel } from '@/Menu'\n\nconst props = defineProps<MenubarLabelProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuLabel v-bind=\"props\">\n    <slot />\n  </MenuLabel>\n</template>\n","<script lang=\"ts\">\nimport type { MenuLabelProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface MenubarLabelProps extends MenuLabelProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuLabel } from '@/Menu'\n\nconst props = defineProps<MenubarLabelProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuLabel v-bind=\"props\">\n    <slot />\n  </MenuLabel>\n</template>\n","<script lang=\"ts\">\nimport type { MenuPortalProps } from '@/Menu'\n\nexport interface MenubarPortalProps extends MenuPortalProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuPortal } from '@/Menu'\n\nconst props = defineProps<MenubarPortalProps>()\n</script>\n\n<template>\n  <MenuPortal v-bind=\"props\">\n    <slot />\n  </MenuPortal>\n</template>\n","<script lang=\"ts\">\nimport type { MenuPortalProps } from '@/Menu'\n\nexport interface MenubarPortalProps extends MenuPortalProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuPortal } from '@/Menu'\n\nconst props = defineProps<MenubarPortalProps>()\n</script>\n\n<template>\n  <MenuPortal v-bind=\"props\">\n    <slot />\n  </MenuPortal>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuRadioGroupEmits,\n  MenuRadioGroupProps,\n} from '@/Menu'\n\nexport type MenubarRadioGroupEmits = MenuRadioGroupEmits\n\nexport interface MenubarRadioGroupProps extends MenuRadioGroupProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuRadioGroup } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<MenubarRadioGroupProps>()\nconst emits = defineEmits<MenubarRadioGroupEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuRadioGroup v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuRadioGroup>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuRadioGroupEmits,\n  MenuRadioGroupProps,\n} from '@/Menu'\n\nexport type MenubarRadioGroupEmits = MenuRadioGroupEmits\n\nexport interface MenubarRadioGroupProps extends MenuRadioGroupProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuRadioGroup } from '@/Menu'\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\n\nconst props = defineProps<MenubarRadioGroupProps>()\nconst emits = defineEmits<MenubarRadioGroupEmits>()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuRadioGroup v-bind=\"{ ...props, ...emitsAsProps }\">\n    <slot />\n  </MenuRadioGroup>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuRadioItemEmits,\n  MenuRadioItemProps,\n} from '@/Menu'\n\nexport type MenubarRadioItemEmits = MenuRadioItemEmits\n\nexport interface MenubarRadioItemProps extends MenuRadioItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuRadioItem } from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\n\nconst props = defineProps<MenuRadioItemProps>()\nconst emits = defineEmits<MenuRadioItemEmits>()\n\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuRadioItem v-bind=\"forwarded\">\n    <slot />\n  </MenuRadioItem>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuRadioItemEmits,\n  MenuRadioItemProps,\n} from '@/Menu'\n\nexport type MenubarRadioItemEmits = MenuRadioItemEmits\n\nexport interface MenubarRadioItemProps extends MenuRadioItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuRadioItem } from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\n\nconst props = defineProps<MenuRadioItemProps>()\nconst emits = defineEmits<MenuRadioItemEmits>()\n\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuRadioItem v-bind=\"forwarded\">\n    <slot />\n  </MenuRadioItem>\n</template>\n","<script lang=\"ts\">\nimport type { MenuSeparatorProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface MenubarSeparatorProps extends MenuSeparatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSeparator } from '@/Menu'\n\nconst props = defineProps<MenubarSeparatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSeparator v-bind=\"props\">\n    <slot />\n  </MenuSeparator>\n</template>\n","<script lang=\"ts\">\nimport type { MenuSeparatorProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface MenubarSeparatorProps extends MenuSeparatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSeparator } from '@/Menu'\n\nconst props = defineProps<MenubarSeparatorProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSeparator v-bind=\"props\">\n    <slot />\n  </MenuSeparator>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { MenuSubEmits, MenuSubProps } from '@/Menu'\n\nexport type MenubarSubEmits = MenuSubEmits\nexport interface MenubarSubProps extends MenuSubProps {\n  /** The open state of the submenu when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { MenuSub } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = withDefaults(defineProps<MenubarSubProps>(), {\n  open: undefined,\n})\nconst emit = defineEmits<MenubarSubEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nuseForwardExpose()\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen ?? false,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n</script>\n\n<template>\n  <MenuSub v-model:open=\"open\">\n    <slot :open=\"open\" />\n  </MenuSub>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { MenuSubEmits, MenuSubProps } from '@/Menu'\n\nexport type MenubarSubEmits = MenuSubEmits\nexport interface MenubarSubProps extends MenuSubProps {\n  /** The open state of the submenu when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { MenuSub } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nconst props = withDefaults(defineProps<MenubarSubProps>(), {\n  open: undefined,\n})\nconst emit = defineEmits<MenubarSubEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nuseForwardExpose()\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen ?? false,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n</script>\n\n<template>\n  <MenuSub v-model:open=\"open\">\n    <slot :open=\"open\" />\n  </MenuSub>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuSubContentEmits,\n  MenuSubContentProps,\n} from '@/Menu'\nimport { useCollection } from '@/Collection'\n\nexport type MenubarSubContentEmits = MenuSubContentEmits\n\nexport interface MenubarSubContentProps extends MenuSubContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSubContent } from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\nimport { wrapArray } from '@/shared/useTypeahead'\nimport { injectMenubarMenuContext } from './MenubarMenu.vue'\nimport { injectMenubarRootContext } from './MenubarRoot.vue'\n\nconst props = defineProps<MenubarSubContentProps>()\nconst emits = defineEmits<MenubarSubContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n\nconst { getItems } = useCollection({ key: 'Menubar' })\n\nconst rootContext = injectMenubarRootContext()\nconst menuContext = injectMenubarMenuContext()\n\nfunction handleArrowNavigation(event: KeyboardEvent) {\n  const target = event.target as HTMLElement\n  const targetIsSubTrigger = target.hasAttribute(\n    'data-reka-menubar-subtrigger',\n  )\n\n  // Prevent navigation when we're opening a submenu\n  if (targetIsSubTrigger)\n    return\n\n  let candidateValues = getItems().filter(i => i.ref.dataset.disabled !== '').map(i => i.ref.dataset.value)\n  const currentIndex = candidateValues.indexOf(menuContext.value)\n\n  candidateValues = rootContext.loop.value\n    ? wrapArray(candidateValues, currentIndex + 1)\n    : candidateValues.slice(currentIndex + 1)\n\n  const [nextValue] = candidateValues\n  if (nextValue)\n    rootContext.onMenuOpen(nextValue)\n}\n</script>\n\n<template>\n  <MenuSubContent\n    v-bind=\"forwarded\"\n    data-reka-menubar-content=\"\"\n    :style=\"{\n      '--reka-menubar-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-menubar-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-menubar-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-menubar-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-menubar-trigger-height': 'var(--reka-popper-anchor-height)',\n    }\"\n    @keydown.arrow-right=\"handleArrowNavigation\"\n  >\n    <slot />\n  </MenuSubContent>\n</template>\n","<script lang=\"ts\">\nimport type {\n  MenuSubContentEmits,\n  MenuSubContentProps,\n} from '@/Menu'\nimport { useCollection } from '@/Collection'\n\nexport type MenubarSubContentEmits = MenuSubContentEmits\n\nexport interface MenubarSubContentProps extends MenuSubContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSubContent } from '@/Menu'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\nimport { wrapArray } from '@/shared/useTypeahead'\nimport { injectMenubarMenuContext } from './MenubarMenu.vue'\nimport { injectMenubarRootContext } from './MenubarRoot.vue'\n\nconst props = defineProps<MenubarSubContentProps>()\nconst emits = defineEmits<MenubarSubContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\nuseForwardExpose()\n\nconst { getItems } = useCollection({ key: 'Menubar' })\n\nconst rootContext = injectMenubarRootContext()\nconst menuContext = injectMenubarMenuContext()\n\nfunction handleArrowNavigation(event: KeyboardEvent) {\n  const target = event.target as HTMLElement\n  const targetIsSubTrigger = target.hasAttribute(\n    'data-reka-menubar-subtrigger',\n  )\n\n  // Prevent navigation when we're opening a submenu\n  if (targetIsSubTrigger)\n    return\n\n  let candidateValues = getItems().filter(i => i.ref.dataset.disabled !== '').map(i => i.ref.dataset.value)\n  const currentIndex = candidateValues.indexOf(menuContext.value)\n\n  candidateValues = rootContext.loop.value\n    ? wrapArray(candidateValues, currentIndex + 1)\n    : candidateValues.slice(currentIndex + 1)\n\n  const [nextValue] = candidateValues\n  if (nextValue)\n    rootContext.onMenuOpen(nextValue)\n}\n</script>\n\n<template>\n  <MenuSubContent\n    v-bind=\"forwarded\"\n    data-reka-menubar-content=\"\"\n    :style=\"{\n      '--reka-menubar-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-menubar-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-menubar-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-menubar-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-menubar-trigger-height': 'var(--reka-popper-anchor-height)',\n    }\"\n    @keydown.arrow-right=\"handleArrowNavigation\"\n  >\n    <slot />\n  </MenuSubContent>\n</template>\n","<script lang=\"ts\">\nimport type { MenuSubTriggerProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface MenubarSubTriggerProps extends MenuSubTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSubTrigger } from '@/Menu'\n\nconst props = defineProps<MenubarSubTriggerProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSubTrigger\n    v-bind=\"props\"\n    data-reka-menubar-subtrigger=\"\"\n  >\n    <slot />\n  </MenuSubTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { MenuSubTriggerProps } from '@/Menu'\nimport { useForwardExpose } from '@/shared'\n\nexport interface MenubarSubTriggerProps extends MenuSubTriggerProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { MenuSubTrigger } from '@/Menu'\n\nconst props = defineProps<MenubarSubTriggerProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <MenuSubTrigger\n    v-bind=\"props\"\n    data-reka-menubar-subtrigger=\"\"\n  >\n    <slot />\n  </MenuSubTrigger>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { useForwardExpose } from '@/shared'\n\nexport interface MenubarTriggerProps extends PrimitiveProps {\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted, ref } from 'vue'\nimport { MenuAnchor } from '@/Menu'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\nimport { injectMenubarMenuContext } from './MenubarMenu.vue'\nimport { injectMenubarRootContext } from './MenubarRoot.vue'\n\nwithDefaults(defineProps<MenubarTriggerProps>(), {\n  as: 'button',\n})\nconst rootContext = injectMenubarRootContext()\nconst menuContext = injectMenubarMenuContext()\n\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\nconst { CollectionItem } = useCollection({ key: 'Menubar' })\n\nconst isFocused = ref(false)\n\nconst open = computed(() => rootContext.modelValue.value === menuContext.value)\n\nonMounted(() => {\n  menuContext.triggerElement = triggerElement\n})\n</script>\n\n<template>\n  <RovingFocusItem\n    as-child\n    :focusable=\"!disabled\"\n    :tab-stop-id=\"menuContext.value\"\n  >\n    <CollectionItem>\n      <MenuAnchor as-child>\n        <Primitive\n          :id=\"menuContext.triggerId\"\n          :ref=\"forwardRef\"\n          :as=\"as\"\n          :as-child=\"asChild\"\n          :type=\"as === 'button' ? 'button' : undefined\"\n          role=\"menuitem\"\n          aria-haspopup=\"menu\"\n          :aria-expanded=\"open\"\n          :aria-controls=\"open ? menuContext.contentId : undefined\"\n          :data-highlighted=\"isFocused ? '' : undefined\"\n          :data-state=\"open ? 'open' : 'closed'\"\n          :data-disabled=\"disabled ? '' : undefined\"\n          :disabled=\"disabled\"\n          :data-value=\"menuContext.value\"\n          @pointerdown=\"(event: PointerEvent) => {\n            // only call handler if it's the left button (mousedown gets triggered by all mouse buttons)\n            // but not when the control key is pressed (avoiding MacOS right click)\n            if (!disabled && event.button === 0 && event.ctrlKey === false) {\n              rootContext.onMenuOpen(menuContext.value);\n              // prevent trigger focusing when opening\n              // this allows the content to be given focus without competition\n              if (!open) event.preventDefault();\n            }\n          }\"\n          @pointerenter=\"() => {\n            const menubarOpen = Boolean(rootContext.modelValue.value);\n            if (menubarOpen && !open) {\n              rootContext.onMenuOpen(menuContext.value);\n              triggerElement?.focus()\n            }\n          }\"\n          @keydown.enter.space.arrow-down=\"(event: KeyboardEvent) => {\n            if (disabled) return;\n            if (['Enter', ' '].includes(event.key)) rootContext.onMenuToggle(menuContext.value);\n            if (event.key === 'ArrowDown') rootContext.onMenuOpen(menuContext.value);\n            // prevent keydown from scrolling window / first focused item to execute\n            // that keydown (inadvertently closing the menu)\n            if (['Enter', ' ', 'ArrowDown'].includes(event.key)) {\n              menuContext.wasKeyboardTriggerOpenRef.value = true;\n              event.preventDefault();\n            }\n          }\"\n          @focus=\"isFocused = true\"\n          @blur=\"isFocused = false\"\n        >\n          <slot />\n        </Primitive>\n      </MenuAnchor>\n    </CollectionItem>\n  </RovingFocusItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { useForwardExpose } from '@/shared'\n\nexport interface MenubarTriggerProps extends PrimitiveProps {\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted, ref } from 'vue'\nimport { MenuAnchor } from '@/Menu'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\nimport { injectMenubarMenuContext } from './MenubarMenu.vue'\nimport { injectMenubarRootContext } from './MenubarRoot.vue'\n\nwithDefaults(defineProps<MenubarTriggerProps>(), {\n  as: 'button',\n})\nconst rootContext = injectMenubarRootContext()\nconst menuContext = injectMenubarMenuContext()\n\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\nconst { CollectionItem } = useCollection({ key: 'Menubar' })\n\nconst isFocused = ref(false)\n\nconst open = computed(() => rootContext.modelValue.value === menuContext.value)\n\nonMounted(() => {\n  menuContext.triggerElement = triggerElement\n})\n</script>\n\n<template>\n  <RovingFocusItem\n    as-child\n    :focusable=\"!disabled\"\n    :tab-stop-id=\"menuContext.value\"\n  >\n    <CollectionItem>\n      <MenuAnchor as-child>\n        <Primitive\n          :id=\"menuContext.triggerId\"\n          :ref=\"forwardRef\"\n          :as=\"as\"\n          :as-child=\"asChild\"\n          :type=\"as === 'button' ? 'button' : undefined\"\n          role=\"menuitem\"\n          aria-haspopup=\"menu\"\n          :aria-expanded=\"open\"\n          :aria-controls=\"open ? menuContext.contentId : undefined\"\n          :data-highlighted=\"isFocused ? '' : undefined\"\n          :data-state=\"open ? 'open' : 'closed'\"\n          :data-disabled=\"disabled ? '' : undefined\"\n          :disabled=\"disabled\"\n          :data-value=\"menuContext.value\"\n          @pointerdown=\"(event: PointerEvent) => {\n            // only call handler if it's the left button (mousedown gets triggered by all mouse buttons)\n            // but not when the control key is pressed (avoiding MacOS right click)\n            if (!disabled && event.button === 0 && event.ctrlKey === false) {\n              rootContext.onMenuOpen(menuContext.value);\n              // prevent trigger focusing when opening\n              // this allows the content to be given focus without competition\n              if (!open) event.preventDefault();\n            }\n          }\"\n          @pointerenter=\"() => {\n            const menubarOpen = Boolean(rootContext.modelValue.value);\n            if (menubarOpen && !open) {\n              rootContext.onMenuOpen(menuContext.value);\n              triggerElement?.focus()\n            }\n          }\"\n          @keydown.enter.space.arrow-down=\"(event: KeyboardEvent) => {\n            if (disabled) return;\n            if (['Enter', ' '].includes(event.key)) rootContext.onMenuToggle(menuContext.value);\n            if (event.key === 'ArrowDown') rootContext.onMenuOpen(menuContext.value);\n            // prevent keydown from scrolling window / first focused item to execute\n            // that keydown (inadvertently closing the menu)\n            if (['Enter', ' ', 'ArrowDown'].includes(event.key)) {\n              menuContext.wasKeyboardTriggerOpenRef.value = true;\n              event.preventDefault();\n            }\n          }\"\n          @focus=\"isFocused = true\"\n          @blur=\"isFocused = false\"\n        >\n          <slot />\n        </Primitive>\n      </MenuAnchor>\n    </CollectionItem>\n  </RovingFocusItem>\n</template>\n","import type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher } from '@/date'\nimport type { DateFormatterOptions } from '@/shared/useDateFormatter'\nimport { endOfMonth } from '@internationalized/date'\nimport { computed, ref, watch } from 'vue'\nimport { createMonthGrid, isAfter, isBefore, isSameYearMonth, toDate } from '@/date'\nimport { useDateFormatter } from '@/shared'\n\nexport type UseMonthPickerProps = {\n  locale: Ref<string>\n  placeholder: Ref<DateValue>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  disabled: Ref<boolean>\n  isMonthDisabled?: Matcher | Ref<Matcher | undefined>\n  isMonthUnavailable?: Matcher | Ref<Matcher | undefined>\n  calendarLabel: Ref<string | undefined>\n  nextPage: Ref<((placeholder: DateValue) => DateValue) | undefined>\n  prevPage: Ref<((placeholder: DateValue) => DateValue) | undefined>\n}\n\nexport type UseMonthPickerStateProps = {\n  isMonthDisabled: Matcher\n  isMonthUnavailable: Matcher\n  date: Ref<DateValue | DateValue[] | undefined>\n}\n\nexport function useMonthPickerState(props: UseMonthPickerStateProps) {\n  function isMonthSelected(dateObj: DateValue) {\n    if (Array.isArray(props.date.value))\n      return props.date.value.some(d => isSameYearMonth(d, dateObj))\n    else if (!props.date.value)\n      return false\n    else\n      return isSameYearMonth(props.date.value, dateObj)\n  }\n\n  const isInvalid = computed(() => {\n    if (Array.isArray(props.date.value)) {\n      if (!props.date.value.length)\n        return false\n      for (const dateObj of props.date.value) {\n        if (props.isMonthDisabled?.(dateObj))\n          return true\n        if (props.isMonthUnavailable?.(dateObj))\n          return true\n      }\n    }\n    else {\n      if (!props.date.value)\n        return false\n      if (props.isMonthDisabled?.(props.date.value))\n        return true\n      if (props.isMonthUnavailable?.(props.date.value))\n        return true\n    }\n    return false\n  })\n\n  return { isMonthSelected, isInvalid }\n}\n\nexport function useMonthPicker(props: UseMonthPickerProps) {\n  const formatter = useDateFormatter(props.locale.value)\n\n  const resolveMatcher = (matcher?: Matcher | Ref<Matcher | undefined>) =>\n    typeof matcher === 'function' ? matcher : matcher?.value\n\n  const headingFormatOptions = computed(() => {\n    const options: DateFormatterOptions = {\n      calendar: props.placeholder.value.calendar.identifier,\n    }\n\n    if (props.placeholder.value.calendar.identifier === 'gregory' && props.placeholder.value.era === 'BC')\n      options.era = 'short'\n\n    return options\n  })\n\n  const grid = ref<Grid<DateValue>>(createMonthGrid({ dateObj: props.placeholder.value })) as Ref<Grid<DateValue>>\n\n  function isMonthDisabled(dateObj: DateValue) {\n    if (resolveMatcher(props.isMonthDisabled)?.(dateObj) || props.disabled.value)\n      return true\n    if (props.maxValue.value && isAfter(dateObj.set({ day: 1 }), props.maxValue.value))\n      return true\n    if (props.minValue.value && isBefore(endOfMonth(dateObj), props.minValue.value))\n      return true\n    return false\n  }\n\n  const isMonthUnavailable = (date: DateValue) => {\n    if (resolveMatcher(props.isMonthUnavailable)?.(date))\n      return true\n    return false\n  }\n\n  const isNextButtonDisabled = (nextPageFunc?: (date: DateValue) => DateValue) => {\n    if (!props.maxValue.value)\n      return false\n    if (props.disabled.value)\n      return true\n\n    const currentDate = grid.value.value\n    if (nextPageFunc || props.nextPage.value) {\n      const nextDate = (nextPageFunc || props.nextPage.value)!(currentDate)\n      return isAfter(nextDate.set({ month: 1, day: 1 }), props.maxValue.value)\n    }\n\n    const nextYear = currentDate.add({ years: 1 }).set({ month: 1, day: 1 })\n    return isAfter(nextYear, props.maxValue.value)\n  }\n\n  const isPrevButtonDisabled = (prevPageFunc?: (date: DateValue) => DateValue) => {\n    if (!props.minValue.value)\n      return false\n    if (props.disabled.value)\n      return true\n\n    const currentDate = grid.value.value\n    if (prevPageFunc || props.prevPage.value) {\n      const prevDate = (prevPageFunc || props.prevPage.value)!(currentDate)\n      return isBefore(endOfMonth(prevDate.set({ month: 12 })), props.minValue.value)\n    }\n\n    const prevYear = currentDate.subtract({ years: 1 }).set({ month: 12, day: 31 })\n    return isBefore(prevYear, props.minValue.value)\n  }\n\n  const nextPage = (nextPageFunc?: (date: DateValue) => DateValue) => {\n    const currentDate = grid.value.value\n\n    if (nextPageFunc || props.nextPage.value) {\n      const newDate = (nextPageFunc || props.nextPage.value)!(currentDate)\n      grid.value = createMonthGrid({ dateObj: newDate })\n      props.placeholder.value = newDate.set({ month: props.placeholder.value.month, day: props.placeholder.value.day })\n      return\n    }\n\n    const newDate = currentDate.add({ years: 1 })\n    grid.value = createMonthGrid({ dateObj: newDate })\n    props.placeholder.value = newDate.set({ month: props.placeholder.value.month, day: props.placeholder.value.day })\n  }\n\n  const prevPage = (prevPageFunc?: (date: DateValue) => DateValue) => {\n    const currentDate = grid.value.value\n\n    if (prevPageFunc || props.prevPage.value) {\n      const newDate = (prevPageFunc || props.prevPage.value)!(currentDate)\n      grid.value = createMonthGrid({ dateObj: newDate })\n      props.placeholder.value = newDate.set({ month: props.placeholder.value.month, day: props.placeholder.value.day })\n      return\n    }\n\n    const newDate = currentDate.subtract({ years: 1 })\n    grid.value = createMonthGrid({ dateObj: newDate })\n    props.placeholder.value = newDate.set({ month: props.placeholder.value.month, day: props.placeholder.value.day })\n  }\n\n  watch(props.placeholder, (value) => {\n    if (value.year === grid.value.value.year)\n      return\n    grid.value = createMonthGrid({ dateObj: value })\n  })\n\n  watch(props.locale, () => {\n    formatter.setLocale(props.locale.value)\n    grid.value = createMonthGrid({ dateObj: props.placeholder.value })\n  })\n\n  const headingValue = computed(() => {\n    if (props.locale.value !== formatter.getLocale())\n      formatter.setLocale(props.locale.value)\n\n    return formatter.fullYear(toDate(grid.value.value), headingFormatOptions.value)\n  })\n\n  const fullCalendarLabel = computed(() => `${props.calendarLabel.value ?? 'Month Picker'}, ${headingValue.value}`)\n\n  return {\n    isMonthDisabled,\n    isMonthUnavailable,\n    isNextButtonDisabled,\n    isPrevButtonDisabled,\n    grid,\n    formatter,\n    nextPage,\n    prevPage,\n    headingValue,\n    fullCalendarLabel,\n  }\n}\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { Direction } from '@/shared/types'\nimport { isSameYearMonth } from '@/date'\nimport { createContext, useDirection, useId, useLocale } from '@/shared'\nimport { getDefaultDate, handleCalendarInitialFocus } from '@/shared/date'\nimport { useMonthPicker, useMonthPickerState } from './useMonthPicker'\n\ntype MonthPickerRootContext = {\n  locale: Ref<string>\n  modelValue: Ref<DateValue | DateValue[] | undefined>\n  placeholder: Ref<DateValue>\n  multiple: Ref<boolean>\n  preventDeselect: Ref<boolean>\n  grid: Ref<Grid<DateValue>>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  initialFocus: Ref<boolean>\n  onMonthChange: (date: DateValue) => void\n  onPlaceholderChange: (date: DateValue) => void\n  fullCalendarLabel: Ref<string>\n  parentElement: Ref<HTMLElement | undefined>\n  headingValue: Ref<string>\n  headingId: string\n  isInvalid: Ref<boolean>\n  isMonthDisabled: Matcher\n  isMonthSelected: Matcher\n  isMonthUnavailable?: Matcher\n  prevPage: (prevPageFunc?: (date: DateValue) => DateValue) => void\n  nextPage: (nextPageFunc?: (date: DateValue) => DateValue) => void\n  isNextButtonDisabled: (nextPageFunc?: (date: DateValue) => DateValue) => boolean\n  isPrevButtonDisabled: (prevPageFunc?: (date: DateValue) => DateValue) => boolean\n  formatter: Formatter\n  dir: Ref<Direction>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n}\n\nexport interface MonthPickerRootProps extends PrimitiveProps {\n  /** The default value for the month picker */\n  defaultValue?: DateValue\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The placeholder date, which is used to determine what year to display when no date is selected */\n  placeholder?: DateValue\n  /** Whether or not to prevent the user from deselecting a date without selecting another date first */\n  preventDeselect?: boolean\n  /** The accessible label for the month picker */\n  calendarLabel?: string\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether the month picker is disabled */\n  disabled?: boolean\n  /** Whether the month picker is readonly */\n  readonly?: boolean\n  /** If true, the month picker will focus the selected month, today, or the first month of the year on mount */\n  initialFocus?: boolean\n  /** A function that returns whether or not a month is disabled */\n  isMonthDisabled?: Matcher\n  /** A function that returns whether or not a month is unavailable */\n  isMonthUnavailable?: Matcher\n  /** The reading direction of the calendar when applicable. If omitted, inherits globally from `ConfigProvider` or assumes LTR. */\n  dir?: Direction\n  /** A function that returns the next page of the month picker. Receives the current placeholder as an argument. */\n  nextPage?: (placeholder: DateValue) => DateValue\n  /** A function that returns the previous page of the month picker. Receives the current placeholder as an argument. */\n  prevPage?: (placeholder: DateValue) => DateValue\n  /** The controlled selected month value of the month picker. Can be bound as `v-model`. */\n  modelValue?: DateValue | DateValue[] | null\n  /** Whether multiple months can be selected */\n  multiple?: boolean\n}\n\nexport type MonthPickerRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateValue | DateValue[] | undefined]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n}\n\nexport const [injectMonthPickerRootContext, provideMonthPickerRootContext]\n  = createContext<MonthPickerRootContext>('MonthPickerRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { onMounted, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthPickerRootProps>(), {\n  defaultValue: undefined,\n  as: 'div',\n  preventDeselect: false,\n  multiple: false,\n  disabled: false,\n  readonly: false,\n  initialFocus: false,\n  placeholder: undefined,\n  isMonthDisabled: undefined,\n  isMonthUnavailable: undefined,\n})\nconst emits = defineEmits<MonthPickerRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the placeholder */\n    date: DateValue\n    /** The grid of months */\n    grid: Grid<DateValue>\n    /** The month picker locale */\n    locale: string\n    /** The current selected value */\n    modelValue: DateValue | DateValue[] | undefined\n  }) => any\n}>()\n\nconst {\n  disabled,\n  readonly,\n  initialFocus,\n  multiple,\n  minValue,\n  maxValue,\n  preventDeselect,\n  isMonthDisabled: propsIsMonthDisabled,\n  isMonthUnavailable: propsIsMonthUnavailable,\n  calendarLabel,\n  defaultValue,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n  dir: propDir,\n  locale: propLocale,\n} = toRefs(props)\n\nconst { primitiveElement, currentElement: parentElement } = usePrimitiveElement()\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\nconst headingId = useId(undefined, 'reka-month-picker-heading')\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateValue | DateValue[] | undefined>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: modelValue.value,\n  locale: props.locale,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nfunction onPlaceholderChange(value: DateValue) {\n  placeholder.value = value.copy()\n}\n\nconst {\n  fullCalendarLabel,\n  headingValue,\n  isMonthDisabled,\n  isMonthUnavailable,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  nextPage,\n  prevPage,\n  formatter,\n  grid,\n} = useMonthPicker({\n  locale,\n  placeholder,\n  minValue,\n  maxValue,\n  disabled,\n  isMonthDisabled: propsIsMonthDisabled,\n  isMonthUnavailable: propsIsMonthUnavailable,\n  calendarLabel,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n})\n\nconst { isInvalid, isMonthSelected } = useMonthPickerState({\n  date: modelValue,\n  isMonthDisabled,\n  isMonthUnavailable,\n})\n\nwatch(modelValue, (_modelValue) => {\n  if (Array.isArray(_modelValue) && _modelValue.length) {\n    const lastValue = _modelValue.at(-1)\n    if (lastValue && !isSameYearMonth(placeholder.value, lastValue))\n      onPlaceholderChange(lastValue)\n  }\n  else if (!Array.isArray(_modelValue) && _modelValue && !isSameYearMonth(placeholder.value, _modelValue)) {\n    onPlaceholderChange(_modelValue)\n  }\n})\n\nfunction resolveMonthValue(value: DateValue, reference?: DateValue) {\n  if (!reference)\n    return value.copy()\n  return value.copy().set({ day: reference.day })\n}\n\nfunction onMonthChange(value: DateValue) {\n  if (!multiple.value) {\n    if (!modelValue.value) {\n      modelValue.value = resolveMonthValue(value, placeholder.value)\n      return\n    }\n\n    if (!preventDeselect.value && isSameYearMonth(modelValue.value as DateValue, value)) {\n      placeholder.value = resolveMonthValue(value, modelValue.value as DateValue)\n      modelValue.value = undefined\n    }\n    else {\n      modelValue.value = resolveMonthValue(value, modelValue.value as DateValue)\n    }\n  }\n  else if (!modelValue.value) {\n    modelValue.value = [resolveMonthValue(value, placeholder.value)]\n  }\n  else {\n    const modelValueArray = Array.isArray(modelValue.value)\n      ? modelValue.value\n      : [modelValue.value]\n\n    const index = modelValueArray.findIndex(date => isSameYearMonth(date, value))\n    if (index === -1) {\n      modelValue.value = [...modelValueArray, resolveMonthValue(value, placeholder.value)]\n    }\n    else if (!preventDeselect.value) {\n      const next = modelValueArray.filter(date => !isSameYearMonth(date, value))\n      if (!next.length) {\n        placeholder.value = resolveMonthValue(value, modelValueArray[index])\n        modelValue.value = undefined\n        return\n      }\n      modelValue.value = next.map(date => date.copy())\n    }\n  }\n}\n\nonMounted(() => {\n  if (initialFocus.value)\n    handleCalendarInitialFocus(parentElement.value)\n})\n\nprovideMonthPickerRootContext({\n  isMonthUnavailable,\n  dir,\n  isMonthDisabled,\n  locale,\n  formatter,\n  modelValue,\n  placeholder,\n  disabled,\n  initialFocus,\n  grid,\n  multiple,\n  readonly,\n  preventDeselect,\n  fullCalendarLabel,\n  headingValue,\n  headingId,\n  isInvalid,\n  isMonthSelected,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  nextPage,\n  prevPage,\n  parentElement,\n  onPlaceholderChange,\n  onMonthChange,\n  minValue,\n  maxValue,\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"fullCalendarLabel\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n  >\n    <slot\n      :date=\"placeholder\"\n      :grid=\"grid\"\n      :locale=\"locale\"\n      :model-value=\"modelValue\"\n    />\n    <div\n      style=\"border: 0px; clip: rect(0px, 0px, 0px, 0px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; white-space: nowrap; width: 1px;\"\n    >\n      <div\n        role=\"heading\"\n        aria-level=\"2\"\n      >\n        {{ fullCalendarLabel }}\n      </div>\n    </div>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { Direction } from '@/shared/types'\nimport { isSameYearMonth } from '@/date'\nimport { createContext, useDirection, useId, useLocale } from '@/shared'\nimport { getDefaultDate, handleCalendarInitialFocus } from '@/shared/date'\nimport { useMonthPicker, useMonthPickerState } from './useMonthPicker'\n\ntype MonthPickerRootContext = {\n  locale: Ref<string>\n  modelValue: Ref<DateValue | DateValue[] | undefined>\n  placeholder: Ref<DateValue>\n  multiple: Ref<boolean>\n  preventDeselect: Ref<boolean>\n  grid: Ref<Grid<DateValue>>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  initialFocus: Ref<boolean>\n  onMonthChange: (date: DateValue) => void\n  onPlaceholderChange: (date: DateValue) => void\n  fullCalendarLabel: Ref<string>\n  parentElement: Ref<HTMLElement | undefined>\n  headingValue: Ref<string>\n  headingId: string\n  isInvalid: Ref<boolean>\n  isMonthDisabled: Matcher\n  isMonthSelected: Matcher\n  isMonthUnavailable?: Matcher\n  prevPage: (prevPageFunc?: (date: DateValue) => DateValue) => void\n  nextPage: (nextPageFunc?: (date: DateValue) => DateValue) => void\n  isNextButtonDisabled: (nextPageFunc?: (date: DateValue) => DateValue) => boolean\n  isPrevButtonDisabled: (prevPageFunc?: (date: DateValue) => DateValue) => boolean\n  formatter: Formatter\n  dir: Ref<Direction>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n}\n\nexport interface MonthPickerRootProps extends PrimitiveProps {\n  /** The default value for the month picker */\n  defaultValue?: DateValue\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The placeholder date, which is used to determine what year to display when no date is selected */\n  placeholder?: DateValue\n  /** Whether or not to prevent the user from deselecting a date without selecting another date first */\n  preventDeselect?: boolean\n  /** The accessible label for the month picker */\n  calendarLabel?: string\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether the month picker is disabled */\n  disabled?: boolean\n  /** Whether the month picker is readonly */\n  readonly?: boolean\n  /** If true, the month picker will focus the selected month, today, or the first month of the year on mount */\n  initialFocus?: boolean\n  /** A function that returns whether or not a month is disabled */\n  isMonthDisabled?: Matcher\n  /** A function that returns whether or not a month is unavailable */\n  isMonthUnavailable?: Matcher\n  /** The reading direction of the calendar when applicable. If omitted, inherits globally from `ConfigProvider` or assumes LTR. */\n  dir?: Direction\n  /** A function that returns the next page of the month picker. Receives the current placeholder as an argument. */\n  nextPage?: (placeholder: DateValue) => DateValue\n  /** A function that returns the previous page of the month picker. Receives the current placeholder as an argument. */\n  prevPage?: (placeholder: DateValue) => DateValue\n  /** The controlled selected month value of the month picker. Can be bound as `v-model`. */\n  modelValue?: DateValue | DateValue[] | null\n  /** Whether multiple months can be selected */\n  multiple?: boolean\n}\n\nexport type MonthPickerRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateValue | DateValue[] | undefined]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n}\n\nexport const [injectMonthPickerRootContext, provideMonthPickerRootContext]\n  = createContext<MonthPickerRootContext>('MonthPickerRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { onMounted, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthPickerRootProps>(), {\n  defaultValue: undefined,\n  as: 'div',\n  preventDeselect: false,\n  multiple: false,\n  disabled: false,\n  readonly: false,\n  initialFocus: false,\n  placeholder: undefined,\n  isMonthDisabled: undefined,\n  isMonthUnavailable: undefined,\n})\nconst emits = defineEmits<MonthPickerRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the placeholder */\n    date: DateValue\n    /** The grid of months */\n    grid: Grid<DateValue>\n    /** The month picker locale */\n    locale: string\n    /** The current selected value */\n    modelValue: DateValue | DateValue[] | undefined\n  }) => any\n}>()\n\nconst {\n  disabled,\n  readonly,\n  initialFocus,\n  multiple,\n  minValue,\n  maxValue,\n  preventDeselect,\n  isMonthDisabled: propsIsMonthDisabled,\n  isMonthUnavailable: propsIsMonthUnavailable,\n  calendarLabel,\n  defaultValue,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n  dir: propDir,\n  locale: propLocale,\n} = toRefs(props)\n\nconst { primitiveElement, currentElement: parentElement } = usePrimitiveElement()\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\nconst headingId = useId(undefined, 'reka-month-picker-heading')\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateValue | DateValue[] | undefined>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: modelValue.value,\n  locale: props.locale,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nfunction onPlaceholderChange(value: DateValue) {\n  placeholder.value = value.copy()\n}\n\nconst {\n  fullCalendarLabel,\n  headingValue,\n  isMonthDisabled,\n  isMonthUnavailable,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  nextPage,\n  prevPage,\n  formatter,\n  grid,\n} = useMonthPicker({\n  locale,\n  placeholder,\n  minValue,\n  maxValue,\n  disabled,\n  isMonthDisabled: propsIsMonthDisabled,\n  isMonthUnavailable: propsIsMonthUnavailable,\n  calendarLabel,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n})\n\nconst { isInvalid, isMonthSelected } = useMonthPickerState({\n  date: modelValue,\n  isMonthDisabled,\n  isMonthUnavailable,\n})\n\nwatch(modelValue, (_modelValue) => {\n  if (Array.isArray(_modelValue) && _modelValue.length) {\n    const lastValue = _modelValue.at(-1)\n    if (lastValue && !isSameYearMonth(placeholder.value, lastValue))\n      onPlaceholderChange(lastValue)\n  }\n  else if (!Array.isArray(_modelValue) && _modelValue && !isSameYearMonth(placeholder.value, _modelValue)) {\n    onPlaceholderChange(_modelValue)\n  }\n})\n\nfunction resolveMonthValue(value: DateValue, reference?: DateValue) {\n  if (!reference)\n    return value.copy()\n  return value.copy().set({ day: reference.day })\n}\n\nfunction onMonthChange(value: DateValue) {\n  if (!multiple.value) {\n    if (!modelValue.value) {\n      modelValue.value = resolveMonthValue(value, placeholder.value)\n      return\n    }\n\n    if (!preventDeselect.value && isSameYearMonth(modelValue.value as DateValue, value)) {\n      placeholder.value = resolveMonthValue(value, modelValue.value as DateValue)\n      modelValue.value = undefined\n    }\n    else {\n      modelValue.value = resolveMonthValue(value, modelValue.value as DateValue)\n    }\n  }\n  else if (!modelValue.value) {\n    modelValue.value = [resolveMonthValue(value, placeholder.value)]\n  }\n  else {\n    const modelValueArray = Array.isArray(modelValue.value)\n      ? modelValue.value\n      : [modelValue.value]\n\n    const index = modelValueArray.findIndex(date => isSameYearMonth(date, value))\n    if (index === -1) {\n      modelValue.value = [...modelValueArray, resolveMonthValue(value, placeholder.value)]\n    }\n    else if (!preventDeselect.value) {\n      const next = modelValueArray.filter(date => !isSameYearMonth(date, value))\n      if (!next.length) {\n        placeholder.value = resolveMonthValue(value, modelValueArray[index])\n        modelValue.value = undefined\n        return\n      }\n      modelValue.value = next.map(date => date.copy())\n    }\n  }\n}\n\nonMounted(() => {\n  if (initialFocus.value)\n    handleCalendarInitialFocus(parentElement.value)\n})\n\nprovideMonthPickerRootContext({\n  isMonthUnavailable,\n  dir,\n  isMonthDisabled,\n  locale,\n  formatter,\n  modelValue,\n  placeholder,\n  disabled,\n  initialFocus,\n  grid,\n  multiple,\n  readonly,\n  preventDeselect,\n  fullCalendarLabel,\n  headingValue,\n  headingId,\n  isInvalid,\n  isMonthSelected,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  nextPage,\n  prevPage,\n  parentElement,\n  onPlaceholderChange,\n  onMonthChange,\n  minValue,\n  maxValue,\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"fullCalendarLabel\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n  >\n    <slot\n      :date=\"placeholder\"\n      :grid=\"grid\"\n      :locale=\"locale\"\n      :model-value=\"modelValue\"\n    />\n    <div\n      style=\"border: 0px; clip: rect(0px, 0px, 0px, 0px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; white-space: nowrap; width: 1px;\"\n    >\n      <div\n        role=\"heading\"\n        aria-level=\"2\"\n      >\n        {{ fullCalendarLabel }}\n      </div>\n    </div>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerCellProps extends PrimitiveProps {\n  /** The date value for the cell */\n  date: DateValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectMonthPickerRootContext } from './MonthPickerRoot.vue'\n\nwithDefaults(defineProps<MonthPickerCellProps>(), { as: 'td' })\nconst rootContext = injectMonthPickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"gridcell\"\n    :aria-selected=\"rootContext.isMonthSelected(date) ? true : undefined\"\n    :aria-disabled=\"rootContext.isMonthDisabled(date) || rootContext.isMonthUnavailable?.(date)\"\n    :data-disabled=\"rootContext.isMonthDisabled(date) ? '' : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerCellProps extends PrimitiveProps {\n  /** The date value for the cell */\n  date: DateValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectMonthPickerRootContext } from './MonthPickerRoot.vue'\n\nwithDefaults(defineProps<MonthPickerCellProps>(), { as: 'td' })\nconst rootContext = injectMonthPickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"gridcell\"\n    :aria-selected=\"rootContext.isMonthSelected(date) ? true : undefined\"\n    :aria-disabled=\"rootContext.isMonthDisabled(date) || rootContext.isMonthUnavailable?.(date)\"\n    :data-disabled=\"rootContext.isMonthDisabled(date) ? '' : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { endOfMonth, getLocalTimeZone, toCalendar, today } from '@internationalized/date'\nimport { computed, nextTick } from 'vue'\nimport { isSameYearMonth, toDate } from '@/date'\nimport { useKbd } from '@/shared'\n\nexport interface MonthPickerCellTriggerProps extends PrimitiveProps {\n  /** The date value provided to the cell trigger */\n  month: DateValue\n}\n\nexport interface MonthPickerCellTriggerSlot {\n  default?: (props: {\n    /** Current month value (short name) */\n    monthValue: string\n    /** Current disable state */\n    disabled: boolean\n    /** Current selected state */\n    selected: boolean\n    /** Current month/year is today state */\n    today: boolean\n    /** Current unavailable state */\n    unavailable: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectMonthPickerRootContext } from './MonthPickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthPickerCellTriggerProps>(), { as: 'div' })\n\ndefineSlots<MonthPickerCellTriggerSlot>()\n\nconst kbd = useKbd()\nconst rootContext = injectMonthPickerRootContext()\n\nconst { primitiveElement } = usePrimitiveElement()\n\nconst shortMonthValue = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.custom(toDate(props.month), { month: 'short' })\n})\n\nconst labelText = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.custom(toDate(props.month), {\n    month: 'long',\n    year: 'numeric',\n  })\n})\n\nconst isUnavailable = computed(() => rootContext.isMonthUnavailable?.(props.month) ?? false)\n\nconst isCurrentMonth = computed(() => {\n  const todayDate = toCalendar(today(getLocalTimeZone()), props.month.calendar)\n  return isSameYearMonth(props.month, todayDate)\n})\n\nconst isDisabled = computed(() => rootContext.isMonthDisabled(props.month))\n\nconst isFocusedMonth = computed(() => {\n  return !rootContext.disabled.value && isSameYearMonth(props.month, rootContext.placeholder.value)\n})\n\nconst isSelectedMonth = computed(() => rootContext.isMonthSelected(props.month))\n\nfunction changeMonth(date: DateValue) {\n  if (rootContext.readonly.value)\n    return\n  if (rootContext.isMonthDisabled(date) || rootContext.isMonthUnavailable?.(date))\n    return\n\n  rootContext.onMonthChange(date)\n}\n\nfunction handleClick() {\n  if (isDisabled.value)\n    return\n  changeMonth(props.month)\n}\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  if (isDisabled.value)\n    return\n  e.preventDefault()\n  e.stopPropagation()\n  const parentElement = rootContext.parentElement.value!\n  const sign = rootContext.dir.value === 'rtl' ? -1 : 1\n\n  switch (e.code) {\n    case kbd.ARROW_RIGHT:\n      shiftFocus(props.month, sign)\n      break\n    case kbd.ARROW_LEFT:\n      shiftFocus(props.month, -sign)\n      break\n    case kbd.ARROW_UP:\n      shiftFocus(props.month, -4)\n      break\n    case kbd.ARROW_DOWN:\n      shiftFocus(props.month, 4)\n      break\n    case kbd.PAGE_UP:\n      shiftFocusYear(-1)\n      break\n    case kbd.PAGE_DOWN:\n      shiftFocusYear(1)\n      break\n    case kbd.ENTER:\n    case kbd.SPACE_CODE:\n      changeMonth(props.month)\n  }\n\n  function shiftFocus(currentMonth: DateValue, add: number, depth = 0) {\n    if (depth > 48)\n      return\n    const candidateMonthValue = currentMonth.add({ months: add })\n\n    if ((rootContext.minValue.value && endOfMonth(candidateMonthValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && candidateMonthValue.set({ day: 1 }).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    const candidateMonth = parentElement.querySelector<HTMLElement>(`[data-value='${candidateMonthValue.toString()}']`)\n\n    if (!candidateMonth) {\n      if (add > 0) {\n        if (rootContext.isNextButtonDisabled())\n          return\n        rootContext.nextPage()\n      }\n      else {\n        if (rootContext.isPrevButtonDisabled())\n          return\n        rootContext.prevPage()\n      }\n      nextTick(() => {\n        shiftFocus(currentMonth, add, depth + 1)\n      })\n      return\n    }\n\n    if (candidateMonth && candidateMonth.hasAttribute('data-disabled'))\n      return shiftFocus(candidateMonthValue, add, depth + 1)\n\n    rootContext.onPlaceholderChange(candidateMonthValue)\n    candidateMonth?.focus()\n  }\n\n  function shiftFocusYear(years: number) {\n    const candidateMonthValue = props.month.add({ years })\n\n    if ((rootContext.minValue.value && endOfMonth(candidateMonthValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && candidateMonthValue.set({ day: 1 }).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    if (years > 0) {\n      if (rootContext.isNextButtonDisabled())\n        return\n      rootContext.nextPage()\n    }\n    else {\n      if (rootContext.isPrevButtonDisabled())\n        return\n      rootContext.prevPage()\n    }\n\n    nextTick(() => {\n      const candidateMonth = parentElement.querySelector<HTMLElement>(`[data-value='${candidateMonthValue.toString()}']`)\n      if (candidateMonth && !candidateMonth.hasAttribute('data-disabled')) {\n        rootContext.onPlaceholderChange(candidateMonthValue)\n        candidateMonth?.focus()\n      }\n    })\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    role=\"button\"\n    :aria-label=\"labelText\"\n    data-reka-month-picker-cell-trigger\n    :aria-disabled=\"isDisabled || isUnavailable ? true : undefined\"\n    :data-selected=\"isSelectedMonth ? true : undefined\"\n    :data-value=\"month.toString()\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-unavailable=\"isUnavailable ? '' : undefined\"\n    :data-today=\"isCurrentMonth ? '' : undefined\"\n    :data-focused=\"isFocusedMonth ? '' : undefined\"\n    :tabindex=\"isFocusedMonth ? 0 : isDisabled ? undefined : -1\"\n    @click=\"handleClick\"\n    @keydown.up.down.left.right.space.enter.page-up.page-down=\"handleArrowKey\"\n    @keydown.enter.prevent\n  >\n    <slot\n      :month-value=\"shortMonthValue\"\n      :disabled=\"isDisabled\"\n      :today=\"isCurrentMonth\"\n      :selected=\"isSelectedMonth\"\n      :unavailable=\"isUnavailable\"\n    >\n      {{ shortMonthValue }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { endOfMonth, getLocalTimeZone, toCalendar, today } from '@internationalized/date'\nimport { computed, nextTick } from 'vue'\nimport { isSameYearMonth, toDate } from '@/date'\nimport { useKbd } from '@/shared'\n\nexport interface MonthPickerCellTriggerProps extends PrimitiveProps {\n  /** The date value provided to the cell trigger */\n  month: DateValue\n}\n\nexport interface MonthPickerCellTriggerSlot {\n  default?: (props: {\n    /** Current month value (short name) */\n    monthValue: string\n    /** Current disable state */\n    disabled: boolean\n    /** Current selected state */\n    selected: boolean\n    /** Current month/year is today state */\n    today: boolean\n    /** Current unavailable state */\n    unavailable: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectMonthPickerRootContext } from './MonthPickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthPickerCellTriggerProps>(), { as: 'div' })\n\ndefineSlots<MonthPickerCellTriggerSlot>()\n\nconst kbd = useKbd()\nconst rootContext = injectMonthPickerRootContext()\n\nconst { primitiveElement } = usePrimitiveElement()\n\nconst shortMonthValue = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.custom(toDate(props.month), { month: 'short' })\n})\n\nconst labelText = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.custom(toDate(props.month), {\n    month: 'long',\n    year: 'numeric',\n  })\n})\n\nconst isUnavailable = computed(() => rootContext.isMonthUnavailable?.(props.month) ?? false)\n\nconst isCurrentMonth = computed(() => {\n  const todayDate = toCalendar(today(getLocalTimeZone()), props.month.calendar)\n  return isSameYearMonth(props.month, todayDate)\n})\n\nconst isDisabled = computed(() => rootContext.isMonthDisabled(props.month))\n\nconst isFocusedMonth = computed(() => {\n  return !rootContext.disabled.value && isSameYearMonth(props.month, rootContext.placeholder.value)\n})\n\nconst isSelectedMonth = computed(() => rootContext.isMonthSelected(props.month))\n\nfunction changeMonth(date: DateValue) {\n  if (rootContext.readonly.value)\n    return\n  if (rootContext.isMonthDisabled(date) || rootContext.isMonthUnavailable?.(date))\n    return\n\n  rootContext.onMonthChange(date)\n}\n\nfunction handleClick() {\n  if (isDisabled.value)\n    return\n  changeMonth(props.month)\n}\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  if (isDisabled.value)\n    return\n  e.preventDefault()\n  e.stopPropagation()\n  const parentElement = rootContext.parentElement.value!\n  const sign = rootContext.dir.value === 'rtl' ? -1 : 1\n\n  switch (e.code) {\n    case kbd.ARROW_RIGHT:\n      shiftFocus(props.month, sign)\n      break\n    case kbd.ARROW_LEFT:\n      shiftFocus(props.month, -sign)\n      break\n    case kbd.ARROW_UP:\n      shiftFocus(props.month, -4)\n      break\n    case kbd.ARROW_DOWN:\n      shiftFocus(props.month, 4)\n      break\n    case kbd.PAGE_UP:\n      shiftFocusYear(-1)\n      break\n    case kbd.PAGE_DOWN:\n      shiftFocusYear(1)\n      break\n    case kbd.ENTER:\n    case kbd.SPACE_CODE:\n      changeMonth(props.month)\n  }\n\n  function shiftFocus(currentMonth: DateValue, add: number, depth = 0) {\n    if (depth > 48)\n      return\n    const candidateMonthValue = currentMonth.add({ months: add })\n\n    if ((rootContext.minValue.value && endOfMonth(candidateMonthValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && candidateMonthValue.set({ day: 1 }).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    const candidateMonth = parentElement.querySelector<HTMLElement>(`[data-value='${candidateMonthValue.toString()}']`)\n\n    if (!candidateMonth) {\n      if (add > 0) {\n        if (rootContext.isNextButtonDisabled())\n          return\n        rootContext.nextPage()\n      }\n      else {\n        if (rootContext.isPrevButtonDisabled())\n          return\n        rootContext.prevPage()\n      }\n      nextTick(() => {\n        shiftFocus(currentMonth, add, depth + 1)\n      })\n      return\n    }\n\n    if (candidateMonth && candidateMonth.hasAttribute('data-disabled'))\n      return shiftFocus(candidateMonthValue, add, depth + 1)\n\n    rootContext.onPlaceholderChange(candidateMonthValue)\n    candidateMonth?.focus()\n  }\n\n  function shiftFocusYear(years: number) {\n    const candidateMonthValue = props.month.add({ years })\n\n    if ((rootContext.minValue.value && endOfMonth(candidateMonthValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && candidateMonthValue.set({ day: 1 }).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    if (years > 0) {\n      if (rootContext.isNextButtonDisabled())\n        return\n      rootContext.nextPage()\n    }\n    else {\n      if (rootContext.isPrevButtonDisabled())\n        return\n      rootContext.prevPage()\n    }\n\n    nextTick(() => {\n      const candidateMonth = parentElement.querySelector<HTMLElement>(`[data-value='${candidateMonthValue.toString()}']`)\n      if (candidateMonth && !candidateMonth.hasAttribute('data-disabled')) {\n        rootContext.onPlaceholderChange(candidateMonthValue)\n        candidateMonth?.focus()\n      }\n    })\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    role=\"button\"\n    :aria-label=\"labelText\"\n    data-reka-month-picker-cell-trigger\n    :aria-disabled=\"isDisabled || isUnavailable ? true : undefined\"\n    :data-selected=\"isSelectedMonth ? true : undefined\"\n    :data-value=\"month.toString()\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-unavailable=\"isUnavailable ? '' : undefined\"\n    :data-today=\"isCurrentMonth ? '' : undefined\"\n    :data-focused=\"isFocusedMonth ? '' : undefined\"\n    :tabindex=\"isFocusedMonth ? 0 : isDisabled ? undefined : -1\"\n    @click=\"handleClick\"\n    @keydown.up.down.left.right.space.enter.page-up.page-down=\"handleArrowKey\"\n    @keydown.enter.prevent\n  >\n    <slot\n      :month-value=\"shortMonthValue\"\n      :disabled=\"isDisabled\"\n      :today=\"isCurrentMonth\"\n      :selected=\"isSelectedMonth\"\n      :unavailable=\"isUnavailable\"\n    >\n      {{ shortMonthValue }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerGridProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectMonthPickerRootContext } from './MonthPickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthPickerGridProps>(), { as: 'table' })\n\nconst rootContext = injectMonthPickerRootContext()\nconst disabled = computed(() => rootContext.disabled.value ? true : undefined)\nconst readonly = computed(() => rootContext.readonly.value ? true : undefined)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    role=\"application\"\n    :aria-labelledby=\"rootContext.headingId\"\n    :aria-readonly=\"readonly\"\n    :aria-disabled=\"disabled\"\n    :data-readonly=\"readonly && ''\"\n    :data-disabled=\"disabled && ''\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerGridProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectMonthPickerRootContext } from './MonthPickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthPickerGridProps>(), { as: 'table' })\n\nconst rootContext = injectMonthPickerRootContext()\nconst disabled = computed(() => rootContext.disabled.value ? true : undefined)\nconst readonly = computed(() => rootContext.readonly.value ? true : undefined)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    role=\"application\"\n    :aria-labelledby=\"rootContext.headingId\"\n    :aria-readonly=\"readonly\"\n    :aria-disabled=\"disabled\"\n    :data-readonly=\"readonly && ''\"\n    :data-disabled=\"disabled && ''\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerGridBodyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthPickerGridBodyProps>(), { as: 'tbody' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerGridBodyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthPickerGridBodyProps>(), { as: 'tbody' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerGridRowProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthPickerGridRowProps>(), { as: 'tr' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    role=\"row\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerGridRowProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthPickerGridRowProps>(), { as: 'tr' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    role=\"row\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthPickerHeaderProps>(), { as: 'div' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthPickerHeaderProps>(), { as: 'div' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerHeadingProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectMonthPickerRootContext } from './MonthPickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthPickerHeadingProps>(), { as: 'div' })\n\ndefineSlots<{\n  default?: (props: {\n    /** Current year heading */\n    headingValue: string\n  }) => any\n}>()\n\nconst rootContext = injectMonthPickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.headingId\"\n    role=\"heading\"\n    aria-level=\"2\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n  >\n    <slot :heading-value=\"rootContext.headingValue.value\">\n      {{ rootContext.headingValue.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerHeadingProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectMonthPickerRootContext } from './MonthPickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthPickerHeadingProps>(), { as: 'div' })\n\ndefineSlots<{\n  default?: (props: {\n    /** Current year heading */\n    headingValue: string\n  }) => any\n}>()\n\nconst rootContext = injectMonthPickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.headingId\"\n    role=\"heading\"\n    aria-level=\"2\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n  >\n    <slot :heading-value=\"rootContext.headingValue.value\">\n      {{ rootContext.headingValue.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerNextProps extends PrimitiveProps {\n  /** The function to be used for the next page. Overwrites the `nextPage` function set on the `MonthPickerRoot`. */\n  nextPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface MonthPickerNextSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectMonthPickerRootContext } from './MonthPickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthPickerNextProps>(), { as: 'button' })\ndefineSlots<MonthPickerNextSlot>()\n\nconst rootContext = injectMonthPickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isNextButtonDisabled(props.nextPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.nextPage(props.nextPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Next year\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Next year\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerNextProps extends PrimitiveProps {\n  /** The function to be used for the next page. Overwrites the `nextPage` function set on the `MonthPickerRoot`. */\n  nextPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface MonthPickerNextSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectMonthPickerRootContext } from './MonthPickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthPickerNextProps>(), { as: 'button' })\ndefineSlots<MonthPickerNextSlot>()\n\nconst rootContext = injectMonthPickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isNextButtonDisabled(props.nextPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.nextPage(props.nextPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Next year\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Next year\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerPrevProps extends PrimitiveProps {\n  /** The function to be used for the prev page. Overwrites the `prevPage` function set on the `MonthPickerRoot`. */\n  prevPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface MonthPickerPrevSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectMonthPickerRootContext } from './MonthPickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthPickerPrevProps>(), { as: 'button' })\ndefineSlots<MonthPickerPrevSlot>()\n\nconst rootContext = injectMonthPickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isPrevButtonDisabled(props.prevPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.prevPage(props.prevPage)\n}\n</script>\n\n<template>\n  <Primitive\n    aria-label=\"Previous year\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Prev year\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthPickerPrevProps extends PrimitiveProps {\n  /** The function to be used for the prev page. Overwrites the `prevPage` function set on the `MonthPickerRoot`. */\n  prevPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface MonthPickerPrevSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectMonthPickerRootContext } from './MonthPickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthPickerPrevProps>(), { as: 'button' })\ndefineSlots<MonthPickerPrevSlot>()\n\nconst rootContext = injectMonthPickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isPrevButtonDisabled(props.prevPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.prevPage(props.prevPage)\n}\n</script>\n\n<template>\n  <Primitive\n    aria-label=\"Previous year\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Prev year\n    </slot>\n  </Primitive>\n</template>\n","import type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Matcher } from '@/date'\nimport { computed } from 'vue'\nimport { areAllMonthsBetweenValid, compareYearMonth, getMonthsBetween, isSameYearMonth } from '@/date'\n\nexport type UseRangeMonthPickerProps = {\n  start: Ref<DateValue | undefined>\n  end: Ref<DateValue | undefined>\n  isMonthDisabled: Matcher\n  isMonthUnavailable: Matcher\n  focusedValue: Ref<DateValue | undefined>\n  allowNonContiguousRanges: Ref<boolean>\n  fixedDate: Ref<'start' | 'end' | undefined>\n  maximumMonths?: Ref<number | undefined>\n}\n\nexport function useRangeMonthPickerState(props: UseRangeMonthPickerProps) {\n  const isStartInvalid = computed(() => {\n    if (!props.start.value)\n      return false\n    if (props.isMonthDisabled(props.start.value))\n      return true\n    return false\n  })\n\n  const isEndInvalid = computed(() => {\n    if (!props.end.value)\n      return false\n    if (props.isMonthDisabled(props.end.value))\n      return true\n    return false\n  })\n\n  const isInvalid = computed(() => {\n    if (isStartInvalid.value || isEndInvalid.value)\n      return true\n    if (props.start.value && props.end.value && compareYearMonth(props.end.value, props.start.value) < 0)\n      return true\n    return false\n  })\n\n  const isSelectionStart = (date: DateValue) => {\n    if (!props.start.value)\n      return false\n    return isSameYearMonth(props.start.value, date)\n  }\n\n  const isSelectionEnd = (date: DateValue) => {\n    if (!props.end.value)\n      return false\n    return isSameYearMonth(props.end.value, date)\n  }\n\n  const isSelected = (date: DateValue) => {\n    if (props.start.value && isSameYearMonth(props.start.value, date))\n      return true\n    if (props.end.value && isSameYearMonth(props.end.value, date))\n      return true\n    if (props.end.value && props.start.value) {\n      return compareYearMonth(date, props.start.value) > 0 && compareYearMonth(date, props.end.value) < 0\n    }\n    return false\n  }\n\n  const rangeIsMonthDisabled = (date: DateValue) => {\n    if (props.isMonthDisabled(date))\n      return true\n\n    if (props.maximumMonths?.value) {\n      const maximumMonths = props.maximumMonths.value\n\n      if (props.start.value && props.end.value) {\n        if (props.fixedDate.value) {\n          const diff = getMonthsBetween(props.start.value, props.end.value)\n          if (diff <= maximumMonths) {\n            const monthsLeft = maximumMonths - diff\n            const startLimit = props.start.value.subtract({ months: monthsLeft })\n            const endLimit = props.end.value.add({ months: monthsLeft })\n            return compareYearMonth(date, startLimit) < 0 || compareYearMonth(date, endLimit) > 0\n          }\n\n          const fixedValue = props.fixedDate.value === 'start' ? props.start.value : props.end.value\n          const maxDate = fixedValue.add({ months: maximumMonths - 1 })\n          const minDate = fixedValue.subtract({ months: maximumMonths - 1 })\n          return compareYearMonth(date, minDate) < 0 || compareYearMonth(date, maxDate) > 0\n        }\n        return false\n      }\n      if (props.start.value) {\n        const maxDate = props.start.value.add({ months: maximumMonths - 1 })\n        const minDate = props.start.value.subtract({ months: maximumMonths - 1 })\n        return compareYearMonth(date, minDate) < 0 || compareYearMonth(date, maxDate) > 0\n      }\n    }\n\n    return false\n  }\n\n  const highlightedRange = computed(() => {\n    if (props.start.value && props.end.value && !props.fixedDate.value)\n      return null\n    if (!props.start.value || !props.focusedValue.value)\n      return null\n\n    const isStartBeforeFocused = compareYearMonth(props.start.value, props.focusedValue.value) < 0\n    const start = isStartBeforeFocused ? props.start.value : props.focusedValue.value\n    const end = isStartBeforeFocused ? props.focusedValue.value : props.start.value\n\n    if (isSameYearMonth(start, end)) {\n      return { start, end }\n    }\n\n    if (props.maximumMonths?.value && !props.end.value) {\n      const maximumMonths = props.maximumMonths.value\n      const anchor = props.start.value\n      const focused = props.focusedValue.value\n\n      if (compareYearMonth(focused, anchor) >= 0) {\n        const maxEnd = anchor.add({ months: maximumMonths - 1 })\n        const cappedEnd = compareYearMonth(focused, maxEnd) > 0 ? maxEnd : focused\n        return { start: anchor, end: cappedEnd }\n      }\n      else {\n        const minStart = anchor.subtract({ months: maximumMonths - 1 })\n        const cappedStart = compareYearMonth(focused, minStart) < 0 ? minStart : focused\n        return { start: cappedStart, end: anchor }\n      }\n    }\n\n    const isValid = areAllMonthsBetweenValid(\n      start,\n      end,\n      props.allowNonContiguousRanges.value ? () => false : props.isMonthUnavailable,\n      rangeIsMonthDisabled,\n    )\n    if (isValid)\n      return { start, end }\n\n    return null\n  })\n\n  const isHighlightedStart = (date: DateValue) => {\n    if (!highlightedRange.value?.start)\n      return false\n    return isSameYearMonth(highlightedRange.value.start, date)\n  }\n\n  const isHighlightedEnd = (date: DateValue) => {\n    if (!highlightedRange.value?.end)\n      return false\n    return isSameYearMonth(highlightedRange.value.end, date)\n  }\n\n  return {\n    isInvalid,\n    isSelected,\n    highlightedRange,\n    isSelectionStart,\n    isSelectionEnd,\n    isHighlightedStart,\n    isHighlightedEnd,\n    isMonthDisabled: rangeIsMonthDisabled,\n  }\n}\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { DateRange } from '@/shared/date'\nimport type { Direction } from '@/shared/types'\nimport { compareYearMonth, isSameYearMonth } from '@/date'\nimport { useMonthPicker } from '@/MonthPicker/useMonthPicker'\nimport { createContext, useDirection, useId, useKbd, useLocale } from '@/shared'\nimport { getDefaultDate, handleCalendarInitialFocus } from '@/shared/date'\nimport { useRangeMonthPickerState } from './useRangeMonthPicker'\n\ntype MonthRangePickerRootContext = {\n  modelValue: Ref<DateRange>\n  startValue: Ref<DateValue | undefined>\n  endValue: Ref<DateValue | undefined>\n  locale: Ref<string>\n  placeholder: Ref<DateValue>\n  preventDeselect: Ref<boolean>\n  grid: Ref<Grid<DateValue>>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  initialFocus: Ref<boolean>\n  onPlaceholderChange: (date: DateValue) => void\n  fullCalendarLabel: Ref<string>\n  parentElement: Ref<HTMLElement | undefined>\n  headingValue: Ref<string>\n  headingId: string\n  isInvalid: Ref<boolean>\n  isMonthDisabled: Matcher\n  isMonthUnavailable?: Matcher\n  allowNonContiguousRanges: Ref<boolean>\n  highlightedRange: Ref<{ start: DateValue, end: DateValue } | null>\n  focusedValue: Ref<DateValue | undefined>\n  lastPressedDateValue: Ref<DateValue | undefined>\n  isSelected: (date: DateValue) => boolean\n  isSelectionEnd: (date: DateValue) => boolean\n  isSelectionStart: (date: DateValue) => boolean\n  isHighlightedStart: (date: DateValue) => boolean\n  isHighlightedEnd: (date: DateValue) => boolean\n  prevPage: (prevPageFunc?: (date: DateValue) => DateValue) => void\n  nextPage: (nextPageFunc?: (date: DateValue) => DateValue) => void\n  isNextButtonDisabled: (nextPageFunc?: (date: DateValue) => DateValue) => boolean\n  isPrevButtonDisabled: (prevPageFunc?: (date: DateValue) => DateValue) => boolean\n  formatter: Formatter\n  dir: Ref<Direction>\n  fixedDate: Ref<'start' | 'end' | undefined>\n  maximumMonths: Ref<number | undefined>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n}\n\nexport interface MonthRangePickerRootProps extends PrimitiveProps {\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The default value for the calendar */\n  defaultValue?: DateRange\n  /** The controlled selected month range of the month range picker. Can be bound as `v-model`. */\n  modelValue?: DateRange | null\n  /** The placeholder date, which is used to determine what year to display when no date is selected. */\n  placeholder?: DateValue\n  /** When combined with `isMonthUnavailable`, determines whether non-contiguous ranges may be selected. */\n  allowNonContiguousRanges?: boolean\n  /** Whether or not to prevent the user from deselecting a date without selecting another date first */\n  preventDeselect?: boolean\n  /** The maximum number of months that can be selected in a range */\n  maximumMonths?: number\n  /** The accessible label for the calendar */\n  calendarLabel?: string\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether or not the calendar is disabled */\n  disabled?: boolean\n  /** Whether or not the calendar is readonly */\n  readonly?: boolean\n  /** If true, the calendar will focus the selected month on mount */\n  initialFocus?: boolean\n  /** A function that returns whether or not a month is disabled */\n  isMonthDisabled?: Matcher\n  /** A function that returns whether or not a month is unavailable */\n  isMonthUnavailable?: Matcher\n  /** The reading direction of the calendar when applicable. */\n  dir?: Direction\n  /** A function that returns the next page of the calendar. */\n  nextPage?: (placeholder: DateValue) => DateValue\n  /** A function that returns the previous page of the calendar. */\n  prevPage?: (placeholder: DateValue) => DateValue\n  /** Which part of the range should be fixed */\n  fixedDate?: 'start' | 'end'\n}\n\nexport type MonthRangePickerRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateRange]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n  /** Event handler called whenever the start value changes */\n  'update:startValue': [date: DateValue | undefined]\n}\n\nexport const [injectMonthRangePickerRootContext, provideMonthRangePickerRootContext]\n  = createContext<MonthRangePickerRootContext>('MonthRangePickerRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener, useVModel } from '@vueuse/core'\nimport { computed, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthRangePickerRootProps>(), {\n  defaultValue: () => ({ start: undefined, end: undefined }),\n  as: 'div',\n  preventDeselect: false,\n  disabled: false,\n  readonly: false,\n  initialFocus: false,\n  placeholder: undefined,\n  isMonthDisabled: undefined,\n  isMonthUnavailable: undefined,\n  allowNonContiguousRanges: false,\n  maximumMonths: undefined,\n})\nconst emits = defineEmits<MonthRangePickerRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the placeholder */\n    date: DateValue\n    /** The grid of months */\n    grid: Grid<DateValue>\n    /** The calendar locale */\n    locale: string\n    /** The current date range */\n    modelValue: DateRange\n  }) => any\n}>()\n\nconst {\n  disabled,\n  readonly,\n  initialFocus,\n  preventDeselect,\n  isMonthUnavailable: propsIsMonthUnavailable,\n  isMonthDisabled: propsIsMonthDisabled,\n  calendarLabel,\n  maxValue,\n  minValue,\n  dir: propDir,\n  locale: propLocale,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n  allowNonContiguousRanges,\n  fixedDate,\n  maximumMonths,\n} = toRefs(props)\n\nconst { primitiveElement, currentElement: parentElement } = usePrimitiveElement()\nconst dir = useDirection(propDir)\nconst locale = useLocale(propLocale)\nconst headingId = useId(undefined, 'reka-month-range-picker-heading')\n\nconst lastPressedDateValue = ref() as Ref<DateValue | undefined>\nconst focusedValue = ref() as Ref<DateValue | undefined>\nconst isEditing = ref(false)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? { start: undefined, end: undefined },\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateRange | null>\n\nconst normalizeRange = (value?: DateRange | null): DateRange => value ?? { start: undefined, end: undefined }\nconst normalizedModelValue = computed(() => normalizeRange(modelValue.value))\n\nconst validModelValue = ref(normalizeRange(modelValue.value)) as Ref<DateRange>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: normalizeRange(modelValue.value).start,\n  locale: props.locale,\n})\n\nconst startValue = ref(normalizeRange(modelValue.value).start) as Ref<DateValue | undefined>\nconst endValue = ref(normalizeRange(modelValue.value).end) as Ref<DateValue | undefined>\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nfunction onPlaceholderChange(value: DateValue) {\n  placeholder.value = value.copy()\n}\n\nconst {\n  fullCalendarLabel,\n  headingValue,\n  isMonthDisabled,\n  isMonthUnavailable,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  grid,\n  nextPage,\n  prevPage,\n  formatter,\n} = useMonthPicker({\n  locale,\n  placeholder,\n  minValue,\n  maxValue,\n  disabled,\n  isMonthDisabled: propsIsMonthDisabled,\n  isMonthUnavailable: propsIsMonthUnavailable,\n  calendarLabel,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n})\n\nconst {\n  isInvalid,\n  isSelected,\n  highlightedRange,\n  isSelectionStart,\n  isSelectionEnd,\n  isHighlightedStart,\n  isHighlightedEnd,\n  isMonthDisabled: rangeIsMonthDisabled,\n} = useRangeMonthPickerState({\n  start: startValue,\n  end: endValue,\n  isMonthDisabled,\n  isMonthUnavailable,\n  focusedValue,\n  allowNonContiguousRanges,\n  fixedDate,\n  maximumMonths,\n})\n\nwatch(modelValue, (_modelValue) => {\n  const next = normalizeRange(_modelValue)\n\n  const isStartSynced = (!next.start && !startValue.value)\n    || (!!next.start && !!startValue.value && isSameYearMonth(next.start, startValue.value))\n\n  if (!isStartSynced) {\n    startValue.value = next.start?.copy?.()\n  }\n\n  const isEndSynced = (!next.end && !endValue.value)\n    || (!!next.end && !!endValue.value && isSameYearMonth(next.end, endValue.value))\n\n  if (!isEndSynced) {\n    endValue.value = next.end?.copy?.()\n  }\n\n  if (next.start && next.end) {\n    validModelValue.value = {\n      start: next.start.copy(),\n      end: next.end.copy(),\n    }\n  }\n})\n\nwatch(startValue, (_startValue) => {\n  if (_startValue && !isSameYearMonth(_startValue, placeholder.value))\n    onPlaceholderChange(_startValue)\n\n  emits('update:startValue', _startValue)\n})\n\nwatch([startValue, endValue], ([_startValue, _endValue]) => {\n  const value = modelValue.value\n\n  if (\n    value\n    && value.start\n    && value.end\n    && _startValue\n    && _endValue\n    && isSameYearMonth(value.start, _startValue)\n    && isSameYearMonth(value.end, _endValue)\n  ) {\n    return\n  }\n\n  isEditing.value = true\n  if (_endValue && _startValue) {\n    const nextValue = compareYearMonth(_endValue, _startValue) < 0\n      ? { start: _endValue.copy(), end: _startValue.copy() }\n      : { start: _startValue.copy(), end: _endValue.copy() }\n\n    modelValue.value = { start: nextValue.start, end: nextValue.end }\n    isEditing.value = false\n    validModelValue.value = { start: nextValue.start.copy(), end: nextValue.end.copy() }\n  }\n  else {\n    modelValue.value = _startValue\n      ? { start: _startValue.copy(), end: undefined }\n      : { start: _endValue?.copy(), end: undefined }\n  }\n})\n\nconst kbd = useKbd()\nuseEventListener(parentElement, 'keydown', (ev) => {\n  if (ev.key === kbd.ESCAPE && isEditing.value) {\n    startValue.value = validModelValue.value.start?.copy()\n    endValue.value = validModelValue.value.end?.copy()\n  }\n})\n\nprovideMonthRangePickerRootContext({\n  isMonthUnavailable,\n  startValue,\n  endValue,\n  formatter,\n  modelValue: normalizedModelValue,\n  placeholder,\n  disabled,\n  initialFocus,\n  grid,\n  readonly,\n  preventDeselect,\n  fullCalendarLabel,\n  headingValue,\n  headingId,\n  isInvalid,\n  isMonthDisabled: rangeIsMonthDisabled,\n  allowNonContiguousRanges,\n  highlightedRange,\n  focusedValue,\n  lastPressedDateValue,\n  isSelected,\n  isSelectionEnd,\n  isSelectionStart,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  nextPage,\n  prevPage,\n  parentElement,\n  onPlaceholderChange,\n  locale,\n  dir,\n  isHighlightedStart,\n  isHighlightedEnd,\n  fixedDate,\n  maximumMonths,\n  minValue,\n  maxValue,\n})\n\nonMounted(() => {\n  if (initialFocus.value)\n    handleCalendarInitialFocus(parentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"fullCalendarLabel\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n  >\n    <div\n      style=\"border: 0px; clip: rect(0px, 0px, 0px, 0px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; white-space: nowrap; width: 1px;\"\n    >\n      <div\n        role=\"heading\"\n        aria-level=\"2\"\n      >\n        {{ fullCalendarLabel }}\n      </div>\n    </div>\n\n    <slot\n      :date=\"placeholder\"\n      :grid=\"grid\"\n      :locale=\"locale\"\n      :model-value=\"normalizedModelValue\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { DateRange } from '@/shared/date'\nimport type { Direction } from '@/shared/types'\nimport { compareYearMonth, isSameYearMonth } from '@/date'\nimport { useMonthPicker } from '@/MonthPicker/useMonthPicker'\nimport { createContext, useDirection, useId, useKbd, useLocale } from '@/shared'\nimport { getDefaultDate, handleCalendarInitialFocus } from '@/shared/date'\nimport { useRangeMonthPickerState } from './useRangeMonthPicker'\n\ntype MonthRangePickerRootContext = {\n  modelValue: Ref<DateRange>\n  startValue: Ref<DateValue | undefined>\n  endValue: Ref<DateValue | undefined>\n  locale: Ref<string>\n  placeholder: Ref<DateValue>\n  preventDeselect: Ref<boolean>\n  grid: Ref<Grid<DateValue>>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  initialFocus: Ref<boolean>\n  onPlaceholderChange: (date: DateValue) => void\n  fullCalendarLabel: Ref<string>\n  parentElement: Ref<HTMLElement | undefined>\n  headingValue: Ref<string>\n  headingId: string\n  isInvalid: Ref<boolean>\n  isMonthDisabled: Matcher\n  isMonthUnavailable?: Matcher\n  allowNonContiguousRanges: Ref<boolean>\n  highlightedRange: Ref<{ start: DateValue, end: DateValue } | null>\n  focusedValue: Ref<DateValue | undefined>\n  lastPressedDateValue: Ref<DateValue | undefined>\n  isSelected: (date: DateValue) => boolean\n  isSelectionEnd: (date: DateValue) => boolean\n  isSelectionStart: (date: DateValue) => boolean\n  isHighlightedStart: (date: DateValue) => boolean\n  isHighlightedEnd: (date: DateValue) => boolean\n  prevPage: (prevPageFunc?: (date: DateValue) => DateValue) => void\n  nextPage: (nextPageFunc?: (date: DateValue) => DateValue) => void\n  isNextButtonDisabled: (nextPageFunc?: (date: DateValue) => DateValue) => boolean\n  isPrevButtonDisabled: (prevPageFunc?: (date: DateValue) => DateValue) => boolean\n  formatter: Formatter\n  dir: Ref<Direction>\n  fixedDate: Ref<'start' | 'end' | undefined>\n  maximumMonths: Ref<number | undefined>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n}\n\nexport interface MonthRangePickerRootProps extends PrimitiveProps {\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The default value for the calendar */\n  defaultValue?: DateRange\n  /** The controlled selected month range of the month range picker. Can be bound as `v-model`. */\n  modelValue?: DateRange | null\n  /** The placeholder date, which is used to determine what year to display when no date is selected. */\n  placeholder?: DateValue\n  /** When combined with `isMonthUnavailable`, determines whether non-contiguous ranges may be selected. */\n  allowNonContiguousRanges?: boolean\n  /** Whether or not to prevent the user from deselecting a date without selecting another date first */\n  preventDeselect?: boolean\n  /** The maximum number of months that can be selected in a range */\n  maximumMonths?: number\n  /** The accessible label for the calendar */\n  calendarLabel?: string\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether or not the calendar is disabled */\n  disabled?: boolean\n  /** Whether or not the calendar is readonly */\n  readonly?: boolean\n  /** If true, the calendar will focus the selected month on mount */\n  initialFocus?: boolean\n  /** A function that returns whether or not a month is disabled */\n  isMonthDisabled?: Matcher\n  /** A function that returns whether or not a month is unavailable */\n  isMonthUnavailable?: Matcher\n  /** The reading direction of the calendar when applicable. */\n  dir?: Direction\n  /** A function that returns the next page of the calendar. */\n  nextPage?: (placeholder: DateValue) => DateValue\n  /** A function that returns the previous page of the calendar. */\n  prevPage?: (placeholder: DateValue) => DateValue\n  /** Which part of the range should be fixed */\n  fixedDate?: 'start' | 'end'\n}\n\nexport type MonthRangePickerRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateRange]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n  /** Event handler called whenever the start value changes */\n  'update:startValue': [date: DateValue | undefined]\n}\n\nexport const [injectMonthRangePickerRootContext, provideMonthRangePickerRootContext]\n  = createContext<MonthRangePickerRootContext>('MonthRangePickerRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener, useVModel } from '@vueuse/core'\nimport { computed, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthRangePickerRootProps>(), {\n  defaultValue: () => ({ start: undefined, end: undefined }),\n  as: 'div',\n  preventDeselect: false,\n  disabled: false,\n  readonly: false,\n  initialFocus: false,\n  placeholder: undefined,\n  isMonthDisabled: undefined,\n  isMonthUnavailable: undefined,\n  allowNonContiguousRanges: false,\n  maximumMonths: undefined,\n})\nconst emits = defineEmits<MonthRangePickerRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the placeholder */\n    date: DateValue\n    /** The grid of months */\n    grid: Grid<DateValue>\n    /** The calendar locale */\n    locale: string\n    /** The current date range */\n    modelValue: DateRange\n  }) => any\n}>()\n\nconst {\n  disabled,\n  readonly,\n  initialFocus,\n  preventDeselect,\n  isMonthUnavailable: propsIsMonthUnavailable,\n  isMonthDisabled: propsIsMonthDisabled,\n  calendarLabel,\n  maxValue,\n  minValue,\n  dir: propDir,\n  locale: propLocale,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n  allowNonContiguousRanges,\n  fixedDate,\n  maximumMonths,\n} = toRefs(props)\n\nconst { primitiveElement, currentElement: parentElement } = usePrimitiveElement()\nconst dir = useDirection(propDir)\nconst locale = useLocale(propLocale)\nconst headingId = useId(undefined, 'reka-month-range-picker-heading')\n\nconst lastPressedDateValue = ref() as Ref<DateValue | undefined>\nconst focusedValue = ref() as Ref<DateValue | undefined>\nconst isEditing = ref(false)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? { start: undefined, end: undefined },\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateRange | null>\n\nconst normalizeRange = (value?: DateRange | null): DateRange => value ?? { start: undefined, end: undefined }\nconst normalizedModelValue = computed(() => normalizeRange(modelValue.value))\n\nconst validModelValue = ref(normalizeRange(modelValue.value)) as Ref<DateRange>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: normalizeRange(modelValue.value).start,\n  locale: props.locale,\n})\n\nconst startValue = ref(normalizeRange(modelValue.value).start) as Ref<DateValue | undefined>\nconst endValue = ref(normalizeRange(modelValue.value).end) as Ref<DateValue | undefined>\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nfunction onPlaceholderChange(value: DateValue) {\n  placeholder.value = value.copy()\n}\n\nconst {\n  fullCalendarLabel,\n  headingValue,\n  isMonthDisabled,\n  isMonthUnavailable,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  grid,\n  nextPage,\n  prevPage,\n  formatter,\n} = useMonthPicker({\n  locale,\n  placeholder,\n  minValue,\n  maxValue,\n  disabled,\n  isMonthDisabled: propsIsMonthDisabled,\n  isMonthUnavailable: propsIsMonthUnavailable,\n  calendarLabel,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n})\n\nconst {\n  isInvalid,\n  isSelected,\n  highlightedRange,\n  isSelectionStart,\n  isSelectionEnd,\n  isHighlightedStart,\n  isHighlightedEnd,\n  isMonthDisabled: rangeIsMonthDisabled,\n} = useRangeMonthPickerState({\n  start: startValue,\n  end: endValue,\n  isMonthDisabled,\n  isMonthUnavailable,\n  focusedValue,\n  allowNonContiguousRanges,\n  fixedDate,\n  maximumMonths,\n})\n\nwatch(modelValue, (_modelValue) => {\n  const next = normalizeRange(_modelValue)\n\n  const isStartSynced = (!next.start && !startValue.value)\n    || (!!next.start && !!startValue.value && isSameYearMonth(next.start, startValue.value))\n\n  if (!isStartSynced) {\n    startValue.value = next.start?.copy?.()\n  }\n\n  const isEndSynced = (!next.end && !endValue.value)\n    || (!!next.end && !!endValue.value && isSameYearMonth(next.end, endValue.value))\n\n  if (!isEndSynced) {\n    endValue.value = next.end?.copy?.()\n  }\n\n  if (next.start && next.end) {\n    validModelValue.value = {\n      start: next.start.copy(),\n      end: next.end.copy(),\n    }\n  }\n})\n\nwatch(startValue, (_startValue) => {\n  if (_startValue && !isSameYearMonth(_startValue, placeholder.value))\n    onPlaceholderChange(_startValue)\n\n  emits('update:startValue', _startValue)\n})\n\nwatch([startValue, endValue], ([_startValue, _endValue]) => {\n  const value = modelValue.value\n\n  if (\n    value\n    && value.start\n    && value.end\n    && _startValue\n    && _endValue\n    && isSameYearMonth(value.start, _startValue)\n    && isSameYearMonth(value.end, _endValue)\n  ) {\n    return\n  }\n\n  isEditing.value = true\n  if (_endValue && _startValue) {\n    const nextValue = compareYearMonth(_endValue, _startValue) < 0\n      ? { start: _endValue.copy(), end: _startValue.copy() }\n      : { start: _startValue.copy(), end: _endValue.copy() }\n\n    modelValue.value = { start: nextValue.start, end: nextValue.end }\n    isEditing.value = false\n    validModelValue.value = { start: nextValue.start.copy(), end: nextValue.end.copy() }\n  }\n  else {\n    modelValue.value = _startValue\n      ? { start: _startValue.copy(), end: undefined }\n      : { start: _endValue?.copy(), end: undefined }\n  }\n})\n\nconst kbd = useKbd()\nuseEventListener(parentElement, 'keydown', (ev) => {\n  if (ev.key === kbd.ESCAPE && isEditing.value) {\n    startValue.value = validModelValue.value.start?.copy()\n    endValue.value = validModelValue.value.end?.copy()\n  }\n})\n\nprovideMonthRangePickerRootContext({\n  isMonthUnavailable,\n  startValue,\n  endValue,\n  formatter,\n  modelValue: normalizedModelValue,\n  placeholder,\n  disabled,\n  initialFocus,\n  grid,\n  readonly,\n  preventDeselect,\n  fullCalendarLabel,\n  headingValue,\n  headingId,\n  isInvalid,\n  isMonthDisabled: rangeIsMonthDisabled,\n  allowNonContiguousRanges,\n  highlightedRange,\n  focusedValue,\n  lastPressedDateValue,\n  isSelected,\n  isSelectionEnd,\n  isSelectionStart,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  nextPage,\n  prevPage,\n  parentElement,\n  onPlaceholderChange,\n  locale,\n  dir,\n  isHighlightedStart,\n  isHighlightedEnd,\n  fixedDate,\n  maximumMonths,\n  minValue,\n  maxValue,\n})\n\nonMounted(() => {\n  if (initialFocus.value)\n    handleCalendarInitialFocus(parentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"fullCalendarLabel\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n  >\n    <div\n      style=\"border: 0px; clip: rect(0px, 0px, 0px, 0px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; white-space: nowrap; width: 1px;\"\n    >\n      <div\n        role=\"heading\"\n        aria-level=\"2\"\n      >\n        {{ fullCalendarLabel }}\n      </div>\n    </div>\n\n    <slot\n      :date=\"placeholder\"\n      :grid=\"grid\"\n      :locale=\"locale\"\n      :model-value=\"normalizedModelValue\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerCellProps extends PrimitiveProps {\n  /** The date value for the cell */\n  date: DateValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectMonthRangePickerRootContext } from './MonthRangePickerRoot.vue'\n\nwithDefaults(defineProps<MonthRangePickerCellProps>(), { as: 'td' })\nconst rootContext = injectMonthRangePickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"gridcell\"\n    :aria-selected=\"rootContext.isSelected(date) ? true : undefined\"\n    :aria-disabled=\"rootContext.isMonthDisabled(date) || rootContext.isMonthUnavailable?.(date)\"\n    :data-disabled=\"rootContext.isMonthDisabled(date) ? '' : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerCellProps extends PrimitiveProps {\n  /** The date value for the cell */\n  date: DateValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectMonthRangePickerRootContext } from './MonthRangePickerRoot.vue'\n\nwithDefaults(defineProps<MonthRangePickerCellProps>(), { as: 'td' })\nconst rootContext = injectMonthRangePickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"gridcell\"\n    :aria-selected=\"rootContext.isSelected(date) ? true : undefined\"\n    :aria-disabled=\"rootContext.isMonthDisabled(date) || rootContext.isMonthUnavailable?.(date)\"\n    :data-disabled=\"rootContext.isMonthDisabled(date) ? '' : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { endOfMonth, getLocalTimeZone, toCalendar, today } from '@internationalized/date'\nimport { computed, nextTick } from 'vue'\nimport { isMonthBetweenInclusive, isSameYearMonth, toDate } from '@/date'\nimport { useKbd } from '@/shared'\n\nexport interface MonthRangePickerCellTriggerProps extends PrimitiveProps {\n  /** The date value provided to the cell trigger */\n  month: DateValue\n}\n\nexport interface MonthRangePickerCellTriggerSlot {\n  default?: (props: {\n    /** Current month value (short name) */\n    monthValue: string\n    /** Current disable state */\n    disabled: boolean\n    /** Current selected state */\n    selected: boolean\n    /** Current month is today's month state */\n    today: boolean\n    /** Current unavailable state */\n    unavailable: boolean\n    /** Current highlighted state */\n    highlighted: boolean\n    /** Current highlighted start state */\n    highlightedStart: boolean\n    /** Current highlighted end state */\n    highlightedEnd: boolean\n    /** Current selection start state */\n    selectionStart: boolean\n    /** Current selection end state */\n    selectionEnd: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectMonthRangePickerRootContext } from './MonthRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthRangePickerCellTriggerProps>(), { as: 'div' })\n\ndefineSlots<MonthRangePickerCellTriggerSlot>()\n\nconst kbd = useKbd()\nconst rootContext = injectMonthRangePickerRootContext()\n\nconst { primitiveElement } = usePrimitiveElement()\n\nconst shortMonthValue = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.custom(toDate(props.month), { month: 'short' })\n})\n\nconst labelText = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.custom(toDate(props.month), { month: 'long', year: 'numeric' })\n})\n\nconst isUnavailable = computed(() => rootContext.isMonthUnavailable?.(props.month) ?? false)\n\nconst isCurrentMonth = computed(() => {\n  const todayDate = toCalendar(today(getLocalTimeZone()), props.month.calendar)\n  return isSameYearMonth(props.month, todayDate)\n})\n\nconst isDisabled = computed(() => rootContext.isMonthDisabled(props.month))\n\nconst isFocusedMonth = computed(() => {\n  return !rootContext.disabled.value && isSameYearMonth(props.month, rootContext.placeholder.value)\n})\n\nconst isSelectedMonth = computed(() => rootContext.isSelected(props.month))\nconst isSelectionStart = computed(() => rootContext.isSelectionStart(props.month))\nconst isSelectionEnd = computed(() => rootContext.isSelectionEnd(props.month))\nconst isHighlightStart = computed(() => rootContext.isHighlightedStart(props.month))\nconst isHighlightEnd = computed(() => rootContext.isHighlightedEnd(props.month))\nconst isHighlighted = computed(() => rootContext.highlightedRange.value\n  ? isMonthBetweenInclusive(props.month, rootContext.highlightedRange.value.start, rootContext.highlightedRange.value.end)\n  : false)\nconst allowNonContiguousRanges = computed(() => rootContext.allowNonContiguousRanges.value)\n\nfunction changeMonth(e: MouseEvent | KeyboardEvent, date: DateValue) {\n  if (rootContext.readonly.value)\n    return\n  if (rootContext.isMonthDisabled(date) || rootContext.isMonthUnavailable?.(date))\n    return\n\n  if (rootContext.startValue.value && rootContext.highlightedRange.value === null) {\n    if (isSameYearMonth(date, rootContext.startValue.value) && !rootContext.preventDeselect.value && !rootContext.endValue.value) {\n      rootContext.startValue.value = undefined\n      rootContext.onPlaceholderChange(date)\n      rootContext.lastPressedDateValue.value = date.copy()\n      return\n    }\n    else if (!rootContext.endValue.value) {\n      e.preventDefault()\n      if (rootContext.lastPressedDateValue.value && isSameYearMonth(rootContext.lastPressedDateValue.value, date))\n        rootContext.startValue.value = date.copy()\n      rootContext.lastPressedDateValue.value = date.copy()\n      return\n    }\n  }\n\n  rootContext.lastPressedDateValue.value = date.copy()\n\n  if (\n    rootContext.startValue.value\n    && rootContext.endValue.value\n    && isSameYearMonth(rootContext.startValue.value, rootContext.endValue.value)\n    && isSameYearMonth(rootContext.startValue.value, date)\n    && !rootContext.preventDeselect.value\n  ) {\n    rootContext.startValue.value = undefined\n    rootContext.endValue.value = undefined\n    rootContext.onPlaceholderChange(date)\n    return\n  }\n\n  if (!rootContext.startValue.value) {\n    rootContext.startValue.value = date.copy()\n  }\n  else if (!rootContext.endValue.value) {\n    rootContext.endValue.value = date.copy()\n  }\n  else if (rootContext.endValue.value && rootContext.startValue.value) {\n    if (!rootContext.fixedDate.value) {\n      rootContext.endValue.value = undefined\n      rootContext.startValue.value = date.copy()\n    }\n    else if (rootContext.fixedDate.value === 'start') {\n      if (date.compare(rootContext.startValue.value) < 0) {\n        rootContext.startValue.value = date.copy()\n      }\n      else {\n        rootContext.endValue.value = date.copy()\n      }\n    }\n    else if (rootContext.fixedDate.value === 'end') {\n      if (date.compare(rootContext.endValue.value) > 0) {\n        rootContext.endValue.value = date.copy()\n      }\n      else {\n        rootContext.startValue.value = date.copy()\n      }\n    }\n  }\n}\n\nfunction handleClick(e: MouseEvent) {\n  if (isDisabled.value)\n    return\n  changeMonth(e, props.month)\n}\n\nfunction handleFocus() {\n  if (isDisabled.value || rootContext.isMonthUnavailable?.(props.month))\n    return\n  rootContext.focusedValue.value = props.month.copy()\n}\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  if (isDisabled.value)\n    return\n  e.preventDefault()\n  e.stopPropagation()\n  const parentElement = rootContext.parentElement.value!\n  const sign = rootContext.dir.value === 'rtl' ? -1 : 1\n\n  switch (e.code) {\n    case kbd.ARROW_RIGHT:\n      shiftFocus(props.month, sign)\n      break\n    case kbd.ARROW_LEFT:\n      shiftFocus(props.month, -sign)\n      break\n    case kbd.ARROW_UP:\n      shiftFocus(props.month, -4)\n      break\n    case kbd.ARROW_DOWN:\n      shiftFocus(props.month, 4)\n      break\n    case kbd.PAGE_UP:\n      shiftFocusYear(-1)\n      break\n    case kbd.PAGE_DOWN:\n      shiftFocusYear(1)\n      break\n    case kbd.ENTER:\n    case kbd.SPACE_CODE:\n      changeMonth(e, props.month)\n  }\n\n  function shiftFocus(currentMonth: DateValue, add: number, depth = 0) {\n    if (depth > 48)\n      return\n    const candidateMonthValue = currentMonth.add({ months: add })\n\n    if ((rootContext.minValue.value && endOfMonth(candidateMonthValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && candidateMonthValue.set({ day: 1 }).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    const candidateMonth = parentElement.querySelector<HTMLElement>(`[data-value='${candidateMonthValue.toString()}']`)\n\n    if (!candidateMonth) {\n      if (add > 0) {\n        if (rootContext.isNextButtonDisabled())\n          return\n        rootContext.nextPage()\n      }\n      else {\n        if (rootContext.isPrevButtonDisabled())\n          return\n        rootContext.prevPage()\n      }\n      nextTick(() => {\n        shiftFocus(currentMonth, add, depth + 1)\n      })\n      return\n    }\n\n    if (candidateMonth && candidateMonth.hasAttribute('data-disabled'))\n      return shiftFocus(candidateMonthValue, add, depth + 1)\n\n    rootContext.onPlaceholderChange(candidateMonthValue)\n    candidateMonth?.focus()\n  }\n\n  function shiftFocusYear(years: number) {\n    const candidateMonthValue = props.month.add({ years })\n\n    if ((rootContext.minValue.value && endOfMonth(candidateMonthValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && candidateMonthValue.set({ day: 1 }).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    if (years > 0) {\n      if (rootContext.isNextButtonDisabled())\n        return\n      rootContext.nextPage()\n    }\n    else {\n      if (rootContext.isPrevButtonDisabled())\n        return\n      rootContext.prevPage()\n    }\n\n    nextTick(() => {\n      const candidateMonth = parentElement.querySelector<HTMLElement>(`[data-value='${candidateMonthValue.toString()}']`)\n      if (candidateMonth && !candidateMonth.hasAttribute('data-disabled')) {\n        rootContext.onPlaceholderChange(candidateMonthValue)\n        candidateMonth?.focus()\n        return\n      }\n\n      shiftFocus(candidateMonthValue, years > 0 ? 1 : -1, 1)\n    })\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    role=\"button\"\n    :aria-label=\"labelText\"\n    data-reka-month-range-picker-cell-trigger\n    :aria-pressed=\"isSelectedMonth && (allowNonContiguousRanges || !isUnavailable) ? true : undefined\"\n    :aria-disabled=\"isDisabled || isUnavailable ? true : undefined\"\n    :data-highlighted=\"isHighlighted && (allowNonContiguousRanges || !isUnavailable) ? '' : undefined\"\n    :data-selection-start=\"isSelectionStart ? true : undefined\"\n    :data-selection-end=\"isSelectionEnd ? true : undefined\"\n    :data-highlighted-start=\"isHighlightStart ? true : undefined\"\n    :data-highlighted-end=\"isHighlightEnd ? true : undefined\"\n    :data-selected=\"isSelectedMonth && (allowNonContiguousRanges || !isUnavailable) ? true : undefined\"\n    :data-value=\"month.toString()\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-unavailable=\"isUnavailable ? '' : undefined\"\n    :data-today=\"isCurrentMonth ? '' : undefined\"\n    :data-focused=\"isFocusedMonth ? '' : undefined\"\n    :tabindex=\"isFocusedMonth ? 0 : isDisabled ? undefined : -1\"\n    @click=\"handleClick\"\n    @focusin=\"handleFocus\"\n    @mouseenter=\"handleFocus\"\n    @keydown.up.down.left.right.space.enter.page-up.page-down=\"handleArrowKey\"\n    @keydown.enter.prevent\n  >\n    <slot\n      :month-value=\"shortMonthValue\"\n      :disabled=\"isDisabled\"\n      :today=\"isCurrentMonth\"\n      :selected=\"isSelectedMonth\"\n      :unavailable=\"isUnavailable\"\n      :highlighted=\"isHighlighted && (allowNonContiguousRanges || !isUnavailable)\"\n      :highlighted-start=\"isHighlightStart\"\n      :highlighted-end=\"isHighlightEnd\"\n      :selection-start=\"isSelectionStart\"\n      :selection-end=\"isSelectionEnd\"\n    >\n      {{ shortMonthValue }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { endOfMonth, getLocalTimeZone, toCalendar, today } from '@internationalized/date'\nimport { computed, nextTick } from 'vue'\nimport { isMonthBetweenInclusive, isSameYearMonth, toDate } from '@/date'\nimport { useKbd } from '@/shared'\n\nexport interface MonthRangePickerCellTriggerProps extends PrimitiveProps {\n  /** The date value provided to the cell trigger */\n  month: DateValue\n}\n\nexport interface MonthRangePickerCellTriggerSlot {\n  default?: (props: {\n    /** Current month value (short name) */\n    monthValue: string\n    /** Current disable state */\n    disabled: boolean\n    /** Current selected state */\n    selected: boolean\n    /** Current month is today's month state */\n    today: boolean\n    /** Current unavailable state */\n    unavailable: boolean\n    /** Current highlighted state */\n    highlighted: boolean\n    /** Current highlighted start state */\n    highlightedStart: boolean\n    /** Current highlighted end state */\n    highlightedEnd: boolean\n    /** Current selection start state */\n    selectionStart: boolean\n    /** Current selection end state */\n    selectionEnd: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectMonthRangePickerRootContext } from './MonthRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthRangePickerCellTriggerProps>(), { as: 'div' })\n\ndefineSlots<MonthRangePickerCellTriggerSlot>()\n\nconst kbd = useKbd()\nconst rootContext = injectMonthRangePickerRootContext()\n\nconst { primitiveElement } = usePrimitiveElement()\n\nconst shortMonthValue = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.custom(toDate(props.month), { month: 'short' })\n})\n\nconst labelText = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.custom(toDate(props.month), { month: 'long', year: 'numeric' })\n})\n\nconst isUnavailable = computed(() => rootContext.isMonthUnavailable?.(props.month) ?? false)\n\nconst isCurrentMonth = computed(() => {\n  const todayDate = toCalendar(today(getLocalTimeZone()), props.month.calendar)\n  return isSameYearMonth(props.month, todayDate)\n})\n\nconst isDisabled = computed(() => rootContext.isMonthDisabled(props.month))\n\nconst isFocusedMonth = computed(() => {\n  return !rootContext.disabled.value && isSameYearMonth(props.month, rootContext.placeholder.value)\n})\n\nconst isSelectedMonth = computed(() => rootContext.isSelected(props.month))\nconst isSelectionStart = computed(() => rootContext.isSelectionStart(props.month))\nconst isSelectionEnd = computed(() => rootContext.isSelectionEnd(props.month))\nconst isHighlightStart = computed(() => rootContext.isHighlightedStart(props.month))\nconst isHighlightEnd = computed(() => rootContext.isHighlightedEnd(props.month))\nconst isHighlighted = computed(() => rootContext.highlightedRange.value\n  ? isMonthBetweenInclusive(props.month, rootContext.highlightedRange.value.start, rootContext.highlightedRange.value.end)\n  : false)\nconst allowNonContiguousRanges = computed(() => rootContext.allowNonContiguousRanges.value)\n\nfunction changeMonth(e: MouseEvent | KeyboardEvent, date: DateValue) {\n  if (rootContext.readonly.value)\n    return\n  if (rootContext.isMonthDisabled(date) || rootContext.isMonthUnavailable?.(date))\n    return\n\n  if (rootContext.startValue.value && rootContext.highlightedRange.value === null) {\n    if (isSameYearMonth(date, rootContext.startValue.value) && !rootContext.preventDeselect.value && !rootContext.endValue.value) {\n      rootContext.startValue.value = undefined\n      rootContext.onPlaceholderChange(date)\n      rootContext.lastPressedDateValue.value = date.copy()\n      return\n    }\n    else if (!rootContext.endValue.value) {\n      e.preventDefault()\n      if (rootContext.lastPressedDateValue.value && isSameYearMonth(rootContext.lastPressedDateValue.value, date))\n        rootContext.startValue.value = date.copy()\n      rootContext.lastPressedDateValue.value = date.copy()\n      return\n    }\n  }\n\n  rootContext.lastPressedDateValue.value = date.copy()\n\n  if (\n    rootContext.startValue.value\n    && rootContext.endValue.value\n    && isSameYearMonth(rootContext.startValue.value, rootContext.endValue.value)\n    && isSameYearMonth(rootContext.startValue.value, date)\n    && !rootContext.preventDeselect.value\n  ) {\n    rootContext.startValue.value = undefined\n    rootContext.endValue.value = undefined\n    rootContext.onPlaceholderChange(date)\n    return\n  }\n\n  if (!rootContext.startValue.value) {\n    rootContext.startValue.value = date.copy()\n  }\n  else if (!rootContext.endValue.value) {\n    rootContext.endValue.value = date.copy()\n  }\n  else if (rootContext.endValue.value && rootContext.startValue.value) {\n    if (!rootContext.fixedDate.value) {\n      rootContext.endValue.value = undefined\n      rootContext.startValue.value = date.copy()\n    }\n    else if (rootContext.fixedDate.value === 'start') {\n      if (date.compare(rootContext.startValue.value) < 0) {\n        rootContext.startValue.value = date.copy()\n      }\n      else {\n        rootContext.endValue.value = date.copy()\n      }\n    }\n    else if (rootContext.fixedDate.value === 'end') {\n      if (date.compare(rootContext.endValue.value) > 0) {\n        rootContext.endValue.value = date.copy()\n      }\n      else {\n        rootContext.startValue.value = date.copy()\n      }\n    }\n  }\n}\n\nfunction handleClick(e: MouseEvent) {\n  if (isDisabled.value)\n    return\n  changeMonth(e, props.month)\n}\n\nfunction handleFocus() {\n  if (isDisabled.value || rootContext.isMonthUnavailable?.(props.month))\n    return\n  rootContext.focusedValue.value = props.month.copy()\n}\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  if (isDisabled.value)\n    return\n  e.preventDefault()\n  e.stopPropagation()\n  const parentElement = rootContext.parentElement.value!\n  const sign = rootContext.dir.value === 'rtl' ? -1 : 1\n\n  switch (e.code) {\n    case kbd.ARROW_RIGHT:\n      shiftFocus(props.month, sign)\n      break\n    case kbd.ARROW_LEFT:\n      shiftFocus(props.month, -sign)\n      break\n    case kbd.ARROW_UP:\n      shiftFocus(props.month, -4)\n      break\n    case kbd.ARROW_DOWN:\n      shiftFocus(props.month, 4)\n      break\n    case kbd.PAGE_UP:\n      shiftFocusYear(-1)\n      break\n    case kbd.PAGE_DOWN:\n      shiftFocusYear(1)\n      break\n    case kbd.ENTER:\n    case kbd.SPACE_CODE:\n      changeMonth(e, props.month)\n  }\n\n  function shiftFocus(currentMonth: DateValue, add: number, depth = 0) {\n    if (depth > 48)\n      return\n    const candidateMonthValue = currentMonth.add({ months: add })\n\n    if ((rootContext.minValue.value && endOfMonth(candidateMonthValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && candidateMonthValue.set({ day: 1 }).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    const candidateMonth = parentElement.querySelector<HTMLElement>(`[data-value='${candidateMonthValue.toString()}']`)\n\n    if (!candidateMonth) {\n      if (add > 0) {\n        if (rootContext.isNextButtonDisabled())\n          return\n        rootContext.nextPage()\n      }\n      else {\n        if (rootContext.isPrevButtonDisabled())\n          return\n        rootContext.prevPage()\n      }\n      nextTick(() => {\n        shiftFocus(currentMonth, add, depth + 1)\n      })\n      return\n    }\n\n    if (candidateMonth && candidateMonth.hasAttribute('data-disabled'))\n      return shiftFocus(candidateMonthValue, add, depth + 1)\n\n    rootContext.onPlaceholderChange(candidateMonthValue)\n    candidateMonth?.focus()\n  }\n\n  function shiftFocusYear(years: number) {\n    const candidateMonthValue = props.month.add({ years })\n\n    if ((rootContext.minValue.value && endOfMonth(candidateMonthValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && candidateMonthValue.set({ day: 1 }).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    if (years > 0) {\n      if (rootContext.isNextButtonDisabled())\n        return\n      rootContext.nextPage()\n    }\n    else {\n      if (rootContext.isPrevButtonDisabled())\n        return\n      rootContext.prevPage()\n    }\n\n    nextTick(() => {\n      const candidateMonth = parentElement.querySelector<HTMLElement>(`[data-value='${candidateMonthValue.toString()}']`)\n      if (candidateMonth && !candidateMonth.hasAttribute('data-disabled')) {\n        rootContext.onPlaceholderChange(candidateMonthValue)\n        candidateMonth?.focus()\n        return\n      }\n\n      shiftFocus(candidateMonthValue, years > 0 ? 1 : -1, 1)\n    })\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    role=\"button\"\n    :aria-label=\"labelText\"\n    data-reka-month-range-picker-cell-trigger\n    :aria-pressed=\"isSelectedMonth && (allowNonContiguousRanges || !isUnavailable) ? true : undefined\"\n    :aria-disabled=\"isDisabled || isUnavailable ? true : undefined\"\n    :data-highlighted=\"isHighlighted && (allowNonContiguousRanges || !isUnavailable) ? '' : undefined\"\n    :data-selection-start=\"isSelectionStart ? true : undefined\"\n    :data-selection-end=\"isSelectionEnd ? true : undefined\"\n    :data-highlighted-start=\"isHighlightStart ? true : undefined\"\n    :data-highlighted-end=\"isHighlightEnd ? true : undefined\"\n    :data-selected=\"isSelectedMonth && (allowNonContiguousRanges || !isUnavailable) ? true : undefined\"\n    :data-value=\"month.toString()\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-unavailable=\"isUnavailable ? '' : undefined\"\n    :data-today=\"isCurrentMonth ? '' : undefined\"\n    :data-focused=\"isFocusedMonth ? '' : undefined\"\n    :tabindex=\"isFocusedMonth ? 0 : isDisabled ? undefined : -1\"\n    @click=\"handleClick\"\n    @focusin=\"handleFocus\"\n    @mouseenter=\"handleFocus\"\n    @keydown.up.down.left.right.space.enter.page-up.page-down=\"handleArrowKey\"\n    @keydown.enter.prevent\n  >\n    <slot\n      :month-value=\"shortMonthValue\"\n      :disabled=\"isDisabled\"\n      :today=\"isCurrentMonth\"\n      :selected=\"isSelectedMonth\"\n      :unavailable=\"isUnavailable\"\n      :highlighted=\"isHighlighted && (allowNonContiguousRanges || !isUnavailable)\"\n      :highlighted-start=\"isHighlightStart\"\n      :highlighted-end=\"isHighlightEnd\"\n      :selection-start=\"isSelectionStart\"\n      :selection-end=\"isSelectionEnd\"\n    >\n      {{ shortMonthValue }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerGridProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectMonthRangePickerRootContext } from './MonthRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthRangePickerGridProps>(), { as: 'table' })\n\nconst rootContext = injectMonthRangePickerRootContext()\nconst disabled = computed(() => rootContext.disabled.value ? true : undefined)\nconst readonly = computed(() => rootContext.readonly.value ? true : undefined)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    role=\"application\"\n    :aria-labelledby=\"rootContext.headingId\"\n    :aria-readonly=\"readonly\"\n    :aria-disabled=\"disabled\"\n    :data-readonly=\"readonly && ''\"\n    :data-disabled=\"disabled && ''\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerGridProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectMonthRangePickerRootContext } from './MonthRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthRangePickerGridProps>(), { as: 'table' })\n\nconst rootContext = injectMonthRangePickerRootContext()\nconst disabled = computed(() => rootContext.disabled.value ? true : undefined)\nconst readonly = computed(() => rootContext.readonly.value ? true : undefined)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    role=\"application\"\n    :aria-labelledby=\"rootContext.headingId\"\n    :aria-readonly=\"readonly\"\n    :aria-disabled=\"disabled\"\n    :data-readonly=\"readonly && ''\"\n    :data-disabled=\"disabled && ''\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerGridBodyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthRangePickerGridBodyProps>(), { as: 'tbody' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerGridBodyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthRangePickerGridBodyProps>(), { as: 'tbody' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerGridRowProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthRangePickerGridRowProps>(), { as: 'tr' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    role=\"row\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerGridRowProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthRangePickerGridRowProps>(), { as: 'tr' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    role=\"row\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthRangePickerHeaderProps>(), { as: 'div' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<MonthRangePickerHeaderProps>(), { as: 'div' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerHeadingProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectMonthRangePickerRootContext } from './MonthRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthRangePickerHeadingProps>(), { as: 'div' })\n\ndefineSlots<{\n  default?: (props: {\n    /** Current year heading */\n    headingValue: string\n  }) => any\n}>()\n\nconst rootContext = injectMonthRangePickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.headingId\"\n    role=\"heading\"\n    aria-level=\"2\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n  >\n    <slot :heading-value=\"rootContext.headingValue.value\">\n      {{ rootContext.headingValue.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerHeadingProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectMonthRangePickerRootContext } from './MonthRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthRangePickerHeadingProps>(), { as: 'div' })\n\ndefineSlots<{\n  default?: (props: {\n    /** Current year heading */\n    headingValue: string\n  }) => any\n}>()\n\nconst rootContext = injectMonthRangePickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.headingId\"\n    role=\"heading\"\n    aria-level=\"2\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n  >\n    <slot :heading-value=\"rootContext.headingValue.value\">\n      {{ rootContext.headingValue.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerNextProps extends PrimitiveProps {\n  /** The function to be used for the next page. Overwrites the `nextPage` function set on the Root. */\n  nextPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface MonthRangePickerNextSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectMonthRangePickerRootContext } from './MonthRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthRangePickerNextProps>(), { as: 'button' })\ndefineSlots<MonthRangePickerNextSlot>()\n\nconst rootContext = injectMonthRangePickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isNextButtonDisabled(props.nextPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.nextPage(props.nextPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Next year\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Next year\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerNextProps extends PrimitiveProps {\n  /** The function to be used for the next page. Overwrites the `nextPage` function set on the Root. */\n  nextPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface MonthRangePickerNextSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectMonthRangePickerRootContext } from './MonthRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthRangePickerNextProps>(), { as: 'button' })\ndefineSlots<MonthRangePickerNextSlot>()\n\nconst rootContext = injectMonthRangePickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isNextButtonDisabled(props.nextPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.nextPage(props.nextPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Next year\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Next year\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerPrevProps extends PrimitiveProps {\n  /** The function to be used for the prev page. Overwrites the `prevPage` function set on the Root. */\n  prevPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface MonthRangePickerPrevSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectMonthRangePickerRootContext } from './MonthRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthRangePickerPrevProps>(), { as: 'button' })\ndefineSlots<MonthRangePickerPrevSlot>()\n\nconst rootContext = injectMonthRangePickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isPrevButtonDisabled(props.prevPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.prevPage(props.prevPage)\n}\n</script>\n\n<template>\n  <Primitive\n    aria-label=\"Previous year\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Prev year\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface MonthRangePickerPrevProps extends PrimitiveProps {\n  /** The function to be used for the prev page. Overwrites the `prevPage` function set on the Root. */\n  prevPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface MonthRangePickerPrevSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectMonthRangePickerRootContext } from './MonthRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<MonthRangePickerPrevProps>(), { as: 'button' })\ndefineSlots<MonthRangePickerPrevSlot>()\n\nconst rootContext = injectMonthRangePickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isPrevButtonDisabled(props.prevPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.prevPage(props.prevPage)\n}\n</script>\n\n<template>\n  <Primitive\n    aria-label=\"Previous year\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Prev year\n    </slot>\n  </Primitive>\n</template>\n","import { getActiveElement } from '@/shared'\n\nexport type Orientation = 'vertical' | 'horizontal'\nexport type Direction = 'ltr' | 'rtl'\n\nexport function getOpenState(open: boolean) {\n  return open ? 'open' : 'closed'\n}\n\nexport function makeTriggerId(baseId: string, value: string) {\n  return `${baseId}-trigger-${value}`\n}\n\nexport function makeContentId(baseId: string, value: string) {\n  return `${baseId}-content-${value}`\n}\n\nexport const LINK_SELECT = 'navigationMenu.linkSelect'\nexport const EVENT_ROOT_CONTENT_DISMISS = 'navigationMenu.rootContentDismiss'\n\n/**\n * Returns a list of potential tabbable candidates.\n *\n * NOTE: This is only a close approximation. For example it doesn't take into account cases like when\n * elements are not visible. This cannot be worked out easily by just reading a property, but rather\n * necessitate runtime knowledge (computed styles, etc). We deal with these cases separately.\n *\n * See: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker\n * Credit: https://github.com/discord/focus-layers/blob/master/src/util/wrapFocus.tsx#L1\n */\nexport function getTabbableCandidates(container: HTMLElement) {\n  const nodes: HTMLElement[] = []\n  const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {\n    acceptNode: (node: any) => {\n      const isHiddenInput = node.tagName === 'INPUT' && node.type === 'hidden'\n      if (node.disabled || node.hidden || isHiddenInput)\n        return NodeFilter.FILTER_SKIP\n      // `.tabIndex` is not the same as the `tabindex` attribute. It works on the\n      // runtime's understanding of tabbability, so this automatically accounts\n      // for any kind of element that could be tabbed to.\n      return node.tabIndex >= 0\n        ? NodeFilter.FILTER_ACCEPT\n        : NodeFilter.FILTER_SKIP\n    },\n  })\n  while (walker.nextNode()) nodes.push(walker.currentNode as HTMLElement)\n  // we do not take into account the order of nodes with positive `tabIndex` as it\n  // hinders accessibility to have tab order different from visual order.\n  return nodes\n}\n\nexport function focusFirst(candidates: HTMLElement[]) {\n  const previouslyFocusedElement = getActiveElement()\n  return candidates.some((candidate) => {\n    // if focus is already where we want to go, we don't want to keep going through the candidates\n    if (candidate === previouslyFocusedElement)\n      return true\n    candidate.focus()\n    return getActiveElement() !== previouslyFocusedElement\n  })\n}\n\nexport function removeFromTabOrder(candidates: HTMLElement[]) {\n  candidates.forEach((candidate) => {\n    candidate.dataset.tabindex = candidate.getAttribute('tabindex') || ''\n    candidate.setAttribute('tabindex', '-1')\n  })\n  return () => {\n    candidates.forEach((candidate) => {\n      const prevTabIndex = candidate.dataset.tabindex as string\n      candidate.setAttribute('tabindex', prevTabIndex)\n    })\n  }\n}\n\nexport function whenMouse<E extends PointerEvent>(handler: (event?: E) => void) {\n  return (event: E) => (event.pointerType === 'mouse' ? handler(event) : undefined)\n}\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\n\nimport type { Direction, Orientation } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { createContext, useDirection, useForwardExpose, useId } from '@/shared'\nimport { EVENT_ROOT_CONTENT_DISMISS } from './utils'\n\nexport interface NavigationMenuRootProps extends PrimitiveProps {\n  /** The controlled value of the menu item to activate. Can be used as `v-model`. */\n  modelValue?: string\n  /**\n   * The value of the menu item that should be active when initially rendered.\n   *\n   * Use when you do not need to control the value state.\n   */\n  defaultValue?: string\n  /**\n   * The reading direction of the combobox when applicable.\n   *\n   *  If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode.\n   */\n  dir?: Direction\n  /** The orientation of the menu. */\n  orientation?: Orientation\n  /**\n   * The duration from when the pointer enters the trigger until the tooltip gets opened.\n   * @defaultValue 200\n   */\n  delayDuration?: number\n  /**\n   * How much time a user has to enter another trigger without incurring a delay again.\n   * @defaultValue 300\n   */\n  skipDelayDuration?: number\n\n  /**\n   * If `true`, menu cannot be open by click on trigger\n   * @defaultValue false\n   */\n  disableClickTrigger?: boolean\n  /**\n   * If `true`, menu cannot be open by hover on trigger\n   * @defaultValue false\n   */\n  disableHoverTrigger?: boolean\n  /**\n   * If `true`, menu will not close during pointer leave event\n   * @defaultValue false\n   */\n  disablePointerLeaveClose?: boolean\n\n  /**\n   * When `true`, the element will be unmounted on closed state.\n   *\n   * @defaultValue `true`\n   */\n  unmountOnHide?: boolean\n}\nexport type NavigationMenuRootEmits = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: string]\n}\n\nexport interface NavigationMenuContext {\n  isRootMenu: boolean\n  modelValue: Ref<string>\n  previousValue: Ref<string>\n  baseId: string\n  dir: Ref<Direction>\n  orientation: Orientation\n  disableClickTrigger: Ref<boolean>\n  disableHoverTrigger: Ref<boolean>\n  unmountOnHide: Ref<boolean>\n  rootNavigationMenu: Ref<HTMLElement | undefined>\n  activeTrigger: Ref<HTMLElement | undefined>\n  indicatorTrack: Ref<HTMLElement | undefined>\n  onIndicatorTrackChange: (indicatorTrack: HTMLElement | undefined) => void\n  viewport: Ref<HTMLElement | undefined>\n  onViewportChange: (viewport: HTMLElement | undefined) => void\n  onTriggerEnter: (itemValue: string) => void\n  onTriggerLeave: () => void\n  onContentEnter: (itemValue: string) => void\n  onContentLeave: () => void\n  onItemSelect: (itemValue: string) => void\n  onItemDismiss: () => void\n}\n\nexport const [injectNavigationMenuContext, provideNavigationMenuContext]\n  = createContext<NavigationMenuContext>(['NavigationMenuRoot', 'NavigationMenuSub'], 'NavigationMenuContext')\n</script>\n\n<script setup lang=\"ts\">\nimport { refAutoReset, useDebounceFn, useEventListener, useVModel } from '@vueuse/core'\nimport {\n  computed,\n  ref,\n  toRefs,\n  watchEffect,\n} from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\n\nconst props = withDefaults(defineProps<NavigationMenuRootProps>(), {\n  modelValue: undefined,\n  delayDuration: 200,\n  skipDelayDuration: 300,\n  orientation: 'horizontal',\n  disableClickTrigger: false,\n  disableHoverTrigger: false,\n  unmountOnHide: true,\n  as: 'nav',\n})\nconst emits = defineEmits<NavigationMenuRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? '',\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<string>\nconst previousValue = ref('')\n\nconst { forwardRef, currentElement: rootNavigationMenu } = useForwardExpose()\n\nconst indicatorTrack = ref<HTMLElement>()\nconst viewport = ref<HTMLElement>()\nconst activeTrigger = ref<HTMLElement>()\n\nconst { getItems, CollectionSlot } = useCollection({ key: 'NavigationMenu', isProvider: true })\n\nconst { delayDuration, skipDelayDuration, dir: propDir, disableClickTrigger, disableHoverTrigger, unmountOnHide } = toRefs(props)\nconst dir = useDirection(propDir)\n\nconst isDelaySkipped = refAutoReset(false, skipDelayDuration)\nconst skipNextClose = ref(false)\nconst computedDelay = computed(() => {\n  const isOpen = modelValue.value !== ''\n  if (isOpen || isDelaySkipped.value)\n    return 150 // 150ms for user to switch trigger or move into content view\n  else return delayDuration.value\n})\n\nconst debouncedFn = useDebounceFn((val?: string) => {\n  // passing `undefined` meant to reset the debounce timer\n  if (typeof val === 'string') {\n    if (val === '' && skipNextClose.value) {\n      skipNextClose.value = false\n      return\n    }\n    previousValue.value = modelValue.value\n    modelValue.value = val\n    if (val === '')\n      isDelaySkipped.value = true\n  }\n}, computedDelay)\n\nwatchEffect(() => {\n  if (!modelValue.value)\n    return\n\n  const items = getItems().map(i => i.ref)\n  activeTrigger.value = items.find(item =>\n    item.id.includes(modelValue.value),\n  )\n})\n\nuseEventListener(rootNavigationMenu, EVENT_ROOT_CONTENT_DISMISS, onItemDismiss)\n\nprovideNavigationMenuContext({\n  isRootMenu: true,\n  modelValue,\n  previousValue,\n  baseId: useId(undefined, 'reka-navigation-menu'),\n  disableClickTrigger,\n  disableHoverTrigger,\n  dir,\n  unmountOnHide,\n  orientation: props.orientation,\n  rootNavigationMenu,\n  indicatorTrack,\n  activeTrigger,\n  onIndicatorTrackChange: (val) => {\n    indicatorTrack.value = val\n  },\n  viewport,\n  onViewportChange: (val) => {\n    viewport.value = val\n  },\n  onTriggerEnter: (val) => {\n    if (modelValue.value !== '') {\n      skipNextClose.value = true\n      previousValue.value = modelValue.value\n      modelValue.value = val\n    }\n    else {\n      debouncedFn(val)\n    }\n  },\n  onTriggerLeave: () => {\n    skipNextClose.value = false\n    debouncedFn('')\n  },\n  onContentEnter: () => {\n    debouncedFn()\n  },\n  onContentLeave: () => {\n    if (!props.disablePointerLeaveClose) {\n      skipNextClose.value = false\n      debouncedFn('')\n    }\n  },\n  onItemSelect: (val) => {\n    // When selecting item we trigger update immediately\n    previousValue.value = modelValue.value\n    modelValue.value = val\n  },\n  onItemDismiss,\n})\n\nfunction onItemDismiss() {\n  previousValue.value = modelValue.value\n  modelValue.value = ''\n}\n</script>\n\n<template>\n  <CollectionSlot>\n    <Primitive\n      :ref=\"forwardRef\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :data-orientation=\"orientation\"\n      :dir=\"dir\"\n      data-reka-navigation-menu\n    >\n      <slot :model-value=\"modelValue\" />\n    </Primitive>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\n\nimport type { Direction, Orientation } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { createContext, useDirection, useForwardExpose, useId } from '@/shared'\nimport { EVENT_ROOT_CONTENT_DISMISS } from './utils'\n\nexport interface NavigationMenuRootProps extends PrimitiveProps {\n  /** The controlled value of the menu item to activate. Can be used as `v-model`. */\n  modelValue?: string\n  /**\n   * The value of the menu item that should be active when initially rendered.\n   *\n   * Use when you do not need to control the value state.\n   */\n  defaultValue?: string\n  /**\n   * The reading direction of the combobox when applicable.\n   *\n   *  If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode.\n   */\n  dir?: Direction\n  /** The orientation of the menu. */\n  orientation?: Orientation\n  /**\n   * The duration from when the pointer enters the trigger until the tooltip gets opened.\n   * @defaultValue 200\n   */\n  delayDuration?: number\n  /**\n   * How much time a user has to enter another trigger without incurring a delay again.\n   * @defaultValue 300\n   */\n  skipDelayDuration?: number\n\n  /**\n   * If `true`, menu cannot be open by click on trigger\n   * @defaultValue false\n   */\n  disableClickTrigger?: boolean\n  /**\n   * If `true`, menu cannot be open by hover on trigger\n   * @defaultValue false\n   */\n  disableHoverTrigger?: boolean\n  /**\n   * If `true`, menu will not close during pointer leave event\n   * @defaultValue false\n   */\n  disablePointerLeaveClose?: boolean\n\n  /**\n   * When `true`, the element will be unmounted on closed state.\n   *\n   * @defaultValue `true`\n   */\n  unmountOnHide?: boolean\n}\nexport type NavigationMenuRootEmits = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: string]\n}\n\nexport interface NavigationMenuContext {\n  isRootMenu: boolean\n  modelValue: Ref<string>\n  previousValue: Ref<string>\n  baseId: string\n  dir: Ref<Direction>\n  orientation: Orientation\n  disableClickTrigger: Ref<boolean>\n  disableHoverTrigger: Ref<boolean>\n  unmountOnHide: Ref<boolean>\n  rootNavigationMenu: Ref<HTMLElement | undefined>\n  activeTrigger: Ref<HTMLElement | undefined>\n  indicatorTrack: Ref<HTMLElement | undefined>\n  onIndicatorTrackChange: (indicatorTrack: HTMLElement | undefined) => void\n  viewport: Ref<HTMLElement | undefined>\n  onViewportChange: (viewport: HTMLElement | undefined) => void\n  onTriggerEnter: (itemValue: string) => void\n  onTriggerLeave: () => void\n  onContentEnter: (itemValue: string) => void\n  onContentLeave: () => void\n  onItemSelect: (itemValue: string) => void\n  onItemDismiss: () => void\n}\n\nexport const [injectNavigationMenuContext, provideNavigationMenuContext]\n  = createContext<NavigationMenuContext>(['NavigationMenuRoot', 'NavigationMenuSub'], 'NavigationMenuContext')\n</script>\n\n<script setup lang=\"ts\">\nimport { refAutoReset, useDebounceFn, useEventListener, useVModel } from '@vueuse/core'\nimport {\n  computed,\n  ref,\n  toRefs,\n  watchEffect,\n} from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\n\nconst props = withDefaults(defineProps<NavigationMenuRootProps>(), {\n  modelValue: undefined,\n  delayDuration: 200,\n  skipDelayDuration: 300,\n  orientation: 'horizontal',\n  disableClickTrigger: false,\n  disableHoverTrigger: false,\n  unmountOnHide: true,\n  as: 'nav',\n})\nconst emits = defineEmits<NavigationMenuRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? '',\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<string>\nconst previousValue = ref('')\n\nconst { forwardRef, currentElement: rootNavigationMenu } = useForwardExpose()\n\nconst indicatorTrack = ref<HTMLElement>()\nconst viewport = ref<HTMLElement>()\nconst activeTrigger = ref<HTMLElement>()\n\nconst { getItems, CollectionSlot } = useCollection({ key: 'NavigationMenu', isProvider: true })\n\nconst { delayDuration, skipDelayDuration, dir: propDir, disableClickTrigger, disableHoverTrigger, unmountOnHide } = toRefs(props)\nconst dir = useDirection(propDir)\n\nconst isDelaySkipped = refAutoReset(false, skipDelayDuration)\nconst skipNextClose = ref(false)\nconst computedDelay = computed(() => {\n  const isOpen = modelValue.value !== ''\n  if (isOpen || isDelaySkipped.value)\n    return 150 // 150ms for user to switch trigger or move into content view\n  else return delayDuration.value\n})\n\nconst debouncedFn = useDebounceFn((val?: string) => {\n  // passing `undefined` meant to reset the debounce timer\n  if (typeof val === 'string') {\n    if (val === '' && skipNextClose.value) {\n      skipNextClose.value = false\n      return\n    }\n    previousValue.value = modelValue.value\n    modelValue.value = val\n    if (val === '')\n      isDelaySkipped.value = true\n  }\n}, computedDelay)\n\nwatchEffect(() => {\n  if (!modelValue.value)\n    return\n\n  const items = getItems().map(i => i.ref)\n  activeTrigger.value = items.find(item =>\n    item.id.includes(modelValue.value),\n  )\n})\n\nuseEventListener(rootNavigationMenu, EVENT_ROOT_CONTENT_DISMISS, onItemDismiss)\n\nprovideNavigationMenuContext({\n  isRootMenu: true,\n  modelValue,\n  previousValue,\n  baseId: useId(undefined, 'reka-navigation-menu'),\n  disableClickTrigger,\n  disableHoverTrigger,\n  dir,\n  unmountOnHide,\n  orientation: props.orientation,\n  rootNavigationMenu,\n  indicatorTrack,\n  activeTrigger,\n  onIndicatorTrackChange: (val) => {\n    indicatorTrack.value = val\n  },\n  viewport,\n  onViewportChange: (val) => {\n    viewport.value = val\n  },\n  onTriggerEnter: (val) => {\n    if (modelValue.value !== '') {\n      skipNextClose.value = true\n      previousValue.value = modelValue.value\n      modelValue.value = val\n    }\n    else {\n      debouncedFn(val)\n    }\n  },\n  onTriggerLeave: () => {\n    skipNextClose.value = false\n    debouncedFn('')\n  },\n  onContentEnter: () => {\n    debouncedFn()\n  },\n  onContentLeave: () => {\n    if (!props.disablePointerLeaveClose) {\n      skipNextClose.value = false\n      debouncedFn('')\n    }\n  },\n  onItemSelect: (val) => {\n    // When selecting item we trigger update immediately\n    previousValue.value = modelValue.value\n    modelValue.value = val\n  },\n  onItemDismiss,\n})\n\nfunction onItemDismiss() {\n  previousValue.value = modelValue.value\n  modelValue.value = ''\n}\n</script>\n\n<template>\n  <CollectionSlot>\n    <Primitive\n      :ref=\"forwardRef\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :data-orientation=\"orientation\"\n      :dir=\"dir\"\n      data-reka-navigation-menu\n    >\n      <slot :model-value=\"modelValue\" />\n    </Primitive>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { createContext, getActiveElement, useArrowNavigation, useForwardExpose, useId } from '@/shared'\n\nexport interface NavigationMenuItemProps extends PrimitiveProps {\n  /**\n   * A unique value that associates the item with an active value when the navigation menu is controlled.\n   *\n   *  This prop is managed automatically when uncontrolled.\n   */\n  value?: string\n}\n\nexport type NavigationMenuItemContext = {\n  value: string\n  contentId: string\n  triggerRef: Ref<HTMLElement | undefined>\n  focusProxyRef: Ref<HTMLElement | undefined>\n  wasEscapeCloseRef: Ref<boolean>\n  onEntryKeyDown: () => void\n  onFocusProxyEnter: (side: 'start' | 'end') => void\n  onContentFocusOutside: () => void\n  onRootContentClose: () => void\n}\n\nexport const [injectNavigationMenuItemContext, provideNavigationMenuItemContext]\n  = createContext<NavigationMenuItemContext>('NavigationMenuItem')\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\nimport {\n  focusFirst,\n  getTabbableCandidates,\n  makeContentId,\n  removeFromTabOrder,\n} from './utils'\n\nconst props = withDefaults(defineProps<NavigationMenuItemProps>(), {\n  as: 'li',\n})\n\nuseForwardExpose()\nconst { getItems } = useCollection({ key: 'NavigationMenu' })\n\nconst context = injectNavigationMenuContext()\n\nconst value = useId(props.value)\nconst triggerRef = ref<HTMLElement>()\nconst focusProxyRef = ref<HTMLElement>()\n\nconst contentId = makeContentId(context.baseId, value)\n\nlet restoreContentTabOrderRef: () => void = () => ({})\n\nconst wasEscapeCloseRef = ref(false)\nasync function handleContentEntry(side = 'start') {\n  const el = document.getElementById(contentId)\n  if (el) {\n    restoreContentTabOrderRef()\n    const candidates = getTabbableCandidates(el)\n    if (candidates.length)\n      focusFirst(side === 'start' ? candidates : candidates.reverse())\n  }\n}\n\nfunction handleContentExit() {\n  const el = document.getElementById(contentId)\n  if (el) {\n    const candidates = getTabbableCandidates(el)\n    if (candidates.length)\n      restoreContentTabOrderRef = removeFromTabOrder(candidates)\n  }\n}\n\nprovideNavigationMenuItemContext({\n  value,\n  contentId,\n  triggerRef,\n  focusProxyRef,\n  wasEscapeCloseRef,\n  onEntryKeyDown: handleContentEntry,\n  onFocusProxyEnter: handleContentEntry,\n  onContentFocusOutside: handleContentExit,\n  onRootContentClose: handleContentExit,\n})\n\nfunction handleClose() {\n  context.onItemDismiss()\n  triggerRef.value?.focus()\n}\n\nfunction handleKeydown(ev: KeyboardEvent) {\n  const currentFocus = getActiveElement() as HTMLElement\n  if (ev.keyCode === 32 || ev.key === 'Enter') {\n    if (context.modelValue.value === value) {\n      handleClose()\n      ev.preventDefault()\n      return\n    }\n    else {\n      (ev.target as HTMLElement).click()\n      ev.preventDefault()\n      return\n    }\n  }\n\n  const itemsArray = getItems().filter(i =>\n    i.ref.parentElement?.hasAttribute('data-menu-item'),\n  ).map(i => i.ref)\n\n  // prevent triggering when the focus is on link\n  if (!itemsArray.includes(currentFocus))\n    return\n\n  const newSelectedElement = useArrowNavigation(ev, currentFocus, undefined, {\n    itemsArray,\n    loop: false,\n  })\n\n  if (newSelectedElement)\n    newSelectedElement?.focus()\n\n  ev.preventDefault()\n  ev.stopPropagation()\n}\n</script>\n\n<template>\n  <Primitive\n    :as-child=\"asChild\"\n    :as=\"as\"\n    data-menu-item\n    @keydown.up.down.left.right.home.end.space=\"handleKeydown\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { createContext, getActiveElement, useArrowNavigation, useForwardExpose, useId } from '@/shared'\n\nexport interface NavigationMenuItemProps extends PrimitiveProps {\n  /**\n   * A unique value that associates the item with an active value when the navigation menu is controlled.\n   *\n   *  This prop is managed automatically when uncontrolled.\n   */\n  value?: string\n}\n\nexport type NavigationMenuItemContext = {\n  value: string\n  contentId: string\n  triggerRef: Ref<HTMLElement | undefined>\n  focusProxyRef: Ref<HTMLElement | undefined>\n  wasEscapeCloseRef: Ref<boolean>\n  onEntryKeyDown: () => void\n  onFocusProxyEnter: (side: 'start' | 'end') => void\n  onContentFocusOutside: () => void\n  onRootContentClose: () => void\n}\n\nexport const [injectNavigationMenuItemContext, provideNavigationMenuItemContext]\n  = createContext<NavigationMenuItemContext>('NavigationMenuItem')\n</script>\n\n<script setup lang=\"ts\">\nimport { ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\nimport {\n  focusFirst,\n  getTabbableCandidates,\n  makeContentId,\n  removeFromTabOrder,\n} from './utils'\n\nconst props = withDefaults(defineProps<NavigationMenuItemProps>(), {\n  as: 'li',\n})\n\nuseForwardExpose()\nconst { getItems } = useCollection({ key: 'NavigationMenu' })\n\nconst context = injectNavigationMenuContext()\n\nconst value = useId(props.value)\nconst triggerRef = ref<HTMLElement>()\nconst focusProxyRef = ref<HTMLElement>()\n\nconst contentId = makeContentId(context.baseId, value)\n\nlet restoreContentTabOrderRef: () => void = () => ({})\n\nconst wasEscapeCloseRef = ref(false)\nasync function handleContentEntry(side = 'start') {\n  const el = document.getElementById(contentId)\n  if (el) {\n    restoreContentTabOrderRef()\n    const candidates = getTabbableCandidates(el)\n    if (candidates.length)\n      focusFirst(side === 'start' ? candidates : candidates.reverse())\n  }\n}\n\nfunction handleContentExit() {\n  const el = document.getElementById(contentId)\n  if (el) {\n    const candidates = getTabbableCandidates(el)\n    if (candidates.length)\n      restoreContentTabOrderRef = removeFromTabOrder(candidates)\n  }\n}\n\nprovideNavigationMenuItemContext({\n  value,\n  contentId,\n  triggerRef,\n  focusProxyRef,\n  wasEscapeCloseRef,\n  onEntryKeyDown: handleContentEntry,\n  onFocusProxyEnter: handleContentEntry,\n  onContentFocusOutside: handleContentExit,\n  onRootContentClose: handleContentExit,\n})\n\nfunction handleClose() {\n  context.onItemDismiss()\n  triggerRef.value?.focus()\n}\n\nfunction handleKeydown(ev: KeyboardEvent) {\n  const currentFocus = getActiveElement() as HTMLElement\n  if (ev.keyCode === 32 || ev.key === 'Enter') {\n    if (context.modelValue.value === value) {\n      handleClose()\n      ev.preventDefault()\n      return\n    }\n    else {\n      (ev.target as HTMLElement).click()\n      ev.preventDefault()\n      return\n    }\n  }\n\n  const itemsArray = getItems().filter(i =>\n    i.ref.parentElement?.hasAttribute('data-menu-item'),\n  ).map(i => i.ref)\n\n  // prevent triggering when the focus is on link\n  if (!itemsArray.includes(currentFocus))\n    return\n\n  const newSelectedElement = useArrowNavigation(ev, currentFocus, undefined, {\n    itemsArray,\n    loop: false,\n  })\n\n  if (newSelectedElement)\n    newSelectedElement?.focus()\n\n  ev.preventDefault()\n  ev.stopPropagation()\n}\n</script>\n\n<template>\n  <Primitive\n    :as-child=\"asChild\"\n    :as=\"as\"\n    data-menu-item\n    @keydown.up.down.left.right.home.end.space=\"handleKeydown\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type {\n  DismissableLayerEmits,\n  DismissableLayerProps,\n  FocusOutsideEvent,\n} from '@/DismissableLayer'\nimport type { PointerDownOutsideEvent } from '@/DismissableLayer/utils'\nimport { useCollection } from '@/Collection'\n\ntype MotionAttribute = 'to-start' | 'to-end' | 'from-start' | 'from-end'\n\nexport type NavigationMenuContentImplEmits = DismissableLayerEmits\n\nexport interface NavigationMenuContentImplProps extends DismissableLayerProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, ref, watchEffect } from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { getActiveElement, useArrowNavigation, useForwardExpose } from '@/shared'\nimport { injectNavigationMenuItemContext } from './NavigationMenuItem.vue'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\nimport {\n  EVENT_ROOT_CONTENT_DISMISS,\n  focusFirst,\n  getOpenState,\n  getTabbableCandidates,\n  makeContentId,\n  makeTriggerId,\n} from './utils'\n\nconst props = defineProps<NavigationMenuContentImplProps>()\nconst emits = defineEmits<NavigationMenuContentImplEmits>()\n\nconst { getItems } = useCollection({ key: 'NavigationMenu' })\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst menuContext = injectNavigationMenuContext()\nconst itemContext = injectNavigationMenuItemContext()\n\nconst triggerId = makeTriggerId(menuContext.baseId, itemContext.value)\nconst contentId = makeContentId(menuContext.baseId, itemContext.value)\n\nconst prevMotionAttributeRef = ref<MotionAttribute | null>(null)\nconst motionAttribute = computed(() => {\n  const values = getItems().map(i => i.ref.id.split('trigger-')[1])\n  if (menuContext.dir.value === 'rtl')\n    values.reverse()\n  const index = values.indexOf(menuContext.modelValue.value)\n  const prevIndex = values.indexOf(menuContext.previousValue.value)\n  const isSelected = itemContext.value === menuContext.modelValue.value\n  const wasSelected = prevIndex === values.indexOf(itemContext.value)\n\n  // We only want to update selected and the last selected content\n  // this avoids animations being interrupted outside of that range\n  if (!isSelected && !wasSelected)\n    return prevMotionAttributeRef.value\n\n  const attribute = (() => {\n    // Don't provide a direction on the initial open\n    if (index !== prevIndex) {\n      // If we're moving to this item from another\n      if (isSelected && prevIndex !== -1)\n        return index > prevIndex ? 'from-end' : 'from-start'\n      // If we're leaving this item for another\n      if (wasSelected && index !== -1)\n        return index > prevIndex ? 'to-start' : 'to-end'\n    }\n    // Otherwise we're entering from closed or leaving the list\n    // entirely and should not animate in any direction\n    return null\n  })()\n\n  // eslint-disable-next-line vue/no-side-effects-in-computed-properties\n  prevMotionAttributeRef.value = attribute\n  return attribute\n})\n\nfunction handleFocusOutside(ev: FocusOutsideEvent) {\n  emits('focusOutside', ev)\n  emits('interactOutside', ev)\n\n  const target = ev.detail.originalEvent.target as HTMLElement\n  if (target.hasAttribute('data-navigation-menu-trigger'))\n    ev.preventDefault()\n\n  if (!ev.defaultPrevented) {\n    itemContext.onContentFocusOutside()\n\n    const target = ev.target as HTMLElement\n    // Only dismiss content when focus moves outside of the menu\n    if (menuContext.rootNavigationMenu?.value?.contains(target))\n      ev.preventDefault()\n  }\n}\n\nfunction handlePointerDownOutside(ev: PointerDownOutsideEvent) {\n  emits('pointerDownOutside', ev)\n\n  if (!ev.defaultPrevented) {\n    const target = ev.target as HTMLElement\n    const isTrigger = getItems().some(i =>\n      i.ref.contains(target),\n    )\n    const isRootViewport\n      = menuContext.isRootMenu && menuContext.viewport.value?.contains(target)\n\n    if (isTrigger || isRootViewport || !menuContext.isRootMenu)\n      ev.preventDefault()\n  }\n}\n\nwatchEffect((cleanupFn) => {\n  const content = currentElement.value\n  if (menuContext.isRootMenu && content) {\n    // Bubble dismiss to the root content node and focus its trigger\n    const handleClose = () => {\n      menuContext.onItemDismiss()\n      itemContext.onRootContentClose()\n      if (content.contains(getActiveElement()))\n        itemContext.triggerRef.value?.focus()\n    }\n    content.addEventListener(EVENT_ROOT_CONTENT_DISMISS, handleClose)\n\n    cleanupFn(() =>\n      content.removeEventListener(EVENT_ROOT_CONTENT_DISMISS, handleClose),\n    )\n  }\n})\n\nfunction handleEscapeKeyDown(ev: KeyboardEvent) {\n  emits('escapeKeyDown', ev)\n\n  if (!ev.defaultPrevented) {\n    menuContext.onItemDismiss()\n    itemContext.triggerRef?.value?.focus()\n    itemContext.wasEscapeCloseRef.value = true\n  }\n}\n\nfunction handleKeydown(ev: KeyboardEvent) {\n  // prevent parent menu triggering keydown event\n  if ((ev.target as HTMLElement).closest('[data-reka-navigation-menu]') !== menuContext.rootNavigationMenu.value)\n    return\n\n  const isMetaKey = ev.altKey || ev.ctrlKey || ev.metaKey\n  const isTabKey = ev.key === 'Tab' && !isMetaKey\n  const candidates = getTabbableCandidates(ev.currentTarget as HTMLElement)\n\n  if (isTabKey) {\n    const focusedElement = getActiveElement()\n    const index = candidates.findIndex(\n      candidate => candidate === focusedElement,\n    )\n    const isMovingBackwards = ev.shiftKey\n    const nextCandidates = isMovingBackwards\n      ? candidates.slice(0, index).reverse()\n      : candidates.slice(index + 1, candidates.length)\n\n    if (focusFirst(nextCandidates)) {\n      // prevent browser tab keydown because we've handled focus\n      ev.preventDefault()\n    }\n    else {\n      // If we can't focus that means we're at the edges\n      // so focus the proxy and let browser handle\n      // tab/shift+tab keypress on the proxy instead\n      itemContext.focusProxyRef.value?.focus()\n      return\n    }\n  }\n\n  const newSelectedElement = useArrowNavigation(\n    ev,\n    getActiveElement() as HTMLElement,\n    undefined,\n    { itemsArray: candidates, loop: false, enableIgnoredElement: true },\n  )\n  newSelectedElement?.focus()\n}\n\nfunction handleDismiss() {\n  if (menuContext.modelValue.value !== itemContext.value)\n    return\n\n  const rootContentDismissEvent = new Event(EVENT_ROOT_CONTENT_DISMISS, {\n    bubbles: true,\n    cancelable: true,\n  })\n  currentElement.value?.dispatchEvent(rootContentDismissEvent)\n}\n</script>\n\n<template>\n  <DismissableLayer\n    :id=\"contentId\"\n    :ref=\"forwardRef\"\n    :aria-labelledby=\"triggerId\"\n    :data-motion=\"motionAttribute\"\n    :data-state=\"getOpenState(menuContext.modelValue.value === itemContext.value)\"\n    :data-orientation=\"menuContext.orientation\"\n    v-bind=\"props\"\n    @keydown=\"handleKeydown\"\n    @escape-key-down=\"handleEscapeKeyDown\"\n    @pointer-down-outside=\"handlePointerDownOutside\"\n    @focus-outside=\"handleFocusOutside\"\n    @dismiss=\"handleDismiss\"\n  >\n    <slot />\n  </DismissableLayer>\n</template>\n","<script lang=\"ts\">\nimport type {\n  DismissableLayerEmits,\n  DismissableLayerProps,\n  FocusOutsideEvent,\n} from '@/DismissableLayer'\nimport type { PointerDownOutsideEvent } from '@/DismissableLayer/utils'\nimport { useCollection } from '@/Collection'\n\ntype MotionAttribute = 'to-start' | 'to-end' | 'from-start' | 'from-end'\n\nexport type NavigationMenuContentImplEmits = DismissableLayerEmits\n\nexport interface NavigationMenuContentImplProps extends DismissableLayerProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, ref, watchEffect } from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { getActiveElement, useArrowNavigation, useForwardExpose } from '@/shared'\nimport { injectNavigationMenuItemContext } from './NavigationMenuItem.vue'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\nimport {\n  EVENT_ROOT_CONTENT_DISMISS,\n  focusFirst,\n  getOpenState,\n  getTabbableCandidates,\n  makeContentId,\n  makeTriggerId,\n} from './utils'\n\nconst props = defineProps<NavigationMenuContentImplProps>()\nconst emits = defineEmits<NavigationMenuContentImplEmits>()\n\nconst { getItems } = useCollection({ key: 'NavigationMenu' })\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst menuContext = injectNavigationMenuContext()\nconst itemContext = injectNavigationMenuItemContext()\n\nconst triggerId = makeTriggerId(menuContext.baseId, itemContext.value)\nconst contentId = makeContentId(menuContext.baseId, itemContext.value)\n\nconst prevMotionAttributeRef = ref<MotionAttribute | null>(null)\nconst motionAttribute = computed(() => {\n  const values = getItems().map(i => i.ref.id.split('trigger-')[1])\n  if (menuContext.dir.value === 'rtl')\n    values.reverse()\n  const index = values.indexOf(menuContext.modelValue.value)\n  const prevIndex = values.indexOf(menuContext.previousValue.value)\n  const isSelected = itemContext.value === menuContext.modelValue.value\n  const wasSelected = prevIndex === values.indexOf(itemContext.value)\n\n  // We only want to update selected and the last selected content\n  // this avoids animations being interrupted outside of that range\n  if (!isSelected && !wasSelected)\n    return prevMotionAttributeRef.value\n\n  const attribute = (() => {\n    // Don't provide a direction on the initial open\n    if (index !== prevIndex) {\n      // If we're moving to this item from another\n      if (isSelected && prevIndex !== -1)\n        return index > prevIndex ? 'from-end' : 'from-start'\n      // If we're leaving this item for another\n      if (wasSelected && index !== -1)\n        return index > prevIndex ? 'to-start' : 'to-end'\n    }\n    // Otherwise we're entering from closed or leaving the list\n    // entirely and should not animate in any direction\n    return null\n  })()\n\n  // eslint-disable-next-line vue/no-side-effects-in-computed-properties\n  prevMotionAttributeRef.value = attribute\n  return attribute\n})\n\nfunction handleFocusOutside(ev: FocusOutsideEvent) {\n  emits('focusOutside', ev)\n  emits('interactOutside', ev)\n\n  const target = ev.detail.originalEvent.target as HTMLElement\n  if (target.hasAttribute('data-navigation-menu-trigger'))\n    ev.preventDefault()\n\n  if (!ev.defaultPrevented) {\n    itemContext.onContentFocusOutside()\n\n    const target = ev.target as HTMLElement\n    // Only dismiss content when focus moves outside of the menu\n    if (menuContext.rootNavigationMenu?.value?.contains(target))\n      ev.preventDefault()\n  }\n}\n\nfunction handlePointerDownOutside(ev: PointerDownOutsideEvent) {\n  emits('pointerDownOutside', ev)\n\n  if (!ev.defaultPrevented) {\n    const target = ev.target as HTMLElement\n    const isTrigger = getItems().some(i =>\n      i.ref.contains(target),\n    )\n    const isRootViewport\n      = menuContext.isRootMenu && menuContext.viewport.value?.contains(target)\n\n    if (isTrigger || isRootViewport || !menuContext.isRootMenu)\n      ev.preventDefault()\n  }\n}\n\nwatchEffect((cleanupFn) => {\n  const content = currentElement.value\n  if (menuContext.isRootMenu && content) {\n    // Bubble dismiss to the root content node and focus its trigger\n    const handleClose = () => {\n      menuContext.onItemDismiss()\n      itemContext.onRootContentClose()\n      if (content.contains(getActiveElement()))\n        itemContext.triggerRef.value?.focus()\n    }\n    content.addEventListener(EVENT_ROOT_CONTENT_DISMISS, handleClose)\n\n    cleanupFn(() =>\n      content.removeEventListener(EVENT_ROOT_CONTENT_DISMISS, handleClose),\n    )\n  }\n})\n\nfunction handleEscapeKeyDown(ev: KeyboardEvent) {\n  emits('escapeKeyDown', ev)\n\n  if (!ev.defaultPrevented) {\n    menuContext.onItemDismiss()\n    itemContext.triggerRef?.value?.focus()\n    itemContext.wasEscapeCloseRef.value = true\n  }\n}\n\nfunction handleKeydown(ev: KeyboardEvent) {\n  // prevent parent menu triggering keydown event\n  if ((ev.target as HTMLElement).closest('[data-reka-navigation-menu]') !== menuContext.rootNavigationMenu.value)\n    return\n\n  const isMetaKey = ev.altKey || ev.ctrlKey || ev.metaKey\n  const isTabKey = ev.key === 'Tab' && !isMetaKey\n  const candidates = getTabbableCandidates(ev.currentTarget as HTMLElement)\n\n  if (isTabKey) {\n    const focusedElement = getActiveElement()\n    const index = candidates.findIndex(\n      candidate => candidate === focusedElement,\n    )\n    const isMovingBackwards = ev.shiftKey\n    const nextCandidates = isMovingBackwards\n      ? candidates.slice(0, index).reverse()\n      : candidates.slice(index + 1, candidates.length)\n\n    if (focusFirst(nextCandidates)) {\n      // prevent browser tab keydown because we've handled focus\n      ev.preventDefault()\n    }\n    else {\n      // If we can't focus that means we're at the edges\n      // so focus the proxy and let browser handle\n      // tab/shift+tab keypress on the proxy instead\n      itemContext.focusProxyRef.value?.focus()\n      return\n    }\n  }\n\n  const newSelectedElement = useArrowNavigation(\n    ev,\n    getActiveElement() as HTMLElement,\n    undefined,\n    { itemsArray: candidates, loop: false, enableIgnoredElement: true },\n  )\n  newSelectedElement?.focus()\n}\n\nfunction handleDismiss() {\n  if (menuContext.modelValue.value !== itemContext.value)\n    return\n\n  const rootContentDismissEvent = new Event(EVENT_ROOT_CONTENT_DISMISS, {\n    bubbles: true,\n    cancelable: true,\n  })\n  currentElement.value?.dispatchEvent(rootContentDismissEvent)\n}\n</script>\n\n<template>\n  <DismissableLayer\n    :id=\"contentId\"\n    :ref=\"forwardRef\"\n    :aria-labelledby=\"triggerId\"\n    :data-motion=\"motionAttribute\"\n    :data-state=\"getOpenState(menuContext.modelValue.value === itemContext.value)\"\n    :data-orientation=\"menuContext.orientation\"\n    v-bind=\"props\"\n    @keydown=\"handleKeydown\"\n    @escape-key-down=\"handleEscapeKeyDown\"\n    @pointer-down-outside=\"handlePointerDownOutside\"\n    @focus-outside=\"handleFocusOutside\"\n    @dismiss=\"handleDismiss\"\n  >\n    <slot />\n  </DismissableLayer>\n</template>\n","<script lang=\"ts\">\nimport type { NavigationMenuContentImplEmits, NavigationMenuContentImplProps } from './NavigationMenuContentImpl.vue'\n\nexport type NavigationMenuContentEmits = NavigationMenuContentImplEmits\n\nexport interface NavigationMenuContentProps extends NavigationMenuContentImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { isClient, reactiveOmit } from '@vueuse/shared'\nimport { computed } from 'vue'\nimport { Presence } from '@/Presence'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\nimport NavigationMenuContentImpl from './NavigationMenuContentImpl.vue'\nimport { injectNavigationMenuItemContext } from './NavigationMenuItem.vue'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\nimport { getOpenState, whenMouse } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<NavigationMenuContentProps>()\nconst emits = defineEmits<NavigationMenuContentEmits>()\n\nconst forwarded = useForwardPropsEmits(reactiveOmit(props, 'forceMount'), emits)\nconst { forwardRef } = useForwardExpose()\n\nconst menuContext = injectNavigationMenuContext()\nconst itemContext = injectNavigationMenuItemContext()\n\nconst open = computed(() => itemContext.value === menuContext.modelValue.value)\n\n// We persist the last active content value as the viewport may be animating out\n// and we want the content to remain mounted for the lifecycle of the viewport.\nconst isLastActiveValue = computed(() => {\n  if (menuContext.viewport.value) {\n    if (!menuContext.modelValue.value && menuContext.previousValue.value)\n      return (menuContext.previousValue.value === itemContext.value)\n  }\n  return false\n})\n</script>\n\n<template>\n  <Teleport\n    :to=\"isClient && menuContext.viewport.value ? menuContext.viewport.value : 'body'\"\n    :disabled=\"isClient && menuContext.viewport.value ? !menuContext.viewport.value : true\"\n  >\n    <Presence\n      v-slot=\"{ present }\"\n      :present=\"forceMount || open || isLastActiveValue\"\n      :force-mount=\"!menuContext.unmountOnHide.value\"\n    >\n      <NavigationMenuContentImpl\n        :ref=\"forwardRef\"\n        :data-state=\"getOpenState(open)\"\n        :style=\"{\n          pointerEvents: !open && menuContext.isRootMenu ? 'none' : undefined,\n        }\"\n        v-bind=\"{ ...$attrs, ...forwarded }\"\n        :hidden=\"!present\"\n        @pointerenter=\"menuContext.onContentEnter(itemContext.value)\"\n        @pointerleave=\"whenMouse(() => menuContext.onContentLeave())($event)\"\n        @pointer-down-outside=\"emits('pointerDownOutside', $event)\"\n        @focus-outside=\"emits('focusOutside', $event)\"\n        @interact-outside=\"emits('interactOutside', $event)\"\n      >\n        <slot />\n      </NavigationMenuContentImpl>\n    </Presence>\n  </Teleport>\n</template>\n","<script lang=\"ts\">\nimport type { NavigationMenuContentImplEmits, NavigationMenuContentImplProps } from './NavigationMenuContentImpl.vue'\n\nexport type NavigationMenuContentEmits = NavigationMenuContentImplEmits\n\nexport interface NavigationMenuContentProps extends NavigationMenuContentImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { isClient, reactiveOmit } from '@vueuse/shared'\nimport { computed } from 'vue'\nimport { Presence } from '@/Presence'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\nimport NavigationMenuContentImpl from './NavigationMenuContentImpl.vue'\nimport { injectNavigationMenuItemContext } from './NavigationMenuItem.vue'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\nimport { getOpenState, whenMouse } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<NavigationMenuContentProps>()\nconst emits = defineEmits<NavigationMenuContentEmits>()\n\nconst forwarded = useForwardPropsEmits(reactiveOmit(props, 'forceMount'), emits)\nconst { forwardRef } = useForwardExpose()\n\nconst menuContext = injectNavigationMenuContext()\nconst itemContext = injectNavigationMenuItemContext()\n\nconst open = computed(() => itemContext.value === menuContext.modelValue.value)\n\n// We persist the last active content value as the viewport may be animating out\n// and we want the content to remain mounted for the lifecycle of the viewport.\nconst isLastActiveValue = computed(() => {\n  if (menuContext.viewport.value) {\n    if (!menuContext.modelValue.value && menuContext.previousValue.value)\n      return (menuContext.previousValue.value === itemContext.value)\n  }\n  return false\n})\n</script>\n\n<template>\n  <Teleport\n    :to=\"isClient && menuContext.viewport.value ? menuContext.viewport.value : 'body'\"\n    :disabled=\"isClient && menuContext.viewport.value ? !menuContext.viewport.value : true\"\n  >\n    <Presence\n      v-slot=\"{ present }\"\n      :present=\"forceMount || open || isLastActiveValue\"\n      :force-mount=\"!menuContext.unmountOnHide.value\"\n    >\n      <NavigationMenuContentImpl\n        :ref=\"forwardRef\"\n        :data-state=\"getOpenState(open)\"\n        :style=\"{\n          pointerEvents: !open && menuContext.isRootMenu ? 'none' : undefined,\n        }\"\n        v-bind=\"{ ...$attrs, ...forwarded }\"\n        :hidden=\"!present\"\n        @pointerenter=\"menuContext.onContentEnter(itemContext.value)\"\n        @pointerleave=\"whenMouse(() => menuContext.onContentLeave())($event)\"\n        @pointer-down-outside=\"emits('pointerDownOutside', $event)\"\n        @focus-outside=\"emits('focusOutside', $event)\"\n        @interact-outside=\"emits('interactOutside', $event)\"\n      >\n        <slot />\n      </NavigationMenuContentImpl>\n    </Presence>\n  </Teleport>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface NavigationMenuIndicatorProps extends PrimitiveProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useResizeObserver } from '@vueuse/core'\nimport { computed, ref, watchEffect } from 'vue'\nimport { Presence } from '@/Presence'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<NavigationMenuIndicatorProps>()\n\nconst { forwardRef } = useForwardExpose()\nconst menuContext = injectNavigationMenuContext()\n\nconst indicatorStyle = ref<{ size: number, position: number }>()\nconst isHorizontal = computed(() => menuContext.orientation === 'horizontal')\nconst isVisible = computed(() => !!menuContext.modelValue.value)\nconst { activeTrigger } = menuContext\n\nfunction handlePositionChange() {\n  if (!activeTrigger.value) {\n    return\n  }\n\n  indicatorStyle.value = {\n    size: isHorizontal.value\n      ? activeTrigger.value.offsetWidth\n      : activeTrigger.value.offsetHeight,\n    position: isHorizontal.value\n      ? activeTrigger.value.offsetLeft\n      : activeTrigger.value.offsetTop,\n  }\n}\n\nwatchEffect(() => {\n  if (!menuContext.modelValue.value) {\n    return\n  }\n  handlePositionChange()\n})\n\nuseResizeObserver(activeTrigger, handlePositionChange)\nuseResizeObserver(menuContext.indicatorTrack, handlePositionChange)\n</script>\n\n<template>\n  <Teleport\n    v-if=\"menuContext.indicatorTrack.value\"\n    :to=\"menuContext.indicatorTrack.value\"\n  >\n    <Presence :present=\"forceMount || isVisible\">\n      <Primitive\n        :ref=\"forwardRef\"\n        aria-hidden=\"true\"\n        :data-state=\"isVisible ? 'visible' : 'hidden'\"\n        :data-orientation=\"menuContext.orientation\"\n        :as-child=\"props.asChild\"\n        :as=\"as\"\n        :style=\"{\n          ...(indicatorStyle ? {\n            '--reka-navigation-menu-indicator-size': `${indicatorStyle.size}px`,\n            '--reka-navigation-menu-indicator-position': `${indicatorStyle.position}px`,\n          } : {}),\n        }\"\n        v-bind=\"$attrs\"\n      >\n        <slot />\n      </Primitive>\n    </Presence>\n  </Teleport>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface NavigationMenuIndicatorProps extends PrimitiveProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useResizeObserver } from '@vueuse/core'\nimport { computed, ref, watchEffect } from 'vue'\nimport { Presence } from '@/Presence'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<NavigationMenuIndicatorProps>()\n\nconst { forwardRef } = useForwardExpose()\nconst menuContext = injectNavigationMenuContext()\n\nconst indicatorStyle = ref<{ size: number, position: number }>()\nconst isHorizontal = computed(() => menuContext.orientation === 'horizontal')\nconst isVisible = computed(() => !!menuContext.modelValue.value)\nconst { activeTrigger } = menuContext\n\nfunction handlePositionChange() {\n  if (!activeTrigger.value) {\n    return\n  }\n\n  indicatorStyle.value = {\n    size: isHorizontal.value\n      ? activeTrigger.value.offsetWidth\n      : activeTrigger.value.offsetHeight,\n    position: isHorizontal.value\n      ? activeTrigger.value.offsetLeft\n      : activeTrigger.value.offsetTop,\n  }\n}\n\nwatchEffect(() => {\n  if (!menuContext.modelValue.value) {\n    return\n  }\n  handlePositionChange()\n})\n\nuseResizeObserver(activeTrigger, handlePositionChange)\nuseResizeObserver(menuContext.indicatorTrack, handlePositionChange)\n</script>\n\n<template>\n  <Teleport\n    v-if=\"menuContext.indicatorTrack.value\"\n    :to=\"menuContext.indicatorTrack.value\"\n  >\n    <Presence :present=\"forceMount || isVisible\">\n      <Primitive\n        :ref=\"forwardRef\"\n        aria-hidden=\"true\"\n        :data-state=\"isVisible ? 'visible' : 'hidden'\"\n        :data-orientation=\"menuContext.orientation\"\n        :as-child=\"props.asChild\"\n        :as=\"as\"\n        :style=\"{\n          ...(indicatorStyle ? {\n            '--reka-navigation-menu-indicator-size': `${indicatorStyle.size}px`,\n            '--reka-navigation-menu-indicator-position': `${indicatorStyle.position}px`,\n          } : {}),\n        }\"\n        v-bind=\"$attrs\"\n      >\n        <slot />\n      </Primitive>\n    </Presence>\n  </Teleport>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { useForwardExpose } from '@/shared'\n\nexport type NavigationMenuLinkEmits = {\n  /**\n   * Event handler called when the user selects a link (via mouse or keyboard).\n   *\n   * Calling `event.preventDefault` in this handler will prevent the navigation menu from closing when selecting that link.\n   */\n  select: [payload: CustomEvent<{ originalEvent: Event }>]\n}\nexport interface NavigationMenuLinkProps extends PrimitiveProps {\n  /** Used to identify the link as the currently active page. */\n  active?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { EVENT_ROOT_CONTENT_DISMISS, LINK_SELECT } from './utils'\n\nconst props = withDefaults(defineProps<NavigationMenuLinkProps>(), {\n  as: 'a',\n})\n\nconst emits = defineEmits<NavigationMenuLinkEmits>()\n\nconst { CollectionItem } = useCollection({ key: 'NavigationMenu' })\nuseForwardExpose()\n\nasync function handleClick(ev: MouseEvent) {\n  const linkSelectEvent = new CustomEvent(LINK_SELECT, {\n    bubbles: true,\n    cancelable: true,\n    detail: {\n      originalEvent: ev,\n    },\n  })\n  emits('select', linkSelectEvent)\n\n  if (!linkSelectEvent.defaultPrevented && !ev.metaKey) {\n    const rootContentDismissEvent = new CustomEvent(\n      EVENT_ROOT_CONTENT_DISMISS,\n      {\n        bubbles: true,\n        cancelable: true,\n      },\n    )\n    ev.target?.dispatchEvent(rootContentDismissEvent)\n  }\n}\n</script>\n\n<template>\n  <CollectionItem>\n    <Primitive\n      :as=\"as\"\n      :data-active=\"active ? '' : undefined\"\n      :aria-current=\"active ? 'page' : undefined\"\n      :as-child=\"props.asChild\"\n      @click=\"handleClick\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { useForwardExpose } from '@/shared'\n\nexport type NavigationMenuLinkEmits = {\n  /**\n   * Event handler called when the user selects a link (via mouse or keyboard).\n   *\n   * Calling `event.preventDefault` in this handler will prevent the navigation menu from closing when selecting that link.\n   */\n  select: [payload: CustomEvent<{ originalEvent: Event }>]\n}\nexport interface NavigationMenuLinkProps extends PrimitiveProps {\n  /** Used to identify the link as the currently active page. */\n  active?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { EVENT_ROOT_CONTENT_DISMISS, LINK_SELECT } from './utils'\n\nconst props = withDefaults(defineProps<NavigationMenuLinkProps>(), {\n  as: 'a',\n})\n\nconst emits = defineEmits<NavigationMenuLinkEmits>()\n\nconst { CollectionItem } = useCollection({ key: 'NavigationMenu' })\nuseForwardExpose()\n\nasync function handleClick(ev: MouseEvent) {\n  const linkSelectEvent = new CustomEvent(LINK_SELECT, {\n    bubbles: true,\n    cancelable: true,\n    detail: {\n      originalEvent: ev,\n    },\n  })\n  emits('select', linkSelectEvent)\n\n  if (!linkSelectEvent.defaultPrevented && !ev.metaKey) {\n    const rootContentDismissEvent = new CustomEvent(\n      EVENT_ROOT_CONTENT_DISMISS,\n      {\n        bubbles: true,\n        cancelable: true,\n      },\n    )\n    ev.target?.dispatchEvent(rootContentDismissEvent)\n  }\n}\n</script>\n\n<template>\n  <CollectionItem>\n    <Primitive\n      :as=\"as\"\n      :data-active=\"active ? '' : undefined\"\n      :aria-current=\"active ? 'page' : undefined\"\n      :as-child=\"props.asChild\"\n      @click=\"handleClick\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface NavigationMenuListProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted } from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<NavigationMenuListProps>(), {\n  as: 'ul',\n})\n\nconst menuContext = injectNavigationMenuContext()\nconst { forwardRef, currentElement } = useForwardExpose()\n\nonMounted(() => {\n  menuContext.onIndicatorTrackChange(currentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    style=\"position: relative\"\n  >\n    <Primitive\n      v-bind=\"$attrs\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n      :data-orientation=\"menuContext.orientation\"\n    >\n      <slot />\n    </Primitive>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface NavigationMenuListProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted } from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<NavigationMenuListProps>(), {\n  as: 'ul',\n})\n\nconst menuContext = injectNavigationMenuContext()\nconst { forwardRef, currentElement } = useForwardExpose()\n\nonMounted(() => {\n  menuContext.onIndicatorTrackChange(currentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    style=\"position: relative\"\n  >\n    <Primitive\n      v-bind=\"$attrs\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n      :data-orientation=\"menuContext.orientation\"\n    >\n      <slot />\n    </Primitive>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Orientation } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\n\nexport type NavigationMenuSubEmits = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: string]\n}\n\nexport interface NavigationMenuSubProps extends PrimitiveProps {\n  /** The controlled value of the sub menu item to activate. Can be used as `v-model`. */\n  modelValue?: string\n  /**\n   * The value of the menu item that should be active when initially rendered.\n   *\n   * Use when you do not need to control the value state.\n   */\n  defaultValue?: string\n  /** The orientation of the menu. */\n  orientation?: Orientation\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, watchEffect } from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectNavigationMenuContext, provideNavigationMenuContext } from './NavigationMenuRoot.vue'\n\nconst props = withDefaults(defineProps<NavigationMenuSubProps>(), {\n  orientation: 'horizontal',\n})\nconst emits = defineEmits<NavigationMenuSubEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? '',\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<string>\nconst previousValue = ref('')\n\nconst menuContext = injectNavigationMenuContext()\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst indicatorTrack = ref<HTMLElement>()\nconst viewport = ref<HTMLElement>()\nconst activeTrigger = ref<HTMLElement>()\n\nconst { getItems, CollectionSlot } = useCollection({ key: 'NavigationMenu', isProvider: true })\n\nwatchEffect(() => {\n  if (!modelValue.value)\n    return\n\n  const items = getItems().map(i => i.ref)\n  activeTrigger.value = items.find(item =>\n    item.id.includes(modelValue.value),\n  )\n})\n\nprovideNavigationMenuContext({\n  ...menuContext,\n  isRootMenu: false,\n  modelValue,\n  previousValue,\n  activeTrigger,\n  orientation: props.orientation,\n  rootNavigationMenu: currentElement,\n  indicatorTrack,\n  onIndicatorTrackChange: (val) => {\n    indicatorTrack.value = val\n  },\n  viewport,\n  onViewportChange: (val) => {\n    viewport.value = val\n  },\n\n  onTriggerEnter: (val) => {\n    modelValue.value = val\n  },\n  onTriggerLeave: () => {\n    // do nothing for submenu\n  },\n  onContentEnter: () => {\n    // do nothing for submenu\n  },\n  onContentLeave: () => {\n    // do nothing for submenu\n  },\n  onItemSelect: (val) => {\n    modelValue.value = val\n  },\n  onItemDismiss: () => {\n    modelValue.value = ''\n  },\n})\n</script>\n\n<template>\n  <CollectionSlot>\n    <Primitive\n      :ref=\"forwardRef\"\n      :data-orientation=\"orientation\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n      data-reka-navigation-menu\n    >\n      <slot :model-value=\"modelValue\" />\n    </Primitive>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Orientation } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\n\nexport type NavigationMenuSubEmits = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: string]\n}\n\nexport interface NavigationMenuSubProps extends PrimitiveProps {\n  /** The controlled value of the sub menu item to activate. Can be used as `v-model`. */\n  modelValue?: string\n  /**\n   * The value of the menu item that should be active when initially rendered.\n   *\n   * Use when you do not need to control the value state.\n   */\n  defaultValue?: string\n  /** The orientation of the menu. */\n  orientation?: Orientation\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { ref, watchEffect } from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectNavigationMenuContext, provideNavigationMenuContext } from './NavigationMenuRoot.vue'\n\nconst props = withDefaults(defineProps<NavigationMenuSubProps>(), {\n  orientation: 'horizontal',\n})\nconst emits = defineEmits<NavigationMenuSubEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? '',\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<string>\nconst previousValue = ref('')\n\nconst menuContext = injectNavigationMenuContext()\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst indicatorTrack = ref<HTMLElement>()\nconst viewport = ref<HTMLElement>()\nconst activeTrigger = ref<HTMLElement>()\n\nconst { getItems, CollectionSlot } = useCollection({ key: 'NavigationMenu', isProvider: true })\n\nwatchEffect(() => {\n  if (!modelValue.value)\n    return\n\n  const items = getItems().map(i => i.ref)\n  activeTrigger.value = items.find(item =>\n    item.id.includes(modelValue.value),\n  )\n})\n\nprovideNavigationMenuContext({\n  ...menuContext,\n  isRootMenu: false,\n  modelValue,\n  previousValue,\n  activeTrigger,\n  orientation: props.orientation,\n  rootNavigationMenu: currentElement,\n  indicatorTrack,\n  onIndicatorTrackChange: (val) => {\n    indicatorTrack.value = val\n  },\n  viewport,\n  onViewportChange: (val) => {\n    viewport.value = val\n  },\n\n  onTriggerEnter: (val) => {\n    modelValue.value = val\n  },\n  onTriggerLeave: () => {\n    // do nothing for submenu\n  },\n  onContentEnter: () => {\n    // do nothing for submenu\n  },\n  onContentLeave: () => {\n    // do nothing for submenu\n  },\n  onItemSelect: (val) => {\n    modelValue.value = val\n  },\n  onItemDismiss: () => {\n    modelValue.value = ''\n  },\n})\n</script>\n\n<template>\n  <CollectionSlot>\n    <Primitive\n      :ref=\"forwardRef\"\n      :data-orientation=\"orientation\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n      data-reka-navigation-menu\n    >\n      <slot :model-value=\"modelValue\" />\n    </Primitive>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { ComponentPublicInstance } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { useForwardExpose } from '@/shared'\n\nexport interface NavigationMenuTriggerProps extends PrimitiveProps {\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { refAutoReset, unrefElement } from '@vueuse/core'\nimport { computed, onMounted, ref } from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { VisuallyHidden } from '@/VisuallyHidden'\nimport { injectNavigationMenuItemContext } from './NavigationMenuItem.vue'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\nimport { getOpenState, makeContentId, makeTriggerId } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<NavigationMenuTriggerProps>(), {\n  as: 'button',\n})\n\nconst menuContext = injectNavigationMenuContext()\nconst itemContext = injectNavigationMenuItemContext()\n\nconst { CollectionItem } = useCollection({ key: 'NavigationMenu' })\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\nconst triggerId = ref('')\nconst contentId = ref('')\n\nconst hasPointerMoveOpenedRef = refAutoReset(false, 300)\nconst wasClickCloseRef = ref(false)\n\nconst open = computed(() => itemContext.value === menuContext.modelValue.value)\n\nonMounted(() => {\n  itemContext.triggerRef = triggerElement\n  triggerId.value = makeTriggerId(menuContext.baseId, itemContext.value)\n  contentId.value = makeContentId(menuContext.baseId, itemContext.value)\n})\n\nfunction handlePointerEnter() {\n  if (menuContext.disableHoverTrigger.value)\n    return\n\n  wasClickCloseRef.value = false\n  itemContext.wasEscapeCloseRef.value = false\n}\n\nfunction handlePointerMove(ev: PointerEvent) {\n  if (menuContext.disableHoverTrigger.value)\n    return\n\n  if (ev.pointerType === 'mouse') {\n    if (\n      props.disabled\n      || wasClickCloseRef.value\n      || itemContext.wasEscapeCloseRef.value\n      || hasPointerMoveOpenedRef.value\n    ) {\n      return\n    }\n\n    menuContext.onTriggerEnter(itemContext.value)\n    hasPointerMoveOpenedRef.value = true\n  }\n}\n\nfunction handlePointerLeave(ev: PointerEvent) {\n  if (menuContext.disableHoverTrigger.value)\n    return\n\n  if (ev.pointerType === 'mouse') {\n    if (props.disabled)\n      return\n    menuContext.onTriggerLeave()\n    hasPointerMoveOpenedRef.value = false\n  }\n}\n\nfunction handleClick(event: MouseEvent | PointerEvent) {\n  if (\n    (!('pointerType' in event) || event.pointerType === 'mouse')\n    && menuContext.disableClickTrigger.value\n  ) {\n    return\n  }\n\n  // if open via pointermove, we prevent click event\n  if (hasPointerMoveOpenedRef.value)\n    return\n\n  if (open.value)\n    menuContext.onItemSelect('')\n  else menuContext.onItemSelect(itemContext.value)\n\n  wasClickCloseRef.value = open.value\n}\n\nfunction handleKeydown(ev: KeyboardEvent) {\n  const verticalEntryKey = menuContext.dir.value === 'rtl' ? 'ArrowLeft' : 'ArrowRight'\n  const entryKey = { horizontal: 'ArrowDown', vertical: verticalEntryKey }[\n    menuContext.orientation\n  ]\n  if (open.value && ev.key === entryKey) {\n    itemContext.onEntryKeyDown()\n    // Prevent FocusGroupItem from handling the event\n    ev.preventDefault()\n    ev.stopPropagation()\n  }\n}\n\nfunction setFocusProxyRef(node: Element | ComponentPublicInstance | null) {\n  if (!node)\n    return undefined\n  // @ts-expect-error unrefElement expect MaybeRef, but also support Vnode\n  itemContext.focusProxyRef.value = unrefElement(node)\n  return undefined\n}\n\nfunction handleVisuallyHiddenFocus(ev: FocusEvent) {\n  const content = document.getElementById(itemContext.contentId)\n  const prevFocusedElement = ev.relatedTarget as HTMLElement | null\n\n  const wasTriggerFocused = prevFocusedElement === triggerElement.value\n  const wasFocusFromContent = content?.contains(prevFocusedElement)\n\n  if (wasTriggerFocused || !wasFocusFromContent)\n    itemContext.onFocusProxyEnter(wasTriggerFocused ? 'start' : 'end')\n}\n</script>\n\n<template>\n  <CollectionItem>\n    <Primitive\n      :id=\"triggerId\"\n      :ref=\"forwardRef\"\n      :disabled=\"disabled\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :data-state=\"getOpenState(open)\"\n      data-navigation-menu-trigger\n      :aria-expanded=\"open\"\n      :aria-controls=\"contentId\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n      v-bind=\"$attrs\"\n      @pointerenter=\"handlePointerEnter\"\n      @pointermove=\"handlePointerMove\"\n      @pointerleave=\"handlePointerLeave\"\n      @click=\"handleClick\"\n      @keydown=\"handleKeydown\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n\n  <template v-if=\"open\">\n    <VisuallyHidden\n      :ref=\"setFocusProxyRef\"\n      aria-hidden=\"true\"\n      :tabindex=\"0\"\n      @focus=\"handleVisuallyHiddenFocus\"\n    />\n    <span\n      v-if=\"menuContext.viewport\"\n      :aria-owns=\"contentId\"\n    />\n  </template>\n</template>\n","<script lang=\"ts\">\nimport type { ComponentPublicInstance } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { useForwardExpose } from '@/shared'\n\nexport interface NavigationMenuTriggerProps extends PrimitiveProps {\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { refAutoReset, unrefElement } from '@vueuse/core'\nimport { computed, onMounted, ref } from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { VisuallyHidden } from '@/VisuallyHidden'\nimport { injectNavigationMenuItemContext } from './NavigationMenuItem.vue'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\nimport { getOpenState, makeContentId, makeTriggerId } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<NavigationMenuTriggerProps>(), {\n  as: 'button',\n})\n\nconst menuContext = injectNavigationMenuContext()\nconst itemContext = injectNavigationMenuItemContext()\n\nconst { CollectionItem } = useCollection({ key: 'NavigationMenu' })\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\nconst triggerId = ref('')\nconst contentId = ref('')\n\nconst hasPointerMoveOpenedRef = refAutoReset(false, 300)\nconst wasClickCloseRef = ref(false)\n\nconst open = computed(() => itemContext.value === menuContext.modelValue.value)\n\nonMounted(() => {\n  itemContext.triggerRef = triggerElement\n  triggerId.value = makeTriggerId(menuContext.baseId, itemContext.value)\n  contentId.value = makeContentId(menuContext.baseId, itemContext.value)\n})\n\nfunction handlePointerEnter() {\n  if (menuContext.disableHoverTrigger.value)\n    return\n\n  wasClickCloseRef.value = false\n  itemContext.wasEscapeCloseRef.value = false\n}\n\nfunction handlePointerMove(ev: PointerEvent) {\n  if (menuContext.disableHoverTrigger.value)\n    return\n\n  if (ev.pointerType === 'mouse') {\n    if (\n      props.disabled\n      || wasClickCloseRef.value\n      || itemContext.wasEscapeCloseRef.value\n      || hasPointerMoveOpenedRef.value\n    ) {\n      return\n    }\n\n    menuContext.onTriggerEnter(itemContext.value)\n    hasPointerMoveOpenedRef.value = true\n  }\n}\n\nfunction handlePointerLeave(ev: PointerEvent) {\n  if (menuContext.disableHoverTrigger.value)\n    return\n\n  if (ev.pointerType === 'mouse') {\n    if (props.disabled)\n      return\n    menuContext.onTriggerLeave()\n    hasPointerMoveOpenedRef.value = false\n  }\n}\n\nfunction handleClick(event: MouseEvent | PointerEvent) {\n  if (\n    (!('pointerType' in event) || event.pointerType === 'mouse')\n    && menuContext.disableClickTrigger.value\n  ) {\n    return\n  }\n\n  // if open via pointermove, we prevent click event\n  if (hasPointerMoveOpenedRef.value)\n    return\n\n  if (open.value)\n    menuContext.onItemSelect('')\n  else menuContext.onItemSelect(itemContext.value)\n\n  wasClickCloseRef.value = open.value\n}\n\nfunction handleKeydown(ev: KeyboardEvent) {\n  const verticalEntryKey = menuContext.dir.value === 'rtl' ? 'ArrowLeft' : 'ArrowRight'\n  const entryKey = { horizontal: 'ArrowDown', vertical: verticalEntryKey }[\n    menuContext.orientation\n  ]\n  if (open.value && ev.key === entryKey) {\n    itemContext.onEntryKeyDown()\n    // Prevent FocusGroupItem from handling the event\n    ev.preventDefault()\n    ev.stopPropagation()\n  }\n}\n\nfunction setFocusProxyRef(node: Element | ComponentPublicInstance | null) {\n  if (!node)\n    return undefined\n  // @ts-expect-error unrefElement expect MaybeRef, but also support Vnode\n  itemContext.focusProxyRef.value = unrefElement(node)\n  return undefined\n}\n\nfunction handleVisuallyHiddenFocus(ev: FocusEvent) {\n  const content = document.getElementById(itemContext.contentId)\n  const prevFocusedElement = ev.relatedTarget as HTMLElement | null\n\n  const wasTriggerFocused = prevFocusedElement === triggerElement.value\n  const wasFocusFromContent = content?.contains(prevFocusedElement)\n\n  if (wasTriggerFocused || !wasFocusFromContent)\n    itemContext.onFocusProxyEnter(wasTriggerFocused ? 'start' : 'end')\n}\n</script>\n\n<template>\n  <CollectionItem>\n    <Primitive\n      :id=\"triggerId\"\n      :ref=\"forwardRef\"\n      :disabled=\"disabled\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :data-state=\"getOpenState(open)\"\n      data-navigation-menu-trigger\n      :aria-expanded=\"open\"\n      :aria-controls=\"contentId\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n      v-bind=\"$attrs\"\n      @pointerenter=\"handlePointerEnter\"\n      @pointermove=\"handlePointerMove\"\n      @pointerleave=\"handlePointerLeave\"\n      @click=\"handleClick\"\n      @keydown=\"handleKeydown\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n\n  <template v-if=\"open\">\n    <VisuallyHidden\n      :ref=\"setFocusProxyRef\"\n      aria-hidden=\"true\"\n      :tabindex=\"0\"\n      @focus=\"handleVisuallyHiddenFocus\"\n    />\n    <span\n      v-if=\"menuContext.viewport\"\n      :aria-owns=\"contentId\"\n    />\n  </template>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface NavigationMenuViewportProps extends PrimitiveProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n  /**\n   * Placement of the viewport for css variables `(--reka-navigation-menu-viewport-left, --reka-navigation-menu-viewport-top)`.\n   * @defaultValue 'center'\n   */\n  align?: 'start' | 'center' | 'end'\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useResizeObserver } from '@vueuse/core'\nimport { computed, nextTick, ref, watch } from 'vue'\nimport { Presence } from '@/Presence'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\nimport { getOpenState, whenMouse } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<NavigationMenuViewportProps>(), {\n  align: 'center',\n})\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst menuContext = injectNavigationMenuContext()\nconst { activeTrigger, rootNavigationMenu, modelValue } = menuContext\n\nconst size = ref<{ width: number, height: number }>()\nconst position = ref<{ left: number, top: number }>()\n\nconst open = computed(() => !!menuContext.modelValue.value)\n\nwatch(currentElement, () => {\n  menuContext.onViewportChange(currentElement.value)\n})\n\nconst content = ref<HTMLElement>()\n\nwatch([modelValue, open], () => {\n  nextTick(() => {\n    if (!currentElement.value)\n      return\n\n    requestAnimationFrame(() => {\n      const el = (currentElement.value as HTMLElement)?.querySelector('[data-state=open]') as HTMLElement | undefined\n      content.value = el\n    })\n  })\n}, { immediate: true })\n\nfunction updatePosition() {\n  if (content.value && activeTrigger.value && rootNavigationMenu.value) {\n    const bodyWidth = document.documentElement.offsetWidth\n    const bodyHeight = document.documentElement.offsetHeight\n    const rootRect = rootNavigationMenu.value.getBoundingClientRect()\n    const rect = activeTrigger.value.getBoundingClientRect()\n    const { offsetWidth, offsetHeight } = content.value\n\n    // Find the beginning of the position of the menu item\n    const startPositionLeft = rect.left - rootRect.left\n    const startPositionTop = rect.top - rootRect.top\n\n    // Aligning to specified alignment\n    let posLeft = null\n    let posTop = null\n    switch (props.align) {\n      case 'start':\n        posLeft = startPositionLeft\n        posTop = startPositionTop\n        break\n      case 'end':\n        posLeft = startPositionLeft - offsetWidth + rect.width\n        posTop = startPositionTop - offsetHeight + rect.height\n        break\n      default:\n        // center\n        posLeft = startPositionLeft - offsetWidth / 2 + rect.width / 2\n        posTop = startPositionTop - offsetHeight / 2 + rect.height / 2\n    }\n\n    const screenOffset = 10\n\n    // Do not let go of the left side of the screen\n    if (posLeft + rootRect.left < screenOffset) {\n      posLeft = screenOffset - rootRect.left\n    }\n\n    // Now also check the right side of the screen\n    const rightOffset = posLeft + rootRect.left + offsetWidth\n    if (rightOffset > bodyWidth - screenOffset) {\n      posLeft -= rightOffset - bodyWidth + screenOffset\n\n      // Recheck the left side of the screen\n      if (posLeft < screenOffset - rootRect.left) {\n        // Just set the menu to the full width of the screen\n        posLeft = screenOffset - rootRect.left\n      }\n    }\n\n    // Do not let go of the top side of the screen\n    if (posTop + rootRect.top < screenOffset) {\n      posTop = screenOffset - rootRect.top\n    }\n\n    // Now also check the bottom side of the screen\n    const bottomOffset = posTop + rootRect.top + offsetHeight\n    if (bottomOffset > bodyHeight - screenOffset) {\n      posTop -= bottomOffset - bodyHeight + screenOffset\n\n      // Recheck the top side of the screen\n      if (posTop < screenOffset - rootRect.top) {\n        // Just set the menu to the full height of the screen\n        posTop = screenOffset - rootRect.top\n      }\n    }\n\n    // Possible blurring font with decimal values\n    posLeft = Math.round(posLeft)\n    posTop = Math.round(posTop)\n\n    position.value = {\n      left: posLeft,\n      top: posTop,\n    }\n  }\n}\n\nuseResizeObserver(content, () => {\n  if (content.value) {\n    size.value = {\n      width: content.value.offsetWidth,\n      height: content.value.offsetHeight,\n    }\n    updatePosition()\n  }\n})\n\nuseResizeObserver([globalThis.document?.body, rootNavigationMenu], () => {\n  updatePosition()\n})\n</script>\n\n<template>\n  <Presence\n    v-slot=\"{ present }\"\n    :present=\"forceMount || open\"\n    :force-mount=\"!menuContext.unmountOnHide.value\"\n    @after-leave=\"() => {\n      size = undefined\n      position = undefined\n    }\"\n  >\n    <Primitive\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :data-state=\"getOpenState(open)\"\n      :data-orientation=\"menuContext.orientation\"\n      :style=\"{\n        // Prevent interaction when animating out\n        pointerEvents: !open && menuContext.isRootMenu ? 'none' : undefined,\n        ['--reka-navigation-menu-viewport-width']: size ? `${size?.width}px` : undefined,\n        ['--reka-navigation-menu-viewport-height']: size ? `${size?.height}px` : undefined,\n        ['--reka-navigation-menu-viewport-left']: position ? `${position?.left}px` : undefined,\n        ['--reka-navigation-menu-viewport-top']: position ? `${position?.top}px` : undefined,\n      }\"\n      :hidden=\"!present\"\n      @pointerenter=\"menuContext.onContentEnter(menuContext.modelValue.value)\"\n      @pointerleave=\"whenMouse(() => menuContext.onContentLeave())($event)\"\n    >\n      <slot />\n    </Primitive>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface NavigationMenuViewportProps extends PrimitiveProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n  /**\n   * Placement of the viewport for css variables `(--reka-navigation-menu-viewport-left, --reka-navigation-menu-viewport-top)`.\n   * @defaultValue 'center'\n   */\n  align?: 'start' | 'center' | 'end'\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useResizeObserver } from '@vueuse/core'\nimport { computed, nextTick, ref, watch } from 'vue'\nimport { Presence } from '@/Presence'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectNavigationMenuContext } from './NavigationMenuRoot.vue'\nimport { getOpenState, whenMouse } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<NavigationMenuViewportProps>(), {\n  align: 'center',\n})\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst menuContext = injectNavigationMenuContext()\nconst { activeTrigger, rootNavigationMenu, modelValue } = menuContext\n\nconst size = ref<{ width: number, height: number }>()\nconst position = ref<{ left: number, top: number }>()\n\nconst open = computed(() => !!menuContext.modelValue.value)\n\nwatch(currentElement, () => {\n  menuContext.onViewportChange(currentElement.value)\n})\n\nconst content = ref<HTMLElement>()\n\nwatch([modelValue, open], () => {\n  nextTick(() => {\n    if (!currentElement.value)\n      return\n\n    requestAnimationFrame(() => {\n      const el = (currentElement.value as HTMLElement)?.querySelector('[data-state=open]') as HTMLElement | undefined\n      content.value = el\n    })\n  })\n}, { immediate: true })\n\nfunction updatePosition() {\n  if (content.value && activeTrigger.value && rootNavigationMenu.value) {\n    const bodyWidth = document.documentElement.offsetWidth\n    const bodyHeight = document.documentElement.offsetHeight\n    const rootRect = rootNavigationMenu.value.getBoundingClientRect()\n    const rect = activeTrigger.value.getBoundingClientRect()\n    const { offsetWidth, offsetHeight } = content.value\n\n    // Find the beginning of the position of the menu item\n    const startPositionLeft = rect.left - rootRect.left\n    const startPositionTop = rect.top - rootRect.top\n\n    // Aligning to specified alignment\n    let posLeft = null\n    let posTop = null\n    switch (props.align) {\n      case 'start':\n        posLeft = startPositionLeft\n        posTop = startPositionTop\n        break\n      case 'end':\n        posLeft = startPositionLeft - offsetWidth + rect.width\n        posTop = startPositionTop - offsetHeight + rect.height\n        break\n      default:\n        // center\n        posLeft = startPositionLeft - offsetWidth / 2 + rect.width / 2\n        posTop = startPositionTop - offsetHeight / 2 + rect.height / 2\n    }\n\n    const screenOffset = 10\n\n    // Do not let go of the left side of the screen\n    if (posLeft + rootRect.left < screenOffset) {\n      posLeft = screenOffset - rootRect.left\n    }\n\n    // Now also check the right side of the screen\n    const rightOffset = posLeft + rootRect.left + offsetWidth\n    if (rightOffset > bodyWidth - screenOffset) {\n      posLeft -= rightOffset - bodyWidth + screenOffset\n\n      // Recheck the left side of the screen\n      if (posLeft < screenOffset - rootRect.left) {\n        // Just set the menu to the full width of the screen\n        posLeft = screenOffset - rootRect.left\n      }\n    }\n\n    // Do not let go of the top side of the screen\n    if (posTop + rootRect.top < screenOffset) {\n      posTop = screenOffset - rootRect.top\n    }\n\n    // Now also check the bottom side of the screen\n    const bottomOffset = posTop + rootRect.top + offsetHeight\n    if (bottomOffset > bodyHeight - screenOffset) {\n      posTop -= bottomOffset - bodyHeight + screenOffset\n\n      // Recheck the top side of the screen\n      if (posTop < screenOffset - rootRect.top) {\n        // Just set the menu to the full height of the screen\n        posTop = screenOffset - rootRect.top\n      }\n    }\n\n    // Possible blurring font with decimal values\n    posLeft = Math.round(posLeft)\n    posTop = Math.round(posTop)\n\n    position.value = {\n      left: posLeft,\n      top: posTop,\n    }\n  }\n}\n\nuseResizeObserver(content, () => {\n  if (content.value) {\n    size.value = {\n      width: content.value.offsetWidth,\n      height: content.value.offsetHeight,\n    }\n    updatePosition()\n  }\n})\n\nuseResizeObserver([globalThis.document?.body, rootNavigationMenu], () => {\n  updatePosition()\n})\n</script>\n\n<template>\n  <Presence\n    v-slot=\"{ present }\"\n    :present=\"forceMount || open\"\n    :force-mount=\"!menuContext.unmountOnHide.value\"\n    @after-leave=\"() => {\n      size = undefined\n      position = undefined\n    }\"\n  >\n    <Primitive\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :data-state=\"getOpenState(open)\"\n      :data-orientation=\"menuContext.orientation\"\n      :style=\"{\n        // Prevent interaction when animating out\n        pointerEvents: !open && menuContext.isRootMenu ? 'none' : undefined,\n        ['--reka-navigation-menu-viewport-width']: size ? `${size?.width}px` : undefined,\n        ['--reka-navigation-menu-viewport-height']: size ? `${size?.height}px` : undefined,\n        ['--reka-navigation-menu-viewport-left']: position ? `${position?.left}px` : undefined,\n        ['--reka-navigation-menu-viewport-top']: position ? `${position?.top}px` : undefined,\n      }\"\n      :hidden=\"!present\"\n      @pointerenter=\"menuContext.onContentEnter(menuContext.modelValue.value)\"\n      @pointerleave=\"whenMouse(() => menuContext.onContentLeave())($event)\"\n    >\n      <slot />\n    </Primitive>\n  </Presence>\n</template>\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nlet formatterCache = new Map<string, Intl.NumberFormat>();\n\nlet supportsSignDisplay = false;\ntry {\n  supportsSignDisplay =\n    new Intl.NumberFormat('de-DE', {signDisplay: 'exceptZero'}).resolvedOptions().signDisplay ===\n    'exceptZero';\n  // eslint-disable-next-line no-empty\n} catch {}\n\nlet supportsUnit = false;\ntry {\n  supportsUnit =\n    new Intl.NumberFormat('de-DE', {style: 'unit', unit: 'degree'}).resolvedOptions().style ===\n    'unit';\n  // eslint-disable-next-line no-empty\n} catch {}\n\n// Polyfill for units since Safari doesn't support them yet. See https://bugs.webkit.org/show_bug.cgi?id=215438.\n// Currently only polyfilling the unit degree in narrow format for ColorSlider in our supported locales.\n// Values were determined by switching to each locale manually in Chrome.\nconst UNITS = {\n  degree: {\n    narrow: {\n      default: '°',\n      'ja-JP': ' 度',\n      'zh-TW': '度',\n      'sl-SI': ' °'\n      // Arabic?? But Safari already doesn't use Arabic digits so might be ok...\n      // https://bugs.webkit.org/show_bug.cgi?id=218139\n    }\n  }\n};\n\nexport interface NumberFormatOptions extends Intl.NumberFormatOptions {\n  /** Overrides default numbering system for the current locale. */\n  numberingSystem?: string;\n}\n\ninterface NumberRangeFormatPart extends Intl.NumberFormatPart {\n  source: 'startRange' | 'endRange' | 'shared';\n}\n\n/**\n * A wrapper around Intl.NumberFormat providing additional options, polyfills, and caching for\n * performance.\n */\nexport class NumberFormatter implements Intl.NumberFormat {\n  private numberFormatter: Intl.NumberFormat;\n  private options: NumberFormatOptions;\n\n  constructor(locale: string, options: NumberFormatOptions = {}) {\n    this.numberFormatter = getCachedNumberFormatter(locale, options);\n    this.options = options;\n  }\n\n  /**\n   * Formats a number value as a string, according to the locale and options provided to the\n   * constructor.\n   */\n  format(value: number): string {\n    let res = '';\n    if (!supportsSignDisplay && this.options.signDisplay != null) {\n      res = numberFormatSignDisplayPolyfill(this.numberFormatter, this.options.signDisplay, value);\n    } else {\n      res = this.numberFormatter.format(value);\n    }\n\n    if (this.options.style === 'unit' && !supportsUnit) {\n      let {unit, unitDisplay = 'short', locale} = this.resolvedOptions();\n      if (!unit) {\n        return res;\n      }\n      let values = UNITS[unit]?.[unitDisplay];\n      res += values[locale] || values.default;\n    }\n\n    return res;\n  }\n\n  /** Formats a number to an array of parts such as separators, digits, punctuation, and more. */\n  formatToParts(value: number): Intl.NumberFormatPart[] {\n    // TODO: implement signDisplay for formatToParts\n    return this.numberFormatter.formatToParts(value);\n  }\n\n  /** Formats a number range as a string. */\n  formatRange(start: number, end: number): string {\n    if (typeof this.numberFormatter.formatRange === 'function') {\n      return this.numberFormatter.formatRange(start, end);\n    }\n\n    if (end < start) {\n      throw new RangeError('End date must be >= start date');\n    }\n\n    // Very basic fallback for old browsers.\n    return `${this.format(start)} – ${this.format(end)}`;\n  }\n\n  /** Formats a number range as an array of parts. */\n  formatRangeToParts(start: number, end: number): NumberRangeFormatPart[] {\n    if (typeof this.numberFormatter.formatRangeToParts === 'function') {\n      return this.numberFormatter.formatRangeToParts(start, end);\n    }\n\n    if (end < start) {\n      throw new RangeError('End date must be >= start date');\n    }\n\n    let startParts = this.numberFormatter.formatToParts(start);\n    let endParts = this.numberFormatter.formatToParts(end);\n    return [\n      ...startParts.map(p => ({...p, source: 'startRange'}) as NumberRangeFormatPart),\n      {type: 'literal', value: ' – ', source: 'shared'},\n      ...endParts.map(p => ({...p, source: 'endRange'}) as NumberRangeFormatPart)\n    ];\n  }\n\n  /** Returns the resolved formatting options based on the values passed to the constructor. */\n  resolvedOptions(): Intl.ResolvedNumberFormatOptions {\n    let options = this.numberFormatter.resolvedOptions();\n    if (!supportsSignDisplay && this.options.signDisplay != null) {\n      options = {...options, signDisplay: this.options.signDisplay};\n    }\n\n    if (!supportsUnit && this.options.style === 'unit') {\n      options = {\n        ...options,\n        style: 'unit',\n        unit: this.options.unit,\n        unitDisplay: this.options.unitDisplay\n      };\n    }\n\n    return options;\n  }\n}\n\nfunction getCachedNumberFormatter(\n  locale: string,\n  options: NumberFormatOptions = {}\n): Intl.NumberFormat {\n  let {numberingSystem} = options;\n  if (numberingSystem && locale.includes('-nu-')) {\n    if (!locale.includes('-u-')) {\n      locale += '-u-';\n    }\n    locale += `-nu-${numberingSystem}`;\n  }\n\n  if (options.style === 'unit' && !supportsUnit) {\n    let {unit, unitDisplay = 'short'} = options;\n    if (!unit) {\n      throw new Error('unit option must be provided with style: \"unit\"');\n    }\n    if (!UNITS[unit]?.[unitDisplay]) {\n      throw new Error(`Unsupported unit ${unit} with unitDisplay = ${unitDisplay}`);\n    }\n    options = {...options, style: 'decimal'};\n  }\n\n  let cacheKey =\n    locale +\n    (options\n      ? Object.entries(options)\n          .sort((a, b) => (a[0] < b[0] ? -1 : 1))\n          .join()\n      : '');\n  if (formatterCache.has(cacheKey)) {\n    return formatterCache.get(cacheKey)!;\n  }\n\n  let numberFormatter = new Intl.NumberFormat(locale, options);\n  formatterCache.set(cacheKey, numberFormatter);\n  return numberFormatter;\n}\n\n/** @private - Exported for tests */\nexport function numberFormatSignDisplayPolyfill(\n  numberFormat: Intl.NumberFormat,\n  signDisplay: string,\n  num: number\n): string {\n  if (signDisplay === 'auto') {\n    return numberFormat.format(num);\n  } else if (signDisplay === 'never') {\n    return numberFormat.format(Math.abs(num));\n  } else {\n    let needsPositiveSign = false;\n    if (signDisplay === 'always') {\n      needsPositiveSign = num > 0 || Object.is(num, 0);\n    } else if (signDisplay === 'exceptZero') {\n      if (Object.is(num, -0) || Object.is(num, 0)) {\n        num = Math.abs(num);\n      } else {\n        needsPositiveSign = num > 0;\n      }\n    }\n\n    if (needsPositiveSign) {\n      let negative = numberFormat.format(-num);\n      let noSign = numberFormat.format(num);\n      // ignore RTL/LTR marker character\n      let minus = negative.replace(noSign, '').replace(/\\u200e|\\u061C/, '');\n      if ([...minus].length !== 1) {\n        console.warn('@react-aria/i18n polyfill for NumberFormat signDisplay: Unsupported case');\n      }\n      let positive = negative.replace(noSign, '!!!').replace(minus, '+').replace('!!!', noSign);\n      return positive;\n    } else {\n      return numberFormat.format(num);\n    }\n  }\n}\n","/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {NumberFormatter} from './NumberFormatter';\n\ninterface Symbols {\n  minusSign?: string;\n  plusSign?: string;\n  decimal?: string;\n  group?: string;\n  literals: RegExp;\n  numeral: RegExp;\n  numerals: string[];\n  index: (v: string) => string;\n  noNumeralUnits: Array<{unit: string; value: number}>;\n}\n\nconst CURRENCY_SIGN_REGEX = new RegExp('^.*\\\\(.*\\\\).*$');\nconst NUMBERING_SYSTEMS = ['latn', 'arab', 'hanidec', 'deva', 'beng', 'fullwide'];\n\n/**\n * A NumberParser can be used to perform locale-aware parsing of numbers from Unicode strings,\n * as well as validation of partial user input. It automatically detects the numbering system\n * used in the input, and supports parsing decimals, percentages, currency values, and units\n * according to the locale.\n */\nexport class NumberParser {\n  private locale: string;\n  private options: Intl.NumberFormatOptions;\n\n  constructor(locale: string, options: Intl.NumberFormatOptions = {}) {\n    this.locale = locale;\n    this.options = options;\n  }\n\n  /**\n   * Parses the given string to a number. Returns NaN if a valid number could not be parsed.\n   */\n  parse(value: string): number {\n    return getNumberParserImpl(this.locale, this.options, value).parse(value);\n  }\n\n  /**\n   * Returns whether the given string could potentially be a valid number. This should be used to\n   * validate user input as the user types. If a `minValue` or `maxValue` is provided, the validity\n   * of the minus/plus sign characters can be checked.\n   */\n  isValidPartialNumber(value: string, minValue?: number, maxValue?: number): boolean {\n    return getNumberParserImpl(this.locale, this.options, value).isValidPartialNumber(\n      value,\n      minValue,\n      maxValue\n    );\n  }\n\n  /**\n   * Returns a numbering system for which the given string is valid in the current locale.\n   * If no numbering system could be detected, the default numbering system for the current\n   * locale is returned.\n   */\n  getNumberingSystem(value: string): string {\n    return getNumberParserImpl(this.locale, this.options, value).options.numberingSystem;\n  }\n}\n\nconst numberParserCache = new Map<string, NumberParserImpl>();\nfunction getNumberParserImpl(locale: string, options: Intl.NumberFormatOptions, value: string) {\n  // First try the default numbering system for the provided locale\n  let defaultParser = getCachedNumberParser(locale, options);\n\n  // If that doesn't match, and the locale doesn't include a hard coded numbering system,\n  // try each of the other supported numbering systems until we find one that matches.\n  if (!locale.includes('-nu-') && !defaultParser.isValidPartialNumber(value)) {\n    for (let numberingSystem of NUMBERING_SYSTEMS) {\n      if (numberingSystem !== defaultParser.options.numberingSystem) {\n        let parser = getCachedNumberParser(\n          locale + (locale.includes('-u-') ? '-nu-' : '-u-nu-') + numberingSystem,\n          options\n        );\n        if (parser.isValidPartialNumber(value)) {\n          return parser;\n        }\n      }\n    }\n  }\n\n  return defaultParser;\n}\n\nfunction getCachedNumberParser(locale: string, options: Intl.NumberFormatOptions) {\n  let cacheKey =\n    locale +\n    (options\n      ? Object.entries(options)\n          .sort((a, b) => (a[0] < b[0] ? -1 : 1))\n          .join()\n      : '');\n  let parser = numberParserCache.get(cacheKey);\n  if (!parser) {\n    parser = new NumberParserImpl(locale, options);\n    numberParserCache.set(cacheKey, parser);\n  }\n\n  return parser;\n}\n\n// The actual number parser implementation. Instances of this class are cached\n// based on the locale, options, and detected numbering system.\nclass NumberParserImpl {\n  formatter: Intl.NumberFormat;\n  options: Intl.ResolvedNumberFormatOptions;\n  symbols: Symbols;\n  locale: string;\n\n  constructor(locale: string, options: Intl.NumberFormatOptions = {}) {\n    this.locale = locale;\n    // see https://tc39.es/ecma402/#sec-setnfdigitoptions, when using roundingIncrement, the maximumFractionDigits and minimumFractionDigits must be equal\n    // by default, they are 0 and 3 respectively, so we set them to 0 if neither are set\n    if (options.roundingIncrement !== 1 && options.roundingIncrement != null) {\n      if (options.maximumFractionDigits == null && options.minimumFractionDigits == null) {\n        options.maximumFractionDigits = 0;\n        options.minimumFractionDigits = 0;\n      } else if (options.maximumFractionDigits == null) {\n        options.maximumFractionDigits = options.minimumFractionDigits;\n      } else if (options.minimumFractionDigits == null) {\n        options.minimumFractionDigits = options.maximumFractionDigits;\n      }\n      // if both are specified, let the normal Range Error be thrown\n    }\n    this.formatter = new Intl.NumberFormat(locale, options);\n    this.options = this.formatter.resolvedOptions();\n    this.symbols = getSymbols(locale, this.formatter, this.options, options);\n    if (\n      this.options.style === 'percent' &&\n      ((this.options.minimumFractionDigits ?? 0) > 18 ||\n        (this.options.maximumFractionDigits ?? 0) > 18)\n    ) {\n      console.warn(\n        'NumberParser cannot handle percentages with greater than 18 decimal places, please reduce the number in your options.'\n      );\n    }\n  }\n\n  parse(value: string) {\n    let isGroupSymbolAllowed = this.formatter.resolvedOptions().useGrouping;\n    // to parse the number, we need to remove anything that isn't actually part of the number, for example we want '-10.40' not '-10.40 USD'\n    let fullySanitizedValue = this.sanitize(value);\n\n    // Return NaN if there is a group symbol but useGrouping is false\n    if (\n      !isGroupSymbolAllowed &&\n      this.symbols.group &&\n      fullySanitizedValue.includes(this.symbols.group)\n    ) {\n      return NaN;\n    } else if (this.symbols.group) {\n      fullySanitizedValue = fullySanitizedValue.replaceAll(this.symbols.group!, '');\n    }\n\n    if (this.symbols.decimal) {\n      fullySanitizedValue = fullySanitizedValue.replace(this.symbols.decimal!, '.');\n    }\n    if (this.symbols.minusSign) {\n      fullySanitizedValue = fullySanitizedValue.replace(this.symbols.minusSign!, '-');\n    }\n    fullySanitizedValue = fullySanitizedValue.replace(this.symbols.numeral, this.symbols.index);\n\n    if (this.options.style === 'percent') {\n      // javascript is bad at dividing by 100 and maintaining the same significant figures, so perform it on the string before parsing\n      let isNegative = fullySanitizedValue.indexOf('-');\n      fullySanitizedValue = fullySanitizedValue.replace('-', '');\n      fullySanitizedValue = fullySanitizedValue.replace('+', '');\n      let index = fullySanitizedValue.indexOf('.');\n      if (index === -1) {\n        index = fullySanitizedValue.length;\n      }\n      fullySanitizedValue = fullySanitizedValue.replace('.', '');\n      if (index - 2 === 0) {\n        fullySanitizedValue = `0.${fullySanitizedValue}`;\n      } else if (index - 2 === -1) {\n        fullySanitizedValue = `0.0${fullySanitizedValue}`;\n      } else if (index - 2 === -2) {\n        fullySanitizedValue = '0.00';\n      } else {\n        fullySanitizedValue = `${fullySanitizedValue.slice(0, index - 2)}.${fullySanitizedValue.slice(index - 2)}`;\n      }\n      if (isNegative > -1) {\n        fullySanitizedValue = `-${fullySanitizedValue}`;\n      }\n    }\n\n    let newValue = fullySanitizedValue ? +fullySanitizedValue : NaN;\n    if (isNaN(newValue)) {\n      return NaN;\n    }\n\n    if (this.options.style === 'percent') {\n      // extra step for rounding percents to what our formatter would output\n      let options = {\n        ...this.options,\n        style: 'decimal' as const,\n        minimumFractionDigits: Math.min((this.options.minimumFractionDigits ?? 0) + 2, 20),\n        maximumFractionDigits: Math.min((this.options.maximumFractionDigits ?? 0) + 2, 20)\n      };\n      return new NumberParser(this.locale, options).parse(\n        new NumberFormatter(this.locale, options).format(newValue)\n      );\n    }\n\n    // accounting will always be stripped to a positive number, so if it's accounting and has a () around everything, then we need to make it negative again\n    if (this.options.currencySign === 'accounting' && CURRENCY_SIGN_REGEX.test(value)) {\n      newValue = -1 * newValue;\n    }\n    return newValue;\n  }\n\n  sanitize(value: string) {\n    let isGroupSymbolAllowed = this.formatter.resolvedOptions().useGrouping;\n    // If the value is only a unit and it matches one of the formatted numbers where the value is part of the unit and doesn't have any numerals, then\n    // return the known value for that case.\n    if (\n      this.symbols.noNumeralUnits.length > 0 &&\n      this.symbols.noNumeralUnits.find(obj => obj.unit === value)\n    ) {\n      return this.symbols.noNumeralUnits.find(obj => obj.unit === value)!.value.toString();\n    }\n\n    value = value.replace(this.symbols.literals, '');\n\n    // Replace the ASCII minus sign with the minus sign used in the current locale\n    // so that both are allowed in case the user's keyboard doesn't have the locale's minus sign.\n    if (this.symbols.minusSign) {\n      value = value.replace('-', this.symbols.minusSign);\n    }\n\n    // In arab numeral system, their decimal character is 1643, but most keyboards don't type that\n    // instead they use the , (44) character or apparently the (1548) character.\n    if (this.options.numberingSystem === 'arab') {\n      if (this.symbols.decimal) {\n        value = replaceAll(value, ',', this.symbols.decimal);\n        value = replaceAll(value, String.fromCharCode(1548), this.symbols.decimal);\n      }\n      if (this.symbols.group && isGroupSymbolAllowed) {\n        value = replaceAll(value, '.', this.symbols.group);\n      }\n    }\n\n    // In some locale styles, such as swiss currency, the group character can be a special single quote\n    // that keyboards don't typically have. This expands the character to include the easier to type single quote.\n    if (this.symbols.group === '’' && value.includes(\"'\") && isGroupSymbolAllowed) {\n      value = replaceAll(value, \"'\", this.symbols.group);\n    }\n\n    // On newer ICU versions, the special single quote has been normalized, so we need to backport.\n    if (this.symbols.group === \"'\" && value.includes('’') && isGroupSymbolAllowed) {\n      value = replaceAll(value, '’', this.symbols.group);\n    }\n\n    // fr-FR group character is narrow non-breaking space, char code 8239 (U+202F), but that's not a key on the french keyboard,\n    // so allow space and non-breaking space as a group char as well\n    if (this.options.locale === 'fr-FR' && this.symbols.group && isGroupSymbolAllowed) {\n      value = replaceAll(value, ' ', this.symbols.group);\n      value = replaceAll(value, /\\u00A0/g, this.symbols.group);\n    }\n\n    return value;\n  }\n\n  isValidPartialNumber(\n    value: string,\n    minValue: number = -Infinity,\n    maxValue: number = Infinity\n  ): boolean {\n    let isGroupSymbolAllowed = this.formatter.resolvedOptions().useGrouping;\n    value = this.sanitize(value);\n\n    // Remove minus or plus sign, which must be at the start of the string.\n    if (this.symbols.minusSign && value.startsWith(this.symbols.minusSign) && minValue < 0) {\n      value = value.slice(this.symbols.minusSign.length);\n    } else if (this.symbols.plusSign && value.startsWith(this.symbols.plusSign) && maxValue > 0) {\n      value = value.slice(this.symbols.plusSign.length);\n    }\n\n    // Numbers that can't have any decimal values fail if a decimal character is typed\n    if (\n      this.symbols.decimal &&\n      value.indexOf(this.symbols.decimal) > -1 &&\n      this.options.maximumFractionDigits === 0\n    ) {\n      return false;\n    }\n\n    // Remove numerals, groups, and decimals\n    if (this.symbols.group && isGroupSymbolAllowed) {\n      value = replaceAll(value, this.symbols.group, '');\n    }\n    value = value.replace(this.symbols.numeral, '');\n    if (this.symbols.decimal) {\n      value = value.replace(this.symbols.decimal, '');\n    }\n\n    // The number is valid if there are no remaining characters\n    return value.length === 0;\n  }\n}\n\nconst nonLiteralParts = new Set([\n  'decimal',\n  'fraction',\n  'integer',\n  'minusSign',\n  'plusSign',\n  'group'\n]);\n\n// This list is derived from https://www.unicode.org/cldr/charts/49/supplemental/language_plural_rules.html#comparison and includes\n// all unique numbers which we need to check in order to determine all the plural forms for a given locale.\n// Run scripts/generateAllPlurals.mjs to generate this list.\nconst pluralNumbers = [0, 4, 2, 1, 11, 20, 3, 7, 100, 21, 0.1, 1.1];\n\nfunction getSymbols(\n  locale: string,\n  formatter: Intl.NumberFormat,\n  intlOptions: Intl.ResolvedNumberFormatOptions,\n  originalOptions: Intl.NumberFormatOptions\n): Symbols {\n  // formatter needs access to all decimal places in order to generate the correct literal strings for the plural set\n  let symbolFormatter = new Intl.NumberFormat(locale, {\n    ...intlOptions,\n    // Resets so we get the full range of symbols\n    minimumSignificantDigits: 1,\n    maximumSignificantDigits: 21,\n    roundingIncrement: 1,\n    roundingPriority: 'auto',\n    roundingMode: 'halfExpand',\n    useGrouping: true\n  });\n  // Note: some locale's don't add a group symbol until there is a ten thousands place\n  let allParts = symbolFormatter.formatToParts(-10000.111);\n  let posAllParts = symbolFormatter.formatToParts(10000.111);\n  let pluralParts = pluralNumbers.map(n => symbolFormatter.formatToParts(n));\n  // if the plural parts include a unit but no integer or fraction, then we need to add the unit to the special set\n  let noNumeralUnits = pluralParts\n    .map((p, i) => {\n      let unit = p.find(p => p.type === 'unit');\n      if (unit && !p.some(p => p.type === 'integer' || p.type === 'fraction')) {\n        return {unit: unit.value, value: pluralNumbers[i]};\n      }\n      return null;\n    })\n    .filter(p => !!p);\n\n  let minusSign = allParts.find(p => p.type === 'minusSign')?.value ?? '-';\n  let plusSign = posAllParts.find(p => p.type === 'plusSign')?.value;\n\n  // Safari does not support the signDisplay option, but our number parser polyfills it.\n  // If no plus sign was returned, but the original options contained signDisplay, default to the '+' character.\n  if (\n    !plusSign &&\n    (originalOptions?.signDisplay === 'exceptZero' || originalOptions?.signDisplay === 'always')\n  ) {\n    plusSign = '+';\n  }\n\n  // If maximumSignificantDigits is 1 (the minimum) then we won't get decimal characters out of the above formatters\n  // Percent also defaults to 0 fractionDigits, so we need to make a new one that isn't percent to get an accurate decimal\n  let decimalParts = new Intl.NumberFormat(locale, {\n    ...intlOptions,\n    minimumFractionDigits: 2,\n    maximumFractionDigits: 2\n  }).formatToParts(0.001);\n\n  let decimal = decimalParts.find(p => p.type === 'decimal')?.value;\n  let group = allParts.find(p => p.type === 'group')?.value;\n\n  // this set is also for a regex, it's all literals that might be in the string we want to eventually parse that\n  // don't contribute to the numerical value\n  let allPartsLiterals = allParts\n    .filter(p => !nonLiteralParts.has(p.type))\n    .map(p => escapeRegex(p.value));\n  let pluralPartsLiterals = pluralParts.flatMap(p =>\n    p.filter(p => !nonLiteralParts.has(p.type)).map(p => escapeRegex(p.value))\n  );\n  let sortedLiterals = [...new Set([...allPartsLiterals, ...pluralPartsLiterals])].sort(\n    (a, b) => b.length - a.length\n  );\n\n  // Match both whitespace and formatting characters\n  let literals =\n    sortedLiterals.length === 0\n      ? new RegExp('\\\\p{White_Space}|\\\\p{Cf}', 'gu')\n      : new RegExp(`${sortedLiterals.join('|')}|\\\\p{White_Space}|\\\\p{Cf}`, 'gu');\n\n  // These are for replacing non-latn characters with the latn equivalent\n  let numerals = [\n    ...new Intl.NumberFormat(intlOptions.locale, {useGrouping: false}).format(9876543210)\n  ].reverse();\n  let indexes = new Map(numerals.map((d, i) => [d, i]));\n  let numeral = new RegExp(`[${numerals.join('')}]`, 'g');\n  let index = d => String(indexes.get(d));\n\n  return {minusSign, plusSign, decimal, group, literals, numeral, numerals, index, noNumeralUnits};\n}\n\nfunction replaceAll(str: string, find: string | RegExp, replace: string) {\n  if (str.replaceAll) {\n    return str.replaceAll(find, replace);\n  }\n\n  return str.split(find).join(replace);\n}\n\nfunction escapeRegex(string: string) {\n  return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n","import type { MaybeComputedElementRef } from '@vueuse/core'\nimport type { Ref } from 'vue'\nimport { NumberFormatter, NumberParser } from '@internationalized/number'\nimport { unrefElement, useEventListener } from '@vueuse/core'\nimport { createEventHook, isClient, reactiveComputed } from '@vueuse/shared'\nimport { computed, ref } from 'vue'\n\nexport function usePressedHold(options: { target?: MaybeComputedElementRef, disabled: Ref<boolean> }) {\n  const { disabled } = options\n  const timeout = ref<number>()\n  const triggerHook = createEventHook()\n  const resetTimeout = () => window.clearTimeout(timeout.value)\n\n  const onIncrementPressStart = (delay: number) => {\n    resetTimeout()\n    if (disabled.value)\n      return\n\n    triggerHook.trigger()\n\n    timeout.value = window.setTimeout(() => {\n      onIncrementPressStart(60)\n    }, delay)\n  }\n\n  const handlePressStart = () => {\n    onIncrementPressStart(400)\n  }\n\n  const handlePressEnd = () => {\n    resetTimeout()\n  }\n\n  // Handle press event, modified version of useMousePressed\n  const isPressed = ref(false)\n  const target = computed(() => unrefElement(options.target))\n\n  const onPressStart = (event: PointerEvent) => {\n    // Only handle left clicks, and ignore events that bubbled through portals.\n    if (event.button !== 0 || isPressed.value)\n      return\n\n    event.preventDefault()\n    isPressed.value = true\n    handlePressStart()\n  }\n\n  const onPressRelease = () => {\n    isPressed.value = false\n    handlePressEnd()\n  }\n\n  if (isClient) {\n    useEventListener(target || window, 'pointerdown', onPressStart)\n    useEventListener(window, 'pointerup', onPressRelease)\n    useEventListener(window, 'pointercancel', onPressRelease)\n  }\n\n  return {\n    isPressed,\n    onTrigger: triggerHook.on,\n  }\n}\n\nexport function useNumberFormatter(locale: Ref<string>, options: Ref<Intl.NumberFormatOptions | undefined> = ref({})) {\n  return reactiveComputed(() => new NumberFormatter(locale.value, options.value))\n}\n\nexport function useNumberParser(locale: Ref<string>, options: Ref<Intl.NumberFormatOptions | undefined> = ref({})) {\n  return reactiveComputed(() => new NumberParser(locale.value, options.value))\n}\n\nexport function handleDecimalOperation(operator: '-' | '+', value1: number, value2: number): number {\n  let result = operator === '+' ? value1 + value2 : value1 - value2\n\n  // Check if we have decimals\n  if (value1 % 1 !== 0 || value2 % 1 !== 0) {\n    const value1Decimal = value1.toString().split('.')\n    const value2Decimal = value2.toString().split('.')\n    const value1DecimalLength = (value1Decimal[1] && value1Decimal[1].length) || 0\n    const value2DecimalLength = (value2Decimal[1] && value2Decimal[1].length) || 0\n    const multiplier = 10 ** Math.max(value1DecimalLength, value2DecimalLength)\n\n    // Transform the decimals to integers based on the precision\n    value1 = Math.round(value1 * multiplier)\n    value2 = Math.round(value2 * multiplier)\n\n    // Perform the operation on integers values to make sure we don't get a fancy decimal value\n    result = operator === '+' ? value1 + value2 : value1 - value2\n\n    // Transform the integer result back to decimal\n    result /= multiplier\n  }\n\n  return result\n}\n","<script lang=\"ts\">\nimport type { HTMLAttributes, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { FormFieldProps } from '@/shared/types'\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRefs } from 'vue'\nimport { clamp, createContext, isNullish, snapValueToStep, useFormControl, useLocale } from '@/shared'\n\nexport interface NumberFieldRootProps extends PrimitiveProps, FormFieldProps {\n  defaultValue?: number\n  modelValue?: number | null\n  /** The smallest value allowed for the input. */\n  min?: number\n  /** The largest value allowed for the input. */\n  max?: number\n  /** The amount that the input value changes with each increment or decrement \"tick\". */\n  step?: number\n  /** When `false`, prevents the value from snapping to the nearest increment of the step value */\n  stepSnapping?: boolean\n  /** When `true`, the input will be focused when the value changes. */\n  focusOnChange?: boolean\n  /** Formatting options for the value displayed in the number field. This also affects what characters are allowed to be typed by the user. */\n  formatOptions?: Intl.NumberFormatOptions\n  /** The locale to use for formatting and currencies */\n  locale?: string\n  /** When `true`, prevents the user from interacting with the Number Field. */\n  disabled?: boolean\n  /** When `true`, the Number Field is read-only. */\n  readonly?: boolean\n  /** When `true`, prevents the value from changing on wheel scroll. */\n  disableWheelChange?: boolean\n  /** When `true`, inverts the direction of the wheel change. */\n  invertWheelChange?: boolean\n  /** Id of the element */\n  id?: string\n}\n\nexport type NumberFieldRootEmits = {\n  'update:modelValue': [val: number]\n}\n\ninterface NumberFieldRootContext {\n  modelValue: Ref<number | undefined>\n  handleIncrease: (multiplier?: number) => void\n  handleDecrease: (multiplier?: number) => void\n  handleMinMaxValue: (type: 'min' | 'max') => void\n  inputEl: Ref<HTMLInputElement | undefined>\n  onInputElement: (el: HTMLInputElement) => void\n  inputMode: Ref<HTMLAttributes['inputmode']>\n  textValue: Ref<string>\n  validate: (val: string) => boolean\n  applyInputValue: (val: string) => void\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  disableWheelChange: Ref<boolean>\n  invertWheelChange: Ref<boolean>\n  max: Ref<number | undefined>\n  min: Ref<number | undefined>\n  isDecreaseDisabled: Ref<boolean>\n  isIncreaseDisabled: Ref<boolean>\n  id: Ref<string | undefined>\n}\n\nexport const [injectNumberFieldRootContext, provideNumberFieldRootContext] = createContext<NumberFieldRootContext>('NumberFieldRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\nimport { handleDecimalOperation, useNumberFormatter, useNumberParser } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<NumberFieldRootProps>(), {\n  as: 'div',\n  defaultValue: undefined,\n  step: 1,\n  stepSnapping: true,\n  focusOnChange: true,\n})\nconst emits = defineEmits<NumberFieldRootEmits>()\nconst { disabled, readonly, disableWheelChange, invertWheelChange, min, max, step, stepSnapping, formatOptions, id, locale: propLocale } = toRefs(props)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<number | undefined>\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst locale = useLocale(propLocale)\nconst isFormControl = useFormControl(currentElement)\nconst inputEl = ref<HTMLInputElement>()\n\nconst isDecreaseDisabled = computed(() => (\n  !isNullish(modelValue.value) && (\n    clampInputValue(modelValue.value) === min.value\n    || (min.value && !isNaN(modelValue.value)\n    )\n      ? (handleDecimalOperation('-', modelValue.value, step.value) < min.value)\n      : false)),\n)\nconst isIncreaseDisabled = computed(() => (\n  !isNullish(modelValue.value) && (\n    clampInputValue(modelValue.value) === max.value\n    || (max.value && !isNaN(modelValue.value)\n    )\n      ? (handleDecimalOperation('+', modelValue.value, step.value) > max.value)\n      : false)),\n)\n\nfunction handleChangingValue(type: 'increase' | 'decrease', multiplier = 1) {\n  if (props.focusOnChange) {\n    inputEl.value?.focus()\n  }\n  if (props.disabled || props.readonly)\n    return\n  const currentInputValue = numberParser.parse(inputEl.value?.value ?? '')\n  if (isNaN(currentInputValue)) {\n    modelValue.value = min.value ?? 0\n  }\n  else {\n    if (type === 'increase')\n      modelValue.value = clampInputValue(currentInputValue + ((step.value ?? 1) * multiplier))\n    else\n      modelValue.value = clampInputValue(currentInputValue - ((step.value ?? 1) * multiplier))\n  }\n}\n\nfunction handleIncrease(multiplier = 1) {\n  handleChangingValue('increase', multiplier)\n}\nfunction handleDecrease(multiplier = 1) {\n  handleChangingValue('decrease', multiplier)\n}\n\nfunction handleMinMaxValue(type: 'min' | 'max') {\n  if (type === 'min' && min.value !== undefined)\n    modelValue.value = clampInputValue(min.value)\n  else if (type === 'max' && max.value !== undefined)\n    modelValue.value = clampInputValue(max.value)\n}\n\n// Formatter\nconst numberFormatter = useNumberFormatter(locale, formatOptions)\nconst numberParser = useNumberParser(locale, formatOptions)\n\nconst inputMode = computed<HTMLAttributes['inputmode']>(() => {\n  // The inputMode attribute influences the software keyboard that is shown on touch devices.\n  // Browsers and operating systems are quite inconsistent about what keys are available, however.\n  // We choose between numeric and decimal based on whether we allow negative and fractional numbers,\n  // and based on testing on various devices to determine what keys are available in each inputMode.\n  const hasDecimals = numberFormatter.resolvedOptions().maximumFractionDigits! > 0\n\n  return hasDecimals ? 'decimal' : 'numeric'\n})\n// Replace negative textValue formatted using currencySign: 'accounting'\n// with a textValue that can be announced using a minus sign.\nconst textValueFormatter = useNumberFormatter(locale, formatOptions)\nconst textValue = computed(() => isNullish(modelValue.value) || isNaN(modelValue.value) ? '' : textValueFormatter.format(modelValue.value))\n\nfunction validate(val: string) {\n  return numberParser.isValidPartialNumber(val, min.value, max.value)\n}\n\nfunction setInputValue(val: string) {\n  if (inputEl.value)\n    inputEl.value.value = val\n}\n\nfunction clampInputValue(val: number) {\n  // Clamp to min and max, round to the nearest step, and round to specified number of digits\n  let clampedValue: number\n  if (step.value === undefined || isNaN(step.value) || !stepSnapping.value)\n    clampedValue = clamp(val, min.value, max.value)\n  else\n    clampedValue = snapValueToStep(val, min.value, max.value, step.value)\n\n  clampedValue = numberParser.parse(numberFormatter.format(clampedValue))\n  return clampedValue\n}\n\nfunction applyInputValue(val: string) {\n  const parsedValue = numberParser.parse(val)\n  modelValue.value = isNaN(parsedValue) ? undefined : clampInputValue(parsedValue)\n  // Set to empty state if input value is empty\n  if (!val.length)\n    return setInputValue(val)\n\n  // if it failed to parse, then reset input to formatted version of current number\n  if (isNaN(parsedValue))\n    return setInputValue(textValue.value)\n\n  return setInputValue(textValue.value)\n}\n\nprovideNumberFieldRootContext({\n  modelValue,\n  handleDecrease,\n  handleIncrease,\n  handleMinMaxValue,\n  inputMode,\n  inputEl,\n  onInputElement: el => inputEl.value = el,\n  textValue,\n  readonly,\n  validate,\n  applyInputValue,\n  disabled,\n  disableWheelChange,\n  invertWheelChange,\n  max,\n  min,\n  isDecreaseDisabled,\n  isIncreaseDisabled,\n  id,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    ref=\"primitiveElement\"\n    role=\"group\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"readonly ? '' : undefined\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :text-value=\"textValue\"\n      :readonly=\"readonly\"\n    />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      type=\"text\"\n      :value=\"modelValue\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :readonly=\"readonly\"\n      :required=\"required\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { HTMLAttributes, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { FormFieldProps } from '@/shared/types'\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRefs } from 'vue'\nimport { clamp, createContext, isNullish, snapValueToStep, useFormControl, useLocale } from '@/shared'\n\nexport interface NumberFieldRootProps extends PrimitiveProps, FormFieldProps {\n  defaultValue?: number\n  modelValue?: number | null\n  /** The smallest value allowed for the input. */\n  min?: number\n  /** The largest value allowed for the input. */\n  max?: number\n  /** The amount that the input value changes with each increment or decrement \"tick\". */\n  step?: number\n  /** When `false`, prevents the value from snapping to the nearest increment of the step value */\n  stepSnapping?: boolean\n  /** When `true`, the input will be focused when the value changes. */\n  focusOnChange?: boolean\n  /** Formatting options for the value displayed in the number field. This also affects what characters are allowed to be typed by the user. */\n  formatOptions?: Intl.NumberFormatOptions\n  /** The locale to use for formatting and currencies */\n  locale?: string\n  /** When `true`, prevents the user from interacting with the Number Field. */\n  disabled?: boolean\n  /** When `true`, the Number Field is read-only. */\n  readonly?: boolean\n  /** When `true`, prevents the value from changing on wheel scroll. */\n  disableWheelChange?: boolean\n  /** When `true`, inverts the direction of the wheel change. */\n  invertWheelChange?: boolean\n  /** Id of the element */\n  id?: string\n}\n\nexport type NumberFieldRootEmits = {\n  'update:modelValue': [val: number]\n}\n\ninterface NumberFieldRootContext {\n  modelValue: Ref<number | undefined>\n  handleIncrease: (multiplier?: number) => void\n  handleDecrease: (multiplier?: number) => void\n  handleMinMaxValue: (type: 'min' | 'max') => void\n  inputEl: Ref<HTMLInputElement | undefined>\n  onInputElement: (el: HTMLInputElement) => void\n  inputMode: Ref<HTMLAttributes['inputmode']>\n  textValue: Ref<string>\n  validate: (val: string) => boolean\n  applyInputValue: (val: string) => void\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  disableWheelChange: Ref<boolean>\n  invertWheelChange: Ref<boolean>\n  max: Ref<number | undefined>\n  min: Ref<number | undefined>\n  isDecreaseDisabled: Ref<boolean>\n  isIncreaseDisabled: Ref<boolean>\n  id: Ref<string | undefined>\n}\n\nexport const [injectNumberFieldRootContext, provideNumberFieldRootContext] = createContext<NumberFieldRootContext>('NumberFieldRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\nimport { handleDecimalOperation, useNumberFormatter, useNumberParser } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<NumberFieldRootProps>(), {\n  as: 'div',\n  defaultValue: undefined,\n  step: 1,\n  stepSnapping: true,\n  focusOnChange: true,\n})\nconst emits = defineEmits<NumberFieldRootEmits>()\nconst { disabled, readonly, disableWheelChange, invertWheelChange, min, max, step, stepSnapping, formatOptions, id, locale: propLocale } = toRefs(props)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<number | undefined>\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst locale = useLocale(propLocale)\nconst isFormControl = useFormControl(currentElement)\nconst inputEl = ref<HTMLInputElement>()\n\nconst isDecreaseDisabled = computed(() => (\n  !isNullish(modelValue.value) && (\n    clampInputValue(modelValue.value) === min.value\n    || (min.value && !isNaN(modelValue.value)\n    )\n      ? (handleDecimalOperation('-', modelValue.value, step.value) < min.value)\n      : false)),\n)\nconst isIncreaseDisabled = computed(() => (\n  !isNullish(modelValue.value) && (\n    clampInputValue(modelValue.value) === max.value\n    || (max.value && !isNaN(modelValue.value)\n    )\n      ? (handleDecimalOperation('+', modelValue.value, step.value) > max.value)\n      : false)),\n)\n\nfunction handleChangingValue(type: 'increase' | 'decrease', multiplier = 1) {\n  if (props.focusOnChange) {\n    inputEl.value?.focus()\n  }\n  if (props.disabled || props.readonly)\n    return\n  const currentInputValue = numberParser.parse(inputEl.value?.value ?? '')\n  if (isNaN(currentInputValue)) {\n    modelValue.value = min.value ?? 0\n  }\n  else {\n    if (type === 'increase')\n      modelValue.value = clampInputValue(currentInputValue + ((step.value ?? 1) * multiplier))\n    else\n      modelValue.value = clampInputValue(currentInputValue - ((step.value ?? 1) * multiplier))\n  }\n}\n\nfunction handleIncrease(multiplier = 1) {\n  handleChangingValue('increase', multiplier)\n}\nfunction handleDecrease(multiplier = 1) {\n  handleChangingValue('decrease', multiplier)\n}\n\nfunction handleMinMaxValue(type: 'min' | 'max') {\n  if (type === 'min' && min.value !== undefined)\n    modelValue.value = clampInputValue(min.value)\n  else if (type === 'max' && max.value !== undefined)\n    modelValue.value = clampInputValue(max.value)\n}\n\n// Formatter\nconst numberFormatter = useNumberFormatter(locale, formatOptions)\nconst numberParser = useNumberParser(locale, formatOptions)\n\nconst inputMode = computed<HTMLAttributes['inputmode']>(() => {\n  // The inputMode attribute influences the software keyboard that is shown on touch devices.\n  // Browsers and operating systems are quite inconsistent about what keys are available, however.\n  // We choose between numeric and decimal based on whether we allow negative and fractional numbers,\n  // and based on testing on various devices to determine what keys are available in each inputMode.\n  const hasDecimals = numberFormatter.resolvedOptions().maximumFractionDigits! > 0\n\n  return hasDecimals ? 'decimal' : 'numeric'\n})\n// Replace negative textValue formatted using currencySign: 'accounting'\n// with a textValue that can be announced using a minus sign.\nconst textValueFormatter = useNumberFormatter(locale, formatOptions)\nconst textValue = computed(() => isNullish(modelValue.value) || isNaN(modelValue.value) ? '' : textValueFormatter.format(modelValue.value))\n\nfunction validate(val: string) {\n  return numberParser.isValidPartialNumber(val, min.value, max.value)\n}\n\nfunction setInputValue(val: string) {\n  if (inputEl.value)\n    inputEl.value.value = val\n}\n\nfunction clampInputValue(val: number) {\n  // Clamp to min and max, round to the nearest step, and round to specified number of digits\n  let clampedValue: number\n  if (step.value === undefined || isNaN(step.value) || !stepSnapping.value)\n    clampedValue = clamp(val, min.value, max.value)\n  else\n    clampedValue = snapValueToStep(val, min.value, max.value, step.value)\n\n  clampedValue = numberParser.parse(numberFormatter.format(clampedValue))\n  return clampedValue\n}\n\nfunction applyInputValue(val: string) {\n  const parsedValue = numberParser.parse(val)\n  modelValue.value = isNaN(parsedValue) ? undefined : clampInputValue(parsedValue)\n  // Set to empty state if input value is empty\n  if (!val.length)\n    return setInputValue(val)\n\n  // if it failed to parse, then reset input to formatted version of current number\n  if (isNaN(parsedValue))\n    return setInputValue(textValue.value)\n\n  return setInputValue(textValue.value)\n}\n\nprovideNumberFieldRootContext({\n  modelValue,\n  handleDecrease,\n  handleIncrease,\n  handleMinMaxValue,\n  inputMode,\n  inputEl,\n  onInputElement: el => inputEl.value = el,\n  textValue,\n  readonly,\n  validate,\n  applyInputValue,\n  disabled,\n  disableWheelChange,\n  invertWheelChange,\n  max,\n  min,\n  isDecreaseDisabled,\n  isIncreaseDisabled,\n  id,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    ref=\"primitiveElement\"\n    role=\"group\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"readonly ? '' : undefined\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :text-value=\"textValue\"\n      :readonly=\"readonly\"\n    />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      type=\"text\"\n      :value=\"modelValue\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :readonly=\"readonly\"\n      :required=\"required\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed } from 'vue'\nimport { injectNumberFieldRootContext } from './NumberFieldRoot.vue'\nimport { usePressedHold } from './utils'\n\nexport interface NumberFieldDecrementProps extends PrimitiveProps {\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<NumberFieldDecrementProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectNumberFieldRootContext()\nconst isDisabled = computed(() => rootContext.disabled?.value || rootContext.readonly.value || props.disabled || rootContext.isDecreaseDisabled.value)\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst { isPressed, onTrigger } = usePressedHold({ target: currentElement, disabled: isDisabled })\n\nonTrigger(() => {\n  rootContext.handleDecrease()\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    ref=\"primitiveElement\"\n    tabindex=\"-1\"\n    aria-label=\"Decrease\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :style=\"{\n      userSelect: isPressed ? 'none' : undefined,\n    }\"\n    :disabled=\"isDisabled ? '' : undefined\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-pressed=\"isPressed ? 'true' : undefined\"\n    @contextmenu.prevent\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed } from 'vue'\nimport { injectNumberFieldRootContext } from './NumberFieldRoot.vue'\nimport { usePressedHold } from './utils'\n\nexport interface NumberFieldDecrementProps extends PrimitiveProps {\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<NumberFieldDecrementProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectNumberFieldRootContext()\nconst isDisabled = computed(() => rootContext.disabled?.value || rootContext.readonly.value || props.disabled || rootContext.isDecreaseDisabled.value)\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst { isPressed, onTrigger } = usePressedHold({ target: currentElement, disabled: isDisabled })\n\nonTrigger(() => {\n  rootContext.handleDecrease()\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    ref=\"primitiveElement\"\n    tabindex=\"-1\"\n    aria-label=\"Decrease\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :style=\"{\n      userSelect: isPressed ? 'none' : undefined,\n    }\"\n    :disabled=\"isDisabled ? '' : undefined\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-pressed=\"isPressed ? 'true' : undefined\"\n    @contextmenu.prevent\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed } from 'vue'\nimport { injectNumberFieldRootContext } from './NumberFieldRoot.vue'\nimport { usePressedHold } from './utils'\n\nexport interface NumberFieldIncrementProps extends PrimitiveProps {\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<NumberFieldIncrementProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectNumberFieldRootContext()\nconst isDisabled = computed(() => rootContext.disabled?.value || rootContext.readonly.value || props.disabled || rootContext.isIncreaseDisabled.value)\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst { isPressed, onTrigger } = usePressedHold({ target: currentElement, disabled: isDisabled })\n\nonTrigger(() => {\n  rootContext.handleIncrease()\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    ref=\"primitiveElement\"\n    tabindex=\"-1\"\n    aria-label=\"Increase\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :style=\"{\n      userSelect: isPressed ? 'none' : undefined,\n    }\"\n    :disabled=\"isDisabled ? '' : undefined\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-pressed=\"isPressed ? 'true' : undefined\"\n    @contextmenu.prevent\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed } from 'vue'\nimport { injectNumberFieldRootContext } from './NumberFieldRoot.vue'\nimport { usePressedHold } from './utils'\n\nexport interface NumberFieldIncrementProps extends PrimitiveProps {\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<NumberFieldIncrementProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectNumberFieldRootContext()\nconst isDisabled = computed(() => rootContext.disabled?.value || rootContext.readonly.value || props.disabled || rootContext.isIncreaseDisabled.value)\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst { isPressed, onTrigger } = usePressedHold({ target: currentElement, disabled: isDisabled })\n\nonTrigger(() => {\n  rootContext.handleIncrease()\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    ref=\"primitiveElement\"\n    tabindex=\"-1\"\n    aria-label=\"Increase\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :style=\"{\n      userSelect: isPressed ? 'none' : undefined,\n    }\"\n    :disabled=\"isDisabled ? '' : undefined\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-pressed=\"isPressed ? 'true' : undefined\"\n    @contextmenu.prevent\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { onMounted, ref, watch } from 'vue'\nimport { getActiveElement, useComposing, useKbd } from '@/shared'\nimport { injectNumberFieldRootContext } from './NumberFieldRoot.vue'\n\nexport interface NumberFieldInputProps extends PrimitiveProps {\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<NumberFieldInputProps>(), {\n  as: 'input',\n})\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst rootContext = injectNumberFieldRootContext()\nconst kbd = useKbd()\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing()\n\nfunction handleKeydown(event: KeyboardEvent) {\n  // Don't step/apply mid-composition, keys are used for IME candidate navigation and commit.\n  // `isComposing` stays true until the tick after `compositionend`, so the commit keydown\n  // (which can report `event.isComposing === false`) is still skipped.\n  if (isComposing.value || event.isComposing)\n    return\n\n  switch (event.key) {\n    case kbd.ARROW_UP:\n      event.preventDefault()\n      rootContext.handleIncrease()\n      break\n    case kbd.ARROW_DOWN:\n      event.preventDefault()\n      rootContext.handleDecrease()\n      break\n    case kbd.PAGE_UP:\n      event.preventDefault()\n      rootContext.handleIncrease(10)\n      break\n    case kbd.PAGE_DOWN:\n      event.preventDefault()\n      rootContext.handleDecrease(10)\n      break\n    case kbd.HOME:\n      event.preventDefault()\n      rootContext.handleMinMaxValue('min')\n      break\n    case kbd.END:\n      event.preventDefault()\n      rootContext.handleMinMaxValue('max')\n      break\n    case kbd.ENTER:\n      rootContext.applyInputValue((event.target as HTMLInputElement)?.value)\n      break\n  }\n}\n\nfunction handleWheelEvent(event: WheelEvent) {\n  if (rootContext.disableWheelChange.value)\n    return\n\n  // only handle when in focus\n  if (event.target !== getActiveElement())\n    return\n\n  // if on a trackpad, users can scroll in both X and Y at once, check the magnitude of the change\n  // if it's mostly in the X direction, then just return, the user probably doesn't mean to inc/dec\n  // this isn't perfect, events come in fast with small deltas and a part of the scroll may give a false indication\n  // especially if the user is scrolling near 45deg\n  if (Math.abs(event.deltaY) <= Math.abs(event.deltaX))\n    return\n\n  event.preventDefault()\n  if (event.deltaY > 0)\n    rootContext.invertWheelChange.value ? rootContext.handleDecrease() : rootContext.handleIncrease()\n  else if (event.deltaY < 0)\n    rootContext.invertWheelChange.value ? rootContext.handleIncrease() : rootContext.handleDecrease()\n}\n\nonMounted(() => {\n  rootContext.onInputElement(currentElement.value as HTMLInputElement)\n})\n\nconst inputValue = ref(rootContext.textValue.value)\nwatch(() => rootContext.textValue.value, () => {\n  inputValue.value = rootContext.textValue.value\n}, { immediate: true, deep: true })\n\nfunction handleChange() {\n  requestAnimationFrame(() => {\n    inputValue.value = rootContext.textValue.value\n  })\n}\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.id.value\"\n    ref=\"primitiveElement\"\n    :value=\"inputValue\"\n    role=\"spinbutton\"\n    type=\"text\"\n    tabindex=\"0\"\n    :inputmode=\"rootContext.inputMode.value\"\n    :disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :readonly=\"rootContext.readonly.value ? '' : undefined\"\n    :data-readonly=\"rootContext.readonly.value ? '' : undefined\"\n    autocomplete=\"off\"\n    autocorrect=\"off\"\n    spellcheck=\"false\"\n    aria-roledescription=\"Number field\"\n    :aria-valuenow=\"rootContext.modelValue.value\"\n    :aria-valuemin=\"rootContext.min.value\"\n    :aria-valuemax=\"rootContext.max.value\"\n    @keydown=\"handleKeydown\"\n    @wheel=\"handleWheelEvent\"\n    @beforeinput=\"(event: InputEvent) => {\n      if (event.isComposing) return\n      const target = event.target as HTMLInputElement\n      let nextValue\n        = target.value.slice(0, target.selectionStart ?? undefined)\n          + (event.data ?? '')\n          + target.value.slice(target.selectionEnd ?? undefined);\n\n      // validate\n      if (!rootContext.validate(nextValue))\n        event.preventDefault()\n    }\"\n    @input=\"(event: InputEvent) => {\n      const target = event.target as HTMLInputElement\n      inputValue = target.value\n    }\"\n    @change=\"handleChange\"\n    @blur=\"rootContext.applyInputValue($event.target?.value)\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { onMounted, ref, watch } from 'vue'\nimport { getActiveElement, useComposing, useKbd } from '@/shared'\nimport { injectNumberFieldRootContext } from './NumberFieldRoot.vue'\n\nexport interface NumberFieldInputProps extends PrimitiveProps {\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<NumberFieldInputProps>(), {\n  as: 'input',\n})\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\nconst rootContext = injectNumberFieldRootContext()\nconst kbd = useKbd()\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing()\n\nfunction handleKeydown(event: KeyboardEvent) {\n  // Don't step/apply mid-composition, keys are used for IME candidate navigation and commit.\n  // `isComposing` stays true until the tick after `compositionend`, so the commit keydown\n  // (which can report `event.isComposing === false`) is still skipped.\n  if (isComposing.value || event.isComposing)\n    return\n\n  switch (event.key) {\n    case kbd.ARROW_UP:\n      event.preventDefault()\n      rootContext.handleIncrease()\n      break\n    case kbd.ARROW_DOWN:\n      event.preventDefault()\n      rootContext.handleDecrease()\n      break\n    case kbd.PAGE_UP:\n      event.preventDefault()\n      rootContext.handleIncrease(10)\n      break\n    case kbd.PAGE_DOWN:\n      event.preventDefault()\n      rootContext.handleDecrease(10)\n      break\n    case kbd.HOME:\n      event.preventDefault()\n      rootContext.handleMinMaxValue('min')\n      break\n    case kbd.END:\n      event.preventDefault()\n      rootContext.handleMinMaxValue('max')\n      break\n    case kbd.ENTER:\n      rootContext.applyInputValue((event.target as HTMLInputElement)?.value)\n      break\n  }\n}\n\nfunction handleWheelEvent(event: WheelEvent) {\n  if (rootContext.disableWheelChange.value)\n    return\n\n  // only handle when in focus\n  if (event.target !== getActiveElement())\n    return\n\n  // if on a trackpad, users can scroll in both X and Y at once, check the magnitude of the change\n  // if it's mostly in the X direction, then just return, the user probably doesn't mean to inc/dec\n  // this isn't perfect, events come in fast with small deltas and a part of the scroll may give a false indication\n  // especially if the user is scrolling near 45deg\n  if (Math.abs(event.deltaY) <= Math.abs(event.deltaX))\n    return\n\n  event.preventDefault()\n  if (event.deltaY > 0)\n    rootContext.invertWheelChange.value ? rootContext.handleDecrease() : rootContext.handleIncrease()\n  else if (event.deltaY < 0)\n    rootContext.invertWheelChange.value ? rootContext.handleIncrease() : rootContext.handleDecrease()\n}\n\nonMounted(() => {\n  rootContext.onInputElement(currentElement.value as HTMLInputElement)\n})\n\nconst inputValue = ref(rootContext.textValue.value)\nwatch(() => rootContext.textValue.value, () => {\n  inputValue.value = rootContext.textValue.value\n}, { immediate: true, deep: true })\n\nfunction handleChange() {\n  requestAnimationFrame(() => {\n    inputValue.value = rootContext.textValue.value\n  })\n}\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.id.value\"\n    ref=\"primitiveElement\"\n    :value=\"inputValue\"\n    role=\"spinbutton\"\n    type=\"text\"\n    tabindex=\"0\"\n    :inputmode=\"rootContext.inputMode.value\"\n    :disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :readonly=\"rootContext.readonly.value ? '' : undefined\"\n    :data-readonly=\"rootContext.readonly.value ? '' : undefined\"\n    autocomplete=\"off\"\n    autocorrect=\"off\"\n    spellcheck=\"false\"\n    aria-roledescription=\"Number field\"\n    :aria-valuenow=\"rootContext.modelValue.value\"\n    :aria-valuemin=\"rootContext.min.value\"\n    :aria-valuemax=\"rootContext.max.value\"\n    @keydown=\"handleKeydown\"\n    @wheel=\"handleWheelEvent\"\n    @beforeinput=\"(event: InputEvent) => {\n      if (event.isComposing) return\n      const target = event.target as HTMLInputElement\n      let nextValue\n        = target.value.slice(0, target.selectionStart ?? undefined)\n          + (event.data ?? '')\n          + target.value.slice(target.selectionEnd ?? undefined);\n\n      // validate\n      if (!rootContext.validate(nextValue))\n        event.preventDefault()\n    }\"\n    @input=\"(event: InputEvent) => {\n      const target = event.target as HTMLInputElement\n      inputValue = target.value\n    }\"\n    @change=\"handleChange\"\n    @blur=\"rootContext.applyInputValue($event.target?.value)\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationEllipsisProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<PaginationEllipsisProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    data-type=\"ellipsis\"\n  >\n    <slot>&#8230;</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationEllipsisProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<PaginationEllipsisProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    data-type=\"ellipsis\"\n  >\n    <slot>&#8230;</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useForwardExpose } from '@/shared'\n\ntype PaginationRootContext = {\n  page: Ref<number>\n  onPageChange: (value: number) => void\n  pageCount: Ref<number>\n  siblingCount: Ref<number>\n  disabled: Ref<boolean>\n  showEdges: Ref<boolean>\n}\n\nexport interface PaginationRootProps extends PrimitiveProps {\n  /** The controlled value of the current page. Can be binded as `v-model:page`. */\n  page?: number\n  /**\n   * The value of the page that should be active when initially rendered.\n   *\n   * Use when you do not need to control the value state.\n   */\n  defaultPage?: number\n  /** Number of items per page */\n  itemsPerPage: number\n  /** Number of items in your list */\n  total?: number\n  /** Number of sibling should be shown around the current page */\n  siblingCount?: number\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n  /** When `true`, always show first page, last page, and ellipsis */\n  showEdges?: boolean\n}\n\nexport type PaginationRootEmits = {\n  /** Event handler called when the page value changes */\n  'update:page': [value: number]\n}\n\nexport const [injectPaginationRootContext, providePaginationRootContext]\n  = createContext<PaginationRootContext>('PaginationRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<PaginationRootProps>(), {\n  as: 'nav',\n  total: 0,\n  siblingCount: 2,\n  defaultPage: 1,\n  showEdges: false,\n})\nconst emits = defineEmits<PaginationRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current page state */\n    page: typeof page.value\n    /** Number of pages */\n    pageCount: typeof pageCount.value\n  }) => any\n}>()\n\nconst { siblingCount, disabled, showEdges } = toRefs(props)\n\nuseForwardExpose()\nconst page = useVModel(props, 'page', emits, {\n  defaultValue: props.defaultPage,\n  passive: (props.page === undefined) as false,\n}) as Ref<number>\n\nconst pageCount = computed(() => Math.max(1, Math.ceil(props.total / (props.itemsPerPage || 1))))\n\nprovidePaginationRootContext({\n  page,\n  onPageChange(value) {\n    page.value = value\n  },\n  pageCount,\n  siblingCount,\n  disabled,\n  showEdges,\n})\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n  >\n    <slot\n      :page=\"page\"\n      :page-count=\"pageCount\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useForwardExpose } from '@/shared'\n\ntype PaginationRootContext = {\n  page: Ref<number>\n  onPageChange: (value: number) => void\n  pageCount: Ref<number>\n  siblingCount: Ref<number>\n  disabled: Ref<boolean>\n  showEdges: Ref<boolean>\n}\n\nexport interface PaginationRootProps extends PrimitiveProps {\n  /** The controlled value of the current page. Can be binded as `v-model:page`. */\n  page?: number\n  /**\n   * The value of the page that should be active when initially rendered.\n   *\n   * Use when you do not need to control the value state.\n   */\n  defaultPage?: number\n  /** Number of items per page */\n  itemsPerPage: number\n  /** Number of items in your list */\n  total?: number\n  /** Number of sibling should be shown around the current page */\n  siblingCount?: number\n  /** When `true`, prevents the user from interacting with item */\n  disabled?: boolean\n  /** When `true`, always show first page, last page, and ellipsis */\n  showEdges?: boolean\n}\n\nexport type PaginationRootEmits = {\n  /** Event handler called when the page value changes */\n  'update:page': [value: number]\n}\n\nexport const [injectPaginationRootContext, providePaginationRootContext]\n  = createContext<PaginationRootContext>('PaginationRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<PaginationRootProps>(), {\n  as: 'nav',\n  total: 0,\n  siblingCount: 2,\n  defaultPage: 1,\n  showEdges: false,\n})\nconst emits = defineEmits<PaginationRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current page state */\n    page: typeof page.value\n    /** Number of pages */\n    pageCount: typeof pageCount.value\n  }) => any\n}>()\n\nconst { siblingCount, disabled, showEdges } = toRefs(props)\n\nuseForwardExpose()\nconst page = useVModel(props, 'page', emits, {\n  defaultValue: props.defaultPage,\n  passive: (props.page === undefined) as false,\n}) as Ref<number>\n\nconst pageCount = computed(() => Math.max(1, Math.ceil(props.total / (props.itemsPerPage || 1))))\n\nprovidePaginationRootContext({\n  page,\n  onPageChange(value) {\n    page.value = value\n  },\n  pageCount,\n  siblingCount,\n  disabled,\n  showEdges,\n})\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n  >\n    <slot\n      :page=\"page\"\n      :page-count=\"pageCount\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationFirstProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPaginationRootContext } from './PaginationRoot.vue'\n\nconst props = withDefaults(defineProps<PaginationFirstProps>(), { as: 'button' })\n\nconst rootContext = injectPaginationRootContext()\nuseForwardExpose()\n\nconst disabled = computed((): boolean => rootContext.page.value === 1 || rootContext.disabled.value)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"First Page\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :disabled\n    @click=\"!disabled && rootContext.onPageChange(1)\"\n  >\n    <slot>First page</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationFirstProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPaginationRootContext } from './PaginationRoot.vue'\n\nconst props = withDefaults(defineProps<PaginationFirstProps>(), { as: 'button' })\n\nconst rootContext = injectPaginationRootContext()\nuseForwardExpose()\n\nconst disabled = computed((): boolean => rootContext.page.value === 1 || rootContext.disabled.value)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"First Page\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :disabled\n    @click=\"!disabled && rootContext.onPageChange(1)\"\n  >\n    <slot>First page</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationLastProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPaginationRootContext } from './PaginationRoot.vue'\n\nconst props = withDefaults(defineProps<PaginationLastProps>(), { as: 'button' })\n\nconst rootContext = injectPaginationRootContext()\nuseForwardExpose()\n\nconst disabled = computed((): boolean => rootContext.page.value === rootContext.pageCount.value || rootContext.disabled.value)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"Last Page\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :disabled\n    @click=\"!disabled && rootContext.onPageChange(rootContext.pageCount.value)\"\n  >\n    <slot>Last page</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationLastProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPaginationRootContext } from './PaginationRoot.vue'\n\nconst props = withDefaults(defineProps<PaginationLastProps>(), { as: 'button' })\n\nconst rootContext = injectPaginationRootContext()\nuseForwardExpose()\n\nconst disabled = computed((): boolean => rootContext.page.value === rootContext.pageCount.value || rootContext.disabled.value)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"Last Page\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :disabled\n    @click=\"!disabled && rootContext.onPageChange(rootContext.pageCount.value)\"\n  >\n    <slot>Last page</slot>\n  </Primitive>\n</template>\n","// reference https://github.com/chakra-ui/zag/blob/main/packages/machines/pagination/src/pagination.utils.ts\n\ntype Pages = Array<{ type: 'ellipsis' } | { type: 'page', value: number }>\n\nfunction range(start: number, end: number) {\n  const length = end - start + 1\n  return Array.from({ length }, (_, idx) => idx + start)\n}\n\nexport function transform(items: (string | number)[]): Pages {\n  return items.map((value) => {\n    if (typeof value === 'number')\n      return { type: 'page', value }\n    return { type: 'ellipsis' }\n  })\n}\n\nconst ELLIPSIS = 'ellipsis'\n\nexport function getRange(currentPage: number, pageCount: number, siblingCount: number, showEdges: boolean) {\n  const firstPageIndex = 1\n  const lastPageIndex = pageCount\n\n  const leftSiblingIndex = Math.max(currentPage - siblingCount, firstPageIndex)\n  const rightSiblingIndex = Math.min(currentPage + siblingCount, lastPageIndex)\n\n  if (showEdges) {\n    /**\n     * `2 * siblingCount + 5` explanation:\n     * 2 * siblingCount for left/right siblings\n     * 5 for 2x left/right ellipsis, 2x first/last page + 1x current page\n     *\n     * For some page counts (e.g. totalPages: 8, siblingCount: 2),\n     * calculated max page is higher than total pages,\n     * so we need to take the minimum of both.\n     */\n    const totalPageNumbers = Math.min(2 * siblingCount + 5, pageCount)\n\n    const itemCount = totalPageNumbers - 2 // 2 stands for one ellipsis and either first or last page\n\n    const showLeftEllipsis\n      // default condition\n      = leftSiblingIndex > firstPageIndex + 2\n      // if the current page is towards the end of the list\n        && Math.abs(lastPageIndex - itemCount - firstPageIndex + 1) > 2\n      // if the current page is towards the middle of the list\n        && Math.abs(leftSiblingIndex - firstPageIndex) > 2\n\n    const showRightEllipsis\n      // default condition\n      = rightSiblingIndex < lastPageIndex - 2\n      // if the current page is towards the start of the list\n        && Math.abs(lastPageIndex - itemCount) > 2\n      // if the current page is towards the middle of the list\n        && Math.abs(lastPageIndex - rightSiblingIndex) > 2\n\n    if (!showLeftEllipsis && showRightEllipsis) {\n      const leftRange = range(1, itemCount)\n\n      return [...leftRange, ELLIPSIS, lastPageIndex]\n    }\n\n    if (showLeftEllipsis && !showRightEllipsis) {\n      const rightRange = range(lastPageIndex - itemCount + 1, lastPageIndex)\n\n      return [firstPageIndex, ELLIPSIS, ...rightRange]\n    }\n\n    if (showLeftEllipsis && showRightEllipsis) {\n      const middleRange = range(leftSiblingIndex, rightSiblingIndex)\n\n      return [firstPageIndex, ELLIPSIS, ...middleRange, ELLIPSIS, lastPageIndex]\n    }\n\n    const fullRange = range(firstPageIndex, lastPageIndex)\n    return fullRange\n  }\n  else {\n    const itemCount = siblingCount * 2 + 1\n\n    if (pageCount < itemCount)\n      return range(1, lastPageIndex)\n\n    else if (currentPage <= (siblingCount + 1))\n      return range(firstPageIndex, itemCount)\n\n    else if ((pageCount - currentPage) <= siblingCount)\n      return range(pageCount - itemCount + 1, lastPageIndex)\n\n    else\n      return range(leftSiblingIndex, rightSiblingIndex)\n  }\n}\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationListProps extends PrimitiveProps { }\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPaginationRootContext } from './PaginationRoot.vue'\nimport { getRange, transform } from './utils'\n\nconst props = defineProps<PaginationListProps>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Pages item */\n    items: typeof transformedRange.value\n  }) => any\n}>()\n\nuseForwardExpose()\nconst rootContext = injectPaginationRootContext()\n\nconst transformedRange = computed(() => {\n  return transform(\n    getRange(\n      rootContext.page.value,\n      rootContext.pageCount.value,\n      rootContext.siblingCount.value,\n      rootContext.showEdges.value,\n    ),\n  )\n})\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot :items=\"transformedRange\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationListProps extends PrimitiveProps { }\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPaginationRootContext } from './PaginationRoot.vue'\nimport { getRange, transform } from './utils'\n\nconst props = defineProps<PaginationListProps>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Pages item */\n    items: typeof transformedRange.value\n  }) => any\n}>()\n\nuseForwardExpose()\nconst rootContext = injectPaginationRootContext()\n\nconst transformedRange = computed(() => {\n  return transform(\n    getRange(\n      rootContext.page.value,\n      rootContext.pageCount.value,\n      rootContext.siblingCount.value,\n      rootContext.showEdges.value,\n    ),\n  )\n})\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot :items=\"transformedRange\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationListItemProps extends PrimitiveProps {\n  /** Value for the page */\n  value: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPaginationRootContext } from './PaginationRoot.vue'\n\nconst props = withDefaults(defineProps<PaginationListItemProps>(), { as: 'button' })\nuseForwardExpose()\n\nconst rootContext = injectPaginationRootContext()\nconst isSelected = computed(() => rootContext.page.value === props.value)\n\nconst disabled = computed((): boolean => rootContext.disabled.value)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    data-type=\"page\"\n    :aria-label=\"`Page ${value}`\"\n    :aria-current=\"isSelected ? 'page' : undefined\"\n    :data-selected=\"isSelected ? 'true' : undefined\"\n    :disabled\n    :type=\"as === 'button' ? 'button' : undefined\"\n    @click=\"!disabled && rootContext.onPageChange(value)\"\n  >\n    <slot>{{ value }}</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationListItemProps extends PrimitiveProps {\n  /** Value for the page */\n  value: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPaginationRootContext } from './PaginationRoot.vue'\n\nconst props = withDefaults(defineProps<PaginationListItemProps>(), { as: 'button' })\nuseForwardExpose()\n\nconst rootContext = injectPaginationRootContext()\nconst isSelected = computed(() => rootContext.page.value === props.value)\n\nconst disabled = computed((): boolean => rootContext.disabled.value)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    data-type=\"page\"\n    :aria-label=\"`Page ${value}`\"\n    :aria-current=\"isSelected ? 'page' : undefined\"\n    :data-selected=\"isSelected ? 'true' : undefined\"\n    :disabled\n    :type=\"as === 'button' ? 'button' : undefined\"\n    @click=\"!disabled && rootContext.onPageChange(value)\"\n  >\n    <slot>{{ value }}</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationNextProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPaginationRootContext } from './PaginationRoot.vue'\n\nconst props = withDefaults(defineProps<PaginationNextProps>(), { as: 'button' })\n\nuseForwardExpose()\nconst rootContext = injectPaginationRootContext()\n\nconst disabled = computed((): boolean => rootContext.page.value === rootContext.pageCount.value || rootContext.disabled.value)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"Next Page\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :disabled\n    @click=\"!disabled && rootContext.onPageChange(rootContext.page.value + 1)\"\n  >\n    <slot>Next page</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationNextProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPaginationRootContext } from './PaginationRoot.vue'\n\nconst props = withDefaults(defineProps<PaginationNextProps>(), { as: 'button' })\n\nuseForwardExpose()\nconst rootContext = injectPaginationRootContext()\n\nconst disabled = computed((): boolean => rootContext.page.value === rootContext.pageCount.value || rootContext.disabled.value)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"Next Page\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :disabled\n    @click=\"!disabled && rootContext.onPageChange(rootContext.page.value + 1)\"\n  >\n    <slot>Next page</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationPrevProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPaginationRootContext } from './PaginationRoot.vue'\n\nconst props = withDefaults(defineProps<PaginationPrevProps>(), { as: 'button' })\n\nuseForwardExpose()\nconst rootContext = injectPaginationRootContext()\n\nconst disabled = computed((): boolean => rootContext.page.value === 1 || rootContext.disabled.value)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"Previous Page\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :disabled\n    @click=\"!disabled && rootContext.onPageChange(rootContext.page.value - 1)\"\n  >\n    <slot>Prev page</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface PaginationPrevProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPaginationRootContext } from './PaginationRoot.vue'\n\nconst props = withDefaults(defineProps<PaginationPrevProps>(), { as: 'button' })\n\nuseForwardExpose()\nconst rootContext = injectPaginationRootContext()\n\nconst disabled = computed((): boolean => rootContext.page.value === 1 || rootContext.disabled.value)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    aria-label=\"Previous Page\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :disabled\n    @click=\"!disabled && rootContext.onPageChange(rootContext.page.value - 1)\"\n  >\n    <slot>Prev page</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport { computed, ref, toRefs, watch } from 'vue'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\nimport VisuallyHiddenInput from '@/VisuallyHidden/VisuallyHiddenInput.vue'\n\nexport type PinInputType = 'text' | 'number'\n\n// Using this type to avoid mixed arrays (string | number)[].\n// The value type can be number[] only when the type is explicitly set to 'number'\nexport type PinInputValue<Type extends PinInputType> = [Type] extends ['number'] ? number[] : string[]\n\n// provide the mixed arrays because the `type` is dynamic in the context\nexport type PinInputContextValue<Type extends PinInputType = 'text'>\n  = Type extends 'number'\n    ? Type extends 'string'\n      ? string[] | number[]\n      : number[]\n    : string[]\n\nexport type PinInputRootEmits<Type extends PinInputType = 'text'> = {\n  'update:modelValue': [value: PinInputValue<Type>]\n  'complete': [value: PinInputValue<Type>]\n}\n\nexport interface PinInputRootProps<Type extends PinInputType = 'text'> extends PrimitiveProps, FormFieldProps {\n  /** The controlled checked state of the pin input. Can be binded as `v-model`. */\n  modelValue?: PinInputValue<Type> | null\n  /** The default value of the pin inputs when it is initially rendered. Use when you do not need to control its checked state. */\n  defaultValue?: PinInputValue<Type>\n  /** The placeholder character to use for empty pin-inputs. */\n  placeholder?: string\n  /** When `true`, pin inputs will be treated as password. */\n  mask?: boolean\n  /** When `true`, mobile devices will autodetect the OTP from messages or clipboard, and enable the autocomplete field. */\n  otp?: boolean\n  /** Input type for the inputs. */\n  type?: Type\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** When `true`, prevents the user from interacting with the pin input */\n  disabled?: boolean\n  /** Id of the element */\n  id?: string\n}\n\nexport interface PinInputRootContext<Type extends PinInputType = 'text'> {\n  modelValue: Ref<PinInputContextValue<Type>>\n  currentModelValue: ComputedRef<PinInputContextValue<Type>>\n  mask: Ref<boolean>\n  otp: Ref<boolean>\n  placeholder: Ref<string>\n  type: Ref<PinInputType>\n  dir: Ref<Direction>\n  disabled: Ref<boolean>\n  isCompleted: ComputedRef<boolean>\n  inputElements?: Ref<Set<HTMLInputElement>>\n  onInputElementChange: (el: HTMLInputElement) => void\n  isNumericMode: ComputedRef<boolean>\n}\n\nexport const [injectPinInputRootContext, providePinInputRootContext]\n  = createContext<PinInputRootContext<PinInputType>>('PinInputRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"Type extends PinInputType\">\nimport { useVModel } from '@vueuse/core'\nimport { Primitive } from '@/Primitive'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<PinInputRootProps<Type>>(), {\n  placeholder: '',\n  type: 'text' as any,\n})\nconst emits = defineEmits<PinInputRootEmits<Type>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { mask, otp, placeholder, type, disabled, dir: propDir } = toRefs(props)\nconst { forwardRef } = useForwardExpose()\nconst dir = useDirection(propDir)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? [] as any,\n  passive: true,\n  deep: true,\n}) as Ref<PinInputValue<Type>>\n\nconst currentModelValue = computed(() => Array.isArray(modelValue.value) ? [...modelValue.value] : [])\n\nconst inputElements = ref<Set<HTMLInputElement>>(new Set())\nfunction onInputElementChange(el: HTMLInputElement) {\n  inputElements.value.add(el)\n}\n\nconst isNumericMode = computed(() => props.type === 'number')\nconst isCompleted = computed(() => {\n  const modelValues = currentModelValue.value.filter(i => !!i || (isNumericMode.value && i === 0))\n  return modelValues.length === inputElements.value.size\n})\n\nwatch(modelValue, () => {\n  if (isCompleted.value)\n    emits('complete', modelValue.value)\n}, { deep: true })\n\nprovidePinInputRootContext({\n  modelValue,\n  currentModelValue: currentModelValue as ComputedRef<PinInputValue<Type>>,\n  mask,\n  otp,\n  placeholder,\n  type,\n  dir,\n  disabled,\n  isCompleted,\n  inputElements,\n  onInputElementChange,\n  isNumericMode,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    :dir=\"dir\"\n    :data-complete=\"isCompleted ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n  >\n    <slot :model-value=\"modelValue\" />\n\n    <VisuallyHiddenInput\n      :id=\"id\"\n      as=\"input\"\n      feature=\"focusable\"\n      tabindex=\"-1\"\n      :value=\"currentModelValue.join('')\"\n      :name=\"name ?? ''\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n      @focus=\"Array.from(inputElements)?.[0]?.focus()\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport { computed, ref, toRefs, watch } from 'vue'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\nimport VisuallyHiddenInput from '@/VisuallyHidden/VisuallyHiddenInput.vue'\n\nexport type PinInputType = 'text' | 'number'\n\n// Using this type to avoid mixed arrays (string | number)[].\n// The value type can be number[] only when the type is explicitly set to 'number'\nexport type PinInputValue<Type extends PinInputType> = [Type] extends ['number'] ? number[] : string[]\n\n// provide the mixed arrays because the `type` is dynamic in the context\nexport type PinInputContextValue<Type extends PinInputType = 'text'>\n  = Type extends 'number'\n    ? Type extends 'string'\n      ? string[] | number[]\n      : number[]\n    : string[]\n\nexport type PinInputRootEmits<Type extends PinInputType = 'text'> = {\n  'update:modelValue': [value: PinInputValue<Type>]\n  'complete': [value: PinInputValue<Type>]\n}\n\nexport interface PinInputRootProps<Type extends PinInputType = 'text'> extends PrimitiveProps, FormFieldProps {\n  /** The controlled checked state of the pin input. Can be binded as `v-model`. */\n  modelValue?: PinInputValue<Type> | null\n  /** The default value of the pin inputs when it is initially rendered. Use when you do not need to control its checked state. */\n  defaultValue?: PinInputValue<Type>\n  /** The placeholder character to use for empty pin-inputs. */\n  placeholder?: string\n  /** When `true`, pin inputs will be treated as password. */\n  mask?: boolean\n  /** When `true`, mobile devices will autodetect the OTP from messages or clipboard, and enable the autocomplete field. */\n  otp?: boolean\n  /** Input type for the inputs. */\n  type?: Type\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** When `true`, prevents the user from interacting with the pin input */\n  disabled?: boolean\n  /** Id of the element */\n  id?: string\n}\n\nexport interface PinInputRootContext<Type extends PinInputType = 'text'> {\n  modelValue: Ref<PinInputContextValue<Type>>\n  currentModelValue: ComputedRef<PinInputContextValue<Type>>\n  mask: Ref<boolean>\n  otp: Ref<boolean>\n  placeholder: Ref<string>\n  type: Ref<PinInputType>\n  dir: Ref<Direction>\n  disabled: Ref<boolean>\n  isCompleted: ComputedRef<boolean>\n  inputElements?: Ref<Set<HTMLInputElement>>\n  onInputElementChange: (el: HTMLInputElement) => void\n  isNumericMode: ComputedRef<boolean>\n}\n\nexport const [injectPinInputRootContext, providePinInputRootContext]\n  = createContext<PinInputRootContext<PinInputType>>('PinInputRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"Type extends PinInputType\">\nimport { useVModel } from '@vueuse/core'\nimport { Primitive } from '@/Primitive'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<PinInputRootProps<Type>>(), {\n  placeholder: '',\n  type: 'text' as any,\n})\nconst emits = defineEmits<PinInputRootEmits<Type>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { mask, otp, placeholder, type, disabled, dir: propDir } = toRefs(props)\nconst { forwardRef } = useForwardExpose()\nconst dir = useDirection(propDir)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? [] as any,\n  passive: true,\n  deep: true,\n}) as Ref<PinInputValue<Type>>\n\nconst currentModelValue = computed(() => Array.isArray(modelValue.value) ? [...modelValue.value] : [])\n\nconst inputElements = ref<Set<HTMLInputElement>>(new Set())\nfunction onInputElementChange(el: HTMLInputElement) {\n  inputElements.value.add(el)\n}\n\nconst isNumericMode = computed(() => props.type === 'number')\nconst isCompleted = computed(() => {\n  const modelValues = currentModelValue.value.filter(i => !!i || (isNumericMode.value && i === 0))\n  return modelValues.length === inputElements.value.size\n})\n\nwatch(modelValue, () => {\n  if (isCompleted.value)\n    emits('complete', modelValue.value)\n}, { deep: true })\n\nprovidePinInputRootContext({\n  modelValue,\n  currentModelValue: currentModelValue as ComputedRef<PinInputValue<Type>>,\n  mask,\n  otp,\n  placeholder,\n  type,\n  dir,\n  disabled,\n  isCompleted,\n  inputElements,\n  onInputElementChange,\n  isNumericMode,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    :dir=\"dir\"\n    :data-complete=\"isCompleted ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n  >\n    <slot :model-value=\"modelValue\" />\n\n    <VisuallyHiddenInput\n      :id=\"id\"\n      as=\"input\"\n      feature=\"focusable\"\n      tabindex=\"-1\"\n      :value=\"currentModelValue.join('')\"\n      :name=\"name ?? ''\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n      @focus=\"Array.from(inputElements)?.[0]?.focus()\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PinInputContextValue } from './PinInputRoot.vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { getActiveElement, useArrowNavigation, useComposing } from '@/shared'\nimport { injectPinInputRootContext } from './PinInputRoot.vue'\n\nexport interface PinInputInputProps extends PrimitiveProps {\n  /** Position of the value this input binds to. */\n  index: number\n  /** When `true`, prevents the user from interacting with the pin input */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, nextTick, onMounted, onUnmounted, watch } from 'vue'\n\nconst props = withDefaults(defineProps<PinInputInputProps>(), {\n  as: 'input',\n})\n\nconst context = injectPinInputRootContext()\nconst inputElements = computed(() => [...context.inputElements!.value])\nconst currentValue = computed(() => context.currentModelValue.value[props.index])\n\nconst disabled = computed(() => props.disabled || context.disabled.value)\nconst isOtpMode = computed(() => context.otp.value)\nconst isPasswordMode = computed(() => context.mask.value)\n\nconst NUMBER_REG = /^\\d*$/\nconst NON_NUMBER_REG = /\\D/g\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing((event) => {\n  const target = event.target as HTMLInputElement\n  const value = event.data || target.value\n\n  if (context.isNumericMode.value) {\n    const filtered = value.replace(NON_NUMBER_REG, '')\n    if (!filtered) {\n      target.value = ''\n      return\n    }\n    if (filtered.length > 1) {\n      handleMultipleCharacter(filtered)\n      return\n    }\n    target.value = filtered\n    updateModelValueAt(props.index, filtered)\n    const nextEl = inputElements.value[props.index + 1]\n    if (nextEl)\n      nextEl.focus()\n    return\n  }\n\n  if (value.length > 1) {\n    handleMultipleCharacter(value)\n    return\n  }\n\n  target.value = value\n  updateModelValueAt(props.index, value)\n\n  const nextEl = inputElements.value[props.index + 1]\n  if (nextEl)\n    nextEl.focus()\n})\n\nfunction handleInput(event: InputEvent) {\n  if (isComposing.value || event.isComposing)\n    return\n  const target = event.target as HTMLInputElement\n\n  if ((event.data?.length ?? 0) > 1) {\n    handleMultipleCharacter(target.value)\n    return\n  }\n\n  if (context.isNumericMode.value && !NUMBER_REG.test(target.value)) {\n    target.value = target.value.replace(NON_NUMBER_REG, '')\n    return\n  }\n\n  target.value = event.data || target.value.slice(-1)\n  updateModelValueAt(props.index, target.value)\n\n  const nextEl = inputElements.value[props.index + 1]\n  if (nextEl)\n    nextEl.focus()\n}\n\nfunction updatePlaceholder() {\n  nextTick(() => {\n    const target = currentElement.value as HTMLInputElement\n    if (!target) {\n      return\n    }\n    if (!target.value && target === getActiveElement()) {\n      target.placeholder = ''\n    }\n    else {\n      target.placeholder = context.placeholder.value\n    }\n  })\n}\n\nfunction handleKeydown(event: KeyboardEvent) {\n  // Don't move between inputs mid-composition, arrow keys are used for IME candidate navigation\n  if (isComposing.value || event.isComposing)\n    return\n  useArrowNavigation(event, getActiveElement() as HTMLElement, undefined, {\n    itemsArray: inputElements.value,\n    focus: true,\n    loop: false,\n    arrowKeyOptions: 'horizontal',\n    dir: context.dir.value,\n  })\n}\n\nfunction handleBackspace(event: KeyboardEvent) {\n  event.preventDefault()\n  const target = event.target as HTMLInputElement\n  const value = target.value\n\n  if (value) {\n    updateModelValueAt(props.index, '')\n  }\n  else {\n    const prevEl = inputElements.value[props.index - 1]\n    if (prevEl) {\n      prevEl.focus()\n      updateModelValueAt(props.index - 1, '')\n    }\n  }\n}\n\nfunction handleDelete(event: KeyboardEvent) {\n  if (event.key === 'Delete') {\n    event.preventDefault()\n    updateModelValueAt(props.index, '')\n  }\n}\n\nfunction handleFocus(event: FocusEvent) {\n  // In OTP mode, inputs should be filled one by one without skipping middle inputs\n  if (context.otp.value) {\n    const firstEmptyInputIdx = inputElements.value.findIndex((_, idx) =>\n      context.currentModelValue.value[idx] === ''\n      || context.currentModelValue.value[idx] === undefined,\n    )\n    if (firstEmptyInputIdx !== -1 && firstEmptyInputIdx < props.index) {\n      inputElements.value[firstEmptyInputIdx].focus()\n      return\n    }\n  }\n\n  const target = event.target as HTMLInputElement\n  target.setSelectionRange(1, 1)\n  updatePlaceholder()\n}\n\nfunction handleBlur(event: FocusEvent) {\n  updatePlaceholder()\n}\n\nfunction handlePaste(event: ClipboardEvent) {\n  event.preventDefault()\n  const clipboardData = event.clipboardData\n  if (!clipboardData)\n    return\n\n  const rawValues = clipboardData.getData('text')\n  const values = context.isNumericMode.value\n    ? rawValues.replace(NON_NUMBER_REG, '')\n    : rawValues\n  handleMultipleCharacter(values)\n}\n\nfunction handleMultipleCharacter(values: string) {\n  const tempModelValue = [...context.currentModelValue.value] as typeof context.currentModelValue.value\n  const initialIndex = values.length >= inputElements.value.length ? 0 : props.index\n  const lastIndex = Math.min(initialIndex + values.length, inputElements.value.length)\n  for (let i = initialIndex; i < lastIndex; i++) {\n    const input = inputElements.value[i]\n    const value = values[i - initialIndex]\n    if (context.isNumericMode.value) {\n      const num = Number.parseInt(value)\n      if (Number.isNaN(num))\n        continue\n      tempModelValue[i] = num\n    }\n    else {\n      tempModelValue[i] = value\n    }\n    input.focus()\n  }\n  context.modelValue.value = tempModelValue\n  inputElements.value[lastIndex]?.focus()\n}\n\nfunction removeTrailingEmptyStrings(input: PinInputContextValue<typeof context.type.value>) {\n  let i = input.length - 1\n\n  while (i >= 0 && input[i] === '') {\n    input.pop()\n    i--\n  }\n\n  return input\n}\n\nfunction updateModelValueAt(index: number, value: string) {\n  const tempModelValue = [...context.currentModelValue.value] as typeof context.currentModelValue.value\n\n  if (context.isNumericMode.value) {\n    const num = +value\n\n    if (value === '' || isNaN(num)) {\n      delete tempModelValue[index]\n    }\n    else {\n      tempModelValue[index] = num\n    }\n  }\n  else {\n    tempModelValue[index] = value\n  }\n\n  context.modelValue.value = removeTrailingEmptyStrings(tempModelValue)\n}\n\nwatch(currentValue, updatePlaceholder)\n\nonMounted(() => {\n  context.onInputElementChange(currentElement.value as HTMLInputElement)\n})\nonUnmounted(() => {\n  context.inputElements?.value.delete(currentElement.value as HTMLInputElement)\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    autocapitalize=\"none\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :autocomplete=\"isOtpMode ? 'one-time-code' : 'false'\"\n    :type=\"isPasswordMode ? 'password' : 'text'\"\n    :inputmode=\"context.isNumericMode.value ? 'numeric' : 'text'\"\n    :pattern=\"context.isNumericMode.value ? '[0-9]*' : undefined\"\n    :placeholder=\"context.placeholder.value\"\n    :value=\"currentValue\"\n    :disabled=\"disabled\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-complete=\"context.isCompleted.value ? '' : undefined\"\n    :aria-label=\"`pin input ${index + 1} of ${inputElements.length}`\"\n    @input=\"handleInput($event as InputEvent)\"\n    @keydown.left.right.up.down.home.end=\"handleKeydown\"\n    @keydown.backspace=\"handleBackspace\"\n    @keydown.delete=\"handleDelete\"\n    @focus=\"handleFocus\"\n    @blur=\"handleBlur\"\n    @paste=\"handlePaste\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PinInputContextValue } from './PinInputRoot.vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { getActiveElement, useArrowNavigation, useComposing } from '@/shared'\nimport { injectPinInputRootContext } from './PinInputRoot.vue'\n\nexport interface PinInputInputProps extends PrimitiveProps {\n  /** Position of the value this input binds to. */\n  index: number\n  /** When `true`, prevents the user from interacting with the pin input */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, nextTick, onMounted, onUnmounted, watch } from 'vue'\n\nconst props = withDefaults(defineProps<PinInputInputProps>(), {\n  as: 'input',\n})\n\nconst context = injectPinInputRootContext()\nconst inputElements = computed(() => [...context.inputElements!.value])\nconst currentValue = computed(() => context.currentModelValue.value[props.index])\n\nconst disabled = computed(() => props.disabled || context.disabled.value)\nconst isOtpMode = computed(() => context.otp.value)\nconst isPasswordMode = computed(() => context.mask.value)\n\nconst NUMBER_REG = /^\\d*$/\nconst NON_NUMBER_REG = /\\D/g\n\nconst { primitiveElement, currentElement } = usePrimitiveElement()\n\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing((event) => {\n  const target = event.target as HTMLInputElement\n  const value = event.data || target.value\n\n  if (context.isNumericMode.value) {\n    const filtered = value.replace(NON_NUMBER_REG, '')\n    if (!filtered) {\n      target.value = ''\n      return\n    }\n    if (filtered.length > 1) {\n      handleMultipleCharacter(filtered)\n      return\n    }\n    target.value = filtered\n    updateModelValueAt(props.index, filtered)\n    const nextEl = inputElements.value[props.index + 1]\n    if (nextEl)\n      nextEl.focus()\n    return\n  }\n\n  if (value.length > 1) {\n    handleMultipleCharacter(value)\n    return\n  }\n\n  target.value = value\n  updateModelValueAt(props.index, value)\n\n  const nextEl = inputElements.value[props.index + 1]\n  if (nextEl)\n    nextEl.focus()\n})\n\nfunction handleInput(event: InputEvent) {\n  if (isComposing.value || event.isComposing)\n    return\n  const target = event.target as HTMLInputElement\n\n  if ((event.data?.length ?? 0) > 1) {\n    handleMultipleCharacter(target.value)\n    return\n  }\n\n  if (context.isNumericMode.value && !NUMBER_REG.test(target.value)) {\n    target.value = target.value.replace(NON_NUMBER_REG, '')\n    return\n  }\n\n  target.value = event.data || target.value.slice(-1)\n  updateModelValueAt(props.index, target.value)\n\n  const nextEl = inputElements.value[props.index + 1]\n  if (nextEl)\n    nextEl.focus()\n}\n\nfunction updatePlaceholder() {\n  nextTick(() => {\n    const target = currentElement.value as HTMLInputElement\n    if (!target) {\n      return\n    }\n    if (!target.value && target === getActiveElement()) {\n      target.placeholder = ''\n    }\n    else {\n      target.placeholder = context.placeholder.value\n    }\n  })\n}\n\nfunction handleKeydown(event: KeyboardEvent) {\n  // Don't move between inputs mid-composition, arrow keys are used for IME candidate navigation\n  if (isComposing.value || event.isComposing)\n    return\n  useArrowNavigation(event, getActiveElement() as HTMLElement, undefined, {\n    itemsArray: inputElements.value,\n    focus: true,\n    loop: false,\n    arrowKeyOptions: 'horizontal',\n    dir: context.dir.value,\n  })\n}\n\nfunction handleBackspace(event: KeyboardEvent) {\n  event.preventDefault()\n  const target = event.target as HTMLInputElement\n  const value = target.value\n\n  if (value) {\n    updateModelValueAt(props.index, '')\n  }\n  else {\n    const prevEl = inputElements.value[props.index - 1]\n    if (prevEl) {\n      prevEl.focus()\n      updateModelValueAt(props.index - 1, '')\n    }\n  }\n}\n\nfunction handleDelete(event: KeyboardEvent) {\n  if (event.key === 'Delete') {\n    event.preventDefault()\n    updateModelValueAt(props.index, '')\n  }\n}\n\nfunction handleFocus(event: FocusEvent) {\n  // In OTP mode, inputs should be filled one by one without skipping middle inputs\n  if (context.otp.value) {\n    const firstEmptyInputIdx = inputElements.value.findIndex((_, idx) =>\n      context.currentModelValue.value[idx] === ''\n      || context.currentModelValue.value[idx] === undefined,\n    )\n    if (firstEmptyInputIdx !== -1 && firstEmptyInputIdx < props.index) {\n      inputElements.value[firstEmptyInputIdx].focus()\n      return\n    }\n  }\n\n  const target = event.target as HTMLInputElement\n  target.setSelectionRange(1, 1)\n  updatePlaceholder()\n}\n\nfunction handleBlur(event: FocusEvent) {\n  updatePlaceholder()\n}\n\nfunction handlePaste(event: ClipboardEvent) {\n  event.preventDefault()\n  const clipboardData = event.clipboardData\n  if (!clipboardData)\n    return\n\n  const rawValues = clipboardData.getData('text')\n  const values = context.isNumericMode.value\n    ? rawValues.replace(NON_NUMBER_REG, '')\n    : rawValues\n  handleMultipleCharacter(values)\n}\n\nfunction handleMultipleCharacter(values: string) {\n  const tempModelValue = [...context.currentModelValue.value] as typeof context.currentModelValue.value\n  const initialIndex = values.length >= inputElements.value.length ? 0 : props.index\n  const lastIndex = Math.min(initialIndex + values.length, inputElements.value.length)\n  for (let i = initialIndex; i < lastIndex; i++) {\n    const input = inputElements.value[i]\n    const value = values[i - initialIndex]\n    if (context.isNumericMode.value) {\n      const num = Number.parseInt(value)\n      if (Number.isNaN(num))\n        continue\n      tempModelValue[i] = num\n    }\n    else {\n      tempModelValue[i] = value\n    }\n    input.focus()\n  }\n  context.modelValue.value = tempModelValue\n  inputElements.value[lastIndex]?.focus()\n}\n\nfunction removeTrailingEmptyStrings(input: PinInputContextValue<typeof context.type.value>) {\n  let i = input.length - 1\n\n  while (i >= 0 && input[i] === '') {\n    input.pop()\n    i--\n  }\n\n  return input\n}\n\nfunction updateModelValueAt(index: number, value: string) {\n  const tempModelValue = [...context.currentModelValue.value] as typeof context.currentModelValue.value\n\n  if (context.isNumericMode.value) {\n    const num = +value\n\n    if (value === '' || isNaN(num)) {\n      delete tempModelValue[index]\n    }\n    else {\n      tempModelValue[index] = num\n    }\n  }\n  else {\n    tempModelValue[index] = value\n  }\n\n  context.modelValue.value = removeTrailingEmptyStrings(tempModelValue)\n}\n\nwatch(currentValue, updatePlaceholder)\n\nonMounted(() => {\n  context.onInputElementChange(currentElement.value as HTMLInputElement)\n})\nonUnmounted(() => {\n  context.inputElements?.value.delete(currentElement.value as HTMLInputElement)\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    autocapitalize=\"none\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :autocomplete=\"isOtpMode ? 'one-time-code' : 'false'\"\n    :type=\"isPasswordMode ? 'password' : 'text'\"\n    :inputmode=\"context.isNumericMode.value ? 'numeric' : 'text'\"\n    :pattern=\"context.isNumericMode.value ? '[0-9]*' : undefined\"\n    :placeholder=\"context.placeholder.value\"\n    :value=\"currentValue\"\n    :disabled=\"disabled\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-complete=\"context.isCompleted.value ? '' : undefined\"\n    :aria-label=\"`pin input ${index + 1} of ${inputElements.length}`\"\n    @input=\"handleInput($event as InputEvent)\"\n    @keydown.left.right.up.down.home.end=\"handleKeydown\"\n    @keydown.backspace=\"handleBackspace\"\n    @keydown.delete=\"handleDelete\"\n    @focus=\"handleFocus\"\n    @blur=\"handleBlur\"\n    @paste=\"handlePaste\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, isNullish, useForwardExpose } from '@/shared'\n\nexport type ProgressRootEmits = {\n  /** Event handler called when the progress value changes */\n  'update:modelValue': [value: string[] | undefined]\n  /** Event handler called when the max value changes */\n  'update:max': [value: number]\n}\n\nexport interface ProgressRootProps extends PrimitiveProps {\n  /** The progress value. Can be bind as `v-model`. */\n  modelValue?: number | null\n  /** The maximum progress value. */\n  max?: number\n  /**\n   * A function to get the accessible label text in a human-readable format.\n   *\n   *  If not provided, the value label will be read as the numeric value as a percentage of the max value.\n   */\n  getValueLabel?: (value: number | null | undefined, max: number) => string | undefined\n  /**\n   * A function to get the accessible value text representing the current value in a human-readable format.\n   */\n  getValueText?: (value: number | null | undefined, max: number) => string | undefined\n}\n\nconst DEFAULT_MAX = 100\n\ninterface ProgressRootContext {\n  modelValue?: Readonly<Ref<ProgressRootProps['modelValue']>>\n  max: Readonly<Ref<number>>\n  progressState: ComputedRef<ProgressState>\n}\n\nexport const [injectProgressRootContext, provideProgressRootContext]\n  = createContext<ProgressRootContext>('ProgressRoot')\n\nexport type ProgressState = 'indeterminate' | 'loading' | 'complete'\n\nconst isNumber = (v: any): v is number => typeof v === 'number'\n\nfunction validateValue(value: any, max: number): number | null {\n  const isValidValueError\n    = isNullish(value)\n      || (isNumber(value) && !Number.isNaN(value) && value <= max && value >= 0)\n\n  if (isValidValueError)\n    return value as null\n\n  console.error(`Invalid prop \\`value\\` of value \\`${value}\\` supplied to \\`ProgressRoot\\`. The \\`value\\` prop must be:\n  - a positive number\n  - less than the value passed to \\`max\\` (or ${DEFAULT_MAX} if no \\`max\\` prop is set)\n  - \\`null\\`  or \\`undefined\\` if the progress is indeterminate.\n\nDefaulting to \\`null\\`.`)\n  return null\n}\n\nfunction validateMax(max: number): number {\n  const isValidMaxError = isNumber(max) && !Number.isNaN(max) && max > 0\n\n  if (isValidMaxError)\n    return max\n\n  console.error(\n    `Invalid prop \\`max\\` of value \\`${max}\\` supplied to \\`ProgressRoot\\`. Only numbers greater than 0 are valid max values. Defaulting to \\`${DEFAULT_MAX}\\`.`,\n  )\n  return DEFAULT_MAX\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, watch } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<ProgressRootProps>(), {\n  max: DEFAULT_MAX,\n  getValueLabel: (value: number | null | undefined, max: number) =>\n    isNumber(value) ? `${Math.round((value / max) * DEFAULT_MAX)}%` : undefined,\n})\n\nconst emit = defineEmits<ProgressRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nuseForwardExpose()\nconst modelValue = useVModel(props, 'modelValue', emit, {\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst max = useVModel(props, 'max', emit, {\n  passive: (props.max === undefined) as false,\n})\n\n// ------- Watch for correct values -------\nwatch(\n  () => modelValue.value,\n  async (value) => {\n    const correctedValue = validateValue(value, props.max)\n    if (correctedValue !== value) {\n      await nextTick()\n      modelValue.value = correctedValue\n    }\n  },\n  { immediate: true },\n)\n\nwatch(\n  () => props.max,\n  (newMax) => {\n    const correctedMax = validateMax(props.max)\n    if (correctedMax !== newMax)\n      max.value = correctedMax\n  },\n  { immediate: true },\n)\n// ------- End of watch for correct values -------\n\nconst progressState = computed<ProgressState>(() => {\n  if (isNullish(modelValue.value))\n    return 'indeterminate'\n  if (modelValue.value === max.value)\n    return 'complete'\n  return 'loading'\n})\n\nprovideProgressRootContext({\n  modelValue,\n  max,\n  progressState,\n})\n</script>\n\n<template>\n  <Primitive\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :aria-valuemax=\"max\"\n    :aria-valuemin=\"0\"\n    :aria-valuenow=\"isNumber(modelValue) ? modelValue : undefined\"\n    :aria-valuetext=\"getValueText?.(modelValue, max)\"\n    :aria-label=\"getValueLabel(modelValue, max)\"\n    role=\"progressbar\"\n    :data-state=\"progressState\"\n    :data-value=\"modelValue ?? undefined\"\n    :data-max=\"max\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, isNullish, useForwardExpose } from '@/shared'\n\nexport type ProgressRootEmits = {\n  /** Event handler called when the progress value changes */\n  'update:modelValue': [value: string[] | undefined]\n  /** Event handler called when the max value changes */\n  'update:max': [value: number]\n}\n\nexport interface ProgressRootProps extends PrimitiveProps {\n  /** The progress value. Can be bind as `v-model`. */\n  modelValue?: number | null\n  /** The maximum progress value. */\n  max?: number\n  /**\n   * A function to get the accessible label text in a human-readable format.\n   *\n   *  If not provided, the value label will be read as the numeric value as a percentage of the max value.\n   */\n  getValueLabel?: (value: number | null | undefined, max: number) => string | undefined\n  /**\n   * A function to get the accessible value text representing the current value in a human-readable format.\n   */\n  getValueText?: (value: number | null | undefined, max: number) => string | undefined\n}\n\nconst DEFAULT_MAX = 100\n\ninterface ProgressRootContext {\n  modelValue?: Readonly<Ref<ProgressRootProps['modelValue']>>\n  max: Readonly<Ref<number>>\n  progressState: ComputedRef<ProgressState>\n}\n\nexport const [injectProgressRootContext, provideProgressRootContext]\n  = createContext<ProgressRootContext>('ProgressRoot')\n\nexport type ProgressState = 'indeterminate' | 'loading' | 'complete'\n\nconst isNumber = (v: any): v is number => typeof v === 'number'\n\nfunction validateValue(value: any, max: number): number | null {\n  const isValidValueError\n    = isNullish(value)\n      || (isNumber(value) && !Number.isNaN(value) && value <= max && value >= 0)\n\n  if (isValidValueError)\n    return value as null\n\n  console.error(`Invalid prop \\`value\\` of value \\`${value}\\` supplied to \\`ProgressRoot\\`. The \\`value\\` prop must be:\n  - a positive number\n  - less than the value passed to \\`max\\` (or ${DEFAULT_MAX} if no \\`max\\` prop is set)\n  - \\`null\\`  or \\`undefined\\` if the progress is indeterminate.\n\nDefaulting to \\`null\\`.`)\n  return null\n}\n\nfunction validateMax(max: number): number {\n  const isValidMaxError = isNumber(max) && !Number.isNaN(max) && max > 0\n\n  if (isValidMaxError)\n    return max\n\n  console.error(\n    `Invalid prop \\`max\\` of value \\`${max}\\` supplied to \\`ProgressRoot\\`. Only numbers greater than 0 are valid max values. Defaulting to \\`${DEFAULT_MAX}\\`.`,\n  )\n  return DEFAULT_MAX\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, watch } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<ProgressRootProps>(), {\n  max: DEFAULT_MAX,\n  getValueLabel: (value: number | null | undefined, max: number) =>\n    isNumber(value) ? `${Math.round((value / max) * DEFAULT_MAX)}%` : undefined,\n})\n\nconst emit = defineEmits<ProgressRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nuseForwardExpose()\nconst modelValue = useVModel(props, 'modelValue', emit, {\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst max = useVModel(props, 'max', emit, {\n  passive: (props.max === undefined) as false,\n})\n\n// ------- Watch for correct values -------\nwatch(\n  () => modelValue.value,\n  async (value) => {\n    const correctedValue = validateValue(value, props.max)\n    if (correctedValue !== value) {\n      await nextTick()\n      modelValue.value = correctedValue\n    }\n  },\n  { immediate: true },\n)\n\nwatch(\n  () => props.max,\n  (newMax) => {\n    const correctedMax = validateMax(props.max)\n    if (correctedMax !== newMax)\n      max.value = correctedMax\n  },\n  { immediate: true },\n)\n// ------- End of watch for correct values -------\n\nconst progressState = computed<ProgressState>(() => {\n  if (isNullish(modelValue.value))\n    return 'indeterminate'\n  if (modelValue.value === max.value)\n    return 'complete'\n  return 'loading'\n})\n\nprovideProgressRootContext({\n  modelValue,\n  max,\n  progressState,\n})\n</script>\n\n<template>\n  <Primitive\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :aria-valuemax=\"max\"\n    :aria-valuemin=\"0\"\n    :aria-valuenow=\"isNumber(modelValue) ? modelValue : undefined\"\n    :aria-valuetext=\"getValueText?.(modelValue, max)\"\n    :aria-label=\"getValueLabel(modelValue, max)\"\n    role=\"progressbar\"\n    :data-state=\"progressState\"\n    :data-value=\"modelValue ?? undefined\"\n    :data-max=\"max\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ProgressIndicatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectProgressRootContext } from './ProgressRoot.vue'\n\nconst props = defineProps<ProgressIndicatorProps>()\n\nconst rootContext = injectProgressRootContext()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :data-state=\"rootContext.progressState.value\"\n    :data-value=\"rootContext.modelValue?.value ?? undefined\"\n    :data-max=\"rootContext.max.value\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ProgressIndicatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectProgressRootContext } from './ProgressRoot.vue'\n\nconst props = defineProps<ProgressIndicatorProps>()\n\nconst rootContext = injectProgressRootContext()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :data-state=\"rootContext.progressState.value\"\n    :data-value=\"rootContext.modelValue?.value ?? undefined\"\n    :data-max=\"rootContext.max.value\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","import type { AcceptableValue } from '@/shared/types'\nimport { handleAndDispatchCustomEvent } from '@/shared'\n\nexport type SelectEvent = CustomEvent<{ originalEvent: MouseEvent, value?: AcceptableValue }>\nexport const RADIO_SELECT = 'radio.select'\n\nexport function handleSelect(event: MouseEvent, value: AcceptableValue | undefined, callback: (event: SelectEvent) => void) {\n  const eventDetail = { originalEvent: event, value }\n  handleAndDispatchCustomEvent(RADIO_SELECT, callback, eventDetail)\n}\n","<script lang=\"ts\">\nimport type { SelectEvent } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue, FormFieldProps } from '@/shared/types'\n\nexport type RadioEmits = {\n  'update:checked': [value: boolean]\n  'select': [SelectEvent]\n}\n\nexport interface RadioProps extends PrimitiveProps, FormFieldProps {\n  id?: string\n  /** The value given as data when submitted with a `name`. */\n  value?: AcceptableValue\n  /** When `true`, prevents the user from interacting with the radio item. */\n  disabled?: boolean\n  checked?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useFormControl, useForwardExpose } from '@/shared'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\nimport { handleSelect } from './utils'\n\nconst props = withDefaults(defineProps<RadioProps>(), {\n  disabled: false,\n  checked: undefined,\n  as: 'button',\n})\nconst emits = defineEmits<RadioEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current checked state */\n    checked: typeof checked.value\n  }) => any\n}>()\n\nconst checked = useVModel(props, 'checked', emits, {\n  passive: (props.checked === undefined) as false,\n})\n\nconst { value } = toRefs(props)\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\nconst isFormControl = useFormControl(triggerElement)\n\nconst ariaLabel = computed(() => props.id && triggerElement.value ? (document.querySelector(`[for=\"${props.id}\"]`) as HTMLLabelElement)?.innerText ?? props.value : undefined)\n\nfunction handleClick(event: MouseEvent) {\n  if (props.disabled)\n    return\n\n  handleSelect(event, props.value, (ev) => {\n    emits('select', ev)\n    if (ev?.defaultPrevented)\n      return\n\n    checked.value = true\n    if (isFormControl.value) {\n    // if radio is in a form, stop propagation from the button so that we only propagate\n    // one click event (from the input). We propagate changes from an input so that native\n    // form validation works and form events reflect radio updates.\n      ev.stopPropagation()\n    }\n  })\n}\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    :id=\"id\"\n    :ref=\"forwardRef\"\n    role=\"radio\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :as=\"as\"\n    :aria-checked=\"checked\"\n    :aria-label=\"ariaLabel\"\n    :as-child=\"asChild\"\n    :disabled=\"disabled ? '' : undefined\"\n    :data-state=\"checked ? 'checked' : 'unchecked'\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :value=\"value\"\n    :required=\"required\"\n    :name=\"name\"\n    @click.stop=\"handleClick\"\n  >\n    <slot :checked=\"checked\" />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      type=\"radio\"\n      tabindex=\"-1\"\n      :value=\"value\"\n      :checked=\"!!checked\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { SelectEvent } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue, FormFieldProps } from '@/shared/types'\n\nexport type RadioEmits = {\n  'update:checked': [value: boolean]\n  'select': [SelectEvent]\n}\n\nexport interface RadioProps extends PrimitiveProps, FormFieldProps {\n  id?: string\n  /** The value given as data when submitted with a `name`. */\n  value?: AcceptableValue\n  /** When `true`, prevents the user from interacting with the radio item. */\n  disabled?: boolean\n  checked?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useFormControl, useForwardExpose } from '@/shared'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\nimport { handleSelect } from './utils'\n\nconst props = withDefaults(defineProps<RadioProps>(), {\n  disabled: false,\n  checked: undefined,\n  as: 'button',\n})\nconst emits = defineEmits<RadioEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current checked state */\n    checked: typeof checked.value\n  }) => any\n}>()\n\nconst checked = useVModel(props, 'checked', emits, {\n  passive: (props.checked === undefined) as false,\n})\n\nconst { value } = toRefs(props)\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\nconst isFormControl = useFormControl(triggerElement)\n\nconst ariaLabel = computed(() => props.id && triggerElement.value ? (document.querySelector(`[for=\"${props.id}\"]`) as HTMLLabelElement)?.innerText ?? props.value : undefined)\n\nfunction handleClick(event: MouseEvent) {\n  if (props.disabled)\n    return\n\n  handleSelect(event, props.value, (ev) => {\n    emits('select', ev)\n    if (ev?.defaultPrevented)\n      return\n\n    checked.value = true\n    if (isFormControl.value) {\n    // if radio is in a form, stop propagation from the button so that we only propagate\n    // one click event (from the input). We propagate changes from an input so that native\n    // form validation works and form events reflect radio updates.\n      ev.stopPropagation()\n    }\n  })\n}\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    :id=\"id\"\n    :ref=\"forwardRef\"\n    role=\"radio\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :as=\"as\"\n    :aria-checked=\"checked\"\n    :aria-label=\"ariaLabel\"\n    :as-child=\"asChild\"\n    :disabled=\"disabled ? '' : undefined\"\n    :data-state=\"checked ? 'checked' : 'unchecked'\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :value=\"value\"\n    :required=\"required\"\n    :name=\"name\"\n    @click.stop=\"handleClick\"\n  >\n    <slot :checked=\"checked\" />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      type=\"radio\"\n      tabindex=\"-1\"\n      :value=\"value\"\n      :checked=\"!!checked\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue, DataOrientation, Direction, FormFieldProps } from '@/shared/types'\nimport { createContext, useDirection, useFormControl, useForwardExpose } from '@/shared'\n\nexport interface RadioGroupRootProps extends PrimitiveProps, FormFieldProps {\n  /** The controlled value of the radio item to check. Can be binded as `v-model`. */\n  modelValue?: AcceptableValue\n  /**\n   * The value of the radio item that should be checked when initially rendered.\n   *\n   * Use when you do not need to control the state of the radio items.\n   */\n  defaultValue?: AcceptableValue\n  /** When `true`, prevents the user from interacting with radio items. */\n  disabled?: boolean\n  /** The orientation of the component. */\n  orientation?: DataOrientation\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** When `true`, keyboard navigation will loop from last item to first, and vice versa. */\n  loop?: boolean\n}\nexport type RadioGroupRootEmits = {\n  /** Event handler called when the radio group value changes */\n  'update:modelValue': [payload: AcceptableValue]\n}\n\ninterface RadioGroupRootContext {\n  modelValue?: Readonly<Ref<AcceptableValue | undefined>>\n  changeModelValue: (value?: AcceptableValue) => void\n  disabled: Ref<boolean>\n  loop: Ref<boolean>\n  orientation: Ref<DataOrientation | undefined>\n  name?: string\n  required: Ref<boolean>\n}\n\nexport const [injectRadioGroupRootContext, provideRadioGroupRootContext]\n  = createContext<RadioGroupRootContext>('RadioGroupRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusGroup } from '@/RovingFocus'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\nconst props = withDefaults(defineProps<RadioGroupRootProps>(), {\n  disabled: false,\n  required: false,\n  orientation: undefined,\n  loop: true,\n})\n\nconst emits = defineEmits<RadioGroupRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst { disabled, loop, orientation, name, required, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nconst isFormControl = useFormControl(currentElement)\n\nprovideRadioGroupRootContext({\n  modelValue,\n  changeModelValue: (value) => {\n    modelValue.value = value\n  },\n  disabled,\n  loop,\n  orientation,\n  name: name?.value,\n  required,\n})\n</script>\n\n<template>\n  <RovingFocusGroup\n    as-child\n    :orientation=\"orientation\"\n    :dir=\"dir\"\n    :loop=\"loop\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"radiogroup\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      :aria-orientation=\"orientation\"\n      :aria-required=\"required\"\n      :dir=\"dir\"\n    >\n      <slot :model-value=\"modelValue\" />\n\n      <VisuallyHiddenInput\n        v-if=\"isFormControl && name\"\n        :required=\"required\"\n        :disabled=\"disabled\"\n        :value=\"modelValue\"\n        :name=\"name\"\n      />\n    </Primitive>\n  </RovingFocusGroup>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue, DataOrientation, Direction, FormFieldProps } from '@/shared/types'\nimport { createContext, useDirection, useFormControl, useForwardExpose } from '@/shared'\n\nexport interface RadioGroupRootProps extends PrimitiveProps, FormFieldProps {\n  /** The controlled value of the radio item to check. Can be binded as `v-model`. */\n  modelValue?: AcceptableValue\n  /**\n   * The value of the radio item that should be checked when initially rendered.\n   *\n   * Use when you do not need to control the state of the radio items.\n   */\n  defaultValue?: AcceptableValue\n  /** When `true`, prevents the user from interacting with radio items. */\n  disabled?: boolean\n  /** The orientation of the component. */\n  orientation?: DataOrientation\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** When `true`, keyboard navigation will loop from last item to first, and vice versa. */\n  loop?: boolean\n}\nexport type RadioGroupRootEmits = {\n  /** Event handler called when the radio group value changes */\n  'update:modelValue': [payload: AcceptableValue]\n}\n\ninterface RadioGroupRootContext {\n  modelValue?: Readonly<Ref<AcceptableValue | undefined>>\n  changeModelValue: (value?: AcceptableValue) => void\n  disabled: Ref<boolean>\n  loop: Ref<boolean>\n  orientation: Ref<DataOrientation | undefined>\n  name?: string\n  required: Ref<boolean>\n}\n\nexport const [injectRadioGroupRootContext, provideRadioGroupRootContext]\n  = createContext<RadioGroupRootContext>('RadioGroupRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusGroup } from '@/RovingFocus'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\nconst props = withDefaults(defineProps<RadioGroupRootProps>(), {\n  disabled: false,\n  required: false,\n  orientation: undefined,\n  loop: true,\n})\n\nconst emits = defineEmits<RadioGroupRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst { disabled, loop, orientation, name, required, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nconst isFormControl = useFormControl(currentElement)\n\nprovideRadioGroupRootContext({\n  modelValue,\n  changeModelValue: (value) => {\n    modelValue.value = value\n  },\n  disabled,\n  loop,\n  orientation,\n  name: name?.value,\n  required,\n})\n</script>\n\n<template>\n  <RovingFocusGroup\n    as-child\n    :orientation=\"orientation\"\n    :dir=\"dir\"\n    :loop=\"loop\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"radiogroup\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      :aria-orientation=\"orientation\"\n      :aria-required=\"required\"\n      :dir=\"dir\"\n    >\n      <slot :model-value=\"modelValue\" />\n\n      <VisuallyHiddenInput\n        v-if=\"isFormControl && name\"\n        :required=\"required\"\n        :disabled=\"disabled\"\n        :value=\"modelValue\"\n        :name=\"name\"\n      />\n    </Primitive>\n  </RovingFocusGroup>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef } from 'vue'\nimport type { RadioProps } from './Radio.vue'\nimport type { SelectEvent } from './utils'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface RadioGroupItemProps extends Omit<RadioProps, 'checked'> {}\nexport type RadioGroupItemEmits = {\n  select: [event: SelectEvent]\n}\n\ninterface RadioGroupItemContext {\n  disabled: ComputedRef<boolean>\n  checked: ComputedRef<boolean>\n}\n\nexport const [injectRadioGroupItemContext, provideRadiogroupItemContext]\n  = createContext<RadioGroupItemContext>('RadioGroupItem')\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener } from '@vueuse/core'\nimport { isEqual } from 'ohash'\nimport { computed, ref } from 'vue'\nimport { RovingFocusItem } from '@/RovingFocus'\nimport Radio from './Radio.vue'\nimport { injectRadioGroupRootContext } from './RadioGroupRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<RadioGroupItemProps>(), {\n  disabled: false,\n  as: 'button',\n})\n\nconst emits = defineEmits<RadioGroupItemEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current checked state */\n    checked: typeof checked.value\n    /** Required state */\n    required: typeof required.value\n    /** Disabled state */\n    disabled: typeof disabled.value\n  }) => any\n}>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst rootContext = injectRadioGroupRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || props.disabled)\nconst required = computed(() => rootContext.required.value || props.required)\nconst checked = computed(() => isEqual(rootContext.modelValue?.value, props.value))\n\nprovideRadiogroupItemContext({ disabled, checked })\n\nconst isArrowKeyPressed = ref(false)\nconst ARROW_KEYS = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']\n\nuseEventListener('keydown', (event) => {\n  if (ARROW_KEYS.includes(event.key))\n    isArrowKeyPressed.value = true\n})\nuseEventListener('keyup', () => {\n  isArrowKeyPressed.value = false\n})\n\nfunction handleFocus() {\n  setTimeout(() => {\n    /**\n     * Our `RovingFocusGroup` will focus the radio when navigating with arrow keys\n     * and we need to 'check' it in that case. We click it to 'check' it (instead\n     * of updating `context.value`) so that the radio change event fires.\n     */\n    if (isArrowKeyPressed.value)\n      currentElement.value?.click()\n  }, 0)\n}\n</script>\n\n<template>\n  <RovingFocusItem\n    :checked=\"checked\"\n    :disabled=\"disabled\"\n    as-child\n    :focusable=\"!disabled\"\n    :active=\"checked\"\n  >\n    <Radio\n      v-bind=\"{ ...$attrs, ...props }\"\n      :ref=\"forwardRef\"\n      :checked=\"checked\"\n      :required=\"required\"\n      :disabled=\"disabled\"\n      @update:checked=\"rootContext.changeModelValue(value)\"\n      @select=\"emits('select', $event)\"\n      @keydown.enter.prevent\n      @focus=\"handleFocus\"\n    >\n      <slot\n        :checked=\"checked\"\n        :required=\"required\"\n        :disabled=\"disabled\"\n      />\n    </Radio>\n  </RovingFocusItem>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef } from 'vue'\nimport type { RadioProps } from './Radio.vue'\nimport type { SelectEvent } from './utils'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface RadioGroupItemProps extends Omit<RadioProps, 'checked'> {}\nexport type RadioGroupItemEmits = {\n  select: [event: SelectEvent]\n}\n\ninterface RadioGroupItemContext {\n  disabled: ComputedRef<boolean>\n  checked: ComputedRef<boolean>\n}\n\nexport const [injectRadioGroupItemContext, provideRadiogroupItemContext]\n  = createContext<RadioGroupItemContext>('RadioGroupItem')\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener } from '@vueuse/core'\nimport { isEqual } from 'ohash'\nimport { computed, ref } from 'vue'\nimport { RovingFocusItem } from '@/RovingFocus'\nimport Radio from './Radio.vue'\nimport { injectRadioGroupRootContext } from './RadioGroupRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<RadioGroupItemProps>(), {\n  disabled: false,\n  as: 'button',\n})\n\nconst emits = defineEmits<RadioGroupItemEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current checked state */\n    checked: typeof checked.value\n    /** Required state */\n    required: typeof required.value\n    /** Disabled state */\n    disabled: typeof disabled.value\n  }) => any\n}>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst rootContext = injectRadioGroupRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || props.disabled)\nconst required = computed(() => rootContext.required.value || props.required)\nconst checked = computed(() => isEqual(rootContext.modelValue?.value, props.value))\n\nprovideRadiogroupItemContext({ disabled, checked })\n\nconst isArrowKeyPressed = ref(false)\nconst ARROW_KEYS = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']\n\nuseEventListener('keydown', (event) => {\n  if (ARROW_KEYS.includes(event.key))\n    isArrowKeyPressed.value = true\n})\nuseEventListener('keyup', () => {\n  isArrowKeyPressed.value = false\n})\n\nfunction handleFocus() {\n  setTimeout(() => {\n    /**\n     * Our `RovingFocusGroup` will focus the radio when navigating with arrow keys\n     * and we need to 'check' it in that case. We click it to 'check' it (instead\n     * of updating `context.value`) so that the radio change event fires.\n     */\n    if (isArrowKeyPressed.value)\n      currentElement.value?.click()\n  }, 0)\n}\n</script>\n\n<template>\n  <RovingFocusItem\n    :checked=\"checked\"\n    :disabled=\"disabled\"\n    as-child\n    :focusable=\"!disabled\"\n    :active=\"checked\"\n  >\n    <Radio\n      v-bind=\"{ ...$attrs, ...props }\"\n      :ref=\"forwardRef\"\n      :checked=\"checked\"\n      :required=\"required\"\n      :disabled=\"disabled\"\n      @update:checked=\"rootContext.changeModelValue(value)\"\n      @select=\"emits('select', $event)\"\n      @keydown.enter.prevent\n      @focus=\"handleFocus\"\n    >\n      <slot\n        :checked=\"checked\"\n        :required=\"required\"\n        :disabled=\"disabled\"\n      />\n    </Radio>\n  </RovingFocusItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface RadioGroupIndicatorProps extends PrimitiveProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { Primitive } from '@/Primitive'\nimport { injectRadioGroupItemContext } from './RadioGroupItem.vue'\n\nwithDefaults(defineProps<RadioGroupIndicatorProps>(), {\n  as: 'span',\n})\n\nconst { forwardRef } = useForwardExpose()\nconst itemContext = injectRadioGroupItemContext()\n</script>\n\n<template>\n  <Presence\n    :present=\"forceMount || itemContext.checked.value\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :data-state=\"itemContext.checked.value ? 'checked' : 'unchecked'\"\n      :data-disabled=\"itemContext.disabled.value ? '' : undefined\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      v-bind=\"$attrs\"\n    >\n      <slot />\n    </Primitive>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface RadioGroupIndicatorProps extends PrimitiveProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { Primitive } from '@/Primitive'\nimport { injectRadioGroupItemContext } from './RadioGroupItem.vue'\n\nwithDefaults(defineProps<RadioGroupIndicatorProps>(), {\n  as: 'span',\n})\n\nconst { forwardRef } = useForwardExpose()\nconst itemContext = injectRadioGroupItemContext()\n</script>\n\n<template>\n  <Presence\n    :present=\"forceMount || itemContext.checked.value\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :data-state=\"itemContext.checked.value ? 'checked' : 'unchecked'\"\n      :data-disabled=\"itemContext.disabled.value ? '' : undefined\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      v-bind=\"$attrs\"\n    >\n      <slot />\n    </Primitive>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Direction, ScrollType } from './types'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\nexport interface ScrollAreaRootContext {\n  type: Ref<ScrollType>\n  dir: Ref<Direction>\n  scrollHideDelay: Ref<number>\n  scrollArea: Ref<HTMLElement | undefined>\n  viewport: Ref<HTMLElement | undefined>\n  onViewportChange: (viewport: HTMLElement | null) => void\n  content: Ref<HTMLElement | undefined>\n  onContentChange: (content: HTMLElement) => void\n  scrollbarX: Ref<HTMLElement | undefined>\n  onScrollbarXChange: (scrollbar: HTMLElement | null) => void\n  scrollbarXEnabled: Ref<boolean>\n  onScrollbarXEnabledChange: (rendered: boolean) => void\n  scrollbarY: Ref<HTMLElement | undefined>\n  onScrollbarYChange: (scrollbar: HTMLElement | null) => void\n  scrollbarYEnabled: Ref<boolean>\n  onScrollbarYEnabledChange: (rendered: boolean) => void\n  onCornerWidthChange: (width: number) => void\n  onCornerHeightChange: (height: number) => void\n}\n\nexport const [injectScrollAreaRootContext, provideScrollAreaRootContext]\n  = createContext<ScrollAreaRootContext>('ScrollAreaRoot')\n\nexport interface ScrollAreaRootProps extends PrimitiveProps {\n  /**\n   * Describes the nature of scrollbar visibility, similar to how the scrollbar preferences in MacOS control visibility of native scrollbars.\n   *\n   * `auto` - means that scrollbars are visible when content is overflowing on the corresponding orientation. <br>\n   * `always` - means that scrollbars are always visible regardless of whether the content is overflowing.<br>\n   * `scroll` - means that scrollbars are visible when the user is scrolling along its corresponding orientation.<br>\n   * `hover` - when the user is scrolling along its corresponding orientation and when the user is hovering over the scroll area.<br>\n   * `glimpse` - a hybrid approach that briefly shows scrollbars when the user enters the scroll area, then hides them until further interaction.\n   */\n  type?: ScrollType\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** If type is set to either `scroll` or `hover`, this prop determines the length of time, in milliseconds, <br> before the scrollbars are hidden after the user stops interacting with scrollbars. */\n  scrollHideDelay?: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<ScrollAreaRootProps>(), {\n  type: 'hover',\n  scrollHideDelay: 600,\n})\n\nconst cornerWidth = ref(0)\nconst cornerHeight = ref(0)\nconst viewport = ref<HTMLElement>()\nconst content = ref<HTMLElement>()\nconst scrollbarX = ref<HTMLElement>()\nconst scrollbarY = ref<HTMLElement>()\nconst scrollbarXEnabled = ref(false)\nconst scrollbarYEnabled = ref(false)\n\nconst { type, dir: propDir, scrollHideDelay } = toRefs(props)\nconst dir = useDirection(propDir)\n\nfunction scrollTop() {\n  viewport.value?.scrollTo({\n    top: 0,\n  })\n}\nfunction scrollTopLeft() {\n  viewport.value?.scrollTo({\n    top: 0,\n    left: 0,\n  })\n}\n\ndefineExpose({\n  /** Viewport element within ScrollArea */\n  viewport,\n  /** Scroll viewport to top */\n  scrollTop,\n  /** Scroll viewport to top-left */\n  scrollTopLeft,\n})\n\nconst { forwardRef, currentElement: scrollArea } = useForwardExpose()\n\nprovideScrollAreaRootContext({\n  type,\n  dir,\n  scrollHideDelay,\n  scrollArea,\n  viewport,\n  onViewportChange: (el) => {\n    viewport.value = el || undefined\n  },\n  content,\n  onContentChange: (el) => {\n    content.value = el\n  },\n  scrollbarX,\n  scrollbarXEnabled,\n  scrollbarY,\n  scrollbarYEnabled,\n  onScrollbarXChange: (scrollbar) => {\n    scrollbarX.value = scrollbar || undefined\n  },\n  onScrollbarYChange: (scrollbar) => {\n    scrollbarY.value = scrollbar || undefined\n  },\n  onScrollbarXEnabledChange: (rendered) => {\n    scrollbarXEnabled.value = rendered\n  },\n  onScrollbarYEnabledChange: (rendered) => {\n    scrollbarYEnabled.value = rendered\n  },\n  onCornerWidthChange: (width) => {\n    cornerWidth.value = width\n  },\n  onCornerHeightChange: (height) => {\n    cornerHeight.value = height\n  },\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as-child=\"props.asChild\"\n    :as=\"as\"\n    :dir=\"dir\"\n    :style=\"{\n      position: 'relative',\n      // Pass corner sizes as CSS vars to reduce re-renders of context consumers\n      ['--reka-scroll-area-corner-width' as any]: `${cornerWidth}px`,\n      ['--reka-scroll-area-corner-height' as any]: `${cornerHeight}px`,\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Direction, ScrollType } from './types'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\nexport interface ScrollAreaRootContext {\n  type: Ref<ScrollType>\n  dir: Ref<Direction>\n  scrollHideDelay: Ref<number>\n  scrollArea: Ref<HTMLElement | undefined>\n  viewport: Ref<HTMLElement | undefined>\n  onViewportChange: (viewport: HTMLElement | null) => void\n  content: Ref<HTMLElement | undefined>\n  onContentChange: (content: HTMLElement) => void\n  scrollbarX: Ref<HTMLElement | undefined>\n  onScrollbarXChange: (scrollbar: HTMLElement | null) => void\n  scrollbarXEnabled: Ref<boolean>\n  onScrollbarXEnabledChange: (rendered: boolean) => void\n  scrollbarY: Ref<HTMLElement | undefined>\n  onScrollbarYChange: (scrollbar: HTMLElement | null) => void\n  scrollbarYEnabled: Ref<boolean>\n  onScrollbarYEnabledChange: (rendered: boolean) => void\n  onCornerWidthChange: (width: number) => void\n  onCornerHeightChange: (height: number) => void\n}\n\nexport const [injectScrollAreaRootContext, provideScrollAreaRootContext]\n  = createContext<ScrollAreaRootContext>('ScrollAreaRoot')\n\nexport interface ScrollAreaRootProps extends PrimitiveProps {\n  /**\n   * Describes the nature of scrollbar visibility, similar to how the scrollbar preferences in MacOS control visibility of native scrollbars.\n   *\n   * `auto` - means that scrollbars are visible when content is overflowing on the corresponding orientation. <br>\n   * `always` - means that scrollbars are always visible regardless of whether the content is overflowing.<br>\n   * `scroll` - means that scrollbars are visible when the user is scrolling along its corresponding orientation.<br>\n   * `hover` - when the user is scrolling along its corresponding orientation and when the user is hovering over the scroll area.<br>\n   * `glimpse` - a hybrid approach that briefly shows scrollbars when the user enters the scroll area, then hides them until further interaction.\n   */\n  type?: ScrollType\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** If type is set to either `scroll` or `hover`, this prop determines the length of time, in milliseconds, <br> before the scrollbars are hidden after the user stops interacting with scrollbars. */\n  scrollHideDelay?: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<ScrollAreaRootProps>(), {\n  type: 'hover',\n  scrollHideDelay: 600,\n})\n\nconst cornerWidth = ref(0)\nconst cornerHeight = ref(0)\nconst viewport = ref<HTMLElement>()\nconst content = ref<HTMLElement>()\nconst scrollbarX = ref<HTMLElement>()\nconst scrollbarY = ref<HTMLElement>()\nconst scrollbarXEnabled = ref(false)\nconst scrollbarYEnabled = ref(false)\n\nconst { type, dir: propDir, scrollHideDelay } = toRefs(props)\nconst dir = useDirection(propDir)\n\nfunction scrollTop() {\n  viewport.value?.scrollTo({\n    top: 0,\n  })\n}\nfunction scrollTopLeft() {\n  viewport.value?.scrollTo({\n    top: 0,\n    left: 0,\n  })\n}\n\ndefineExpose({\n  /** Viewport element within ScrollArea */\n  viewport,\n  /** Scroll viewport to top */\n  scrollTop,\n  /** Scroll viewport to top-left */\n  scrollTopLeft,\n})\n\nconst { forwardRef, currentElement: scrollArea } = useForwardExpose()\n\nprovideScrollAreaRootContext({\n  type,\n  dir,\n  scrollHideDelay,\n  scrollArea,\n  viewport,\n  onViewportChange: (el) => {\n    viewport.value = el || undefined\n  },\n  content,\n  onContentChange: (el) => {\n    content.value = el\n  },\n  scrollbarX,\n  scrollbarXEnabled,\n  scrollbarY,\n  scrollbarYEnabled,\n  onScrollbarXChange: (scrollbar) => {\n    scrollbarX.value = scrollbar || undefined\n  },\n  onScrollbarYChange: (scrollbar) => {\n    scrollbarY.value = scrollbar || undefined\n  },\n  onScrollbarXEnabledChange: (rendered) => {\n    scrollbarXEnabled.value = rendered\n  },\n  onScrollbarYEnabledChange: (rendered) => {\n    scrollbarYEnabled.value = rendered\n  },\n  onCornerWidthChange: (width) => {\n    cornerWidth.value = width\n  },\n  onCornerHeightChange: (height) => {\n    cornerHeight.value = height\n  },\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as-child=\"props.asChild\"\n    :as=\"as\"\n    :dir=\"dir\"\n    :style=\"{\n      position: 'relative',\n      // Pass corner sizes as CSS vars to reduce re-renders of context consumers\n      ['--reka-scroll-area-corner-width' as any]: `${cornerWidth}px`,\n      ['--reka-scroll-area-corner-height' as any]: `${cornerHeight}px`,\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script setup lang=\"ts\">\nimport { useResizeObserver } from '@vueuse/core'\nimport { computed, ref, watch } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\n\nconst rootContext = injectScrollAreaRootContext()\n\nconst width = ref(0)\nconst height = ref(0)\n\nconst hasSize = computed(() => !!width.value && !!height.value)\n\nfunction setCornerHeight() {\n  const offsetHeight = rootContext.scrollbarX.value?.offsetHeight || 0\n  rootContext.onCornerHeightChange(offsetHeight)\n  height.value = offsetHeight\n}\nfunction setCornerWidth() {\n  const offsetWidth = rootContext.scrollbarY.value?.offsetWidth || 0\n  rootContext.onCornerWidthChange(offsetWidth)\n  width.value = offsetWidth\n}\n\nuseResizeObserver(rootContext.scrollbarX.value, setCornerHeight)\nuseResizeObserver(rootContext.scrollbarY.value, setCornerWidth)\n\n// because we are not remounting the component, useResizeObserver doesn't trigger, thus using watcher here\nwatch(() => rootContext.scrollbarX.value, setCornerHeight)\nwatch(() => rootContext.scrollbarY.value, setCornerWidth)\n</script>\n\n<template>\n  <Primitive\n    v-if=\"hasSize\"\n    :style=\"{\n      width: `${width}px`,\n      height: `${height}px`,\n      position: 'absolute',\n      right: rootContext.dir.value === 'ltr' ? 0 : undefined,\n      left: rootContext.dir.value === 'rtl' ? 0 : undefined,\n      bottom: 0,\n    }\"\n    v-bind=\"$parent?.$props\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script setup lang=\"ts\">\nimport { useResizeObserver } from '@vueuse/core'\nimport { computed, ref, watch } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\n\nconst rootContext = injectScrollAreaRootContext()\n\nconst width = ref(0)\nconst height = ref(0)\n\nconst hasSize = computed(() => !!width.value && !!height.value)\n\nfunction setCornerHeight() {\n  const offsetHeight = rootContext.scrollbarX.value?.offsetHeight || 0\n  rootContext.onCornerHeightChange(offsetHeight)\n  height.value = offsetHeight\n}\nfunction setCornerWidth() {\n  const offsetWidth = rootContext.scrollbarY.value?.offsetWidth || 0\n  rootContext.onCornerWidthChange(offsetWidth)\n  width.value = offsetWidth\n}\n\nuseResizeObserver(rootContext.scrollbarX.value, setCornerHeight)\nuseResizeObserver(rootContext.scrollbarY.value, setCornerWidth)\n\n// because we are not remounting the component, useResizeObserver doesn't trigger, thus using watcher here\nwatch(() => rootContext.scrollbarX.value, setCornerHeight)\nwatch(() => rootContext.scrollbarY.value, setCornerWidth)\n</script>\n\n<template>\n  <Primitive\n    v-if=\"hasSize\"\n    :style=\"{\n      width: `${width}px`,\n      height: `${height}px`,\n      position: 'absolute',\n      right: rootContext.dir.value === 'ltr' ? 0 : undefined,\n      left: rootContext.dir.value === 'rtl' ? 0 : undefined,\n      bottom: 0,\n    }\"\n    v-bind=\"$parent?.$props\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ScrollAreaCornerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport ScrollAreaCornerImpl from './ScrollAreaCornerImpl.vue'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\n\nconst props = defineProps<ScrollAreaCornerProps>()\n\nconst { forwardRef } = useForwardExpose()\nconst rootContext = injectScrollAreaRootContext()\n\nconst hasBothScrollbarsVisible = computed(\n  () => !!rootContext.scrollbarX.value && !!rootContext.scrollbarY.value,\n)\nconst hasCorner = computed(\n  () => rootContext.type.value !== 'scroll' && hasBothScrollbarsVisible.value,\n)\n</script>\n\n<template>\n  <ScrollAreaCornerImpl\n    v-if=\"hasCorner\"\n    v-bind=\"props\"\n    :ref=\"forwardRef\"\n  >\n    <slot />\n  </ScrollAreaCornerImpl>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ScrollAreaCornerProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport ScrollAreaCornerImpl from './ScrollAreaCornerImpl.vue'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\n\nconst props = defineProps<ScrollAreaCornerProps>()\n\nconst { forwardRef } = useForwardExpose()\nconst rootContext = injectScrollAreaRootContext()\n\nconst hasBothScrollbarsVisible = computed(\n  () => !!rootContext.scrollbarX.value && !!rootContext.scrollbarY.value,\n)\nconst hasCorner = computed(\n  () => rootContext.type.value !== 'scroll' && hasBothScrollbarsVisible.value,\n)\n</script>\n\n<template>\n  <ScrollAreaCornerImpl\n    v-if=\"hasCorner\"\n    v-bind=\"props\"\n    :ref=\"forwardRef\"\n  >\n    <slot />\n  </ScrollAreaCornerImpl>\n</template>\n","import type { Direction, Sizes } from './types'\nimport { clamp } from '@/shared'\n\n// https://github.com/tmcw-up-for-adoption/simple-linear-scale/blob/master/index.js\nfunction linearScale(\n  input: readonly [number, number],\n  output: readonly [number, number],\n) {\n  return (value: number) => {\n    if (input[0] === input[1] || output[0] === output[1])\n      return output[0]\n    const ratio = (output[1] - output[0]) / (input[1] - input[0])\n    return output[0] + ratio * (value - input[0])\n  }\n}\n\nexport function getThumbSize(sizes: Sizes) {\n  const ratio = getThumbRatio(sizes.viewport, sizes.content)\n  const scrollbarPadding\n    = sizes.scrollbar.paddingStart + sizes.scrollbar.paddingEnd\n  const thumbSize = (sizes.scrollbar.size - scrollbarPadding) * ratio\n  // minimum of 18 matches macOS minimum\n  return Math.max(thumbSize, 18)\n}\n\nexport function getThumbRatio(viewportSize: number, contentSize: number) {\n  const ratio = viewportSize / contentSize\n  return Number.isNaN(ratio) ? 0 : ratio\n}\n\n// Custom scroll handler to avoid scroll-linked effects\n// https://developer.mozilla.org/en-US/docs/Mozilla/Performance/Scroll-linked_effects\nexport function addUnlinkedScrollListener(\n  node: HTMLElement,\n  handler = () => {},\n) {\n  let prevPosition = { left: node.scrollLeft, top: node.scrollTop }\n  let rAF = 0;\n  (function loop() {\n    const position = { left: node.scrollLeft, top: node.scrollTop }\n    const isHorizontalScroll = prevPosition.left !== position.left\n    const isVerticalScroll = prevPosition.top !== position.top\n    if (isHorizontalScroll || isVerticalScroll)\n      handler()\n    prevPosition = position\n    rAF = window.requestAnimationFrame(loop)\n  })()\n  return () => window.cancelAnimationFrame(rAF)\n}\n\nexport function getThumbOffsetFromScroll(\n  scrollPos: number,\n  sizes: Sizes,\n  dir: Direction = 'ltr',\n) {\n  const thumbSizePx = getThumbSize(sizes)\n  const scrollbarPadding\n    = sizes.scrollbar.paddingStart + sizes.scrollbar.paddingEnd\n  const scrollbar = sizes.scrollbar.size - scrollbarPadding\n  const maxScrollPos = sizes.content - sizes.viewport\n  const maxThumbPos = scrollbar - thumbSizePx\n  const scrollClampRange\n    = dir === 'ltr' ? [0, maxScrollPos] : [maxScrollPos * -1, 0]\n  const scrollWithoutMomentum = clamp(\n    scrollPos,\n    scrollClampRange[0],\n    scrollClampRange[1],\n  )\n  const interpolate = linearScale([0, maxScrollPos], [0, maxThumbPos])\n  return interpolate(scrollWithoutMomentum)\n}\n\nexport function toInt(value?: string) {\n  return value ? Number.parseInt(value, 10) : 0\n}\n\nexport function getScrollPositionFromPointer(\n  pointerPos: number,\n  pointerOffset: number,\n  sizes: Sizes,\n  dir: Direction = 'ltr',\n) {\n  const thumbSizePx = getThumbSize(sizes)\n  const thumbCenter = thumbSizePx / 2\n  const offset = pointerOffset || thumbCenter\n  const thumbOffsetFromEnd = thumbSizePx - offset\n  const minPointerPos = sizes.scrollbar.paddingStart + offset\n  const maxPointerPos\n    = sizes.scrollbar.size - sizes.scrollbar.paddingEnd - thumbOffsetFromEnd\n  const maxScrollPos = sizes.content - sizes.viewport\n  const scrollRange\n    = dir === 'ltr' ? [0, maxScrollPos] : [maxScrollPos * -1, 0]\n  const interpolate = linearScale(\n    [minPointerPos, maxPointerPos],\n    scrollRange as [number, number],\n  )\n  return interpolate(pointerPos)\n}\n\nexport function isScrollingWithinScrollbarBounds(\n  scrollPos: number,\n  maxScrollPos: number,\n) {\n  return scrollPos > 0 && scrollPos < maxScrollPos\n}\n","<script setup lang=\"ts\">\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport ScrollAreaScrollbarImpl from './ScrollAreaScrollbarImpl.vue'\nimport { injectScrollAreaScrollbarVisibleContext } from './ScrollAreaScrollbarVisible.vue'\nimport { getThumbSize } from './utils'\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarVisibleContext = injectScrollAreaScrollbarVisibleContext()\n\nconst { forwardRef, currentElement: scrollbarElement } = useForwardExpose()\n\nonMounted(() => {\n  if (scrollbarElement.value)\n    rootContext.onScrollbarXChange(scrollbarElement.value)\n})\n// Clear the registration on unmount so consumers (e.g. ScrollAreaCorner) don't\n// hold a stale reference once the scrollbar is removed (e.g. between hover cycles).\nonUnmounted(() => {\n  rootContext.onScrollbarXChange(null)\n})\nconst sizes = computed(() => scrollbarVisibleContext.sizes.value)\n</script>\n\n<template>\n  <ScrollAreaScrollbarImpl\n    :ref=\"forwardRef\"\n    :is-horizontal=\"true\"\n    data-orientation=\"horizontal\"\n    :style=\"{\n      bottom: 0,\n      left: rootContext.dir.value === 'rtl' ? 'var(--reka-scroll-area-corner-width)' : 0,\n      right: rootContext.dir.value === 'ltr' ? 'var(--reka-scroll-area-corner-width)' : 0,\n      ['--reka-scroll-area-thumb-width' as any]: sizes ? `${getThumbSize(sizes)}px` : undefined,\n    }\"\n    @on-drag-scroll=\"scrollbarVisibleContext.onDragScroll($event.x)\"\n  >\n    <slot />\n  </ScrollAreaScrollbarImpl>\n</template>\n","<script setup lang=\"ts\">\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport ScrollAreaScrollbarImpl from './ScrollAreaScrollbarImpl.vue'\nimport { injectScrollAreaScrollbarVisibleContext } from './ScrollAreaScrollbarVisible.vue'\nimport { getThumbSize } from './utils'\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarVisibleContext = injectScrollAreaScrollbarVisibleContext()\n\nconst { forwardRef, currentElement: scrollbarElement } = useForwardExpose()\n\nonMounted(() => {\n  if (scrollbarElement.value)\n    rootContext.onScrollbarXChange(scrollbarElement.value)\n})\n// Clear the registration on unmount so consumers (e.g. ScrollAreaCorner) don't\n// hold a stale reference once the scrollbar is removed (e.g. between hover cycles).\nonUnmounted(() => {\n  rootContext.onScrollbarXChange(null)\n})\nconst sizes = computed(() => scrollbarVisibleContext.sizes.value)\n</script>\n\n<template>\n  <ScrollAreaScrollbarImpl\n    :ref=\"forwardRef\"\n    :is-horizontal=\"true\"\n    data-orientation=\"horizontal\"\n    :style=\"{\n      bottom: 0,\n      left: rootContext.dir.value === 'rtl' ? 'var(--reka-scroll-area-corner-width)' : 0,\n      right: rootContext.dir.value === 'ltr' ? 'var(--reka-scroll-area-corner-width)' : 0,\n      ['--reka-scroll-area-thumb-width' as any]: sizes ? `${getThumbSize(sizes)}px` : undefined,\n    }\"\n    @on-drag-scroll=\"scrollbarVisibleContext.onDragScroll($event.x)\"\n  >\n    <slot />\n  </ScrollAreaScrollbarImpl>\n</template>\n","<script setup lang=\"ts\">\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport ScrollAreaScrollbarImpl from './ScrollAreaScrollbarImpl.vue'\nimport { injectScrollAreaScrollbarVisibleContext } from './ScrollAreaScrollbarVisible.vue'\nimport { getThumbSize } from './utils'\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarVisibleContext = injectScrollAreaScrollbarVisibleContext()\n\nconst { forwardRef, currentElement: scrollbarElement } = useForwardExpose()\n\nonMounted(() => {\n  if (scrollbarElement.value)\n    rootContext.onScrollbarYChange(scrollbarElement.value)\n})\n// Clear the registration on unmount so consumers (e.g. ScrollAreaCorner) don't\n// hold a stale reference once the scrollbar is removed (e.g. between hover cycles).\nonUnmounted(() => {\n  rootContext.onScrollbarYChange(null)\n})\n\nconst sizes = computed(() => scrollbarVisibleContext.sizes.value)\n</script>\n\n<template>\n  <ScrollAreaScrollbarImpl\n    :ref=\"forwardRef\"\n    :is-horizontal=\"false\"\n    data-orientation=\"vertical\"\n    :style=\"{\n      top: 0,\n      right: rootContext.dir.value === 'ltr' ? 0 : undefined,\n      left: rootContext.dir.value === 'rtl' ? 0 : undefined,\n      bottom: 'var(--reka-scroll-area-corner-height)',\n      ['--reka-scroll-area-thumb-height' as any]: sizes ? `${getThumbSize(sizes)}px` : undefined,\n    }\"\n    @on-drag-scroll=\"scrollbarVisibleContext.onDragScroll($event.y)\"\n  >\n    <slot />\n  </ScrollAreaScrollbarImpl>\n</template>\n","<script setup lang=\"ts\">\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport ScrollAreaScrollbarImpl from './ScrollAreaScrollbarImpl.vue'\nimport { injectScrollAreaScrollbarVisibleContext } from './ScrollAreaScrollbarVisible.vue'\nimport { getThumbSize } from './utils'\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarVisibleContext = injectScrollAreaScrollbarVisibleContext()\n\nconst { forwardRef, currentElement: scrollbarElement } = useForwardExpose()\n\nonMounted(() => {\n  if (scrollbarElement.value)\n    rootContext.onScrollbarYChange(scrollbarElement.value)\n})\n// Clear the registration on unmount so consumers (e.g. ScrollAreaCorner) don't\n// hold a stale reference once the scrollbar is removed (e.g. between hover cycles).\nonUnmounted(() => {\n  rootContext.onScrollbarYChange(null)\n})\n\nconst sizes = computed(() => scrollbarVisibleContext.sizes.value)\n</script>\n\n<template>\n  <ScrollAreaScrollbarImpl\n    :ref=\"forwardRef\"\n    :is-horizontal=\"false\"\n    data-orientation=\"vertical\"\n    :style=\"{\n      top: 0,\n      right: rootContext.dir.value === 'ltr' ? 0 : undefined,\n      left: rootContext.dir.value === 'rtl' ? 0 : undefined,\n      bottom: 'var(--reka-scroll-area-corner-height)',\n      ['--reka-scroll-area-thumb-height' as any]: sizes ? `${getThumbSize(sizes)}px` : undefined,\n    }\"\n    @on-drag-scroll=\"scrollbarVisibleContext.onDragScroll($event.y)\"\n  >\n    <slot />\n  </ScrollAreaScrollbarImpl>\n</template>\n","<script lang=\"ts\">\nexport interface ScrollAreaScrollbarAutoProps {\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useDebounceFn, useResizeObserver } from '@vueuse/core'\nimport { onMounted, ref } from 'vue'\nimport { Presence } from '@/Presence'\nimport { useForwardExpose } from '@/shared'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport { injectScrollAreaScrollbarContext } from './ScrollAreaScrollbar.vue'\nimport ScrollAreaScrollbarVisible from './ScrollAreaScrollbarVisible.vue'\n\ndefineProps<ScrollAreaScrollbarAutoProps>()\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarContext = injectScrollAreaScrollbarContext()\n\nconst { forwardRef } = useForwardExpose()\n\nconst visible = ref(false)\n\nconst handleResize = useDebounceFn(() => {\n  if (rootContext.viewport.value) {\n    const isOverflowX\n      = rootContext.viewport.value.offsetWidth\n        < rootContext.viewport.value.scrollWidth\n    const isOverflowY\n      = rootContext.viewport.value.offsetHeight\n        < rootContext.viewport.value.scrollHeight\n\n    visible.value = scrollbarContext.isHorizontal.value\n      ? isOverflowX\n      : isOverflowY\n  }\n}, 10)\n\nonMounted(() => handleResize())\n\nuseResizeObserver(rootContext.viewport, handleResize)\nuseResizeObserver(rootContext.content, handleResize)\n</script>\n\n<template>\n  <Presence :present=\"forceMount || visible\">\n    <ScrollAreaScrollbarVisible\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :data-state=\"visible ? 'visible' : 'hidden'\"\n    >\n      <slot />\n    </ScrollAreaScrollbarVisible>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nexport interface ScrollAreaScrollbarAutoProps {\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useDebounceFn, useResizeObserver } from '@vueuse/core'\nimport { onMounted, ref } from 'vue'\nimport { Presence } from '@/Presence'\nimport { useForwardExpose } from '@/shared'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport { injectScrollAreaScrollbarContext } from './ScrollAreaScrollbar.vue'\nimport ScrollAreaScrollbarVisible from './ScrollAreaScrollbarVisible.vue'\n\ndefineProps<ScrollAreaScrollbarAutoProps>()\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarContext = injectScrollAreaScrollbarContext()\n\nconst { forwardRef } = useForwardExpose()\n\nconst visible = ref(false)\n\nconst handleResize = useDebounceFn(() => {\n  if (rootContext.viewport.value) {\n    const isOverflowX\n      = rootContext.viewport.value.offsetWidth\n        < rootContext.viewport.value.scrollWidth\n    const isOverflowY\n      = rootContext.viewport.value.offsetHeight\n        < rootContext.viewport.value.scrollHeight\n\n    visible.value = scrollbarContext.isHorizontal.value\n      ? isOverflowX\n      : isOverflowY\n  }\n}, 10)\n\nonMounted(() => handleResize())\n\nuseResizeObserver(rootContext.viewport, handleResize)\nuseResizeObserver(rootContext.content, handleResize)\n</script>\n\n<template>\n  <Presence :present=\"forceMount || visible\">\n    <ScrollAreaScrollbarVisible\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :data-state=\"visible ? 'visible' : 'hidden'\"\n    >\n      <slot />\n    </ScrollAreaScrollbarVisible>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { ScrollAreaScrollbarAutoProps } from './ScrollAreaScrollbarAuto.vue'\n\nexport interface ScrollAreaScrollbarGlimpseProps extends ScrollAreaScrollbarAutoProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useDebounceFn } from '@vueuse/core'\nimport { computed, onMounted, onUnmounted, watchEffect } from 'vue'\nimport { Presence } from '@/Presence'\nimport { useForwardExpose } from '@/shared'\nimport { useStateMachine } from '../shared/useStateMachine'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport { injectScrollAreaScrollbarContext } from './ScrollAreaScrollbar.vue'\nimport ScrollAreaScrollbarAuto from './ScrollAreaScrollbarAuto.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\ndefineProps<ScrollAreaScrollbarGlimpseProps>()\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarContext = injectScrollAreaScrollbarContext()\n\nconst { forwardRef } = useForwardExpose()\n\nconst { state, dispatch } = useStateMachine('hidden', {\n  hidden: {\n    POINTER_ENTER: 'glimpse',\n    SCROLL: 'scrolling',\n  },\n  glimpse: {\n    HIDE: 'hidden',\n    POINTER_LEAVE: 'hidden',\n    SCROLL: 'scrolling',\n    POINTER_ENTER: 'glimpse',\n  },\n  scrolling: {\n    SCROLL_END: 'idle',\n    POINTER_ENTER: 'interacting',\n  },\n  interacting: {\n    SCROLL: 'interacting',\n    POINTER_LEAVE: 'idle',\n  },\n  idle: {\n    HIDE: 'hidden',\n    SCROLL: 'scrolling',\n    POINTER_ENTER: 'interacting',\n  },\n})\n\nconst visible = computed(() => state.value !== 'hidden')\n\nfunction handlePointerEnter() {\n  dispatch('POINTER_ENTER')\n}\n\nfunction handlePointerLeave() {\n  dispatch('POINTER_LEAVE')\n}\n\nconst debounceScrollEnd = useDebounceFn(() => dispatch('SCROLL_END'), 100)\n\nwatchEffect((onCleanup) => {\n  if (state.value === 'glimpse') {\n    const timeId = window.setTimeout(dispatch, rootContext.scrollHideDelay.value, 'HIDE')\n\n    onCleanup(() => {\n      window.clearTimeout(timeId)\n    })\n  }\n})\n\nwatchEffect((onCleanup) => {\n  if (state.value === 'idle') {\n    const timeId = window.setTimeout(dispatch, rootContext.scrollHideDelay.value, 'HIDE')\n\n    onCleanup(() => {\n      window.clearTimeout(timeId)\n    })\n  }\n})\n\nwatchEffect((onCleanup) => {\n  const viewport = rootContext.viewport.value\n  const scrollDirection = scrollbarContext.isHorizontal.value\n    ? 'scrollLeft'\n    : 'scrollTop'\n\n  if (viewport) {\n    let prevScrollPos = viewport[scrollDirection]\n    const handleScroll = () => {\n      const scrollPos = viewport[scrollDirection]\n      const hasScrollInDirectionChanged = prevScrollPos !== scrollPos\n      if (hasScrollInDirectionChanged) {\n        dispatch('SCROLL')\n        debounceScrollEnd()\n      }\n      prevScrollPos = scrollPos\n    }\n    viewport.addEventListener('scroll', handleScroll)\n\n    onCleanup(() => {\n      viewport.removeEventListener('scroll', handleScroll)\n    })\n  }\n})\n\nonMounted(() => {\n  const scrollArea = rootContext.scrollArea.value\n\n  if (scrollArea) {\n    scrollArea.addEventListener('pointerenter', handlePointerEnter)\n    scrollArea.addEventListener('pointerleave', handlePointerLeave)\n  }\n})\n\nonUnmounted(() => {\n  const scrollArea = rootContext.scrollArea.value\n  if (scrollArea) {\n    scrollArea.removeEventListener('pointerenter', handlePointerEnter)\n    scrollArea.removeEventListener('pointerleave', handlePointerLeave)\n  }\n})\n</script>\n\n<template>\n  <Presence :present=\"forceMount || visible\">\n    <ScrollAreaScrollbarAuto\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :data-state=\"visible ? 'visible' : 'hidden'\"\n    >\n      <slot />\n    </ScrollAreaScrollbarAuto>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { ScrollAreaScrollbarAutoProps } from './ScrollAreaScrollbarAuto.vue'\n\nexport interface ScrollAreaScrollbarGlimpseProps extends ScrollAreaScrollbarAutoProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useDebounceFn } from '@vueuse/core'\nimport { computed, onMounted, onUnmounted, watchEffect } from 'vue'\nimport { Presence } from '@/Presence'\nimport { useForwardExpose } from '@/shared'\nimport { useStateMachine } from '../shared/useStateMachine'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport { injectScrollAreaScrollbarContext } from './ScrollAreaScrollbar.vue'\nimport ScrollAreaScrollbarAuto from './ScrollAreaScrollbarAuto.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\ndefineProps<ScrollAreaScrollbarGlimpseProps>()\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarContext = injectScrollAreaScrollbarContext()\n\nconst { forwardRef } = useForwardExpose()\n\nconst { state, dispatch } = useStateMachine('hidden', {\n  hidden: {\n    POINTER_ENTER: 'glimpse',\n    SCROLL: 'scrolling',\n  },\n  glimpse: {\n    HIDE: 'hidden',\n    POINTER_LEAVE: 'hidden',\n    SCROLL: 'scrolling',\n    POINTER_ENTER: 'glimpse',\n  },\n  scrolling: {\n    SCROLL_END: 'idle',\n    POINTER_ENTER: 'interacting',\n  },\n  interacting: {\n    SCROLL: 'interacting',\n    POINTER_LEAVE: 'idle',\n  },\n  idle: {\n    HIDE: 'hidden',\n    SCROLL: 'scrolling',\n    POINTER_ENTER: 'interacting',\n  },\n})\n\nconst visible = computed(() => state.value !== 'hidden')\n\nfunction handlePointerEnter() {\n  dispatch('POINTER_ENTER')\n}\n\nfunction handlePointerLeave() {\n  dispatch('POINTER_LEAVE')\n}\n\nconst debounceScrollEnd = useDebounceFn(() => dispatch('SCROLL_END'), 100)\n\nwatchEffect((onCleanup) => {\n  if (state.value === 'glimpse') {\n    const timeId = window.setTimeout(dispatch, rootContext.scrollHideDelay.value, 'HIDE')\n\n    onCleanup(() => {\n      window.clearTimeout(timeId)\n    })\n  }\n})\n\nwatchEffect((onCleanup) => {\n  if (state.value === 'idle') {\n    const timeId = window.setTimeout(dispatch, rootContext.scrollHideDelay.value, 'HIDE')\n\n    onCleanup(() => {\n      window.clearTimeout(timeId)\n    })\n  }\n})\n\nwatchEffect((onCleanup) => {\n  const viewport = rootContext.viewport.value\n  const scrollDirection = scrollbarContext.isHorizontal.value\n    ? 'scrollLeft'\n    : 'scrollTop'\n\n  if (viewport) {\n    let prevScrollPos = viewport[scrollDirection]\n    const handleScroll = () => {\n      const scrollPos = viewport[scrollDirection]\n      const hasScrollInDirectionChanged = prevScrollPos !== scrollPos\n      if (hasScrollInDirectionChanged) {\n        dispatch('SCROLL')\n        debounceScrollEnd()\n      }\n      prevScrollPos = scrollPos\n    }\n    viewport.addEventListener('scroll', handleScroll)\n\n    onCleanup(() => {\n      viewport.removeEventListener('scroll', handleScroll)\n    })\n  }\n})\n\nonMounted(() => {\n  const scrollArea = rootContext.scrollArea.value\n\n  if (scrollArea) {\n    scrollArea.addEventListener('pointerenter', handlePointerEnter)\n    scrollArea.addEventListener('pointerleave', handlePointerLeave)\n  }\n})\n\nonUnmounted(() => {\n  const scrollArea = rootContext.scrollArea.value\n  if (scrollArea) {\n    scrollArea.removeEventListener('pointerenter', handlePointerEnter)\n    scrollArea.removeEventListener('pointerleave', handlePointerLeave)\n  }\n})\n</script>\n\n<template>\n  <Presence :present=\"forceMount || visible\">\n    <ScrollAreaScrollbarAuto\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :data-state=\"visible ? 'visible' : 'hidden'\"\n    >\n      <slot />\n    </ScrollAreaScrollbarAuto>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { ScrollAreaScrollbarAutoProps } from './ScrollAreaScrollbarAuto.vue'\n\nexport interface ScrollAreaScrollbarHoverProps extends ScrollAreaScrollbarAutoProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted, onUnmounted, ref } from 'vue'\nimport { Presence } from '@/Presence'\nimport { useForwardExpose } from '@/shared'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport ScrollAreaScrollbarAuto from './ScrollAreaScrollbarAuto.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\ndefineProps<ScrollAreaScrollbarHoverProps>()\n\nconst rootContext = injectScrollAreaRootContext()\n\nconst { forwardRef } = useForwardExpose()\n\nlet timeout: ReturnType<typeof setTimeout> | undefined | number\nconst visible = ref(false)\n\nfunction handlePointerEnter() {\n  window.clearTimeout(timeout)\n  visible.value = true\n}\nfunction handlePointerLeave() {\n  timeout = window.setTimeout(() => {\n    visible.value = false\n  }, rootContext.scrollHideDelay.value)\n}\n\nonMounted(() => {\n  const scrollArea = rootContext.scrollArea.value\n\n  if (scrollArea) {\n    scrollArea.addEventListener('pointerenter', handlePointerEnter)\n    scrollArea.addEventListener('pointerleave', handlePointerLeave)\n  }\n})\n\nonUnmounted(() => {\n  const scrollArea = rootContext.scrollArea.value\n  if (scrollArea) {\n    window.clearTimeout(timeout)\n    scrollArea.removeEventListener('pointerenter', handlePointerEnter)\n    scrollArea.removeEventListener('pointerleave', handlePointerLeave)\n  }\n})\n</script>\n\n<template>\n  <Presence :present=\"forceMount || visible\">\n    <ScrollAreaScrollbarAuto\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :data-state=\"visible ? 'visible' : 'hidden'\"\n    >\n      <slot />\n    </ScrollAreaScrollbarAuto>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { ScrollAreaScrollbarAutoProps } from './ScrollAreaScrollbarAuto.vue'\n\nexport interface ScrollAreaScrollbarHoverProps extends ScrollAreaScrollbarAutoProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted, onUnmounted, ref } from 'vue'\nimport { Presence } from '@/Presence'\nimport { useForwardExpose } from '@/shared'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport ScrollAreaScrollbarAuto from './ScrollAreaScrollbarAuto.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\ndefineProps<ScrollAreaScrollbarHoverProps>()\n\nconst rootContext = injectScrollAreaRootContext()\n\nconst { forwardRef } = useForwardExpose()\n\nlet timeout: ReturnType<typeof setTimeout> | undefined | number\nconst visible = ref(false)\n\nfunction handlePointerEnter() {\n  window.clearTimeout(timeout)\n  visible.value = true\n}\nfunction handlePointerLeave() {\n  timeout = window.setTimeout(() => {\n    visible.value = false\n  }, rootContext.scrollHideDelay.value)\n}\n\nonMounted(() => {\n  const scrollArea = rootContext.scrollArea.value\n\n  if (scrollArea) {\n    scrollArea.addEventListener('pointerenter', handlePointerEnter)\n    scrollArea.addEventListener('pointerleave', handlePointerLeave)\n  }\n})\n\nonUnmounted(() => {\n  const scrollArea = rootContext.scrollArea.value\n  if (scrollArea) {\n    window.clearTimeout(timeout)\n    scrollArea.removeEventListener('pointerenter', handlePointerEnter)\n    scrollArea.removeEventListener('pointerleave', handlePointerLeave)\n  }\n})\n</script>\n\n<template>\n  <Presence :present=\"forceMount || visible\">\n    <ScrollAreaScrollbarAuto\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :data-state=\"visible ? 'visible' : 'hidden'\"\n    >\n      <slot />\n    </ScrollAreaScrollbarAuto>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nexport interface ScrollAreaScrollbarScrollProps {\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useDebounceFn } from '@vueuse/core'\nimport { computed, watchEffect } from 'vue'\nimport { Presence } from '@/Presence'\nimport { useForwardExpose } from '@/shared'\nimport { useStateMachine } from '../shared/useStateMachine'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport { injectScrollAreaScrollbarContext } from './ScrollAreaScrollbar.vue'\nimport ScrollAreaScrollbarVisible from './ScrollAreaScrollbarVisible.vue'\n\ndefineProps<ScrollAreaScrollbarScrollProps>()\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarContext = injectScrollAreaScrollbarContext()\n\nconst { forwardRef } = useForwardExpose()\n\nconst { state, dispatch } = useStateMachine('hidden', {\n  hidden: {\n    SCROLL: 'scrolling',\n  },\n  scrolling: {\n    SCROLL_END: 'idle',\n    POINTER_ENTER: 'interacting',\n  },\n  interacting: {\n    SCROLL: 'interacting',\n    POINTER_LEAVE: 'idle',\n  },\n  idle: {\n    HIDE: 'hidden',\n    SCROLL: 'scrolling',\n    POINTER_ENTER: 'interacting',\n  },\n})\n\nconst visible = computed(() => state.value !== 'hidden')\n\nwatchEffect((onCleanup) => {\n  if (state.value === 'idle') {\n    const timeId = window.setTimeout(dispatch, rootContext.scrollHideDelay.value, 'HIDE')\n\n    onCleanup(() => {\n      window.clearTimeout(timeId)\n    })\n  }\n})\n\nconst debounceScrollEnd = useDebounceFn(() => dispatch('SCROLL_END'), 100)\n\nwatchEffect((onCleanup) => {\n  const viewport = rootContext.viewport.value\n  const scrollDirection = scrollbarContext.isHorizontal.value\n    ? 'scrollLeft'\n    : 'scrollTop'\n\n  if (viewport) {\n    let prevScrollPos = viewport[scrollDirection]\n    const handleScroll = () => {\n      const scrollPos = viewport[scrollDirection]\n      const hasScrollInDirectionChanged = prevScrollPos !== scrollPos\n      if (hasScrollInDirectionChanged) {\n        dispatch('SCROLL')\n        debounceScrollEnd()\n      }\n      prevScrollPos = scrollPos\n    }\n    viewport.addEventListener('scroll', handleScroll)\n\n    onCleanup(() => {\n      viewport.removeEventListener('scroll', handleScroll)\n    })\n  }\n})\n</script>\n\n<template>\n  <Presence :present=\"forceMount || visible\">\n    <ScrollAreaScrollbarVisible\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :data-state=\"visible ? 'visible' : 'hidden'\"\n    >\n      <slot />\n    </ScrollAreaScrollbarVisible>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nexport interface ScrollAreaScrollbarScrollProps {\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useDebounceFn } from '@vueuse/core'\nimport { computed, watchEffect } from 'vue'\nimport { Presence } from '@/Presence'\nimport { useForwardExpose } from '@/shared'\nimport { useStateMachine } from '../shared/useStateMachine'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport { injectScrollAreaScrollbarContext } from './ScrollAreaScrollbar.vue'\nimport ScrollAreaScrollbarVisible from './ScrollAreaScrollbarVisible.vue'\n\ndefineProps<ScrollAreaScrollbarScrollProps>()\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarContext = injectScrollAreaScrollbarContext()\n\nconst { forwardRef } = useForwardExpose()\n\nconst { state, dispatch } = useStateMachine('hidden', {\n  hidden: {\n    SCROLL: 'scrolling',\n  },\n  scrolling: {\n    SCROLL_END: 'idle',\n    POINTER_ENTER: 'interacting',\n  },\n  interacting: {\n    SCROLL: 'interacting',\n    POINTER_LEAVE: 'idle',\n  },\n  idle: {\n    HIDE: 'hidden',\n    SCROLL: 'scrolling',\n    POINTER_ENTER: 'interacting',\n  },\n})\n\nconst visible = computed(() => state.value !== 'hidden')\n\nwatchEffect((onCleanup) => {\n  if (state.value === 'idle') {\n    const timeId = window.setTimeout(dispatch, rootContext.scrollHideDelay.value, 'HIDE')\n\n    onCleanup(() => {\n      window.clearTimeout(timeId)\n    })\n  }\n})\n\nconst debounceScrollEnd = useDebounceFn(() => dispatch('SCROLL_END'), 100)\n\nwatchEffect((onCleanup) => {\n  const viewport = rootContext.viewport.value\n  const scrollDirection = scrollbarContext.isHorizontal.value\n    ? 'scrollLeft'\n    : 'scrollTop'\n\n  if (viewport) {\n    let prevScrollPos = viewport[scrollDirection]\n    const handleScroll = () => {\n      const scrollPos = viewport[scrollDirection]\n      const hasScrollInDirectionChanged = prevScrollPos !== scrollPos\n      if (hasScrollInDirectionChanged) {\n        dispatch('SCROLL')\n        debounceScrollEnd()\n      }\n      prevScrollPos = scrollPos\n    }\n    viewport.addEventListener('scroll', handleScroll)\n\n    onCleanup(() => {\n      viewport.removeEventListener('scroll', handleScroll)\n    })\n  }\n})\n</script>\n\n<template>\n  <Presence :present=\"forceMount || visible\">\n    <ScrollAreaScrollbarVisible\n      v-bind=\"$attrs\"\n      :ref=\"forwardRef\"\n      :data-state=\"visible ? 'visible' : 'hidden'\"\n    >\n      <slot />\n    </ScrollAreaScrollbarVisible>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface ScrollAreaScrollbarProps extends PrimitiveProps {\n  /** The orientation of the scrollbar */\n  orientation?: 'vertical' | 'horizontal'\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n\nexport interface ScrollAreaScrollbarContext {\n  as: Ref<PrimitiveProps['as']>\n  orientation: Ref<'vertical' | 'horizontal'>\n  forceMount?: Ref<boolean>\n  isHorizontal: Ref<boolean>\n  asChild: Ref<boolean>\n}\n\nexport const [injectScrollAreaScrollbarContext, provideScrollAreaScrollbarContext]\n  = createContext<ScrollAreaScrollbarContext>('ScrollAreaScrollbar')\n</script>\n\n<script setup lang=\"ts\">\nimport {\n  computed,\n  onUnmounted,\n  toRefs,\n  watch,\n} from 'vue'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport ScrollAreaScrollbarAuto from './ScrollAreaScrollbarAuto.vue'\nimport ScrollAreaScrollbarGlimpse from './ScrollAreaScrollbarGlimpse.vue'\nimport ScrollAreaScrollbarHover from './ScrollAreaScrollbarHover.vue'\nimport ScrollAreaScrollbarScroll from './ScrollAreaScrollbarScroll.vue'\nimport ScrollAreaScrollbarVisible from './ScrollAreaScrollbarVisible.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ScrollAreaScrollbarProps>(), {\n  orientation: 'vertical',\n  as: 'div',\n})\n\nconst { forwardRef } = useForwardExpose()\nconst rootContext = injectScrollAreaRootContext()\n\nconst isHorizontal = computed(() => props.orientation === 'horizontal')\n\nwatch(\n  isHorizontal,\n  () => {\n    if (isHorizontal.value)\n      rootContext.onScrollbarXEnabledChange(true)\n    else rootContext.onScrollbarYEnabledChange(true)\n  },\n  { immediate: true },\n)\n\nonUnmounted(() => {\n  rootContext.onScrollbarXEnabledChange(false)\n  rootContext.onScrollbarYEnabledChange(false)\n})\n\nconst { orientation, forceMount, asChild, as } = toRefs(props)\nprovideScrollAreaScrollbarContext({\n  orientation,\n  forceMount,\n  isHorizontal,\n  as,\n  asChild,\n})\n</script>\n\n<template>\n  <ScrollAreaScrollbarHover\n    v-if=\"rootContext.type.value === 'hover'\"\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    :force-mount=\"forceMount\"\n  >\n    <slot />\n  </ScrollAreaScrollbarHover>\n  <ScrollAreaScrollbarScroll\n    v-else-if=\"rootContext.type.value === 'scroll'\"\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    :force-mount=\"forceMount\"\n  >\n    <slot />\n  </ScrollAreaScrollbarScroll>\n  <ScrollAreaScrollbarGlimpse\n    v-else-if=\"rootContext.type.value === 'glimpse'\"\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    :force-mount=\"forceMount\"\n  >\n    <slot />\n  </ScrollAreaScrollbarGlimpse>\n  <ScrollAreaScrollbarAuto\n    v-else-if=\"rootContext.type.value === 'auto'\"\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    :force-mount=\"forceMount\"\n  >\n    <slot />\n  </ScrollAreaScrollbarAuto>\n  <ScrollAreaScrollbarVisible\n    v-else-if=\"rootContext.type.value === 'always'\"\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    data-state=\"visible\"\n  >\n    <slot />\n  </ScrollAreaScrollbarVisible>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface ScrollAreaScrollbarProps extends PrimitiveProps {\n  /** The orientation of the scrollbar */\n  orientation?: 'vertical' | 'horizontal'\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n\nexport interface ScrollAreaScrollbarContext {\n  as: Ref<PrimitiveProps['as']>\n  orientation: Ref<'vertical' | 'horizontal'>\n  forceMount?: Ref<boolean>\n  isHorizontal: Ref<boolean>\n  asChild: Ref<boolean>\n}\n\nexport const [injectScrollAreaScrollbarContext, provideScrollAreaScrollbarContext]\n  = createContext<ScrollAreaScrollbarContext>('ScrollAreaScrollbar')\n</script>\n\n<script setup lang=\"ts\">\nimport {\n  computed,\n  onUnmounted,\n  toRefs,\n  watch,\n} from 'vue'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport ScrollAreaScrollbarAuto from './ScrollAreaScrollbarAuto.vue'\nimport ScrollAreaScrollbarGlimpse from './ScrollAreaScrollbarGlimpse.vue'\nimport ScrollAreaScrollbarHover from './ScrollAreaScrollbarHover.vue'\nimport ScrollAreaScrollbarScroll from './ScrollAreaScrollbarScroll.vue'\nimport ScrollAreaScrollbarVisible from './ScrollAreaScrollbarVisible.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ScrollAreaScrollbarProps>(), {\n  orientation: 'vertical',\n  as: 'div',\n})\n\nconst { forwardRef } = useForwardExpose()\nconst rootContext = injectScrollAreaRootContext()\n\nconst isHorizontal = computed(() => props.orientation === 'horizontal')\n\nwatch(\n  isHorizontal,\n  () => {\n    if (isHorizontal.value)\n      rootContext.onScrollbarXEnabledChange(true)\n    else rootContext.onScrollbarYEnabledChange(true)\n  },\n  { immediate: true },\n)\n\nonUnmounted(() => {\n  rootContext.onScrollbarXEnabledChange(false)\n  rootContext.onScrollbarYEnabledChange(false)\n})\n\nconst { orientation, forceMount, asChild, as } = toRefs(props)\nprovideScrollAreaScrollbarContext({\n  orientation,\n  forceMount,\n  isHorizontal,\n  as,\n  asChild,\n})\n</script>\n\n<template>\n  <ScrollAreaScrollbarHover\n    v-if=\"rootContext.type.value === 'hover'\"\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    :force-mount=\"forceMount\"\n  >\n    <slot />\n  </ScrollAreaScrollbarHover>\n  <ScrollAreaScrollbarScroll\n    v-else-if=\"rootContext.type.value === 'scroll'\"\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    :force-mount=\"forceMount\"\n  >\n    <slot />\n  </ScrollAreaScrollbarScroll>\n  <ScrollAreaScrollbarGlimpse\n    v-else-if=\"rootContext.type.value === 'glimpse'\"\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    :force-mount=\"forceMount\"\n  >\n    <slot />\n  </ScrollAreaScrollbarGlimpse>\n  <ScrollAreaScrollbarAuto\n    v-else-if=\"rootContext.type.value === 'auto'\"\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    :force-mount=\"forceMount\"\n  >\n    <slot />\n  </ScrollAreaScrollbarAuto>\n  <ScrollAreaScrollbarVisible\n    v-else-if=\"rootContext.type.value === 'always'\"\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n    data-state=\"visible\"\n  >\n    <slot />\n  </ScrollAreaScrollbarVisible>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Direction, Sizes } from './types'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface ScrollAreaScrollbarVisibleContext {\n  sizes: Ref<Sizes>\n  hasThumb: Ref<boolean>\n  handleWheelScroll: (event: WheelEvent, payload: number) => void\n  handleThumbDown: (\n    event: MouseEvent,\n    payload: { x: number, y: number },\n  ) => void\n  handleThumbUp: (event: MouseEvent) => void\n  handleSizeChange: (payload: Sizes) => void\n  onThumbPositionChange: () => void\n  onDragScroll: (payload: number) => void\n  onThumbChange: (element: HTMLElement) => void\n}\n\nexport const [injectScrollAreaScrollbarVisibleContext, provideScrollAreaScrollbarVisibleContext]\n  = createContext<ScrollAreaScrollbarVisibleContext>('ScrollAreaScrollbarVisible')\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, ref } from 'vue'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport { injectScrollAreaScrollbarContext } from './ScrollAreaScrollbar.vue'\nimport ScrollAreaScrollbarX from './ScrollAreaScrollbarX.vue'\nimport ScrollAreaScrollbarY from './ScrollAreaScrollbarY.vue'\nimport {\n  getScrollPositionFromPointer,\n  getThumbOffsetFromScroll,\n  getThumbRatio,\n  isScrollingWithinScrollbarBounds,\n} from './utils'\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarContext = injectScrollAreaScrollbarContext()\nconst { forwardRef } = useForwardExpose()\n\nconst sizes = ref<Sizes>({\n  content: 0,\n  viewport: 0,\n  scrollbar: { size: 0, paddingStart: 0, paddingEnd: 0 },\n})\n\nconst hasThumb = computed(() => {\n  const thumbRatio = getThumbRatio(sizes.value.viewport, sizes.value.content)\n  return Boolean(thumbRatio > 0 && thumbRatio < 1)\n})\n\nconst thumbRef = ref<HTMLElement>()\nconst pointerOffset = ref(0)\n\nfunction handleWheelScroll(event: WheelEvent, payload: number) {\n  if (isShowingScrollbarX.value) {\n    const scrollPos = rootContext.viewport.value!.scrollLeft + event.deltaY\n\n    rootContext.viewport.value!.scrollLeft = scrollPos\n    // prevent window scroll when wheeling on scrollbar\n    if (isScrollingWithinScrollbarBounds(scrollPos, payload))\n      event.preventDefault()\n  }\n  else {\n    const scrollPos = rootContext.viewport.value!.scrollTop + event.deltaY\n\n    rootContext.viewport.value!.scrollTop = scrollPos\n    // prevent window scroll when wheeling on scrollbar\n    if (isScrollingWithinScrollbarBounds(scrollPos, payload))\n      event.preventDefault()\n  }\n}\n\nfunction handleThumbDown(event: MouseEvent, payload: { x: number, y: number }) {\n  if (isShowingScrollbarX.value)\n    pointerOffset.value = payload.x\n  else pointerOffset.value = payload.y\n}\nfunction handleThumbUp(event: MouseEvent) {\n  pointerOffset.value = 0\n}\n\nfunction handleSizeChange(payload: Sizes) {\n  sizes.value = payload\n}\n\nfunction getScrollPosition(pointerPos: number, dir?: Direction) {\n  return getScrollPositionFromPointer(\n    pointerPos,\n    pointerOffset.value,\n    sizes.value,\n    dir,\n  )\n}\n\nconst isShowingScrollbarX = computed(\n  () => scrollbarContext.isHorizontal.value,\n)\n\nfunction onDragScroll(payload: number) {\n  if (isShowingScrollbarX.value) {\n    rootContext.viewport.value!.scrollLeft = getScrollPosition(\n      payload,\n      rootContext.dir.value,\n    )\n  }\n  else {\n    rootContext.viewport.value!.scrollTop = getScrollPosition(payload)\n  }\n}\n\nfunction onThumbPositionChange() {\n  if (isShowingScrollbarX.value) {\n    if (rootContext.viewport.value && thumbRef.value) {\n      const scrollPos = rootContext.viewport.value.scrollLeft\n      const offset = getThumbOffsetFromScroll(\n        scrollPos,\n        sizes.value,\n        rootContext.dir.value,\n      )\n      thumbRef.value.style.transform = `translate3d(${offset}px, 0, 0)`\n    }\n  }\n  else {\n    if (rootContext.viewport.value && thumbRef.value) {\n      const scrollPos = rootContext.viewport.value.scrollTop\n      const offset = getThumbOffsetFromScroll(scrollPos, sizes.value)\n      thumbRef.value.style.transform = `translate3d(0, ${offset}px, 0)`\n    }\n  }\n}\nfunction onThumbChange(element: HTMLElement) {\n  thumbRef.value = element\n}\n\nprovideScrollAreaScrollbarVisibleContext({\n  sizes,\n  hasThumb,\n  handleWheelScroll,\n  handleThumbDown,\n  handleThumbUp,\n  handleSizeChange,\n  onThumbPositionChange,\n  onThumbChange,\n  onDragScroll,\n})\n</script>\n\n<template>\n  <ScrollAreaScrollbarX\n    v-if=\"isShowingScrollbarX\"\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n  >\n    <slot />\n  </ScrollAreaScrollbarX>\n  <ScrollAreaScrollbarY\n    v-else\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n  >\n    <slot />\n  </ScrollAreaScrollbarY>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { Direction, Sizes } from './types'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface ScrollAreaScrollbarVisibleContext {\n  sizes: Ref<Sizes>\n  hasThumb: Ref<boolean>\n  handleWheelScroll: (event: WheelEvent, payload: number) => void\n  handleThumbDown: (\n    event: MouseEvent,\n    payload: { x: number, y: number },\n  ) => void\n  handleThumbUp: (event: MouseEvent) => void\n  handleSizeChange: (payload: Sizes) => void\n  onThumbPositionChange: () => void\n  onDragScroll: (payload: number) => void\n  onThumbChange: (element: HTMLElement) => void\n}\n\nexport const [injectScrollAreaScrollbarVisibleContext, provideScrollAreaScrollbarVisibleContext]\n  = createContext<ScrollAreaScrollbarVisibleContext>('ScrollAreaScrollbarVisible')\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, ref } from 'vue'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport { injectScrollAreaScrollbarContext } from './ScrollAreaScrollbar.vue'\nimport ScrollAreaScrollbarX from './ScrollAreaScrollbarX.vue'\nimport ScrollAreaScrollbarY from './ScrollAreaScrollbarY.vue'\nimport {\n  getScrollPositionFromPointer,\n  getThumbOffsetFromScroll,\n  getThumbRatio,\n  isScrollingWithinScrollbarBounds,\n} from './utils'\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarContext = injectScrollAreaScrollbarContext()\nconst { forwardRef } = useForwardExpose()\n\nconst sizes = ref<Sizes>({\n  content: 0,\n  viewport: 0,\n  scrollbar: { size: 0, paddingStart: 0, paddingEnd: 0 },\n})\n\nconst hasThumb = computed(() => {\n  const thumbRatio = getThumbRatio(sizes.value.viewport, sizes.value.content)\n  return Boolean(thumbRatio > 0 && thumbRatio < 1)\n})\n\nconst thumbRef = ref<HTMLElement>()\nconst pointerOffset = ref(0)\n\nfunction handleWheelScroll(event: WheelEvent, payload: number) {\n  if (isShowingScrollbarX.value) {\n    const scrollPos = rootContext.viewport.value!.scrollLeft + event.deltaY\n\n    rootContext.viewport.value!.scrollLeft = scrollPos\n    // prevent window scroll when wheeling on scrollbar\n    if (isScrollingWithinScrollbarBounds(scrollPos, payload))\n      event.preventDefault()\n  }\n  else {\n    const scrollPos = rootContext.viewport.value!.scrollTop + event.deltaY\n\n    rootContext.viewport.value!.scrollTop = scrollPos\n    // prevent window scroll when wheeling on scrollbar\n    if (isScrollingWithinScrollbarBounds(scrollPos, payload))\n      event.preventDefault()\n  }\n}\n\nfunction handleThumbDown(event: MouseEvent, payload: { x: number, y: number }) {\n  if (isShowingScrollbarX.value)\n    pointerOffset.value = payload.x\n  else pointerOffset.value = payload.y\n}\nfunction handleThumbUp(event: MouseEvent) {\n  pointerOffset.value = 0\n}\n\nfunction handleSizeChange(payload: Sizes) {\n  sizes.value = payload\n}\n\nfunction getScrollPosition(pointerPos: number, dir?: Direction) {\n  return getScrollPositionFromPointer(\n    pointerPos,\n    pointerOffset.value,\n    sizes.value,\n    dir,\n  )\n}\n\nconst isShowingScrollbarX = computed(\n  () => scrollbarContext.isHorizontal.value,\n)\n\nfunction onDragScroll(payload: number) {\n  if (isShowingScrollbarX.value) {\n    rootContext.viewport.value!.scrollLeft = getScrollPosition(\n      payload,\n      rootContext.dir.value,\n    )\n  }\n  else {\n    rootContext.viewport.value!.scrollTop = getScrollPosition(payload)\n  }\n}\n\nfunction onThumbPositionChange() {\n  if (isShowingScrollbarX.value) {\n    if (rootContext.viewport.value && thumbRef.value) {\n      const scrollPos = rootContext.viewport.value.scrollLeft\n      const offset = getThumbOffsetFromScroll(\n        scrollPos,\n        sizes.value,\n        rootContext.dir.value,\n      )\n      thumbRef.value.style.transform = `translate3d(${offset}px, 0, 0)`\n    }\n  }\n  else {\n    if (rootContext.viewport.value && thumbRef.value) {\n      const scrollPos = rootContext.viewport.value.scrollTop\n      const offset = getThumbOffsetFromScroll(scrollPos, sizes.value)\n      thumbRef.value.style.transform = `translate3d(0, ${offset}px, 0)`\n    }\n  }\n}\nfunction onThumbChange(element: HTMLElement) {\n  thumbRef.value = element\n}\n\nprovideScrollAreaScrollbarVisibleContext({\n  sizes,\n  hasThumb,\n  handleWheelScroll,\n  handleThumbDown,\n  handleThumbUp,\n  handleSizeChange,\n  onThumbPositionChange,\n  onThumbChange,\n  onDragScroll,\n})\n</script>\n\n<template>\n  <ScrollAreaScrollbarX\n    v-if=\"isShowingScrollbarX\"\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n  >\n    <slot />\n  </ScrollAreaScrollbarX>\n  <ScrollAreaScrollbarY\n    v-else\n    v-bind=\"$attrs\"\n    :ref=\"forwardRef\"\n  >\n    <slot />\n  </ScrollAreaScrollbarY>\n</template>\n","<script lang=\"ts\">\ntype ScrollbarAreaScrollbarImplEmits = {\n  onDragScroll: [payload: { x: number, y: number }]\n  onWheelScroll: [payload: { x: number, y: number }]\n  onThumbPointerDown: [payload: { x: number, y: number }]\n}\n\nexport interface ScrollAreaScrollbarImplProps {\n  isHorizontal: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useResizeObserver } from '@vueuse/core'\nimport { onMounted, onUnmounted, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport { injectScrollAreaScrollbarContext } from './ScrollAreaScrollbar.vue'\nimport { injectScrollAreaScrollbarVisibleContext } from './ScrollAreaScrollbarVisible.vue'\nimport { toInt } from './utils'\n\nconst props = defineProps<ScrollAreaScrollbarImplProps>()\nconst emit = defineEmits<ScrollbarAreaScrollbarImplEmits>()\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarVisibleContext = injectScrollAreaScrollbarVisibleContext()\nconst scrollbarContext = injectScrollAreaScrollbarContext()\n\nconst { forwardRef, currentElement: scrollbar } = useForwardExpose()\nconst prevWebkitUserSelectRef = ref('')\nconst rectRef = ref<DOMRect>()\n\nfunction handleDragScroll(event: MouseEvent) {\n  if (rectRef.value) {\n    const x = event.clientX - rectRef.value?.left\n    const y = event.clientY - rectRef.value?.top\n    emit('onDragScroll', { x, y })\n  }\n}\n\nfunction handlePointerDown(event: PointerEvent) {\n  const mainPointer = 0\n  if (event.button === mainPointer) {\n    const element = event.target as HTMLElement\n    element.setPointerCapture(event.pointerId)\n    rectRef.value = scrollbar.value!.getBoundingClientRect()\n\n    // pointer capture doesn't prevent text selection in Safari\n    // so we remove text selection manually when scrolling\n    prevWebkitUserSelectRef.value = document.body.style.webkitUserSelect\n    document.body.style.webkitUserSelect = 'none'\n    if (rootContext.viewport)\n      rootContext.viewport.value!.style.scrollBehavior = 'auto'\n\n    handleDragScroll(event)\n  }\n}\n\nfunction handlePointerMove(event: PointerEvent) {\n  handleDragScroll(event)\n}\n\nfunction handlePointerUp(event: PointerEvent) {\n  const element = event.target as HTMLElement\n  if (element.hasPointerCapture(event.pointerId))\n    element.releasePointerCapture(event.pointerId)\n\n  document.body.style.webkitUserSelect = prevWebkitUserSelectRef.value\n  if (rootContext.viewport)\n    rootContext.viewport.value!.style.scrollBehavior = ''\n\n  rectRef.value = undefined\n}\n\nfunction handleWheel(event: WheelEvent) {\n  const element = event.target as HTMLElement\n  const isScrollbarWheel = scrollbar.value?.contains(element)\n  const maxScrollPos\n    = scrollbarVisibleContext.sizes.value.content\n      - scrollbarVisibleContext.sizes.value.viewport\n  if (isScrollbarWheel)\n    scrollbarVisibleContext.handleWheelScroll(event, maxScrollPos)\n}\n\nonMounted(() => {\n  document.addEventListener('wheel', handleWheel, { passive: false })\n})\nonUnmounted(() => {\n  document.removeEventListener('wheel', handleWheel)\n})\n\nfunction handleSizeChange() {\n  if (!scrollbar.value)\n    return\n  if (props.isHorizontal) {\n    scrollbarVisibleContext.handleSizeChange({\n      content: rootContext.viewport.value?.scrollWidth ?? 0,\n      viewport: rootContext.viewport.value?.offsetWidth ?? 0,\n      scrollbar: {\n        size: scrollbar.value.clientWidth ?? 0,\n        paddingStart: toInt(getComputedStyle(scrollbar.value).paddingLeft),\n        paddingEnd: toInt(getComputedStyle(scrollbar.value).paddingRight),\n      },\n    })\n  }\n  else {\n    scrollbarVisibleContext.handleSizeChange({\n      content: rootContext.viewport.value?.scrollHeight ?? 0,\n      viewport: rootContext.viewport.value?.offsetHeight ?? 0,\n      scrollbar: {\n        size: scrollbar.value?.clientHeight ?? 0,\n        paddingStart: toInt(getComputedStyle(scrollbar.value!).paddingTop),\n        paddingEnd: toInt(getComputedStyle(scrollbar.value!).paddingBottom),\n      },\n    })\n  }\n\n  scrollbarVisibleContext.onThumbPositionChange()\n}\n\nuseResizeObserver(scrollbar, handleSizeChange)\nuseResizeObserver(rootContext.content, handleSizeChange)\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    style=\"position: absolute\"\n    data-scrollbarimpl\n    :as=\"scrollbarContext.as.value\"\n    :as-child=\"scrollbarContext.asChild.value\"\n    @pointerdown=\"handlePointerDown\"\n    @pointermove=\"handlePointerMove\"\n    @pointerup=\"handlePointerUp\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\ntype ScrollbarAreaScrollbarImplEmits = {\n  onDragScroll: [payload: { x: number, y: number }]\n  onWheelScroll: [payload: { x: number, y: number }]\n  onThumbPointerDown: [payload: { x: number, y: number }]\n}\n\nexport interface ScrollAreaScrollbarImplProps {\n  isHorizontal: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useResizeObserver } from '@vueuse/core'\nimport { onMounted, onUnmounted, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport { injectScrollAreaScrollbarContext } from './ScrollAreaScrollbar.vue'\nimport { injectScrollAreaScrollbarVisibleContext } from './ScrollAreaScrollbarVisible.vue'\nimport { toInt } from './utils'\n\nconst props = defineProps<ScrollAreaScrollbarImplProps>()\nconst emit = defineEmits<ScrollbarAreaScrollbarImplEmits>()\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarVisibleContext = injectScrollAreaScrollbarVisibleContext()\nconst scrollbarContext = injectScrollAreaScrollbarContext()\n\nconst { forwardRef, currentElement: scrollbar } = useForwardExpose()\nconst prevWebkitUserSelectRef = ref('')\nconst rectRef = ref<DOMRect>()\n\nfunction handleDragScroll(event: MouseEvent) {\n  if (rectRef.value) {\n    const x = event.clientX - rectRef.value?.left\n    const y = event.clientY - rectRef.value?.top\n    emit('onDragScroll', { x, y })\n  }\n}\n\nfunction handlePointerDown(event: PointerEvent) {\n  const mainPointer = 0\n  if (event.button === mainPointer) {\n    const element = event.target as HTMLElement\n    element.setPointerCapture(event.pointerId)\n    rectRef.value = scrollbar.value!.getBoundingClientRect()\n\n    // pointer capture doesn't prevent text selection in Safari\n    // so we remove text selection manually when scrolling\n    prevWebkitUserSelectRef.value = document.body.style.webkitUserSelect\n    document.body.style.webkitUserSelect = 'none'\n    if (rootContext.viewport)\n      rootContext.viewport.value!.style.scrollBehavior = 'auto'\n\n    handleDragScroll(event)\n  }\n}\n\nfunction handlePointerMove(event: PointerEvent) {\n  handleDragScroll(event)\n}\n\nfunction handlePointerUp(event: PointerEvent) {\n  const element = event.target as HTMLElement\n  if (element.hasPointerCapture(event.pointerId))\n    element.releasePointerCapture(event.pointerId)\n\n  document.body.style.webkitUserSelect = prevWebkitUserSelectRef.value\n  if (rootContext.viewport)\n    rootContext.viewport.value!.style.scrollBehavior = ''\n\n  rectRef.value = undefined\n}\n\nfunction handleWheel(event: WheelEvent) {\n  const element = event.target as HTMLElement\n  const isScrollbarWheel = scrollbar.value?.contains(element)\n  const maxScrollPos\n    = scrollbarVisibleContext.sizes.value.content\n      - scrollbarVisibleContext.sizes.value.viewport\n  if (isScrollbarWheel)\n    scrollbarVisibleContext.handleWheelScroll(event, maxScrollPos)\n}\n\nonMounted(() => {\n  document.addEventListener('wheel', handleWheel, { passive: false })\n})\nonUnmounted(() => {\n  document.removeEventListener('wheel', handleWheel)\n})\n\nfunction handleSizeChange() {\n  if (!scrollbar.value)\n    return\n  if (props.isHorizontal) {\n    scrollbarVisibleContext.handleSizeChange({\n      content: rootContext.viewport.value?.scrollWidth ?? 0,\n      viewport: rootContext.viewport.value?.offsetWidth ?? 0,\n      scrollbar: {\n        size: scrollbar.value.clientWidth ?? 0,\n        paddingStart: toInt(getComputedStyle(scrollbar.value).paddingLeft),\n        paddingEnd: toInt(getComputedStyle(scrollbar.value).paddingRight),\n      },\n    })\n  }\n  else {\n    scrollbarVisibleContext.handleSizeChange({\n      content: rootContext.viewport.value?.scrollHeight ?? 0,\n      viewport: rootContext.viewport.value?.offsetHeight ?? 0,\n      scrollbar: {\n        size: scrollbar.value?.clientHeight ?? 0,\n        paddingStart: toInt(getComputedStyle(scrollbar.value!).paddingTop),\n        paddingEnd: toInt(getComputedStyle(scrollbar.value!).paddingBottom),\n      },\n    })\n  }\n\n  scrollbarVisibleContext.onThumbPositionChange()\n}\n\nuseResizeObserver(scrollbar, handleSizeChange)\nuseResizeObserver(rootContext.content, handleSizeChange)\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    style=\"position: absolute\"\n    data-scrollbarimpl\n    :as=\"scrollbarContext.as.value\"\n    :as-child=\"scrollbarContext.asChild.value\"\n    @pointerdown=\"handlePointerDown\"\n    @pointermove=\"handlePointerMove\"\n    @pointerup=\"handlePointerUp\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ScrollAreaThumbProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { watchOnce } from '@vueuse/core'\nimport { computed, onUnmounted, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport { injectScrollAreaScrollbarVisibleContext } from './ScrollAreaScrollbarVisible.vue'\nimport { addUnlinkedScrollListener } from './utils'\n\nconst props = defineProps<ScrollAreaThumbProps>()\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarContextVisible = injectScrollAreaScrollbarVisibleContext()\n\nfunction handlePointerDown(event: MouseEvent) {\n  const thumb = event.target as HTMLElement\n  const thumbRect = thumb.getBoundingClientRect()\n  const x = event.clientX - thumbRect.left\n  const y = event.clientY - thumbRect.top\n  scrollbarContextVisible.handleThumbDown(event, { x, y })\n}\n\nfunction handlePointerUp(event: MouseEvent) {\n  scrollbarContextVisible.handleThumbUp(event)\n}\n\nconst { forwardRef, currentElement: thumbElement } = useForwardExpose()\nconst removeUnlinkedScrollListenerRef = ref<() => void>()\nconst viewport = computed(() => rootContext.viewport.value)\n\nfunction handleScroll() {\n  if (!removeUnlinkedScrollListenerRef.value) {\n    const listener = addUnlinkedScrollListener(\n      viewport.value!,\n      scrollbarContextVisible.onThumbPositionChange,\n    )\n    removeUnlinkedScrollListenerRef.value = listener\n    scrollbarContextVisible.onThumbPositionChange()\n  }\n}\n\nconst sizes = computed(() => scrollbarContextVisible.sizes.value)\n\nwatchOnce(sizes, () => {\n  scrollbarContextVisible.onThumbChange(thumbElement.value!)\n  if (viewport.value) {\n    /**\n     * We only bind to native scroll event so we know when scroll starts and ends.\n     * When scroll starts we start a requestAnimationFrame loop that checks for\n     * changes to scroll position. That rAF loop triggers our thumb position change\n     * when relevant to avoid scroll-linked effects. We cancel the loop when scroll ends.\n     * https://developer.mozilla.org/en-US/docs/Mozilla/Performance/Scroll-linked_effects\n     */\n    scrollbarContextVisible.onThumbPositionChange()\n    viewport.value.addEventListener('scroll', handleScroll)\n  }\n})\n\nonUnmounted(() => {\n  viewport.value!.removeEventListener('scroll', handleScroll)\n  rootContext.viewport.value?.removeEventListener('scroll', handleScroll)\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :data-state=\"scrollbarContextVisible.hasThumb ? 'visible' : 'hidden'\"\n    :style=\"{\n      width: 'var(--reka-scroll-area-thumb-width)',\n      height: 'var(--reka-scroll-area-thumb-height)',\n    }\"\n    :as-child=\"props.asChild\"\n    :as=\"as\"\n    @pointerdown=\"handlePointerDown\"\n    @pointerup=\"handlePointerUp\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ScrollAreaThumbProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { watchOnce } from '@vueuse/core'\nimport { computed, onUnmounted, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\nimport { injectScrollAreaScrollbarVisibleContext } from './ScrollAreaScrollbarVisible.vue'\nimport { addUnlinkedScrollListener } from './utils'\n\nconst props = defineProps<ScrollAreaThumbProps>()\n\nconst rootContext = injectScrollAreaRootContext()\nconst scrollbarContextVisible = injectScrollAreaScrollbarVisibleContext()\n\nfunction handlePointerDown(event: MouseEvent) {\n  const thumb = event.target as HTMLElement\n  const thumbRect = thumb.getBoundingClientRect()\n  const x = event.clientX - thumbRect.left\n  const y = event.clientY - thumbRect.top\n  scrollbarContextVisible.handleThumbDown(event, { x, y })\n}\n\nfunction handlePointerUp(event: MouseEvent) {\n  scrollbarContextVisible.handleThumbUp(event)\n}\n\nconst { forwardRef, currentElement: thumbElement } = useForwardExpose()\nconst removeUnlinkedScrollListenerRef = ref<() => void>()\nconst viewport = computed(() => rootContext.viewport.value)\n\nfunction handleScroll() {\n  if (!removeUnlinkedScrollListenerRef.value) {\n    const listener = addUnlinkedScrollListener(\n      viewport.value!,\n      scrollbarContextVisible.onThumbPositionChange,\n    )\n    removeUnlinkedScrollListenerRef.value = listener\n    scrollbarContextVisible.onThumbPositionChange()\n  }\n}\n\nconst sizes = computed(() => scrollbarContextVisible.sizes.value)\n\nwatchOnce(sizes, () => {\n  scrollbarContextVisible.onThumbChange(thumbElement.value!)\n  if (viewport.value) {\n    /**\n     * We only bind to native scroll event so we know when scroll starts and ends.\n     * When scroll starts we start a requestAnimationFrame loop that checks for\n     * changes to scroll position. That rAF loop triggers our thumb position change\n     * when relevant to avoid scroll-linked effects. We cancel the loop when scroll ends.\n     * https://developer.mozilla.org/en-US/docs/Mozilla/Performance/Scroll-linked_effects\n     */\n    scrollbarContextVisible.onThumbPositionChange()\n    viewport.value.addEventListener('scroll', handleScroll)\n  }\n})\n\nonUnmounted(() => {\n  viewport.value!.removeEventListener('scroll', handleScroll)\n  rootContext.viewport.value?.removeEventListener('scroll', handleScroll)\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :data-state=\"scrollbarContextVisible.hasThumb ? 'visible' : 'hidden'\"\n    :style=\"{\n      width: 'var(--reka-scroll-area-thumb-width)',\n      height: 'var(--reka-scroll-area-thumb-height)',\n    }\"\n    :as-child=\"props.asChild\"\n    :as=\"as\"\n    @pointerdown=\"handlePointerDown\"\n    @pointerup=\"handlePointerUp\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { useNonce } from '@/shared/useNonce'\n\nexport interface ScrollAreaViewportProps extends PrimitiveProps {\n  /**\n   * Will add `nonce` attribute to the style tag which can be used by Content Security Policy. <br> If omitted, inherits globally from `ConfigProvider`.\n   */\n  nonce?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted, ref, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<ScrollAreaViewportProps>()\n\nconst { nonce: propNonce } = toRefs(props)\nconst nonce = useNonce(propNonce)\n\nconst rootContext = injectScrollAreaRootContext()\n\nconst viewportElement = ref<HTMLElement>()\n\nonMounted(() => {\n  rootContext.onViewportChange(viewportElement.value!)\n  rootContext.onContentChange(contentElement.value!)\n})\n\ndefineExpose({\n  viewportElement,\n})\nconst { forwardRef, currentElement: contentElement } = useForwardExpose()\n</script>\n\n<template>\n  <div\n    ref=\"viewportElement\"\n    data-reka-scroll-area-viewport=\"\"\n    :style=\"{\n      /**\n       * We don't support `visible` because the intention is to have at least one scrollbar\n       * if this component is used and `visible` will behave like `auto` in that case\n       * https://developer.mozilla.org/en-US/docs/Web/CSS/overflowed#description\n       *\n       * We don't handle `auto` because the intention is for the native implementation\n       * to be hidden if using this component. We just want to ensure the node is scrollable\n       * so could have used either `scroll` or `auto` here. We picked `scroll` to prevent\n       * the browser from having to work out whether to render native scrollbars or not,\n       * we tell it to with the intention of hiding them in CSS.\n       */\n      overflowX: rootContext.scrollbarXEnabled.value ? 'scroll' : 'hidden',\n      overflowY: rootContext.scrollbarYEnabled.value ? 'scroll' : 'hidden',\n    }\"\n    v-bind=\"$attrs\"\n    :tabindex=\"0\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :style=\"{\n        /**\n         * When horizontal scrollbar is visible: this element should be at least\n         * as wide as its children for size calculations to work correctly.\n         *\n         * When horizontal scrollbar is NOT visible: this element's width should\n         * be constrained by the parent container to enable `text-overflow: ellipsis`\n         */\n        minWidth: rootContext.scrollbarXEnabled.value ? 'fit-content' : undefined,\n      }\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n    >\n      <slot />\n    </Primitive>\n  </div>\n  <Primitive\n    as=\"style\"\n    :nonce=\"nonce\"\n  >\n    /* Hide scrollbars cross-browser and enable momentum scroll for touch\n    devices */\n    [data-reka-scroll-area-viewport] {\n    scrollbar-width:none;\n    -ms-overflow-style:none;\n    -webkit-overflow-scrolling:touch;\n    }\n\n    [data-reka-scroll-area-viewport]::-webkit-scrollbar {\n    display:none;\n    }\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { useNonce } from '@/shared/useNonce'\n\nexport interface ScrollAreaViewportProps extends PrimitiveProps {\n  /**\n   * Will add `nonce` attribute to the style tag which can be used by Content Security Policy. <br> If omitted, inherits globally from `ConfigProvider`.\n   */\n  nonce?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted, ref, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectScrollAreaRootContext } from './ScrollAreaRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<ScrollAreaViewportProps>()\n\nconst { nonce: propNonce } = toRefs(props)\nconst nonce = useNonce(propNonce)\n\nconst rootContext = injectScrollAreaRootContext()\n\nconst viewportElement = ref<HTMLElement>()\n\nonMounted(() => {\n  rootContext.onViewportChange(viewportElement.value!)\n  rootContext.onContentChange(contentElement.value!)\n})\n\ndefineExpose({\n  viewportElement,\n})\nconst { forwardRef, currentElement: contentElement } = useForwardExpose()\n</script>\n\n<template>\n  <div\n    ref=\"viewportElement\"\n    data-reka-scroll-area-viewport=\"\"\n    :style=\"{\n      /**\n       * We don't support `visible` because the intention is to have at least one scrollbar\n       * if this component is used and `visible` will behave like `auto` in that case\n       * https://developer.mozilla.org/en-US/docs/Web/CSS/overflowed#description\n       *\n       * We don't handle `auto` because the intention is for the native implementation\n       * to be hidden if using this component. We just want to ensure the node is scrollable\n       * so could have used either `scroll` or `auto` here. We picked `scroll` to prevent\n       * the browser from having to work out whether to render native scrollbars or not,\n       * we tell it to with the intention of hiding them in CSS.\n       */\n      overflowX: rootContext.scrollbarXEnabled.value ? 'scroll' : 'hidden',\n      overflowY: rootContext.scrollbarYEnabled.value ? 'scroll' : 'hidden',\n    }\"\n    v-bind=\"$attrs\"\n    :tabindex=\"0\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :style=\"{\n        /**\n         * When horizontal scrollbar is visible: this element should be at least\n         * as wide as its children for size calculations to work correctly.\n         *\n         * When horizontal scrollbar is NOT visible: this element's width should\n         * be constrained by the parent container to enable `text-overflow: ellipsis`\n         */\n        minWidth: rootContext.scrollbarXEnabled.value ? 'fit-content' : undefined,\n      }\"\n      :as-child=\"props.asChild\"\n      :as=\"as\"\n    >\n      <slot />\n    </Primitive>\n  </div>\n  <Primitive\n    as=\"style\"\n    :nonce=\"nonce\"\n  >\n    /* Hide scrollbars cross-browser and enable momentum scroll for touch\n    devices */\n    [data-reka-scroll-area-viewport] {\n    scrollbar-width:none;\n    -ms-overflow-style:none;\n    -webkit-overflow-scrolling:touch;\n    }\n\n    [data-reka-scroll-area-viewport]::-webkit-scrollbar {\n    display:none;\n    }\n  </Primitive>\n</template>\n","import type { AcceptableValue } from '@/shared/types'\nimport { isEqual } from 'ohash'\n\nexport const OPEN_KEYS = [' ', 'Enter', 'ArrowUp', 'ArrowDown']\nexport const SELECTION_KEYS = [' ', 'Enter']\nexport const CONTENT_MARGIN = 10\n\nexport function valueComparator<T>(value: T | T[] | undefined, currentValue: T, comparator?: string | ((a: T, b: T) => boolean)) {\n  if (value === undefined)\n    return false\n  else if (Array.isArray(value))\n    return value.some(val => compare(val, currentValue, comparator))\n  else\n    return compare(value, currentValue, comparator)\n}\n\nexport function compare<T>(value?: T, currentValue?: T, comparator?: string | ((a: T, b: T) => boolean)) {\n  if (value === undefined || currentValue === undefined)\n    return false\n\n  if (typeof value === 'string')\n    return value === currentValue\n\n  if (typeof comparator === 'function')\n    return comparator(value, currentValue)\n\n  if (typeof comparator === 'string')\n    return value?.[comparator as keyof T] === currentValue?.[comparator as keyof T]\n\n  return isEqual(value, currentValue)\n}\n\nexport function shouldShowPlaceholder(value?: AcceptableValue | AcceptableValue[]): boolean {\n  return value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0)\n}\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { AcceptableValue, Direction, FormFieldProps } from '@/shared/types'\nimport { useCollection } from '@/Collection'\nimport { createContext, isNullish, useDirection, useFormControl } from '@/shared'\nimport { compare, valueComparator } from './utils'\n\nexport interface SelectRootProps<T = AcceptableValue> extends FormFieldProps {\n  /** The controlled open state of the Select. Can be bind as `v-model:open`. */\n  open?: boolean\n  /** The open state of the select when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /** The value of the select when initially rendered. Use when you do not need to control the state of the Select */\n  defaultValue?: T | Array<T>\n  /** The controlled value of the Select. Can be bind as `v-model`. */\n  modelValue?: T | Array<T>\n  /** Use this to compare objects by a particular field, or pass your own comparison function for complete control over how objects are compared. */\n  by?: string | ((a: T, b: T) => boolean)\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** Whether multiple options can be selected or not. */\n  multiple?: boolean\n  /** Native html input `autocomplete` attribute. */\n  autocomplete?: string\n  /** When `true`, prevents the user from interacting with Select */\n  disabled?: boolean\n}\n\nexport type SelectRootEmits<T = AcceptableValue> = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: T]\n  /** Event handler called when the open state of the context menu changes. */\n  'update:open': [value: boolean]\n}\n\nexport interface SelectRootContext<T> {\n  triggerElement: Ref<HTMLElement | undefined>\n  onTriggerChange: (node: HTMLElement | undefined) => void\n  valueElement: Ref<HTMLElement | undefined>\n  onValueElementChange: (node: HTMLElement) => void\n  contentId: string\n  modelValue: Ref<T | Array<T> | undefined>\n  onValueChange: (value: T) => void\n  open: Ref<boolean>\n  multiple: Ref<boolean>\n  required?: Ref<boolean>\n  by?: string | ((a: T, b: T) => boolean)\n  onOpenChange: (open: boolean) => void\n  dir: Ref<Direction>\n  triggerPointerDownPosRef: Ref<{ x: number, y: number } | null>\n  isEmptyModelValue: Ref<boolean>\n  disabled?: Ref<boolean>\n\n  optionsSet: Ref<Set<SelectOption>>\n  onOptionAdd: (option: SelectOption) => void\n  onOptionRemove: (option: SelectOption) => void\n}\n\nexport const [injectSelectRootContext, provideSelectRootContext]\n  = createContext<SelectRootContext<AcceptableValue>>('SelectRoot')\n\ninterface SelectOption { value: any, disabled?: boolean, textContent: string }\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRefs } from 'vue'\nimport { PopperRoot } from '@/Popper'\nimport BubbleSelect from './BubbleSelect.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<SelectRootProps<T>>(), {\n  modelValue: undefined,\n  open: undefined,\n})\nconst emits = defineEmits<SelectRootEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nconst { required, disabled, multiple, dir: propDir } = toRefs(props)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  // @ts-expect-error Missing infer for AcceptableValue\n  defaultValue: props.defaultValue ?? (multiple.value ? [] : undefined),\n  passive: (props.modelValue === undefined) as false,\n  deep: true,\n}) as Ref<T | T[] | undefined>\n\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst triggerElement = ref<HTMLElement>()\nconst valueElement = ref<HTMLElement>()\nconst triggerPointerDownPosRef = ref({\n  x: 0,\n  y: 0,\n})\n\nconst isEmptyModelValue = computed(() => {\n  if (multiple.value && Array.isArray(modelValue.value))\n    return modelValue.value?.length === 0\n  else\n    return isNullish(modelValue.value)\n})\n\nuseCollection({ isProvider: true })\nconst dir = useDirection(propDir)\n\nconst isFormControl = useFormControl(triggerElement)\nconst optionsSet = ref<Set<SelectOption>>(new Set())\n\n// The native `select` only associates the correct default value if the corresponding\n// `option` is rendered as a child **at the same time** as itself.\n// Because it might take a few renders for our items to gather the information to build\n// the native `option`(s), we generate a key on the `select` to make sure Vue re-builds it\n// each time the options change.\nconst nativeSelectKey = computed(() => {\n  return Array.from(optionsSet.value)\n    .map(option => option.value)\n    .join(';')\n})\n\nfunction handleValueChange(value: T) {\n  if (multiple.value) {\n    const array = Array.isArray(modelValue.value) ? [...modelValue.value] : []\n    const index = array.findIndex(i => compare(i, value, props.by))\n    index === -1 ? array.push(value) : array.splice(index, 1)\n    modelValue.value = [...array]\n  }\n  else {\n    modelValue.value = value\n  }\n}\n\nfunction getOption(value: SelectOption['value']) {\n  return Array.from(optionsSet.value)\n    .find(option => valueComparator(value, option.value, props.by))\n}\n\nprovideSelectRootContext({\n  triggerElement,\n  onTriggerChange: (node) => {\n    triggerElement.value = node\n  },\n  valueElement,\n  onValueElementChange: (node) => {\n    valueElement.value = node\n  },\n  contentId: '',\n  modelValue,\n  // @ts-expect-error Missing infer for AcceptableValue\n  onValueChange: handleValueChange,\n  // @ts-expect-error Missing infer for AcceptableValue\n  by: props.by,\n  open,\n  multiple,\n  required,\n  onOpenChange: (value) => {\n    open.value = value\n  },\n  dir,\n  triggerPointerDownPosRef,\n  disabled,\n  isEmptyModelValue,\n\n  optionsSet,\n  onOptionAdd: (option) => {\n    const existingOption = getOption(option.value)\n    if (existingOption) {\n      optionsSet.value.delete(existingOption)\n    }\n\n    optionsSet.value.add(option)\n  },\n  onOptionRemove: (option) => {\n    const existingOption = getOption(option.value)\n    if (existingOption) {\n      optionsSet.value.delete(existingOption)\n    }\n  },\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <slot\n      :model-value=\"modelValue\"\n      :open=\"open\"\n    />\n\n    <BubbleSelect\n      v-if=\"isFormControl && name\"\n      :key=\"nativeSelectKey\"\n      aria-hidden=\"true\"\n      tabindex=\"-1\"\n      :multiple=\"multiple\"\n      :required=\"required\"\n      :name=\"name\"\n      :autocomplete=\"autocomplete\"\n      :disabled=\"disabled\"\n      :value=\"modelValue\"\n    >\n      <option\n        v-if=\"isNullish(modelValue)\"\n        value=\"\"\n      />\n      <option\n        v-for=\"option in Array.from(optionsSet)\"\n        :key=\"option.value ?? ''\"\n        v-bind=\"option\"\n      />\n    </BubbleSelect>\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { AcceptableValue, Direction, FormFieldProps } from '@/shared/types'\nimport { useCollection } from '@/Collection'\nimport { createContext, isNullish, useDirection, useFormControl } from '@/shared'\nimport { compare, valueComparator } from './utils'\n\nexport interface SelectRootProps<T = AcceptableValue> extends FormFieldProps {\n  /** The controlled open state of the Select. Can be bind as `v-model:open`. */\n  open?: boolean\n  /** The open state of the select when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /** The value of the select when initially rendered. Use when you do not need to control the state of the Select */\n  defaultValue?: T | Array<T>\n  /** The controlled value of the Select. Can be bind as `v-model`. */\n  modelValue?: T | Array<T>\n  /** Use this to compare objects by a particular field, or pass your own comparison function for complete control over how objects are compared. */\n  by?: string | ((a: T, b: T) => boolean)\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** Whether multiple options can be selected or not. */\n  multiple?: boolean\n  /** Native html input `autocomplete` attribute. */\n  autocomplete?: string\n  /** When `true`, prevents the user from interacting with Select */\n  disabled?: boolean\n}\n\nexport type SelectRootEmits<T = AcceptableValue> = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [value: T]\n  /** Event handler called when the open state of the context menu changes. */\n  'update:open': [value: boolean]\n}\n\nexport interface SelectRootContext<T> {\n  triggerElement: Ref<HTMLElement | undefined>\n  onTriggerChange: (node: HTMLElement | undefined) => void\n  valueElement: Ref<HTMLElement | undefined>\n  onValueElementChange: (node: HTMLElement) => void\n  contentId: string\n  modelValue: Ref<T | Array<T> | undefined>\n  onValueChange: (value: T) => void\n  open: Ref<boolean>\n  multiple: Ref<boolean>\n  required?: Ref<boolean>\n  by?: string | ((a: T, b: T) => boolean)\n  onOpenChange: (open: boolean) => void\n  dir: Ref<Direction>\n  triggerPointerDownPosRef: Ref<{ x: number, y: number } | null>\n  isEmptyModelValue: Ref<boolean>\n  disabled?: Ref<boolean>\n\n  optionsSet: Ref<Set<SelectOption>>\n  onOptionAdd: (option: SelectOption) => void\n  onOptionRemove: (option: SelectOption) => void\n}\n\nexport const [injectSelectRootContext, provideSelectRootContext]\n  = createContext<SelectRootContext<AcceptableValue>>('SelectRoot')\n\ninterface SelectOption { value: any, disabled?: boolean, textContent: string }\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, ref, toRefs } from 'vue'\nimport { PopperRoot } from '@/Popper'\nimport BubbleSelect from './BubbleSelect.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<SelectRootProps<T>>(), {\n  modelValue: undefined,\n  open: undefined,\n})\nconst emits = defineEmits<SelectRootEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nconst { required, disabled, multiple, dir: propDir } = toRefs(props)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  // @ts-expect-error Missing infer for AcceptableValue\n  defaultValue: props.defaultValue ?? (multiple.value ? [] : undefined),\n  passive: (props.modelValue === undefined) as false,\n  deep: true,\n}) as Ref<T | T[] | undefined>\n\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nconst triggerElement = ref<HTMLElement>()\nconst valueElement = ref<HTMLElement>()\nconst triggerPointerDownPosRef = ref({\n  x: 0,\n  y: 0,\n})\n\nconst isEmptyModelValue = computed(() => {\n  if (multiple.value && Array.isArray(modelValue.value))\n    return modelValue.value?.length === 0\n  else\n    return isNullish(modelValue.value)\n})\n\nuseCollection({ isProvider: true })\nconst dir = useDirection(propDir)\n\nconst isFormControl = useFormControl(triggerElement)\nconst optionsSet = ref<Set<SelectOption>>(new Set())\n\n// The native `select` only associates the correct default value if the corresponding\n// `option` is rendered as a child **at the same time** as itself.\n// Because it might take a few renders for our items to gather the information to build\n// the native `option`(s), we generate a key on the `select` to make sure Vue re-builds it\n// each time the options change.\nconst nativeSelectKey = computed(() => {\n  return Array.from(optionsSet.value)\n    .map(option => option.value)\n    .join(';')\n})\n\nfunction handleValueChange(value: T) {\n  if (multiple.value) {\n    const array = Array.isArray(modelValue.value) ? [...modelValue.value] : []\n    const index = array.findIndex(i => compare(i, value, props.by))\n    index === -1 ? array.push(value) : array.splice(index, 1)\n    modelValue.value = [...array]\n  }\n  else {\n    modelValue.value = value\n  }\n}\n\nfunction getOption(value: SelectOption['value']) {\n  return Array.from(optionsSet.value)\n    .find(option => valueComparator(value, option.value, props.by))\n}\n\nprovideSelectRootContext({\n  triggerElement,\n  onTriggerChange: (node) => {\n    triggerElement.value = node\n  },\n  valueElement,\n  onValueElementChange: (node) => {\n    valueElement.value = node\n  },\n  contentId: '',\n  modelValue,\n  // @ts-expect-error Missing infer for AcceptableValue\n  onValueChange: handleValueChange,\n  // @ts-expect-error Missing infer for AcceptableValue\n  by: props.by,\n  open,\n  multiple,\n  required,\n  onOpenChange: (value) => {\n    open.value = value\n  },\n  dir,\n  triggerPointerDownPosRef,\n  disabled,\n  isEmptyModelValue,\n\n  optionsSet,\n  onOptionAdd: (option) => {\n    const existingOption = getOption(option.value)\n    if (existingOption) {\n      optionsSet.value.delete(existingOption)\n    }\n\n    optionsSet.value.add(option)\n  },\n  onOptionRemove: (option) => {\n    const existingOption = getOption(option.value)\n    if (existingOption) {\n      optionsSet.value.delete(existingOption)\n    }\n  },\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <slot\n      :model-value=\"modelValue\"\n      :open=\"open\"\n    />\n\n    <BubbleSelect\n      v-if=\"isFormControl && name\"\n      :key=\"nativeSelectKey\"\n      aria-hidden=\"true\"\n      tabindex=\"-1\"\n      :multiple=\"multiple\"\n      :required=\"required\"\n      :name=\"name\"\n      :autocomplete=\"autocomplete\"\n      :disabled=\"disabled\"\n      :value=\"modelValue\"\n    >\n      <option\n        v-if=\"isNullish(modelValue)\"\n        value=\"\"\n      />\n      <option\n        v-for=\"option in Array.from(optionsSet)\"\n        :key=\"option.value ?? ''\"\n        v-bind=\"option\"\n      />\n    </BubbleSelect>\n  </PopperRoot>\n</template>\n","<script setup lang=\"ts\">\nimport { ref, watch } from 'vue'\nimport { VisuallyHidden } from '@/VisuallyHidden'\nimport { injectSelectRootContext } from './SelectRoot.vue'\n\ninterface BubbleSelectProps {\n  autocomplete?: string\n  autofocus?: boolean\n  disabled?: boolean\n  form?: string\n  multiple?: boolean\n  name?: string\n  required?: boolean\n  size?: number\n  value?: any\n}\n\nconst props = defineProps<BubbleSelectProps>()\nconst selectElement = ref<HTMLElement>()\nconst rootContext = injectSelectRootContext()\n\n// This would bubble \"change\" event to form, with the target as Select element.\nwatch(() => props.value, (cur, prev) => {\n  const selectProto = window.HTMLSelectElement.prototype\n  const descriptor = Object.getOwnPropertyDescriptor(\n    selectProto,\n    'value',\n  ) as PropertyDescriptor\n  const setValue = descriptor.set\n  if (cur !== prev && setValue && selectElement.value) {\n    const event = new Event('change', { bubbles: true })\n    setValue.call(selectElement.value, cur)\n    selectElement.value.dispatchEvent(event)\n  }\n})\n\n/**\n * Form autofill will trigger an `input` event on the `select` element.\n * We listen to that event and update our internal state to support it.\n */\nfunction handleInput(event: Event) {\n  rootContext.onValueChange((event.target as HTMLSelectElement).value)\n}\n\n/**\n * We purposefully use a `select` here to support form autofill as much\n * as possible.\n *\n * We purposefully do not add the `value` attribute here to allow the value\n * to be set programmatically and bubble to any parent form `onChange` event.\n *\n * We use `VisuallyHidden` rather than `display: \"none\"` because Safari autofill\n * won't work otherwise.\n */\n</script>\n\n<template>\n  <VisuallyHidden as-child>\n    <select\n      ref=\"selectElement\"\n      v-bind=\"props\"\n      @input=\"handleInput\"\n    >\n      <slot />\n    </select>\n  </VisuallyHidden>\n</template>\n","<script setup lang=\"ts\">\nimport { ref, watch } from 'vue'\nimport { VisuallyHidden } from '@/VisuallyHidden'\nimport { injectSelectRootContext } from './SelectRoot.vue'\n\ninterface BubbleSelectProps {\n  autocomplete?: string\n  autofocus?: boolean\n  disabled?: boolean\n  form?: string\n  multiple?: boolean\n  name?: string\n  required?: boolean\n  size?: number\n  value?: any\n}\n\nconst props = defineProps<BubbleSelectProps>()\nconst selectElement = ref<HTMLElement>()\nconst rootContext = injectSelectRootContext()\n\n// This would bubble \"change\" event to form, with the target as Select element.\nwatch(() => props.value, (cur, prev) => {\n  const selectProto = window.HTMLSelectElement.prototype\n  const descriptor = Object.getOwnPropertyDescriptor(\n    selectProto,\n    'value',\n  ) as PropertyDescriptor\n  const setValue = descriptor.set\n  if (cur !== prev && setValue && selectElement.value) {\n    const event = new Event('change', { bubbles: true })\n    setValue.call(selectElement.value, cur)\n    selectElement.value.dispatchEvent(event)\n  }\n})\n\n/**\n * Form autofill will trigger an `input` event on the `select` element.\n * We listen to that event and update our internal state to support it.\n */\nfunction handleInput(event: Event) {\n  rootContext.onValueChange((event.target as HTMLSelectElement).value)\n}\n\n/**\n * We purposefully use a `select` here to support form autofill as much\n * as possible.\n *\n * We purposefully do not add the `value` attribute here to allow the value\n * to be set programmatically and bubble to any parent form `onChange` event.\n *\n * We use `VisuallyHidden` rather than `display: \"none\"` because Safari autofill\n * won't work otherwise.\n */\n</script>\n\n<template>\n  <VisuallyHidden as-child>\n    <select\n      ref=\"selectElement\"\n      v-bind=\"props\"\n      @input=\"handleInput\"\n    >\n      <slot />\n    </select>\n  </VisuallyHidden>\n</template>\n","<script lang=\"ts\">\nimport type { PopperContentProps } from '@/Popper'\n\nexport interface SelectPopperPositionProps extends PopperContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperContent } from '@/Popper'\nimport { useForwardProps } from '..'\nimport { CONTENT_MARGIN } from './utils'\n\nconst props = withDefaults(defineProps<SelectPopperPositionProps>(), {\n  align: 'start',\n  collisionPadding: CONTENT_MARGIN,\n})\nconst forwarded = useForwardProps(props)\n</script>\n\n<template>\n  <PopperContent\n    v-bind=\"forwarded\"\n    :style=\"{\n      // Ensure border-box for floating-ui calculations\n      'boxSizing': 'border-box',\n      '--reka-select-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-select-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-select-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-select-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-select-trigger-height': 'var(--reka-popper-anchor-height)',\n    }\"\n  >\n    <slot />\n  </PopperContent>\n</template>\n","<script lang=\"ts\">\nimport type { PopperContentProps } from '@/Popper'\n\nexport interface SelectPopperPositionProps extends PopperContentProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperContent } from '@/Popper'\nimport { useForwardProps } from '..'\nimport { CONTENT_MARGIN } from './utils'\n\nconst props = withDefaults(defineProps<SelectPopperPositionProps>(), {\n  align: 'start',\n  collisionPadding: CONTENT_MARGIN,\n})\nconst forwarded = useForwardProps(props)\n</script>\n\n<template>\n  <PopperContent\n    v-bind=\"forwarded\"\n    :style=\"{\n      // Ensure border-box for floating-ui calculations\n      'boxSizing': 'border-box',\n      '--reka-select-content-transform-origin':\n        'var(--reka-popper-transform-origin)',\n      '--reka-select-content-available-width':\n        'var(--reka-popper-available-width)',\n      '--reka-select-content-available-height':\n        'var(--reka-popper-available-height)',\n      '--reka-select-trigger-width': 'var(--reka-popper-anchor-width)',\n      '--reka-select-trigger-height': 'var(--reka-popper-anchor-height)',\n    }\"\n  >\n    <slot />\n  </PopperContent>\n</template>\n","<script lang=\"ts\">\nimport type {\n  ComponentPublicInstance,\n  Ref,\n} from 'vue'\nimport type { DismissableLayerProps, PointerDownOutsideEvent } from '@/DismissableLayer'\nimport type { PopperContentProps } from '@/Popper'\nimport type { AcceptableValue } from '@/shared/types'\nimport { useCollection } from '@/Collection'\nimport {\n  createContext,\n  useFocusGuards,\n  useForwardProps,\n  useHideOthers,\n  useTypeahead,\n} from '@/shared'\nimport { useBodyScrollLock } from '@/shared/useBodyScrollLock'\nimport { valueComparator } from './utils'\n\nexport interface SelectContentContext {\n  content?: Ref<HTMLElement | undefined>\n  viewport?: Ref<HTMLElement | undefined>\n  onViewportChange: (node: HTMLElement | undefined) => void\n  itemRefCallback: (\n    node: HTMLElement | undefined,\n    value: AcceptableValue,\n    disabled: boolean,\n  ) => void\n  selectedItem?: Ref<HTMLElement | undefined>\n  onItemLeave?: () => void\n  itemTextRefCallback: (\n    node: HTMLElement | undefined,\n    value: AcceptableValue,\n    disabled: boolean,\n  ) => void\n  focusSelectedItem?: () => void\n  selectedItemText?: Ref<HTMLElement | undefined>\n  position?: 'item-aligned' | 'popper'\n  isPositioned?: Ref<boolean>\n  searchRef?: Ref<string>\n}\n\nexport const SelectContentDefaultContextValue: SelectContentContext = {\n  onViewportChange: () => {},\n  itemTextRefCallback: () => {},\n  itemRefCallback: () => {},\n}\n\nexport type SelectContentImplEmits = {\n  closeAutoFocus: [event: Event]\n  /**\n   * Event handler called when the escape key is down.\n   * Can be prevented.\n   */\n  escapeKeyDown: [event: KeyboardEvent]\n  /**\n   * Event handler called when a `pointerdown` event happens outside of the `DismissableLayer`.\n   * Can be prevented.\n   */\n  pointerDownOutside: [event: PointerDownOutsideEvent]\n}\n\nexport interface SelectContentImplProps extends PopperContentProps, DismissableLayerProps {\n  /**\n   *  The positioning mode to use\n   *\n   *  `item-aligned (default)` - behaves similarly to a native MacOS menu by positioning content relative to the active item. <br>\n   *  `popper` - positions content in the same way as our other primitives, for example `Popover` or `DropdownMenu`.\n   */\n  position?: 'item-aligned' | 'popper'\n  /**\n   * The document.body will be lock, and scrolling will be disabled.\n   *\n   * @defaultValue true\n   */\n  bodyLock?: boolean\n}\n\nexport const [injectSelectContentContext, provideSelectContentContext]\n  = createContext<SelectContentContext>('SelectContent')\n</script>\n\n<script setup lang=\"ts\">\nimport { unrefElement } from '@vueuse/core'\nimport {\n  computed,\n  ref,\n  watch,\n  watchEffect,\n} from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { FocusScope } from '@/FocusScope'\nimport { focusFirst } from '@/Menu/utils'\nimport SelectItemAlignedPosition from './SelectItemAlignedPosition.vue'\nimport SelectPopperPosition from './SelectPopperPosition.vue'\nimport { injectSelectRootContext } from './SelectRoot.vue'\n\nconst props = withDefaults(defineProps<SelectContentImplProps>(), {\n  align: 'start',\n  position: 'item-aligned',\n  bodyLock: true,\n  disableOutsidePointerEvents: true,\n})\nconst emits = defineEmits<SelectContentImplEmits>()\n\nconst rootContext = injectSelectRootContext()\n\nuseFocusGuards()\nuseBodyScrollLock(props.bodyLock)\nconst { CollectionSlot, getItems } = useCollection()\n\nconst content = ref<HTMLElement>()\nuseHideOthers(content)\n\nconst { search, handleTypeaheadSearch } = useTypeahead()\n\nconst viewport = ref<HTMLElement>()\nconst selectedItem = ref<HTMLElement>()\nconst selectedItemText = ref<HTMLElement>()\nconst isPositioned = ref(false)\nconst firstValidItemFoundRef = ref(false)\nconst firstSelectedItemInArrayFoundRef = ref(false)\n\nfunction focusSelectedItem() {\n  if (selectedItem.value && content.value)\n    focusFirst([selectedItem.value, content.value])\n}\n\nwatch(isPositioned, () => {\n  focusSelectedItem()\n})\n\n// prevent selecting items on `pointerup` in some cases after opening from `pointerdown`\n// and close on `pointerup` outside.\nconst { onOpenChange, triggerPointerDownPosRef } = rootContext\nwatchEffect((cleanupFn) => {\n  if (!content.value)\n    return\n  let pointerMoveDelta = { x: 0, y: 0 }\n\n  const handlePointerMove = (event: PointerEvent) => {\n    pointerMoveDelta = {\n      x: Math.abs(\n        Math.round(event.pageX) - (triggerPointerDownPosRef.value?.x ?? 0),\n      ),\n      y: Math.abs(\n        Math.round(event.pageY) - (triggerPointerDownPosRef.value?.y ?? 0),\n      ),\n    }\n  }\n  const handlePointerUp = (event: PointerEvent) => {\n    // Prevent options from being untappable on touch devices\n    // https://github.com/unovue/reka-ui/issues/804\n    if (event.pointerType === 'touch')\n      return\n\n    // If the pointer hasn't moved by a certain threshold then we prevent selecting item on `pointerup`.\n    if (pointerMoveDelta.x <= 10 && pointerMoveDelta.y <= 10) {\n      event.preventDefault()\n    }\n    else {\n      // otherwise, if the event was outside the content, close.\n      if (!content.value?.contains(event.target as HTMLElement))\n        onOpenChange(false)\n    }\n    document.removeEventListener('pointermove', handlePointerMove)\n    triggerPointerDownPosRef.value = null\n  }\n\n  if (triggerPointerDownPosRef.value !== null) {\n    document.addEventListener('pointermove', handlePointerMove)\n    document.addEventListener('pointerup', handlePointerUp, {\n      capture: true,\n      once: true,\n    })\n  }\n\n  cleanupFn(() => {\n    document.removeEventListener('pointermove', handlePointerMove)\n    document.removeEventListener('pointerup', handlePointerUp, {\n      capture: true,\n    })\n  })\n})\n\nfunction handleKeyDown(event: KeyboardEvent) {\n  const isModifierKey = event.ctrlKey || event.altKey || event.metaKey\n\n  // select should not be navigated using tab key so we prevent it\n  if (event.key === 'Tab')\n    event.preventDefault()\n\n  if (!isModifierKey && event.key.length === 1)\n    handleTypeaheadSearch(event.key, getItems())\n\n  if (['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) {\n    const collectionItems = getItems().map(i => i.ref)\n    let candidateNodes = [...collectionItems]\n\n    if (['ArrowUp', 'End'].includes(event.key))\n      candidateNodes = candidateNodes.slice().reverse()\n\n    if (['ArrowUp', 'ArrowDown'].includes(event.key)) {\n      const currentElement = event.target as HTMLElement\n      const currentIndex = candidateNodes.indexOf(currentElement)\n      candidateNodes = candidateNodes.slice(currentIndex + 1)\n    }\n    setTimeout(() => focusFirst(candidateNodes))\n    event.preventDefault()\n  }\n}\n\nconst pickedProps = computed(() => {\n  if (props.position === 'popper')\n    return props\n  else return {}\n})\n\nconst forwardedProps = useForwardProps(pickedProps.value)\n\nprovideSelectContentContext({\n  content,\n  viewport,\n  onViewportChange: (node) => {\n    viewport.value = node\n  },\n  itemRefCallback: (node, value, disabled) => {\n    const isFirstValidItem = !firstValidItemFoundRef.value && !disabled\n    const isSelectedItem = valueComparator(rootContext.modelValue.value, value, rootContext.by)\n\n    if (rootContext.multiple.value) {\n      if (firstSelectedItemInArrayFoundRef.value) {\n        return\n      }\n      if (isSelectedItem || isFirstValidItem) {\n        selectedItem.value = node\n\n        // make sure to keep the first item highlighted when `multiple`\n        if (isSelectedItem) {\n          firstSelectedItemInArrayFoundRef.value = true\n        }\n      }\n    }\n    else {\n      if (isSelectedItem || isFirstValidItem) {\n        selectedItem.value = node\n      }\n    }\n\n    if (isFirstValidItem) {\n      firstValidItemFoundRef.value = true\n    }\n  },\n  selectedItem,\n  selectedItemText,\n  onItemLeave: () => {\n    content.value?.focus()\n  },\n  itemTextRefCallback: (node, value, disabled) => {\n    const isFirstValidItem = !firstValidItemFoundRef.value && !disabled\n    const isSelectedItem = valueComparator(rootContext.modelValue.value, value, rootContext.by)\n\n    if (isSelectedItem || isFirstValidItem)\n      selectedItemText.value = node\n  },\n  focusSelectedItem,\n  position: props.position,\n  isPositioned,\n  searchRef: search,\n})\n</script>\n\n<template>\n  <CollectionSlot>\n    <FocusScope\n      as-child\n      @mount-auto-focus.prevent\n      @unmount-auto-focus=\"\n        (event) => {\n          emits('closeAutoFocus', event);\n          if (event.defaultPrevented) return;\n          rootContext.triggerElement.value?.focus({ preventScroll: true });\n          event.preventDefault();\n        }\n      \"\n    >\n      <DismissableLayer\n        as-child\n        :disable-outside-pointer-events=\"disableOutsidePointerEvents\"\n        @focus-outside.prevent\n        @dismiss=\"rootContext.onOpenChange(false)\"\n        @escape-key-down=\"emits('escapeKeyDown', $event)\"\n        @pointer-down-outside=\"emits('pointerDownOutside', $event)\"\n      >\n        <component\n          :is=\"\n            position === 'popper'\n              ? SelectPopperPosition\n              : SelectItemAlignedPosition\n          \"\n          v-bind=\"{ ...$attrs, ...forwardedProps }\"\n          :id=\"rootContext.contentId\"\n          :ref=\"\n            (vnode: Element | ComponentPublicInstance | null) => {\n              if (!vnode) return undefined\n              const el = unrefElement(vnode as ComponentPublicInstance) as HTMLElement | undefined\n              // special case for PopperContent\n              if (el?.hasAttribute('data-reka-popper-content-wrapper'))\n                content = el.firstElementChild as HTMLElement\n              else\n                content = el\n              return undefined\n            }\n          \"\n          role=\"listbox\"\n          :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n          :dir=\"rootContext.dir.value\"\n          :style=\"{\n            // flex layout so we can place the scroll buttons properly\n            display: 'flex',\n            flexDirection: 'column',\n            // reset the outline by default as the content MAY get focused\n            outline: 'none',\n          }\"\n          @contextmenu.prevent\n          @placed=\"isPositioned = true\"\n          @keydown=\"(handleKeyDown as any)\"\n        >\n          <slot />\n        </component>\n      </DismissableLayer>\n    </FocusScope>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type {\n  ComponentPublicInstance,\n  Ref,\n} from 'vue'\nimport type { DismissableLayerProps, PointerDownOutsideEvent } from '@/DismissableLayer'\nimport type { PopperContentProps } from '@/Popper'\nimport type { AcceptableValue } from '@/shared/types'\nimport { useCollection } from '@/Collection'\nimport {\n  createContext,\n  useFocusGuards,\n  useForwardProps,\n  useHideOthers,\n  useTypeahead,\n} from '@/shared'\nimport { useBodyScrollLock } from '@/shared/useBodyScrollLock'\nimport { valueComparator } from './utils'\n\nexport interface SelectContentContext {\n  content?: Ref<HTMLElement | undefined>\n  viewport?: Ref<HTMLElement | undefined>\n  onViewportChange: (node: HTMLElement | undefined) => void\n  itemRefCallback: (\n    node: HTMLElement | undefined,\n    value: AcceptableValue,\n    disabled: boolean,\n  ) => void\n  selectedItem?: Ref<HTMLElement | undefined>\n  onItemLeave?: () => void\n  itemTextRefCallback: (\n    node: HTMLElement | undefined,\n    value: AcceptableValue,\n    disabled: boolean,\n  ) => void\n  focusSelectedItem?: () => void\n  selectedItemText?: Ref<HTMLElement | undefined>\n  position?: 'item-aligned' | 'popper'\n  isPositioned?: Ref<boolean>\n  searchRef?: Ref<string>\n}\n\nexport const SelectContentDefaultContextValue: SelectContentContext = {\n  onViewportChange: () => {},\n  itemTextRefCallback: () => {},\n  itemRefCallback: () => {},\n}\n\nexport type SelectContentImplEmits = {\n  closeAutoFocus: [event: Event]\n  /**\n   * Event handler called when the escape key is down.\n   * Can be prevented.\n   */\n  escapeKeyDown: [event: KeyboardEvent]\n  /**\n   * Event handler called when a `pointerdown` event happens outside of the `DismissableLayer`.\n   * Can be prevented.\n   */\n  pointerDownOutside: [event: PointerDownOutsideEvent]\n}\n\nexport interface SelectContentImplProps extends PopperContentProps, DismissableLayerProps {\n  /**\n   *  The positioning mode to use\n   *\n   *  `item-aligned (default)` - behaves similarly to a native MacOS menu by positioning content relative to the active item. <br>\n   *  `popper` - positions content in the same way as our other primitives, for example `Popover` or `DropdownMenu`.\n   */\n  position?: 'item-aligned' | 'popper'\n  /**\n   * The document.body will be lock, and scrolling will be disabled.\n   *\n   * @defaultValue true\n   */\n  bodyLock?: boolean\n}\n\nexport const [injectSelectContentContext, provideSelectContentContext]\n  = createContext<SelectContentContext>('SelectContent')\n</script>\n\n<script setup lang=\"ts\">\nimport { unrefElement } from '@vueuse/core'\nimport {\n  computed,\n  ref,\n  watch,\n  watchEffect,\n} from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { FocusScope } from '@/FocusScope'\nimport { focusFirst } from '@/Menu/utils'\nimport SelectItemAlignedPosition from './SelectItemAlignedPosition.vue'\nimport SelectPopperPosition from './SelectPopperPosition.vue'\nimport { injectSelectRootContext } from './SelectRoot.vue'\n\nconst props = withDefaults(defineProps<SelectContentImplProps>(), {\n  align: 'start',\n  position: 'item-aligned',\n  bodyLock: true,\n  disableOutsidePointerEvents: true,\n})\nconst emits = defineEmits<SelectContentImplEmits>()\n\nconst rootContext = injectSelectRootContext()\n\nuseFocusGuards()\nuseBodyScrollLock(props.bodyLock)\nconst { CollectionSlot, getItems } = useCollection()\n\nconst content = ref<HTMLElement>()\nuseHideOthers(content)\n\nconst { search, handleTypeaheadSearch } = useTypeahead()\n\nconst viewport = ref<HTMLElement>()\nconst selectedItem = ref<HTMLElement>()\nconst selectedItemText = ref<HTMLElement>()\nconst isPositioned = ref(false)\nconst firstValidItemFoundRef = ref(false)\nconst firstSelectedItemInArrayFoundRef = ref(false)\n\nfunction focusSelectedItem() {\n  if (selectedItem.value && content.value)\n    focusFirst([selectedItem.value, content.value])\n}\n\nwatch(isPositioned, () => {\n  focusSelectedItem()\n})\n\n// prevent selecting items on `pointerup` in some cases after opening from `pointerdown`\n// and close on `pointerup` outside.\nconst { onOpenChange, triggerPointerDownPosRef } = rootContext\nwatchEffect((cleanupFn) => {\n  if (!content.value)\n    return\n  let pointerMoveDelta = { x: 0, y: 0 }\n\n  const handlePointerMove = (event: PointerEvent) => {\n    pointerMoveDelta = {\n      x: Math.abs(\n        Math.round(event.pageX) - (triggerPointerDownPosRef.value?.x ?? 0),\n      ),\n      y: Math.abs(\n        Math.round(event.pageY) - (triggerPointerDownPosRef.value?.y ?? 0),\n      ),\n    }\n  }\n  const handlePointerUp = (event: PointerEvent) => {\n    // Prevent options from being untappable on touch devices\n    // https://github.com/unovue/reka-ui/issues/804\n    if (event.pointerType === 'touch')\n      return\n\n    // If the pointer hasn't moved by a certain threshold then we prevent selecting item on `pointerup`.\n    if (pointerMoveDelta.x <= 10 && pointerMoveDelta.y <= 10) {\n      event.preventDefault()\n    }\n    else {\n      // otherwise, if the event was outside the content, close.\n      if (!content.value?.contains(event.target as HTMLElement))\n        onOpenChange(false)\n    }\n    document.removeEventListener('pointermove', handlePointerMove)\n    triggerPointerDownPosRef.value = null\n  }\n\n  if (triggerPointerDownPosRef.value !== null) {\n    document.addEventListener('pointermove', handlePointerMove)\n    document.addEventListener('pointerup', handlePointerUp, {\n      capture: true,\n      once: true,\n    })\n  }\n\n  cleanupFn(() => {\n    document.removeEventListener('pointermove', handlePointerMove)\n    document.removeEventListener('pointerup', handlePointerUp, {\n      capture: true,\n    })\n  })\n})\n\nfunction handleKeyDown(event: KeyboardEvent) {\n  const isModifierKey = event.ctrlKey || event.altKey || event.metaKey\n\n  // select should not be navigated using tab key so we prevent it\n  if (event.key === 'Tab')\n    event.preventDefault()\n\n  if (!isModifierKey && event.key.length === 1)\n    handleTypeaheadSearch(event.key, getItems())\n\n  if (['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) {\n    const collectionItems = getItems().map(i => i.ref)\n    let candidateNodes = [...collectionItems]\n\n    if (['ArrowUp', 'End'].includes(event.key))\n      candidateNodes = candidateNodes.slice().reverse()\n\n    if (['ArrowUp', 'ArrowDown'].includes(event.key)) {\n      const currentElement = event.target as HTMLElement\n      const currentIndex = candidateNodes.indexOf(currentElement)\n      candidateNodes = candidateNodes.slice(currentIndex + 1)\n    }\n    setTimeout(() => focusFirst(candidateNodes))\n    event.preventDefault()\n  }\n}\n\nconst pickedProps = computed(() => {\n  if (props.position === 'popper')\n    return props\n  else return {}\n})\n\nconst forwardedProps = useForwardProps(pickedProps.value)\n\nprovideSelectContentContext({\n  content,\n  viewport,\n  onViewportChange: (node) => {\n    viewport.value = node\n  },\n  itemRefCallback: (node, value, disabled) => {\n    const isFirstValidItem = !firstValidItemFoundRef.value && !disabled\n    const isSelectedItem = valueComparator(rootContext.modelValue.value, value, rootContext.by)\n\n    if (rootContext.multiple.value) {\n      if (firstSelectedItemInArrayFoundRef.value) {\n        return\n      }\n      if (isSelectedItem || isFirstValidItem) {\n        selectedItem.value = node\n\n        // make sure to keep the first item highlighted when `multiple`\n        if (isSelectedItem) {\n          firstSelectedItemInArrayFoundRef.value = true\n        }\n      }\n    }\n    else {\n      if (isSelectedItem || isFirstValidItem) {\n        selectedItem.value = node\n      }\n    }\n\n    if (isFirstValidItem) {\n      firstValidItemFoundRef.value = true\n    }\n  },\n  selectedItem,\n  selectedItemText,\n  onItemLeave: () => {\n    content.value?.focus()\n  },\n  itemTextRefCallback: (node, value, disabled) => {\n    const isFirstValidItem = !firstValidItemFoundRef.value && !disabled\n    const isSelectedItem = valueComparator(rootContext.modelValue.value, value, rootContext.by)\n\n    if (isSelectedItem || isFirstValidItem)\n      selectedItemText.value = node\n  },\n  focusSelectedItem,\n  position: props.position,\n  isPositioned,\n  searchRef: search,\n})\n</script>\n\n<template>\n  <CollectionSlot>\n    <FocusScope\n      as-child\n      @mount-auto-focus.prevent\n      @unmount-auto-focus=\"\n        (event) => {\n          emits('closeAutoFocus', event);\n          if (event.defaultPrevented) return;\n          rootContext.triggerElement.value?.focus({ preventScroll: true });\n          event.preventDefault();\n        }\n      \"\n    >\n      <DismissableLayer\n        as-child\n        :disable-outside-pointer-events=\"disableOutsidePointerEvents\"\n        @focus-outside.prevent\n        @dismiss=\"rootContext.onOpenChange(false)\"\n        @escape-key-down=\"emits('escapeKeyDown', $event)\"\n        @pointer-down-outside=\"emits('pointerDownOutside', $event)\"\n      >\n        <component\n          :is=\"\n            position === 'popper'\n              ? SelectPopperPosition\n              : SelectItemAlignedPosition\n          \"\n          v-bind=\"{ ...$attrs, ...forwardedProps }\"\n          :id=\"rootContext.contentId\"\n          :ref=\"\n            (vnode: Element | ComponentPublicInstance | null) => {\n              if (!vnode) return undefined\n              const el = unrefElement(vnode as ComponentPublicInstance) as HTMLElement | undefined\n              // special case for PopperContent\n              if (el?.hasAttribute('data-reka-popper-content-wrapper'))\n                content = el.firstElementChild as HTMLElement\n              else\n                content = el\n              return undefined\n            }\n          \"\n          role=\"listbox\"\n          :data-state=\"rootContext.open.value ? 'open' : 'closed'\"\n          :dir=\"rootContext.dir.value\"\n          :style=\"{\n            // flex layout so we can place the scroll buttons properly\n            display: 'flex',\n            flexDirection: 'column',\n            // reset the outline by default as the content MAY get focused\n            outline: 'none',\n          }\"\n          @contextmenu.prevent\n          @placed=\"isPositioned = true\"\n          @keydown=\"(handleKeyDown as any)\"\n        >\n          <slot />\n        </component>\n      </DismissableLayer>\n    </FocusScope>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useResizeObserver } from '@vueuse/core'\nimport { useCollection } from '@/Collection'\nimport { clamp, createContext, useForwardExpose } from '@/shared'\n\ninterface SelectItemAlignedPositionContext {\n  contentWrapper?: Ref<HTMLElement | undefined>\n  shouldExpandOnScrollRef?: Ref<boolean>\n  onScrollButtonChange: (node: HTMLElement | undefined) => void\n}\n\nexport interface SelectItemAlignedPositionProps extends PrimitiveProps {}\n\nexport const [injectSelectItemAlignedPositionContext, provideSelectItemAlignedPositionContext]\n  = createContext<SelectItemAlignedPositionContext>('SelectItemAlignedPosition')\n</script>\n\n<script setup lang=\"ts\">\nimport { nextTick, onMounted, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\nimport { injectSelectRootContext } from './SelectRoot.vue'\nimport { CONTENT_MARGIN } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<SelectItemAlignedPositionProps>()\nconst emits = defineEmits<{\n  placed: []\n}>()\n\nconst { getItems } = useCollection()\nconst rootContext = injectSelectRootContext()\nconst contentContext = injectSelectContentContext()\n\nconst shouldExpandOnScrollRef = ref(false)\nconst shouldRepositionRef = ref(true)\n\nconst contentWrapperElement = ref<HTMLElement>()\nconst { forwardRef, currentElement: contentElement } = useForwardExpose()\n\nconst { viewport, selectedItem, selectedItemText, focusSelectedItem }\n  = contentContext!\n\nfunction position() {\n  if (\n    rootContext.triggerElement.value\n    && rootContext.valueElement.value\n    && contentWrapperElement.value\n    && contentElement.value\n    && viewport?.value\n    && selectedItem?.value\n    && selectedItemText?.value\n  ) {\n    const triggerRect = rootContext.triggerElement.value.getBoundingClientRect()\n\n    // -----------------------------------------------------------------------------------------\n    //  Horizontal positioning\n    // -----------------------------------------------------------------------------------------\n    const contentRect = contentElement.value.getBoundingClientRect()\n    const valueNodeRect = rootContext.valueElement.value.getBoundingClientRect()\n    const itemTextRect = selectedItemText.value.getBoundingClientRect()\n\n    if (rootContext.dir.value !== 'rtl') {\n      const itemTextOffset = itemTextRect.left - contentRect.left\n      const left = valueNodeRect.left - itemTextOffset\n      const leftDelta = triggerRect.left - left\n      const minContentWidth = triggerRect.width + leftDelta\n      const contentWidth = Math.max(minContentWidth, contentRect.width)\n      const rightEdge = window.innerWidth - CONTENT_MARGIN\n      const clampedLeft = clamp(left, CONTENT_MARGIN, Math.max(CONTENT_MARGIN, rightEdge - contentWidth))\n\n      contentWrapperElement.value.style.minWidth = `${minContentWidth}px`\n      contentWrapperElement.value.style.left = `${clampedLeft}px`\n    }\n    else {\n      const itemTextOffset = contentRect.right - itemTextRect.right\n      const right = window.innerWidth - valueNodeRect.right - itemTextOffset\n      const rightDelta = window.innerWidth - triggerRect.right - right\n      const minContentWidth = triggerRect.width + rightDelta\n      const contentWidth = Math.max(minContentWidth, contentRect.width)\n      const leftEdge = window.innerWidth - CONTENT_MARGIN\n      const clampedRight = clamp(\n        right,\n        CONTENT_MARGIN,\n        Math.max(CONTENT_MARGIN, leftEdge - contentWidth),\n      )\n\n      contentWrapperElement.value.style.minWidth = `${minContentWidth}px`\n      contentWrapperElement.value.style.right = `${clampedRight}px`\n    }\n\n    // -----------------------------------------------------------------------------------------\n    // Vertical positioning\n    // -----------------------------------------------------------------------------------------\n    const items = getItems().map(i => i.ref)\n    const availableHeight = window.innerHeight - CONTENT_MARGIN * 2\n    const itemsHeight = viewport.value.scrollHeight\n\n    const contentStyles = window.getComputedStyle(contentElement.value)\n    const contentBorderTopWidth = Number.parseInt(\n      contentStyles.borderTopWidth,\n      10,\n    )\n    const contentPaddingTop = Number.parseInt(contentStyles.paddingTop, 10)\n    const contentBorderBottomWidth = Number.parseInt(\n      contentStyles.borderBottomWidth,\n      10,\n    )\n    const contentPaddingBottom = Number.parseInt(\n      contentStyles.paddingBottom,\n      10,\n    )\n\n    const fullContentHeight = contentBorderTopWidth + contentPaddingTop + itemsHeight + contentPaddingBottom + contentBorderBottomWidth\n    const minContentHeight = Math.min(\n      selectedItem.value.offsetHeight * 5,\n      fullContentHeight,\n    )\n\n    const viewportStyles = window.getComputedStyle(viewport.value)\n    const viewportPaddingTop = Number.parseInt(viewportStyles.paddingTop, 10)\n    const viewportPaddingBottom = Number.parseInt(\n      viewportStyles.paddingBottom,\n      10,\n    )\n\n    const topEdgeToTriggerMiddle\n      = triggerRect.top + triggerRect.height / 2 - CONTENT_MARGIN\n    const triggerMiddleToBottomEdge = availableHeight - topEdgeToTriggerMiddle\n\n    const selectedItemHalfHeight = selectedItem.value.offsetHeight / 2\n    const itemOffsetMiddle\n      = selectedItem.value.offsetTop + selectedItemHalfHeight\n    const contentTopToItemMiddle\n      = contentBorderTopWidth + contentPaddingTop + itemOffsetMiddle\n    const itemMiddleToContentBottom\n      = fullContentHeight - contentTopToItemMiddle\n\n    const willAlignWithoutTopOverflow\n      = contentTopToItemMiddle <= topEdgeToTriggerMiddle\n\n    if (willAlignWithoutTopOverflow) {\n      const isLastItem = selectedItem.value === items.at(-1)\n      contentWrapperElement.value.style.bottom = `${0}px`\n      const viewportOffsetBottom\n        = contentElement.value.clientHeight\n          - viewport.value.offsetTop\n          - viewport.value.offsetHeight\n      const clampedTriggerMiddleToBottomEdge = Math.max(\n        triggerMiddleToBottomEdge,\n        selectedItemHalfHeight\n        // viewport might have padding bottom, include it to avoid a scrollable viewport\n        + (isLastItem ? viewportPaddingBottom : 0)\n        + viewportOffsetBottom\n        + contentBorderBottomWidth,\n      )\n      const height = contentTopToItemMiddle + clampedTriggerMiddleToBottomEdge\n      contentWrapperElement.value.style.height = `${height}px`\n    }\n    else {\n      const isFirstItem = selectedItem.value === items[0]\n      contentWrapperElement.value.style.top = `${0}px`\n      const clampedTopEdgeToTriggerMiddle = Math.max(\n        topEdgeToTriggerMiddle,\n        contentBorderTopWidth\n        + viewport.value.offsetTop\n        // viewport might have padding top, include it to avoid a scrollable viewport\n        + (isFirstItem ? viewportPaddingTop : 0)\n        + selectedItemHalfHeight,\n      )\n      const height = clampedTopEdgeToTriggerMiddle + itemMiddleToContentBottom\n      contentWrapperElement.value.style.height = `${height}px`\n      viewport.value.scrollTop\n        = contentTopToItemMiddle\n          - topEdgeToTriggerMiddle\n          + viewport.value.offsetTop\n    }\n\n    contentWrapperElement.value.style.margin = `${CONTENT_MARGIN}px 0`\n    contentWrapperElement.value.style.minHeight = `${minContentHeight}px`\n    contentWrapperElement.value.style.maxHeight = `${availableHeight}px`\n    // -----------------------------------------------------------------------------------------\n\n    emits('placed')\n\n    // we don't want the initial scroll position adjustment to trigger \"expand on scroll\"\n    // so we explicitly turn it on only after they've registered.\n    requestAnimationFrame(() => (shouldExpandOnScrollRef.value = true))\n  }\n}\n\n// copy z-index from content to wrapper\nconst contentZIndex = ref('')\n\nonMounted(async () => {\n  await nextTick()\n  position()\n  if (contentElement.value)\n    contentZIndex.value = window.getComputedStyle(contentElement.value).zIndex\n})\n\n// When the viewport becomes scrollable at the top, the scroll up button will mount.\n// Because it is part of the normal flow, it will push down the viewport, thus throwing our\n// trigger => selectedItem alignment off by the amount the viewport was pushed down.\n// We wait for this to happen and then re-run the positining logic one more time to account for it.\nfunction handleScrollButtonChange(node: HTMLElement | undefined) {\n  if (node && shouldRepositionRef.value === true) {\n    position()\n    focusSelectedItem?.()\n    shouldRepositionRef.value = false\n  }\n}\n\n// Resize and position when trigger element changes\nuseResizeObserver(rootContext.triggerElement, () => {\n  position()\n})\n\nprovideSelectItemAlignedPositionContext({\n  contentWrapper: contentWrapperElement,\n  shouldExpandOnScrollRef,\n  onScrollButtonChange: handleScrollButtonChange,\n})\n</script>\n\n<template>\n  <div\n    ref=\"contentWrapperElement\"\n    :style=\"{\n      display: 'flex',\n      flexDirection: 'column',\n      position: 'fixed',\n      zIndex: contentZIndex,\n    }\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :style=\"{\n        // When we get the height of the content, it includes borders. If we were to set\n        // the height without having `boxSizing: 'border-box'` it would be too big.\n        boxSizing: 'border-box',\n        // We need to ensure the content doesn't get taller than the wrapper\n        maxHeight: '100%',\n      }\"\n      v-bind=\"{ ...$attrs, ...props }\"\n    >\n      <slot />\n    </Primitive>\n  </div>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useResizeObserver } from '@vueuse/core'\nimport { useCollection } from '@/Collection'\nimport { clamp, createContext, useForwardExpose } from '@/shared'\n\ninterface SelectItemAlignedPositionContext {\n  contentWrapper?: Ref<HTMLElement | undefined>\n  shouldExpandOnScrollRef?: Ref<boolean>\n  onScrollButtonChange: (node: HTMLElement | undefined) => void\n}\n\nexport interface SelectItemAlignedPositionProps extends PrimitiveProps {}\n\nexport const [injectSelectItemAlignedPositionContext, provideSelectItemAlignedPositionContext]\n  = createContext<SelectItemAlignedPositionContext>('SelectItemAlignedPosition')\n</script>\n\n<script setup lang=\"ts\">\nimport { nextTick, onMounted, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\nimport { injectSelectRootContext } from './SelectRoot.vue'\nimport { CONTENT_MARGIN } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<SelectItemAlignedPositionProps>()\nconst emits = defineEmits<{\n  placed: []\n}>()\n\nconst { getItems } = useCollection()\nconst rootContext = injectSelectRootContext()\nconst contentContext = injectSelectContentContext()\n\nconst shouldExpandOnScrollRef = ref(false)\nconst shouldRepositionRef = ref(true)\n\nconst contentWrapperElement = ref<HTMLElement>()\nconst { forwardRef, currentElement: contentElement } = useForwardExpose()\n\nconst { viewport, selectedItem, selectedItemText, focusSelectedItem }\n  = contentContext!\n\nfunction position() {\n  if (\n    rootContext.triggerElement.value\n    && rootContext.valueElement.value\n    && contentWrapperElement.value\n    && contentElement.value\n    && viewport?.value\n    && selectedItem?.value\n    && selectedItemText?.value\n  ) {\n    const triggerRect = rootContext.triggerElement.value.getBoundingClientRect()\n\n    // -----------------------------------------------------------------------------------------\n    //  Horizontal positioning\n    // -----------------------------------------------------------------------------------------\n    const contentRect = contentElement.value.getBoundingClientRect()\n    const valueNodeRect = rootContext.valueElement.value.getBoundingClientRect()\n    const itemTextRect = selectedItemText.value.getBoundingClientRect()\n\n    if (rootContext.dir.value !== 'rtl') {\n      const itemTextOffset = itemTextRect.left - contentRect.left\n      const left = valueNodeRect.left - itemTextOffset\n      const leftDelta = triggerRect.left - left\n      const minContentWidth = triggerRect.width + leftDelta\n      const contentWidth = Math.max(minContentWidth, contentRect.width)\n      const rightEdge = window.innerWidth - CONTENT_MARGIN\n      const clampedLeft = clamp(left, CONTENT_MARGIN, Math.max(CONTENT_MARGIN, rightEdge - contentWidth))\n\n      contentWrapperElement.value.style.minWidth = `${minContentWidth}px`\n      contentWrapperElement.value.style.left = `${clampedLeft}px`\n    }\n    else {\n      const itemTextOffset = contentRect.right - itemTextRect.right\n      const right = window.innerWidth - valueNodeRect.right - itemTextOffset\n      const rightDelta = window.innerWidth - triggerRect.right - right\n      const minContentWidth = triggerRect.width + rightDelta\n      const contentWidth = Math.max(minContentWidth, contentRect.width)\n      const leftEdge = window.innerWidth - CONTENT_MARGIN\n      const clampedRight = clamp(\n        right,\n        CONTENT_MARGIN,\n        Math.max(CONTENT_MARGIN, leftEdge - contentWidth),\n      )\n\n      contentWrapperElement.value.style.minWidth = `${minContentWidth}px`\n      contentWrapperElement.value.style.right = `${clampedRight}px`\n    }\n\n    // -----------------------------------------------------------------------------------------\n    // Vertical positioning\n    // -----------------------------------------------------------------------------------------\n    const items = getItems().map(i => i.ref)\n    const availableHeight = window.innerHeight - CONTENT_MARGIN * 2\n    const itemsHeight = viewport.value.scrollHeight\n\n    const contentStyles = window.getComputedStyle(contentElement.value)\n    const contentBorderTopWidth = Number.parseInt(\n      contentStyles.borderTopWidth,\n      10,\n    )\n    const contentPaddingTop = Number.parseInt(contentStyles.paddingTop, 10)\n    const contentBorderBottomWidth = Number.parseInt(\n      contentStyles.borderBottomWidth,\n      10,\n    )\n    const contentPaddingBottom = Number.parseInt(\n      contentStyles.paddingBottom,\n      10,\n    )\n\n    const fullContentHeight = contentBorderTopWidth + contentPaddingTop + itemsHeight + contentPaddingBottom + contentBorderBottomWidth\n    const minContentHeight = Math.min(\n      selectedItem.value.offsetHeight * 5,\n      fullContentHeight,\n    )\n\n    const viewportStyles = window.getComputedStyle(viewport.value)\n    const viewportPaddingTop = Number.parseInt(viewportStyles.paddingTop, 10)\n    const viewportPaddingBottom = Number.parseInt(\n      viewportStyles.paddingBottom,\n      10,\n    )\n\n    const topEdgeToTriggerMiddle\n      = triggerRect.top + triggerRect.height / 2 - CONTENT_MARGIN\n    const triggerMiddleToBottomEdge = availableHeight - topEdgeToTriggerMiddle\n\n    const selectedItemHalfHeight = selectedItem.value.offsetHeight / 2\n    const itemOffsetMiddle\n      = selectedItem.value.offsetTop + selectedItemHalfHeight\n    const contentTopToItemMiddle\n      = contentBorderTopWidth + contentPaddingTop + itemOffsetMiddle\n    const itemMiddleToContentBottom\n      = fullContentHeight - contentTopToItemMiddle\n\n    const willAlignWithoutTopOverflow\n      = contentTopToItemMiddle <= topEdgeToTriggerMiddle\n\n    if (willAlignWithoutTopOverflow) {\n      const isLastItem = selectedItem.value === items.at(-1)\n      contentWrapperElement.value.style.bottom = `${0}px`\n      const viewportOffsetBottom\n        = contentElement.value.clientHeight\n          - viewport.value.offsetTop\n          - viewport.value.offsetHeight\n      const clampedTriggerMiddleToBottomEdge = Math.max(\n        triggerMiddleToBottomEdge,\n        selectedItemHalfHeight\n        // viewport might have padding bottom, include it to avoid a scrollable viewport\n        + (isLastItem ? viewportPaddingBottom : 0)\n        + viewportOffsetBottom\n        + contentBorderBottomWidth,\n      )\n      const height = contentTopToItemMiddle + clampedTriggerMiddleToBottomEdge\n      contentWrapperElement.value.style.height = `${height}px`\n    }\n    else {\n      const isFirstItem = selectedItem.value === items[0]\n      contentWrapperElement.value.style.top = `${0}px`\n      const clampedTopEdgeToTriggerMiddle = Math.max(\n        topEdgeToTriggerMiddle,\n        contentBorderTopWidth\n        + viewport.value.offsetTop\n        // viewport might have padding top, include it to avoid a scrollable viewport\n        + (isFirstItem ? viewportPaddingTop : 0)\n        + selectedItemHalfHeight,\n      )\n      const height = clampedTopEdgeToTriggerMiddle + itemMiddleToContentBottom\n      contentWrapperElement.value.style.height = `${height}px`\n      viewport.value.scrollTop\n        = contentTopToItemMiddle\n          - topEdgeToTriggerMiddle\n          + viewport.value.offsetTop\n    }\n\n    contentWrapperElement.value.style.margin = `${CONTENT_MARGIN}px 0`\n    contentWrapperElement.value.style.minHeight = `${minContentHeight}px`\n    contentWrapperElement.value.style.maxHeight = `${availableHeight}px`\n    // -----------------------------------------------------------------------------------------\n\n    emits('placed')\n\n    // we don't want the initial scroll position adjustment to trigger \"expand on scroll\"\n    // so we explicitly turn it on only after they've registered.\n    requestAnimationFrame(() => (shouldExpandOnScrollRef.value = true))\n  }\n}\n\n// copy z-index from content to wrapper\nconst contentZIndex = ref('')\n\nonMounted(async () => {\n  await nextTick()\n  position()\n  if (contentElement.value)\n    contentZIndex.value = window.getComputedStyle(contentElement.value).zIndex\n})\n\n// When the viewport becomes scrollable at the top, the scroll up button will mount.\n// Because it is part of the normal flow, it will push down the viewport, thus throwing our\n// trigger => selectedItem alignment off by the amount the viewport was pushed down.\n// We wait for this to happen and then re-run the positining logic one more time to account for it.\nfunction handleScrollButtonChange(node: HTMLElement | undefined) {\n  if (node && shouldRepositionRef.value === true) {\n    position()\n    focusSelectedItem?.()\n    shouldRepositionRef.value = false\n  }\n}\n\n// Resize and position when trigger element changes\nuseResizeObserver(rootContext.triggerElement, () => {\n  position()\n})\n\nprovideSelectItemAlignedPositionContext({\n  contentWrapper: contentWrapperElement,\n  shouldExpandOnScrollRef,\n  onScrollButtonChange: handleScrollButtonChange,\n})\n</script>\n\n<template>\n  <div\n    ref=\"contentWrapperElement\"\n    :style=\"{\n      display: 'flex',\n      flexDirection: 'column',\n      position: 'fixed',\n      zIndex: contentZIndex,\n    }\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :style=\"{\n        // When we get the height of the content, it includes borders. If we were to set\n        // the height without having `boxSizing: 'border-box'` it would be too big.\n        boxSizing: 'border-box',\n        // We need to ensure the content doesn't get taller than the wrapper\n        maxHeight: '100%',\n      }\"\n      v-bind=\"{ ...$attrs, ...props }\"\n    >\n      <slot />\n    </Primitive>\n  </div>\n</template>\n","<script lang=\"ts\">\nimport type { PopperArrowProps } from '@/Popper'\n\nexport interface SelectArrowProps extends PopperArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperArrow } from '@/Popper'\nimport { injectSelectContentContext, SelectContentDefaultContextValue } from './SelectContentImpl.vue'\n\nconst props = withDefaults(defineProps<SelectArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nconst contentContext = injectSelectContentContext(SelectContentDefaultContextValue)\n</script>\n\n<template>\n  <PopperArrow\n    v-if=\"contentContext.position === 'popper'\"\n    v-bind=\"props\"\n  >\n    <slot />\n  </PopperArrow>\n</template>\n","<script lang=\"ts\">\nimport type { PopperArrowProps } from '@/Popper'\n\nexport interface SelectArrowProps extends PopperArrowProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperArrow } from '@/Popper'\nimport { injectSelectContentContext, SelectContentDefaultContextValue } from './SelectContentImpl.vue'\n\nconst props = withDefaults(defineProps<SelectArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nconst contentContext = injectSelectContentContext(SelectContentDefaultContextValue)\n</script>\n\n<template>\n  <PopperArrow\n    v-if=\"contentContext.position === 'popper'\"\n    v-bind=\"props\"\n  >\n    <slot />\n  </PopperArrow>\n</template>\n","<script setup lang=\"ts\">\nimport type { SelectRootContext } from './SelectRoot.vue'\nimport type { AcceptableValue } from '@/shared/types'\nimport { provideSelectContentContext, SelectContentDefaultContextValue } from './SelectContentImpl.vue'\nimport { provideSelectRootContext } from './SelectRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<{\n  context: SelectRootContext<AcceptableValue>\n}>()\n\nprovideSelectRootContext(props.context)\nprovideSelectContentContext(SelectContentDefaultContextValue)\n</script>\n\n<template>\n  <slot />\n</template>\n","<script setup lang=\"ts\">\nimport type { SelectRootContext } from './SelectRoot.vue'\nimport type { AcceptableValue } from '@/shared/types'\nimport { provideSelectContentContext, SelectContentDefaultContextValue } from './SelectContentImpl.vue'\nimport { provideSelectRootContext } from './SelectRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<{\n  context: SelectRootContext<AcceptableValue>\n}>()\n\nprovideSelectRootContext(props.context)\nprovideSelectContentContext(SelectContentDefaultContextValue)\n</script>\n\n<template>\n  <slot />\n</template>\n","<script lang=\"ts\">\nimport type {\n  SelectContentImplEmits,\n  SelectContentImplProps,\n} from './SelectContentImpl.vue'\nimport { computed, onMounted, onUnmounted, ref, watch } from 'vue'\n\nexport type SelectContentEmits = SelectContentImplEmits\n\nexport interface SelectContentProps extends SelectContentImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardPropsEmits } from '@/shared'\nimport SelectContentImpl from './SelectContentImpl.vue'\nimport SelectProvider from './SelectProvider.vue'\nimport { injectSelectRootContext } from './SelectRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<SelectContentProps>()\n\nconst emits = defineEmits<SelectContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst rootContext = injectSelectRootContext()\n\nconst fragment = ref<DocumentFragment>()\nonMounted(() => {\n  fragment.value = new DocumentFragment()\n})\n\nconst presenceRef = ref<InstanceType<typeof Presence>>()\n\nconst present = computed(() => props.forceMount || rootContext.open.value)\nconst renderPresence = ref(present.value)\n\nlet renderPresenceTimeout: ReturnType<typeof setTimeout> | undefined\n\nfunction clearRenderPresenceTimeout() {\n  if (renderPresenceTimeout) {\n    clearTimeout(renderPresenceTimeout)\n    renderPresenceTimeout = undefined\n  }\n}\n\nwatch(present, (_value, _oldValue, onCleanup) => {\n  // Toggle render presence after a delay (nextTick is not enough)\n  // to allow children to re-render with the latest state.\n  // Otherwise, they would remain in the old state during the transition,\n  // which would prevent the animation that depend on state (e.g., data-[state=closed])\n  // from being applied accurately.\n  // @see https://github.com/unovue/reka-ui/issues/1865\n  clearRenderPresenceTimeout()\n  renderPresenceTimeout = setTimeout(() => {\n    renderPresence.value = present.value\n    renderPresenceTimeout = undefined\n  })\n  onCleanup(clearRenderPresenceTimeout)\n})\n\nonUnmounted(clearRenderPresenceTimeout)\n</script>\n\n<template>\n  <Presence\n    v-if=\"present || renderPresence || presenceRef?.present\"\n    ref=\"presenceRef\"\n    :present=\"present\"\n  >\n    <SelectContentImpl v-bind=\"{ ...forwarded, ...$attrs }\">\n      <slot />\n    </SelectContentImpl>\n  </Presence>\n\n  <div v-else-if=\"fragment\">\n    <Teleport :to=\"fragment\">\n      <SelectProvider :context=\"rootContext\">\n        <slot />\n      </SelectProvider>\n    </Teleport>\n  </div>\n</template>\n","<script lang=\"ts\">\nimport type {\n  SelectContentImplEmits,\n  SelectContentImplProps,\n} from './SelectContentImpl.vue'\nimport { computed, onMounted, onUnmounted, ref, watch } from 'vue'\n\nexport type SelectContentEmits = SelectContentImplEmits\n\nexport interface SelectContentProps extends SelectContentImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardPropsEmits } from '@/shared'\nimport SelectContentImpl from './SelectContentImpl.vue'\nimport SelectProvider from './SelectProvider.vue'\nimport { injectSelectRootContext } from './SelectRoot.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = defineProps<SelectContentProps>()\n\nconst emits = defineEmits<SelectContentEmits>()\nconst forwarded = useForwardPropsEmits(props, emits)\n\nconst rootContext = injectSelectRootContext()\n\nconst fragment = ref<DocumentFragment>()\nonMounted(() => {\n  fragment.value = new DocumentFragment()\n})\n\nconst presenceRef = ref<InstanceType<typeof Presence>>()\n\nconst present = computed(() => props.forceMount || rootContext.open.value)\nconst renderPresence = ref(present.value)\n\nlet renderPresenceTimeout: ReturnType<typeof setTimeout> | undefined\n\nfunction clearRenderPresenceTimeout() {\n  if (renderPresenceTimeout) {\n    clearTimeout(renderPresenceTimeout)\n    renderPresenceTimeout = undefined\n  }\n}\n\nwatch(present, (_value, _oldValue, onCleanup) => {\n  // Toggle render presence after a delay (nextTick is not enough)\n  // to allow children to re-render with the latest state.\n  // Otherwise, they would remain in the old state during the transition,\n  // which would prevent the animation that depend on state (e.g., data-[state=closed])\n  // from being applied accurately.\n  // @see https://github.com/unovue/reka-ui/issues/1865\n  clearRenderPresenceTimeout()\n  renderPresenceTimeout = setTimeout(() => {\n    renderPresence.value = present.value\n    renderPresenceTimeout = undefined\n  })\n  onCleanup(clearRenderPresenceTimeout)\n})\n\nonUnmounted(clearRenderPresenceTimeout)\n</script>\n\n<template>\n  <Presence\n    v-if=\"present || renderPresence || presenceRef?.present\"\n    ref=\"presenceRef\"\n    :present=\"present\"\n  >\n    <SelectContentImpl v-bind=\"{ ...forwarded, ...$attrs }\">\n      <slot />\n    </SelectContentImpl>\n  </Presence>\n\n  <div v-else-if=\"fragment\">\n    <Teleport :to=\"fragment\">\n      <SelectProvider :context=\"rootContext\">\n        <slot />\n      </SelectProvider>\n    </Teleport>\n  </div>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useId } from '@/shared'\n\nexport interface SelectGroupProps extends PrimitiveProps {}\n\ninterface SelectGroupContext {\n  id: string\n}\n\nexport const [injectSelectGroupContext, provideSelectGroupContext]\n  = createContext<SelectGroupContext>('SelectGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<SelectGroupProps>()\n\nconst id = useId(undefined, 'reka-select-group')\nprovideSelectGroupContext({ id })\n</script>\n\n<template>\n  <Primitive\n    role=\"group\"\n    v-bind=\"props\"\n    :aria-labelledby=\"id\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useId } from '@/shared'\n\nexport interface SelectGroupProps extends PrimitiveProps {}\n\ninterface SelectGroupContext {\n  id: string\n}\n\nexport const [injectSelectGroupContext, provideSelectGroupContext]\n  = createContext<SelectGroupContext>('SelectGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<SelectGroupProps>()\n\nconst id = useId(undefined, 'reka-select-group')\nprovideSelectGroupContext({ id })\n</script>\n\n<template>\n  <Primitive\n    role=\"group\"\n    v-bind=\"props\"\n    :aria-labelledby=\"id\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface SelectIconProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nwithDefaults(defineProps<SelectIconProps>(), {\n  as: 'span',\n})\n</script>\n\n<template>\n  <Primitive\n    aria-hidden=\"true\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n  >\n    <slot>▼</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface SelectIconProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nwithDefaults(defineProps<SelectIconProps>(), {\n  as: 'span',\n})\n</script>\n\n<template>\n  <Primitive\n    aria-hidden=\"true\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n  >\n    <slot>▼</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue } from '@/shared/types'\nimport { useCollection } from '@/Collection'\nimport { createContext, getActiveElement, handleAndDispatchCustomEvent, useForwardExpose, useId } from '@/shared'\n\ninterface SelectItemContext<T = AcceptableValue> {\n  value: T\n  textId: string\n  disabled: Ref<boolean>\n  isSelected: Ref<boolean>\n  onItemTextChange: (node: HTMLElement | undefined) => void\n}\n\nexport const [injectSelectItemContext, provideSelectItemContext]\n  = createContext<SelectItemContext>('SelectItem')\n\nexport type SelectEvent<T> = CustomEvent<{ originalEvent: PointerEvent | KeyboardEvent, value?: T }>\n\nexport type SelectItemEmits<T = AcceptableValue> = {\n  /** Event handler called when the selecting item. <br> It can be prevented by calling `event.preventDefault`. */\n  select: [event: SelectEvent<T>]\n}\n\nexport interface SelectItemProps<T = AcceptableValue> extends PrimitiveProps {\n  /** The value given as data when submitted with a `name`. */\n  value: T\n  /** When `true`, prevents the user from interacting with the item. */\n  disabled?: boolean\n  /**\n   * Optional text used for typeahead purposes.\n   *\n   * By default the typeahead behavior will use the `.textContent` of the `SelectItemText` part.\n   *\n   * Use this when the content is complex, or you have non-textual content inside.\n   */\n  textValue?: string\n}\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport {\n  computed,\n  nextTick,\n  onMounted,\n  ref,\n  toRefs,\n} from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\nimport { injectSelectRootContext } from './SelectRoot.vue'\nimport { SELECTION_KEYS, valueComparator } from './utils'\n\nconst props = defineProps<SelectItemProps>()\nconst emits = defineEmits<SelectItemEmits<T>>()\nconst { disabled } = toRefs(props)\n\nconst rootContext = injectSelectRootContext()\nconst contentContext = injectSelectContentContext()\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { CollectionItem } = useCollection()\n\nconst isSelected = computed(() => valueComparator(rootContext.modelValue?.value, props.value, rootContext.by))\nconst isFocused = ref(false)\nconst textValue = ref(props.textValue ?? '')\nconst textId = useId(undefined, 'reka-select-item-text')\n\nconst SELECT_SELECT = 'select.select'\n\nasync function handleSelectCustomEvent(ev: PointerEvent | KeyboardEvent) {\n  if (ev.defaultPrevented)\n    return\n\n  const eventDetail = { originalEvent: ev, value: props.value as T }\n  handleAndDispatchCustomEvent(SELECT_SELECT, handleSelect, eventDetail)\n}\n\nasync function handleSelect(ev: SelectEvent<T>) {\n  await nextTick()\n  emits('select', ev)\n  if (ev.defaultPrevented)\n    return\n\n  if (!disabled.value) {\n    rootContext.onValueChange(props.value)\n    if (!rootContext.multiple.value)\n      rootContext.onOpenChange(false)\n  }\n}\n\nasync function handlePointerMove(event: PointerEvent) {\n  await nextTick()\n  if (event.defaultPrevented)\n    return\n  if (disabled.value) {\n    contentContext.onItemLeave?.()\n  }\n  else {\n    // even though safari doesn't support this option, it's acceptable\n    // as it only means it might scroll a few pixels when using the pointer.\n    (event.currentTarget as HTMLElement | null)?.focus({ preventScroll: true })\n  }\n}\n\nasync function handlePointerLeave(event: PointerEvent) {\n  await nextTick()\n  if (event.defaultPrevented)\n    return\n  if (event.currentTarget === getActiveElement())\n    contentContext.onItemLeave?.()\n}\n\nasync function handleKeyDown(event: KeyboardEvent) {\n  await nextTick()\n  if (event.defaultPrevented)\n    return\n  const isTypingAhead = contentContext.searchRef?.value !== ''\n  if (isTypingAhead && event.key === ' ')\n    return\n  if (SELECTION_KEYS.includes(event.key))\n    handleSelectCustomEvent(event)\n  // prevent page scroll if using the space key to select an item\n  if (event.key === ' ')\n    event.preventDefault()\n}\n\nif (props.value === '') {\n  throw new Error(\n    'A <SelectItem /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.',\n  )\n}\n\nonMounted(() => {\n  if (!currentElement.value)\n    return\n  contentContext.itemRefCallback(\n    currentElement.value,\n    props.value,\n    props.disabled,\n  )\n})\n\nprovideSelectItemContext({\n  value: props.value,\n  disabled,\n  textId,\n  isSelected,\n  onItemTextChange: (node) => {\n    textValue.value = ((textValue.value || node?.textContent) ?? '').trim()\n  },\n})\n</script>\n\n<template>\n  <CollectionItem :value=\"{ textValue }\">\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"option\"\n      :aria-labelledby=\"textId\"\n      :data-highlighted=\"isFocused ? '' : undefined\"\n      :aria-selected=\"isSelected\"\n      :data-state=\"isSelected ? 'checked' : 'unchecked'\"\n      :aria-disabled=\"disabled || undefined\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :tabindex=\"disabled ? undefined : -1\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      @focus=\"isFocused = true\"\n      @blur=\"isFocused = false\"\n      @pointerup=\"handleSelectCustomEvent\"\n      @pointerdown=\"(event: PointerEvent) => {\n        (event.currentTarget as HTMLElement).focus({ preventScroll: true })\n      }\"\n      @touchend.prevent.stop\n      @pointermove=\"handlePointerMove\"\n      @pointerleave=\"handlePointerLeave\"\n      @keydown=\"handleKeyDown\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue } from '@/shared/types'\nimport { useCollection } from '@/Collection'\nimport { createContext, getActiveElement, handleAndDispatchCustomEvent, useForwardExpose, useId } from '@/shared'\n\ninterface SelectItemContext<T = AcceptableValue> {\n  value: T\n  textId: string\n  disabled: Ref<boolean>\n  isSelected: Ref<boolean>\n  onItemTextChange: (node: HTMLElement | undefined) => void\n}\n\nexport const [injectSelectItemContext, provideSelectItemContext]\n  = createContext<SelectItemContext>('SelectItem')\n\nexport type SelectEvent<T> = CustomEvent<{ originalEvent: PointerEvent | KeyboardEvent, value?: T }>\n\nexport type SelectItemEmits<T = AcceptableValue> = {\n  /** Event handler called when the selecting item. <br> It can be prevented by calling `event.preventDefault`. */\n  select: [event: SelectEvent<T>]\n}\n\nexport interface SelectItemProps<T = AcceptableValue> extends PrimitiveProps {\n  /** The value given as data when submitted with a `name`. */\n  value: T\n  /** When `true`, prevents the user from interacting with the item. */\n  disabled?: boolean\n  /**\n   * Optional text used for typeahead purposes.\n   *\n   * By default the typeahead behavior will use the `.textContent` of the `SelectItemText` part.\n   *\n   * Use this when the content is complex, or you have non-textual content inside.\n   */\n  textValue?: string\n}\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableValue = AcceptableValue\">\nimport {\n  computed,\n  nextTick,\n  onMounted,\n  ref,\n  toRefs,\n} from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\nimport { injectSelectRootContext } from './SelectRoot.vue'\nimport { SELECTION_KEYS, valueComparator } from './utils'\n\nconst props = defineProps<SelectItemProps>()\nconst emits = defineEmits<SelectItemEmits<T>>()\nconst { disabled } = toRefs(props)\n\nconst rootContext = injectSelectRootContext()\nconst contentContext = injectSelectContentContext()\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { CollectionItem } = useCollection()\n\nconst isSelected = computed(() => valueComparator(rootContext.modelValue?.value, props.value, rootContext.by))\nconst isFocused = ref(false)\nconst textValue = ref(props.textValue ?? '')\nconst textId = useId(undefined, 'reka-select-item-text')\n\nconst SELECT_SELECT = 'select.select'\n\nasync function handleSelectCustomEvent(ev: PointerEvent | KeyboardEvent) {\n  if (ev.defaultPrevented)\n    return\n\n  const eventDetail = { originalEvent: ev, value: props.value as T }\n  handleAndDispatchCustomEvent(SELECT_SELECT, handleSelect, eventDetail)\n}\n\nasync function handleSelect(ev: SelectEvent<T>) {\n  await nextTick()\n  emits('select', ev)\n  if (ev.defaultPrevented)\n    return\n\n  if (!disabled.value) {\n    rootContext.onValueChange(props.value)\n    if (!rootContext.multiple.value)\n      rootContext.onOpenChange(false)\n  }\n}\n\nasync function handlePointerMove(event: PointerEvent) {\n  await nextTick()\n  if (event.defaultPrevented)\n    return\n  if (disabled.value) {\n    contentContext.onItemLeave?.()\n  }\n  else {\n    // even though safari doesn't support this option, it's acceptable\n    // as it only means it might scroll a few pixels when using the pointer.\n    (event.currentTarget as HTMLElement | null)?.focus({ preventScroll: true })\n  }\n}\n\nasync function handlePointerLeave(event: PointerEvent) {\n  await nextTick()\n  if (event.defaultPrevented)\n    return\n  if (event.currentTarget === getActiveElement())\n    contentContext.onItemLeave?.()\n}\n\nasync function handleKeyDown(event: KeyboardEvent) {\n  await nextTick()\n  if (event.defaultPrevented)\n    return\n  const isTypingAhead = contentContext.searchRef?.value !== ''\n  if (isTypingAhead && event.key === ' ')\n    return\n  if (SELECTION_KEYS.includes(event.key))\n    handleSelectCustomEvent(event)\n  // prevent page scroll if using the space key to select an item\n  if (event.key === ' ')\n    event.preventDefault()\n}\n\nif (props.value === '') {\n  throw new Error(\n    'A <SelectItem /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.',\n  )\n}\n\nonMounted(() => {\n  if (!currentElement.value)\n    return\n  contentContext.itemRefCallback(\n    currentElement.value,\n    props.value,\n    props.disabled,\n  )\n})\n\nprovideSelectItemContext({\n  value: props.value,\n  disabled,\n  textId,\n  isSelected,\n  onItemTextChange: (node) => {\n    textValue.value = ((textValue.value || node?.textContent) ?? '').trim()\n  },\n})\n</script>\n\n<template>\n  <CollectionItem :value=\"{ textValue }\">\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"option\"\n      :aria-labelledby=\"textId\"\n      :data-highlighted=\"isFocused ? '' : undefined\"\n      :aria-selected=\"isSelected\"\n      :data-state=\"isSelected ? 'checked' : 'unchecked'\"\n      :aria-disabled=\"disabled || undefined\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :tabindex=\"disabled ? undefined : -1\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      @focus=\"isFocused = true\"\n      @blur=\"isFocused = false\"\n      @pointerup=\"handleSelectCustomEvent\"\n      @pointerdown=\"(event: PointerEvent) => {\n        (event.currentTarget as HTMLElement).focus({ preventScroll: true })\n      }\"\n      @touchend.prevent.stop\n      @pointermove=\"handlePointerMove\"\n      @pointerleave=\"handlePointerLeave\"\n      @keydown=\"handleKeyDown\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface SelectItemIndicatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectSelectItemContext } from './SelectItem.vue'\n\nconst props = withDefaults(defineProps<SelectItemIndicatorProps>(), {\n  as: 'span',\n})\n\nconst itemContext = injectSelectItemContext()\n</script>\n\n<template>\n  <Primitive\n    v-if=\"itemContext.isSelected.value\"\n    aria-hidden=\"true\"\n    v-bind=\"props\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface SelectItemIndicatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectSelectItemContext } from './SelectItem.vue'\n\nconst props = withDefaults(defineProps<SelectItemIndicatorProps>(), {\n  as: 'span',\n})\n\nconst itemContext = injectSelectItemContext()\n</script>\n\n<template>\n  <Primitive\n    v-if=\"itemContext.isSelected.value\"\n    aria-hidden=\"true\"\n    v-bind=\"props\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectSelectRootContext } from './SelectRoot.vue'\n\nexport interface SelectItemTextProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\nimport { injectSelectItemContext } from './SelectItem.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<SelectItemTextProps>(), {\n  as: 'span',\n})\n\nconst rootContext = injectSelectRootContext()\nconst contentContext = injectSelectContentContext()\nconst itemContext = injectSelectItemContext()\n\nconst { forwardRef, currentElement: itemTextElement } = useForwardExpose()\n\nconst optionProps = computed(() => {\n  return {\n    value: itemContext.value,\n    disabled: itemContext.disabled.value,\n    textContent: itemTextElement.value?.textContent ?? itemContext.value?.toString() ?? '',\n  }\n})\n\nonMounted(() => {\n  if (!itemTextElement.value)\n    return\n  itemContext.onItemTextChange(itemTextElement.value)\n  contentContext.itemTextRefCallback(\n    itemTextElement.value,\n    itemContext.value,\n    itemContext.disabled.value,\n  )\n  rootContext.onOptionAdd(optionProps.value)\n})\n\nonUnmounted(() => {\n  rootContext.onOptionRemove(optionProps.value)\n})\n</script>\n\n<template>\n  <Primitive\n    :id=\"itemContext.textId\"\n    :ref=\"forwardRef\"\n    v-bind=\"{ ...props, ...$attrs }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectSelectRootContext } from './SelectRoot.vue'\n\nexport interface SelectItemTextProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\nimport { injectSelectItemContext } from './SelectItem.vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<SelectItemTextProps>(), {\n  as: 'span',\n})\n\nconst rootContext = injectSelectRootContext()\nconst contentContext = injectSelectContentContext()\nconst itemContext = injectSelectItemContext()\n\nconst { forwardRef, currentElement: itemTextElement } = useForwardExpose()\n\nconst optionProps = computed(() => {\n  return {\n    value: itemContext.value,\n    disabled: itemContext.disabled.value,\n    textContent: itemTextElement.value?.textContent ?? itemContext.value?.toString() ?? '',\n  }\n})\n\nonMounted(() => {\n  if (!itemTextElement.value)\n    return\n  itemContext.onItemTextChange(itemTextElement.value)\n  contentContext.itemTextRefCallback(\n    itemTextElement.value,\n    itemContext.value,\n    itemContext.disabled.value,\n  )\n  rootContext.onOptionAdd(optionProps.value)\n})\n\nonUnmounted(() => {\n  rootContext.onOptionRemove(optionProps.value)\n})\n</script>\n\n<template>\n  <Primitive\n    :id=\"itemContext.textId\"\n    :ref=\"forwardRef\"\n    v-bind=\"{ ...props, ...$attrs }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface SelectLabelProps extends PrimitiveProps {\n  for?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectSelectGroupContext } from './SelectGroup.vue'\n\nconst props = withDefaults(defineProps<SelectLabelProps>(), {\n  as: 'div',\n})\n\nconst groupContext = injectSelectGroupContext({ id: '' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"groupContext.id\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface SelectLabelProps extends PrimitiveProps {\n  for?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectSelectGroupContext } from './SelectGroup.vue'\n\nconst props = withDefaults(defineProps<SelectLabelProps>(), {\n  as: 'div',\n})\n\nconst groupContext = injectSelectGroupContext({ id: '' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"groupContext.id\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface SelectPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<SelectPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface SelectPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<SelectPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script setup lang=\"ts\">\nimport { onBeforeUnmount, ref, watchEffect } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\nimport { getActiveElement } from '@/shared'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\n\nexport type SelectScrollButtonImplEmits = {\n  autoScroll: []\n}\n\nconst emits = defineEmits<SelectScrollButtonImplEmits>()\nconst { getItems } = useCollection()\n\nconst contentContext = injectSelectContentContext()\nconst autoScrollTimerRef = ref<number | null>(null)\n\nfunction clearAutoScrollTimer() {\n  if (autoScrollTimerRef.value !== null) {\n    window.clearInterval(autoScrollTimerRef.value)\n    autoScrollTimerRef.value = null\n  }\n}\n\nwatchEffect(() => {\n  const activeItem = getItems().map(i => i.ref).find(\n    item => item === getActiveElement(),\n  )\n  activeItem?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction handlePointerDown() {\n  if (autoScrollTimerRef.value === null) {\n    autoScrollTimerRef.value = window.setInterval(() => {\n      emits('autoScroll')\n    }, 50)\n  }\n}\n\nfunction handlePointerMove() {\n  contentContext.onItemLeave?.()\n  if (autoScrollTimerRef.value === null) {\n    autoScrollTimerRef.value = window.setInterval(() => {\n      emits('autoScroll')\n    }, 50)\n  }\n}\n\nonBeforeUnmount(() => clearAutoScrollTimer())\n</script>\n\n<template>\n  <Primitive\n    aria-hidden=\"true\"\n    :style=\"{\n      flexShrink: 0,\n    }\"\n    v-bind=\"$parent?.$props\"\n    @pointerdown=\"handlePointerDown\"\n    @pointermove=\"handlePointerMove\"\n    @pointerleave=\"\n      () => {\n        clearAutoScrollTimer();\n      }\n    \"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script setup lang=\"ts\">\nimport { onBeforeUnmount, ref, watchEffect } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\nimport { getActiveElement } from '@/shared'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\n\nexport type SelectScrollButtonImplEmits = {\n  autoScroll: []\n}\n\nconst emits = defineEmits<SelectScrollButtonImplEmits>()\nconst { getItems } = useCollection()\n\nconst contentContext = injectSelectContentContext()\nconst autoScrollTimerRef = ref<number | null>(null)\n\nfunction clearAutoScrollTimer() {\n  if (autoScrollTimerRef.value !== null) {\n    window.clearInterval(autoScrollTimerRef.value)\n    autoScrollTimerRef.value = null\n  }\n}\n\nwatchEffect(() => {\n  const activeItem = getItems().map(i => i.ref).find(\n    item => item === getActiveElement(),\n  )\n  activeItem?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction handlePointerDown() {\n  if (autoScrollTimerRef.value === null) {\n    autoScrollTimerRef.value = window.setInterval(() => {\n      emits('autoScroll')\n    }, 50)\n  }\n}\n\nfunction handlePointerMove() {\n  contentContext.onItemLeave?.()\n  if (autoScrollTimerRef.value === null) {\n    autoScrollTimerRef.value = window.setInterval(() => {\n      emits('autoScroll')\n    }, 50)\n  }\n}\n\nonBeforeUnmount(() => clearAutoScrollTimer())\n</script>\n\n<template>\n  <Primitive\n    aria-hidden=\"true\"\n    :style=\"{\n      flexShrink: 0,\n    }\"\n    v-bind=\"$parent?.$props\"\n    @pointerdown=\"handlePointerDown\"\n    @pointermove=\"handlePointerMove\"\n    @pointerleave=\"\n      () => {\n        clearAutoScrollTimer();\n      }\n    \"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface SelectScrollDownButtonProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref, watch, watchEffect } from 'vue'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\nimport { injectSelectItemAlignedPositionContext } from './SelectItemAlignedPosition.vue'\nimport SelectScrollButtonImpl from './SelectScrollButtonImpl.vue'\n\ndefineProps<SelectScrollDownButtonProps>()\n\nconst contentContext = injectSelectContentContext()\nconst alignedPositionContext\n  = contentContext.position === 'item-aligned'\n    ? injectSelectItemAlignedPositionContext()\n    : undefined\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst canScrollDown = ref(false)\n\nwatchEffect((cleanupFn) => {\n  if (contentContext.viewport?.value && contentContext.isPositioned?.value) {\n    const viewport = contentContext.viewport.value\n\n    function handleScroll() {\n      const maxScroll = viewport.scrollHeight - viewport.clientHeight\n      // we use Math.ceil here because if the UI is zoomed-in\n      // `scrollTop` is not always reported as an integer\n      canScrollDown.value = Math.ceil(viewport.scrollTop) < maxScroll\n    }\n    handleScroll()\n    viewport.addEventListener('scroll', handleScroll)\n\n    cleanupFn(() => viewport.removeEventListener('scroll', handleScroll))\n  }\n})\n\nwatch(currentElement, () => {\n  if (currentElement.value)\n    alignedPositionContext?.onScrollButtonChange(currentElement.value)\n})\n</script>\n\n<template>\n  <SelectScrollButtonImpl\n    v-if=\"canScrollDown\"\n    :ref=\"forwardRef\"\n    @auto-scroll=\"\n      () => {\n        const { viewport, selectedItem } = contentContext;\n        if (viewport?.value && selectedItem?.value) {\n          viewport.value.scrollTop = viewport.value.scrollTop + selectedItem.value.offsetHeight;\n        }\n      }\n    \"\n  >\n    <slot />\n  </SelectScrollButtonImpl>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface SelectScrollDownButtonProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref, watch, watchEffect } from 'vue'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\nimport { injectSelectItemAlignedPositionContext } from './SelectItemAlignedPosition.vue'\nimport SelectScrollButtonImpl from './SelectScrollButtonImpl.vue'\n\ndefineProps<SelectScrollDownButtonProps>()\n\nconst contentContext = injectSelectContentContext()\nconst alignedPositionContext\n  = contentContext.position === 'item-aligned'\n    ? injectSelectItemAlignedPositionContext()\n    : undefined\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst canScrollDown = ref(false)\n\nwatchEffect((cleanupFn) => {\n  if (contentContext.viewport?.value && contentContext.isPositioned?.value) {\n    const viewport = contentContext.viewport.value\n\n    function handleScroll() {\n      const maxScroll = viewport.scrollHeight - viewport.clientHeight\n      // we use Math.ceil here because if the UI is zoomed-in\n      // `scrollTop` is not always reported as an integer\n      canScrollDown.value = Math.ceil(viewport.scrollTop) < maxScroll\n    }\n    handleScroll()\n    viewport.addEventListener('scroll', handleScroll)\n\n    cleanupFn(() => viewport.removeEventListener('scroll', handleScroll))\n  }\n})\n\nwatch(currentElement, () => {\n  if (currentElement.value)\n    alignedPositionContext?.onScrollButtonChange(currentElement.value)\n})\n</script>\n\n<template>\n  <SelectScrollButtonImpl\n    v-if=\"canScrollDown\"\n    :ref=\"forwardRef\"\n    @auto-scroll=\"\n      () => {\n        const { viewport, selectedItem } = contentContext;\n        if (viewport?.value && selectedItem?.value) {\n          viewport.value.scrollTop = viewport.value.scrollTop + selectedItem.value.offsetHeight;\n        }\n      }\n    \"\n  >\n    <slot />\n  </SelectScrollButtonImpl>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface SelectScrollUpButtonProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref, watch, watchEffect } from 'vue'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\nimport { injectSelectItemAlignedPositionContext } from './SelectItemAlignedPosition.vue'\nimport SelectScrollButtonImpl from './SelectScrollButtonImpl.vue'\n\ndefineProps<SelectScrollUpButtonProps>()\n\nconst contentContext = injectSelectContentContext()\nconst alignedPositionContext\n  = contentContext.position === 'item-aligned'\n    ? injectSelectItemAlignedPositionContext()\n    : undefined\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst canScrollUp = ref(false)\n\nwatchEffect((cleanupFn) => {\n  if (contentContext.viewport?.value && contentContext.isPositioned?.value) {\n    const viewport = contentContext.viewport.value\n\n    function handleScroll() {\n      canScrollUp.value = viewport.scrollTop > 0\n    }\n    handleScroll()\n    viewport.addEventListener('scroll', handleScroll)\n\n    cleanupFn(() => viewport.removeEventListener('scroll', handleScroll))\n  }\n})\n\nwatch(currentElement, () => {\n  if (currentElement.value)\n    alignedPositionContext?.onScrollButtonChange(currentElement.value)\n})\n</script>\n\n<template>\n  <SelectScrollButtonImpl\n    v-if=\"canScrollUp\"\n    :ref=\"forwardRef\"\n    @auto-scroll=\"() => {\n      const { viewport, selectedItem } = contentContext;\n      if (viewport?.value && selectedItem?.value) {\n        viewport.value.scrollTop = viewport.value.scrollTop - selectedItem.value.offsetHeight;\n      }\n    }\"\n  >\n    <slot />\n  </SelectScrollButtonImpl>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface SelectScrollUpButtonProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ref, watch, watchEffect } from 'vue'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\nimport { injectSelectItemAlignedPositionContext } from './SelectItemAlignedPosition.vue'\nimport SelectScrollButtonImpl from './SelectScrollButtonImpl.vue'\n\ndefineProps<SelectScrollUpButtonProps>()\n\nconst contentContext = injectSelectContentContext()\nconst alignedPositionContext\n  = contentContext.position === 'item-aligned'\n    ? injectSelectItemAlignedPositionContext()\n    : undefined\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst canScrollUp = ref(false)\n\nwatchEffect((cleanupFn) => {\n  if (contentContext.viewport?.value && contentContext.isPositioned?.value) {\n    const viewport = contentContext.viewport.value\n\n    function handleScroll() {\n      canScrollUp.value = viewport.scrollTop > 0\n    }\n    handleScroll()\n    viewport.addEventListener('scroll', handleScroll)\n\n    cleanupFn(() => viewport.removeEventListener('scroll', handleScroll))\n  }\n})\n\nwatch(currentElement, () => {\n  if (currentElement.value)\n    alignedPositionContext?.onScrollButtonChange(currentElement.value)\n})\n</script>\n\n<template>\n  <SelectScrollButtonImpl\n    v-if=\"canScrollUp\"\n    :ref=\"forwardRef\"\n    @auto-scroll=\"() => {\n      const { viewport, selectedItem } = contentContext;\n      if (viewport?.value && selectedItem?.value) {\n        viewport.value.scrollTop = viewport.value.scrollTop - selectedItem.value.offsetHeight;\n      }\n    }\"\n  >\n    <slot />\n  </SelectScrollButtonImpl>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface SelectSeparatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<SelectSeparatorProps>()\n</script>\n\n<template>\n  <Primitive\n    aria-hidden=\"true\"\n    v-bind=\"props\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface SelectSeparatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<SelectSeparatorProps>()\n</script>\n\n<template>\n  <Primitive\n    aria-hidden=\"true\"\n    v-bind=\"props\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport { useCollection } from '@/Collection'\n\nexport interface SelectTriggerProps extends PopperAnchorProps {\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport type { PopperAnchorProps } from '@/Popper'\nimport { computed, onMounted } from 'vue'\nimport { PopperAnchor } from '@/Popper'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose, useId, useTypeahead } from '@/shared'\nimport {\n  injectSelectRootContext,\n} from './SelectRoot.vue'\nimport { OPEN_KEYS, shouldShowPlaceholder } from './utils'\n\nconst props = withDefaults(defineProps<SelectTriggerProps>(), {\n  as: 'button',\n})\nconst rootContext = injectSelectRootContext()\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\n\nconst isDisabled = computed(() => rootContext.disabled?.value || props.disabled)\n\nrootContext.contentId ||= useId(undefined, 'reka-select-content')\nonMounted(() => {\n  rootContext.onTriggerChange(triggerElement.value)\n})\n\nconst { getItems } = useCollection()\nconst { search, handleTypeaheadSearch, resetTypeahead } = useTypeahead()\nfunction handleOpen() {\n  if (!isDisabled.value) {\n    rootContext.onOpenChange(true)\n    // reset typeahead when we open\n    resetTypeahead()\n  }\n}\n\nfunction handlePointerOpen(event: PointerEvent) {\n  handleOpen()\n  rootContext.triggerPointerDownPosRef.value = {\n    x: Math.round(event.pageX),\n    y: Math.round(event.pageY),\n  }\n}\n</script>\n\n<template>\n  <PopperAnchor\n    as-child\n    :reference=\"reference\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"combobox\"\n      :type=\"as === 'button' ? 'button' : undefined\"\n      :aria-controls=\"rootContext.contentId\"\n      :aria-expanded=\"rootContext.open.value || false\"\n      :aria-required=\"rootContext.required?.value\"\n      aria-autocomplete=\"none\"\n      :disabled=\"isDisabled\"\n      :dir=\"rootContext?.dir.value\"\n      :data-state=\"rootContext?.open.value ? 'open' : 'closed'\"\n      :data-disabled=\"isDisabled ? '' : undefined\"\n      :data-placeholder=\"shouldShowPlaceholder(rootContext.modelValue?.value) ? '' : undefined\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      @click=\"\n        (event: MouseEvent) => {\n          // Whilst browsers generally have no issue focusing the trigger when clicking\n          // on a label, Safari seems to struggle with the fact that there's no `onClick`.\n          // We force `focus` in this case. Note: this doesn't create any other side-effect\n          // because we are preventing default in `onPointerDown` so effectively\n          // this only runs for a label 'click'\n          (event?.currentTarget as HTMLElement)?.focus();\n        }\n      \"\n      @pointerdown=\"\n        (event: PointerEvent) => {\n          // Prevent opening on touch down.\n          // https://github.com/unovue/reka-ui/issues/804\n          if (event.pointerType === 'touch')\n            return event.preventDefault();\n\n          // prevent implicit pointer capture\n          // https://www.w3.org/TR/pointerevents3/#implicit-pointer-capture\n          const target = event.target as HTMLElement;\n          if (target.hasPointerCapture(event.pointerId)) {\n            target.releasePointerCapture(event.pointerId);\n          }\n\n          // only call handler if it's the left button (mousedown gets triggered by all mouse buttons)\n          // but not when the control key is pressed (avoiding MacOS right click)\n          if (event.button === 0 && event.ctrlKey === false) {\n            handlePointerOpen(event)\n            // prevent trigger from stealing focus from the active item after opening.\n            event.preventDefault();\n          }\n        }\n      \"\n      @pointerup.prevent=\"\n        (event: PointerEvent) => {\n          // Only open on pointer up when using touch devices\n          // https://github.com/unovue/reka-ui/issues/804\n          if (event.pointerType === 'touch')\n            handlePointerOpen(event)\n        }\n      \"\n      @keydown=\"\n        (event: KeyboardEvent) => {\n          const isTypingAhead = search !== '';\n          const isModifierKey = event.ctrlKey || event.altKey || event.metaKey;\n          if (!isModifierKey && event.key.length === 1)\n            if (isTypingAhead && event.key === ' ') return;\n\n          handleTypeaheadSearch(event.key, getItems());\n          if (OPEN_KEYS.includes(event.key)) {\n            handleOpen();\n            event.preventDefault();\n          }\n        }\n      \"\n    >\n      <slot />\n    </Primitive>\n  </PopperAnchor>\n</template>\n","<script lang=\"ts\">\nimport { useCollection } from '@/Collection'\n\nexport interface SelectTriggerProps extends PopperAnchorProps {\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport type { PopperAnchorProps } from '@/Popper'\nimport { computed, onMounted } from 'vue'\nimport { PopperAnchor } from '@/Popper'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose, useId, useTypeahead } from '@/shared'\nimport {\n  injectSelectRootContext,\n} from './SelectRoot.vue'\nimport { OPEN_KEYS, shouldShowPlaceholder } from './utils'\n\nconst props = withDefaults(defineProps<SelectTriggerProps>(), {\n  as: 'button',\n})\nconst rootContext = injectSelectRootContext()\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\n\nconst isDisabled = computed(() => rootContext.disabled?.value || props.disabled)\n\nrootContext.contentId ||= useId(undefined, 'reka-select-content')\nonMounted(() => {\n  rootContext.onTriggerChange(triggerElement.value)\n})\n\nconst { getItems } = useCollection()\nconst { search, handleTypeaheadSearch, resetTypeahead } = useTypeahead()\nfunction handleOpen() {\n  if (!isDisabled.value) {\n    rootContext.onOpenChange(true)\n    // reset typeahead when we open\n    resetTypeahead()\n  }\n}\n\nfunction handlePointerOpen(event: PointerEvent) {\n  handleOpen()\n  rootContext.triggerPointerDownPosRef.value = {\n    x: Math.round(event.pageX),\n    y: Math.round(event.pageY),\n  }\n}\n</script>\n\n<template>\n  <PopperAnchor\n    as-child\n    :reference=\"reference\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"combobox\"\n      :type=\"as === 'button' ? 'button' : undefined\"\n      :aria-controls=\"rootContext.contentId\"\n      :aria-expanded=\"rootContext.open.value || false\"\n      :aria-required=\"rootContext.required?.value\"\n      aria-autocomplete=\"none\"\n      :disabled=\"isDisabled\"\n      :dir=\"rootContext?.dir.value\"\n      :data-state=\"rootContext?.open.value ? 'open' : 'closed'\"\n      :data-disabled=\"isDisabled ? '' : undefined\"\n      :data-placeholder=\"shouldShowPlaceholder(rootContext.modelValue?.value) ? '' : undefined\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      @click=\"\n        (event: MouseEvent) => {\n          // Whilst browsers generally have no issue focusing the trigger when clicking\n          // on a label, Safari seems to struggle with the fact that there's no `onClick`.\n          // We force `focus` in this case. Note: this doesn't create any other side-effect\n          // because we are preventing default in `onPointerDown` so effectively\n          // this only runs for a label 'click'\n          (event?.currentTarget as HTMLElement)?.focus();\n        }\n      \"\n      @pointerdown=\"\n        (event: PointerEvent) => {\n          // Prevent opening on touch down.\n          // https://github.com/unovue/reka-ui/issues/804\n          if (event.pointerType === 'touch')\n            return event.preventDefault();\n\n          // prevent implicit pointer capture\n          // https://www.w3.org/TR/pointerevents3/#implicit-pointer-capture\n          const target = event.target as HTMLElement;\n          if (target.hasPointerCapture(event.pointerId)) {\n            target.releasePointerCapture(event.pointerId);\n          }\n\n          // only call handler if it's the left button (mousedown gets triggered by all mouse buttons)\n          // but not when the control key is pressed (avoiding MacOS right click)\n          if (event.button === 0 && event.ctrlKey === false) {\n            handlePointerOpen(event)\n            // prevent trigger from stealing focus from the active item after opening.\n            event.preventDefault();\n          }\n        }\n      \"\n      @pointerup.prevent=\"\n        (event: PointerEvent) => {\n          // Only open on pointer up when using touch devices\n          // https://github.com/unovue/reka-ui/issues/804\n          if (event.pointerType === 'touch')\n            handlePointerOpen(event)\n        }\n      \"\n      @keydown=\"\n        (event: KeyboardEvent) => {\n          const isTypingAhead = search !== '';\n          const isModifierKey = event.ctrlKey || event.altKey || event.metaKey;\n          if (!isModifierKey && event.key.length === 1)\n            if (isTypingAhead && event.key === ' ') return;\n\n          handleTypeaheadSearch(event.key, getItems());\n          if (OPEN_KEYS.includes(event.key)) {\n            handleOpen();\n            event.preventDefault();\n          }\n        }\n      \"\n    >\n      <slot />\n    </Primitive>\n  </PopperAnchor>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue } from '@/shared/types'\nimport { valueComparator } from './utils'\n\nexport interface SelectValueProps extends PrimitiveProps {\n  /** The content that will be rendered inside the `SelectValue` when no `value` or `defaultValue` is set. */\n  placeholder?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectSelectRootContext } from './SelectRoot.vue'\n\nconst props = withDefaults(defineProps<SelectValueProps>(), {\n  as: 'span',\n  placeholder: '',\n})\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst rootContext = injectSelectRootContext()\n\nonMounted(() => {\n  rootContext.valueElement = currentElement\n})\n\nconst selectedLabel = computed(() => {\n  let list: string[] = []\n  const options = Array.from(rootContext.optionsSet.value)\n  const getOption = (value?: AcceptableValue) => options.find(option => valueComparator(value, option.value, rootContext.by))\n  if (Array.isArray(rootContext.modelValue.value)) {\n    list = rootContext.modelValue.value.map(value => getOption(value)?.textContent ?? '')\n  }\n  else {\n    list = [getOption(rootContext.modelValue.value)?.textContent ?? '']\n  }\n  return list.filter(Boolean)\n})\n\nconst slotText = computed(() => {\n  return selectedLabel.value.length ? selectedLabel.value.join(', ') : props.placeholder\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :style=\"{ pointerEvents: 'none' }\"\n    :data-placeholder=\"selectedLabel.length ? undefined : props.placeholder\"\n  >\n    <slot\n      :selected-label=\"selectedLabel\"\n      :model-value=\"rootContext.modelValue.value\"\n    >\n      {{ slotText }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { AcceptableValue } from '@/shared/types'\nimport { valueComparator } from './utils'\n\nexport interface SelectValueProps extends PrimitiveProps {\n  /** The content that will be rendered inside the `SelectValue` when no `value` or `defaultValue` is set. */\n  placeholder?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectSelectRootContext } from './SelectRoot.vue'\n\nconst props = withDefaults(defineProps<SelectValueProps>(), {\n  as: 'span',\n  placeholder: '',\n})\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst rootContext = injectSelectRootContext()\n\nonMounted(() => {\n  rootContext.valueElement = currentElement\n})\n\nconst selectedLabel = computed(() => {\n  let list: string[] = []\n  const options = Array.from(rootContext.optionsSet.value)\n  const getOption = (value?: AcceptableValue) => options.find(option => valueComparator(value, option.value, rootContext.by))\n  if (Array.isArray(rootContext.modelValue.value)) {\n    list = rootContext.modelValue.value.map(value => getOption(value)?.textContent ?? '')\n  }\n  else {\n    list = [getOption(rootContext.modelValue.value)?.textContent ?? '']\n  }\n  return list.filter(Boolean)\n})\n\nconst slotText = computed(() => {\n  return selectedLabel.value.length ? selectedLabel.value.join(', ') : props.placeholder\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :style=\"{ pointerEvents: 'none' }\"\n    :data-placeholder=\"selectedLabel.length ? undefined : props.placeholder\"\n  >\n    <slot\n      :selected-label=\"selectedLabel\"\n      :model-value=\"rootContext.modelValue.value\"\n    >\n      {{ slotText }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { useNonce } from '@/shared/useNonce'\n\nexport interface SelectViewportProps extends PrimitiveProps {\n  /**\n   * Will add `nonce` attribute to the style tag which can be used by Content Security Policy. <br> If omitted, inherits globally from `ConfigProvider`.\n   */\n  nonce?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted, ref, toRefs } from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\nimport { injectSelectItemAlignedPositionContext } from './SelectItemAlignedPosition.vue'\nimport { CONTENT_MARGIN } from './utils'\n\nconst props = defineProps<SelectViewportProps>()\nconst { nonce: propNonce } = toRefs(props)\nconst nonce = useNonce(propNonce)\n\nconst contentContext = injectSelectContentContext()\nconst alignedPositionContext\n  = contentContext.position === 'item-aligned'\n    ? injectSelectItemAlignedPositionContext()\n    : undefined\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nonMounted(() => {\n  contentContext?.onViewportChange(currentElement.value)\n})\n\nconst prevScrollTopRef = ref(0)\n\nfunction handleScroll(event: WheelEvent) {\n  const viewport = event.currentTarget as HTMLElement\n  const { shouldExpandOnScrollRef, contentWrapper } = alignedPositionContext ?? {}\n  if (shouldExpandOnScrollRef?.value && contentWrapper?.value) {\n    const scrolledBy = Math.abs(prevScrollTopRef.value - viewport.scrollTop)\n    if (scrolledBy > 0) {\n      const availableHeight = window.innerHeight - CONTENT_MARGIN * 2\n      const cssMinHeight = Number.parseFloat(\n        contentWrapper.value.style.minHeight,\n      )\n      const cssHeight = Number.parseFloat(contentWrapper.value.style.height)\n      const prevHeight = Math.max(cssMinHeight, cssHeight)\n\n      if (prevHeight < availableHeight) {\n        const nextHeight = prevHeight + scrolledBy\n        const clampedNextHeight = Math.min(availableHeight, nextHeight)\n        const heightDiff = nextHeight - clampedNextHeight\n\n        contentWrapper.value.style.height = `${clampedNextHeight}px`\n        if (contentWrapper.value.style.bottom === '0px') {\n          viewport.scrollTop = heightDiff > 0 ? heightDiff : 0\n          // ensure the content stays pinned to the bottom\n          contentWrapper.value.style.justifyContent = 'flex-end'\n        }\n      }\n    }\n  }\n  prevScrollTopRef.value = viewport.scrollTop\n}\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    data-reka-select-viewport\n    role=\"presentation\"\n    v-bind=\"{ ...$attrs, ...props }\"\n    :style=\"{\n      // we use position: 'relative' here on the `viewport` so that when we call\n      // `selectedItem.offsetTop` in calculations, the offset is relative to the viewport\n      // (independent of the scrollUpButton).\n      position: 'relative',\n      flex: 1,\n      overflow: 'hidden auto',\n    }\"\n    @scroll=\"handleScroll\"\n  >\n    <slot />\n  </Primitive>\n  <Primitive\n    as=\"style\"\n    :nonce=\"nonce\"\n  >\n    /* Hide scrollbars cross-browser and enable momentum scroll for touch\n    devices */ [data-reka-select-viewport] { scrollbar-width:none; -ms-overflow-style: none;\n    -webkit-overflow-scrolling: touch; }\n    [data-reka-select-viewport]::-webkit-scrollbar { display: none; }\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { useNonce } from '@/shared/useNonce'\n\nexport interface SelectViewportProps extends PrimitiveProps {\n  /**\n   * Will add `nonce` attribute to the style tag which can be used by Content Security Policy. <br> If omitted, inherits globally from `ConfigProvider`.\n   */\n  nonce?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { onMounted, ref, toRefs } from 'vue'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectSelectContentContext } from './SelectContentImpl.vue'\nimport { injectSelectItemAlignedPositionContext } from './SelectItemAlignedPosition.vue'\nimport { CONTENT_MARGIN } from './utils'\n\nconst props = defineProps<SelectViewportProps>()\nconst { nonce: propNonce } = toRefs(props)\nconst nonce = useNonce(propNonce)\n\nconst contentContext = injectSelectContentContext()\nconst alignedPositionContext\n  = contentContext.position === 'item-aligned'\n    ? injectSelectItemAlignedPositionContext()\n    : undefined\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nonMounted(() => {\n  contentContext?.onViewportChange(currentElement.value)\n})\n\nconst prevScrollTopRef = ref(0)\n\nfunction handleScroll(event: WheelEvent) {\n  const viewport = event.currentTarget as HTMLElement\n  const { shouldExpandOnScrollRef, contentWrapper } = alignedPositionContext ?? {}\n  if (shouldExpandOnScrollRef?.value && contentWrapper?.value) {\n    const scrolledBy = Math.abs(prevScrollTopRef.value - viewport.scrollTop)\n    if (scrolledBy > 0) {\n      const availableHeight = window.innerHeight - CONTENT_MARGIN * 2\n      const cssMinHeight = Number.parseFloat(\n        contentWrapper.value.style.minHeight,\n      )\n      const cssHeight = Number.parseFloat(contentWrapper.value.style.height)\n      const prevHeight = Math.max(cssMinHeight, cssHeight)\n\n      if (prevHeight < availableHeight) {\n        const nextHeight = prevHeight + scrolledBy\n        const clampedNextHeight = Math.min(availableHeight, nextHeight)\n        const heightDiff = nextHeight - clampedNextHeight\n\n        contentWrapper.value.style.height = `${clampedNextHeight}px`\n        if (contentWrapper.value.style.bottom === '0px') {\n          viewport.scrollTop = heightDiff > 0 ? heightDiff : 0\n          // ensure the content stays pinned to the bottom\n          contentWrapper.value.style.justifyContent = 'flex-end'\n        }\n      }\n    }\n  }\n  prevScrollTopRef.value = viewport.scrollTop\n}\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    data-reka-select-viewport\n    role=\"presentation\"\n    v-bind=\"{ ...$attrs, ...props }\"\n    :style=\"{\n      // we use position: 'relative' here on the `viewport` so that when we call\n      // `selectedItem.offsetTop` in calculations, the offset is relative to the viewport\n      // (independent of the scrollUpButton).\n      position: 'relative',\n      flex: 1,\n      overflow: 'hidden auto',\n    }\"\n    @scroll=\"handleScroll\"\n  >\n    <slot />\n  </Primitive>\n  <Primitive\n    as=\"style\"\n    :nonce=\"nonce\"\n  >\n    /* Hide scrollbars cross-browser and enable momentum scroll for touch\n    devices */ [data-reka-select-viewport] { scrollbar-width:none; -ms-overflow-style: none;\n    -webkit-overflow-scrolling: touch; }\n    [data-reka-select-viewport]::-webkit-scrollbar { display: none; }\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DataOrientation } from '../types'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface BaseSeparatorProps extends PrimitiveProps {\n  /**\n   * Orientation of the component.\n   *\n   * Either `vertical` or `horizontal`. Defaults to `horizontal`.\n   */\n  orientation?: DataOrientation\n  /**\n   * Whether or not the component is purely decorative. <br>When `true`, accessibility-related attributes\n   * are updated so that that the rendered element is removed from the accessibility tree.\n   */\n  decorative?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<BaseSeparatorProps>(), {\n  orientation: 'horizontal',\n})\n\nconst ORIENTATIONS = ['horizontal', 'vertical'] as const\nfunction isValidOrientation(orientation: any): orientation is DataOrientation {\n  return ORIENTATIONS.includes(orientation)\n}\n\nconst computedOrientation = computed(() =>\n  isValidOrientation(props.orientation) ? props.orientation : 'horizontal',\n)\n// `aria-orientation` defaults to `horizontal` so we only need it if `orientation` is vertical\nconst ariaOrientation = computed(() =>\n  computedOrientation.value === 'vertical' ? props.orientation : undefined,\n)\n\nconst semanticProps = computed(() =>\n  props.decorative\n    ? { role: 'none' }\n    : { 'aria-orientation': ariaOrientation.value, 'role': 'separator' },\n)\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :data-orientation=\"computedOrientation\"\n    v-bind=\"semanticProps\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DataOrientation } from '../types'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface BaseSeparatorProps extends PrimitiveProps {\n  /**\n   * Orientation of the component.\n   *\n   * Either `vertical` or `horizontal`. Defaults to `horizontal`.\n   */\n  orientation?: DataOrientation\n  /**\n   * Whether or not the component is purely decorative. <br>When `true`, accessibility-related attributes\n   * are updated so that that the rendered element is removed from the accessibility tree.\n   */\n  decorative?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<BaseSeparatorProps>(), {\n  orientation: 'horizontal',\n})\n\nconst ORIENTATIONS = ['horizontal', 'vertical'] as const\nfunction isValidOrientation(orientation: any): orientation is DataOrientation {\n  return ORIENTATIONS.includes(orientation)\n}\n\nconst computedOrientation = computed(() =>\n  isValidOrientation(props.orientation) ? props.orientation : 'horizontal',\n)\n// `aria-orientation` defaults to `horizontal` so we only need it if `orientation` is vertical\nconst ariaOrientation = computed(() =>\n  computedOrientation.value === 'vertical' ? props.orientation : undefined,\n)\n\nconst semanticProps = computed(() =>\n  props.decorative\n    ? { role: 'none' }\n    : { 'aria-orientation': ariaOrientation.value, 'role': 'separator' },\n)\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :data-orientation=\"computedOrientation\"\n    v-bind=\"semanticProps\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { BaseSeparatorProps } from '@/shared/component/BaseSeparator.vue'\n\nexport interface SeparatorProps extends BaseSeparatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport BaseSeparator from '@/shared/component/BaseSeparator.vue'\n\nconst props = withDefaults(defineProps<SeparatorProps>(), {\n  orientation: 'horizontal',\n})\n</script>\n\n<template>\n  <BaseSeparator v-bind=\"props\">\n    <slot />\n  </BaseSeparator>\n</template>\n","<script lang=\"ts\">\nimport type { BaseSeparatorProps } from '@/shared/component/BaseSeparator.vue'\n\nexport interface SeparatorProps extends BaseSeparatorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport BaseSeparator from '@/shared/component/BaseSeparator.vue'\n\nconst props = withDefaults(defineProps<SeparatorProps>(), {\n  orientation: 'horizontal',\n})\n</script>\n\n<template>\n  <BaseSeparator v-bind=\"props\">\n    <slot />\n  </BaseSeparator>\n</template>\n","export function assert(\n  expectedCondition: any,\n  message = 'Assertion failed!',\n): asserts expectedCondition {\n  if (!expectedCondition) {\n    console.error(message)\n\n    throw new Error(message)\n  }\n}\n","import type { PanelData } from '../SplitterPanel.vue'\nimport { isBrowser } from '@/shared'\n\nexport function getPanelElement(\n  id: string,\n  scope: ParentNode | HTMLElement = document,\n): HTMLElement | null {\n  if (!isBrowser)\n    return null\n  const element = scope.querySelector(`[data-panel-id=\"${id}\"]`)\n  if (element)\n    return element as HTMLElement\n\n  return null\n}\n\nexport function getPanelElementsForGroup(\n  groupId: string,\n  scope: ParentNode | HTMLElement = document,\n): HTMLElement[] {\n  if (!isBrowser)\n    return []\n  return Array.from(\n    scope.querySelectorAll(`[data-panel][data-panel-group-id=\"${groupId}\"]`),\n  )\n}\n\nexport function getPanelGroupElement(\n  id: string,\n  rootElement: ParentNode | HTMLElement = document,\n): HTMLElement | null {\n  if (!isBrowser)\n    return null\n  // If the root element is the PanelGroup\n  if (\n    rootElement instanceof HTMLElement\n    && (rootElement as HTMLElement)?.dataset?.panelGroupId === id\n  ) {\n    return rootElement as HTMLElement\n  }\n\n  // Else query children\n  const element = rootElement.querySelector(\n    `[data-panel-group][data-panel-group-id=\"${id}\"]`,\n  )\n  if (element)\n    return element as HTMLElement\n\n  return null\n}\n\nexport function getResizeHandleElement(\n  id: string,\n  scope: ParentNode | HTMLElement = document,\n): HTMLElement | null {\n  if (!isBrowser)\n    return null\n  const element = scope.querySelector(`[data-panel-resize-handle-id=\"${id}\"]`)\n  if (element)\n    return element as HTMLElement\n\n  return null\n}\n\nexport function getResizeHandleElementIndex(\n  groupId: string,\n  id: string,\n  scope: ParentNode | HTMLElement = document,\n): number | null {\n  if (!isBrowser)\n    return null\n  const handles = getResizeHandleElementsForGroup(groupId, scope)\n  const index = handles.findIndex(\n    handle => handle.getAttribute('data-panel-resize-handle-id') === id,\n  )\n  return index ?? null\n}\n\nexport function getResizeHandleElementsForGroup(\n  groupId: string,\n  scope: ParentNode | HTMLElement = document,\n): HTMLElement[] {\n  if (!isBrowser)\n    return []\n  return Array.from(\n    scope.querySelectorAll(\n      `[data-panel-resize-handle-id][data-panel-group-id=\"${groupId}\"]`,\n    ),\n  )\n}\n\nexport function getResizeHandlePanelIds(\n  groupId: string,\n  handleId: string,\n  panelsArray: PanelData[],\n  scope: ParentNode | HTMLElement = document,\n): [idBefore: string | null, idAfter: string | null] {\n  const handle = getResizeHandleElement(handleId, scope)\n  const handles = getResizeHandleElementsForGroup(groupId, scope)\n  const index = handle ? handles.indexOf(handle) : -1\n\n  const idBefore: string | null = panelsArray[index]?.id ?? null\n  const idAfter: string | null = panelsArray[index + 1]?.id ?? null\n\n  return [idBefore, idAfter]\n}\n","import type { Direction, ResizeEvent } from './types'\n\nexport function isKeyDown(event: ResizeEvent): event is KeyboardEvent {\n  return event.type === 'keydown'\n}\n\nexport function isMouseEvent(event: ResizeEvent): event is MouseEvent {\n  return event.type.startsWith('mouse')\n}\n\nexport function isTouchEvent(event: ResizeEvent): event is TouchEvent {\n  return event.type.startsWith('touch')\n}\n\nexport function getResizeEventCoordinates(event: ResizeEvent) {\n  if (isMouseEvent(event)) {\n    return {\n      x: event.clientX,\n      y: event.clientY,\n    }\n  }\n  else if (isTouchEvent(event)) {\n    const touch = event.touches[0]\n    if (touch && touch.clientX && touch.clientY) {\n      return {\n        x: touch.clientX,\n        y: touch.clientY,\n      }\n    }\n  }\n\n  return {\n    x: Number.POSITIVE_INFINITY,\n    y: Number.POSITIVE_INFINITY,\n  }\n}\n\nexport function getResizeEventCursorPosition(\n  direction: Direction,\n  event: ResizeEvent,\n): number {\n  const isHorizontal = direction === 'horizontal'\n\n  const { x, y } = getResizeEventCoordinates(event)\n\n  return isHorizontal ? x : y\n}\n","import type { PanelData } from '../SplitterPanel.vue'\nimport type { Direction, DragState, ResizeEvent } from './types'\nimport { assert } from './assert'\nimport { getPanelGroupElement, getResizeHandleElement } from './dom'\nimport { getResizeEventCursorPosition, isKeyDown } from './events'\n\nexport function calculateDragOffsetPercentage(\n  event: ResizeEvent,\n  dragHandleId: string,\n  direction: Direction,\n  initialDragState: DragState,\n  panelGroupElement: HTMLElement,\n): number {\n  const isHorizontal = direction === 'horizontal'\n\n  const handleElement = getResizeHandleElement(dragHandleId, panelGroupElement)\n  assert(handleElement)\n\n  const groupId = handleElement.getAttribute('data-panel-group-id')\n  assert(groupId)\n\n  const { initialCursorPosition } = initialDragState\n\n  const cursorPosition = getResizeEventCursorPosition(direction, event)\n\n  const groupElement = getPanelGroupElement(groupId, panelGroupElement)\n  assert(groupElement)\n\n  const groupRect = groupElement.getBoundingClientRect()\n  const groupSizeInPixels = isHorizontal ? groupRect.width : groupRect.height\n\n  const offsetPixels = cursorPosition - initialCursorPosition\n  const offsetPercentage = (offsetPixels / groupSizeInPixels) * 100\n\n  return offsetPercentage\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX\nexport function calculateDeltaPercentage(\n  event: ResizeEvent,\n  dragHandleId: string,\n  direction: Direction,\n  initialDragState: DragState | null,\n  keyboardResizeBy: number | null,\n  panelGroupElement: HTMLElement,\n): number {\n  if (isKeyDown(event)) {\n    const isHorizontal = direction === 'horizontal'\n\n    let delta = 0\n    if (event.shiftKey)\n      delta = 100\n    else\n      delta = keyboardResizeBy ?? 10\n\n    let movement = 0\n    switch (event.key) {\n      case 'ArrowDown':\n        movement = isHorizontal ? 0 : delta\n        break\n      case 'ArrowLeft':\n        movement = isHorizontal ? -delta : 0\n        break\n      case 'ArrowRight':\n        movement = isHorizontal ? delta : 0\n        break\n      case 'ArrowUp':\n        movement = isHorizontal ? 0 : -delta\n        break\n      case 'End':\n        movement = 100\n        break\n      case 'Home':\n        movement = -100\n        break\n    }\n\n    return movement\n  }\n  else {\n    if (initialDragState == null)\n      return 0\n\n    return calculateDragOffsetPercentage(\n      event,\n      dragHandleId,\n      direction,\n      initialDragState,\n      panelGroupElement,\n    )\n  }\n}\n\nexport function calculateAriaValues({\n  layout,\n  panelsArray,\n  pivotIndices,\n}: {\n  layout: number[]\n  panelsArray: PanelData[]\n  pivotIndices: number[]\n}) {\n  let currentMinSize = 0\n  let currentMaxSize = 100\n  let totalMinSize = 0\n  let totalMaxSize = 0\n\n  const firstIndex = pivotIndices[0]\n  assert(firstIndex != null)\n\n  // A panel's effective min/max sizes also need to account for other panel's sizes.\n  panelsArray.forEach((panelData, index) => {\n    const { constraints } = panelData\n    const { maxSize = 100, minSize = 0 } = constraints\n\n    if (index === firstIndex) {\n      currentMinSize = minSize\n      currentMaxSize = maxSize\n    }\n    else {\n      totalMinSize += minSize\n      totalMaxSize += maxSize\n    }\n  })\n\n  const valueMax = Math.min(currentMaxSize, 100 - totalMinSize)\n  const valueMin = Math.max(currentMinSize, 100 - totalMaxSize)\n\n  const valueNow = layout[firstIndex]\n\n  return {\n    valueMax,\n    valueMin,\n    valueNow,\n  }\n}\n\nexport function calculateUnsafeDefaultLayout({\n  panelDataArray,\n}: {\n  panelDataArray: PanelData[]\n}): number[] {\n  const layout: number[] = Array.from({ length: panelDataArray.length })\n\n  const panelConstraintsArray = panelDataArray.map(\n    panelData => panelData.constraints,\n  )\n\n  let numPanelsWithSizes = 0\n  let remainingSize = 100\n\n  // Distribute default sizes first\n  for (let index = 0; index < panelDataArray.length; index++) {\n    const panelConstraints = panelConstraintsArray[index]\n    assert(panelConstraints)\n    const { defaultSize } = panelConstraints\n\n    if (defaultSize != null) {\n      numPanelsWithSizes++\n      layout[index] = defaultSize\n      remainingSize -= defaultSize\n    }\n  }\n\n  // Remaining size should be distributed evenly between panels without default sizes\n  for (let index = 0; index < panelDataArray.length; index++) {\n    const panelConstraints = panelConstraintsArray[index]\n    assert(panelConstraints)\n    const { defaultSize } = panelConstraints\n\n    if (defaultSize != null)\n      continue\n\n    const numRemainingPanels = panelDataArray.length - numPanelsWithSizes\n    const size = remainingSize / numRemainingPanels\n\n    numPanelsWithSizes++\n    layout[index] = size\n    remainingSize -= size\n  }\n\n  return layout\n}\n","import { PRECISION } from './constants'\n\nexport function fuzzyCompareNumbers(\n  actual: number,\n  expected: number,\n  fractionDigits: number = PRECISION,\n): number {\n  actual = Number.parseFloat(actual.toFixed(fractionDigits))\n  expected = Number.parseFloat(expected.toFixed(fractionDigits))\n\n  const delta = actual - expected\n  if (delta === 0)\n    return 0\n  else\n    return delta > 0 ? 1 : -1\n}\n\nexport function fuzzyNumbersEqual(\n  actual: number,\n  expected: number,\n  fractionDigits?: number,\n): boolean {\n  return fuzzyCompareNumbers(actual, expected, fractionDigits) === 0\n}\n","import type { PanelData } from '../SplitterPanel.vue'\nimport { assert } from './assert'\nimport { fuzzyNumbersEqual } from './compare'\n\n// Layout should be pre-converted into percentages\nexport function callPanelCallbacks(\n  panelsArray: PanelData[],\n  layout: number[],\n  panelIdToLastNotifiedSizeMap: Record<string, number>,\n  groupSizeInPixels?: number | null,\n) {\n  layout.forEach((size, index) => {\n    const panelData = panelsArray[index]\n    assert(panelData)\n\n    const { callbacks, constraints, id: panelId } = panelData\n    const { collapsedSize = 0, collapsible, sizeUnit } = constraints\n\n    // Convert size to native units for px panels\n    let displaySize = size\n    if (sizeUnit === 'px' && groupSizeInPixels != null) {\n      displaySize = (size / 100) * groupSizeInPixels\n    }\n\n    const lastNotifiedSize = panelIdToLastNotifiedSizeMap[panelId]\n    if (lastNotifiedSize == null || !fuzzyNumbersEqual(displaySize, lastNotifiedSize)) {\n      panelIdToLastNotifiedSizeMap[panelId] = displaySize\n\n      const { onCollapse, onExpand, onResize } = callbacks\n\n      if (onResize)\n        onResize(displaySize, lastNotifiedSize)\n\n      if (collapsible && (onCollapse || onExpand)) {\n        if (\n          onExpand\n          && (lastNotifiedSize == null || fuzzyNumbersEqual(lastNotifiedSize, collapsedSize))\n          && !fuzzyNumbersEqual(displaySize, collapsedSize)\n        ) {\n          onExpand()\n        }\n\n        if (\n          onCollapse\n          && (lastNotifiedSize == null || !fuzzyNumbersEqual(lastNotifiedSize, collapsedSize))\n          && fuzzyNumbersEqual(displaySize, collapsedSize)\n        ) {\n          onCollapse()\n        }\n      }\n    }\n  })\n}\n","export default function debounce<T extends Function>(\n  callback: T,\n  durationMs = 10,\n) {\n  let timeoutId: NodeJS.Timeout | null = null\n\n  const callable = (...args: any) => {\n    if (timeoutId !== null)\n      clearTimeout(timeoutId)\n\n    timeoutId = setTimeout(() => {\n      callback(...args)\n    }, durationMs)\n  }\n\n  return callable as unknown as T\n}\n","import type { PanelConstraints } from '../SplitterPanel.vue'\nimport { assert } from './assert'\nimport { fuzzyCompareNumbers } from './compare'\nimport { PRECISION } from './constants'\n\n// Panel size must be in percentages; pixel values should be pre-converted\nexport function resizePanel({\n  panelConstraints: panelConstraintsArray,\n  panelIndex,\n  size,\n}: {\n  panelConstraints: PanelConstraints[]\n  panelIndex: number\n  size: number\n}) {\n  const panelConstraints = panelConstraintsArray[panelIndex]\n  assert(panelConstraints != null)\n\n  const { collapsedSize = 0, collapsible, maxSize = 100, minSize = 0 } = panelConstraints\n\n  if (fuzzyCompareNumbers(size, minSize) < 0) {\n    if (collapsible) {\n      // Collapsible panels should snap closed or open only once they cross the halfway point between collapsed and min size.\n      const halfwayPoint = (collapsedSize + minSize) / 2\n      if (fuzzyCompareNumbers(size, halfwayPoint) < 0)\n        size = collapsedSize\n      else\n        size = minSize\n    }\n    else {\n      size = minSize\n    }\n  }\n\n  size = Math.min(maxSize, size)\n  size = Number.parseFloat(size.toFixed(PRECISION))\n\n  return size\n}\n","/* eslint-disable no-lone-blocks */\nimport type { PanelConstraints } from '../SplitterPanel.vue'\nimport { assert } from './assert'\nimport { fuzzyCompareNumbers, fuzzyNumbersEqual } from './compare'\nimport { resizePanel } from './resizePanel'\n\nexport function compareLayouts(a: number[], b: number[]) {\n  if (a.length !== b.length) {\n    return false\n  }\n  else {\n    for (let index = 0; index < a.length; index++) {\n      if (a[index] !== b[index])\n        return false\n    }\n  }\n  return true\n}\n\n// All units must be in percentages; pixel values should be pre-converted\nexport function adjustLayoutByDelta({\n  delta,\n  layout: prevLayout,\n  panelConstraints: panelConstraintsArray,\n  pivotIndices,\n  trigger,\n}: {\n  delta: number\n  layout: number[]\n  panelConstraints: PanelConstraints[]\n  pivotIndices: number[]\n  trigger: 'imperative-api' | 'keyboard' | 'mouse-or-touch'\n}): number[] {\n  if (fuzzyNumbersEqual(delta, 0))\n    return prevLayout\n\n  const nextLayout = [...prevLayout]\n\n  const [firstPivotIndex, secondPivotIndex] = pivotIndices\n  assert(firstPivotIndex != null)\n  assert(secondPivotIndex != null)\n\n  let deltaApplied = 0\n\n  // const DEBUG = [];\n  // DEBUG.push(`adjustLayoutByDelta() ${prevLayout.join(\", \")}`);\n  // DEBUG.push(`  delta: ${delta}`);\n  // DEBUG.push(`  pivotIndices: ${pivotIndices.join(\", \")}`);\n  // DEBUG.push(`  trigger: ${trigger}`);\n  // DEBUG.push(\"\");\n\n  // A resizing panel affects the panels before or after it.\n  //\n  // A negative delta means the panel(s) immediately after the resize handle should grow/expand by decreasing its offset.\n  // Other panels may also need to shrink/contract (and shift) to make room, depending on the min weights.\n  //\n  // A positive delta means the panel(s) immediately before the resize handle should \"expand\".\n  // This is accomplished by shrinking/contracting (and shifting) one or more of the panels after the resize handle.\n\n  {\n    // If this is a resize triggered by a keyboard event, our logic for expanding/collapsing is different.\n    // We no longer check the halfway threshold because this may prevent the panel from expanding at all.\n    if (trigger === 'keyboard') {\n      {\n        // Check if we should expand a collapsed panel\n        const index = delta < 0 ? secondPivotIndex : firstPivotIndex\n        const panelConstraints = panelConstraintsArray[index]\n        assert(panelConstraints)\n\n        // DEBUG.push(`edge case check 1: ${index}`);\n        // DEBUG.push(`  -> collapsible? ${constraints.collapsible}`);\n        if (panelConstraints.collapsible) {\n          const prevSize = prevLayout[index]\n          assert(prevSize != null)\n\n          const panelConstraints = panelConstraintsArray[index]\n          assert(panelConstraints)\n          const { collapsedSize = 0, minSize = 0 } = panelConstraints\n\n          if (fuzzyNumbersEqual(prevSize, collapsedSize)) {\n            const localDelta = minSize - prevSize\n            // DEBUG.push(`  -> expand delta: ${localDelta}`);\n\n            if (fuzzyCompareNumbers(localDelta, Math.abs(delta)) > 0)\n              delta = delta < 0 ? 0 - localDelta : localDelta\n              // DEBUG.push(`  -> delta: ${delta}`);\n          }\n        }\n      }\n\n      {\n        // Check if we should collapse a panel at its minimum size\n        const index = delta < 0 ? firstPivotIndex : secondPivotIndex\n        const panelConstraints = panelConstraintsArray[index]\n        assert(panelConstraints)\n        const { collapsible } = panelConstraints\n\n        // DEBUG.push(`edge case check 2: ${index}`);\n        // DEBUG.push(`  -> collapsible? ${collapsible}`);\n        if (collapsible) {\n          const prevSize = prevLayout[index]\n          assert(prevSize != null)\n\n          const panelConstraints = panelConstraintsArray[index]\n          assert(panelConstraints)\n          const { collapsedSize = 0, minSize = 0 } = panelConstraints\n\n          if (fuzzyNumbersEqual(prevSize, minSize)) {\n            const localDelta = prevSize - collapsedSize\n            // DEBUG.push(`  -> expand delta: ${localDelta}`);\n\n            if (fuzzyCompareNumbers(localDelta, Math.abs(delta)) > 0)\n              delta = delta < 0 ? 0 - localDelta : localDelta\n              // DEBUG.push(`  -> delta: ${delta}`);\n          }\n        }\n      }\n    }\n    // DEBUG.push(\"\");\n  }\n\n  {\n    // Pre-calculate max available delta in the opposite direction of our pivot.\n    // This will be the maximum amount we're allowed to expand/contract the panels in the primary direction.\n    // If this amount is less than the requested delta, adjust the requested delta.\n    // If this amount is greater than the requested delta, that's useful information too–\n    // as an expanding panel might change from collapsed to min size.\n\n    const increment = delta < 0 ? 1 : -1\n\n    let index = delta < 0 ? secondPivotIndex : firstPivotIndex\n    let maxAvailableDelta = 0\n\n    // DEBUG.push(\"pre calc...\");\n    while (true) {\n      const prevSize = prevLayout[index]\n      assert(prevSize != null)\n\n      const maxSafeSize = resizePanel({\n        panelConstraints: panelConstraintsArray,\n        panelIndex: index,\n        size: 100,\n      })\n      const delta = maxSafeSize - prevSize\n      // DEBUG.push(`  ${index}: ${prevSize} -> ${maxSafeSize}`);\n\n      maxAvailableDelta += delta\n      index += increment\n\n      if (index < 0 || index >= panelConstraintsArray.length)\n        break\n    }\n\n    // DEBUG.push(`  -> max available delta: ${maxAvailableDelta}`);\n    const minAbsDelta = Math.min(Math.abs(delta), Math.abs(maxAvailableDelta))\n    delta = delta < 0 ? 0 - minAbsDelta : minAbsDelta\n    // DEBUG.push(`  -> adjusted delta: ${delta}`);\n    // DEBUG.push(\"\");\n  }\n\n  {\n    // Delta added to a panel needs to be subtracted from other panels (within the constraints that those panels allow).\n\n    const pivotIndex = delta < 0 ? firstPivotIndex : secondPivotIndex\n    let index = pivotIndex\n    while (index >= 0 && index < panelConstraintsArray.length) {\n      const deltaRemaining = Math.abs(delta) - Math.abs(deltaApplied)\n\n      const prevSize = prevLayout[index]\n      assert(prevSize != null)\n\n      const unsafeSize = prevSize - deltaRemaining\n      const safeSize = resizePanel({\n        panelConstraints: panelConstraintsArray,\n        panelIndex: index,\n        size: unsafeSize,\n      })\n\n      if (!fuzzyNumbersEqual(prevSize, safeSize)) {\n        deltaApplied += prevSize - safeSize\n\n        nextLayout[index] = safeSize\n\n        if (\n          deltaApplied\n            .toPrecision(3)\n            .localeCompare(Math.abs(delta).toPrecision(3), undefined, {\n              numeric: true,\n            }) >= 0\n        ) {\n          break\n        }\n      }\n\n      if (delta < 0)\n        index--\n      else\n        index++\n    }\n  }\n  // DEBUG.push(`after 1: ${nextLayout.join(\", \")}`);\n  // DEBUG.push(`  deltaApplied: ${deltaApplied}`);\n  // DEBUG.push(\"\");\n\n  // If we were unable to resize any of the panels panels, return the previous state.\n  // This will essentially bailout and ignore e.g. drags past a panel's boundaries\n  if (fuzzyNumbersEqual(deltaApplied, 0)) {\n    // console.log(DEBUG.join(\"\\n\"));\n    return prevLayout\n  }\n\n  {\n    // Now distribute the applied delta to the panels in the other direction\n    const pivotIndex = delta < 0 ? secondPivotIndex : firstPivotIndex\n\n    const prevSize = prevLayout[pivotIndex]\n    assert(prevSize != null)\n\n    const unsafeSize = prevSize + deltaApplied\n    const safeSize = resizePanel({\n      panelConstraints: panelConstraintsArray,\n      panelIndex: pivotIndex,\n      size: unsafeSize,\n    })\n\n    // Adjust the pivot panel before, but only by the amount that surrounding panels were able to shrink/contract.\n    nextLayout[pivotIndex] = safeSize\n\n    // Edge case where expanding or contracting one panel caused another one to change collapsed state\n    if (!fuzzyNumbersEqual(safeSize, unsafeSize)) {\n      let deltaRemaining = unsafeSize - safeSize\n\n      const pivotIndex = delta < 0 ? secondPivotIndex : firstPivotIndex\n      let index = pivotIndex\n      while (index >= 0 && index < panelConstraintsArray.length) {\n        const prevSize = nextLayout[index]\n        assert(prevSize != null)\n\n        const unsafeSize = prevSize + deltaRemaining\n        const safeSize = resizePanel({\n          panelConstraints: panelConstraintsArray,\n          panelIndex: index,\n          size: unsafeSize,\n        })\n\n        if (!fuzzyNumbersEqual(prevSize, safeSize)) {\n          deltaRemaining -= safeSize - prevSize\n\n          nextLayout[index] = safeSize\n        }\n\n        if (fuzzyNumbersEqual(deltaRemaining, 0))\n          break\n\n        if (delta > 0)\n          index--\n        else\n          index++\n      }\n    }\n  }\n  // DEBUG.push(`after 2: ${nextLayout.join(\", \")}`);\n  // DEBUG.push(`  deltaApplied: ${deltaApplied}`);\n  // DEBUG.push(\"\");\n\n  const totalSize = nextLayout.reduce((total, size) => size + total, 0)\n  // DEBUG.push(`total size: ${totalSize}`);\n  // console.log(DEBUG.join(\"\\n\"));\n\n  if (!fuzzyNumbersEqual(totalSize, 100))\n    return prevLayout\n\n  return nextLayout\n}\n","import { getResizeHandleElementIndex } from './dom'\n\nexport function determinePivotIndices(\n  groupId: string,\n  dragHandleId: string,\n  panelGroupElement: ParentNode,\n): [indexBefore: number, indexAfter: number] {\n  const index = getResizeHandleElementIndex(\n    groupId,\n    dragHandleId,\n    panelGroupElement,\n  )\n\n  return index != null ? [index, index + 1] : [-1, -1]\n}\n","export interface Rectangle {\n  x: number\n  y: number\n  width: number\n  height: number\n}\n\nexport function intersects(\n  rectOne: Rectangle,\n  rectTwo: Rectangle,\n  strict: boolean,\n): boolean {\n  if (strict) {\n    return (\n      rectOne.x < rectTwo.x + rectTwo.width\n      && rectOne.x + rectOne.width > rectTwo.x\n      && rectOne.y < rectTwo.y + rectTwo.height\n      && rectOne.y + rectOne.height > rectTwo.y\n    )\n  }\n  else {\n    return (\n      rectOne.x <= rectTwo.x + rectTwo.width\n      && rectOne.x + rectOne.width >= rectTwo.x\n      && rectOne.y <= rectTwo.y + rectTwo.height\n      && rectOne.y + rectOne.height >= rectTwo.y\n    )\n  }\n}\n\nexport function getIntersectingRectangle(\n  rectOne: Rectangle,\n  rectTwo: Rectangle,\n  strict: boolean,\n): Rectangle {\n  if (!intersects(rectOne, rectTwo, strict)) {\n    return {\n      x: 0,\n      y: 0,\n      width: 0,\n      height: 0,\n    }\n  }\n\n  return {\n    x: Math.max(rectOne.x, rectTwo.x),\n    y: Math.max(rectOne.y, rectTwo.y),\n    width:\n      Math.min(rectOne.x + rectOne.width, rectTwo.x + rectTwo.width)\n      - Math.max(rectOne.x, rectTwo.x),\n    height:\n      Math.min(rectOne.y + rectOne.height, rectTwo.y + rectTwo.height)\n      - Math.max(rectOne.y, rectTwo.y),\n  }\n}\n","// Forked from NPM stacking-order@2.0.0\n// Background at https://github.com/Rich-Harris/stacking-order/issues/3\n\nimport { assert } from './assert'\n\n/**\n * Determine which of two nodes appears in front of the other —\n * if `a` is in front, returns 1, otherwise returns -1\n * @param {HTMLElement} a\n * @param {HTMLElement} b\n */\nexport function compare(a: HTMLElement, b: HTMLElement): number {\n  if (a === b)\n    throw new Error('Cannot compare node with itself')\n\n  const ancestors = {\n    a: getAncestors(a),\n    b: getAncestors(b),\n  }\n\n  let common_ancestor\n\n  // remove shared ancestors\n  while (ancestors.a.at(-1) === ancestors.b.at(-1)) {\n    a = ancestors.a.pop() as HTMLElement\n    b = ancestors.b.pop() as HTMLElement\n\n    common_ancestor = a\n  }\n\n  assert(common_ancestor)\n\n  const z_indexes = {\n    a: getZIndex(findStackingContext(ancestors.a)),\n    b: getZIndex(findStackingContext(ancestors.b)),\n  }\n\n  if (z_indexes.a === z_indexes.b) {\n    const children = common_ancestor.childNodes\n\n    const furthest_ancestors = {\n      a: ancestors.a.at(-1),\n      b: ancestors.b.at(-1),\n    }\n\n    let i = children.length\n    while (i--) {\n      const child = children[i]\n      if (child === furthest_ancestors.a)\n        return 1\n      if (child === furthest_ancestors.b)\n        return -1\n    }\n  }\n\n  return Math.sign(z_indexes.a - z_indexes.b)\n}\n\nconst props\n  = /\\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\\b/\n\n/** @param {HTMLElement} node */\nfunction isFlexItem(node: HTMLElement) {\n  const display = getComputedStyle(getParent(node)).display\n  return display === 'flex' || display === 'inline-flex'\n}\n\n/** @param {HTMLElement} node */\nfunction createsStackingContext(node: HTMLElement) {\n  const style = getComputedStyle(node)\n\n  // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context\n  if (style.position === 'fixed')\n    return true\n  // Forked to fix upstream bug https://github.com/Rich-Harris/stacking-order/issues/3\n  // if (\n  //   (style.zIndex !== \"auto\" && style.position !== \"static\") ||\n  //   isFlexItem(node)\n  // )\n  if (\n    style.zIndex !== 'auto'\n    && (style.position !== 'static' || isFlexItem(node))\n  ) {\n    return true\n  }\n  if (+style.opacity < 1)\n    return true\n  if ('transform' in style && style.transform !== 'none')\n    return true\n  if ('webkitTransform' in style && style.webkitTransform !== 'none')\n    return true\n  if ('mixBlendMode' in style && style.mixBlendMode !== 'normal')\n    return true\n  if ('filter' in style && style.filter !== 'none')\n    return true\n  if ('webkitFilter' in style && style.webkitFilter !== 'none')\n    return true\n  if ('isolation' in style && style.isolation === 'isolate')\n    return true\n  if (props.test(style.willChange))\n    return true\n  // @ts-expect-error non-standard styling https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-overflow-scrolling\n  if (style.webkitOverflowScrolling === 'touch')\n    return true\n\n  return false\n}\n\n/** @param {HTMLElement[]} nodes */\nfunction findStackingContext(nodes: HTMLElement[]) {\n  let i = nodes.length\n\n  while (i--) {\n    const node = nodes[i]\n    assert(node)\n    if (createsStackingContext(node))\n      return node\n  }\n\n  return null\n}\n\n/** @param {HTMLElement} node */\nfunction getZIndex(node: HTMLElement | null) {\n  return (node && Number(getComputedStyle(node).zIndex)) || 0\n}\n\n/** @param {HTMLElement} node */\nfunction getAncestors(node: HTMLElement) {\n  const ancestors = []\n\n  while (node) {\n    ancestors.push(node)\n    node = getParent(node)\n  }\n\n  return ancestors // [ node, ... <body>, <html>, document ]\n}\n\n/** @param {HTMLElement} node */\nfunction getParent(node: HTMLElement) {\n  // @ts-expect-error host should exist\n  return (node.parentNode instanceof DocumentFragment && node.parentNode?.host) || node.parentNode\n}\n","import type { Ref } from 'vue'\nimport type { Direction, ResizeEvent } from './types'\nimport { getResizeEventCoordinates } from './events'\nimport { intersects } from './rects'\nimport { compare } from './stackingOrder'\nimport { resetGlobalCursorStyle, setGlobalCursorStyle } from './style'\n\nexport type ResizeHandlerAction = 'down' | 'move' | 'up'\nexport type SetResizeHandlerState = (\n  action: ResizeHandlerAction,\n  isActive: boolean,\n  event: ResizeEvent,\n) => void\n\nexport type PointerHitAreaMargins = {\n  coarse: number\n  fine: number\n}\n\nexport type ResizeHandlerData = {\n  direction: Ref<Direction>\n  element: HTMLElement\n  hitAreaMargins: PointerHitAreaMargins\n  nonce: Ref<string | undefined>\n  setResizeHandlerState: SetResizeHandlerState\n}\n\nexport const EXCEEDED_HORIZONTAL_MIN = 0b0001\nexport const EXCEEDED_HORIZONTAL_MAX = 0b0010\nexport const EXCEEDED_VERTICAL_MIN = 0b0100\nexport const EXCEEDED_VERTICAL_MAX = 0b1000\n\nfunction getInputType(): 'coarse' | 'fine' | undefined {\n  if (typeof matchMedia === 'function')\n    return matchMedia('(pointer:coarse)').matches ? 'coarse' : 'fine'\n}\n\nconst isCoarsePointer = getInputType() === 'coarse'\n\nconst intersectingHandles: ResizeHandlerData[] = []\nlet isPointerDown = false\nconst ownerDocumentCounts: Map<Document, number> = new Map()\nconst panelConstraintFlags: Map<string, number> = new Map()\n\nconst registeredResizeHandlers = new Set<ResizeHandlerData>()\n\nexport function registerResizeHandle(\n  resizeHandleId: string,\n  element: HTMLElement,\n  direction: Ref<Direction>,\n  hitAreaMargins: PointerHitAreaMargins,\n  nonce: Ref<string | undefined>,\n  setResizeHandlerState: SetResizeHandlerState,\n) {\n  const { ownerDocument } = element\n\n  const data: ResizeHandlerData = {\n    direction,\n    element,\n    hitAreaMargins,\n    nonce,\n    setResizeHandlerState,\n  }\n\n  const count = ownerDocumentCounts.get(ownerDocument) ?? 0\n  ownerDocumentCounts.set(ownerDocument, count + 1)\n\n  registeredResizeHandlers.add(data)\n\n  updateListeners()\n\n  return function unregisterResizeHandle() {\n    panelConstraintFlags.delete(resizeHandleId)\n    registeredResizeHandlers.delete(data)\n\n    const count = ownerDocumentCounts.get(ownerDocument) ?? 1\n    ownerDocumentCounts.set(ownerDocument, count - 1)\n\n    updateListeners()\n    resetGlobalCursorStyle()\n\n    if (count === 1)\n      ownerDocumentCounts.delete(ownerDocument)\n  }\n}\n\nfunction handlePointerDown(event: ResizeEvent) {\n  const { target } = event\n  const { x, y } = getResizeEventCoordinates(event)\n\n  isPointerDown = true\n\n  recalculateIntersectingHandles({ target, x, y })\n  updateListeners()\n\n  if (intersectingHandles.length > 0) {\n    updateResizeHandlerStates('down', event)\n\n    event.preventDefault()\n  }\n}\n\nfunction handlePointerMove(event: ResizeEvent) {\n  const { x, y } = getResizeEventCoordinates(event)\n\n  if (!isPointerDown) {\n    const { target } = event\n\n    // Recalculate intersecting handles whenever the pointer moves, except if it has already been pressed\n    // at that point, the handles may not move with the pointer (depending on constraints)\n    // but the same set of active handles should be locked until the pointer is released\n    recalculateIntersectingHandles({ target, x, y })\n  }\n\n  updateResizeHandlerStates('move', event)\n\n  // Update cursor based on return value(s) from active handles\n  updateCursor()\n\n  if (intersectingHandles.length > 0)\n    event.preventDefault()\n}\n\nfunction handlePointerUp(event: ResizeEvent) {\n  const { target } = event\n  const { x, y } = getResizeEventCoordinates(event)\n\n  panelConstraintFlags.clear()\n  isPointerDown = false\n\n  if (intersectingHandles.length > 0)\n    event.preventDefault()\n\n  updateResizeHandlerStates('up', event)\n  recalculateIntersectingHandles({ target, x, y })\n  updateCursor()\n\n  updateListeners()\n}\n\nfunction recalculateIntersectingHandles({\n  target,\n  x,\n  y,\n}: {\n  target: EventTarget | null\n  x: number\n  y: number\n}) {\n  intersectingHandles.splice(0)\n\n  let targetElement: HTMLElement | null = null\n  if (target instanceof HTMLElement)\n    targetElement = target\n\n  registeredResizeHandlers.forEach((data) => {\n    const { element: dragHandleElement, hitAreaMargins } = data\n\n    const dragHandleRect = dragHandleElement.getBoundingClientRect()\n    const { bottom, left, right, top } = dragHandleRect\n\n    const margin = isCoarsePointer\n      ? hitAreaMargins.coarse\n      : hitAreaMargins.fine\n\n    const eventIntersects\n      = x >= left - margin\n        && x <= right + margin\n        && y >= top - margin\n        && y <= bottom + margin\n\n    if (eventIntersects) {\n      // TRICKY\n      // We listen for pointers events at the root in order to support hit area margins\n      // (determining when the pointer is close enough to an element to be considered a \"hit\")\n      // Clicking on an element \"above\" a handle (e.g. a modal) should prevent a hit though\n      // so at this point we need to compare stacking order of a potentially intersecting drag handle,\n      // and the element that was actually clicked/touched\n      if (\n        targetElement !== null\n        && dragHandleElement !== targetElement\n        && !dragHandleElement.contains(targetElement)\n        && !targetElement.contains(dragHandleElement)\n        // Calculating stacking order has a cost, so we should avoid it if possible\n        // That is why we only check potentially intersecting handles,\n        // and why we skip if the event target is within the handle's DOM\n        && compare(targetElement, dragHandleElement) > 0\n      ) {\n        // If the target is above the drag handle, then we also need to confirm they overlap\n        // If they are beside each other (e.g. a panel and its drag handle) then the handle is still interactive\n        //\n        // It's not enough to compare only the target\n        // The target might be a small element inside of a larger container\n        // (For example, a SPAN or a DIV inside of a larger modal dialog)\n        let currentElement: HTMLElement | null = targetElement\n        let didIntersect = false\n        while (currentElement) {\n          if (currentElement.contains(dragHandleElement)) {\n            break\n          }\n          else if (\n            intersects(\n              currentElement.getBoundingClientRect(),\n              dragHandleRect,\n              true,\n            )\n          ) {\n            didIntersect = true\n            break\n          }\n\n          currentElement = currentElement.parentElement\n        }\n\n        if (didIntersect)\n          return\n      }\n\n      intersectingHandles.push(data)\n    }\n  })\n}\n\nexport function reportConstraintsViolation(\n  resizeHandleId: string,\n  flag: number,\n) {\n  panelConstraintFlags.set(resizeHandleId, flag)\n}\n\nfunction updateCursor() {\n  let intersectsHorizontal = false\n  let intersectsVertical = false\n  let nonce: string | undefined\n\n  intersectingHandles.forEach((data) => {\n    const { direction, nonce: _nonce } = data\n\n    if (direction.value === 'horizontal')\n      intersectsHorizontal = true\n    else\n      intersectsVertical = true\n\n    nonce = _nonce.value\n  })\n\n  let constraintFlags = 0\n  panelConstraintFlags.forEach((flag) => {\n    constraintFlags |= flag\n  })\n\n  if (intersectsHorizontal && intersectsVertical)\n    setGlobalCursorStyle('intersection', constraintFlags, nonce)\n  else if (intersectsHorizontal)\n    setGlobalCursorStyle('horizontal', constraintFlags, nonce)\n  else if (intersectsVertical)\n    setGlobalCursorStyle('vertical', constraintFlags, nonce)\n  else\n    resetGlobalCursorStyle()\n}\n\nfunction updateListeners() {\n  ownerDocumentCounts.forEach((_, ownerDocument) => {\n    const { body } = ownerDocument\n\n    body.removeEventListener('contextmenu', handlePointerUp)\n    body.removeEventListener('mousedown', handlePointerDown)\n    body.removeEventListener('mouseleave', handlePointerMove)\n    body.removeEventListener('mousemove', handlePointerMove)\n    body.removeEventListener('touchmove', handlePointerMove)\n    body.removeEventListener('touchstart', handlePointerDown)\n  })\n\n  window.removeEventListener('mouseup', handlePointerUp)\n  window.removeEventListener('touchcancel', handlePointerUp)\n  window.removeEventListener('touchend', handlePointerUp)\n\n  if (registeredResizeHandlers.size > 0) {\n    if (isPointerDown) {\n      if (intersectingHandles.length > 0) {\n        ownerDocumentCounts.forEach((count, ownerDocument) => {\n          const { body } = ownerDocument\n\n          if (count > 0) {\n            body.addEventListener('contextmenu', handlePointerUp)\n            body.addEventListener('mouseleave', handlePointerMove)\n            body.addEventListener('mousemove', handlePointerMove)\n            body.addEventListener('touchmove', handlePointerMove, {\n              passive: false,\n            })\n          }\n        })\n      }\n\n      window.addEventListener('mouseup', handlePointerUp)\n      window.addEventListener('touchcancel', handlePointerUp)\n      window.addEventListener('touchend', handlePointerUp)\n    }\n    else {\n      ownerDocumentCounts.forEach((count, ownerDocument) => {\n        const { body } = ownerDocument\n\n        if (count > 0) {\n          body.addEventListener('mousedown', handlePointerDown)\n          body.addEventListener('mousemove', handlePointerMove)\n          body.addEventListener('touchmove', handlePointerMove, {\n            passive: false,\n          })\n          body.addEventListener('touchstart', handlePointerDown)\n        }\n      })\n    }\n  }\n}\n\nfunction updateResizeHandlerStates(\n  action: ResizeHandlerAction,\n  event: ResizeEvent,\n) {\n  registeredResizeHandlers.forEach((data) => {\n    const { setResizeHandlerState } = data\n\n    const isActive = intersectingHandles.includes(data)\n\n    setResizeHandlerState(action, isActive, event)\n  })\n}\n","import type { CSSProperties } from 'vue'\nimport type { PanelData } from '../SplitterPanel.vue'\nimport type { DragState } from './types'\nimport {\n  EXCEEDED_HORIZONTAL_MAX,\n  EXCEEDED_HORIZONTAL_MIN,\n  EXCEEDED_VERTICAL_MAX,\n  EXCEEDED_VERTICAL_MIN,\n} from './registry'\n\ntype CursorState = 'horizontal' | 'intersection' | 'vertical'\n\nlet currentCursorStyle: string | null = null\nlet styleElement: HTMLStyleElement | null = null\n\nexport function getCursorStyle(\n  state: CursorState,\n  constraintFlags: number,\n): string {\n  if (constraintFlags) {\n    const horizontalMin = (constraintFlags & EXCEEDED_HORIZONTAL_MIN) !== 0\n    const horizontalMax = (constraintFlags & EXCEEDED_HORIZONTAL_MAX) !== 0\n    const verticalMin = (constraintFlags & EXCEEDED_VERTICAL_MIN) !== 0\n    const verticalMax = (constraintFlags & EXCEEDED_VERTICAL_MAX) !== 0\n\n    if (horizontalMin) {\n      if (verticalMin)\n        return 'se-resize'\n      else if (verticalMax)\n        return 'ne-resize'\n      else\n        return 'e-resize'\n    }\n    else if (horizontalMax) {\n      if (verticalMin)\n        return 'sw-resize'\n      else if (verticalMax)\n        return 'nw-resize'\n      else\n        return 'w-resize'\n    }\n    else if (verticalMin) {\n      return 's-resize'\n    }\n    else if (verticalMax) {\n      return 'n-resize'\n    }\n  }\n\n  switch (state) {\n    case 'horizontal':\n      return 'ew-resize'\n    case 'intersection':\n      return 'move'\n    case 'vertical':\n      return 'ns-resize'\n  }\n}\n\nexport function resetGlobalCursorStyle() {\n  if (styleElement !== null) {\n    document.head.removeChild(styleElement)\n\n    currentCursorStyle = null\n    styleElement = null\n  }\n}\n\nexport function setGlobalCursorStyle(\n  state: CursorState,\n  constraintFlags: number,\n  nonce?: string,\n) {\n  const style = getCursorStyle(state, constraintFlags)\n\n  if (currentCursorStyle === style)\n    return\n\n  currentCursorStyle = style\n\n  if (styleElement === null) {\n    styleElement = document.createElement('style')\n    if (nonce)\n      styleElement.nonce = nonce\n    document.head.appendChild(styleElement)\n  }\n\n  styleElement.innerHTML = `*{cursor: ${style}!important;}`\n}\n\n// the % of the group's overall space this panel should occupy.\nexport function computePanelFlexBoxStyle({\n  defaultSize,\n  dragState,\n  layout,\n  panelData,\n  panelIndex,\n  precision = 3,\n}: {\n  defaultSize: number | undefined\n  layout: number[]\n  dragState: DragState | null\n  panelData: PanelData[]\n  panelIndex: number\n  precision?: number\n}): CSSProperties {\n  const size = layout[panelIndex]\n\n  let flexGrow\n  if (size == null) {\n    // Initial render (before panels have registered themselves)\n    // In order to support server rendering, fall back to default size if provided\n    flexGrow\n      = defaultSize !== undefined ? defaultSize.toPrecision(precision) : '1'\n  }\n  else if (panelData.length === 1) {\n    // Special case: Single panel group should always fill full width/height\n    flexGrow = '1'\n  }\n  else {\n    flexGrow = size.toPrecision(precision)\n  }\n\n  return {\n    flexBasis: 0,\n    flexGrow,\n    flexShrink: 1,\n\n    // Without this, Panel sizes may be unintentionally overridden by their content\n    overflow: 'hidden',\n\n    // Disable pointer events inside of a panel during resize\n    // This avoid edge cases like nested iframes\n    pointerEvents: dragState !== null ? 'none' : undefined,\n  }\n}\n","import type { PanelConstraints, PanelData } from '../SplitterPanel.vue'\n\nexport type SizeUnit = '%' | 'px'\n\ntype ConvertConstraintsToPercentOptions = {\n  panelDataArray: PanelData[]\n  groupSizeInPixels: number | null\n}\n\ntype ConvertValueOptions = {\n  sizeUnit: SizeUnit\n  groupSizeInPixels: number | null\n  value: number | undefined\n}\n\nfunction convertValueToPercent({ sizeUnit, groupSizeInPixels, value }: ConvertValueOptions): number | undefined {\n  if (value == null)\n    return value\n\n  if (sizeUnit === '%')\n    return value\n\n  if (groupSizeInPixels == null || groupSizeInPixels === 0)\n    return undefined\n\n  return (value / groupSizeInPixels) * 100\n}\n\nexport function convertPanelConstraintsToPercent({\n  panelDataArray,\n  groupSizeInPixels,\n}: ConvertConstraintsToPercentOptions): PanelConstraints[] | null {\n  const requiresMeasurement = panelDataArray.some(\n    panelData => (panelData.constraints.sizeUnit ?? '%') === 'px',\n  )\n\n  if (requiresMeasurement && (!groupSizeInPixels || Number.isNaN(groupSizeInPixels)))\n    return null\n\n  return panelDataArray.map((panelData) => {\n    const constraints = panelData.constraints\n    const sizeUnit = constraints.sizeUnit ?? '%'\n\n    const collapsedSize = convertValueToPercent({\n      groupSizeInPixels,\n      sizeUnit,\n      value: constraints.collapsedSize,\n    })\n\n    const defaultSize = convertValueToPercent({\n      groupSizeInPixels,\n      sizeUnit,\n      value: constraints.defaultSize,\n    })\n\n    const maxSize = convertValueToPercent({\n      groupSizeInPixels,\n      sizeUnit,\n      value: constraints.maxSize,\n    })\n\n    const minSize = convertValueToPercent({\n      groupSizeInPixels,\n      sizeUnit,\n      value: constraints.minSize,\n    })\n\n    return {\n      ...constraints,\n      collapsedSize: collapsedSize ?? constraints.collapsedSize ?? 0,\n      defaultSize,\n      maxSize: maxSize ?? 100,\n      minSize: minSize ?? 0,\n      sizeUnit: '%',\n    }\n  })\n}\n\ntype RecalculateLayoutOptions = {\n  layout: number[]\n  panelDataArray: PanelData[]\n  prevGroupSize: number | null\n  nextGroupSize: number | null\n}\n\nexport function hasPixelSizedPanel(panelDataArray: PanelData[]): boolean {\n  return panelDataArray.some(panelData => (panelData.constraints.sizeUnit ?? '%') === 'px')\n}\n\nexport function recalculateLayoutForPixelPanels({\n  layout,\n  panelDataArray,\n  prevGroupSize,\n  nextGroupSize,\n}: RecalculateLayoutOptions): number[] | null {\n  if (!hasPixelSizedPanel(panelDataArray)) {\n    return null\n  }\n\n  if (\n    prevGroupSize == null\n    || nextGroupSize == null\n    || prevGroupSize === 0\n    || nextGroupSize === 0\n    || Number.isNaN(prevGroupSize)\n    || Number.isNaN(nextGroupSize)\n  ) {\n    return null\n  }\n\n  const pixelPanelIndices = panelDataArray.reduce<number[]>((indices, panelData, index) => {\n    if ((panelData.constraints.sizeUnit ?? '%') === 'px')\n      indices.push(index)\n\n    return indices\n  }, [])\n\n  if (pixelPanelIndices.length === 0) {\n    return null\n  }\n\n  const pixelIndexSet = new Set(pixelPanelIndices)\n\n  const nextLayout = layout.map(size => size ?? 0)\n\n  const prevPercentForPixelPanels = pixelPanelIndices.reduce((sum, index) => sum + (layout[index] ?? 0), 0)\n\n  const nextPixelPercents = pixelPanelIndices.map((index) => {\n    const prevPercent = layout[index] ?? 0\n    const prevPixelSize = (prevPercent / 100) * prevGroupSize\n    return (prevPixelSize / nextGroupSize) * 100\n  })\n\n  const totalNextPixelPercent = nextPixelPercents.reduce((sum, value) => sum + value, 0)\n\n  const prevPercentForPercentPanels = layout.reduce((sum, size, index) => {\n    if (pixelIndexSet.has(index))\n      return sum\n\n    return sum + (size ?? 0)\n  }, 0)\n\n  const availableNextPercent = Math.max(0, 100 - totalNextPixelPercent)\n  const scaleFactor = prevPercentForPercentPanels > 0\n    ? availableNextPercent / prevPercentForPercentPanels\n    : 0\n\n  pixelPanelIndices.forEach((panelIndex, arrayIndex) => {\n    nextLayout[panelIndex] = nextPixelPercents[arrayIndex]\n  })\n\n  for (let index = 0; index < nextLayout.length; index++) {\n    if (pixelIndexSet.has(index))\n      continue\n\n    const prevSize = layout[index] ?? 0\n    nextLayout[index] = prevSize * scaleFactor\n  }\n\n  // Normalize to ensure percentages always sum to exactly 100.\n  // Floating-point arithmetic in the px→% conversions above can cause drift\n  // (e.g. 99.89% instead of 100%) that gets persisted to localStorage and\n  // triggers validation warnings on every subsequent page load.\n  const total = nextLayout.reduce((sum, size) => sum + size, 0)\n  if (total > 0 && Math.abs(total - 100) > 1e-9) {\n    const factor = 100 / total\n    for (let index = 0; index < nextLayout.length; index++) {\n      nextLayout[index] = (nextLayout[index] ?? 0) * factor\n    }\n  }\n\n  return nextLayout\n}\n","import type { PanelConstraints } from '../SplitterPanel.vue'\nimport { assert } from './assert'\nimport { fuzzyNumbersEqual } from './compare'\nimport { resizePanel } from './resizePanel'\n\n// All units must be in percentages; pixel values should be pre-converted\nexport function validatePanelGroupLayout({\n  layout: prevLayout,\n  panelConstraints,\n}: {\n  layout: number[]\n  panelConstraints: PanelConstraints[]\n}): number[] {\n  const nextLayout = [...prevLayout]\n  const nextLayoutTotalSize = nextLayout.reduce(\n    (accumulated, current) => accumulated + current,\n    0,\n  )\n\n  // Validate layout expectations\n  if (nextLayout.length !== panelConstraints.length) {\n    throw new Error(\n      `Invalid ${panelConstraints.length} panel layout: ${nextLayout\n        .map(size => `${size}%`)\n        .join(', ')}`,\n    )\n  }\n  else if (!fuzzyNumbersEqual(nextLayoutTotalSize, 100)) {\n    // This is not ideal so we should warn about it, but it may be recoverable in some cases\n    // (especially if the amount is small)\n\n    if (true) {\n      console.warn(\n        `WARNING: Invalid layout total size: ${nextLayout\n          .map(size => `${size}%`)\n          .join(', ')}. Layout normalization will be applied.`,\n      )\n    }\n    for (let index = 0; index < panelConstraints.length; index++) {\n      const unsafeSize = nextLayout[index]\n      assert(unsafeSize != null)\n      const safeSize = (100 / nextLayoutTotalSize) * unsafeSize\n      nextLayout[index] = safeSize\n    }\n  }\n\n  let remainingSize = 0\n\n  // First pass: Validate the proposed layout given each panel's constraints\n  for (let index = 0; index < panelConstraints.length; index++) {\n    const unsafeSize = nextLayout[index]\n    assert(unsafeSize != null)\n\n    const safeSize = resizePanel({\n      panelConstraints,\n      panelIndex: index,\n      size: unsafeSize,\n    })\n\n    if (unsafeSize !== safeSize) {\n      remainingSize += unsafeSize - safeSize\n\n      nextLayout[index] = safeSize\n    }\n  }\n\n  // If there is additional, left over space, assign it to any panel(s) that permits it\n  // (It's not worth taking multiple additional passes to evenly distribute)\n  if (!fuzzyNumbersEqual(remainingSize, 0)) {\n    for (let index = 0; index < panelConstraints.length; index++) {\n      const prevSize = nextLayout[index]\n      assert(prevSize != null)\n      const unsafeSize = prevSize + remainingSize\n      const safeSize = resizePanel({\n        panelConstraints,\n        panelIndex: index,\n        size: unsafeSize,\n      })\n\n      if (prevSize !== safeSize) {\n        remainingSize -= safeSize - prevSize\n        nextLayout[index] = safeSize\n\n        // Once we've used up the remainder, bail\n        if (fuzzyNumbersEqual(remainingSize, 0))\n          break\n      }\n    }\n  }\n\n  return nextLayout\n}\n\nexport function validatePanelConstraints({\n  panelConstraints: panelConstraintsArray,\n  panelId,\n  panelIndex,\n}: {\n  panelConstraints: PanelConstraints[]\n  panelId: string | undefined\n  panelIndex: number\n}): boolean {\n  if (import.meta.env.DEV) {\n    const warnings = []\n\n    const panelConstraints = panelConstraintsArray[panelIndex]\n    assert(panelConstraints)\n\n    const {\n      collapsedSize = 0,\n      collapsible = false,\n      defaultSize,\n      maxSize = 100,\n      minSize = 0,\n      sizeUnit = '%',\n    } = panelConstraints\n\n    if (minSize > maxSize) {\n      warnings.push(\n        `min size (${minSize}${sizeUnit}) should not be greater than max size (${maxSize}${sizeUnit})`,\n      )\n    }\n\n    if (defaultSize != null) {\n      if (defaultSize < 0) {\n        warnings.push('default size should not be less than 0')\n      }\n      else if (\n        defaultSize < minSize\n        && (!collapsible || defaultSize !== collapsedSize)\n      ) {\n        warnings.push('default size should not be less than min size')\n      }\n\n      if (sizeUnit === '%' && defaultSize > 100)\n        warnings.push('default size should not be greater than 100')\n      else if (defaultSize > maxSize)\n        warnings.push('default size should not be greater than max size')\n    }\n\n    if (collapsedSize > minSize)\n      warnings.push('collapsed size should not be greater than min size')\n\n    if (warnings.length > 0) {\n      const name = panelId != null ? `Panel \"${panelId}\"` : 'Panel'\n      console.warn(\n        `${name} has an invalid configuration:\\n\\n${warnings.join('\\n')}`,\n      )\n\n      return false\n    }\n  }\n\n  return true\n}\n","import type { Ref } from 'vue'\nimport type { PanelData } from '../../SplitterPanel.vue'\nimport { watchEffect } from 'vue'\nimport { assert } from '../assert'\nimport { calculateAriaValues } from '../calculate'\nimport { fuzzyNumbersEqual } from '../compare'\nimport { getPanelGroupElement, getResizeHandleElementsForGroup, getResizeHandlePanelIds } from '../dom'\nimport { adjustLayoutByDelta } from '../layout'\nimport { determinePivotIndices } from '../pivot'\n\n// https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/\n\nexport function useWindowSplitterPanelGroupBehavior({\n  eagerValuesRef,\n  groupId,\n  layout,\n  panelDataArray,\n  panelGroupElement,\n  setLayout,\n  getPanelDataWithPercentConstraints,\n}: {\n  eagerValuesRef: Ref<{\n    panelDataArray: PanelData[]\n  }>\n  groupId: string\n  layout: Ref<number[]>\n  panelDataArray: PanelData[]\n  panelGroupElement: Ref<ParentNode | null>\n  setLayout: (sizes: number[]) => void\n  getPanelDataWithPercentConstraints: (groupSizeOverride?: number | null) => PanelData[] | null\n}): void {\n  watchEffect((onCleanup) => {\n    const _panelGroupElement = panelGroupElement.value\n    if (!_panelGroupElement)\n      return\n\n    const panelDataArrayWithPercentConstraints = getPanelDataWithPercentConstraints()\n    if (!panelDataArrayWithPercentConstraints)\n      return\n\n    const resizeHandleElements = getResizeHandleElementsForGroup(\n      groupId,\n      _panelGroupElement,\n    )\n\n    for (let index = 0; index < panelDataArrayWithPercentConstraints.length - 1; index++) {\n      const { valueMax, valueMin, valueNow } = calculateAriaValues({\n        layout: layout.value,\n        panelsArray: panelDataArrayWithPercentConstraints,\n        pivotIndices: [index, index + 1],\n      })\n\n      const resizeHandleElement = resizeHandleElements[index]\n      if (resizeHandleElement == null) {\n        if (import.meta.env.DEV)\n          console.warn(`WARNING: Missing resize handle for PanelGroup \"${groupId}\"`)\n      }\n      else {\n        const panelData = panelDataArrayWithPercentConstraints[index]\n        assert(panelData)\n\n        resizeHandleElement.setAttribute('aria-controls', panelData.id)\n        resizeHandleElement.setAttribute(\n          'aria-valuemax',\n          `${Math.round(valueMax)}`,\n        )\n        resizeHandleElement.setAttribute(\n          'aria-valuemin',\n          `${Math.round(valueMin)}`,\n        )\n        resizeHandleElement.setAttribute(\n          'aria-valuenow',\n          valueNow != null ? `${Math.round(valueNow)}` : '',\n        )\n      }\n    }\n\n    onCleanup(() => {\n      resizeHandleElements.forEach((resizeHandleElement) => {\n        resizeHandleElement.removeAttribute('aria-controls')\n        resizeHandleElement.removeAttribute('aria-valuemax')\n        resizeHandleElement.removeAttribute('aria-valuemin')\n        resizeHandleElement.removeAttribute('aria-valuenow')\n      })\n    })\n  })\n\n  watchEffect((onCleanup) => {\n    const _panelGroupElement = panelGroupElement.value\n    if (!_panelGroupElement)\n      return\n\n    const eagerValues = eagerValuesRef.value\n    assert(eagerValues)\n\n    const panelDataArrayWithPercentConstraints = getPanelDataWithPercentConstraints()\n    if (!panelDataArrayWithPercentConstraints)\n      return\n\n    const { panelDataArray } = eagerValues\n    const groupElement = getPanelGroupElement(groupId, _panelGroupElement)\n    assert(groupElement != null, `No group found for id \"${groupId}\"`)\n\n    const handles = getResizeHandleElementsForGroup(groupId, _panelGroupElement)\n    assert(handles)\n\n    const cleanupFunctions = handles.map((handle) => {\n      const handleId = handle.getAttribute('data-panel-resize-handle-id')\n      assert(handleId)\n\n      const [idBefore, idAfter] = getResizeHandlePanelIds(\n        groupId,\n        handleId,\n        panelDataArray,\n        _panelGroupElement,\n      )\n      if (idBefore == null || idAfter == null)\n        return () => {}\n\n      const onKeyDown = (event: KeyboardEvent) => {\n        if (event.defaultPrevented)\n          return\n\n        switch (event.key) {\n          case 'Enter': {\n            event.preventDefault()\n\n            const index = panelDataArrayWithPercentConstraints.findIndex(\n              panelData => panelData.id === idBefore,\n            )\n            if (index >= 0) {\n              const panelData = panelDataArrayWithPercentConstraints[index]\n              assert(panelData)\n\n              const size = layout.value[index]\n\n              const {\n                collapsedSize = 0,\n                collapsible,\n                minSize = 0,\n              } = panelData.constraints\n\n              if (size != null && collapsible) {\n                const nextLayout = adjustLayoutByDelta({\n                  delta: fuzzyNumbersEqual(size, collapsedSize)\n                    ? minSize - collapsedSize\n                    : collapsedSize - size,\n                  layout: layout.value,\n                  panelConstraints: panelDataArrayWithPercentConstraints.map(\n                    panelData => panelData.constraints,\n                  ),\n                  pivotIndices: determinePivotIndices(\n                    groupId,\n                    handleId,\n                    _panelGroupElement,\n                  ),\n                  trigger: 'keyboard',\n                })\n                if (layout.value !== nextLayout)\n                  setLayout(nextLayout)\n              }\n            }\n            break\n          }\n        }\n      }\n\n      handle.addEventListener('keydown', onKeyDown)\n      return () => {\n        handle.removeEventListener('keydown', onKeyDown)\n      }\n    })\n\n    onCleanup(() => {\n      cleanupFunctions.forEach(cleanupFunction => cleanupFunction())\n    })\n  })\n}\n","import type { PanelGroupStorage } from '../SplitterGroup.vue'\nimport type { PanelData } from '../SplitterPanel.vue'\n\n// PanelGroup might be rendering in a server-side environment where localStorage is not available\n// or on a browser with cookies/storage disabled.\n// In either case, this function avoids accessing localStorage until needed,\n// and avoids throwing user-visible errors.\nexport function initializeDefaultStorage(storageObject: PanelGroupStorage) {\n  try {\n    if (typeof localStorage !== 'undefined') {\n      // Bypass this check for future calls\n      storageObject.getItem = (name: string) => {\n        return localStorage.getItem(name)\n      }\n      storageObject.setItem = (name: string, value: string) => {\n        localStorage.setItem(name, value)\n      }\n    }\n    else {\n      throw new TypeError('localStorage not supported in this environment')\n    }\n  }\n  catch (error) {\n    console.error(error)\n\n    storageObject.getItem = () => null\n    storageObject.setItem = () => {}\n  }\n}\n\nexport type PanelConfigurationState = {\n  expandToSizes: {\n    [panelId: string]: number\n  }\n  layout: number[]\n  sizeUnits?: {\n    [panelIndex: number]: 'px' | '%'\n  }\n}\n\nexport type SerializedPanelGroupState = {\n  [panelIds: string]: PanelConfigurationState\n}\n\nfunction getPanelGroupKey(autoSaveId: string): string {\n  return `reka:${autoSaveId}`\n}\n\n// Note that Panel ids might be user-provided (stable) or useId generated (non-deterministic)\n// so they should not be used as part of the serialization key.\n// Using the min/max size attributes should work well enough as a backup.\n// Pre-sorting by minSize allows remembering layouts even if panels are re-ordered/dragged.\nfunction getPanelKey(panels: PanelData[]): string {\n  return panels\n    .map((panel) => {\n      const { constraints, id, idIsFromProps, order } = panel\n      if (idIsFromProps) {\n        return id\n      }\n      else {\n        return order\n          ? `${order}:${JSON.stringify(constraints)}`\n          : JSON.stringify(constraints)\n      }\n    })\n    .sort((a, b) => a.localeCompare(b))\n    .join(',')\n}\n\nfunction loadSerializedPanelGroupState(\n  autoSaveId: string,\n  storage: PanelGroupStorage,\n): SerializedPanelGroupState | null {\n  try {\n    const panelGroupKey = getPanelGroupKey(autoSaveId)\n    const serialized = storage.getItem(panelGroupKey)\n    if (serialized) {\n      const parsed = JSON.parse(serialized)\n      if (typeof parsed === 'object' && parsed != null)\n        return parsed as SerializedPanelGroupState\n    }\n  }\n  catch (error) {}\n\n  return null\n}\n\nexport function loadPanelGroupState(\n  autoSaveId: string,\n  panels: PanelData[],\n  storage: PanelGroupStorage,\n): PanelConfigurationState | null {\n  const state = loadSerializedPanelGroupState(autoSaveId, storage) ?? {}\n  const panelKey = getPanelKey(panels)\n  return state[panelKey] ?? null\n}\n\nexport function savePanelGroupState(\n  autoSaveId: string,\n  panels: PanelData[],\n  panelSizesBeforeCollapse: Map<string, number>,\n  sizes: number[],\n  storage: PanelGroupStorage,\n): void {\n  const panelGroupKey = getPanelGroupKey(autoSaveId)\n  const panelKey = getPanelKey(panels)\n  const state = loadSerializedPanelGroupState(autoSaveId, storage) ?? {}\n\n  // Store the size units for each panel so we can restore them correctly\n  const sizeUnits: { [panelIndex: number]: 'px' | '%' } = {}\n  panels.forEach((panel, index) => {\n    const unit = panel.constraints.sizeUnit ?? '%'\n    if (unit === 'px') {\n      sizeUnits[index] = 'px'\n    }\n  })\n\n  state[panelKey] = {\n    expandToSizes: Object.fromEntries(panelSizesBeforeCollapse.entries()),\n    layout: sizes,\n    ...(Object.keys(sizeUnits).length > 0 && { sizeUnits }),\n  }\n\n  try {\n    storage.setItem(panelGroupKey, JSON.stringify(state))\n  }\n  catch (error) {\n    console.error(error)\n  }\n}\n","<script lang=\"ts\">\nimport type { CSSProperties, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed, ref, toRefs, watch, watchEffect } from 'vue'\nimport { areEqual, createContext, useDirection, useForwardExpose, useId } from '@/shared'\nimport { useWindowSplitterPanelGroupBehavior } from './utils/composables/useWindowSplitterPanelGroupBehavior'\nimport {\n  initializeDefaultStorage,\n  loadPanelGroupState,\n  savePanelGroupState,\n} from './utils/storage'\n\nexport interface SplitterGroupProps extends PrimitiveProps {\n  /** Group id; falls back to `useId` when not provided. */\n  id?: string | null\n  /** Unique id used to auto-save group arrangement via `localStorage`. */\n  autoSaveId?: string | null\n  /** The group orientation of splitter. */\n  direction: Direction\n  /** Step size when arrow key was pressed. */\n  keyboardResizeBy?: number | null\n  /** Custom storage API; defaults to localStorage */\n  storage?: PanelGroupStorage\n}\n\nexport type SplitterGroupEmits = {\n  /** Event handler called when group layout changes */\n  layout: [val: number[]]\n}\n\nconst LOCAL_STORAGE_DEBOUNCE_INTERVAL = 100\n\nexport type PanelGroupStorage = {\n  getItem: (name: string) => string | null\n  setItem: (name: string, value: string) => void\n}\n\nconst defaultStorage: PanelGroupStorage = {\n  getItem: (name: string) => {\n    initializeDefaultStorage(defaultStorage)\n    return defaultStorage.getItem(name)\n  },\n  setItem: (name: string, value: string) => {\n    initializeDefaultStorage(defaultStorage)\n    defaultStorage.setItem(name, value)\n  },\n}\n\nexport type PanelGroupContext = {\n  direction: Ref<Direction>\n  dragState: DragState | null\n  groupId: string\n  reevaluatePanelConstraints: (panelData: PanelData, prevConstraints: PanelConstraints) => void\n  registerPanel: (panelData: PanelData) => void\n  registerResizeHandle: (dragHandleId: string) => ResizeHandler\n  resizePanel: (panelData: PanelData, size: number) => void\n  startDragging: (dragHandleId: string, event: ResizeEvent) => void\n  stopDragging: () => void\n  unregisterPanel: (panelData: PanelData) => void\n  panelGroupElement: Ref<ParentNode | null>\n\n  // Exposed function for child component\n  collapsePanel: (panelData: PanelData) => void\n  expandPanel: (panelData: PanelData) => void\n  isPanelCollapsed: (panelData: PanelData) => boolean\n  isPanelExpanded: (panelData: PanelData) => boolean\n  getPanelSize: (panelData: PanelData) => number\n  getPanelStyle: (panelData: PanelData, defaultSize: number | undefined) => CSSProperties\n}\n\nexport const [injectPanelGroupContext, providePanelGroupContext] = createContext<PanelGroupContext>('PanelGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport type { PanelConstraints, PanelData } from './SplitterPanel.vue'\n\nimport type { Direction, DragState, ResizeEvent, ResizeHandler } from './utils/types'\nimport { Primitive } from '@/Primitive'\nimport { assert } from './utils/assert'\nimport { calculateDeltaPercentage, calculateUnsafeDefaultLayout } from './utils/calculate'\nimport { callPanelCallbacks } from './utils/callPanelCallbacks'\nimport { fuzzyCompareNumbers } from './utils/compare'\nimport debounce from './utils/debounce'\nimport { getResizeHandleElement } from './utils/dom'\nimport { getResizeEventCursorPosition, isKeyDown, isMouseEvent, isTouchEvent } from './utils/events'\nimport { adjustLayoutByDelta, compareLayouts } from './utils/layout'\nimport { determinePivotIndices } from './utils/pivot'\nimport {\n  EXCEEDED_HORIZONTAL_MAX,\n  EXCEEDED_HORIZONTAL_MIN,\n  EXCEEDED_VERTICAL_MAX,\n  EXCEEDED_VERTICAL_MIN,\n  reportConstraintsViolation,\n} from './utils/registry'\nimport { computePanelFlexBoxStyle } from './utils/style'\nimport { convertPanelConstraintsToPercent, hasPixelSizedPanel, recalculateLayoutForPixelPanels } from './utils/units'\nimport { validatePanelGroupLayout } from './utils/validation'\n\nconst props = withDefaults(defineProps<SplitterGroupProps>(), {\n  autoSaveId: null,\n  keyboardResizeBy: 10,\n  storage: () => defaultStorage,\n})\nconst emits = defineEmits<SplitterGroupEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current size of layout */\n    layout: typeof layout.value\n  }) => any\n}>()\n\nconst debounceMap: {\n  [key: string]: typeof savePanelGroupState\n} = {}\n\nconst { direction } = toRefs(props)\nconst groupId = useId(props.id, 'reka-splitter-group')\nconst dir = useDirection()\nconst { forwardRef, currentElement: panelGroupElementRef } = useForwardExpose()\n\nconst dragState = ref<DragState | null>(null)\nconst groupSizeInPixels = ref<number | null>(null)\nconst groupSizeAtLastLayoutInit = ref<number | null>(null)\nconst layout = ref<number[]>([])\nconst panelIdToLastNotifiedSizeMapRef = ref<Record<string, number>>({})\nconst panelSizeBeforeCollapseRef = ref<Map<string, number>>(new Map())\nconst prevDeltaRef = ref<number>(0)\n\nconst committedValuesRef = computed(() => ({\n  autoSaveId: props.autoSaveId,\n  direction: props.direction,\n  dragState: dragState.value,\n  id: groupId,\n  keyboardResizeBy: props.keyboardResizeBy,\n  storage: props.storage,\n}) satisfies {\n  autoSaveId: string | null\n  direction: Direction\n  dragState: DragState | null\n  id: string\n  keyboardResizeBy: number | null\n  storage: PanelGroupStorage\n})\n\nconst eagerValuesRef = ref<{\n  layout: number[]\n  panelDataArray: PanelData[]\n  panelDataArrayChanged: boolean\n}>({\n  layout: layout.value,\n  panelDataArray: [],\n  panelDataArrayChanged: false,\n})\n\nfunction getGroupSizeInPixels(): number | null {\n  if (groupSizeInPixels.value != null)\n    return groupSizeInPixels.value\n\n  const element = panelGroupElementRef.value\n  if (element && element instanceof HTMLElement) {\n    const rect = element.getBoundingClientRect()\n    const size = direction.value === 'horizontal' ? rect.width : rect.height\n\n    if (!Number.isNaN(size)) {\n      groupSizeInPixels.value = size\n      return size\n    }\n  }\n\n  return null\n}\n\nfunction getPanelConstraintsInPercent(groupSizeOverride?: number | null) {\n  const groupSize = groupSizeOverride ?? getGroupSizeInPixels()\n\n  return convertPanelConstraintsToPercent({\n    panelDataArray: eagerValuesRef.value.panelDataArray,\n    groupSizeInPixels: groupSize,\n  })\n}\n\nfunction getPanelDataWithPercentConstraints(groupSizeOverride?: number | null) {\n  const percentConstraints = getPanelConstraintsInPercent(groupSizeOverride)\n\n  if (!percentConstraints)\n    return null\n\n  return eagerValuesRef.value.panelDataArray.map((panelData, index) => ({\n    ...panelData,\n    constraints: percentConstraints[index],\n  }))\n}\n\nconst setLayout = (val: number[]) => layout.value = val\n\n/** Convert internal layout (always in %) to native units for each panel */\nfunction convertLayoutToNativeUnits(internalLayout: number[]): number[] {\n  const { panelDataArray } = eagerValuesRef.value\n  const groupSize = getGroupSizeInPixels()\n\n  return internalLayout.map((size, index) => {\n    const panelData = panelDataArray[index]\n    if (panelData && (panelData.constraints.sizeUnit ?? '%') === 'px' && groupSize != null) {\n      return (size / 100) * groupSize\n    }\n    return size\n  })\n}\n\nuseWindowSplitterPanelGroupBehavior({\n  eagerValuesRef,\n  groupId,\n  layout,\n  panelDataArray: eagerValuesRef.value.panelDataArray,\n  setLayout,\n  panelGroupElement: panelGroupElementRef,\n  getPanelDataWithPercentConstraints,\n})\n\nwatchEffect((onCleanup) => {\n  const element = panelGroupElementRef.value\n  if (!element)\n    return\n\n  if (typeof ResizeObserver !== 'function')\n    return\n\n  const resizeObserver = new ResizeObserver((entries) => {\n    const entry = entries[0]\n    if (!entry)\n      return\n\n    const { height, width } = entry.contentRect\n    const nextSize = direction.value === 'horizontal' ? width : height\n\n    if (!Number.isNaN(nextSize))\n      groupSizeInPixels.value = nextSize\n  })\n\n  if (element instanceof HTMLElement)\n    resizeObserver.observe(element)\n\n  onCleanup(() => resizeObserver.disconnect())\n})\n\nwatchEffect(() => {\n  const { panelDataArray } = eagerValuesRef.value\n  const { autoSaveId } = props\n  // If this panel has been configured to persist sizing information, save sizes to local storage.\n  if (autoSaveId) {\n    if (layout.value.length === 0 || layout.value.length !== panelDataArray.length)\n      return\n\n    let debouncedSave = debounceMap[autoSaveId]\n\n    // Limit the frequency of localStorage updates.\n    if (!debouncedSave) {\n      debouncedSave = debounce(\n        savePanelGroupState,\n        LOCAL_STORAGE_DEBOUNCE_INTERVAL,\n      )\n\n      debounceMap[autoSaveId] = debouncedSave\n    }\n\n    // Clone mutable data before passing to the debounced function,\n    // else we run the risk of saving an incorrect combination of mutable and immutable values to state.\n    const clonedPanelDataArray = [...panelDataArray]\n    const clonedPanelSizesBeforeCollapse = new Map(\n      panelSizeBeforeCollapseRef.value,\n    )\n\n    debouncedSave(\n      autoSaveId,\n      clonedPanelDataArray,\n      clonedPanelSizesBeforeCollapse,\n      layout.value,\n      props.storage,\n    )\n  }\n})\n\nfunction getPanelStyle(panelData: PanelData, defaultSize: number | undefined) {\n  const { panelDataArray } = eagerValuesRef.value\n\n  const panelIndex = findPanelDataIndex(panelDataArray, panelData)\n\n  return computePanelFlexBoxStyle({\n    defaultSize,\n    dragState: dragState.value,\n    layout: layout.value,\n    panelData: panelDataArray,\n    panelIndex,\n  })\n}\n\nfunction registerPanel(panelData: PanelData) {\n  const { panelDataArray } = eagerValuesRef.value\n\n  panelDataArray.push(panelData)\n  panelDataArray.sort((panelA, panelB) => {\n    const orderA = panelA.order\n    const orderB = panelB.order\n    if (orderA == null && orderB == null)\n      return 0\n    else if (orderA == null)\n      return -1\n    else if (orderB == null)\n      return 1\n    else\n      return orderA - orderB\n  })\n\n  eagerValuesRef.value.panelDataArrayChanged = true\n}\n\n// (Re)calculate group layout whenever panels are registered or unregistered.\n// useIsomorphicLayoutEffect\nwatch(() => eagerValuesRef.value.panelDataArrayChanged, () => {\n  if (eagerValuesRef.value.panelDataArrayChanged) {\n    eagerValuesRef.value.panelDataArrayChanged = false\n\n    const { autoSaveId, storage } = committedValuesRef.value\n    const { layout: prevLayout, panelDataArray } = eagerValuesRef.value\n\n    // If this panel has been configured to persist sizing information,\n    // default size should be restored from local storage if possible.\n    let unsafeLayout: number[] | null = null\n    if (autoSaveId) {\n      const state = loadPanelGroupState(autoSaveId, panelDataArray, storage)\n      if (state) {\n        panelSizeBeforeCollapseRef.value = new Map(\n          Object.entries(state.expandToSizes),\n        )\n        unsafeLayout = state.layout\n      }\n    }\n\n    if (unsafeLayout === null) {\n      const panelDataArrayWithPercentConstraints = getPanelDataWithPercentConstraints()\n      if (!panelDataArrayWithPercentConstraints)\n        return\n\n      unsafeLayout = calculateUnsafeDefaultLayout({\n        panelDataArray: panelDataArrayWithPercentConstraints,\n      })\n    }\n\n    const panelConstraints = getPanelConstraintsInPercent()\n    if (!panelConstraints)\n      return\n\n    // Validate even saved layouts in case something has changed since last render\n    // e.g. for pixel groups, this could be the size of the window\n    const nextLayout = validatePanelGroupLayout({\n      layout: unsafeLayout,\n      panelConstraints,\n    })\n\n    // Track the group size used for this initialization.\n    // Used to detect when a nested px group was measured with an unreliable (too small)\n    // container size before the outer group finished layout.\n    groupSizeAtLastLayoutInit.value = getGroupSizeInPixels()\n\n    if (!areEqual(prevLayout, nextLayout)) {\n      setLayout(nextLayout)\n\n      eagerValuesRef.value.layout = nextLayout\n      emits('layout', convertLayoutToNativeUnits(nextLayout))\n\n      callPanelCallbacks(\n        panelDataArray,\n        nextLayout,\n        panelIdToLastNotifiedSizeMapRef.value,\n        getGroupSizeInPixels(),\n      )\n    }\n  }\n})\n\nwatch(groupSizeInPixels, (nextSize, prevSize) => {\n  if (prevSize == null || nextSize == null)\n    return\n\n  const { layout: prevLayout, panelDataArray } = eagerValuesRef.value\n  if (prevLayout.length === 0)\n    return\n  if (!hasPixelSizedPanel(panelDataArray))\n    return\n\n  // Detect if the layout was initialized with an unreliably small container.\n  // This happens with nested SplitterGroups using sizeUnit=\"px\": the inner group's\n  // ResizeObserver fires before the outer group's flex layout completes, giving a\n  // near-zero container size (e.g. 3.45px). When the outer group finishes and the\n  // container grows to its real size (e.g. 923px), we must re-initialize rather\n  // than recalculate (which would \"preserve\" the garbage pixel sizes from 3.45px).\n  // We guard with initSize < 50 so that legitimately small-but-real containers\n  // (e.g. a sidebar at 60px) are not accidentally re-initialized on normal resizes.\n  const initSize = groupSizeAtLastLayoutInit.value\n  if (initSize != null && initSize > 0 && initSize < 50 && nextSize > initSize * 10) {\n    eagerValuesRef.value.panelDataArrayChanged = true\n    return\n  }\n\n  const recalculatedLayout = recalculateLayoutForPixelPanels({\n    layout: prevLayout,\n    panelDataArray,\n    prevGroupSize: prevSize,\n    nextGroupSize: nextSize,\n  })\n\n  if (!recalculatedLayout)\n    return\n\n  const panelConstraints = getPanelConstraintsInPercent(nextSize)\n  if (!panelConstraints)\n    return\n\n  const nextLayout = validatePanelGroupLayout({\n    layout: recalculatedLayout,\n    panelConstraints,\n  })\n\n  if (!compareLayouts(prevLayout, nextLayout)) {\n    setLayout(nextLayout)\n\n    eagerValuesRef.value.layout = nextLayout\n    emits('layout', convertLayoutToNativeUnits(nextLayout))\n\n    callPanelCallbacks(\n      panelDataArray,\n      nextLayout,\n      panelIdToLastNotifiedSizeMapRef.value,\n      getGroupSizeInPixels(),\n    )\n  }\n})\n\nfunction registerResizeHandle(dragHandleId: string) {\n  return function resizeHandler(event: ResizeEvent) {\n    event.preventDefault()\n    const panelGroupElement = panelGroupElementRef.value\n    if (!panelGroupElement)\n      return () => null\n\n    const { direction, dragState, id: groupId, keyboardResizeBy } = committedValuesRef.value\n    const { layout: prevLayout, panelDataArray } = eagerValuesRef.value\n\n    const { initialLayout } = dragState ?? {}\n\n    const pivotIndices = determinePivotIndices(\n      groupId,\n      dragHandleId,\n      panelGroupElement,\n    )\n\n    let delta = calculateDeltaPercentage(\n      event,\n      dragHandleId,\n      direction,\n      dragState,\n      keyboardResizeBy,\n      panelGroupElement,\n    )\n    if (delta === 0)\n      return\n\n    // Support RTL layouts\n    const isHorizontal = direction === 'horizontal'\n    if (dir.value === 'rtl' && isHorizontal)\n      delta = -delta\n\n    const panelConstraints = getPanelConstraintsInPercent()\n    if (!panelConstraints)\n      return\n\n    const nextLayout = adjustLayoutByDelta({\n      delta,\n      layout: initialLayout ?? prevLayout,\n      panelConstraints,\n      pivotIndices,\n      trigger: isKeyDown(event) ? 'keyboard' : 'mouse-or-touch',\n    })\n\n    const layoutChanged = !compareLayouts(prevLayout, nextLayout)\n\n    // Only update the cursor for layout changes triggered by touch/mouse events (not keyboard)\n    // Update the cursor even if the layout hasn't changed (we may need to show an invalid cursor state)\n    if (isMouseEvent(event) || isTouchEvent(event)) {\n      // Watch for multiple subsequent deltas; this might occur for tiny cursor movements.\n      // In this case, Panel sizes might not change–\n      // but updating cursor in this scenario would cause a flicker.\n      if (prevDeltaRef.value !== delta) {\n        prevDeltaRef.value = delta\n\n        if (!layoutChanged) {\n          // If the pointer has moved too far to resize the panel any further, note this so we can update the cursor.\n          // This mimics VS Code behavior.\n          if (isHorizontal) {\n            reportConstraintsViolation(\n              dragHandleId,\n              delta < 0 ? EXCEEDED_HORIZONTAL_MIN : EXCEEDED_HORIZONTAL_MAX,\n            )\n          }\n          else {\n            reportConstraintsViolation(\n              dragHandleId,\n              delta < 0 ? EXCEEDED_VERTICAL_MIN : EXCEEDED_VERTICAL_MAX,\n            )\n          }\n        }\n        else {\n          reportConstraintsViolation(dragHandleId, 0)\n        }\n      }\n    }\n\n    if (layoutChanged) {\n      setLayout(nextLayout)\n\n      eagerValuesRef.value.layout = nextLayout\n      emits('layout', convertLayoutToNativeUnits(nextLayout))\n\n      callPanelCallbacks(\n        panelDataArray,\n        nextLayout,\n        panelIdToLastNotifiedSizeMapRef.value,\n        getGroupSizeInPixels(),\n      )\n    }\n  }\n}\n\nfunction resizePanel(panelData: PanelData, unsafePanelSize: number) {\n  const { layout: prevLayout, panelDataArray } = eagerValuesRef.value\n\n  const panelConstraintsArray = getPanelConstraintsInPercent()\n  if (!panelConstraintsArray)\n    return\n\n  const panelIndex = findPanelDataIndex(panelDataArray, panelData)\n  const panelUnit = panelData.constraints.sizeUnit ?? '%'\n\n  // Convert px to percent if needed for internal calculation\n  let sizeInPercent = unsafePanelSize\n  if (panelUnit === 'px') {\n    const groupSize = getGroupSizeInPixels()\n    if (groupSize != null) {\n      sizeInPercent = (unsafePanelSize / groupSize) * 100\n    }\n  }\n\n  const { panelSize, pivotIndices } = panelDataHelper(\n    panelDataArray,\n    panelData,\n    prevLayout,\n    panelConstraintsArray,\n  )\n\n  assert(panelSize != null)\n\n  const isLastPanel = panelIndex === panelDataArray.length - 1\n  const delta = isLastPanel\n    ? panelSize - sizeInPercent\n    : sizeInPercent - panelSize\n\n  const nextLayout = adjustLayoutByDelta({\n    delta,\n    layout: prevLayout,\n    panelConstraints: panelConstraintsArray,\n    pivotIndices,\n    trigger: 'imperative-api',\n  })\n\n  if (!compareLayouts(prevLayout, nextLayout)) {\n    setLayout(nextLayout)\n\n    eagerValuesRef.value.layout = nextLayout\n    emits('layout', convertLayoutToNativeUnits(nextLayout))\n\n    callPanelCallbacks(\n      panelDataArray,\n      nextLayout,\n      panelIdToLastNotifiedSizeMapRef.value,\n      getGroupSizeInPixels(),\n    )\n  }\n}\n\nfunction reevaluatePanelConstraints(panelData: PanelData, prevConstraints: PanelConstraints) {\n  const { layout, panelDataArray } = eagerValuesRef.value\n  const index = findPanelDataIndex(panelDataArray, panelData)\n  panelDataArray[index] = panelData\n  eagerValuesRef.value.panelDataArrayChanged = true\n\n  const panelConstraintsArray = getPanelConstraintsInPercent()\n  if (!panelConstraintsArray)\n    return\n\n  const nextConstraints = panelConstraintsArray[index]\n  const { panelSize: prevPanelSize } = panelDataHelper(\n    panelDataArray,\n    panelData,\n    layout,\n    panelConstraintsArray,\n  )\n\n  if (prevPanelSize === null)\n    return\n\n  const nextCollapsedSize = nextConstraints?.collapsedSize ?? 0\n  const nextMaxSize = nextConstraints?.maxSize ?? 100\n  const nextMinSize = nextConstraints?.minSize ?? 0\n\n  if (nextConstraints?.collapsible && isPanelCollapsed(panelData)) {\n    if (prevPanelSize !== nextCollapsedSize)\n      resizePanel(panelData, nextCollapsedSize)\n  }\n  else if (prevPanelSize < nextMinSize) {\n    resizePanel(panelData, nextMinSize)\n  }\n  else if (prevPanelSize > nextMaxSize) {\n    resizePanel(panelData, nextMaxSize)\n  }\n}\n\nfunction startDragging(dragHandleId: string, event: ResizeEvent) {\n  const { direction } = committedValuesRef.value\n  const { layout } = eagerValuesRef.value\n  if (!panelGroupElementRef.value)\n    return\n\n  const handleElement = getResizeHandleElement(\n    dragHandleId,\n    panelGroupElementRef.value,\n  )\n  assert(handleElement)\n\n  const initialCursorPosition = getResizeEventCursorPosition(\n    direction,\n    event,\n  )\n\n  dragState.value = {\n    dragHandleId,\n    dragHandleRect: handleElement.getBoundingClientRect(),\n    initialCursorPosition,\n    initialLayout: layout,\n  }\n}\nfunction stopDragging() {\n  dragState.value = null\n}\n\nfunction unregisterPanel(panelData: PanelData) {\n  const { panelDataArray } = eagerValuesRef.value\n\n  const index = findPanelDataIndex(panelDataArray, panelData)\n  if (index >= 0) {\n    panelDataArray.splice(index, 1)\n\n    // TRICKY\n    // When a panel is removed from the group, we should delete the most recent prev-size entry for it.\n    // If we don't do this, then a conditionally rendered panel might not call onResize when it's re-mounted.\n    // Strict effects mode makes this tricky though because all panels will be registered, unregistered, then re-registered on mount.\n    delete panelIdToLastNotifiedSizeMapRef.value[panelData.id]\n\n    eagerValuesRef.value.panelDataArrayChanged = true\n  }\n}\n\nfunction collapsePanel(panelData: PanelData) {\n  const { layout: prevLayout, panelDataArray } = eagerValuesRef.value\n\n  if (panelData.constraints.collapsible) {\n    const panelConstraintsArray = getPanelConstraintsInPercent()\n    if (!panelConstraintsArray)\n      return\n\n    const {\n      collapsedSize = 0,\n      panelSize,\n      pivotIndices,\n    } = panelDataHelper(panelDataArray, panelData, prevLayout, panelConstraintsArray)\n\n    assert(\n      panelSize != null,\n      `Panel size not found for panel \"${panelData.id}\"`,\n    )\n\n    if (panelSize !== collapsedSize) {\n      // Store size before collapse;\n      // This is the size that gets restored if the expand() API is used.\n      const sizeUnit = panelData.constraints.sizeUnit ?? '%'\n      const groupSize = groupSizeInPixels.value ?? getGroupSizeInPixels()\n      const sizeBeforeCollapse = sizeUnit === 'px' && groupSize\n        ? (panelSize / 100) * groupSize\n        : panelSize\n\n      panelSizeBeforeCollapseRef.value.set(panelData.id, sizeBeforeCollapse)\n\n      const isLastPanel\n        = findPanelDataIndex(panelDataArray, panelData)\n          === panelDataArray.length - 1\n      const delta = isLastPanel\n        ? panelSize - collapsedSize\n        : collapsedSize - panelSize\n\n      const nextLayout = adjustLayoutByDelta({\n        delta,\n        layout: prevLayout,\n        panelConstraints: panelConstraintsArray,\n        pivotIndices,\n        trigger: 'imperative-api',\n      })\n\n      if (!compareLayouts(prevLayout, nextLayout)) {\n        setLayout(nextLayout)\n\n        eagerValuesRef.value.layout = nextLayout\n\n        emits('layout', convertLayoutToNativeUnits(nextLayout))\n\n        callPanelCallbacks(\n          panelDataArray,\n          nextLayout,\n          panelIdToLastNotifiedSizeMapRef.value,\n          getGroupSizeInPixels(),\n        )\n      }\n    }\n  }\n}\n\nfunction expandPanel(panelData: PanelData) {\n  const { layout: prevLayout, panelDataArray } = eagerValuesRef.value\n\n  if (panelData.constraints.collapsible) {\n    const panelConstraintsArray = getPanelConstraintsInPercent()\n    if (!panelConstraintsArray)\n      return\n\n    const {\n      collapsedSize = 0,\n      panelSize = 0,\n      minSize = 0,\n      pivotIndices,\n    } = panelDataHelper(panelDataArray, panelData, prevLayout, panelConstraintsArray)\n\n    if (fuzzyCompareNumbers(panelSize, collapsedSize) <= 0) {\n      // Restore this panel to the size it was before it was collapsed, if possible.\n      const prevPanelSize = panelSizeBeforeCollapseRef.value.get(\n        panelData.id,\n      )\n      const sizeUnit = panelData.constraints.sizeUnit ?? '%'\n      const groupSize = groupSizeInPixels.value ?? getGroupSizeInPixels()\n\n      const restoredSize\n        = sizeUnit === 'px' && groupSize\n          ? prevPanelSize != null\n            ? (prevPanelSize / groupSize) * 100\n            : null\n          : prevPanelSize\n\n      const baseSize\n        = restoredSize != null && restoredSize >= minSize\n          ? restoredSize\n          : minSize\n\n      const isLastPanel\n        = findPanelDataIndex(panelDataArray, panelData)\n          === panelDataArray.length - 1\n      const delta = isLastPanel ? panelSize - baseSize : baseSize - panelSize\n\n      const nextLayout = adjustLayoutByDelta({\n        delta,\n        layout: prevLayout,\n        panelConstraints: panelConstraintsArray,\n        pivotIndices,\n        trigger: 'imperative-api',\n      })\n\n      if (!compareLayouts(prevLayout, nextLayout)) {\n        setLayout(nextLayout)\n\n        eagerValuesRef.value.layout = nextLayout\n\n        emits('layout', convertLayoutToNativeUnits(nextLayout))\n\n        callPanelCallbacks(\n          panelDataArray,\n          nextLayout,\n          panelIdToLastNotifiedSizeMapRef.value,\n          getGroupSizeInPixels(),\n        )\n      }\n    }\n  }\n}\n\nfunction getPanelSize(panelData: PanelData) {\n  const { layout, panelDataArray } = eagerValuesRef.value\n\n  const { panelSize } = panelDataHelper(panelDataArray, panelData, layout)\n\n  assert(\n    panelSize != null,\n    `Panel size not found for panel \"${panelData.id}\"`,\n  )\n\n  // If the panel uses px units, convert from percent back to px\n  const panelUnit = panelData.constraints.sizeUnit ?? '%'\n  if (panelUnit === 'px') {\n    const groupSize = getGroupSizeInPixels()\n    if (groupSize != null) {\n      return (panelSize / 100) * groupSize\n    }\n  }\n\n  return panelSize\n}\n\nfunction isPanelCollapsed(panelData: PanelData) {\n  const { layout, panelDataArray } = eagerValuesRef.value\n\n  const panelConstraintsArray = getPanelConstraintsInPercent()\n\n  const {\n    collapsedSize = 0,\n    collapsible,\n    panelSize,\n  } = panelDataHelper(\n    panelDataArray,\n    panelData,\n    layout,\n    panelConstraintsArray ?? undefined,\n  )\n\n  if (!collapsible)\n    return false\n\n  // panelSize is undefined during ssr due to vue ssr reactivity limitation.\n  if (panelSize === undefined) {\n    const panelIndex = findPanelDataIndex(panelDataArray, panelData)\n    const constraints = panelConstraintsArray?.[panelIndex] ?? panelData.constraints\n    return constraints.defaultSize === constraints.collapsedSize\n  }\n  else {\n    return panelSize === collapsedSize\n  }\n}\n\nfunction isPanelExpanded(panelData: PanelData) {\n  const { layout, panelDataArray } = eagerValuesRef.value\n\n  const panelConstraintsArray = getPanelConstraintsInPercent()\n\n  const {\n    collapsedSize = 0,\n    collapsible,\n    panelSize,\n  } = panelDataHelper(\n    panelDataArray,\n    panelData,\n    layout,\n    panelConstraintsArray ?? undefined,\n  )\n\n  assert(\n    panelSize != null,\n    `Panel size not found for panel \"${panelData.id}\"`,\n  )\n\n  return !collapsible || panelSize > collapsedSize\n}\n\nprovidePanelGroupContext({\n  direction,\n  dragState: dragState.value,\n  groupId,\n  reevaluatePanelConstraints,\n  registerPanel,\n  registerResizeHandle,\n  resizePanel,\n  startDragging,\n  stopDragging,\n  unregisterPanel,\n  panelGroupElement: panelGroupElementRef,\n\n  collapsePanel,\n  expandPanel,\n  isPanelCollapsed,\n  isPanelExpanded,\n  getPanelSize,\n  getPanelStyle,\n})\n\nfunction findPanelDataIndex(panelDataArray: PanelData[], panelData: PanelData) {\n  return panelDataArray.findIndex(\n    prevPanelData =>\n      prevPanelData === panelData || prevPanelData.id === panelData.id,\n  )\n}\n\nfunction panelDataHelper(\n  panelDataArray: PanelData[],\n  panelData: PanelData,\n  layout: number[],\n  panelConstraints?: PanelConstraints[] | null,\n) {\n  const panelIndex = findPanelDataIndex(panelDataArray, panelData)\n\n  const isLastPanel = panelIndex === panelDataArray.length - 1\n  const pivotIndices = isLastPanel\n    ? [panelIndex - 1, panelIndex]\n    : [panelIndex, panelIndex + 1]\n\n  const constraints = panelConstraints ?? getPanelConstraintsInPercent()\n  const panelConstraintsFromGroup = constraints?.[panelIndex]\n\n  const panelSize = layout[panelIndex]\n\n  return {\n    ...(panelConstraintsFromGroup ?? panelData.constraints),\n    panelSize,\n    pivotIndices,\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :style=\"{\n      display: 'flex',\n      flexDirection: direction === 'horizontal' ? 'row' : 'column',\n      height: '100%',\n      overflow: 'hidden',\n      width: '100%',\n    }\"\n    data-panel-group=\"\"\n    :data-orientation=\"direction\"\n    :data-panel-group-id=\"groupId\"\n  >\n    <slot :layout=\"layout\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { CSSProperties, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed, ref, toRefs, watch, watchEffect } from 'vue'\nimport { areEqual, createContext, useDirection, useForwardExpose, useId } from '@/shared'\nimport { useWindowSplitterPanelGroupBehavior } from './utils/composables/useWindowSplitterPanelGroupBehavior'\nimport {\n  initializeDefaultStorage,\n  loadPanelGroupState,\n  savePanelGroupState,\n} from './utils/storage'\n\nexport interface SplitterGroupProps extends PrimitiveProps {\n  /** Group id; falls back to `useId` when not provided. */\n  id?: string | null\n  /** Unique id used to auto-save group arrangement via `localStorage`. */\n  autoSaveId?: string | null\n  /** The group orientation of splitter. */\n  direction: Direction\n  /** Step size when arrow key was pressed. */\n  keyboardResizeBy?: number | null\n  /** Custom storage API; defaults to localStorage */\n  storage?: PanelGroupStorage\n}\n\nexport type SplitterGroupEmits = {\n  /** Event handler called when group layout changes */\n  layout: [val: number[]]\n}\n\nconst LOCAL_STORAGE_DEBOUNCE_INTERVAL = 100\n\nexport type PanelGroupStorage = {\n  getItem: (name: string) => string | null\n  setItem: (name: string, value: string) => void\n}\n\nconst defaultStorage: PanelGroupStorage = {\n  getItem: (name: string) => {\n    initializeDefaultStorage(defaultStorage)\n    return defaultStorage.getItem(name)\n  },\n  setItem: (name: string, value: string) => {\n    initializeDefaultStorage(defaultStorage)\n    defaultStorage.setItem(name, value)\n  },\n}\n\nexport type PanelGroupContext = {\n  direction: Ref<Direction>\n  dragState: DragState | null\n  groupId: string\n  reevaluatePanelConstraints: (panelData: PanelData, prevConstraints: PanelConstraints) => void\n  registerPanel: (panelData: PanelData) => void\n  registerResizeHandle: (dragHandleId: string) => ResizeHandler\n  resizePanel: (panelData: PanelData, size: number) => void\n  startDragging: (dragHandleId: string, event: ResizeEvent) => void\n  stopDragging: () => void\n  unregisterPanel: (panelData: PanelData) => void\n  panelGroupElement: Ref<ParentNode | null>\n\n  // Exposed function for child component\n  collapsePanel: (panelData: PanelData) => void\n  expandPanel: (panelData: PanelData) => void\n  isPanelCollapsed: (panelData: PanelData) => boolean\n  isPanelExpanded: (panelData: PanelData) => boolean\n  getPanelSize: (panelData: PanelData) => number\n  getPanelStyle: (panelData: PanelData, defaultSize: number | undefined) => CSSProperties\n}\n\nexport const [injectPanelGroupContext, providePanelGroupContext] = createContext<PanelGroupContext>('PanelGroup')\n</script>\n\n<script setup lang=\"ts\">\nimport type { PanelConstraints, PanelData } from './SplitterPanel.vue'\n\nimport type { Direction, DragState, ResizeEvent, ResizeHandler } from './utils/types'\nimport { Primitive } from '@/Primitive'\nimport { assert } from './utils/assert'\nimport { calculateDeltaPercentage, calculateUnsafeDefaultLayout } from './utils/calculate'\nimport { callPanelCallbacks } from './utils/callPanelCallbacks'\nimport { fuzzyCompareNumbers } from './utils/compare'\nimport debounce from './utils/debounce'\nimport { getResizeHandleElement } from './utils/dom'\nimport { getResizeEventCursorPosition, isKeyDown, isMouseEvent, isTouchEvent } from './utils/events'\nimport { adjustLayoutByDelta, compareLayouts } from './utils/layout'\nimport { determinePivotIndices } from './utils/pivot'\nimport {\n  EXCEEDED_HORIZONTAL_MAX,\n  EXCEEDED_HORIZONTAL_MIN,\n  EXCEEDED_VERTICAL_MAX,\n  EXCEEDED_VERTICAL_MIN,\n  reportConstraintsViolation,\n} from './utils/registry'\nimport { computePanelFlexBoxStyle } from './utils/style'\nimport { convertPanelConstraintsToPercent, hasPixelSizedPanel, recalculateLayoutForPixelPanels } from './utils/units'\nimport { validatePanelGroupLayout } from './utils/validation'\n\nconst props = withDefaults(defineProps<SplitterGroupProps>(), {\n  autoSaveId: null,\n  keyboardResizeBy: 10,\n  storage: () => defaultStorage,\n})\nconst emits = defineEmits<SplitterGroupEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current size of layout */\n    layout: typeof layout.value\n  }) => any\n}>()\n\nconst debounceMap: {\n  [key: string]: typeof savePanelGroupState\n} = {}\n\nconst { direction } = toRefs(props)\nconst groupId = useId(props.id, 'reka-splitter-group')\nconst dir = useDirection()\nconst { forwardRef, currentElement: panelGroupElementRef } = useForwardExpose()\n\nconst dragState = ref<DragState | null>(null)\nconst groupSizeInPixels = ref<number | null>(null)\nconst groupSizeAtLastLayoutInit = ref<number | null>(null)\nconst layout = ref<number[]>([])\nconst panelIdToLastNotifiedSizeMapRef = ref<Record<string, number>>({})\nconst panelSizeBeforeCollapseRef = ref<Map<string, number>>(new Map())\nconst prevDeltaRef = ref<number>(0)\n\nconst committedValuesRef = computed(() => ({\n  autoSaveId: props.autoSaveId,\n  direction: props.direction,\n  dragState: dragState.value,\n  id: groupId,\n  keyboardResizeBy: props.keyboardResizeBy,\n  storage: props.storage,\n}) satisfies {\n  autoSaveId: string | null\n  direction: Direction\n  dragState: DragState | null\n  id: string\n  keyboardResizeBy: number | null\n  storage: PanelGroupStorage\n})\n\nconst eagerValuesRef = ref<{\n  layout: number[]\n  panelDataArray: PanelData[]\n  panelDataArrayChanged: boolean\n}>({\n  layout: layout.value,\n  panelDataArray: [],\n  panelDataArrayChanged: false,\n})\n\nfunction getGroupSizeInPixels(): number | null {\n  if (groupSizeInPixels.value != null)\n    return groupSizeInPixels.value\n\n  const element = panelGroupElementRef.value\n  if (element && element instanceof HTMLElement) {\n    const rect = element.getBoundingClientRect()\n    const size = direction.value === 'horizontal' ? rect.width : rect.height\n\n    if (!Number.isNaN(size)) {\n      groupSizeInPixels.value = size\n      return size\n    }\n  }\n\n  return null\n}\n\nfunction getPanelConstraintsInPercent(groupSizeOverride?: number | null) {\n  const groupSize = groupSizeOverride ?? getGroupSizeInPixels()\n\n  return convertPanelConstraintsToPercent({\n    panelDataArray: eagerValuesRef.value.panelDataArray,\n    groupSizeInPixels: groupSize,\n  })\n}\n\nfunction getPanelDataWithPercentConstraints(groupSizeOverride?: number | null) {\n  const percentConstraints = getPanelConstraintsInPercent(groupSizeOverride)\n\n  if (!percentConstraints)\n    return null\n\n  return eagerValuesRef.value.panelDataArray.map((panelData, index) => ({\n    ...panelData,\n    constraints: percentConstraints[index],\n  }))\n}\n\nconst setLayout = (val: number[]) => layout.value = val\n\n/** Convert internal layout (always in %) to native units for each panel */\nfunction convertLayoutToNativeUnits(internalLayout: number[]): number[] {\n  const { panelDataArray } = eagerValuesRef.value\n  const groupSize = getGroupSizeInPixels()\n\n  return internalLayout.map((size, index) => {\n    const panelData = panelDataArray[index]\n    if (panelData && (panelData.constraints.sizeUnit ?? '%') === 'px' && groupSize != null) {\n      return (size / 100) * groupSize\n    }\n    return size\n  })\n}\n\nuseWindowSplitterPanelGroupBehavior({\n  eagerValuesRef,\n  groupId,\n  layout,\n  panelDataArray: eagerValuesRef.value.panelDataArray,\n  setLayout,\n  panelGroupElement: panelGroupElementRef,\n  getPanelDataWithPercentConstraints,\n})\n\nwatchEffect((onCleanup) => {\n  const element = panelGroupElementRef.value\n  if (!element)\n    return\n\n  if (typeof ResizeObserver !== 'function')\n    return\n\n  const resizeObserver = new ResizeObserver((entries) => {\n    const entry = entries[0]\n    if (!entry)\n      return\n\n    const { height, width } = entry.contentRect\n    const nextSize = direction.value === 'horizontal' ? width : height\n\n    if (!Number.isNaN(nextSize))\n      groupSizeInPixels.value = nextSize\n  })\n\n  if (element instanceof HTMLElement)\n    resizeObserver.observe(element)\n\n  onCleanup(() => resizeObserver.disconnect())\n})\n\nwatchEffect(() => {\n  const { panelDataArray } = eagerValuesRef.value\n  const { autoSaveId } = props\n  // If this panel has been configured to persist sizing information, save sizes to local storage.\n  if (autoSaveId) {\n    if (layout.value.length === 0 || layout.value.length !== panelDataArray.length)\n      return\n\n    let debouncedSave = debounceMap[autoSaveId]\n\n    // Limit the frequency of localStorage updates.\n    if (!debouncedSave) {\n      debouncedSave = debounce(\n        savePanelGroupState,\n        LOCAL_STORAGE_DEBOUNCE_INTERVAL,\n      )\n\n      debounceMap[autoSaveId] = debouncedSave\n    }\n\n    // Clone mutable data before passing to the debounced function,\n    // else we run the risk of saving an incorrect combination of mutable and immutable values to state.\n    const clonedPanelDataArray = [...panelDataArray]\n    const clonedPanelSizesBeforeCollapse = new Map(\n      panelSizeBeforeCollapseRef.value,\n    )\n\n    debouncedSave(\n      autoSaveId,\n      clonedPanelDataArray,\n      clonedPanelSizesBeforeCollapse,\n      layout.value,\n      props.storage,\n    )\n  }\n})\n\nfunction getPanelStyle(panelData: PanelData, defaultSize: number | undefined) {\n  const { panelDataArray } = eagerValuesRef.value\n\n  const panelIndex = findPanelDataIndex(panelDataArray, panelData)\n\n  return computePanelFlexBoxStyle({\n    defaultSize,\n    dragState: dragState.value,\n    layout: layout.value,\n    panelData: panelDataArray,\n    panelIndex,\n  })\n}\n\nfunction registerPanel(panelData: PanelData) {\n  const { panelDataArray } = eagerValuesRef.value\n\n  panelDataArray.push(panelData)\n  panelDataArray.sort((panelA, panelB) => {\n    const orderA = panelA.order\n    const orderB = panelB.order\n    if (orderA == null && orderB == null)\n      return 0\n    else if (orderA == null)\n      return -1\n    else if (orderB == null)\n      return 1\n    else\n      return orderA - orderB\n  })\n\n  eagerValuesRef.value.panelDataArrayChanged = true\n}\n\n// (Re)calculate group layout whenever panels are registered or unregistered.\n// useIsomorphicLayoutEffect\nwatch(() => eagerValuesRef.value.panelDataArrayChanged, () => {\n  if (eagerValuesRef.value.panelDataArrayChanged) {\n    eagerValuesRef.value.panelDataArrayChanged = false\n\n    const { autoSaveId, storage } = committedValuesRef.value\n    const { layout: prevLayout, panelDataArray } = eagerValuesRef.value\n\n    // If this panel has been configured to persist sizing information,\n    // default size should be restored from local storage if possible.\n    let unsafeLayout: number[] | null = null\n    if (autoSaveId) {\n      const state = loadPanelGroupState(autoSaveId, panelDataArray, storage)\n      if (state) {\n        panelSizeBeforeCollapseRef.value = new Map(\n          Object.entries(state.expandToSizes),\n        )\n        unsafeLayout = state.layout\n      }\n    }\n\n    if (unsafeLayout === null) {\n      const panelDataArrayWithPercentConstraints = getPanelDataWithPercentConstraints()\n      if (!panelDataArrayWithPercentConstraints)\n        return\n\n      unsafeLayout = calculateUnsafeDefaultLayout({\n        panelDataArray: panelDataArrayWithPercentConstraints,\n      })\n    }\n\n    const panelConstraints = getPanelConstraintsInPercent()\n    if (!panelConstraints)\n      return\n\n    // Validate even saved layouts in case something has changed since last render\n    // e.g. for pixel groups, this could be the size of the window\n    const nextLayout = validatePanelGroupLayout({\n      layout: unsafeLayout,\n      panelConstraints,\n    })\n\n    // Track the group size used for this initialization.\n    // Used to detect when a nested px group was measured with an unreliable (too small)\n    // container size before the outer group finished layout.\n    groupSizeAtLastLayoutInit.value = getGroupSizeInPixels()\n\n    if (!areEqual(prevLayout, nextLayout)) {\n      setLayout(nextLayout)\n\n      eagerValuesRef.value.layout = nextLayout\n      emits('layout', convertLayoutToNativeUnits(nextLayout))\n\n      callPanelCallbacks(\n        panelDataArray,\n        nextLayout,\n        panelIdToLastNotifiedSizeMapRef.value,\n        getGroupSizeInPixels(),\n      )\n    }\n  }\n})\n\nwatch(groupSizeInPixels, (nextSize, prevSize) => {\n  if (prevSize == null || nextSize == null)\n    return\n\n  const { layout: prevLayout, panelDataArray } = eagerValuesRef.value\n  if (prevLayout.length === 0)\n    return\n  if (!hasPixelSizedPanel(panelDataArray))\n    return\n\n  // Detect if the layout was initialized with an unreliably small container.\n  // This happens with nested SplitterGroups using sizeUnit=\"px\": the inner group's\n  // ResizeObserver fires before the outer group's flex layout completes, giving a\n  // near-zero container size (e.g. 3.45px). When the outer group finishes and the\n  // container grows to its real size (e.g. 923px), we must re-initialize rather\n  // than recalculate (which would \"preserve\" the garbage pixel sizes from 3.45px).\n  // We guard with initSize < 50 so that legitimately small-but-real containers\n  // (e.g. a sidebar at 60px) are not accidentally re-initialized on normal resizes.\n  const initSize = groupSizeAtLastLayoutInit.value\n  if (initSize != null && initSize > 0 && initSize < 50 && nextSize > initSize * 10) {\n    eagerValuesRef.value.panelDataArrayChanged = true\n    return\n  }\n\n  const recalculatedLayout = recalculateLayoutForPixelPanels({\n    layout: prevLayout,\n    panelDataArray,\n    prevGroupSize: prevSize,\n    nextGroupSize: nextSize,\n  })\n\n  if (!recalculatedLayout)\n    return\n\n  const panelConstraints = getPanelConstraintsInPercent(nextSize)\n  if (!panelConstraints)\n    return\n\n  const nextLayout = validatePanelGroupLayout({\n    layout: recalculatedLayout,\n    panelConstraints,\n  })\n\n  if (!compareLayouts(prevLayout, nextLayout)) {\n    setLayout(nextLayout)\n\n    eagerValuesRef.value.layout = nextLayout\n    emits('layout', convertLayoutToNativeUnits(nextLayout))\n\n    callPanelCallbacks(\n      panelDataArray,\n      nextLayout,\n      panelIdToLastNotifiedSizeMapRef.value,\n      getGroupSizeInPixels(),\n    )\n  }\n})\n\nfunction registerResizeHandle(dragHandleId: string) {\n  return function resizeHandler(event: ResizeEvent) {\n    event.preventDefault()\n    const panelGroupElement = panelGroupElementRef.value\n    if (!panelGroupElement)\n      return () => null\n\n    const { direction, dragState, id: groupId, keyboardResizeBy } = committedValuesRef.value\n    const { layout: prevLayout, panelDataArray } = eagerValuesRef.value\n\n    const { initialLayout } = dragState ?? {}\n\n    const pivotIndices = determinePivotIndices(\n      groupId,\n      dragHandleId,\n      panelGroupElement,\n    )\n\n    let delta = calculateDeltaPercentage(\n      event,\n      dragHandleId,\n      direction,\n      dragState,\n      keyboardResizeBy,\n      panelGroupElement,\n    )\n    if (delta === 0)\n      return\n\n    // Support RTL layouts\n    const isHorizontal = direction === 'horizontal'\n    if (dir.value === 'rtl' && isHorizontal)\n      delta = -delta\n\n    const panelConstraints = getPanelConstraintsInPercent()\n    if (!panelConstraints)\n      return\n\n    const nextLayout = adjustLayoutByDelta({\n      delta,\n      layout: initialLayout ?? prevLayout,\n      panelConstraints,\n      pivotIndices,\n      trigger: isKeyDown(event) ? 'keyboard' : 'mouse-or-touch',\n    })\n\n    const layoutChanged = !compareLayouts(prevLayout, nextLayout)\n\n    // Only update the cursor for layout changes triggered by touch/mouse events (not keyboard)\n    // Update the cursor even if the layout hasn't changed (we may need to show an invalid cursor state)\n    if (isMouseEvent(event) || isTouchEvent(event)) {\n      // Watch for multiple subsequent deltas; this might occur for tiny cursor movements.\n      // In this case, Panel sizes might not change–\n      // but updating cursor in this scenario would cause a flicker.\n      if (prevDeltaRef.value !== delta) {\n        prevDeltaRef.value = delta\n\n        if (!layoutChanged) {\n          // If the pointer has moved too far to resize the panel any further, note this so we can update the cursor.\n          // This mimics VS Code behavior.\n          if (isHorizontal) {\n            reportConstraintsViolation(\n              dragHandleId,\n              delta < 0 ? EXCEEDED_HORIZONTAL_MIN : EXCEEDED_HORIZONTAL_MAX,\n            )\n          }\n          else {\n            reportConstraintsViolation(\n              dragHandleId,\n              delta < 0 ? EXCEEDED_VERTICAL_MIN : EXCEEDED_VERTICAL_MAX,\n            )\n          }\n        }\n        else {\n          reportConstraintsViolation(dragHandleId, 0)\n        }\n      }\n    }\n\n    if (layoutChanged) {\n      setLayout(nextLayout)\n\n      eagerValuesRef.value.layout = nextLayout\n      emits('layout', convertLayoutToNativeUnits(nextLayout))\n\n      callPanelCallbacks(\n        panelDataArray,\n        nextLayout,\n        panelIdToLastNotifiedSizeMapRef.value,\n        getGroupSizeInPixels(),\n      )\n    }\n  }\n}\n\nfunction resizePanel(panelData: PanelData, unsafePanelSize: number) {\n  const { layout: prevLayout, panelDataArray } = eagerValuesRef.value\n\n  const panelConstraintsArray = getPanelConstraintsInPercent()\n  if (!panelConstraintsArray)\n    return\n\n  const panelIndex = findPanelDataIndex(panelDataArray, panelData)\n  const panelUnit = panelData.constraints.sizeUnit ?? '%'\n\n  // Convert px to percent if needed for internal calculation\n  let sizeInPercent = unsafePanelSize\n  if (panelUnit === 'px') {\n    const groupSize = getGroupSizeInPixels()\n    if (groupSize != null) {\n      sizeInPercent = (unsafePanelSize / groupSize) * 100\n    }\n  }\n\n  const { panelSize, pivotIndices } = panelDataHelper(\n    panelDataArray,\n    panelData,\n    prevLayout,\n    panelConstraintsArray,\n  )\n\n  assert(panelSize != null)\n\n  const isLastPanel = panelIndex === panelDataArray.length - 1\n  const delta = isLastPanel\n    ? panelSize - sizeInPercent\n    : sizeInPercent - panelSize\n\n  const nextLayout = adjustLayoutByDelta({\n    delta,\n    layout: prevLayout,\n    panelConstraints: panelConstraintsArray,\n    pivotIndices,\n    trigger: 'imperative-api',\n  })\n\n  if (!compareLayouts(prevLayout, nextLayout)) {\n    setLayout(nextLayout)\n\n    eagerValuesRef.value.layout = nextLayout\n    emits('layout', convertLayoutToNativeUnits(nextLayout))\n\n    callPanelCallbacks(\n      panelDataArray,\n      nextLayout,\n      panelIdToLastNotifiedSizeMapRef.value,\n      getGroupSizeInPixels(),\n    )\n  }\n}\n\nfunction reevaluatePanelConstraints(panelData: PanelData, prevConstraints: PanelConstraints) {\n  const { layout, panelDataArray } = eagerValuesRef.value\n  const index = findPanelDataIndex(panelDataArray, panelData)\n  panelDataArray[index] = panelData\n  eagerValuesRef.value.panelDataArrayChanged = true\n\n  const panelConstraintsArray = getPanelConstraintsInPercent()\n  if (!panelConstraintsArray)\n    return\n\n  const nextConstraints = panelConstraintsArray[index]\n  const { panelSize: prevPanelSize } = panelDataHelper(\n    panelDataArray,\n    panelData,\n    layout,\n    panelConstraintsArray,\n  )\n\n  if (prevPanelSize === null)\n    return\n\n  const nextCollapsedSize = nextConstraints?.collapsedSize ?? 0\n  const nextMaxSize = nextConstraints?.maxSize ?? 100\n  const nextMinSize = nextConstraints?.minSize ?? 0\n\n  if (nextConstraints?.collapsible && isPanelCollapsed(panelData)) {\n    if (prevPanelSize !== nextCollapsedSize)\n      resizePanel(panelData, nextCollapsedSize)\n  }\n  else if (prevPanelSize < nextMinSize) {\n    resizePanel(panelData, nextMinSize)\n  }\n  else if (prevPanelSize > nextMaxSize) {\n    resizePanel(panelData, nextMaxSize)\n  }\n}\n\nfunction startDragging(dragHandleId: string, event: ResizeEvent) {\n  const { direction } = committedValuesRef.value\n  const { layout } = eagerValuesRef.value\n  if (!panelGroupElementRef.value)\n    return\n\n  const handleElement = getResizeHandleElement(\n    dragHandleId,\n    panelGroupElementRef.value,\n  )\n  assert(handleElement)\n\n  const initialCursorPosition = getResizeEventCursorPosition(\n    direction,\n    event,\n  )\n\n  dragState.value = {\n    dragHandleId,\n    dragHandleRect: handleElement.getBoundingClientRect(),\n    initialCursorPosition,\n    initialLayout: layout,\n  }\n}\nfunction stopDragging() {\n  dragState.value = null\n}\n\nfunction unregisterPanel(panelData: PanelData) {\n  const { panelDataArray } = eagerValuesRef.value\n\n  const index = findPanelDataIndex(panelDataArray, panelData)\n  if (index >= 0) {\n    panelDataArray.splice(index, 1)\n\n    // TRICKY\n    // When a panel is removed from the group, we should delete the most recent prev-size entry for it.\n    // If we don't do this, then a conditionally rendered panel might not call onResize when it's re-mounted.\n    // Strict effects mode makes this tricky though because all panels will be registered, unregistered, then re-registered on mount.\n    delete panelIdToLastNotifiedSizeMapRef.value[panelData.id]\n\n    eagerValuesRef.value.panelDataArrayChanged = true\n  }\n}\n\nfunction collapsePanel(panelData: PanelData) {\n  const { layout: prevLayout, panelDataArray } = eagerValuesRef.value\n\n  if (panelData.constraints.collapsible) {\n    const panelConstraintsArray = getPanelConstraintsInPercent()\n    if (!panelConstraintsArray)\n      return\n\n    const {\n      collapsedSize = 0,\n      panelSize,\n      pivotIndices,\n    } = panelDataHelper(panelDataArray, panelData, prevLayout, panelConstraintsArray)\n\n    assert(\n      panelSize != null,\n      `Panel size not found for panel \"${panelData.id}\"`,\n    )\n\n    if (panelSize !== collapsedSize) {\n      // Store size before collapse;\n      // This is the size that gets restored if the expand() API is used.\n      const sizeUnit = panelData.constraints.sizeUnit ?? '%'\n      const groupSize = groupSizeInPixels.value ?? getGroupSizeInPixels()\n      const sizeBeforeCollapse = sizeUnit === 'px' && groupSize\n        ? (panelSize / 100) * groupSize\n        : panelSize\n\n      panelSizeBeforeCollapseRef.value.set(panelData.id, sizeBeforeCollapse)\n\n      const isLastPanel\n        = findPanelDataIndex(panelDataArray, panelData)\n          === panelDataArray.length - 1\n      const delta = isLastPanel\n        ? panelSize - collapsedSize\n        : collapsedSize - panelSize\n\n      const nextLayout = adjustLayoutByDelta({\n        delta,\n        layout: prevLayout,\n        panelConstraints: panelConstraintsArray,\n        pivotIndices,\n        trigger: 'imperative-api',\n      })\n\n      if (!compareLayouts(prevLayout, nextLayout)) {\n        setLayout(nextLayout)\n\n        eagerValuesRef.value.layout = nextLayout\n\n        emits('layout', convertLayoutToNativeUnits(nextLayout))\n\n        callPanelCallbacks(\n          panelDataArray,\n          nextLayout,\n          panelIdToLastNotifiedSizeMapRef.value,\n          getGroupSizeInPixels(),\n        )\n      }\n    }\n  }\n}\n\nfunction expandPanel(panelData: PanelData) {\n  const { layout: prevLayout, panelDataArray } = eagerValuesRef.value\n\n  if (panelData.constraints.collapsible) {\n    const panelConstraintsArray = getPanelConstraintsInPercent()\n    if (!panelConstraintsArray)\n      return\n\n    const {\n      collapsedSize = 0,\n      panelSize = 0,\n      minSize = 0,\n      pivotIndices,\n    } = panelDataHelper(panelDataArray, panelData, prevLayout, panelConstraintsArray)\n\n    if (fuzzyCompareNumbers(panelSize, collapsedSize) <= 0) {\n      // Restore this panel to the size it was before it was collapsed, if possible.\n      const prevPanelSize = panelSizeBeforeCollapseRef.value.get(\n        panelData.id,\n      )\n      const sizeUnit = panelData.constraints.sizeUnit ?? '%'\n      const groupSize = groupSizeInPixels.value ?? getGroupSizeInPixels()\n\n      const restoredSize\n        = sizeUnit === 'px' && groupSize\n          ? prevPanelSize != null\n            ? (prevPanelSize / groupSize) * 100\n            : null\n          : prevPanelSize\n\n      const baseSize\n        = restoredSize != null && restoredSize >= minSize\n          ? restoredSize\n          : minSize\n\n      const isLastPanel\n        = findPanelDataIndex(panelDataArray, panelData)\n          === panelDataArray.length - 1\n      const delta = isLastPanel ? panelSize - baseSize : baseSize - panelSize\n\n      const nextLayout = adjustLayoutByDelta({\n        delta,\n        layout: prevLayout,\n        panelConstraints: panelConstraintsArray,\n        pivotIndices,\n        trigger: 'imperative-api',\n      })\n\n      if (!compareLayouts(prevLayout, nextLayout)) {\n        setLayout(nextLayout)\n\n        eagerValuesRef.value.layout = nextLayout\n\n        emits('layout', convertLayoutToNativeUnits(nextLayout))\n\n        callPanelCallbacks(\n          panelDataArray,\n          nextLayout,\n          panelIdToLastNotifiedSizeMapRef.value,\n          getGroupSizeInPixels(),\n        )\n      }\n    }\n  }\n}\n\nfunction getPanelSize(panelData: PanelData) {\n  const { layout, panelDataArray } = eagerValuesRef.value\n\n  const { panelSize } = panelDataHelper(panelDataArray, panelData, layout)\n\n  assert(\n    panelSize != null,\n    `Panel size not found for panel \"${panelData.id}\"`,\n  )\n\n  // If the panel uses px units, convert from percent back to px\n  const panelUnit = panelData.constraints.sizeUnit ?? '%'\n  if (panelUnit === 'px') {\n    const groupSize = getGroupSizeInPixels()\n    if (groupSize != null) {\n      return (panelSize / 100) * groupSize\n    }\n  }\n\n  return panelSize\n}\n\nfunction isPanelCollapsed(panelData: PanelData) {\n  const { layout, panelDataArray } = eagerValuesRef.value\n\n  const panelConstraintsArray = getPanelConstraintsInPercent()\n\n  const {\n    collapsedSize = 0,\n    collapsible,\n    panelSize,\n  } = panelDataHelper(\n    panelDataArray,\n    panelData,\n    layout,\n    panelConstraintsArray ?? undefined,\n  )\n\n  if (!collapsible)\n    return false\n\n  // panelSize is undefined during ssr due to vue ssr reactivity limitation.\n  if (panelSize === undefined) {\n    const panelIndex = findPanelDataIndex(panelDataArray, panelData)\n    const constraints = panelConstraintsArray?.[panelIndex] ?? panelData.constraints\n    return constraints.defaultSize === constraints.collapsedSize\n  }\n  else {\n    return panelSize === collapsedSize\n  }\n}\n\nfunction isPanelExpanded(panelData: PanelData) {\n  const { layout, panelDataArray } = eagerValuesRef.value\n\n  const panelConstraintsArray = getPanelConstraintsInPercent()\n\n  const {\n    collapsedSize = 0,\n    collapsible,\n    panelSize,\n  } = panelDataHelper(\n    panelDataArray,\n    panelData,\n    layout,\n    panelConstraintsArray ?? undefined,\n  )\n\n  assert(\n    panelSize != null,\n    `Panel size not found for panel \"${panelData.id}\"`,\n  )\n\n  return !collapsible || panelSize > collapsedSize\n}\n\nprovidePanelGroupContext({\n  direction,\n  dragState: dragState.value,\n  groupId,\n  reevaluatePanelConstraints,\n  registerPanel,\n  registerResizeHandle,\n  resizePanel,\n  startDragging,\n  stopDragging,\n  unregisterPanel,\n  panelGroupElement: panelGroupElementRef,\n\n  collapsePanel,\n  expandPanel,\n  isPanelCollapsed,\n  isPanelExpanded,\n  getPanelSize,\n  getPanelStyle,\n})\n\nfunction findPanelDataIndex(panelDataArray: PanelData[], panelData: PanelData) {\n  return panelDataArray.findIndex(\n    prevPanelData =>\n      prevPanelData === panelData || prevPanelData.id === panelData.id,\n  )\n}\n\nfunction panelDataHelper(\n  panelDataArray: PanelData[],\n  panelData: PanelData,\n  layout: number[],\n  panelConstraints?: PanelConstraints[] | null,\n) {\n  const panelIndex = findPanelDataIndex(panelDataArray, panelData)\n\n  const isLastPanel = panelIndex === panelDataArray.length - 1\n  const pivotIndices = isLastPanel\n    ? [panelIndex - 1, panelIndex]\n    : [panelIndex, panelIndex + 1]\n\n  const constraints = panelConstraints ?? getPanelConstraintsInPercent()\n  const panelConstraintsFromGroup = constraints?.[panelIndex]\n\n  const panelSize = layout[panelIndex]\n\n  return {\n    ...(panelConstraintsFromGroup ?? panelData.constraints),\n    panelSize,\n    pivotIndices,\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :style=\"{\n      display: 'flex',\n      flexDirection: direction === 'horizontal' ? 'row' : 'column',\n      height: '100%',\n      overflow: 'hidden',\n      width: '100%',\n    }\"\n    data-panel-group=\"\"\n    :data-orientation=\"direction\"\n    :data-panel-group-id=\"groupId\"\n  >\n    <slot :layout=\"layout\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useId } from '@/shared'\nimport { PRECISION } from './utils/constants'\n\nexport interface SplitterPanelProps extends PrimitiveProps {\n  /** The size of panel when it is collapsed; interpreted using `sizeUnit`. */\n  collapsedSize?: number\n  /** Should panel collapse when resized beyond its `minSize`. When `true`, it will be collapsed to `collapsedSize`. */\n  collapsible?: boolean\n  /** Initial size of panel, interpreted using `sizeUnit` (percent by default). */\n  defaultSize?: number\n  /** Panel id (unique within group); falls back to `useId` when not provided */\n  id?: string\n  /** The maximum allowable size of panel, interpreted using `sizeUnit`; defaults to `100` (percent). */\n  maxSize?: number\n  /** The minimum allowable size of panel, interpreted using `sizeUnit`; defaults to `10` (percent). */\n  minSize?: number\n  /** The order of panel within group; required for groups with conditionally rendered panels */\n  order?: number\n  /** Unit used for sizing values; `%` by default, or `px` for fixed sizing. */\n  sizeUnit?: '%' | 'px'\n}\n\nexport type SplitterPanelEmits = {\n  /** Event handler called when panel is collapsed. */\n  collapse: []\n  /** Event handler called when panel is expanded. */\n  expand: []\n  /** Event handler called when panel is resized; size parameter is a numeric value between 1-100.  */\n  resize: [size: number, prevSize: number | undefined]\n}\n\nexport type PanelOnCollapse = () => void\nexport type PanelOnExpand = () => void\nexport type PanelOnResize = (\n  size: number,\n  prevSize: number | undefined,\n) => void\n\nexport type PanelCallbacks = {\n  onCollapse?: PanelOnCollapse\n  onExpand?: PanelOnExpand\n  onResize?: PanelOnResize\n}\n\nexport type PanelConstraints = {\n  collapsedSize?: number | undefined\n  collapsible?: boolean | undefined\n  defaultSize?: number | undefined\n  /** Panel id (unique within group); falls back to useId when not provided */\n  maxSize?: number | undefined\n  minSize?: number | undefined\n  sizeUnit?: '%' | 'px' | undefined\n}\n\nexport type PanelData = {\n  callbacks: PanelCallbacks\n  constraints: PanelConstraints\n  id: string\n  idIsFromProps: boolean\n  order: number | undefined\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted, onUnmounted, watch } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPanelGroupContext } from './SplitterGroup.vue'\n\nconst props = defineProps<SplitterPanelProps>()\nconst emits = defineEmits<SplitterPanelEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Is the panel collapsed */\n    isCollapsed: typeof isCollapsed.value\n    /** Is the panel expanded */\n    isExpanded: typeof isExpanded.value\n    /** If panel is `collapsible`, collapse it fully. */\n    collapse: typeof collapse\n    /** If panel is currently collapsed, expand it to its most recent size. */\n    expand: typeof expand\n    /** Resize panel to the specified percentage (1 - 100). */\n    resize: typeof resize\n  }) => any\n}>()\n\nconst panelGroupContext = injectPanelGroupContext()\nif (panelGroupContext === null) {\n  throw new Error(\n    'SplitterPanel components must be rendered within a SplitterGroup container',\n  )\n}\n\nconst { collapsePanel, expandPanel, getPanelSize, getPanelStyle, isPanelCollapsed, resizePanel, groupId, reevaluatePanelConstraints, registerPanel, unregisterPanel } = panelGroupContext\nconst panelId = useId(props.id, 'reka-splitter-panel')\n\nconst panelDataRef = computed(() => ({\n  callbacks: {\n    onCollapse: () => emits('collapse'),\n    onExpand: () => emits('expand'),\n    onResize: (...args) => emits('resize', ...args),\n  },\n  constraints: {\n    collapsedSize: props.collapsedSize && Number.parseFloat(props.collapsedSize.toFixed(PRECISION)),\n    collapsible: props.collapsible,\n    defaultSize: props.defaultSize,\n    /** Panel id (unique within group); falls back to useId when not provided */\n    /** Panel id (unique within group); falls back to useId when not provided */\n    maxSize: props.maxSize,\n    minSize: props.minSize,\n    sizeUnit: props.sizeUnit ?? '%',\n  },\n  id: panelId,\n  idIsFromProps: props.id !== undefined,\n  order: props.order,\n}) satisfies PanelData)\n\nwatch(() => panelDataRef.value.constraints, (constraints, prevConstraints) => {\n  // If constraints have changed, we should revisit panel sizes.\n  // This is uncommon but may happen if people are trying to implement pixel based constraints.\n  if (\n    prevConstraints.collapsedSize !== constraints.collapsedSize\n    || prevConstraints.collapsible !== constraints.collapsible\n    || prevConstraints.maxSize !== constraints.maxSize\n    || prevConstraints.minSize !== constraints.minSize\n    || prevConstraints.sizeUnit !== constraints.sizeUnit\n  ) {\n    reevaluatePanelConstraints(panelDataRef.value, prevConstraints)\n  }\n}, { deep: true })\n\nonMounted(() => {\n  registerPanel(panelDataRef.value)\n})\n\nonUnmounted(() => {\n  unregisterPanel(panelDataRef.value)\n})\n\nconst style = computed(() => getPanelStyle(panelDataRef.value, props.defaultSize))\n/** Panel id (unique within group); falls back to useId when not provided */\n\nconst isCollapsed = computed(() => isPanelCollapsed(panelDataRef.value))\nconst isExpanded = computed(() => !isCollapsed.value)\n\nfunction collapse() {\n  collapsePanel(panelDataRef.value)\n}\n\nfunction expand() {\n  expandPanel(panelDataRef.value)\n}\n\nfunction resize(size: number) {\n  resizePanel(panelDataRef.value, size)\n}\n\ndefineExpose({\n  /** If panel is `collapsible`, collapse it fully. */\n  collapse,\n  /** If panel is currently collapsed, expand it to its most recent size. */\n  expand,\n  /** Gets the current size of the panel (in the panel's sizeUnit: percentage for '%', pixels for 'px'). */\n  getSize() {\n    return getPanelSize(panelDataRef.value)\n  },\n  /** Resize panel to the specified size (in the panel's sizeUnit: percentage for '%', pixels for 'px'). */\n  resize,\n  /** Returns `true` if the panel is currently collapsed */\n  isCollapsed,\n  /** Returns `true` if the panel is currently not collapsed */\n  isExpanded,\n})\n</script>\n\n<template>\n  <Primitive\n    :id=\"panelId\"\n    :style=\"style\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    data-panel=\"\"\n    :data-panel-collapsible=\"collapsible || undefined\"\n    :data-panel-group-id=\"groupId\"\n    :data-panel-id=\"panelId\"\n    :data-panel-size=\" Number.parseFloat(`${style.flexGrow}`).toFixed(1)\"\n    :data-state=\"collapsible ? isCollapsed ? 'collapsed' : 'expanded' : undefined\"\n  >\n    <slot\n      :is-collapsed=\"isCollapsed\"\n      :is-expanded=\"isExpanded\"\n      :expand=\"expand\"\n      :collapse=\"collapse\"\n      :resize=\"resize\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useId } from '@/shared'\nimport { PRECISION } from './utils/constants'\n\nexport interface SplitterPanelProps extends PrimitiveProps {\n  /** The size of panel when it is collapsed; interpreted using `sizeUnit`. */\n  collapsedSize?: number\n  /** Should panel collapse when resized beyond its `minSize`. When `true`, it will be collapsed to `collapsedSize`. */\n  collapsible?: boolean\n  /** Initial size of panel, interpreted using `sizeUnit` (percent by default). */\n  defaultSize?: number\n  /** Panel id (unique within group); falls back to `useId` when not provided */\n  id?: string\n  /** The maximum allowable size of panel, interpreted using `sizeUnit`; defaults to `100` (percent). */\n  maxSize?: number\n  /** The minimum allowable size of panel, interpreted using `sizeUnit`; defaults to `10` (percent). */\n  minSize?: number\n  /** The order of panel within group; required for groups with conditionally rendered panels */\n  order?: number\n  /** Unit used for sizing values; `%` by default, or `px` for fixed sizing. */\n  sizeUnit?: '%' | 'px'\n}\n\nexport type SplitterPanelEmits = {\n  /** Event handler called when panel is collapsed. */\n  collapse: []\n  /** Event handler called when panel is expanded. */\n  expand: []\n  /** Event handler called when panel is resized; size parameter is a numeric value between 1-100.  */\n  resize: [size: number, prevSize: number | undefined]\n}\n\nexport type PanelOnCollapse = () => void\nexport type PanelOnExpand = () => void\nexport type PanelOnResize = (\n  size: number,\n  prevSize: number | undefined,\n) => void\n\nexport type PanelCallbacks = {\n  onCollapse?: PanelOnCollapse\n  onExpand?: PanelOnExpand\n  onResize?: PanelOnResize\n}\n\nexport type PanelConstraints = {\n  collapsedSize?: number | undefined\n  collapsible?: boolean | undefined\n  defaultSize?: number | undefined\n  /** Panel id (unique within group); falls back to useId when not provided */\n  maxSize?: number | undefined\n  minSize?: number | undefined\n  sizeUnit?: '%' | 'px' | undefined\n}\n\nexport type PanelData = {\n  callbacks: PanelCallbacks\n  constraints: PanelConstraints\n  id: string\n  idIsFromProps: boolean\n  order: number | undefined\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted, onUnmounted, watch } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectPanelGroupContext } from './SplitterGroup.vue'\n\nconst props = defineProps<SplitterPanelProps>()\nconst emits = defineEmits<SplitterPanelEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Is the panel collapsed */\n    isCollapsed: typeof isCollapsed.value\n    /** Is the panel expanded */\n    isExpanded: typeof isExpanded.value\n    /** If panel is `collapsible`, collapse it fully. */\n    collapse: typeof collapse\n    /** If panel is currently collapsed, expand it to its most recent size. */\n    expand: typeof expand\n    /** Resize panel to the specified percentage (1 - 100). */\n    resize: typeof resize\n  }) => any\n}>()\n\nconst panelGroupContext = injectPanelGroupContext()\nif (panelGroupContext === null) {\n  throw new Error(\n    'SplitterPanel components must be rendered within a SplitterGroup container',\n  )\n}\n\nconst { collapsePanel, expandPanel, getPanelSize, getPanelStyle, isPanelCollapsed, resizePanel, groupId, reevaluatePanelConstraints, registerPanel, unregisterPanel } = panelGroupContext\nconst panelId = useId(props.id, 'reka-splitter-panel')\n\nconst panelDataRef = computed(() => ({\n  callbacks: {\n    onCollapse: () => emits('collapse'),\n    onExpand: () => emits('expand'),\n    onResize: (...args) => emits('resize', ...args),\n  },\n  constraints: {\n    collapsedSize: props.collapsedSize && Number.parseFloat(props.collapsedSize.toFixed(PRECISION)),\n    collapsible: props.collapsible,\n    defaultSize: props.defaultSize,\n    /** Panel id (unique within group); falls back to useId when not provided */\n    /** Panel id (unique within group); falls back to useId when not provided */\n    maxSize: props.maxSize,\n    minSize: props.minSize,\n    sizeUnit: props.sizeUnit ?? '%',\n  },\n  id: panelId,\n  idIsFromProps: props.id !== undefined,\n  order: props.order,\n}) satisfies PanelData)\n\nwatch(() => panelDataRef.value.constraints, (constraints, prevConstraints) => {\n  // If constraints have changed, we should revisit panel sizes.\n  // This is uncommon but may happen if people are trying to implement pixel based constraints.\n  if (\n    prevConstraints.collapsedSize !== constraints.collapsedSize\n    || prevConstraints.collapsible !== constraints.collapsible\n    || prevConstraints.maxSize !== constraints.maxSize\n    || prevConstraints.minSize !== constraints.minSize\n    || prevConstraints.sizeUnit !== constraints.sizeUnit\n  ) {\n    reevaluatePanelConstraints(panelDataRef.value, prevConstraints)\n  }\n}, { deep: true })\n\nonMounted(() => {\n  registerPanel(panelDataRef.value)\n})\n\nonUnmounted(() => {\n  unregisterPanel(panelDataRef.value)\n})\n\nconst style = computed(() => getPanelStyle(panelDataRef.value, props.defaultSize))\n/** Panel id (unique within group); falls back to useId when not provided */\n\nconst isCollapsed = computed(() => isPanelCollapsed(panelDataRef.value))\nconst isExpanded = computed(() => !isCollapsed.value)\n\nfunction collapse() {\n  collapsePanel(panelDataRef.value)\n}\n\nfunction expand() {\n  expandPanel(panelDataRef.value)\n}\n\nfunction resize(size: number) {\n  resizePanel(panelDataRef.value, size)\n}\n\ndefineExpose({\n  /** If panel is `collapsible`, collapse it fully. */\n  collapse,\n  /** If panel is currently collapsed, expand it to its most recent size. */\n  expand,\n  /** Gets the current size of the panel (in the panel's sizeUnit: percentage for '%', pixels for 'px'). */\n  getSize() {\n    return getPanelSize(panelDataRef.value)\n  },\n  /** Resize panel to the specified size (in the panel's sizeUnit: percentage for '%', pixels for 'px'). */\n  resize,\n  /** Returns `true` if the panel is currently collapsed */\n  isCollapsed,\n  /** Returns `true` if the panel is currently not collapsed */\n  isExpanded,\n})\n</script>\n\n<template>\n  <Primitive\n    :id=\"panelId\"\n    :style=\"style\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    data-panel=\"\"\n    :data-panel-collapsible=\"collapsible || undefined\"\n    :data-panel-group-id=\"groupId\"\n    :data-panel-id=\"panelId\"\n    :data-panel-size=\" Number.parseFloat(`${style.flexGrow}`).toFixed(1)\"\n    :data-state=\"collapsible ? isCollapsed ? 'collapsed' : 'expanded' : undefined\"\n  >\n    <slot\n      :is-collapsed=\"isCollapsed\"\n      :is-expanded=\"isExpanded\"\n      :expand=\"expand\"\n      :collapse=\"collapse\"\n      :resize=\"resize\"\n    />\n  </Primitive>\n</template>\n","import type { Ref } from 'vue'\nimport type { ResizeHandler } from '../types'\nimport { watchEffect } from 'vue'\nimport { assert } from '../assert'\nimport { getResizeHandleElement, getResizeHandleElementIndex, getResizeHandleElementsForGroup } from '../dom'\n\n// https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/\n\nexport function useWindowSplitterResizeHandlerBehavior({\n  disabled,\n  handleId,\n  resizeHandler,\n  panelGroupElement,\n}: {\n  disabled: Ref<boolean>\n  handleId: string\n  resizeHandler: Ref<ResizeHandler | null>\n  panelGroupElement: Ref<ParentNode | null>\n}): void {\n  watchEffect((onCleanup) => {\n    const _panelGroupElement = panelGroupElement.value\n    if (disabled.value || resizeHandler.value === null || _panelGroupElement === null)\n      return\n\n    const handleElement = getResizeHandleElement(handleId, _panelGroupElement)\n    if (handleElement == null)\n      return\n\n    const onKeyDown = (event: KeyboardEvent) => {\n      if (event.defaultPrevented)\n        return\n\n      switch (event.key) {\n        case 'ArrowDown':\n        case 'ArrowLeft':\n        case 'ArrowRight':\n        case 'ArrowUp':\n        case 'End':\n        case 'Home': {\n          event.preventDefault()\n\n          resizeHandler.value?.(event)\n          break\n        }\n        case 'F6': {\n          event.preventDefault()\n\n          const groupId = handleElement.getAttribute('data-panel-group-id')\n          assert(groupId)\n\n          const handles = getResizeHandleElementsForGroup(\n            groupId,\n            _panelGroupElement,\n          )\n          const index = getResizeHandleElementIndex(\n            groupId,\n            handleId,\n            _panelGroupElement,\n          )\n\n          assert(index !== null)\n\n          const nextIndex = event.shiftKey\n            ? index > 0\n              ? index - 1\n              : handles.length - 1\n            : index + 1 < handles.length\n              ? index + 1\n              : 0\n\n          const nextHandle = handles[nextIndex] as HTMLElement\n          nextHandle.focus()\n\n          break\n        }\n      }\n    }\n\n    handleElement.addEventListener('keydown', onKeyDown)\n    onCleanup(() => {\n      handleElement.removeEventListener('keydown', onKeyDown)\n    })\n  })\n}\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { ref, toRefs, watch, watchEffect } from 'vue'\nimport { useNonce } from '@/shared/useNonce'\nimport { useWindowSplitterResizeHandlerBehavior } from './utils/composables/useWindowSplitterBehavior'\n\nexport interface SplitterResizeHandleProps extends PrimitiveProps {\n  /** Resize handle id (unique within group); falls back to `useId` when not provided */\n  id?: string\n  /** Allow this much margin when determining resizable handle hit detection */\n  hitAreaMargins?: PointerHitAreaMargins\n  /** Tabindex for the handle */\n  tabindex?: number\n  /** Disable drag handle */\n  disabled?: boolean\n  /**\n   * Will add `nonce` attribute to the style tag which can be used by Content Security Policy. <br> If omitted, inherits globally from `ConfigProvider`.\n   */\n  nonce?: string\n}\n\nexport type PanelResizeHandleOnDragging = (isDragging: boolean) => void\nexport type ResizeHandlerState = 'drag' | 'hover' | 'inactive'\n\nexport type SplitterResizeHandleEmits = {\n  /** Event handler called when dragging the handler. */\n  dragging: [isDragging: boolean]\n}\n</script>\n\n<script setup lang=\"ts\">\nimport type { PointerHitAreaMargins, ResizeHandlerAction } from './utils/registry'\nimport type { ResizeEvent, ResizeHandler } from './utils/types'\nimport { Primitive } from '@/Primitive'\nimport { isBrowser, useForwardExpose, useId } from '@/shared'\nimport { injectPanelGroupContext } from './SplitterGroup.vue'\nimport { assert } from './utils/assert'\nimport { registerResizeHandle } from './utils/registry'\n\nconst props = withDefaults(defineProps<SplitterResizeHandleProps>(), {\n  tabindex: 0,\n})\nconst emits = defineEmits<SplitterResizeHandleEmits>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { disabled } = toRefs(props)\n\nconst panelGroupContext = injectPanelGroupContext()\nif (panelGroupContext === null) {\n  throw new Error(\n    'PanelResizeHandle components must be rendered within a PanelGroup container',\n  )\n}\n\nconst {\n  direction,\n  groupId,\n  registerResizeHandle: registerResizeHandleWithParentGroup,\n  startDragging,\n  stopDragging,\n  panelGroupElement,\n} = panelGroupContext\n\nconst resizeHandleId = useId(props.id, 'reka-splitter-resize-handle')\nconst state = ref<ResizeHandlerState>('inactive')\nconst isFocused = ref(false)\nconst resizeHandler = ref<ResizeHandler | null>(null)\nconst { nonce: propNonce } = toRefs(props)\nconst nonce = useNonce(propNonce)\n\nwatch(disabled, () => {\n  if (!isBrowser)\n    return\n  if (disabled.value)\n    resizeHandler.value = null\n  else\n    resizeHandler.value = registerResizeHandleWithParentGroup(resizeHandleId)\n}, { immediate: true })\n\nwatchEffect((onCleanup) => {\n  if (disabled.value || resizeHandler.value === null)\n    return\n\n  const element = currentElement.value\n  if (!element)\n    return\n\n  assert(element)\n\n  const setResizeHandlerState = (\n    action: ResizeHandlerAction,\n    isActive: boolean,\n    event: ResizeEvent,\n  ) => {\n    if (isActive) {\n      switch (action) {\n        case 'down': {\n          state.value = 'drag'\n\n          startDragging(resizeHandleId, event)\n          emits('dragging', true)\n          break\n        }\n        case 'move': {\n          if (state.value !== 'drag')\n            state.value = 'hover'\n\n          resizeHandler.value?.(event)\n          break\n        }\n        case 'up': {\n          state.value = 'hover'\n\n          stopDragging()\n          emits('dragging', false)\n          break\n        }\n      }\n    }\n    else {\n      state.value = 'inactive'\n    }\n  }\n\n  onCleanup(registerResizeHandle(\n    resizeHandleId,\n    element,\n    direction,\n    {\n      // Coarse inputs (e.g. finger/touch)\n      coarse: props.hitAreaMargins?.coarse ?? 15,\n      // Fine inputs (e.g. mouse)\n      fine: props.hitAreaMargins?.fine ?? 5,\n    },\n    nonce,\n    setResizeHandlerState,\n  ))\n})\n\nuseWindowSplitterResizeHandlerBehavior({\n  disabled,\n  resizeHandler,\n  handleId: resizeHandleId,\n  panelGroupElement,\n})\n</script>\n\n<template>\n  <Primitive\n    :id=\"resizeHandleId\"\n    :ref=\"forwardRef\"\n    :style=\"{\n      touchAction: 'none',\n      userSelect: 'none',\n    }\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"separator\"\n    data-resize-handle=\"\"\n    :tabindex=\"tabindex\"\n    :data-state=\"state\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-orientation=\"direction\"\n    :data-panel-group-id=\"groupId\"\n    :data-resize-handle-active=\"state === 'drag' ? 'pointer' : isFocused ? 'keyboard' : undefined\"\n    :data-resize-handle-state=\"state\"\n    :data-panel-resize-handle-enabled=\"!disabled\"\n    :data-panel-resize-handle-id=\" resizeHandleId\"\n    @blur=\"isFocused = false\"\n    @focus=\"isFocused = false\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { ref, toRefs, watch, watchEffect } from 'vue'\nimport { useNonce } from '@/shared/useNonce'\nimport { useWindowSplitterResizeHandlerBehavior } from './utils/composables/useWindowSplitterBehavior'\n\nexport interface SplitterResizeHandleProps extends PrimitiveProps {\n  /** Resize handle id (unique within group); falls back to `useId` when not provided */\n  id?: string\n  /** Allow this much margin when determining resizable handle hit detection */\n  hitAreaMargins?: PointerHitAreaMargins\n  /** Tabindex for the handle */\n  tabindex?: number\n  /** Disable drag handle */\n  disabled?: boolean\n  /**\n   * Will add `nonce` attribute to the style tag which can be used by Content Security Policy. <br> If omitted, inherits globally from `ConfigProvider`.\n   */\n  nonce?: string\n}\n\nexport type PanelResizeHandleOnDragging = (isDragging: boolean) => void\nexport type ResizeHandlerState = 'drag' | 'hover' | 'inactive'\n\nexport type SplitterResizeHandleEmits = {\n  /** Event handler called when dragging the handler. */\n  dragging: [isDragging: boolean]\n}\n</script>\n\n<script setup lang=\"ts\">\nimport type { PointerHitAreaMargins, ResizeHandlerAction } from './utils/registry'\nimport type { ResizeEvent, ResizeHandler } from './utils/types'\nimport { Primitive } from '@/Primitive'\nimport { isBrowser, useForwardExpose, useId } from '@/shared'\nimport { injectPanelGroupContext } from './SplitterGroup.vue'\nimport { assert } from './utils/assert'\nimport { registerResizeHandle } from './utils/registry'\n\nconst props = withDefaults(defineProps<SplitterResizeHandleProps>(), {\n  tabindex: 0,\n})\nconst emits = defineEmits<SplitterResizeHandleEmits>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { disabled } = toRefs(props)\n\nconst panelGroupContext = injectPanelGroupContext()\nif (panelGroupContext === null) {\n  throw new Error(\n    'PanelResizeHandle components must be rendered within a PanelGroup container',\n  )\n}\n\nconst {\n  direction,\n  groupId,\n  registerResizeHandle: registerResizeHandleWithParentGroup,\n  startDragging,\n  stopDragging,\n  panelGroupElement,\n} = panelGroupContext\n\nconst resizeHandleId = useId(props.id, 'reka-splitter-resize-handle')\nconst state = ref<ResizeHandlerState>('inactive')\nconst isFocused = ref(false)\nconst resizeHandler = ref<ResizeHandler | null>(null)\nconst { nonce: propNonce } = toRefs(props)\nconst nonce = useNonce(propNonce)\n\nwatch(disabled, () => {\n  if (!isBrowser)\n    return\n  if (disabled.value)\n    resizeHandler.value = null\n  else\n    resizeHandler.value = registerResizeHandleWithParentGroup(resizeHandleId)\n}, { immediate: true })\n\nwatchEffect((onCleanup) => {\n  if (disabled.value || resizeHandler.value === null)\n    return\n\n  const element = currentElement.value\n  if (!element)\n    return\n\n  assert(element)\n\n  const setResizeHandlerState = (\n    action: ResizeHandlerAction,\n    isActive: boolean,\n    event: ResizeEvent,\n  ) => {\n    if (isActive) {\n      switch (action) {\n        case 'down': {\n          state.value = 'drag'\n\n          startDragging(resizeHandleId, event)\n          emits('dragging', true)\n          break\n        }\n        case 'move': {\n          if (state.value !== 'drag')\n            state.value = 'hover'\n\n          resizeHandler.value?.(event)\n          break\n        }\n        case 'up': {\n          state.value = 'hover'\n\n          stopDragging()\n          emits('dragging', false)\n          break\n        }\n      }\n    }\n    else {\n      state.value = 'inactive'\n    }\n  }\n\n  onCleanup(registerResizeHandle(\n    resizeHandleId,\n    element,\n    direction,\n    {\n      // Coarse inputs (e.g. finger/touch)\n      coarse: props.hitAreaMargins?.coarse ?? 15,\n      // Fine inputs (e.g. mouse)\n      fine: props.hitAreaMargins?.fine ?? 5,\n    },\n    nonce,\n    setResizeHandlerState,\n  ))\n})\n\nuseWindowSplitterResizeHandlerBehavior({\n  disabled,\n  resizeHandler,\n  handleId: resizeHandleId,\n  panelGroupElement,\n})\n</script>\n\n<template>\n  <Primitive\n    :id=\"resizeHandleId\"\n    :ref=\"forwardRef\"\n    :style=\"{\n      touchAction: 'none',\n      userSelect: 'none',\n    }\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"separator\"\n    data-resize-handle=\"\"\n    :tabindex=\"tabindex\"\n    :data-state=\"state\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-orientation=\"direction\"\n    :data-panel-group-id=\"groupId\"\n    :data-resize-handle-active=\"state === 'drag' ? 'pointer' : isFocused ? 'keyboard' : undefined\"\n    :data-resize-handle-state=\"state\"\n    :data-panel-resize-handle-enabled=\"!disabled\"\n    :data-panel-resize-handle-id=\" resizeHandleId\"\n    @blur=\"isFocused = false\"\n    @focus=\"isFocused = false\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { DataOrientation, Direction } from '../shared/types'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, ref, toRefs, watch } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\nexport interface StepperRootContext {\n  modelValue: Ref<number | undefined>\n  changeModelValue: (value: number) => void\n  orientation: Ref<DataOrientation>\n  dir: Ref<Direction>\n  linear: Ref<boolean>\n  totalStepperItems: Ref<Set<HTMLElement>>\n}\n\nexport interface StepperRootProps extends PrimitiveProps {\n  /**\n   * The value of the step that should be active when initially rendered. Use when you do not need to control the state of the steps.\n   */\n  defaultValue?: number\n  /**\n   * The orientation the steps are laid out.\n   * Mainly so arrow navigation is done accordingly (left & right vs. up & down).\n   * @defaultValue horizontal\n   */\n  orientation?: DataOrientation\n  /**\n   * The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode.\n   */\n  dir?: Direction\n  /** The controlled value of the step to activate. Can be bound as `v-model`. */\n  modelValue?: number\n  /** Whether or not the steps must be completed in order. */\n  linear?: boolean\n}\nexport type StepperRootEmits = {\n  /** Event handler called when the value changes */\n  'update:modelValue': [payload: number | undefined]\n}\n\nexport const [injectStepperRootContext, provideStepperRootContext]\n  = createContext<StepperRootContext>('StepperRoot')\n</script>\n\n<script setup lang=\"ts\">\nconst props = withDefaults(defineProps<StepperRootProps>(), {\n  orientation: 'horizontal',\n  linear: true,\n  defaultValue: 1,\n})\nconst emits = defineEmits<StepperRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current step */\n    modelValue: number | undefined\n    /** Total number of steps */\n    totalSteps: number\n    /** Whether or not the next step is disabled */\n    isNextDisabled: boolean\n    /** Whether or not the previous step is disabled */\n    isPrevDisabled: boolean\n    /** Whether or not the first step is active */\n    isFirstStep: boolean\n    /** Whether or not the last step is active */\n    isLastStep: boolean\n    /** Go to a specific step */\n    goToStep: (step: number) => void\n    /** Go to the next step */\n    nextStep: () => void\n    /** Go to the previous step */\n    prevStep: () => void\n    /** Whether or not there is a next step */\n    hasNext: () => boolean\n    /** Whether or not there is a previous step */\n    hasPrev: () => boolean\n  }) => any\n}>()\n\nconst { dir: propDir, orientation: propOrientation, linear } = toRefs(props)\nconst dir = useDirection(propDir)\n\nconst totalStepperItems = ref<Set<HTMLElement>>(new Set())\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst totalStepperItemsArray = computed(() => Array.from(totalStepperItems.value))\n\nconst isFirstStep = computed(() => modelValue.value === 1)\nconst isLastStep = computed(() => modelValue.value === totalStepperItemsArray.value.length)\n\nconst totalSteps = computed(() => totalStepperItems.value.size)\n\nfunction goToStep(step: number) {\n  if (step > totalSteps.value)\n    return\n\n  if (step < 1)\n    return\n\n  if (totalStepperItems.value.size && !!totalStepperItemsArray.value[step] && !!totalStepperItemsArray.value[step].getAttribute('disabled'))\n    return\n\n  if (linear.value) {\n    if (step > (modelValue.value ?? 1) + 1)\n      return\n  }\n\n  modelValue.value = step\n}\n\nfunction nextStep() {\n  goToStep((modelValue.value ?? 1) + 1)\n}\n\nfunction prevStep() {\n  goToStep((modelValue.value ?? 1) - 1)\n}\n\nfunction hasNext() {\n  return (modelValue.value ?? 1) < totalSteps.value\n}\n\nfunction hasPrev() {\n  return (modelValue.value ?? 1) > 1\n}\n\nconst nextStepperItem = ref<HTMLElement | null>(null)\nconst prevStepperItem = ref<HTMLElement | null>(null)\nconst isNextDisabled = computed(() => nextStepperItem.value ? nextStepperItem.value.getAttribute('disabled') === '' : true)\nconst isPrevDisabled = computed(() => prevStepperItem.value ? prevStepperItem.value.getAttribute('disabled') === '' : true)\n\nwatch(modelValue, async () => {\n  await nextTick(() => {\n    nextStepperItem.value = totalStepperItemsArray.value.length && modelValue.value! < totalStepperItemsArray.value.length ? totalStepperItemsArray.value[modelValue.value!] : null\n    prevStepperItem.value = totalStepperItemsArray.value.length && modelValue.value! > 1 ? totalStepperItemsArray.value[modelValue.value! - 2] : null\n  })\n})\nwatch(totalStepperItemsArray, async () => {\n  await nextTick(() => {\n    nextStepperItem.value = totalStepperItemsArray.value.length && modelValue.value! < totalStepperItemsArray.value.length ? totalStepperItemsArray.value[modelValue.value!] : null\n    prevStepperItem.value = totalStepperItemsArray.value.length && modelValue.value! > 1 ? totalStepperItemsArray.value[modelValue.value! - 2] : null\n  })\n})\n\nprovideStepperRootContext({\n  modelValue,\n  changeModelValue: (value: number) => {\n    modelValue.value = value\n  },\n  orientation: propOrientation,\n  dir,\n  linear,\n  totalStepperItems,\n})\n\ndefineExpose({\n  goToStep,\n  nextStep,\n  prevStep,\n  modelValue,\n  totalSteps,\n  isNextDisabled,\n  isPrevDisabled,\n  isFirstStep,\n  isLastStep,\n  hasNext,\n  hasPrev,\n})\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    role=\"group\"\n    aria-label=\"progress\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :data-linear=\"linear ? '' : undefined\"\n    :data-orientation=\"orientation\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :total-steps=\"totalStepperItems.size\"\n      :is-next-disabled=\"isNextDisabled\"\n      :is-prev-disabled=\"isPrevDisabled\"\n      :is-first-step=\"isFirstStep\"\n      :is-last-step=\"isLastStep\"\n      :go-to-step=\"goToStep\"\n      :next-step=\"nextStep\"\n      :prev-step=\"prevStep\"\n      :has-next=\"hasNext\"\n      :has-prev=\"hasPrev\"\n    />\n\n    <div\n      aria-live=\"polite\"\n      aria-atomic=\"true\"\n      role=\"status\"\n      :style=\"{\n        transform: 'translateX(-100%)',\n        position: 'absolute',\n        pointerEvents: 'none',\n        opacity: 0,\n        margin: 0,\n      }\"\n    >\n      Step {{ modelValue }} of {{ totalStepperItems.size }}\n    </div>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { DataOrientation, Direction } from '../shared/types'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, ref, toRefs, watch } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\nexport interface StepperRootContext {\n  modelValue: Ref<number | undefined>\n  changeModelValue: (value: number) => void\n  orientation: Ref<DataOrientation>\n  dir: Ref<Direction>\n  linear: Ref<boolean>\n  totalStepperItems: Ref<Set<HTMLElement>>\n}\n\nexport interface StepperRootProps extends PrimitiveProps {\n  /**\n   * The value of the step that should be active when initially rendered. Use when you do not need to control the state of the steps.\n   */\n  defaultValue?: number\n  /**\n   * The orientation the steps are laid out.\n   * Mainly so arrow navigation is done accordingly (left & right vs. up & down).\n   * @defaultValue horizontal\n   */\n  orientation?: DataOrientation\n  /**\n   * The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode.\n   */\n  dir?: Direction\n  /** The controlled value of the step to activate. Can be bound as `v-model`. */\n  modelValue?: number\n  /** Whether or not the steps must be completed in order. */\n  linear?: boolean\n}\nexport type StepperRootEmits = {\n  /** Event handler called when the value changes */\n  'update:modelValue': [payload: number | undefined]\n}\n\nexport const [injectStepperRootContext, provideStepperRootContext]\n  = createContext<StepperRootContext>('StepperRoot')\n</script>\n\n<script setup lang=\"ts\">\nconst props = withDefaults(defineProps<StepperRootProps>(), {\n  orientation: 'horizontal',\n  linear: true,\n  defaultValue: 1,\n})\nconst emits = defineEmits<StepperRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current step */\n    modelValue: number | undefined\n    /** Total number of steps */\n    totalSteps: number\n    /** Whether or not the next step is disabled */\n    isNextDisabled: boolean\n    /** Whether or not the previous step is disabled */\n    isPrevDisabled: boolean\n    /** Whether or not the first step is active */\n    isFirstStep: boolean\n    /** Whether or not the last step is active */\n    isLastStep: boolean\n    /** Go to a specific step */\n    goToStep: (step: number) => void\n    /** Go to the next step */\n    nextStep: () => void\n    /** Go to the previous step */\n    prevStep: () => void\n    /** Whether or not there is a next step */\n    hasNext: () => boolean\n    /** Whether or not there is a previous step */\n    hasPrev: () => boolean\n  }) => any\n}>()\n\nconst { dir: propDir, orientation: propOrientation, linear } = toRefs(props)\nconst dir = useDirection(propDir)\n\nconst totalStepperItems = ref<Set<HTMLElement>>(new Set())\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst totalStepperItemsArray = computed(() => Array.from(totalStepperItems.value))\n\nconst isFirstStep = computed(() => modelValue.value === 1)\nconst isLastStep = computed(() => modelValue.value === totalStepperItemsArray.value.length)\n\nconst totalSteps = computed(() => totalStepperItems.value.size)\n\nfunction goToStep(step: number) {\n  if (step > totalSteps.value)\n    return\n\n  if (step < 1)\n    return\n\n  if (totalStepperItems.value.size && !!totalStepperItemsArray.value[step] && !!totalStepperItemsArray.value[step].getAttribute('disabled'))\n    return\n\n  if (linear.value) {\n    if (step > (modelValue.value ?? 1) + 1)\n      return\n  }\n\n  modelValue.value = step\n}\n\nfunction nextStep() {\n  goToStep((modelValue.value ?? 1) + 1)\n}\n\nfunction prevStep() {\n  goToStep((modelValue.value ?? 1) - 1)\n}\n\nfunction hasNext() {\n  return (modelValue.value ?? 1) < totalSteps.value\n}\n\nfunction hasPrev() {\n  return (modelValue.value ?? 1) > 1\n}\n\nconst nextStepperItem = ref<HTMLElement | null>(null)\nconst prevStepperItem = ref<HTMLElement | null>(null)\nconst isNextDisabled = computed(() => nextStepperItem.value ? nextStepperItem.value.getAttribute('disabled') === '' : true)\nconst isPrevDisabled = computed(() => prevStepperItem.value ? prevStepperItem.value.getAttribute('disabled') === '' : true)\n\nwatch(modelValue, async () => {\n  await nextTick(() => {\n    nextStepperItem.value = totalStepperItemsArray.value.length && modelValue.value! < totalStepperItemsArray.value.length ? totalStepperItemsArray.value[modelValue.value!] : null\n    prevStepperItem.value = totalStepperItemsArray.value.length && modelValue.value! > 1 ? totalStepperItemsArray.value[modelValue.value! - 2] : null\n  })\n})\nwatch(totalStepperItemsArray, async () => {\n  await nextTick(() => {\n    nextStepperItem.value = totalStepperItemsArray.value.length && modelValue.value! < totalStepperItemsArray.value.length ? totalStepperItemsArray.value[modelValue.value!] : null\n    prevStepperItem.value = totalStepperItemsArray.value.length && modelValue.value! > 1 ? totalStepperItemsArray.value[modelValue.value! - 2] : null\n  })\n})\n\nprovideStepperRootContext({\n  modelValue,\n  changeModelValue: (value: number) => {\n    modelValue.value = value\n  },\n  orientation: propOrientation,\n  dir,\n  linear,\n  totalStepperItems,\n})\n\ndefineExpose({\n  goToStep,\n  nextStep,\n  prevStep,\n  modelValue,\n  totalSteps,\n  isNextDisabled,\n  isPrevDisabled,\n  isFirstStep,\n  isLastStep,\n  hasNext,\n  hasPrev,\n})\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    role=\"group\"\n    aria-label=\"progress\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :data-linear=\"linear ? '' : undefined\"\n    :data-orientation=\"orientation\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :total-steps=\"totalStepperItems.size\"\n      :is-next-disabled=\"isNextDisabled\"\n      :is-prev-disabled=\"isPrevDisabled\"\n      :is-first-step=\"isFirstStep\"\n      :is-last-step=\"isLastStep\"\n      :go-to-step=\"goToStep\"\n      :next-step=\"nextStep\"\n      :prev-step=\"prevStep\"\n      :has-next=\"hasNext\"\n      :has-prev=\"hasPrev\"\n    />\n\n    <div\n      aria-live=\"polite\"\n      aria-atomic=\"true\"\n      role=\"status\"\n      :style=\"{\n        transform: 'translateX(-100%)',\n        position: 'absolute',\n        pointerEvents: 'none',\n        opacity: 0,\n        margin: 0,\n      }\"\n    >\n      Step {{ modelValue }} of {{ totalStepperItems.size }}\n    </div>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\n\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { createContext, useForwardExpose, useId } from '@/shared'\nimport { injectStepperRootContext } from './StepperRoot.vue'\n\nexport const [injectStepperItemContext, provideStepperItemContext] = createContext<StepperItemContext>('StepperItem')\n\nexport type StepperState = 'completed' | 'active' | 'inactive'\n\nexport interface StepperItemContext {\n  titleId: string\n  descriptionId: string\n  step: Ref<number>\n  state: Ref<StepperState>\n  disabled: Ref<boolean>\n  isFocusable: Ref<boolean>\n}\n\nexport interface StepperItemProps extends PrimitiveProps {\n  /** A unique value that associates the stepper item with an index */\n  step: number\n  /** When `true`, prevents the user from interacting with the step. */\n  disabled?: boolean\n  /** Shows whether the step is completed. */\n  completed?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = withDefaults(defineProps<StepperItemProps>(), {\n  completed: false,\n  disabled: false,\n})\n\ndefineSlots<{\n  default?: (props: {\n    /** The current state of the stepper item */\n    state: StepperState\n  }) => any\n}>()\n\nconst { disabled, step, completed } = toRefs(props)\n\nconst { forwardRef } = useForwardExpose()\n\nconst rootContext = injectStepperRootContext()\n\nconst titleId = useId(undefined, 'reka-stepper-item-title')\nconst descriptionId = useId(undefined, 'reka-stepper-item-description')\n\nconst itemState = computed(() => {\n  if (completed.value)\n    return 'completed'\n  if (rootContext.modelValue.value === step.value)\n    return 'active'\n  if (rootContext.modelValue.value! > step.value)\n    return 'completed'\n  return 'inactive'\n})\n\nconst isFocusable = computed(() => {\n  if (disabled.value)\n    return false\n  if (rootContext.linear.value)\n    return step.value <= rootContext.modelValue.value! || step.value === rootContext.modelValue.value! + 1\n\n  return true\n})\n\nprovideStepperItemContext({\n  titleId,\n  descriptionId,\n  state: itemState,\n  disabled,\n  step,\n  isFocusable,\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-current=\"itemState === 'active' ? 'true' : undefined\"\n    :data-state=\"itemState\"\n    :disabled=\"disabled || !isFocusable ? '' : undefined\"\n    :data-disabled=\"disabled || !isFocusable ? '' : undefined\"\n    :data-orientation=\"rootContext.orientation.value\"\n  >\n    <slot :state=\"itemState\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\n\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { createContext, useForwardExpose, useId } from '@/shared'\nimport { injectStepperRootContext } from './StepperRoot.vue'\n\nexport const [injectStepperItemContext, provideStepperItemContext] = createContext<StepperItemContext>('StepperItem')\n\nexport type StepperState = 'completed' | 'active' | 'inactive'\n\nexport interface StepperItemContext {\n  titleId: string\n  descriptionId: string\n  step: Ref<number>\n  state: Ref<StepperState>\n  disabled: Ref<boolean>\n  isFocusable: Ref<boolean>\n}\n\nexport interface StepperItemProps extends PrimitiveProps {\n  /** A unique value that associates the stepper item with an index */\n  step: number\n  /** When `true`, prevents the user from interacting with the step. */\n  disabled?: boolean\n  /** Shows whether the step is completed. */\n  completed?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = withDefaults(defineProps<StepperItemProps>(), {\n  completed: false,\n  disabled: false,\n})\n\ndefineSlots<{\n  default?: (props: {\n    /** The current state of the stepper item */\n    state: StepperState\n  }) => any\n}>()\n\nconst { disabled, step, completed } = toRefs(props)\n\nconst { forwardRef } = useForwardExpose()\n\nconst rootContext = injectStepperRootContext()\n\nconst titleId = useId(undefined, 'reka-stepper-item-title')\nconst descriptionId = useId(undefined, 'reka-stepper-item-description')\n\nconst itemState = computed(() => {\n  if (completed.value)\n    return 'completed'\n  if (rootContext.modelValue.value === step.value)\n    return 'active'\n  if (rootContext.modelValue.value! > step.value)\n    return 'completed'\n  return 'inactive'\n})\n\nconst isFocusable = computed(() => {\n  if (disabled.value)\n    return false\n  if (rootContext.linear.value)\n    return step.value <= rootContext.modelValue.value! || step.value === rootContext.modelValue.value! + 1\n\n  return true\n})\n\nprovideStepperItemContext({\n  titleId,\n  descriptionId,\n  state: itemState,\n  disabled,\n  step,\n  isFocusable,\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-current=\"itemState === 'active' ? 'true' : undefined\"\n    :data-state=\"itemState\"\n    :disabled=\"disabled || !isFocusable ? '' : undefined\"\n    :data-disabled=\"disabled || !isFocusable ? '' : undefined\"\n    :data-orientation=\"rootContext.orientation.value\"\n  >\n    <slot :state=\"itemState\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectStepperItemContext } from './StepperItem.vue'\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nexport interface StepperDescriptionProps extends PrimitiveProps { }\n\nconst props = withDefaults(defineProps<StepperDescriptionProps>(), { as: 'p' })\n\nuseForwardExpose()\nconst itemContext = injectStepperItemContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"itemContext.descriptionId\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectStepperItemContext } from './StepperItem.vue'\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nexport interface StepperDescriptionProps extends PrimitiveProps { }\n\nconst props = withDefaults(defineProps<StepperDescriptionProps>(), { as: 'p' })\n\nuseForwardExpose()\nconst itemContext = injectStepperItemContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"itemContext.descriptionId\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectStepperItemContext } from './StepperItem.vue'\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nexport interface StepperIndicatorProps extends PrimitiveProps { }\n\nconst props = defineProps<StepperIndicatorProps>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current step */\n    step: number\n  }) => any\n}>()\n\nconst itemContext = injectStepperItemContext()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n  >\n    <slot :step=\"itemContext.step.value\">\n      Step {{ itemContext.step.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectStepperItemContext } from './StepperItem.vue'\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nexport interface StepperIndicatorProps extends PrimitiveProps { }\n\nconst props = defineProps<StepperIndicatorProps>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current step */\n    step: number\n  }) => any\n}>()\n\nconst itemContext = injectStepperItemContext()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n  >\n    <slot :step=\"itemContext.step.value\">\n      Step {{ itemContext.step.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { SeparatorProps } from '@/Separator'\nimport { Separator } from '@/Separator'\nimport { useForwardExpose } from '@/shared'\nimport { injectStepperItemContext } from './StepperItem.vue'\nimport { injectStepperRootContext } from './StepperRoot.vue'\n</script>\n\n<script setup lang=\"ts\">\nexport interface StepperSeparatorProps extends SeparatorProps { }\n\nconst props = withDefaults(defineProps<StepperSeparatorProps>(), {})\n\nconst rootContext = injectStepperRootContext()\nconst itemContext = injectStepperItemContext()\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Separator\n    v-bind=\"props\"\n    decorative\n    :orientation=\"rootContext.orientation.value\"\n    :data-state=\"itemContext.state.value\"\n  >\n    <slot />\n  </Separator>\n</template>\n","<script lang=\"ts\">\nimport type { SeparatorProps } from '@/Separator'\nimport { Separator } from '@/Separator'\nimport { useForwardExpose } from '@/shared'\nimport { injectStepperItemContext } from './StepperItem.vue'\nimport { injectStepperRootContext } from './StepperRoot.vue'\n</script>\n\n<script setup lang=\"ts\">\nexport interface StepperSeparatorProps extends SeparatorProps { }\n\nconst props = withDefaults(defineProps<StepperSeparatorProps>(), {})\n\nconst rootContext = injectStepperRootContext()\nconst itemContext = injectStepperItemContext()\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Separator\n    v-bind=\"props\"\n    decorative\n    :orientation=\"rootContext.orientation.value\"\n    :data-state=\"itemContext.state.value\"\n  >\n    <slot />\n  </Separator>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectStepperItemContext } from './StepperItem.vue'\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nexport interface StepperTitleProps extends PrimitiveProps { }\n\nconst props = withDefaults(defineProps<StepperTitleProps>(), { as: 'h4' })\nconst itemContext = injectStepperItemContext()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"itemContext.titleId\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectStepperItemContext } from './StepperItem.vue'\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nexport interface StepperTitleProps extends PrimitiveProps { }\n\nconst props = withDefaults(defineProps<StepperTitleProps>(), { as: 'h4' })\nconst itemContext = injectStepperItemContext()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"itemContext.titleId\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { getActiveElement, useArrowNavigation, useForwardExpose, useKbd } from '@/shared'\n\nexport interface StepperTriggerProps extends PrimitiveProps {\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectStepperItemContext } from './StepperItem.vue'\nimport { injectStepperRootContext } from './StepperRoot.vue'\n\nwithDefaults(defineProps<StepperTriggerProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectStepperRootContext()\nconst itemContext = injectStepperItemContext()\n\nconst kbd = useKbd()\nconst stepperItems = computed(() => Array.from(rootContext.totalStepperItems.value))\n\nfunction handleMouseDown(event: MouseEvent) {\n  if (itemContext.disabled.value)\n    return\n  if (rootContext.linear.value) {\n    if (itemContext.step.value <= rootContext.modelValue.value! || itemContext.step.value === rootContext.modelValue.value! + 1) {\n      if (event.ctrlKey === false) {\n        rootContext.changeModelValue(itemContext.step.value)\n        return\n      }\n    }\n  }\n  else {\n    if (event.ctrlKey === false) {\n      rootContext.changeModelValue(itemContext.step.value)\n      return\n    }\n  }\n\n  // prevent focus to avoid accidental activation\n  event.preventDefault()\n}\n\nfunction handleKeyDown(event: KeyboardEvent) {\n  event.preventDefault()\n\n  if (itemContext.disabled.value)\n    return\n\n  if ((event.key === kbd.ENTER || event.key === kbd.SPACE) && !event.ctrlKey && !event.shiftKey)\n    rootContext.changeModelValue(itemContext.step.value)\n\n  if ([kbd.ARROW_LEFT, kbd.ARROW_RIGHT, kbd.ARROW_UP, kbd.ARROW_DOWN].includes(event.key)) {\n    useArrowNavigation(event, getActiveElement() as HTMLElement, undefined, {\n      itemsArray: stepperItems.value,\n      focus: true,\n      loop: false,\n      arrowKeyOptions: rootContext.orientation.value,\n      dir: rootContext.dir.value,\n    })\n  }\n}\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nonMounted(() => {\n  rootContext.totalStepperItems.value.add(currentElement.value)\n})\n\nonUnmounted(() => {\n  rootContext.totalStepperItems.value.delete(currentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :data-state=\"itemContext.state.value\"\n    :disabled=\"itemContext.disabled.value || !itemContext.isFocusable.value ? '' : undefined\"\n    :data-disabled=\"itemContext.disabled.value || !itemContext.isFocusable.value ? '' : undefined\"\n    :data-orientation=\"rootContext.orientation.value\"\n    :tabindex=\"itemContext.isFocusable.value ? 0 : -1\"\n    :aria-describedby=\"itemContext.descriptionId\"\n    :aria-labelledby=\"itemContext.titleId\"\n    @mousedown.left=\"handleMouseDown\"\n    @keydown.enter.space.left.right.up.down=\"handleKeyDown\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed, onMounted, onUnmounted } from 'vue'\nimport { getActiveElement, useArrowNavigation, useForwardExpose, useKbd } from '@/shared'\n\nexport interface StepperTriggerProps extends PrimitiveProps {\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectStepperItemContext } from './StepperItem.vue'\nimport { injectStepperRootContext } from './StepperRoot.vue'\n\nwithDefaults(defineProps<StepperTriggerProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectStepperRootContext()\nconst itemContext = injectStepperItemContext()\n\nconst kbd = useKbd()\nconst stepperItems = computed(() => Array.from(rootContext.totalStepperItems.value))\n\nfunction handleMouseDown(event: MouseEvent) {\n  if (itemContext.disabled.value)\n    return\n  if (rootContext.linear.value) {\n    if (itemContext.step.value <= rootContext.modelValue.value! || itemContext.step.value === rootContext.modelValue.value! + 1) {\n      if (event.ctrlKey === false) {\n        rootContext.changeModelValue(itemContext.step.value)\n        return\n      }\n    }\n  }\n  else {\n    if (event.ctrlKey === false) {\n      rootContext.changeModelValue(itemContext.step.value)\n      return\n    }\n  }\n\n  // prevent focus to avoid accidental activation\n  event.preventDefault()\n}\n\nfunction handleKeyDown(event: KeyboardEvent) {\n  event.preventDefault()\n\n  if (itemContext.disabled.value)\n    return\n\n  if ((event.key === kbd.ENTER || event.key === kbd.SPACE) && !event.ctrlKey && !event.shiftKey)\n    rootContext.changeModelValue(itemContext.step.value)\n\n  if ([kbd.ARROW_LEFT, kbd.ARROW_RIGHT, kbd.ARROW_UP, kbd.ARROW_DOWN].includes(event.key)) {\n    useArrowNavigation(event, getActiveElement() as HTMLElement, undefined, {\n      itemsArray: stepperItems.value,\n      focus: true,\n      loop: false,\n      arrowKeyOptions: rootContext.orientation.value,\n      dir: rootContext.dir.value,\n    })\n  }\n}\n\nconst { forwardRef, currentElement } = useForwardExpose()\n\nonMounted(() => {\n  rootContext.totalStepperItems.value.add(currentElement.value)\n})\n\nonUnmounted(() => {\n  rootContext.totalStepperItems.value.delete(currentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :data-state=\"itemContext.state.value\"\n    :disabled=\"itemContext.disabled.value || !itemContext.isFocusable.value ? '' : undefined\"\n    :data-disabled=\"itemContext.disabled.value || !itemContext.isFocusable.value ? '' : undefined\"\n    :data-orientation=\"rootContext.orientation.value\"\n    :tabindex=\"itemContext.isFocusable.value ? 0 : -1\"\n    :aria-describedby=\"itemContext.descriptionId\"\n    :aria-labelledby=\"itemContext.titleId\"\n    @mousedown.left=\"handleMouseDown\"\n    @keydown.enter.space.left.right.up.down=\"handleKeyDown\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { FormFieldProps } from '@/shared/types'\nimport { createContext, useFormControl, useForwardExpose } from '@/shared'\n\nexport interface SwitchRootProps<T = boolean> extends PrimitiveProps, FormFieldProps {\n  /** The state of the switch when it is initially rendered. Use when you do not need to control its state. */\n  defaultValue?: T\n  /** The controlled state of the switch. Can be bind as `v-model`. */\n  modelValue?: T | null\n  /** When `true`, prevents the user from interacting with the switch. */\n  disabled?: boolean\n  id?: string\n  /** The value given as data when submitted with a `name`. */\n  value?: string\n  /**\n   * The value used when the switch is on. Defaults to `true`.\n   */\n  trueValue?: T\n  /**\n   * The value used when the switch is off. Defaults to `false`.\n   */\n  falseValue?: T\n}\n\nexport type SwitchRootEmits<T = boolean> = {\n  /** Event handler called when the value of the switch changes. */\n  'update:modelValue': [payload: T]\n}\n\nexport interface SwitchRootContext {\n  checked: ComputedRef<boolean>\n  toggleCheck: () => void\n  disabled: Ref<boolean>\n}\n\nexport const [injectSwitchRootContext, provideSwitchRootContext]\n  = createContext<SwitchRootContext>('SwitchRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T = boolean\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\nconst props = withDefaults(defineProps<SwitchRootProps<T>>(), {\n  as: 'button',\n  modelValue: undefined,\n  value: 'on',\n  trueValue: (() => true) as unknown as undefined,\n  falseValue: (() => false) as unknown as undefined,\n})\nconst emit = defineEmits<SwitchRootEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current value */\n    modelValue: typeof modelValue.value\n    /** Whether the switch is checked */\n    checked: typeof checked.value\n  }) => any\n}>()\n\nconst { disabled } = toRefs(props)\n\nconst modelValue = useVModel(props as any, 'modelValue', emit as any, {\n  defaultValue: props.defaultValue ?? props.falseValue,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<T>\n\nconst checked = computed(() => modelValue.value === props.trueValue)\n\nfunction toggleCheck() {\n  if (disabled.value)\n    return\n\n  modelValue.value = checked.value ? props.falseValue as T : props.trueValue as T\n}\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst isFormControl = useFormControl(currentElement)\nconst ariaLabel = computed(() => props.id && currentElement.value ? (document.querySelector(`[for=\"${props.id}\"]`) as HTMLLabelElement)?.innerText : undefined)\n\nprovideSwitchRootContext({\n  checked,\n  toggleCheck,\n  disabled,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    :id=\"id\"\n    :ref=\"forwardRef\"\n    role=\"switch\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :value=\"value\"\n    :aria-label=\"$attrs['aria-label'] || ariaLabel\"\n    :aria-checked=\"checked\"\n    :aria-required=\"required\"\n    :data-state=\"checked ? 'checked' : 'unchecked'\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :disabled=\"disabled\"\n    @click=\"toggleCheck\"\n    @keydown.enter.prevent=\"toggleCheck\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :checked=\"checked\"\n    />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      type=\"checkbox\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n      :value=\"value\"\n      :checked=\"checked\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { FormFieldProps } from '@/shared/types'\nimport { createContext, useFormControl, useForwardExpose } from '@/shared'\n\nexport interface SwitchRootProps<T = boolean> extends PrimitiveProps, FormFieldProps {\n  /** The state of the switch when it is initially rendered. Use when you do not need to control its state. */\n  defaultValue?: T\n  /** The controlled state of the switch. Can be bind as `v-model`. */\n  modelValue?: T | null\n  /** When `true`, prevents the user from interacting with the switch. */\n  disabled?: boolean\n  id?: string\n  /** The value given as data when submitted with a `name`. */\n  value?: string\n  /**\n   * The value used when the switch is on. Defaults to `true`.\n   */\n  trueValue?: T\n  /**\n   * The value used when the switch is off. Defaults to `false`.\n   */\n  falseValue?: T\n}\n\nexport type SwitchRootEmits<T = boolean> = {\n  /** Event handler called when the value of the switch changes. */\n  'update:modelValue': [payload: T]\n}\n\nexport interface SwitchRootContext {\n  checked: ComputedRef<boolean>\n  toggleCheck: () => void\n  disabled: Ref<boolean>\n}\n\nexport const [injectSwitchRootContext, provideSwitchRootContext]\n  = createContext<SwitchRootContext>('SwitchRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T = boolean\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\nconst props = withDefaults(defineProps<SwitchRootProps<T>>(), {\n  as: 'button',\n  modelValue: undefined,\n  value: 'on',\n  trueValue: (() => true) as unknown as undefined,\n  falseValue: (() => false) as unknown as undefined,\n})\nconst emit = defineEmits<SwitchRootEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current value */\n    modelValue: typeof modelValue.value\n    /** Whether the switch is checked */\n    checked: typeof checked.value\n  }) => any\n}>()\n\nconst { disabled } = toRefs(props)\n\nconst modelValue = useVModel(props as any, 'modelValue', emit as any, {\n  defaultValue: props.defaultValue ?? props.falseValue,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<T>\n\nconst checked = computed(() => modelValue.value === props.trueValue)\n\nfunction toggleCheck() {\n  if (disabled.value)\n    return\n\n  modelValue.value = checked.value ? props.falseValue as T : props.trueValue as T\n}\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst isFormControl = useFormControl(currentElement)\nconst ariaLabel = computed(() => props.id && currentElement.value ? (document.querySelector(`[for=\"${props.id}\"]`) as HTMLLabelElement)?.innerText : undefined)\n\nprovideSwitchRootContext({\n  checked,\n  toggleCheck,\n  disabled,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    :id=\"id\"\n    :ref=\"forwardRef\"\n    role=\"switch\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :value=\"value\"\n    :aria-label=\"$attrs['aria-label'] || ariaLabel\"\n    :aria-checked=\"checked\"\n    :aria-required=\"required\"\n    :data-state=\"checked ? 'checked' : 'unchecked'\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n    :disabled=\"disabled\"\n    @click=\"toggleCheck\"\n    @keydown.enter.prevent=\"toggleCheck\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :checked=\"checked\"\n    />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name\"\n      type=\"checkbox\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n      :value=\"value\"\n      :checked=\"checked\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface SwitchThumbProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectSwitchRootContext } from './SwitchRoot.vue'\n\nwithDefaults(defineProps<SwitchThumbProps>(), { as: 'span' })\n\nconst rootContext = injectSwitchRootContext()\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    :data-state=\"rootContext.checked.value ? 'checked' : 'unchecked'\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface SwitchThumbProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectSwitchRootContext } from './SwitchRoot.vue'\n\nwithDefaults(defineProps<SwitchThumbProps>(), { as: 'span' })\n\nconst rootContext = injectSwitchRootContext()\n\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive\n    :data-state=\"rootContext.checked.value ? 'checked' : 'unchecked'\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { DataOrientation, Direction, StringOrNumber } from '../shared/types'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useVModel } from '@vueuse/core'\nimport { createContext, useDirection, useForwardExpose, useId } from '@/shared'\n\nexport interface TabsRootContext {\n  modelValue: Ref<StringOrNumber | undefined>\n  changeModelValue: (value: StringOrNumber) => void\n  orientation: Ref<DataOrientation>\n  dir: Ref<Direction>\n  unmountOnHide: Ref<boolean>\n  activationMode: 'automatic' | 'manual'\n  baseId: string\n  tabsList: Ref<HTMLElement | undefined>\n  contentIds: Ref<Set<StringOrNumber>>\n  registerContent: (value: StringOrNumber) => void\n  unregisterContent: (value: StringOrNumber) => void\n}\n\nexport interface TabsRootProps<T extends StringOrNumber = StringOrNumber> extends PrimitiveProps {\n  /**\n   * The value of the tab that should be active when initially rendered. Use when you do not need to control the state of the tabs\n   */\n  defaultValue?: T\n  /**\n   * The orientation the tabs are laid out.\n   * Mainly so arrow navigation is done accordingly (left & right vs. up & down)\n   * @defaultValue horizontal\n   */\n  orientation?: DataOrientation\n  /**\n   * The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode.\n   */\n  dir?: Direction\n  /**\n   * Whether a tab is activated automatically (on focus) or manually (on click).\n   * @defaultValue automatic\n   */\n  activationMode?: 'automatic' | 'manual'\n  /** The controlled value of the tab to activate. Can be bind as `v-model`. */\n  modelValue?: T\n  /**\n   * When `true`, the element will be unmounted on closed state.\n   *\n   * @defaultValue `true`\n   */\n  unmountOnHide?: boolean\n}\nexport type TabsRootEmits<T extends StringOrNumber = StringOrNumber> = {\n  /** Event handler called when the value changes */\n  'update:modelValue': [payload: T]\n}\n\nexport const [injectTabsRootContext, provideTabsRootContext]\n  = createContext<TabsRootContext>('TabsRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends StringOrNumber = StringOrNumber\">\nimport { ref, shallowRef, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<TabsRootProps<T>>(), {\n  orientation: 'horizontal',\n  activationMode: 'automatic',\n  unmountOnHide: true,\n})\nconst emits = defineEmits<TabsRootEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { orientation, unmountOnHide, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nuseForwardExpose()\n\nconst modelValue = useVModel<TabsRootProps<T>, 'modelValue', 'update:modelValue'>(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst tabsList = ref<HTMLElement>()\nconst contentIds = shallowRef<Set<StringOrNumber>>(new Set())\n\nprovideTabsRootContext({\n  modelValue,\n  changeModelValue: (value: StringOrNumber) => {\n    modelValue.value = value as T\n  },\n  orientation,\n  dir,\n  unmountOnHide,\n  activationMode: props.activationMode,\n  baseId: useId(undefined, 'reka-tabs'),\n  tabsList,\n  contentIds,\n  registerContent: (value: StringOrNumber) => {\n    contentIds.value = new Set([...contentIds.value, value])\n  },\n  unregisterContent: (value: StringOrNumber) => {\n    const newSet = new Set(contentIds.value)\n    newSet.delete(value)\n    contentIds.value = newSet\n  },\n})\n</script>\n\n<template>\n  <Primitive\n    :dir=\"dir\"\n    :data-orientation=\"orientation\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n  >\n    <slot :model-value=\"modelValue\" />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { DataOrientation, Direction, StringOrNumber } from '../shared/types'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useVModel } from '@vueuse/core'\nimport { createContext, useDirection, useForwardExpose, useId } from '@/shared'\n\nexport interface TabsRootContext {\n  modelValue: Ref<StringOrNumber | undefined>\n  changeModelValue: (value: StringOrNumber) => void\n  orientation: Ref<DataOrientation>\n  dir: Ref<Direction>\n  unmountOnHide: Ref<boolean>\n  activationMode: 'automatic' | 'manual'\n  baseId: string\n  tabsList: Ref<HTMLElement | undefined>\n  contentIds: Ref<Set<StringOrNumber>>\n  registerContent: (value: StringOrNumber) => void\n  unregisterContent: (value: StringOrNumber) => void\n}\n\nexport interface TabsRootProps<T extends StringOrNumber = StringOrNumber> extends PrimitiveProps {\n  /**\n   * The value of the tab that should be active when initially rendered. Use when you do not need to control the state of the tabs\n   */\n  defaultValue?: T\n  /**\n   * The orientation the tabs are laid out.\n   * Mainly so arrow navigation is done accordingly (left & right vs. up & down)\n   * @defaultValue horizontal\n   */\n  orientation?: DataOrientation\n  /**\n   * The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode.\n   */\n  dir?: Direction\n  /**\n   * Whether a tab is activated automatically (on focus) or manually (on click).\n   * @defaultValue automatic\n   */\n  activationMode?: 'automatic' | 'manual'\n  /** The controlled value of the tab to activate. Can be bind as `v-model`. */\n  modelValue?: T\n  /**\n   * When `true`, the element will be unmounted on closed state.\n   *\n   * @defaultValue `true`\n   */\n  unmountOnHide?: boolean\n}\nexport type TabsRootEmits<T extends StringOrNumber = StringOrNumber> = {\n  /** Event handler called when the value changes */\n  'update:modelValue': [payload: T]\n}\n\nexport const [injectTabsRootContext, provideTabsRootContext]\n  = createContext<TabsRootContext>('TabsRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends StringOrNumber = StringOrNumber\">\nimport { ref, shallowRef, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<TabsRootProps<T>>(), {\n  orientation: 'horizontal',\n  activationMode: 'automatic',\n  unmountOnHide: true,\n})\nconst emits = defineEmits<TabsRootEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { orientation, unmountOnHide, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nuseForwardExpose()\n\nconst modelValue = useVModel<TabsRootProps<T>, 'modelValue', 'update:modelValue'>(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n})\n\nconst tabsList = ref<HTMLElement>()\nconst contentIds = shallowRef<Set<StringOrNumber>>(new Set())\n\nprovideTabsRootContext({\n  modelValue,\n  changeModelValue: (value: StringOrNumber) => {\n    modelValue.value = value as T\n  },\n  orientation,\n  dir,\n  unmountOnHide,\n  activationMode: props.activationMode,\n  baseId: useId(undefined, 'reka-tabs'),\n  tabsList,\n  contentIds,\n  registerContent: (value: StringOrNumber) => {\n    contentIds.value = new Set([...contentIds.value, value])\n  },\n  unregisterContent: (value: StringOrNumber) => {\n    const newSet = new Set(contentIds.value)\n    newSet.delete(value)\n    contentIds.value = newSet\n  },\n})\n</script>\n\n<template>\n  <Primitive\n    :dir=\"dir\"\n    :data-orientation=\"orientation\"\n    :as-child=\"asChild\"\n    :as=\"as\"\n  >\n    <slot :model-value=\"modelValue\" />\n  </Primitive>\n</template>\n","import type { StringOrNumber } from '@/shared/types'\n\nexport function makeTriggerId(baseId: string, value: StringOrNumber) {\n  return `${baseId}-trigger-${value}`\n}\n\nexport function makeContentId(baseId: string, value: StringOrNumber) {\n  return `${baseId}-content-${value}`\n}\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { StringOrNumber } from '@/shared/types'\nimport { useForwardExpose } from '@/shared'\n\nexport interface TabsContentProps extends PrimitiveProps {\n  /** A unique value that associates the content with a trigger. */\n  value: StringOrNumber\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onBeforeUnmount, onMounted, ref } from 'vue'\nimport { Presence } from '@/Presence'\nimport { Primitive } from '@/Primitive'\nimport { injectTabsRootContext } from './TabsRoot.vue'\nimport { makeContentId, makeTriggerId } from './utils'\n\nconst props = defineProps<TabsContentProps>()\n\nconst { forwardRef } = useForwardExpose()\nconst rootContext = injectTabsRootContext()\nconst triggerId = computed(() => makeTriggerId(rootContext.baseId, props.value))\nconst contentId = computed(() => makeContentId(rootContext.baseId, props.value))\n\nconst isSelected = computed(() => props.value === rootContext.modelValue.value)\n\nconst isMountAnimationPreventedRef = ref(isSelected.value)\n\nonMounted(() => {\n  rootContext.registerContent(props.value)\n  requestAnimationFrame(() => {\n    isMountAnimationPreventedRef.value = false\n  })\n})\n\nonBeforeUnmount(() => {\n  rootContext.unregisterContent(props.value)\n})\n</script>\n\n<template>\n  <Presence\n    v-slot=\"{ present }\"\n    :present=\"forceMount || isSelected\"\n    force-mount\n  >\n    <Primitive\n      :id=\"contentId\"\n      :ref=\"forwardRef\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      role=\"tabpanel\"\n      :data-state=\"isSelected ? 'active' : 'inactive'\"\n      :data-orientation=\"rootContext.orientation.value\"\n      :aria-labelledby=\"triggerId\"\n      :hidden=\"!present\"\n      tabindex=\"0\"\n      :style=\"{\n        animationDuration: isMountAnimationPreventedRef ? '0s' : undefined,\n      }\"\n    >\n      <slot v-if=\"rootContext.unmountOnHide.value ? present : true\" />\n    </Primitive>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { StringOrNumber } from '@/shared/types'\nimport { useForwardExpose } from '@/shared'\n\nexport interface TabsContentProps extends PrimitiveProps {\n  /** A unique value that associates the content with a trigger. */\n  value: StringOrNumber\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onBeforeUnmount, onMounted, ref } from 'vue'\nimport { Presence } from '@/Presence'\nimport { Primitive } from '@/Primitive'\nimport { injectTabsRootContext } from './TabsRoot.vue'\nimport { makeContentId, makeTriggerId } from './utils'\n\nconst props = defineProps<TabsContentProps>()\n\nconst { forwardRef } = useForwardExpose()\nconst rootContext = injectTabsRootContext()\nconst triggerId = computed(() => makeTriggerId(rootContext.baseId, props.value))\nconst contentId = computed(() => makeContentId(rootContext.baseId, props.value))\n\nconst isSelected = computed(() => props.value === rootContext.modelValue.value)\n\nconst isMountAnimationPreventedRef = ref(isSelected.value)\n\nonMounted(() => {\n  rootContext.registerContent(props.value)\n  requestAnimationFrame(() => {\n    isMountAnimationPreventedRef.value = false\n  })\n})\n\nonBeforeUnmount(() => {\n  rootContext.unregisterContent(props.value)\n})\n</script>\n\n<template>\n  <Presence\n    v-slot=\"{ present }\"\n    :present=\"forceMount || isSelected\"\n    force-mount\n  >\n    <Primitive\n      :id=\"contentId\"\n      :ref=\"forwardRef\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      role=\"tabpanel\"\n      :data-state=\"isSelected ? 'active' : 'inactive'\"\n      :data-orientation=\"rootContext.orientation.value\"\n      :aria-labelledby=\"triggerId\"\n      :hidden=\"!present\"\n      tabindex=\"0\"\n      :style=\"{\n        animationDuration: isMountAnimationPreventedRef ? '0s' : undefined,\n      }\"\n    >\n      <slot v-if=\"rootContext.unmountOnHide.value ? present : true\" />\n    </Primitive>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed, ref, watch, watchPostEffect } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport { injectTabsRootContext } from './TabsRoot.vue'\n\nexport interface TabsIndicatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useMounted, useResizeObserver } from '@vueuse/core'\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<TabsIndicatorProps>()\nconst context = injectTabsRootContext()\ndefineExpose({\n  updateIndicatorStyle,\n})\nuseForwardExpose()\n\nconst isMounted = useMounted()\n\ninterface IndicatorStyle {\n  size: number | null\n  position: number | null\n}\nconst indicatorStyle = ref<IndicatorStyle>({\n  size: null,\n  position: null,\n})\nconst tabs = ref<Array<HTMLElement>>([])\n\nwatch(() => [context.modelValue.value, context?.dir.value], () => {\n  updateIndicatorStyle()\n}, { immediate: true, flush: 'post' })\n\nwatchPostEffect(() => {\n  tabs.value = Array.from(context.tabsList.value?.querySelectorAll<HTMLElement>('[role=\"tab\"]') || [])\n})\n\nuseResizeObserver(computed(() => [context.tabsList.value, ...tabs.value]), updateIndicatorStyle)\n\nfunction updateIndicatorStyle() {\n  const activeTab = context.tabsList.value?.querySelector<HTMLButtonElement>('[role=\"tab\"][data-state=\"active\"]')\n\n  if (!activeTab)\n    return\n\n  if (context.orientation.value === 'horizontal') {\n    indicatorStyle.value = {\n      size: activeTab.offsetWidth,\n      position: activeTab.offsetLeft,\n    }\n  }\n  else {\n    indicatorStyle.value = {\n      size: activeTab.offsetHeight,\n      position: activeTab.offsetTop,\n    }\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    v-if=\"isMounted && typeof indicatorStyle.size === 'number'\"\n    v-bind=\"props\"\n    :style=\"{\n      '--reka-tabs-indicator-size': `${indicatorStyle.size}px`,\n      '--reka-tabs-indicator-position': `${indicatorStyle.position}px`,\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed, ref, watch, watchPostEffect } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport { injectTabsRootContext } from './TabsRoot.vue'\n\nexport interface TabsIndicatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useMounted, useResizeObserver } from '@vueuse/core'\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<TabsIndicatorProps>()\nconst context = injectTabsRootContext()\ndefineExpose({\n  updateIndicatorStyle,\n})\nuseForwardExpose()\n\nconst isMounted = useMounted()\n\ninterface IndicatorStyle {\n  size: number | null\n  position: number | null\n}\nconst indicatorStyle = ref<IndicatorStyle>({\n  size: null,\n  position: null,\n})\nconst tabs = ref<Array<HTMLElement>>([])\n\nwatch(() => [context.modelValue.value, context?.dir.value], () => {\n  updateIndicatorStyle()\n}, { immediate: true, flush: 'post' })\n\nwatchPostEffect(() => {\n  tabs.value = Array.from(context.tabsList.value?.querySelectorAll<HTMLElement>('[role=\"tab\"]') || [])\n})\n\nuseResizeObserver(computed(() => [context.tabsList.value, ...tabs.value]), updateIndicatorStyle)\n\nfunction updateIndicatorStyle() {\n  const activeTab = context.tabsList.value?.querySelector<HTMLButtonElement>('[role=\"tab\"][data-state=\"active\"]')\n\n  if (!activeTab)\n    return\n\n  if (context.orientation.value === 'horizontal') {\n    indicatorStyle.value = {\n      size: activeTab.offsetWidth,\n      position: activeTab.offsetLeft,\n    }\n  }\n  else {\n    indicatorStyle.value = {\n      size: activeTab.offsetHeight,\n      position: activeTab.offsetTop,\n    }\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    v-if=\"isMounted && typeof indicatorStyle.size === 'number'\"\n    v-bind=\"props\"\n    :style=\"{\n      '--reka-tabs-indicator-size': `${indicatorStyle.size}px`,\n      '--reka-tabs-indicator-position': `${indicatorStyle.position}px`,\n    }\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface TabsListProps extends PrimitiveProps {\n  /** When `true`, keyboard navigation will loop from last tab to first, and vice versa. */\n  loop?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusGroup } from '@/RovingFocus'\nimport { injectTabsRootContext } from './TabsRoot.vue'\n\nconst props = withDefaults(defineProps<TabsListProps>(), {\n  loop: true,\n})\nconst { loop } = toRefs(props)\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst context = injectTabsRootContext()\n\ncontext.tabsList = currentElement\n</script>\n\n<template>\n  <RovingFocusGroup\n    as-child\n    :orientation=\"context.orientation.value\"\n    :dir=\"context.dir.value\"\n    :loop=\"loop\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"tablist\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      :aria-orientation=\"context.orientation.value\"\n    >\n      <slot />\n    </Primitive>\n  </RovingFocusGroup>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface TabsListProps extends PrimitiveProps {\n  /** When `true`, keyboard navigation will loop from last tab to first, and vice versa. */\n  loop?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusGroup } from '@/RovingFocus'\nimport { injectTabsRootContext } from './TabsRoot.vue'\n\nconst props = withDefaults(defineProps<TabsListProps>(), {\n  loop: true,\n})\nconst { loop } = toRefs(props)\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst context = injectTabsRootContext()\n\ncontext.tabsList = currentElement\n</script>\n\n<template>\n  <RovingFocusGroup\n    as-child\n    :orientation=\"context.orientation.value\"\n    :dir=\"context.dir.value\"\n    :loop=\"loop\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"tablist\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n      :aria-orientation=\"context.orientation.value\"\n    >\n      <slot />\n    </Primitive>\n  </RovingFocusGroup>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { StringOrNumber } from '@/shared/types'\nimport { useForwardExpose } from '@/shared'\n\nexport interface TabsTriggerProps extends PrimitiveProps {\n  /** A unique value that associates the trigger with a content. */\n  value: StringOrNumber\n  /** When `true`, prevents the user from interacting with the tab. */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\nimport { injectTabsRootContext } from './TabsRoot.vue'\nimport { makeContentId, makeTriggerId } from './utils'\n\nconst props = withDefaults(defineProps<TabsTriggerProps>(), {\n  disabled: false,\n  as: 'button',\n})\n\nconst { forwardRef } = useForwardExpose()\nconst rootContext = injectTabsRootContext()\n\nconst triggerId = computed(() => makeTriggerId(rootContext.baseId, props.value))\nconst contentId = computed(() => rootContext.contentIds.value.has(props.value) ? makeContentId(rootContext.baseId, props.value) : undefined)\n\nconst isSelected = computed(() => props.value === rootContext.modelValue.value)\n</script>\n\n<template>\n  <RovingFocusItem\n    as-child\n    :focusable=\"!disabled\"\n    :active=\"isSelected\"\n  >\n    <Primitive\n      :id=\"triggerId\"\n      :ref=\"forwardRef\"\n      role=\"tab\"\n      :type=\"as === 'button' ? 'button' : undefined\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :aria-selected=\"isSelected ? 'true' : 'false'\"\n      :aria-controls=\"contentId\"\n      :data-state=\"isSelected ? 'active' : 'inactive'\"\n      :disabled=\"disabled\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :data-orientation=\"rootContext.orientation.value\"\n      @mousedown.left=\"(event: MouseEvent) => {\n        // only call handler if it's the left button (mousedown gets triggered by all mouse buttons)\n        // but not when the control key is pressed (avoiding MacOS right click)\n        if (!disabled && event.ctrlKey === false) {\n          rootContext.changeModelValue(value);\n        }\n        else {\n          // prevent focus to avoid accidental activation\n          event.preventDefault();\n        }\n      }\"\n      @keydown.enter.space=\"rootContext.changeModelValue(value)\"\n      @focus=\"() => {\n        // handle 'automatic' activation if necessary\n        // ie. activate tab following focus\n        const isAutomaticActivation = rootContext.activationMode !== 'manual';\n        if (!isSelected && !disabled && isAutomaticActivation) {\n          rootContext.changeModelValue(value);\n        }\n      }\"\n    >\n      <slot />\n    </Primitive>\n  </RovingFocusItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { StringOrNumber } from '@/shared/types'\nimport { useForwardExpose } from '@/shared'\n\nexport interface TabsTriggerProps extends PrimitiveProps {\n  /** A unique value that associates the trigger with a content. */\n  value: StringOrNumber\n  /** When `true`, prevents the user from interacting with the tab. */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\nimport { injectTabsRootContext } from './TabsRoot.vue'\nimport { makeContentId, makeTriggerId } from './utils'\n\nconst props = withDefaults(defineProps<TabsTriggerProps>(), {\n  disabled: false,\n  as: 'button',\n})\n\nconst { forwardRef } = useForwardExpose()\nconst rootContext = injectTabsRootContext()\n\nconst triggerId = computed(() => makeTriggerId(rootContext.baseId, props.value))\nconst contentId = computed(() => rootContext.contentIds.value.has(props.value) ? makeContentId(rootContext.baseId, props.value) : undefined)\n\nconst isSelected = computed(() => props.value === rootContext.modelValue.value)\n</script>\n\n<template>\n  <RovingFocusItem\n    as-child\n    :focusable=\"!disabled\"\n    :active=\"isSelected\"\n  >\n    <Primitive\n      :id=\"triggerId\"\n      :ref=\"forwardRef\"\n      role=\"tab\"\n      :type=\"as === 'button' ? 'button' : undefined\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :aria-selected=\"isSelected ? 'true' : 'false'\"\n      :aria-controls=\"contentId\"\n      :data-state=\"isSelected ? 'active' : 'inactive'\"\n      :disabled=\"disabled\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :data-orientation=\"rootContext.orientation.value\"\n      @mousedown.left=\"(event: MouseEvent) => {\n        // only call handler if it's the left button (mousedown gets triggered by all mouse buttons)\n        // but not when the control key is pressed (avoiding MacOS right click)\n        if (!disabled && event.ctrlKey === false) {\n          rootContext.changeModelValue(value);\n        }\n        else {\n          // prevent focus to avoid accidental activation\n          event.preventDefault();\n        }\n      }\"\n      @keydown.enter.space=\"rootContext.changeModelValue(value)\"\n      @focus=\"() => {\n        // handle 'automatic' activation if necessary\n        // ie. activate tab following focus\n        const isAutomaticActivation = rootContext.activationMode !== 'manual';\n        if (!isSelected && !disabled && isAutomaticActivation) {\n          rootContext.changeModelValue(value);\n        }\n      }\"\n    >\n      <slot />\n    </Primitive>\n  </RovingFocusItem>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport { computed, ref, toRefs } from 'vue'\nimport { createContext, useArrowNavigation, useDirection, useFormControl, useForwardExpose } from '@/shared'\n\nexport type AcceptableInputValue = string | number | bigint | Record<string, any>\n\nexport interface TagsInputRootProps<T = AcceptableInputValue> extends PrimitiveProps, FormFieldProps {\n  /** The controlled value of the tags input. Can be bind as `v-model`. */\n  modelValue?: Array<T> | null\n  /** The value of the tags that should be added. Use when you do not need to control the state of the tags input */\n  defaultValue?: Array<T>\n  /** When `true`, allow adding tags on paste. Work in conjunction with delimiter prop. */\n  addOnPaste?: boolean\n  /** When `true` allow adding tags on tab keydown */\n  addOnTab?: boolean\n  /** When `true` allow adding tags blur input */\n  addOnBlur?: boolean\n  /** When `true`, allow duplicated tags. */\n  duplicate?: boolean\n  /** When `true`, prevents the user from interacting with the tags input. */\n  disabled?: boolean\n  /** The character or regular expression to trigger the addition of a new tag. Also used to split tags for `@paste` event */\n  delimiter?: string | RegExp\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** Maximum number of tags. */\n  max?: number\n  id?: string\n  /** Convert the input value to the desired type. Mandatory when using objects as values and using `TagsInputInput` */\n  convertValue?: (value: string) => T\n  /** Display the value of the tag. Useful when you want to apply modifications to the value like adding a suffix or when using object as values */\n  displayValue?: (value: T) => string\n}\n\nexport type TagsInputRootEmits<T = AcceptableInputValue> = {\n  /** Event handler called when the value changes */\n  'update:modelValue': [payload: Array<T>]\n  /** Event handler called when the value is invalid */\n  'invalid': [payload: T]\n  /** Event handler called when tag is added */\n  'addTag': [payload: T]\n  /** Event handler called when tag is removed */\n  'removeTag': [payload: T]\n}\n\nexport interface TagsInputRootContext<T = AcceptableInputValue> {\n  modelValue: Ref<Array<T>>\n  onAddValue: (payload: string) => boolean\n  onRemoveValue: (index: number) => void\n  onInputKeydown: (event: KeyboardEvent) => void\n  selectedElement: Ref<HTMLElement | undefined>\n  isInvalidInput: Ref<boolean>\n  addOnPaste: Ref<boolean>\n  addOnTab: Ref<boolean>\n  addOnBlur: Ref<boolean>\n  disabled: Ref<boolean>\n  delimiter: Ref<string | RegExp>\n  dir: Ref<Direction>\n  max: Ref<number>\n  id: Ref<string | undefined> | undefined\n  displayValue: (value: T) => string\n}\n\nexport const [injectTagsInputRootContext, provideTagsInputRootContext]\n  = createContext<TagsInputRootContext>('TagsInputRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableInputValue = string\">\nimport { useFocusWithin, useVModel } from '@vueuse/core'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\nconst props = withDefaults(defineProps<TagsInputRootProps<T>>(), {\n  defaultValue: () => [],\n  delimiter: ',',\n  max: 0,\n  displayValue: (value: T) => value.toString(),\n})\nconst emits = defineEmits<TagsInputRootEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { addOnPaste, disabled, delimiter, max, id, dir: propDir, addOnBlur, addOnTab } = toRefs(props)\nconst dir = useDirection(propDir)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: true,\n  deep: true,\n}) as Ref<Array<AcceptableInputValue>>\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { focused } = useFocusWithin(currentElement)\nconst isFormControl = useFormControl(currentElement)\n\nconst { getItems, CollectionSlot } = useCollection({ isProvider: true })\n\nconst selectedElement = ref<HTMLElement>()\nconst isInvalidInput = ref(false)\n\nconst currentModelValue = computed(() => Array.isArray(modelValue.value) ? [...modelValue.value] : [])\n\nfunction handleRemoveTag(index: number) {\n  if (index !== -1) {\n    const collection = getItems().filter(i => i.ref.dataset.disabled !== '')\n    modelValue.value = modelValue.value.filter((_, i) => i !== index)\n    emits('removeTag', collection[index].value)\n  }\n}\n\nprovideTagsInputRootContext({\n  modelValue,\n  onAddValue: (_payload) => {\n    const array = [...currentModelValue.value]\n    const modelValueIsObject = array.length > 0 && typeof array[0] === 'object'\n    const defaultValueIsObject = array.length > 0 && typeof props.defaultValue[0] === 'object'\n\n    // Check if the value is an object and if the convertValue function is provided. We don't check this a type level because the use\n    // of `TagsInputInput` is optional.\n    if ((modelValueIsObject || defaultValueIsObject) && typeof props.convertValue !== 'function')\n      throw new Error('You must provide a `convertValue` function when using objects as values.')\n    const payload = props.convertValue ? props.convertValue(_payload) : _payload as T\n\n    if ((array.length >= max.value) && !!max.value) {\n      emits('invalid', payload)\n      return false\n    }\n\n    if (props.duplicate) {\n      modelValue.value = [...array, payload]\n      emits('addTag', payload)\n      return true\n    }\n    else {\n      const exist = array.includes(payload)\n      if (!exist) {\n        modelValue.value = [...array, payload]\n        emits('addTag', payload)\n        return true\n      }\n      else {\n        isInvalidInput.value = true\n      }\n    }\n    emits('invalid', payload)\n    return false\n  },\n  onRemoveValue: handleRemoveTag,\n  onInputKeydown: (event) => {\n    // Don't navigate/select tags mid-composition, keys are used for IME candidate navigation\n    if (event.isComposing)\n      return\n    const target = event.target as HTMLInputElement\n    const collection = getItems().map(i => i.ref).filter(i => i.dataset.disabled !== '')\n    if (!collection.length)\n      return\n    const lastTag = collection.at(-1)\n    switch (event.key) {\n      case 'Delete':\n      case 'Backspace': {\n        if (target.selectionStart !== 0 || target.selectionEnd !== 0)\n          break\n\n        if (selectedElement.value) {\n          const index = collection.findIndex(i => i === selectedElement.value)\n          handleRemoveTag(index)\n          selectedElement.value = selectedElement.value === lastTag ? collection.at(index - 1) : collection.at(index + 1)\n          event.preventDefault()\n        }\n        else if (event.key === 'Backspace') {\n          selectedElement.value = lastTag\n          event.preventDefault()\n        }\n        break\n      }\n      case 'Home':\n      case 'End':\n      case 'ArrowRight':\n      case 'ArrowLeft': {\n        const isArrowRight = (event.key === 'ArrowRight' && dir.value === 'ltr') || (event.key === 'ArrowLeft' && dir.value === 'rtl')\n        const isArrowLeft = !isArrowRight\n        // only focus on tags when cursor is at the first position\n        if (target.selectionStart !== 0 || target.selectionEnd !== 0)\n          break\n\n        // if you press ArrowLeft, then we last tag\n        if (isArrowLeft && !selectedElement.value) {\n          selectedElement.value = lastTag\n          event.preventDefault()\n        }\n        // if you press ArrowRight on last tag, you deselect\n        else if (isArrowRight && lastTag && selectedElement.value === lastTag) {\n          selectedElement.value = undefined\n          event.preventDefault()\n        }\n        else if (selectedElement.value) {\n          const el = useArrowNavigation(event, selectedElement.value, undefined, {\n            itemsArray: collection,\n            loop: false,\n            dir: dir.value,\n          })\n          if (el)\n            selectedElement.value = el\n          event.preventDefault()\n        }\n        break\n      }\n      case 'ArrowUp':\n      case 'ArrowDown': {\n        if (selectedElement.value)\n          event.preventDefault()\n        break\n      }\n      default: {\n        selectedElement.value = undefined\n      }\n    }\n  },\n  selectedElement,\n  isInvalidInput,\n  addOnPaste,\n  addOnBlur,\n  addOnTab,\n  dir,\n  disabled,\n  delimiter,\n  max,\n  id,\n  displayValue: props.displayValue as (value: AcceptableInputValue) => string,\n})\n</script>\n\n<template>\n  <CollectionSlot>\n    <Primitive\n      :ref=\"forwardRef\"\n      :dir=\"dir\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :data-invalid=\"isInvalidInput ? '' : undefined\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :data-focused=\"focused ? '' : undefined\"\n    >\n      <slot :model-value=\"modelValue\" />\n\n      <VisuallyHiddenInput\n        v-if=\"isFormControl && name\"\n        :name=\"name\"\n        :value=\"modelValue\"\n        :required=\"required\"\n        :disabled=\"disabled\"\n      />\n    </Primitive>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport { computed, ref, toRefs } from 'vue'\nimport { createContext, useArrowNavigation, useDirection, useFormControl, useForwardExpose } from '@/shared'\n\nexport type AcceptableInputValue = string | number | bigint | Record<string, any>\n\nexport interface TagsInputRootProps<T = AcceptableInputValue> extends PrimitiveProps, FormFieldProps {\n  /** The controlled value of the tags input. Can be bind as `v-model`. */\n  modelValue?: Array<T> | null\n  /** The value of the tags that should be added. Use when you do not need to control the state of the tags input */\n  defaultValue?: Array<T>\n  /** When `true`, allow adding tags on paste. Work in conjunction with delimiter prop. */\n  addOnPaste?: boolean\n  /** When `true` allow adding tags on tab keydown */\n  addOnTab?: boolean\n  /** When `true` allow adding tags blur input */\n  addOnBlur?: boolean\n  /** When `true`, allow duplicated tags. */\n  duplicate?: boolean\n  /** When `true`, prevents the user from interacting with the tags input. */\n  disabled?: boolean\n  /** The character or regular expression to trigger the addition of a new tag. Also used to split tags for `@paste` event */\n  delimiter?: string | RegExp\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** Maximum number of tags. */\n  max?: number\n  id?: string\n  /** Convert the input value to the desired type. Mandatory when using objects as values and using `TagsInputInput` */\n  convertValue?: (value: string) => T\n  /** Display the value of the tag. Useful when you want to apply modifications to the value like adding a suffix or when using object as values */\n  displayValue?: (value: T) => string\n}\n\nexport type TagsInputRootEmits<T = AcceptableInputValue> = {\n  /** Event handler called when the value changes */\n  'update:modelValue': [payload: Array<T>]\n  /** Event handler called when the value is invalid */\n  'invalid': [payload: T]\n  /** Event handler called when tag is added */\n  'addTag': [payload: T]\n  /** Event handler called when tag is removed */\n  'removeTag': [payload: T]\n}\n\nexport interface TagsInputRootContext<T = AcceptableInputValue> {\n  modelValue: Ref<Array<T>>\n  onAddValue: (payload: string) => boolean\n  onRemoveValue: (index: number) => void\n  onInputKeydown: (event: KeyboardEvent) => void\n  selectedElement: Ref<HTMLElement | undefined>\n  isInvalidInput: Ref<boolean>\n  addOnPaste: Ref<boolean>\n  addOnTab: Ref<boolean>\n  addOnBlur: Ref<boolean>\n  disabled: Ref<boolean>\n  delimiter: Ref<string | RegExp>\n  dir: Ref<Direction>\n  max: Ref<number>\n  id: Ref<string | undefined> | undefined\n  displayValue: (value: T) => string\n}\n\nexport const [injectTagsInputRootContext, provideTagsInputRootContext]\n  = createContext<TagsInputRootContext>('TagsInputRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends AcceptableInputValue = string\">\nimport { useFocusWithin, useVModel } from '@vueuse/core'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\nimport { VisuallyHiddenInput } from '@/VisuallyHidden'\n\nconst props = withDefaults(defineProps<TagsInputRootProps<T>>(), {\n  defaultValue: () => [],\n  delimiter: ',',\n  max: 0,\n  displayValue: (value: T) => value.toString(),\n})\nconst emits = defineEmits<TagsInputRootEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current input values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { addOnPaste, disabled, delimiter, max, id, dir: propDir, addOnBlur, addOnTab } = toRefs(props)\nconst dir = useDirection(propDir)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: true,\n  deep: true,\n}) as Ref<Array<AcceptableInputValue>>\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { focused } = useFocusWithin(currentElement)\nconst isFormControl = useFormControl(currentElement)\n\nconst { getItems, CollectionSlot } = useCollection({ isProvider: true })\n\nconst selectedElement = ref<HTMLElement>()\nconst isInvalidInput = ref(false)\n\nconst currentModelValue = computed(() => Array.isArray(modelValue.value) ? [...modelValue.value] : [])\n\nfunction handleRemoveTag(index: number) {\n  if (index !== -1) {\n    const collection = getItems().filter(i => i.ref.dataset.disabled !== '')\n    modelValue.value = modelValue.value.filter((_, i) => i !== index)\n    emits('removeTag', collection[index].value)\n  }\n}\n\nprovideTagsInputRootContext({\n  modelValue,\n  onAddValue: (_payload) => {\n    const array = [...currentModelValue.value]\n    const modelValueIsObject = array.length > 0 && typeof array[0] === 'object'\n    const defaultValueIsObject = array.length > 0 && typeof props.defaultValue[0] === 'object'\n\n    // Check if the value is an object and if the convertValue function is provided. We don't check this a type level because the use\n    // of `TagsInputInput` is optional.\n    if ((modelValueIsObject || defaultValueIsObject) && typeof props.convertValue !== 'function')\n      throw new Error('You must provide a `convertValue` function when using objects as values.')\n    const payload = props.convertValue ? props.convertValue(_payload) : _payload as T\n\n    if ((array.length >= max.value) && !!max.value) {\n      emits('invalid', payload)\n      return false\n    }\n\n    if (props.duplicate) {\n      modelValue.value = [...array, payload]\n      emits('addTag', payload)\n      return true\n    }\n    else {\n      const exist = array.includes(payload)\n      if (!exist) {\n        modelValue.value = [...array, payload]\n        emits('addTag', payload)\n        return true\n      }\n      else {\n        isInvalidInput.value = true\n      }\n    }\n    emits('invalid', payload)\n    return false\n  },\n  onRemoveValue: handleRemoveTag,\n  onInputKeydown: (event) => {\n    // Don't navigate/select tags mid-composition, keys are used for IME candidate navigation\n    if (event.isComposing)\n      return\n    const target = event.target as HTMLInputElement\n    const collection = getItems().map(i => i.ref).filter(i => i.dataset.disabled !== '')\n    if (!collection.length)\n      return\n    const lastTag = collection.at(-1)\n    switch (event.key) {\n      case 'Delete':\n      case 'Backspace': {\n        if (target.selectionStart !== 0 || target.selectionEnd !== 0)\n          break\n\n        if (selectedElement.value) {\n          const index = collection.findIndex(i => i === selectedElement.value)\n          handleRemoveTag(index)\n          selectedElement.value = selectedElement.value === lastTag ? collection.at(index - 1) : collection.at(index + 1)\n          event.preventDefault()\n        }\n        else if (event.key === 'Backspace') {\n          selectedElement.value = lastTag\n          event.preventDefault()\n        }\n        break\n      }\n      case 'Home':\n      case 'End':\n      case 'ArrowRight':\n      case 'ArrowLeft': {\n        const isArrowRight = (event.key === 'ArrowRight' && dir.value === 'ltr') || (event.key === 'ArrowLeft' && dir.value === 'rtl')\n        const isArrowLeft = !isArrowRight\n        // only focus on tags when cursor is at the first position\n        if (target.selectionStart !== 0 || target.selectionEnd !== 0)\n          break\n\n        // if you press ArrowLeft, then we last tag\n        if (isArrowLeft && !selectedElement.value) {\n          selectedElement.value = lastTag\n          event.preventDefault()\n        }\n        // if you press ArrowRight on last tag, you deselect\n        else if (isArrowRight && lastTag && selectedElement.value === lastTag) {\n          selectedElement.value = undefined\n          event.preventDefault()\n        }\n        else if (selectedElement.value) {\n          const el = useArrowNavigation(event, selectedElement.value, undefined, {\n            itemsArray: collection,\n            loop: false,\n            dir: dir.value,\n          })\n          if (el)\n            selectedElement.value = el\n          event.preventDefault()\n        }\n        break\n      }\n      case 'ArrowUp':\n      case 'ArrowDown': {\n        if (selectedElement.value)\n          event.preventDefault()\n        break\n      }\n      default: {\n        selectedElement.value = undefined\n      }\n    }\n  },\n  selectedElement,\n  isInvalidInput,\n  addOnPaste,\n  addOnBlur,\n  addOnTab,\n  dir,\n  disabled,\n  delimiter,\n  max,\n  id,\n  displayValue: props.displayValue as (value: AcceptableInputValue) => string,\n})\n</script>\n\n<template>\n  <CollectionSlot>\n    <Primitive\n      :ref=\"forwardRef\"\n      :dir=\"dir\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :data-invalid=\"isInvalidInput ? '' : undefined\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :data-focused=\"focused ? '' : undefined\"\n    >\n      <slot :model-value=\"modelValue\" />\n\n      <VisuallyHiddenInput\n        v-if=\"isFormControl && name\"\n        :name=\"name\"\n        :value=\"modelValue\"\n        :required=\"required\"\n        :disabled=\"disabled\"\n      />\n    </Primitive>\n  </CollectionSlot>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectTagsInputRootContext } from './TagsInputRoot.vue'\n\nexport interface TagsInputClearProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<TagsInputClearProps>(), {\n  as: 'button',\n})\n\nuseForwardExpose()\nconst context = injectTagsInputRootContext()\n\nfunction handleCancel() {\n  if (context.disabled.value)\n    return\n  context.modelValue.value = []\n}\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :data-disabled=\"context.disabled.value ? '' : undefined\"\n    @click=\"handleCancel\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\nimport { injectTagsInputRootContext } from './TagsInputRoot.vue'\n\nexport interface TagsInputClearProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<TagsInputClearProps>(), {\n  as: 'button',\n})\n\nuseForwardExpose()\nconst context = injectTagsInputRootContext()\n\nfunction handleCancel() {\n  if (context.disabled.value)\n    return\n  context.modelValue.value = []\n}\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :data-disabled=\"context.disabled.value ? '' : undefined\"\n    @click=\"handleCancel\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useComposing, useForwardExpose } from '@/shared'\n\nexport interface TagsInputInputProps extends PrimitiveProps {\n  /** The placeholder character to use for empty tags input. */\n  placeholder?: string\n  /** Focus on element when mounted. */\n  autoFocus?: boolean\n  /** Maximum number of character allowed. */\n  maxLength?: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { nextTick, onMounted } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectTagsInputRootContext } from './TagsInputRoot.vue'\n\nconst props = withDefaults(defineProps<TagsInputInputProps>(), {\n  as: 'input',\n})\n\nconst context = injectTagsInputRootContext()\nconst { forwardRef, currentElement } = useForwardExpose()\n\nfunction handleBlur(event: FocusEvent) {\n  context.selectedElement.value = undefined\n\n  if (!context.addOnBlur.value)\n    return\n\n  const target = event.target as HTMLInputElement\n\n  // If the blur is caused by clicking an option within the content,\n  // we don't trigger the `addOnBlur` action,\n  // because the clicked option should be added instead of the input's current value.\n  const relatedTarget = event.relatedTarget as HTMLElement | null\n  const controlledId = target.getAttribute('aria-controls')\n  if (controlledId && relatedTarget?.closest(`#${CSS.escape(controlledId)}`))\n    return\n\n  if (!target.value)\n    return\n\n  const isAdded = context.onAddValue(target.value)\n  if (isAdded)\n    target.value = ''\n}\n\nfunction handleTab(event: Event) {\n  if (!context.addOnTab.value)\n    return\n\n  handleCustomKeydown(event)\n}\n\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing()\nasync function handleCustomKeydown(event: Event) {\n  if (isComposing.value)\n    return\n  await nextTick()\n  // if keydown 'Enter' or `Tab` was prevented, we let user handle updating the value themselves\n  if (event.defaultPrevented)\n    return\n\n  const target = event.target as HTMLInputElement\n  if (!target.value)\n    return\n\n  const isAdded = context.onAddValue(target.value)\n  if (isAdded)\n    target.value = ''\n\n  // prevent reloading when using inside of form\n  event.preventDefault()\n}\n\nfunction handleInput(event: InputEvent) {\n  if (isComposing.value)\n    return\n  context.isInvalidInput.value = false\n  if (event.data === null)\n    return\n\n  const delimiter = context.delimiter.value\n  const matchesDelimiter = delimiter === event.data || (delimiter instanceof RegExp && delimiter.test(event.data))\n  if (matchesDelimiter) {\n    const target = event.target as HTMLInputElement\n    target.value = target.value.replace(delimiter, '')\n\n    if (target.value.trim() === '') {\n      target.value = ''\n      return\n    }\n\n    const isAdded = context.onAddValue(target.value)\n    if (isAdded)\n      target.value = ''\n  }\n}\n\nfunction handleInputKeydown(event: KeyboardEvent) {\n  // `isComposing` stays true until the tick after `compositionend`, so arrow/backspace\n  // tag navigation is skipped even when the commit keydown reports `event.isComposing === false`.\n  if (isComposing.value)\n    return\n  context.onInputKeydown(event)\n}\n\nfunction handlePaste(event: ClipboardEvent) {\n  if (context.addOnPaste.value) {\n    event.preventDefault()\n    const clipboardData = event.clipboardData\n    if (!clipboardData)\n      return\n\n    const value = clipboardData.getData('text')\n    if (context.delimiter.value) {\n      const splitValue = value.split(context.delimiter.value)\n      splitValue.forEach((v) => {\n        context.onAddValue(v)\n      })\n    }\n    else {\n      context.onAddValue(value)\n    }\n  }\n}\n\nonMounted(() => {\n  const inputEl = currentElement.value.nodeName === 'INPUT'\n    ? currentElement.value\n    : currentElement.value.querySelector('input')\n\n  if (!inputEl)\n    return\n\n  setTimeout(() => {\n    // make sure all DOM was flush then only capture the focus\n    if (props.autoFocus)\n      inputEl?.focus()\n  }, 1)\n})\n</script>\n\n<template>\n  <Primitive\n    :id=\"context.id?.value\"\n    :ref=\"forwardRef\"\n    type=\"text\"\n    autocomplete=\"off\"\n    autocorrect=\"off\"\n    autocapitalize=\"off\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :maxlength=\"maxLength\"\n    :placeholder=\"placeholder\"\n    :disabled=\"context.disabled.value\"\n    :data-invalid=\"context.isInvalidInput.value ? '' : undefined\"\n    @input=\"handleInput\"\n    @keydown.enter=\"handleCustomKeydown\"\n    @keydown.tab=\"handleTab\"\n    @blur=\"handleBlur\"\n    @keydown=\"handleInputKeydown\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n    @paste=\"handlePaste\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useComposing, useForwardExpose } from '@/shared'\n\nexport interface TagsInputInputProps extends PrimitiveProps {\n  /** The placeholder character to use for empty tags input. */\n  placeholder?: string\n  /** Focus on element when mounted. */\n  autoFocus?: boolean\n  /** Maximum number of character allowed. */\n  maxLength?: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { nextTick, onMounted } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectTagsInputRootContext } from './TagsInputRoot.vue'\n\nconst props = withDefaults(defineProps<TagsInputInputProps>(), {\n  as: 'input',\n})\n\nconst context = injectTagsInputRootContext()\nconst { forwardRef, currentElement } = useForwardExpose()\n\nfunction handleBlur(event: FocusEvent) {\n  context.selectedElement.value = undefined\n\n  if (!context.addOnBlur.value)\n    return\n\n  const target = event.target as HTMLInputElement\n\n  // If the blur is caused by clicking an option within the content,\n  // we don't trigger the `addOnBlur` action,\n  // because the clicked option should be added instead of the input's current value.\n  const relatedTarget = event.relatedTarget as HTMLElement | null\n  const controlledId = target.getAttribute('aria-controls')\n  if (controlledId && relatedTarget?.closest(`#${CSS.escape(controlledId)}`))\n    return\n\n  if (!target.value)\n    return\n\n  const isAdded = context.onAddValue(target.value)\n  if (isAdded)\n    target.value = ''\n}\n\nfunction handleTab(event: Event) {\n  if (!context.addOnTab.value)\n    return\n\n  handleCustomKeydown(event)\n}\n\nconst { isComposing, handleCompositionStart, handleCompositionEnd } = useComposing()\nasync function handleCustomKeydown(event: Event) {\n  if (isComposing.value)\n    return\n  await nextTick()\n  // if keydown 'Enter' or `Tab` was prevented, we let user handle updating the value themselves\n  if (event.defaultPrevented)\n    return\n\n  const target = event.target as HTMLInputElement\n  if (!target.value)\n    return\n\n  const isAdded = context.onAddValue(target.value)\n  if (isAdded)\n    target.value = ''\n\n  // prevent reloading when using inside of form\n  event.preventDefault()\n}\n\nfunction handleInput(event: InputEvent) {\n  if (isComposing.value)\n    return\n  context.isInvalidInput.value = false\n  if (event.data === null)\n    return\n\n  const delimiter = context.delimiter.value\n  const matchesDelimiter = delimiter === event.data || (delimiter instanceof RegExp && delimiter.test(event.data))\n  if (matchesDelimiter) {\n    const target = event.target as HTMLInputElement\n    target.value = target.value.replace(delimiter, '')\n\n    if (target.value.trim() === '') {\n      target.value = ''\n      return\n    }\n\n    const isAdded = context.onAddValue(target.value)\n    if (isAdded)\n      target.value = ''\n  }\n}\n\nfunction handleInputKeydown(event: KeyboardEvent) {\n  // `isComposing` stays true until the tick after `compositionend`, so arrow/backspace\n  // tag navigation is skipped even when the commit keydown reports `event.isComposing === false`.\n  if (isComposing.value)\n    return\n  context.onInputKeydown(event)\n}\n\nfunction handlePaste(event: ClipboardEvent) {\n  if (context.addOnPaste.value) {\n    event.preventDefault()\n    const clipboardData = event.clipboardData\n    if (!clipboardData)\n      return\n\n    const value = clipboardData.getData('text')\n    if (context.delimiter.value) {\n      const splitValue = value.split(context.delimiter.value)\n      splitValue.forEach((v) => {\n        context.onAddValue(v)\n      })\n    }\n    else {\n      context.onAddValue(value)\n    }\n  }\n}\n\nonMounted(() => {\n  const inputEl = currentElement.value.nodeName === 'INPUT'\n    ? currentElement.value\n    : currentElement.value.querySelector('input')\n\n  if (!inputEl)\n    return\n\n  setTimeout(() => {\n    // make sure all DOM was flush then only capture the focus\n    if (props.autoFocus)\n      inputEl?.focus()\n  }, 1)\n})\n</script>\n\n<template>\n  <Primitive\n    :id=\"context.id?.value\"\n    :ref=\"forwardRef\"\n    type=\"text\"\n    autocomplete=\"off\"\n    autocorrect=\"off\"\n    autocapitalize=\"off\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :maxlength=\"maxLength\"\n    :placeholder=\"placeholder\"\n    :disabled=\"context.disabled.value\"\n    :data-invalid=\"context.isInvalidInput.value ? '' : undefined\"\n    @input=\"handleInput\"\n    @keydown.enter=\"handleCustomKeydown\"\n    @keydown.tab=\"handleTab\"\n    @blur=\"handleBlur\"\n    @keydown=\"handleInputKeydown\"\n    @compositionstart=\"handleCompositionStart\"\n    @compositionend=\"handleCompositionEnd\"\n    @paste=\"handlePaste\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { AcceptableInputValue } from './TagsInputRoot.vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed, toRefs } from 'vue'\nimport { createContext, useForwardExpose } from '@/shared'\nimport { injectTagsInputRootContext } from './TagsInputRoot.vue'\n\nexport interface TagsInputItemProps extends PrimitiveProps {\n  /** Value associated with the tags */\n  value: AcceptableInputValue\n  /** When `true`, prevents the user from interacting with the tags input. */\n  disabled?: boolean\n}\n\nexport interface TagsInputItemContext {\n  value: Ref<AcceptableInputValue>\n  displayValue: ComputedRef<string>\n  isSelected: Ref<boolean>\n  disabled?: Ref<boolean>\n  textId: string\n}\n\nexport const [injectTagsInputItemContext, provideTagsInputItemContext]\n  = createContext<TagsInputItemContext>('TagsInputItem')\n</script>\n\n<script setup lang=\"ts\">\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<TagsInputItemProps>()\nconst { value } = toRefs(props)\n\nconst context = injectTagsInputRootContext()\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { CollectionItem } = useCollection()\n\nconst isSelected = computed(() => context.selectedElement.value === currentElement.value)\n\nconst disabled = computed(() => props.disabled || context.disabled.value)\n\nconst itemContext = provideTagsInputItemContext({\n  value,\n  isSelected,\n  disabled,\n  textId: '',\n  displayValue: computed(() => context.displayValue(value.value)),\n})\n</script>\n\n<template>\n  <CollectionItem :value=\"value\">\n    <Primitive\n      :ref=\"forwardRef\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :aria-labelledby=\"itemContext.textId\"\n      :aria-current=\"isSelected\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :data-state=\"isSelected ? 'active' : 'inactive'\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { AcceptableInputValue } from './TagsInputRoot.vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed, toRefs } from 'vue'\nimport { createContext, useForwardExpose } from '@/shared'\nimport { injectTagsInputRootContext } from './TagsInputRoot.vue'\n\nexport interface TagsInputItemProps extends PrimitiveProps {\n  /** Value associated with the tags */\n  value: AcceptableInputValue\n  /** When `true`, prevents the user from interacting with the tags input. */\n  disabled?: boolean\n}\n\nexport interface TagsInputItemContext {\n  value: Ref<AcceptableInputValue>\n  displayValue: ComputedRef<string>\n  isSelected: Ref<boolean>\n  disabled?: Ref<boolean>\n  textId: string\n}\n\nexport const [injectTagsInputItemContext, provideTagsInputItemContext]\n  = createContext<TagsInputItemContext>('TagsInputItem')\n</script>\n\n<script setup lang=\"ts\">\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<TagsInputItemProps>()\nconst { value } = toRefs(props)\n\nconst context = injectTagsInputRootContext()\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { CollectionItem } = useCollection()\n\nconst isSelected = computed(() => context.selectedElement.value === currentElement.value)\n\nconst disabled = computed(() => props.disabled || context.disabled.value)\n\nconst itemContext = provideTagsInputItemContext({\n  value,\n  isSelected,\n  disabled,\n  textId: '',\n  displayValue: computed(() => context.displayValue(value.value)),\n})\n</script>\n\n<template>\n  <CollectionItem :value=\"value\">\n    <Primitive\n      :ref=\"forwardRef\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :aria-labelledby=\"itemContext.textId\"\n      :aria-current=\"isSelected\"\n      :data-disabled=\"disabled ? '' : undefined\"\n      :data-state=\"isSelected ? 'active' : 'inactive'\"\n    >\n      <slot />\n    </Primitive>\n  </CollectionItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { isEqual } from 'ohash'\nimport { computed } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport { injectTagsInputItemContext } from './TagsInputItem.vue'\nimport { injectTagsInputRootContext } from './TagsInputRoot.vue'\n\nexport interface TagsInputItemDeleteProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<TagsInputItemDeleteProps>(), {\n  as: 'button',\n})\n\nuseForwardExpose()\nconst context = injectTagsInputRootContext()\nconst itemContext = injectTagsInputItemContext()\n\nconst disabled = computed(() => itemContext.disabled?.value || context.disabled.value)\n\nfunction handleDelete() {\n  if (disabled.value)\n    return\n  const index = context.modelValue.value.findIndex(i => isEqual(i, itemContext.value.value))\n  context.onRemoveValue(index)\n}\n</script>\n\n<template>\n  <Primitive\n    tabindex=\"-1\"\n    v-bind=\"props\"\n    :aria-labelledby=\"itemContext.textId\"\n    :aria-current=\"itemContext.isSelected.value\"\n    :data-state=\"itemContext.isSelected.value ? 'active' : 'inactive'\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    @click=\"handleDelete\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { isEqual } from 'ohash'\nimport { computed } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport { injectTagsInputItemContext } from './TagsInputItem.vue'\nimport { injectTagsInputRootContext } from './TagsInputRoot.vue'\n\nexport interface TagsInputItemDeleteProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<TagsInputItemDeleteProps>(), {\n  as: 'button',\n})\n\nuseForwardExpose()\nconst context = injectTagsInputRootContext()\nconst itemContext = injectTagsInputItemContext()\n\nconst disabled = computed(() => itemContext.disabled?.value || context.disabled.value)\n\nfunction handleDelete() {\n  if (disabled.value)\n    return\n  const index = context.modelValue.value.findIndex(i => isEqual(i, itemContext.value.value))\n  context.onRemoveValue(index)\n}\n</script>\n\n<template>\n  <Primitive\n    tabindex=\"-1\"\n    v-bind=\"props\"\n    :aria-labelledby=\"itemContext.textId\"\n    :aria-current=\"itemContext.isSelected.value\"\n    :data-state=\"itemContext.isSelected.value ? 'active' : 'inactive'\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    @click=\"handleDelete\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose, useId } from '@/shared'\nimport { injectTagsInputItemContext } from './TagsInputItem.vue'\n\nexport interface TagsInputItemTextProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<TagsInputItemTextProps>(), {\n  as: 'span',\n})\n\nconst itemContext = injectTagsInputItemContext()\nuseForwardExpose()\n\nitemContext.textId ||= useId(undefined, 'reka-tags-input-item-text')\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"itemContext.textId\"\n  >\n    <slot>{{ itemContext.displayValue.value }}</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose, useId } from '@/shared'\nimport { injectTagsInputItemContext } from './TagsInputItem.vue'\n\nexport interface TagsInputItemTextProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<TagsInputItemTextProps>(), {\n  as: 'span',\n})\n\nconst itemContext = injectTagsInputItemContext()\nuseForwardExpose()\n\nitemContext.textId ||= useId(undefined, 'reka-tags-input-item-text')\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"itemContext.textId\"\n  >\n    <slot>{{ itemContext.displayValue.value }}</slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { DateStep, HourCycle, SegmentPart, SegmentValueObj, TimeValue } from '@/shared/date'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport { getLocalTimeZone, isEqualDay, Time, toCalendarDateTime, today } from '@internationalized/date'\nimport { isBefore } from '@/date'\nimport { createContext, isNullish, useDateFormatter, useDirection, useKbd, useLocale } from '@/shared'\nimport {\n  createContent,\n  getDefaultTime,\n  getTimeFieldSegmentElements,\n  initializeTimeSegmentValues,\n  isSegmentNavigationKey,\n  normalizeDateStep,\n  normalizeHourCycle,\n  syncTimeSegmentValues,\n} from '@/shared/date'\n\ntype TimeFieldRootContext = {\n  locale: Ref<string>\n  modelValue: Ref<DateValue | undefined>\n  placeholder: Ref<DateValue>\n  isInvalid: Ref<boolean>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  formatter: Formatter\n  hourCycle: HourCycle\n  step: Ref<DateStep>\n  stepSnapping: Ref<boolean>\n  segmentValues: Ref<SegmentValueObj>\n  segmentContents: Ref<{ part: SegmentPart, value: string }[]>\n  elements: Ref<Set<HTMLElement>>\n  focusNext: () => void\n  setFocusedElement: (el: HTMLElement) => void\n}\n\nexport interface TimeFieldRootProps extends PrimitiveProps, FormFieldProps {\n  /** The default value for the calendar */\n  defaultValue?: TimeValue\n  /** The default placeholder date */\n  defaultPlaceholder?: TimeValue\n  /** The placeholder date, which is used to determine what time to display when no time is selected. This updates as the user navigates the field */\n  placeholder?: TimeValue\n  /** The controlled checked state of the field. Can be bound as `v-model`. */\n  modelValue?: TimeValue | null\n  /** The hour cycle used for formatting times. Defaults to the local preference */\n  hourCycle?: HourCycle\n  /** The stepping interval for the time fields. Defaults to `1`. */\n  step?: DateStep\n  /** Whether to enforce snapping the value to the nearest step increment after input. Defaults to `false`. */\n  stepSnapping?: boolean\n  /** The granularity to use for formatting times. Defaults to minute if a Time is provided, otherwise defaults to minute. The field will render segments for each part of the date up to and including the specified granularity */\n  granularity?: 'hour' | 'minute' | 'second'\n  /** Whether or not to hide the time zone segment of the field */\n  hideTimeZone?: boolean\n  /** The maximum date that can be selected */\n  maxValue?: TimeValue\n  /** The minimum date that can be selected */\n  minValue?: TimeValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether or not the time field is disabled */\n  disabled?: boolean\n  /** Whether or not the time field is readonly */\n  readonly?: boolean\n  /** Id of the element */\n  id?: string\n  /** The reading direction of the time field when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n}\n\nexport type TimeFieldRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: TimeValue | undefined]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: TimeValue]\n}\n\nexport const [injectTimeFieldRootContext, provideTimeFieldRootContext]\n  = createContext<TimeFieldRootContext>('TimeFieldRoot')\n\nfunction convertValue(value: TimeValue, date: DateValue = today(getLocalTimeZone())) {\n  if (value && 'day' in value) {\n    return value\n  }\n\n  return toCalendarDateTime(date, value)\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { VisuallyHidden } from '@/VisuallyHidden'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<TimeFieldRootProps>(), {\n  defaultValue: undefined,\n  disabled: false,\n  readonly: false,\n  placeholder: undefined,\n  isDateUnavailable: undefined,\n  stepSnapping: false,\n})\nconst emits = defineEmits<TimeFieldRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current time of the field */\n    modelValue: TimeValue | undefined\n    /** The time field segment contents */\n    segments: { part: SegmentPart, value: string }[]\n    /** Value if the input is invalid */\n    isInvalid: boolean\n  }) => any\n}>()\n\nconst { disabled, readonly, granularity, defaultValue, minValue, maxValue, stepSnapping, dir: propDir, locale: propLocale } = toRefs(props)\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\n\nconst formatter = useDateFormatter(locale.value, {\n  hourCycle: normalizeHourCycle(props.hourCycle),\n})\nconst { primitiveElement, currentElement: parentElement }\n  = usePrimitiveElement()\nconst segmentElements = ref<Set<HTMLElement>>(new Set())\n\nconst step = computed(() => normalizeDateStep(props))\n\nconst convertedMinValue = computed(() => minValue.value ? convertValue(minValue.value) : undefined)\nconst convertedMaxValue = computed(() => maxValue.value ? convertValue(maxValue.value) : undefined)\n\nonMounted(() => {\n  getTimeFieldSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n})\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<TimeValue>\n\nconst convertedModelValue = computed({\n  get() {\n    if (isNullish(modelValue.value))\n      return modelValue.value\n    return convertValue(modelValue.value)\n  },\n  set(newValue) {\n    if (newValue) {\n      modelValue.value = modelValue.value && 'day' in modelValue.value ? newValue : new Time(newValue.hour, newValue.minute, newValue.second, modelValue.value?.millisecond)\n    }\n    else {\n      modelValue.value = newValue\n    }\n    return newValue\n  },\n})\n\nconst defaultDate = getDefaultTime({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: modelValue.value,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<TimeValue>\n\nconst convertedPlaceholder = computed({\n  get() {\n    return convertValue(placeholder.value)\n  },\n  set(newValue) {\n    if (newValue)\n      placeholder.value = 'day' in placeholder.value ? newValue.copy() : new Time(newValue.hour, newValue.minute, newValue.second, placeholder.value?.millisecond)\n    return newValue\n  },\n})\n\nconst inferredGranularity = computed(() => {\n  if (granularity.value)\n    return granularity.value\n\n  return 'minute'\n})\n\nconst isInvalid = computed(() => {\n  if (!modelValue.value)\n    return false\n\n  if (convertedMinValue.value && isBefore(convertedModelValue.value, convertedMinValue.value))\n    return true\n\n  if (convertedMaxValue.value && isBefore(convertedMaxValue.value, convertedModelValue.value))\n    return true\n\n  return false\n})\n\nconst initialSegments = initializeTimeSegmentValues(inferredGranularity.value)\n\nconst segmentValues = ref<SegmentValueObj>(modelValue.value ? { ...syncTimeSegmentValues({ value: convertedModelValue.value, formatter }) } : { ...initialSegments })\n\nconst allSegmentContent = computed(() => createContent({\n  granularity: inferredGranularity.value,\n  dateRef: convertedPlaceholder.value,\n  formatter,\n  hideTimeZone: props.hideTimeZone,\n  hourCycle: props.hourCycle,\n  segmentValues: segmentValues.value,\n  locale,\n  isTimeValue: true,\n}))\n\nconst segmentContents = computed(() => {\n  const contents = allSegmentContent.value.arr\n\n  // Convert hour values for 12-hour display\n  if (props.hourCycle === 12) {\n    return contents.map((segment) => {\n      if (segment.part === 'hour' && 'hour' in segmentValues.value) {\n        const hour = segmentValues.value.hour\n        if (hour !== null) {\n          const displayHour = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour\n          return { ...segment, value: displayHour.toString() }\n        }\n      }\n      return segment\n    })\n  }\n\n  return contents\n})\n\nconst editableSegmentContents = computed(() => segmentContents.value.filter(({ part }) => part !== 'literal'))\n\nwatch(locale, (value) => {\n  if (formatter.getLocale() !== value) {\n    formatter.setLocale(value)\n    // Locale changed, so we need to clear the segment elements and re-get them (different order)\n    // Get the focusable elements again on the next tick\n    nextTick(() => {\n      segmentElements.value.clear()\n      getTimeFieldSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n    })\n  }\n})\n\nwatch(convertedModelValue, (_modelValue) => {\n  if (!isNullish(_modelValue) && (!isEqualDay(convertedPlaceholder.value, _modelValue) || convertedPlaceholder.value.compare(_modelValue) !== 0))\n    placeholder.value = _modelValue.copy()\n})\n\nwatch([convertedModelValue, locale], ([_modelValue]) => {\n  if (!isNullish(_modelValue)) {\n    segmentValues.value = { ...syncTimeSegmentValues({ value: _modelValue, formatter }) }\n  }\n  // If segment has null value, means that user modified it, thus do not reset the segmentValues\n  else if (Object.values(segmentValues.value).every(value => value !== null) && isNullish(_modelValue)) {\n    segmentValues.value = { ...initialSegments }\n  }\n})\n\nconst currentFocusedElement = ref<HTMLElement | null>(null)\n\nconst currentSegmentIndex = computed(() =>\n  Array.from(segmentElements.value).findIndex(el =>\n    el.getAttribute('data-reka-time-field-segment')\n    === currentFocusedElement.value?.getAttribute('data-reka-time-field-segment')))\n\nconst nextFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const nextCondition = sign < 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (nextCondition)\n    return null\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value + sign]\n  return segmentToFocus\n})\n\nconst prevFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const prevCondition = sign > 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (prevCondition)\n    return null\n\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value - sign]\n  return segmentToFocus\n})\n\nconst kbd = useKbd()\n\nfunction handleKeydown(e: KeyboardEvent) {\n  // Don't navigate between segments mid-composition, arrow keys are used for IME candidate navigation\n  if (e.isComposing)\n    return\n  if (!isSegmentNavigationKey(e.key))\n    return\n  if (e.key === kbd.ARROW_LEFT)\n    prevFocusableSegment.value?.focus()\n  if (e.key === kbd.ARROW_RIGHT)\n    nextFocusableSegment.value?.focus()\n}\n\nfunction setFocusedElement(el: HTMLElement) {\n  currentFocusedElement.value = el\n}\n\nprovideTimeFieldRootContext({\n  locale,\n  modelValue: convertedModelValue,\n  placeholder: convertedPlaceholder,\n  disabled,\n  formatter,\n  hourCycle: props.hourCycle,\n  step,\n  stepSnapping,\n  readonly,\n  segmentValues,\n  isInvalid,\n  segmentContents: editableSegmentContents,\n  elements: segmentElements,\n  setFocusedElement,\n  focusNext() {\n    nextFocusableSegment.value?.focus()\n  },\n})\n\ndefineExpose({\n  /** Helper to set the focused element inside the DateField */\n  setFocusedElement,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    ref=\"primitiveElement\"\n    role=\"group\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n    @keydown.left.right=\"handleKeydown\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :segments=\"segmentContents\"\n      :is-invalid=\"isInvalid\"\n    />\n\n    <VisuallyHidden\n      :id=\"id\"\n      as=\"input\"\n      feature=\"focusable\"\n      tabindex=\"-1\"\n      :value=\"modelValue ? modelValue.toString() : ''\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n      @focus=\"Array.from(segmentElements)?.[0]?.focus()\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { DateStep, HourCycle, SegmentPart, SegmentValueObj, TimeValue } from '@/shared/date'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport { getLocalTimeZone, isEqualDay, Time, toCalendarDateTime, today } from '@internationalized/date'\nimport { isBefore } from '@/date'\nimport { createContext, isNullish, useDateFormatter, useDirection, useKbd, useLocale } from '@/shared'\nimport {\n  createContent,\n  getDefaultTime,\n  getTimeFieldSegmentElements,\n  initializeTimeSegmentValues,\n  isSegmentNavigationKey,\n  normalizeDateStep,\n  normalizeHourCycle,\n  syncTimeSegmentValues,\n} from '@/shared/date'\n\ntype TimeFieldRootContext = {\n  locale: Ref<string>\n  modelValue: Ref<DateValue | undefined>\n  placeholder: Ref<DateValue>\n  isInvalid: Ref<boolean>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  formatter: Formatter\n  hourCycle: HourCycle\n  step: Ref<DateStep>\n  stepSnapping: Ref<boolean>\n  segmentValues: Ref<SegmentValueObj>\n  segmentContents: Ref<{ part: SegmentPart, value: string }[]>\n  elements: Ref<Set<HTMLElement>>\n  focusNext: () => void\n  setFocusedElement: (el: HTMLElement) => void\n}\n\nexport interface TimeFieldRootProps extends PrimitiveProps, FormFieldProps {\n  /** The default value for the calendar */\n  defaultValue?: TimeValue\n  /** The default placeholder date */\n  defaultPlaceholder?: TimeValue\n  /** The placeholder date, which is used to determine what time to display when no time is selected. This updates as the user navigates the field */\n  placeholder?: TimeValue\n  /** The controlled checked state of the field. Can be bound as `v-model`. */\n  modelValue?: TimeValue | null\n  /** The hour cycle used for formatting times. Defaults to the local preference */\n  hourCycle?: HourCycle\n  /** The stepping interval for the time fields. Defaults to `1`. */\n  step?: DateStep\n  /** Whether to enforce snapping the value to the nearest step increment after input. Defaults to `false`. */\n  stepSnapping?: boolean\n  /** The granularity to use for formatting times. Defaults to minute if a Time is provided, otherwise defaults to minute. The field will render segments for each part of the date up to and including the specified granularity */\n  granularity?: 'hour' | 'minute' | 'second'\n  /** Whether or not to hide the time zone segment of the field */\n  hideTimeZone?: boolean\n  /** The maximum date that can be selected */\n  maxValue?: TimeValue\n  /** The minimum date that can be selected */\n  minValue?: TimeValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether or not the time field is disabled */\n  disabled?: boolean\n  /** Whether or not the time field is readonly */\n  readonly?: boolean\n  /** Id of the element */\n  id?: string\n  /** The reading direction of the time field when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n}\n\nexport type TimeFieldRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: TimeValue | undefined]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: TimeValue]\n}\n\nexport const [injectTimeFieldRootContext, provideTimeFieldRootContext]\n  = createContext<TimeFieldRootContext>('TimeFieldRoot')\n\nfunction convertValue(value: TimeValue, date: DateValue = today(getLocalTimeZone())) {\n  if (value && 'day' in value) {\n    return value\n  }\n\n  return toCalendarDateTime(date, value)\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { VisuallyHidden } from '@/VisuallyHidden'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<TimeFieldRootProps>(), {\n  defaultValue: undefined,\n  disabled: false,\n  readonly: false,\n  placeholder: undefined,\n  isDateUnavailable: undefined,\n  stepSnapping: false,\n})\nconst emits = defineEmits<TimeFieldRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current time of the field */\n    modelValue: TimeValue | undefined\n    /** The time field segment contents */\n    segments: { part: SegmentPart, value: string }[]\n    /** Value if the input is invalid */\n    isInvalid: boolean\n  }) => any\n}>()\n\nconst { disabled, readonly, granularity, defaultValue, minValue, maxValue, stepSnapping, dir: propDir, locale: propLocale } = toRefs(props)\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\n\nconst formatter = useDateFormatter(locale.value, {\n  hourCycle: normalizeHourCycle(props.hourCycle),\n})\nconst { primitiveElement, currentElement: parentElement }\n  = usePrimitiveElement()\nconst segmentElements = ref<Set<HTMLElement>>(new Set())\n\nconst step = computed(() => normalizeDateStep(props))\n\nconst convertedMinValue = computed(() => minValue.value ? convertValue(minValue.value) : undefined)\nconst convertedMaxValue = computed(() => maxValue.value ? convertValue(maxValue.value) : undefined)\n\nonMounted(() => {\n  getTimeFieldSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n})\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<TimeValue>\n\nconst convertedModelValue = computed({\n  get() {\n    if (isNullish(modelValue.value))\n      return modelValue.value\n    return convertValue(modelValue.value)\n  },\n  set(newValue) {\n    if (newValue) {\n      modelValue.value = modelValue.value && 'day' in modelValue.value ? newValue : new Time(newValue.hour, newValue.minute, newValue.second, modelValue.value?.millisecond)\n    }\n    else {\n      modelValue.value = newValue\n    }\n    return newValue\n  },\n})\n\nconst defaultDate = getDefaultTime({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: modelValue.value,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<TimeValue>\n\nconst convertedPlaceholder = computed({\n  get() {\n    return convertValue(placeholder.value)\n  },\n  set(newValue) {\n    if (newValue)\n      placeholder.value = 'day' in placeholder.value ? newValue.copy() : new Time(newValue.hour, newValue.minute, newValue.second, placeholder.value?.millisecond)\n    return newValue\n  },\n})\n\nconst inferredGranularity = computed(() => {\n  if (granularity.value)\n    return granularity.value\n\n  return 'minute'\n})\n\nconst isInvalid = computed(() => {\n  if (!modelValue.value)\n    return false\n\n  if (convertedMinValue.value && isBefore(convertedModelValue.value, convertedMinValue.value))\n    return true\n\n  if (convertedMaxValue.value && isBefore(convertedMaxValue.value, convertedModelValue.value))\n    return true\n\n  return false\n})\n\nconst initialSegments = initializeTimeSegmentValues(inferredGranularity.value)\n\nconst segmentValues = ref<SegmentValueObj>(modelValue.value ? { ...syncTimeSegmentValues({ value: convertedModelValue.value, formatter }) } : { ...initialSegments })\n\nconst allSegmentContent = computed(() => createContent({\n  granularity: inferredGranularity.value,\n  dateRef: convertedPlaceholder.value,\n  formatter,\n  hideTimeZone: props.hideTimeZone,\n  hourCycle: props.hourCycle,\n  segmentValues: segmentValues.value,\n  locale,\n  isTimeValue: true,\n}))\n\nconst segmentContents = computed(() => {\n  const contents = allSegmentContent.value.arr\n\n  // Convert hour values for 12-hour display\n  if (props.hourCycle === 12) {\n    return contents.map((segment) => {\n      if (segment.part === 'hour' && 'hour' in segmentValues.value) {\n        const hour = segmentValues.value.hour\n        if (hour !== null) {\n          const displayHour = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour\n          return { ...segment, value: displayHour.toString() }\n        }\n      }\n      return segment\n    })\n  }\n\n  return contents\n})\n\nconst editableSegmentContents = computed(() => segmentContents.value.filter(({ part }) => part !== 'literal'))\n\nwatch(locale, (value) => {\n  if (formatter.getLocale() !== value) {\n    formatter.setLocale(value)\n    // Locale changed, so we need to clear the segment elements and re-get them (different order)\n    // Get the focusable elements again on the next tick\n    nextTick(() => {\n      segmentElements.value.clear()\n      getTimeFieldSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n    })\n  }\n})\n\nwatch(convertedModelValue, (_modelValue) => {\n  if (!isNullish(_modelValue) && (!isEqualDay(convertedPlaceholder.value, _modelValue) || convertedPlaceholder.value.compare(_modelValue) !== 0))\n    placeholder.value = _modelValue.copy()\n})\n\nwatch([convertedModelValue, locale], ([_modelValue]) => {\n  if (!isNullish(_modelValue)) {\n    segmentValues.value = { ...syncTimeSegmentValues({ value: _modelValue, formatter }) }\n  }\n  // If segment has null value, means that user modified it, thus do not reset the segmentValues\n  else if (Object.values(segmentValues.value).every(value => value !== null) && isNullish(_modelValue)) {\n    segmentValues.value = { ...initialSegments }\n  }\n})\n\nconst currentFocusedElement = ref<HTMLElement | null>(null)\n\nconst currentSegmentIndex = computed(() =>\n  Array.from(segmentElements.value).findIndex(el =>\n    el.getAttribute('data-reka-time-field-segment')\n    === currentFocusedElement.value?.getAttribute('data-reka-time-field-segment')))\n\nconst nextFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const nextCondition = sign < 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (nextCondition)\n    return null\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value + sign]\n  return segmentToFocus\n})\n\nconst prevFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const prevCondition = sign > 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (prevCondition)\n    return null\n\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value - sign]\n  return segmentToFocus\n})\n\nconst kbd = useKbd()\n\nfunction handleKeydown(e: KeyboardEvent) {\n  // Don't navigate between segments mid-composition, arrow keys are used for IME candidate navigation\n  if (e.isComposing)\n    return\n  if (!isSegmentNavigationKey(e.key))\n    return\n  if (e.key === kbd.ARROW_LEFT)\n    prevFocusableSegment.value?.focus()\n  if (e.key === kbd.ARROW_RIGHT)\n    nextFocusableSegment.value?.focus()\n}\n\nfunction setFocusedElement(el: HTMLElement) {\n  currentFocusedElement.value = el\n}\n\nprovideTimeFieldRootContext({\n  locale,\n  modelValue: convertedModelValue,\n  placeholder: convertedPlaceholder,\n  disabled,\n  formatter,\n  hourCycle: props.hourCycle,\n  step,\n  stepSnapping,\n  readonly,\n  segmentValues,\n  isInvalid,\n  segmentContents: editableSegmentContents,\n  elements: segmentElements,\n  setFocusedElement,\n  focusNext() {\n    nextFocusableSegment.value?.focus()\n  },\n})\n\ndefineExpose({\n  /** Helper to set the focused element inside the DateField */\n  setFocusedElement,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    ref=\"primitiveElement\"\n    role=\"group\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n    @keydown.left.right=\"handleKeydown\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :segments=\"segmentContents\"\n      :is-invalid=\"isInvalid\"\n    />\n\n    <VisuallyHidden\n      :id=\"id\"\n      as=\"input\"\n      feature=\"focusable\"\n      tabindex=\"-1\"\n      :value=\"modelValue ? modelValue.toString() : ''\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n      @focus=\"Array.from(segmentElements)?.[0]?.focus()\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { SegmentPart } from '@/shared/date'\nimport { computed, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useDateField } from '@/shared/date/useDateField'\nimport { injectTimeFieldRootContext } from './TimeFieldRoot.vue'\n\nexport interface TimeFieldInputProps extends PrimitiveProps {\n  /** The part of the date to render */\n  part: SegmentPart\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<TimeFieldInputProps>()\n\nconst rootContext = injectTimeFieldRootContext()\n\nconst hasLeftFocus = ref(true)\nconst lastKeyZero = ref(false)\n\nconst {\n  handleSegmentClick,\n  handleSegmentKeydown,\n  handleSegmentBeforeInput,\n  handleSegmentCompositionStart,\n  handleSegmentCompositionEnd,\n  handleSegmentFocusOut,\n  attributes,\n} = useDateField({\n  hasLeftFocus,\n  lastKeyZero,\n  placeholder: rootContext.placeholder,\n  hourCycle: rootContext.hourCycle,\n  step: rootContext.step,\n  stepSnapping: rootContext.stepSnapping,\n  segmentValues: rootContext.segmentValues,\n  formatter: rootContext.formatter,\n  part: props.part,\n  disabled: rootContext.disabled,\n  readonly: rootContext.readonly,\n  focusNext: rootContext.focusNext,\n  modelValue: rootContext.modelValue,\n})\n\nconst disabled = computed(() => rootContext.disabled.value)\nconst readonly = computed(() => rootContext.readonly.value)\nconst isInvalid = computed(() => rootContext.isInvalid.value)\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    v-bind=\"attributes\"\n    :contenteditable=\"disabled || readonly ? false : part !== 'literal'\"\n    :data-reka-time-field-segment=\"part\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :aria-readonly=\"readonly ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :aria-invalid=\"isInvalid ? true : undefined\"\n    v-on=\"part !== 'literal' ? {\n      mousedown: handleSegmentClick,\n      keydown: handleSegmentKeydown,\n      beforeinput: handleSegmentBeforeInput,\n      compositionstart: handleSegmentCompositionStart,\n      compositionend: handleSegmentCompositionEnd,\n      focusout: () => {\n        hasLeftFocus = true\n        handleSegmentFocusOut()\n      },\n      focusin: (e: FocusEvent) => {\n        rootContext.setFocusedElement(e.target as HTMLElement)\n      },\n    } : {}\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { SegmentPart } from '@/shared/date'\nimport { computed, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useDateField } from '@/shared/date/useDateField'\nimport { injectTimeFieldRootContext } from './TimeFieldRoot.vue'\n\nexport interface TimeFieldInputProps extends PrimitiveProps {\n  /** The part of the date to render */\n  part: SegmentPart\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<TimeFieldInputProps>()\n\nconst rootContext = injectTimeFieldRootContext()\n\nconst hasLeftFocus = ref(true)\nconst lastKeyZero = ref(false)\n\nconst {\n  handleSegmentClick,\n  handleSegmentKeydown,\n  handleSegmentBeforeInput,\n  handleSegmentCompositionStart,\n  handleSegmentCompositionEnd,\n  handleSegmentFocusOut,\n  attributes,\n} = useDateField({\n  hasLeftFocus,\n  lastKeyZero,\n  placeholder: rootContext.placeholder,\n  hourCycle: rootContext.hourCycle,\n  step: rootContext.step,\n  stepSnapping: rootContext.stepSnapping,\n  segmentValues: rootContext.segmentValues,\n  formatter: rootContext.formatter,\n  part: props.part,\n  disabled: rootContext.disabled,\n  readonly: rootContext.readonly,\n  focusNext: rootContext.focusNext,\n  modelValue: rootContext.modelValue,\n})\n\nconst disabled = computed(() => rootContext.disabled.value)\nconst readonly = computed(() => rootContext.readonly.value)\nconst isInvalid = computed(() => rootContext.isInvalid.value)\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    v-bind=\"attributes\"\n    :contenteditable=\"disabled || readonly ? false : part !== 'literal'\"\n    :data-reka-time-field-segment=\"part\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :aria-readonly=\"readonly ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :aria-invalid=\"isInvalid ? true : undefined\"\n    v-on=\"part !== 'literal' ? {\n      mousedown: handleSegmentClick,\n      keydown: handleSegmentKeydown,\n      beforeinput: handleSegmentBeforeInput,\n      compositionstart: handleSegmentCompositionStart,\n      compositionend: handleSegmentCompositionEnd,\n      focusout: () => {\n        hasLeftFocus = true\n        handleSegmentFocusOut()\n      },\n      focusin: (e: FocusEvent) => {\n        rootContext.setFocusedElement(e.target as HTMLElement)\n      },\n    } : {}\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Matcher } from '@/date'\nimport type { DateRangeType } from '@/DateRangeField/DateRangeFieldRoot.vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { DateStep, HourCycle, SegmentPart, SegmentValueObj, TimeValue } from '@/shared/date'\nimport type { TimeRange } from '@/shared/date/types'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport { getLocalTimeZone, Time, toCalendarDateTime, today } from '@internationalized/date'\nimport { areAllDaysBetweenValid, isBefore, isBeforeOrSame } from '@/date'\nimport { createContext, isNullish, useDateFormatter, useDirection, useKbd, useLocale } from '@/shared'\nimport {\n  createContent,\n  getDefaultTime,\n  getTimeFieldSegmentElements,\n  initializeTimeSegmentValues,\n  isSegmentNavigationKey,\n  normalizeDateStep,\n  normalizeHourCycle,\n\n  syncSegmentValues,\n\n  syncTimeSegmentValues,\n\n} from '@/shared/date'\n\ntype TimeRangeFieldRootContext = {\n  locale: Ref<string>\n  startValue: Ref<DateValue | undefined>\n  endValue: Ref<DateValue | undefined>\n  placeholder: Ref<DateValue>\n  isInvalid: Ref<boolean>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  formatter: Formatter\n  hourCycle: HourCycle\n  step: Ref<DateStep>\n  segmentValues: Record<DateRangeType, Ref<SegmentValueObj>>\n  segmentContents: Ref<{ start: { part: SegmentPart, value: string }[], end: { part: SegmentPart, value: string }[] }>\n  elements: Ref<Set<HTMLElement>>\n  focusNext: () => void\n  setFocusedElement: (el: HTMLElement) => void\n}\n\nexport interface TimeRangeFieldRootProps extends PrimitiveProps, FormFieldProps {\n  /** The default value for the field */\n  defaultValue?: TimeRange\n  /** The default placeholder time */\n  defaultPlaceholder?: TimeValue\n  /** The placeholder time, which is used to determine what time to display when no time is selected. This updates as the user navigates the field */\n  placeholder?: TimeValue\n  /** The controlled checked state of the field. Can be bound as `v-model`. */\n  modelValue?: TimeRange | null\n  /** The hour cycle used for formatting times. Defaults to the local preference */\n  hourCycle?: HourCycle\n  /** The stepping interval for the time fields. Defaults to `1`. */\n  step?: DateStep\n  /** The granularity to use for formatting times. Defaults to minute. The field will render segments for each part of the time up to and including the specified granularity */\n  granularity?: 'hour' | 'minute' | 'second'\n  /** Whether or not to hide the time zone segment of the field */\n  hideTimeZone?: boolean\n  /** The maximum time that can be selected */\n  maxValue?: TimeValue\n  /** The minimum time that can be selected */\n  minValue?: TimeValue\n  /** The locale to use for formatting times */\n  locale?: string\n  /** Whether or not the time field is disabled */\n  disabled?: boolean\n  /** Whether or not the time field is readonly */\n  readonly?: boolean\n  /** Id of the element */\n  id?: string\n  /** The reading direction of the time field when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** A function that returns whether or not a time is unavailable */\n  isTimeUnavailable?: Matcher\n}\n\nexport type TimeRangeFieldRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: TimeRange]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: TimeValue]\n}\n\nexport const [injectTimeRangeFieldRootContext, provideTimeRangeFieldRootContext]\n  = createContext<TimeRangeFieldRootContext>('TimeRangeFieldRoot')\n\nfunction convertValue(value: TimeValue, date: DateValue = today(getLocalTimeZone())) {\n  if (value && 'day' in value) {\n    return value\n  }\n\n  return toCalendarDateTime(date, value)\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { VisuallyHidden } from '@/VisuallyHidden'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<TimeRangeFieldRootProps>(), {\n  defaultValue: undefined,\n  disabled: false,\n  readonly: false,\n  placeholder: undefined,\n  isTimeUnavailable: undefined,\n})\nconst emits = defineEmits<TimeRangeFieldRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current time of the field */\n    modelValue: TimeRange | undefined\n    /** The time field segment contents */\n    segments: { start: { part: SegmentPart, value: string }[], end: { part: SegmentPart, value: string }[] }\n    /** Value if the input is invalid */\n    isInvalid: boolean\n  }) => any\n}>()\n\nconst { disabled, readonly, granularity, defaultValue, minValue, maxValue, dir: propDir, locale: propLocale, isTimeUnavailable: propsIsTimeUnavailable } = toRefs(props)\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\n\nconst formatter = useDateFormatter(locale.value, {\n  hourCycle: normalizeHourCycle(props.hourCycle),\n})\nconst { primitiveElement, currentElement: parentElement }\n  = usePrimitiveElement()\nconst segmentElements = ref<Set<HTMLElement>>(new Set())\n\nconst step = computed(() => normalizeDateStep(props))\n\nconst convertedMinValue = computed(() => minValue.value ? convertValue(minValue.value) : undefined)\nconst convertedMaxValue = computed(() => maxValue.value ? convertValue(maxValue.value) : undefined)\n\nonMounted(() => {\n  getTimeFieldSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n})\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value ?? { start: undefined, end: undefined },\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<TimeRange>\n\nconst isStartInvalid = computed(() => {\n  if (!modelValue.value?.start)\n    return false\n\n  const convertedStartValue = convertValue(modelValue.value.start)\n\n  if (propsIsTimeUnavailable.value?.(convertedStartValue))\n    return true\n\n  if (convertedMinValue.value && isBefore(convertedStartValue, convertedMinValue.value))\n    return true\n\n  if (convertedMaxValue.value && isBefore(convertedMaxValue.value, convertedStartValue))\n    return true\n\n  return false\n})\n\nconst isEndInvalid = computed(() => {\n  if (!modelValue.value?.end)\n    return false\n\n  const convertedEndValue = convertValue(modelValue.value.end)\n\n  if (propsIsTimeUnavailable.value?.(convertedEndValue))\n    return true\n\n  if (convertedMinValue.value && isBefore(convertedEndValue, convertedMinValue.value))\n    return true\n\n  if (convertedMaxValue.value && isBefore(convertedMaxValue.value, convertedEndValue))\n    return true\n\n  return false\n})\n\nconst isInvalid = computed(() => {\n  if (isStartInvalid.value || isEndInvalid.value)\n    return true\n\n  if (!modelValue.value?.start || !modelValue.value?.end)\n    return false\n\n  const convertedModelValue = {\n    start: convertValue(modelValue.value.start),\n    end: convertValue(modelValue.value.end),\n  }\n\n  if (!isBeforeOrSame(convertedModelValue.start, convertedModelValue.end))\n    return true\n\n  if (propsIsTimeUnavailable.value !== undefined) {\n    const allValid = areAllDaysBetweenValid(\n      convertedModelValue.start,\n      convertedModelValue.end,\n      propsIsTimeUnavailable.value,\n      undefined,\n    )\n    if (!allValid)\n      return true\n  }\n  return false\n})\n\nconst startValue = ref(modelValue.value?.start?.copy()) as Ref<TimeValue | undefined>\nconst endValue = ref(modelValue.value?.end?.copy()) as Ref<TimeValue | undefined>\n\nwatch([startValue, endValue], ([_startValue, _endValue]) => {\n  modelValue.value = { start: _startValue?.copy(), end: _endValue?.copy() }\n})\n\nconst convertedStartValue = computed({\n  get() {\n    if (isNullish(startValue.value))\n      return startValue.value\n    return convertValue(startValue.value)\n  },\n  set(newValue) {\n    if (newValue) {\n      startValue.value = startValue.value && 'day' in startValue.value ? newValue : new Time(newValue.hour, newValue.minute, newValue.second, startValue.value?.millisecond)\n    }\n    else {\n      startValue.value = newValue\n    }\n    return newValue\n  },\n})\n\nconst convertedEndValue = computed({\n  get() {\n    if (isNullish(endValue.value))\n      return endValue.value\n    return convertValue(endValue.value)\n  },\n  set(newValue) {\n    if (newValue) {\n      endValue.value = endValue.value && 'day' in endValue.value ? newValue : new Time(newValue.hour, newValue.minute, newValue.second, endValue.value?.millisecond)\n    }\n    else {\n      endValue.value = newValue\n    }\n    return newValue\n  },\n})\n\nconst convertedModelValue = computed(() => ({ start: convertedStartValue.value, end: convertedEndValue.value }))\n\nconst defaultDate = getDefaultTime({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: modelValue.value?.start,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<TimeValue>\n\nconst convertedPlaceholder = computed({\n  get() {\n    return convertValue(placeholder.value)\n  },\n  set(newValue) {\n    if (newValue)\n      placeholder.value = 'day' in placeholder.value ? newValue.copy() : new Time(newValue.hour, newValue.minute, newValue.second, placeholder.value?.millisecond)\n    return newValue\n  },\n})\n\nconst inferredGranularity = computed(() => {\n  if (granularity.value)\n    return granularity.value\n\n  return 'minute'\n})\n\nconst initialSegments = initializeTimeSegmentValues(inferredGranularity.value)\n\nconst startSegmentValues = ref<SegmentValueObj>(convertedStartValue.value ? { ...syncTimeSegmentValues({ value: convertedStartValue.value, formatter }) } : { ...initialSegments })\nconst endSegmentValues = ref<SegmentValueObj>(convertedEndValue.value ? { ...syncTimeSegmentValues({ value: convertedEndValue.value, formatter }) } : { ...initialSegments })\n\nconst startSegmentContent = computed(() => createContent({\n  granularity: inferredGranularity.value,\n  dateRef: convertedPlaceholder.value,\n  formatter,\n  hideTimeZone: props.hideTimeZone,\n  hourCycle: props.hourCycle,\n  segmentValues: startSegmentValues.value,\n  locale,\n  isTimeValue: true,\n}))\n\nconst endSegmentContent = computed(() => createContent({\n  granularity: inferredGranularity.value,\n  dateRef: convertedPlaceholder.value,\n  formatter,\n  hideTimeZone: props.hideTimeZone,\n  hourCycle: props.hourCycle,\n  segmentValues: endSegmentValues.value,\n  locale,\n  isTimeValue: true,\n}))\n\nconst segmentContents = computed(() => ({\n  start: startSegmentContent.value.arr,\n  end: endSegmentContent.value.arr,\n}))\n\nconst editableSegmentContents = computed(() => ({ start: segmentContents.value.start.filter(({ part }) => part !== 'literal'), end: segmentContents.value.end.filter(({ part }) => part !== 'literal') }))\n\nwatch(convertedModelValue, (_modelValue) => {\n  const isStartChanged = _modelValue?.start && convertedStartValue.value\n    ? _modelValue.start.compare(convertedStartValue.value) !== 0\n    : _modelValue?.start !== convertedStartValue.value\n  if (isStartChanged) {\n    convertedStartValue.value = _modelValue?.start?.copy()\n  }\n\n  const isEndChanged = _modelValue?.end && convertedEndValue.value\n    ? _modelValue.end.compare(convertedEndValue.value) !== 0\n    : _modelValue?.end !== convertedEndValue.value\n  if (isEndChanged) {\n    convertedEndValue.value = _modelValue?.end?.copy()\n  }\n})\n\nwatch([convertedStartValue, locale], ([_startValue]) => {\n  if (_startValue !== undefined) {\n    startSegmentValues.value = { ...syncSegmentValues({ value: _startValue, formatter }) }\n  }\n  // If segment has null value, means that user modified it, thus do not reset the segmentValues\n  else if (Object.values(startSegmentValues.value).every(value => value !== null) && _startValue === undefined) {\n    startSegmentValues.value = { ...initialSegments }\n  }\n})\n\nwatch(locale, (value) => {\n  if (formatter.getLocale() !== value) {\n    formatter.setLocale(value)\n    // Locale changed, so we need to clear the segment elements and re-get them (different order)\n    // Get the focusable elements again on the next tick\n    nextTick(() => {\n      segmentElements.value.clear()\n      getTimeFieldSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n    })\n  }\n})\n\nwatch(convertedModelValue, (_modelValue) => {\n  if (_modelValue && _modelValue.start !== undefined && placeholder.value.compare(_modelValue.start) !== 0)\n    placeholder.value = _modelValue.start.copy()\n})\n\nwatch([convertedEndValue, locale], ([_endValue]) => {\n  if (_endValue !== undefined) {\n    endSegmentValues.value = { ...syncSegmentValues({ value: _endValue, formatter }) }\n  }\n  // If segment has null value, means that user modified it, thus do not reset the segmentValues\n  else if (Object.values(endSegmentValues.value).every(value => value !== null) && _endValue === undefined) {\n    endSegmentValues.value = { ...initialSegments }\n  }\n})\n\nconst currentFocusedElement = ref<HTMLElement | null>(null)\n\nconst currentSegmentIndex = computed(() => Array.from(segmentElements.value).findIndex(el =>\n  el.getAttribute('data-reka-time-field-segment') === currentFocusedElement.value?.getAttribute('data-reka-time-field-segment')\n  && el.getAttribute('data-reka-time-range-field-segment-type') === currentFocusedElement.value?.getAttribute('data-reka-time-range-field-segment-type')))\n\nconst nextFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const nextCondition = sign < 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (nextCondition)\n    return null\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value + sign]\n  return segmentToFocus\n})\n\nconst prevFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const prevCondition = sign > 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (prevCondition)\n    return null\n\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value - sign]\n  return segmentToFocus\n})\n\nconst kbd = useKbd()\n\nfunction handleKeydown(e: KeyboardEvent) {\n  // Don't navigate between segments mid-composition, arrow keys are used for IME candidate navigation\n  if (e.isComposing)\n    return\n  if (!isSegmentNavigationKey(e.key))\n    return\n  if (e.key === kbd.ARROW_LEFT)\n    prevFocusableSegment.value?.focus()\n  if (e.key === kbd.ARROW_RIGHT)\n    nextFocusableSegment.value?.focus()\n}\n\nfunction setFocusedElement(el: HTMLElement) {\n  currentFocusedElement.value = el\n}\n\nprovideTimeRangeFieldRootContext({\n  locale,\n  startValue: convertedStartValue,\n  endValue: convertedEndValue,\n  placeholder: convertedPlaceholder,\n  disabled,\n  formatter,\n  hourCycle: props.hourCycle,\n  step,\n  readonly,\n  isInvalid,\n  segmentValues: { start: startSegmentValues, end: endSegmentValues },\n  segmentContents: editableSegmentContents,\n  elements: segmentElements,\n  setFocusedElement,\n  focusNext() {\n    nextFocusableSegment.value?.focus()\n  },\n})\n\ndefineExpose({\n  /** Helper to set the focused element inside the TimeRangeField */\n  setFocusedElement,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    ref=\"primitiveElement\"\n    role=\"group\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n    @keydown.left.right=\"handleKeydown\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :segments=\"segmentContents\"\n      :is-invalid=\"isInvalid\"\n    />\n\n    <VisuallyHidden\n      :id=\"id\"\n      as=\"input\"\n      feature=\"focusable\"\n      tabindex=\"-1\"\n      :value=\"`${modelValue?.start?.toString()} - ${modelValue?.end?.toString()}`\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n      @focus=\"Array.from(segmentElements)?.[0]?.focus()\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Matcher } from '@/date'\nimport type { DateRangeType } from '@/DateRangeField/DateRangeFieldRoot.vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { DateStep, HourCycle, SegmentPart, SegmentValueObj, TimeValue } from '@/shared/date'\nimport type { TimeRange } from '@/shared/date/types'\nimport type { Direction, FormFieldProps } from '@/shared/types'\nimport { getLocalTimeZone, Time, toCalendarDateTime, today } from '@internationalized/date'\nimport { areAllDaysBetweenValid, isBefore, isBeforeOrSame } from '@/date'\nimport { createContext, isNullish, useDateFormatter, useDirection, useKbd, useLocale } from '@/shared'\nimport {\n  createContent,\n  getDefaultTime,\n  getTimeFieldSegmentElements,\n  initializeTimeSegmentValues,\n  isSegmentNavigationKey,\n  normalizeDateStep,\n  normalizeHourCycle,\n\n  syncSegmentValues,\n\n  syncTimeSegmentValues,\n\n} from '@/shared/date'\n\ntype TimeRangeFieldRootContext = {\n  locale: Ref<string>\n  startValue: Ref<DateValue | undefined>\n  endValue: Ref<DateValue | undefined>\n  placeholder: Ref<DateValue>\n  isInvalid: Ref<boolean>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  formatter: Formatter\n  hourCycle: HourCycle\n  step: Ref<DateStep>\n  segmentValues: Record<DateRangeType, Ref<SegmentValueObj>>\n  segmentContents: Ref<{ start: { part: SegmentPart, value: string }[], end: { part: SegmentPart, value: string }[] }>\n  elements: Ref<Set<HTMLElement>>\n  focusNext: () => void\n  setFocusedElement: (el: HTMLElement) => void\n}\n\nexport interface TimeRangeFieldRootProps extends PrimitiveProps, FormFieldProps {\n  /** The default value for the field */\n  defaultValue?: TimeRange\n  /** The default placeholder time */\n  defaultPlaceholder?: TimeValue\n  /** The placeholder time, which is used to determine what time to display when no time is selected. This updates as the user navigates the field */\n  placeholder?: TimeValue\n  /** The controlled checked state of the field. Can be bound as `v-model`. */\n  modelValue?: TimeRange | null\n  /** The hour cycle used for formatting times. Defaults to the local preference */\n  hourCycle?: HourCycle\n  /** The stepping interval for the time fields. Defaults to `1`. */\n  step?: DateStep\n  /** The granularity to use for formatting times. Defaults to minute. The field will render segments for each part of the time up to and including the specified granularity */\n  granularity?: 'hour' | 'minute' | 'second'\n  /** Whether or not to hide the time zone segment of the field */\n  hideTimeZone?: boolean\n  /** The maximum time that can be selected */\n  maxValue?: TimeValue\n  /** The minimum time that can be selected */\n  minValue?: TimeValue\n  /** The locale to use for formatting times */\n  locale?: string\n  /** Whether or not the time field is disabled */\n  disabled?: boolean\n  /** Whether or not the time field is readonly */\n  readonly?: boolean\n  /** Id of the element */\n  id?: string\n  /** The reading direction of the time field when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** A function that returns whether or not a time is unavailable */\n  isTimeUnavailable?: Matcher\n}\n\nexport type TimeRangeFieldRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: TimeRange]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: TimeValue]\n}\n\nexport const [injectTimeRangeFieldRootContext, provideTimeRangeFieldRootContext]\n  = createContext<TimeRangeFieldRootContext>('TimeRangeFieldRoot')\n\nfunction convertValue(value: TimeValue, date: DateValue = today(getLocalTimeZone())) {\n  if (value && 'day' in value) {\n    return value\n  }\n\n  return toCalendarDateTime(date, value)\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { computed, nextTick, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { VisuallyHidden } from '@/VisuallyHidden'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<TimeRangeFieldRootProps>(), {\n  defaultValue: undefined,\n  disabled: false,\n  readonly: false,\n  placeholder: undefined,\n  isTimeUnavailable: undefined,\n})\nconst emits = defineEmits<TimeRangeFieldRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current time of the field */\n    modelValue: TimeRange | undefined\n    /** The time field segment contents */\n    segments: { start: { part: SegmentPart, value: string }[], end: { part: SegmentPart, value: string }[] }\n    /** Value if the input is invalid */\n    isInvalid: boolean\n  }) => any\n}>()\n\nconst { disabled, readonly, granularity, defaultValue, minValue, maxValue, dir: propDir, locale: propLocale, isTimeUnavailable: propsIsTimeUnavailable } = toRefs(props)\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\n\nconst formatter = useDateFormatter(locale.value, {\n  hourCycle: normalizeHourCycle(props.hourCycle),\n})\nconst { primitiveElement, currentElement: parentElement }\n  = usePrimitiveElement()\nconst segmentElements = ref<Set<HTMLElement>>(new Set())\n\nconst step = computed(() => normalizeDateStep(props))\n\nconst convertedMinValue = computed(() => minValue.value ? convertValue(minValue.value) : undefined)\nconst convertedMaxValue = computed(() => maxValue.value ? convertValue(maxValue.value) : undefined)\n\nonMounted(() => {\n  getTimeFieldSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n})\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value ?? { start: undefined, end: undefined },\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<TimeRange>\n\nconst isStartInvalid = computed(() => {\n  if (!modelValue.value?.start)\n    return false\n\n  const convertedStartValue = convertValue(modelValue.value.start)\n\n  if (propsIsTimeUnavailable.value?.(convertedStartValue))\n    return true\n\n  if (convertedMinValue.value && isBefore(convertedStartValue, convertedMinValue.value))\n    return true\n\n  if (convertedMaxValue.value && isBefore(convertedMaxValue.value, convertedStartValue))\n    return true\n\n  return false\n})\n\nconst isEndInvalid = computed(() => {\n  if (!modelValue.value?.end)\n    return false\n\n  const convertedEndValue = convertValue(modelValue.value.end)\n\n  if (propsIsTimeUnavailable.value?.(convertedEndValue))\n    return true\n\n  if (convertedMinValue.value && isBefore(convertedEndValue, convertedMinValue.value))\n    return true\n\n  if (convertedMaxValue.value && isBefore(convertedMaxValue.value, convertedEndValue))\n    return true\n\n  return false\n})\n\nconst isInvalid = computed(() => {\n  if (isStartInvalid.value || isEndInvalid.value)\n    return true\n\n  if (!modelValue.value?.start || !modelValue.value?.end)\n    return false\n\n  const convertedModelValue = {\n    start: convertValue(modelValue.value.start),\n    end: convertValue(modelValue.value.end),\n  }\n\n  if (!isBeforeOrSame(convertedModelValue.start, convertedModelValue.end))\n    return true\n\n  if (propsIsTimeUnavailable.value !== undefined) {\n    const allValid = areAllDaysBetweenValid(\n      convertedModelValue.start,\n      convertedModelValue.end,\n      propsIsTimeUnavailable.value,\n      undefined,\n    )\n    if (!allValid)\n      return true\n  }\n  return false\n})\n\nconst startValue = ref(modelValue.value?.start?.copy()) as Ref<TimeValue | undefined>\nconst endValue = ref(modelValue.value?.end?.copy()) as Ref<TimeValue | undefined>\n\nwatch([startValue, endValue], ([_startValue, _endValue]) => {\n  modelValue.value = { start: _startValue?.copy(), end: _endValue?.copy() }\n})\n\nconst convertedStartValue = computed({\n  get() {\n    if (isNullish(startValue.value))\n      return startValue.value\n    return convertValue(startValue.value)\n  },\n  set(newValue) {\n    if (newValue) {\n      startValue.value = startValue.value && 'day' in startValue.value ? newValue : new Time(newValue.hour, newValue.minute, newValue.second, startValue.value?.millisecond)\n    }\n    else {\n      startValue.value = newValue\n    }\n    return newValue\n  },\n})\n\nconst convertedEndValue = computed({\n  get() {\n    if (isNullish(endValue.value))\n      return endValue.value\n    return convertValue(endValue.value)\n  },\n  set(newValue) {\n    if (newValue) {\n      endValue.value = endValue.value && 'day' in endValue.value ? newValue : new Time(newValue.hour, newValue.minute, newValue.second, endValue.value?.millisecond)\n    }\n    else {\n      endValue.value = newValue\n    }\n    return newValue\n  },\n})\n\nconst convertedModelValue = computed(() => ({ start: convertedStartValue.value, end: convertedEndValue.value }))\n\nconst defaultDate = getDefaultTime({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: modelValue.value?.start,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<TimeValue>\n\nconst convertedPlaceholder = computed({\n  get() {\n    return convertValue(placeholder.value)\n  },\n  set(newValue) {\n    if (newValue)\n      placeholder.value = 'day' in placeholder.value ? newValue.copy() : new Time(newValue.hour, newValue.minute, newValue.second, placeholder.value?.millisecond)\n    return newValue\n  },\n})\n\nconst inferredGranularity = computed(() => {\n  if (granularity.value)\n    return granularity.value\n\n  return 'minute'\n})\n\nconst initialSegments = initializeTimeSegmentValues(inferredGranularity.value)\n\nconst startSegmentValues = ref<SegmentValueObj>(convertedStartValue.value ? { ...syncTimeSegmentValues({ value: convertedStartValue.value, formatter }) } : { ...initialSegments })\nconst endSegmentValues = ref<SegmentValueObj>(convertedEndValue.value ? { ...syncTimeSegmentValues({ value: convertedEndValue.value, formatter }) } : { ...initialSegments })\n\nconst startSegmentContent = computed(() => createContent({\n  granularity: inferredGranularity.value,\n  dateRef: convertedPlaceholder.value,\n  formatter,\n  hideTimeZone: props.hideTimeZone,\n  hourCycle: props.hourCycle,\n  segmentValues: startSegmentValues.value,\n  locale,\n  isTimeValue: true,\n}))\n\nconst endSegmentContent = computed(() => createContent({\n  granularity: inferredGranularity.value,\n  dateRef: convertedPlaceholder.value,\n  formatter,\n  hideTimeZone: props.hideTimeZone,\n  hourCycle: props.hourCycle,\n  segmentValues: endSegmentValues.value,\n  locale,\n  isTimeValue: true,\n}))\n\nconst segmentContents = computed(() => ({\n  start: startSegmentContent.value.arr,\n  end: endSegmentContent.value.arr,\n}))\n\nconst editableSegmentContents = computed(() => ({ start: segmentContents.value.start.filter(({ part }) => part !== 'literal'), end: segmentContents.value.end.filter(({ part }) => part !== 'literal') }))\n\nwatch(convertedModelValue, (_modelValue) => {\n  const isStartChanged = _modelValue?.start && convertedStartValue.value\n    ? _modelValue.start.compare(convertedStartValue.value) !== 0\n    : _modelValue?.start !== convertedStartValue.value\n  if (isStartChanged) {\n    convertedStartValue.value = _modelValue?.start?.copy()\n  }\n\n  const isEndChanged = _modelValue?.end && convertedEndValue.value\n    ? _modelValue.end.compare(convertedEndValue.value) !== 0\n    : _modelValue?.end !== convertedEndValue.value\n  if (isEndChanged) {\n    convertedEndValue.value = _modelValue?.end?.copy()\n  }\n})\n\nwatch([convertedStartValue, locale], ([_startValue]) => {\n  if (_startValue !== undefined) {\n    startSegmentValues.value = { ...syncSegmentValues({ value: _startValue, formatter }) }\n  }\n  // If segment has null value, means that user modified it, thus do not reset the segmentValues\n  else if (Object.values(startSegmentValues.value).every(value => value !== null) && _startValue === undefined) {\n    startSegmentValues.value = { ...initialSegments }\n  }\n})\n\nwatch(locale, (value) => {\n  if (formatter.getLocale() !== value) {\n    formatter.setLocale(value)\n    // Locale changed, so we need to clear the segment elements and re-get them (different order)\n    // Get the focusable elements again on the next tick\n    nextTick(() => {\n      segmentElements.value.clear()\n      getTimeFieldSegmentElements(parentElement.value).forEach(item => segmentElements.value.add(item as HTMLElement))\n    })\n  }\n})\n\nwatch(convertedModelValue, (_modelValue) => {\n  if (_modelValue && _modelValue.start !== undefined && placeholder.value.compare(_modelValue.start) !== 0)\n    placeholder.value = _modelValue.start.copy()\n})\n\nwatch([convertedEndValue, locale], ([_endValue]) => {\n  if (_endValue !== undefined) {\n    endSegmentValues.value = { ...syncSegmentValues({ value: _endValue, formatter }) }\n  }\n  // If segment has null value, means that user modified it, thus do not reset the segmentValues\n  else if (Object.values(endSegmentValues.value).every(value => value !== null) && _endValue === undefined) {\n    endSegmentValues.value = { ...initialSegments }\n  }\n})\n\nconst currentFocusedElement = ref<HTMLElement | null>(null)\n\nconst currentSegmentIndex = computed(() => Array.from(segmentElements.value).findIndex(el =>\n  el.getAttribute('data-reka-time-field-segment') === currentFocusedElement.value?.getAttribute('data-reka-time-field-segment')\n  && el.getAttribute('data-reka-time-range-field-segment-type') === currentFocusedElement.value?.getAttribute('data-reka-time-range-field-segment-type')))\n\nconst nextFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const nextCondition = sign < 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (nextCondition)\n    return null\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value + sign]\n  return segmentToFocus\n})\n\nconst prevFocusableSegment = computed(() => {\n  const sign = dir.value === 'rtl' ? -1 : 1\n  const prevCondition = sign > 0 ? currentSegmentIndex.value < 0 : currentSegmentIndex.value > segmentElements.value.size - 1\n  if (prevCondition)\n    return null\n\n  const segmentToFocus = Array.from(segmentElements.value)[currentSegmentIndex.value - sign]\n  return segmentToFocus\n})\n\nconst kbd = useKbd()\n\nfunction handleKeydown(e: KeyboardEvent) {\n  // Don't navigate between segments mid-composition, arrow keys are used for IME candidate navigation\n  if (e.isComposing)\n    return\n  if (!isSegmentNavigationKey(e.key))\n    return\n  if (e.key === kbd.ARROW_LEFT)\n    prevFocusableSegment.value?.focus()\n  if (e.key === kbd.ARROW_RIGHT)\n    nextFocusableSegment.value?.focus()\n}\n\nfunction setFocusedElement(el: HTMLElement) {\n  currentFocusedElement.value = el\n}\n\nprovideTimeRangeFieldRootContext({\n  locale,\n  startValue: convertedStartValue,\n  endValue: convertedEndValue,\n  placeholder: convertedPlaceholder,\n  disabled,\n  formatter,\n  hourCycle: props.hourCycle,\n  step,\n  readonly,\n  isInvalid,\n  segmentValues: { start: startSegmentValues, end: endSegmentValues },\n  segmentContents: editableSegmentContents,\n  elements: segmentElements,\n  setFocusedElement,\n  focusNext() {\n    nextFocusableSegment.value?.focus()\n  },\n})\n\ndefineExpose({\n  /** Helper to set the focused element inside the TimeRangeField */\n  setFocusedElement,\n})\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"$attrs\"\n    ref=\"primitiveElement\"\n    role=\"group\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n    @keydown.left.right=\"handleKeydown\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :segments=\"segmentContents\"\n      :is-invalid=\"isInvalid\"\n    />\n\n    <VisuallyHidden\n      :id=\"id\"\n      as=\"input\"\n      feature=\"focusable\"\n      tabindex=\"-1\"\n      :value=\"`${modelValue?.start?.toString()} - ${modelValue?.end?.toString()}`\"\n      :name=\"name\"\n      :disabled=\"disabled\"\n      :required=\"required\"\n      @focus=\"Array.from(segmentElements)?.[0]?.focus()\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateRangeType } from '@/DateRangeField/DateRangeFieldRoot.vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { SegmentPart } from '@/shared/date'\nimport { computed, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useDateField } from '@/shared/date/useDateField'\nimport { injectTimeRangeFieldRootContext } from './TimeRangeFieldRoot.vue'\n\nexport interface TimeRangeFieldInputProps extends PrimitiveProps {\n  /** The part of the date to render */\n  part: SegmentPart\n  /** The type of field to render (start or end) */\n  type: DateRangeType\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<TimeRangeFieldInputProps>()\n\nconst rootContext = injectTimeRangeFieldRootContext()\n\nconst hasLeftFocus = ref(true)\nconst lastKeyZero = ref(false)\n\nconst {\n  handleSegmentClick,\n  handleSegmentKeydown,\n  handleSegmentBeforeInput,\n  handleSegmentCompositionStart,\n  handleSegmentCompositionEnd,\n  attributes,\n} = useDateField({\n  hasLeftFocus,\n  lastKeyZero,\n  placeholder: rootContext.placeholder,\n  hourCycle: rootContext.hourCycle,\n  step: rootContext.step,\n  segmentValues: rootContext.segmentValues[props.type],\n  formatter: rootContext.formatter,\n  part: props.part,\n  disabled: rootContext.disabled,\n  readonly: rootContext.readonly,\n  focusNext: rootContext.focusNext,\n  modelValue: props.type === 'start' ? rootContext.startValue : rootContext.endValue,\n})\n\nconst disabled = computed(() => rootContext.disabled.value)\nconst readonly = computed(() => rootContext.readonly.value)\nconst isInvalid = computed(() => rootContext.isInvalid.value)\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    v-bind=\"attributes\"\n    :contenteditable=\"disabled || readonly ? false : part !== 'literal'\"\n    :data-reka-time-field-segment=\"part\"\n    :data-reka-time-range-field-segment-type=\"type\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :aria-readonly=\"readonly ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :aria-invalid=\"isInvalid ? true : undefined\"\n    v-on=\"part !== 'literal' ? {\n      mousedown: handleSegmentClick,\n      keydown: handleSegmentKeydown,\n      beforeinput: handleSegmentBeforeInput,\n      compositionstart: handleSegmentCompositionStart,\n      compositionend: handleSegmentCompositionEnd,\n      focusout: () => { hasLeftFocus = true },\n      focusin: (e: FocusEvent) => {\n        rootContext.setFocusedElement(e.target as HTMLElement)\n      },\n    } : {}\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateRangeType } from '@/DateRangeField/DateRangeFieldRoot.vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { SegmentPart } from '@/shared/date'\nimport { computed, ref } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { useDateField } from '@/shared/date/useDateField'\nimport { injectTimeRangeFieldRootContext } from './TimeRangeFieldRoot.vue'\n\nexport interface TimeRangeFieldInputProps extends PrimitiveProps {\n  /** The part of the date to render */\n  part: SegmentPart\n  /** The type of field to render (start or end) */\n  type: DateRangeType\n}\n</script>\n\n<script setup lang=\"ts\">\nconst props = defineProps<TimeRangeFieldInputProps>()\n\nconst rootContext = injectTimeRangeFieldRootContext()\n\nconst hasLeftFocus = ref(true)\nconst lastKeyZero = ref(false)\n\nconst {\n  handleSegmentClick,\n  handleSegmentKeydown,\n  handleSegmentBeforeInput,\n  handleSegmentCompositionStart,\n  handleSegmentCompositionEnd,\n  attributes,\n} = useDateField({\n  hasLeftFocus,\n  lastKeyZero,\n  placeholder: rootContext.placeholder,\n  hourCycle: rootContext.hourCycle,\n  step: rootContext.step,\n  segmentValues: rootContext.segmentValues[props.type],\n  formatter: rootContext.formatter,\n  part: props.part,\n  disabled: rootContext.disabled,\n  readonly: rootContext.readonly,\n  focusNext: rootContext.focusNext,\n  modelValue: props.type === 'start' ? rootContext.startValue : rootContext.endValue,\n})\n\nconst disabled = computed(() => rootContext.disabled.value)\nconst readonly = computed(() => rootContext.readonly.value)\nconst isInvalid = computed(() => rootContext.isInvalid.value)\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    v-bind=\"attributes\"\n    :contenteditable=\"disabled || readonly ? false : part !== 'literal'\"\n    :data-reka-time-field-segment=\"part\"\n    :data-reka-time-range-field-segment-type=\"type\"\n    :aria-disabled=\"disabled ? true : undefined\"\n    :aria-readonly=\"readonly ? true : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :aria-invalid=\"isInvalid ? true : undefined\"\n    v-on=\"part !== 'literal' ? {\n      mousedown: handleSegmentClick,\n      keydown: handleSegmentKeydown,\n      beforeinput: handleSegmentBeforeInput,\n      compositionstart: handleSegmentCompositionStart,\n      compositionend: handleSegmentCompositionEnd,\n      focusout: () => { hasLeftFocus = true },\n      focusin: (e: FocusEvent) => {\n        rootContext.setFocusedElement(e.target as HTMLElement)\n      },\n    } : {}\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ToastAnnounceExcludeProps extends PrimitiveProps {\n  altText?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\ndefineProps<ToastAnnounceExcludeProps>()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    data-reka-toast-announce-exclude=\"\"\n    :data-reka-toast-announce-alt=\"altText || undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ToastAnnounceExcludeProps extends PrimitiveProps {\n  altText?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\ndefineProps<ToastAnnounceExcludeProps>()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    data-reka-toast-announce-exclude=\"\"\n    :data-reka-toast-announce-alt=\"altText || undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { SwipeDirection } from './utils'\nimport { useCollection } from '@/Collection'\nimport { createContext } from '@/shared'\n\ntype ToastProviderContext = {\n  label: Ref<string>\n  duration: Ref<number>\n  disableSwipe: Ref<boolean>\n  swipeDirection: Ref<SwipeDirection>\n  swipeThreshold: Ref<number>\n  toastCount: Ref<number>\n  viewport: Ref<HTMLElement | undefined>\n  onViewportChange: (viewport: HTMLElement) => void\n  onToastAdd: () => void\n  onToastRemove: () => void\n  isFocusedToastEscapeKeyDownRef: Ref<boolean>\n  isClosePausedRef: Ref<boolean>\n}\n\nexport interface ToastProviderProps {\n  /**\n   * An author-localized label for each toast. Used to help screen reader users\n   * associate the interruption with a toast.\n   * @defaultValue 'Notification'\n   */\n  label?: string\n  /**\n   * Time in milliseconds that each toast should remain visible for.\n   * @defaultValue 5000\n   */\n  duration?: number\n  /**\n   * Whether to disable the ability to swipe to close the toast.\n   * @defaultValue false\n   */\n  disableSwipe?: boolean\n  /**\n   * Direction of pointer swipe that should close the toast.\n   * @defaultValue 'right'\n   */\n  swipeDirection?: SwipeDirection\n  /**\n   * Distance in pixels that the swipe must pass before a close is triggered.\n   * @defaultValue 50\n   */\n  swipeThreshold?: number\n}\n\nexport const [injectToastProviderContext, provideToastProviderContext]\n  = createContext<ToastProviderContext>('ToastProvider')\n</script>\n\n<script setup lang=\"ts\">\nimport { ref, toRefs } from 'vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ToastProviderProps>(), {\n  label: 'Notification',\n  duration: 5000,\n  swipeDirection: 'right',\n  swipeThreshold: 50,\n})\nconst { label, duration, disableSwipe, swipeDirection, swipeThreshold } = toRefs(props)\nuseCollection({ isProvider: true })\n\nconst viewport = ref<HTMLElement>()\nconst toastCount = ref(0)\nconst isFocusedToastEscapeKeyDownRef = ref(false)\nconst isClosePausedRef = ref(false)\n\nif (props.label && typeof props.label === 'string' && !props.label.trim()) {\n  const error = 'Invalid prop `label` supplied to `ToastProvider`. Expected non-empty `string`.'\n  throw new Error(error)\n}\n\nprovideToastProviderContext({\n  label,\n  duration,\n  disableSwipe,\n  swipeDirection,\n  swipeThreshold,\n  toastCount,\n  viewport,\n  onViewportChange(el) {\n    viewport.value = el\n  },\n  onToastAdd() {\n    toastCount.value++\n  },\n  onToastRemove() {\n    toastCount.value--\n  },\n  isFocusedToastEscapeKeyDownRef,\n  isClosePausedRef,\n\n})\n</script>\n\n<template>\n  <slot />\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { SwipeDirection } from './utils'\nimport { useCollection } from '@/Collection'\nimport { createContext } from '@/shared'\n\ntype ToastProviderContext = {\n  label: Ref<string>\n  duration: Ref<number>\n  disableSwipe: Ref<boolean>\n  swipeDirection: Ref<SwipeDirection>\n  swipeThreshold: Ref<number>\n  toastCount: Ref<number>\n  viewport: Ref<HTMLElement | undefined>\n  onViewportChange: (viewport: HTMLElement) => void\n  onToastAdd: () => void\n  onToastRemove: () => void\n  isFocusedToastEscapeKeyDownRef: Ref<boolean>\n  isClosePausedRef: Ref<boolean>\n}\n\nexport interface ToastProviderProps {\n  /**\n   * An author-localized label for each toast. Used to help screen reader users\n   * associate the interruption with a toast.\n   * @defaultValue 'Notification'\n   */\n  label?: string\n  /**\n   * Time in milliseconds that each toast should remain visible for.\n   * @defaultValue 5000\n   */\n  duration?: number\n  /**\n   * Whether to disable the ability to swipe to close the toast.\n   * @defaultValue false\n   */\n  disableSwipe?: boolean\n  /**\n   * Direction of pointer swipe that should close the toast.\n   * @defaultValue 'right'\n   */\n  swipeDirection?: SwipeDirection\n  /**\n   * Distance in pixels that the swipe must pass before a close is triggered.\n   * @defaultValue 50\n   */\n  swipeThreshold?: number\n}\n\nexport const [injectToastProviderContext, provideToastProviderContext]\n  = createContext<ToastProviderContext>('ToastProvider')\n</script>\n\n<script setup lang=\"ts\">\nimport { ref, toRefs } from 'vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ToastProviderProps>(), {\n  label: 'Notification',\n  duration: 5000,\n  swipeDirection: 'right',\n  swipeThreshold: 50,\n})\nconst { label, duration, disableSwipe, swipeDirection, swipeThreshold } = toRefs(props)\nuseCollection({ isProvider: true })\n\nconst viewport = ref<HTMLElement>()\nconst toastCount = ref(0)\nconst isFocusedToastEscapeKeyDownRef = ref(false)\nconst isClosePausedRef = ref(false)\n\nif (props.label && typeof props.label === 'string' && !props.label.trim()) {\n  const error = 'Invalid prop `label` supplied to `ToastProvider`. Expected non-empty `string`.'\n  throw new Error(error)\n}\n\nprovideToastProviderContext({\n  label,\n  duration,\n  disableSwipe,\n  swipeDirection,\n  swipeThreshold,\n  toastCount,\n  viewport,\n  onViewportChange(el) {\n    viewport.value = el\n  },\n  onToastAdd() {\n    toastCount.value++\n  },\n  onToastRemove() {\n    toastCount.value--\n  },\n  isFocusedToastEscapeKeyDownRef,\n  isClosePausedRef,\n\n})\n</script>\n\n<template>\n  <slot />\n</template>\n","<script setup lang=\"ts\">\nimport { isClient, useTimeout } from '@vueuse/shared'\nimport { onScopeDispose, ref } from 'vue'\nimport { VisuallyHidden } from '@/VisuallyHidden'\nimport { injectToastProviderContext } from './ToastProvider.vue'\n\nconst providerContext = injectToastProviderContext()\n\nconst isAnnounced = useTimeout(1000)\nconst renderAnnounceText = ref(false)\n\n// Render text content in the next frame to ensure toast is announced in NVDA.\n// Double rAF mirrors Radix UI's `useNextFrame` behavior.\nlet raf1 = 0\nlet raf2 = 0\nif (isClient) {\n  raf1 = requestAnimationFrame(() => {\n    raf2 = requestAnimationFrame(() => {\n      renderAnnounceText.value = true\n    })\n  })\n  onScopeDispose(() => {\n    cancelAnimationFrame(raf1)\n    cancelAnimationFrame(raf2)\n  })\n}\n</script>\n\n<template>\n  <VisuallyHidden\n    v-if=\"isAnnounced || renderAnnounceText\"\n    feature=\"fully-hidden\"\n  >\n    {{ providerContext.label.value }}\n    <slot />\n  </VisuallyHidden>\n</template>\n","<script setup lang=\"ts\">\nimport { isClient, useTimeout } from '@vueuse/shared'\nimport { onScopeDispose, ref } from 'vue'\nimport { VisuallyHidden } from '@/VisuallyHidden'\nimport { injectToastProviderContext } from './ToastProvider.vue'\n\nconst providerContext = injectToastProviderContext()\n\nconst isAnnounced = useTimeout(1000)\nconst renderAnnounceText = ref(false)\n\n// Render text content in the next frame to ensure toast is announced in NVDA.\n// Double rAF mirrors Radix UI's `useNextFrame` behavior.\nlet raf1 = 0\nlet raf2 = 0\nif (isClient) {\n  raf1 = requestAnimationFrame(() => {\n    raf2 = requestAnimationFrame(() => {\n      renderAnnounceText.value = true\n    })\n  })\n  onScopeDispose(() => {\n    cancelAnimationFrame(raf1)\n    cancelAnimationFrame(raf2)\n  })\n}\n</script>\n\n<template>\n  <VisuallyHidden\n    v-if=\"isAnnounced || renderAnnounceText\"\n    feature=\"fully-hidden\"\n  >\n    {{ providerContext.label.value }}\n    <slot />\n  </VisuallyHidden>\n</template>\n","export const TOAST_SWIPE_START = 'toast.swipeStart'\nexport const TOAST_SWIPE_MOVE = 'toast.swipeMove'\nexport const TOAST_SWIPE_CANCEL = 'toast.swipeCancel'\nexport const TOAST_SWIPE_END = 'toast.swipeEnd'\n\nexport const VIEWPORT_NAME = 'ToastViewport'\nexport const VIEWPORT_DEFAULT_HOTKEY = ['F8']\nexport const VIEWPORT_PAUSE = 'toast.viewportPause'\nexport const VIEWPORT_RESUME = 'toast.viewportResume'\n\nexport type SwipeDirection = 'up' | 'down' | 'left' | 'right'\n\nexport type SwipeEvent = { currentTarget: EventTarget & HTMLElement } & Omit<\n  CustomEvent<{ originalEvent: PointerEvent, delta: { x: number, y: number } }>,\n  'currentTarget'\n>\n\nexport function handleAndDispatchCustomEvent<\n  E extends CustomEvent,\n  OriginalEvent extends Event,\n>(\n  name: string,\n  handler: ((event: E) => void) | undefined,\n  detail: { originalEvent: OriginalEvent } & (E extends CustomEvent<infer D>\n    ? D\n    : never),\n) {\n  const currentTarget = detail.originalEvent.currentTarget as HTMLElement\n  const event = new CustomEvent(name, {\n    bubbles: false,\n    cancelable: true,\n    detail,\n  })\n  if (handler)\n    currentTarget.addEventListener(name, handler as EventListener, { once: true })\n\n  currentTarget.dispatchEvent(event)\n}\n\nexport function isDeltaInDirection(delta: { x: number, y: number }, direction: SwipeDirection, threshold = 0) {\n  const deltaX = Math.abs(delta.x)\n  const deltaY = Math.abs(delta.y)\n  const isDeltaX = deltaX > deltaY\n  if (direction === 'left' || direction === 'right')\n    return isDeltaX && deltaX > threshold\n  else\n    return !isDeltaX && deltaY > threshold\n}\n\nexport function isHTMLElement(node: any): node is HTMLElement {\n  return node.nodeType === node.ELEMENT_NODE\n}\n\nexport function getAnnounceTextContent(container: HTMLElement) {\n  const textContent: string[] = []\n  const childNodes = Array.from(container.childNodes)\n\n  childNodes.forEach((node) => {\n    if (node.nodeType === node.TEXT_NODE && node.textContent)\n      textContent.push(node.textContent)\n    if (isHTMLElement(node)) {\n      const isHidden = node.ariaHidden || node.hidden || node.style.display === 'none'\n      const isExcluded = node.dataset.rekaToastAnnounceExclude === ''\n\n      if (!isHidden) {\n        if (isExcluded) {\n          const altText = node.dataset.rekaToastAnnounceAlt\n          if (altText)\n            textContent.push(altText)\n        }\n        else {\n          textContent.push(...getAnnounceTextContent(node))\n        }\n      }\n    }\n  })\n  // We return a collection of text rather than a single concatenated string.\n  // This allows SR VO to naturally pause break between nodes while announcing.\n  return textContent\n}\n","<script lang=\"ts\">\nimport type { SwipeEvent } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { isClient } from '@vueuse/shared'\nimport { useCollection } from '@/Collection'\nimport { createContext, getActiveElement, useForwardExpose } from '@/shared'\n\nexport type ToastRootImplEmits = {\n  close: []\n  /** Event handler called when the escape key is down. It can be prevented by calling `event.preventDefault`. */\n  escapeKeyDown: [event: KeyboardEvent]\n  /** Event handler called when the dismiss timer is paused. This occurs when the pointer is moved over the viewport, the viewport is focused or when the window is blurred. */\n  pause: []\n  /** Event handler called when the dismiss timer is resumed. This occurs when the pointer is moved away from the viewport, the viewport is blurred or when the window is focused. */\n  resume: []\n  /** Event handler called when starting a swipe interaction. It can be prevented by calling `event.preventDefault`. */\n  swipeStart: [event: SwipeEvent]\n  /** Event handler called during a swipe interaction. It can be prevented by calling `event.preventDefault`. */\n  swipeMove: [event: SwipeEvent]\n  /** Event handler called when swipe interaction is cancelled. It can be prevented by calling `event.preventDefault`. */\n  swipeCancel: [event: SwipeEvent]\n  /** Event handler called at the end of a swipe interaction. It can be prevented by calling `event.preventDefault`. */\n  swipeEnd: [event: SwipeEvent]\n}\n\nexport interface ToastRootImplProps extends PrimitiveProps {\n  /**\n   * Control the sensitivity of the toast for accessibility purposes.\n   *\n   * For toasts that are the result of a user action, choose `foreground`. Toasts generated from background tasks should use `background`.\n   */\n  type?: 'foreground' | 'background'\n  /**\n   * The controlled open state of the dialog. Can be bind as `v-model:open`.\n   */\n  open?: boolean\n  /**\n   * Time in milliseconds that toast should remain visible for. Overrides value\n   * given to `ToastProvider`.\n   */\n  duration?: number\n}\n\nexport const [injectToastRootContext, provideToastRootContext]\n  = createContext<{ onClose: () => void }>('ToastRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { onKeyStroke, useRafFn } from '@vueuse/core'\nimport { computed, onMounted, onUnmounted, ref, watch, watchEffect } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport ToastAnnounce from './ToastAnnounce.vue'\nimport { injectToastProviderContext } from './ToastProvider.vue'\nimport { getAnnounceTextContent, handleAndDispatchCustomEvent, isDeltaInDirection, TOAST_SWIPE_CANCEL, TOAST_SWIPE_END, TOAST_SWIPE_MOVE, TOAST_SWIPE_START, VIEWPORT_PAUSE, VIEWPORT_RESUME } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ToastRootImplProps>(), {\n  open: false,\n  as: 'li',\n})\n\nconst emits = defineEmits<ToastRootImplEmits>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { CollectionItem } = useCollection()\n\nconst providerContext = injectToastProviderContext()\nconst pointerStartRef = ref<{ x: number, y: number } | null>(null)\nconst swipeDeltaRef = ref<{ x: number, y: number } | null>(null)\nconst duration = computed(\n  () => typeof props.duration === 'number'\n    ? props.duration\n    : providerContext.duration.value,\n)\n\nconst closeTimerStartTimeRef = ref(0)\nconst closeTimerRemainingTimeRef = ref(duration.value)\nconst closeTimerRef = ref(0)\nconst remainingTime = ref(duration.value)\n\nconst remainingRaf = useRafFn(() => {\n  const elapsedTime = Date.now() - closeTimerStartTimeRef.value\n  remainingTime.value = Math.max(closeTimerRemainingTimeRef.value - elapsedTime, 0)\n}, { fpsLimit: 60 })\n\nfunction startTimer(duration: number) {\n  if (duration <= 0 || duration === Number.POSITIVE_INFINITY)\n    return\n  // startTimer is used inside a watch with immediate set to true.\n  // This results in code execution during SSR.\n  // Ensure this code only runs in a browser environment\n  if (!isClient)\n    return\n  window.clearTimeout(closeTimerRef.value)\n  closeTimerStartTimeRef.value = Date.now()\n  closeTimerRef.value = window.setTimeout(handleClose, duration)\n}\n\nfunction handleClose(event?: PointerEvent) {\n  const isNonPointerEvent = event?.pointerType === ''\n\n  // reka: update to only perform focus when user focus via keyboard\n  // focus viewport if focus is within toast to read the remaining toast\n  // count to SR users and ensure focus isn't lost\n  const isFocusInToast = currentElement.value?.contains(getActiveElement())\n  if (isFocusInToast && isNonPointerEvent)\n    providerContext.viewport.value?.focus()\n\n  if (isNonPointerEvent) {\n    // when manually close the toast, we reset isClosePausedRef\n    providerContext.isClosePausedRef.value = false\n  }\n\n  emits('close')\n}\n\nconst announceTextContent = computed(() => currentElement.value ? getAnnounceTextContent(currentElement.value) : null)\n\nif (props.type && !['foreground', 'background'].includes(props.type)) {\n  const error = 'Invalid prop `type` supplied to `Toast`. Expected `foreground | background`.'\n  throw new Error(error)\n}\n\nwatchEffect((cleanupFn) => {\n  const viewport = providerContext.viewport.value\n  if (viewport) {\n    const handleResume = () => {\n      startTimer(closeTimerRemainingTimeRef.value)\n      remainingRaf.resume()\n      emits('resume')\n    }\n    const handlePause = () => {\n      const elapsedTime = Date.now() - closeTimerStartTimeRef.value\n      closeTimerRemainingTimeRef.value = closeTimerRemainingTimeRef.value - elapsedTime\n      window.clearTimeout(closeTimerRef.value)\n      remainingRaf.pause()\n      emits('pause')\n    }\n    viewport.addEventListener(VIEWPORT_PAUSE, handlePause)\n    viewport.addEventListener(VIEWPORT_RESUME, handleResume)\n    return () => {\n      viewport.removeEventListener(VIEWPORT_PAUSE, handlePause)\n      viewport.removeEventListener(VIEWPORT_RESUME, handleResume)\n    }\n  }\n})\n\n// start timer when toast opens or duration changes.\n// we include `open` in deps because closed !== unmounted when animating\n// so it could reopen before being completely unmounted\nwatch(() => [props.open, duration.value], () => {\n  // Reset the timer when the toast is rerendered with the new duration\n  closeTimerRemainingTimeRef.value = duration.value\n\n  if (props.open && !providerContext.isClosePausedRef.value)\n    startTimer(duration.value)\n}, { immediate: true })\n\nonKeyStroke('Escape', (event) => {\n  emits('escapeKeyDown', event)\n  if (!event.defaultPrevented) {\n    providerContext.isFocusedToastEscapeKeyDownRef.value = true\n    handleClose()\n  }\n})\n\nonMounted(() => {\n  providerContext.onToastAdd()\n})\nonUnmounted(() => {\n  providerContext.onToastRemove()\n})\n\nprovideToastRootContext({ onClose: handleClose })\n</script>\n\n<template>\n  <ToastAnnounce\n    v-if=\"announceTextContent\"\n    role=\"alert\"\n    :aria-live=\"type === 'foreground' ? 'assertive' : 'polite'\"\n  >\n    <!--\n      Render each chunk as its own text node so screen readers get the\n      natural pause break between nodes (see comment in utils.ts).\n      Interpolating the array directly with `{{ announceTextContent }}`\n      would route through Vue's `toDisplayString`, which JSON-stringifies\n      arrays — the live region would then announce literal `[`, quotes\n      and commas instead of the toast title and description.\n    -->\n    <template\n      v-for=\"(text, i) in announceTextContent\"\n      :key=\"i\"\n    >\n      {{ text }}\n    </template>\n  </ToastAnnounce>\n\n  <Teleport\n    v-if=\"providerContext.viewport.value\"\n    :to=\"providerContext.viewport.value\"\n  >\n    <CollectionItem>\n      <Primitive\n        :ref=\"forwardRef\"\n        tabindex=\"0\"\n        v-bind=\"$attrs\"\n        :as=\"as\"\n        :as-child=\"asChild\"\n        :data-state=\"open ? 'open' : 'closed'\"\n        :data-swipe-direction=\"providerContext.swipeDirection.value\"\n        :style=\"providerContext.disableSwipe.value\n          ? undefined\n          : { userSelect: 'none', touchAction: 'none' }\"\n        @pointerdown.left=\"(event: PointerEvent) => {\n          if (providerContext.disableSwipe.value) return;\n\n          pointerStartRef = { x: event.clientX, y: event.clientY };\n        }\"\n        @pointermove=\"(event: PointerEvent) => {\n          if (providerContext.disableSwipe.value || !pointerStartRef) return;\n\n          const x = event.clientX - pointerStartRef.x;\n          const y = event.clientY - pointerStartRef.y;\n          const hasSwipeMoveStarted = Boolean(swipeDeltaRef);\n          const isHorizontalSwipe = ['left', 'right'].includes(providerContext.swipeDirection.value);\n          const clamp = ['left', 'up'].includes(providerContext.swipeDirection.value)\n            ? Math.min\n            : Math.max;\n          const clampedX = isHorizontalSwipe ? clamp(0, x) : 0;\n          const clampedY = !isHorizontalSwipe ? clamp(0, y) : 0;\n          const moveStartBuffer = event.pointerType === 'touch' ? 10 : 2;\n          const delta = { x: clampedX, y: clampedY };\n          const eventDetail = { originalEvent: event, delta };\n          if (hasSwipeMoveStarted) {\n            swipeDeltaRef = delta;\n            handleAndDispatchCustomEvent(TOAST_SWIPE_MOVE, (ev: SwipeEvent) => emits('swipeMove', ev), eventDetail);\n          }\n          else if (isDeltaInDirection(delta, providerContext.swipeDirection.value, moveStartBuffer)) {\n            swipeDeltaRef = delta;\n            handleAndDispatchCustomEvent(TOAST_SWIPE_START, (ev: SwipeEvent) => emits('swipeStart', ev), eventDetail);\n            (event.target as HTMLElement).setPointerCapture(event.pointerId);\n          }\n          else if (Math.abs(x) > moveStartBuffer || Math.abs(y) > moveStartBuffer) {\n            // User is swiping in wrong direction so we disable swipe gesture\n            // for the current pointer down interaction\n            pointerStartRef = null;\n          }\n        }\"\n        @pointerup=\"(event: PointerEvent) => {\n          if (providerContext.disableSwipe.value) return;\n\n          const delta = swipeDeltaRef;\n          const target = event.target as HTMLElement;\n          if (target.hasPointerCapture(event.pointerId)) {\n            target.releasePointerCapture(event.pointerId);\n          }\n          swipeDeltaRef = null;\n          pointerStartRef = null;\n          if (delta) {\n            const toast = event.currentTarget;\n            const eventDetail = { originalEvent: event, delta };\n            if (\n              isDeltaInDirection(delta, providerContext.swipeDirection.value, providerContext.swipeThreshold.value)\n            ) {\n              handleAndDispatchCustomEvent(TOAST_SWIPE_END, (ev: SwipeEvent) => emits('swipeEnd', ev), eventDetail);\n            }\n            else {\n              handleAndDispatchCustomEvent(TOAST_SWIPE_CANCEL, (ev: SwipeEvent) => emits('swipeCancel', ev), eventDetail);\n            }\n            // Prevent click event from triggering on items within the toast when\n            // pointer up is part of a swipe gesture\n            toast?.addEventListener('click', (event) => event.preventDefault(), {\n              once: true,\n            });\n          }\n        }\"\n      >\n        <slot\n          :remaining=\"remainingTime\"\n          :duration=\"duration\"\n        />\n      </Primitive>\n    </CollectionItem>\n  </Teleport>\n</template>\n","<script lang=\"ts\">\nimport type { SwipeEvent } from './utils'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { isClient } from '@vueuse/shared'\nimport { useCollection } from '@/Collection'\nimport { createContext, getActiveElement, useForwardExpose } from '@/shared'\n\nexport type ToastRootImplEmits = {\n  close: []\n  /** Event handler called when the escape key is down. It can be prevented by calling `event.preventDefault`. */\n  escapeKeyDown: [event: KeyboardEvent]\n  /** Event handler called when the dismiss timer is paused. This occurs when the pointer is moved over the viewport, the viewport is focused or when the window is blurred. */\n  pause: []\n  /** Event handler called when the dismiss timer is resumed. This occurs when the pointer is moved away from the viewport, the viewport is blurred or when the window is focused. */\n  resume: []\n  /** Event handler called when starting a swipe interaction. It can be prevented by calling `event.preventDefault`. */\n  swipeStart: [event: SwipeEvent]\n  /** Event handler called during a swipe interaction. It can be prevented by calling `event.preventDefault`. */\n  swipeMove: [event: SwipeEvent]\n  /** Event handler called when swipe interaction is cancelled. It can be prevented by calling `event.preventDefault`. */\n  swipeCancel: [event: SwipeEvent]\n  /** Event handler called at the end of a swipe interaction. It can be prevented by calling `event.preventDefault`. */\n  swipeEnd: [event: SwipeEvent]\n}\n\nexport interface ToastRootImplProps extends PrimitiveProps {\n  /**\n   * Control the sensitivity of the toast for accessibility purposes.\n   *\n   * For toasts that are the result of a user action, choose `foreground`. Toasts generated from background tasks should use `background`.\n   */\n  type?: 'foreground' | 'background'\n  /**\n   * The controlled open state of the dialog. Can be bind as `v-model:open`.\n   */\n  open?: boolean\n  /**\n   * Time in milliseconds that toast should remain visible for. Overrides value\n   * given to `ToastProvider`.\n   */\n  duration?: number\n}\n\nexport const [injectToastRootContext, provideToastRootContext]\n  = createContext<{ onClose: () => void }>('ToastRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { onKeyStroke, useRafFn } from '@vueuse/core'\nimport { computed, onMounted, onUnmounted, ref, watch, watchEffect } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport ToastAnnounce from './ToastAnnounce.vue'\nimport { injectToastProviderContext } from './ToastProvider.vue'\nimport { getAnnounceTextContent, handleAndDispatchCustomEvent, isDeltaInDirection, TOAST_SWIPE_CANCEL, TOAST_SWIPE_END, TOAST_SWIPE_MOVE, TOAST_SWIPE_START, VIEWPORT_PAUSE, VIEWPORT_RESUME } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ToastRootImplProps>(), {\n  open: false,\n  as: 'li',\n})\n\nconst emits = defineEmits<ToastRootImplEmits>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { CollectionItem } = useCollection()\n\nconst providerContext = injectToastProviderContext()\nconst pointerStartRef = ref<{ x: number, y: number } | null>(null)\nconst swipeDeltaRef = ref<{ x: number, y: number } | null>(null)\nconst duration = computed(\n  () => typeof props.duration === 'number'\n    ? props.duration\n    : providerContext.duration.value,\n)\n\nconst closeTimerStartTimeRef = ref(0)\nconst closeTimerRemainingTimeRef = ref(duration.value)\nconst closeTimerRef = ref(0)\nconst remainingTime = ref(duration.value)\n\nconst remainingRaf = useRafFn(() => {\n  const elapsedTime = Date.now() - closeTimerStartTimeRef.value\n  remainingTime.value = Math.max(closeTimerRemainingTimeRef.value - elapsedTime, 0)\n}, { fpsLimit: 60 })\n\nfunction startTimer(duration: number) {\n  if (duration <= 0 || duration === Number.POSITIVE_INFINITY)\n    return\n  // startTimer is used inside a watch with immediate set to true.\n  // This results in code execution during SSR.\n  // Ensure this code only runs in a browser environment\n  if (!isClient)\n    return\n  window.clearTimeout(closeTimerRef.value)\n  closeTimerStartTimeRef.value = Date.now()\n  closeTimerRef.value = window.setTimeout(handleClose, duration)\n}\n\nfunction handleClose(event?: PointerEvent) {\n  const isNonPointerEvent = event?.pointerType === ''\n\n  // reka: update to only perform focus when user focus via keyboard\n  // focus viewport if focus is within toast to read the remaining toast\n  // count to SR users and ensure focus isn't lost\n  const isFocusInToast = currentElement.value?.contains(getActiveElement())\n  if (isFocusInToast && isNonPointerEvent)\n    providerContext.viewport.value?.focus()\n\n  if (isNonPointerEvent) {\n    // when manually close the toast, we reset isClosePausedRef\n    providerContext.isClosePausedRef.value = false\n  }\n\n  emits('close')\n}\n\nconst announceTextContent = computed(() => currentElement.value ? getAnnounceTextContent(currentElement.value) : null)\n\nif (props.type && !['foreground', 'background'].includes(props.type)) {\n  const error = 'Invalid prop `type` supplied to `Toast`. Expected `foreground | background`.'\n  throw new Error(error)\n}\n\nwatchEffect((cleanupFn) => {\n  const viewport = providerContext.viewport.value\n  if (viewport) {\n    const handleResume = () => {\n      startTimer(closeTimerRemainingTimeRef.value)\n      remainingRaf.resume()\n      emits('resume')\n    }\n    const handlePause = () => {\n      const elapsedTime = Date.now() - closeTimerStartTimeRef.value\n      closeTimerRemainingTimeRef.value = closeTimerRemainingTimeRef.value - elapsedTime\n      window.clearTimeout(closeTimerRef.value)\n      remainingRaf.pause()\n      emits('pause')\n    }\n    viewport.addEventListener(VIEWPORT_PAUSE, handlePause)\n    viewport.addEventListener(VIEWPORT_RESUME, handleResume)\n    return () => {\n      viewport.removeEventListener(VIEWPORT_PAUSE, handlePause)\n      viewport.removeEventListener(VIEWPORT_RESUME, handleResume)\n    }\n  }\n})\n\n// start timer when toast opens or duration changes.\n// we include `open` in deps because closed !== unmounted when animating\n// so it could reopen before being completely unmounted\nwatch(() => [props.open, duration.value], () => {\n  // Reset the timer when the toast is rerendered with the new duration\n  closeTimerRemainingTimeRef.value = duration.value\n\n  if (props.open && !providerContext.isClosePausedRef.value)\n    startTimer(duration.value)\n}, { immediate: true })\n\nonKeyStroke('Escape', (event) => {\n  emits('escapeKeyDown', event)\n  if (!event.defaultPrevented) {\n    providerContext.isFocusedToastEscapeKeyDownRef.value = true\n    handleClose()\n  }\n})\n\nonMounted(() => {\n  providerContext.onToastAdd()\n})\nonUnmounted(() => {\n  providerContext.onToastRemove()\n})\n\nprovideToastRootContext({ onClose: handleClose })\n</script>\n\n<template>\n  <ToastAnnounce\n    v-if=\"announceTextContent\"\n    role=\"alert\"\n    :aria-live=\"type === 'foreground' ? 'assertive' : 'polite'\"\n  >\n    <!--\n      Render each chunk as its own text node so screen readers get the\n      natural pause break between nodes (see comment in utils.ts).\n      Interpolating the array directly with `{{ announceTextContent }}`\n      would route through Vue's `toDisplayString`, which JSON-stringifies\n      arrays — the live region would then announce literal `[`, quotes\n      and commas instead of the toast title and description.\n    -->\n    <template\n      v-for=\"(text, i) in announceTextContent\"\n      :key=\"i\"\n    >\n      {{ text }}\n    </template>\n  </ToastAnnounce>\n\n  <Teleport\n    v-if=\"providerContext.viewport.value\"\n    :to=\"providerContext.viewport.value\"\n  >\n    <CollectionItem>\n      <Primitive\n        :ref=\"forwardRef\"\n        tabindex=\"0\"\n        v-bind=\"$attrs\"\n        :as=\"as\"\n        :as-child=\"asChild\"\n        :data-state=\"open ? 'open' : 'closed'\"\n        :data-swipe-direction=\"providerContext.swipeDirection.value\"\n        :style=\"providerContext.disableSwipe.value\n          ? undefined\n          : { userSelect: 'none', touchAction: 'none' }\"\n        @pointerdown.left=\"(event: PointerEvent) => {\n          if (providerContext.disableSwipe.value) return;\n\n          pointerStartRef = { x: event.clientX, y: event.clientY };\n        }\"\n        @pointermove=\"(event: PointerEvent) => {\n          if (providerContext.disableSwipe.value || !pointerStartRef) return;\n\n          const x = event.clientX - pointerStartRef.x;\n          const y = event.clientY - pointerStartRef.y;\n          const hasSwipeMoveStarted = Boolean(swipeDeltaRef);\n          const isHorizontalSwipe = ['left', 'right'].includes(providerContext.swipeDirection.value);\n          const clamp = ['left', 'up'].includes(providerContext.swipeDirection.value)\n            ? Math.min\n            : Math.max;\n          const clampedX = isHorizontalSwipe ? clamp(0, x) : 0;\n          const clampedY = !isHorizontalSwipe ? clamp(0, y) : 0;\n          const moveStartBuffer = event.pointerType === 'touch' ? 10 : 2;\n          const delta = { x: clampedX, y: clampedY };\n          const eventDetail = { originalEvent: event, delta };\n          if (hasSwipeMoveStarted) {\n            swipeDeltaRef = delta;\n            handleAndDispatchCustomEvent(TOAST_SWIPE_MOVE, (ev: SwipeEvent) => emits('swipeMove', ev), eventDetail);\n          }\n          else if (isDeltaInDirection(delta, providerContext.swipeDirection.value, moveStartBuffer)) {\n            swipeDeltaRef = delta;\n            handleAndDispatchCustomEvent(TOAST_SWIPE_START, (ev: SwipeEvent) => emits('swipeStart', ev), eventDetail);\n            (event.target as HTMLElement).setPointerCapture(event.pointerId);\n          }\n          else if (Math.abs(x) > moveStartBuffer || Math.abs(y) > moveStartBuffer) {\n            // User is swiping in wrong direction so we disable swipe gesture\n            // for the current pointer down interaction\n            pointerStartRef = null;\n          }\n        }\"\n        @pointerup=\"(event: PointerEvent) => {\n          if (providerContext.disableSwipe.value) return;\n\n          const delta = swipeDeltaRef;\n          const target = event.target as HTMLElement;\n          if (target.hasPointerCapture(event.pointerId)) {\n            target.releasePointerCapture(event.pointerId);\n          }\n          swipeDeltaRef = null;\n          pointerStartRef = null;\n          if (delta) {\n            const toast = event.currentTarget;\n            const eventDetail = { originalEvent: event, delta };\n            if (\n              isDeltaInDirection(delta, providerContext.swipeDirection.value, providerContext.swipeThreshold.value)\n            ) {\n              handleAndDispatchCustomEvent(TOAST_SWIPE_END, (ev: SwipeEvent) => emits('swipeEnd', ev), eventDetail);\n            }\n            else {\n              handleAndDispatchCustomEvent(TOAST_SWIPE_CANCEL, (ev: SwipeEvent) => emits('swipeCancel', ev), eventDetail);\n            }\n            // Prevent click event from triggering on items within the toast when\n            // pointer up is part of a swipe gesture\n            toast?.addEventListener('click', (event) => event.preventDefault(), {\n              once: true,\n            });\n          }\n        }\"\n      >\n        <slot\n          :remaining=\"remainingTime\"\n          :duration=\"duration\"\n        />\n      </Primitive>\n    </CollectionItem>\n  </Teleport>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ToastCloseProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport ToastAnnounceExclude from './ToastAnnounceExclude.vue'\nimport { injectToastRootContext } from './ToastRootImpl.vue'\n\nconst props = withDefaults(defineProps<ToastCloseProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectToastRootContext()\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <ToastAnnounceExclude as-child>\n    <Primitive\n      v-bind=\"props\"\n      :ref=\"forwardRef\"\n      :type=\"as === 'button' ? 'button' : undefined \"\n      @click=\"rootContext.onClose\"\n    >\n      <slot />\n    </Primitive>\n  </ToastAnnounceExclude>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ToastCloseProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport ToastAnnounceExclude from './ToastAnnounceExclude.vue'\nimport { injectToastRootContext } from './ToastRootImpl.vue'\n\nconst props = withDefaults(defineProps<ToastCloseProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectToastRootContext()\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <ToastAnnounceExclude as-child>\n    <Primitive\n      v-bind=\"props\"\n      :ref=\"forwardRef\"\n      :type=\"as === 'button' ? 'button' : undefined \"\n      @click=\"rootContext.onClose\"\n    >\n      <slot />\n    </Primitive>\n  </ToastAnnounceExclude>\n</template>\n","<script lang=\"ts\">\nimport type { ToastCloseProps } from './ToastClose.vue'\n\nexport interface ToastActionProps extends ToastCloseProps {\n  /**\n   * A short description for an alternate way to carry out the action. For screen reader users\n   * who will not be able to navigate to the button easily/quickly.\n   * @example <ToastAction altText=\"Goto account settings to upgrade\">Upgrade</ToastAction>\n   * @example <ToastAction altText=\"Undo (Alt+U)\">Undo</ToastAction>\n   */\n  altText: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useForwardExpose } from '@/shared'\nimport ToastAnnounceExclude from './ToastAnnounceExclude.vue'\nimport ToastClose from './ToastClose.vue'\n\nconst props = defineProps<ToastActionProps>()\n\nif (!props.altText)\n  throw new Error('Missing prop `altText` expected on `ToastAction`')\n\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <ToastAnnounceExclude\n    v-if=\"altText\"\n    :alt-text=\"altText\"\n    as-child\n  >\n    <ToastClose\n      :ref=\"forwardRef\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n    >\n      <slot />\n    </ToastClose>\n  </ToastAnnounceExclude>\n</template>\n","<script lang=\"ts\">\nimport type { ToastCloseProps } from './ToastClose.vue'\n\nexport interface ToastActionProps extends ToastCloseProps {\n  /**\n   * A short description for an alternate way to carry out the action. For screen reader users\n   * who will not be able to navigate to the button easily/quickly.\n   * @example <ToastAction altText=\"Goto account settings to upgrade\">Upgrade</ToastAction>\n   * @example <ToastAction altText=\"Undo (Alt+U)\">Undo</ToastAction>\n   */\n  altText: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useForwardExpose } from '@/shared'\nimport ToastAnnounceExclude from './ToastAnnounceExclude.vue'\nimport ToastClose from './ToastClose.vue'\n\nconst props = defineProps<ToastActionProps>()\n\nif (!props.altText)\n  throw new Error('Missing prop `altText` expected on `ToastAction`')\n\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <ToastAnnounceExclude\n    v-if=\"altText\"\n    :alt-text=\"altText\"\n    as-child\n  >\n    <ToastClose\n      :ref=\"forwardRef\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n    >\n      <slot />\n    </ToastClose>\n  </ToastAnnounceExclude>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ToastDescriptionProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<ToastDescriptionProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ToastDescriptionProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<ToastDescriptionProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface ToastPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<ToastPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface ToastPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<ToastPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { ToastRootImplEmits, ToastRootImplProps } from './ToastRootImpl.vue'\nimport { useForwardExpose } from '@/shared'\n\nexport type ToastRootEmits = Omit<ToastRootImplEmits, 'close'> & {\n  /** Event handler called when the open state changes */\n  'update:open': [value: boolean]\n}\n\nexport interface ToastRootProps extends ToastRootImplProps {\n  /** The open state of the dialog when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { Presence } from '@/Presence'\nimport ToastRootImpl from './ToastRootImpl.vue'\n\nconst props = withDefaults(defineProps<ToastRootProps>(), {\n  type: 'foreground',\n  open: undefined,\n  defaultOpen: true,\n  as: 'li',\n})\n\nconst emits = defineEmits<ToastRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n    /** Remaining time (in ms) */\n    remaining: number\n    /** Total time the toast will remain visible for (in ms) */\n    duration: number\n  }) => any\n}>()\n\nconst { forwardRef } = useForwardExpose()\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n</script>\n\n<template>\n  <Presence :present=\"forceMount || open\">\n    <ToastRootImpl\n      :ref=\"forwardRef\"\n      v-slot=\"{ remaining, duration: _duration }\"\n      :open=\"open\"\n      :type=\"type\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :duration=\"duration\"\n      v-bind=\"$attrs\"\n      @close=\"open = false\"\n      @pause=\"emits('pause')\"\n      @resume=\"emits('resume')\"\n      @escape-key-down=\"emits('escapeKeyDown', $event)\"\n      @swipe-start=\"(event) => {\n        emits('swipeStart', event);\n        if (!event.defaultPrevented) {\n          (event.currentTarget as HTMLElement).setAttribute('data-swipe', 'start');\n        }\n      }\"\n      @swipe-move=\"(event) => {\n        emits('swipeMove', event);\n        if (!event.defaultPrevented) {\n          const { x, y } = event.detail.delta;\n          const target = event.currentTarget as HTMLElement\n          target.setAttribute('data-swipe', 'move');\n          target.style.setProperty('--reka-toast-swipe-move-x', `${x}px`);\n          target.style.setProperty('--reka-toast-swipe-move-y', `${y}px`);\n        }\n      }\"\n      @swipe-cancel=\"(event) => {\n        emits('swipeCancel', event);\n        if (!event.defaultPrevented) {\n          const target = event.currentTarget as HTMLElement\n          target.setAttribute('data-swipe', 'cancel');\n          target.style.removeProperty('--reka-toast-swipe-move-x');\n          target.style.removeProperty('--reka-toast-swipe-move-y');\n          target.style.removeProperty('--reka-toast-swipe-end-x');\n          target.style.removeProperty('--reka-toast-swipe-end-y');\n        }\n      }\"\n      @swipe-end=\"(event) => {\n        emits('swipeEnd', event);\n        if (!event.defaultPrevented) {\n          const { x, y } = event.detail.delta;\n          const target = event.currentTarget as HTMLElement\n          target.setAttribute('data-swipe', 'end');\n          target.style.removeProperty('--reka-toast-swipe-move-x');\n          target.style.removeProperty('--reka-toast-swipe-move-y');\n          target.style.setProperty('--reka-toast-swipe-end-x', `${x}px`);\n          target.style.setProperty('--reka-toast-swipe-end-y', `${y}px`);\n          open = false;\n        }\n      }\"\n    >\n      <slot\n        :remaining=\"remaining\"\n        :duration=\"_duration\"\n        :open=\"open\"\n      />\n    </ToastRootImpl>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { ToastRootImplEmits, ToastRootImplProps } from './ToastRootImpl.vue'\nimport { useForwardExpose } from '@/shared'\n\nexport type ToastRootEmits = Omit<ToastRootImplEmits, 'close'> & {\n  /** Event handler called when the open state changes */\n  'update:open': [value: boolean]\n}\n\nexport interface ToastRootProps extends ToastRootImplProps {\n  /** The open state of the dialog when it is initially rendered. Use when you do not need to control its open state. */\n  defaultOpen?: boolean\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { Presence } from '@/Presence'\nimport ToastRootImpl from './ToastRootImpl.vue'\n\nconst props = withDefaults(defineProps<ToastRootProps>(), {\n  type: 'foreground',\n  open: undefined,\n  defaultOpen: true,\n  as: 'li',\n})\n\nconst emits = defineEmits<ToastRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n    /** Remaining time (in ms) */\n    remaining: number\n    /** Total time the toast will remain visible for (in ms) */\n    duration: number\n  }) => any\n}>()\n\nconst { forwardRef } = useForwardExpose()\nconst open = useVModel(props, 'open', emits, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n</script>\n\n<template>\n  <Presence :present=\"forceMount || open\">\n    <ToastRootImpl\n      :ref=\"forwardRef\"\n      v-slot=\"{ remaining, duration: _duration }\"\n      :open=\"open\"\n      :type=\"type\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :duration=\"duration\"\n      v-bind=\"$attrs\"\n      @close=\"open = false\"\n      @pause=\"emits('pause')\"\n      @resume=\"emits('resume')\"\n      @escape-key-down=\"emits('escapeKeyDown', $event)\"\n      @swipe-start=\"(event) => {\n        emits('swipeStart', event);\n        if (!event.defaultPrevented) {\n          (event.currentTarget as HTMLElement).setAttribute('data-swipe', 'start');\n        }\n      }\"\n      @swipe-move=\"(event) => {\n        emits('swipeMove', event);\n        if (!event.defaultPrevented) {\n          const { x, y } = event.detail.delta;\n          const target = event.currentTarget as HTMLElement\n          target.setAttribute('data-swipe', 'move');\n          target.style.setProperty('--reka-toast-swipe-move-x', `${x}px`);\n          target.style.setProperty('--reka-toast-swipe-move-y', `${y}px`);\n        }\n      }\"\n      @swipe-cancel=\"(event) => {\n        emits('swipeCancel', event);\n        if (!event.defaultPrevented) {\n          const target = event.currentTarget as HTMLElement\n          target.setAttribute('data-swipe', 'cancel');\n          target.style.removeProperty('--reka-toast-swipe-move-x');\n          target.style.removeProperty('--reka-toast-swipe-move-y');\n          target.style.removeProperty('--reka-toast-swipe-end-x');\n          target.style.removeProperty('--reka-toast-swipe-end-y');\n        }\n      }\"\n      @swipe-end=\"(event) => {\n        emits('swipeEnd', event);\n        if (!event.defaultPrevented) {\n          const { x, y } = event.detail.delta;\n          const target = event.currentTarget as HTMLElement\n          target.setAttribute('data-swipe', 'end');\n          target.style.removeProperty('--reka-toast-swipe-move-x');\n          target.style.removeProperty('--reka-toast-swipe-move-y');\n          target.style.setProperty('--reka-toast-swipe-end-x', `${x}px`);\n          target.style.setProperty('--reka-toast-swipe-end-y', `${y}px`);\n          open = false;\n        }\n      }\"\n    >\n      <slot\n        :remaining=\"remaining\"\n        :duration=\"_duration\"\n        :open=\"open\"\n      />\n    </ToastRootImpl>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ToastTitleProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<ToastTitleProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ToastTitleProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<ToastTitleProps>()\nuseForwardExpose()\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script setup lang=\"ts\">\nimport { VisuallyHidden } from '@/VisuallyHidden'\nimport { injectToastProviderContext } from './ToastProvider.vue'\n\nconst emits = defineEmits<{\n  focusFromOutsideViewport: [void]\n}>()\n\nconst providerContext = injectToastProviderContext()\n</script>\n\n<template>\n  <VisuallyHidden\n    tabindex=\"0\"\n    style=\"position: fixed\"\n    @focus=\"(event: FocusEvent) => {\n      const prevFocusedElement = event.relatedTarget as HTMLElement | null;\n      const isFocusFromOutsideViewport = !providerContext.viewport.value?.contains(prevFocusedElement);\n      if (isFocusFromOutsideViewport) emits('focusFromOutsideViewport');\n    }\"\n  >\n    <slot />\n  </VisuallyHidden>\n</template>\n","<script setup lang=\"ts\">\nimport { VisuallyHidden } from '@/VisuallyHidden'\nimport { injectToastProviderContext } from './ToastProvider.vue'\n\nconst emits = defineEmits<{\n  focusFromOutsideViewport: [void]\n}>()\n\nconst providerContext = injectToastProviderContext()\n</script>\n\n<template>\n  <VisuallyHidden\n    tabindex=\"0\"\n    style=\"position: fixed\"\n    @focus=\"(event: FocusEvent) => {\n      const prevFocusedElement = event.relatedTarget as HTMLElement | null;\n      const isFocusFromOutsideViewport = !providerContext.viewport.value?.contains(prevFocusedElement);\n      if (isFocusFromOutsideViewport) emits('focusFromOutsideViewport');\n    }\"\n  >\n    <slot />\n  </VisuallyHidden>\n</template>\n","<script lang=\"ts\">\nimport type { ComponentPublicInstance } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { getActiveElement, useForwardExpose } from '@/shared'\n\nexport interface ToastViewportProps extends PrimitiveProps {\n  /**\n   * The keys to use as the keyboard shortcut that will move focus to the toast viewport.\n   * @defaultValue ['F8']\n   */\n  hotkey?: string[]\n  /**\n   * An author-localized label for the toast viewport to provide context for screen reader users\n   * when navigating page landmarks. The available `{hotkey}` placeholder will be replaced for you.\n   * Alternatively, you can pass in a custom function to generate the label.\n   * @defaultValue 'Notifications ({hotkey})'\n   */\n  label?: string | ((hotkey: string) => string)\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { onKeyStroke, unrefElement } from '@vueuse/core'\nimport { computed, onMounted, ref, toRefs, watchEffect } from 'vue'\nimport { DismissableLayerBranch } from '@/DismissableLayer'\nimport { focusFirst, getTabbableCandidates } from '@/FocusScope/utils'\nimport { Primitive } from '@/Primitive'\nimport FocusProxy from './FocusProxy.vue'\nimport { injectToastProviderContext } from './ToastProvider.vue'\nimport { VIEWPORT_PAUSE, VIEWPORT_RESUME } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ToastViewportProps>(), {\n  hotkey: () => ['F8'], // from VIEWPORT_DEFAULT_HOTKEY\n  label: 'Notifications ({hotkey})',\n  as: 'ol',\n})\nconst { hotkey, label } = toRefs(props)\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { CollectionSlot, getItems } = useCollection()\nconst providerContext = injectToastProviderContext()\nconst hasToasts = computed(() => providerContext.toastCount.value > 0)\nconst headFocusProxyRef = ref<HTMLElement>()\nconst tailFocusProxyRef = ref<HTMLElement>()\n\nconst KEY_RE = /Key/g\nconst DIGIT_RE = /Digit/g\nconst hotkeyMessage = computed(() => hotkey.value.join('+').replace(KEY_RE, '').replace(DIGIT_RE, ''))\n\nonKeyStroke(hotkey.value, () => {\n  currentElement.value.focus()\n})\n\nonMounted(() => {\n  providerContext.onViewportChange(currentElement.value)\n})\n\nwatchEffect((cleanupFn) => {\n  const viewport = currentElement.value\n  if (hasToasts.value && viewport) {\n    const handlePause = () => {\n      if (!providerContext.isClosePausedRef.value) {\n        const pauseEvent = new CustomEvent(VIEWPORT_PAUSE)\n        viewport.dispatchEvent(pauseEvent)\n        providerContext.isClosePausedRef.value = true\n      }\n    }\n\n    const handleResume = () => {\n      if (providerContext.isClosePausedRef.value) {\n        const resumeEvent = new CustomEvent(VIEWPORT_RESUME)\n        viewport.dispatchEvent(resumeEvent)\n        providerContext.isClosePausedRef.value = false\n      }\n    }\n\n    const handleFocusOutResume = (event: FocusEvent) => {\n      const isFocusMovingOutside = !viewport.contains(event.relatedTarget as HTMLElement)\n      if (isFocusMovingOutside)\n        handleResume()\n    }\n\n    const handlePointerLeaveResume = () => {\n      const isFocusInside = viewport.contains(getActiveElement())\n      if (!isFocusInside)\n        handleResume()\n    }\n\n    // We programmatically manage tabbing as we are unable to influence\n    // the source order with portals, this allows us to reverse the\n    // tab order so that it runs from most recent toast to least\n    const handleKeyDown = (event: KeyboardEvent) => {\n      const isMetaKey = event.altKey || event.ctrlKey || event.metaKey\n      const isTabKey = event.key === 'Tab' && !isMetaKey\n\n      if (isTabKey) {\n        const focusedElement = getActiveElement()\n        const isTabbingBackwards = event.shiftKey\n        const targetIsViewport = event.target === viewport\n\n        // If we're back tabbing after jumping to the viewport then we simply\n        // proxy focus out to the preceding document\n        if (targetIsViewport && isTabbingBackwards) {\n          headFocusProxyRef.value?.focus()\n          return\n        }\n\n        const tabbingDirection = isTabbingBackwards ? 'backwards' : 'forwards'\n        const sortedCandidates = getSortedTabbableCandidates({ tabbingDirection })\n        const index = sortedCandidates.findIndex(candidate => candidate === focusedElement)\n        if (focusFirst(sortedCandidates.slice(index + 1))) {\n          event.preventDefault()\n        }\n        else {\n          // If we can't focus that means we're at the edges so we\n          // proxy to the corresponding exit point and let the browser handle\n          // tab/shift+tab keypress and implicitly pass focus to the next valid element in the document\n          isTabbingBackwards\n            ? headFocusProxyRef.value?.focus()\n            : tailFocusProxyRef.value?.focus()\n        }\n      }\n    }\n\n    viewport.addEventListener('focusin', handlePause)\n    viewport.addEventListener('focusout', handleFocusOutResume)\n    viewport.addEventListener('pointermove', handlePause)\n    viewport.addEventListener('pointerleave', handlePointerLeaveResume)\n    viewport.addEventListener('keydown', handleKeyDown)\n    window.addEventListener('blur', handlePause)\n    window.addEventListener('focus', handleResume)\n\n    cleanupFn(() => {\n      viewport.removeEventListener('focusin', handlePause)\n      viewport.removeEventListener('focusout', handleFocusOutResume)\n      viewport.removeEventListener('pointermove', handlePause)\n      viewport.removeEventListener('pointerleave', handlePointerLeaveResume)\n      viewport.removeEventListener('keydown', handleKeyDown)\n      window.removeEventListener('blur', handlePause)\n      window.removeEventListener('focus', handleResume)\n    })\n  }\n})\n\nfunction getSortedTabbableCandidates({ tabbingDirection }: { tabbingDirection: 'forwards' | 'backwards' }) {\n  const toastItems = getItems().map(i => i.ref)\n  const tabbableCandidates = toastItems.map((toastNode) => {\n    const toastTabbableCandidates = [toastNode, ...getTabbableCandidates(toastNode)]\n    return tabbingDirection === 'forwards'\n      ? toastTabbableCandidates\n      : toastTabbableCandidates.reverse()\n  })\n  return (\n    tabbingDirection === 'forwards' ? tabbableCandidates.reverse() : tabbableCandidates\n  ).flat()\n}\n</script>\n\n<template>\n  <DismissableLayerBranch\n    role=\"region\"\n    :aria-label=\"typeof label === 'string' ? label.replace('{hotkey}', hotkeyMessage) : label(hotkeyMessage)\"\n    tabindex=\"-1\"\n    :style=\"{\n      // incase list has size when empty (e.g. padding), we remove pointer events so\n      // it doesn't prevent interactions with page elements that it overlays\n      pointerEvents: hasToasts ? undefined : 'none',\n    }\"\n  >\n    <FocusProxy\n      v-if=\"hasToasts\"\n      :ref=\"(node: Element | ComponentPublicInstance | null) => {\n        if (!node) return undefined\n        headFocusProxyRef = unrefElement(node as ComponentPublicInstance) as HTMLElement\n        return undefined\n      }\"\n      @focus-from-outside-viewport=\"() => {\n        const tabbableCandidates = getSortedTabbableCandidates({\n          tabbingDirection: 'forwards',\n        })\n        focusFirst(tabbableCandidates)\n      }\"\n    />\n    <CollectionSlot>\n      <Primitive\n        :ref=\"forwardRef\"\n        tabindex=\"-1\"\n        :as=\"as\"\n        :as-child=\"asChild\"\n        v-bind=\"$attrs\"\n      >\n        <slot />\n      </Primitive>\n    </CollectionSlot>\n    <FocusProxy\n      v-if=\"hasToasts\"\n      :ref=\"(node: Element | ComponentPublicInstance | null) => {\n        if (!node) return undefined\n        tailFocusProxyRef = unrefElement(node as ComponentPublicInstance) as HTMLElement\n        return undefined\n      }\"\n      @focus-from-outside-viewport=\"() => {\n        const tabbableCandidates = getSortedTabbableCandidates({\n          tabbingDirection: 'backwards',\n        })\n        focusFirst(tabbableCandidates)\n      }\"\n    />\n  </DismissableLayerBranch>\n</template>\n","<script lang=\"ts\">\nimport type { ComponentPublicInstance } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useCollection } from '@/Collection'\nimport { getActiveElement, useForwardExpose } from '@/shared'\n\nexport interface ToastViewportProps extends PrimitiveProps {\n  /**\n   * The keys to use as the keyboard shortcut that will move focus to the toast viewport.\n   * @defaultValue ['F8']\n   */\n  hotkey?: string[]\n  /**\n   * An author-localized label for the toast viewport to provide context for screen reader users\n   * when navigating page landmarks. The available `{hotkey}` placeholder will be replaced for you.\n   * Alternatively, you can pass in a custom function to generate the label.\n   * @defaultValue 'Notifications ({hotkey})'\n   */\n  label?: string | ((hotkey: string) => string)\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { onKeyStroke, unrefElement } from '@vueuse/core'\nimport { computed, onMounted, ref, toRefs, watchEffect } from 'vue'\nimport { DismissableLayerBranch } from '@/DismissableLayer'\nimport { focusFirst, getTabbableCandidates } from '@/FocusScope/utils'\nimport { Primitive } from '@/Primitive'\nimport FocusProxy from './FocusProxy.vue'\nimport { injectToastProviderContext } from './ToastProvider.vue'\nimport { VIEWPORT_PAUSE, VIEWPORT_RESUME } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<ToastViewportProps>(), {\n  hotkey: () => ['F8'], // from VIEWPORT_DEFAULT_HOTKEY\n  label: 'Notifications ({hotkey})',\n  as: 'ol',\n})\nconst { hotkey, label } = toRefs(props)\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst { CollectionSlot, getItems } = useCollection()\nconst providerContext = injectToastProviderContext()\nconst hasToasts = computed(() => providerContext.toastCount.value > 0)\nconst headFocusProxyRef = ref<HTMLElement>()\nconst tailFocusProxyRef = ref<HTMLElement>()\n\nconst KEY_RE = /Key/g\nconst DIGIT_RE = /Digit/g\nconst hotkeyMessage = computed(() => hotkey.value.join('+').replace(KEY_RE, '').replace(DIGIT_RE, ''))\n\nonKeyStroke(hotkey.value, () => {\n  currentElement.value.focus()\n})\n\nonMounted(() => {\n  providerContext.onViewportChange(currentElement.value)\n})\n\nwatchEffect((cleanupFn) => {\n  const viewport = currentElement.value\n  if (hasToasts.value && viewport) {\n    const handlePause = () => {\n      if (!providerContext.isClosePausedRef.value) {\n        const pauseEvent = new CustomEvent(VIEWPORT_PAUSE)\n        viewport.dispatchEvent(pauseEvent)\n        providerContext.isClosePausedRef.value = true\n      }\n    }\n\n    const handleResume = () => {\n      if (providerContext.isClosePausedRef.value) {\n        const resumeEvent = new CustomEvent(VIEWPORT_RESUME)\n        viewport.dispatchEvent(resumeEvent)\n        providerContext.isClosePausedRef.value = false\n      }\n    }\n\n    const handleFocusOutResume = (event: FocusEvent) => {\n      const isFocusMovingOutside = !viewport.contains(event.relatedTarget as HTMLElement)\n      if (isFocusMovingOutside)\n        handleResume()\n    }\n\n    const handlePointerLeaveResume = () => {\n      const isFocusInside = viewport.contains(getActiveElement())\n      if (!isFocusInside)\n        handleResume()\n    }\n\n    // We programmatically manage tabbing as we are unable to influence\n    // the source order with portals, this allows us to reverse the\n    // tab order so that it runs from most recent toast to least\n    const handleKeyDown = (event: KeyboardEvent) => {\n      const isMetaKey = event.altKey || event.ctrlKey || event.metaKey\n      const isTabKey = event.key === 'Tab' && !isMetaKey\n\n      if (isTabKey) {\n        const focusedElement = getActiveElement()\n        const isTabbingBackwards = event.shiftKey\n        const targetIsViewport = event.target === viewport\n\n        // If we're back tabbing after jumping to the viewport then we simply\n        // proxy focus out to the preceding document\n        if (targetIsViewport && isTabbingBackwards) {\n          headFocusProxyRef.value?.focus()\n          return\n        }\n\n        const tabbingDirection = isTabbingBackwards ? 'backwards' : 'forwards'\n        const sortedCandidates = getSortedTabbableCandidates({ tabbingDirection })\n        const index = sortedCandidates.findIndex(candidate => candidate === focusedElement)\n        if (focusFirst(sortedCandidates.slice(index + 1))) {\n          event.preventDefault()\n        }\n        else {\n          // If we can't focus that means we're at the edges so we\n          // proxy to the corresponding exit point and let the browser handle\n          // tab/shift+tab keypress and implicitly pass focus to the next valid element in the document\n          isTabbingBackwards\n            ? headFocusProxyRef.value?.focus()\n            : tailFocusProxyRef.value?.focus()\n        }\n      }\n    }\n\n    viewport.addEventListener('focusin', handlePause)\n    viewport.addEventListener('focusout', handleFocusOutResume)\n    viewport.addEventListener('pointermove', handlePause)\n    viewport.addEventListener('pointerleave', handlePointerLeaveResume)\n    viewport.addEventListener('keydown', handleKeyDown)\n    window.addEventListener('blur', handlePause)\n    window.addEventListener('focus', handleResume)\n\n    cleanupFn(() => {\n      viewport.removeEventListener('focusin', handlePause)\n      viewport.removeEventListener('focusout', handleFocusOutResume)\n      viewport.removeEventListener('pointermove', handlePause)\n      viewport.removeEventListener('pointerleave', handlePointerLeaveResume)\n      viewport.removeEventListener('keydown', handleKeyDown)\n      window.removeEventListener('blur', handlePause)\n      window.removeEventListener('focus', handleResume)\n    })\n  }\n})\n\nfunction getSortedTabbableCandidates({ tabbingDirection }: { tabbingDirection: 'forwards' | 'backwards' }) {\n  const toastItems = getItems().map(i => i.ref)\n  const tabbableCandidates = toastItems.map((toastNode) => {\n    const toastTabbableCandidates = [toastNode, ...getTabbableCandidates(toastNode)]\n    return tabbingDirection === 'forwards'\n      ? toastTabbableCandidates\n      : toastTabbableCandidates.reverse()\n  })\n  return (\n    tabbingDirection === 'forwards' ? tabbableCandidates.reverse() : tabbableCandidates\n  ).flat()\n}\n</script>\n\n<template>\n  <DismissableLayerBranch\n    role=\"region\"\n    :aria-label=\"typeof label === 'string' ? label.replace('{hotkey}', hotkeyMessage) : label(hotkeyMessage)\"\n    tabindex=\"-1\"\n    :style=\"{\n      // incase list has size when empty (e.g. padding), we remove pointer events so\n      // it doesn't prevent interactions with page elements that it overlays\n      pointerEvents: hasToasts ? undefined : 'none',\n    }\"\n  >\n    <FocusProxy\n      v-if=\"hasToasts\"\n      :ref=\"(node: Element | ComponentPublicInstance | null) => {\n        if (!node) return undefined\n        headFocusProxyRef = unrefElement(node as ComponentPublicInstance) as HTMLElement\n        return undefined\n      }\"\n      @focus-from-outside-viewport=\"() => {\n        const tabbableCandidates = getSortedTabbableCandidates({\n          tabbingDirection: 'forwards',\n        })\n        focusFirst(tabbableCandidates)\n      }\"\n    />\n    <CollectionSlot>\n      <Primitive\n        :ref=\"forwardRef\"\n        tabindex=\"-1\"\n        :as=\"as\"\n        :as-child=\"asChild\"\n        v-bind=\"$attrs\"\n      >\n        <slot />\n      </Primitive>\n    </CollectionSlot>\n    <FocusProxy\n      v-if=\"hasToasts\"\n      :ref=\"(node: Element | ComponentPublicInstance | null) => {\n        if (!node) return undefined\n        tailFocusProxyRef = unrefElement(node as ComponentPublicInstance) as HTMLElement\n        return undefined\n      }\"\n      @focus-from-outside-viewport=\"() => {\n        const tabbableCandidates = getSortedTabbableCandidates({\n          tabbingDirection: 'backwards',\n        })\n        focusFirst(tabbableCandidates)\n      }\"\n    />\n  </DismissableLayerBranch>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { AcceptableValue, DataOrientation, Direction, FormFieldProps, SingleOrMultipleProps } from '../shared/types'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useDirection, useFormControl, useForwardExpose } from '@/shared'\nimport VisuallyHiddenInput from '@/VisuallyHidden/VisuallyHiddenInput.vue'\n\nexport interface ToggleGroupRootProps<T = AcceptableValue | AcceptableValue[]>\n  extends PrimitiveProps, FormFieldProps, SingleOrMultipleProps<T> {\n  /** When `false`, navigating through the items using arrow keys will be disabled. */\n  rovingFocus?: boolean\n  /** When `true`, prevents the user from interacting with the toggle group and all its items. */\n  disabled?: boolean\n  /** The orientation of the component, which determines how focus moves: `horizontal` for left/right arrows and `vertical` for up/down arrows. */\n  orientation?: DataOrientation\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** When `loop` and `rovingFocus` is `true`, keyboard navigation will loop from last item to first, and vice versa. */\n  loop?: boolean\n}\nexport type ToggleGroupRootEmits = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [payload: AcceptableValue | AcceptableValue[]]\n}\n\ninterface ToggleGroupRootContext {\n  isSingle: ComputedRef<boolean>\n  modelValue: Ref<AcceptableValue | AcceptableValue[] | undefined>\n  changeModelValue: (value: AcceptableValue) => void\n  dir?: Ref<Direction>\n  orientation?: DataOrientation\n  loop: Ref<boolean>\n  rovingFocus: Ref<boolean>\n  disabled?: Ref<boolean>\n}\n\nexport const [injectToggleGroupRootContext, provideToggleGroupRootContext]\n  = createContext<ToggleGroupRootContext>('ToggleGroupRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusGroup } from '@/RovingFocus'\nimport { useSingleOrMultipleValue } from '@/shared/useSingleOrMultipleValue'\n\nconst props = withDefaults(defineProps<ToggleGroupRootProps>(), {\n  loop: true,\n  rovingFocus: true,\n  disabled: false,\n})\nconst emits = defineEmits<ToggleGroupRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current toggle values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { loop, rovingFocus, disabled, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst { modelValue, changeModelValue, isSingle } = useSingleOrMultipleValue(props, emits)\nconst isFormControl = useFormControl(currentElement)\n\nprovideToggleGroupRootContext({\n  isSingle,\n  modelValue,\n  changeModelValue,\n  dir,\n  orientation: props.orientation,\n  loop,\n  rovingFocus,\n  disabled,\n})\n</script>\n\n<template>\n  <component\n    :is=\"rovingFocus ? RovingFocusGroup : Primitive\"\n    as-child\n    :orientation=\"rovingFocus ? orientation : undefined\"\n    :dir=\"dir\"\n    :loop=\"rovingFocus ? loop : undefined\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"group\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n    >\n      <slot :model-value=\"modelValue\" />\n\n      <VisuallyHiddenInput\n        v-if=\"isFormControl && name\"\n        :name=\"name\"\n        :required=\"required\"\n        :value=\"modelValue\"\n      />\n    </Primitive>\n  </component>\n</template>\n","<script lang=\"ts\">\nimport type { ComputedRef, Ref } from 'vue'\nimport type { AcceptableValue, DataOrientation, Direction, FormFieldProps, SingleOrMultipleProps } from '../shared/types'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createContext, useDirection, useFormControl, useForwardExpose } from '@/shared'\nimport VisuallyHiddenInput from '@/VisuallyHidden/VisuallyHiddenInput.vue'\n\nexport interface ToggleGroupRootProps<T = AcceptableValue | AcceptableValue[]>\n  extends PrimitiveProps, FormFieldProps, SingleOrMultipleProps<T> {\n  /** When `false`, navigating through the items using arrow keys will be disabled. */\n  rovingFocus?: boolean\n  /** When `true`, prevents the user from interacting with the toggle group and all its items. */\n  disabled?: boolean\n  /** The orientation of the component, which determines how focus moves: `horizontal` for left/right arrows and `vertical` for up/down arrows. */\n  orientation?: DataOrientation\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** When `loop` and `rovingFocus` is `true`, keyboard navigation will loop from last item to first, and vice versa. */\n  loop?: boolean\n}\nexport type ToggleGroupRootEmits = {\n  /** Event handler called when the value changes. */\n  'update:modelValue': [payload: AcceptableValue | AcceptableValue[]]\n}\n\ninterface ToggleGroupRootContext {\n  isSingle: ComputedRef<boolean>\n  modelValue: Ref<AcceptableValue | AcceptableValue[] | undefined>\n  changeModelValue: (value: AcceptableValue) => void\n  dir?: Ref<Direction>\n  orientation?: DataOrientation\n  loop: Ref<boolean>\n  rovingFocus: Ref<boolean>\n  disabled?: Ref<boolean>\n}\n\nexport const [injectToggleGroupRootContext, provideToggleGroupRootContext]\n  = createContext<ToggleGroupRootContext>('ToggleGroupRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusGroup } from '@/RovingFocus'\nimport { useSingleOrMultipleValue } from '@/shared/useSingleOrMultipleValue'\n\nconst props = withDefaults(defineProps<ToggleGroupRootProps>(), {\n  loop: true,\n  rovingFocus: true,\n  disabled: false,\n})\nconst emits = defineEmits<ToggleGroupRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current toggle values */\n    modelValue: typeof modelValue.value\n  }) => any\n}>()\n\nconst { loop, rovingFocus, disabled, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst { modelValue, changeModelValue, isSingle } = useSingleOrMultipleValue(props, emits)\nconst isFormControl = useFormControl(currentElement)\n\nprovideToggleGroupRootContext({\n  isSingle,\n  modelValue,\n  changeModelValue,\n  dir,\n  orientation: props.orientation,\n  loop,\n  rovingFocus,\n  disabled,\n})\n</script>\n\n<template>\n  <component\n    :is=\"rovingFocus ? RovingFocusGroup : Primitive\"\n    as-child\n    :orientation=\"rovingFocus ? orientation : undefined\"\n    :dir=\"dir\"\n    :loop=\"rovingFocus ? loop : undefined\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"group\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n    >\n      <slot :model-value=\"modelValue\" />\n\n      <VisuallyHiddenInput\n        v-if=\"isFormControl && name\"\n        :name=\"name\"\n        :required=\"required\"\n        :value=\"modelValue\"\n      />\n    </Primitive>\n  </component>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { FormFieldProps } from '@/shared/types'\nimport { useFormControl, useForwardExpose } from '@/shared'\nimport { injectToggleGroupRootContext } from '@/ToggleGroup/ToggleGroupRoot.vue'\nimport VisuallyHiddenInput from '@/VisuallyHidden/VisuallyHiddenInput.vue'\n\nexport type ToggleEmits = {\n  /** Event handler called when the value of the toggle changes. */\n  'update:modelValue': [value: boolean]\n}\n\nexport type DataState = 'on' | 'off'\n\nexport interface ToggleProps extends PrimitiveProps, FormFieldProps {\n  /**\n   * The pressed state of the toggle when it is initially rendered. Use when you do not need to control its open state.\n   */\n  defaultValue?: boolean\n  /**\n   * The controlled pressed state of the toggle. Can be bind as `v-model`.\n   */\n  modelValue?: boolean | null\n  /**\n   * When `true`, prevents the user from interacting with the toggle.\n   */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { useVModel } from '@vueuse/core'\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<ToggleProps>(), {\n  modelValue: undefined,\n  disabled: false,\n  as: 'button',\n})\n\nconst emits = defineEmits<ToggleEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current value */\n    modelValue: typeof modelValue.value\n    /** Current state */\n    state: typeof dataState.value\n    /** Current pressed state */\n    pressed: typeof modelValue.value\n    /** Current disabled state */\n    disabled: boolean\n  }) => any\n}>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst toggleGroupContext = injectToggleGroupRootContext(null)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<boolean>\n\nfunction togglePressed() {\n  modelValue.value = !modelValue.value\n}\n\nconst dataState = computed<DataState>(() => {\n  return modelValue.value ? 'on' : 'off'\n})\n\nconst isFormControl = useFormControl(currentElement)\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :as-child=\"props.asChild\"\n    :as=\"as\"\n    :aria-pressed=\"modelValue\"\n    :data-state=\"dataState\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :disabled=\"disabled\"\n    @click=\"togglePressed\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :disabled=\"disabled\"\n      :pressed=\"modelValue\"\n      :state=\"dataState\"\n    />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name && !toggleGroupContext\"\n      type=\"checkbox\"\n      :name=\"name\"\n      :value=\"modelValue\"\n      :required=\"required\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { FormFieldProps } from '@/shared/types'\nimport { useFormControl, useForwardExpose } from '@/shared'\nimport { injectToggleGroupRootContext } from '@/ToggleGroup/ToggleGroupRoot.vue'\nimport VisuallyHiddenInput from '@/VisuallyHidden/VisuallyHiddenInput.vue'\n\nexport type ToggleEmits = {\n  /** Event handler called when the value of the toggle changes. */\n  'update:modelValue': [value: boolean]\n}\n\nexport type DataState = 'on' | 'off'\n\nexport interface ToggleProps extends PrimitiveProps, FormFieldProps {\n  /**\n   * The pressed state of the toggle when it is initially rendered. Use when you do not need to control its open state.\n   */\n  defaultValue?: boolean\n  /**\n   * The controlled pressed state of the toggle. Can be bind as `v-model`.\n   */\n  modelValue?: boolean | null\n  /**\n   * When `true`, prevents the user from interacting with the toggle.\n   */\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { useVModel } from '@vueuse/core'\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<ToggleProps>(), {\n  modelValue: undefined,\n  disabled: false,\n  as: 'button',\n})\n\nconst emits = defineEmits<ToggleEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current value */\n    modelValue: typeof modelValue.value\n    /** Current state */\n    state: typeof dataState.value\n    /** Current pressed state */\n    pressed: typeof modelValue.value\n    /** Current disabled state */\n    disabled: boolean\n  }) => any\n}>()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst toggleGroupContext = injectToggleGroupRootContext(null)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<boolean>\n\nfunction togglePressed() {\n  modelValue.value = !modelValue.value\n}\n\nconst dataState = computed<DataState>(() => {\n  return modelValue.value ? 'on' : 'off'\n})\n\nconst isFormControl = useFormControl(currentElement)\n</script>\n\n<template>\n  <Primitive\n    :ref=\"forwardRef\"\n    :type=\"as === 'button' ? 'button' : undefined\"\n    :as-child=\"props.asChild\"\n    :as=\"as\"\n    :aria-pressed=\"modelValue\"\n    :data-state=\"dataState\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :disabled=\"disabled\"\n    @click=\"togglePressed\"\n  >\n    <slot\n      :model-value=\"modelValue\"\n      :disabled=\"disabled\"\n      :pressed=\"modelValue\"\n      :state=\"dataState\"\n    />\n\n    <VisuallyHiddenInput\n      v-if=\"isFormControl && name && !toggleGroupContext\"\n      type=\"checkbox\"\n      :name=\"name\"\n      :value=\"modelValue\"\n      :required=\"required\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { AcceptableValue } from '@/shared/types'\nimport type { ToggleProps } from '@/Toggle'\nimport { isValueEqualOrExist, useForwardExpose } from '@/shared'\n\nexport interface ToggleGroupItemProps extends Omit<ToggleProps, 'name' | 'required' | 'modelValue' | 'defaultValue'> {\n  /**\n   * A string value for the toggle group item. All items within a toggle group should use a unique value.\n   */\n  value: AcceptableValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\nimport { Toggle } from '@/Toggle'\nimport { injectToggleGroupRootContext } from './ToggleGroupRoot.vue'\n\nconst props = withDefaults(defineProps<ToggleGroupItemProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectToggleGroupRootContext()\nconst disabled = computed(() => rootContext.disabled?.value || props.disabled)\nconst pressed = computed(() => isValueEqualOrExist(rootContext.modelValue.value, props.value))\n\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <component\n    :is=\"rootContext.rovingFocus.value ? RovingFocusItem : Primitive\"\n    as-child\n    v-bind=\"rootContext.rovingFocus.value ? { focusable: !disabled, active: pressed } : {}\"\n  >\n    <Toggle\n      v-bind=\"props\"\n      :ref=\"forwardRef\"\n      v-slot=\"slotProps\"\n      :disabled=\"disabled\"\n      :model-value=\"pressed\"\n      @update:model-value=\"rootContext.changeModelValue(value)\"\n    >\n      <slot v-bind=\"slotProps\" />\n    </Toggle>\n  </component>\n</template>\n","<script lang=\"ts\">\nimport type { AcceptableValue } from '@/shared/types'\nimport type { ToggleProps } from '@/Toggle'\nimport { isValueEqualOrExist, useForwardExpose } from '@/shared'\n\nexport interface ToggleGroupItemProps extends Omit<ToggleProps, 'name' | 'required' | 'modelValue' | 'defaultValue'> {\n  /**\n   * A string value for the toggle group item. All items within a toggle group should use a unique value.\n   */\n  value: AcceptableValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\nimport { Toggle } from '@/Toggle'\nimport { injectToggleGroupRootContext } from './ToggleGroupRoot.vue'\n\nconst props = withDefaults(defineProps<ToggleGroupItemProps>(), {\n  as: 'button',\n})\n\nconst rootContext = injectToggleGroupRootContext()\nconst disabled = computed(() => rootContext.disabled?.value || props.disabled)\nconst pressed = computed(() => isValueEqualOrExist(rootContext.modelValue.value, props.value))\n\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <component\n    :is=\"rootContext.rovingFocus.value ? RovingFocusItem : Primitive\"\n    as-child\n    v-bind=\"rootContext.rovingFocus.value ? { focusable: !disabled, active: pressed } : {}\"\n  >\n    <Toggle\n      v-bind=\"props\"\n      :ref=\"forwardRef\"\n      v-slot=\"slotProps\"\n      :disabled=\"disabled\"\n      :model-value=\"pressed\"\n      @update:model-value=\"rootContext.changeModelValue(value)\"\n    >\n      <slot v-bind=\"slotProps\" />\n    </Toggle>\n  </component>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ToolbarButtonProps extends PrimitiveProps {\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\n\nconst props = withDefaults(defineProps<ToolbarButtonProps>(), { as: 'button' })\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <RovingFocusItem\n    as-child\n    :focusable=\"!disabled\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :type=\"as === 'button' ? 'button' : undefined\"\n      v-bind=\"props\"\n    >\n      <slot />\n    </Primitive>\n  </RovingFocusItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ToolbarButtonProps extends PrimitiveProps {\n  disabled?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\n\nconst props = withDefaults(defineProps<ToolbarButtonProps>(), { as: 'button' })\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <RovingFocusItem\n    as-child\n    :focusable=\"!disabled\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :type=\"as === 'button' ? 'button' : undefined\"\n      v-bind=\"props\"\n    >\n      <slot />\n    </Primitive>\n  </RovingFocusItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ToolbarLinkProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\n\nconst props = withDefaults(defineProps<ToolbarLinkProps>(), { as: 'a' })\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <RovingFocusItem\n    as-child\n    focusable\n  >\n    <Primitive\n      v-bind=\"props\"\n      :ref=\"forwardRef\"\n      @keydown=\"(event: KeyboardEvent) => {\n        if (event.key === ' ') (event.currentTarget as HTMLElement)?.click()\n      }\"\n    >\n      <slot />\n    </Primitive>\n  </RovingFocusItem>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ToolbarLinkProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\n\nconst props = withDefaults(defineProps<ToolbarLinkProps>(), { as: 'a' })\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <RovingFocusItem\n    as-child\n    focusable\n  >\n    <Primitive\n      v-bind=\"props\"\n      :ref=\"forwardRef\"\n      @keydown=\"(event: KeyboardEvent) => {\n        if (event.key === ' ') (event.currentTarget as HTMLElement)?.click()\n      }\"\n    >\n      <slot />\n    </Primitive>\n  </RovingFocusItem>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { DataOrientation, Direction } from '@/shared/types'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\nexport interface ToolbarRootProps extends PrimitiveProps {\n  /** The orientation of the toolbar */\n  orientation?: DataOrientation\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** When `true`, keyboard navigation will loop from last tab to first, and vice versa. */\n  loop?: boolean\n}\n\nexport interface ToolbarRootContext {\n  orientation: Ref<DataOrientation>\n  dir: Ref<Direction>\n}\n\nexport const [injectToolbarRootContext, provideToolbarRootContext]\n  = createContext<ToolbarRootContext>('ToolbarRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusGroup } from '@/RovingFocus'\n\nconst props = withDefaults(defineProps<ToolbarRootProps>(), {\n  orientation: 'horizontal',\n})\nconst { orientation, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nconst { forwardRef } = useForwardExpose()\n\nprovideToolbarRootContext({ orientation, dir })\n</script>\n\n<template>\n  <RovingFocusGroup\n    as-child\n    :orientation=\"orientation\"\n    :dir=\"dir\"\n    :loop=\"loop\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"toolbar\"\n      :aria-orientation=\"orientation\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n    >\n      <slot />\n    </Primitive>\n  </RovingFocusGroup>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { DataOrientation, Direction } from '@/shared/types'\nimport { createContext, useDirection, useForwardExpose } from '@/shared'\n\nexport interface ToolbarRootProps extends PrimitiveProps {\n  /** The orientation of the toolbar */\n  orientation?: DataOrientation\n  /** The reading direction of the combobox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** When `true`, keyboard navigation will loop from last tab to first, and vice versa. */\n  loop?: boolean\n}\n\nexport interface ToolbarRootContext {\n  orientation: Ref<DataOrientation>\n  dir: Ref<Direction>\n}\n\nexport const [injectToolbarRootContext, provideToolbarRootContext]\n  = createContext<ToolbarRootContext>('ToolbarRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusGroup } from '@/RovingFocus'\n\nconst props = withDefaults(defineProps<ToolbarRootProps>(), {\n  orientation: 'horizontal',\n})\nconst { orientation, dir: propDir } = toRefs(props)\nconst dir = useDirection(propDir)\nconst { forwardRef } = useForwardExpose()\n\nprovideToolbarRootContext({ orientation, dir })\n</script>\n\n<template>\n  <RovingFocusGroup\n    as-child\n    :orientation=\"orientation\"\n    :dir=\"dir\"\n    :loop=\"loop\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      role=\"toolbar\"\n      :aria-orientation=\"orientation\"\n      :as-child=\"asChild\"\n      :as=\"as\"\n    >\n      <slot />\n    </Primitive>\n  </RovingFocusGroup>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ToolbarSeparatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useForwardExpose } from '@/shared'\nimport BaseSeparator from '../shared/component/BaseSeparator.vue'\nimport { injectToolbarRootContext } from './ToolbarRoot.vue'\n\nconst props = defineProps<ToolbarSeparatorProps>()\n\nconst rootContext = injectToolbarRootContext()\nuseForwardExpose()\n</script>\n\n<template>\n  <BaseSeparator\n    :orientation=\"rootContext.orientation.value\"\n    :as-child=\"props.asChild\"\n    :as=\"as\"\n  >\n    <slot />\n  </BaseSeparator>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface ToolbarSeparatorProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useForwardExpose } from '@/shared'\nimport BaseSeparator from '../shared/component/BaseSeparator.vue'\nimport { injectToolbarRootContext } from './ToolbarRoot.vue'\n\nconst props = defineProps<ToolbarSeparatorProps>()\n\nconst rootContext = injectToolbarRootContext()\nuseForwardExpose()\n</script>\n\n<template>\n  <BaseSeparator\n    :orientation=\"rootContext.orientation.value\"\n    :as-child=\"props.asChild\"\n    :as=\"as\"\n  >\n    <slot />\n  </BaseSeparator>\n</template>\n","<script lang=\"ts\">\nimport type {\n  ToggleGroupRootEmits,\n  ToggleGroupRootProps,\n} from '@/ToggleGroup'\n\nexport type ToolbarToggleGroupEmits = ToggleGroupRootEmits\n\nexport interface ToolbarToggleGroupProps extends ToggleGroupRootProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\nimport { ToggleGroupRoot } from '@/ToggleGroup'\nimport { injectToolbarRootContext } from './ToolbarRoot.vue'\n\nconst props = defineProps<ToolbarToggleGroupProps>()\nconst emits = defineEmits<ToolbarToggleGroupEmits>()\n\nconst rootContext = injectToolbarRootContext()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <ToggleGroupRoot\n    v-bind=\"{ ...props, ...emitsAsProps }\"\n    :data-orientation=\"rootContext.orientation.value\"\n    :dir=\"rootContext.dir.value\"\n    :roving-focus=\"false\"\n  >\n    <slot />\n  </ToggleGroupRoot>\n</template>\n","<script lang=\"ts\">\nimport type {\n  ToggleGroupRootEmits,\n  ToggleGroupRootProps,\n} from '@/ToggleGroup'\n\nexport type ToolbarToggleGroupEmits = ToggleGroupRootEmits\n\nexport interface ToolbarToggleGroupProps extends ToggleGroupRootProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { useEmitAsProps, useForwardExpose } from '@/shared'\nimport { ToggleGroupRoot } from '@/ToggleGroup'\nimport { injectToolbarRootContext } from './ToolbarRoot.vue'\n\nconst props = defineProps<ToolbarToggleGroupProps>()\nconst emits = defineEmits<ToolbarToggleGroupEmits>()\n\nconst rootContext = injectToolbarRootContext()\n\nconst emitsAsProps = useEmitAsProps(emits)\nuseForwardExpose()\n</script>\n\n<template>\n  <ToggleGroupRoot\n    v-bind=\"{ ...props, ...emitsAsProps }\"\n    :data-orientation=\"rootContext.orientation.value\"\n    :dir=\"rootContext.dir.value\"\n    :roving-focus=\"false\"\n  >\n    <slot />\n  </ToggleGroupRoot>\n</template>\n","<script lang=\"ts\">\nimport type { ToggleGroupItemProps } from '@/ToggleGroup'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ToolbarToggleItemProps extends ToggleGroupItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ToggleGroupItem } from '@/ToggleGroup'\nimport ToolbarButton from './ToolbarButton.vue'\n\nconst props = defineProps<ToolbarToggleItemProps>()\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <ToolbarButton as-child>\n    <ToggleGroupItem\n      v-bind=\"props\"\n      :ref=\"forwardRef\"\n    >\n      <slot />\n    </ToggleGroupItem>\n  </ToolbarButton>\n</template>\n","<script lang=\"ts\">\nimport type { ToggleGroupItemProps } from '@/ToggleGroup'\nimport { useForwardExpose } from '@/shared'\n\nexport interface ToolbarToggleItemProps extends ToggleGroupItemProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ToggleGroupItem } from '@/ToggleGroup'\nimport ToolbarButton from './ToolbarButton.vue'\n\nconst props = defineProps<ToolbarToggleItemProps>()\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <ToolbarButton as-child>\n    <ToggleGroupItem\n      v-bind=\"props\"\n      :ref=\"forwardRef\"\n    >\n      <slot />\n    </ToggleGroupItem>\n  </ToolbarButton>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface TooltipArrowProps extends PrimitiveProps {\n  /**\n   * The width of the arrow in pixels.\n   *\n   * @defaultValue 10\n   */\n  width?: number\n\n  /**\n   * The height of the arrow in pixels.\n   *\n   * @defaultValue 5\n   */\n  height?: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperArrow } from '@/Popper'\n\nconst props = withDefaults(defineProps<TooltipArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nuseForwardExpose()\n</script>\n\n<template>\n  <PopperArrow v-bind=\"props\">\n    <slot />\n  </PopperArrow>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { useForwardExpose } from '@/shared'\n\nexport interface TooltipArrowProps extends PrimitiveProps {\n  /**\n   * The width of the arrow in pixels.\n   *\n   * @defaultValue 10\n   */\n  width?: number\n\n  /**\n   * The height of the arrow in pixels.\n   *\n   * @defaultValue 5\n   */\n  height?: number\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { PopperArrow } from '@/Popper'\n\nconst props = withDefaults(defineProps<TooltipArrowProps>(), {\n  width: 10,\n  height: 5,\n  as: 'svg',\n})\nuseForwardExpose()\n</script>\n\n<template>\n  <PopperArrow v-bind=\"props\">\n    <slot />\n  </PopperArrow>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { TooltipContentProps } from './TooltipContent.vue'\nimport { createContext, useForwardExpose } from '@/shared'\n\ninterface TooltipProviderContext {\n  isOpenDelayed: Ref<boolean>\n  delayDuration: Ref<number>\n  onOpen: () => void\n  onClose: () => void\n  isPointerInTransitRef: Ref<boolean>\n  disableHoverableContent: Ref<boolean>\n  disableClosingTrigger: Ref<boolean>\n  disabled: Ref<boolean>\n  ignoreNonKeyboardFocus: Ref<boolean>\n  content: Ref<TooltipContentProps | undefined>\n}\n\nexport const [injectTooltipProviderContext, provideTooltipProviderContext]\n  = createContext<TooltipProviderContext>('TooltipProvider')\n\nexport interface TooltipProviderProps {\n  /**\n   * The duration from when the pointer enters the trigger until the tooltip gets opened.\n   * @defaultValue 700\n   */\n  delayDuration?: number\n  /**\n   * How much time a user has to enter another trigger without incurring a delay again.\n   * @defaultValue 300\n   */\n  skipDelayDuration?: number\n  /**\n   * When `true`, trying to hover the content will result in the tooltip closing as the pointer leaves the trigger.\n   * @defaultValue false\n   */\n  disableHoverableContent?: boolean\n  /**\n   * When `true`, clicking on trigger will not close the content.\n   * @defaultValue false\n   */\n  disableClosingTrigger?: boolean\n  /**\n   * When `true`, disable tooltip\n   * @defaultValue false\n   */\n  disabled?: boolean\n  /**\n   * Prevent the tooltip from opening if the focus did not come from\n   * the keyboard by matching against the `:focus-visible` selector.\n   * This is useful if you want to avoid opening it when switching\n   * browser tabs or closing a dialog.\n   * @defaultValue false\n   */\n  ignoreNonKeyboardFocus?: boolean\n  /**\n   * Default settings that will be used by all tooltip components.\n   */\n  content?: TooltipContentProps\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useTimeoutFn } from '@vueuse/shared'\nimport { ref, toRefs } from 'vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<TooltipProviderProps>(), {\n  delayDuration: 700,\n  skipDelayDuration: 300,\n  disableHoverableContent: false,\n  ignoreNonKeyboardFocus: false,\n})\nconst { delayDuration, skipDelayDuration, disableHoverableContent, disableClosingTrigger, ignoreNonKeyboardFocus, disabled, content } = toRefs(props)\nuseForwardExpose()\n\nconst isOpenDelayed = ref(true)\n// Reset the inTransit state if idle/scrolled.\nconst isPointerInTransitRef = ref(false)\n\nconst { start: startTimer, stop: clearTimer } = useTimeoutFn(() => {\n  isOpenDelayed.value = true\n}, skipDelayDuration, { immediate: false })\n\nprovideTooltipProviderContext({\n  isOpenDelayed,\n  delayDuration,\n  onOpen() {\n    clearTimer()\n    isOpenDelayed.value = false\n  },\n  onClose() {\n    startTimer()\n  },\n  isPointerInTransitRef,\n  disableHoverableContent,\n  disableClosingTrigger,\n  disabled,\n  ignoreNonKeyboardFocus,\n  content,\n})\n</script>\n\n<template>\n  <slot />\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport type { TooltipContentProps } from './TooltipContent.vue'\nimport { createContext, useForwardExpose } from '@/shared'\n\ninterface TooltipProviderContext {\n  isOpenDelayed: Ref<boolean>\n  delayDuration: Ref<number>\n  onOpen: () => void\n  onClose: () => void\n  isPointerInTransitRef: Ref<boolean>\n  disableHoverableContent: Ref<boolean>\n  disableClosingTrigger: Ref<boolean>\n  disabled: Ref<boolean>\n  ignoreNonKeyboardFocus: Ref<boolean>\n  content: Ref<TooltipContentProps | undefined>\n}\n\nexport const [injectTooltipProviderContext, provideTooltipProviderContext]\n  = createContext<TooltipProviderContext>('TooltipProvider')\n\nexport interface TooltipProviderProps {\n  /**\n   * The duration from when the pointer enters the trigger until the tooltip gets opened.\n   * @defaultValue 700\n   */\n  delayDuration?: number\n  /**\n   * How much time a user has to enter another trigger without incurring a delay again.\n   * @defaultValue 300\n   */\n  skipDelayDuration?: number\n  /**\n   * When `true`, trying to hover the content will result in the tooltip closing as the pointer leaves the trigger.\n   * @defaultValue false\n   */\n  disableHoverableContent?: boolean\n  /**\n   * When `true`, clicking on trigger will not close the content.\n   * @defaultValue false\n   */\n  disableClosingTrigger?: boolean\n  /**\n   * When `true`, disable tooltip\n   * @defaultValue false\n   */\n  disabled?: boolean\n  /**\n   * Prevent the tooltip from opening if the focus did not come from\n   * the keyboard by matching against the `:focus-visible` selector.\n   * This is useful if you want to avoid opening it when switching\n   * browser tabs or closing a dialog.\n   * @defaultValue false\n   */\n  ignoreNonKeyboardFocus?: boolean\n  /**\n   * Default settings that will be used by all tooltip components.\n   */\n  content?: TooltipContentProps\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useTimeoutFn } from '@vueuse/shared'\nimport { ref, toRefs } from 'vue'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<TooltipProviderProps>(), {\n  delayDuration: 700,\n  skipDelayDuration: 300,\n  disableHoverableContent: false,\n  ignoreNonKeyboardFocus: false,\n})\nconst { delayDuration, skipDelayDuration, disableHoverableContent, disableClosingTrigger, ignoreNonKeyboardFocus, disabled, content } = toRefs(props)\nuseForwardExpose()\n\nconst isOpenDelayed = ref(true)\n// Reset the inTransit state if idle/scrolled.\nconst isPointerInTransitRef = ref(false)\n\nconst { start: startTimer, stop: clearTimer } = useTimeoutFn(() => {\n  isOpenDelayed.value = true\n}, skipDelayDuration, { immediate: false })\n\nprovideTooltipProviderContext({\n  isOpenDelayed,\n  delayDuration,\n  onOpen() {\n    clearTimer()\n    isOpenDelayed.value = false\n  },\n  onClose() {\n    startTimer()\n  },\n  isPointerInTransitRef,\n  disableHoverableContent,\n  disableClosingTrigger,\n  disabled,\n  ignoreNonKeyboardFocus,\n  content,\n})\n</script>\n\n<template>\n  <slot />\n</template>\n","export const TOOLTIP_OPEN = 'tooltip.open'\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface TooltipRootProps {\n  /**\n   * The open state of the tooltip when it is initially rendered.\n   * Use when you do not need to control its open state.\n   */\n  defaultOpen?: boolean\n  /**\n   * The controlled open state of the tooltip.\n   */\n  open?: boolean\n  /**\n   * Override the duration given to the `Provider` to customise\n   * the open delay for a specific tooltip.\n   *\n   * @defaultValue 700\n   */\n  delayDuration?: number\n  /**\n   * Prevents Tooltip.Content from remaining open when hovering.\n   * Disabling this has accessibility consequences. Inherits\n   * from Tooltip.Provider.\n   */\n  disableHoverableContent?: boolean\n  /**\n   * When `true`, clicking on trigger will not close the content.\n   * @defaultValue false\n   */\n  disableClosingTrigger?: boolean\n  /**\n   * When `true`, disable tooltip\n   * @defaultValue false\n   */\n  disabled?: boolean\n  /**\n   * Prevent the tooltip from opening if the focus did not come from\n   * the keyboard by matching against the `:focus-visible` selector.\n   * This is useful if you want to avoid opening it when switching\n   * browser tabs or closing a dialog.\n   * @defaultValue false\n   */\n  ignoreNonKeyboardFocus?: boolean\n}\n\nexport type TooltipRootEmits = {\n  /** Event handler called when the open state of the tooltip changes. */\n  'update:open': [value: boolean]\n}\n\nexport interface TooltipContext {\n  contentId: string\n  open: Ref<boolean>\n  stateAttribute: Ref<'closed' | 'delayed-open' | 'instant-open'>\n  trigger: Ref<HTMLElement | undefined>\n  onTriggerChange: (trigger: HTMLElement | undefined) => void\n  onTriggerEnter: () => void\n  onTriggerLeave: () => void\n  onOpen: () => void\n  onClose: () => void\n  disableHoverableContent: Ref<boolean>\n  disableClosingTrigger: Ref<boolean>\n  disabled: Ref<boolean>\n  ignoreNonKeyboardFocus: Ref<boolean>\n}\n\nexport const [injectTooltipRootContext, provideTooltipRootContext]\n  = createContext<TooltipContext>('TooltipRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useTimeoutFn, useVModel } from '@vueuse/core'\nimport { computed, ref, watch } from 'vue'\nimport { PopperRoot } from '@/Popper'\nimport { injectTooltipProviderContext } from './TooltipProvider.vue'\nimport { TOOLTIP_OPEN } from './utils'\n\nconst props = withDefaults(defineProps<TooltipRootProps>(), {\n  defaultOpen: false,\n  open: undefined,\n  delayDuration: undefined,\n  disableHoverableContent: undefined,\n  disableClosingTrigger: undefined,\n  disabled: undefined,\n  ignoreNonKeyboardFocus: undefined,\n})\n\nconst emit = defineEmits<TooltipRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nuseForwardExpose()\nconst providerContext = injectTooltipProviderContext()\n\nconst disableHoverableContent = computed(() => props.disableHoverableContent ?? providerContext.disableHoverableContent.value)\nconst disableClosingTrigger = computed(() => props.disableClosingTrigger ?? providerContext.disableClosingTrigger.value)\nconst disableTooltip = computed(() => props.disabled ?? providerContext.disabled.value)\n\nconst delayDuration = computed(() => props.delayDuration ?? providerContext.delayDuration.value)\nconst ignoreNonKeyboardFocus = computed(() => props.ignoreNonKeyboardFocus ?? providerContext.ignoreNonKeyboardFocus.value)\n\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nwatch(open, (isOpen) => {\n  if (!providerContext.onClose)\n    return\n  if (isOpen) {\n    providerContext.onOpen()\n    // as `onChange` is called within a lifecycle method we\n    // avoid dispatching via `dispatchDiscreteCustomEvent`.\n    document.dispatchEvent(new CustomEvent(TOOLTIP_OPEN))\n  }\n  else {\n    providerContext.onClose()\n  }\n})\n\nconst wasOpenDelayedRef = ref(false)\nconst trigger = ref<HTMLElement>()\n\nconst stateAttribute = computed(() => {\n  if (!open.value)\n    return 'closed'\n  return wasOpenDelayedRef.value ? 'delayed-open' : 'instant-open'\n})\n\nconst { start: startTimer, stop: clearTimer } = useTimeoutFn(() => {\n  wasOpenDelayedRef.value = true\n  open.value = true\n}, delayDuration, { immediate: false })\n\nfunction handleOpen() {\n  clearTimer()\n  wasOpenDelayedRef.value = false\n  open.value = true\n}\nfunction handleClose() {\n  clearTimer()\n  open.value = false\n}\nfunction handleDelayedOpen() {\n  startTimer()\n}\n\nprovideTooltipRootContext({\n  contentId: '',\n  open,\n  stateAttribute,\n  trigger,\n  onTriggerChange(el) {\n    trigger.value = el\n  },\n  onTriggerEnter() {\n    if (providerContext.isOpenDelayed.value)\n      handleDelayedOpen()\n    else handleOpen()\n  },\n  onTriggerLeave() {\n    if (disableHoverableContent.value) {\n      handleClose()\n    }\n    else {\n      // Clear the timer in case the pointer leaves the trigger before the tooltip is opened.\n      clearTimer()\n    }\n  },\n  onOpen: handleOpen,\n  onClose: handleClose,\n  disableHoverableContent,\n  disableClosingTrigger,\n  disabled: disableTooltip,\n  ignoreNonKeyboardFocus,\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <slot :open=\"open\" />\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type { Ref } from 'vue'\nimport { createContext, useForwardExpose } from '@/shared'\n\nexport interface TooltipRootProps {\n  /**\n   * The open state of the tooltip when it is initially rendered.\n   * Use when you do not need to control its open state.\n   */\n  defaultOpen?: boolean\n  /**\n   * The controlled open state of the tooltip.\n   */\n  open?: boolean\n  /**\n   * Override the duration given to the `Provider` to customise\n   * the open delay for a specific tooltip.\n   *\n   * @defaultValue 700\n   */\n  delayDuration?: number\n  /**\n   * Prevents Tooltip.Content from remaining open when hovering.\n   * Disabling this has accessibility consequences. Inherits\n   * from Tooltip.Provider.\n   */\n  disableHoverableContent?: boolean\n  /**\n   * When `true`, clicking on trigger will not close the content.\n   * @defaultValue false\n   */\n  disableClosingTrigger?: boolean\n  /**\n   * When `true`, disable tooltip\n   * @defaultValue false\n   */\n  disabled?: boolean\n  /**\n   * Prevent the tooltip from opening if the focus did not come from\n   * the keyboard by matching against the `:focus-visible` selector.\n   * This is useful if you want to avoid opening it when switching\n   * browser tabs or closing a dialog.\n   * @defaultValue false\n   */\n  ignoreNonKeyboardFocus?: boolean\n}\n\nexport type TooltipRootEmits = {\n  /** Event handler called when the open state of the tooltip changes. */\n  'update:open': [value: boolean]\n}\n\nexport interface TooltipContext {\n  contentId: string\n  open: Ref<boolean>\n  stateAttribute: Ref<'closed' | 'delayed-open' | 'instant-open'>\n  trigger: Ref<HTMLElement | undefined>\n  onTriggerChange: (trigger: HTMLElement | undefined) => void\n  onTriggerEnter: () => void\n  onTriggerLeave: () => void\n  onOpen: () => void\n  onClose: () => void\n  disableHoverableContent: Ref<boolean>\n  disableClosingTrigger: Ref<boolean>\n  disabled: Ref<boolean>\n  ignoreNonKeyboardFocus: Ref<boolean>\n}\n\nexport const [injectTooltipRootContext, provideTooltipRootContext]\n  = createContext<TooltipContext>('TooltipRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useTimeoutFn, useVModel } from '@vueuse/core'\nimport { computed, ref, watch } from 'vue'\nimport { PopperRoot } from '@/Popper'\nimport { injectTooltipProviderContext } from './TooltipProvider.vue'\nimport { TOOLTIP_OPEN } from './utils'\n\nconst props = withDefaults(defineProps<TooltipRootProps>(), {\n  defaultOpen: false,\n  open: undefined,\n  delayDuration: undefined,\n  disableHoverableContent: undefined,\n  disableClosingTrigger: undefined,\n  disabled: undefined,\n  ignoreNonKeyboardFocus: undefined,\n})\n\nconst emit = defineEmits<TooltipRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** Current open state */\n    open: typeof open.value\n  }) => any\n}>()\n\nuseForwardExpose()\nconst providerContext = injectTooltipProviderContext()\n\nconst disableHoverableContent = computed(() => props.disableHoverableContent ?? providerContext.disableHoverableContent.value)\nconst disableClosingTrigger = computed(() => props.disableClosingTrigger ?? providerContext.disableClosingTrigger.value)\nconst disableTooltip = computed(() => props.disabled ?? providerContext.disabled.value)\n\nconst delayDuration = computed(() => props.delayDuration ?? providerContext.delayDuration.value)\nconst ignoreNonKeyboardFocus = computed(() => props.ignoreNonKeyboardFocus ?? providerContext.ignoreNonKeyboardFocus.value)\n\nconst open = useVModel(props, 'open', emit, {\n  defaultValue: props.defaultOpen,\n  passive: (props.open === undefined) as false,\n}) as Ref<boolean>\n\nwatch(open, (isOpen) => {\n  if (!providerContext.onClose)\n    return\n  if (isOpen) {\n    providerContext.onOpen()\n    // as `onChange` is called within a lifecycle method we\n    // avoid dispatching via `dispatchDiscreteCustomEvent`.\n    document.dispatchEvent(new CustomEvent(TOOLTIP_OPEN))\n  }\n  else {\n    providerContext.onClose()\n  }\n})\n\nconst wasOpenDelayedRef = ref(false)\nconst trigger = ref<HTMLElement>()\n\nconst stateAttribute = computed(() => {\n  if (!open.value)\n    return 'closed'\n  return wasOpenDelayedRef.value ? 'delayed-open' : 'instant-open'\n})\n\nconst { start: startTimer, stop: clearTimer } = useTimeoutFn(() => {\n  wasOpenDelayedRef.value = true\n  open.value = true\n}, delayDuration, { immediate: false })\n\nfunction handleOpen() {\n  clearTimer()\n  wasOpenDelayedRef.value = false\n  open.value = true\n}\nfunction handleClose() {\n  clearTimer()\n  open.value = false\n}\nfunction handleDelayedOpen() {\n  startTimer()\n}\n\nprovideTooltipRootContext({\n  contentId: '',\n  open,\n  stateAttribute,\n  trigger,\n  onTriggerChange(el) {\n    trigger.value = el\n  },\n  onTriggerEnter() {\n    if (providerContext.isOpenDelayed.value)\n      handleDelayedOpen()\n    else handleOpen()\n  },\n  onTriggerLeave() {\n    if (disableHoverableContent.value) {\n      handleClose()\n    }\n    else {\n      // Clear the timer in case the pointer leaves the trigger before the tooltip is opened.\n      clearTimer()\n    }\n  },\n  onOpen: handleOpen,\n  onClose: handleClose,\n  disableHoverableContent,\n  disableClosingTrigger,\n  disabled: disableTooltip,\n  ignoreNonKeyboardFocus,\n})\n</script>\n\n<template>\n  <PopperRoot>\n    <slot :open=\"open\" />\n  </PopperRoot>\n</template>\n","<script lang=\"ts\">\nimport type { PopperContentProps } from '@/Popper'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { defu } from 'defu'\nimport { useForwardExpose } from '@/shared'\nimport { injectTooltipProviderContext } from './TooltipProvider.vue'\n\nexport type TooltipContentImplEmits = {\n  /** Event handler called when focus moves to the destructive action after opening. It can be prevented by calling `event.preventDefault` */\n  escapeKeyDown: [event: KeyboardEvent]\n  /** Event handler called when a pointer event occurs outside the bounds of the component. It can be prevented by calling `event.preventDefault`. */\n  pointerDownOutside: [event: Event]\n}\n\nexport interface TooltipContentImplProps\n  extends PrimitiveProps,\n  Pick<\n    PopperContentProps,\n    | 'side'\n    | 'sideOffset'\n    | 'align'\n    | 'alignOffset'\n    | 'avoidCollisions'\n    | 'collisionBoundary'\n    | 'collisionPadding'\n    | 'arrowPadding'\n    | 'sticky'\n    | 'hideWhenDetached'\n    | 'positionStrategy'\n    | 'updatePositionStrategy'\n  > {\n  /**\n   * By default, screenreaders will announce the content inside\n   * the component. If this is not descriptive enough, or you have\n   * content that cannot be announced, use aria-label as a more\n   * descriptive label.\n   *\n   * @defaultValue String\n   */\n  ariaLabel?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener } from '@vueuse/core'\nimport { computed, onMounted } from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { PopperContent } from '@/Popper'\nimport { VisuallyHidden } from '@/VisuallyHidden'\nimport { injectTooltipRootContext } from './TooltipRoot.vue'\nimport { TOOLTIP_OPEN } from './utils'\n\nconst props = withDefaults(defineProps<TooltipContentImplProps>(), {\n  avoidCollisions: undefined,\n  asChild: undefined,\n  hideWhenDetached: undefined,\n})\nconst emits = defineEmits<TooltipContentImplEmits>()\n\nconst rootContext = injectTooltipRootContext()\nconst providerContext = injectTooltipProviderContext()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst ariaLabel = computed(() => props.ariaLabel || currentElement.value?.textContent)\n\nconst popperContentProps = computed(() => {\n  const { ariaLabel: _, ...restProps } = props\n\n  return defu(restProps, providerContext.content.value ?? {}, {\n    side: 'top',\n    sideOffset: 0,\n    align: 'center',\n    avoidCollisions: true,\n    collisionBoundary: [],\n    collisionPadding: 0,\n    arrowPadding: 0,\n    sticky: 'partial',\n    hideWhenDetached: false,\n  } satisfies TooltipContentImplProps)\n})\n\nonMounted(() => {\n  // Close the tooltip if the trigger is scrolled\n  useEventListener(window, 'scroll', (event) => {\n    const target = event.target as HTMLElement\n    if (target?.contains(rootContext.trigger.value!))\n      rootContext.onClose()\n  }, { capture: true })\n  // Close this tooltip if another one opens\n  useEventListener(window, TOOLTIP_OPEN, rootContext.onClose)\n})\n</script>\n\n<template>\n  <DismissableLayer\n    as-child\n    :disable-outside-pointer-events=\"false\"\n    @escape-key-down=\"emits('escapeKeyDown', $event)\"\n    @pointer-down-outside=\"(event) => {\n      if (rootContext.disableClosingTrigger.value && rootContext.trigger.value?.contains(event.target as HTMLElement))\n        event.preventDefault()\n\n      emits('pointerDownOutside', event)\n    }\"\n    @focus-outside.prevent\n    @dismiss=\"rootContext.onClose()\"\n  >\n    <PopperContent\n      :ref=\"forwardRef\"\n      :data-state=\"rootContext.stateAttribute.value\"\n      v-bind=\"{ ...$attrs, ...popperContentProps }\"\n      :style=\"{\n        '--reka-tooltip-content-transform-origin': 'var(--reka-popper-transform-origin)',\n        '--reka-tooltip-content-available-width': 'var(--reka-popper-available-width)',\n        '--reka-tooltip-content-available-height': 'var(--reka-popper-available-height)',\n        '--reka-tooltip-trigger-width': 'var(--reka-popper-anchor-width)',\n        '--reka-tooltip-trigger-height': 'var(--reka-popper-anchor-height)',\n      }\"\n    >\n      <slot />\n      <VisuallyHidden\n        :id=\"rootContext.contentId\"\n        role=\"tooltip\"\n      >\n        {{ ariaLabel }}\n      </VisuallyHidden>\n    </PopperContent>\n  </DismissableLayer>\n</template>\n","<script lang=\"ts\">\nimport type { PopperContentProps } from '@/Popper'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { defu } from 'defu'\nimport { useForwardExpose } from '@/shared'\nimport { injectTooltipProviderContext } from './TooltipProvider.vue'\n\nexport type TooltipContentImplEmits = {\n  /** Event handler called when focus moves to the destructive action after opening. It can be prevented by calling `event.preventDefault` */\n  escapeKeyDown: [event: KeyboardEvent]\n  /** Event handler called when a pointer event occurs outside the bounds of the component. It can be prevented by calling `event.preventDefault`. */\n  pointerDownOutside: [event: Event]\n}\n\nexport interface TooltipContentImplProps\n  extends PrimitiveProps,\n  Pick<\n    PopperContentProps,\n    | 'side'\n    | 'sideOffset'\n    | 'align'\n    | 'alignOffset'\n    | 'avoidCollisions'\n    | 'collisionBoundary'\n    | 'collisionPadding'\n    | 'arrowPadding'\n    | 'sticky'\n    | 'hideWhenDetached'\n    | 'positionStrategy'\n    | 'updatePositionStrategy'\n  > {\n  /**\n   * By default, screenreaders will announce the content inside\n   * the component. If this is not descriptive enough, or you have\n   * content that cannot be announced, use aria-label as a more\n   * descriptive label.\n   *\n   * @defaultValue String\n   */\n  ariaLabel?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener } from '@vueuse/core'\nimport { computed, onMounted } from 'vue'\nimport { DismissableLayer } from '@/DismissableLayer'\nimport { PopperContent } from '@/Popper'\nimport { VisuallyHidden } from '@/VisuallyHidden'\nimport { injectTooltipRootContext } from './TooltipRoot.vue'\nimport { TOOLTIP_OPEN } from './utils'\n\nconst props = withDefaults(defineProps<TooltipContentImplProps>(), {\n  avoidCollisions: undefined,\n  asChild: undefined,\n  hideWhenDetached: undefined,\n})\nconst emits = defineEmits<TooltipContentImplEmits>()\n\nconst rootContext = injectTooltipRootContext()\nconst providerContext = injectTooltipProviderContext()\n\nconst { forwardRef, currentElement } = useForwardExpose()\nconst ariaLabel = computed(() => props.ariaLabel || currentElement.value?.textContent)\n\nconst popperContentProps = computed(() => {\n  const { ariaLabel: _, ...restProps } = props\n\n  return defu(restProps, providerContext.content.value ?? {}, {\n    side: 'top',\n    sideOffset: 0,\n    align: 'center',\n    avoidCollisions: true,\n    collisionBoundary: [],\n    collisionPadding: 0,\n    arrowPadding: 0,\n    sticky: 'partial',\n    hideWhenDetached: false,\n  } satisfies TooltipContentImplProps)\n})\n\nonMounted(() => {\n  // Close the tooltip if the trigger is scrolled\n  useEventListener(window, 'scroll', (event) => {\n    const target = event.target as HTMLElement\n    if (target?.contains(rootContext.trigger.value!))\n      rootContext.onClose()\n  }, { capture: true })\n  // Close this tooltip if another one opens\n  useEventListener(window, TOOLTIP_OPEN, rootContext.onClose)\n})\n</script>\n\n<template>\n  <DismissableLayer\n    as-child\n    :disable-outside-pointer-events=\"false\"\n    @escape-key-down=\"emits('escapeKeyDown', $event)\"\n    @pointer-down-outside=\"(event) => {\n      if (rootContext.disableClosingTrigger.value && rootContext.trigger.value?.contains(event.target as HTMLElement))\n        event.preventDefault()\n\n      emits('pointerDownOutside', event)\n    }\"\n    @focus-outside.prevent\n    @dismiss=\"rootContext.onClose()\"\n  >\n    <PopperContent\n      :ref=\"forwardRef\"\n      :data-state=\"rootContext.stateAttribute.value\"\n      v-bind=\"{ ...$attrs, ...popperContentProps }\"\n      :style=\"{\n        '--reka-tooltip-content-transform-origin': 'var(--reka-popper-transform-origin)',\n        '--reka-tooltip-content-available-width': 'var(--reka-popper-available-width)',\n        '--reka-tooltip-content-available-height': 'var(--reka-popper-available-height)',\n        '--reka-tooltip-trigger-width': 'var(--reka-popper-anchor-width)',\n        '--reka-tooltip-trigger-height': 'var(--reka-popper-anchor-height)',\n      }\"\n    >\n      <slot />\n      <VisuallyHidden\n        :id=\"rootContext.contentId\"\n        role=\"tooltip\"\n      >\n        {{ ariaLabel }}\n      </VisuallyHidden>\n    </PopperContent>\n  </DismissableLayer>\n</template>\n","<script setup lang=\"ts\">\nimport type { TooltipContentImplProps } from './TooltipContentImpl.vue'\nimport { useForwardExpose, useForwardProps, useGraceArea } from '@/shared'\nimport TooltipContentImpl from './TooltipContentImpl.vue'\nimport { injectTooltipProviderContext } from './TooltipProvider.vue'\nimport { injectTooltipRootContext } from './TooltipRoot.vue'\n\nconst props = defineProps<TooltipContentImplProps>()\nconst forwardedProps = useForwardProps(props)\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst { trigger, onClose } = injectTooltipRootContext()\nconst providerContext = injectTooltipProviderContext()\n\nconst { isPointerInTransit, onPointerExit } = useGraceArea(trigger, currentElement)\n\nproviderContext.isPointerInTransitRef = isPointerInTransit\nonPointerExit(() => {\n  onClose()\n})\n</script>\n\n<template>\n  <TooltipContentImpl\n    :ref=\"forwardRef\"\n    v-bind=\"forwardedProps\"\n  >\n    <slot />\n  </TooltipContentImpl>\n</template>\n","<script setup lang=\"ts\">\nimport type { TooltipContentImplProps } from './TooltipContentImpl.vue'\nimport { useForwardExpose, useForwardProps, useGraceArea } from '@/shared'\nimport TooltipContentImpl from './TooltipContentImpl.vue'\nimport { injectTooltipProviderContext } from './TooltipProvider.vue'\nimport { injectTooltipRootContext } from './TooltipRoot.vue'\n\nconst props = defineProps<TooltipContentImplProps>()\nconst forwardedProps = useForwardProps(props)\nconst { forwardRef, currentElement } = useForwardExpose()\n\nconst { trigger, onClose } = injectTooltipRootContext()\nconst providerContext = injectTooltipProviderContext()\n\nconst { isPointerInTransit, onPointerExit } = useGraceArea(trigger, currentElement)\n\nproviderContext.isPointerInTransitRef = isPointerInTransit\nonPointerExit(() => {\n  onClose()\n})\n</script>\n\n<template>\n  <TooltipContentImpl\n    :ref=\"forwardRef\"\n    v-bind=\"forwardedProps\"\n  >\n    <slot />\n  </TooltipContentImpl>\n</template>\n","<script lang=\"ts\">\nimport type { TooltipContentImplEmits, TooltipContentImplProps } from './TooltipContentImpl.vue'\n\nexport type TooltipContentEmits = TooltipContentImplEmits\n\nexport interface TooltipContentProps extends TooltipContentImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\nimport TooltipContentHoverable from './TooltipContentHoverable.vue'\nimport TooltipContentImpl from './TooltipContentImpl.vue'\nimport { injectTooltipRootContext } from './TooltipRoot.vue'\n\nconst props = defineProps<TooltipContentProps>()\nconst emits = defineEmits<TooltipContentEmits>()\n\nconst rootContext = injectTooltipRootContext()\nconst forwarded = useForwardPropsEmits(props, emits)\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <Presence :present=\"forceMount || rootContext.open.value\">\n    <component\n      :is=\"rootContext.disableHoverableContent.value ? TooltipContentImpl : TooltipContentHoverable\"\n      :ref=\"forwardRef\"\n      v-bind=\"forwarded\"\n    >\n      <slot />\n    </component>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { TooltipContentImplEmits, TooltipContentImplProps } from './TooltipContentImpl.vue'\n\nexport type TooltipContentEmits = TooltipContentImplEmits\n\nexport interface TooltipContentProps extends TooltipContentImplProps {\n  /**\n   * Used to force mounting when more control is needed. Useful when\n   * controlling animation with Vue animation libraries.\n   */\n  forceMount?: boolean\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Presence } from '@/Presence'\nimport { useForwardExpose, useForwardPropsEmits } from '@/shared'\nimport TooltipContentHoverable from './TooltipContentHoverable.vue'\nimport TooltipContentImpl from './TooltipContentImpl.vue'\nimport { injectTooltipRootContext } from './TooltipRoot.vue'\n\nconst props = defineProps<TooltipContentProps>()\nconst emits = defineEmits<TooltipContentEmits>()\n\nconst rootContext = injectTooltipRootContext()\nconst forwarded = useForwardPropsEmits(props, emits)\nconst { forwardRef } = useForwardExpose()\n</script>\n\n<template>\n  <Presence :present=\"forceMount || rootContext.open.value\">\n    <component\n      :is=\"rootContext.disableHoverableContent.value ? TooltipContentImpl : TooltipContentHoverable\"\n      :ref=\"forwardRef\"\n      v-bind=\"forwarded\"\n    >\n      <slot />\n    </component>\n  </Presence>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface TooltipPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<TooltipPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport type { TeleportProps } from '@/Teleport'\n\nexport interface TooltipPortalProps extends TeleportProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { TeleportPrimitive } from '@/Teleport'\n\nconst props = defineProps<TooltipPortalProps>()\n</script>\n\n<template>\n  <TeleportPrimitive v-bind=\"props\">\n    <slot />\n  </TeleportPrimitive>\n</template>\n","<script lang=\"ts\">\nimport { useForwardExpose, useId } from '@/shared'\n\nexport type TooltipTriggerDataState\n  = | 'closed'\n    | 'delayed-open'\n    | 'instant-open'\n\nexport interface TooltipTriggerProps extends PopperAnchorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport type { PopperAnchorProps } from '@/Popper'\nimport { computed, onMounted, ref } from 'vue'\nimport { PopperAnchor } from '@/Popper'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectTooltipProviderContext } from './TooltipProvider.vue'\nimport { injectTooltipRootContext } from './TooltipRoot.vue'\n\nconst props = withDefaults(defineProps<TooltipTriggerProps>(), {\n  as: 'button',\n})\nconst rootContext = injectTooltipRootContext()\nconst providerContext = injectTooltipProviderContext()\n\nrootContext.contentId ||= useId(undefined, 'reka-tooltip-content')\n\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\n\nconst isPointerDown = ref(false)\nconst hasPointerMoveOpened = ref(false)\n\nconst tooltipListeners = computed(() => {\n  if (rootContext.disabled.value)\n    return {}\n\n  return {\n    click: handleClick,\n    focus: handleFocus,\n    pointermove: handlePointerMove,\n    pointerleave: handlePointerLeave,\n    pointerdown: handlePointerDown,\n    blur: handleBlur,\n  }\n})\n\nonMounted(() => {\n  rootContext.onTriggerChange(triggerElement.value)\n})\n\nfunction handlePointerUp() {\n  setTimeout(() => {\n    isPointerDown.value = false\n  }, 1)\n}\n\nfunction handlePointerDown() {\n  if (rootContext.open && !rootContext.disableClosingTrigger.value) {\n    rootContext.onClose()\n  }\n  isPointerDown.value = true\n  document.addEventListener('pointerup', handlePointerUp, { once: true })\n}\n\nfunction handlePointerMove(event: PointerEvent) {\n  if (event.pointerType === 'touch')\n    return\n  if (\n    !hasPointerMoveOpened.value && !providerContext.isPointerInTransitRef.value\n  ) {\n    rootContext.onTriggerEnter()\n    hasPointerMoveOpened.value = true\n  }\n}\n\nfunction handlePointerLeave() {\n  rootContext.onTriggerLeave()\n  hasPointerMoveOpened.value = false\n}\n\nfunction handleFocus(event: FocusEvent) {\n  if (isPointerDown.value)\n    return\n\n  if (rootContext.ignoreNonKeyboardFocus.value && !(event.target as HTMLElement).matches?.(':focus-visible'))\n    return\n\n  rootContext.onOpen()\n}\n\nfunction handleBlur() {\n  rootContext.onClose()\n}\n\nfunction handleClick() {\n  if (!rootContext.disableClosingTrigger.value)\n    rootContext.onClose()\n}\n</script>\n\n<template>\n  <PopperAnchor\n    as-child\n    :reference=\"reference\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :aria-describedby=\"\n        rootContext.open.value ? rootContext.contentId : undefined\n      \"\n      :data-state=\"rootContext.stateAttribute.value\"\n      :as=\"as\"\n      :as-child=\"props.asChild\"\n      data-grace-area-trigger\n      v-on=\"tooltipListeners\"\n    >\n      <slot />\n    </Primitive>\n  </PopperAnchor>\n</template>\n","<script lang=\"ts\">\nimport { useForwardExpose, useId } from '@/shared'\n\nexport type TooltipTriggerDataState\n  = | 'closed'\n    | 'delayed-open'\n    | 'instant-open'\n\nexport interface TooltipTriggerProps extends PopperAnchorProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport type { PopperAnchorProps } from '@/Popper'\nimport { computed, onMounted, ref } from 'vue'\nimport { PopperAnchor } from '@/Popper'\nimport {\n  Primitive,\n} from '@/Primitive'\nimport { injectTooltipProviderContext } from './TooltipProvider.vue'\nimport { injectTooltipRootContext } from './TooltipRoot.vue'\n\nconst props = withDefaults(defineProps<TooltipTriggerProps>(), {\n  as: 'button',\n})\nconst rootContext = injectTooltipRootContext()\nconst providerContext = injectTooltipProviderContext()\n\nrootContext.contentId ||= useId(undefined, 'reka-tooltip-content')\n\nconst { forwardRef, currentElement: triggerElement } = useForwardExpose()\n\nconst isPointerDown = ref(false)\nconst hasPointerMoveOpened = ref(false)\n\nconst tooltipListeners = computed(() => {\n  if (rootContext.disabled.value)\n    return {}\n\n  return {\n    click: handleClick,\n    focus: handleFocus,\n    pointermove: handlePointerMove,\n    pointerleave: handlePointerLeave,\n    pointerdown: handlePointerDown,\n    blur: handleBlur,\n  }\n})\n\nonMounted(() => {\n  rootContext.onTriggerChange(triggerElement.value)\n})\n\nfunction handlePointerUp() {\n  setTimeout(() => {\n    isPointerDown.value = false\n  }, 1)\n}\n\nfunction handlePointerDown() {\n  if (rootContext.open && !rootContext.disableClosingTrigger.value) {\n    rootContext.onClose()\n  }\n  isPointerDown.value = true\n  document.addEventListener('pointerup', handlePointerUp, { once: true })\n}\n\nfunction handlePointerMove(event: PointerEvent) {\n  if (event.pointerType === 'touch')\n    return\n  if (\n    !hasPointerMoveOpened.value && !providerContext.isPointerInTransitRef.value\n  ) {\n    rootContext.onTriggerEnter()\n    hasPointerMoveOpened.value = true\n  }\n}\n\nfunction handlePointerLeave() {\n  rootContext.onTriggerLeave()\n  hasPointerMoveOpened.value = false\n}\n\nfunction handleFocus(event: FocusEvent) {\n  if (isPointerDown.value)\n    return\n\n  if (rootContext.ignoreNonKeyboardFocus.value && !(event.target as HTMLElement).matches?.(':focus-visible'))\n    return\n\n  rootContext.onOpen()\n}\n\nfunction handleBlur() {\n  rootContext.onClose()\n}\n\nfunction handleClick() {\n  if (!rootContext.disableClosingTrigger.value)\n    rootContext.onClose()\n}\n</script>\n\n<template>\n  <PopperAnchor\n    as-child\n    :reference=\"reference\"\n  >\n    <Primitive\n      :ref=\"forwardRef\"\n      :aria-describedby=\"\n        rootContext.open.value ? rootContext.contentId : undefined\n      \"\n      :data-state=\"rootContext.stateAttribute.value\"\n      :as=\"as\"\n      :as-child=\"props.asChild\"\n      data-grace-area-trigger\n      v-on=\"tooltipListeners\"\n    >\n      <slot />\n    </Primitive>\n  </PopperAnchor>\n</template>\n","export function flatten<U, T extends { children: any[] }>(items: T[]): U[] {\n  return items.reduce((acc: any[], item: T) => {\n    acc.push(item)\n\n    if (item.children)\n      acc.push(...flatten(item.children))\n\n    return acc\n  }, [])\n}\n\n// TODO: expose more utility function to handle flattened item\n","<script lang=\"ts\">\nimport type { Direction } from '@/shared/types'\nimport { createContext, getActiveElement, useDirection, useSelectionBehavior, useTypeahead } from '@/shared'\nimport { flatten } from './utils'\n\nexport interface TreeRootProps<T = Record<string, any>, U extends Record<string, any> = Record<string, any>, M extends boolean = false> extends PrimitiveProps {\n  /** The controlled value of the tree. Can be binded with `v-model`. */\n  modelValue?: M extends true ? U[] : U\n  /** The value of the tree when initially rendered. Use when you do not need to control the state of the tree */\n  defaultValue?: M extends true ? U[] : U\n  /** List of items */\n  items?: T[]\n  /** The controlled value of the expanded item. Can be binded with `v-model`. */\n  expanded?: string[]\n  /** The value of the expanded tree when initially rendered. Use when you do not need to control the state of the expanded tree */\n  defaultExpanded?: string[]\n  /** This function is passed the index of each item and should return a unique key for that item */\n  getKey: (val: T) => string\n  /** This function is passed the index of each item and should return a list of children for that item */\n  getChildren?: (val: T) => T[] | undefined\n  /** How multiple selection should behave in the collection. */\n  selectionBehavior?: 'toggle' | 'replace'\n  /** Whether multiple options can be selected or not.  */\n  multiple?: M | boolean\n  /** The reading direction of the listbox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** When `true`, prevents the user from interacting with tree  */\n  disabled?: boolean\n  /** When `true`, selecting parent will select the descendants. */\n  propagateSelect?: boolean\n  /** When `true`, selecting children will update the parent state. */\n  bubbleSelect?: boolean\n}\n\nexport type TreeRootEmits<T = Record<string, any>, M extends boolean = false> = {\n  'update:modelValue': [val: M extends true ? T[] : T]\n  'update:expanded': [val: string[]]\n}\n\ninterface TreeRootContext<T = Record<string, any>> {\n  modelValue: Ref<T | T[]>\n  selectedKeys: Ref<string[]>\n  onSelect: (val: T) => void\n  expanded: Ref<string[]>\n  onToggle: (val: T) => void\n  items: Ref<T[]>\n  expandedItems: Ref<T[]>\n  getKey: (val: T) => string\n  getChildren: (val: T) => T[] | undefined\n  multiple: Ref<boolean>\n  disabled: Ref<boolean>\n  dir: Ref<Direction>\n  propagateSelect: Ref<boolean>\n  bubbleSelect: Ref<boolean>\n  isVirtual: Ref<boolean>\n  virtualKeydownHook: EventHook<KeyboardEvent>\n\n  handleMultipleReplace: ReturnType<typeof useSelectionBehavior>['handleMultipleReplace']\n}\n\nexport type FlattenedItem<T> = {\n  _id: string\n  index: number\n  value: T\n  level: number\n  hasChildren: boolean\n  parentItem?: T\n  bind: {\n    value: T\n    level: number\n    [key: string]: any\n  }\n}\n\nexport const [injectTreeRootContext, provideTreeRootContext] = createContext<TreeRootContext<any>>('TreeRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends Record<string, any>, U extends Record<string, any>, M extends boolean = false\">\nimport type { EventHook } from '@vueuse/core'\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createEventHook, useVModel } from '@vueuse/core'\nimport { computed, nextTick, ref, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusGroup } from '@/RovingFocus'\nimport { MAP_KEY_TO_FOCUS_INTENT } from '@/RovingFocus/utils'\n\nconst props = withDefaults(defineProps<TreeRootProps<T, U, M>>(), {\n  as: 'ul',\n  selectionBehavior: 'toggle',\n  getChildren: (val: T) => val.children,\n})\nconst emits = defineEmits<TreeRootEmits<U, M>>()\n\ndefineSlots<{\n  default?: (props: {\n    flattenItems: FlattenedItem<T>[]\n    modelValue: M extends true ? U[] : U\n    expanded: typeof expanded.value\n  }) => any\n}>()\n\nconst { items, multiple, disabled, propagateSelect, dir: propDir, bubbleSelect } = toRefs(props)\nconst { handleTypeaheadSearch } = useTypeahead()\nconst dir = useDirection(propDir)\nconst rovingFocusGroupRef = ref<InstanceType<typeof RovingFocusGroup>>()\n\n// Virtualizer\nconst isVirtual = ref(false)\nconst virtualKeydownHook = createEventHook<KeyboardEvent>()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  // @ts-expect-error idk\n  defaultValue: props.defaultValue ?? (multiple.value ? [] : undefined),\n  passive: true,\n  deep: true,\n}) as Ref<U | U[]>\n\nconst expanded = useVModel(props, 'expanded', emits, {\n  // @ts-expect-error idk\n  defaultValue: props.defaultExpanded ?? [],\n  passive: (props.expanded === undefined) as false,\n  deep: true,\n}) as Ref<string[]>\n\nconst { onSelectItem, handleMultipleReplace } = useSelectionBehavior(modelValue, props)\n\nconst selectedKeys = computed(() => {\n  if (multiple.value && Array.isArray(modelValue.value))\n    return modelValue.value.map(i => props.getKey(i as any))\n  else\n    return [props.getKey(modelValue.value as any ?? {})]\n})\n\nfunction flattenItems(items: T[], level: number = 1, parentItem?: T): FlattenedItem<T>[] {\n  return items.reduce((acc: FlattenedItem<T>[], item: T, index: number) => {\n    const key = props.getKey(item)\n    const children = props.getChildren(item)\n    const isExpanded = expanded.value.includes(key)\n\n    const flattenedItem: FlattenedItem<T> = {\n      _id: key,\n      value: item,\n      index,\n      level,\n      parentItem,\n      hasChildren: !!children,\n      bind: {\n        'value': item,\n        level,\n        'aria-setsize': items.length,\n        'aria-posinset': index + 1,\n      },\n    }\n    acc.push(flattenedItem)\n\n    if (children && isExpanded)\n      acc.push(...flattenItems(children, level + 1, item))\n\n    return acc\n  }, [])\n}\n\nconst expandedItems = computed(() => {\n  const items = props.items\n  const expandedKeys = expanded.value.map(i => i)\n  return flattenItems(items ?? [])\n})\n\nfunction handleKeydown(event: KeyboardEvent) {\n  if (isVirtual.value) {\n    virtualKeydownHook.trigger(event)\n  }\n  else {\n    const collections = rovingFocusGroupRef.value?.getItems() ?? []\n    handleTypeaheadSearch(event.key, collections)\n  }\n}\n\nfunction handleKeydownNavigation(event: KeyboardEvent) {\n  if (isVirtual.value)\n    return\n\n  const intent = MAP_KEY_TO_FOCUS_INTENT[event.key]\n  nextTick(() => {\n    handleMultipleReplace(\n      intent,\n      getActiveElement(),\n      rovingFocusGroupRef.value?.getItems!,\n      expandedItems.value.map(i => i.value),\n    )\n  })\n}\n\nfunction handleBubbleSelect(item: FlattenedItem<T>) {\n  if (item.parentItem != null && Array.isArray(modelValue.value) && props.multiple) {\n    const parentItem = expandedItems.value.find((i) => {\n      return item.parentItem != null && props.getKey(i.value) === props.getKey(item.parentItem)\n    })\n\n    if (parentItem != null) {\n      const areAllChilredOfParentSelected = props.getChildren(parentItem.value)?.every(i => modelValue.value.find((v: any) => props.getKey(v) === props.getKey(i)))\n\n      if (areAllChilredOfParentSelected) {\n        modelValue.value = [...modelValue.value, parentItem.value as any]\n      }\n      else {\n        modelValue.value = modelValue.value.filter((v: any) => props.getKey(v) !== props.getKey(parentItem.value))\n      }\n\n      handleBubbleSelect(parentItem)\n    }\n  }\n}\n\nprovideTreeRootContext({\n  modelValue,\n  selectedKeys,\n  onSelect: (val) => {\n    const condition = (baseValue: U) => props.getKey(baseValue as any ?? {}) === props.getKey(val)\n    const exist = props.multiple && Array.isArray(modelValue.value) ? modelValue.value?.findIndex(condition) !== -1 : undefined\n    onSelectItem(val, condition)\n\n    if (props.bubbleSelect && props.multiple && Array.isArray(modelValue.value)) {\n      const item = expandedItems.value.find((i) => {\n        return props.getKey(i.value) === props.getKey(val)\n      })\n      if (item != null) {\n        handleBubbleSelect(item)\n      }\n    }\n\n    if (props.propagateSelect && props.multiple && Array.isArray(modelValue.value)) {\n      const children = flatten<U, any>(props.getChildren(val) ?? [])\n\n      if (exist) {\n        // remove all child\n        modelValue.value = [...modelValue.value]\n          .filter(i => !children.some(child => props.getKey(i as any ?? {}) === props.getKey(child as any)))\n      }\n      else {\n        // select all child\n        modelValue.value = [...modelValue.value, ...children]\n      }\n    }\n  },\n  expanded,\n  onToggle(val) {\n    const children = val ? props.getChildren(val) : undefined\n    if (!children)\n      return\n\n    const key = props.getKey(val) ?? val\n    if (expanded.value.includes(key))\n      expanded.value = expanded.value.filter(val => val !== key)\n    else\n      expanded.value = [...expanded.value, key]\n  },\n  getKey: props.getKey,\n  getChildren: props.getChildren,\n  items,\n  expandedItems,\n  disabled,\n  multiple,\n  dir,\n  propagateSelect,\n  bubbleSelect,\n\n  isVirtual,\n  virtualKeydownHook,\n  handleMultipleReplace,\n})\n</script>\n\n<template>\n  <RovingFocusGroup\n    ref=\"rovingFocusGroupRef\"\n    as-child\n    orientation=\"vertical\"\n    :dir=\"dir\"\n  >\n    <Primitive\n      role=\"tree\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :aria-multiselectable=\"multiple ? true : undefined\"\n      @keydown=\"handleKeydown\"\n      @keydown.up.down.shift=\"handleKeydownNavigation\"\n    >\n      <slot\n        :flatten-items=\"expandedItems\"\n        :model-value=\"modelValue as M extends true ? U[] : U\"\n        :expanded=\"expanded\"\n      />\n    </Primitive>\n  </RovingFocusGroup>\n</template>\n","<script lang=\"ts\">\nimport type { Direction } from '@/shared/types'\nimport { createContext, getActiveElement, useDirection, useSelectionBehavior, useTypeahead } from '@/shared'\nimport { flatten } from './utils'\n\nexport interface TreeRootProps<T = Record<string, any>, U extends Record<string, any> = Record<string, any>, M extends boolean = false> extends PrimitiveProps {\n  /** The controlled value of the tree. Can be binded with `v-model`. */\n  modelValue?: M extends true ? U[] : U\n  /** The value of the tree when initially rendered. Use when you do not need to control the state of the tree */\n  defaultValue?: M extends true ? U[] : U\n  /** List of items */\n  items?: T[]\n  /** The controlled value of the expanded item. Can be binded with `v-model`. */\n  expanded?: string[]\n  /** The value of the expanded tree when initially rendered. Use when you do not need to control the state of the expanded tree */\n  defaultExpanded?: string[]\n  /** This function is passed the index of each item and should return a unique key for that item */\n  getKey: (val: T) => string\n  /** This function is passed the index of each item and should return a list of children for that item */\n  getChildren?: (val: T) => T[] | undefined\n  /** How multiple selection should behave in the collection. */\n  selectionBehavior?: 'toggle' | 'replace'\n  /** Whether multiple options can be selected or not.  */\n  multiple?: M | boolean\n  /** The reading direction of the listbox when applicable. <br> If omitted, inherits globally from `ConfigProvider` or assumes LTR (left-to-right) reading mode. */\n  dir?: Direction\n  /** When `true`, prevents the user from interacting with tree  */\n  disabled?: boolean\n  /** When `true`, selecting parent will select the descendants. */\n  propagateSelect?: boolean\n  /** When `true`, selecting children will update the parent state. */\n  bubbleSelect?: boolean\n}\n\nexport type TreeRootEmits<T = Record<string, any>, M extends boolean = false> = {\n  'update:modelValue': [val: M extends true ? T[] : T]\n  'update:expanded': [val: string[]]\n}\n\ninterface TreeRootContext<T = Record<string, any>> {\n  modelValue: Ref<T | T[]>\n  selectedKeys: Ref<string[]>\n  onSelect: (val: T) => void\n  expanded: Ref<string[]>\n  onToggle: (val: T) => void\n  items: Ref<T[]>\n  expandedItems: Ref<T[]>\n  getKey: (val: T) => string\n  getChildren: (val: T) => T[] | undefined\n  multiple: Ref<boolean>\n  disabled: Ref<boolean>\n  dir: Ref<Direction>\n  propagateSelect: Ref<boolean>\n  bubbleSelect: Ref<boolean>\n  isVirtual: Ref<boolean>\n  virtualKeydownHook: EventHook<KeyboardEvent>\n\n  handleMultipleReplace: ReturnType<typeof useSelectionBehavior>['handleMultipleReplace']\n}\n\nexport type FlattenedItem<T> = {\n  _id: string\n  index: number\n  value: T\n  level: number\n  hasChildren: boolean\n  parentItem?: T\n  bind: {\n    value: T\n    level: number\n    [key: string]: any\n  }\n}\n\nexport const [injectTreeRootContext, provideTreeRootContext] = createContext<TreeRootContext<any>>('TreeRoot')\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends Record<string, any>, U extends Record<string, any>, M extends boolean = false\">\nimport type { EventHook } from '@vueuse/core'\nimport type { Ref } from 'vue'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { createEventHook, useVModel } from '@vueuse/core'\nimport { computed, nextTick, ref, toRefs } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusGroup } from '@/RovingFocus'\nimport { MAP_KEY_TO_FOCUS_INTENT } from '@/RovingFocus/utils'\n\nconst props = withDefaults(defineProps<TreeRootProps<T, U, M>>(), {\n  as: 'ul',\n  selectionBehavior: 'toggle',\n  getChildren: (val: T) => val.children,\n})\nconst emits = defineEmits<TreeRootEmits<U, M>>()\n\ndefineSlots<{\n  default?: (props: {\n    flattenItems: FlattenedItem<T>[]\n    modelValue: M extends true ? U[] : U\n    expanded: typeof expanded.value\n  }) => any\n}>()\n\nconst { items, multiple, disabled, propagateSelect, dir: propDir, bubbleSelect } = toRefs(props)\nconst { handleTypeaheadSearch } = useTypeahead()\nconst dir = useDirection(propDir)\nconst rovingFocusGroupRef = ref<InstanceType<typeof RovingFocusGroup>>()\n\n// Virtualizer\nconst isVirtual = ref(false)\nconst virtualKeydownHook = createEventHook<KeyboardEvent>()\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  // @ts-expect-error idk\n  defaultValue: props.defaultValue ?? (multiple.value ? [] : undefined),\n  passive: true,\n  deep: true,\n}) as Ref<U | U[]>\n\nconst expanded = useVModel(props, 'expanded', emits, {\n  // @ts-expect-error idk\n  defaultValue: props.defaultExpanded ?? [],\n  passive: (props.expanded === undefined) as false,\n  deep: true,\n}) as Ref<string[]>\n\nconst { onSelectItem, handleMultipleReplace } = useSelectionBehavior(modelValue, props)\n\nconst selectedKeys = computed(() => {\n  if (multiple.value && Array.isArray(modelValue.value))\n    return modelValue.value.map(i => props.getKey(i as any))\n  else\n    return [props.getKey(modelValue.value as any ?? {})]\n})\n\nfunction flattenItems(items: T[], level: number = 1, parentItem?: T): FlattenedItem<T>[] {\n  return items.reduce((acc: FlattenedItem<T>[], item: T, index: number) => {\n    const key = props.getKey(item)\n    const children = props.getChildren(item)\n    const isExpanded = expanded.value.includes(key)\n\n    const flattenedItem: FlattenedItem<T> = {\n      _id: key,\n      value: item,\n      index,\n      level,\n      parentItem,\n      hasChildren: !!children,\n      bind: {\n        'value': item,\n        level,\n        'aria-setsize': items.length,\n        'aria-posinset': index + 1,\n      },\n    }\n    acc.push(flattenedItem)\n\n    if (children && isExpanded)\n      acc.push(...flattenItems(children, level + 1, item))\n\n    return acc\n  }, [])\n}\n\nconst expandedItems = computed(() => {\n  const items = props.items\n  const expandedKeys = expanded.value.map(i => i)\n  return flattenItems(items ?? [])\n})\n\nfunction handleKeydown(event: KeyboardEvent) {\n  if (isVirtual.value) {\n    virtualKeydownHook.trigger(event)\n  }\n  else {\n    const collections = rovingFocusGroupRef.value?.getItems() ?? []\n    handleTypeaheadSearch(event.key, collections)\n  }\n}\n\nfunction handleKeydownNavigation(event: KeyboardEvent) {\n  if (isVirtual.value)\n    return\n\n  const intent = MAP_KEY_TO_FOCUS_INTENT[event.key]\n  nextTick(() => {\n    handleMultipleReplace(\n      intent,\n      getActiveElement(),\n      rovingFocusGroupRef.value?.getItems!,\n      expandedItems.value.map(i => i.value),\n    )\n  })\n}\n\nfunction handleBubbleSelect(item: FlattenedItem<T>) {\n  if (item.parentItem != null && Array.isArray(modelValue.value) && props.multiple) {\n    const parentItem = expandedItems.value.find((i) => {\n      return item.parentItem != null && props.getKey(i.value) === props.getKey(item.parentItem)\n    })\n\n    if (parentItem != null) {\n      const areAllChilredOfParentSelected = props.getChildren(parentItem.value)?.every(i => modelValue.value.find((v: any) => props.getKey(v) === props.getKey(i)))\n\n      if (areAllChilredOfParentSelected) {\n        modelValue.value = [...modelValue.value, parentItem.value as any]\n      }\n      else {\n        modelValue.value = modelValue.value.filter((v: any) => props.getKey(v) !== props.getKey(parentItem.value))\n      }\n\n      handleBubbleSelect(parentItem)\n    }\n  }\n}\n\nprovideTreeRootContext({\n  modelValue,\n  selectedKeys,\n  onSelect: (val) => {\n    const condition = (baseValue: U) => props.getKey(baseValue as any ?? {}) === props.getKey(val)\n    const exist = props.multiple && Array.isArray(modelValue.value) ? modelValue.value?.findIndex(condition) !== -1 : undefined\n    onSelectItem(val, condition)\n\n    if (props.bubbleSelect && props.multiple && Array.isArray(modelValue.value)) {\n      const item = expandedItems.value.find((i) => {\n        return props.getKey(i.value) === props.getKey(val)\n      })\n      if (item != null) {\n        handleBubbleSelect(item)\n      }\n    }\n\n    if (props.propagateSelect && props.multiple && Array.isArray(modelValue.value)) {\n      const children = flatten<U, any>(props.getChildren(val) ?? [])\n\n      if (exist) {\n        // remove all child\n        modelValue.value = [...modelValue.value]\n          .filter(i => !children.some(child => props.getKey(i as any ?? {}) === props.getKey(child as any)))\n      }\n      else {\n        // select all child\n        modelValue.value = [...modelValue.value, ...children]\n      }\n    }\n  },\n  expanded,\n  onToggle(val) {\n    const children = val ? props.getChildren(val) : undefined\n    if (!children)\n      return\n\n    const key = props.getKey(val) ?? val\n    if (expanded.value.includes(key))\n      expanded.value = expanded.value.filter(val => val !== key)\n    else\n      expanded.value = [...expanded.value, key]\n  },\n  getKey: props.getKey,\n  getChildren: props.getChildren,\n  items,\n  expandedItems,\n  disabled,\n  multiple,\n  dir,\n  propagateSelect,\n  bubbleSelect,\n\n  isVirtual,\n  virtualKeydownHook,\n  handleMultipleReplace,\n})\n</script>\n\n<template>\n  <RovingFocusGroup\n    ref=\"rovingFocusGroupRef\"\n    as-child\n    orientation=\"vertical\"\n    :dir=\"dir\"\n  >\n    <Primitive\n      role=\"tree\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :aria-multiselectable=\"multiple ? true : undefined\"\n      @keydown=\"handleKeydown\"\n      @keydown.up.down.shift=\"handleKeydownNavigation\"\n    >\n      <slot\n        :flatten-items=\"expandedItems\"\n        :model-value=\"modelValue as M extends true ? U[] : U\"\n        :expanded=\"expanded\"\n      />\n    </Primitive>\n  </RovingFocusGroup>\n</template>\n","<script lang=\"ts\">\nexport interface TreeItemProps<T> extends PrimitiveProps {\n  /** Value given to this item */\n  value: T\n  /** Level of depth */\n  level: number\n}\n\nexport type SelectEvent<T> = CustomEvent<{ originalEvent: PointerEvent | KeyboardEvent, value?: T, isExpanded: boolean, isSelected: boolean }>\nexport type ToggleEvent<T> = CustomEvent<{ originalEvent: PointerEvent | KeyboardEvent, value?: T, isExpanded: boolean, isSelected: boolean }>\n\nexport type TreeItemEmits<T> = {\n  /** Event handler called when the selecting item. <br> It can be prevented by calling `event.preventDefault`. */\n  select: [event: SelectEvent<T>]\n  /** Event handler called when the selecting item. <br> It can be prevented by calling `event.preventDefault`. */\n  toggle: [event: ToggleEvent<T>]\n}\n\nconst TREE_SELECT = 'tree.select'\nconst TREE_TOGGLE = 'tree.toggle'\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends Record<string, any>\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\nimport { getActiveElement, handleAndDispatchCustomEvent } from '@/shared'\nimport { injectTreeRootContext } from './TreeRoot.vue'\nimport { flatten } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<TreeItemProps<T>>(), {\n  as: 'li',\n})\n\nconst emits = defineEmits<TreeItemEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    isExpanded: boolean\n    isSelected: boolean\n    isIndeterminate: boolean | undefined\n    handleToggle: () => void\n    handleSelect: () => void\n  }) => any\n}>()\nconst rootContext = injectTreeRootContext()\nconst { getItems } = useCollection()\n\nconst hasChildren = computed(() => !!rootContext.getChildren(props.value))\n\nconst isExpanded = computed(() => {\n  const key = rootContext.getKey(props.value)\n  return rootContext.expanded.value.includes(key)\n})\n\nconst isSelected = computed(() => {\n  const key = rootContext.getKey(props.value)\n  return rootContext.selectedKeys.value.includes(key)\n})\n\nconst isIndeterminate = computed(() => {\n  if (rootContext.bubbleSelect.value && hasChildren.value && Array.isArray(rootContext.modelValue.value)) {\n    const children = flatten<T, any>(rootContext.getChildren(props.value) || [])\n\n    return children.some(child => rootContext.modelValue.value.find((v: any) => rootContext.getKey(v) === rootContext.getKey(child)))\n      && !children.every(child => rootContext.modelValue.value.find((v: any) => rootContext.getKey(v) === rootContext.getKey(child)))\n  }\n  else if (rootContext.propagateSelect.value && isSelected.value && hasChildren.value && Array.isArray(rootContext.modelValue.value)) {\n    const children = flatten<T, any>(rootContext.getChildren(props.value) || [])\n\n    return !children.every(child => rootContext.modelValue.value.find((v: any) => rootContext.getKey(v) === rootContext.getKey(child)))\n  }\n  else {\n    return undefined\n  }\n})\n\nfunction handleKeydownRight(ev: KeyboardEvent) {\n  if (!hasChildren.value)\n    return\n\n  if (isExpanded.value) {\n    // go to first child\n    const collection = getItems().map(i => i.ref)\n    const currentElement = getActiveElement() as HTMLElement\n    const currentIndex = collection.indexOf(currentElement)\n    const list = [...collection].slice(currentIndex)\n    const nextElement = list.find(el => Number(el.getAttribute('data-indent')) === (props.level + 1))\n\n    if (nextElement)\n      nextElement.focus()\n  }\n  else {\n    //  open expanded\n    handleToggleCustomEvent(ev)\n  }\n}\n\nfunction handleKeydownLeft(ev: KeyboardEvent) {\n  if (isExpanded.value) {\n    //  close expanded\n    handleToggleCustomEvent(ev)\n  }\n  else {\n    // go back to parent\n    const collection = getItems().map(i => i.ref)\n    const currentElement = getActiveElement() as HTMLElement\n    const currentIndex = collection.indexOf(currentElement)\n    const list = [...collection].slice(0, currentIndex).reverse()\n    const parentElement = list.find(el => Number(el.getAttribute('data-indent')) === (props.level - 1))\n\n    if (parentElement)\n      parentElement.focus()\n  }\n}\n\nasync function handleSelect(ev: SelectEvent<T>) {\n  emits('select', ev)\n  if (ev?.defaultPrevented)\n    return\n\n  rootContext.onSelect(props.value)\n}\nasync function handleToggle(ev: ToggleEvent<T>) {\n  emits('toggle', ev)\n  if (ev?.defaultPrevented)\n    return\n\n  rootContext.onToggle(props.value)\n}\n\nasync function handleSelectCustomEvent(ev?: PointerEvent | KeyboardEvent) {\n  if (!ev)\n    return\n\n  const eventDetail = { originalEvent: ev, value: props.value, isExpanded: isExpanded.value, isSelected: isSelected.value }\n  handleAndDispatchCustomEvent(TREE_SELECT, handleSelect, eventDetail)\n}\n\nasync function handleToggleCustomEvent(ev?: PointerEvent | KeyboardEvent) {\n  if (!ev)\n    return\n\n  const eventDetail = { originalEvent: ev, value: props.value, isExpanded: isExpanded.value, isSelected: isSelected.value }\n  handleAndDispatchCustomEvent(TREE_TOGGLE, handleToggle, eventDetail)\n}\n\ndefineExpose({\n  isExpanded,\n  isSelected,\n  isIndeterminate,\n  handleToggle: () => rootContext.onToggle(props.value),\n  handleSelect: () => rootContext.onSelect(props.value),\n})\n</script>\n\n<template>\n  <RovingFocusItem\n    as-child\n    :value=\"value\"\n    allow-shift-key\n  >\n    <Primitive\n      v-bind=\"$attrs\"\n      role=\"treeitem\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :aria-selected=\"isSelected\"\n      :aria-expanded=\"hasChildren ? isExpanded : undefined\"\n      :aria-level=\"level\"\n      :data-indent=\"level\"\n      :data-selected=\"isSelected ? '' : undefined\"\n      :data-expanded=\"isExpanded ? '' : undefined\"\n      @keydown.enter.space.self.prevent=\"handleSelectCustomEvent\"\n      @keydown.right.prevent=\"(ev: KeyboardEvent) => rootContext.dir.value === 'ltr' ? handleKeydownRight(ev) : handleKeydownLeft(ev)\"\n      @keydown.left.prevent=\"(ev: KeyboardEvent) => rootContext.dir.value === 'ltr' ? handleKeydownLeft(ev) : handleKeydownRight(ev)\"\n      @click.stop=\"(ev: PointerEvent) => {\n        handleSelectCustomEvent(ev)\n        handleToggleCustomEvent(ev)\n      }\"\n    >\n      <slot\n        :is-expanded=\"isExpanded\"\n        :is-selected=\"isSelected\"\n        :is-indeterminate=\"isIndeterminate\"\n        :handle-select=\"() => rootContext.onSelect(value)\"\n        :handle-toggle=\"() => rootContext.onToggle(value)\"\n      />\n    </Primitive>\n  </RovingFocusItem>\n</template>\n","<script lang=\"ts\">\nexport interface TreeItemProps<T> extends PrimitiveProps {\n  /** Value given to this item */\n  value: T\n  /** Level of depth */\n  level: number\n}\n\nexport type SelectEvent<T> = CustomEvent<{ originalEvent: PointerEvent | KeyboardEvent, value?: T, isExpanded: boolean, isSelected: boolean }>\nexport type ToggleEvent<T> = CustomEvent<{ originalEvent: PointerEvent | KeyboardEvent, value?: T, isExpanded: boolean, isSelected: boolean }>\n\nexport type TreeItemEmits<T> = {\n  /** Event handler called when the selecting item. <br> It can be prevented by calling `event.preventDefault`. */\n  select: [event: SelectEvent<T>]\n  /** Event handler called when the selecting item. <br> It can be prevented by calling `event.preventDefault`. */\n  toggle: [event: ToggleEvent<T>]\n}\n\nconst TREE_SELECT = 'tree.select'\nconst TREE_TOGGLE = 'tree.toggle'\n</script>\n\n<script setup lang=\"ts\" generic=\"T extends Record<string, any>\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { computed } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { Primitive } from '@/Primitive'\nimport { RovingFocusItem } from '@/RovingFocus'\nimport { getActiveElement, handleAndDispatchCustomEvent } from '@/shared'\nimport { injectTreeRootContext } from './TreeRoot.vue'\nimport { flatten } from './utils'\n\ndefineOptions({\n  inheritAttrs: false,\n})\n\nconst props = withDefaults(defineProps<TreeItemProps<T>>(), {\n  as: 'li',\n})\n\nconst emits = defineEmits<TreeItemEmits<T>>()\n\ndefineSlots<{\n  default?: (props: {\n    isExpanded: boolean\n    isSelected: boolean\n    isIndeterminate: boolean | undefined\n    handleToggle: () => void\n    handleSelect: () => void\n  }) => any\n}>()\nconst rootContext = injectTreeRootContext()\nconst { getItems } = useCollection()\n\nconst hasChildren = computed(() => !!rootContext.getChildren(props.value))\n\nconst isExpanded = computed(() => {\n  const key = rootContext.getKey(props.value)\n  return rootContext.expanded.value.includes(key)\n})\n\nconst isSelected = computed(() => {\n  const key = rootContext.getKey(props.value)\n  return rootContext.selectedKeys.value.includes(key)\n})\n\nconst isIndeterminate = computed(() => {\n  if (rootContext.bubbleSelect.value && hasChildren.value && Array.isArray(rootContext.modelValue.value)) {\n    const children = flatten<T, any>(rootContext.getChildren(props.value) || [])\n\n    return children.some(child => rootContext.modelValue.value.find((v: any) => rootContext.getKey(v) === rootContext.getKey(child)))\n      && !children.every(child => rootContext.modelValue.value.find((v: any) => rootContext.getKey(v) === rootContext.getKey(child)))\n  }\n  else if (rootContext.propagateSelect.value && isSelected.value && hasChildren.value && Array.isArray(rootContext.modelValue.value)) {\n    const children = flatten<T, any>(rootContext.getChildren(props.value) || [])\n\n    return !children.every(child => rootContext.modelValue.value.find((v: any) => rootContext.getKey(v) === rootContext.getKey(child)))\n  }\n  else {\n    return undefined\n  }\n})\n\nfunction handleKeydownRight(ev: KeyboardEvent) {\n  if (!hasChildren.value)\n    return\n\n  if (isExpanded.value) {\n    // go to first child\n    const collection = getItems().map(i => i.ref)\n    const currentElement = getActiveElement() as HTMLElement\n    const currentIndex = collection.indexOf(currentElement)\n    const list = [...collection].slice(currentIndex)\n    const nextElement = list.find(el => Number(el.getAttribute('data-indent')) === (props.level + 1))\n\n    if (nextElement)\n      nextElement.focus()\n  }\n  else {\n    //  open expanded\n    handleToggleCustomEvent(ev)\n  }\n}\n\nfunction handleKeydownLeft(ev: KeyboardEvent) {\n  if (isExpanded.value) {\n    //  close expanded\n    handleToggleCustomEvent(ev)\n  }\n  else {\n    // go back to parent\n    const collection = getItems().map(i => i.ref)\n    const currentElement = getActiveElement() as HTMLElement\n    const currentIndex = collection.indexOf(currentElement)\n    const list = [...collection].slice(0, currentIndex).reverse()\n    const parentElement = list.find(el => Number(el.getAttribute('data-indent')) === (props.level - 1))\n\n    if (parentElement)\n      parentElement.focus()\n  }\n}\n\nasync function handleSelect(ev: SelectEvent<T>) {\n  emits('select', ev)\n  if (ev?.defaultPrevented)\n    return\n\n  rootContext.onSelect(props.value)\n}\nasync function handleToggle(ev: ToggleEvent<T>) {\n  emits('toggle', ev)\n  if (ev?.defaultPrevented)\n    return\n\n  rootContext.onToggle(props.value)\n}\n\nasync function handleSelectCustomEvent(ev?: PointerEvent | KeyboardEvent) {\n  if (!ev)\n    return\n\n  const eventDetail = { originalEvent: ev, value: props.value, isExpanded: isExpanded.value, isSelected: isSelected.value }\n  handleAndDispatchCustomEvent(TREE_SELECT, handleSelect, eventDetail)\n}\n\nasync function handleToggleCustomEvent(ev?: PointerEvent | KeyboardEvent) {\n  if (!ev)\n    return\n\n  const eventDetail = { originalEvent: ev, value: props.value, isExpanded: isExpanded.value, isSelected: isSelected.value }\n  handleAndDispatchCustomEvent(TREE_TOGGLE, handleToggle, eventDetail)\n}\n\ndefineExpose({\n  isExpanded,\n  isSelected,\n  isIndeterminate,\n  handleToggle: () => rootContext.onToggle(props.value),\n  handleSelect: () => rootContext.onSelect(props.value),\n})\n</script>\n\n<template>\n  <RovingFocusItem\n    as-child\n    :value=\"value\"\n    allow-shift-key\n  >\n    <Primitive\n      v-bind=\"$attrs\"\n      role=\"treeitem\"\n      :as=\"as\"\n      :as-child=\"asChild\"\n      :aria-selected=\"isSelected\"\n      :aria-expanded=\"hasChildren ? isExpanded : undefined\"\n      :aria-level=\"level\"\n      :data-indent=\"level\"\n      :data-selected=\"isSelected ? '' : undefined\"\n      :data-expanded=\"isExpanded ? '' : undefined\"\n      @keydown.enter.space.self.prevent=\"handleSelectCustomEvent\"\n      @keydown.right.prevent=\"(ev: KeyboardEvent) => rootContext.dir.value === 'ltr' ? handleKeydownRight(ev) : handleKeydownLeft(ev)\"\n      @keydown.left.prevent=\"(ev: KeyboardEvent) => rootContext.dir.value === 'ltr' ? handleKeydownLeft(ev) : handleKeydownRight(ev)\"\n      @click.stop=\"(ev: PointerEvent) => {\n        handleSelectCustomEvent(ev)\n        handleToggleCustomEvent(ev)\n      }\"\n    >\n      <slot\n        :is-expanded=\"isExpanded\"\n        :is-selected=\"isSelected\"\n        :is-indeterminate=\"isIndeterminate\"\n        :handle-select=\"() => rootContext.onSelect(value)\"\n        :handle-toggle=\"() => rootContext.onToggle(value)\"\n      />\n    </Primitive>\n  </RovingFocusItem>\n</template>\n","<script lang=\"ts\">\nexport interface TreeVirtualizerProps {\n  /** Number of items rendered outside the visible area */\n  overscan?: number\n  /** Estimated size (in px) of each item */\n  estimateSize?: number | ((index: number) => number)\n  /** Text content for each item to achieve type-ahead feature */\n  textContent?: (item: Record<string, any>) => string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport type { VirtualItem, Virtualizer } from '@tanstack/vue-virtual'\nimport type { Ref } from 'vue'\nimport type { FlattenedItem } from './TreeRoot.vue'\nimport { useVirtualizer } from '@tanstack/vue-virtual'\nimport { refAutoReset, useParentElement } from '@vueuse/core'\nimport { cloneVNode, computed, nextTick, useSlots } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { MAP_KEY_TO_FOCUS_INTENT } from '@/RovingFocus/utils'\nimport { getActiveElement } from '@/shared'\nimport { getNextMatch } from '@/shared/useTypeahead'\nimport { injectTreeRootContext } from './TreeRoot.vue'\n\nconst props = defineProps<TreeVirtualizerProps>()\n\ndefineSlots<{\n  default?: (props: {\n    item: FlattenedItem<Record<string, any>>\n    virtualizer: Virtualizer<Element | Window, Element>\n    virtualItem: VirtualItem\n  }) => any\n}>()\n\nconst slots = useSlots()\nconst rootContext = injectTreeRootContext()\nconst parentEl = useParentElement() as Ref<HTMLElement>\nconst { getItems } = useCollection()\n\n// Reset `search` 1 second after it was last updated\nconst search = refAutoReset('', 1000)\nconst optionsWithMetadata = computed(() => {\n  const parseTextContent = (option: Record<string, any>) => {\n    if (props.textContent)\n      return props.textContent(option)\n    else\n      return option.toString().toLowerCase()\n  }\n\n  return rootContext.expandedItems.value.map((option, index) => ({\n    index,\n    textContent: parseTextContent(option.value),\n  }))\n})\n\n// set virtual true when this component mounted\nrootContext.isVirtual.value = true\n\nconst padding = computed(() => {\n  const el = parentEl.value\n  if (!el) {\n    return { start: 0, end: 0 }\n  }\n  else {\n    const styles = window.getComputedStyle(el)\n    return {\n      start: Number.parseFloat(styles.paddingBlockStart || styles.paddingTop),\n      end: Number.parseFloat(styles.paddingBlockEnd || styles.paddingBottom),\n    }\n  }\n})\n\nconst virtualizer = useVirtualizer(\n  {\n    get scrollPaddingStart() { return padding.value.start },\n    get scrollPaddingEnd() { return padding.value.end },\n    get count() { return rootContext.expandedItems.value.length ?? 0 },\n    get horizontal() { return false },\n    getItemKey(index) {\n      return index + rootContext.getKey(rootContext.expandedItems.value[index].value)\n    },\n    estimateSize(index) {\n      if (typeof props.estimateSize === 'function')\n        return props.estimateSize(index)\n\n      return props.estimateSize ?? 28\n    },\n    getScrollElement() { return parentEl.value },\n    overscan: props.overscan ?? 12,\n  },\n)\n\nconst virtualizedItems = computed(() => virtualizer.value.getVirtualItems().map((item) => {\n  return {\n    item,\n    is: cloneVNode(slots.default!({\n      item: rootContext.expandedItems.value[item.index],\n      virtualizer: virtualizer.value,\n      virtualItem: item,\n    })![0], {\n      'data-index': item.index,\n      'style': {\n        position: 'absolute',\n        top: 0,\n        left: 0,\n        transform: `translateY(${item.start}px)`,\n        overflowAnchor: 'none',\n      },\n    }),\n  }\n}))\n\nfunction scrollToIndexAndFocus(index: number) {\n  virtualizer.value.scrollToIndex(index, { align: 'start' })\n  requestAnimationFrame(() => {\n    const item = parentEl.value.querySelector(`[data-index=\"${index}\"]`) as HTMLElement\n    if (item instanceof HTMLElement)\n      item.focus()\n  })\n}\n\nrootContext.virtualKeydownHook.on((event) => {\n  const isMetaKey = event.altKey || event.ctrlKey || event.metaKey\n  const isTabKey = event.key === 'Tab' && !isMetaKey\n  if (isTabKey)\n    return\n\n  const intent = MAP_KEY_TO_FOCUS_INTENT[event.key]\n\n  if (['first', 'last'].includes(intent)) {\n    event.preventDefault()\n\n    const index = intent === 'first' ? 0 : rootContext.expandedItems.value.length - 1\n    virtualizer.value.scrollToIndex(index)\n    requestAnimationFrame(() => {\n      const items = getItems()\n      const item = intent === 'first' ? items[0] : items.at(-1)!\n      item.ref.focus()\n    })\n  }\n  else if (intent === 'prev' && event.key !== 'ArrowUp') {\n    const currentElement = getActiveElement() as HTMLElement\n    const currentIndex = Number(currentElement.getAttribute('data-index'))\n    const currentLevel = Number(currentElement.getAttribute('data-indent'))\n    const list = rootContext.expandedItems.value.slice(0, currentIndex).map((item, index) => ({ ...item, index })).reverse()\n\n    const parentItem = list.find(item => item.level === (currentLevel - 1))\n    if (parentItem)\n      scrollToIndexAndFocus(parentItem.index)\n  }\n  else if (!intent && !isMetaKey) {\n    search.value += event.key\n    const currentIndex = Number(getActiveElement()?.getAttribute('data-index'))\n    const currentMatch = optionsWithMetadata.value[currentIndex].textContent\n    const filteredOptions = optionsWithMetadata.value.map(i => i.textContent)\n    const next = getNextMatch(filteredOptions, search.value, currentMatch)\n\n    const nextMatch = optionsWithMetadata.value.find(option => option.textContent === next)\n    if (nextMatch)\n      scrollToIndexAndFocus(nextMatch.index)\n  }\n\n  nextTick(() => {\n    if (event.shiftKey && intent)\n      rootContext.handleMultipleReplace(intent, getActiveElement(), getItems, rootContext.expandedItems.value.map(i => i.value))\n  })\n})\n</script>\n\n<template>\n  <div\n    data-reka-virtualizer\n    :style=\"{\n      position: 'relative',\n      width: '100%',\n      height: `${virtualizer.getTotalSize()}px`,\n    }\"\n  >\n    <component\n      :is=\"is\"\n      v-for=\"{ is, item } in virtualizedItems\"\n      :key=\"item.key\"\n    />\n  </div>\n</template>\n","<script lang=\"ts\">\nexport interface TreeVirtualizerProps {\n  /** Number of items rendered outside the visible area */\n  overscan?: number\n  /** Estimated size (in px) of each item */\n  estimateSize?: number | ((index: number) => number)\n  /** Text content for each item to achieve type-ahead feature */\n  textContent?: (item: Record<string, any>) => string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport type { VirtualItem, Virtualizer } from '@tanstack/vue-virtual'\nimport type { Ref } from 'vue'\nimport type { FlattenedItem } from './TreeRoot.vue'\nimport { useVirtualizer } from '@tanstack/vue-virtual'\nimport { refAutoReset, useParentElement } from '@vueuse/core'\nimport { cloneVNode, computed, nextTick, useSlots } from 'vue'\nimport { useCollection } from '@/Collection'\nimport { MAP_KEY_TO_FOCUS_INTENT } from '@/RovingFocus/utils'\nimport { getActiveElement } from '@/shared'\nimport { getNextMatch } from '@/shared/useTypeahead'\nimport { injectTreeRootContext } from './TreeRoot.vue'\n\nconst props = defineProps<TreeVirtualizerProps>()\n\ndefineSlots<{\n  default?: (props: {\n    item: FlattenedItem<Record<string, any>>\n    virtualizer: Virtualizer<Element | Window, Element>\n    virtualItem: VirtualItem\n  }) => any\n}>()\n\nconst slots = useSlots()\nconst rootContext = injectTreeRootContext()\nconst parentEl = useParentElement() as Ref<HTMLElement>\nconst { getItems } = useCollection()\n\n// Reset `search` 1 second after it was last updated\nconst search = refAutoReset('', 1000)\nconst optionsWithMetadata = computed(() => {\n  const parseTextContent = (option: Record<string, any>) => {\n    if (props.textContent)\n      return props.textContent(option)\n    else\n      return option.toString().toLowerCase()\n  }\n\n  return rootContext.expandedItems.value.map((option, index) => ({\n    index,\n    textContent: parseTextContent(option.value),\n  }))\n})\n\n// set virtual true when this component mounted\nrootContext.isVirtual.value = true\n\nconst padding = computed(() => {\n  const el = parentEl.value\n  if (!el) {\n    return { start: 0, end: 0 }\n  }\n  else {\n    const styles = window.getComputedStyle(el)\n    return {\n      start: Number.parseFloat(styles.paddingBlockStart || styles.paddingTop),\n      end: Number.parseFloat(styles.paddingBlockEnd || styles.paddingBottom),\n    }\n  }\n})\n\nconst virtualizer = useVirtualizer(\n  {\n    get scrollPaddingStart() { return padding.value.start },\n    get scrollPaddingEnd() { return padding.value.end },\n    get count() { return rootContext.expandedItems.value.length ?? 0 },\n    get horizontal() { return false },\n    getItemKey(index) {\n      return index + rootContext.getKey(rootContext.expandedItems.value[index].value)\n    },\n    estimateSize(index) {\n      if (typeof props.estimateSize === 'function')\n        return props.estimateSize(index)\n\n      return props.estimateSize ?? 28\n    },\n    getScrollElement() { return parentEl.value },\n    overscan: props.overscan ?? 12,\n  },\n)\n\nconst virtualizedItems = computed(() => virtualizer.value.getVirtualItems().map((item) => {\n  return {\n    item,\n    is: cloneVNode(slots.default!({\n      item: rootContext.expandedItems.value[item.index],\n      virtualizer: virtualizer.value,\n      virtualItem: item,\n    })![0], {\n      'data-index': item.index,\n      'style': {\n        position: 'absolute',\n        top: 0,\n        left: 0,\n        transform: `translateY(${item.start}px)`,\n        overflowAnchor: 'none',\n      },\n    }),\n  }\n}))\n\nfunction scrollToIndexAndFocus(index: number) {\n  virtualizer.value.scrollToIndex(index, { align: 'start' })\n  requestAnimationFrame(() => {\n    const item = parentEl.value.querySelector(`[data-index=\"${index}\"]`) as HTMLElement\n    if (item instanceof HTMLElement)\n      item.focus()\n  })\n}\n\nrootContext.virtualKeydownHook.on((event) => {\n  const isMetaKey = event.altKey || event.ctrlKey || event.metaKey\n  const isTabKey = event.key === 'Tab' && !isMetaKey\n  if (isTabKey)\n    return\n\n  const intent = MAP_KEY_TO_FOCUS_INTENT[event.key]\n\n  if (['first', 'last'].includes(intent)) {\n    event.preventDefault()\n\n    const index = intent === 'first' ? 0 : rootContext.expandedItems.value.length - 1\n    virtualizer.value.scrollToIndex(index)\n    requestAnimationFrame(() => {\n      const items = getItems()\n      const item = intent === 'first' ? items[0] : items.at(-1)!\n      item.ref.focus()\n    })\n  }\n  else if (intent === 'prev' && event.key !== 'ArrowUp') {\n    const currentElement = getActiveElement() as HTMLElement\n    const currentIndex = Number(currentElement.getAttribute('data-index'))\n    const currentLevel = Number(currentElement.getAttribute('data-indent'))\n    const list = rootContext.expandedItems.value.slice(0, currentIndex).map((item, index) => ({ ...item, index })).reverse()\n\n    const parentItem = list.find(item => item.level === (currentLevel - 1))\n    if (parentItem)\n      scrollToIndexAndFocus(parentItem.index)\n  }\n  else if (!intent && !isMetaKey) {\n    search.value += event.key\n    const currentIndex = Number(getActiveElement()?.getAttribute('data-index'))\n    const currentMatch = optionsWithMetadata.value[currentIndex].textContent\n    const filteredOptions = optionsWithMetadata.value.map(i => i.textContent)\n    const next = getNextMatch(filteredOptions, search.value, currentMatch)\n\n    const nextMatch = optionsWithMetadata.value.find(option => option.textContent === next)\n    if (nextMatch)\n      scrollToIndexAndFocus(nextMatch.index)\n  }\n\n  nextTick(() => {\n    if (event.shiftKey && intent)\n      rootContext.handleMultipleReplace(intent, getActiveElement(), getItems, rootContext.expandedItems.value.map(i => i.value))\n  })\n})\n</script>\n\n<template>\n  <div\n    data-reka-virtualizer\n    :style=\"{\n      position: 'relative',\n      width: '100%',\n      height: `${virtualizer.getTotalSize()}px`,\n    }\"\n  >\n    <component\n      :is=\"is\"\n      v-for=\"{ is, item } in virtualizedItems\"\n      :key=\"item.key\"\n    />\n  </div>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { toRefs } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport { useNonce } from '@/shared/useNonce'\n\nexport interface ViewportProps extends PrimitiveProps {\n  /**\n   * Will add `nonce` attribute to the style tag which can be used by Content Security Policy. <br> If omitted, inherits globally from `ConfigProvider`.\n   */\n  nonce?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<ViewportProps>()\nconst { forwardRef } = useForwardExpose()\n\nconst { nonce: propNonce } = toRefs(props)\nconst nonce = useNonce(propNonce)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"{ ...$attrs, ...props }\"\n    :ref=\"forwardRef\"\n    data-reka-viewport\n    role=\"presentation\"\n    :style=\"{\n      // we use position: 'relative' here on the `viewport` so that when we call\n      // `selectedItem.offsetTop` in calculations, the offset is relative to the viewport\n      // (independent of the scrollUpButton).\n      position: 'relative',\n      flex: 1,\n      overflow: 'auto',\n    }\"\n  >\n    <slot />\n  </Primitive>\n  <Primitive\n    as=\"style\"\n    :nonce=\"nonce\"\n  >\n    /* Hide scrollbars cross-browser and enable momentum scroll for touch\n    devices */ [data-reka-viewport] { scrollbar-width:none; -ms-overflow-style: none;\n    -webkit-overflow-scrolling: touch; }\n    [data-reka-viewport]::-webkit-scrollbar { display: none; }\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\nimport { toRefs } from 'vue'\nimport { useForwardExpose } from '@/shared'\nimport { useNonce } from '@/shared/useNonce'\n\nexport interface ViewportProps extends PrimitiveProps {\n  /**\n   * Will add `nonce` attribute to the style tag which can be used by Content Security Policy. <br> If omitted, inherits globally from `ConfigProvider`.\n   */\n  nonce?: string\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = defineProps<ViewportProps>()\nconst { forwardRef } = useForwardExpose()\n\nconst { nonce: propNonce } = toRefs(props)\nconst nonce = useNonce(propNonce)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"{ ...$attrs, ...props }\"\n    :ref=\"forwardRef\"\n    data-reka-viewport\n    role=\"presentation\"\n    :style=\"{\n      // we use position: 'relative' here on the `viewport` so that when we call\n      // `selectedItem.offsetTop` in calculations, the offset is relative to the viewport\n      // (independent of the scrollUpButton).\n      position: 'relative',\n      flex: 1,\n      overflow: 'auto',\n    }\"\n  >\n    <slot />\n  </Primitive>\n  <Primitive\n    as=\"style\"\n    :nonce=\"nonce\"\n  >\n    /* Hide scrollbars cross-browser and enable momentum scroll for touch\n    devices */ [data-reka-viewport] { scrollbar-width:none; -ms-overflow-style: none;\n    -webkit-overflow-scrolling: touch; }\n    [data-reka-viewport]::-webkit-scrollbar { display: none; }\n  </Primitive>\n</template>\n","import type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher } from '@/date'\nimport type { DateFormatterOptions } from '@/shared/useDateFormatter'\nimport { endOfYear, startOfYear } from '@internationalized/date'\nimport { computed, ref, watch } from 'vue'\nimport { createYearGrid, isAfter, isBefore, isSameYear, toDate } from '@/date'\nimport { useDateFormatter } from '@/shared'\n\nexport type UseYearPickerProps = {\n  locale: Ref<string>\n  placeholder: Ref<DateValue>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  disabled: Ref<boolean>\n  yearsPerPage: Ref<number>\n  isYearDisabled?: Matcher | Ref<Matcher | undefined>\n  isYearUnavailable?: Matcher | Ref<Matcher | undefined>\n  calendarLabel: Ref<string | undefined>\n  nextPage: Ref<((placeholder: DateValue) => DateValue) | undefined>\n  prevPage: Ref<((placeholder: DateValue) => DateValue) | undefined>\n}\n\nexport type UseYearPickerStateProps = {\n  isYearDisabled: Matcher\n  isYearUnavailable: Matcher\n  date: Ref<DateValue | DateValue[] | undefined>\n}\n\nexport function useYearPickerState(props: UseYearPickerStateProps) {\n  function isYearSelected(dateObj: DateValue) {\n    if (Array.isArray(props.date.value))\n      return props.date.value.some(d => isSameYear(d, dateObj))\n    else if (!props.date.value)\n      return false\n    else\n      return isSameYear(props.date.value, dateObj)\n  }\n\n  const isInvalid = computed(() => {\n    if (Array.isArray(props.date.value)) {\n      if (!props.date.value.length)\n        return false\n      for (const dateObj of props.date.value) {\n        if (props.isYearDisabled?.(dateObj))\n          return true\n        if (props.isYearUnavailable?.(dateObj))\n          return true\n      }\n    }\n    else {\n      if (!props.date.value)\n        return false\n      if (props.isYearDisabled?.(props.date.value))\n        return true\n      if (props.isYearUnavailable?.(props.date.value))\n        return true\n    }\n    return false\n  })\n\n  return { isYearSelected, isInvalid }\n}\n\nexport function useYearPicker(props: UseYearPickerProps) {\n  const formatter = useDateFormatter(props.locale.value)\n\n  const resolveMatcher = (matcher?: Matcher | Ref<Matcher | undefined>) =>\n    typeof matcher === 'function' ? matcher : matcher?.value\n\n  const headingFormatOptions = computed(() => {\n    const options: DateFormatterOptions = {\n      calendar: props.placeholder.value.calendar.identifier,\n    }\n\n    if (props.placeholder.value.calendar.identifier === 'gregory' && props.placeholder.value.era === 'BC')\n      options.era = 'short'\n\n    return options\n  })\n\n  const grid = ref<Grid<DateValue>>(createYearGrid({\n    dateObj: props.placeholder.value,\n    yearsPerPage: props.yearsPerPage.value,\n  })) as Ref<Grid<DateValue>>\n\n  function isYearDisabled(dateObj: DateValue) {\n    if (resolveMatcher(props.isYearDisabled)?.(dateObj) || props.disabled.value)\n      return true\n    if (props.maxValue.value && isAfter(startOfYear(dateObj), props.maxValue.value))\n      return true\n    if (props.minValue.value && isBefore(endOfYear(dateObj), props.minValue.value))\n      return true\n    return false\n  }\n\n  const isYearUnavailable = (date: DateValue) => {\n    if (resolveMatcher(props.isYearUnavailable)?.(date))\n      return true\n    return false\n  }\n\n  const isNextButtonDisabled = (nextPageFunc?: (date: DateValue) => DateValue) => {\n    if (!props.maxValue.value)\n      return false\n    if (props.disabled.value)\n      return true\n\n    const lastYearInView = grid.value.cells.at(-1)!\n    if (nextPageFunc || props.nextPage.value) {\n      const nextDate = (nextPageFunc || props.nextPage.value)!(lastYearInView)\n      return isAfter(startOfYear(nextDate), props.maxValue.value)\n    }\n\n    const nextPageStart = startOfYear(lastYearInView.add({ years: 1 }))\n    return isAfter(nextPageStart, props.maxValue.value)\n  }\n\n  const isPrevButtonDisabled = (prevPageFunc?: (date: DateValue) => DateValue) => {\n    if (!props.minValue.value)\n      return false\n    if (props.disabled.value)\n      return true\n\n    const firstYearInView = grid.value.value\n    if (prevPageFunc || props.prevPage.value) {\n      const prevDate = (prevPageFunc || props.prevPage.value)!(firstYearInView)\n      return isBefore(endOfYear(prevDate), props.minValue.value)\n    }\n\n    const prevPageEnd = endOfYear(firstYearInView.subtract({ years: 1 }))\n    return isBefore(prevPageEnd, props.minValue.value)\n  }\n\n  const nextPage = (nextPageFunc?: (date: DateValue) => DateValue) => {\n    const firstYearInGrid = grid.value.value\n\n    if (nextPageFunc || props.nextPage.value) {\n      const newDate = (nextPageFunc || props.nextPage.value)!(firstYearInGrid)\n      grid.value = createYearGrid({ dateObj: newDate, yearsPerPage: props.yearsPerPage.value, decadeAligned: false })\n      props.placeholder.value = newDate.set({ month: props.placeholder.value.month, day: props.placeholder.value.day })\n      return\n    }\n\n    const newDate = firstYearInGrid.add({ years: props.yearsPerPage.value })\n    grid.value = createYearGrid({ dateObj: newDate, yearsPerPage: props.yearsPerPage.value, decadeAligned: false })\n    props.placeholder.value = newDate.set({ month: props.placeholder.value.month, day: props.placeholder.value.day })\n  }\n\n  const prevPage = (prevPageFunc?: (date: DateValue) => DateValue) => {\n    const firstYearInGrid = grid.value.value\n\n    if (prevPageFunc || props.prevPage.value) {\n      const newDate = (prevPageFunc || props.prevPage.value)!(firstYearInGrid)\n      grid.value = createYearGrid({ dateObj: newDate, yearsPerPage: props.yearsPerPage.value, decadeAligned: false })\n      props.placeholder.value = newDate.set({ month: props.placeholder.value.month, day: props.placeholder.value.day })\n      return\n    }\n\n    const newDate = firstYearInGrid.subtract({ years: props.yearsPerPage.value })\n    grid.value = createYearGrid({ dateObj: newDate, yearsPerPage: props.yearsPerPage.value, decadeAligned: false })\n    props.placeholder.value = newDate.set({ month: props.placeholder.value.month, day: props.placeholder.value.day })\n  }\n\n  watch(props.placeholder, (value) => {\n    const firstYearInGrid = grid.value.value\n    const lastYearInGrid = grid.value.cells.at(-1)!\n    if (value.year >= firstYearInGrid.year && value.year <= lastYearInGrid.year)\n      return\n    grid.value = createYearGrid({ dateObj: value, yearsPerPage: props.yearsPerPage.value })\n  })\n\n  watch([props.locale, props.yearsPerPage], () => {\n    formatter.setLocale(props.locale.value)\n    grid.value = createYearGrid({ dateObj: props.placeholder.value, yearsPerPage: props.yearsPerPage.value })\n  })\n\n  const headingValue = computed(() => {\n    if (props.locale.value !== formatter.getLocale())\n      formatter.setLocale(props.locale.value)\n\n    const firstYear = grid.value.cells[0]\n    const lastYear = grid.value.cells.at(-1)!\n\n    return `${formatter.fullYear(toDate(firstYear), headingFormatOptions.value)} - ${formatter.fullYear(toDate(lastYear), headingFormatOptions.value)}`\n  })\n\n  const fullCalendarLabel = computed(() => `${props.calendarLabel.value ?? 'Year Picker'}, ${headingValue.value}`)\n\n  return {\n    isYearDisabled,\n    isYearUnavailable,\n    isNextButtonDisabled,\n    isPrevButtonDisabled,\n    grid,\n    formatter,\n    nextPage,\n    prevPage,\n    headingValue,\n    fullCalendarLabel,\n  }\n}\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { Direction } from '@/shared/types'\nimport { isSameYear } from '@/date'\nimport { createContext, useDirection, useId, useLocale } from '@/shared'\nimport { getDefaultDate, handleCalendarInitialFocus } from '@/shared/date'\nimport { useYearPicker, useYearPickerState } from './useYearPicker'\n\ntype YearPickerRootContext = {\n  locale: Ref<string>\n  modelValue: Ref<DateValue | DateValue[] | undefined>\n  placeholder: Ref<DateValue>\n  multiple: Ref<boolean>\n  preventDeselect: Ref<boolean>\n  grid: Ref<Grid<DateValue>>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  initialFocus: Ref<boolean>\n  onYearChange: (date: DateValue) => void\n  onPlaceholderChange: (date: DateValue) => void\n  fullCalendarLabel: Ref<string>\n  parentElement: Ref<HTMLElement | undefined>\n  headingValue: Ref<string>\n  headingId: string\n  isInvalid: Ref<boolean>\n  isYearDisabled: Matcher\n  isYearSelected: Matcher\n  isYearUnavailable?: Matcher\n  prevPage: (prevPageFunc?: (date: DateValue) => DateValue) => void\n  nextPage: (nextPageFunc?: (date: DateValue) => DateValue) => void\n  isNextButtonDisabled: (nextPageFunc?: (date: DateValue) => DateValue) => boolean\n  isPrevButtonDisabled: (prevPageFunc?: (date: DateValue) => DateValue) => boolean\n  formatter: Formatter\n  dir: Ref<Direction>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  yearsPerPage: Ref<number>\n}\n\nexport interface YearPickerRootProps extends PrimitiveProps {\n  /** The default value for the year picker */\n  defaultValue?: DateValue\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The placeholder date, which is used to determine what year range to display when no date is selected */\n  placeholder?: DateValue\n  /** Whether or not to prevent the user from deselecting a date without selecting another date first */\n  preventDeselect?: boolean\n  /** The accessible label for the year picker */\n  calendarLabel?: string\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether the year picker is disabled */\n  disabled?: boolean\n  /** Whether the year picker is readonly */\n  readonly?: boolean\n  /** If true, the year picker will focus the selected year, today, or the first year of the range on mount */\n  initialFocus?: boolean\n  /** A function that returns whether or not a year is disabled */\n  isYearDisabled?: Matcher\n  /** A function that returns whether or not a year is unavailable */\n  isYearUnavailable?: Matcher\n  /** The reading direction of the calendar when applicable. If omitted, inherits globally from `ConfigProvider` or assumes LTR. */\n  dir?: Direction\n  /** A function that returns the next page of the year picker. Receives the current placeholder as an argument. */\n  nextPage?: (placeholder: DateValue) => DateValue\n  /** A function that returns the previous page of the year picker. Receives the current placeholder as an argument. */\n  prevPage?: (placeholder: DateValue) => DateValue\n  /** The controlled selected year value of the year picker. Can be bound as `v-model`. */\n  modelValue?: DateValue | DateValue[] | null\n  /** Whether multiple years can be selected */\n  multiple?: boolean\n  /** Number of years to display per page */\n  yearsPerPage?: number\n}\n\nexport type YearPickerRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateValue | DateValue[] | undefined]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n}\n\nexport const [injectYearPickerRootContext, provideYearPickerRootContext]\n  = createContext<YearPickerRootContext>('YearPickerRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { onMounted, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearPickerRootProps>(), {\n  defaultValue: undefined,\n  as: 'div',\n  preventDeselect: false,\n  multiple: false,\n  disabled: false,\n  readonly: false,\n  initialFocus: false,\n  placeholder: undefined,\n  isYearDisabled: undefined,\n  isYearUnavailable: undefined,\n  yearsPerPage: 12,\n})\nconst emits = defineEmits<YearPickerRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the placeholder */\n    date: DateValue\n    /** The grid of years */\n    grid: Grid<DateValue>\n    /** The year picker locale */\n    locale: string\n    /** The current selected value */\n    modelValue: DateValue | DateValue[] | undefined\n  }) => any\n}>()\n\nconst {\n  disabled,\n  readonly,\n  initialFocus,\n  multiple,\n  minValue,\n  maxValue,\n  preventDeselect,\n  isYearDisabled: propsIsYearDisabled,\n  isYearUnavailable: propsIsYearUnavailable,\n  calendarLabel,\n  defaultValue,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n  dir: propDir,\n  locale: propLocale,\n  yearsPerPage,\n} = toRefs(props)\n\nconst { primitiveElement, currentElement: parentElement } = usePrimitiveElement()\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\nconst headingId = useId(undefined, 'reka-year-picker-heading')\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateValue | DateValue[] | undefined>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: modelValue.value,\n  locale: props.locale,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nfunction onPlaceholderChange(value: DateValue) {\n  placeholder.value = value.copy()\n}\n\nconst {\n  fullCalendarLabel,\n  headingValue,\n  isYearDisabled,\n  isYearUnavailable,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  nextPage,\n  prevPage,\n  formatter,\n  grid,\n} = useYearPicker({\n  locale,\n  placeholder,\n  minValue,\n  maxValue,\n  disabled,\n  yearsPerPage,\n  isYearDisabled: propsIsYearDisabled,\n  isYearUnavailable: propsIsYearUnavailable,\n  calendarLabel,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n})\n\nconst { isInvalid, isYearSelected } = useYearPickerState({\n  date: modelValue,\n  isYearDisabled,\n  isYearUnavailable,\n})\n\nwatch(modelValue, (_modelValue) => {\n  if (Array.isArray(_modelValue) && _modelValue.length) {\n    const lastValue = _modelValue.at(-1)\n    if (lastValue && !isSameYear(placeholder.value, lastValue))\n      onPlaceholderChange(lastValue)\n  }\n  else if (!Array.isArray(_modelValue) && _modelValue && !isSameYear(placeholder.value, _modelValue)) {\n    onPlaceholderChange(_modelValue)\n  }\n})\n\nfunction resolveYearValue(value: DateValue, reference?: DateValue) {\n  if (!reference)\n    return value.copy()\n  return value.copy().set({ month: reference.month, day: reference.day })\n}\n\nfunction onYearChange(value: DateValue) {\n  if (!multiple.value) {\n    if (!modelValue.value) {\n      modelValue.value = resolveYearValue(value, placeholder.value)\n      return\n    }\n\n    if (!preventDeselect.value && isSameYear(modelValue.value as DateValue, value)) {\n      placeholder.value = resolveYearValue(value, modelValue.value as DateValue)\n      modelValue.value = undefined\n    }\n    else {\n      modelValue.value = resolveYearValue(value, modelValue.value as DateValue)\n    }\n  }\n  else if (!modelValue.value) {\n    modelValue.value = [resolveYearValue(value, placeholder.value)]\n  }\n  else if (Array.isArray(modelValue.value)) {\n    const index = modelValue.value.findIndex(date => isSameYear(date, value))\n    if (index === -1) {\n      modelValue.value = [...modelValue.value, resolveYearValue(value, placeholder.value)]\n    }\n    else if (!preventDeselect.value) {\n      const next = modelValue.value.filter(date => !isSameYear(date, value))\n      if (!next.length) {\n        placeholder.value = resolveYearValue(value, modelValue.value[index])\n        modelValue.value = undefined\n        return\n      }\n      modelValue.value = next.map(date => date.copy())\n    }\n  }\n}\n\nonMounted(() => {\n  if (initialFocus.value)\n    handleCalendarInitialFocus(parentElement.value)\n})\n\nprovideYearPickerRootContext({\n  isYearUnavailable,\n  dir,\n  isYearDisabled,\n  locale,\n  formatter,\n  modelValue,\n  placeholder,\n  disabled,\n  initialFocus,\n  grid,\n  multiple,\n  readonly,\n  preventDeselect,\n  fullCalendarLabel,\n  headingValue,\n  headingId,\n  isInvalid,\n  isYearSelected,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  nextPage,\n  prevPage,\n  parentElement,\n  onPlaceholderChange,\n  onYearChange,\n  minValue,\n  maxValue,\n  yearsPerPage,\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"fullCalendarLabel\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n  >\n    <slot\n      :date=\"placeholder\"\n      :grid=\"grid\"\n      :locale=\"locale\"\n      :model-value=\"modelValue\"\n    />\n    <div\n      style=\"border: 0px; clip: rect(0px, 0px, 0px, 0px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; white-space: nowrap; width: 1px;\"\n    >\n      <div\n        role=\"heading\"\n        aria-level=\"2\"\n      >\n        {{ fullCalendarLabel }}\n      </div>\n    </div>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { Direction } from '@/shared/types'\nimport { isSameYear } from '@/date'\nimport { createContext, useDirection, useId, useLocale } from '@/shared'\nimport { getDefaultDate, handleCalendarInitialFocus } from '@/shared/date'\nimport { useYearPicker, useYearPickerState } from './useYearPicker'\n\ntype YearPickerRootContext = {\n  locale: Ref<string>\n  modelValue: Ref<DateValue | DateValue[] | undefined>\n  placeholder: Ref<DateValue>\n  multiple: Ref<boolean>\n  preventDeselect: Ref<boolean>\n  grid: Ref<Grid<DateValue>>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  initialFocus: Ref<boolean>\n  onYearChange: (date: DateValue) => void\n  onPlaceholderChange: (date: DateValue) => void\n  fullCalendarLabel: Ref<string>\n  parentElement: Ref<HTMLElement | undefined>\n  headingValue: Ref<string>\n  headingId: string\n  isInvalid: Ref<boolean>\n  isYearDisabled: Matcher\n  isYearSelected: Matcher\n  isYearUnavailable?: Matcher\n  prevPage: (prevPageFunc?: (date: DateValue) => DateValue) => void\n  nextPage: (nextPageFunc?: (date: DateValue) => DateValue) => void\n  isNextButtonDisabled: (nextPageFunc?: (date: DateValue) => DateValue) => boolean\n  isPrevButtonDisabled: (prevPageFunc?: (date: DateValue) => DateValue) => boolean\n  formatter: Formatter\n  dir: Ref<Direction>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  yearsPerPage: Ref<number>\n}\n\nexport interface YearPickerRootProps extends PrimitiveProps {\n  /** The default value for the year picker */\n  defaultValue?: DateValue\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The placeholder date, which is used to determine what year range to display when no date is selected */\n  placeholder?: DateValue\n  /** Whether or not to prevent the user from deselecting a date without selecting another date first */\n  preventDeselect?: boolean\n  /** The accessible label for the year picker */\n  calendarLabel?: string\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether the year picker is disabled */\n  disabled?: boolean\n  /** Whether the year picker is readonly */\n  readonly?: boolean\n  /** If true, the year picker will focus the selected year, today, or the first year of the range on mount */\n  initialFocus?: boolean\n  /** A function that returns whether or not a year is disabled */\n  isYearDisabled?: Matcher\n  /** A function that returns whether or not a year is unavailable */\n  isYearUnavailable?: Matcher\n  /** The reading direction of the calendar when applicable. If omitted, inherits globally from `ConfigProvider` or assumes LTR. */\n  dir?: Direction\n  /** A function that returns the next page of the year picker. Receives the current placeholder as an argument. */\n  nextPage?: (placeholder: DateValue) => DateValue\n  /** A function that returns the previous page of the year picker. Receives the current placeholder as an argument. */\n  prevPage?: (placeholder: DateValue) => DateValue\n  /** The controlled selected year value of the year picker. Can be bound as `v-model`. */\n  modelValue?: DateValue | DateValue[] | null\n  /** Whether multiple years can be selected */\n  multiple?: boolean\n  /** Number of years to display per page */\n  yearsPerPage?: number\n}\n\nexport type YearPickerRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateValue | DateValue[] | undefined]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n}\n\nexport const [injectYearPickerRootContext, provideYearPickerRootContext]\n  = createContext<YearPickerRootContext>('YearPickerRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useVModel } from '@vueuse/core'\nimport { onMounted, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearPickerRootProps>(), {\n  defaultValue: undefined,\n  as: 'div',\n  preventDeselect: false,\n  multiple: false,\n  disabled: false,\n  readonly: false,\n  initialFocus: false,\n  placeholder: undefined,\n  isYearDisabled: undefined,\n  isYearUnavailable: undefined,\n  yearsPerPage: 12,\n})\nconst emits = defineEmits<YearPickerRootEmits>()\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the placeholder */\n    date: DateValue\n    /** The grid of years */\n    grid: Grid<DateValue>\n    /** The year picker locale */\n    locale: string\n    /** The current selected value */\n    modelValue: DateValue | DateValue[] | undefined\n  }) => any\n}>()\n\nconst {\n  disabled,\n  readonly,\n  initialFocus,\n  multiple,\n  minValue,\n  maxValue,\n  preventDeselect,\n  isYearDisabled: propsIsYearDisabled,\n  isYearUnavailable: propsIsYearUnavailable,\n  calendarLabel,\n  defaultValue,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n  dir: propDir,\n  locale: propLocale,\n  yearsPerPage,\n} = toRefs(props)\n\nconst { primitiveElement, currentElement: parentElement } = usePrimitiveElement()\nconst locale = useLocale(propLocale)\nconst dir = useDirection(propDir)\nconst headingId = useId(undefined, 'reka-year-picker-heading')\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: defaultValue.value,\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateValue | DateValue[] | undefined>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: modelValue.value,\n  locale: props.locale,\n})\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nfunction onPlaceholderChange(value: DateValue) {\n  placeholder.value = value.copy()\n}\n\nconst {\n  fullCalendarLabel,\n  headingValue,\n  isYearDisabled,\n  isYearUnavailable,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  nextPage,\n  prevPage,\n  formatter,\n  grid,\n} = useYearPicker({\n  locale,\n  placeholder,\n  minValue,\n  maxValue,\n  disabled,\n  yearsPerPage,\n  isYearDisabled: propsIsYearDisabled,\n  isYearUnavailable: propsIsYearUnavailable,\n  calendarLabel,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n})\n\nconst { isInvalid, isYearSelected } = useYearPickerState({\n  date: modelValue,\n  isYearDisabled,\n  isYearUnavailable,\n})\n\nwatch(modelValue, (_modelValue) => {\n  if (Array.isArray(_modelValue) && _modelValue.length) {\n    const lastValue = _modelValue.at(-1)\n    if (lastValue && !isSameYear(placeholder.value, lastValue))\n      onPlaceholderChange(lastValue)\n  }\n  else if (!Array.isArray(_modelValue) && _modelValue && !isSameYear(placeholder.value, _modelValue)) {\n    onPlaceholderChange(_modelValue)\n  }\n})\n\nfunction resolveYearValue(value: DateValue, reference?: DateValue) {\n  if (!reference)\n    return value.copy()\n  return value.copy().set({ month: reference.month, day: reference.day })\n}\n\nfunction onYearChange(value: DateValue) {\n  if (!multiple.value) {\n    if (!modelValue.value) {\n      modelValue.value = resolveYearValue(value, placeholder.value)\n      return\n    }\n\n    if (!preventDeselect.value && isSameYear(modelValue.value as DateValue, value)) {\n      placeholder.value = resolveYearValue(value, modelValue.value as DateValue)\n      modelValue.value = undefined\n    }\n    else {\n      modelValue.value = resolveYearValue(value, modelValue.value as DateValue)\n    }\n  }\n  else if (!modelValue.value) {\n    modelValue.value = [resolveYearValue(value, placeholder.value)]\n  }\n  else if (Array.isArray(modelValue.value)) {\n    const index = modelValue.value.findIndex(date => isSameYear(date, value))\n    if (index === -1) {\n      modelValue.value = [...modelValue.value, resolveYearValue(value, placeholder.value)]\n    }\n    else if (!preventDeselect.value) {\n      const next = modelValue.value.filter(date => !isSameYear(date, value))\n      if (!next.length) {\n        placeholder.value = resolveYearValue(value, modelValue.value[index])\n        modelValue.value = undefined\n        return\n      }\n      modelValue.value = next.map(date => date.copy())\n    }\n  }\n}\n\nonMounted(() => {\n  if (initialFocus.value)\n    handleCalendarInitialFocus(parentElement.value)\n})\n\nprovideYearPickerRootContext({\n  isYearUnavailable,\n  dir,\n  isYearDisabled,\n  locale,\n  formatter,\n  modelValue,\n  placeholder,\n  disabled,\n  initialFocus,\n  grid,\n  multiple,\n  readonly,\n  preventDeselect,\n  fullCalendarLabel,\n  headingValue,\n  headingId,\n  isInvalid,\n  isYearSelected,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  nextPage,\n  prevPage,\n  parentElement,\n  onPlaceholderChange,\n  onYearChange,\n  minValue,\n  maxValue,\n  yearsPerPage,\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"fullCalendarLabel\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n  >\n    <slot\n      :date=\"placeholder\"\n      :grid=\"grid\"\n      :locale=\"locale\"\n      :model-value=\"modelValue\"\n    />\n    <div\n      style=\"border: 0px; clip: rect(0px, 0px, 0px, 0px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; white-space: nowrap; width: 1px;\"\n    >\n      <div\n        role=\"heading\"\n        aria-level=\"2\"\n      >\n        {{ fullCalendarLabel }}\n      </div>\n    </div>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerCellProps extends PrimitiveProps {\n  /** The date value for the cell */\n  date: DateValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectYearPickerRootContext } from './YearPickerRoot.vue'\n\nwithDefaults(defineProps<YearPickerCellProps>(), { as: 'td' })\nconst rootContext = injectYearPickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"gridcell\"\n    :aria-selected=\"rootContext.isYearSelected(date) ? true : undefined\"\n    :aria-disabled=\"rootContext.isYearDisabled(date) || rootContext.isYearUnavailable?.(date)\"\n    :data-disabled=\"rootContext.isYearDisabled(date) ? '' : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerCellProps extends PrimitiveProps {\n  /** The date value for the cell */\n  date: DateValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectYearPickerRootContext } from './YearPickerRoot.vue'\n\nwithDefaults(defineProps<YearPickerCellProps>(), { as: 'td' })\nconst rootContext = injectYearPickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"gridcell\"\n    :aria-selected=\"rootContext.isYearSelected(date) ? true : undefined\"\n    :aria-disabled=\"rootContext.isYearDisabled(date) || rootContext.isYearUnavailable?.(date)\"\n    :data-disabled=\"rootContext.isYearDisabled(date) ? '' : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { endOfYear, getLocalTimeZone, startOfYear, toCalendar, today } from '@internationalized/date'\nimport { computed, nextTick } from 'vue'\nimport { isSameYear, toDate } from '@/date'\nimport { useKbd } from '@/shared'\n\nexport interface YearPickerCellTriggerProps extends PrimitiveProps {\n  /** The date value provided to the cell trigger */\n  year: DateValue\n}\n\nexport interface YearPickerCellTriggerSlot {\n  default?: (props: {\n    /** Current year value */\n    yearValue: string\n    /** Current disable state */\n    disabled: boolean\n    /** Current selected state */\n    selected: boolean\n    /** Current year is today state */\n    today: boolean\n    /** Current unavailable state */\n    unavailable: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectYearPickerRootContext } from './YearPickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearPickerCellTriggerProps>(), { as: 'div' })\n\ndefineSlots<YearPickerCellTriggerSlot>()\n\nconst kbd = useKbd()\nconst rootContext = injectYearPickerRootContext()\n\nconst { primitiveElement } = usePrimitiveElement()\n\nconst yearValue = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.fullYear(toDate(props.year))\n})\n\nconst labelText = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.custom(toDate(props.year), {\n    year: 'numeric',\n  })\n})\n\nconst isUnavailable = computed(() => rootContext.isYearUnavailable?.(props.year) ?? false)\n\nconst isCurrentYear = computed(() => {\n  const todayDate = toCalendar(today(getLocalTimeZone()), props.year.calendar)\n  return isSameYear(props.year, todayDate)\n})\n\nconst isDisabled = computed(() => rootContext.isYearDisabled(props.year))\n\nconst isFocusedYear = computed(() => {\n  return !rootContext.disabled.value && isSameYear(props.year, rootContext.placeholder.value)\n})\n\nconst isSelectedYear = computed(() => rootContext.isYearSelected(props.year))\n\nfunction changeYear(date: DateValue) {\n  if (rootContext.readonly.value)\n    return\n  if (rootContext.isYearDisabled(date) || rootContext.isYearUnavailable?.(date))\n    return\n\n  rootContext.onYearChange(date)\n}\n\nfunction handleClick() {\n  if (isDisabled.value)\n    return\n  changeYear(props.year)\n}\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  if (isDisabled.value)\n    return\n  e.preventDefault()\n  e.stopPropagation()\n  const parentElement = rootContext.parentElement.value!\n  const sign = rootContext.dir.value === 'rtl' ? -1 : 1\n\n  switch (e.code) {\n    case kbd.ARROW_RIGHT:\n      shiftFocus(props.year, sign)\n      break\n    case kbd.ARROW_LEFT:\n      shiftFocus(props.year, -sign)\n      break\n    case kbd.ARROW_UP:\n      shiftFocus(props.year, -4)\n      break\n    case kbd.ARROW_DOWN:\n      shiftFocus(props.year, 4)\n      break\n    case kbd.PAGE_UP:\n      shiftFocusPage(-1)\n      break\n    case kbd.PAGE_DOWN:\n      shiftFocusPage(1)\n      break\n    case kbd.ENTER:\n    case kbd.SPACE_CODE:\n      changeYear(props.year)\n  }\n\n  function shiftFocus(currentYear: DateValue, add: number, depth = 0) {\n    if (depth > 48)\n      return\n    const candidateYearValue = currentYear.add({ years: add })\n\n    if ((rootContext.minValue.value && endOfYear(candidateYearValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && startOfYear(candidateYearValue).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    const candidateYear = parentElement.querySelector<HTMLElement>(`[data-value='${candidateYearValue.toString()}']`)\n\n    if (!candidateYear) {\n      if (add > 0) {\n        if (rootContext.isNextButtonDisabled())\n          return\n        rootContext.nextPage()\n      }\n      else {\n        if (rootContext.isPrevButtonDisabled())\n          return\n        rootContext.prevPage()\n      }\n      nextTick(() => {\n        shiftFocus(currentYear, add, depth + 1)\n      })\n      return\n    }\n\n    if (candidateYear && candidateYear.hasAttribute('data-disabled'))\n      return shiftFocus(candidateYearValue, add, depth + 1)\n\n    rootContext.onPlaceholderChange(candidateYearValue)\n    candidateYear?.focus()\n  }\n\n  function shiftFocusPage(direction: number) {\n    const yearsPerPage = rootContext.yearsPerPage.value\n    const candidateYearValue = props.year.add({ years: direction * yearsPerPage })\n\n    if ((rootContext.minValue.value && endOfYear(candidateYearValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && startOfYear(candidateYearValue).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    if (direction > 0) {\n      if (rootContext.isNextButtonDisabled())\n        return\n      rootContext.nextPage()\n    }\n    else {\n      if (rootContext.isPrevButtonDisabled())\n        return\n      rootContext.prevPage()\n    }\n\n    nextTick(() => {\n      const candidateYear = parentElement.querySelector<HTMLElement>(`[data-value='${candidateYearValue.toString()}']`)\n      if (candidateYear && !candidateYear.hasAttribute('data-disabled')) {\n        rootContext.onPlaceholderChange(candidateYearValue)\n        candidateYear?.focus()\n        return\n      }\n\n      if (!candidateYear || candidateYear.hasAttribute('data-disabled'))\n        shiftFocus(candidateYearValue, direction > 0 ? 1 : -1, 1)\n    })\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    role=\"button\"\n    :aria-label=\"labelText\"\n    data-reka-year-picker-cell-trigger\n    :aria-disabled=\"isDisabled || isUnavailable ? true : undefined\"\n    :data-selected=\"isSelectedYear ? '' : undefined\"\n    :data-value=\"year.toString()\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-unavailable=\"isUnavailable ? '' : undefined\"\n    :data-today=\"isCurrentYear ? '' : undefined\"\n    :data-focused=\"isFocusedYear ? '' : undefined\"\n    :tabindex=\"isFocusedYear ? 0 : isDisabled ? undefined : -1\"\n    @click=\"handleClick\"\n    @keydown.up.down.left.right.space.enter.page-up.page-down=\"handleArrowKey\"\n    @keydown.enter.prevent\n  >\n    <slot\n      :year-value=\"yearValue\"\n      :disabled=\"isDisabled\"\n      :today=\"isCurrentYear\"\n      :selected=\"isSelectedYear\"\n      :unavailable=\"isUnavailable\"\n    >\n      {{ yearValue }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { endOfYear, getLocalTimeZone, startOfYear, toCalendar, today } from '@internationalized/date'\nimport { computed, nextTick } from 'vue'\nimport { isSameYear, toDate } from '@/date'\nimport { useKbd } from '@/shared'\n\nexport interface YearPickerCellTriggerProps extends PrimitiveProps {\n  /** The date value provided to the cell trigger */\n  year: DateValue\n}\n\nexport interface YearPickerCellTriggerSlot {\n  default?: (props: {\n    /** Current year value */\n    yearValue: string\n    /** Current disable state */\n    disabled: boolean\n    /** Current selected state */\n    selected: boolean\n    /** Current year is today state */\n    today: boolean\n    /** Current unavailable state */\n    unavailable: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectYearPickerRootContext } from './YearPickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearPickerCellTriggerProps>(), { as: 'div' })\n\ndefineSlots<YearPickerCellTriggerSlot>()\n\nconst kbd = useKbd()\nconst rootContext = injectYearPickerRootContext()\n\nconst { primitiveElement } = usePrimitiveElement()\n\nconst yearValue = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.fullYear(toDate(props.year))\n})\n\nconst labelText = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.custom(toDate(props.year), {\n    year: 'numeric',\n  })\n})\n\nconst isUnavailable = computed(() => rootContext.isYearUnavailable?.(props.year) ?? false)\n\nconst isCurrentYear = computed(() => {\n  const todayDate = toCalendar(today(getLocalTimeZone()), props.year.calendar)\n  return isSameYear(props.year, todayDate)\n})\n\nconst isDisabled = computed(() => rootContext.isYearDisabled(props.year))\n\nconst isFocusedYear = computed(() => {\n  return !rootContext.disabled.value && isSameYear(props.year, rootContext.placeholder.value)\n})\n\nconst isSelectedYear = computed(() => rootContext.isYearSelected(props.year))\n\nfunction changeYear(date: DateValue) {\n  if (rootContext.readonly.value)\n    return\n  if (rootContext.isYearDisabled(date) || rootContext.isYearUnavailable?.(date))\n    return\n\n  rootContext.onYearChange(date)\n}\n\nfunction handleClick() {\n  if (isDisabled.value)\n    return\n  changeYear(props.year)\n}\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  if (isDisabled.value)\n    return\n  e.preventDefault()\n  e.stopPropagation()\n  const parentElement = rootContext.parentElement.value!\n  const sign = rootContext.dir.value === 'rtl' ? -1 : 1\n\n  switch (e.code) {\n    case kbd.ARROW_RIGHT:\n      shiftFocus(props.year, sign)\n      break\n    case kbd.ARROW_LEFT:\n      shiftFocus(props.year, -sign)\n      break\n    case kbd.ARROW_UP:\n      shiftFocus(props.year, -4)\n      break\n    case kbd.ARROW_DOWN:\n      shiftFocus(props.year, 4)\n      break\n    case kbd.PAGE_UP:\n      shiftFocusPage(-1)\n      break\n    case kbd.PAGE_DOWN:\n      shiftFocusPage(1)\n      break\n    case kbd.ENTER:\n    case kbd.SPACE_CODE:\n      changeYear(props.year)\n  }\n\n  function shiftFocus(currentYear: DateValue, add: number, depth = 0) {\n    if (depth > 48)\n      return\n    const candidateYearValue = currentYear.add({ years: add })\n\n    if ((rootContext.minValue.value && endOfYear(candidateYearValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && startOfYear(candidateYearValue).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    const candidateYear = parentElement.querySelector<HTMLElement>(`[data-value='${candidateYearValue.toString()}']`)\n\n    if (!candidateYear) {\n      if (add > 0) {\n        if (rootContext.isNextButtonDisabled())\n          return\n        rootContext.nextPage()\n      }\n      else {\n        if (rootContext.isPrevButtonDisabled())\n          return\n        rootContext.prevPage()\n      }\n      nextTick(() => {\n        shiftFocus(currentYear, add, depth + 1)\n      })\n      return\n    }\n\n    if (candidateYear && candidateYear.hasAttribute('data-disabled'))\n      return shiftFocus(candidateYearValue, add, depth + 1)\n\n    rootContext.onPlaceholderChange(candidateYearValue)\n    candidateYear?.focus()\n  }\n\n  function shiftFocusPage(direction: number) {\n    const yearsPerPage = rootContext.yearsPerPage.value\n    const candidateYearValue = props.year.add({ years: direction * yearsPerPage })\n\n    if ((rootContext.minValue.value && endOfYear(candidateYearValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && startOfYear(candidateYearValue).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    if (direction > 0) {\n      if (rootContext.isNextButtonDisabled())\n        return\n      rootContext.nextPage()\n    }\n    else {\n      if (rootContext.isPrevButtonDisabled())\n        return\n      rootContext.prevPage()\n    }\n\n    nextTick(() => {\n      const candidateYear = parentElement.querySelector<HTMLElement>(`[data-value='${candidateYearValue.toString()}']`)\n      if (candidateYear && !candidateYear.hasAttribute('data-disabled')) {\n        rootContext.onPlaceholderChange(candidateYearValue)\n        candidateYear?.focus()\n        return\n      }\n\n      if (!candidateYear || candidateYear.hasAttribute('data-disabled'))\n        shiftFocus(candidateYearValue, direction > 0 ? 1 : -1, 1)\n    })\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    role=\"button\"\n    :aria-label=\"labelText\"\n    data-reka-year-picker-cell-trigger\n    :aria-disabled=\"isDisabled || isUnavailable ? true : undefined\"\n    :data-selected=\"isSelectedYear ? '' : undefined\"\n    :data-value=\"year.toString()\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-unavailable=\"isUnavailable ? '' : undefined\"\n    :data-today=\"isCurrentYear ? '' : undefined\"\n    :data-focused=\"isFocusedYear ? '' : undefined\"\n    :tabindex=\"isFocusedYear ? 0 : isDisabled ? undefined : -1\"\n    @click=\"handleClick\"\n    @keydown.up.down.left.right.space.enter.page-up.page-down=\"handleArrowKey\"\n    @keydown.enter.prevent\n  >\n    <slot\n      :year-value=\"yearValue\"\n      :disabled=\"isDisabled\"\n      :today=\"isCurrentYear\"\n      :selected=\"isSelectedYear\"\n      :unavailable=\"isUnavailable\"\n    >\n      {{ yearValue }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerGridProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectYearPickerRootContext } from './YearPickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearPickerGridProps>(), { as: 'table' })\n\nconst rootContext = injectYearPickerRootContext()\nconst disabled = computed(() => rootContext.disabled.value ? true : undefined)\nconst readonly = computed(() => rootContext.readonly.value ? true : undefined)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    role=\"application\"\n    :aria-labelledby=\"rootContext.headingId\"\n    :aria-readonly=\"readonly\"\n    :aria-disabled=\"disabled\"\n    :data-readonly=\"readonly && ''\"\n    :data-disabled=\"disabled && ''\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerGridProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectYearPickerRootContext } from './YearPickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearPickerGridProps>(), { as: 'table' })\n\nconst rootContext = injectYearPickerRootContext()\nconst disabled = computed(() => rootContext.disabled.value ? true : undefined)\nconst readonly = computed(() => rootContext.readonly.value ? true : undefined)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    role=\"application\"\n    :aria-labelledby=\"rootContext.headingId\"\n    :aria-readonly=\"readonly\"\n    :aria-disabled=\"disabled\"\n    :data-readonly=\"readonly && ''\"\n    :data-disabled=\"disabled && ''\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerGridBodyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearPickerGridBodyProps>(), { as: 'tbody' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerGridBodyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearPickerGridBodyProps>(), { as: 'tbody' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerGridRowProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearPickerGridRowProps>(), { as: 'tr' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    role=\"row\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerGridRowProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearPickerGridRowProps>(), { as: 'tr' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    role=\"row\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearPickerHeaderProps>(), { as: 'div' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearPickerHeaderProps>(), { as: 'div' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerHeadingProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectYearPickerRootContext } from './YearPickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearPickerHeadingProps>(), { as: 'div' })\n\ndefineSlots<{\n  default?: (props: {\n    /** Current year range heading */\n    headingValue: string\n  }) => any\n}>()\n\nconst rootContext = injectYearPickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.headingId\"\n    role=\"heading\"\n    aria-level=\"2\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n  >\n    <slot :heading-value=\"rootContext.headingValue.value\">\n      {{ rootContext.headingValue.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerHeadingProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectYearPickerRootContext } from './YearPickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearPickerHeadingProps>(), { as: 'div' })\n\ndefineSlots<{\n  default?: (props: {\n    /** Current year range heading */\n    headingValue: string\n  }) => any\n}>()\n\nconst rootContext = injectYearPickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.headingId\"\n    role=\"heading\"\n    aria-level=\"2\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n  >\n    <slot :heading-value=\"rootContext.headingValue.value\">\n      {{ rootContext.headingValue.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerNextProps extends PrimitiveProps {\n  /** The function to be used for the next page. Overwrites the `nextPage` function set on the `YearPickerRoot`. */\n  nextPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface YearPickerNextSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectYearPickerRootContext } from './YearPickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearPickerNextProps>(), { as: 'button' })\ndefineSlots<YearPickerNextSlot>()\n\nconst rootContext = injectYearPickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isNextButtonDisabled(props.nextPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.nextPage(props.nextPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Next page\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Next page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerNextProps extends PrimitiveProps {\n  /** The function to be used for the next page. Overwrites the `nextPage` function set on the `YearPickerRoot`. */\n  nextPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface YearPickerNextSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectYearPickerRootContext } from './YearPickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearPickerNextProps>(), { as: 'button' })\ndefineSlots<YearPickerNextSlot>()\n\nconst rootContext = injectYearPickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isNextButtonDisabled(props.nextPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.nextPage(props.nextPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Next page\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Next page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerPrevProps extends PrimitiveProps {\n  /** The function to be used for the prev page. Overwrites the `prevPage` function set on the `YearPickerRoot`. */\n  prevPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface YearPickerPrevSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectYearPickerRootContext } from './YearPickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearPickerPrevProps>(), { as: 'button' })\ndefineSlots<YearPickerPrevSlot>()\n\nconst rootContext = injectYearPickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isPrevButtonDisabled(props.prevPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.prevPage(props.prevPage)\n}\n</script>\n\n<template>\n  <Primitive\n    aria-label=\"Previous page\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Prev page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearPickerPrevProps extends PrimitiveProps {\n  /** The function to be used for the prev page. Overwrites the `prevPage` function set on the `YearPickerRoot`. */\n  prevPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface YearPickerPrevSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectYearPickerRootContext } from './YearPickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearPickerPrevProps>(), { as: 'button' })\ndefineSlots<YearPickerPrevSlot>()\n\nconst rootContext = injectYearPickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isPrevButtonDisabled(props.prevPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.prevPage(props.prevPage)\n}\n</script>\n\n<template>\n  <Primitive\n    aria-label=\"Previous page\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Prev page\n    </slot>\n  </Primitive>\n</template>\n","import type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Matcher } from '@/date'\nimport { computed } from 'vue'\nimport { areAllYearsBetweenValid, getYearsBetween, isSameYear } from '@/date'\n\nexport type UseRangeYearPickerProps = {\n  start: Ref<DateValue | undefined>\n  end: Ref<DateValue | undefined>\n  isYearDisabled: Matcher\n  isYearUnavailable: Matcher\n  focusedValue: Ref<DateValue | undefined>\n  allowNonContiguousRanges: Ref<boolean>\n  fixedDate: Ref<'start' | 'end' | undefined>\n  maximumYears?: Ref<number | undefined>\n}\n\nexport function useRangeYearPickerState(props: UseRangeYearPickerProps) {\n  const isStartInvalid = computed(() => {\n    if (!props.start.value)\n      return false\n    if (props.isYearDisabled(props.start.value))\n      return true\n    return false\n  })\n\n  const isEndInvalid = computed(() => {\n    if (!props.end.value)\n      return false\n    if (props.isYearDisabled(props.end.value))\n      return true\n    return false\n  })\n\n  const isInvalid = computed(() => {\n    if (isStartInvalid.value || isEndInvalid.value)\n      return true\n    if (props.start.value && props.end.value && props.end.value.year < props.start.value.year)\n      return true\n    return false\n  })\n\n  const isSelectionStart = (date: DateValue) => {\n    if (!props.start.value)\n      return false\n    return isSameYear(props.start.value, date)\n  }\n\n  const isSelectionEnd = (date: DateValue) => {\n    if (!props.end.value)\n      return false\n    return isSameYear(props.end.value, date)\n  }\n\n  const isSelected = (date: DateValue) => {\n    if (props.start.value && isSameYear(props.start.value, date))\n      return true\n    if (props.end.value && isSameYear(props.end.value, date))\n      return true\n    if (props.end.value && props.start.value) {\n      return date.year > props.start.value.year && date.year < props.end.value.year\n    }\n    return false\n  }\n\n  const rangeIsYearDisabled = (date: DateValue) => {\n    if (props.isYearDisabled(date))\n      return true\n\n    if (props.maximumYears?.value) {\n      const maximumYears = props.maximumYears.value\n\n      if (props.start.value && props.end.value) {\n        if (props.fixedDate.value) {\n          const diff = getYearsBetween(props.start.value, props.end.value)\n          if (diff <= maximumYears) {\n            const yearsLeft = maximumYears - diff\n            const startLimit = props.start.value.subtract({ years: yearsLeft })\n            const endLimit = props.end.value.add({ years: yearsLeft })\n            return date.year < startLimit.year || date.year > endLimit.year\n          }\n\n          const fixedValue = props.fixedDate.value === 'start' ? props.start.value : props.end.value\n          const maxDate = fixedValue.add({ years: maximumYears - 1 })\n          const minDate = fixedValue.subtract({ years: maximumYears - 1 })\n          return date.year < minDate.year || date.year > maxDate.year\n        }\n        return false\n      }\n      if (props.start.value) {\n        const maxDate = props.start.value.add({ years: maximumYears - 1 })\n        const minDate = props.start.value.subtract({ years: maximumYears - 1 })\n        return date.year < minDate.year || date.year > maxDate.year\n      }\n    }\n\n    return false\n  }\n\n  const highlightedRange = computed(() => {\n    if (props.start.value && props.end.value && !props.fixedDate.value)\n      return null\n    if (!props.start.value || !props.focusedValue.value)\n      return null\n\n    const isStartBeforeFocused = props.start.value.year < props.focusedValue.value.year\n    const start = isStartBeforeFocused ? props.start.value : props.focusedValue.value\n    const end = isStartBeforeFocused ? props.focusedValue.value : props.start.value\n\n    if (isSameYear(start, end)) {\n      return { start, end }\n    }\n\n    if (props.maximumYears?.value && !props.end.value) {\n      const maximumYears = props.maximumYears.value\n      const anchor = props.start.value\n      const focused = props.focusedValue.value\n\n      if (focused.year >= anchor.year) {\n        const maxEnd = anchor.add({ years: maximumYears - 1 })\n        const cappedEnd = focused.year > maxEnd.year ? maxEnd : focused\n        return { start: anchor, end: cappedEnd }\n      }\n      else {\n        const minStart = anchor.subtract({ years: maximumYears - 1 })\n        const cappedStart = focused.year < minStart.year ? minStart : focused\n        return { start: cappedStart, end: anchor }\n      }\n    }\n\n    const isValid = areAllYearsBetweenValid(\n      start,\n      end,\n      props.allowNonContiguousRanges.value ? () => false : props.isYearUnavailable,\n      rangeIsYearDisabled,\n    )\n    if (isValid)\n      return { start, end }\n\n    return null\n  })\n\n  const isHighlightedStart = (date: DateValue) => {\n    if (!highlightedRange.value?.start)\n      return false\n    return isSameYear(highlightedRange.value.start, date)\n  }\n\n  const isHighlightedEnd = (date: DateValue) => {\n    if (!highlightedRange.value?.end)\n      return false\n    return isSameYear(highlightedRange.value.end, date)\n  }\n\n  return {\n    isInvalid,\n    isSelected,\n    highlightedRange,\n    isSelectionStart,\n    isSelectionEnd,\n    isHighlightedStart,\n    isHighlightedEnd,\n    isYearDisabled: rangeIsYearDisabled,\n  }\n}\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { DateRange } from '@/shared/date'\nimport type { Direction } from '@/shared/types'\nimport { isSameYear } from '@/date'\nimport { createContext, useDirection, useId, useKbd, useLocale } from '@/shared'\nimport { getDefaultDate, handleCalendarInitialFocus } from '@/shared/date'\nimport { useYearPicker } from '@/YearPicker/useYearPicker'\nimport { useRangeYearPickerState } from './useRangeYearPicker'\n\ntype YearRangePickerRootContext = {\n  modelValue: Ref<DateRange>\n  startValue: Ref<DateValue | undefined>\n  endValue: Ref<DateValue | undefined>\n  locale: Ref<string>\n  placeholder: Ref<DateValue>\n  preventDeselect: Ref<boolean>\n  grid: Ref<Grid<DateValue>>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  initialFocus: Ref<boolean>\n  onPlaceholderChange: (date: DateValue) => void\n  fullCalendarLabel: Ref<string>\n  parentElement: Ref<HTMLElement | undefined>\n  headingValue: Ref<string>\n  headingId: string\n  isInvalid: Ref<boolean>\n  isYearDisabled: Matcher\n  isYearUnavailable?: Matcher\n  allowNonContiguousRanges: Ref<boolean>\n  highlightedRange: Ref<{ start: DateValue, end: DateValue } | null>\n  focusedValue: Ref<DateValue | undefined>\n  lastPressedDateValue: Ref<DateValue | undefined>\n  isSelected: (date: DateValue) => boolean\n  isSelectionEnd: (date: DateValue) => boolean\n  isSelectionStart: (date: DateValue) => boolean\n  isHighlightedStart: (date: DateValue) => boolean\n  isHighlightedEnd: (date: DateValue) => boolean\n  prevPage: (prevPageFunc?: (date: DateValue) => DateValue) => void\n  nextPage: (nextPageFunc?: (date: DateValue) => DateValue) => void\n  isNextButtonDisabled: (nextPageFunc?: (date: DateValue) => DateValue) => boolean\n  isPrevButtonDisabled: (prevPageFunc?: (date: DateValue) => DateValue) => boolean\n  formatter: Formatter\n  dir: Ref<Direction>\n  fixedDate: Ref<'start' | 'end' | undefined>\n  maximumYears: Ref<number | undefined>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  yearsPerPage: Ref<number>\n}\n\nexport interface YearRangePickerRootProps extends PrimitiveProps {\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The default value for the calendar */\n  defaultValue?: DateRange\n  /** The controlled selected year range of the year range picker. Can be bound as `v-model`. */\n  modelValue?: DateRange | null\n  /** The placeholder date, which is used to determine what year range to display when no date is selected. */\n  placeholder?: DateValue\n  /** When combined with `isYearUnavailable`, determines whether non-contiguous ranges may be selected. */\n  allowNonContiguousRanges?: boolean\n  /** Whether or not to prevent the user from deselecting a date without selecting another date first */\n  preventDeselect?: boolean\n  /** The maximum number of years that can be selected in a range */\n  maximumYears?: number\n  /** The accessible label for the calendar */\n  calendarLabel?: string\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether or not the calendar is disabled */\n  disabled?: boolean\n  /** Whether or not the calendar is readonly */\n  readonly?: boolean\n  /** If true, the calendar will focus the selected year on mount */\n  initialFocus?: boolean\n  /** A function that returns whether or not a year is disabled */\n  isYearDisabled?: Matcher\n  /** A function that returns whether or not a year is unavailable */\n  isYearUnavailable?: Matcher\n  /** The reading direction of the calendar when applicable. */\n  dir?: Direction\n  /** A function that returns the next page of the calendar. */\n  nextPage?: (placeholder: DateValue) => DateValue\n  /** A function that returns the previous page of the calendar. */\n  prevPage?: (placeholder: DateValue) => DateValue\n  /** Which part of the range should be fixed */\n  fixedDate?: 'start' | 'end'\n  /** Number of years to display per page */\n  yearsPerPage?: number\n}\n\nexport type YearRangePickerRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateRange]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n  /** Event handler called whenever the start value changes */\n  'update:startValue': [date: DateValue | undefined]\n}\n\nexport const [injectYearRangePickerRootContext, provideYearRangePickerRootContext]\n  = createContext<YearRangePickerRootContext>('YearRangePickerRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener, useVModel } from '@vueuse/core'\nimport { computed, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearRangePickerRootProps>(), {\n  defaultValue: () => ({ start: undefined, end: undefined }),\n  as: 'div',\n  preventDeselect: false,\n  disabled: false,\n  readonly: false,\n  initialFocus: false,\n  placeholder: undefined,\n  isYearDisabled: undefined,\n  isYearUnavailable: undefined,\n  allowNonContiguousRanges: false,\n  maximumYears: undefined,\n  yearsPerPage: 12,\n})\nconst emits = defineEmits<YearRangePickerRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the placeholder */\n    date: DateValue\n    /** The grid of years */\n    grid: Grid<DateValue>\n    /** The calendar locale */\n    locale: string\n    /** The current date range */\n    modelValue: DateRange\n  }) => any\n}>()\n\nconst {\n  disabled,\n  readonly,\n  initialFocus,\n  preventDeselect,\n  isYearUnavailable: propsIsYearUnavailable,\n  isYearDisabled: propsIsYearDisabled,\n  calendarLabel,\n  maxValue,\n  minValue,\n  dir: propDir,\n  locale: propLocale,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n  allowNonContiguousRanges,\n  fixedDate,\n  maximumYears,\n  yearsPerPage,\n} = toRefs(props)\n\nconst { primitiveElement, currentElement: parentElement } = usePrimitiveElement()\nconst dir = useDirection(propDir)\nconst locale = useLocale(propLocale)\nconst headingId = useId(undefined, 'reka-year-range-picker-heading')\n\nconst lastPressedDateValue = ref() as Ref<DateValue | undefined>\nconst focusedValue = ref() as Ref<DateValue | undefined>\nconst isEditing = ref(false)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? { start: undefined, end: undefined },\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateRange | null>\n\nconst normalizeRange = (value?: DateRange | null): DateRange => value ?? { start: undefined, end: undefined }\nconst normalizedModelValue = computed(() => normalizeRange(modelValue.value))\n\nconst validModelValue = ref(normalizeRange(modelValue.value)) as Ref<DateRange>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: normalizeRange(modelValue.value).start,\n  locale: props.locale,\n})\n\nconst startValue = ref(normalizeRange(modelValue.value).start) as Ref<DateValue | undefined>\nconst endValue = ref(normalizeRange(modelValue.value).end) as Ref<DateValue | undefined>\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nfunction onPlaceholderChange(value: DateValue) {\n  placeholder.value = value.copy()\n}\n\nconst {\n  fullCalendarLabel,\n  headingValue,\n  isYearDisabled,\n  isYearUnavailable,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  grid,\n  nextPage,\n  prevPage,\n  formatter,\n} = useYearPicker({\n  locale,\n  placeholder,\n  minValue,\n  maxValue,\n  disabled,\n  yearsPerPage,\n  isYearDisabled: propsIsYearDisabled,\n  isYearUnavailable: propsIsYearUnavailable,\n  calendarLabel,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n})\n\nconst {\n  isInvalid,\n  isSelected,\n  highlightedRange,\n  isSelectionStart,\n  isSelectionEnd,\n  isHighlightedStart,\n  isHighlightedEnd,\n  isYearDisabled: rangeIsYearDisabled,\n} = useRangeYearPickerState({\n  start: startValue,\n  end: endValue,\n  isYearDisabled,\n  isYearUnavailable,\n  focusedValue,\n  allowNonContiguousRanges,\n  fixedDate,\n  maximumYears,\n})\n\nwatch(modelValue, (_modelValue) => {\n  const next = normalizeRange(_modelValue)\n\n  const isStartSynced = (!next.start && !startValue.value)\n    || (!!next.start && !!startValue.value && isSameYear(next.start, startValue.value))\n\n  if (!isStartSynced) {\n    startValue.value = next.start?.copy?.()\n  }\n\n  const isEndSynced = (!next.end && !endValue.value)\n    || (!!next.end && !!endValue.value && isSameYear(next.end, endValue.value))\n\n  if (!isEndSynced) {\n    endValue.value = next.end?.copy?.()\n  }\n})\n\nwatch(startValue, (_startValue) => {\n  if (_startValue && !isSameYear(_startValue, placeholder.value))\n    onPlaceholderChange(_startValue)\n\n  emits('update:startValue', _startValue)\n})\n\nwatch([startValue, endValue], ([_startValue, _endValue]) => {\n  const value = modelValue.value\n\n  if (\n    value\n    && value.start\n    && value.end\n    && _startValue\n    && _endValue\n    && isSameYear(value.start, _startValue)\n    && isSameYear(value.end, _endValue)\n  ) {\n    return\n  }\n\n  isEditing.value = true\n  if (_endValue && _startValue) {\n    const nextValue = _endValue.year < _startValue.year\n      ? { start: _endValue.copy(), end: _startValue.copy() }\n      : { start: _startValue.copy(), end: _endValue.copy() }\n\n    modelValue.value = { start: nextValue.start, end: nextValue.end }\n    isEditing.value = false\n    validModelValue.value = { start: nextValue.start.copy(), end: nextValue.end.copy() }\n  }\n  else {\n    modelValue.value = _startValue\n      ? { start: _startValue.copy(), end: undefined }\n      : { start: _endValue?.copy(), end: undefined }\n  }\n})\n\nconst kbd = useKbd()\nuseEventListener(parentElement, 'keydown', (ev) => {\n  if (ev.key === kbd.ESCAPE && isEditing.value) {\n    startValue.value = validModelValue.value.start?.copy()\n    endValue.value = validModelValue.value.end?.copy()\n  }\n})\n\nprovideYearRangePickerRootContext({\n  isYearUnavailable,\n  startValue,\n  endValue,\n  formatter,\n  modelValue: normalizedModelValue,\n  placeholder,\n  disabled,\n  initialFocus,\n  grid,\n  readonly,\n  preventDeselect,\n  fullCalendarLabel,\n  headingValue,\n  headingId,\n  isInvalid,\n  isYearDisabled: rangeIsYearDisabled,\n  allowNonContiguousRanges,\n  highlightedRange,\n  focusedValue,\n  lastPressedDateValue,\n  isSelected,\n  isSelectionEnd,\n  isSelectionStart,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  nextPage,\n  prevPage,\n  parentElement,\n  onPlaceholderChange,\n  locale,\n  dir,\n  isHighlightedStart,\n  isHighlightedEnd,\n  fixedDate,\n  maximumYears,\n  minValue,\n  maxValue,\n  yearsPerPage,\n})\n\nonMounted(() => {\n  if (initialFocus.value)\n    handleCalendarInitialFocus(parentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"fullCalendarLabel\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n  >\n    <div\n      style=\"border: 0px; clip: rect(0px, 0px, 0px, 0px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; white-space: nowrap; width: 1px;\"\n    >\n      <div\n        role=\"heading\"\n        aria-level=\"2\"\n      >\n        {{ fullCalendarLabel }}\n      </div>\n    </div>\n\n    <slot\n      :date=\"placeholder\"\n      :grid=\"grid\"\n      :locale=\"locale\"\n      :model-value=\"normalizedModelValue\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { Ref } from 'vue'\nimport type { Grid, Matcher } from '@/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport type { Formatter } from '@/shared'\nimport type { DateRange } from '@/shared/date'\nimport type { Direction } from '@/shared/types'\nimport { isSameYear } from '@/date'\nimport { createContext, useDirection, useId, useKbd, useLocale } from '@/shared'\nimport { getDefaultDate, handleCalendarInitialFocus } from '@/shared/date'\nimport { useYearPicker } from '@/YearPicker/useYearPicker'\nimport { useRangeYearPickerState } from './useRangeYearPicker'\n\ntype YearRangePickerRootContext = {\n  modelValue: Ref<DateRange>\n  startValue: Ref<DateValue | undefined>\n  endValue: Ref<DateValue | undefined>\n  locale: Ref<string>\n  placeholder: Ref<DateValue>\n  preventDeselect: Ref<boolean>\n  grid: Ref<Grid<DateValue>>\n  disabled: Ref<boolean>\n  readonly: Ref<boolean>\n  initialFocus: Ref<boolean>\n  onPlaceholderChange: (date: DateValue) => void\n  fullCalendarLabel: Ref<string>\n  parentElement: Ref<HTMLElement | undefined>\n  headingValue: Ref<string>\n  headingId: string\n  isInvalid: Ref<boolean>\n  isYearDisabled: Matcher\n  isYearUnavailable?: Matcher\n  allowNonContiguousRanges: Ref<boolean>\n  highlightedRange: Ref<{ start: DateValue, end: DateValue } | null>\n  focusedValue: Ref<DateValue | undefined>\n  lastPressedDateValue: Ref<DateValue | undefined>\n  isSelected: (date: DateValue) => boolean\n  isSelectionEnd: (date: DateValue) => boolean\n  isSelectionStart: (date: DateValue) => boolean\n  isHighlightedStart: (date: DateValue) => boolean\n  isHighlightedEnd: (date: DateValue) => boolean\n  prevPage: (prevPageFunc?: (date: DateValue) => DateValue) => void\n  nextPage: (nextPageFunc?: (date: DateValue) => DateValue) => void\n  isNextButtonDisabled: (nextPageFunc?: (date: DateValue) => DateValue) => boolean\n  isPrevButtonDisabled: (prevPageFunc?: (date: DateValue) => DateValue) => boolean\n  formatter: Formatter\n  dir: Ref<Direction>\n  fixedDate: Ref<'start' | 'end' | undefined>\n  maximumYears: Ref<number | undefined>\n  minValue: Ref<DateValue | undefined>\n  maxValue: Ref<DateValue | undefined>\n  yearsPerPage: Ref<number>\n}\n\nexport interface YearRangePickerRootProps extends PrimitiveProps {\n  /** The default placeholder date */\n  defaultPlaceholder?: DateValue\n  /** The default value for the calendar */\n  defaultValue?: DateRange\n  /** The controlled selected year range of the year range picker. Can be bound as `v-model`. */\n  modelValue?: DateRange | null\n  /** The placeholder date, which is used to determine what year range to display when no date is selected. */\n  placeholder?: DateValue\n  /** When combined with `isYearUnavailable`, determines whether non-contiguous ranges may be selected. */\n  allowNonContiguousRanges?: boolean\n  /** Whether or not to prevent the user from deselecting a date without selecting another date first */\n  preventDeselect?: boolean\n  /** The maximum number of years that can be selected in a range */\n  maximumYears?: number\n  /** The accessible label for the calendar */\n  calendarLabel?: string\n  /** The maximum date that can be selected */\n  maxValue?: DateValue\n  /** The minimum date that can be selected */\n  minValue?: DateValue\n  /** The locale to use for formatting dates */\n  locale?: string\n  /** Whether or not the calendar is disabled */\n  disabled?: boolean\n  /** Whether or not the calendar is readonly */\n  readonly?: boolean\n  /** If true, the calendar will focus the selected year on mount */\n  initialFocus?: boolean\n  /** A function that returns whether or not a year is disabled */\n  isYearDisabled?: Matcher\n  /** A function that returns whether or not a year is unavailable */\n  isYearUnavailable?: Matcher\n  /** The reading direction of the calendar when applicable. */\n  dir?: Direction\n  /** A function that returns the next page of the calendar. */\n  nextPage?: (placeholder: DateValue) => DateValue\n  /** A function that returns the previous page of the calendar. */\n  prevPage?: (placeholder: DateValue) => DateValue\n  /** Which part of the range should be fixed */\n  fixedDate?: 'start' | 'end'\n  /** Number of years to display per page */\n  yearsPerPage?: number\n}\n\nexport type YearRangePickerRootEmits = {\n  /** Event handler called whenever the model value changes */\n  'update:modelValue': [date: DateRange]\n  /** Event handler called whenever the placeholder value changes */\n  'update:placeholder': [date: DateValue]\n  /** Event handler called whenever the start value changes */\n  'update:startValue': [date: DateValue | undefined]\n}\n\nexport const [injectYearRangePickerRootContext, provideYearRangePickerRootContext]\n  = createContext<YearRangePickerRootContext>('YearRangePickerRoot')\n</script>\n\n<script setup lang=\"ts\">\nimport { useEventListener, useVModel } from '@vueuse/core'\nimport { computed, onMounted, ref, toRefs, watch } from 'vue'\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearRangePickerRootProps>(), {\n  defaultValue: () => ({ start: undefined, end: undefined }),\n  as: 'div',\n  preventDeselect: false,\n  disabled: false,\n  readonly: false,\n  initialFocus: false,\n  placeholder: undefined,\n  isYearDisabled: undefined,\n  isYearUnavailable: undefined,\n  allowNonContiguousRanges: false,\n  maximumYears: undefined,\n  yearsPerPage: 12,\n})\nconst emits = defineEmits<YearRangePickerRootEmits>()\n\ndefineSlots<{\n  default?: (props: {\n    /** The current date of the placeholder */\n    date: DateValue\n    /** The grid of years */\n    grid: Grid<DateValue>\n    /** The calendar locale */\n    locale: string\n    /** The current date range */\n    modelValue: DateRange\n  }) => any\n}>()\n\nconst {\n  disabled,\n  readonly,\n  initialFocus,\n  preventDeselect,\n  isYearUnavailable: propsIsYearUnavailable,\n  isYearDisabled: propsIsYearDisabled,\n  calendarLabel,\n  maxValue,\n  minValue,\n  dir: propDir,\n  locale: propLocale,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n  allowNonContiguousRanges,\n  fixedDate,\n  maximumYears,\n  yearsPerPage,\n} = toRefs(props)\n\nconst { primitiveElement, currentElement: parentElement } = usePrimitiveElement()\nconst dir = useDirection(propDir)\nconst locale = useLocale(propLocale)\nconst headingId = useId(undefined, 'reka-year-range-picker-heading')\n\nconst lastPressedDateValue = ref() as Ref<DateValue | undefined>\nconst focusedValue = ref() as Ref<DateValue | undefined>\nconst isEditing = ref(false)\n\nconst modelValue = useVModel(props, 'modelValue', emits, {\n  defaultValue: props.defaultValue ?? { start: undefined, end: undefined },\n  passive: (props.modelValue === undefined) as false,\n}) as Ref<DateRange | null>\n\nconst normalizeRange = (value?: DateRange | null): DateRange => value ?? { start: undefined, end: undefined }\nconst normalizedModelValue = computed(() => normalizeRange(modelValue.value))\n\nconst validModelValue = ref(normalizeRange(modelValue.value)) as Ref<DateRange>\n\nconst defaultDate = getDefaultDate({\n  defaultPlaceholder: props.placeholder,\n  defaultValue: normalizeRange(modelValue.value).start,\n  locale: props.locale,\n})\n\nconst startValue = ref(normalizeRange(modelValue.value).start) as Ref<DateValue | undefined>\nconst endValue = ref(normalizeRange(modelValue.value).end) as Ref<DateValue | undefined>\n\nconst placeholder = useVModel(props, 'placeholder', emits, {\n  defaultValue: props.defaultPlaceholder ?? defaultDate.copy(),\n  passive: (props.placeholder === undefined) as false,\n}) as Ref<DateValue>\n\nfunction onPlaceholderChange(value: DateValue) {\n  placeholder.value = value.copy()\n}\n\nconst {\n  fullCalendarLabel,\n  headingValue,\n  isYearDisabled,\n  isYearUnavailable,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  grid,\n  nextPage,\n  prevPage,\n  formatter,\n} = useYearPicker({\n  locale,\n  placeholder,\n  minValue,\n  maxValue,\n  disabled,\n  yearsPerPage,\n  isYearDisabled: propsIsYearDisabled,\n  isYearUnavailable: propsIsYearUnavailable,\n  calendarLabel,\n  nextPage: propsNextPage,\n  prevPage: propsPrevPage,\n})\n\nconst {\n  isInvalid,\n  isSelected,\n  highlightedRange,\n  isSelectionStart,\n  isSelectionEnd,\n  isHighlightedStart,\n  isHighlightedEnd,\n  isYearDisabled: rangeIsYearDisabled,\n} = useRangeYearPickerState({\n  start: startValue,\n  end: endValue,\n  isYearDisabled,\n  isYearUnavailable,\n  focusedValue,\n  allowNonContiguousRanges,\n  fixedDate,\n  maximumYears,\n})\n\nwatch(modelValue, (_modelValue) => {\n  const next = normalizeRange(_modelValue)\n\n  const isStartSynced = (!next.start && !startValue.value)\n    || (!!next.start && !!startValue.value && isSameYear(next.start, startValue.value))\n\n  if (!isStartSynced) {\n    startValue.value = next.start?.copy?.()\n  }\n\n  const isEndSynced = (!next.end && !endValue.value)\n    || (!!next.end && !!endValue.value && isSameYear(next.end, endValue.value))\n\n  if (!isEndSynced) {\n    endValue.value = next.end?.copy?.()\n  }\n})\n\nwatch(startValue, (_startValue) => {\n  if (_startValue && !isSameYear(_startValue, placeholder.value))\n    onPlaceholderChange(_startValue)\n\n  emits('update:startValue', _startValue)\n})\n\nwatch([startValue, endValue], ([_startValue, _endValue]) => {\n  const value = modelValue.value\n\n  if (\n    value\n    && value.start\n    && value.end\n    && _startValue\n    && _endValue\n    && isSameYear(value.start, _startValue)\n    && isSameYear(value.end, _endValue)\n  ) {\n    return\n  }\n\n  isEditing.value = true\n  if (_endValue && _startValue) {\n    const nextValue = _endValue.year < _startValue.year\n      ? { start: _endValue.copy(), end: _startValue.copy() }\n      : { start: _startValue.copy(), end: _endValue.copy() }\n\n    modelValue.value = { start: nextValue.start, end: nextValue.end }\n    isEditing.value = false\n    validModelValue.value = { start: nextValue.start.copy(), end: nextValue.end.copy() }\n  }\n  else {\n    modelValue.value = _startValue\n      ? { start: _startValue.copy(), end: undefined }\n      : { start: _endValue?.copy(), end: undefined }\n  }\n})\n\nconst kbd = useKbd()\nuseEventListener(parentElement, 'keydown', (ev) => {\n  if (ev.key === kbd.ESCAPE && isEditing.value) {\n    startValue.value = validModelValue.value.start?.copy()\n    endValue.value = validModelValue.value.end?.copy()\n  }\n})\n\nprovideYearRangePickerRootContext({\n  isYearUnavailable,\n  startValue,\n  endValue,\n  formatter,\n  modelValue: normalizedModelValue,\n  placeholder,\n  disabled,\n  initialFocus,\n  grid,\n  readonly,\n  preventDeselect,\n  fullCalendarLabel,\n  headingValue,\n  headingId,\n  isInvalid,\n  isYearDisabled: rangeIsYearDisabled,\n  allowNonContiguousRanges,\n  highlightedRange,\n  focusedValue,\n  lastPressedDateValue,\n  isSelected,\n  isSelectionEnd,\n  isSelectionStart,\n  isNextButtonDisabled,\n  isPrevButtonDisabled,\n  nextPage,\n  prevPage,\n  parentElement,\n  onPlaceholderChange,\n  locale,\n  dir,\n  isHighlightedStart,\n  isHighlightedEnd,\n  fixedDate,\n  maximumYears,\n  minValue,\n  maxValue,\n  yearsPerPage,\n})\n\nonMounted(() => {\n  if (initialFocus.value)\n    handleCalendarInitialFocus(parentElement.value)\n})\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"as\"\n    :as-child=\"asChild\"\n    :aria-label=\"fullCalendarLabel\"\n    :data-readonly=\"readonly ? '' : undefined\"\n    :data-disabled=\"disabled ? '' : undefined\"\n    :data-invalid=\"isInvalid ? '' : undefined\"\n    :dir=\"dir\"\n  >\n    <div\n      style=\"border: 0px; clip: rect(0px, 0px, 0px, 0px); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; white-space: nowrap; width: 1px;\"\n    >\n      <div\n        role=\"heading\"\n        aria-level=\"2\"\n      >\n        {{ fullCalendarLabel }}\n      </div>\n    </div>\n\n    <slot\n      :date=\"placeholder\"\n      :grid=\"grid\"\n      :locale=\"locale\"\n      :model-value=\"normalizedModelValue\"\n    />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerCellProps extends PrimitiveProps {\n  /** The date value for the cell */\n  date: DateValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectYearRangePickerRootContext } from './YearRangePickerRoot.vue'\n\nwithDefaults(defineProps<YearRangePickerCellProps>(), { as: 'td' })\nconst rootContext = injectYearRangePickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"gridcell\"\n    :aria-selected=\"rootContext.isSelected(date) ? true : undefined\"\n    :aria-disabled=\"rootContext.isYearDisabled(date) || rootContext.isYearUnavailable?.(date)\"\n    :data-disabled=\"rootContext.isYearDisabled(date) ? '' : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerCellProps extends PrimitiveProps {\n  /** The date value for the cell */\n  date: DateValue\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectYearRangePickerRootContext } from './YearRangePickerRoot.vue'\n\nwithDefaults(defineProps<YearRangePickerCellProps>(), { as: 'td' })\nconst rootContext = injectYearRangePickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    :as=\"as\"\n    :as-child=\"asChild\"\n    role=\"gridcell\"\n    :aria-selected=\"rootContext.isSelected(date) ? true : undefined\"\n    :aria-disabled=\"rootContext.isYearDisabled(date) || rootContext.isYearUnavailable?.(date)\"\n    :data-disabled=\"rootContext.isYearDisabled(date) ? '' : undefined\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { endOfYear, getLocalTimeZone, startOfYear, toCalendar, today } from '@internationalized/date'\nimport { computed, nextTick } from 'vue'\nimport { isSameYear, isYearBetweenInclusive, toDate } from '@/date'\nimport { useKbd } from '@/shared'\n\nexport interface YearRangePickerCellTriggerProps extends PrimitiveProps {\n  /** The date value provided to the cell trigger */\n  year: DateValue\n}\n\nexport interface YearRangePickerCellTriggerSlot {\n  default?: (props: {\n    /** Current year value */\n    yearValue: string\n    /** Current disable state */\n    disabled: boolean\n    /** Current selected state */\n    selected: boolean\n    /** Current year is today's year state */\n    today: boolean\n    /** Current unavailable state */\n    unavailable: boolean\n    /** Current highlighted state */\n    highlighted: boolean\n    /** Current highlighted start state */\n    highlightedStart: boolean\n    /** Current highlighted end state */\n    highlightedEnd: boolean\n    /** Current selection start state */\n    selectionStart: boolean\n    /** Current selection end state */\n    selectionEnd: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectYearRangePickerRootContext } from './YearRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearRangePickerCellTriggerProps>(), { as: 'div' })\n\ndefineSlots<YearRangePickerCellTriggerSlot>()\n\nconst kbd = useKbd()\nconst rootContext = injectYearRangePickerRootContext()\n\nconst { primitiveElement } = usePrimitiveElement()\n\nconst yearValue = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.fullYear(toDate(props.year))\n})\n\nconst labelText = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.custom(toDate(props.year), { year: 'numeric' })\n})\n\nconst isUnavailable = computed(() => rootContext.isYearUnavailable?.(props.year) ?? false)\n\nconst isCurrentYear = computed(() => {\n  const todayDate = toCalendar(today(getLocalTimeZone()), props.year.calendar)\n  return isSameYear(props.year, todayDate)\n})\n\nconst isDisabled = computed(() => rootContext.isYearDisabled(props.year))\n\nconst isFocusedYear = computed(() => {\n  return !rootContext.disabled.value && isSameYear(props.year, rootContext.placeholder.value)\n})\n\nconst isSelectedYear = computed(() => rootContext.isSelected(props.year))\nconst isSelectionStart = computed(() => rootContext.isSelectionStart(props.year))\nconst isSelectionEnd = computed(() => rootContext.isSelectionEnd(props.year))\nconst isHighlightStart = computed(() => rootContext.isHighlightedStart(props.year))\nconst isHighlightEnd = computed(() => rootContext.isHighlightedEnd(props.year))\nconst isHighlighted = computed(() => rootContext.highlightedRange.value\n  ? isYearBetweenInclusive(props.year, rootContext.highlightedRange.value.start, rootContext.highlightedRange.value.end)\n  : false)\nconst allowNonContiguousRanges = computed(() => rootContext.allowNonContiguousRanges.value)\n\nfunction changeYear(e: MouseEvent | KeyboardEvent, date: DateValue) {\n  if (rootContext.readonly.value)\n    return\n  if (rootContext.isYearDisabled(date) || rootContext.isYearUnavailable?.(date))\n    return\n\n  if (rootContext.startValue.value && rootContext.highlightedRange.value === null) {\n    if (isSameYear(date, rootContext.startValue.value) && !rootContext.preventDeselect.value && !rootContext.endValue.value) {\n      rootContext.startValue.value = undefined\n      rootContext.onPlaceholderChange(date)\n      rootContext.lastPressedDateValue.value = date.copy()\n      return\n    }\n    else if (!rootContext.endValue.value) {\n      e.preventDefault()\n      if (rootContext.lastPressedDateValue.value && isSameYear(rootContext.lastPressedDateValue.value, date))\n        rootContext.startValue.value = date.copy()\n      rootContext.lastPressedDateValue.value = date.copy()\n      return\n    }\n  }\n\n  rootContext.lastPressedDateValue.value = date.copy()\n\n  if (\n    rootContext.startValue.value\n    && rootContext.endValue.value\n    && isSameYear(rootContext.startValue.value, rootContext.endValue.value)\n    && isSameYear(rootContext.startValue.value, date)\n    && !rootContext.preventDeselect.value\n  ) {\n    rootContext.startValue.value = undefined\n    rootContext.endValue.value = undefined\n    rootContext.onPlaceholderChange(date)\n    return\n  }\n\n  if (!rootContext.startValue.value) {\n    rootContext.startValue.value = date.copy()\n  }\n  else if (!rootContext.endValue.value) {\n    rootContext.endValue.value = date.copy()\n  }\n  else if (rootContext.endValue.value && rootContext.startValue.value) {\n    if (!rootContext.fixedDate.value) {\n      rootContext.endValue.value = undefined\n      rootContext.startValue.value = date.copy()\n    }\n    else if (rootContext.fixedDate.value === 'start') {\n      if (date.compare(rootContext.startValue.value) < 0) {\n        rootContext.startValue.value = date.copy()\n      }\n      else {\n        rootContext.endValue.value = date.copy()\n      }\n    }\n    else if (rootContext.fixedDate.value === 'end') {\n      if (date.compare(rootContext.endValue.value) > 0) {\n        rootContext.endValue.value = date.copy()\n      }\n      else {\n        rootContext.startValue.value = date.copy()\n      }\n    }\n  }\n}\n\nfunction handleClick(e: MouseEvent) {\n  if (isDisabled.value)\n    return\n  changeYear(e, props.year)\n}\n\nfunction handleFocus() {\n  if (isDisabled.value || rootContext.isYearUnavailable?.(props.year))\n    return\n  rootContext.focusedValue.value = props.year.copy()\n}\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  if (isDisabled.value)\n    return\n  e.preventDefault()\n  e.stopPropagation()\n  const parentElement = rootContext.parentElement.value!\n  const sign = rootContext.dir.value === 'rtl' ? -1 : 1\n\n  switch (e.code) {\n    case kbd.ARROW_RIGHT:\n      shiftFocus(props.year, sign)\n      break\n    case kbd.ARROW_LEFT:\n      shiftFocus(props.year, -sign)\n      break\n    case kbd.ARROW_UP:\n      shiftFocus(props.year, -4)\n      break\n    case kbd.ARROW_DOWN:\n      shiftFocus(props.year, 4)\n      break\n    case kbd.PAGE_UP:\n      shiftFocusPage(-1)\n      break\n    case kbd.PAGE_DOWN:\n      shiftFocusPage(1)\n      break\n    case kbd.ENTER:\n    case kbd.SPACE_CODE:\n      changeYear(e, props.year)\n  }\n\n  function shiftFocus(currentYear: DateValue, add: number, depth = 0) {\n    if (depth > 48)\n      return\n    const candidateYearValue = currentYear.add({ years: add })\n\n    if ((rootContext.minValue.value && endOfYear(candidateYearValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && startOfYear(candidateYearValue).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    const candidateYear = parentElement.querySelector<HTMLElement>(`[data-value='${candidateYearValue.toString()}']`)\n\n    if (!candidateYear) {\n      if (add > 0) {\n        if (rootContext.isNextButtonDisabled())\n          return\n        rootContext.nextPage()\n      }\n      else {\n        if (rootContext.isPrevButtonDisabled())\n          return\n        rootContext.prevPage()\n      }\n      nextTick(() => {\n        shiftFocus(currentYear, add, depth + 1)\n      })\n      return\n    }\n\n    if (candidateYear && candidateYear.hasAttribute('data-disabled'))\n      return shiftFocus(candidateYearValue, add, depth + 1)\n\n    rootContext.onPlaceholderChange(candidateYearValue)\n    candidateYear?.focus()\n  }\n\n  function shiftFocusPage(direction: number) {\n    const yearsPerPage = rootContext.yearsPerPage.value\n    const candidateYearValue = props.year.add({ years: direction * yearsPerPage })\n\n    if ((rootContext.minValue.value && endOfYear(candidateYearValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && startOfYear(candidateYearValue).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    if (direction > 0) {\n      if (rootContext.isNextButtonDisabled())\n        return\n      rootContext.nextPage()\n    }\n    else {\n      if (rootContext.isPrevButtonDisabled())\n        return\n      rootContext.prevPage()\n    }\n\n    nextTick(() => {\n      const candidateYear = parentElement.querySelector<HTMLElement>(`[data-value='${candidateYearValue.toString()}']`)\n      if (candidateYear && !candidateYear.hasAttribute('data-disabled')) {\n        rootContext.onPlaceholderChange(candidateYearValue)\n        candidateYear?.focus()\n        return\n      }\n\n      if (!candidateYear || candidateYear.hasAttribute('data-disabled'))\n        shiftFocus(candidateYearValue, direction > 0 ? 1 : -1, 1)\n    })\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    role=\"button\"\n    :aria-label=\"labelText\"\n    data-reka-year-range-picker-cell-trigger\n    :aria-pressed=\"isSelectedYear && (allowNonContiguousRanges || !isUnavailable) ? true : undefined\"\n    :aria-disabled=\"isDisabled || isUnavailable ? true : undefined\"\n    :data-highlighted=\"isHighlighted && (allowNonContiguousRanges || !isUnavailable) ? '' : undefined\"\n    :data-selection-start=\"isSelectionStart ? true : undefined\"\n    :data-selection-end=\"isSelectionEnd ? true : undefined\"\n    :data-highlighted-start=\"isHighlightStart ? true : undefined\"\n    :data-highlighted-end=\"isHighlightEnd ? true : undefined\"\n    :data-selected=\"isSelectedYear && (allowNonContiguousRanges || !isUnavailable) ? true : undefined\"\n    :data-value=\"year.toString()\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-unavailable=\"isUnavailable ? '' : undefined\"\n    :data-today=\"isCurrentYear ? '' : undefined\"\n    :data-focused=\"isFocusedYear ? '' : undefined\"\n    :tabindex=\"isFocusedYear ? 0 : isDisabled ? undefined : -1\"\n    @click=\"handleClick\"\n    @focusin=\"handleFocus\"\n    @mouseenter=\"handleFocus\"\n    @keydown.up.down.left.right.space.enter.page-up.page-down=\"handleArrowKey\"\n    @keydown.enter.prevent\n  >\n    <slot\n      :year-value=\"yearValue\"\n      :disabled=\"isDisabled\"\n      :today=\"isCurrentYear\"\n      :selected=\"isSelectedYear\"\n      :unavailable=\"isUnavailable\"\n      :highlighted=\"isHighlighted && (allowNonContiguousRanges || !isUnavailable)\"\n      :highlighted-start=\"isHighlightStart\"\n      :highlighted-end=\"isHighlightEnd\"\n      :selection-start=\"isSelectionStart\"\n      :selection-end=\"isSelectionEnd\"\n    >\n      {{ yearValue }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\nimport { endOfYear, getLocalTimeZone, startOfYear, toCalendar, today } from '@internationalized/date'\nimport { computed, nextTick } from 'vue'\nimport { isSameYear, isYearBetweenInclusive, toDate } from '@/date'\nimport { useKbd } from '@/shared'\n\nexport interface YearRangePickerCellTriggerProps extends PrimitiveProps {\n  /** The date value provided to the cell trigger */\n  year: DateValue\n}\n\nexport interface YearRangePickerCellTriggerSlot {\n  default?: (props: {\n    /** Current year value */\n    yearValue: string\n    /** Current disable state */\n    disabled: boolean\n    /** Current selected state */\n    selected: boolean\n    /** Current year is today's year state */\n    today: boolean\n    /** Current unavailable state */\n    unavailable: boolean\n    /** Current highlighted state */\n    highlighted: boolean\n    /** Current highlighted start state */\n    highlightedStart: boolean\n    /** Current highlighted end state */\n    highlightedEnd: boolean\n    /** Current selection start state */\n    selectionStart: boolean\n    /** Current selection end state */\n    selectionEnd: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive, usePrimitiveElement } from '@/Primitive'\nimport { injectYearRangePickerRootContext } from './YearRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearRangePickerCellTriggerProps>(), { as: 'div' })\n\ndefineSlots<YearRangePickerCellTriggerSlot>()\n\nconst kbd = useKbd()\nconst rootContext = injectYearRangePickerRootContext()\n\nconst { primitiveElement } = usePrimitiveElement()\n\nconst yearValue = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.fullYear(toDate(props.year))\n})\n\nconst labelText = computed(() => {\n  rootContext.locale.value\n  return rootContext.formatter.custom(toDate(props.year), { year: 'numeric' })\n})\n\nconst isUnavailable = computed(() => rootContext.isYearUnavailable?.(props.year) ?? false)\n\nconst isCurrentYear = computed(() => {\n  const todayDate = toCalendar(today(getLocalTimeZone()), props.year.calendar)\n  return isSameYear(props.year, todayDate)\n})\n\nconst isDisabled = computed(() => rootContext.isYearDisabled(props.year))\n\nconst isFocusedYear = computed(() => {\n  return !rootContext.disabled.value && isSameYear(props.year, rootContext.placeholder.value)\n})\n\nconst isSelectedYear = computed(() => rootContext.isSelected(props.year))\nconst isSelectionStart = computed(() => rootContext.isSelectionStart(props.year))\nconst isSelectionEnd = computed(() => rootContext.isSelectionEnd(props.year))\nconst isHighlightStart = computed(() => rootContext.isHighlightedStart(props.year))\nconst isHighlightEnd = computed(() => rootContext.isHighlightedEnd(props.year))\nconst isHighlighted = computed(() => rootContext.highlightedRange.value\n  ? isYearBetweenInclusive(props.year, rootContext.highlightedRange.value.start, rootContext.highlightedRange.value.end)\n  : false)\nconst allowNonContiguousRanges = computed(() => rootContext.allowNonContiguousRanges.value)\n\nfunction changeYear(e: MouseEvent | KeyboardEvent, date: DateValue) {\n  if (rootContext.readonly.value)\n    return\n  if (rootContext.isYearDisabled(date) || rootContext.isYearUnavailable?.(date))\n    return\n\n  if (rootContext.startValue.value && rootContext.highlightedRange.value === null) {\n    if (isSameYear(date, rootContext.startValue.value) && !rootContext.preventDeselect.value && !rootContext.endValue.value) {\n      rootContext.startValue.value = undefined\n      rootContext.onPlaceholderChange(date)\n      rootContext.lastPressedDateValue.value = date.copy()\n      return\n    }\n    else if (!rootContext.endValue.value) {\n      e.preventDefault()\n      if (rootContext.lastPressedDateValue.value && isSameYear(rootContext.lastPressedDateValue.value, date))\n        rootContext.startValue.value = date.copy()\n      rootContext.lastPressedDateValue.value = date.copy()\n      return\n    }\n  }\n\n  rootContext.lastPressedDateValue.value = date.copy()\n\n  if (\n    rootContext.startValue.value\n    && rootContext.endValue.value\n    && isSameYear(rootContext.startValue.value, rootContext.endValue.value)\n    && isSameYear(rootContext.startValue.value, date)\n    && !rootContext.preventDeselect.value\n  ) {\n    rootContext.startValue.value = undefined\n    rootContext.endValue.value = undefined\n    rootContext.onPlaceholderChange(date)\n    return\n  }\n\n  if (!rootContext.startValue.value) {\n    rootContext.startValue.value = date.copy()\n  }\n  else if (!rootContext.endValue.value) {\n    rootContext.endValue.value = date.copy()\n  }\n  else if (rootContext.endValue.value && rootContext.startValue.value) {\n    if (!rootContext.fixedDate.value) {\n      rootContext.endValue.value = undefined\n      rootContext.startValue.value = date.copy()\n    }\n    else if (rootContext.fixedDate.value === 'start') {\n      if (date.compare(rootContext.startValue.value) < 0) {\n        rootContext.startValue.value = date.copy()\n      }\n      else {\n        rootContext.endValue.value = date.copy()\n      }\n    }\n    else if (rootContext.fixedDate.value === 'end') {\n      if (date.compare(rootContext.endValue.value) > 0) {\n        rootContext.endValue.value = date.copy()\n      }\n      else {\n        rootContext.startValue.value = date.copy()\n      }\n    }\n  }\n}\n\nfunction handleClick(e: MouseEvent) {\n  if (isDisabled.value)\n    return\n  changeYear(e, props.year)\n}\n\nfunction handleFocus() {\n  if (isDisabled.value || rootContext.isYearUnavailable?.(props.year))\n    return\n  rootContext.focusedValue.value = props.year.copy()\n}\n\nfunction handleArrowKey(e: KeyboardEvent) {\n  if (isDisabled.value)\n    return\n  e.preventDefault()\n  e.stopPropagation()\n  const parentElement = rootContext.parentElement.value!\n  const sign = rootContext.dir.value === 'rtl' ? -1 : 1\n\n  switch (e.code) {\n    case kbd.ARROW_RIGHT:\n      shiftFocus(props.year, sign)\n      break\n    case kbd.ARROW_LEFT:\n      shiftFocus(props.year, -sign)\n      break\n    case kbd.ARROW_UP:\n      shiftFocus(props.year, -4)\n      break\n    case kbd.ARROW_DOWN:\n      shiftFocus(props.year, 4)\n      break\n    case kbd.PAGE_UP:\n      shiftFocusPage(-1)\n      break\n    case kbd.PAGE_DOWN:\n      shiftFocusPage(1)\n      break\n    case kbd.ENTER:\n    case kbd.SPACE_CODE:\n      changeYear(e, props.year)\n  }\n\n  function shiftFocus(currentYear: DateValue, add: number, depth = 0) {\n    if (depth > 48)\n      return\n    const candidateYearValue = currentYear.add({ years: add })\n\n    if ((rootContext.minValue.value && endOfYear(candidateYearValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && startOfYear(candidateYearValue).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    const candidateYear = parentElement.querySelector<HTMLElement>(`[data-value='${candidateYearValue.toString()}']`)\n\n    if (!candidateYear) {\n      if (add > 0) {\n        if (rootContext.isNextButtonDisabled())\n          return\n        rootContext.nextPage()\n      }\n      else {\n        if (rootContext.isPrevButtonDisabled())\n          return\n        rootContext.prevPage()\n      }\n      nextTick(() => {\n        shiftFocus(currentYear, add, depth + 1)\n      })\n      return\n    }\n\n    if (candidateYear && candidateYear.hasAttribute('data-disabled'))\n      return shiftFocus(candidateYearValue, add, depth + 1)\n\n    rootContext.onPlaceholderChange(candidateYearValue)\n    candidateYear?.focus()\n  }\n\n  function shiftFocusPage(direction: number) {\n    const yearsPerPage = rootContext.yearsPerPage.value\n    const candidateYearValue = props.year.add({ years: direction * yearsPerPage })\n\n    if ((rootContext.minValue.value && endOfYear(candidateYearValue).compare(rootContext.minValue.value) < 0)\n      || (rootContext.maxValue.value && startOfYear(candidateYearValue).compare(rootContext.maxValue.value) > 0)) {\n      return\n    }\n\n    if (direction > 0) {\n      if (rootContext.isNextButtonDisabled())\n        return\n      rootContext.nextPage()\n    }\n    else {\n      if (rootContext.isPrevButtonDisabled())\n        return\n      rootContext.prevPage()\n    }\n\n    nextTick(() => {\n      const candidateYear = parentElement.querySelector<HTMLElement>(`[data-value='${candidateYearValue.toString()}']`)\n      if (candidateYear && !candidateYear.hasAttribute('data-disabled')) {\n        rootContext.onPlaceholderChange(candidateYearValue)\n        candidateYear?.focus()\n        return\n      }\n\n      if (!candidateYear || candidateYear.hasAttribute('data-disabled'))\n        shiftFocus(candidateYearValue, direction > 0 ? 1 : -1, 1)\n    })\n  }\n}\n</script>\n\n<template>\n  <Primitive\n    ref=\"primitiveElement\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    role=\"button\"\n    :aria-label=\"labelText\"\n    data-reka-year-range-picker-cell-trigger\n    :aria-pressed=\"isSelectedYear && (allowNonContiguousRanges || !isUnavailable) ? true : undefined\"\n    :aria-disabled=\"isDisabled || isUnavailable ? true : undefined\"\n    :data-highlighted=\"isHighlighted && (allowNonContiguousRanges || !isUnavailable) ? '' : undefined\"\n    :data-selection-start=\"isSelectionStart ? true : undefined\"\n    :data-selection-end=\"isSelectionEnd ? true : undefined\"\n    :data-highlighted-start=\"isHighlightStart ? true : undefined\"\n    :data-highlighted-end=\"isHighlightEnd ? true : undefined\"\n    :data-selected=\"isSelectedYear && (allowNonContiguousRanges || !isUnavailable) ? true : undefined\"\n    :data-value=\"year.toString()\"\n    :data-disabled=\"isDisabled ? '' : undefined\"\n    :data-unavailable=\"isUnavailable ? '' : undefined\"\n    :data-today=\"isCurrentYear ? '' : undefined\"\n    :data-focused=\"isFocusedYear ? '' : undefined\"\n    :tabindex=\"isFocusedYear ? 0 : isDisabled ? undefined : -1\"\n    @click=\"handleClick\"\n    @focusin=\"handleFocus\"\n    @mouseenter=\"handleFocus\"\n    @keydown.up.down.left.right.space.enter.page-up.page-down=\"handleArrowKey\"\n    @keydown.enter.prevent\n  >\n    <slot\n      :year-value=\"yearValue\"\n      :disabled=\"isDisabled\"\n      :today=\"isCurrentYear\"\n      :selected=\"isSelectedYear\"\n      :unavailable=\"isUnavailable\"\n      :highlighted=\"isHighlighted && (allowNonContiguousRanges || !isUnavailable)\"\n      :highlighted-start=\"isHighlightStart\"\n      :highlighted-end=\"isHighlightEnd\"\n      :selection-start=\"isSelectionStart\"\n      :selection-end=\"isSelectionEnd\"\n    >\n      {{ yearValue }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerGridProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectYearRangePickerRootContext } from './YearRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearRangePickerGridProps>(), { as: 'table' })\n\nconst rootContext = injectYearRangePickerRootContext()\nconst disabled = computed(() => rootContext.disabled.value ? true : undefined)\nconst readonly = computed(() => rootContext.readonly.value ? true : undefined)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    role=\"application\"\n    :aria-labelledby=\"rootContext.headingId\"\n    :aria-readonly=\"readonly\"\n    :aria-disabled=\"disabled\"\n    :data-readonly=\"readonly && ''\"\n    :data-disabled=\"disabled && ''\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerGridProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectYearRangePickerRootContext } from './YearRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearRangePickerGridProps>(), { as: 'table' })\n\nconst rootContext = injectYearRangePickerRootContext()\nconst disabled = computed(() => rootContext.disabled.value ? true : undefined)\nconst readonly = computed(() => rootContext.readonly.value ? true : undefined)\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    tabindex=\"-1\"\n    role=\"application\"\n    :aria-labelledby=\"rootContext.headingId\"\n    :aria-readonly=\"readonly\"\n    :aria-disabled=\"disabled\"\n    :data-readonly=\"readonly && ''\"\n    :data-disabled=\"disabled && ''\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerGridBodyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearRangePickerGridBodyProps>(), { as: 'tbody' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerGridBodyProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearRangePickerGridBodyProps>(), { as: 'tbody' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerGridRowProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearRangePickerGridRowProps>(), { as: 'tr' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    role=\"row\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerGridRowProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearRangePickerGridRowProps>(), { as: 'tr' })\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    role=\"row\"\n  >\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearRangePickerHeaderProps>(), { as: 'div' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerHeaderProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\n\nconst props = withDefaults(defineProps<YearRangePickerHeaderProps>(), { as: 'div' })\n</script>\n\n<template>\n  <Primitive v-bind=\"props\">\n    <slot />\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerHeadingProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectYearRangePickerRootContext } from './YearRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearRangePickerHeadingProps>(), { as: 'div' })\n\ndefineSlots<{\n  default?: (props: {\n    /** Current year range heading */\n    headingValue: string\n  }) => any\n}>()\n\nconst rootContext = injectYearRangePickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.headingId\"\n    role=\"heading\"\n    aria-level=\"2\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n  >\n    <slot :heading-value=\"rootContext.headingValue.value\">\n      {{ rootContext.headingValue.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerHeadingProps extends PrimitiveProps {}\n</script>\n\n<script setup lang=\"ts\">\nimport { Primitive } from '@/Primitive'\nimport { injectYearRangePickerRootContext } from './YearRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearRangePickerHeadingProps>(), { as: 'div' })\n\ndefineSlots<{\n  default?: (props: {\n    /** Current year range heading */\n    headingValue: string\n  }) => any\n}>()\n\nconst rootContext = injectYearRangePickerRootContext()\n</script>\n\n<template>\n  <Primitive\n    v-bind=\"props\"\n    :id=\"rootContext.headingId\"\n    role=\"heading\"\n    aria-level=\"2\"\n    :data-disabled=\"rootContext.disabled.value ? '' : undefined\"\n  >\n    <slot :heading-value=\"rootContext.headingValue.value\">\n      {{ rootContext.headingValue.value }}\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerNextProps extends PrimitiveProps {\n  /** The function to be used for the next page. Overwrites the `nextPage` function set on the Root. */\n  nextPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface YearRangePickerNextSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectYearRangePickerRootContext } from './YearRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearRangePickerNextProps>(), { as: 'button' })\ndefineSlots<YearRangePickerNextSlot>()\n\nconst rootContext = injectYearRangePickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isNextButtonDisabled(props.nextPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.nextPage(props.nextPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Next page\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Next page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerNextProps extends PrimitiveProps {\n  /** The function to be used for the next page. Overwrites the `nextPage` function set on the Root. */\n  nextPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface YearRangePickerNextSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectYearRangePickerRootContext } from './YearRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearRangePickerNextProps>(), { as: 'button' })\ndefineSlots<YearRangePickerNextSlot>()\n\nconst rootContext = injectYearRangePickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isNextButtonDisabled(props.nextPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.nextPage(props.nextPage)\n}\n</script>\n\n<template>\n  <Primitive\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    aria-label=\"Next page\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Next page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerPrevProps extends PrimitiveProps {\n  /** The function to be used for the prev page. Overwrites the `prevPage` function set on the Root. */\n  prevPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface YearRangePickerPrevSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectYearRangePickerRootContext } from './YearRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearRangePickerPrevProps>(), { as: 'button' })\ndefineSlots<YearRangePickerPrevSlot>()\n\nconst rootContext = injectYearRangePickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isPrevButtonDisabled(props.prevPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.prevPage(props.prevPage)\n}\n</script>\n\n<template>\n  <Primitive\n    aria-label=\"Previous page\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Prev page\n    </slot>\n  </Primitive>\n</template>\n","<script lang=\"ts\">\nimport type { DateValue } from '@internationalized/date'\nimport type { PrimitiveProps } from '@/Primitive'\n\nexport interface YearRangePickerPrevProps extends PrimitiveProps {\n  /** The function to be used for the prev page. Overwrites the `prevPage` function set on the Root. */\n  prevPage?: (placeholder: DateValue) => DateValue\n}\n\nexport interface YearRangePickerPrevSlot {\n  default?: (props: {\n    /** Current disable state */\n    disabled: boolean\n  }) => any\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue'\nimport { Primitive } from '@/Primitive'\nimport { injectYearRangePickerRootContext } from './YearRangePickerRoot.vue'\n\nconst props = withDefaults(defineProps<YearRangePickerPrevProps>(), { as: 'button' })\ndefineSlots<YearRangePickerPrevSlot>()\n\nconst rootContext = injectYearRangePickerRootContext()\n\nconst disabled = computed(() => rootContext.disabled.value || rootContext.isPrevButtonDisabled(props.prevPage))\n\nfunction handleClick() {\n  if (disabled.value)\n    return\n  rootContext.prevPage(props.prevPage)\n}\n</script>\n\n<template>\n  <Primitive\n    aria-label=\"Previous page\"\n    :as=\"props.as\"\n    :as-child=\"props.asChild\"\n    :type=\"props.as === 'button' ? 'button' : undefined\"\n    :aria-disabled=\"disabled || undefined\"\n    :data-disabled=\"disabled || undefined\"\n    :disabled=\"disabled\"\n    @click=\"handleClick\"\n  >\n    <slot :disabled>\n      Prev page\n    </slot>\n  </Primitive>\n</template>\n","","require('./shared/arrays.cjs');\nrequire('./shared/browser.cjs');\nrequire('./shared/clamp.cjs');\nconst require_shared_createContext = require('./shared/createContext.cjs');\nrequire('./shared/getActiveElement.cjs');\nrequire('./shared/handleAndDispatchCustomEvent.cjs');\nrequire('./shared/isValidVNodeElement.cjs');\nrequire('./shared/nullish.cjs');\nrequire('./shared/isValueEqualOrExist.cjs');\nrequire('./shared/object.cjs');\nrequire('./shared/onFocusOutside.cjs');\nrequire('./shared/renderSlotFragments.cjs');\nrequire('./shared/trap-focus.cjs');\nrequire('./shared/useArrowNavigation.cjs');\nconst require_ConfigProvider_ConfigProvider = require('./ConfigProvider/ConfigProvider.cjs');\nconst require_shared_useBodyScrollLock = require('./shared/useBodyScrollLock.cjs');\nrequire('./shared/useComposing.cjs');\nrequire('./date/comparators.cjs');\nrequire('./date/utils.cjs');\nrequire('./date/calendar.cjs');\nrequire('./date/index.cjs');\nconst require_shared_useDateFormatter = require('./shared/useDateFormatter.cjs');\nconst require_shared_useDirection = require('./shared/useDirection.cjs');\nconst require_shared_useEmitAsProps = require('./shared/useEmitAsProps.cjs');\nconst require_shared_useFilter = require('./shared/useFilter.cjs');\nrequire('./shared/useFocusGuards.cjs');\nrequire('./shared/useFormControl.cjs');\nconst require_shared_useForwardExpose = require('./shared/useForwardExpose.cjs');\nconst require_shared_useForwardProps = require('./shared/useForwardProps.cjs');\nconst require_shared_useForwardPropsEmits = require('./shared/useForwardPropsEmits.cjs');\nrequire('./shared/useForwardRef.cjs');\nrequire('./shared/useGraceArea.cjs');\nrequire('./shared/useHideOthers.cjs');\nconst require_shared_useId = require('./shared/useId.cjs');\nrequire('./shared/useKbd.cjs');\nconst require_shared_useLocale = require('./shared/useLocale.cjs');\nrequire('./shared/useSelectionBehavior.cjs');\nrequire('./shared/useSize.cjs');\nconst require_shared_useStateMachine = require('./shared/useStateMachine.cjs');\nrequire('./shared/useTypeahead.cjs');\nconst require_shared_withDefault = require('./shared/withDefault.cjs');\nrequire('./shared/index.cjs');\nrequire('./Presence/usePresence.cjs');\nconst require_Presence_Presence = require('./Presence/Presence.cjs');\nconst require_Primitive_Slot = require('./Primitive/Slot.cjs');\nconst require_Primitive_Primitive = require('./Primitive/Primitive.cjs');\nrequire('./Primitive/usePrimitiveElement.cjs');\nconst require_Collapsible_CollapsibleRoot = require('./Collapsible/CollapsibleRoot.cjs');\nconst require_Collapsible_CollapsibleContent = require('./Collapsible/CollapsibleContent.cjs');\nconst require_Collapsible_CollapsibleTrigger = require('./Collapsible/CollapsibleTrigger.cjs');\nrequire('./shared/useSingleOrMultipleValue.cjs');\nconst require_Accordion_AccordionRoot = require('./Accordion/AccordionRoot.cjs');\nconst require_Accordion_AccordionItem = require('./Accordion/AccordionItem.cjs');\nconst require_Accordion_AccordionContent = require('./Accordion/AccordionContent.cjs');\nconst require_Accordion_AccordionHeader = require('./Accordion/AccordionHeader.cjs');\nconst require_Accordion_AccordionTrigger = require('./Accordion/AccordionTrigger.cjs');\nconst require_Dialog_DialogRoot = require('./Dialog/DialogRoot.cjs');\nconst require_Dialog_DialogClose = require('./Dialog/DialogClose.cjs');\nrequire('./DismissableLayer/utils.cjs');\nrequire('./DismissableLayer/DismissableLayer.cjs');\nrequire('./DismissableLayer/DismissableLayerBranch.cjs');\nrequire('./FocusScope/stack.cjs');\nrequire('./FocusScope/utils.cjs');\nconst require_FocusScope_FocusScope = require('./FocusScope/FocusScope.cjs');\nrequire('./Menu/utils.cjs');\nrequire('./Dialog/utils.cjs');\nrequire('./Dialog/DialogContentImpl.cjs');\nrequire('./Dialog/DialogContentModal.cjs');\nrequire('./Dialog/DialogContentNonModal.cjs');\nconst require_Dialog_DialogContent = require('./Dialog/DialogContent.cjs');\nconst require_Dialog_DialogDescription = require('./Dialog/DialogDescription.cjs');\nrequire('./Dialog/DialogOverlayImpl.cjs');\nconst require_Dialog_DialogOverlay = require('./Dialog/DialogOverlay.cjs');\nrequire('./Teleport/Teleport.cjs');\nconst require_Dialog_DialogPortal = require('./Dialog/DialogPortal.cjs');\nconst require_Dialog_DialogTitle = require('./Dialog/DialogTitle.cjs');\nconst require_Dialog_DialogTrigger = require('./Dialog/DialogTrigger.cjs');\nconst require_AlertDialog_AlertDialogAction = require('./AlertDialog/AlertDialogAction.cjs');\nconst require_AlertDialog_AlertDialogContent = require('./AlertDialog/AlertDialogContent.cjs');\nconst require_AlertDialog_AlertDialogCancel = require('./AlertDialog/AlertDialogCancel.cjs');\nconst require_AlertDialog_AlertDialogDescription = require('./AlertDialog/AlertDialogDescription.cjs');\nconst require_AlertDialog_AlertDialogOverlay = require('./AlertDialog/AlertDialogOverlay.cjs');\nconst require_AlertDialog_AlertDialogPortal = require('./AlertDialog/AlertDialogPortal.cjs');\nconst require_AlertDialog_AlertDialogRoot = require('./AlertDialog/AlertDialogRoot.cjs');\nconst require_AlertDialog_AlertDialogTitle = require('./AlertDialog/AlertDialogTitle.cjs');\nconst require_AlertDialog_AlertDialogTrigger = require('./AlertDialog/AlertDialogTrigger.cjs');\nconst require_AspectRatio_AspectRatio = require('./AspectRatio/AspectRatio.cjs');\nrequire('./Collection/Collection.cjs');\nconst require_VisuallyHidden_VisuallyHidden = require('./VisuallyHidden/VisuallyHidden.cjs');\nrequire('./VisuallyHidden/VisuallyHiddenInputBubble.cjs');\nrequire('./VisuallyHidden/VisuallyHiddenInput.cjs');\nrequire('./Listbox/utils.cjs');\nrequire('./RovingFocus/utils.cjs');\nconst require_Listbox_ListboxRoot = require('./Listbox/ListboxRoot.cjs');\nconst require_Listbox_ListboxContent = require('./Listbox/ListboxContent.cjs');\nconst require_Listbox_ListboxFilter = require('./Listbox/ListboxFilter.cjs');\nconst require_Listbox_ListboxGroup = require('./Listbox/ListboxGroup.cjs');\nconst require_Listbox_ListboxGroupLabel = require('./Listbox/ListboxGroupLabel.cjs');\nconst require_Listbox_ListboxItem = require('./Listbox/ListboxItem.cjs');\nconst require_Listbox_ListboxItemIndicator = require('./Listbox/ListboxItemIndicator.cjs');\nconst require_Listbox_ListboxVirtualizer = require('./Listbox/ListboxVirtualizer.cjs');\nrequire('./Popper/PopperRoot.cjs');\nrequire('./Popper/PopperAnchor.cjs');\nrequire('./component/Arrow.cjs');\nrequire('./Popper/utils.cjs');\nrequire('./Popper/PopperContent.cjs');\nrequire('./Popper/PopperArrow.cjs');\nconst require_Combobox_ComboboxRoot = require('./Combobox/ComboboxRoot.cjs');\nconst require_Autocomplete_AutocompleteRoot = require('./Autocomplete/AutocompleteRoot.cjs');\nconst require_Autocomplete_AutocompleteInput = require('./Autocomplete/AutocompleteInput.cjs');\nconst require_Combobox_ComboboxAnchor = require('./Combobox/ComboboxAnchor.cjs');\nrequire('./Combobox/ComboboxContentImpl.cjs');\nconst require_Combobox_ComboboxArrow = require('./Combobox/ComboboxArrow.cjs');\nconst require_Combobox_ComboboxCancel = require('./Combobox/ComboboxCancel.cjs');\nconst require_Combobox_ComboboxContent = require('./Combobox/ComboboxContent.cjs');\nconst require_Combobox_ComboboxEmpty = require('./Combobox/ComboboxEmpty.cjs');\nconst require_Combobox_ComboboxGroup = require('./Combobox/ComboboxGroup.cjs');\nconst require_Combobox_ComboboxInput = require('./Combobox/ComboboxInput.cjs');\nconst require_Combobox_ComboboxItem = require('./Combobox/ComboboxItem.cjs');\nconst require_Combobox_ComboboxItemIndicator = require('./Combobox/ComboboxItemIndicator.cjs');\nconst require_Combobox_ComboboxLabel = require('./Combobox/ComboboxLabel.cjs');\nconst require_Combobox_ComboboxPortal = require('./Combobox/ComboboxPortal.cjs');\nconst require_Combobox_ComboboxSeparator = require('./Combobox/ComboboxSeparator.cjs');\nconst require_Combobox_ComboboxTrigger = require('./Combobox/ComboboxTrigger.cjs');\nrequire('./shared/useNonce.cjs');\nconst require_Combobox_ComboboxViewport = require('./Combobox/ComboboxViewport.cjs');\nconst require_Combobox_ComboboxVirtualizer = require('./Combobox/ComboboxVirtualizer.cjs');\nconst require_Avatar_AvatarRoot = require('./Avatar/AvatarRoot.cjs');\nconst require_Avatar_AvatarFallback = require('./Avatar/AvatarFallback.cjs');\nrequire('./Avatar/utils.cjs');\nconst require_Avatar_AvatarImage = require('./Avatar/AvatarImage.cjs');\nrequire('./date/parser.cjs');\nrequire('./date/parts.cjs');\nrequire('./date/placeholders.cjs');\nrequire('./date/segment.cjs');\nrequire('./date/useDateField.cjs');\nrequire('./Calendar/useCalendar.cjs');\nconst require_Calendar_CalendarRoot = require('./Calendar/CalendarRoot.cjs');\nconst require_Calendar_CalendarCell = require('./Calendar/CalendarCell.cjs');\nconst require_Calendar_CalendarCellTrigger = require('./Calendar/CalendarCellTrigger.cjs');\nconst require_Calendar_CalendarGrid = require('./Calendar/CalendarGrid.cjs');\nconst require_Calendar_CalendarGridBody = require('./Calendar/CalendarGridBody.cjs');\nconst require_Calendar_CalendarGridHead = require('./Calendar/CalendarGridHead.cjs');\nconst require_Calendar_CalendarGridRow = require('./Calendar/CalendarGridRow.cjs');\nconst require_Calendar_CalendarHeadCell = require('./Calendar/CalendarHeadCell.cjs');\nconst require_Calendar_CalendarHeader = require('./Calendar/CalendarHeader.cjs');\nconst require_Calendar_CalendarHeading = require('./Calendar/CalendarHeading.cjs');\nconst require_Calendar_CalendarNext = require('./Calendar/CalendarNext.cjs');\nconst require_Calendar_CalendarPrev = require('./Calendar/CalendarPrev.cjs');\nconst require_RovingFocus_RovingFocusGroup = require('./RovingFocus/RovingFocusGroup.cjs');\nconst require_RovingFocus_RovingFocusItem = require('./RovingFocus/RovingFocusItem.cjs');\nconst require_Checkbox_CheckboxGroupRoot = require('./Checkbox/CheckboxGroupRoot.cjs');\nrequire('./Checkbox/utils.cjs');\nconst require_Checkbox_CheckboxRoot = require('./Checkbox/CheckboxRoot.cjs');\nconst require_Checkbox_CheckboxIndicator = require('./Checkbox/CheckboxIndicator.cjs');\nconst require_color_convert = require('./color/convert.cjs');\nconst require_color_channel = require('./color/channel.cjs');\nconst require_color_gradient = require('./color/gradient.cjs');\nconst require_color_parse = require('./color/parse.cjs');\nrequire('./color/utils.cjs');\nconst require_ColorArea_ColorAreaRoot = require('./ColorArea/ColorAreaRoot.cjs');\nrequire('./ColorArea/utils.cjs');\nconst require_ColorArea_ColorAreaArea = require('./ColorArea/ColorAreaArea.cjs');\nconst require_ColorArea_ColorAreaThumb = require('./ColorArea/ColorAreaThumb.cjs');\nconst require_ColorField_ColorFieldRoot = require('./ColorField/ColorFieldRoot.cjs');\nconst require_ColorField_ColorFieldInput = require('./ColorField/ColorFieldInput.cjs');\nrequire('./Slider/utils.cjs');\nrequire('./Slider/SliderImpl.cjs');\nrequire('./Slider/SliderHorizontal.cjs');\nrequire('./Slider/SliderVertical.cjs');\nconst require_Slider_SliderRoot = require('./Slider/SliderRoot.cjs');\nconst require_Slider_SliderRange = require('./Slider/SliderRange.cjs');\nrequire('./Slider/SliderThumbImpl.cjs');\nconst require_Slider_SliderThumb = require('./Slider/SliderThumb.cjs');\nconst require_Slider_SliderTrack = require('./Slider/SliderTrack.cjs');\nconst require_ColorSlider_ColorSliderRoot = require('./ColorSlider/ColorSliderRoot.cjs');\nconst require_ColorSlider_ColorSliderThumb = require('./ColorSlider/ColorSliderThumb.cjs');\nconst require_ColorSlider_ColorSliderTrack = require('./ColorSlider/ColorSliderTrack.cjs');\nconst require_ColorSwatch_ColorSwatch = require('./ColorSwatch/ColorSwatch.cjs');\nconst require_ColorSwatchPicker_ColorSwatchPickerItem = require('./ColorSwatchPicker/ColorSwatchPickerItem.cjs');\nconst require_ColorSwatchPicker_ColorSwatchPickerItemIndicator = require('./ColorSwatchPicker/ColorSwatchPickerItemIndicator.cjs');\nconst require_ColorSwatchPicker_ColorSwatchPickerItemSwatch = require('./ColorSwatchPicker/ColorSwatchPickerItemSwatch.cjs');\nconst require_ColorSwatchPicker_ColorSwatchPickerRoot = require('./ColorSwatchPicker/ColorSwatchPickerRoot.cjs');\nrequire('./Menu/MenuAnchor.cjs');\nrequire('./Menu/MenuArrow.cjs');\nrequire('./shared/useIsUsingKeyboard.cjs');\nrequire('./Menu/MenuRoot.cjs');\nrequire('./Menu/MenuContentImpl.cjs');\nrequire('./Menu/MenuItemImpl.cjs');\nrequire('./Menu/MenuItem.cjs');\nrequire('./Menu/MenuItemIndicator.cjs');\nrequire('./Menu/MenuCheckboxItem.cjs');\nrequire('./Menu/MenuRootContentModal.cjs');\nrequire('./Menu/MenuRootContentNonModal.cjs');\nrequire('./Menu/MenuContent.cjs');\nrequire('./Menu/MenuGroup.cjs');\nrequire('./Menu/MenuLabel.cjs');\nrequire('./Menu/MenuPortal.cjs');\nrequire('./Menu/MenuRadioGroup.cjs');\nrequire('./Menu/MenuRadioItem.cjs');\nrequire('./Menu/MenuSeparator.cjs');\nrequire('./Menu/MenuSub.cjs');\nrequire('./Menu/MenuSubContent.cjs');\nrequire('./Menu/MenuSubTrigger.cjs');\nconst require_ContextMenu_ContextMenuArrow = require('./ContextMenu/ContextMenuArrow.cjs');\nconst require_ContextMenu_ContextMenuCheckboxItem = require('./ContextMenu/ContextMenuCheckboxItem.cjs');\nconst require_ContextMenu_ContextMenuRoot = require('./ContextMenu/ContextMenuRoot.cjs');\nconst require_ContextMenu_ContextMenuContent = require('./ContextMenu/ContextMenuContent.cjs');\nconst require_ContextMenu_ContextMenuGroup = require('./ContextMenu/ContextMenuGroup.cjs');\nconst require_ContextMenu_ContextMenuItem = require('./ContextMenu/ContextMenuItem.cjs');\nconst require_ContextMenu_ContextMenuItemIndicator = require('./ContextMenu/ContextMenuItemIndicator.cjs');\nconst require_ContextMenu_ContextMenuLabel = require('./ContextMenu/ContextMenuLabel.cjs');\nconst require_ContextMenu_ContextMenuPortal = require('./ContextMenu/ContextMenuPortal.cjs');\nconst require_ContextMenu_ContextMenuRadioGroup = require('./ContextMenu/ContextMenuRadioGroup.cjs');\nconst require_ContextMenu_ContextMenuRadioItem = require('./ContextMenu/ContextMenuRadioItem.cjs');\nconst require_ContextMenu_ContextMenuSeparator = require('./ContextMenu/ContextMenuSeparator.cjs');\nconst require_ContextMenu_ContextMenuSub = require('./ContextMenu/ContextMenuSub.cjs');\nconst require_ContextMenu_ContextMenuSubContent = require('./ContextMenu/ContextMenuSubContent.cjs');\nconst require_ContextMenu_ContextMenuSubTrigger = require('./ContextMenu/ContextMenuSubTrigger.cjs');\nrequire('./ContextMenu/utils.cjs');\nconst require_ContextMenu_ContextMenuTrigger = require('./ContextMenu/ContextMenuTrigger.cjs');\nconst require_DateField_DateFieldRoot = require('./DateField/DateFieldRoot.cjs');\nconst require_DateField_DateFieldInput = require('./DateField/DateFieldInput.cjs');\nconst require_DatePicker_DatePickerAnchor = require('./DatePicker/DatePickerAnchor.cjs');\nconst require_DatePicker_DatePickerArrow = require('./DatePicker/DatePickerArrow.cjs');\nconst require_DatePicker_DatePickerRoot = require('./DatePicker/DatePickerRoot.cjs');\nconst require_DatePicker_DatePickerCalendar = require('./DatePicker/DatePickerCalendar.cjs');\nconst require_DatePicker_DatePickerCell = require('./DatePicker/DatePickerCell.cjs');\nconst require_DatePicker_DatePickerCellTrigger = require('./DatePicker/DatePickerCellTrigger.cjs');\nconst require_DatePicker_DatePickerClose = require('./DatePicker/DatePickerClose.cjs');\nconst require_DatePicker_DatePickerContent = require('./DatePicker/DatePickerContent.cjs');\nconst require_DatePicker_DatePickerField = require('./DatePicker/DatePickerField.cjs');\nconst require_DatePicker_DatePickerGrid = require('./DatePicker/DatePickerGrid.cjs');\nconst require_DatePicker_DatePickerGridBody = require('./DatePicker/DatePickerGridBody.cjs');\nconst require_DatePicker_DatePickerGridHead = require('./DatePicker/DatePickerGridHead.cjs');\nconst require_DatePicker_DatePickerGridRow = require('./DatePicker/DatePickerGridRow.cjs');\nconst require_DatePicker_DatePickerHeadCell = require('./DatePicker/DatePickerHeadCell.cjs');\nconst require_DatePicker_DatePickerHeader = require('./DatePicker/DatePickerHeader.cjs');\nconst require_DatePicker_DatePickerHeading = require('./DatePicker/DatePickerHeading.cjs');\nconst require_DatePicker_DatePickerInput = require('./DatePicker/DatePickerInput.cjs');\nconst require_DatePicker_DatePickerNext = require('./DatePicker/DatePickerNext.cjs');\nconst require_DatePicker_DatePickerPrev = require('./DatePicker/DatePickerPrev.cjs');\nconst require_DatePicker_DatePickerTrigger = require('./DatePicker/DatePickerTrigger.cjs');\nconst require_DateRangeField_DateRangeFieldRoot = require('./DateRangeField/DateRangeFieldRoot.cjs');\nconst require_DateRangeField_DateRangeFieldInput = require('./DateRangeField/DateRangeFieldInput.cjs');\nconst require_DateRangePicker_DateRangePickerAnchor = require('./DateRangePicker/DateRangePickerAnchor.cjs');\nconst require_DateRangePicker_DateRangePickerArrow = require('./DateRangePicker/DateRangePickerArrow.cjs');\nconst require_DateRangePicker_DateRangePickerRoot = require('./DateRangePicker/DateRangePickerRoot.cjs');\nconst require_DateRangePicker_DateRangePickerCalendar = require('./DateRangePicker/DateRangePickerCalendar.cjs');\nconst require_DateRangePicker_DateRangePickerCell = require('./DateRangePicker/DateRangePickerCell.cjs');\nconst require_DateRangePicker_DateRangePickerCellTrigger = require('./DateRangePicker/DateRangePickerCellTrigger.cjs');\nconst require_DateRangePicker_DateRangePickerClose = require('./DateRangePicker/DateRangePickerClose.cjs');\nconst require_DateRangePicker_DateRangePickerContent = require('./DateRangePicker/DateRangePickerContent.cjs');\nconst require_DateRangePicker_DateRangePickerField = require('./DateRangePicker/DateRangePickerField.cjs');\nconst require_DateRangePicker_DateRangePickerGrid = require('./DateRangePicker/DateRangePickerGrid.cjs');\nconst require_DateRangePicker_DateRangePickerGridBody = require('./DateRangePicker/DateRangePickerGridBody.cjs');\nconst require_DateRangePicker_DateRangePickerGridHead = require('./DateRangePicker/DateRangePickerGridHead.cjs');\nconst require_DateRangePicker_DateRangePickerGridRow = require('./DateRangePicker/DateRangePickerGridRow.cjs');\nconst require_DateRangePicker_DateRangePickerHeadCell = require('./DateRangePicker/DateRangePickerHeadCell.cjs');\nconst require_DateRangePicker_DateRangePickerHeader = require('./DateRangePicker/DateRangePickerHeader.cjs');\nconst require_DateRangePicker_DateRangePickerHeading = require('./DateRangePicker/DateRangePickerHeading.cjs');\nconst require_DateRangePicker_DateRangePickerInput = require('./DateRangePicker/DateRangePickerInput.cjs');\nconst require_DateRangePicker_DateRangePickerNext = require('./DateRangePicker/DateRangePickerNext.cjs');\nconst require_DateRangePicker_DateRangePickerPrev = require('./DateRangePicker/DateRangePickerPrev.cjs');\nconst require_DateRangePicker_DateRangePickerTrigger = require('./DateRangePicker/DateRangePickerTrigger.cjs');\nconst require_DropdownMenu_DropdownMenuArrow = require('./DropdownMenu/DropdownMenuArrow.cjs');\nconst require_DropdownMenu_DropdownMenuCheckboxItem = require('./DropdownMenu/DropdownMenuCheckboxItem.cjs');\nconst require_DropdownMenu_DropdownMenuRoot = require('./DropdownMenu/DropdownMenuRoot.cjs');\nconst require_DropdownMenu_DropdownMenuContent = require('./DropdownMenu/DropdownMenuContent.cjs');\nconst require_DropdownMenu_DropdownMenuFilter = require('./DropdownMenu/DropdownMenuFilter.cjs');\nconst require_DropdownMenu_DropdownMenuGroup = require('./DropdownMenu/DropdownMenuGroup.cjs');\nconst require_DropdownMenu_DropdownMenuItem = require('./DropdownMenu/DropdownMenuItem.cjs');\nconst require_DropdownMenu_DropdownMenuItemIndicator = require('./DropdownMenu/DropdownMenuItemIndicator.cjs');\nconst require_DropdownMenu_DropdownMenuLabel = require('./DropdownMenu/DropdownMenuLabel.cjs');\nconst require_DropdownMenu_DropdownMenuPortal = require('./DropdownMenu/DropdownMenuPortal.cjs');\nconst require_DropdownMenu_DropdownMenuRadioGroup = require('./DropdownMenu/DropdownMenuRadioGroup.cjs');\nconst require_DropdownMenu_DropdownMenuRadioItem = require('./DropdownMenu/DropdownMenuRadioItem.cjs');\nconst require_DropdownMenu_DropdownMenuSeparator = require('./DropdownMenu/DropdownMenuSeparator.cjs');\nconst require_DropdownMenu_DropdownMenuSub = require('./DropdownMenu/DropdownMenuSub.cjs');\nconst require_DropdownMenu_DropdownMenuSubContent = require('./DropdownMenu/DropdownMenuSubContent.cjs');\nconst require_DropdownMenu_DropdownMenuSubTrigger = require('./DropdownMenu/DropdownMenuSubTrigger.cjs');\nconst require_DropdownMenu_DropdownMenuTrigger = require('./DropdownMenu/DropdownMenuTrigger.cjs');\nconst require_Editable_EditableRoot = require('./Editable/EditableRoot.cjs');\nconst require_Editable_EditableArea = require('./Editable/EditableArea.cjs');\nconst require_Editable_EditableCancelTrigger = require('./Editable/EditableCancelTrigger.cjs');\nconst require_Editable_EditableEditTrigger = require('./Editable/EditableEditTrigger.cjs');\nconst require_Editable_EditableInput = require('./Editable/EditableInput.cjs');\nconst require_Editable_EditablePreview = require('./Editable/EditablePreview.cjs');\nconst require_Editable_EditableSubmitTrigger = require('./Editable/EditableSubmitTrigger.cjs');\nconst require_HoverCard_HoverCardArrow = require('./HoverCard/HoverCardArrow.cjs');\nconst require_HoverCard_HoverCardRoot = require('./HoverCard/HoverCardRoot.cjs');\nrequire('./HoverCard/utils.cjs');\nrequire('./HoverCard/HoverCardContentImpl.cjs');\nconst require_HoverCard_HoverCardContent = require('./HoverCard/HoverCardContent.cjs');\nconst require_HoverCard_HoverCardPortal = require('./HoverCard/HoverCardPortal.cjs');\nconst require_HoverCard_HoverCardTrigger = require('./HoverCard/HoverCardTrigger.cjs');\nconst require_Label_Label = require('./Label/Label.cjs');\nconst require_Menubar_MenubarArrow = require('./Menubar/MenubarArrow.cjs');\nconst require_Menubar_MenubarCheckboxItem = require('./Menubar/MenubarCheckboxItem.cjs');\nconst require_Menubar_MenubarRoot = require('./Menubar/MenubarRoot.cjs');\nconst require_Menubar_MenubarMenu = require('./Menubar/MenubarMenu.cjs');\nconst require_Menubar_MenubarContent = require('./Menubar/MenubarContent.cjs');\nconst require_Menubar_MenubarGroup = require('./Menubar/MenubarGroup.cjs');\nconst require_Menubar_MenubarItem = require('./Menubar/MenubarItem.cjs');\nconst require_Menubar_MenubarItemIndicator = require('./Menubar/MenubarItemIndicator.cjs');\nconst require_Menubar_MenubarLabel = require('./Menubar/MenubarLabel.cjs');\nconst require_Menubar_MenubarPortal = require('./Menubar/MenubarPortal.cjs');\nconst require_Menubar_MenubarRadioGroup = require('./Menubar/MenubarRadioGroup.cjs');\nconst require_Menubar_MenubarRadioItem = require('./Menubar/MenubarRadioItem.cjs');\nconst require_Menubar_MenubarSeparator = require('./Menubar/MenubarSeparator.cjs');\nconst require_Menubar_MenubarSub = require('./Menubar/MenubarSub.cjs');\nconst require_Menubar_MenubarSubContent = require('./Menubar/MenubarSubContent.cjs');\nconst require_Menubar_MenubarSubTrigger = require('./Menubar/MenubarSubTrigger.cjs');\nconst require_Menubar_MenubarTrigger = require('./Menubar/MenubarTrigger.cjs');\nrequire('./MonthPicker/useMonthPicker.cjs');\nconst require_MonthPicker_MonthPickerRoot = require('./MonthPicker/MonthPickerRoot.cjs');\nconst require_MonthPicker_MonthPickerCell = require('./MonthPicker/MonthPickerCell.cjs');\nconst require_MonthPicker_MonthPickerCellTrigger = require('./MonthPicker/MonthPickerCellTrigger.cjs');\nconst require_MonthPicker_MonthPickerGrid = require('./MonthPicker/MonthPickerGrid.cjs');\nconst require_MonthPicker_MonthPickerGridBody = require('./MonthPicker/MonthPickerGridBody.cjs');\nconst require_MonthPicker_MonthPickerGridRow = require('./MonthPicker/MonthPickerGridRow.cjs');\nconst require_MonthPicker_MonthPickerHeader = require('./MonthPicker/MonthPickerHeader.cjs');\nconst require_MonthPicker_MonthPickerHeading = require('./MonthPicker/MonthPickerHeading.cjs');\nconst require_MonthPicker_MonthPickerNext = require('./MonthPicker/MonthPickerNext.cjs');\nconst require_MonthPicker_MonthPickerPrev = require('./MonthPicker/MonthPickerPrev.cjs');\nrequire('./MonthRangePicker/useRangeMonthPicker.cjs');\nconst require_MonthRangePicker_MonthRangePickerRoot = require('./MonthRangePicker/MonthRangePickerRoot.cjs');\nconst require_MonthRangePicker_MonthRangePickerCell = require('./MonthRangePicker/MonthRangePickerCell.cjs');\nconst require_MonthRangePicker_MonthRangePickerCellTrigger = require('./MonthRangePicker/MonthRangePickerCellTrigger.cjs');\nconst require_MonthRangePicker_MonthRangePickerGrid = require('./MonthRangePicker/MonthRangePickerGrid.cjs');\nconst require_MonthRangePicker_MonthRangePickerGridBody = require('./MonthRangePicker/MonthRangePickerGridBody.cjs');\nconst require_MonthRangePicker_MonthRangePickerGridRow = require('./MonthRangePicker/MonthRangePickerGridRow.cjs');\nconst require_MonthRangePicker_MonthRangePickerHeader = require('./MonthRangePicker/MonthRangePickerHeader.cjs');\nconst require_MonthRangePicker_MonthRangePickerHeading = require('./MonthRangePicker/MonthRangePickerHeading.cjs');\nconst require_MonthRangePicker_MonthRangePickerNext = require('./MonthRangePicker/MonthRangePickerNext.cjs');\nconst require_MonthRangePicker_MonthRangePickerPrev = require('./MonthRangePicker/MonthRangePickerPrev.cjs');\nrequire('./NavigationMenu/utils.cjs');\nconst require_NavigationMenu_NavigationMenuRoot = require('./NavigationMenu/NavigationMenuRoot.cjs');\nconst require_NavigationMenu_NavigationMenuItem = require('./NavigationMenu/NavigationMenuItem.cjs');\nrequire('./NavigationMenu/NavigationMenuContentImpl.cjs');\nconst require_NavigationMenu_NavigationMenuContent = require('./NavigationMenu/NavigationMenuContent.cjs');\nconst require_NavigationMenu_NavigationMenuIndicator = require('./NavigationMenu/NavigationMenuIndicator.cjs');\nconst require_NavigationMenu_NavigationMenuLink = require('./NavigationMenu/NavigationMenuLink.cjs');\nconst require_NavigationMenu_NavigationMenuList = require('./NavigationMenu/NavigationMenuList.cjs');\nconst require_NavigationMenu_NavigationMenuSub = require('./NavigationMenu/NavigationMenuSub.cjs');\nconst require_NavigationMenu_NavigationMenuTrigger = require('./NavigationMenu/NavigationMenuTrigger.cjs');\nconst require_NavigationMenu_NavigationMenuViewport = require('./NavigationMenu/NavigationMenuViewport.cjs');\nrequire('./NumberField/utils.cjs');\nconst require_NumberField_NumberFieldRoot = require('./NumberField/NumberFieldRoot.cjs');\nconst require_NumberField_NumberFieldDecrement = require('./NumberField/NumberFieldDecrement.cjs');\nconst require_NumberField_NumberFieldIncrement = require('./NumberField/NumberFieldIncrement.cjs');\nconst require_NumberField_NumberFieldInput = require('./NumberField/NumberFieldInput.cjs');\nconst require_Pagination_PaginationEllipsis = require('./Pagination/PaginationEllipsis.cjs');\nconst require_Pagination_PaginationRoot = require('./Pagination/PaginationRoot.cjs');\nconst require_Pagination_PaginationFirst = require('./Pagination/PaginationFirst.cjs');\nconst require_Pagination_PaginationLast = require('./Pagination/PaginationLast.cjs');\nrequire('./Pagination/utils.cjs');\nconst require_Pagination_PaginationList = require('./Pagination/PaginationList.cjs');\nconst require_Pagination_PaginationListItem = require('./Pagination/PaginationListItem.cjs');\nconst require_Pagination_PaginationNext = require('./Pagination/PaginationNext.cjs');\nconst require_Pagination_PaginationPrev = require('./Pagination/PaginationPrev.cjs');\nconst require_PinInput_PinInputRoot = require('./PinInput/PinInputRoot.cjs');\nconst require_PinInput_PinInputInput = require('./PinInput/PinInputInput.cjs');\nconst require_Popover_PopoverRoot = require('./Popover/PopoverRoot.cjs');\nconst require_Popover_PopoverAnchor = require('./Popover/PopoverAnchor.cjs');\nconst require_Popover_PopoverArrow = require('./Popover/PopoverArrow.cjs');\nconst require_Popover_PopoverClose = require('./Popover/PopoverClose.cjs');\nrequire('./Popover/PopoverContentImpl.cjs');\nrequire('./Popover/PopoverContentModal.cjs');\nrequire('./Popover/PopoverContentNonModal.cjs');\nconst require_Popover_PopoverContent = require('./Popover/PopoverContent.cjs');\nconst require_Popover_PopoverPortal = require('./Popover/PopoverPortal.cjs');\nconst require_Popover_PopoverTrigger = require('./Popover/PopoverTrigger.cjs');\nconst require_Progress_ProgressRoot = require('./Progress/ProgressRoot.cjs');\nconst require_Progress_ProgressIndicator = require('./Progress/ProgressIndicator.cjs');\nrequire('./RadioGroup/utils.cjs');\nrequire('./RadioGroup/Radio.cjs');\nconst require_RadioGroup_RadioGroupRoot = require('./RadioGroup/RadioGroupRoot.cjs');\nconst require_RadioGroup_RadioGroupItem = require('./RadioGroup/RadioGroupItem.cjs');\nconst require_RadioGroup_RadioGroupIndicator = require('./RadioGroup/RadioGroupIndicator.cjs');\nrequire('./RangeCalendar/useRangeCalendar.cjs');\nconst require_RangeCalendar_RangeCalendarRoot = require('./RangeCalendar/RangeCalendarRoot.cjs');\nconst require_RangeCalendar_RangeCalendarCell = require('./RangeCalendar/RangeCalendarCell.cjs');\nconst require_RangeCalendar_RangeCalendarCellTrigger = require('./RangeCalendar/RangeCalendarCellTrigger.cjs');\nconst require_RangeCalendar_RangeCalendarGrid = require('./RangeCalendar/RangeCalendarGrid.cjs');\nconst require_RangeCalendar_RangeCalendarGridBody = require('./RangeCalendar/RangeCalendarGridBody.cjs');\nconst require_RangeCalendar_RangeCalendarGridHead = require('./RangeCalendar/RangeCalendarGridHead.cjs');\nconst require_RangeCalendar_RangeCalendarGridRow = require('./RangeCalendar/RangeCalendarGridRow.cjs');\nconst require_RangeCalendar_RangeCalendarHeadCell = require('./RangeCalendar/RangeCalendarHeadCell.cjs');\nconst require_RangeCalendar_RangeCalendarHeader = require('./RangeCalendar/RangeCalendarHeader.cjs');\nconst require_RangeCalendar_RangeCalendarHeading = require('./RangeCalendar/RangeCalendarHeading.cjs');\nconst require_RangeCalendar_RangeCalendarNext = require('./RangeCalendar/RangeCalendarNext.cjs');\nconst require_RangeCalendar_RangeCalendarPrev = require('./RangeCalendar/RangeCalendarPrev.cjs');\nconst require_ScrollArea_ScrollAreaRoot = require('./ScrollArea/ScrollAreaRoot.cjs');\nrequire('./ScrollArea/ScrollAreaCornerImpl.cjs');\nconst require_ScrollArea_ScrollAreaCorner = require('./ScrollArea/ScrollAreaCorner.cjs');\nrequire('./ScrollArea/utils.cjs');\nrequire('./ScrollArea/ScrollAreaScrollbarImpl.cjs');\nrequire('./ScrollArea/ScrollAreaScrollbarX.cjs');\nrequire('./ScrollArea/ScrollAreaScrollbarY.cjs');\nrequire('./ScrollArea/ScrollAreaScrollbarVisible.cjs');\nrequire('./ScrollArea/ScrollAreaScrollbarAuto.cjs');\nconst require_ScrollArea_ScrollAreaScrollbarGlimpse = require('./ScrollArea/ScrollAreaScrollbarGlimpse.cjs');\nrequire('./ScrollArea/ScrollAreaScrollbarHover.cjs');\nrequire('./ScrollArea/ScrollAreaScrollbarScroll.cjs');\nconst require_ScrollArea_ScrollAreaScrollbar = require('./ScrollArea/ScrollAreaScrollbar.cjs');\nconst require_ScrollArea_ScrollAreaThumb = require('./ScrollArea/ScrollAreaThumb.cjs');\nconst require_ScrollArea_ScrollAreaViewport = require('./ScrollArea/ScrollAreaViewport.cjs');\nrequire('./Select/BubbleSelect.cjs');\nrequire('./Select/utils.cjs');\nconst require_Select_SelectRoot = require('./Select/SelectRoot.cjs');\nrequire('./Select/SelectItemAlignedPosition.cjs');\nrequire('./Select/SelectPopperPosition.cjs');\nrequire('./Select/SelectContentImpl.cjs');\nconst require_Select_SelectArrow = require('./Select/SelectArrow.cjs');\nrequire('./Select/SelectProvider.cjs');\nconst require_Select_SelectContent = require('./Select/SelectContent.cjs');\nconst require_Select_SelectGroup = require('./Select/SelectGroup.cjs');\nconst require_Select_SelectIcon = require('./Select/SelectIcon.cjs');\nconst require_Select_SelectItem = require('./Select/SelectItem.cjs');\nconst require_Select_SelectItemIndicator = require('./Select/SelectItemIndicator.cjs');\nconst require_Select_SelectItemText = require('./Select/SelectItemText.cjs');\nconst require_Select_SelectLabel = require('./Select/SelectLabel.cjs');\nconst require_Select_SelectPortal = require('./Select/SelectPortal.cjs');\nrequire('./Select/SelectScrollButtonImpl.cjs');\nconst require_Select_SelectScrollDownButton = require('./Select/SelectScrollDownButton.cjs');\nconst require_Select_SelectScrollUpButton = require('./Select/SelectScrollUpButton.cjs');\nconst require_Select_SelectSeparator = require('./Select/SelectSeparator.cjs');\nconst require_Select_SelectTrigger = require('./Select/SelectTrigger.cjs');\nconst require_Select_SelectValue = require('./Select/SelectValue.cjs');\nconst require_Select_SelectViewport = require('./Select/SelectViewport.cjs');\nrequire('./component/BaseSeparator.cjs');\nconst require_Separator_Separator = require('./Separator/Separator.cjs');\nrequire('./utils/assert.cjs');\nrequire('./utils/dom.cjs');\nrequire('./utils/events.cjs');\nrequire('./utils/calculate.cjs');\nrequire('./utils/constants.cjs');\nrequire('./utils/compare.cjs');\nrequire('./utils/callPanelCallbacks.cjs');\nrequire('./utils/debounce.cjs');\nrequire('./utils/resizePanel.cjs');\nrequire('./utils/layout.cjs');\nrequire('./utils/pivot.cjs');\nrequire('./utils/rects.cjs');\nrequire('./utils/stackingOrder.cjs');\nrequire('./utils/style.cjs');\nrequire('./utils/registry.cjs');\nrequire('./utils/units.cjs');\nrequire('./utils/validation.cjs');\nrequire('./composables/useWindowSplitterPanelGroupBehavior.cjs');\nrequire('./utils/storage.cjs');\nconst require_Splitter_SplitterGroup = require('./Splitter/SplitterGroup.cjs');\nconst require_Splitter_SplitterPanel = require('./Splitter/SplitterPanel.cjs');\nrequire('./composables/useWindowSplitterBehavior.cjs');\nconst require_Splitter_SplitterResizeHandle = require('./Splitter/SplitterResizeHandle.cjs');\nconst require_Stepper_StepperRoot = require('./Stepper/StepperRoot.cjs');\nconst require_Stepper_StepperItem = require('./Stepper/StepperItem.cjs');\nconst require_Stepper_StepperDescription = require('./Stepper/StepperDescription.cjs');\nconst require_Stepper_StepperIndicator = require('./Stepper/StepperIndicator.cjs');\nconst require_Stepper_StepperSeparator = require('./Stepper/StepperSeparator.cjs');\nconst require_Stepper_StepperTitle = require('./Stepper/StepperTitle.cjs');\nconst require_Stepper_StepperTrigger = require('./Stepper/StepperTrigger.cjs');\nconst require_Switch_SwitchRoot = require('./Switch/SwitchRoot.cjs');\nconst require_Switch_SwitchThumb = require('./Switch/SwitchThumb.cjs');\nconst require_Tabs_TabsRoot = require('./Tabs/TabsRoot.cjs');\nrequire('./Tabs/utils.cjs');\nconst require_Tabs_TabsContent = require('./Tabs/TabsContent.cjs');\nconst require_Tabs_TabsIndicator = require('./Tabs/TabsIndicator.cjs');\nconst require_Tabs_TabsList = require('./Tabs/TabsList.cjs');\nconst require_Tabs_TabsTrigger = require('./Tabs/TabsTrigger.cjs');\nconst require_TagsInput_TagsInputRoot = require('./TagsInput/TagsInputRoot.cjs');\nconst require_TagsInput_TagsInputClear = require('./TagsInput/TagsInputClear.cjs');\nconst require_TagsInput_TagsInputInput = require('./TagsInput/TagsInputInput.cjs');\nconst require_TagsInput_TagsInputItem = require('./TagsInput/TagsInputItem.cjs');\nconst require_TagsInput_TagsInputItemDelete = require('./TagsInput/TagsInputItemDelete.cjs');\nconst require_TagsInput_TagsInputItemText = require('./TagsInput/TagsInputItemText.cjs');\nconst require_TimeField_TimeFieldRoot = require('./TimeField/TimeFieldRoot.cjs');\nconst require_TimeField_TimeFieldInput = require('./TimeField/TimeFieldInput.cjs');\nconst require_TimeRangeField_TimeRangeFieldRoot = require('./TimeRangeField/TimeRangeFieldRoot.cjs');\nconst require_TimeRangeField_TimeRangeFieldInput = require('./TimeRangeField/TimeRangeFieldInput.cjs');\nrequire('./Toast/ToastAnnounceExclude.cjs');\nconst require_Toast_ToastProvider = require('./Toast/ToastProvider.cjs');\nrequire('./Toast/ToastAnnounce.cjs');\nrequire('./Toast/utils.cjs');\nrequire('./Toast/ToastRootImpl.cjs');\nconst require_Toast_ToastClose = require('./Toast/ToastClose.cjs');\nconst require_Toast_ToastAction = require('./Toast/ToastAction.cjs');\nconst require_Toast_ToastDescription = require('./Toast/ToastDescription.cjs');\nconst require_Toast_ToastPortal = require('./Toast/ToastPortal.cjs');\nconst require_Toast_ToastRoot = require('./Toast/ToastRoot.cjs');\nconst require_Toast_ToastTitle = require('./Toast/ToastTitle.cjs');\nrequire('./Toast/FocusProxy.cjs');\nconst require_Toast_ToastViewport = require('./Toast/ToastViewport.cjs');\nconst require_ToggleGroup_ToggleGroupRoot = require('./ToggleGroup/ToggleGroupRoot.cjs');\nconst require_Toggle_Toggle = require('./Toggle/Toggle.cjs');\nconst require_ToggleGroup_ToggleGroupItem = require('./ToggleGroup/ToggleGroupItem.cjs');\nconst require_Toolbar_ToolbarButton = require('./Toolbar/ToolbarButton.cjs');\nconst require_Toolbar_ToolbarLink = require('./Toolbar/ToolbarLink.cjs');\nconst require_Toolbar_ToolbarRoot = require('./Toolbar/ToolbarRoot.cjs');\nconst require_Toolbar_ToolbarSeparator = require('./Toolbar/ToolbarSeparator.cjs');\nconst require_Toolbar_ToolbarToggleGroup = require('./Toolbar/ToolbarToggleGroup.cjs');\nconst require_Toolbar_ToolbarToggleItem = require('./Toolbar/ToolbarToggleItem.cjs');\nconst require_Tooltip_TooltipArrow = require('./Tooltip/TooltipArrow.cjs');\nconst require_Tooltip_TooltipProvider = require('./Tooltip/TooltipProvider.cjs');\nrequire('./Tooltip/utils.cjs');\nconst require_Tooltip_TooltipRoot = require('./Tooltip/TooltipRoot.cjs');\nrequire('./Tooltip/TooltipContentImpl.cjs');\nrequire('./Tooltip/TooltipContentHoverable.cjs');\nconst require_Tooltip_TooltipContent = require('./Tooltip/TooltipContent.cjs');\nconst require_Tooltip_TooltipPortal = require('./Tooltip/TooltipPortal.cjs');\nconst require_Tooltip_TooltipTrigger = require('./Tooltip/TooltipTrigger.cjs');\nrequire('./Tree/utils.cjs');\nconst require_Tree_TreeRoot = require('./Tree/TreeRoot.cjs');\nconst require_Tree_TreeItem = require('./Tree/TreeItem.cjs');\nconst require_Tree_TreeVirtualizer = require('./Tree/TreeVirtualizer.cjs');\nconst require_Viewport_Viewport = require('./Viewport/Viewport.cjs');\nrequire('./YearPicker/useYearPicker.cjs');\nconst require_YearPicker_YearPickerRoot = require('./YearPicker/YearPickerRoot.cjs');\nconst require_YearPicker_YearPickerCell = require('./YearPicker/YearPickerCell.cjs');\nconst require_YearPicker_YearPickerCellTrigger = require('./YearPicker/YearPickerCellTrigger.cjs');\nconst require_YearPicker_YearPickerGrid = require('./YearPicker/YearPickerGrid.cjs');\nconst require_YearPicker_YearPickerGridBody = require('./YearPicker/YearPickerGridBody.cjs');\nconst require_YearPicker_YearPickerGridRow = require('./YearPicker/YearPickerGridRow.cjs');\nconst require_YearPicker_YearPickerHeader = require('./YearPicker/YearPickerHeader.cjs');\nconst require_YearPicker_YearPickerHeading = require('./YearPicker/YearPickerHeading.cjs');\nconst require_YearPicker_YearPickerNext = require('./YearPicker/YearPickerNext.cjs');\nconst require_YearPicker_YearPickerPrev = require('./YearPicker/YearPickerPrev.cjs');\nrequire('./YearRangePicker/useRangeYearPicker.cjs');\nconst require_YearRangePicker_YearRangePickerRoot = require('./YearRangePicker/YearRangePickerRoot.cjs');\nconst require_YearRangePicker_YearRangePickerCell = require('./YearRangePicker/YearRangePickerCell.cjs');\nconst require_YearRangePicker_YearRangePickerCellTrigger = require('./YearRangePicker/YearRangePickerCellTrigger.cjs');\nconst require_YearRangePicker_YearRangePickerGrid = require('./YearRangePicker/YearRangePickerGrid.cjs');\nconst require_YearRangePicker_YearRangePickerGridBody = require('./YearRangePicker/YearRangePickerGridBody.cjs');\nconst require_YearRangePicker_YearRangePickerGridRow = require('./YearRangePicker/YearRangePickerGridRow.cjs');\nconst require_YearRangePicker_YearRangePickerHeader = require('./YearRangePicker/YearRangePickerHeader.cjs');\nconst require_YearRangePicker_YearRangePickerHeading = require('./YearRangePicker/YearRangePickerHeading.cjs');\nconst require_YearRangePicker_YearRangePickerNext = require('./YearRangePicker/YearRangePickerNext.cjs');\nconst require_YearRangePicker_YearRangePickerPrev = require('./YearRangePicker/YearRangePickerPrev.cjs');\nrequire('./index2.cjs');\n\nexports.AccordionContent = require_Accordion_AccordionContent.AccordionContent_default;\nexports.AccordionHeader = require_Accordion_AccordionHeader.AccordionHeader_default;\nexports.AccordionItem = require_Accordion_AccordionItem.AccordionItem_default;\nexports.AccordionRoot = require_Accordion_AccordionRoot.AccordionRoot_default;\nexports.AccordionTrigger = require_Accordion_AccordionTrigger.AccordionTrigger_default;\nexports.AlertDialogAction = require_AlertDialog_AlertDialogAction.AlertDialogAction_default;\nexports.AlertDialogCancel = require_AlertDialog_AlertDialogCancel.AlertDialogCancel_default;\nexports.AlertDialogContent = require_AlertDialog_AlertDialogContent.AlertDialogContent_default;\nexports.AlertDialogDescription = require_AlertDialog_AlertDialogDescription.AlertDialogDescription_default;\nexports.AlertDialogOverlay = require_AlertDialog_AlertDialogOverlay.AlertDialogOverlay_default;\nexports.AlertDialogPortal = require_AlertDialog_AlertDialogPortal.AlertDialogPortal_default;\nexports.AlertDialogRoot = require_AlertDialog_AlertDialogRoot.AlertDialogRoot_default;\nexports.AlertDialogTitle = require_AlertDialog_AlertDialogTitle.AlertDialogTitle_default;\nexports.AlertDialogTrigger = require_AlertDialog_AlertDialogTrigger.AlertDialogTrigger_default;\nexports.AspectRatio = require_AspectRatio_AspectRatio.AspectRatio_default;\nexports.AutocompleteAnchor = require_Combobox_ComboboxAnchor.ComboboxAnchor_default;\nexports.AutocompleteArrow = require_Combobox_ComboboxArrow.ComboboxArrow_default;\nexports.AutocompleteCancel = require_Combobox_ComboboxCancel.ComboboxCancel_default;\nexports.AutocompleteContent = require_Combobox_ComboboxContent.ComboboxContent_default;\nexports.AutocompleteEmpty = require_Combobox_ComboboxEmpty.ComboboxEmpty_default;\nexports.AutocompleteGroup = require_Combobox_ComboboxGroup.ComboboxGroup_default;\nexports.AutocompleteInput = require_Autocomplete_AutocompleteInput.AutocompleteInput_default;\nexports.AutocompleteItem = require_Combobox_ComboboxItem.ComboboxItem_default;\nexports.AutocompleteItemIndicator = require_Combobox_ComboboxItemIndicator.ComboboxItemIndicator_default;\nexports.AutocompleteLabel = require_Combobox_ComboboxLabel.ComboboxLabel_default;\nexports.AutocompletePortal = require_Combobox_ComboboxPortal.ComboboxPortal_default;\nexports.AutocompleteRoot = require_Autocomplete_AutocompleteRoot.AutocompleteRoot_default;\nexports.AutocompleteSeparator = require_Combobox_ComboboxSeparator.ComboboxSeparator_default;\nexports.AutocompleteTrigger = require_Combobox_ComboboxTrigger.ComboboxTrigger_default;\nexports.AutocompleteViewport = require_Combobox_ComboboxViewport.ComboboxViewport_default;\nexports.AutocompleteVirtualizer = require_Combobox_ComboboxVirtualizer.ComboboxVirtualizer_default;\nexports.AvatarFallback = require_Avatar_AvatarFallback.AvatarFallback_default;\nexports.AvatarImage = require_Avatar_AvatarImage.AvatarImage_default;\nexports.AvatarRoot = require_Avatar_AvatarRoot.AvatarRoot_default;\nexports.CalendarCell = require_Calendar_CalendarCell.CalendarCell_default;\nexports.CalendarCellTrigger = require_Calendar_CalendarCellTrigger.CalendarCellTrigger_default;\nexports.CalendarGrid = require_Calendar_CalendarGrid.CalendarGrid_default;\nexports.CalendarGridBody = require_Calendar_CalendarGridBody.CalendarGridBody_default;\nexports.CalendarGridHead = require_Calendar_CalendarGridHead.CalendarGridHead_default;\nexports.CalendarGridRow = require_Calendar_CalendarGridRow.CalendarGridRow_default;\nexports.CalendarHeadCell = require_Calendar_CalendarHeadCell.CalendarHeadCell_default;\nexports.CalendarHeader = require_Calendar_CalendarHeader.CalendarHeader_default;\nexports.CalendarHeading = require_Calendar_CalendarHeading.CalendarHeading_default;\nexports.CalendarNext = require_Calendar_CalendarNext.CalendarNext_default;\nexports.CalendarPrev = require_Calendar_CalendarPrev.CalendarPrev_default;\nexports.CalendarRoot = require_Calendar_CalendarRoot.CalendarRoot_default;\nexports.CheckboxGroupRoot = require_Checkbox_CheckboxGroupRoot.CheckboxGroupRoot_default;\nexports.CheckboxIndicator = require_Checkbox_CheckboxIndicator.CheckboxIndicator_default;\nexports.CheckboxRoot = require_Checkbox_CheckboxRoot.CheckboxRoot_default;\nexports.CollapsibleContent = require_Collapsible_CollapsibleContent.CollapsibleContent_default;\nexports.CollapsibleRoot = require_Collapsible_CollapsibleRoot.CollapsibleRoot_default;\nexports.CollapsibleTrigger = require_Collapsible_CollapsibleTrigger.CollapsibleTrigger_default;\nexports.ColorAreaArea = require_ColorArea_ColorAreaArea.ColorAreaArea_default;\nexports.ColorAreaRoot = require_ColorArea_ColorAreaRoot.ColorAreaRoot_default;\nexports.ColorAreaThumb = require_ColorArea_ColorAreaThumb.ColorAreaThumb_default;\nexports.ColorFieldInput = require_ColorField_ColorFieldInput.ColorFieldInput_default;\nexports.ColorFieldRoot = require_ColorField_ColorFieldRoot.ColorFieldRoot_default;\nexports.ColorSliderRoot = require_ColorSlider_ColorSliderRoot.ColorSliderRoot_default;\nexports.ColorSliderThumb = require_ColorSlider_ColorSliderThumb.ColorSliderThumb_default;\nexports.ColorSliderTrack = require_ColorSlider_ColorSliderTrack.ColorSliderTrack_default;\nexports.ColorSwatch = require_ColorSwatch_ColorSwatch.ColorSwatch_default;\nexports.ColorSwatchPickerItem = require_ColorSwatchPicker_ColorSwatchPickerItem.ColorSwatchPickerItem_default;\nexports.ColorSwatchPickerItemIndicator = require_ColorSwatchPicker_ColorSwatchPickerItemIndicator.ColorSwatchPickerItemIndicator_default;\nexports.ColorSwatchPickerItemSwatch = require_ColorSwatchPicker_ColorSwatchPickerItemSwatch.ColorSwatchPickerItemSwatch_default;\nexports.ColorSwatchPickerRoot = require_ColorSwatchPicker_ColorSwatchPickerRoot.ColorSwatchPickerRoot_default;\nexports.ComboboxAnchor = require_Combobox_ComboboxAnchor.ComboboxAnchor_default;\nexports.ComboboxArrow = require_Combobox_ComboboxArrow.ComboboxArrow_default;\nexports.ComboboxCancel = require_Combobox_ComboboxCancel.ComboboxCancel_default;\nexports.ComboboxContent = require_Combobox_ComboboxContent.ComboboxContent_default;\nexports.ComboboxEmpty = require_Combobox_ComboboxEmpty.ComboboxEmpty_default;\nexports.ComboboxGroup = require_Combobox_ComboboxGroup.ComboboxGroup_default;\nexports.ComboboxInput = require_Combobox_ComboboxInput.ComboboxInput_default;\nexports.ComboboxItem = require_Combobox_ComboboxItem.ComboboxItem_default;\nexports.ComboboxItemIndicator = require_Combobox_ComboboxItemIndicator.ComboboxItemIndicator_default;\nexports.ComboboxLabel = require_Combobox_ComboboxLabel.ComboboxLabel_default;\nexports.ComboboxPortal = require_Combobox_ComboboxPortal.ComboboxPortal_default;\nexports.ComboboxRoot = require_Combobox_ComboboxRoot.ComboboxRoot_default;\nexports.ComboboxSeparator = require_Combobox_ComboboxSeparator.ComboboxSeparator_default;\nexports.ComboboxTrigger = require_Combobox_ComboboxTrigger.ComboboxTrigger_default;\nexports.ComboboxViewport = require_Combobox_ComboboxViewport.ComboboxViewport_default;\nexports.ComboboxVirtualizer = require_Combobox_ComboboxVirtualizer.ComboboxVirtualizer_default;\nexports.ConfigProvider = require_ConfigProvider_ConfigProvider.ConfigProvider_default;\nexports.ContextMenuArrow = require_ContextMenu_ContextMenuArrow.ContextMenuArrow_default;\nexports.ContextMenuCheckboxItem = require_ContextMenu_ContextMenuCheckboxItem.ContextMenuCheckboxItem_default;\nexports.ContextMenuContent = require_ContextMenu_ContextMenuContent.ContextMenuContent_default;\nexports.ContextMenuGroup = require_ContextMenu_ContextMenuGroup.ContextMenuGroup_default;\nexports.ContextMenuItem = require_ContextMenu_ContextMenuItem.ContextMenuItem_default;\nexports.ContextMenuItemIndicator = require_ContextMenu_ContextMenuItemIndicator.ContextMenuItemIndicator_default;\nexports.ContextMenuLabel = require_ContextMenu_ContextMenuLabel.ContextMenuLabel_default;\nexports.ContextMenuPortal = require_ContextMenu_ContextMenuPortal.ContextMenuPortal_default;\nexports.ContextMenuRadioGroup = require_ContextMenu_ContextMenuRadioGroup.ContextMenuRadioGroup_default;\nexports.ContextMenuRadioItem = require_ContextMenu_ContextMenuRadioItem.ContextMenuRadioItem_default;\nexports.ContextMenuRoot = require_ContextMenu_ContextMenuRoot.ContextMenuRoot_default;\nexports.ContextMenuSeparator = require_ContextMenu_ContextMenuSeparator.ContextMenuSeparator_default;\nexports.ContextMenuSub = require_ContextMenu_ContextMenuSub.ContextMenuSub_default;\nexports.ContextMenuSubContent = require_ContextMenu_ContextMenuSubContent.ContextMenuSubContent_default;\nexports.ContextMenuSubTrigger = require_ContextMenu_ContextMenuSubTrigger.ContextMenuSubTrigger_default;\nexports.ContextMenuTrigger = require_ContextMenu_ContextMenuTrigger.ContextMenuTrigger_default;\nexports.DateFieldInput = require_DateField_DateFieldInput.DateFieldInput_default;\nexports.DateFieldRoot = require_DateField_DateFieldRoot.DateFieldRoot_default;\nexports.DatePickerAnchor = require_DatePicker_DatePickerAnchor.DatePickerAnchor_default;\nexports.DatePickerArrow = require_DatePicker_DatePickerArrow.DatePickerArrow_default;\nexports.DatePickerCalendar = require_DatePicker_DatePickerCalendar.DatePickerCalendar_default;\nexports.DatePickerCell = require_DatePicker_DatePickerCell.DatePickerCell_default;\nexports.DatePickerCellTrigger = require_DatePicker_DatePickerCellTrigger.DatePickerCellTrigger_default;\nexports.DatePickerClose = require_DatePicker_DatePickerClose.DatePickerClose_default;\nexports.DatePickerContent = require_DatePicker_DatePickerContent.DatePickerContent_default;\nexports.DatePickerField = require_DatePicker_DatePickerField.DatePickerField_default;\nexports.DatePickerGrid = require_DatePicker_DatePickerGrid.DatePickerGrid_default;\nexports.DatePickerGridBody = require_DatePicker_DatePickerGridBody.DatePickerGridBody_default;\nexports.DatePickerGridHead = require_DatePicker_DatePickerGridHead.DatePickerGridHead_default;\nexports.DatePickerGridRow = require_DatePicker_DatePickerGridRow.DatePickerGridRow_default;\nexports.DatePickerHeadCell = require_DatePicker_DatePickerHeadCell.DatePickerHeadCell_default;\nexports.DatePickerHeader = require_DatePicker_DatePickerHeader.DatePickerHeader_default;\nexports.DatePickerHeading = require_DatePicker_DatePickerHeading.DatePickerHeading_default;\nexports.DatePickerInput = require_DatePicker_DatePickerInput.DatePickerInput_default;\nexports.DatePickerNext = require_DatePicker_DatePickerNext.DatePickerNext_default;\nexports.DatePickerPrev = require_DatePicker_DatePickerPrev.DatePickerPrev_default;\nexports.DatePickerRoot = require_DatePicker_DatePickerRoot.DatePickerRoot_default;\nexports.DatePickerTrigger = require_DatePicker_DatePickerTrigger.DatePickerTrigger_default;\nexports.DateRangeFieldInput = require_DateRangeField_DateRangeFieldInput.DateRangeFieldInput_default;\nexports.DateRangeFieldRoot = require_DateRangeField_DateRangeFieldRoot.DateRangeFieldRoot_default;\nexports.DateRangePickerAnchor = require_DateRangePicker_DateRangePickerAnchor.DateRangePickerAnchor_default;\nexports.DateRangePickerArrow = require_DateRangePicker_DateRangePickerArrow.DateRangePickerArrow_default;\nexports.DateRangePickerCalendar = require_DateRangePicker_DateRangePickerCalendar.DateRangePickerCalendar_default;\nexports.DateRangePickerCell = require_DateRangePicker_DateRangePickerCell.DateRangePickerCell_default;\nexports.DateRangePickerCellTrigger = require_DateRangePicker_DateRangePickerCellTrigger.DateRangePickerCellTrigger_default;\nexports.DateRangePickerClose = require_DateRangePicker_DateRangePickerClose.DateRangePickerClose_default;\nexports.DateRangePickerContent = require_DateRangePicker_DateRangePickerContent.DateRangePickerContent_default;\nexports.DateRangePickerField = require_DateRangePicker_DateRangePickerField.DateRangePickerField_default;\nexports.DateRangePickerGrid = require_DateRangePicker_DateRangePickerGrid.DateRangePickerGrid_default;\nexports.DateRangePickerGridBody = require_DateRangePicker_DateRangePickerGridBody.DateRangePickerGridBody_default;\nexports.DateRangePickerGridHead = require_DateRangePicker_DateRangePickerGridHead.DateRangePickerGridHead_default;\nexports.DateRangePickerGridRow = require_DateRangePicker_DateRangePickerGridRow.DateRangePickerGridRow_default;\nexports.DateRangePickerHeadCell = require_DateRangePicker_DateRangePickerHeadCell.DateRangePickerHeadCell_default;\nexports.DateRangePickerHeader = require_DateRangePicker_DateRangePickerHeader.DateRangePickerHeader_default;\nexports.DateRangePickerHeading = require_DateRangePicker_DateRangePickerHeading.DateRangePickerHeading_default;\nexports.DateRangePickerInput = require_DateRangePicker_DateRangePickerInput.DateRangePickerInput_default;\nexports.DateRangePickerNext = require_DateRangePicker_DateRangePickerNext.DateRangePickerNext_default;\nexports.DateRangePickerPrev = require_DateRangePicker_DateRangePickerPrev.DateRangePickerPrev_default;\nexports.DateRangePickerRoot = require_DateRangePicker_DateRangePickerRoot.DateRangePickerRoot_default;\nexports.DateRangePickerTrigger = require_DateRangePicker_DateRangePickerTrigger.DateRangePickerTrigger_default;\nexports.DialogClose = require_Dialog_DialogClose.DialogClose_default;\nexports.DialogContent = require_Dialog_DialogContent.DialogContent_default;\nexports.DialogDescription = require_Dialog_DialogDescription.DialogDescription_default;\nexports.DialogOverlay = require_Dialog_DialogOverlay.DialogOverlay_default;\nexports.DialogPortal = require_Dialog_DialogPortal.DialogPortal_default;\nexports.DialogRoot = require_Dialog_DialogRoot.DialogRoot_default;\nexports.DialogTitle = require_Dialog_DialogTitle.DialogTitle_default;\nexports.DialogTrigger = require_Dialog_DialogTrigger.DialogTrigger_default;\nexports.DropdownMenuArrow = require_DropdownMenu_DropdownMenuArrow.DropdownMenuArrow_default;\nexports.DropdownMenuCheckboxItem = require_DropdownMenu_DropdownMenuCheckboxItem.DropdownMenuCheckboxItem_default;\nexports.DropdownMenuContent = require_DropdownMenu_DropdownMenuContent.DropdownMenuContent_default;\nexports.DropdownMenuFilter = require_DropdownMenu_DropdownMenuFilter.DropdownMenuFilter_default;\nexports.DropdownMenuGroup = require_DropdownMenu_DropdownMenuGroup.DropdownMenuGroup_default;\nexports.DropdownMenuItem = require_DropdownMenu_DropdownMenuItem.DropdownMenuItem_default;\nexports.DropdownMenuItemIndicator = require_DropdownMenu_DropdownMenuItemIndicator.DropdownMenuItemIndicator_default;\nexports.DropdownMenuLabel = require_DropdownMenu_DropdownMenuLabel.DropdownMenuLabel_default;\nexports.DropdownMenuPortal = require_DropdownMenu_DropdownMenuPortal.DropdownMenuPortal_default;\nexports.DropdownMenuRadioGroup = require_DropdownMenu_DropdownMenuRadioGroup.DropdownMenuRadioGroup_default;\nexports.DropdownMenuRadioItem = require_DropdownMenu_DropdownMenuRadioItem.DropdownMenuRadioItem_default;\nexports.DropdownMenuRoot = require_DropdownMenu_DropdownMenuRoot.DropdownMenuRoot_default;\nexports.DropdownMenuSeparator = require_DropdownMenu_DropdownMenuSeparator.DropdownMenuSeparator_default;\nexports.DropdownMenuSub = require_DropdownMenu_DropdownMenuSub.DropdownMenuSub_default;\nexports.DropdownMenuSubContent = require_DropdownMenu_DropdownMenuSubContent.DropdownMenuSubContent_default;\nexports.DropdownMenuSubTrigger = require_DropdownMenu_DropdownMenuSubTrigger.DropdownMenuSubTrigger_default;\nexports.DropdownMenuTrigger = require_DropdownMenu_DropdownMenuTrigger.DropdownMenuTrigger_default;\nexports.EditableArea = require_Editable_EditableArea.EditableArea_default;\nexports.EditableCancelTrigger = require_Editable_EditableCancelTrigger.EditableCancelTrigger_default;\nexports.EditableEditTrigger = require_Editable_EditableEditTrigger.EditableEditTrigger_default;\nexports.EditableInput = require_Editable_EditableInput.EditableInput_default;\nexports.EditablePreview = require_Editable_EditablePreview.EditablePreview_default;\nexports.EditableRoot = require_Editable_EditableRoot.EditableRoot_default;\nexports.EditableSubmitTrigger = require_Editable_EditableSubmitTrigger.EditableSubmitTrigger_default;\nexports.FocusScope = require_FocusScope_FocusScope.FocusScope_default;\nexports.HoverCardArrow = require_HoverCard_HoverCardArrow.HoverCardArrow_default;\nexports.HoverCardContent = require_HoverCard_HoverCardContent.HoverCardContent_default;\nexports.HoverCardPortal = require_HoverCard_HoverCardPortal.HoverCardPortal_default;\nexports.HoverCardRoot = require_HoverCard_HoverCardRoot.HoverCardRoot_default;\nexports.HoverCardTrigger = require_HoverCard_HoverCardTrigger.HoverCardTrigger_default;\nexports.Label = require_Label_Label.Label_default;\nexports.ListboxContent = require_Listbox_ListboxContent.ListboxContent_default;\nexports.ListboxFilter = require_Listbox_ListboxFilter.ListboxFilter_default;\nexports.ListboxGroup = require_Listbox_ListboxGroup.ListboxGroup_default;\nexports.ListboxGroupLabel = require_Listbox_ListboxGroupLabel.ListboxGroupLabel_default;\nexports.ListboxItem = require_Listbox_ListboxItem.ListboxItem_default;\nexports.ListboxItemIndicator = require_Listbox_ListboxItemIndicator.ListboxItemIndicator_default;\nexports.ListboxRoot = require_Listbox_ListboxRoot.ListboxRoot_default;\nexports.ListboxVirtualizer = require_Listbox_ListboxVirtualizer.ListboxVirtualizer_default;\nexports.MenubarArrow = require_Menubar_MenubarArrow.MenubarArrow_default;\nexports.MenubarCheckboxItem = require_Menubar_MenubarCheckboxItem.MenubarCheckboxItem_default;\nexports.MenubarContent = require_Menubar_MenubarContent.MenubarContent_default;\nexports.MenubarGroup = require_Menubar_MenubarGroup.MenubarGroup_default;\nexports.MenubarItem = require_Menubar_MenubarItem.MenubarItem_default;\nexports.MenubarItemIndicator = require_Menubar_MenubarItemIndicator.MenubarItemIndicator_default;\nexports.MenubarLabel = require_Menubar_MenubarLabel.MenubarLabel_default;\nexports.MenubarMenu = require_Menubar_MenubarMenu.MenubarMenu_default;\nexports.MenubarPortal = require_Menubar_MenubarPortal.MenubarPortal_default;\nexports.MenubarRadioGroup = require_Menubar_MenubarRadioGroup.MenubarRadioGroup_default;\nexports.MenubarRadioItem = require_Menubar_MenubarRadioItem.MenubarRadioItem_default;\nexports.MenubarRoot = require_Menubar_MenubarRoot.MenubarRoot_default;\nexports.MenubarSeparator = require_Menubar_MenubarSeparator.MenubarSeparator_default;\nexports.MenubarSub = require_Menubar_MenubarSub.MenubarSub_default;\nexports.MenubarSubContent = require_Menubar_MenubarSubContent.MenubarSubContent_default;\nexports.MenubarSubTrigger = require_Menubar_MenubarSubTrigger.MenubarSubTrigger_default;\nexports.MenubarTrigger = require_Menubar_MenubarTrigger.MenubarTrigger_default;\nexports.MonthPickerCell = require_MonthPicker_MonthPickerCell.MonthPickerCell_default;\nexports.MonthPickerCellTrigger = require_MonthPicker_MonthPickerCellTrigger.MonthPickerCellTrigger_default;\nexports.MonthPickerGrid = require_MonthPicker_MonthPickerGrid.MonthPickerGrid_default;\nexports.MonthPickerGridBody = require_MonthPicker_MonthPickerGridBody.MonthPickerGridBody_default;\nexports.MonthPickerGridRow = require_MonthPicker_MonthPickerGridRow.MonthPickerGridRow_default;\nexports.MonthPickerHeader = require_MonthPicker_MonthPickerHeader.MonthPickerHeader_default;\nexports.MonthPickerHeading = require_MonthPicker_MonthPickerHeading.MonthPickerHeading_default;\nexports.MonthPickerNext = require_MonthPicker_MonthPickerNext.MonthPickerNext_default;\nexports.MonthPickerPrev = require_MonthPicker_MonthPickerPrev.MonthPickerPrev_default;\nexports.MonthPickerRoot = require_MonthPicker_MonthPickerRoot.MonthPickerRoot_default;\nexports.MonthRangePickerCell = require_MonthRangePicker_MonthRangePickerCell.MonthRangePickerCell_default;\nexports.MonthRangePickerCellTrigger = require_MonthRangePicker_MonthRangePickerCellTrigger.MonthRangePickerCellTrigger_default;\nexports.MonthRangePickerGrid = require_MonthRangePicker_MonthRangePickerGrid.MonthRangePickerGrid_default;\nexports.MonthRangePickerGridBody = require_MonthRangePicker_MonthRangePickerGridBody.MonthRangePickerGridBody_default;\nexports.MonthRangePickerGridRow = require_MonthRangePicker_MonthRangePickerGridRow.MonthRangePickerGridRow_default;\nexports.MonthRangePickerHeader = require_MonthRangePicker_MonthRangePickerHeader.MonthRangePickerHeader_default;\nexports.MonthRangePickerHeading = require_MonthRangePicker_MonthRangePickerHeading.MonthRangePickerHeading_default;\nexports.MonthRangePickerNext = require_MonthRangePicker_MonthRangePickerNext.MonthRangePickerNext_default;\nexports.MonthRangePickerPrev = require_MonthRangePicker_MonthRangePickerPrev.MonthRangePickerPrev_default;\nexports.MonthRangePickerRoot = require_MonthRangePicker_MonthRangePickerRoot.MonthRangePickerRoot_default;\nexports.NavigationMenuContent = require_NavigationMenu_NavigationMenuContent.NavigationMenuContent_default;\nexports.NavigationMenuIndicator = require_NavigationMenu_NavigationMenuIndicator.NavigationMenuIndicator_default;\nexports.NavigationMenuItem = require_NavigationMenu_NavigationMenuItem.NavigationMenuItem_default;\nexports.NavigationMenuLink = require_NavigationMenu_NavigationMenuLink.NavigationMenuLink_default;\nexports.NavigationMenuList = require_NavigationMenu_NavigationMenuList.NavigationMenuList_default;\nexports.NavigationMenuRoot = require_NavigationMenu_NavigationMenuRoot.NavigationMenuRoot_default;\nexports.NavigationMenuSub = require_NavigationMenu_NavigationMenuSub.NavigationMenuSub_default;\nexports.NavigationMenuTrigger = require_NavigationMenu_NavigationMenuTrigger.NavigationMenuTrigger_default;\nexports.NavigationMenuViewport = require_NavigationMenu_NavigationMenuViewport.NavigationMenuViewport_default;\nexports.NumberFieldDecrement = require_NumberField_NumberFieldDecrement.NumberFieldDecrement_default;\nexports.NumberFieldIncrement = require_NumberField_NumberFieldIncrement.NumberFieldIncrement_default;\nexports.NumberFieldInput = require_NumberField_NumberFieldInput.NumberFieldInput_default;\nexports.NumberFieldRoot = require_NumberField_NumberFieldRoot.NumberFieldRoot_default;\nexports.PaginationEllipsis = require_Pagination_PaginationEllipsis.PaginationEllipsis_default;\nexports.PaginationFirst = require_Pagination_PaginationFirst.PaginationFirst_default;\nexports.PaginationLast = require_Pagination_PaginationLast.PaginationLast_default;\nexports.PaginationList = require_Pagination_PaginationList.PaginationList_default;\nexports.PaginationListItem = require_Pagination_PaginationListItem.PaginationListItem_default;\nexports.PaginationNext = require_Pagination_PaginationNext.PaginationNext_default;\nexports.PaginationPrev = require_Pagination_PaginationPrev.PaginationPrev_default;\nexports.PaginationRoot = require_Pagination_PaginationRoot.PaginationRoot_default;\nexports.PinInputInput = require_PinInput_PinInputInput.PinInputInput_default;\nexports.PinInputRoot = require_PinInput_PinInputRoot.PinInputRoot_default;\nexports.PopoverAnchor = require_Popover_PopoverAnchor.PopoverAnchor_default;\nexports.PopoverArrow = require_Popover_PopoverArrow.PopoverArrow_default;\nexports.PopoverClose = require_Popover_PopoverClose.PopoverClose_default;\nexports.PopoverContent = require_Popover_PopoverContent.PopoverContent_default;\nexports.PopoverPortal = require_Popover_PopoverPortal.PopoverPortal_default;\nexports.PopoverRoot = require_Popover_PopoverRoot.PopoverRoot_default;\nexports.PopoverTrigger = require_Popover_PopoverTrigger.PopoverTrigger_default;\nexports.Presence = require_Presence_Presence.Presence_default;\nexports.Primitive = require_Primitive_Primitive.Primitive;\nexports.ProgressIndicator = require_Progress_ProgressIndicator.ProgressIndicator_default;\nexports.ProgressRoot = require_Progress_ProgressRoot.ProgressRoot_default;\nexports.RadioGroupIndicator = require_RadioGroup_RadioGroupIndicator.RadioGroupIndicator_default;\nexports.RadioGroupItem = require_RadioGroup_RadioGroupItem.RadioGroupItem_default;\nexports.RadioGroupRoot = require_RadioGroup_RadioGroupRoot.RadioGroupRoot_default;\nexports.RangeCalendarCell = require_RangeCalendar_RangeCalendarCell.RangeCalendarCell_default;\nexports.RangeCalendarCellTrigger = require_RangeCalendar_RangeCalendarCellTrigger.RangeCalendarCellTrigger_default;\nexports.RangeCalendarGrid = require_RangeCalendar_RangeCalendarGrid.RangeCalendarGrid_default;\nexports.RangeCalendarGridBody = require_RangeCalendar_RangeCalendarGridBody.RangeCalendarGridBody_default;\nexports.RangeCalendarGridHead = require_RangeCalendar_RangeCalendarGridHead.RangeCalendarGridHead_default;\nexports.RangeCalendarGridRow = require_RangeCalendar_RangeCalendarGridRow.RangeCalendarGridRow_default;\nexports.RangeCalendarHeadCell = require_RangeCalendar_RangeCalendarHeadCell.RangeCalendarHeadCell_default;\nexports.RangeCalendarHeader = require_RangeCalendar_RangeCalendarHeader.RangeCalendarHeader_default;\nexports.RangeCalendarHeading = require_RangeCalendar_RangeCalendarHeading.RangeCalendarHeading_default;\nexports.RangeCalendarNext = require_RangeCalendar_RangeCalendarNext.RangeCalendarNext_default;\nexports.RangeCalendarPrev = require_RangeCalendar_RangeCalendarPrev.RangeCalendarPrev_default;\nexports.RangeCalendarRoot = require_RangeCalendar_RangeCalendarRoot.RangeCalendarRoot_default;\nexports.RovingFocusGroup = require_RovingFocus_RovingFocusGroup.RovingFocusGroup_default;\nexports.RovingFocusItem = require_RovingFocus_RovingFocusItem.RovingFocusItem_default;\nexports.ScrollAreaCorner = require_ScrollArea_ScrollAreaCorner.ScrollAreaCorner_default;\nexports.ScrollAreaRoot = require_ScrollArea_ScrollAreaRoot.ScrollAreaRoot_default;\nexports.ScrollAreaScrollbar = require_ScrollArea_ScrollAreaScrollbar.ScrollAreaScrollbar_default;\nexports.ScrollAreaScrollbarGlimpse = require_ScrollArea_ScrollAreaScrollbarGlimpse.ScrollAreaScrollbarGlimpse_default;\nexports.ScrollAreaThumb = require_ScrollArea_ScrollAreaThumb.ScrollAreaThumb_default;\nexports.ScrollAreaViewport = require_ScrollArea_ScrollAreaViewport.ScrollAreaViewport_default;\nexports.SelectArrow = require_Select_SelectArrow.SelectArrow_default;\nexports.SelectContent = require_Select_SelectContent.SelectContent_default;\nexports.SelectGroup = require_Select_SelectGroup.SelectGroup_default;\nexports.SelectIcon = require_Select_SelectIcon.SelectIcon_default;\nexports.SelectItem = require_Select_SelectItem.SelectItem_default;\nexports.SelectItemIndicator = require_Select_SelectItemIndicator.SelectItemIndicator_default;\nexports.SelectItemText = require_Select_SelectItemText.SelectItemText_default;\nexports.SelectLabel = require_Select_SelectLabel.SelectLabel_default;\nexports.SelectPortal = require_Select_SelectPortal.SelectPortal_default;\nexports.SelectRoot = require_Select_SelectRoot.SelectRoot_default;\nexports.SelectScrollDownButton = require_Select_SelectScrollDownButton.SelectScrollDownButton_default;\nexports.SelectScrollUpButton = require_Select_SelectScrollUpButton.SelectScrollUpButton_default;\nexports.SelectSeparator = require_Select_SelectSeparator.SelectSeparator_default;\nexports.SelectTrigger = require_Select_SelectTrigger.SelectTrigger_default;\nexports.SelectValue = require_Select_SelectValue.SelectValue_default;\nexports.SelectViewport = require_Select_SelectViewport.SelectViewport_default;\nexports.Separator = require_Separator_Separator.Separator_default;\nexports.SliderRange = require_Slider_SliderRange.SliderRange_default;\nexports.SliderRoot = require_Slider_SliderRoot.SliderRoot_default;\nexports.SliderThumb = require_Slider_SliderThumb.SliderThumb_default;\nexports.SliderTrack = require_Slider_SliderTrack.SliderTrack_default;\nexports.Slot = require_Primitive_Slot.Slot;\nexports.SplitterGroup = require_Splitter_SplitterGroup.SplitterGroup_default;\nexports.SplitterPanel = require_Splitter_SplitterPanel.SplitterPanel_default;\nexports.SplitterResizeHandle = require_Splitter_SplitterResizeHandle.SplitterResizeHandle_default;\nexports.StepperDescription = require_Stepper_StepperDescription.StepperDescription_default;\nexports.StepperIndicator = require_Stepper_StepperIndicator.StepperIndicator_default;\nexports.StepperItem = require_Stepper_StepperItem.StepperItem_default;\nexports.StepperRoot = require_Stepper_StepperRoot.StepperRoot_default;\nexports.StepperSeparator = require_Stepper_StepperSeparator.StepperSeparator_default;\nexports.StepperTitle = require_Stepper_StepperTitle.StepperTitle_default;\nexports.StepperTrigger = require_Stepper_StepperTrigger.StepperTrigger_default;\nexports.SwitchRoot = require_Switch_SwitchRoot.SwitchRoot_default;\nexports.SwitchThumb = require_Switch_SwitchThumb.SwitchThumb_default;\nexports.TabsContent = require_Tabs_TabsContent.TabsContent_default;\nexports.TabsIndicator = require_Tabs_TabsIndicator.TabsIndicator_default;\nexports.TabsList = require_Tabs_TabsList.TabsList_default;\nexports.TabsRoot = require_Tabs_TabsRoot.TabsRoot_default;\nexports.TabsTrigger = require_Tabs_TabsTrigger.TabsTrigger_default;\nexports.TagsInputClear = require_TagsInput_TagsInputClear.TagsInputClear_default;\nexports.TagsInputInput = require_TagsInput_TagsInputInput.TagsInputInput_default;\nexports.TagsInputItem = require_TagsInput_TagsInputItem.TagsInputItem_default;\nexports.TagsInputItemDelete = require_TagsInput_TagsInputItemDelete.TagsInputItemDelete_default;\nexports.TagsInputItemText = require_TagsInput_TagsInputItemText.TagsInputItemText_default;\nexports.TagsInputRoot = require_TagsInput_TagsInputRoot.TagsInputRoot_default;\nexports.TimeFieldInput = require_TimeField_TimeFieldInput.TimeFieldInput_default;\nexports.TimeFieldRoot = require_TimeField_TimeFieldRoot.TimeFieldRoot_default;\nexports.TimeRangeFieldInput = require_TimeRangeField_TimeRangeFieldInput.TimeRangeFieldInput_default;\nexports.TimeRangeFieldRoot = require_TimeRangeField_TimeRangeFieldRoot.TimeRangeFieldRoot_default;\nexports.ToastAction = require_Toast_ToastAction.ToastAction_default;\nexports.ToastClose = require_Toast_ToastClose.ToastClose_default;\nexports.ToastDescription = require_Toast_ToastDescription.ToastDescription_default;\nexports.ToastPortal = require_Toast_ToastPortal.ToastPortal_default;\nexports.ToastProvider = require_Toast_ToastProvider.ToastProvider_default;\nexports.ToastRoot = require_Toast_ToastRoot.ToastRoot_default;\nexports.ToastTitle = require_Toast_ToastTitle.ToastTitle_default;\nexports.ToastViewport = require_Toast_ToastViewport.ToastViewport_default;\nexports.Toggle = require_Toggle_Toggle.Toggle_default;\nexports.ToggleGroupItem = require_ToggleGroup_ToggleGroupItem.ToggleGroupItem_default;\nexports.ToggleGroupRoot = require_ToggleGroup_ToggleGroupRoot.ToggleGroupRoot_default;\nexports.ToolbarButton = require_Toolbar_ToolbarButton.ToolbarButton_default;\nexports.ToolbarLink = require_Toolbar_ToolbarLink.ToolbarLink_default;\nexports.ToolbarRoot = require_Toolbar_ToolbarRoot.ToolbarRoot_default;\nexports.ToolbarSeparator = require_Toolbar_ToolbarSeparator.ToolbarSeparator_default;\nexports.ToolbarToggleGroup = require_Toolbar_ToolbarToggleGroup.ToolbarToggleGroup_default;\nexports.ToolbarToggleItem = require_Toolbar_ToolbarToggleItem.ToolbarToggleItem_default;\nexports.TooltipArrow = require_Tooltip_TooltipArrow.TooltipArrow_default;\nexports.TooltipContent = require_Tooltip_TooltipContent.TooltipContent_default;\nexports.TooltipPortal = require_Tooltip_TooltipPortal.TooltipPortal_default;\nexports.TooltipProvider = require_Tooltip_TooltipProvider.TooltipProvider_default;\nexports.TooltipRoot = require_Tooltip_TooltipRoot.TooltipRoot_default;\nexports.TooltipTrigger = require_Tooltip_TooltipTrigger.TooltipTrigger_default;\nexports.TreeItem = require_Tree_TreeItem.TreeItem_default;\nexports.TreeRoot = require_Tree_TreeRoot.TreeRoot_default;\nexports.TreeVirtualizer = require_Tree_TreeVirtualizer.TreeVirtualizer_default;\nexports.Viewport = require_Viewport_Viewport.Viewport_default;\nexports.VisuallyHidden = require_VisuallyHidden_VisuallyHidden.VisuallyHidden_default;\nexports.YearPickerCell = require_YearPicker_YearPickerCell.YearPickerCell_default;\nexports.YearPickerCellTrigger = require_YearPicker_YearPickerCellTrigger.YearPickerCellTrigger_default;\nexports.YearPickerGrid = require_YearPicker_YearPickerGrid.YearPickerGrid_default;\nexports.YearPickerGridBody = require_YearPicker_YearPickerGridBody.YearPickerGridBody_default;\nexports.YearPickerGridRow = require_YearPicker_YearPickerGridRow.YearPickerGridRow_default;\nexports.YearPickerHeader = require_YearPicker_YearPickerHeader.YearPickerHeader_default;\nexports.YearPickerHeading = require_YearPicker_YearPickerHeading.YearPickerHeading_default;\nexports.YearPickerNext = require_YearPicker_YearPickerNext.YearPickerNext_default;\nexports.YearPickerPrev = require_YearPicker_YearPickerPrev.YearPickerPrev_default;\nexports.YearPickerRoot = require_YearPicker_YearPickerRoot.YearPickerRoot_default;\nexports.YearRangePickerCell = require_YearRangePicker_YearRangePickerCell.YearRangePickerCell_default;\nexports.YearRangePickerCellTrigger = require_YearRangePicker_YearRangePickerCellTrigger.YearRangePickerCellTrigger_default;\nexports.YearRangePickerGrid = require_YearRangePicker_YearRangePickerGrid.YearRangePickerGrid_default;\nexports.YearRangePickerGridBody = require_YearRangePicker_YearRangePickerGridBody.YearRangePickerGridBody_default;\nexports.YearRangePickerGridRow = require_YearRangePicker_YearRangePickerGridRow.YearRangePickerGridRow_default;\nexports.YearRangePickerHeader = require_YearRangePicker_YearRangePickerHeader.YearRangePickerHeader_default;\nexports.YearRangePickerHeading = require_YearRangePicker_YearRangePickerHeading.YearRangePickerHeading_default;\nexports.YearRangePickerNext = require_YearRangePicker_YearRangePickerNext.YearRangePickerNext_default;\nexports.YearRangePickerPrev = require_YearRangePicker_YearRangePickerPrev.YearRangePickerPrev_default;\nexports.YearRangePickerRoot = require_YearRangePicker_YearRangePickerRoot.YearRangePickerRoot_default;\nexports.colorToHex = require_color_convert.colorToHex;\nexports.colorToHsb = require_color_convert.colorToHsb;\nexports.colorToHsl = require_color_convert.colorToHsl;\nexports.colorToRgb = require_color_convert.colorToRgb;\nexports.colorToString = require_color_convert.colorToString;\nexports.convertToHsb = require_color_convert.convertToHsb;\nexports.convertToHsl = require_color_convert.convertToHsl;\nexports.convertToRgb = require_color_convert.convertToRgb;\nexports.createContext = require_shared_createContext.createContext;\nexports.getAreaBackgroundStyle = require_color_gradient.getAreaBackgroundStyle;\nexports.getAreaGradient = require_color_gradient.getAreaGradient;\nexports.getChannelName = require_color_channel.getChannelName;\nexports.getChannelRange = require_color_channel.getChannelRange;\nexports.getChannelValue = require_color_channel.getChannelValue;\nexports.getSliderBackgroundStyle = require_color_gradient.getSliderBackgroundStyle;\nexports.getSliderGradient = require_color_gradient.getSliderGradient;\nexports.injectAccordionItemContext = require_Accordion_AccordionItem.injectAccordionItemContext;\nexports.injectAccordionRootContext = require_Accordion_AccordionRoot.injectAccordionRootContext;\nexports.injectAlertDialogContentContext = require_AlertDialog_AlertDialogContent.injectAlertDialogContentContext;\nexports.injectAutocompleteRootContext = require_Autocomplete_AutocompleteRoot.injectAutocompleteRootContext;\nexports.injectAvatarRootContext = require_Avatar_AvatarRoot.injectAvatarRootContext;\nexports.injectCalendarRootContext = require_Calendar_CalendarRoot.injectCalendarRootContext;\nexports.injectCheckboxGroupRootContext = require_Checkbox_CheckboxGroupRoot.injectCheckboxGroupRootContext;\nexports.injectCheckboxRootContext = require_Checkbox_CheckboxRoot.injectCheckboxRootContext;\nexports.injectCollapsibleRootContext = require_Collapsible_CollapsibleRoot.injectCollapsibleRootContext;\nexports.injectColorAreaRootContext = require_ColorArea_ColorAreaRoot.injectColorAreaRootContext;\nexports.injectColorFieldRootContext = require_ColorField_ColorFieldRoot.injectColorFieldRootContext;\nexports.injectColorSliderRootContext = require_ColorSlider_ColorSliderRoot.injectColorSliderRootContext;\nexports.injectComboboxGroupContext = require_Combobox_ComboboxGroup.injectComboboxGroupContext;\nexports.injectComboboxItemContext = require_Listbox_ListboxItem.injectListboxItemContext;\nexports.injectComboboxRootContext = require_Combobox_ComboboxRoot.injectComboboxRootContext;\nexports.injectConfigProviderContext = require_ConfigProvider_ConfigProvider.injectConfigProviderContext;\nexports.injectContextMenuRootContext = require_ContextMenu_ContextMenuRoot.injectContextMenuRootContext;\nexports.injectDateFieldRootContext = require_DateField_DateFieldRoot.injectDateFieldRootContext;\nexports.injectDatePickerRootContext = require_DatePicker_DatePickerRoot.injectDatePickerRootContext;\nexports.injectDateRangeFieldRootContext = require_DateRangeField_DateRangeFieldRoot.injectDateRangeFieldRootContext;\nexports.injectDateRangePickerRootContext = require_DateRangePicker_DateRangePickerRoot.injectDateRangePickerRootContext;\nexports.injectDialogRootContext = require_Dialog_DialogRoot.injectDialogRootContext;\nexports.injectDropdownMenuRootContext = require_DropdownMenu_DropdownMenuRoot.injectDropdownMenuRootContext;\nexports.injectEditableRootContext = require_Editable_EditableRoot.injectEditableRootContext;\nexports.injectHoverCardRootContext = require_HoverCard_HoverCardRoot.injectHoverCardRootContext;\nexports.injectListboxGroupContext = require_Listbox_ListboxGroup.injectListboxGroupContext;\nexports.injectListboxItemContext = require_Listbox_ListboxItem.injectListboxItemContext;\nexports.injectListboxRootContext = require_Listbox_ListboxRoot.injectListboxRootContext;\nexports.injectMenubarMenuContext = require_Menubar_MenubarMenu.injectMenubarMenuContext;\nexports.injectMenubarRootContext = require_Menubar_MenubarRoot.injectMenubarRootContext;\nexports.injectMonthPickerRootContext = require_MonthPicker_MonthPickerRoot.injectMonthPickerRootContext;\nexports.injectMonthRangePickerRootContext = require_MonthRangePicker_MonthRangePickerRoot.injectMonthRangePickerRootContext;\nexports.injectNavigationMenuContext = require_NavigationMenu_NavigationMenuRoot.injectNavigationMenuContext;\nexports.injectNavigationMenuItemContext = require_NavigationMenu_NavigationMenuItem.injectNavigationMenuItemContext;\nexports.injectNumberFieldRootContext = require_NumberField_NumberFieldRoot.injectNumberFieldRootContext;\nexports.injectPaginationRootContext = require_Pagination_PaginationRoot.injectPaginationRootContext;\nexports.injectPinInputRootContext = require_PinInput_PinInputRoot.injectPinInputRootContext;\nexports.injectPopoverRootContext = require_Popover_PopoverRoot.injectPopoverRootContext;\nexports.injectProgressRootContext = require_Progress_ProgressRoot.injectProgressRootContext;\nexports.injectRadioGroupItemContext = require_RadioGroup_RadioGroupItem.injectRadioGroupItemContext;\nexports.injectRadioGroupRootContext = require_RadioGroup_RadioGroupRoot.injectRadioGroupRootContext;\nexports.injectRangeCalendarRootContext = require_RangeCalendar_RangeCalendarRoot.injectRangeCalendarRootContext;\nexports.injectScrollAreaRootContext = require_ScrollArea_ScrollAreaRoot.injectScrollAreaRootContext;\nexports.injectScrollAreaScrollbarContext = require_ScrollArea_ScrollAreaScrollbar.injectScrollAreaScrollbarContext;\nexports.injectSelectGroupContext = require_Select_SelectGroup.injectSelectGroupContext;\nexports.injectSelectItemContext = require_Select_SelectItem.injectSelectItemContext;\nexports.injectSelectRootContext = require_Select_SelectRoot.injectSelectRootContext;\nexports.injectSliderRootContext = require_Slider_SliderRoot.injectSliderRootContext;\nexports.injectSplitterGroupContext = require_Splitter_SplitterGroup.injectPanelGroupContext;\nexports.injectStepperItemContext = require_Stepper_StepperItem.injectStepperItemContext;\nexports.injectStepperRootContext = require_Stepper_StepperRoot.injectStepperRootContext;\nexports.injectSwitchRootContext = require_Switch_SwitchRoot.injectSwitchRootContext;\nexports.injectTabsRootContext = require_Tabs_TabsRoot.injectTabsRootContext;\nexports.injectTagsInputItemContext = require_TagsInput_TagsInputItem.injectTagsInputItemContext;\nexports.injectTagsInputRootContext = require_TagsInput_TagsInputRoot.injectTagsInputRootContext;\nexports.injectTimeFieldRootContext = require_TimeField_TimeFieldRoot.injectTimeFieldRootContext;\nexports.injectTimeRangeFieldRootContext = require_TimeRangeField_TimeRangeFieldRoot.injectTimeRangeFieldRootContext;\nexports.injectToastProviderContext = require_Toast_ToastProvider.injectToastProviderContext;\nexports.injectToggleGroupRootContext = require_ToggleGroup_ToggleGroupRoot.injectToggleGroupRootContext;\nexports.injectToolbarRootContext = require_Toolbar_ToolbarRoot.injectToolbarRootContext;\nexports.injectTooltipProviderContext = require_Tooltip_TooltipProvider.injectTooltipProviderContext;\nexports.injectTooltipRootContext = require_Tooltip_TooltipRoot.injectTooltipRootContext;\nexports.injectTreeRootContext = require_Tree_TreeRoot.injectTreeRootContext;\nexports.injectYearPickerRootContext = require_YearPicker_YearPickerRoot.injectYearPickerRootContext;\nexports.injectYearRangePickerRootContext = require_YearRangePicker_YearRangePickerRoot.injectYearRangePickerRootContext;\nexports.isValidColor = require_color_parse.isValidColor;\nexports.normalizeColor = require_color_parse.normalizeColor;\nexports.parseColor = require_color_parse.parseColor;\nexports.setChannelValue = require_color_channel.setChannelValue;\nexports.setChannelValues = require_color_channel.setChannelValues;\nexports.useBodyScrollLock = require_shared_useBodyScrollLock.useBodyScrollLock;\nexports.useDateFormatter = require_shared_useDateFormatter.useDateFormatter;\nexports.useDirection = require_shared_useDirection.useDirection;\nexports.useEmitAsProps = require_shared_useEmitAsProps.useEmitAsProps;\nexports.useFilter = require_shared_useFilter.useFilter;\nexports.useForwardExpose = require_shared_useForwardExpose.useForwardExpose;\nexports.useForwardProps = require_shared_useForwardProps.useForwardProps;\nexports.useForwardPropsEmits = require_shared_useForwardPropsEmits.useForwardPropsEmits;\nexports.useId = require_shared_useId.useId;\nexports.useLocale = require_shared_useLocale.useLocale;\nexports.useStateMachine = require_shared_useStateMachine.useStateMachine;\nexports.withDefault = require_shared_withDefault.withDefault;","//We implement the backend version of getWHDebugFlags so bridge can access us without going through a recursive dep\n\nimport type { DTAPStage } from \"./concepts\";\n\n/// List global polyfills currently active. This may be needed to align TypeScript hosts configuration\nexport const globalPolyfills: string[] = [];\n\n/// An object with string keys and typed values\nexport interface WellKnownFlags {\n  /** Log RPcs */\n  rpc?: boolean;\n  /** Log web traffic */\n  wrq?: boolean;\n  /** Autoprofile */\n  apr?: boolean;\n  /** IPC */\n  ipc?: boolean;\n  /** async */\n  async?: boolean;\n}\nexport type DebugFlags = WellKnownFlags & { [key: string]: boolean | undefined };\n\nexport type DebugConfig = {\n  tags: readonly string[];\n  outputsession: string;\n  context: string;\n};\n\n/// Empty or no parameter lang is get, otherwise it's a set\nexport type GetSetAssetBase = (assetBase?: string | null) => string | null;\n\nexport type EnvHooks = {\n  currentAssetBase: GetSetAssetBase;\n};\n\n\nconst settingschangedcallbacks = new Array<() => void>;\n\n/* Global debug flags are set by `wh debug`, local flags are prefilled by environment variables.\n   Edits to the debug flags will be applied to the local flags (unless setDebugFlagsOverrideCB returns\n   override records).\n*/\nconst globalDebugFlags: DebugFlags = {}, localDebugFlags: DebugFlags = {};\n\n/** Returns the flag override records. The first record is examined first, then the second, etc. */\nlet debugFlagsOverridesCB: undefined | (() => DebugFlags[]);\n\n/** Override the debug flag override getter. */\nexport function setDebugFlagsOverrideCB(cb: undefined | (() => DebugFlags[])) {\n  debugFlagsOverridesCB = cb;\n}\n\n/* Proxy handler for the published debug flags. Uses the override records (with the first record\n   examined first, then the second, etc.) to override the flags from baseDebugFlags. Setting to `true` sets\n   the flag, `false` disables it and setting to `undefined` has the same effect as deleting the property in the\n   current top record (exposing any value from a lower record, like the debug settings from `wh debug`).\n*/\nclass DebugFlagsProxyHandler implements ProxyHandler<DebugFlags> {\n  private getRecordList(): DebugFlags[] {\n    return [...debugFlagsOverridesCB?.() ?? [], localDebugFlags, globalDebugFlags];\n  }\n\n  get(target: DebugFlags, p: string) {\n    for (const record of this.getRecordList())\n      if (p in record && typeof record[p] !== \"undefined\")\n        return record[p];\n    return undefined;\n  }\n  has(target: DebugFlags, p: string): boolean {\n    return this.get(target, p) !== undefined;\n  }\n  ownKeys(target: DebugFlags): Array<string | symbol> {\n    const keys = new Array<string | symbol>;\n    for (const record of this.getRecordList())\n      for (const key of Reflect.ownKeys(record))\n        if (typeof key === \"string\" && record[key] !== undefined && !keys.includes(key))\n          keys.push(key);\n    return keys;\n  }\n  set(target: DebugFlags, p: string, newValue: boolean | undefined): boolean {\n    const toModify = this.getRecordList()[0];\n    if (typeof newValue === \"boolean\")\n      toModify[p] = newValue;\n    else\n      delete toModify[p];\n\n    runSettingsCallbacks();\n    return true;\n  }\n  deleteProperty(target: DebugFlags, p: string): boolean {\n    const toModify = this.getRecordList()[0];\n    delete toModify[p];\n\n    runSettingsCallbacks();\n    return true;\n  }\n  getOwnPropertyDescriptor(target: DebugFlags, p: string): PropertyDescriptor | undefined {\n    const value = this.get(target, p);\n    return value !== undefined ? { enumerable: true, value, configurable: true } : undefined;\n  }\n}\n\nexport const debugFlags = new Proxy<DebugFlags>({\n  [Symbol.for('nodejs.util.inspect.custom')]: formatForConsoleLogs\n}, new DebugFlagsProxyHandler());\n\nfunction formatForConsoleLogs() {\n  return `DebugFlags [${[...Object.keys(debugFlags)].filter(key => debugFlags[key]).join(\", \")}]`;\n}\n\nfunction runSettingsCallbacks() {\n  for (const cb of [...settingschangedcallbacks]) {\n    try {\n      cb();\n    } catch (e) {\n      console.error(\"Error invoking settings change callback\", cb?.name, e);\n      //ignore, debugFlags can change due to external updates so they're basically signal handlers and there's no real point in crashing whatever was really running\n    }\n  }\n}\n\n/** Update the debugconfig as present in the system configuration record\n    @param settings - debugconfig cell of the system configuration record\n*/\nexport function updateDebugConfig(settings: DebugConfig | null) {\n  const oldenabledflags = Object.keys(globalDebugFlags).sort();\n  const newenabledflags = settings?.tags ? [...settings.tags].sort() : [];\n\n  if (oldenabledflags.join(\",\") !== newenabledflags.join(\",\")) {\n    for (const flag of newenabledflags)\n      globalDebugFlags[flag] = true;\n    for (const flag of oldenabledflags)\n      if (!newenabledflags.includes(flag))\n        delete globalDebugFlags[flag];\n\n    runSettingsCallbacks();\n  }\n  if (debugFlags.async && Error.stackTraceLimit < 100)\n    Error.stackTraceLimit = 100;\n}\n\nexport function registerDebugConfigChangedCallback(cb: () => void) {\n  settingschangedcallbacks.push(cb);\n}\n\nexport function updateLocalDebugFlags(mode: \"enable\" | \"disable\" | \"clear\", flags: string[]): DebugFlags {\n  switch (mode) {\n    case \"enable\":\n    case \"disable\":\n      for (const flag of flags)\n        localDebugFlags[flag] = mode === \"enable\";\n      break;\n    case \"clear\":\n      for (const flag of Object.keys(localDebugFlags))\n        delete localDebugFlags[flag];\n  }\n  runSettingsCallbacks();\n  return { ...globalDebugFlags, ...localDebugFlags };\n}\n\n/** DTAP stage set for this WebHare */\nlet dtapStage: DTAPStage = \"production\";\n\n/** @deprecated We now recommend checking dtapStage against production/acceptance Explicitly */\nlet isLive: boolean = dtapStage === \"production\" || dtapStage === \"acceptance\";\n\n/** The backend base URL. Used for eg. autoconfiguring JSON/RPC */\nlet backendBase = \"\";\n\n/** The global assetbase */\nlet assetBase: string | null = null;\n\n//deprecated variants\n/** @deprecated For WH5.4 and up use 'dtapStage' */\nlet dtapstage: DTAPStage = dtapStage;\n/** @deprecated For WH5.4 and up compare 'dtapStage' for production or acceptance */\nlet islive: boolean = isLive;\n\nlet hooks: EnvHooks | undefined;\nlet hookFactory: (() => EnvHooks) | undefined;\nlet gotHooks = false;\n\nexport function initEnv(setDtapStage: DTAPStage, setBackendBase: string) {\n  dtapStage = setDtapStage;\n  isLive = dtapStage === \"production\" || dtapStage === \"acceptance\";\n  backendBase = setBackendBase;\n\n  dtapstage = dtapStage;\n  islive = isLive;\n}\n\nexport function setEnvHooksFactory(newHookFactory: () => EnvHooks) {\n  if (gotHooks)\n    throw new Error(`The call to setEnvHooksFactory was too late - hooks have already been retrieved once`);\n  hookFactory = newHookFactory;\n}\n\nexport function getEnvHooks() {\n  gotHooks = true;\n  return hookFactory?.();\n}\n\nfunction ensureHooks(): EnvHooks {\n  return hooks ??= getEnvHooks?.() ?? {\n    currentAssetBase: (newAssetBase) => {\n      if (newAssetBase !== undefined)\n        assetBase = newAssetBase;\n      return assetBase;\n    }\n  };\n}\n\n/** Get the base url for assets. This may point towards eg. a CDN\n * @returns The base url for assets, ending with a '/'. null if not set\n */\nexport function getAssetBase(): string | null {\n  return ensureHooks().currentAssetBase();\n}\n\n/** Get the base url for a module's public assets (those located in the module's `public` folder)\n */\nexport function getModulePublicAssetBase(module: string) {\n  return `${getAssetBase() || \"/\"}.wh/mod/${encodeURIComponent(module)}/public/`;\n}\n\n/** Set the base url for assets */\nexport function setAssetBase(base: string | null): void {\n  if (base && !base.endsWith(\"/\"))\n    throw new Error(`Asset base must end with a '/'`);\n\n  ensureHooks().currentAssetBase(base);\n}\n\nexport { dtapStage, isLive, backendBase, localDebugFlags };\nexport { dtapstage, islive }; //deprecated variants\n","\n//Note that @webhare/env does not invoke this API itself. In WebHare @webhare/frontend/src/init uses this to initialize\nexport function getBrowserDebugFlags(varname: string): string[] {\n  const flags = [];\n  const urldebugvar = new URL(location.href).searchParams.get(varname);\n  if (urldebugvar)\n    flags.push(...urldebugvar.split(','));\n\n  //not importing getCookie to solve some import ordering issues\n  if (typeof document !== \"undefined\") { //'document' is undefined in a worker but assetpacks compiled for a ServiceWorker will also load us\n    const debugcookie = document.cookie.match(`(?:^|;)\\\\s*${varname}=([^;]*)`); //TODO escape varname\n    if (debugcookie) {\n      const debugcookievalue = decodeURIComponent(debugcookie[1]);\n      if (debugcookievalue)\n        flags.push(... (debugcookievalue.split('.').filter(flag => !flag.startsWith('sig='))));\n    }\n  }\n\n  if (typeof sessionStorage !== \"undefined\") {\n    const sessionDebug = sessionStorage.getItem(varname);\n    if (sessionDebug)\n      flags.push(...sessionDebug.split(','));\n  }\n\n  return flags;\n}\n","/** Rect describing an elements position */\nexport type Rect = {\n  top: number;\n  bottom: number;\n  left: number;\n  right: number;\n  width: number;\n  height: number;\n};\n\n/** Elements you can set a value on and would have to trigger change and/or input events */\nexport type FormControlElement = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;\n\n/** Types that support querySelector(All) */\ntype QuerySelectorAble = ParentNode | ShadowRoot;\n\nexport function qS<E extends Element = HTMLElement>(startnode: QuerySelectorAble, selector: string): E | null;\nexport function qS<E extends Element = HTMLElement>(selector: string): E | null;\n\n/** Match the first element using a CSS selector\n * @param node_or_selector - The starting node or selector\n * @param selector - The selector to match if the starting node was specified\n * @returns The first matching element or null\n */\nexport function qS<E extends Element>(node_or_selector: QuerySelectorAble | string, selector?: string): E | null {\n  if (typeof node_or_selector === 'string')\n    return document.querySelector<E>(node_or_selector);\n  else if (selector)\n    return node_or_selector.querySelector<E>(selector);\n  return null;\n}\n\n\nexport function qR<E extends Element = HTMLElement>(startnode: QuerySelectorAble, selector: string): E;\nexport function qR<E extends Element = HTMLElement>(selector: string): E;\n\n/** Match a specific element using a CSS selector, requiring it to exist and be unique\n * @param node_or_selector - The starting node or selector\n * @param selector - The selector to match if the starting node was specified\n * @returns The requested element. Throw it the selector doesn't match exactly one element\n */\nexport function qR<E extends Element>(node_or_selector: QuerySelectorAble | string, selector?: string): E {\n  const matches = qSA<E>(node_or_selector as QuerySelectorAble, selector as string);\n  if (matches.length === 1)\n    return matches[0];\n\n  if (typeof node_or_selector !== 'string') {\n    console.error(`${matches.length} elements match selector \\`${selector}\\` with startingpoint`, node_or_selector, matches);\n    throw new Error(`${matches.length} elements match selector \\`${selector}\\` given startingpoint '${node_or_selector.nodeName}'`);\n  } else {\n    console.error(`${matches.length} elements match selector \\`${node_or_selector}\\` in the document`, matches);\n    throw new Error(`${matches.length} elements match selector \\`${node_or_selector}\\` in the document`);\n  }\n}\n\nexport function qSA<E extends Element = HTMLElement>(startnode: QuerySelectorAble, selector: string): E[];\nexport function qSA<E extends Element = HTMLElement>(selector: string): E[];\n\n/** Find multiple elements using a CSS selector\n * @param node_or_selector - The starting node or selector\n * @param selector - The selector to match if the starting node was specified\n * @returns The requested elements.\n */\nexport function qSA<E extends Element>(node_or_selector: QuerySelectorAble | string, selector?: string): E[] {\n  if (typeof node_or_selector === 'string')\n    return Array.from(document.querySelectorAll(node_or_selector));\n  else if (selector)\n    return Array.from(node_or_selector.querySelectorAll(selector));\n\n  return [];\n}\n\n/** Return whether the passed element is a FormControlElement */\nexport function isFormControl(field: Element): field is FormControlElement {\n  return isHTMLElement(field) && [\"INPUT\", \"SELECT\", \"TEXTAREA\"].includes(field.tagName);\n}\n\n/** Return whether the passed element is an editable text field */\nexport function isEditControl(field: Element): field is HTMLElement {\n  return isHTMLElement(field) && ([\"INPUT\", \"TEXTAREA\"].includes(field.tagName) || field.isContentEditable);\n}\n\n/** Test whether node is an Element, even if it's in a different iframe */\nexport function isElement(node: unknown): node is Element {\n  //TODO What is actually going on if defaultView is missing?\n  if (!node || typeof node !== \"object\")\n    return false;\n\n  /* Getting the proto doesn't always work:\n  const proto = (node as Element).ownerDocument.defaultView?.Element;\n  (because our iframes derive off about? not sure) so until someone finds the real answer, we'll do a heuristic\n  */\n\n  /** Analyzing node.constructor.name doesn't work because custom elements don't necessarily have their constructor's name ending in Element\n  return Boolean(\"ownerDocument\" in node && node.constructor.name.match(/Element$/));\n  */\n\n  return Boolean(\"ownerDocument\" in node && (node as Element).nodeType === 1);\n\n}\n\n/** Test whether node is a HTMLElement, even if it's in a different iframe */\nexport function isHTMLElement(node: unknown): node is HTMLElement {\n  return isElement(node) && \"accessKey\" in node;\n}\n\n/**\n * get the relative bound difference between two elements, and return a writable copy\n *\n * @param node - The node for which you need coordinates\n * @param relativeto - Optional reference point. If not set, you just get a 'normal' coordinate object\n */\nexport function getRelativeBounds(node: Element, relativeto?: Element): Rect {\n  if (!relativeto)\n    relativeto = node.ownerDocument.documentElement;\n\n  const nodecoords = node.getBoundingClientRect();\n  const relcoords = relativeto.getBoundingClientRect();\n  return {\n    top: nodecoords.top - relcoords.top,\n    left: nodecoords.left - relcoords.left,\n    right: nodecoords.right - relcoords.left,\n    bottom: nodecoords.bottom - relcoords.top,\n    width: nodecoords.width,\n    height: nodecoords.height\n  };\n}\n\nexport type ParsedLanguageTag = {\n  /** The full tag, eg en-US */\n  tag: string;\n  /** The language code, eg 'en' */\n  language: string;\n  region?: string;\n  /** The script, eg 'Hant' */\n  script?: string;\n};\n\n/** Parse a BCP47 language tag */\nexport function parseLanguageTag(languageTag: string): ParsedLanguageTag {\n  /* https://datatracker.ietf.org/doc/html/rfc5646#section-2.1\n     langtag       = language\n                 [\"-\" script]\n                 [\"-\" region]\n                 *(\"-\" variant)\n                 *(\"-\" extension)\n                 [\"-\" privateuse]\n     BUT: we're limiting ourselves to language, script and region for now\n\n     language      = 2*3ALPHA           ; shortest ISO 639 code\n                    [\"-\" extlang]       ; sometimes followed by\n                                          extended language subtags\n\n                                           extlang       = 3ALPHA              ; selected ISO 639 codes\n                 *2(\"-\" 3ALPHA)      ; permanently reserved\n\n      script        = 4ALPHA              ; ISO 15924 code\n\n      region        = 2ALPHA              ; ISO 3166-1 code\n                    / 3DIGIT              ; UN M.49 code\n\n     Note that we're not yet fully implementing the spec, just the parts we expect to encounter in practice\n  */\n  const match = languageTag.match(/^([a-z]{2,}(-[a-z]{3})?)(-[A-Za-z]{4,})?(-[A-Z]{2}|-\\d{3})?$/);\n  if (!match)\n    throw new Error(`Invalid language tag: ${languageTag}`);\n\n  return {\n    tag: languageTag,\n    language: match[1],\n    ...(match[3] ? { script: match[3].substring(1) } : {}),\n    ...(match[4] ? { region: match[4].substring(1) } : {})\n  };\n}\n\n/** Get the effective language for an element (or the document)\n * @param node - The element for which to get the effective language. If not specified, the documentElement and finally the browser is used\n * @returns The language code, eg. \"nl\" or \"en-GB\"\n */\nexport function getLang(node?: Element): ParsedLanguageTag {\n  if (!node && typeof document !== \"undefined\")\n    node = document.documentElement;\n  const tag = (node?.closest('[lang]')?.getAttribute(\"lang\") || navigator.language || \"en\");\n  return parseLanguageTag(tag);\n}\n","//TODO can we replace ourselves with nodejs util.types in a pure NodeJS environment?\n\nimport type { Money } from \"./money.ts\";\n\nexport function getWHType(obj: unknown): string | null { //not exporting this directly as we hope JS comes up with better solutions for instanceOf not being compatible with realms/reloading\n  // Ideally we'd use symbol but it breaks tree shaking in esbuild, so this is our workaround. Reported as https://github.com/evanw/esbuild/issues/3940\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Can't cleanly type this it seems and it's low level anyway\n  return (obj as any)?.constructor?.[\"__ $whTypeSymbol\"] ?? null;\n}\n\nfunction isCrossRealm(value: unknown): value is object {\n  return Boolean(value // it's not null\n    && typeof value === \"object\" //and it's an object\n    && !(value instanceof Object)); //and it's not an instance of our Object\n}\n\n/** Test whether a value looks like an instance of Money */\nexport function isMoney(value: unknown): value is Money {\n  return getWHType(value) === \"Money\";\n}\n\n/** Test whether a value looks like an instance of Temporal.Instant */\nexport function isTemporalInstant(value: unknown): value is Temporal.Instant {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.Instant');\n}\n\n/** Test whether a value looks like an instance of Temporal.PlainDateTime */\nexport function isTemporalPlainDateTime(value: unknown): value is Temporal.PlainDateTime {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.PlainDateTime');\n}\n\n/** Test whether a value looks like an instance of Temporal.PlainDate */\nexport function isTemporalPlainDate(value: unknown): value is Temporal.PlainDate {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.PlainDate');\n}\n\n/** Test whether a value looks like an instance of Temporal.PlainTime */\nexport function isTemporalPlainTime(value: unknown): value is Temporal.PlainTime {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.PlainTime');\n}\n\n/** Test whether a value looks like an instance of Temporal.ZonedDateTime */\nexport function isTemporalZonedDateTime(value: unknown): value is Temporal.ZonedDateTime {\n  return Boolean(value && typeof value === \"object\" && Symbol.toStringTag in value && value?.[Symbol.toStringTag] === 'Temporal.ZonedDateTime');\n}\n\n/** Test whether a value looks like an instance of Date (assumes no subclasses) */\nexport function isDate(value: unknown): value is Date {\n  return value instanceof Date || (isCrossRealm(value) && value.constructor.name === \"Date\");\n}\n\n/** Test whether a value appears to implement the Blob interface */\nexport function isBlob(value: unknown): value is Blob {\n  return value instanceof Blob || Boolean(value && typeof value === \"object\" && \"size\" in value && \"type\" in value && \"slice\" in value && typeof value.slice === \"function\" && \"stream\" in value && typeof value.stream === \"function\");\n}\n\n/** Test whether a value appears to implement the File interface */\nexport function isFile(value: unknown): value is File {\n  return isBlob(value) && \"name\" in value;\n}\n\n/** Check if the object is probably an Error object. Can't use 'instanceof Error' as an Error might come from a different frame */\nexport function isError(e: unknown): e is Error {\n  return e instanceof Error || (isCrossRealm(e) && \"name\" in e && \"stack\" in e && \"message\" in e);\n}\n\n/** Check if the object looks like a promise */\nexport function isPromise<T>(e: T | Promise<T>): e is Promise<Awaited<T>> {\n  return Boolean(e && typeof (e as Promise<unknown>).then === \"function\" && typeof (e as Promise<unknown>).catch === \"function\");\n}\n\n/** Check the type of a value, return its JS or STD type\n * @param value - The value to check\n * @returns The type of the value. If the value is an object but recognized as any of Money, Date, Blob, Temporal.Instant/PlainDate/PlainDateTime, that type is returned.\n */\nexport function stdTypeOf(value: unknown): \"string\" | \"number\" | \"boolean\" | \"null\" | \"symbol\" | \"bigint\" | \"function\" | \"object\" | \"undefined\" | \"Date\" | \"Money\" | \"Array\" | \"Instant\" | \"PlainDate\" | \"PlainDateTime\" | \"PlainTime\" | \"ZonedDateTime\" | \"File\" | \"Blob\" {\n  const t = typeof value;\n  if (t === \"object\") {\n    if (!value)\n      return \"null\";\n    if (Array.isArray(value))\n      return \"Array\";\n    if (isMoney(value))\n      return \"Money\";\n    if (isBlob(value))\n      return isFile(value) ? \"File\" : \"Blob\";\n    if (isDate(value))\n      return \"Date\";\n    if (isTemporalInstant(value))\n      return \"Instant\";\n    if (isTemporalPlainTime(value))\n      return \"PlainTime\";\n    if (isTemporalPlainDate(value))\n      return \"PlainDate\";\n    if (isTemporalPlainDateTime(value))\n      return \"PlainDateTime\";\n    if (isTemporalZonedDateTime(value))\n      return \"ZonedDateTime\";\n  }\n  return t;\n}\n","/* A math library for safe calculation with money amounts in JS. If you don't\n   know why we need this, try to predict what the following code would print:\n   var cents=0;for(var i=0;i<100;++i)cents+=0.01;cents-=1;console.log(cents);\n   and think twice about whether you want to code anything financial in JS.\n\n   Money values supplied from HareScript should be formatted using FormatJSFinmathMoney\n*/\n\nexport type FinmathInput = string | number;\n\nexport type RoundMode = \"none\" | \"toward-zero\" | \"down\" | \"up\" | \"half-toward-zero\" | \"half-down\" | \"half-up\" | \"toward-infinity\" | \"half-toward-infinity\";\n\nexport interface SplitNumber {\n  num: number;\n  decimals: number;\n}\n\n//a 'price' is a string of the form \"nnn[.NNNN]\"\n\nfunction stripUnneededDecimals(num: number, decimals: number) {\n  //we have a maximum of 5 digits of external precision\n  if (decimals > 5) {\n    // math.round rounds toward positive infinity\n    const isneg = num < 0;\n    if (isneg)\n      num = -num;\n\n    while (decimals > 6) { //truncate excess digits\n      num = Math.floor(num / 10);\n      --decimals;\n    }\n    //round up if 6th decimal >= 5\n    num = Math.round(num / 10);\n    decimals = 5;\n\n    if (isneg)\n      num = -num;\n  }\n\n  //strip unneeded decimals\n  while (decimals > 0 && !(num % 10)) {\n    num /= 10;\n    --decimals;\n  }\n\n  return { num, decimals };\n}\n\nfunction toText(amount: SplitNumber, decimalpoint: string, mindecimals: number) {\n  if (!Number.isSafeInteger(amount.num))\n    throw new Error(\"Result would overflow the safe value range\");\n\n  let num, decimals;\n  ({ num, decimals } = stripUnneededDecimals(amount.num, amount.decimals));\n\n  // Strip sign from number, may need to prefix it\n  const isnegative = num < 0;\n  if (isnegative)\n    num = -num;\n\n  let astext = String(num);\n\n  // Ensure we have enough leading 0's to render the first integer digit\n  if (astext.length <= decimals)\n    astext = '00000000000000000000'.substr(0, decimals + 1 - astext.length) + astext;\n  // make sure we have enough 0's to show mindecimals\n  if (decimals < mindecimals) {\n    astext += '00000000000000000000'.substr(0, mindecimals - decimals);\n    decimals = mindecimals;\n  }\n\n  // insert decimal point if needed\n  if (decimals)\n    astext = astext.substr(0, astext.length - decimals) + decimalpoint + astext.substr(-decimals);\n\n  // add sign if needed\n  astext = (isnegative ? \"-\" : \"\") + astext;\n  return astext;\n}\n\n/** Convert a money of any format to a split number object\n    @param money - Either an integer number or string with a number\n    @returns Split number object\n*/\nfunction splitValue(money: FinmathInput): SplitNumber {\n  if (typeof money === 'number') {\n    if (money !== Math.floor(money))\n      throw new Error(\"Non-integer number passed\");\n    if (!Number.isSafeInteger(money))\n      throw new Error(`The value ${money} is outside the safe value range`);\n    return { num: money, decimals: 0 };\n  }\n  if (typeof money !== 'string')\n    throw new Error(\"Number or string expected, got \" + money);\n\n  const split = money.match(/^(-)?([0-9]*)(\\.([0-9]{0,5})([0-9]*))?$/);\n  if (!split)\n    throw new Error(`Illegal money value received: '${money}'`);\n\n  const sign = split[1] === '-' ? -1 : 1;\n  const decimals = split[3] ? split[4].length : 0;\n  // If there are more than 5 decimals, round up (using halfExpand strategy)\n  const num = sign * (parseInt(split[2] || \"0\") * Math.pow(10, decimals) + (parseInt((split[4] || '')) || 0) + (split[5]?.[0] >= '5' ? 1 : 0));\n  if (!Number.isSafeInteger(num))\n    throw new Error(`The value '${money}' is outside the safe value range`);\n\n  return stripUnneededDecimals(num, decimals);\n}\n\n/** Convert split number into a string\n*/\nfunction joinPrice(parts: SplitNumber): string {\n  return toText(parts, '.', 0);\n}\n\nfunction adjustDecimals(amount: SplitNumber, requiredecimals: number) {\n  const toadd = requiredecimals - amount.decimals;\n  if (toadd <= 0)\n    return;\n\n  let multiplier = 1;\n  for (let idx = 0; idx < toadd; ++idx)\n    multiplier *= 10;\n\n  if (!Number.isSafeInteger(amount.num * multiplier))\n    throw new Error(\"adjustDecimals would overflow the safe value range\");\n\n  amount.num *= multiplier;\n  amount.decimals += toadd;\n}\n\n/** Returns if a price string is valid\n*/\nexport function isValidPrice(money: string) {\n  if (typeof money !== 'string' || !money.match(/[0-9]+(\\.[0-9]{0,5})?$/))\n    return false;\n  return true;\n}\n\nfunction __add(lhs: SplitNumber, rhs: SplitNumber) {\n  //equalize # of decimals, and then it's a simple addition\n  const requiredecimals = Math.max(lhs.decimals, rhs.decimals);\n  adjustDecimals(lhs, requiredecimals);\n  adjustDecimals(rhs, requiredecimals);\n  return { num: lhs.num + rhs.num, decimals: requiredecimals };\n}\n\n/** Adds two numbers together\n*/\nexport function add(amount1: FinmathInput, amount2: FinmathInput): string {\n  return joinPrice(__add(splitValue(amount1), splitValue(amount2)));\n}\n\n/** Subtracts a number from another number\n*/\nexport function subtract(amount: FinmathInput, tosubtract: FinmathInput) {\n  const lhs = splitValue(amount), rhs = splitValue(tosubtract);\n  rhs.num = -rhs.num;\n  return joinPrice(__add(lhs, rhs));\n}\n\nfunction __multiply(lhs: SplitNumber, rhs: SplitNumber) {\n  //ADDME the naive 'add decimals, multiple nums' approach gets you out of the safe range real fast. needs tests\n  return { num: lhs.num * rhs.num, decimals: lhs.decimals + rhs.decimals };\n}\n\n/** Multiplies two numbers together\n*/\nexport function multiply(amount1: FinmathInput, amount2: FinmathInput): string {\n  const lhs = splitValue(amount1), rhs = splitValue(amount2);\n  return joinPrice(__multiply(lhs, rhs));\n}\n\n/** Compares two numbers\n    @param amount1 - Left hand value\n    @param amount2 - Right hand value\n    @returns Returns 0 if amount1 === amount2, -1 if amount1 \\< amount2, 1 if amount1 \\> amount2\n*/\nexport function cmp(amount1: FinmathInput, amount2: FinmathInput) {\n  const diff = __add(splitValue(amount1), __multiply(splitValue(amount2), { num: -1, decimals: 0 }));\n  return diff.num < 0 ? -1 : diff.num === 0 ? 0 : 1;\n}\n\n/** Returns a percentage of an amount\n    @param amount - Original amount\n    @param perc - Percentage of the amount to return\n    @returns Percentage of the amount\n*/\nexport function getPercentageOfAmount(amount: FinmathInput, perc: FinmathInput) {\n  const lhs = splitValue(amount), rhs = splitValue(perc);\n  const result = __multiply(lhs, rhs);\n  result.decimals += 2;\n  return joinPrice(normalize(result));\n}\n\nfunction normalize(amount: SplitNumber) {\n  while (amount.decimals && (amount.num % 10) === 0) {\n    amount.num /= 10;\n    --amount.decimals;\n  }\n  return amount;\n}\n\n/// format a price amount. extend # of decimals to specified # if not enough\nexport function formatPrice(money: FinmathInput, decimalpoint: string, decimals: number) {\n  return toText(splitValue(money), decimalpoint, decimals);\n}\n\n/** Rounds integer to multiple, exposed for testing only\n*/\nexport function __roundIntegerToMultiple(value: number, roundunit: number, mode: RoundMode) {\n  switch (mode) {\n    case \"none\":\n      {\n        // no rounding\n      } break;\n    case \"toward-zero\":\n      {\n        value = Math.trunc(value / roundunit) * roundunit;\n      } break;\n    case \"toward-infinity\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit - 1) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit + 1) / roundunit) * roundunit;\n      } break;\n    case \"down\":\n      {\n        if (value > 0)\n          value = Math.trunc(value / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit + 1) / roundunit) * roundunit;\n      } break;\n    case \"up\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit - 1) / roundunit) * roundunit;\n        else\n          value = Math.trunc(value / roundunit) * roundunit;\n      } break;\n    case \"half-toward-zero\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + (roundunit - 1) / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - (roundunit - 1) / 2) / roundunit) * roundunit;\n      } break;\n    case \"half-toward-infinity\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit / 2) / roundunit) * roundunit;\n      } break;\n    case \"half-down\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + (roundunit - 1) / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - roundunit / 2) / roundunit) * roundunit;\n      } break;\n    case \"half-up\":\n      {\n        if (value > 0)\n          value = Math.trunc((value + roundunit / 2) / roundunit) * roundunit;\n        else\n          value = Math.trunc((value - (roundunit - 1) / 2) / roundunit) * roundunit;\n      } break;\n    default:\n      {\n        throw new Error(`Unknown rounding mode ${mode}`);\n      }\n  }\n  return value;\n}\n\n/** Rounds a value to a multiple of a unit, with a specific rounding mode\n    @param value - Value to round\n    @param unit - The value will be rounded to a mulitple of this unit (except when rounding mode is 'none')\n    @param mode - Rounding mode. Possible values:\n      <ul>\n        <li>none: No rounding</li>\n        <li>toward-zero: Round toward zero</li>\n        <li>down: Round toward negative infity</li>\n        <li>up: Round toward positive infity</li>\n        <li>half-toward-zero: Round nearest multiple, round half of a multiple toward zero</li>\n        <li>half-down: Round nearest multiple, round half of a multiple toward negative infinity</li>\n        <li>half-up: Round nearest multiple, round half of a multiple toward positive infity</li>\n      </ul>\n    @returns The rounded value\n*/\nexport function roundToMultiple(value: FinmathInput, unit: FinmathInput, mode: RoundMode) {\n  const split_value = splitValue(value);\n  const split_unit = splitValue(unit);\n\n  const requiredecimals = Math.max(split_value.decimals, split_unit.decimals);\n  adjustDecimals(split_value, requiredecimals);\n  adjustDecimals(split_unit, requiredecimals);\n\n  const result = { num: __roundIntegerToMultiple(split_value.num, split_unit.num, mode), decimals: split_value.decimals };\n  return joinPrice(result);\n}\n\n/** Returns the minimum of all the arguments\n    @param amount - First value\n    @param amounts - Rest of the values\n    @returns The lowest value among amount and amounts\n*/\nexport function min(amount: FinmathInput, ...amounts: FinmathInput[]) {\n  for (const val of amounts)\n    if (cmp(amount, val) > 0)\n      amount = val;\n  return joinPrice(splitValue(amount));\n}\n\n/** Returns the maximum of all the arguments\n    @param amount - First value\n    @param amounts - Rest of the values\n    @returns The highest value among amount and amounts\n*/\nexport function max(amount: FinmathInput, ...amounts: FinmathInput[]) {\n  for (const val of amounts)\n    if (cmp(amount, val) < 0)\n      amount = val;\n  return joinPrice(splitValue(amount));\n}\n\n/** Returns a power of 10\n    @param exp - Integer power, must be 0 or bigger\n    @returns Requested power of 10\n*/\nfunction getNonNegativePowerOf10(exp: number) {\n  let retval = 1, running_exp = 10;\n  while (exp) {\n    if (exp & 1)\n      retval *= running_exp;\n    running_exp *= running_exp;\n    exp = exp >> 1;\n  }\n  return retval;\n}\n\n/** Divides two values, with 5 decimals of precision\n    @param value - Value To divide\n    @param divisor - Divisor\n    @returns Divided value, with 5 decimals of precision\n*/\nexport function divide(value: FinmathInput, divisor: FinmathInput) {\n  const lhs = splitValue(value), rhs = splitValue(divisor);\n  const mul10exp = lhs.decimals - rhs.decimals - 5;\n  const mulfactor = mul10exp < 0 ? getNonNegativePowerOf10(-mul10exp) : 1;\n  const roundunit = mul10exp > 0 ? getNonNegativePowerOf10(mul10exp) : 1;\n  return joinPrice({ num: __roundIntegerToMultiple(mulfactor * lhs.num / rhs.num, roundunit, \"half-toward-infinity\"), decimals: 5 });\n}\n\nexport function moneyDivide(value: FinmathInput, divisor: FinmathInput) { //divide was added in 5.0. remove this old name eventually\n  return divide(value, divisor);\n}\n\n/** Test whether two values have a specific relation\n    @param lhs - Left hand value\n    @param relation - One of '\\<', '\\<=', '==', '!=', '\\>', '\\>=''\n    @param rhs - Right hand value\n    @returns TRUE if the relation holds\n    @example\n      console.log(finmath.test(1, '\\<', 2)); // prints 'true'\n*/\nexport function test(lhs: FinmathInput, relation: \"<\" | \"<=\" | \"==\" | \"!=\" | \">\" | \">=\", rhs: FinmathInput) {\n  const compareresult = cmp(lhs, rhs);\n  switch (relation) {\n    case '<': return compareresult < 0;\n    case '<=': return compareresult <= 0;\n    case '==': return compareresult === 0;\n    case '!=': return compareresult !== 0;\n    case '>': return compareresult > 0;\n    case '>=': return compareresult >= 0;\n  }\n  throw Error(`Cannot test for unknown relation '${relation}'`);\n}\n","/* A Money type library for safe calculation with money amounts in JS. If you don't\n   know why we need this, try to predict what the following code would print:\n   var cents=0;for(var i=0;i<100;++i)cents+=0.01;cents-=1;console.log(cents);\n   and think twice about whether you want to code anything financial in JS.\n\n   We haven't decideded yet what range Money should support. To keep our options open and keep HS compatbility for now\n   we will fix ourselves to 5 digits (HS compat) and not allow values bigger than 900_000_000 (2**53 / 100000 'number' compatbiility clamped to a more readable number)\n\n  Users should not rely on JS Money keeping this smaller range in the future. Money values supplied from HareScript should be formatted using FormatJSFinmathMoney\n*/\n\nimport * as finmath from \"./finmath.ts\"; //TODO absorb into us as soon as noone externally depends on finmath anymore\nimport { isMoney } from \"./quacks.ts\";\n\nexport type MoneyRoundingMode = \"none\" | \"toward-zero\" | \"down\" | \"up\" | \"half-toward-zero\" | \"half-down\" | \"half-up\" | \"toward-infinity\" | \"half-toward-infinity\";\nexport type MoneyTestTypes = \"<\" | \"<=\" | \"==\" | \"!=\" | \">\" | \">=\";\n\ntype MoneyParameter = Money | string;\n\ninterface SplitNumber {\n  num: number;\n  decimals: number;\n}\n\nexport interface MoneyFormatOptions {\n  //thousand separator. defaults to \"\"\n  thousandsSeparator?: string;\n  //decimal separator. defaults to \".\"\n  decimalSeparator?: string;\n  //minimum # of decimals. defaults to 2\n  minDecimals?: number;\n}\n\nfunction stripUnneededDecimals(num: number, decimals: number) {\n  //we have a maximum of 5 digits of external precision\n  if (decimals > 5) {\n    // math.round rounds toward positive infinity\n    const isneg = num < 0;\n    if (isneg)\n      num = -num;\n\n    while (decimals > 6) { //truncate excess digits\n      num = Math.floor(num / 10);\n      --decimals;\n    }\n    //round up if 6th decimal >= 5\n    num = Math.round(num / 10);\n    decimals = 5;\n\n    if (isneg)\n      num = -num;\n  }\n\n  //strip unneeded decimals\n  while (decimals > 0 && !(num % 10)) {\n    num /= 10;\n    --decimals;\n  }\n\n  return { num, decimals };\n}\n\n/** Convert a money of any format to a split number object\n    @param money - Either an integer number or string with a number\n    @returns Split number object\n*/\nfunction splitValue(money: MoneyParameter): SplitNumber {\n  if (typeof money === 'number') {\n    if (money !== Math.floor(money))\n      throw new Error(\"Non-integer number passed\");\n    if (!Number.isSafeInteger(money))\n      throw new Error(`The value ${money} is outside the safe value range`);\n    return { num: money, decimals: 0 };\n  }\n  if (typeof money !== 'string')\n    throw new Error(\"Number or string expected, got \" + money);\n\n  const split = money.match(/^(-)?([0-9]*)(\\.([0-9]{0,5})([0-9]*))?$/);\n  if (!split)\n    throw new Error(`Illegal money value received: '${money}'`);\n\n  const sign = split[1] === '-' ? -1 : 1;\n  const decimals = split[3] ? split[4].length : 0;\n  // If there are more than 5 decimals, round up (using halfExpand strategy)\n  const num = sign * (parseInt(split[2] || \"0\") * Math.pow(10, decimals) + (parseInt((split[4] || '')) || 0) + (split[5]?.[0] >= '5' ? 1 : 0));\n  if (!Number.isSafeInteger(num))\n    throw new Error(`The value '${money}' is outside the safe value range`);\n\n  return stripUnneededDecimals(num, decimals);\n}\n\nfunction toText(amount: SplitNumber, decimalpoint: string, mindecimals: number, thousandpoint: string) {\n  if (!Number.isSafeInteger(amount.num))\n    throw new Error(\"Result would overflow the safe value range\");\n\n  let { num, decimals } = stripUnneededDecimals(amount.num, amount.decimals);\n\n  // Strip sign from number, may need to prefix it\n  const isnegative = num < 0;\n  if (isnegative)\n    num = -num;\n\n  let astext = String(num);\n\n  // Ensure we have enough leading 0's to render the first integer digit\n  if (astext.length <= decimals)\n    astext = '00000000000000000000'.substring(0, decimals + 1 - astext.length) + astext;\n  // make sure we have enough 0's to show mindecimals\n  if (decimals < mindecimals) {\n    astext += '00000000000000000000'.substring(0, mindecimals - decimals);\n    decimals = mindecimals;\n  }\n\n  let beforepoint = astext.substring(0, astext.length - decimals);\n  const afterpoint = astext.substring(astext.length - decimals);\n\n  // Add thouands points if neeed\n  if (thousandpoint)\n    beforepoint = beforepoint.replaceAll(/\\B(?=(\\d{3})+(?!\\d))/g, thousandpoint);\n\n  return (isnegative ? \"-\" : \"\") + beforepoint + (afterpoint.length ? decimalpoint + afterpoint : \"\");\n}\n\n/** A decimal based JS money type*/\nexport class Money {\n  /** finmath-compatible value */\n  readonly value: string;\n  private static \"__ $whTypeSymbol\" = \"Money\";\n\n  constructor(value: MoneyParameter = \"0\") {\n    this.value = Money.parseParameter(value);\n\n    const intvalue = parseInt(this.value);\n    //We need the number to be in the safe range even after adding 5 decimals\n    if (intvalue <= (Number.MIN_SAFE_INTEGER / 100000) || intvalue >= (Number.MAX_SAFE_INTEGER / 100000))\n      throw new TypeError(`Money value '${value}' is out of range`);\n  }\n\n  private static parseParameter(param: MoneyParameter): string {\n    if (typeof param === \"string\")\n      return toText(splitValue(param), \".\", 0, \"\");\n    if (Money.isMoney(param))\n      return (param as unknown as { value: string }).value;\n\n    throw new TypeError(`Money cannot be constructed out of a value of type ${typeof param}`);\n  }\n\n  static isMoney(value: unknown): value is Money {\n    return isMoney(value);\n  }\n\n  static fromNumber(value: number): Money {\n    return new Money(String(value));\n  }\n\n  /** Adds numbers together\n  */\n  static add(left: MoneyParameter, ...right: MoneyParameter[]): Money {\n    let sum = Money.parseParameter(left);\n    for (const item of right)\n      sum = finmath.add(sum, Money.parseParameter(item));\n    return new Money(sum);\n  }\n\n  /** Subtracts a number from another number\n  */\n  static subtract(left: MoneyParameter, right: MoneyParameter): Money {\n    return new Money(finmath.subtract(Money.parseParameter(left), Money.parseParameter(right)));\n  }\n\n  /** Rounds a value to a multiple of a unit, with a specific rounding mode\n      @param amount - Value to round\n      @param roundto - The value will be rounded to a mulitple of this unit (except when rounding mode is 'none')\n      @param mode - Rounding mode. Possible values:<br>\n        <ul>\n          <li>none: No rounding</li>\n          <li>toward-zero: Round toward zero</li>\n          <li>down: Round toward negative infity</li>\n          <li>up: Round toward positive infity</li>\n          <li>half-toward-zero: Round nearest multiple, round half of a multiple toward zero</li>\n          <li>half-down: Round nearest multiple, round half of a multiple toward negative infinity</li>\n          <li>half-up: Round nearest multiple, round half of a multiple toward positive infity</li>\n        </ul>\n      @returns The rounded value\n  */\n  static roundToMultiple(amount: MoneyParameter, roundto: MoneyParameter, mode: MoneyRoundingMode): Money {\n    return new Money(finmath.roundToMultiple(Money.parseParameter(amount), Money.parseParameter(roundto), mode));\n  }\n\n  /** Compares two numbers\n      @param lhs - Left hand value\n      @param rhs - Right hand value\n      @returns Returns 0 if amount1 === amount2, -1 if amount1 \\< amount2, 1 if amount1 \\> amount2\n  */\n  static cmp(lhs: MoneyParameter, rhs: MoneyParameter): -1 | 0 | 1 {\n    return finmath.cmp(Money.parseParameter(lhs), Money.parseParameter(rhs));\n  }\n\n  /** Test whether two values have a specific relation\n      @param lhs - Left hand value\n      @param relation - One of '\\<', '\\<=', '==', '!=', '\\>', '\\>=''\n      @param rhs - Right hand value\n      @returns TRUE if the relation holds\n      @example\n        console.log(Money.check(1, '\\<', 2)); // prints 'true'\n  */\n  static check(lhs: MoneyParameter, relation: MoneyTestTypes, rhs: MoneyParameter): boolean {\n    return finmath.test(Money.parseParameter(lhs), relation, Money.parseParameter(rhs));\n  }\n\n  /** Multiplies two numbers together\n  */\n  static multiply(left: MoneyParameter, right: MoneyParameter): Money {\n    return new Money(finmath.multiply(Money.parseParameter(left), Money.parseParameter(right)));\n  }\n\n  /** Returns a percentage of an amount\n      @param amount - Original amount\n      @param percentage - Percentage of the amount to return\n      @returns Percentage of the amount\n  */\n  static getPercentage(amount: MoneyParameter, percentage: MoneyParameter): Money {\n    return new Money(finmath.getPercentageOfAmount(Money.parseParameter(amount), Money.parseParameter(percentage)));\n  }\n\n  /** Divides two values, (currently with up to 5 decimals of precision)\n      @param numerator - Value to divide\n      @param divisor - Divisor\n      @returns Divided value\n  */\n  static divide(numerator: MoneyParameter, divisor: MoneyParameter): Money {\n    return new Money(finmath.divide(Money.parseParameter(numerator), Money.parseParameter(divisor)));\n  }\n  /** Returns the minimum of all the arguments\n      @param amount - First value\n      @param amounts - Rest of the values\n      @returns The lowest value among amount and amounts\n  */\n  static min(amount: MoneyParameter, ...amounts: MoneyParameter[]): Money {\n    return new Money(finmath.min(Money.parseParameter(amount), ...(amounts.map(Money.parseParameter))));\n\n  }\n\n  /** Returns the maximum of all the arguments\n      @param amount - First value\n      @param amounts - Rest of the values\n      @returns The highest value among amount and amounts\n  */\n  static max(amount: MoneyParameter, ...amounts: MoneyParameter[]): Money {\n    return new Money(finmath.max(Money.parseParameter(amount), ...(amounts.map(Money.parseParameter))));\n  }\n\n  /** format a price amount. extend # of decimals to specified # if not enough */\n  format(format?: MoneyFormatOptions): string {\n    return toText(splitValue(this.value),\n      format?.decimalSeparator ?? \".\",\n      format?.minDecimals ?? 2,\n      format?.thousandsSeparator ?? \"\");\n  }\n\n  toJSON(): string {\n    return this.value;\n  }\n\n  toString(): string {\n    return this.value;\n  }\n\n  toNumber(): number {\n    return parseFloat(this.value);\n  }\n}\n","import { stdTypeOf } from \"./quacks.ts\";\nimport { Money } from \"./money.ts\";\n\nexport type WildcardTypes = \"?*\";\n\n/** Encode string for use in a regexp\n * @param text - Text to encode\n * @param options - Options for encoding\n * @param options.wildcards - Type of wildcards to encode (defaults to none)\n * @returns Encoded for safe use in a RegExp\n*/\nexport function escapeRegExp(text: string, options?: { wildcards?: WildcardTypes }): string {\n  let mask = text.replaceAll(/[/\\-\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'); // $& means the whole matched string\n  if (options?.wildcards === \"?*\") {\n    mask = mask.replaceAll(\"\\\\*\", \".*\");\n    mask = mask.replaceAll(\"\\\\?\", \".\");\n  }\n  return mask;\n}\n\n/** Create a regular expression from one or more wildcard masks\n * @param masks - One or more masks with '?' and/or '*' wildcards\n * @returns Regular expression string\n*/\nexport function regExpFromWildcards(masks: string | string[], options?: { wildcards?: WildcardTypes; caseInsensitive?: boolean }): RegExp {\n  if (Array.isArray(masks) && masks.length === 0)\n    throw new Error(\"Empty mask list\");\n\n  const code = Array.isArray(masks)\n    ? `^(${masks.map(mask => escapeRegExp(mask, { wildcards: options?.wildcards || \"?*\" })).join('|')})$`\n    : `^${escapeRegExp(masks, { wildcards: options?.wildcards || \"?*\" })}$`;\n  return new RegExp(code, options?.caseInsensitive ? \"i\" : undefined);\n}\n\nfunction isHTMLUnrepresentableChar(curch: number) {\n  return (curch < 32 && curch !== 9 && curch !== 10 && curch !== 13)\n    || (curch >= 128 && curch <= 159);\n}\n\nfunction encodeEntities(str: string, html: boolean) {\n  let s = \"\";\n  for (const char of str) {\n    const curch = char.codePointAt(0);\n    if (curch === undefined || isHTMLUnrepresentableChar(curch))\n      continue;\n    if (curch >= 32 && curch < 128 && curch !== 38 && curch !== 60 && curch !== 62 && (html || curch !== 34 && curch !== 39)) {\n      s += String.fromCodePoint(curch);\n      continue;\n    }\n\n    switch (curch) {\n      case 10:\n        {\n          if (html) {\n            s += \"<br>\";\n            continue;\n          }\n          break;\n        }\n      case 13:\n        {\n          if (html)\n            continue;\n          break;\n        }\n      case 34:\n        {\n          s += \"&quot;\";\n          continue;\n        }\n      case 38:\n        {\n          s += \"&amp;\";\n          continue;\n        }\n      case 39:\n        {\n          s += \"&apos;\";\n          continue;\n        }\n      case 60:\n        {\n          s += \"&lt;\";\n          continue;\n        }\n      case 62:\n        {\n          s += \"&gt;\";\n          continue;\n        }\n    }\n\n    s += \"&#\" + curch + \";\";\n  }\n  return s;\n}\n\nfunction decodeEntities(str: string, html: boolean) {\n  if (html)\n    str = str.replace(/<br *\\/?>/g, \"\\n\");\n\n  str = str.replace(/&#(\\d+);/g, (_, dec) => String.fromCharCode(dec))\n    .replace(/&lt;/g, \"<\")\n    .replace(/&gt;/g, \">\")\n    .replace(/&quot;/g, '\"')\n    .replace(/&apos;/g, \"'\")\n    .replace(/&amp;/g, \"&\");\n\n  return str;\n}\n\nexport type StringEncodings = \"base64url\" | \"attribute\" | \"html\";\n\nexport function encodeString(str: string, encoding: StringEncodings): string {\n  if (encoding === \"base64url\")\n    return btoa(str).replaceAll(\"=\", \"\").replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\");\n  if (encoding === \"attribute\")\n    return encodeEntities(str, false);\n  if (encoding === \"html\")\n    return encodeEntities(str, true);\n\n  throw new Error(`Invalid encoding '${encoding}'`);\n}\n\nexport function decodeString(str: string, encoding: StringEncodings): string {\n  if (encoding === \"base64url\")\n    return atob(str.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\"));\n  if (encoding === \"attribute\")\n    return decodeEntities(str, false);\n  if (encoding === \"html\")\n    return decodeEntities(str, true);\n\n  throw new Error(`Invalid encoding '${encoding}'`);\n}\n\ntype JSONReplacerArgument = ((this: unknown, key: string, value: unknown) => unknown) | undefined;\n\nexport interface StringifyOptions {\n  replacer?: JSONReplacerArgument;\n  space?: string | number;\n  stable?: boolean;\n  ///Encode with types (preserve Money, Date, BigInt). Needs std.parseTyped\n  typed?: boolean;\n  ///What to target: string (like JSON.stringify), script (escapes '/') or attribute (escapes '/' and applies attribute encoding)\n  target?: \"string\" | \"script\" | \"attribute\";\n}\n\n/** Improved JSON encoder\n * @param arg - Object to encode\n * @param options - Encoding options\n*/\nexport function stringify(arg: unknown, options?: StringifyOptions) {\n  const usereplacer: JSONReplacerArgument = options?.stable || options?.typed ? (function (this: unknown, key: string, value: unknown) {\n    if (options.typed) {\n      const origvalue = (this as Record<string, unknown>)[key]; //We can't use 'value' as .toJSON() will already have been invoked\n      const type = stdTypeOf(origvalue);\n      switch (type) {\n        case \"function\":\n          throw new Error(`Cannot stringify property '${key}' of type \"${type}'`);\n        case \"Date\":\n          value = { \"$stdType\": \"Date\", date: (origvalue as Date).toISOString() };\n          break;\n        case \"Money\":\n        case \"bigint\":\n        case \"Instant\":\n        case \"PlainDate\":\n        case \"PlainTime\":\n        case \"PlainDateTime\":\n        case \"ZonedDateTime\":\n          value = { \"$stdType\": type, [type.toLowerCase()]: (origvalue as { toString: () => string }).toString() };\n          break;\n        case \"object\":\n          if (\"$stdType\" in (origvalue as { \"$stdType\": string }))\n            throw new Error(`Cannot encode objects with already embedded '$stdType's`);\n        //fallthrough\n      }\n    }\n    if (options.stable && value && typeof value === \"object\" && !Array.isArray(value))\n      value = Object.fromEntries(Object.entries(value).sort((lhs, rhs) => lhs < rhs ? -1 : lhs === rhs ? 0 : 1));\n    if (options.replacer)\n      value = options.replacer.call(this, key, value);\n    return value;\n  }) : options?.replacer ?? undefined;\n\n  let result = JSON.stringify(arg, usereplacer, options?.space);\n  if (options?.target && [\"script\", \"attribute\"].includes(options.target)) {\n    result = result.replaceAll(\"/\", \"\\\\/\");\n    if (options.target === \"attribute\")\n      result = encodeEntities(result, false);\n  }\n  return result;\n}\n\n/** Decode JSON with types (Generated using stringify with typed:true ) */\nexport function parseTyped(input: string) {\n  return JSON.parse(input, (key, value) => {\n    switch (value?.[\"$stdType\"]) {\n      case \"Money\":\n        return new Money(value.money);\n      case \"Date\":\n        return new Date(value.date);\n      case \"bigint\":\n      case \"BigInt\": //pre wh5.7 spelling\n        return BigInt(value.bigint as string);\n      case \"Instant\":\n      case \"PlainDate\":\n      case \"PlainTime\":\n      case \"PlainDateTime\":\n      case \"ZonedDateTime\":\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we just assume/require you to have Temporal installed if you expect to receive/decode Temporal types. browsers should catch up eventually\n        if (!(globalThis as any).Temporal)\n          throw new Error(`Temporal is not available in this environment, cannot deserialize value of type Temporal.${value[\"$stdType\"]}. Load eg. @webhare/deps/temporal-polyfill to use Temporal types in browsers`);\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we just assume/require you to have Temporal installed if you expect to receive/decode Temporal types. browsers should catch up eventually\n        return (globalThis as any).Temporal[value[\"$stdType\"]].from(value[value[\"$stdType\"].toLowerCase()]);\n      case undefined:\n        return value;\n      default:\n        throw new Error(`Unrecognized type '${value[\"$stdType\"]}'`);\n    }\n  });\n}\n\n/** Generate a slug from a (suggested) (file)name\n * @param text - Text to convert\n * @param options - Options for slugification\n * @param options.separator - Separator to use between words (defaults to '-')\n * @param options.keep - Set of characters to keep in addition to a-z0-9\n * @returns Slugified text or null if we couldn't generate anything reeadable\n */\nexport function slugify(text: string, { separator = \"-\", keep = \"\" }: {\n  separator?: string;\n  keep?: string;\n} = {}): string | null {\n  //This function mixes HS getSafeName with a few more modern approaches\n  const keepclass = `[^a-z0-9${escapeRegExp(keep)}]`;\n  text = text\n    .normalize('NFD')                   // split an accented letter in the base letter and the acent\n    // eslint-disable-next-line no-control-regex\n    .replaceAll(/[\\u0000-\\u001F]/g, '')\n    .replaceAll(/[\\u0300-\\u036f]/g, '')   // remove all previously split accents\n    .replaceAll(/ß/g, 'ss')               // german ss\n    .toLowerCase()\n    .replace(new RegExp(`^${keepclass}+`), \"\") //replace bad characters at the start\n    .replace(new RegExp(`${keepclass}+$`), \"\") //.. and end\n    .replaceAll(new RegExp(`${keepclass}+`, \"g\"), separator); // replace all non alphanumeric/space with a single dash\n\n  return text || null; //we return 'null' on purpose so callers realize we won't necessarily give them a string!\n}\n\n/** Check if an email address is valid in modern times (an emailcheck much closer to what a browser would do, with additional sanity checks. No attempt to allow all legacy styles supported by the RFCs but 99.9%+ sure to be an error if seen submitted in a form\n    @returns True if the email address appears to be a well-formed email address to a non-greybeard\n*/\nexport function isValidEmail(email: string): boolean {\n  if (email.length > 254) //TODO count bytes instead of characters\n    return false;\n\n  return /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*(?:\\.[a-zA-Z0-9-]{2,})$/.test(email);\n}\n\n/** Uppercases a string using the C-locale (so only the ASCII characters a-z are uppercased)\n * @param str - String to uppercase\n * @returns Uppercased string\n */\nexport function toCLocaleUppercase(str: string) {\n  return str.replaceAll(/[a-z]+/g, part => part.toUpperCase());\n}\n\n/** Lowercases a string using the C-locale (so only the ASCII characters A-Z are lowercased)\n * @param str - String to lowercase\n * @returns Lowercased string\n */\nexport function toCLocaleLowercase(str: string) {\n  return str.replaceAll(/[A-Z]+/g, part => part.toLowerCase());\n}\n\n/** Calculate the levenshtein distance between two strings */\nexport function levenshteinDistance(a: string, b: string): number {\n  /* calculateLevenshteinDistance is adopted from https://github.com/gustf/js-levenshtein/blob/master/index.js, licensed MIT © Gustaf Andersson\n    Picked over fastest-levenshtein because a permanent 256KB memory area for a bit more speed doesn't seem worth it\n  */\n  function _min(d0: number, d1: number, d2: number, bx: number, ay: number) {\n    return d0 < d1 || d2 < d1\n      ? d0 > d2\n        ? d2 + 1\n        : d0 + 1\n      : bx === ay\n        ? d1\n        : d1 + 1;\n  }\n\n  if (a === b) {\n    return 0;\n  }\n\n  if (a.length > b.length) {\n    const tmp = a;\n    a = b;\n    b = tmp;\n  }\n\n  let la = a.length;\n  let lb = b.length;\n\n  while (la > 0 && (a.charCodeAt(la - 1) === b.charCodeAt(lb - 1))) {\n    la--;\n    lb--;\n  }\n\n  let offset = 0;\n\n  while (offset < la && (a.charCodeAt(offset) === b.charCodeAt(offset))) {\n    offset++;\n  }\n\n  la -= offset;\n  lb -= offset;\n\n  if (la === 0 || lb < 3) {\n    return lb;\n  }\n\n  let x = 0;\n  let y, d0, d1, d2, d3, dd = 0, dy, ay, bx0, bx1, bx2, bx3;\n\n  const vector: number[] = [];\n\n  for (y = 0; y < la; y++) {\n    vector.push(y + 1);\n    vector.push(a.charCodeAt(offset + y));\n  }\n\n  const len = vector.length - 1;\n\n  for (; x < lb - 3;) {\n    bx0 = b.charCodeAt(offset + (d0 = x));\n    bx1 = b.charCodeAt(offset + (d1 = x + 1));\n    bx2 = b.charCodeAt(offset + (d2 = x + 2));\n    bx3 = b.charCodeAt(offset + (d3 = x + 3));\n    dd = (x += 4);\n    for (y = 0; y < len; y += 2) {\n      dy = vector[y];\n      ay = vector[y + 1];\n      d0 = _min(dy, d0, d1, bx0, ay);\n      d1 = _min(d0, d1, d2, bx1, ay);\n      d2 = _min(d1, d2, d3, bx2, ay);\n      dd = _min(d2, d3, dd, bx3, ay);\n      vector[y] = dd;\n      d3 = d2;\n      d2 = d1;\n      d1 = d0;\n      d0 = dy;\n    }\n  }\n\n  for (; x < lb;) {\n    bx0 = b.charCodeAt(offset + (d0 = x));\n    dd = ++x;\n    for (y = 0; y < len; y += 2) {\n      dy = vector[y];\n      vector[y] = dd = _min(dy, d0, dd, bx0, vector[y + 1]);\n      d0 = dy;\n    }\n  }\n\n  return dd;\n}\n\n/** Return the length of the string in bytes when UTF-8 encoded */\nexport function getUTF8Length(str: string) {\n  return new TextEncoder().encode(str).length;\n}\n\n/** Truncate the string so it's at most len UTF-8 bytes long */\nexport function limitUTF8Length(str: string, len: number) {\n  // TextEncoder.encodeInto writes into the given array until there's no more room to add more valid UTF-8 sequences from the\n  // source. We can use this property to limit the number of bytes by creating an array that has room for at most the given\n  // number of bytes.\n  const utf8array = new Uint8Array(len);\n  // This function returns the actual number of bytes written to the array\n  const { written } = new TextEncoder().encodeInto(str, utf8array);\n  // Decode only the actually written bytes\n  return new TextDecoder().decode(utf8array.subarray(0, written));\n}\n\n/** Update the search parameters in a URL\n * @param inUrl - URL to update\n * @param updates - Updates to apply, use 'null' to delete a variable\n * @returns Updated URL\n */\nexport function updateURL(inUrl: string | URL, updates: Record<string, string | null>): URL {\n  const u = new URL(inUrl);\n  for (const [k, v] of Object.entries(updates)) {\n    if (v === null) {\n      u.searchParams.delete(k);\n    } else {\n      u.searchParams.set(k, v);\n    }\n  }\n  return u;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any -- Cannot specify this without using any */\n\nexport interface EmplaceHandler<ValueType> {\n  insert?: () => ValueType;\n  update?: (current: ValueType) => ValueType;\n}\n\nfunction binarySearchImpl<A, K>(compareFn: (element: A, key: K) => number, contents: A[], searchfor: K, upper_bound: boolean): { present: boolean; index: number } {\n  let first = 0;\n  let len = contents.length;\n  let present = false;\n\n  const cmpbound = upper_bound ? 1 : 0;\n  let unsorted_cmp = 0; // if this is non-0 and cmp is this value, we have an unsorted list\n  while (len > 0) {\n    const half = Math.floor(len / 2);\n    const middle = first + half;\n    const cmp = compareFn(contents[middle], searchfor);\n    if (cmp === 0) {\n      present = true;\n      unsorted_cmp = upper_bound ? -1 : 1;\n    } else if (cmp === unsorted_cmp)\n      throw new Error(`The provided array was not properly sorted!`);\n\n    if (cmp < cmpbound) {\n      first = middle + 1;\n      len -= half;\n      --len;\n    } else {\n      len = half;\n    }\n  }\n  return { present, index: first };\n}\n\n//emplace is based on https://github.com/tc39/proposal-upsert (a Map.prototype.emplace)\n/** Place a value into a Map\n * @param map - The map to place the value into\n * @param key - The key to add/replace\n * @param handler - Callbacks for inserting or updating the value\n * @returns The value that was placed into the map.\n * @throws If the key is not found and no insert handler is provided\n */\nexport function emplace<T extends Map<any, any> | WeakMap<any, any>>(\n  map: T,\n  key: T extends Map<infer K, any> ? K : T extends WeakMap<infer K, any> ? K : never,\n  handler?: T extends Map<any, infer V> ? EmplaceHandler<V> : T extends WeakMap<any, infer V> ? EmplaceHandler<V> : never):\n  T extends Map<any, infer V> ? V : T extends WeakMap<any, infer V> ? V : never {\n  let current = map.get(key);\n  if (current !== undefined) {\n    if (handler?.update) {\n      current = handler.update(current);\n      map.set(key, current);\n    }\n    return current;\n  }\n\n  if (!handler?.insert)\n    throw new Error(\"Key not found and no insert handler provided\");\n\n  const setvalue = handler.insert();\n  map.set(key, setvalue);\n  return setvalue;\n}\n\n// the `| keyof X` is needed to be able to use a `keyof X` type as key parameter in DistributedPick or DistributedOmit in generics\nexport type DistributedKeys<X extends object> = (X extends object ? keyof X : never) | keyof X;\n\n/** Applies Pick to all types in a union. Allows all keys that are present in any object in the union. Warning: You might not be\n    able to use all keys of the union if TypeScript has narrowed the union to a specific type. Eg:\n```typescript\ntype A = { x: number; t: \"a\"; a: number } | { x: number; t: \"b\"; b: number };\nconst a: A = { t: \"a\", a: 1 };\nconst b = pick(a, [\"t\", \"a\", \"b\"]); // No overload matches this call. <snip> Type '\"b\"' is not assignable to type '\"a\" | \"t\" | \"d\"'.\n```\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to return\n    @returns Type with only the specified keys (distributed over the union if present)\n*/\nexport type DistributedPick<X extends object, Y extends DistributedKeys<X>> = X extends object ? Pick<X, keyof X & Y> : never;\n\n/** Applies Omit to all types in a union. Allows all keys that are not present in any object in the union. Warning: You might not be\n    able to use all keys of the union if TypeScript has narrowed the union to a specific type. Eg:\n```typescript\ntype A = { x: number; t: \"a\"; a: number } | { x: number; t: \"b\"; b: number };\nconst a: A = { t: \"a\", a: 1 };\nconst b = omit(a, [\"b\"]); // No overload matches this call. <snip> Type '\"b\"' is not assignable to type '\"a\" | \"t\" | \"d\"'.\n```\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to leave out\n    @returns Type with only the specified keys left out (distributed over the union if present)\n*/\nexport type DistributedOmit<X extends object, Y extends DistributedKeys<X>> = X extends object ? Omit<X, keyof X & Y> : never;\n\n/** Returns an object with a selection of properties\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to return\n    @param obj - Object to pick properties out of\n    @param keys - Names of the properties to pick\n    @returns Resulting object\n*/\nexport function pick<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(obj: T, keys: readonly K[]): DistributedPick<T, K>;\n\n/** Returns an array with a selection of properties\n    @typeParam T - Type of the supplied array\n    @typeParam K - Type of the property keys to return\n    @param arr - Array to pick properties out of\n    @param keys - Names of the properties to pick\n    @returns Resulting array\n*/\nexport function pick<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(arr: T[], keys: readonly K[]): Array<DistributedPick<T, K>>;\n\nexport function pick<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(value: T | T[], keys: readonly K[]): DistributedPick<T, K> | Array<DistributedPick<T, K>> {\n  if (Array.isArray(value))\n    return value.map((elt: T) => pick(elt, keys));\n  const ret = {} as T;\n  keys.forEach((key: K) => {\n    if (key in value)\n      ret[key] = value[key];\n  });\n  return ret as object as DistributedPick<T, K>;\n}\n\n/** Returns an object with a selection of properties left out\n    @typeParam T - Type of the supplied object\n    @typeParam K - Type of the property keys to leave out\n    @param obj - Object to leave properties out of\n    @param keys - Names of the properties to remove\n    @returns Resulting object\n*/\nexport function omit<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(obj: T, keys: readonly K[]): DistributedOmit<T, K>;\n\n/** Returns an array with a selection of properties left out\n    @typeParam T - Type of the supplied array\n    @typeParam K - Type of the property keys to leave out\n    @param arr - Array to leave properties out of\n    @param keys - Names of the properties to leave out\n    @returns Resulting array\n*/\nexport function omit<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(arr: T[], keys: readonly K[]): Array<DistributedOmit<T, K>>;\n\nexport function omit<T extends object, K extends string & NoInfer<DistributedKeys<T>>>(value: T | T[], keys: readonly K[]): DistributedOmit<T, K> | Array<DistributedOmit<T, K>> {\n  if (Array.isArray(value))\n    return value.map((elt: T) => omit(elt, keys));\n  const ret = {} as T;\n  for (const [key, val] of Object.entries(value)) {\n    if (!keys.includes(key as K))\n      ret[key as K] = val;\n  }\n  return ret as object as DistributedOmit<T, K>;\n}\n\n/** Shuffle an array in-place\n * @param array - Array to shuffle\n * @returns The shuffled array\n*/\nexport function shuffle<T>(array: T[]): T[] {\n  for (let i = array.length - 1; i > 0; i--) {\n    const j = Math.floor(Math.random() * (i + 1));\n    [array[i], array[j]] = [array[j], array[i]];\n  }\n  return array;\n}\n\n/** Returns (and TypeScript-asserts) that the specified function is truthy. Handy for adjusting the type of an array when\n * filtering out falsy values\n * @example\n * const myarray: Array&lt;number | null&gt; = [0, null];\n * const filtered: number[] = myarray.filter(isTruthy);\n **/\nexport function isTruthy<T>(a: T): a is (T & {}) {\n  return Boolean(a);\n}\n\n/** Append to array, without overflowing the stack (eg V8 overflows at more than 32K entries)\n * @param array - Array to append to\n * @param values - Values to append\n*/\nexport function appendToArray<T>(array: T[], values: ReadonlyArray<NoInfer<T>>): void {\n  if (values.length < 1000)\n    array.push(...values); //push should be safe enough\n  else for (const value of values) //performance wise this appears just as fast as tricks with pushing blocks of slices\n    array.push(value);\n\n  //not returning the original array to make it clear we're not creating a new one\n}\n\ntype TypedEntriesInternal<T extends object, K extends keyof T> = K extends keyof T ? [K, T[K]] : never;\n\n/** Returns a union of [ key, value ] types for an object */\nexport type TypedEntries<T extends object> = T extends object ? TypedEntriesInternal<T, keyof T & string> : never;\n\n/** Returns an array of key/values of the enumerable own properties of an object, with exact types. Use when\n * no extra properties are expected on the object. Exists because Object.entries returns always string as key type.\n * @param obj - Object that contains the properties and methods\n */\nexport function typedEntries<T extends object>(obj: T): Array<TypedEntries<T>> {\n  return Object.entries(obj) as Array<TypedEntries<T>>;\n}\n\n/** Returns an array of keys of the enumerable own properties of an object, with exact types. Use when\n * no extra properties are expected on the object. Exists because Object.keys returns always string as key type.\n * @param obj - Object that contains the properties and methods\n */\nexport function typedKeys<T extends object>(obj: T): Array<keyof T & string> {\n  return Object.keys(obj) as Array<keyof T & string>;\n}\n\n/** Given a union of [key, value] types, returns the object constructed from those pairs. Exists because\n *  Object.fromEntries does not take the type of the keys and values into account.\n * @typeParam T - Union of [key, value] pairs\n */\nexport type TypedFromEntries<T extends [string, unknown]> = { [C in T as C[0]]: C[1] };\n\n/** Returns an object from an iterable of [key, value] pairs, with exact types. Exists because Object.fromEntries\n * doesn't take the type of the keys and values into account.\n * @param entries - Iterable of [key, value] pairs\n * @returns An object with the same keys and values as the input\n */\nexport function typedFromEntries<T extends [string, unknown]>(entries: Iterable<T>): TypedFromEntries<T> {\n  return Object.fromEntries(entries) as TypedFromEntries<T>;\n}\n\n\nexport class SortedMultiSet<V> {\n  private contents: V[] = [];\n  private compareFn;\n\n  constructor(compareFn: (lhs: V, rhs: V) => number, contents?: V[]) {\n    this.compareFn = compareFn;\n    if (contents)\n      this.addMultiple(contents);\n  }\n\n  get size() {\n    return this.contents.length;\n  }\n\n  at(index: number): V | undefined {\n    return this.contents.at(index);\n  }\n\n  add(value: V): number {\n    const pos = this.upperBound(value);\n    this.contents.splice(pos, 0, value);\n    return pos;\n  }\n\n  addMultiple(values: V[]): void {\n    for (const value of values) {\n      this.add(value);\n    }\n  }\n\n  delete(key: V): void {\n    const [start, limit] = this.range(key);\n    this.contents.splice(start, limit - start);\n  }\n\n  clear() {\n    this.contents.splice(0, this.contents.length);\n  }\n\n  lowerBound(key: Readonly<V>): { present: boolean; index: number } {\n    return binarySearchImpl(this.compareFn, this.contents, key, false);\n  }\n\n  upperBound(key: Readonly<V>): number {\n    return binarySearchImpl(this.compareFn, this.contents, key, true).index;\n  }\n\n  range(key: Readonly<V>): [number, number] {\n    return [this.lowerBound(key).index, this.upperBound(key)];\n  }\n\n  slice(start: number, limit: number): V[] {\n    return this.contents.slice(start, limit);\n  }\n\n  *#sliceIterator(start: number, limit: number): Generator<V, void> {\n    for (let idx = start; idx < limit; ++idx)\n      yield this.contents[idx];\n  }\n\n  sliceRange(key: Readonly<V>): V[] {\n    const [start, limit] = this.range(key);\n    return this.slice(start, limit);\n  }\n\n  rangeIterator(key: Readonly<V>): Iterable<V> {\n    const [start, limit] = this.range(key);\n    return this.#sliceIterator(start, limit);\n  }\n}\n\nexport class SortedMultiMap<K, V> {\n  private compareFn;\n  private contents: Array<[K, V]> = [];\n\n  constructor(compareFn: (lhs: K, rhs: K) => number, contents?: Array<[K, V]>) {\n    this.compareFn = (element: [K, V], key: K) => compareFn(element[0], key);\n    if (contents)\n      this.addMultiple(contents);\n  }\n\n  get size() {\n    return this.contents.length;\n  }\n\n  at(index: number): [K, V] | undefined {\n    return this.contents.at(index);\n  }\n\n  add(key: K, value: V): number {\n    const pos = this.upperBound(key);\n    this.contents.splice(pos, 0, [key, value]);\n    return pos;\n  }\n\n  addMultiple(values: Array<[K, V]>) {\n    for (const [key, value] of values) {\n      this.add(key, value);\n    }\n  }\n\n  delete(key: K): void {\n    const [start, limit] = this.range(key);\n    this.contents.splice(start, limit - start);\n  }\n\n  clear() {\n    this.contents.splice(0, this.contents.length);\n  }\n\n  lowerBound(key: Readonly<K>): { present: boolean; index: number } {\n    return binarySearchImpl(this.compareFn, this.contents, key, false);\n  }\n\n  upperBound(key: Readonly<K>): number {\n    return binarySearchImpl(this.compareFn, this.contents, key, true).index;\n  }\n\n  range(key: Readonly<K>): [number, number] {\n    return [this.lowerBound(key).index, this.upperBound(key)];\n  }\n\n  slice(start: number, limit: number): Array<[K, V]> {\n    return this.contents.slice(start, limit);\n  }\n\n  *#sliceIterator(start: number, limit: number): Generator<[K, V], void> {\n    for (let idx = start; idx < limit; ++idx)\n      yield this.contents[idx];\n  }\n\n  sliceRange(key: Readonly<K>): Array<[K, V]> {\n    const [start, limit] = this.range(key);\n    return this.slice(start, limit);\n  }\n\n  rangeIterator(key: Readonly<K>): Iterable<[K, V]> {\n    const [start, limit] = this.range(key);\n    return this.#sliceIterator(start, limit);\n  }\n}\n","const unlock = Symbol(\"unlock\");\n\n/** A mutex which is only visible in the current JavaScript VM\n\n    @example\n```ts\nconst mutex = new LocalMutex;\n\nusing lock = await mutex.lock();\nlock.release();\n\n// If you'll be relying on automatic release\nusing lock = await mutex.lock();\nvoid(lock);\n```\n\n*/\nexport class LocalMutex {\n  private locked = false;\n  private unlockList = new Array<() => void>;\n\n  /** Lock this mutex\n   * @returns Lock object. Use with `using` to ensure automatic unlock\n   */\n  async lock() {\n    if (this.locked) {\n      const defer = Promise.withResolvers<void>();\n      this.unlockList.push(() => defer.resolve());\n      await defer.promise;\n    } else {\n      this.locked = true;\n    }\n    return new LocalLock(this);\n  }\n\n  [unlock](): void {\n    if (this.unlockList.length > 0)\n      (this.unlockList.shift()!)(); //we're fair... unlock longest waiter\n    else\n      this.locked = false;\n  }\n}\n\n/** Instance of a LocalMutex lock */\nclass LocalLock implements Disposable {\n  private mutex: LocalMutex | null;\n\n  constructor(mutex: LocalMutex) {\n    this.mutex = mutex;\n  }\n  /** Explicitly release the lock\n   * @throws Error if the lock is already released\n  */\n  release() {\n    if (!this.mutex)\n      throw new Error(\"Lock already released\");\n\n    this.mutex[unlock]();\n    this.mutex = null;\n  }\n  [Symbol.dispose]() {\n    this.mutex?.[unlock]();\n  }\n}\n\nexport type { LocalLock };\n","/* frontend-config parses the wh-config object in the browser and mocks any missing data. @webhare/env does not actually expose this config, @webhare/frontend does\n   The frontend configuration is built in PageBuildRequest's 'frontendConfig' member */\n\nimport type { DTAPStage } from \"@webhare/env/src/concepts\";\nimport { debugFlags, initEnv } from \"@webhare/env/src/envbackend\";\nimport { getBrowserDebugFlags } from \"@webhare/env/src/init-browser\";\nimport { getLang } from \"@webhare/dompack/src/tree\";\nimport type { FrontendDataTypes } from \"@webhare/frontend\";\nimport { omit } from \"@webhare/std\";\n\n\n/** The format of the <script id=\"wh-config\"> object  */\nexport type WHConfigScriptData = {\n  //NOTE: existing frontend code doesn't expect site/obj to ever be null. not sure if 'object' provides the best interface or whether we need some sort of 'unknown but an existing object'\n  /** Page (targetobject) specific settings\n   *  @deprecated Use setFrontendData for type-safe settings\n  */\n  obj: { [key: string]: unknown };\n  /** Site specific settings\n   *  @deprecated Use setFrontendData for type-safe settings\n   */\n  site: { [key: string]: unknown };\n\n  /** Numeric server version number (eg 5.02.24 = 50224)\n   *  @deprecated Interpreting numbers (or version strings) is dangerous. Feature flags/testing or limiting your entire module to compatible versions is safer\n  */\n  server: number;\n  /** Root URL of this site */\n  siteRoot: string;\n} & {\n  ///Plugins may add keys at this level\n  [key in keyof FrontendDataTypes]?: FrontendDataTypes[key];\n};\n\nexport type WHConfigScriptData_FromServer = WHConfigScriptData & { dtapStage: DTAPStage };\n\n//names fields can still have when not yet republished\nexport interface WHConfigScriptData_OldPublishFields {\n  islive: boolean;\n  dtapstage: DTAPStage;\n  siteroot: string;\n}\n\n//fallback names with deprecation warnings\nexport interface WHConfigScriptData_LegacyFields {\n  /** @deprecated Use dtapStage in WH5.4+ */\n  islive: boolean;\n  /** @deprecated Use `dtapStage` from \"\\@webhare/env\"; in WH5.4+ */\n  dtapstage: DTAPStage;\n  /** @deprecated Use `getSiteRoot` from \"\\@webhare/frontend\"; in WH5.7+ */\n  siteroot: string;\n}\n\nlet config: WHConfigScriptData_FromServer | undefined;\nlet siteroot;\nlet dtapStage: DTAPStage = \"production\";\n\n//if document is undefined, we're serverside or in a worker\nconst whconfigel = typeof document !== \"undefined\" ? document.querySelector('script#wh-config') : null;\nif (whconfigel?.textContent) {\n  const parsedConfig: WHConfigScriptData_FromServer & WHConfigScriptData_OldPublishFields = JSON.parse(whconfigel.textContent);\n  config = omit(parsedConfig, [\"siteroot\", \"dtapstage\", \"islive\"]);\n\n  //Fallbacks for pages last published with WH5.3 *and* pages published from HareScript which still emit lowercase props\n  siteroot = parsedConfig.siteRoot ?? parsedConfig.siteroot!;\n  dtapStage = parsedConfig.dtapStage ?? parsedConfig.dtapstage;\n}\n\ninitEnv(dtapStage, '/');\n\nif (typeof location !== \"undefined\")\n  for (const flag of getBrowserDebugFlags('wh-debug'))\n    debugFlags[flag] = true;\n\n\n/** @deprecated frontendConfig has been deprecated. Switch to the getFrontendData system */\n// Make sure we have obj/site as some sort of object, to prevent crashes on naive 'if ($wh.config.obj.x)' tests'\nexport const frontendConfig: WHConfigScriptData & WHConfigScriptData_LegacyFields = {\n  server: 0,\n  ...config,\n  obj: config?.obj || {},\n  site: config?.site || {},\n  siteRoot: siteroot || \"\",\n  dtapstage: dtapStage,\n  islive: dtapStage === \"production\" || dtapStage === \"acceptance\",\n  siteroot: siteroot || \"\",\n};\n\nif (typeof document !== \"undefined\") {\n  //@ts-expect-error -- locale isn't supposed to exist - but some old code is still referring to it\n  frontendConfig.locale = getLang().tag;\n}\n\nif (dtapStage === \"development\") { //WH6.0: it's time to hard phase-out the old fields\n  for (const prop of [\"islive\", \"dtapstage\", \"siteroot\", \"locale\"] as const)\n    Object.defineProperty(frontendConfig, prop, {\n      get() { throw new Error(`frontendConfig.${prop} will be removed`); }\n    });\n}\n\n//NOTE: These APIs need to live in init.ts so eg gtm.ts can access us without triggering a CSS reset through frontend.ts. When frontend.ts stops auto-resetting we might move it back\n\nexport function getFrontendData<Type extends keyof FrontendDataTypes>(type: Type, options: { allowMissing: true }): FrontendDataTypes[Type] | null;\nexport function getFrontendData<Type extends keyof FrontendDataTypes>(type: Type, options?: { allowMissing: boolean }): FrontendDataTypes[Type];\n\n/** Get data exported by the response\n * @typeParam Type - The type of data to get\n * @param dataObject - The data object of data to get\n * @param allowMissing - If true, return null if the data object is missing. Otherwise throw an error\n * @example\n```\n  declare module \"@webhare/frontend\" {\n    interface FrontendDataTypes {\n      \"mymodule:type\": {\n        test: number;\n      };\n    }\n  }\n\n  const data = getFrontendData(\"mymodule:type\");\n```\n*/\nexport function getFrontendData<Type extends keyof FrontendDataTypes>(dataObject: Type, { allowMissing = false } = {}): FrontendDataTypes[Type] | null {\n  const retval = config?.[dataObject] as FrontendDataTypes[Type];\n  if (!retval)\n    if (allowMissing)\n      return null;\n    else\n      throw new Error(`Missing frontend data object: ${dataObject}`);\n\n  return retval;\n}\n\n/** Get the current site root\n *\n * @returns The site root URL (ending with a slash)\n*/\nexport function getSiteRoot() { //now an API to improve treeshaking\n  return frontendConfig.siteRoot;\n}\n","// Set up dispose symbols - https://github.com/evanw/esbuild/pull/3192 \"you'll need to polyfill Symbol.dispose if it's not present before you use it.\n\n//@ts-expect-error -- It's marked readonly\nSymbol.dispose ||= Symbol.for('Symbol.dispose');\n//@ts-expect-error -- It's marked readonly\nSymbol.asyncDispose ||= Symbol.for('Symbol.asyncDispose');\n\n// Set up promise resolvers (ES2024)\nPromise.withResolvers ||= function <T>(): PromiseWithResolvers<T> {\n  let resolve: (value: T | PromiseLike<T>) => void;\n  let reject: (reason: Error) => void;\n  const promise = new Promise<T>((_resolve, _reject) => { resolve = _resolve; reject = _reject; });\n  // @ts-expect-error `resolve` and `reject` are assigned synchronously, which isn't picked up by the TypeScript compiler (see\n  // https://github.com/Microsoft/TypeScript/issues/30053)\n  return { promise, resolve, reject };\n};\n\n// Polyfills for https://caniuse.com/?search=groupby - needed until we can assume safari 17.4 as global baseline\nif (!Map.groupBy)\n  Map.groupBy = function <Item, Key>(items: Iterable<Item>, callbackfn: (item: Item, idx: number) => Key): Map<Key, Item[]> {\n    const retval = new Map<Key, Item[]>;\n    let idx = 0;\n    for (const item of items) {\n      const key = callbackfn(item, idx++);\n      let list = retval.get(key);\n      if (!list)\n        retval.set(key, list = []);\n      list.push(item);\n    }\n    return retval;\n  };\n\nif (!Object.groupBy)\n  Object.groupBy = function <Item, Key extends string | number | symbol>(items: Iterable<Item>, callbackfn: (item: Item, idx: number) => Key): Partial<Record<Key, Item[]>> {\n    return Object.fromEntries(Map.groupBy(items, callbackfn).entries()) as Partial<Record<Key, Item[]>>;\n  };\n","/* eslint-disable @typescript-eslint/no-loop-func */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-this-alias */\n\n/* Iterator polyfills (https://caniuse.com/?search=iterator) - stage 4 ES but not in all browsers yet\n   Based on https://github.com/alkihis/iterator-polyfill/tree/master but we removed all the AsyncIterator\n   stuff as that's still stage 2 AND not implemented in TypeScript (as of 5.6)\n\n   We're ignoring a few linting/any issues as we really don't care to maintain this much\n   Fixed an issue with .some - reported as https://github.com/alkihis/iterator-polyfill/issues/6\n*/\n\n(function () {\n  // polyfill already applied / proposal implemented\n  if ('Iterator' in globalThis) {\n    return;\n  }\n\n  // Polyfill for Iterator\n  const IteratorPrototype = {};\n\n  const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());\n  const OriginalIteratorPrototype = Object.getPrototypeOf(ArrayIteratorPrototype);\n\n  Object.setPrototypeOf(OriginalIteratorPrototype, IteratorPrototype);\n\n  Object.defineProperties(IteratorPrototype, {\n    [Symbol.iterator]: {\n      value() {\n        return this;\n      }\n    },\n    map: {\n      *value<T, R>(callback: (value: T) => R): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = callback(value.value);\n          const next_value = yield real_value;\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      },\n    },\n    filter: {\n      *value<T>(callback: (value: T) => boolean): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n          if (callback(real_value)) {\n            next_value = yield real_value;\n            value = it.next(next_value);\n          } else {\n            value = it.next(next_value);\n          }\n        }\n\n        return value.value;\n      },\n    },\n    find: {\n      value<T>(callback: (value: boolean) => T) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            return real_value;\n\n          value = it.next();\n        }\n      }\n    },\n    every: {\n      value<T>(callback: (value: T) => boolean) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (!callback(real_value))\n            return false;\n\n          value = it.next();\n        }\n\n        return true;\n      }\n    },\n    some: {\n      value<T>(callback: (value: T) => boolean) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value)) {\n            it.return();\n            return true;\n          }\n\n          value = it.next();\n        }\n\n        return false;\n      }\n    },\n    toArray: {\n      value(max_count = Infinity) {\n        const values = [];\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (max_count <= 0)\n            return values;\n\n          values.push(real_value);\n\n          if (max_count !== Infinity)\n            max_count--;\n\n          value = it.next();\n        }\n\n        return values;\n      }\n    },\n    take: {\n      *value(limit: number): Generator<any, any, any> {\n        limit = Number(limit);\n        if (limit < 0)\n          throw new RangeError('Invalid limit.');\n\n        const it = this;\n        let value = it.next();\n        let remaining = limit;\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (remaining <= 0)\n            return;\n\n          next_value = yield real_value;\n          value = it.next(next_value);\n          remaining--;\n        }\n\n        return value.value;\n      },\n    },\n    drop: {\n      *value(limit: number): Generator<any, any, any> {\n        limit = Number(limit);\n        if (limit < 0)\n          throw new RangeError('Invalid limit.');\n\n        const it = this;\n        let value = it.next();\n        let remaining = limit;\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (remaining > 0) {\n            value = it.next(next_value);\n            remaining--;\n            continue;\n          }\n\n          next_value = yield real_value;\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      },\n    },\n    asIndexedPairs: {\n      *value(): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let index = 0;\n\n        while (!value.done) {\n          const real_value = value.value;\n          const next_value = yield [index, real_value];\n          value = it.next(next_value);\n          index++;\n        }\n\n        return value.value;\n      }\n    },\n    flatMap: {\n      *value<T, R extends object>(mapper: (value: T) => IterableIterator<R> | R): Generator<any, any, any> {\n        if (typeof mapper !== 'function') {\n          throw new TypeError('Mapper must be a function.');\n        }\n\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n          const mapped = mapper(real_value);\n\n          if (Symbol.iterator in mapped) {\n            next_value = yield* mapped[Symbol.iterator]();\n          } else {\n            next_value = yield mapped;\n          }\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      },\n    },\n    reduce: {\n      value<T, V>(reducer: (acc: V, value: T) => V, initial_value?: V) {\n        let acc = initial_value;\n\n        const it = this;\n        if (acc === undefined) {\n          acc = it.next().value;\n        }\n\n        let value = it.next();\n        while (!value.done) {\n          const real_value = value.value;\n\n          acc = reducer(acc!, real_value);\n\n          value = it.next();\n        }\n\n        return acc;\n      }\n    },\n    forEach: {\n      value<T>(callback: (value: T) => any) {\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          callback(real_value);\n\n          value = it.next();\n        }\n      }\n    },\n    [Symbol.toStringTag]: {\n      value: 'IteratorPrototype'\n    },\n\n    /* OUTSIDE PROPOSAL */\n    count: {\n      value() {\n        let count = 0;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          count++;\n          value = it.next();\n        }\n\n        return count;\n      },\n    },\n    join: {\n      value(string: string) {\n        let final = '';\n        let first = true;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (first) {\n            first = false;\n            final += real_value;\n          } else {\n            final += string + real_value;\n          }\n\n          value = it.next();\n        }\n\n        return final;\n      }\n    },\n    chain: {\n      *value<I>(...iterables: IterableIterator<I>[]) {\n        yield* this;\n\n        for (const it of iterables) {\n          yield* it;\n        }\n      }\n    },\n    zip: {\n      *value<T, O>(...others: IterableIterator<O>[]): Iterator<(T | O)[]> {\n        const it_array = [this, ...others].map((e: any) => Symbol.iterator in e ? e[Symbol.iterator]() : e as Iterator<T | O>);\n        let values = it_array.map(e => e.next());\n        let next_value: any;\n\n        while (values.every(e => !e.done)) {\n          next_value = yield values.map(e => e.value);\n          values = it_array.map(e => e.next(next_value));\n        }\n      },\n    },\n    takeWhile: {\n      *value<T>(callback: (value: T) => boolean): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            next_value = yield real_value;\n          else\n            return;\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      }\n    },\n    dropWhile: {\n      *value<T>(callback: (value: T) => boolean): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n        let finished = false;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (!finished && callback(real_value)) {\n            value = it.next(next_value);\n            continue;\n          }\n\n          finished = true;\n          next_value = yield real_value;\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      }\n    },\n    fuse: {\n      *value(): Generator<any, any, any> {\n        const it = this;\n        let value = it.next();\n        let next_value;\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (real_value !== undefined && real_value !== null)\n            next_value = yield real_value;\n          else\n            return;\n\n          value = it.next(next_value);\n        }\n\n        return value.value;\n      }\n    },\n    partition: {\n      value<T>(callback: (value: T) => boolean) {\n        const partition1 = [], partition2 = [];\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            partition1.push(real_value);\n          else\n            partition2.push(real_value);\n\n          value = it.next();\n        }\n\n        return [partition1, partition2];\n      },\n    },\n    findIndex: {\n      value<T>(callback: (value: T) => boolean) {\n        const it = this;\n        let i = 0;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (callback(real_value))\n            return i;\n\n          value = it.next();\n          i++;\n        }\n\n        return -1;\n      }\n    },\n    max: {\n      value() {\n        let max = -Infinity;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (max < real_value)\n            max = real_value;\n\n          value = it.next();\n        }\n\n        return max;\n      },\n    },\n    min: {\n      value() {\n        let min = Infinity;\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n\n          if (min > real_value)\n            min = real_value;\n\n          value = it.next();\n        }\n\n        return min;\n      },\n    },\n    cycle: {\n      *value(): Generator<any, any, any> {\n        const values = [];\n\n        const it = this;\n        let value = it.next();\n\n        while (!value.done) {\n          const real_value = value.value;\n          values.push(real_value);\n\n          const next_value = yield real_value;\n          value = it.next(next_value);\n        }\n\n        while (true) {\n          yield* values;\n        }\n      },\n    },\n  });\n\n  //iterator.from from https://github.com/rauschma/iterator-helpers-polyfill/\n\n  function isObject(value: unknown) {\n    if (value === null) return false;\n    const t = typeof value;\n    return t === 'object' || t === 'function';\n  }\n\n  function GetIteratorFlattenable<T>(obj: Record<symbol, any>): T {\n    if (!isObject(obj)) {\n      throw new TypeError();\n    }\n    const method = obj[Symbol.iterator];\n    let iterator = undefined;\n    if (typeof method !== 'function') {\n      iterator = obj;\n    } else {\n      iterator = method.call(obj);\n    }\n    if (!isObject(iterator)) {\n      throw new TypeError();\n    }\n    return iterator;\n  }\n\n  if (!('Iterator' in globalThis)) {\n    const Iterator = function Iterator() { };\n\n    Iterator.prototype = IteratorPrototype;\n\n    // @ts-expect-error We're still missing From in this poyfill\n    (globalThis).Iterator = Iterator;\n  }\n\n\n  //----- Static method -----\n  // Must be done after Iterator.prototype was set up,\n  // so that `extends Iterator` works below\n\n  class WrappedIterator<T, TReturn = any, TNext = undefined> extends Iterator<T, TReturn, TNext> {\n    #iterator;\n    constructor(iterator: Iterator<T, TReturn, TNext>) {\n      super();\n      this.#iterator = iterator;\n    }\n    override next(...args: [] | [TNext]): any {\n      return this.#iterator.next(...args);\n    }\n    // `async` helps with line (*)\n    override return(value?: TReturn | PromiseLike<TReturn>): any {\n      const returnMethod = this.#iterator.return;\n      if (returnMethod === undefined) {\n        return { done: true, value: value as any }; // (*)\n      }\n      return returnMethod.call(this.#iterator);\n    }\n  }\n\n  function Iterator_from<T>(value: any) {\n    const iterator = GetIteratorFlattenable<Iterator<T>>(value);\n    if (iterator instanceof Iterator) {\n      return iterator;\n    }\n    // `iterator´ does not support the new API – wrap it so that it does\n    return new WrappedIterator(iterator);\n  }\n\n  Object.defineProperty(\n    Iterator, 'from',\n    {\n      writable: true,\n      enumerable: false,\n      configurable: true,\n      value: Iterator_from,\n    }\n  );\n})();\n","type FormValueList = Array<{ name: string; value: string }>;\n\n/** A navigation instruction encapsulates the next step that a client has to take in eg. a login, payment or wizard flow.\n * Use navigateTo to execute a navigation in a browser\n*/\n\nexport type NavigateInstruction =\n  {\n    type: \"redirect\";\n    url: string;\n  } | {\n    type: \"form\";\n    form: {\n      action: string;\n      vars: FormValueList;\n      method?: \"POST\";\n    };\n  } | {\n    type: \"reload\";\n  } | {\n    type: \"postmessage\";\n    message: unknown;\n    target?: \"parent\" | \"opener\";\n  } | {\n    type: \"close\";\n  };\n\nfunction submitForm(action: string, values: FormValueList, method = \"POST\") {\n  const form = document.createElement(\"form\");\n  form.method = method;\n  form.action = action;\n  form.append(...values.map(item => {\n    const input = document.createElement(\"input\");\n    input.type = \"hidden\";\n    input.name = item.name;\n    input.value = item.value;\n    return input;\n  }));\n  document.body.appendChild(form);\n  form.submit();\n}\n\n/** Navigate to a specific URL (may be hookable by other scripts)\n* @param navigation - Target URL or NavigateInstruction\n*/\nexport function navigateTo(navigation: string | NavigateInstruction) {\n  if (typeof window === \"undefined\")\n    throw new Error(`navigateTo() is not available in this environment`);\n\n  if (typeof navigation === \"string\")\n    navigation = { type: \"redirect\", url: navigation };\n\n  switch (navigation.type) {\n    case \"redirect\":\n      {\n        location.href = navigation.url;\n      } break;\n\n    case \"form\":\n      {\n        submitForm(navigation.form.action, navigation.form.vars, navigation.form.method);\n      } break;\n\n    case \"reload\":\n      {\n        window.location.reload();\n      } break;\n\n    case \"postmessage\":\n      {\n        if (!navigation.target || navigation.target === \"parent\")\n          window.parent.postMessage(navigation.message, \"*\");\n        else if (navigation.target === \"opener\") {\n          window.opener.postMessage(navigation.message, \"*\");\n          window.close();\n        } else\n          throw Error(\"Unknown postmessage target '\" + navigation.target + \"' received\");\n      } break;\n\n    case \"close\":\n      {\n        window.close();\n      } break;\n\n    default:\n      throw new Error(`Unknown navigation type '${(navigation as { type: string }).type}'`);\n  }\n}\n","/* Manages the $wh global, an API for just-in-time debugging */\nimport type { DebugRegistry } from \"@webhare/env\";\nimport { debugFlags } from \"./envbackend\";\n\nlet debugRegFinalizer: FinalizationRegistry<{ type: keyof DebugRegistry; key: string }> | undefined;\n\nexport type WHGlobal = DebugRegistry & {\n  debugFlags: typeof debugFlags;\n  /** Global counter to avoid HMRs from duplicating IDs */\n  nextId: number;\n};\n\ndeclare global {\n  var $wh: WHGlobal;\n}\n\nglobalThis.$wh = {\n  debugFlags,\n  nextId: 1\n} satisfies WHGlobal;\n\nexport function addToDebugRegistry<T extends keyof DebugRegistry>(type: T, key: string, value: NonNullable<ReturnType<NonNullable<DebugRegistry[T]>[string][\"deref\"]>>) {\n  const debugRegistry = globalThis.$wh as unknown as DebugRegistry;\n  //@ts-ignore prevents '>   Type '{}' is not assignable to type 'never'. in jssdk builds, probably because noone yet extends DebugRegistry there\n  debugRegistry[type] ||= {};\n  debugRegFinalizer ||= new FinalizationRegistry(({ type: t, key: k }) => {\n    delete debugRegistry![t]?.[k];\n  });\n\n  if (debugRegistry[type][key])\n    console.error(`Debug registry key ${key} already exists, overwriting it`);\n\n  (debugRegistry[type] as Record<string, unknown>)[key] = new WeakRef(value);\n  debugRegFinalizer.register(value, { type, key });\n}\n","import type { FormControlElement } from \"@webhare/dompack\";\n\nexport const CustomEvent = globalThis.CustomEvent;\n/** Wrap an event to ensure it's target is a HTMLElement\n * @typeParam EventType - The expected event type\n * @typeParam CurrentTargetType - The type of the elemnt you're binding the event to. Optional, defaults to HTMLElement\n * @typeParam RelatedTargetType - The type of the elemnt you're binding the event to. Optional, defaults to HTMLElement\n*/\nexport type DocEvent<EventType extends Event, CurrentTargetType extends HTMLElement = HTMLElement, RelatedTargetType extends HTMLElement = HTMLElement> = EventType & {\n  target: HTMLElement;\n  currentTarget: CurrentTargetType;\n  relatedTarget: RelatedTargetType | null;\n};\n\nexport type DomEventOptions =\n  {\n    bubbles?: boolean;\n    cancelable?: boolean;\n    relatedTarget?: EventTarget;\n    detail?: object;\n  };\n\nexport function dispatchDomEvent(element: EventTarget, eventtype: string, options?: DomEventOptions) {\n  //see here https://developer.mozilla.org/en-US/docs/Web/Events whether an event is bubbles/cancelabel\n  options = {\n    bubbles: [\n      \"input\", \"change\", \"click\", \"contextmenu\", \"dblclick\",\n      \"reset\", \"submit\"\n    ].includes(eventtype),\n    cancelable: [\n      \"animationstart\", \"animationcancel\", \"animationend\", \"animationiteration\",\n      \"beforeunload\",\n      \"click\", \"contextmenu\", \"dblclick\",\n      \"reset\", \"submit\",\n      \"transitionstart\", \"transitioncancel\", \"transitionend\", \"transitionrun\"\n    ].includes(eventtype),\n    ...options\n  };\n\n  if (!element || !(element as Node).ownerDocument)\n    return true; //the element has left the dom... so there's no more bubbling. just drop it\n\n  //FIXME the load/scroll is buggy and we should be probably be using new Event (but an earlier attempt at that triggered quite a few test failures)\n  const createtype = /*[\"load\",\"scroll\"].includes(eventtype) === \"load\" ? \"UIEvents\" :*/[\"focus\", \"blur\", \"focusin\", \"focusout\"].includes(eventtype) ? \"FocusEvent\" : eventtype === \"click\" ? \"MouseEvents\" : \"HTMLEvents\";\n  //we verified its non-null ness above but TS doesn't really understand that\n  const evt = (element as Node).ownerDocument!.createEvent(createtype);\n  evt.initEvent(eventtype, options.bubbles, options.cancelable);\n  if (options.detail)\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we should just rewrite to new Event\n    (evt as any).detail = options.detail;\n  if (options.relatedTarget) //its a readonly prop, so redefine it\n    Object.defineProperty(evt, 'relatedTarget', { value: options.relatedTarget, writable: false });\n\n  //TODO: Should we keep this code?\n  // @ts-expect-error IScroll is a custom Window property set by IScroll\n  if (eventtype === 'click' && window.IScroll)\n    // @ts-expect-error _constructed is a custom Event property used by IScroll\n    evt._constructed = true; //ensure IScroll doesn't blindly cancel our synthetic clicks\n\n  return element.dispatchEvent(evt);\n}\n\n/** Fire the proper modified events (input and/or change) on the element after changing its value\n * @param element - Element to receive event\n * @param options - Event options\n * @deprecated Use changeValue so we can figure out the proper events to fire\n */\nexport function fireModifiedEvents(element: FormControlElement, options?: DomEventOptions) {\n  dispatchDomEvent(element, 'input', options);\n  dispatchDomEvent(element, 'change', options);\n}\n\n//manually fire 'onchange' events. needed for event simulation - DEPRECATED\n/**\n * @param element - Element to receive event\n * @param type - Event type\n * @param options - Event options\n * @deprecated Use dispatchDomEvent instead\n */\nexport function fireHTMLEvent(element: EventTarget, type: string, options?: DomEventOptions) {\n  return dispatchDomEvent(element, type, options);\n}\n\ntype CustomEventParams =\n  {\n    /** Whether this event should bubble up in the DOM */\n    bubbles: boolean;\n    /** Whether this event can be cancelled */\n    cancelable: boolean;\n    /** Custom event information */\n    detail?: unknown;\n    /** Handler to execute if the default isn't prevented by a event listener */\n    defaulthandler?: (evt: CustomEvent) => void;\n  };\n\n/** Fire a custom event\n    @param node - node to fire the event on\n    @param event - event type. You should add this event to the GlobalEventHandlersEventMap for validation in dispatchCustomEvent calls and addEventListener callbacks.\n    @param params - Event options\n    @returns true if the default wasn't prevented\n */\n\nexport function dispatchCustomEvent<K extends string>(\n  node: EventTarget,\n  event: K,\n  params: CustomEventParams & (K extends keyof GlobalEventHandlersEventMap ?\n    GlobalEventHandlersEventMap[K] extends CustomEvent ?\n    { detail: GlobalEventHandlersEventMap[K][\"detail\"] } : unknown : unknown)) {\n\n  if (!params)\n    throw new Error(`Missing dispatchCustomEvent params`);\n  ['bubbles', 'cancelable'].forEach(prop => {\n    if (!(prop in params))\n      throw new Error(`Missing '${prop}' in dispatchCustomEvent params`);\n  });\n\n  const evt = new CustomEvent(event, {\n    bubbles: params.bubbles,\n    cancelable: params.cancelable,\n    detail: params.detail\n  });\n  let defaultaction = true;\n  try {\n    if (!node.dispatchEvent(evt))\n      defaultaction = false; //defaultPrevented is unreliable on IE11, so double check\n  } finally {\n    if (!evt.defaultPrevented && params.defaulthandler && defaultaction) {\n      params.defaulthandler(evt);\n    }\n  }\n  return defaultaction && !evt.defaultPrevented;\n}\n\n/**\n     Change the value of a form element, and fire the correct events as if it were a user change\n *\n    @param element - Element to change\n    @param newvalue - New value\n */\nexport function changeValue(element: FormControlElement, newvalue: string | number | boolean) {\n  if (element.matches(`input[type=radio], input[type=checkbox]`)) {\n    if (Boolean((element as HTMLInputElement).checked) === Boolean(newvalue))\n      return;\n    (element as HTMLInputElement).checked = Boolean(newvalue);\n  } else {\n    //FIXME it's not really clean to assume that this element is changeable - throw for non input/select..\n    const asString = String(newvalue);\n    if ((element as HTMLInputElement).value === asString)\n      return;\n\n    (element as HTMLInputElement).value = String(newvalue);\n  }\n  dispatchDomEvent(element as EventTarget, 'input');\n  dispatchDomEvent(element as EventTarget, 'change');\n}\n\nlet keydata: { mapping: { [key: string]: string } };\n\nfunction initKeyMapping() {\n  keydata =\n  {\n    // Mapping from keyIdentifier/key to key. If not found, translate U+XXXX to the unicode char and return that.\n\n    // List of all current key mappings (and current inconsistencies\n    // at https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values\n    mapping:\n    {\n      \"Del\": \"Delete\", // IE/edge use 'Del' instead of 'Delete'\n      \"Esc\": \"Escape\", // IE/edge use 'Esc' instead of 'Escape'\n      \"OS\": \"Meta\", // Meta key is called OS on IE 9 and Firefox (tested v50)\n      \"Win\": \"Meta\", // Meta key is called Win on IE/Edge\n      \"Scroll\": \"ScrollLock\", // More IE/Edge, from tests\n      \"PrintScreen\": \"Print\", // More IE/Edge, from tests\n      \"MozHomeScreen\": \"GoHome\", // Prior to Firefox 37, the Home button generated a key code of \"Exit\". Starting in Firefox 37, the button generates the key code \"MozHomeScreen\".\n\n      // Internet Explorer 9 and Firefox 36 and earlier return \"Left\", \"Right\", \"Up\", and \"Down\" for the arrow keys, instead of \"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", and \"ArrowDown\".\n      \"Left\": \"ArrowLeft\",\n      \"Right\": \"ArrowRight\",\n      \"Up\": \"ArrowUp\",\n      \"Down\": \"ArrowDown\",\n      // More IE and old Firefox stuff\n      \"Crsel\": \"CrSel\",\n      \"Exsel\": \"ExSel\",\n      \"Nonconvert\": \"NonConvert\",\n      // Internet Explorer 9 and Firefox 36 and earlier report \"Apps\" instead of \"ContextMenu\" for the context menu key.\n      \"Apps\": \"ContextMenu\",\n      // Internet Explorer 9 and Firefox 36 and earlier use \"MediaNextTrack\" and \"MediaPreviousTrack\" instead of \"MediaTrackNext\" and \"MediaTrackPrevious\".\n      \"MediaNextTrack\": \"MediaTrackNext\",\n      \"MediaPreviousTrack\": \"MediaTrackPrevious\",\n      // In Internet Explorer 9, and prior to Firefox 49, \"AudioVolumeUp\", \"AudioVolumeDown\", and \"AudioVolumeMute\" were \"VolumeUp\", \"VolumeDown\", and \"VolumeMute\".\n      // In Firefox 49 they were updated to match the latest specification. The old names are still used on Boot to Gecko.\n      \"VolumeUp\": \"AudioVolumeUp\",\n      \"VolumeDown\": \"AudioVolumeDown\",\n      \"VolumeMute\": \"AudioVolumeMute\",\n      // Firefox added proper support for the \"TV\" key in Firefox 37; before that, this key generated the key code \"Live\".\n      \"Live\": \"TV\",\n      // Internet Explorer 9 and Firefox 36 and earlier identify the zoom toggle button as \"Zoom\". Firefox 37 corrects this to \"ZoomToggle\".\n      \"Zoom\": \"ZoomToggle\",\n      // Internet Explorer 9 and Firefox 36 and earlier use \"SelectMedia\" instead of \"LaunchMediaPlayer\". Firefox 37 through Firefox 48 use \"MediaSelect\". Firefox 49 has been updated to match the latest specification, and to return \"LaunchMediaPlayer\".\n      \"SelectMedia\": \"LaunchMediaPlayer\",\n      \"MediaSelect\": \"LaunchMediaPlayer\",\n      // Google Chrome returns \"LaunchCalculator\" instead of \"LaunchApplication1\". See Chromium bug 612743 for more information.\n      // Google Chrome returns \"LaunchMyComputer\" instead of \"LaunchApplication2\". See Chromium bug 612743 for more information.\n      // (LaunchCalculator and LaunchMyComputer are valid too, so no translation)\n\n      // While older browsers used words like \"Add\", \"Decimal\", \"Multiply\", and so forth modern browsers identify these using the actual character (\"+\", \".\", \"*\", and so forth).\n      \"Multiply\": \"*\",\n      \"Add\": \"+\",\n      \"Divide\": \"/\",\n      \"Subtract\": \"-\",\n      \"Decimal\": \".\", // (mozilla Key_Values doc says depends on region)\n      \"Separator\": \".\", // (mozilla Key_Values doc says depends on region)\n\n      // keyIdenfier spec mapping of non-printable keys: https://www.w3.org/TR/2009/WD-DOM-Level-3-Events-20090908/#keyset-keyidentifiers\n      // Used in safari\n      \"U+0008\": \"Backspace\",\n      \"U+0009\": \"Tab\",\n      \"U+000D\": \"Enter\",\n      \"U+0018\": \"Cancel\",\n      \"U+001B\": \"Escape\",\n      \"U+007F\": \"Delete\",\n      \"U+0300\": \"DeadGrave\",\n      \"U+0301\": \"DeadEacute\",\n      \"U+0302\": \"DeadCircumflex\",\n      \"U+0303\": \"DeadTilde\",\n      \"U+0304\": \"DeadMacron\",\n      \"U+0306\": \"DeadBreve\",\n      \"U+0307\": \"DeadAboveDot\",\n      \"U+0308\": \"DeadUmlaut\",\n      \"U+030A\": \"DeadAboveRing\",\n      \"U+030B\": \"DeadDoubleacute\",\n      \"U+030C\": \"DeadCaron\",\n      \"U+0327\": \"DeadCedilla\",\n      \"U+0328\": \"DeadOgonek\",\n      \"U+0345\": \"DeadIota\",\n      \"U+3099\": \"DeadVoicedSound\",\n      \"U+309A\": \"DeadSemivoicedSound\",\n\n      // keyIdenfier spec mapping to characters: https://www.w3.org/TR/2009/WD-DOM-Level-3-Events-20090908/#keyset-keyidentifiers\n      \"Exclamation\": \"!\",\n      \"DoubleQuote\": \"\\\"\",\n      \"Hash\": \"#\",\n      \"Dollar\": \"$\",\n      \"Ampersand\": \"&\",\n      \"LeftParen\": \"(\",\n      \"RightParen\": \")\",\n      \"Asterisk\": \"*\",\n      \"Plus\": \"+\",\n      \"Percent\": \"%\",\n      \"Comma\": \",\",\n      \"HyphenMinus\": \"-\",\n      \"Period\": \".\",\n      \"Solidus\": \"/\",\n      \"Colon\": \":\",\n      \"Semicolon\": \";\",\n      \"LessThan\": \"<\",\n      \"Equals\": \"=\",\n      \"GreaterThan\": \">\",\n      \"QuestionMark\": \"?\",\n      \"At\": \"@\",\n      \"LeftSquareBracket\": \"[\",\n      \"Backslash\": \"\\\\\",\n      \"RightSquareBracket\": \"]\",\n      \"Circumflex\": \"^\",\n      \"Underscore\": \"_\",\n      \"Grave\": \"`\",\n      \"LeftCurlyBracket\": \"{\",\n      \"Pipe\": \"|\",\n      \"RightCurlyBracket\": \"}\",\n      \"Euro\": \"€\",\n      \"InvertedExclamation\": \"¡\",\n\n      // Safari fixes: viewed in local tests\n      \"U+0010\": \"ContextMenu\"\n    }\n  };\n}\n\nexport type NormalizedKeyboardEvent =\n  {\n    type: string;\n    target: EventTarget | null;\n    key: string;\n    code: string;\n    ctrlKey: boolean;\n    altKey: boolean;\n    location: number;\n    shiftKey: boolean;\n    metaKey: boolean;\n    repeat: boolean;\n    isComposing: boolean;\n  };\n\n/**\n     Returns normalized keyboard event properties, following the current W3C UI Events spec\n *\n    @param evt - Keyboard event\n    @returns Normalized keyboard event data\n */\nexport function normalizeKeyboardEventData(evt: KeyboardEvent): NormalizedKeyboardEvent {\n  // event.key is supported from chrome:51, edge, ff: 29, ie: 9, not in safari\n  // event.keyIdentifier in chrome 26-54, opera 15-41, safara: 5.1\n  // safari doesn't provide either in keypress events, use U+evt.keyCode (uppercase 4-byte hex)\n\n  let key = evt.key;\n  if (!keydata)\n    initKeyMapping();\n  if (keydata.mapping[key])\n    key = keydata.mapping[key];\n  else if (key.startsWith(\"U+\")) // U+xxxx code\n    key = String.fromCodePoint(parseInt(key.substring(2), 16));\n\n  // Seen in chrome 56.0.2924.76 on linux, numpad '.' without numlock returns key \"\\u0000\"\n  if (evt.key === \"\\u0000\" && evt.code === \"NumpadDecimal\")\n    key = \".\";\n\n  return (\n    {\n      type: evt.type,\n      target: evt.target,\n      key: key,\n      code: evt.code || \"Unidentified\",\n      ctrlKey: evt.ctrlKey,\n      altKey: evt.altKey,\n      location: evt.location,\n      shiftKey: evt.shiftKey,\n      metaKey: evt.metaKey,\n      repeat: evt.repeat,\n      isComposing: evt.isComposing\n    });\n}\n\n/**\n * Stop, fully, an event\n *\n * @param event - Event to stop\n */\nexport function stop(event: Event) {\n  event.preventDefault();\n  event.stopImmediatePropagation();\n}\n\n/** Add an event listener to HTMLElements inside a document (which allows us to ensure that 'target' is a HTMLElement for easier typings) */\nexport function addDocEventListener<CurrentTargetType extends HTMLElement, Type extends keyof HTMLElementEventMap>(node: CurrentTargetType, type: Type, listener: (this: CurrentTargetType, ev: DocEvent<HTMLElementEventMap[Type], CurrentTargetType>) => void | Promise<void>, options?: AddEventListenerOptions): void;\nexport function addDocEventListener<CurrentTargetType extends HTMLElement>(node: CurrentTargetType, type: string, listener: (this: CurrentTargetType, evt: DocEvent<Event, CurrentTargetType>) => void | Promise<void>, options?: AddEventListenerOptions): void;\n\nexport function addDocEventListener<CurrentTargetType extends HTMLElement>(node: CurrentTargetType, type: string, listener: (this: CurrentTargetType, evt: DocEvent<Event, CurrentTargetType>) => void | Promise<void>, options?: AddEventListenerOptions): void {\n  node.addEventListener(type, listener as EventListener, options);\n}\n","import { debugFlags } from '@webhare/env';\nimport * as domevents from '../../../modules/system/js/dompack/src/events';\nimport \"@webhare/tsrun/src/polyfills\";\n\nlet locallocks: BusyLock[] = [];\nlet modallocked = false;\nlet uiwatcher: NodeJS.Timeout | null = null;\nlet installedanticancelhandler = false;\n\nlet currentbusymodaldialog: HTMLDialogElement | null = null;\nlet currentbusymodaluserdialog: HTMLDialogElement | null = null;\nlet busymodalcontent: string | HTMLElement | HTMLDialogElement | undefined;\nlet mylockmgr: LockManager | undefined;\n\nexport type BusyModalEvent = CustomEvent<{ show: boolean }>;\n\n// As 'Lock' already exists on the Web (https://developer.mozilla.org/docs/Web/API/Lock) and it's seldom used just use a longer name. Available since WH 5.4\nexport interface UIBusyLock extends Disposable {\n  release(): void;\n  [Symbol.dispose](): void;\n}\n\ndeclare global {\n  interface GlobalEventHandlersEventMap {\n    \"dompack:busymodal\": BusyModalEvent;\n  }\n  interface Window {\n    __dompack_busylockmanager?: LockManager;\n  }\n\n  // __dompack_busylockmanager: LockManager | undefined;  //\n}\n\nfunction getLockmgr(): LockManager {\n  if (!mylockmgr) {\n    mylockmgr = getParentLockManager() || new LockManager;\n    if (typeof window !== \"undefined\")\n      window.__dompack_busylockmanager = mylockmgr;\n  }\n  return mylockmgr;\n}\n\nfunction anyModalLocks() {\n  return locallocks.some(l => l.modal);\n}\n\n/* scheduleCheckUIFree is invoked by release() or when waitUIFree is explicitly called. the call from release() should\n   be a 'fast' path. We schedule a full check for the next tick if there's a chance it might actually find a free UI */\nfunction scheduleCheckUIFree() {\n  if (!uiwatcher && locallocks.length === 0)\n    uiwatcher = setTimeout(() => checkUIFree(), 0);\n}\n\n/* check if the UI is actually free. if so, remove busymodals and resolve waitUIFrees for the benefit of testfw  */\nfunction checkUIFree() {\n  uiwatcher = null;\n\n  if (modallocked && !anyModalLocks()) { //did the last frame-level *modal* lock just get released?\n    modallocked = false;\n    toggleBusyModal(false);\n  }\n\n  if (locallocks.length === 0) {\n    const lockmgr = getLockmgr();\n    lockmgr.busyframes.delete(window); //we won't release our block in the lockmanager until we've had a chance to remove our modal layer\n    lockmgr.checkUIFree(); //to resolve any waitUIFrees. runs in the top-level frame. note that lockmgr cares about ALL ui locks, not just modals\n  }\n}\n\nfunction isDialogElement(el: unknown): boolean {\n  return typeof el === \"object\" && (el as HTMLElement).matches?.(\"dialog\") || false;\n}\n\nfunction checkCancelEvent(evt: Event) {\n  if (modallocked)\n    evt.preventDefault();\n}\n\nfunction toggleBusyModal(show: boolean) {\n  //'islock' is legacy non-camel version. TypeScript typing should help us transition (since 5.3). 'as' shuts up the warning TODO remove 'islock' and the 'as'\n  if (!domevents.dispatchCustomEvent(window, 'dompack:busymodal', { bubbles: true, cancelable: true, detail: { show: show, islock: show } as BusyModalEvent['detail'] }))\n    return; //cancelled!\n\n  if (!installedanticancelhandler) {\n    //capture cancel, as it doesn't bubble up\n    addEventListener(\"cancel\", evt => checkCancelEvent(evt), { capture: true });\n    installedanticancelhandler = true;\n  }\n\n  if (show) {\n    if (isDialogElement(busymodalcontent)) { //the user provided us with an element\n      currentbusymodaluserdialog = busymodalcontent as HTMLDialogElement;\n      currentbusymodaluserdialog.showModal();\n    } else if (busymodalcontent) { //we'll create our own dialog\n      const dialog = document.createElement('dialog');\n      const toembed = typeof busymodalcontent === \"string\" ? document.createTextNode(busymodalcontent) : busymodalcontent.cloneNode(true);\n      dialog.className = \"dompack-busydialog\";\n      dialog.role = \"status\";\n      dialog.ariaLive = \"off\";\n      dialog.append(toembed);\n      document.body.appendChild(dialog);\n      currentbusymodaldialog = dialog;\n      dialog.showModal();\n      return;\n    }\n\n    document.documentElement.classList.add(\"dompack--busymodal\");\n    return;\n  }\n\n  //hiding\n  document.documentElement.classList.remove(\"dompack--busymodal\");\n  if (currentbusymodaluserdialog)\n    currentbusymodaluserdialog.close();\n  if (currentbusymodaldialog) { //we added a dialog to the dom\n    currentbusymodaldialog.close();\n    document.body.removeChild(currentbusymodaldialog);\n    currentbusymodaldialog = null;\n  }\n}\n\nclass LockManager {\n  locks: BusyLock[];\n  busyframes: Set<Window> = new Set;\n  busycounter: number;\n  deferreduipromise: PromiseWithResolvers<boolean> | null;\n\n  //this object is not for external consumption\n  constructor() {\n    this.locks = [];\n    this.busycounter = 0;\n    this.deferreduipromise = null;\n  }\n  add(lock: BusyLock) {\n    this.locks.push(lock);\n    const returnvalue = this.busycounter++;\n    return returnvalue;\n  }\n  release(lock: BusyLock) {\n    const pos = this.locks.indexOf(lock);\n    if (pos === -1) {\n      if (debugFlags.bus) {\n        console.error(\"Duplicate release of busy lock #\" + lock.locknum);\n        console.log(\"Lock allocated:\");\n        console.log(lock.acquirestack);\n        console.log(\"Lock first released:\");\n        console.log(lock.releasestack);\n      }\n      throw new Error(\"Duplicate release of busy lock\");\n    }\n\n    this.locks.splice(pos, 1);\n  }\n  getNumLocks() {\n    return this.locks.length;\n  }\n  //used by child windows to schedule a check in *our* frame (eg before they themselves are unloaded)\n  scheduleCheckUIFree() {\n    scheduleCheckUIFree();\n  }\n  checkUIFree() {\n    if (this.locks.length === 0 && this.busyframes.size === 0 && this.deferreduipromise) {\n      this.deferreduipromise.resolve(true);\n      this.deferreduipromise = null;\n    }\n  }\n  waitUIFree() {\n    if (!this.deferreduipromise)\n      this.deferreduipromise = Promise.withResolvers();\n\n    scheduleCheckUIFree(); //ensures uiwait is released at next tick if no locks are present at all\n    return this.deferreduipromise.promise;\n  }\n  logLocks() {\n    this.locks.forEach(lock => console.log('[bus] lock #' + lock.locknum, lock.acquirestack, lock));\n    console.log(\"[bus] total \" + this.locks.length + \" locks\");\n  }\n  getLockIds() {\n    return this.locks.map(l => \"#\" + l.locknum).join(\", \");\n  }\n}\n\n/** Configure an (accessible) modal dialog\n * @param bmc - What to show in the dialog: either a text or DOM fragment to clone.\n *              If a <dialog> element is passed, this dialog will be used instead of creating a new one.\n */\nexport function setupBusyModal(bmc: NonNullable<typeof busymodalcontent>) {\n  busymodalcontent = bmc;\n}\n\ninterface LockOptions {\n  ///Whether this lock should enable a modality laayer\n  modal?: boolean;\n}\n\nclass BusyLock implements UIBusyLock {\n  modal: boolean;\n  locknum: number;\n  acquirestack: string | undefined;\n  releasestack: string | undefined;\n\n  constructor(options?: LockOptions) {\n    //legacy non-camel name is 'ismodal'\n    this.modal = options?.modal ?? (options as { ismodal?: boolean })?.ismodal ?? false;\n\n    const lockmgr = getLockmgr();\n    this.locknum = lockmgr.add(this);\n    lockmgr.busyframes.add(window);\n    locallocks.push(this);\n\n    if (this.modal && !modallocked) {\n      modallocked = true;\n      toggleBusyModal(true);\n    }\n\n    if (debugFlags.bus) {\n      this.acquirestack = (new Error).stack;\n      console.trace('[bus] Busy lock #' + this.locknum + ' taken. ' + lockmgr.getNumLocks() + \" locks active now: \" + lockmgr.getLockIds());\n    }\n  }\n\n  [Symbol.dispose]() {\n    if (debugFlags.bus)\n      this.releasestack = (new Error).stack;\n\n    const lockmgr = getLockmgr();\n    lockmgr.release(this);\n    const lockpos = locallocks.indexOf(this);\n    locallocks.splice(lockpos, 1);\n\n    if (debugFlags.bus) {\n      console.trace('[bus] Busy lock #' + this.locknum + ' released. ' + lockmgr.getNumLocks() + \" locks active now: \" + lockmgr.getLockIds());\n    }\n\n    scheduleCheckUIFree();\n  }\n\n  release() {\n    this[Symbol.dispose]();\n  }\n}\n\n/** Return a promise resolving as soon as the UI (any accessible frame) is free for at least one tick */\nexport function waitUIFree() {\n  return getLockmgr().waitUIFree();\n}\n\n/**\n     flag userinterface as busy. tests then know not to interact with the UI until the busy flag is released\n *\n    @param options - Options.<br>\n                   - modal: true/false - Whether the lock is a modal lock\n */\nexport function flagUIBusy(options?: LockOptions): UIBusyLock {\n  return new BusyLock(options);\n}\n\nexport function getUIBusyCounter() {\n  return getLockmgr().busycounter;\n}\n\nfunction getParentLockManager(): LockManager | null {\n  try { //we're accessing a parent window, so we may hit security exceptions\n    if (!(window.parent?.__dompack_busylockmanager))\n      return null;\n\n    //if we connected to a parent...  deregister our locks, eg. if parent navigated our frame away\n    window.addEventListener(\"pagehide\", () => {\n      if (debugFlags.bus)\n        console.log(\"[bus] Frame unloading, \" + locallocks.length + \" locks pending.\", locallocks.map(l => \"#\" + l.locknum).join(\", \"), locallocks);\n\n      //switch to local instance in case anyone still tries to touch these locks during unload\n      const lockmgr = getLockmgr();\n      const locallockmgr = new LockManager;\n      locallocks.forEach(lock => { lockmgr.release(lock); locallockmgr.add(lock); });\n      locallocks = [];\n\n      lockmgr.busyframes.delete(window); //explicitly remove us so we won't be waited upon\n      lockmgr.scheduleCheckUIFree();\n      mylockmgr = locallockmgr;\n    });\n\n    return window.parent.__dompack_busylockmanager;\n  } catch (e) {\n    return null;\n  }\n}\n","\n/* Regex to identify dimensionless style sttributes. copied from old version of preact/src/constants.js (MIT)\n   meant to capture:\n  { boxFlex:1, boxFlexGroup:1, columnCount:1, fillOpacity:1, flex:1, flexGrow:1,\n    flexPositive:1, flexShrink:1, flexNegative:1, fontWeight:1, lineClamp:1, lineHeight:1,\n    opacity:1, order:1, orphans:1, strokeOpacity:1, widows:1, zIndex:1, zoom:1\n*/\nconst IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;\n\nexport { qS, qSA } from '@webhare/dompack/src/tree.ts';\n\nfunction generateInsertList(nodes: Array<string | Node>) {\n  if (nodes.length === 1)\n    return typeof nodes[0] === 'string' ? document.createTextNode(nodes[0]) : nodes[0];\n\n  const frag = document.createDocumentFragment();\n  nodes.forEach(node => frag.appendChild(typeof node === 'string' ? document.createTextNode(node) : node));\n  return frag;\n}\n\n/** @deprecated Use node.matches() */\nexport function matches(node: Element, selector: string): boolean {\n  //only invoke 'matches' if it exists. it *should* but past versions of dompack.matches would check for it too (and thus not fail if you passed in a string instead of a Node)\n  return node.matches?.(selector);\n}\n/** @deprecated Use node.closest() */\nexport function closest(node: Element, selector: string) {\n  if (node.closest)\n    return node.closest(selector);\n  //TODO: Warn about out-of-date browser?\n  let testNode: Element | null = node;\n  for (; testNode && !matches(testNode, selector); testNode = testNode.parentElement)\n    /*iterate*/;\n  return testNode;\n}\n//implements contains. TODO we only really need this on IE11, which doesn't consider a text node a child, we can probably fall back to native elsewhere ?\n/** @deprecated Use node.contains() */\nexport function contains(ancestor: Node, child: Node) {\n  if (ancestor.contains)\n    return ancestor.contains(child);\n  //TODO: Warn about out-of-date browser?\n  for (let testNode: Node | null = child; testNode; testNode = testNode.parentNode)\n    if (testNode === ancestor)\n      return true;\n  return false;\n}\n//insert a range of nodes before a node: https://dom.spec.whatwg.org/#dom-childnode-before\n/** @deprecated Use node.before() */\nexport function before(node: ChildNode, ...nodes: Array<string | Node>) {\n  if (node.before) {\n    node.before(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.insertBefore(generateInsertList(nodes), node);\n}\n//insert a range of nodes after a node: https://dom.spec.whatwg.org/#dom-childnode-after\n/** @deprecated Use node.after() */\nexport function after(node: ChildNode, ...nodes: Array<string | Node>) {\n  if (node.after) {\n    node.after(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.insertBefore(generateInsertList(nodes), node.nextSibling);\n}\n//replace node with a set of nodes : https://dom.spec.whatwg.org/#dom-childnode-replacewith\n/** @deprecated Use node.replaceWith() */\nexport function replaceWith(node: ChildNode, ...nodes: Array<string | Node>) {\n  if (node.replaceWith) {\n    node.replaceWith(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.replaceChild(generateInsertList(nodes), node);\n}\n//remove node with a set of nodes : https://dom.spec.whatwg.org/#dom-childnode-remove\n/** @deprecated Use node.remove() */\nexport function remove(node: ChildNode) {\n  if (node.remove) {\n    node.remove();\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  if (node.parentNode)\n    node.parentNode.removeChild(node);\n}\n//insert nodes at start: https://dom.spec.whatwg.org/#dom-parentnode-prepend\n/** @deprecated Use node.prepend() */\nexport function prepend(node: ParentNode, ...nodes: Array<string | Node>) {\n  if (node.prepend) {\n    node.prepend(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  node.insertBefore(generateInsertList(nodes), node.firstChild);\n}\n//insert nodes at end: https://dom.spec.whatwg.org/#dom-parentnode-append\n/** @deprecated Use node.append() */\nexport function append(node: ParentNode, ...nodes: Array<string | Node>) {\n  if (node.append) {\n    node.append(...nodes);\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  node.appendChild(generateInsertList(nodes));\n}\n\n/**\n * Toggle a single class\n *\n * @param node - Node to modify\n * @param classname - Class to toggle\n * @param settoggle - true to enable, false to disable, undefined to toggle\n * @deprecated Just use classList.toggle on the node itself\n */\n/** @deprecated Use classList.toggle() */\nexport function toggleClass(node: Element, classname: string, settoggle?: boolean) {\n  if (arguments.length === 2) //in old dompack, 2 argument version toggled and 3 argument version toggled off. match that behavior\n    node.classList.toggle(classname);\n  else\n    node.classList.toggle(classname, settoggle);\n}\n\n/**\n     Toggle classes in a node\n *\n    @param node - Node which classes to toggle\n    @param toggles - Object, all keys will be added/removed based on the truthyness of their values\n */\nexport function toggleClasses(node: Element, toggles: { [key: string]: boolean }) {\n  if (typeof (toggles) !== \"object\")\n    throw new Error(\"Expected an object with keys as classnames\");\n  Object.keys(toggles).forEach(key => node.classList[toggles[key] ? \"add\" : \"remove\"](key));\n}\n\n/* remove the contents of an existing node */\n/** @deprecated Use node.replaceChildren() */\nexport function empty(node: Element) {\n  if (node.replaceChildren) {\n    node.replaceChildren();\n    return;\n  }\n  //TODO: Warn about out-of-date browser?\n  while (node.lastChild)\n    node.removeChild(node.lastChild);\n}\n\nexport function isDomReady() {\n  //ensure no domready events can run if there will never be a dom\n  return typeof document !== \"undefined\" && (document.readyState === \"interactive\" || document.readyState === \"complete\");\n}\n\n/* run the specified function 'on ready'. adds to DOMContentLoaded if dom is not ready yet. Exceptions/rejections from the ready handler will not be fatal to the rest of code execution */\nexport function onDomReady(callback: () => unknown | Promise<unknown>) {\n  if (isDomReady()) {\n    try {\n      void callback(); //Ignore unhandled rejections\n    } catch (e) { // We don't want our caller to 'stop' due to a domready exception as its usually the toplevel initialization code, so log the exception ourselves\n      void Promise.reject(new Error(\"Synchronous onDomReady handler failed\", { cause: e })); //Let it propagate as a standard unhandled rejection\n    }\n  } else\n    document.addEventListener(\"DOMContentLoaded\", () => void callback());\n}\n\n//parse JSON data, throw with more info on parse failure\nexport function getJSONAttribute<T>(node: Element, attributename: string): T | null {\n  try {\n    if (node.hasAttribute(attributename))\n      return JSON.parse(node.getAttribute(attributename) as string);\n  } catch (e) {\n    console.error(\"JSON parse failure on attribute '\" + attributename + \"' of node\", node);\n    throw e;\n  }\n  return null;\n}\n\n/**\n     Get the base URI of the current document. IE11 doesn't implement document.baseURI\n *\n    @param doc - Document to query. Defaults to window.document\n    @deprecated Use document.baseURI\n */\nexport function getBaseURI(doc: Document | undefined) {\n  if (!doc)\n    doc = window.document;\n  if (doc.baseURI)\n    return doc.baseURI;\n\n  const base = doc.querySelector('base');\n  if (base && base.href)\n    return base.href;\n  return doc.URL;\n}\n\n/**\n     Sets multiple styles on a node, automatically adding 'px' to numbers when appropriate\n    (can be used as replacement for Mootools .setStyles)\n *\n * @param node - Node to update\n * @param value - Styles to set\n */\nexport function setStyles(node: HTMLElement, value?: string | { [key: string]: string | number }) {\n  if (!value)\n    node.style.cssText = '';\n  else if (typeof value === 'string')\n    node.style.cssText = value || '';\n  else {\n    for (const [key, propvalue] of Object.entries(value)) {\n      // for numbers, add 'px' if the constant isn't dimensionless (eg zIndex)\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any -- we don't know which keys will be set\n      (node.style as any)[key] = typeof value[key] === 'number' && IS_NON_DIMENSIONAL.test(key) === false\n        ? propvalue + 'px'\n        : propvalue;\n    }\n  }\n}\n","import * as domtree from './tree';\nimport * as domevents from './events';\n\nexport type TakeFocusEvent = CustomEvent<{ options?: FocusOptions }>;\n\ndeclare global {\n  interface GlobalEventHandlersEventMap {\n    \"dompack:takefocus\": TakeFocusEvent;\n  }\n}\n\ntype RegistrationHandler<E extends Element = HTMLElement> = (node: E, index?: number) => void;\ntype ComponentRegistration<E extends Element = HTMLElement> =\n  {\n    selector: string;\n    handler: RegistrationHandler<E>;\n    index: number;\n    num: number;\n    afterdomready: boolean;\n  };\n\nconst components: Array<ComponentRegistration<Element>> = [];\nconst map = new WeakMap();\n\n//is a node completely in the dom? if we can find a sibling anywhere, it must be closed\nfunction isNodeCompletelyInDom(node: Element | null) {\n  for (; node; node = node.parentElement)\n    if (node.nextSibling)\n      return true;\n  return false;\n}\nfunction processRegistration<E extends Element>(item: E, reg: ComponentRegistration<E>, domready: boolean) {\n  if (!domready && !isNodeCompletelyInDom(item))\n    return; //not safe to register\n\n  if (!map.has(item))\n    map.set(item, [reg.num]);\n  else {\n    const list = map.get(item);\n    if (list.includes(reg.num))\n      return;\n    list.push(reg.num);\n  }\n  reg.handler(item, reg.index++); //note: if an exception is reported from Object.handler,\n}\nfunction applyRegistration<E extends Element>(reg: ComponentRegistration<E>, startnode?: Element) {\n  const domready = domtree.isDomReady();\n  if (reg.afterdomready && !domready)\n    return;\n\n  const items = Array.from((startnode || document).querySelectorAll(reg.selector)) as E[];\n  if (startnode?.matches(reg.selector))\n    items.unshift(startnode as E); //if startnode matches it has to be an E\n\n  items.forEach(item => {\n    try {\n      processRegistration<E>(item, reg, domready);\n    } catch (e) {\n      console.error(\"Exception handling registration of\", item, \"for rule\", reg.selector);\n      console.log(\"Registration\", reg);\n      if (e instanceof Error) {\n        console.log(e, e.stack);\n        if (window.onerror) {\n          // Send to onerror to trigger exception reporting\n          try {\n            // @ts-expect-error: fileName, lineNumber and columnNumber are non-standard\n            window.onerror(e.message, e.fileName || \"\", e.lineNumber || 1, e.columNumber || 1, e);\n          } catch (e2) { }\n        }\n      } else\n        console.log(e);\n    }\n  });\n}\n\n/* A focus implementation that allows the node to intercept focused, allowing eg\n   radio/checkbox replacements to redirect focus but also explicitly preventing\n   focus of a disabled element\n   Returns true when the focus operation was successfull or handled by an event handler.\n   @param node Node to focus\n   @param options.preventScroll Prevent scroll to focused element\n*/\nexport function focus(node: Element, options?: FocusOptions) {\n  if (!domevents.dispatchCustomEvent(node, 'dompack:takefocus', { bubbles: true, cancelable: true, detail: { options } }))\n    return true;\n\n  if (typeof (node as HTMLElement).focus !== \"function\" || (node as HTMLInputElement).disabled)\n    return false;\n\n  (node as HTMLInputElement).focus(options);\n  return true;\n}\n\n/**\n * @param node - Node to show\n * @param options - Scroll options\n * @deprecated invoke scrollIntoView directly  on the nodes\n */\nexport function scrollIntoView(node: Element, options?: ScrollIntoViewOptions) {\n  node.scrollIntoView(options);\n  return true;\n}\n\n/**\n    Register a component for auto-initialization.\n\n    @param selector - Selector the component must match\n    @param handler - Handler\n    @param options - Any unrecognized options are passed to the handler\n\n    The handler will be invoked with two parameters\n    - the node to register\n    - the index of the node (a unique counter for this selector - first is 0)\n */\n\nexport function register<E extends Element = HTMLElement>(selector: string, handler: RegistrationHandler<E>, options?: { afterdomready: boolean }) {\n  const newreg: ComponentRegistration<E> =\n  {\n    selector: selector,\n    handler: handler,\n    index: 0,\n    num: components.length,\n    afterdomready: !options || options.afterdomready\n  };\n  if (components.length === 0 && !domtree.isDomReady()) //first component... we'll need a ready handler\n    domtree.onDomReady(() => registerMissed());\n\n  components.push(newreg as ComponentRegistration<Element>);\n  applyRegistration(newreg);\n}\n\n// register any components we missed on previous scans\nexport function registerMissed(startnode?: Element) {\n  const todo = components.slice(0);\n  todo.forEach(item => applyRegistration(item, startnode));\n}\n","import { buildCookieHeader, type CookieOptions } from '@webhare/dompack/src/cookiebuilder';\nimport { escapeRegExp, parseTyped, stringify } from '@webhare/std';\n\nconst backup: {\n  sessionStorage?: Record<string, string>;\n  localStorage?: Record<string, string>;\n} = {};\ntype BrowserStorage = keyof typeof backup;\n\nexport function listCookies() {\n  return document.cookie.split(';').map(cookie => {\n    const parts = cookie.split('=');\n    return { name: decodeURIComponent(parts[0].trim()), value: decodeURIComponent(parts[1] || '') };\n  });\n}\n\nexport function setCookie(key: string, value: string, options?: CookieOptions) {\n  document.cookie = buildCookieHeader(key, value, options);\n}\n\nexport function getCookie(key: string): string | null {\n  const value = document.cookie.match('(?:^|;)\\\\s*' + escapeRegExp(key) + '=([^;]*)');\n  return (value) ? decodeURIComponent(value[1]) : null;\n}\n\nexport function deleteCookie(key: string, options?: CookieOptions) {\n  setCookie(key, '', { ...options, duration: -1, expires: undefined });\n}\n\nfunction get(storage: BrowserStorage, key: string): unknown | null {\n  let foundvalue: string | undefined | null = backup[storage]?.[key];\n  if (foundvalue) //if it's in the backups storage encoding can't fail either\n    return parseTyped(foundvalue);\n\n  try {\n    foundvalue = window[storage].getItem(key);\n    if (foundvalue)\n      return parseTyped(foundvalue);\n  } catch (e) {\n    //we ignore parse failures\n  }\n  return null;\n}\n\nfunction set(storage: BrowserStorage, key: string, value: unknown) {\n  const tostore = value !== null && value !== undefined ? stringify(value, { typed: true }) : null;\n  try {\n    if (tostore !== null)\n      window[storage].setItem(key, tostore);\n    else\n      window[storage].removeItem(key);\n    return;\n  } catch (e) {\n    //ignore\n  }\n\n  const store = (backup[storage] ||= {});\n  if (tostore !== null)\n    store[key] = tostore;\n  else\n    delete store[key];\n}\n\nexport function getSession<T>(key: string): T | null {\n  return get(\"sessionStorage\", key) as T | null;\n}\nexport function setSession<T>(key: string, value: T | null) {\n  set(\"sessionStorage\", key, value);\n}\nexport function getLocal<T>(key: string): T | null {\n  return get(\"localStorage\", key) as T | null;\n}\nexport function setLocal<T>(key: string, value: T | null) {\n  set(\"localStorage\", key, value);\n}\nexport function listSessionKeys() {\n  try {\n    return Object.keys(window.sessionStorage);\n  } catch (e) {\n    return Object.keys(backup.sessionStorage || {});\n  }\n}\nexport function listLocalKeys() {\n  try {\n    return Object.keys(window.localStorage);\n  } catch (e) {\n    return Object.keys(backup.localStorage || {});\n  }\n}\n","/* Identify devices for the purpose of analytics/tracing\n   NOT a library for feature detection!\n   Originally based on Mootools.Browser\n*/\n\nexport type Platform = \"windows\" | \"ios\" | \"webos\" | \"android\" | \"linux\" | \"mac\" | \"other\";\nexport type Device = \"desktop\" | \"mobile\" | \"tablet\" | \"\";\n\n/** Valid KeyboardEvent.key values (next to 'plain' keys)\n    This list was built from https://www.w3.org/TR/uievents-key/\n    using `console.log([...new Set([...document.querySelectorAll(\".key-table-key .key\")].map(_ => _.textContent))].toSorted().join(' | '))`\n*/\nexport type KeyAttributeValue = \"AVRInput\" | \"AVRPower\" | \"Accept\" | \"Again\" | \"AllCandidates\" | \"Alphanumeric\" | \"Alt\" | \"AltGraph\" | \"AppSwitch\" | \"ArrowDown\" | \"ArrowLeft\" | \"ArrowRight\" | \"ArrowUp\" | \"Attn\" | \"AudioBalanceLeft\" | \"AudioBalanceRight\" | \"AudioBassBoostDown\" | \"AudioBassBoostToggle\" | \"AudioBassBoostUp\" | \"AudioFaderFront\" | \"AudioFaderRear\" | \"AudioSurroundModeNext\" | \"AudioTrebleDown\" | \"AudioTrebleUp\" | \"AudioVolumeDown\" | \"AudioVolumeMute\" | \"AudioVolumeUp\" | \"Backspace\" | \"BrightnessDown\" | \"BrightnessUp\" | \"BrowserBack\" | \"BrowserFavorites\" | \"BrowserForward\" | \"BrowserHome\" | \"BrowserRefresh\" | \"BrowserSearch\" | \"BrowserStop\" | \"Call\" | \"Camera\" | \"CameraFocus\" | \"Cancel\" | \"CapsLock\" | \"ChannelDown\" | \"ChannelUp\" | \"Clear\" | \"Close\" | \"ClosedCaptionToggle\" | \"CodeInput\" | \"ColorF0Red\" | \"ColorF1Green\" | \"ColorF2Yellow\" | \"ColorF3Blue\" | \"ColorF4Grey\" | \"ColorF5Brown\" | \"Compose\" | \"ContextMenu\" | \"Control\" | \"Convert\" | \"Copy\" | \"CrSel\" | \"Cut\" | \"DVR\" | \"Dead\" | \"Delete\" | \"Dimmer\" | \"DisplaySwap\" | \"Eisu\" | \"Eject\" | \"End\" | \"EndCall\" | \"Enter\" | \"EraseEof\" | \"Escape\" | \"ExSel\" | \"Execute\" | \"Exit\" | \"F1\" | \"F10\" | \"F11\" | \"F12\" | \"F2\" | \"F3\" | \"F4\" | \"F5\" | \"F6\" | \"F7\" | \"F8\" | \"F9\" | \"FavoriteClear0\" | \"FavoriteClear1\" | \"FavoriteClear2\" | \"FavoriteClear3\" | \"FavoriteRecall0\" | \"FavoriteRecall1\" | \"FavoriteRecall2\" | \"FavoriteRecall3\" | \"FavoriteStore0\" | \"FavoriteStore1\" | \"FavoriteStore2\" | \"FavoriteStore3\" | \"FinalMode\" | \"Find\" | \"Fn\" | \"FnLock\" | \"GoBack\" | \"GoHome\" | \"GroupFirst\" | \"GroupLast\" | \"GroupNext\" | \"GroupPrevious\" | \"Guide\" | \"GuideNextDay\" | \"GuidePreviousDay\" | \"HangulMode\" | \"HanjaMode\" | \"Hankaku\" | \"HeadsetHook\" | \"Help\" | \"Hibernate\" | \"Hiragana\" | \"HiraganaKatakana\" | \"Home\" | \"Hyper\" | \"Info\" | \"Insert\" | \"InstantReplay\" | \"JunjaMode\" | \"KanaMode\" | \"KanjiMode\" | \"Katakana\" | \"Key11\" | \"Key12\" | \"LastNumberRedial\" | \"LaunchApplication1\" | \"LaunchApplication2\" | \"LaunchCalendar\" | \"LaunchContacts\" | \"LaunchMail\" | \"LaunchMediaPlayer\" | \"LaunchMusicPlayer\" | \"LaunchPhone\" | \"LaunchScreenSaver\" | \"LaunchSpreadsheet\" | \"LaunchWebBrowser\" | \"LaunchWebCam\" | \"LaunchWordProcessor\" | \"Link\" | \"ListProgram\" | \"LiveContent\" | \"Lock\" | \"LogOff\" | \"MailForward\" | \"MailReply\" | \"MailSend\" | \"MannerMode\" | \"MediaApps\" | \"MediaAudioTrack\" | \"MediaClose\" | \"MediaFastForward\" | \"MediaLast\" | \"MediaNextTrack\" | \"MediaPause\" | \"MediaPlay\" | \"MediaPlayPause\" | \"MediaPreviousTrack\" | \"MediaRecord\" | \"MediaRewind\" | \"MediaSkipBackward\" | \"MediaSkipForward\" | \"MediaStepBackward\" | \"MediaStepForward\" | \"MediaStop\" | \"MediaTopMenu\" | \"MediaTrackNext\" | \"MediaTrackPrevious\" | \"Meta\" | \"MicrophoneToggle\" | \"MicrophoneVolumeDown\" | \"MicrophoneVolumeMute\" | \"MicrophoneVolumeUp\" | \"ModeChange\" | \"NavigateIn\" | \"NavigateNext\" | \"NavigateOut\" | \"NavigatePrevious\" | \"New\" | \"NextCandidate\" | \"NextFavoriteChannel\" | \"NextUserProfile\" | \"NonConvert\" | \"Notification\" | \"NumLock\" | \"OnDemand\" | \"Open\" | \"PageDown\" | \"PageUp\" | \"Pairing\" | \"Paste\" | \"Pause\" | \"PinPDown\" | \"PinPMove\" | \"PinPToggle\" | \"PinPUp\" | \"Play\" | \"PlaySpeedDown\" | \"PlaySpeedReset\" | \"PlaySpeedUp\" | \"Power\" | \"PowerOff\" | \"PreviousCandidate\" | \"Print\" | \"PrintScreen\" | \"Process\" | \"Props\" | \"RandomToggle\" | \"RcLowBattery\" | \"RecordSpeedNext\" | \"Redo\" | \"RfBypass\" | \"Romaji\" | \"STBInput\" | \"STBPower\" | \"Save\" | \"ScanChannelsToggle\" | \"ScreenModeNext\" | \"ScrollLock\" | \"Select\" | \"Settings\" | \"Shift\" | \"SingleCandidate\" | \"Soft1\" | \"Soft2\" | \"Soft3\" | \"Soft4\" | \"SpeechCorrectionList\" | \"SpeechInputToggle\" | \"SpellCheck\" | \"SplitScreenToggle\" | \"Standby\" | \"Subtitle\" | \"Super\" | \"Symbol\" | \"SymbolLock\" | \"TV\" | \"TV3DMode\" | \"TVAntennaCable\" | \"TVAudioDescription\" | \"TVAudioDescriptionMixDown\" | \"TVAudioDescriptionMixUp\" | \"TVContentsMenu\" | \"TVDataService\" | \"TVInput\" | \"TVInputComponent1\" | \"TVInputComponent2\" | \"TVInputComposite1\" | \"TVInputComposite2\" | \"TVInputHDMI1\" | \"TVInputHDMI2\" | \"TVInputHDMI3\" | \"TVInputHDMI4\" | \"TVInputVGA1\" | \"TVMediaContext\" | \"TVNetwork\" | \"TVNumberEntry\" | \"TVPower\" | \"TVRadioService\" | \"TVSatellite\" | \"TVSatelliteBS\" | \"TVSatelliteCS\" | \"TVSatelliteToggle\" | \"TVTerrestrialAnalog\" | \"TVTerrestrialDigital\" | \"TVTimer\" | \"Tab\" | \"Teletext\" | \"Undo\" | \"Unidentified\" | \"VideoModeNext\" | \"VoiceDial\" | \"WakeUp\" | \"Wink\" | \"Zenkaku\" | \"ZenkakuHankaku\" | \"ZoomIn\" | \"ZoomOut\" | \"ZoomToggle\";\n\nexport type UserAgentInfo =\n  {\n    /** Browser name, eg 'chrome' or 'firefox' */\n    name: string;\n    /** Browser numeric version (eg 97) */\n    version: number;\n    /** Platform the browser is running on (eg 'windows') */\n    platform: Platform;\n    /** Type of device (eg 'desktop' or 'tablet' for an iPad) */\n    device: Device;\n    /** platform-browsername-version eg ios-safari-11 */\n    triplet: string;\n  };\n\nexport function parseUserAgent(ua: string): UserAgentInfo {\n  ua = ua.toLowerCase();\n\n  // chrome is included in the edge UA, so need to check for edge first, before checking if it's chrome.\n  // safari is included in the miuibrowser UA, so need to check for miuibrowser first, before checking if it's safari.\n  let UA: RegExpMatchArray | null = ua.match(/(edge|miuibrowser)[\\s/:]([\\w\\d.]+)/);\n  if (!UA)\n    UA = ua.match(/(opera|ie|firefox|chrome|trident|crios|version)[\\s/:]([\\w\\d.]+)?.*?(safari|(?:rv[\\s/:]|version[\\s/:])([\\w\\d.]+)|$)/);\n  if (!UA) { //try ios 11.4.1\n    UA = ua.match(/; cpu os ([\\d]+)/);\n    if (UA)\n      UA = ['', 'safari', UA[1]];\n  }\n  if (!UA)\n    UA = ['', 'unknown', \"0\"];\n\n  if (UA[1] === 'trident') {\n    UA[1] = 'ie';\n    if (UA[4]) UA[2] = UA[4];\n  } else if (UA[1] === 'crios') {\n    UA[1] = 'chrome';\n  }\n\n  let platform = ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || ua.match(/mac|win|linux/) || ['other'])[0];\n  if (platform === 'win')\n    platform = 'windows';\n\n  const name = (UA[1] === 'version') ? UA[3] : UA[1];\n  const version = parseInt((UA[1] === 'opera' && UA[4]) ? UA[4] : UA[2]);\n  const device = ua.match(/ipad/) ? 'tablet' : ['ios', 'webos', 'android'].includes(platform) ? 'mobile' : ['mac', 'windows', 'linux'].includes(platform) ? 'desktop' : '';\n\n  return {\n    name,\n    version,\n    platform: platform as Platform,\n    device,\n    triplet: platform + '-' + name + '-' + version\n  };\n}\n\n/**\n * Is the native 'multiselect' modifier for this platform pressed? (Cmd for Mac, Ctrl for Windows/Linux)\n *\n * @param event - Event to check\n */\nexport function isMultiSelectKey(event: KeyboardEvent | MouseEvent): boolean {\n  return browser.platform === 'mac' ? event.metaKey : event.ctrlKey;\n}\n\n/**\n * Is the native 'copy' modifier for this platform pressed?\n *\n * @param event - Event to check\n */\nexport function isCopyKey(event: KeyboardEvent | MouseEvent): boolean {\n  return browser.platform === 'mac' ? event.altKey : event.ctrlKey;\n}\n\n/** @deprecated Use getBrowser() instead, available since WH5.6.3. We will remove `browser` in the future to improve tree shaking */\nexport const browser: Readonly<UserAgentInfo> = Object.freeze(parseUserAgent(globalThis.navigator?.userAgent || \"\"));\n\n/** Get browser information */\nexport function getBrowser(): Readonly<UserAgentInfo> {\n  //Offer this as a function to improve treeshakability\n  return browser;\n}\n\n//CSS Query used to find valid submittors\nexport const submitselector = 'input[type=submit],input[type=image],button[type=submit],button:not([type])';\n//Must match possible types returned by the submitselector\nexport type SubmitSelectorType = HTMLInputElement | HTMLButtonElement;\n","import { isHTMLElement } from \"@webhare/dompack\";\nimport type { CMSConfig } from \"@mod-system/js/internal/generation/gen_misc_ts\";\n\nlet config: CMSConfig | undefined;\n\nfunction forwardPublisherNavigation(event: Event) {\n  /* we watch for clicks.. as we only want to update the Publisher's selection for user triggered actions (otherwise we'd\n     start navigation in response to JS or internal link autoredirects) */\n  if (!isHTMLElement(event.target) || !config?.interfaceServers)\n    return;\n\n  const navaction = event.target.closest<HTMLAnchorElement>('a[href]');\n  if (!navaction)\n    return;\n\n  const desturl = navaction.href;\n  if (desturl.split('#')[0] !== location.href.split('#')[0]) { //it's actual navigation...\n    for (const origin of config.interfaceServers) {\n      try {\n        window.top?.postMessage({ type: \"webhare-navigation\", location: desturl }, origin);\n      } catch (ignore) {\n        //ignore crossdomain errors\n      }\n    }\n  }\n}\n\nasync function configureForCMS() {\n  try {\n    const res = await fetch(\"/.wh/ea/config/cms.json\");\n    config = await res.json();\n  } catch (e) {\n    console.log(\"Failed to get CMS configuration\", e);\n    return;\n  }\n  window.addEventListener(\"click\", forwardPublisherNavigation);\n}\n\nif (typeof window !== \"undefined\" && window !== window.top) { //if we're in an iframe, we may be running in WebHare and need to forward navigation events\n  //we have no way to detect whether we're in a WebHare iframe or a 3rd party iframe. assume it's webhare and grab the interface servers\n  void configureForCMS();\n}\n","import \"@webhare/dompack/reset.css\";\nimport \"./frontend.scss\";\n\nimport { createApp } from \"vue\";\nimport { onDomReady, setupWRDAuth } from \"./lib/runtime\";\nimport App from \"./App.vue\";\nimport { initTheme } from \"./lib/useTheme\";\nimport { refreshChatToken } from \"./lib/chatGateway\";\n\n// Single declaration of the backend→frontend data contract (visible module-wide\n// via declaration merging, so webdesign.ts's setFrontendData typechecks too).\ndeclare module \"@webhare/frontend\" {\n  interface FrontendDataTypes {\n    \"btw:coach\": { hosted: true; siteRoot: string; chatApiBase: string };\n  }\n}\n\nconst LOGGED_IN_CLASS = \"wh-wrdauth--isloggedin\";\n\n// Resolve & apply the theme synchronously so the first paint matches the stored\n// preference (dark by default).\ninitTheme();\n\nonDomReady(() => {\n  createApp(App).mount(\"#app\");\n\n  // After mount — dompack.register() does a one-shot scan, so the LoginForm must\n  // already be in the DOM when setupWRDAuth() runs (it is: App renders it via\n  // v-else for logged-out users). onLogin avoids a full reload and mints a fresh\n  // chat token now that we know the user.\n  setupWRDAuth({\n    onLogin: async () => {\n      await refreshChatToken();\n    },\n  });\n\n  // Already logged in on load → pre-fetch a chat token so the first message\n  // doesn't wait on it.\n  if (document.documentElement.classList.contains(LOGGED_IN_CLASS)) {\n    void refreshChatToken();\n  }\n});\n","var UNKNOWN_FUNCTION = '<unknown>';\n/**\n * This parses the different stack traces and puts them into one format\n * This borrows heavily from TraceKit (https://github.com/csnover/TraceKit)\n */\n\nfunction parse(stackString) {\n  var lines = stackString.split('\\n');\n  return lines.reduce(function (stack, line) {\n    var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);\n\n    if (parseResult) {\n      stack.push(parseResult);\n    }\n\n    return stack;\n  }, []);\n}\nvar chromeRe = /^\\s*at (.*?) ?\\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\\/|[a-z]:\\\\|\\\\\\\\).*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nvar chromeEvalRe = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nfunction parseChrome(line) {\n  var parts = chromeRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line\n\n  var isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n  var submatch = chromeEvalRe.exec(parts[2]);\n\n  if (isEval && submatch != null) {\n    // throw out eval line/column and use top-most line/column number\n    parts[2] = submatch[1]; // url\n\n    parts[3] = submatch[2]; // line\n\n    parts[4] = submatch[3]; // column\n  }\n\n  return {\n    file: !isNative ? parts[2] : null,\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: isNative ? [parts[2]] : [],\n    lineNumber: parts[3] ? +parts[3] : null,\n    column: parts[4] ? +parts[4] : null\n  };\n}\n\nvar winjsRe = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nfunction parseWinjs(line) {\n  var parts = winjsRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  return {\n    file: parts[2],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: [],\n    lineNumber: +parts[3],\n    column: parts[4] ? +parts[4] : null\n  };\n}\n\nvar geckoRe = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nvar geckoEvalRe = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nfunction parseGecko(line) {\n  var parts = geckoRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  var isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n  var submatch = geckoEvalRe.exec(parts[3]);\n\n  if (isEval && submatch != null) {\n    // throw out eval line/column and use top-most line number\n    parts[3] = submatch[1];\n    parts[4] = submatch[2];\n    parts[5] = null; // no column when eval\n  }\n\n  return {\n    file: parts[3],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: parts[2] ? parts[2].split(',') : [],\n    lineNumber: parts[4] ? +parts[4] : null,\n    column: parts[5] ? +parts[5] : null\n  };\n}\n\nvar javaScriptCoreRe = /^\\s*(?:([^@]*)(?:\\((.*?)\\))?@)?(\\S.*?):(\\d+)(?::(\\d+))?\\s*$/i;\n\nfunction parseJSC(line) {\n  var parts = javaScriptCoreRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  return {\n    file: parts[3],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: [],\n    lineNumber: +parts[4],\n    column: parts[5] ? +parts[5] : null\n  };\n}\n\nvar nodeRe = /^\\s*at (?:((?:\\[object object\\])?[^\\\\/]+(?: \\[as \\S+\\])?) )?\\(?(.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nfunction parseNode(line) {\n  var parts = nodeRe.exec(line);\n\n  if (!parts) {\n    return null;\n  }\n\n  return {\n    file: parts[2],\n    methodName: parts[1] || UNKNOWN_FUNCTION,\n    arguments: [],\n    lineNumber: +parts[3],\n    column: parts[4] ? +parts[4] : null\n  };\n}\n\nexport { parse };\n","import * as stacktrace_parser from \"stacktrace-parser\";\n\nexport type StackTraceItem = {\n  filename: string;\n  line: number;\n  col: number;\n  func: string;\n};\n\nexport type StackTrace = StackTraceItem[];\n\nexport function parseTrace(e: Error): StackTrace {\n  if (!e?.stack)\n    return [];\n\n  const trace = stacktrace_parser.parse(e.stack);\n  return trace.map(i => ({ filename: i.file || \"\", line: i.lineNumber || 1, col: i.column || 1, func: (i.methodName || \"\") }));\n}\n\nexport function getStackTrace(): StackTrace {\n  return parseTrace(new Error()).slice(1);\n}\n\nexport function formatTrace(trace: StackTraceItem[]): string {\n  return trace.map(e =>\n    `    at ${e.func} (${e.filename}:${e.line}:${e.col})`).join(\"\\n\");\n}\n\nexport function prependStackTrace(error: Error, trace: StackTrace) {\n  if (!error.stack)\n    return; //no stack to manipulate\n\n  const stacklines = error.stack?.split(\"\\n\") || [];\n  const tracelines = formatTrace(trace);\n  error.stack = (stacklines[0] ? stacklines[0] + \"\\n\" : \"\") + tracelines + '\\n' + (stacklines.slice(1).join(\"\\n\"));\n  return error;\n}\n","// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/rpc\" {\n  export interface KnownRPCServices {\n    /* Filled by generated services.ts files */\n  }\n}\n\nimport { debugFlags, backendBase } from \"@webhare/env\";\nimport { type StackTrace, parseTrace, prependStackTrace, type PromisifyFunctionReturnType } from \"@webhare/js-api-tools\";\nimport { omit, parseTyped, stringify } from \"@webhare/std\";\n\n//Preload interface definitions. To solve this cleaner we would have to do some sort of auto-inject but how to robustly do that accross IDEs/Tscs ?\n\n//@ts-ignore Ignore if it doesn't exist. this line *must* remain a @ts-ignore\nimport type { } from \"@mod-platform/generated/ts/services.ts\";\n//@ts-ignore Ignore if it doesn't exist. this line *must* remain a @ts-ignore\nimport type { } from \"wh:ts/services.ts\";\n\nfunction isAbsolute(url: string) {\n  return url.startsWith(\"http:\") || url.startsWith(\"https:\");\n}\n\nfunction getBaseURL() {\n  if (!backendBase)\n    throw new Error(`You must set the baseUrl option when using the RPC Client outside Webhare`);\n  return isAbsolute(backendBase) ? backendBase : new URL(backendBase, location.origin);\n}\n\nexport interface RPCClientOptions {\n  /** Custom request update. Use to eg. set keepalive or add debug variables to the URL */\n  onBeforeRequest?: (url: URL, requestInit: RequestInit & { headers: Headers }) => void;\n  /** Response callback. Use this if you need to capture details on the incoming respones. May be invoked multiple times per request, eg due to 429 errors! */\n  onResponse?: (response: Response) => void;\n  /** Call timeout */\n  timeout?: number;\n  /** Abort signal to cancel the RPC */\n  signal?: AbortSignal;\n  /** Retry on 429 */\n  retry429?: boolean;\n  /** Silent - do not log errors */\n  silent?: boolean;\n  /** Debug (Follows 'rpc' debugflag if not explicity specified) */\n  debug?: boolean;\n  /** Headers to submit (Eg Authorization) */\n  headers?: Record<string, string>;\n  /** Base URL for service paths */\n  baseUrl?: string;\n}\n\n/** RPC Response format */\nexport type RPCResponse = ({\n  /** Result. Not present if the function didn't return anything */\n  result?: unknown;\n} | {\n  /** Error message */\n  error: string;\n  /** Captured stack trace (if 'etr' debugFlag is set) */\n  trace?: StackTrace;\n}) & {\n  /** Captured console log entries (if 'etr' debugFlag is set) */\n  consoleLog?: Array<{\n    //TODO this is Serialized<ConsoleLogItem[]> - should probably rename it to SerializedToJSON and move to std or env ?\n    /** Date when console function was called */\n    when: string;\n    /** `console` method that was called (eg 'log') */\n    method: string;\n    /** Logged data */\n    data: string;\n    /** Location of caller */\n    location?: {\n      filename: string;\n      line: number;\n      col: number;\n      func: string;\n    };\n    /** Codecontext */\n    codeContextId?: string;\n  }>;\n};\n\nclass ControlledCall {\n  client: RPCClient;\n  options: RPCClientOptions;\n  abortcontroller?: AbortController;\n  timeout?: number;\n  _callurl: string;\n  _fetchoptions: RequestInit;\n  promise: Promise<unknown>;\n  timedout?: boolean;\n  aborted?: boolean;\n\n  constructor(client: RPCClient, method: string, stack: StackTrace | null, options: RPCClientOptions, callurl: URL, fetchoptions: RequestInit) {\n    this.client = client;\n    this.options = options;\n\n    if (options.timeout || options.signal) {\n      this.abortcontroller = new AbortController;\n      fetchoptions.signal = this.abortcontroller.signal;\n\n      if (options.timeout && options.timeout > 0) {\n        this.timeout = options.timeout;\n        setTimeout(() => this._handleTimeout(), options.timeout);\n      }\n      if (options.signal) {\n        options.signal.addEventListener(\"abort\", () => this._abort());\n      }\n    }\n\n    this._callurl = callurl.toString();\n    this._fetchoptions = fetchoptions;\n\n    const fetchpromise = fetch(this._callurl, this._fetchoptions);\n    this.promise = this._completeCall(method, stack, fetchpromise) as Promise<unknown>;\n  }\n  _handleTimeout() {\n    this.timedout = true;\n    this.abortcontroller?.abort();\n  }\n  _abort() {\n    this.aborted = true;\n    this.abortcontroller?.abort();\n  }\n\n  async _completeCall(method: string, requestStack: StackTrace | null, fetchpromise: Promise<Response>) {\n    let response;\n    for (; ;) { //loop to handle \"429 Conflict\"s\n      try { //we should only guard the fetch call and specifically *not* the onResponse callback\n        response = await fetchpromise;\n      } catch (exception) {\n        if (this.client.debug)\n          console.log(`[rpc] Exception invoking '${method}'`, exception);\n\n        if (this.aborted)\n          throw new Error(`RPC Aborted`);\n        else if (this.timedout)\n          throw new Error(`RPC Timeout: timeout was set to ${this.timeout} milliseconds`);\n        else\n          throw new Error(`RPC Failed: exception: ` + exception);\n      }\n\n      this.options.onResponse?.(response); //allow hooks to capture headers\n\n      if (response.status === 429 && !(\"retry429\" in this.options && !this.options.retry429) && response.headers.get(\"Retry-After\")) {\n        const retryafter = parseInt(response.headers.get(\"Retry-After\") || \"\");\n        if (this.client.debug)\n          console.warn(`[rpc] We are being throttled (429 Too Many Requests) - retrying after ${retryafter} seconds`);\n\n        await new Promise(resolve => setTimeout(resolve, retryafter * 1000));\n        fetchpromise = fetch(this._callurl, this._fetchoptions);\n        continue;\n      }\n      break;\n    }\n\n    let jsonresponse: RPCResponse;\n    try {\n      jsonresponse = parseTyped(await response.text());\n      if (jsonresponse.consoleLog) {\n        for (const logitem of jsonresponse.consoleLog) {\n          //should we log 'when'? it's getting more and more noisy then though....\n          //TODO should we match the remote's method (after validating) or just keep everything at 'log' ?\n          console.log(`[remote:${logitem.method}] ${logitem.location ? `${logitem.location.filename.split(\"/\").at(-1)}:${logitem.location.line}: ` : ''}${logitem.data}`);\n        }\n      }\n\n      if (this.client.debug)\n        console.log(`[rpc] Received response to '${method}'`, omit(jsonresponse, [\"consoleLog\", \"trace\"]));\n    } catch (exception) {\n      if (this.client.debug)\n        console.warn(`[rpc] Response was not valid JSON`, exception);\n      throw new Error(\"RPC Failed: Invalid response received\", { cause: exception });\n    }\n\n    if (\"error\" in jsonresponse) {\n      const err = new Error(`RPC Error: ${jsonresponse.error}`);\n      if (jsonresponse.trace) {\n        try {\n          prependStackTrace(err, jsonresponse.trace);\n        } catch (err2) {\n          //ignore stacktrace manipulation error\n        }\n      }\n\n      if (this.options.debug) {\n        console.group();\n        console.warn(\"RPC failed:\", err);\n        if (requestStack) {\n          console.warn(\"Stack at calling point\");\n          console.log(requestStack);\n        }\n        console.groupEnd();\n      }\n\n      throw err;\n    }\n\n    return jsonresponse.result;\n  }\n}\n\nclass RPCClient {\n  readonly url: string;\n  options: RPCClientOptions;\n\n  constructor(url: string, options?: RPCClientOptions) {\n    this.url = url;\n    this.options = {\n      timeout: 0,\n      debug: false,\n      ...options\n    };\n  }\n\n  get debug() {\n    return this.options.debug || debugFlags.rpc;\n  }\n\n  _tryLogError(requestStack: StackTrace | null, error: Error) {\n  }\n\n  invoke(method: string, params: unknown[]) {\n    //build the URL, add profiling and function parameters where needed\n    //We'll delay the baseurl calculation until the first call to allow for the backendBase to be set up\n    const callurl = isAbsolute(this.url) ? new URL(this.url + method) : new URL(this.url + method, this.options.baseUrl || getBaseURL());\n\n    let requestStack: StackTrace | null = null;\n\n    const fetchoptions: RequestInit & { headers: Headers } = {\n      method: \"POST\",\n      headers: new Headers({\n        \"Accept\": \"application/json\",\n        \"Content-Type\": \"application/json; charset=utf-8\",\n        ...this.options.headers\n      }),\n      body: stringify(params, { typed: true }),\n    };\n\n    if (typeof location !== \"undefined\")\n      callurl.searchParams.set(\"pathname\", location.pathname);\n\n    if (this.debug) {\n      requestStack = parseTrace(new Error);\n      console.log(`[rpc] Invoking '${method}'`, params);\n    }\n\n    this.options.onBeforeRequest?.(callurl, fetchoptions);\n    return new ControlledCall(this, method, requestStack, this.options, callurl, fetchoptions).promise;\n  }\n}\n\ntype ServiceBase<T> = {\n  withOptions(options: RPCClientOptions): T & ServiceBase<T>;\n};\n\nclass ServiceProxy<Service extends keyof KnownRPCServices | object> {\n  client: RPCClient;\n\n  constructor(client: RPCClient) {\n    this.client = client;\n  }\n\n  get(target: object, prop: string, receiver: unknown) {\n    if ([\"then\", \"catch\", \"finally\"].includes(prop)) //do not appear like our object is a promise\n      return undefined;\n\n    if (prop === 'withOptions') { //create a withOptions function\n      return (options: RPCClientOptions) => {\n        const newoptions = {\n          ...this.client.options,\n          ...options,\n          headers: { ...this.client.options.headers, ...options.headers }\n        };\n        return rpc(this.client.url as (Service extends keyof KnownRPCServices ? Service : string), newoptions);\n      };\n    }\n\n    return (...args: unknown[]) => this.client.invoke(prop, args);\n  }\n}\n\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- need any to not worry about the actual first arg\ntype OmitFirstArg<F> = F extends (x: any, ...args: infer P) => infer R ? (...args: P) => R : never;\n\nexport type OmitRPCContextArgs<ServiceType> = {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- need any to not worry about the actual first arg\n  [K in keyof ServiceType as ServiceType[K] extends (...a: any) => any ? K : never]: ServiceType[K] extends (...a: any[]) => void ? OmitFirstArg<ServiceType[K]> : never;\n};\n\n/** Creates an async version of the functions in a class, removes context parameters\n * @typeParam ServiceType - Type definition of the service class that implements this service.\n*/\ntype ConvertToRPCInterface<ServiceType> = {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- using any is needed for this type definition\n  [K in keyof ServiceType as ServiceType[K] extends (...a: any) => any ? K : never]: ServiceType[K] extends (...a: any[]) => void ? PromisifyFunctionReturnType<ServiceType[K]> : never;\n};\n\ntype ExtractInterface<Service extends object> = ConvertToRPCInterface<Service> & ServiceBase<ConvertToRPCInterface<Service>>;\n\n/** Get the client interface type as would be returned by createClient\n * @typeParam Service - either the `module:service` name or the interface to implement. If you want to pass the implementation's type you should wrap it into `OmitRPCContextArgs`.\n*/\nexport type GetRPCClientInterface<Service extends (keyof KnownRPCServices) | object> = Service extends keyof KnownRPCServices ? ExtractInterface<OmitRPCContextArgs<KnownRPCServices[Service]>> : Service extends object ? ExtractInterface<Service> : never;\n\n/** Create a WebHare RPC client\n  @param service - URL (https://<ORIGIN>/.wh/rpc/module/service/) or service name (module:service) to invoke\n*/\nexport function rpc<Service extends keyof KnownRPCServices>(service: Service extends keyof KnownRPCServices ? Service : string, options?: RPCClientOptions): GetRPCClientInterface<Service>;\nexport function rpc<Service extends object>(service: Service extends keyof KnownRPCServices ? Service : string, options?: RPCClientOptions): GetRPCClientInterface<Service>;\n\nexport function rpc<Service extends keyof KnownRPCServices | object>(service: Service extends keyof KnownRPCServices ? Service : string, options?: RPCClientOptions): GetRPCClientInterface<Service> {\n  //NOTE: needed the separate overloads to get Intellisense to list the known services for createRPClient's first argument\n\n  if (!service)\n    throw new Error(`You must specify either a WebHare rpcService name or a full URL`);\n\n  const servicematch = service.match(/^([a-z0-9_]+):([a-z0-9_]+)$/);\n  if (servicematch)\n    service = `/.wh/rpc/${servicematch[1]}/${servicematch[2]}/` as (Service extends keyof KnownRPCServices ? Service : string);\n  else if (!service.endsWith('/'))\n    throw new Error(`Service URL must end in a slash`);\n\n  const rpcclient = new RPCClient(service, options);\n  return new Proxy({}, new ServiceProxy<GetRPCClientInterface<Service>>(rpcclient)) as GetRPCClientInterface<Service>;\n}\n","import type { NavigateInstruction } from \"@webhare/env\";\n\n/** Login failure reasons that can also be used by custom isLoginDenied checks */\nexport type LoginErrorCode = \"internal-error\" | \"incorrect-login-password\" | \"incorrect-email-password\" | \"account-disabled\" | \"unknown-account\" | \"require-external-login\";\n\n/** Login reasons that require further client side work but are not errors per-se */\nexport type LoginIncompleteCode = \"totp\" | \"incomplete-account\";\n\nexport type LoginTweaks = {\n  /** Limit session duration (development servers only) */\n  limitExpiry?: number;\n  /** Language code */\n  lang?: string;\n};\n\nexport type LoginResult = {\n  loggedIn: boolean;\n  navigateTo: NavigateInstruction;\n} | {\n  loggedIn: false;\n  code: LoginErrorCode;\n  error?: string;\n};\n\nexport type LogoutResult = { success: true } | {\n  error: string;\n  code: LoginErrorCode | LoginIncompleteCode;\n};\n\nexport const PublicCookieSuffix = \"_publicauthdata\";\n\n/* APIs and types shared between the client and server */\nexport function getCompleteAccountNavigation(token: string, pathname: string): NavigateInstruction {\n  return {\n    type: \"redirect\", //TODO or use a \"form\" too? went for a session now as an excursion to followup GET pages is much more likely in this procedure than with totp\n    url: \"/.wh/common/authpages/?wrd_pwdaction=completeaccount&token=\" + encodeURIComponent(token || '') + \"&pathname=\" + encodeURIComponent(pathname)\n  };\n}\n","import { createClient } from \"@webhare/jsonrpc-client\";\nimport { type NavigateInstruction, navigateTo } from \"@webhare/env\";\nimport * as dompack from '@webhare/dompack';\nimport type { LoginOptions } from \"@webhare/auth/src/identity\";\nimport { rpc } from \"@webhare/rpc\";\n\n//NOTE: Do *NOT* load @webhare/frontend or we enforce the new CSS reset!\nimport { getFrontendData } from '@webhare/frontend/src/init';\nimport { PublicCookieSuffix, type LoginErrorCode, type LoginResult, type LoginTweaks } from \"@webhare/auth/src/shared\";\nimport { parseTyped, toSnakeCase, type ToSnakeCase } from \"@webhare/std\";\nimport type WRDAuthenticationProvider from \"@mod-wrd/js/auth\";\nimport type { OAuth2PromptFlag } from \"@webhare/auth/src/oauth2-client\";\n\n/** WRDAuth configuration */\nexport interface WRDAuthOptions {\n  /** Callback that is invoked after a succesful login. If not set the page will be reloaded. */\n  onLogin?: () => Promise<void> | void;\n}\n\nexport interface PublicAuthData {\n  expiresMs: number;\n  userInfo?: object | null;\n  persistent?: boolean;\n}\n\ndeclare module \"@webhare/frontend\" {\n  interface FrontendDataTypes {\n    \"wrd:auth\": {\n      /** WRDAuth cookiename (used to store userinfo and expiry) */\n      cookiename: string;\n    };\n  }\n}\n\ndeclare global {\n  interface Window {\n    $wh$legacyAuthProvider: WRDAuthenticationProvider;\n    triggerWebHareSSO?: (tag: string, options?: SSOLoginOptions) => Promise<void>;\n  }\n}\n\n/** Current authoptions. undefined if setupWRDAuth hasn't been invoked yet */\nlet authOptions: WRDAuthOptions | undefined;\n\n/** Get current login cookie. If empty, wrdauth is not initialized here */\nfunction getCookieName(): string | null {\n  const settings = getFrontendData(\"wrd:auth\", { allowMissing: true });\n  return settings?.cookiename || null;\n}\n\nfunction getAuthLocalData(): PublicAuthData | null {\n  const c = getCookieName();\n  if (!c)\n    return null;\n\n  try {\n    return parseTyped(dompack.getCookie(c + PublicCookieSuffix)!) as PublicAuthData;\n  } catch {\n    return null;\n  }\n}\n\nasync function submitLoginForm(node: HTMLFormElement, event: SubmitEvent) {\n  if (node.propWhFormhandler)\n    return; //already handled by publisher forms so we'll defer to that\n  dompack.stop(event);\n\n  const username = (node.elements.namedItem(\"login\") as HTMLInputElement)?.value;\n  const password = (node.elements.namedItem(\"password\") as HTMLInputElement)?.value;\n  const site = (node.elements.namedItem(\"site\") as HTMLInputElement)?.value || undefined;\n  const returnto = (node.elements.namedItem(\"returnto\") as HTMLInputElement)?.value || undefined;\n  const persistentlogin = (node.elements.namedItem(\"persistent\") as HTMLInputElement)?.checked;\n  if (!login || !password)\n    throw new Error(`submitLoginForm: required elements login/password not set or missing`);\n\n  using lock = dompack.flagUIBusy({ modal: true });\n  void (lock);\n\n  const loginresult = await login(username, password, {\n    persistent: persistentlogin,\n    site,\n    returnTo: returnto ? new URL(returnto, location.href).toString() : location.href.split('#')[0]\n  });\n  if (loginresult.loggedIn) {\n    refreshLoginStatus();\n    if (loginresult.navigateTo.type === \"redirect\" && loginresult.navigateTo.url.split('#')[0] === location.href.split('#')[0]  //stay on same page\n      && authOptions?.onLogin) {\n\n      if (loginresult.navigateTo.url.includes('#')) //execute any #hash instruction\n        history.replaceState(null, \"\", loginresult.navigateTo.url.substring(loginresult.navigateTo.url.indexOf('#')));\n\n      await authOptions.onLogin();\n    } else {\n      //Reload the page to get the new login status - TODO put this behind a 'login state change' event and allow users to cancel it if they can deal with login/logout on-page\n      console.log(\"Post login redirect\", loginresult.navigateTo);\n      navigateTo(loginresult.navigateTo);\n    }\n  } else if (\"navigateTo\" in loginresult) {\n    console.log(\"Login incomplete, redirecting to\", loginresult.navigateTo);\n    navigateTo(loginresult.navigateTo);\n  } else\n    failLogin(loginresult.error ?? loginresult.code, { code: loginresult.code, data: \"\" }, node); //FIXME restore the code & data members from old wrdauth\n}\n\nfunction refreshLoginStatus() {\n  const loggedIn = isLoggedIn();\n  document.documentElement.classList.toggle(\"wh-wrdauth--isloggedin\", loggedIn);\n\n  window.$wh$legacyAuthProvider?.refresh();\n}\n\n/** Return whether a user's currently logged in */\nexport function isLoggedIn(): boolean {\n  return (getAuthLocalData()?.expiresMs || 0) > Date.now();\n}\n\n/** Setup WRDAuth frontend integration */\nexport function setupWRDAuth(options?: WRDAuthOptions) {\n  if (authOptions)\n    throw new Error(`Duplicate setupWRDAuth call`);\n\n  authOptions = { ...options };\n\n  dompack.register<HTMLFormElement>('form.wh-wrdauth__loginform,form.wh-wrdauth-login__form', node => {\n    node.setAttribute(\"data-wh-wrdauth-attached\", \"\");\n    dompack.addDocEventListener(node, \"submit\", evt => submitLoginForm(node, evt));\n  });\n  dompack.register('.wh-wrdauth__logout', node => {\n    function handleLogoutClick(event: Event) {\n      dompack.stop(event);\n\n      //letting rejections escape - our trigger is generally setup in HTML so there's nothing to catch but uncaught rejection handlers anyway\n      if (node instanceof HTMLAnchorElement && node.href && node.href.split('#')[0] !== location.href.split('#')[0]) { //logout link sending you elsewhere\n        void doLogout().then(() => {\n          console.log(\"Logout complete, redirecting to\", node.href);\n          navigateTo({ type: \"redirect\", url: node.href });\n        });\n      } else {\n        void logout(); //TODO what if the logout only changed the anchor? but what's the usecase for that?\n      }\n    }\n\n    dompack.addDocEventListener(node, \"click\", event => handleLogoutClick(event));\n  });\n\n  dompack.onDomReady(() => {\n    if (\"$wh$wrdauth\" in window) {\n      console.error(\"Both setupWRDAuth from @webhare/frontend and @mod-wrd/js/auth are present in this page. Mixing these is not supported!\");\n    }\n  });\n\n  refreshLoginStatus();\n}\n\nfunction failLogin(message: string, response: { code: LoginErrorCode; data: string }, form: HTMLFormElement) {\n  const evtdetail = {\n    message: message,\n    code: response.code,\n    data: response.data\n  };\n\n  const cancelled = !dompack.dispatchCustomEvent(form || document.documentElement, \"wh:wrdauth-loginfailed\", { bubbles: true, cancelable: true, detail: evtdetail });\n  if (!cancelled) {\n    //TODO depending on error we may need to change a different field?\n    const loginfield = dompack.qR<HTMLInputElement>(form, \"input[name=password]\");\n    loginfield.setCustomValidity(message);\n    // loginfield.reportValidity(); //this actually blocks wh-form error handling from showing the error in-page when so desired\n    loginfield.focus();\n  }\n}\n\n/** Retrieve userinfo if set by onFrontendUserInfo in your WRDAuth customizer */\nexport function getUserInfo<T extends object = object>(): T | null {\n  return isLoggedIn() ? getAuthLocalData()?.userInfo as T | null : null;\n}\n\nfunction getLoginTweaks(): LoginTweaks {\n  const tweaks: LoginTweaks = {\n    lang: dompack.getLang().tag\n  };\n\n  const urlvars = new URL(location.href);\n  if (urlvars.searchParams.has(\"wrdauth_limit_expiry\"))\n    tweaks.limitExpiry = parseInt(urlvars.searchParams.get(\"wrdauth_limit_expiry\") || '0') || undefined;\n\n  return tweaks;\n}\n\n/** Implements the common username/password flows */\nexport async function login(username: string, password: string, options: LoginOptions = {}): Promise<LoginResult> {\n  const cookieName = getCookieName();\n  if (!cookieName)\n    throw new Error(\"WRDAuth not initialized, please call setupWRDAuth first and ensure this page has a <wrdauth> rule\");\n\n  const result = await rpc(\"platform:authservice\").login(username, password, cookieName, dompack.getBrowser().triplet, { ...options, ...getLoginTweaks() });\n  if (result.loggedIn && !getAuthLocalData())\n    throw new Error(\"Login succeeded but no auth data was set in the cookie\");\n\n  return result;\n}\n\n/** Execute and verify cookie clearance to prepare for logging out */\nasync function doLogout() {\n  const cookieName = getCookieName();\n  if (!cookieName)\n    throw new Error(\"WRDAuth not initialized, please call setupWRDAuth first and ensure this page has a <wrdauth> rule\");\n\n  await rpc(\"platform:authservice\").logout(cookieName, dompack.getBrowser().triplet);\n\n  if (getAuthLocalData())\n    throw new Error(\"Logged out but we still have auth data in the cookie\");\n}\n\n/** Logout the current user */\nexport async function logout() {\n  await doLogout();\n  console.log(\"Reloading to process the new logged out status\");\n  navigateTo({ type: \"reload\" }); //TODO put this behind a 'login state change' event\n}\n\nexport interface MyService {\n  startLogin2(urlpath: string, tag: string, options: ToSnakeCase<SSOLoginOptions>): Promise<NavigateInstruction>;\n}\n\ninterface SSOLoginOptions {\n  /** @deprecated use prompt: \"none\" from WH6.0 up */\n  passive?: boolean;\n  /** Set the prompt flag for the authorize request */\n  prompt?: OAuth2PromptFlag;\n}\n\nexport function startSSOLogin(tag: string, options?: SSOLoginOptions): Promise<void> {\n  const client = createClient<MyService>(\"wrd:auth\");\n\n  if (options?.passive)\n    options = { prompt: \"none\", ...options, passive: undefined }; //force prompt to none in passive mode, and remove the passive flag since it doesn't mean anything to the server\n\n  const defer = Promise.withResolvers<void>();\n\n  //Launch SSO login for the current page.\n  //TODO also pass getLoginTweaks() at least to OIDC logins as soon as we've ported this to authservice\n  client.startLogin2(location.pathname + location.search + location.hash, tag, toSnakeCase(options) || {}).then(instr => {\n    //we leave the promise unresolved so any busy layers stay active during the actual redirect\n    //TODO can we have navigateTo detect failed navigations so we can throw ?\n    navigateTo(instr);\n  }).catch((e: Error) => {\n    defer.reject(e);\n  });\n\n  return defer.promise;\n}\n\n/** Configure WebHare external auth buttons (even hidden ones) to listen for bookmarklet login requests */\nexport function setupWebHareSSOTrigger(): void {\n  window.triggerWebHareSSO = startSSOLogin;\n}\n","import { qSA } from \"@webhare/dompack\";\nimport { debugFlags } from \"@webhare/env\";\nimport type { FormAnalyticsEvent } from \"@webhare/forms\";\nimport type { DataLayerEntry } from \"./gtm-types\";\nimport { omit } from \"@webhare/std\";\n\ndeclare global {\n  interface Window {\n    /** The google tag manager (GTM) datalayer */\n    dataLayer: DataLayerEntry[]; //technically window.dataLayer may not exist and should be optional, but we already used to declare it as existing from gtm.ts\n  }\n  //It's safer to access dataLayer through globalThis, which will always be available in all environments unlike 'window'\n  var dataLayer: DataLayerEntry[] | undefined;\n}\n\n//ADDME if we ever figure out a bundler trick to flush this command to the top of all imports/loads, that would be great (we could consider *ALWAYS* putting this in the generated startup code, or we'd need to do a tree pre-walk to see if gtm.es is loaded anywhere)\n(globalThis as unknown as Window).dataLayer ||= [];\nlet lastSeen: DataLayerEntry | undefined;\n\nfunction showDataLayerUpdates() {\n  if (!globalThis.dataLayer)\n    return; //not set up (yet?)\n\n  if (debugFlags.anl)\n    globalThis.dataLayer.slice(globalThis.dataLayer.indexOf(lastSeen!) + 1).forEach(entry => console.log(\"[anl] dataLayer.push:\", entry));\n\n  lastSeen = globalThis.dataLayer[globalThis.dataLayer.length - 1];\n}\n\n/** Push to the dataLayer\n * @param vars - The variables to push\n * @param options - Options for the push\n *   timeout Time before any eventCallback is forcibly called (default 200ms)\n*/\nexport function pushToDataLayer(vars: DataLayerEntry, options?: { timeout?: number }) {\n  if (vars.eventCallback) { //we'll wrap the callback into a promise to ensure it's only invoked once\n    const savecallback = vars.eventCallback;\n    let newcallback: () => void;\n    void (new Promise<void>(resolve => newcallback = resolve)).then(() => savecallback());\n    setTimeout(() => newcallback, options?.timeout || 200);\n  }\n\n  globalThis.dataLayer?.push(vars);\n  showDataLayerUpdates();\n}\n\nfunction collectFormValues(formnode: HTMLFormElement): Record<string, unknown> {\n  const donefields: Record<string, boolean> = {};\n  const outdata: Record<string, unknown> = {};\n\n  const multifields = qSA<HTMLInputElement>(formnode, 'input[type=radio], input[type=checkbox]');\n  for (const multifield of multifields) {\n    if (!multifield.name || donefields[multifield.name])\n      continue; //we did this one\n\n    donefields[multifield.name] = true;\n\n    let idx = 0;\n    const values = [];\n    const labels = [];\n    const checkboxes = multifields.filter(node => node.name === multifield.name);\n\n    for (const node of checkboxes.filter(cbox => cbox.checked)) {\n      const keyname = 'form_' + multifield.name + (idx ? '_' + idx : '');\n      let labelsfornode = node.dataset.gtmTag || qSA(`label[for=\"${CSS.escape(node.id)}\"]`).map(labelnode => labelnode.textContent).filter(labelnode => Boolean(labelnode)).join(' ');\n      labelsfornode = labelsfornode.trim(); //TODO normalize whitespace\n      outdata[keyname] = node.value;\n      outdata[keyname + '_label'] = labelsfornode;\n\n      ++idx;\n      values.push(node.value);\n      labels.push(labelsfornode);\n    }\n\n    if (values.length) {\n      const allkeyname = 'form_' + multifield.name + '_all';\n      outdata[allkeyname] = values.join(';');\n      outdata[allkeyname + '_label'] = labels.join(';');\n    }\n  }\n\n  for (const field of formnode.querySelectorAll<HTMLSelectElement | HTMLInputElement>('input:not([type=radio]):not([type=checkbox]),select,textarea')) {\n    if (!field.name || donefields[field.name])\n      continue;\n\n    donefields[field.name] = true;\n\n    const val = field.value;\n    outdata['form_' + field.name] = val;\n    if (field.matches('select')) {\n      const opt = (field as HTMLSelectElement).options[(field as HTMLSelectElement).selectedIndex];\n      if (opt)\n        outdata['form_' + field.name + '_label'] = opt.dataset.gtmTag || opt.textContent;\n    }\n  }\n  return outdata;\n}\n\n/** Setup the dataLayer */\nlet didinit: boolean | undefined;\nexport function setupGTM() {\n  if (!didinit) {\n    didinit = true;\n    if (debugFlags.anl)\n      setInterval(showDataLayerUpdates, 100);\n  }\n}\n\n/** Setup dataLayer events for form analytics events\n * @param options - Options for the form analytics setup\n     - `eventPrefix`. Prefix to use. Default is `wh-platform:form_` but existing integrations may (also) require `publisher:form`\n*/\nexport function setupFormAnalyticsForGTM(options?: { eventPrefix: string }): void {\n  setupGTM(); //ensurse the GTM basics are installed\n\n  addEventListener(\"wh:form-analytics\", (e: FormAnalyticsEvent) => {\n    //we use the same prefixing as pxl events would\n    const entry: DataLayerEntry = {\n      event: `${options?.eventPrefix || \"platform:form_\"}${e.detail.event}`\n    };\n\n    for (const [key, val] of Object.entries(e.detail))\n      if (key !== \"event\" && [\"string\", \"number\", \"boolean\"].includes(typeof val))\n        entry[`formmeta_${key}`] = val;\n\n    const form = e.target as HTMLFormElement | undefined;\n    if (form?.dataset.gtmSubmit) {\n      //When set, we push both the form: variable in gtmSubmit and the current form field avlues\n      Object.assign(entry, JSON.parse(form.dataset.gtmSubmit));\n      Object.assign(entry, collectFormValues(form));\n    }\n\n    pushToDataLayer(entry);\n  });\n}\n\nfunction processClickDataLayerTags(event: MouseEvent) {\n  const entry: Record<string, unknown> = {};\n\n  for (let node = event.target as HTMLElement | undefined | null; node; node = node?.parentElement)\n    for (const attr of node.attributes)\n      if (attr.nodeName.startsWith(\"data-wh-datalayer-onclick-\")) {\n        const key = attr.nodeName.substring(26);\n        if (key !== \"__proto__\" && !(key in entry)) //as we're working upwards, don't overwrite already set keys\n          entry[key] = attr.nodeValue || \"\";\n      } else if (attr.nodeName === \"data-wh-datalayer-onclick\") { //JSON setter\n        const data = JSON.parse(attr.nodeValue!);\n        for (const [key, value] of Object.entries(data))\n          if (key !== \"__proto__\" && !(key in entry)) //as we're working upwards, don't overwrite already set keys\n            entry[key] = value;\n      }\n\n  if (Object.keys(entry).length)\n    pushToDataLayer(entry as DataLayerEntry);\n}\n\n/** Setup support for data-wh-datalayer-onclick-xxx=\"yyy\" attributes. When clicking an element with these attributes the JSON from the attribute and all parents are merged together and pushed to the dataLayer  */\nexport function setupDataLayerTags() {\n  //we capture so we can also simply set variables for any existing GTM handlers\n  window.addEventListener(\"click\", processClickDataLayerTags, { capture: true });\n}\n\n/** Get the current variables in the GTM datalayer\n * @param win - The window to get the dataLayer from (default: current window)\n * @return The current variables in the GTM datalayer, merged together from all entries. Note that this is a snapshot and won't update as the dataLayer changes\n*/\nexport function getCurrentDataLayerVariables<DataLayerFormat extends object = Record<string, unknown>>(win: Window = window): DataLayerFormat {\n  const state: DataLayerFormat = {} as DataLayerFormat;\n  if (win.dataLayer)\n    win.dataLayer.forEach(entry =>\n      Object.assign(state, structuredClone(omit(entry, [\"event\", \"eventCallback\", \"gtm.uniqueEventId\"]))));\n  return state;\n}\n","/* To verify tree shaking viability, try:\n   whcd\n   cd whtree\n   echo 'import \"@webhare/frontend\"' | node_modules/.bin/esbuild --loader:.css=empty --tsconfig=tsconfig.json --bundle --minify\n*/\n\n// This gets TypeScript to refer to us by our @webhare/... name in auto imports:\ndeclare module \"@webhare/frontend\" {\n}\n\nimport { onDomReady } from \"@webhare/dompack\";\nexport { frontendConfig, getFrontendData, getSiteRoot } from \"./init\";\nexport { startSSOLogin, login, setupWRDAuth, isLoggedIn, logout, getUserInfo, setupWebHareSSOTrigger } from \"./auth\";\nexport { loadAssetPack, setupAuthorMode, type AuthorModeOptions } from \"./authormode\";\nexport { setPxlOptions, sendPxl, getPxlUserId, getPxlSessionId, setupFormAnalytics, type PxlData } from \"./pxl\";\nexport { getRemoteIPAddress, getGeoIPInfo, type GetIPInfoOptions, type GeoIPInfoResult } from \"./analytics\";\nexport { setupGTM, setupFormAnalyticsForGTM, pushToDataLayer, setupDataLayerTags, getCurrentDataLayerVariables } from \"./gtm\";\nexport { setupLinksInNewWindow, type LinkOpenOptions } from \"./linkhandler\";\n\nexport type * from \"./gtm-types\";\n\n// we shouldn't deprecate navigateTo exported from frontend. in fact it makes more sense to export it from frontend than env as it's browser-only\nexport { navigateTo } from \"@webhare/env\";\n\n/** Registry for data we receive from the backend */\nexport interface FrontendDataTypes {\n}\n\n/** Registry for expected PXL formats */\nexport interface PxlDataTypes {\n}\n\n/** Test whether the current page is being iframed in the WebHare test framework */\nexport function isInTestFramework(): boolean {\n  if (window.top !== window) { //in a frame\n    try {\n      if ((window.top as { __testframework?: unknown })?.__testframework)\n        return true;//we're inside a testframe, pretend to be the parent\n    } catch (ignore) {\n    }\n  }\n  return false;\n}\n\nfunction postRenderChecks() {\n  const log = document.getElementById(\"wh-console-log\");\n  if (log) {\n    const logtext = atob(log.textContent || \"\");\n    console.group(\"[etr] Server-side console output\");\n    console.log(logtext);\n    console.groupEnd();\n  }\n}\n\nonDomReady(postRenderChecks);\n","import { onBeforeUnmount, onMounted, readonly, ref } from \"vue\";\n\nconst LOGGED_IN_CLASS = \"wh-wrdauth--isloggedin\";\n\n// Reactive WRDAuth state driven by the `.wh-wrdauth--isloggedin` class that\n// setupWRDAuth() toggles on <html>. Read synchronously in the ref initializer\n// so the first render already reflects login state (no flash of LoginForm for\n// users who arrive logged in).\nexport function useWrdAuthState() {\n  const isLoggedIn = ref(document.documentElement.classList.contains(LOGGED_IN_CLASS));\n  let observer: MutationObserver | null = null;\n\n  function read() {\n    isLoggedIn.value = document.documentElement.classList.contains(LOGGED_IN_CLASS);\n  }\n\n  onMounted(() => {\n    read();\n    observer = new MutationObserver(read);\n    observer.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\"] });\n  });\n\n  onBeforeUnmount(() => {\n    observer?.disconnect();\n    observer = null;\n  });\n\n  return { isLoggedIn: readonly(isLoggedIn) };\n}\n","<script setup lang=\"ts\">\nimport { onBeforeUnmount, onMounted, ref } from \"vue\";\nimport ChatView from \"./ChatView.vue\";\nimport { api } from \"../lib/api\";\nimport { useConversationHistory } from \"../lib/useConversationHistory\";\nimport { clearConversationHash, conversationIdFromHash, setConversationHash } from \"../lib/chatHistory\";\n\nconst { chats, session, loading, error, refresh, open, start, retry } = useConversationHistory({\n  list: () => api.listConversations(),\n  load: id => api.getConversation({ id }),\n  navigate: id => id ? setConversationHash(id) : clearConversationHash(),\n});\nconst initialLoading = ref(!!conversationIdFromHash());\nconst busy = ref(false);\n\nfunction readHash() {\n  if (busy.value) {\n    setConversationHash(session.value.id);\n    return;\n  }\n  const id = conversationIdFromHash();\n  if (id && id !== session.value.id) void open(id);\n  else if (!id) start();\n}\n\nfunction refreshOnFocus() {\n  if (document.visibilityState === \"visible\") void refresh();\n}\n\nonMounted(async () => {\n  window.addEventListener(\"hashchange\", readHash);\n  window.addEventListener(\"focus\", refreshOnFocus);\n  document.addEventListener(\"visibilitychange\", refreshOnFocus);\n  const id = conversationIdFromHash();\n  await Promise.all([refresh(), id ? open(id) : Promise.resolve()]);\n  initialLoading.value = false;\n});\n\nonBeforeUnmount(() => {\n  window.removeEventListener(\"hashchange\", readHash);\n  window.removeEventListener(\"focus\", refreshOnFocus);\n  document.removeEventListener(\"visibilitychange\", refreshOnFocus);\n});\n</script>\n\n<template>\n  <div v-if=\"initialLoading\" class=\"workspace-loading\" role=\"status\">Gesprek laden…</div>\n  <ChatView\n    v-else\n    :key=\"session.revision\"\n    :session=\"session\"\n    :chats=\"chats\"\n    :history-loading=\"loading\"\n    :history-error=\"error\"\n    @select-chat=\"open\"\n    @new-chat=\"start\"\n    @refresh-history=\"refresh\"\n    @retry-history=\"retry\"\n    @busy=\"busy = $event\"\n  />\n</template>\n\n<style scoped>\n.workspace-loading {\n  display: grid;\n  place-items: center;\n  min-height: 100dvh;\n  color: var(--btw-fg-muted);\n}\n</style>\n","<template>\n  <div class=\"chat\">\n    <Sidebar\n      :chats=\"sidebarChats\"\n      :current-chat-id=\"conversationId\"\n      :busy=\"isBusy || historyLoading\"\n      :has-messages=\"chat.messages.length > 0\"\n      :active=\"mockState.active\"\n      :active-conversation-title=\"activeConversation?.title\"\n      :system-prompt=\"meta?.systemPrompt ?? ''\"\n      :api-offline=\"showApiWarning\"\n      @start-test-mode=\"pickerOpen = true\"\n      @stop-test-mode=\"stopTestMode\"\n      @select-chat=\"emit('select-chat', $event)\"\n      @new-chat=\"emit('new-chat')\"\n      @download=\"downloadMarkdown\"\n    />\n\n    <div class=\"chat__main\" :aria-busy=\"historyLoading\">\n      <div v-if=\"historyError\" class=\"chat__history-error\" role=\"alert\">\n        <span>{{ historyError }}</span>\n        <button type=\"button\" class=\"chat__retry\" @click=\"emit('retry-history')\">Opnieuw proberen</button>\n      </div>\n      <div v-if=\"historyLoading\" class=\"chat__history-loading\" role=\"status\">Gesprek laden…</div>\n      <div v-if=\"showApiWarning\" class=\"chat__api-warning\" role=\"alert\">\n        <AlertTriangle :size=\"16\" class=\"chat__api-warning-icon\" />\n        <span>\n          De chat-API draait niet op <code>localhost:4104</code>. Start 'm met\n          <code>./start</code> — zonder API geen modellen en geen antwoorden.\n        </span>\n      </div>\n\n      <div ref=\"scrollEl\" class=\"chat__scroll\" @scroll=\"onScroll\">\n        <!-- Sticky header: gesprekstitel links, download rechts -->\n        <header v-if=\"chat.messages.length > 0\" class=\"chat__header\">\n          <span class=\"chat__header-title\" :title=\"conversationTitle\">{{ conversationTitle }}</span>\n          <button\n            type=\"button\"\n            class=\"chat__header-action\"\n            aria-label=\"Download gesprek\"\n            title=\"Download als Markdown\"\n            @click=\"downloadMarkdown\"\n          >\n            <Download :size=\"16\" />\n          </button>\n        </header>\n\n        <div class=\"chat__inner\">\n          <!-- Empty state -->\n          <div v-if=\"chat.messages.length === 0\" class=\"chat__empty\">\n            <div class=\"chat__empty-head\">\n              <MessageSquare :size=\"32\" class=\"chat__empty-icon\" />\n              <h2 class=\"chat__empty-title\">Welkom bij de BTW Coach</h2>\n              <p class=\"chat__empty-desc\">\n                Stel je vraag over Brede Welvaart in Twente — bijvoorbeeld over beleid, welzijn,\n                duurzaamheid of sociale cohesie in de regio.\n              </p>\n            </div>\n\n            <div class=\"chat__suggestions\">\n              <h3 class=\"chat__suggestions-label\">Relevante test-vragen</h3>\n              <div class=\"chat__suggestions-grid\">\n                <button\n                  v-for=\"(q, i) in RELEVANT_QUESTIONS\"\n                  :key=\"`r${i}`\"\n                  type=\"button\"\n                  class=\"chat__suggestion\"\n                  @click=\"sendText(q.text)\"\n                >\n                  {{ q.text }}\n                  <span v-if=\"q.note\" class=\"chat__suggestion-note\">{{ q.note }}</span>\n                </button>\n              </div>\n            </div>\n\n            <div class=\"chat__suggestions\">\n              <h3 class=\"chat__suggestions-label\">Niet-relevante test-vragen</h3>\n              <div class=\"chat__suggestions-grid\">\n                <button\n                  v-for=\"(q, i) in IRRELEVANT_QUESTIONS\"\n                  :key=\"`i${i}`\"\n                  type=\"button\"\n                  class=\"chat__suggestion\"\n                  @click=\"sendText(q.text)\"\n                >\n                  {{ q.text }}\n                  <span v-if=\"q.note\" class=\"chat__suggestion-note\">{{ q.note }}</span>\n                </button>\n              </div>\n            </div>\n          </div>\n\n          <!-- Messages -->\n          <template v-else>\n            <MessageItem\n              v-for=\"(m, i) in chat.messages\"\n              :key=\"m.id\"\n              :message=\"m\"\n              :is-last=\"i === chat.messages.length - 1\"\n              :is-streaming=\"chat.status === 'streaming'\"\n              :feedback=\"feedbackMap[m.id]\"\n              @feedback=\"(rating) => openFeedback(m, rating)\"\n            />\n            <div v-if=\"chat.status === 'submitted'\" class=\"chat__thinking\">\n              <span class=\"chat__dot\" /><span class=\"chat__dot\" /><span class=\"chat__dot\" />\n            </div>\n          </template>\n          <div v-if=\"chat.error\" class=\"chat__error\" role=\"alert\">\n            <AlertTriangle :size=\"18\" aria-hidden=\"true\" />\n            <div>\n              <p v-if=\"sessionExpired\">{{ SESSION_EXPIRED_MESSAGE }}</p>\n              <p v-else>Het gekozen model kan nu geen antwoord geven. Probeer het later opnieuw.</p>\n              <button v-if=\"!sessionExpired\" type=\"button\" class=\"chat__retry\" @click=\"chat.regenerate()\">\n                Opnieuw proberen\n              </button>\n            </div>\n          </div>\n        </div>\n\n        <!-- Scroll to bottom -->\n        <button\n          v-if=\"!isAtBottom\"\n          type=\"button\"\n          class=\"chat__float chat__float--scroll\"\n          aria-label=\"Naar beneden\"\n          @click=\"scrollToBottom('smooth')\"\n        >\n          <ArrowDown :size=\"16\" />\n        </button>\n      </div>\n\n      <div class=\"chat__dock\">\n        <PromptInput\n          v-model=\"input\"\n          v-model:model-id=\"modelId\"\n          :models=\"meta?.models ?? []\"\n          :status=\"historyLoading ? 'submitted' : chat.status\"\n          @submit=\"handleSubmit\"\n          @stop=\"chat.stop()\"\n        />\n      </div>\n    </div>\n\n    <TestModePicker\n      v-model:open=\"pickerOpen\"\n      :conversations=\"meta?.mockConversations ?? []\"\n      @select=\"selectConversation\"\n    />\n\n    <FeedbackDialog\n      v-model:open=\"feedbackDialog.open\"\n      :rating=\"feedbackDialog.rating\"\n      :existing-comment=\"feedbackDialog.existingComment\"\n      @submit=\"onFeedbackSubmit\"\n    />\n  </div>\n</template>\n\n<script setup lang=\"ts\">\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from \"vue\";\nimport { MessageSquare, Download, ArrowDown, AlertTriangle } from \"lucide-vue-next\";\nimport Sidebar from \"./Sidebar.vue\";\nimport PromptInput from \"./PromptInput.vue\";\nimport MessageItem from \"./MessageItem.vue\";\nimport TestModePicker from \"./TestModePicker.vue\";\nimport FeedbackDialog from \"./FeedbackDialog.vue\";\nimport { createChat } from \"../lib/chat\";\nimport { SESSION_EXPIRED_MESSAGE } from \"../lib/chatAuth\";\nimport {\n  setConversationHash,\n  type FeedbackState,\n  type PersistedChat,\n} from \"../lib/chatHistory\";\nimport { submitFeedback } from \"../lib/api\";\nimport type { ConversationSession, ConversationSummary } from \"../lib/useConversationHistory\";\nimport { fetchMeta, isLocalhost, type ChatMeta } from \"../lib/meta\";\n\nconst props = defineProps<{\n  session: ConversationSession;\n  chats: ConversationSummary[];\n  historyLoading: boolean;\n  historyError: string;\n}>();\nconst emit = defineEmits<{\n  \"select-chat\": [id: string];\n  \"new-chat\": [snapshot?: PersistedChat];\n  \"refresh-history\": [];\n  \"retry-history\": [];\n  busy: [value: boolean];\n}>();\n\nconst RELEVANT_QUESTIONS: { text: string; note?: string }[] = [\n  { text: \"Hoe versterken we sociale verbondenheid in een nieuwe Twentse woonwijk?\", note: \"Raakt WHR 2026 (social connections als welzijnsfactor, generatieverschillen, digitale verdringing)\" },\n  { text: \"Waar moeten we als gemeente op rapporteren voor duurzaamheid?\", note: \"Raakt de Handreiking direct (kernset indicatoren, dubbele materialiteit, stappenplan)\" },\n  { text: \"Wat draagt meer bij aan welzijn van inwoners: inkomen of sociale contacten?\", note: \"Raakt WHR 2026 (income vs connection, life satisfaction data)\" },\n  { text: \"Welke duurzaamheidsgrenzen raken ons in Twente het meest?\", note: \"Combineert Rockström (planetaire grenzen) met Handreiking (gemeentelijk beleid)\" },\n];\nconst IRRELEVANT_QUESTIONS: { text: string; note?: string }[] = [\n  { text: \"Wat is een mooi recept voor soep?\", note: \"Valt buiten het kennisgebied van de coach\" },\n  { text: \"Hoeveel van de negen planetaire grenzen zijn er inmiddels overschreden volgens het meest recente onderzoek van Richardson uit 2023? En hoe verhoudt dat zich tot de oorspronkelijke drie van Rockström?\", note: \"De Richardson 2023-studie staat niet in de kennisbank\" },\n];\n\nconst DEFAULT_MODEL_ID = \"mistral-large\";\nconst MODEL_STORAGE_KEY = \"btw-model-id\";\n\nconst input = ref(\"\");\nconst modelId = ref(DEFAULT_MODEL_ID);\n\n// A keyed view gets a fresh Chat instance for each server-loaded conversation.\n// The Chat id stays identical to the external id used by WRD logging.\nconst conversationId = props.session.id;\nconst persisted = props.session.snapshot;\n\ntype MockState = { active: false } | { active: true; conversationId: string };\nconst mockState = ref<MockState>(\n  persisted?.mock.active && persisted.mock.conversationId\n    ? { active: true, conversationId: persisted.mock.conversationId }\n    : { active: false },\n);\nconst pickerOpen = ref(false);\nconst meta = ref<ChatMeta | null>(null);\nconst metaFailed = ref(false);\n\n// Show a developer hint only locally: a failed meta fetch there almost always\n// means the chat-API on port 4104 isn't running (`./start`).\nconst showApiWarning = computed(() => metaFailed.value && isLocalhost());\n\n// The Chat instance reads mock-mode + model selection per request via getters,\n// so a single instance follows the live selection.\nconst chat = createChat({\n  id: conversationId,\n  initialMessages: persisted?.messages ?? [],\n  getMockMode: () => mockState.value.active,\n  getModelId: () => modelId.value,\n});\n\nconst isBusy = computed(() => chat.status === \"submitted\" || chat.status === \"streaming\");\n// A retry cannot help once the token can no longer be renewed: the user must log in again.\nconst sessionExpired = computed(() => chat.error?.message === SESSION_EXPIRED_MESSAGE);\nwatch(isBusy, value => emit(\"busy\", value), { immediate: true });\nonBeforeUnmount(() => { void chat.stop(); });\n\nconst sidebarChats = computed(() => {\n  if (!chat.messages.length || mockState.value.active || props.chats.some(item => item.id === conversationId)) return props.chats;\n  const current = { id: conversationId, title: conversationTitle.value, updatedAt: Date.now() };\n  return [current, ...props.chats.filter(item => item.id !== conversationId)];\n});\n\nconst activeConversation = computed(() =>\n  mockState.value.active\n    ? meta.value?.mockConversations.find((c) => c.id === mockState.value.conversationId)\n    : undefined,\n);\n\n// Header title: first ~50 chars of the opening question (ellipsis if longer).\nconst conversationTitle = computed(() => {\n  const firstUser = chat.messages.find((m) => m.role === \"user\");\n  const text = textOf(firstUser).trim().replace(/\\s+/g, \" \");\n  if (!text) return \"Gesprek\";\n  return text.length > 50 ? `${text.slice(0, 50).trimEnd()}…` : text;\n});\n\n// ── Feedback ───────────────────────────────────────────────────────────────\n// Per assistant message.id → the rating/comment the user left. Restored from the\n// persisted snapshot so the active thumb survives a refresh; kept in sync with\n// the server via submitFeedback (upsert per messageId).\nconst feedbackMap = ref<Record<string, FeedbackState>>(persisted?.feedback ?? {});\n\nconst feedbackDialog = ref<{\n  open: boolean;\n  messageId: string;\n  rating: \"positive\" | \"negative\";\n  question: string;\n  response: string;\n  existingComment: string;\n}>({ open: false, messageId: \"\", rating: \"positive\", question: \"\", response: \"\", existingComment: \"\" });\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction textOf(m: any | undefined): string {\n  if (!m) return \"\";\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  return (m.parts ?? []).filter((p: any) => p.type === \"text\").map((p: any) => p.text).join(\"\");\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction openFeedback(message: any, rating: \"positive\" | \"negative\") {\n  const idx = chat.messages.findIndex((m) => m.id === message.id);\n  const priorUser = idx > 0\n    ? [...chat.messages.slice(0, idx)].reverse().find((m) => m.role === \"user\")\n    : undefined;\n  feedbackDialog.value = {\n    open: true,\n    messageId: message.id,\n    rating,\n    question: textOf(priorUser),\n    response: textOf(message),\n    existingComment: feedbackMap.value[message.id]?.comment ?? \"\",\n  };\n}\n\nasync function onFeedbackSubmit(comment: string) {\n  const d = feedbackDialog.value;\n  feedbackDialog.value = { ...d, open: false };\n  // Optimistic local state (also triggers the persist watch below).\n  feedbackMap.value = { ...feedbackMap.value, [d.messageId]: { rating: d.rating, comment } };\n  try {\n    const res = await submitFeedback({\n      externalId: conversationId,\n      messageId: d.messageId,\n      rating: d.rating,\n      comment,\n      question: d.question,\n      response: d.response,\n    });\n    if (!res.ok) console.error(\"submitFeedback:\", res.error);\n  } catch (err) {\n    console.error(\"submitFeedback failed:\", err);\n  }\n}\n\nonMounted(async () => {\n  // Restore the persisted model (in onMounted, not the ref initializer, to keep\n  // SSR-safe / avoid hydration mismatch).\n  try {\n    const stored = localStorage.getItem(MODEL_STORAGE_KEY);\n    if (stored) modelId.value = stored;\n  } catch { /* ignore */ }\n\n  try {\n    meta.value = await fetchMeta();\n    // If no stored choice, adopt the server default.\n    if (!localStorage.getItem(MODEL_STORAGE_KEY) && meta.value.defaultModelId) {\n      modelId.value = meta.value.defaultModelId;\n    }\n    // If the (possibly persisted) selection is unknown or now disabled, fall\n    // back to the server default so the picker never shows a greyed selection.\n    const current = meta.value.models.find((m) => m.id === modelId.value);\n    if ((!current || current.disabled) && meta.value.defaultModelId) {\n      modelId.value = meta.value.defaultModelId;\n    }\n  } catch (err) {\n    console.error(\"fetchMeta failed:\", err);\n    metaFailed.value = true;\n  }\n\n  // Resume: prefill the next mock question (meta is now loaded) and open the\n  // conversation scrolled to the latest message.\n  prefillNextMockQuestion();\n  if (chat.messages.length > 0) void nextTick(() => scrollToBottom(\"auto\"));\n});\n\n// Persist model selection on change.\nwatch(modelId, (id) => {\n  try { localStorage.setItem(MODEL_STORAGE_KEY, id); } catch { /* ignore */ }\n});\n\n// ── Sending ──────────────────────────────────────────────────────────────────\nfunction handleSubmit() {\n  const text = input.value.trim();\n  if (!text || isBusy.value || props.historyLoading) return;\n  void chat.sendMessage({ text });\n  input.value = \"\";\n}\nfunction sendText(text: string) {\n  if (!text.trim() || isBusy.value || props.historyLoading) return;\n  void chat.sendMessage({ text });\n}\n\n// ── Test mode ────────────────────────────────────────────────────────────────\nfunction selectConversation(conversationId: string) {\n  if (isBusy.value || props.historyLoading) return;\n  emit(\"new-chat\", { messages: [], mock: { active: true, conversationId } });\n}\nfunction stopTestMode() {\n  if (isBusy.value || props.historyLoading) return;\n  emit(\"new-chat\");\n}\n\n// Auto-prefill the next mock question after each turn completes. Extracted so\n// onMounted can also trigger it on resume, once meta has loaded (the watcher\n// alone doesn't fire for the async meta arrival).\nfunction prefillNextMockQuestion() {\n  if (!mockState.value.active) return;\n  if (chat.status === \"submitted\" || chat.status === \"streaming\") return;\n  const conv = meta.value?.mockConversations.find((c) => c.id === mockState.value.conversationId);\n  if (!conv) return;\n  const userCount = chat.messages.filter((m) => m.role === \"user\").length;\n  const next = conv.questions[userCount];\n  if (next) input.value = next;\n}\nwatch(\n  [() => chat.messages.length, () => chat.status, mockState],\n  prefillNextMockQuestion,\n);\n\n// ── Persistence / resume ─────────────────────────────────────────────────────\n// The streaming API writes each completed turn to WRD. Refresh its summaries\n// after a turn settles; opening a conversation always reads its server history.\nwatch(\n  () => chat.status,\n  (_status, previous) => {\n    if (chat.messages.length && !mockState.value.active) setConversationHash(conversationId);\n    if ((previous === \"submitted\" || previous === \"streaming\") && !isBusy.value) {\n      emit(\"refresh-history\");\n    }\n  },\n);\n\n// ── Scroll / stick-to-bottom ─────────────────────────────────────────────────\nconst scrollEl = ref<HTMLElement | null>(null);\nconst isAtBottom = ref(true);\n\nfunction onScroll() {\n  const el = scrollEl.value;\n  if (!el) return;\n  isAtBottom.value = el.scrollHeight - el.scrollTop - el.clientHeight < 80;\n}\nfunction scrollToBottom(behavior: ScrollBehavior = \"auto\") {\n  const el = scrollEl.value;\n  if (!el) return;\n  el.scrollTo({ top: el.scrollHeight, behavior });\n}\n\n// Follow new content while the user is at the bottom.\nwatch(\n  [() => chat.messages, () => chat.status],\n  () => {\n    if (isAtBottom.value) void nextTick(() => scrollToBottom(\"smooth\"));\n  },\n  { deep: true },\n);\n\n// ── Download as markdown ─────────────────────────────────────────────────────\nfunction downloadMarkdown() {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  const md = chat.messages\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    .map((m: any) => {\n      const role = m.role === \"user\" ? \"Gebruiker\" : \"BTW Coach\";\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      const text = (m.parts ?? []).filter((p: any) => p.type === \"text\").map((p: any) => p.text).join(\"\");\n      return `**${role}:** ${text}`;\n    })\n    .join(\"\\n\\n\");\n  const blob = new Blob([md], { type: \"text/markdown\" });\n  const url = URL.createObjectURL(blob);\n  const a = document.createElement(\"a\");\n  a.href = url;\n  a.download = \"btw-coach-gesprek.md\";\n  document.body.appendChild(a);\n  a.click();\n  a.remove();\n  URL.revokeObjectURL(url);\n}\n</script>\n\n<style scoped>\n.chat {\n  display: flex;\n  /* Pin the chat to the viewport height so .chat__scroll is the internal\n     scroller (the document must not scroll), keeping the header + dock fixed.\n     #app is only min-height:100dvh, so without an explicit height here the\n     flex chain grows with the content and the whole page scrolls instead.\n     flex: none (not flex: 1) so this explicit height wins over a 0% basis. */\n  flex: none;\n  height: 100dvh;\n  min-height: 0;\n}\n.chat__main {\n  display: flex;\n  flex-direction: column;\n  flex: 1;\n  min-width: 0;\n  /* Also cap height so .chat__scroll (not the document) is the scroller.\n     Without this the flex chain leaks and the whole page scrolls, defeating\n     the sticky header, the scroll-to-bottom button and stream auto-follow. */\n  min-height: 0;\n}\n.chat__scroll {\n  position: relative;\n  flex: 1;\n  min-height: 0;\n  overflow-y: auto;\n}\n.chat__api-warning {\n  display: flex;\n  align-items: flex-start;\n  gap: 8px;\n  margin: 12px 20px 0;\n  padding: 10px 14px;\n  border: 1px solid var(--btw-warning, #b45309);\n  border-radius: 10px;\n  background: color-mix(in oklab, var(--btw-warning, #b45309) 12%, transparent);\n  color: var(--btw-fg);\n  font-size: 13px;\n  line-height: 1.5;\n}\n.chat__api-warning-icon { flex-shrink: 0; margin-top: 1px; color: var(--btw-warning, #b45309); }\n.chat__api-warning code {\n  font-family: var(--font-mono);\n  font-size: 12px;\n  padding: 1px 5px;\n  border-radius: 5px;\n  background: var(--btw-surface-2);\n}\n.chat__inner {\n  max-width: 768px;\n  margin: 0 auto;\n  padding: 28px 20px 8px;\n  display: flex;\n  flex-direction: column;\n  gap: 24px;\n}\n.chat__error {\n  display: flex;\n  align-items: flex-start;\n  gap: 10px;\n  padding: 14px 16px;\n  border: 1px solid var(--btw-warning, #b45309);\n  border-radius: 10px;\n  background: color-mix(in oklab, var(--btw-warning, #b45309) 12%, transparent);\n  color: var(--btw-fg);\n  line-height: 1.5;\n}\n.chat__error > svg { flex-shrink: 0; margin-top: 3px; }\n.chat__error p { margin: 0; }\n.chat__retry {\n  margin-top: 8px;\n  padding: 4px 0;\n  border: 0;\n  background: transparent;\n  color: var(--btw-fg);\n  font: inherit;\n  text-decoration: underline;\n  cursor: pointer;\n}\n\n/* Empty state */\n.chat__empty {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: 26px;\n  padding: 40px 0;\n}\n.chat__empty-head {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  text-align: center;\n  gap: 8px;\n  max-width: 480px;\n}\n.chat__empty-icon { color: var(--btw-accent); }\n.chat__empty-title { margin: 4px 0 0; font-size: 20px; font-weight: 700; color: var(--btw-fg); }\n.chat__empty-desc { margin: 0; font-size: 14px; color: var(--btw-fg-muted); line-height: 1.55; }\n.chat__suggestions { width: 100%; max-width: 640px; }\n.chat__suggestions-label {\n  margin: 0 0 8px;\n  font-size: 11px;\n  font-weight: 600;\n  letter-spacing: 0.05em;\n  text-transform: uppercase;\n  color: var(--btw-fg-subtle);\n}\n.chat__suggestions-grid {\n  display: grid;\n  grid-template-columns: 1fr;\n  gap: 8px;\n}\n@media (min-width: 640px) {\n  .chat__suggestions-grid { grid-template-columns: 1fr 1fr; }\n}\n.chat__suggestion {\n  display: block;\n  padding: 12px 14px;\n  border: 1px solid var(--btw-line);\n  border-radius: 12px;\n  background: var(--btw-surface);\n  color: var(--btw-fg-muted);\n  font-size: 13.5px;\n  text-align: left;\n  cursor: pointer;\n  transition: background 0.12s, color 0.12s, border-color 0.12s;\n}\n.chat__suggestion:hover {\n  background: var(--btw-accent-soft);\n  border-color: var(--btw-accent-soft);\n  color: var(--btw-fg);\n}\n.chat__suggestion-note {\n  display: block;\n  margin-top: 5px;\n  font-size: 11.5px;\n  font-style: italic;\n  color: var(--btw-fg-subtle);\n}\n\n/* Thinking dots */\n.chat__thinking { display: flex; gap: 5px; padding: 4px 2px; }\n.chat__dot {\n  width: 7px; height: 7px; border-radius: 50%;\n  background: var(--btw-fg-subtle);\n  animation: btw-bounce 1.2s infinite ease-in-out;\n}\n.chat__dot:nth-child(2) { animation-delay: 0.15s; }\n.chat__dot:nth-child(3) { animation-delay: 0.3s; }\n@keyframes btw-bounce {\n  0%, 80%, 100% { opacity: 0.3; transform: translateY(0); }\n  40% { opacity: 1; transform: translateY(-3px); }\n}\n\n/* Sticky header */\n.chat__header {\n  position: sticky;\n  top: 0;\n  z-index: 5;\n  display: flex;\n  align-items: center;\n  gap: 12px;\n  padding: 10px 20px;\n  background: color-mix(in oklab, var(--btw-bg) 82%, transparent);\n  backdrop-filter: blur(12px) saturate(1.4);\n  -webkit-backdrop-filter: blur(12px) saturate(1.4);\n  border-bottom: 1px solid var(--btw-line);\n}\n.chat__header-title {\n  flex: 1;\n  min-width: 0;\n  font-size: 13.5px;\n  font-weight: 600;\n  color: var(--btw-fg-muted);\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n}\n.chat__header-action {\n  flex-shrink: 0;\n  display: grid;\n  place-items: center;\n  width: 32px;\n  height: 32px;\n  border-radius: 8px;\n  border: 1px solid var(--btw-line);\n  background: var(--btw-surface);\n  color: var(--btw-fg-muted);\n  cursor: pointer;\n  transition: background 0.12s, color 0.12s;\n}\n.chat__header-action:hover { background: var(--btw-surface-2); color: var(--btw-fg); }\n\n/* Floating buttons */\n.chat__float {\n  position: sticky;\n  display: grid;\n  place-items: center;\n  width: 36px;\n  height: 36px;\n  border-radius: 999px;\n  border: 1px solid var(--btw-line);\n  background: var(--btw-surface);\n  color: var(--btw-fg-muted);\n  cursor: pointer;\n  box-shadow: var(--btw-shadow-card);\n  transition: background 0.12s, color 0.12s;\n}\n.chat__float:hover { background: var(--btw-surface-2); color: var(--btw-fg); }\n.chat__float--scroll {\n  bottom: 16px;\n  left: 50%;\n  margin-left: -18px;\n}\n\n.chat__dock {\n  flex-shrink: 0;\n  padding: 12px 20px 18px;\n  border-top: 1px solid var(--btw-line);\n}\n\n@media (max-width: 720px) {\n  .chat { flex-direction: column; }\n  .chat__inner { padding: 18px 16px 8px; gap: 20px; }\n  .chat__dock { padding: 8px 12px max(12px, env(safe-area-inset-bottom)); border-top: 0; }\n  .chat__empty { padding: 24px 0; gap: 24px; }\n  .chat__header { display: none; }\n  .chat__header-action { width: 44px; height: 44px; }\n  .chat__float { width: 44px; height: 44px; }\n  .chat__float--scroll { margin-left: -22px; }\n}\n.chat__history-error, .chat__history-loading {\n  padding: 12px 16px;\n  color: var(--btw-fg-muted);\n  font-size: 14px;\n}\n.chat__history-error { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }\n.chat__history-error .chat__retry { margin: 0; }\n@media (prefers-reduced-motion: reduce) {\n  .chat__float { transition: none; }\n}\n</style>\n","/**\n * Check if a component has an accessibility prop\n *\n * @param {object} props\n * @returns {boolean} Whether the component has an accessibility prop\n */\nexport const hasA11yProp = (props: Record<string, any>) => {\n  for (const prop in props) {\n    if (prop.startsWith('aria-') || prop === 'role' || prop === 'title') {\n      return true;\n    }\n  }\n\n  return false;\n};\n","/**\n * Is empty string\n *\n * @param {unknown} value\n * @returns {boolean} Whether the value is an empty string\n */\nexport const isEmptyString = (value: unknown): boolean => value === '';\n","/**\n * Merges classes into a single string\n *\n * @param {array} classes\n * @returns {string} A string of classes\n */\nexport const mergeClasses = <ClassType = string | undefined | null>(...classes: ClassType[]) =>\n  classes\n    .filter((className, index, array) => {\n      return (\n        Boolean(className) &&\n        (className as string).trim() !== '' &&\n        array.indexOf(className) === index\n      );\n    })\n    .join(' ')\n    .trim();\n","/**\n * Converts string to kebab case\n *\n * @param {string} string\n * @returns {string} A kebabized string\n */\nexport const toKebabCase = (string: string) =>\n  string.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n","/**\n * Converts string to camel case\n *\n * @param {string} string\n * @returns {string} A camelized string\n */\nexport const toCamelCase = <T extends string>(string: T) =>\n  string.replace(/^([A-Z])|[\\s-_]+(\\w)/g, (match, p1, p2) =>\n    p2 ? p2.toUpperCase() : p1.toLowerCase(),\n  );\n","import { CamelToPascal } from '../utility-types';\nimport { toCamelCase } from './toCamelCase';\n\n/**\n * Converts string to pascal case\n *\n * @param {string} string\n * @returns {string} A pascalized string\n */\nexport const toPascalCase = <T extends string>(string: T): CamelToPascal<T> => {\n  const camelCase = toCamelCase(string);\n\n  return (camelCase.charAt(0).toUpperCase() + camelCase.slice(1)) as CamelToPascal<T>;\n};\n","export default {\n  xmlns: 'http://www.w3.org/2000/svg',\n  width: 24,\n  height: 24,\n  viewBox: '0 0 24 24',\n  fill: 'none',\n  stroke: 'currentColor',\n  'stroke-width': 2,\n  'stroke-linecap': 'round',\n  'stroke-linejoin': 'round',\n};\n","import { type FunctionalComponent, h } from 'vue';\nimport {\n  mergeClasses,\n  toKebabCase,\n  toPascalCase,\n  isEmptyString,\n  hasA11yProp,\n} from '@lucide/shared';\nimport defaultAttributes from './defaultAttributes';\nimport { IconNode, LucideProps } from './types';\n\ninterface IconProps {\n  iconNode: IconNode;\n  name: string;\n}\n\nconst Icon: FunctionalComponent<LucideProps & IconProps> = (\n  {\n    name,\n    iconNode,\n    absoluteStrokeWidth,\n    'absolute-stroke-width': absoluteStrokeWidthKebabCase,\n    strokeWidth,\n    'stroke-width': strokeWidthKebabCase,\n    size = defaultAttributes.width,\n    color = defaultAttributes.stroke,\n    ...props\n  },\n  { slots },\n) => {\n  return h(\n    'svg',\n    {\n      ...defaultAttributes,\n      ...props,\n      width: size,\n      height: size,\n      stroke: color,\n      'stroke-width':\n        isEmptyString(absoluteStrokeWidth) ||\n        isEmptyString(absoluteStrokeWidthKebabCase) ||\n        absoluteStrokeWidth === true ||\n        absoluteStrokeWidthKebabCase === true\n          ? (Number(strokeWidth || strokeWidthKebabCase || defaultAttributes['stroke-width']) *\n              24) /\n            Number(size)\n          : strokeWidth || strokeWidthKebabCase || defaultAttributes['stroke-width'],\n      class: mergeClasses(\n        'lucide',\n        props.class,\n        ...(name\n          ? [`lucide-${toKebabCase(toPascalCase(name))}-icon`, `lucide-${toKebabCase(name)}`]\n          : ['lucide-icon']),\n      ),\n      ...(!slots.default && !hasA11yProp(props) && { 'aria-hidden': 'true' }),\n    },\n    [...iconNode.map((child) => h(...child)), ...(slots.default ? [slots.default()] : [])],\n  );\n};\n\nexport default Icon;\n","import { h } from 'vue';\nimport type { FunctionalComponent } from 'vue';\nimport { IconNode, LucideProps } from './types';\nimport Icon from './Icon';\n\n// Create interface extending SVGAttributes\n\n/**\n * Create a Lucide icon component\n * @param {string} iconName\n * @param {array} iconNode\n * @returns {FunctionalComponent} LucideIcon\n */\nconst createLucideIcon =\n  (iconName: string, iconNode: IconNode): FunctionalComponent<LucideProps> =>\n  (props, { slots, attrs }) =>\n    h(\n      Icon,\n      {\n        ...attrs,\n        ...props,\n        iconNode,\n        name: iconName,\n      },\n      slots,\n    );\n\nexport default createLucideIcon;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ArrowDown\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTIgNXYxNCIgLz4KICA8cGF0aCBkPSJtMTkgMTItNyA3LTctNyIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/arrow-down\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst ArrowDown = createLucideIcon('arrow-down', [\n  ['path', { d: 'M12 5v14', key: 's699le' }],\n  ['path', { d: 'm19 12-7 7-7-7', key: '1idqje' }],\n]);\n\nexport default ArrowDown;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Brain\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTIgMThWNSIgLz4KICA8cGF0aCBkPSJNMTUgMTNhNC4xNyA0LjE3IDAgMCAxLTMtNCA0LjE3IDQuMTcgMCAwIDEtMyA0IiAvPgogIDxwYXRoIGQ9Ik0xNy41OTggNi41QTMgMyAwIDEgMCAxMiA1YTMgMyAwIDEgMC01LjU5OCAxLjUiIC8+CiAgPHBhdGggZD0iTTE3Ljk5NyA1LjEyNWE0IDQgMCAwIDEgMi41MjYgNS43NyIgLz4KICA8cGF0aCBkPSJNMTggMThhNCA0IDAgMCAwIDItNy40NjQiIC8+CiAgPHBhdGggZD0iTTE5Ljk2NyAxNy40ODNBNCA0IDAgMSAxIDEyIDE4YTQgNCAwIDEgMS03Ljk2Ny0uNTE3IiAvPgogIDxwYXRoIGQ9Ik02IDE4YTQgNCAwIDAgMS0yLTcuNDY0IiAvPgogIDxwYXRoIGQ9Ik02LjAwMyA1LjEyNWE0IDQgMCAwIDAtMi41MjYgNS43NyIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/brain\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst Brain = createLucideIcon('brain', [\n  ['path', { d: 'M12 18V5', key: 'adv99a' }],\n  ['path', { d: 'M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4', key: '1e3is1' }],\n  ['path', { d: 'M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5', key: '1gqd8o' }],\n  ['path', { d: 'M17.997 5.125a4 4 0 0 1 2.526 5.77', key: 'iwvgf7' }],\n  ['path', { d: 'M18 18a4 4 0 0 0 2-7.464', key: 'efp6ie' }],\n  ['path', { d: 'M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517', key: '1gq6am' }],\n  ['path', { d: 'M6 18a4 4 0 0 1-2-7.464', key: 'k1g0md' }],\n  ['path', { d: 'M6.003 5.125a4 4 0 0 0-2.526 5.77', key: 'q97ue3' }],\n]);\n\nexport default Brain;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Check\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMjAgNiA5IDE3bC01LTUiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/check\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst Check = createLucideIcon('check', [['path', { d: 'M20 6 9 17l-5-5', key: '1gmf2c' }]]);\n\nexport default Check;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ChevronDown\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJtNiA5IDYgNiA2LTYiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/chevron-down\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst ChevronDown = createLucideIcon('chevron-down', [\n  ['path', { d: 'm6 9 6 6 6-6', key: 'qrunsl' }],\n]);\n\nexport default ChevronDown;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name CircleAlert\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCIgLz4KICA8bGluZSB4MT0iMTIiIHgyPSIxMiIgeTE9IjgiIHkyPSIxMiIgLz4KICA8bGluZSB4MT0iMTIiIHgyPSIxMi4wMSIgeTE9IjE2IiB5Mj0iMTYiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/circle-alert\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst CircleAlert = createLucideIcon('circle-alert', [\n  ['circle', { cx: '12', cy: '12', r: '10', key: '1mglay' }],\n  ['line', { x1: '12', x2: '12', y1: '8', y2: '12', key: '1pkeuh' }],\n  ['line', { x1: '12', x2: '12.01', y1: '16', y2: '16', key: '4dfq90' }],\n]);\n\nexport default CircleAlert;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Copy\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cmVjdCB3aWR0aD0iMTQiIGhlaWdodD0iMTQiIHg9IjgiIHk9IjgiIHJ4PSIyIiByeT0iMiIgLz4KICA8cGF0aCBkPSJNNCAxNmMtMS4xIDAtMi0uOS0yLTJWNGMwLTEuMS45LTIgMi0yaDEwYzEuMSAwIDIgLjkgMiAyIiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/copy\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst Copy = createLucideIcon('copy', [\n  ['rect', { width: '14', height: '14', x: '8', y: '8', rx: '2', ry: '2', key: '17jyea' }],\n  ['path', { d: 'M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2', key: 'zix9uf' }],\n]);\n\nexport default Copy;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name CornerDownLeft\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMjAgNHY3YTQgNCAwIDAgMS00IDRINCIgLz4KICA8cGF0aCBkPSJtOSAxMC01IDUgNSA1IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/corner-down-left\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst CornerDownLeft = createLucideIcon('corner-down-left', [\n  ['path', { d: 'M20 4v7a4 4 0 0 1-4 4H4', key: '6o5b7l' }],\n  ['path', { d: 'm9 10-5 5 5 5', key: '1kshq7' }],\n]);\n\nexport default CornerDownLeft;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Download\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTIgMTVWMyIgLz4KICA8cGF0aCBkPSJNMjEgMTV2NGEyIDIgMCAwIDEtMiAySDVhMiAyIDAgMCAxLTItMnYtNCIgLz4KICA8cGF0aCBkPSJtNyAxMCA1IDUgNS01IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/download\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst Download = createLucideIcon('download', [\n  ['path', { d: 'M12 15V3', key: 'm9g1x1' }],\n  ['path', { d: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4', key: 'ih7n3h' }],\n  ['path', { d: 'm7 10 5 5 5-5', key: 'brsn70' }],\n]);\n\nexport default Download;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name FileText\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNNiAyMmEyIDIgMCAwIDEtMi0yVjRhMiAyIDAgMCAxIDItMmg4YTIuNCAyLjQgMCAwIDEgMS43MDQuNzA2bDMuNTg4IDMuNTg4QTIuNCAyLjQgMCAwIDEgMjAgOHYxMmEyIDIgMCAwIDEtMiAyeiIgLz4KICA8cGF0aCBkPSJNMTQgMnY1YTEgMSAwIDAgMCAxIDFoNSIgLz4KICA8cGF0aCBkPSJNMTAgOUg4IiAvPgogIDxwYXRoIGQ9Ik0xNiAxM0g4IiAvPgogIDxwYXRoIGQ9Ik0xNiAxN0g4IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/file-text\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst FileText = createLucideIcon('file-text', [\n  [\n    'path',\n    {\n      d: 'M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z',\n      key: '1oefj6',\n    },\n  ],\n  ['path', { d: 'M14 2v5a1 1 0 0 0 1 1h5', key: 'wfsgrz' }],\n  ['path', { d: 'M10 9H8', key: 'b1mrlr' }],\n  ['path', { d: 'M16 13H8', key: 't4e002' }],\n  ['path', { d: 'M16 17H8', key: 'z1uh3a' }],\n]);\n\nexport default FileText;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name FlaskConical\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTQgMnY2YTIgMiAwIDAgMCAuMjQ1Ljk2bDUuNTEgMTAuMDhBMiAyIDAgMCAxIDE4IDIySDZhMiAyIDAgMCAxLTEuNzU1LTIuOTZsNS41MS0xMC4wOEEyIDIgMCAwIDAgMTAgOFYyIiAvPgogIDxwYXRoIGQ9Ik02LjQ1MyAxNWgxMS4wOTQiIC8+CiAgPHBhdGggZD0iTTguNSAyaDciIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/flask-conical\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst FlaskConical = createLucideIcon('flask-conical', [\n  [\n    'path',\n    {\n      d: 'M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2',\n      key: '18mbvz',\n    },\n  ],\n  ['path', { d: 'M6.453 15h11.094', key: '3shlmq' }],\n  ['path', { d: 'M8.5 2h7', key: 'csnxdl' }],\n]);\n\nexport default FlaskConical;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name LoaderCircle\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMjEgMTJhOSA5IDAgMSAxLTYuMjE5LTguNTYiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/loader-circle\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst LoaderCircle = createLucideIcon('loader-circle', [\n  ['path', { d: 'M21 12a9 9 0 1 1-6.219-8.56', key: '13zald' }],\n]);\n\nexport default LoaderCircle;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name LogOut\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJtMTYgMTcgNS01LTUtNSIgLz4KICA8cGF0aCBkPSJNMjEgMTJIOSIgLz4KICA8cGF0aCBkPSJNOSAyMUg1YTIgMiAwIDAgMS0yLTJWNWEyIDIgMCAwIDEgMi0yaDQiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/log-out\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst LogOut = createLucideIcon('log-out', [\n  ['path', { d: 'm16 17 5-5-5-5', key: '1bji2h' }],\n  ['path', { d: 'M21 12H9', key: 'dn1m92' }],\n  ['path', { d: 'M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4', key: '1uf3rs' }],\n]);\n\nexport default LogOut;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Menu\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNNCA1aDE2IiAvPgogIDxwYXRoIGQ9Ik00IDEyaDE2IiAvPgogIDxwYXRoIGQ9Ik00IDE5aDE2IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/menu\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst Menu = createLucideIcon('menu', [\n  ['path', { d: 'M4 5h16', key: '1tepv9' }],\n  ['path', { d: 'M4 12h16', key: '1lakjw' }],\n  ['path', { d: 'M4 19h16', key: '1djgab' }],\n]);\n\nexport default Menu;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name MessageSquare\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMjIgMTdhMiAyIDAgMCAxLTIgMkg2LjgyOGEyIDIgMCAwIDAtMS40MTQuNTg2bC0yLjIwMiAyLjIwMkEuNzEuNzEgMCAwIDEgMiAyMS4yODZWNWEyIDIgMCAwIDEgMi0yaDE2YTIgMiAwIDAgMSAyIDJ6IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/message-square\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst MessageSquare = createLucideIcon('message-square', [\n  [\n    'path',\n    {\n      d: 'M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z',\n      key: '18887p',\n    },\n  ],\n]);\n\nexport default MessageSquare;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Moon\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMjAuOTg1IDEyLjQ4NmE5IDkgMCAxIDEtOS40NzMtOS40NzJjLjQwNS0uMDIyLjYxNy40Ni40MDIuODAzYTYgNiAwIDAgMCA4LjI2OCA4LjI2OGMuMzQ0LS4yMTUuODI1LS4wMDQuODAzLjQwMSIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/moon\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst Moon = createLucideIcon('moon', [\n  [\n    'path',\n    {\n      d: 'M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401',\n      key: 'kfwtm',\n    },\n  ],\n]);\n\nexport default Moon;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Search\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJtMjEgMjEtNC4zNC00LjM0IiAvPgogIDxjaXJjbGUgY3g9IjExIiBjeT0iMTEiIHI9IjgiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/search\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst Search = createLucideIcon('search', [\n  ['path', { d: 'm21 21-4.34-4.34', key: '14j7rj' }],\n  ['circle', { cx: '11', cy: '11', r: '8', key: '4ej97u' }],\n]);\n\nexport default Search;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name SquarePen\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTIgM0g1YTIgMiAwIDAgMC0yIDJ2MTRhMiAyIDAgMCAwIDIgMmgxNGEyIDIgMCAwIDAgMi0ydi03IiAvPgogIDxwYXRoIGQ9Ik0xOC4zNzUgMi42MjVhMSAxIDAgMCAxIDMgM2wtOS4wMTMgOS4wMTRhMiAyIDAgMCAxLS44NTMuNTA1bC0yLjg3My44NGEuNS41IDAgMCAxLS42Mi0uNjJsLjg0LTIuODczYTIgMiAwIDAgMSAuNTA2LS44NTJ6IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/square-pen\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst SquarePen = createLucideIcon('square-pen', [\n  ['path', { d: 'M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7', key: '1m0v6g' }],\n  [\n    'path',\n    {\n      d: 'M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z',\n      key: 'ohrbg2',\n    },\n  ],\n]);\n\nexport default SquarePen;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Square\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cmVjdCB3aWR0aD0iMTgiIGhlaWdodD0iMTgiIHg9IjMiIHk9IjMiIHJ4PSIyIiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/square\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst Square = createLucideIcon('square', [\n  ['rect', { width: '18', height: '18', x: '3', y: '3', rx: '2', key: 'afitv7' }],\n]);\n\nexport default Square;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Sun\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSI0IiAvPgogIDxwYXRoIGQ9Ik0xMiAydjIiIC8+CiAgPHBhdGggZD0iTTEyIDIwdjIiIC8+CiAgPHBhdGggZD0ibTQuOTMgNC45MyAxLjQxIDEuNDEiIC8+CiAgPHBhdGggZD0ibTE3LjY2IDE3LjY2IDEuNDEgMS40MSIgLz4KICA8cGF0aCBkPSJNMiAxMmgyIiAvPgogIDxwYXRoIGQ9Ik0yMCAxMmgyIiAvPgogIDxwYXRoIGQ9Im02LjM0IDE3LjY2LTEuNDEgMS40MSIgLz4KICA8cGF0aCBkPSJtMTkuMDcgNC45My0xLjQxIDEuNDEiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/sun\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst Sun = createLucideIcon('sun', [\n  ['circle', { cx: '12', cy: '12', r: '4', key: '4exip2' }],\n  ['path', { d: 'M12 2v2', key: 'tus03m' }],\n  ['path', { d: 'M12 20v2', key: '1lh1kg' }],\n  ['path', { d: 'm4.93 4.93 1.41 1.41', key: '149t6j' }],\n  ['path', { d: 'm17.66 17.66 1.41 1.41', key: 'ptbguv' }],\n  ['path', { d: 'M2 12h2', key: '1t8f8n' }],\n  ['path', { d: 'M20 12h2', key: '1q8mjw' }],\n  ['path', { d: 'm6.34 17.66-1.41 1.41', key: '1m8zz5' }],\n  ['path', { d: 'm19.07 4.93-1.41 1.41', key: '1shlcs' }],\n]);\n\nexport default Sun;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ThumbsUp\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTUgNS44OCAxNCAxMGg1LjgzYTIgMiAwIDAgMSAxLjkyIDIuNTZsLTIuMzMgOEEyIDIgMCAwIDEgMTcuNSAyMkg0YTIgMiAwIDAgMS0yLTJ2LThhMiAyIDAgMCAxIDItMmgyLjc2YTIgMiAwIDAgMCAxLjc5LTEuMTFMMTIgMmEzLjEzIDMuMTMgMCAwIDEgMyAzLjg4WiIgLz4KICA8cGF0aCBkPSJNNyAxMHYxMiIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/thumbs-up\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst ThumbsUp = createLucideIcon('thumbs-up', [\n  [\n    'path',\n    {\n      d: 'M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z',\n      key: 'emmmcr',\n    },\n  ],\n  ['path', { d: 'M7 10v12', key: '1qc93n' }],\n]);\n\nexport default ThumbsUp;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ThumbsDown\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNOSAxOC4xMiAxMCAxNEg0LjE3YTIgMiAwIDAgMS0xLjkyLTIuNTZsMi4zMy04QTIgMiAwIDAgMSA2LjUgMkgyMGEyIDIgMCAwIDEgMiAydjhhMiAyIDAgMCAxLTIgMmgtMi43NmEyIDIgMCAwIDAtMS43OSAxLjExTDEyIDIyYTMuMTMgMy4xMyAwIDAgMS0zLTMuODhaIiAvPgogIDxwYXRoIGQ9Ik0xNyAxNFYyIiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/thumbs-down\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst ThumbsDown = createLucideIcon('thumbs-down', [\n  [\n    'path',\n    {\n      d: 'M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z',\n      key: 'm61m77',\n    },\n  ],\n  ['path', { d: 'M17 14V2', key: '8ymqnk' }],\n]);\n\nexport default ThumbsDown;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name TriangleAlert\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJtMjEuNzMgMTgtOC0xNGEyIDIgMCAwIDAtMy40OCAwbC04IDE0QTIgMiAwIDAgMCA0IDIxaDE2YTIgMiAwIDAgMCAxLjczLTMiIC8+CiAgPHBhdGggZD0iTTEyIDl2NCIgLz4KICA8cGF0aCBkPSJNMTIgMTdoLjAxIiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/triangle-alert\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst TriangleAlert = createLucideIcon('triangle-alert', [\n  [\n    'path',\n    {\n      d: 'm21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3',\n      key: 'wmoenq',\n    },\n  ],\n  ['path', { d: 'M12 9v4', key: 'juzpu7' }],\n  ['path', { d: 'M12 17h.01', key: 'p32p05' }],\n]);\n\nexport default TriangleAlert;\n","import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name X\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTggNiA2IDE4IiAvPgogIDxwYXRoIGQ9Im02IDYgMTIgMTIiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/x\n * @see https://lucide.dev/guide/packages/lucide-vue-next - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {FunctionalComponent} Vue component\n *\n */\nconst X = createLucideIcon('x', [\n  ['path', { d: 'M18 6 6 18', key: '1bl5f8' }],\n  ['path', { d: 'm6 6 12 12', key: 'd8bk6v' }],\n]);\n\nexport default X;\n","<script setup lang=\"ts\">\nimport { computed, nextTick, onMounted, onBeforeUnmount, shallowRef } from \"vue\";\nimport { Menu, SquarePen, X, AlertTriangle, Download } from \"lucide-vue-next\";\nimport { StreamMarkdown } from \"streamdown-vue\";\nimport { DialogRoot, DialogTrigger, DialogPortal, DialogOverlay, DialogContent, DialogTitle, DialogDescription, DialogClose } from \"reka-ui\";\nimport SidebarNavigation from \"./SidebarNavigation.vue\";\nimport ResizableDialog from \"./ResizableDialog.vue\";\n\nconst props = defineProps<{\n  active: boolean;\n  activeConversationTitle?: string;\n  systemPrompt: string;\n  apiOffline?: boolean;\n  chats: Array<{ id: string; title: string; updatedAt: number }>;\n  currentChatId: string;\n  busy: boolean;\n  hasMessages: boolean;\n}>();\nconst emit = defineEmits<{\n  (e: \"select-chat\", id: string): void;\n  (e: \"new-chat\"): void;\n  (e: \"start-test-mode\"): void;\n  (e: \"stop-test-mode\"): void;\n  (e: \"download\"): void;\n}>();\n\nconst menuOpen = shallowRef(false);\nconst promptOpen = shallowRef(false);\nconst mobileTitle = computed(() => props.active ? \"Testmodus\" : props.chats.find(chat => chat.id === props.currentChatId)?.title || \"BTW Coach\");\nconst navigationProps = computed(() => ({\n  active: props.active,\n  activeConversationTitle: props.activeConversationTitle,\n  chats: props.chats,\n  currentChatId: props.currentChatId,\n  busy: props.busy,\n}));\n\nfunction selectChat(id: string) {\n  if (props.busy) return;\n  menuOpen.value = false;\n  emit(\"select-chat\", id);\n}\n\nfunction navigate(action: \"new-chat\" | \"start-test-mode\" | \"stop-test-mode\") {\n  if (props.busy) return;\n  menuOpen.value = false;\n  if (action === \"new-chat\") emit(\"new-chat\");\n  else if (action === \"start-test-mode\") emit(\"start-test-mode\");\n  else emit(\"stop-test-mode\");\n}\n\nasync function showPrompt() {\n  menuOpen.value = false;\n  await nextTick();\n  promptOpen.value = true;\n}\n\nlet desktopQuery: MediaQueryList | undefined;\nfunction closeDesktopMenu() {\n  if (desktopQuery?.matches) menuOpen.value = false;\n}\nonMounted(() => {\n  desktopQuery = window.matchMedia(\"(min-width: 721px)\");\n  desktopQuery.addEventListener(\"change\", closeDesktopMenu);\n});\nonBeforeUnmount(() => desktopQuery?.removeEventListener(\"change\", closeDesktopMenu));\n</script>\n\n<template>\n  <aside class=\"sidebar\" aria-label=\"Navigatie\">\n    <div class=\"sidebar__header\">\n      <h1 class=\"sidebar__title\">BTW Coach</h1>\n      <p class=\"sidebar__subtitle\">Kennisassistent voor Brede Welvaart in Twente</p>\n    </div>\n    <SidebarNavigation\n      v-bind=\"navigationProps\"\n      @select-chat=\"selectChat\"\n      @new-chat=\"navigate('new-chat')\"\n      @start-test-mode=\"navigate('start-test-mode')\"\n      @stop-test-mode=\"navigate('stop-test-mode')\"\n      @show-prompt=\"showPrompt\"\n    />\n  </aside>\n\n  <DialogRoot v-model:open=\"menuOpen\">\n    <header class=\"mobile-header\">\n      <DialogTrigger class=\"sidebar__icon-button\" aria-label=\"Menu openen\">\n        <Menu :size=\"21\" aria-hidden=\"true\" />\n      </DialogTrigger>\n      <h1 class=\"mobile-header__title\" :title=\"mobileTitle\">{{ mobileTitle }}</h1>\n      <button v-if=\"hasMessages\" type=\"button\" class=\"sidebar__icon-button\" aria-label=\"Download gesprek\" @click=\"emit('download')\">\n        <Download :size=\"20\" aria-hidden=\"true\" />\n      </button>\n      <button type=\"button\" class=\"sidebar__icon-button\" aria-label=\"Nieuw gesprek\" :disabled=\"busy\" @click=\"navigate('new-chat')\">\n        <SquarePen :size=\"20\" aria-hidden=\"true\" />\n      </button>\n    </header>\n    <DialogPortal>\n      <DialogOverlay class=\"sidebar-drawer__overlay\" />\n      <DialogContent class=\"sidebar-drawer\">\n        <div class=\"sidebar-drawer__header\">\n          <DialogTitle class=\"sidebar__title\">BTW Coach</DialogTitle>\n          <DialogClose class=\"sidebar__icon-button\" aria-label=\"Menu sluiten\">\n            <X :size=\"21\" aria-hidden=\"true\" />\n          </DialogClose>\n        </div>\n        <DialogDescription class=\"sidebar-drawer__description\">Je gesprekken en instellingen</DialogDescription>\n        <SidebarNavigation\n          v-bind=\"navigationProps\"\n          @select-chat=\"selectChat\"\n          @new-chat=\"navigate('new-chat')\"\n          @start-test-mode=\"navigate('start-test-mode')\"\n          @stop-test-mode=\"navigate('stop-test-mode')\"\n          @show-prompt=\"showPrompt\"\n        />\n      </DialogContent>\n    </DialogPortal>\n  </DialogRoot>\n    <ResizableDialog\n      v-model:open=\"promptOpen\"\n      title=\"Systeemprompt\"\n      dialog-id=\"prompt-viewer\"\n      :default-width=\"800\"\n      :default-height=\"600\"\n    >\n      <StreamMarkdown v-if=\"systemPrompt\" class=\"sidebar__prompt\" :content=\"systemPrompt\" />\n      <div v-else class=\"sidebar__prompt-empty\">\n        <template v-if=\"apiOffline\">\n          <AlertTriangle :size=\"16\" class=\"sidebar__prompt-empty-icon\" />\n          <p>\n            De chat-API draait niet op <code>localhost:4104</code>. Start 'm met\n            <code>./start</code> — dan verschijnt de prompt hier.\n          </p>\n        </template>\n        <p v-else>(prompt nog niet geladen)</p>\n      </div>\n    </ResizableDialog>\n</template>\n\n<style scoped>\n\n.sidebar { display: flex; flex-direction: column; width: 256px; min-height: 0; flex-shrink: 0; border-right: 1px solid var(--btw-line); background: var(--btw-surface); }\n.sidebar__header { padding: 18px 16px; }\n.sidebar__title { margin: 0; font-size: 16px; font-weight: 600; letter-spacing: -0.01em; color: var(--btw-fg); }\n.sidebar__subtitle { margin: 4px 0 0; font-size: 12px; color: var(--btw-fg-muted); line-height: 1.45; }\n.mobile-header { display: none; }\n.sidebar__icon-button { display: grid; place-items: center; width: 44px; height: 44px; flex-shrink: 0; padding: 0; border: 0; border-radius: 10px; background: transparent; color: var(--btw-fg-muted); cursor: pointer; }\n.sidebar__icon-button:hover { background: var(--btw-surface-2); color: var(--btw-fg); }\n.sidebar__icon-button:focus-visible { outline: 2px solid var(--btw-accent); outline-offset: -2px; }\n.sidebar__icon-button:active { transform: translateY(1px); }\n.sidebar__icon-button:disabled { opacity: 0.5; cursor: not-allowed; }\n.sidebar-drawer__overlay { position: fixed; inset: 0; z-index: 80; background: rgba(0, 0, 0, 0.45); }\n.sidebar-drawer { position: fixed; top: 0; bottom: 0; left: 0; z-index: 81; display: flex; flex-direction: column; width: min(320px, calc(100vw - 48px)); height: 100dvh; padding-top: env(safe-area-inset-top); box-sizing: border-box; background: var(--btw-surface); color: var(--btw-fg); border-right: 1px solid var(--btw-line); }\n.sidebar-drawer__header { display: flex; align-items: center; justify-content: space-between; min-height: 56px; padding: 0 12px 0 18px; flex-shrink: 0; }\n.sidebar-drawer__description { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }\n/* Mobile: collapse the sidebar to a top bar. */\n@media (max-width: 720px) {\n  .sidebar { display: none; }\n  .mobile-header { display: flex; align-items: center; gap: 6px; min-width: 0; height: 56px; box-sizing: content-box; flex-shrink: 0; padding: env(safe-area-inset-top) 8px 0; border-bottom: 1px solid var(--btw-line); background: var(--btw-surface); }\n  .mobile-header__title { flex: 1; min-width: 0; margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 14px; font-weight: 600; text-align: center; color: var(--btw-fg); }\n}\n.sidebar__prompt {\n  font-size: 13.5px;\n  line-height: 1.6;\n  color: var(--btw-fg-muted);\n}\n.sidebar__prompt-empty {\n  display: flex;\n  align-items: flex-start;\n  gap: 8px;\n  font-size: 13.5px;\n  line-height: 1.6;\n  color: var(--btw-fg-muted);\n}\n.sidebar__prompt-empty p { margin: 0; }\n.sidebar__prompt-empty-icon { flex-shrink: 0; margin-top: 2px; color: var(--btw-warning, #b45309); }\n.sidebar__prompt-empty code {\n  font-family: var(--font-mono);\n  font-size: 0.85em;\n  background: var(--btw-surface-2);\n  padding: 1px 5px;\n  border-radius: 5px;\n}\n.sidebar__prompt :deep(h1) { font-size: 1.4em; font-weight: 700; margin: 14px 0 6px; color: var(--btw-fg); }\n.sidebar__prompt :deep(h2) { font-size: 1.2em; font-weight: 700; margin: 14px 0 6px; color: var(--btw-fg); }\n.sidebar__prompt :deep(h3) { font-size: 1.05em; font-weight: 600; margin: 12px 0 4px; color: var(--btw-fg); }\n.sidebar__prompt :deep(ul) { padding-left: 20px; margin: 0 0 10px; }\n.sidebar__prompt :deep(code) { font-family: var(--font-mono); font-size: 0.85em; background: var(--btw-surface-2); padding: 1px 5px; border-radius: 5px; }\n\n</style>\n","import { h as m, defineComponent as _, ref as P, inject as K, provide as me, onMounted as le, watch as ge, nextTick as pe, onBeforeUnmount as ke } from \"vue\";\nimport { unified as ye } from \"unified\";\nimport be from \"remark-parse\";\nimport we from \"remark-gfm\";\nimport ee from \"remark-math\";\nimport ve from \"remark-rehype\";\nimport $e from \"rehype-katex\";\nimport { createHighlighterCore as Ce } from \"shiki/core\";\nimport { createJavaScriptRegexEngine as Se } from \"shiki/engine/javascript\";\nimport Be from \"@shikijs/themes/github-light\";\nimport Le from \"@shikijs/themes/github-dark\";\nimport { marked as Ae } from \"marked\";\nconst Ie = \"3.12.1\", Me = `https://esm.sh/@shikijs/langs@${Ie}/es2022/`, ce = Symbol.for(\"streamdown.vue.shikiRemote\"), je = (e) => (typeof e == \"function\" && (e[ce] = !0), e), Ne = (e) => typeof e == \"function\" && !!e?.[ce], M = (e) => {\n  const t = () => import(\n    /* @vite-ignore */\n    `@shikijs/langs/${e}`\n  ), n = () => import(\n    /* webpackIgnore: true */\n    /* @vite-ignore */\n    `${Me}${e}.mjs`\n  );\n  return je(async () => {\n    if (typeof window > \"u\")\n      return t();\n    try {\n      return await n();\n    } catch {\n      return t();\n    }\n  });\n}, Pe = {\n  py: \"python\",\n  python3: \"python\",\n  shellscript: \"shell\",\n  shellsession: \"shell\",\n  sh: \"shell\",\n  zsh: \"shell\",\n  bash: \"bash\",\n  \"markdown-vue\": \"vue\",\n  \"vue-directives\": \"vue\",\n  \"vue-interpolations\": \"vue\",\n  \"vue-sfc-style-variable-injection\": \"vue\",\n  md: \"markdown\",\n  \"html-derivative\": \"html\",\n  ts: \"typescript\",\n  js: \"javascript\",\n  yml: \"yaml\"\n}, Ee = (e) => e.trim().toLowerCase().replace(/^language-/, \"\"), O = (e) => {\n  const t = Ee(e);\n  return t && (Pe[t] ?? t);\n}, j = /* @__PURE__ */ new Map(), E = /* @__PURE__ */ new Map(), te = (e, t) => {\n  const n = O(e);\n  n && E.set(n, t);\n}, de = (e) => {\n  const t = O(e);\n  if (!t) return;\n  if (j.has(t)) return t;\n  const n = E.get(t);\n  if (n && j.has(n)) return n;\n}, De = (e) => {\n  for (const [t, n] of Array.from(E.entries()))\n    (n === e || t === e) && E.delete(t);\n};\nfunction Te(e) {\n  const t = O(e.id);\n  t && (j.set(t, e.loader), te(t, t), (e.aliases ?? []).forEach((n) => te(n, t)));\n}\nfunction _e(e) {\n  e.forEach(Te);\n}\nfunction Oe(e) {\n  const t = de(e);\n  if (!t) {\n    const n = O(e);\n    n && E.delete(n);\n    return;\n  }\n  j.delete(t), De(t);\n}\nfunction Kt(e) {\n  e.forEach(Oe);\n}\nfunction ue(e) {\n  const t = /* @__PURE__ */ new Set(), n = [], r = [], a = [];\n  return e.forEach((c) => {\n    const l = de(c);\n    if (!l) {\n      r.push(O(c) || c);\n      return;\n    }\n    if (t.has(l)) return;\n    const g = j.get(l);\n    if (!g) {\n      r.push(l);\n      return;\n    }\n    t.add(l), a.push(l), n.push(g);\n  }), { inputs: n, missing: r, resolved: a };\n}\nfunction xe() {\n  return Array.from(j.keys()).sort();\n}\nfunction He() {\n  return j.size > 0;\n}\nfunction Zt() {\n  j.clear(), E.clear();\n}\nconst Re = [\n  {\n    id: \"cpp\",\n    aliases: [\"c++\"],\n    loader: M(\"cpp\")\n  },\n  {\n    id: \"java\",\n    aliases: [\"java\"],\n    loader: M(\"java\")\n  },\n  {\n    id: \"c\",\n    loader: M(\"c\")\n  },\n  {\n    id: \"csharp\",\n    aliases: [\"cs\", \"c#\"],\n    loader: M(\"csharp\")\n  },\n  {\n    id: \"php\",\n    loader: M(\"php\")\n  },\n  {\n    id: \"ruby\",\n    loader: M(\"ruby\")\n  },\n  {\n    id: \"kotlin\",\n    loader: M(\"kotlin\")\n  },\n  {\n    id: \"swift\",\n    loader: M(\"swift\")\n  },\n  {\n    id: \"sql\",\n    loader: M(\"sql\")\n  },\n  {\n    id: \"typescript\",\n    aliases: [\"ts\"],\n    loader: () => import(\"@shikijs/langs/typescript\")\n  },\n  {\n    id: \"tsx\",\n    loader: () => import(\"@shikijs/langs/tsx\")\n  },\n  {\n    id: \"javascript\",\n    aliases: [\"js\"],\n    loader: () => import(\"@shikijs/langs/javascript\")\n  },\n  {\n    id: \"jsx\",\n    loader: () => import(\"@shikijs/langs/jsx\")\n  },\n  {\n    id: \"json\",\n    loader: () => import(\"@shikijs/langs/json\")\n  },\n  {\n    id: \"bash\",\n    loader: () => import(\"@shikijs/langs/bash\")\n  },\n  {\n    id: \"shell\",\n    aliases: [\"shellscript\", \"shellsession\", \"sh\", \"zsh\"],\n    loader: () => import(\"@shikijs/langs/shellscript\")\n  },\n  {\n    id: \"python\",\n    aliases: [\"py\"],\n    loader: () => import(\"@shikijs/langs/python\")\n  },\n  {\n    id: \"diff\",\n    loader: () => import(\"@shikijs/langs/diff\")\n  },\n  {\n    id: \"markdown\",\n    aliases: [\"md\"],\n    loader: () => import(\"@shikijs/langs/markdown\")\n  },\n  {\n    id: \"vue\",\n    loader: () => import(\"@shikijs/langs/vue\")\n  },\n  {\n    id: \"html\",\n    loader: () => import(\"@shikijs/langs/html\")\n  },\n  {\n    id: \"css\",\n    loader: () => import(\"@shikijs/langs/css\")\n  },\n  {\n    id: \"go\",\n    loader: () => import(\"@shikijs/langs/go\")\n  },\n  {\n    id: \"rust\",\n    loader: () => import(\"@shikijs/langs/rust\")\n  },\n  {\n    id: \"yaml\",\n    aliases: [\"yml\"],\n    loader: () => import(\"@shikijs/langs/yaml\")\n  }\n];\nlet ne = !1;\nfunction Jt() {\n  ne || (ne = !0, _e(Re.slice()));\n}\nconst re = (e) => e.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").toLowerCase(), Ue = (e) => e.replace(\n  /^([A-Z])|[\\s-_]+(\\w)/g,\n  (t, n, r) => r ? r.toUpperCase() : n.toLowerCase()\n), ze = (e) => {\n  const t = Ue(e);\n  return t.charAt(0).toUpperCase() + t.slice(1);\n}, We = (...e) => e.filter((t, n, r) => !!t && t.trim() !== \"\" && r.indexOf(t) === n).join(\" \").trim(), ae = (e) => e === \"\";\nvar T = {\n  xmlns: \"http://www.w3.org/2000/svg\",\n  width: 24,\n  height: 24,\n  viewBox: \"0 0 24 24\",\n  fill: \"none\",\n  stroke: \"currentColor\",\n  \"stroke-width\": 2,\n  \"stroke-linecap\": \"round\",\n  \"stroke-linejoin\": \"round\"\n};\nconst qe = ({\n  name: e,\n  iconNode: t,\n  absoluteStrokeWidth: n,\n  \"absolute-stroke-width\": r,\n  strokeWidth: a,\n  \"stroke-width\": c,\n  size: l = T.width,\n  color: g = T.stroke,\n  ...o\n}, { slots: p }) => m(\n  \"svg\",\n  {\n    ...T,\n    ...o,\n    width: l,\n    height: l,\n    stroke: g,\n    \"stroke-width\": ae(n) || ae(r) || n === !0 || r === !0 ? Number(a || c || T[\"stroke-width\"]) * 24 / Number(l) : a || c || T[\"stroke-width\"],\n    class: We(\n      \"lucide\",\n      o.class,\n      ...e ? [`lucide-${re(ze(e))}-icon`, `lucide-${re(e)}`] : [\"lucide-icon\"]\n    )\n  },\n  [...t.map((L) => m(...L)), ...p.default ? [p.default()] : []]\n);\nconst Z = (e, t) => (n, { slots: r, attrs: a }) => m(\n  qe,\n  {\n    ...a,\n    ...n,\n    iconNode: t,\n    name: e\n  },\n  r\n);\nconst Fe = Z(\"check\", [[\"path\", { d: \"M20 6 9 17l-5-5\", key: \"1gmf2c\" }]]);\nconst Ge = Z(\"copy\", [\n  [\"rect\", { width: \"14\", height: \"14\", x: \"8\", y: \"8\", rx: \"2\", ry: \"2\", key: \"17jyea\" }],\n  [\"path\", { d: \"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\", key: \"zix9uf\" }]\n]);\nconst Ve = Z(\"download\", [\n  [\"path\", { d: \"M12 15V3\", key: \"m9g1x1\" }],\n  [\"path\", { d: \"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\", key: \"ih7n3h\" }],\n  [\"path\", { d: \"m7 10 5 5 5-5\", key: \"brsn70\" }]\n]), J = Symbol(\"code-block-meta\"), Ke = Symbol(\"global-code-block-actions\"), he = _({\n  name: \"CopyButton\",\n  props: {\n    // text is optional now; will default to injected code.\n    text: { type: String, required: !1 },\n    floating: { type: Boolean, default: !0 }\n  },\n  setup(e) {\n    const t = P(!1), n = K(J, { code: \"\", language: \"\" }), r = async () => {\n      try {\n        const a = e.text ?? n.code;\n        if (!a) return;\n        await navigator.clipboard?.writeText(a), t.value = !0, setTimeout(() => {\n          t.value = !1;\n        }, 2e3);\n      } catch {\n      }\n    };\n    return () => m(\n      \"button\",\n      {\n        class: [\n          e.floating ? \"absolute top-2 right-2 opacity-0 group-hover:opacity-100\" : \"opacity-80 hover:opacity-100\",\n          \"p-1 rounded bg-gray-200 dark:bg-gray-700 transition-opacity flex items-center justify-center\"\n        ].join(\" \"),\n        onClick: r,\n        \"aria-live\": \"polite\"\n      },\n      [\n        t.value ? m(Fe, { class: \"h-4 w-4\" }) : m(Ge, { class: \"h-4 w-4\" }),\n        m(\n          \"span\",\n          { class: \"sr-only\" },\n          t.value ? \"Copied\" : \"Copy\"\n        )\n      ]\n    );\n  }\n}), Ze = {\n  javascript: \"js\",\n  js: \"js\",\n  typescript: \"ts\",\n  ts: \"ts\",\n  json: \"json\",\n  vue: \"vue\",\n  html: \"html\",\n  css: \"css\",\n  md: \"md\",\n  markdown: \"md\",\n  sh: \"sh\",\n  bash: \"sh\",\n  py: \"py\",\n  python: \"py\",\n  go: \"go\",\n  rust: \"rs\",\n  rs: \"rs\"\n}, Je = _({\n  name: \"DownloadButton\",\n  props: {\n    text: { type: String, required: !1 },\n    // optional override\n    filename: { type: String, required: !1 },\n    floating: { type: Boolean, default: !0 }\n  },\n  setup(e) {\n    const t = K(J, { code: \"\", language: \"\" }), n = () => {\n      const r = e.text ?? t.code;\n      if (!r) return;\n      const a = t.language && Ze[t.language.toLowerCase()] || \"txt\", c = e.filename || `file.${a}`;\n      try {\n        const l = new Blob([r], { type: \"text/plain\" }), g = URL.createObjectURL(l), o = document.createElement(\"a\");\n        o.href = g, o.download = c, document.body.appendChild(o), o.click(), document.body.removeChild(o), URL.revokeObjectURL(g);\n      } catch {\n      }\n    };\n    return () => m(\n      \"button\",\n      {\n        class: [\n          e.floating ? \"absolute top-2 right-9 opacity-0 group-hover:opacity-100\" : \"opacity-80 hover:opacity-100\",\n          \"p-1 rounded bg-gray-200 dark:bg-gray-700 transition-opacity flex items-center justify-center\"\n        ].join(\" \"),\n        onClick: n,\n        \"aria-live\": \"polite\",\n        title: \"Download code\"\n      },\n      [\n        m(Ve, { class: \"h-4 w-4\" }),\n        m(\"span\", { class: \"sr-only\" }, \"Download\")\n      ]\n    );\n  }\n});\nlet V = null, q = null;\nconst Xe = [Be, Le];\nlet F = null;\nconst Ye = () => (F || (F = Se()), F), Qe = () => {\n  if (!He())\n    return console.warn(\n      \"[streamdown-vue] No Shiki languages are registered. Code blocks will render without syntax highlighting.\"\n    ), [];\n  const e = xe(), { inputs: t, missing: n } = ue(e);\n  return n.length && console.warn(\n    `[streamdown-vue] Some requested Shiki languages are not registered: ${n.join(\n      \", \"\n    )}`\n  ), t.filter((r) => !Ne(r));\n};\nasync function et(e) {\n  if (!V) return !1;\n  const { inputs: t } = ue([e]);\n  return t.length ? (await V.loadLanguage(...t), !0) : !1;\n}\nasync function tt() {\n  if (!q) {\n    const e = Qe();\n    q = Ce({\n      themes: Xe,\n      langs: e,\n      engine: Ye()\n    }).then((t) => (V = t, t));\n  }\n  return await q;\n}\nconst se = _({\n  name: \"CodeBlock\",\n  props: {\n    code: { type: String, required: !0 },\n    language: { type: String, default: \"\" },\n    theme: {\n      type: [String, Object],\n      default: void 0\n    },\n    showLineNumbers: { type: Boolean, default: !1 },\n    selectable: { type: Boolean, default: !0 },\n    // Array of extra action components (or render functions) appended to header right side.\n    actions: { type: Array, default: () => [] },\n    // Hide built-in copy or download buttons if user wants total control.\n    hideCopy: { type: Boolean, default: !1 },\n    hideDownload: { type: Boolean, default: !1 }\n  },\n  setup(e, { attrs: t, slots: n }) {\n    const r = P(\"\");\n    me(J, {\n      get code() {\n        return e.code;\n      },\n      get language() {\n        return e.language;\n      }\n    });\n    const a = K(Ke, []);\n    let c = null, l = async () => {\n    }, g = 0;\n    if (typeof window > \"u\") {\n      const s = (v) => v.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\"), u = e.language ? `language-${e.language}` : \"\", h = [u];\n      e.selectable || h.push(\"select-none\");\n      let d;\n      e.showLineNumbers ? d = e.code.split(/\\r?\\n/).map(\n        (N, A) => `<span class=\"line\"><span class=\"code-line-number select-none opacity-60 pr-4 text-xs\" data-line-number data-streamdown=\"code-line-number\">${A + 1}</span>${s(N)}</span>`\n      ).join(`\n`) : d = s(e.code);\n      const w = h.filter(Boolean).length ? ` class=\"${h.join(\" \")}\"` : \"\", y = u ? ` class=\"${u}\"` : \"\";\n      r.value = `<pre data-streamdown=\"pre\"${w}><code data-streamdown=\"code\"${y}>${d}</code></pre>`;\n    }\n    const o = (s) => s.replace(\n      /(<pre[^>]*style=\")([^\"]*)(\"[^>]*>)/g,\n      (u, h, d, w) => {\n        const y = d.split(/;\\s*/).filter(\n          (v) => v && !/background(-color)?\\s*:/.test(\n            v.toLowerCase()\n          )\n        ).join(\"; \");\n        return `${h}${y}${w}`.replace(/style=\"\"/, \"\");\n      }\n    ), p = (s) => {\n      if (!e.showLineNumbers) return s;\n      let u = 0;\n      return s.replace(/<span class=\"line(.*?)\">/g, (h, d) => (u += 1, `<span class=\"line${d}\"><span class=\"code-line-number select-none opacity-60 pr-4 text-xs\" data-line-number data-streamdown=\"code-line-number\">${u}</span>`));\n    }, L = (s) => e.selectable ? s : s.replace(\"<pre\", '<pre class=\"select-none\"'), i = (s) => {\n      const u = L(\n        p(o(s))\n      );\n      return k(u);\n    }, k = (s) => s.replace(\n      /<pre(?![^>]*data-streamdown=)/g,\n      '<pre data-streamdown=\"pre\"'\n    ).replace(\n      /<code(?![^>]*data-streamdown=)/g,\n      '<code data-streamdown=\"code\"'\n    ), f = () => {\n      if (typeof document < \"u\") {\n        const s = \"streamdown-dual-theme-styles\";\n        if (!document.getElementById(s)) {\n          const u = document.createElement(\"style\");\n          u.id = s, u.textContent = `\n                        html.dark .shiki-themes, html.dark .shiki-themes span {\n                            color: var(--shiki-dark) !important;\n                            font-style: var(--shiki-dark-font-style) !important;\n                            font-weight: var(--shiki-dark-font-weight) !important;\n                            text-decoration: var(--shiki-dark-text-decoration) !important;\n                        }\n                        @media (prefers-color-scheme: dark) {\n                            html:not(.light) .shiki-themes,\n                            html:not(.light) .shiki-themes span {\n                                color: var(--shiki-dark) !important;\n                                font-style: var(--shiki-dark-font-style) !important;\n                                font-weight: var(--shiki-dark-font-weight) !important;\n                                text-decoration: var(--shiki-dark-text-decoration) !important;\n                            }\n                        }\n                    `, document.head.appendChild(u);\n        }\n      }\n    }, C = (s, u, h, d) => {\n      if (typeof h == \"object\" && h !== null)\n        return d.codeToHtml(s, {\n          lang: u,\n          themes: { light: h.light, dark: h.dark }\n        });\n      const y = h || (c?.matches ? \"github-dark\" : \"github-light\");\n      return d.codeToHtml(s, {\n        lang: u,\n        theme: y\n      });\n    }, B = async () => {\n      const s = ++g;\n      try {\n        const u = await tt(), h = e.language || \"txt\";\n        let d = \"\";\n        try {\n          d = C(\n            e.code,\n            h,\n            e.theme,\n            u\n          );\n        } catch (w) {\n          if (h && !u.getLoadedLanguages().includes(h)) {\n            if (!await et(h)) throw new Error(\"missing lang\");\n            d = C(\n              e.code,\n              h,\n              e.theme,\n              u\n            );\n          } else\n            throw w;\n        }\n        s === g && (r.value = i(d));\n      } catch {\n        s === g && (r.value = i(\n          `<pre><code>${e.code}</code></pre>`\n        ));\n      }\n    };\n    return le(() => {\n      const s = typeof e.theme == \"object\" && e.theme !== null;\n      s && f(), l = B, l(), s || (c = window.matchMedia(\"(prefers-color-scheme: dark)\"), c.addEventListener(\"change\", l));\n    }), ge(\n      () => [e.code, e.language, e.theme],\n      () => {\n        pe(() => l());\n      }\n    ), ke(() => {\n      c && c.removeEventListener(\"change\", l);\n    }), () => m(\n      \"div\",\n      {\n        class: \"group rounded-md border bg-gray-50 dark:bg-gray-800 overflow-hidden\",\n        \"data-streamdown\": \"code-block\",\n        ...t\n      },\n      [\n        // Header bar (language + copy) always visible; stable height avoids layout shift\n        m(\n          \"div\",\n          {\n            class: \"flex items-center justify-between text-xs px-2 py-1 border-b border-gray-200 dark:border-gray-700 bg-gray-100 dark:bg-gray-900 gap-2\",\n            \"data-streamdown\": \"code-block-header\"\n          },\n          [\n            e.language ? m(\n              \"span\",\n              {\n                class: \"px-1 py-0.5 rounded bg-gray-200 dark:bg-gray-700 font-mono text-[10px] leading-none tracking-wide\",\n                \"data-streamdown\": \"code-lang\"\n              },\n              e.language\n            ) : m(\"span\", {\n              class: \"h-4\",\n              \"data-streamdown\": \"code-lang-empty\"\n            }),\n            m(\n              \"div\",\n              {\n                class: \"flex items-center gap-1\",\n                \"data-streamdown\": \"code-actions\"\n              },\n              [\n                // user supplied actions (prop)\n                ...e.actions.map(\n                  (s, u) => m(s, {\n                    key: u,\n                    code: e.code,\n                    language: e.language\n                  })\n                ),\n                // global injected actions\n                ...a.map(\n                  (s, u) => m(s, {\n                    key: `g-${u}`,\n                    code: e.code,\n                    language: e.language\n                  })\n                ),\n                // slot based actions (<template #actions>)\n                ...n.actions ? n.actions() : [],\n                e.hideDownload ? null : m(Je, {\n                  floating: !1,\n                  \"data-streamdown\": \"download-button\"\n                }),\n                e.hideCopy ? null : m(he, {\n                  floating: !1,\n                  \"data-streamdown\": \"copy-button\"\n                })\n              ].filter(Boolean)\n            )\n          ]\n        ),\n        // Code body\n        m(\"div\", {\n          innerHTML: r.value,\n          class: \"px-4 py-3 overflow-x-auto\",\n          \"data-streamdown\": \"code-body\"\n        })\n      ]\n    );\n  }\n});\nlet oe = !1;\nconst G = {}, nt = (e) => {\n  let t = 0;\n  for (let n = 0; n < e.length; n++)\n    t = (t << 5) - t + e.charCodeAt(n), t |= 0;\n  return Math.abs(t).toString(36);\n}, rt = _({\n  name: \"MermaidBlock\",\n  props: {\n    code: { type: String, required: !0 }\n  },\n  setup(e) {\n    const t = P(\"\"), n = P(\"\"), r = P(\"\"), a = P(!0), c = `streamdown-vue-mermaid-${nt(e.code)}`;\n    return le(async () => {\n      a.value = !0;\n      try {\n        const g = (await import(\"mermaid\")).default;\n        if (oe || (g.initialize({ startOnLoad: !1 }), oe = !0), G[c]) {\n          t.value = G[c], a.value = !1;\n          return;\n        }\n        const { svg: o } = await g.render(c, e.code);\n        t.value = o, n.value = o, G[c] = o, r.value = \"\";\n      } catch (g) {\n        r.value = g.message || \"Failed to render mermaid diagram\", t.value = n.value;\n      } finally {\n        a.value = !1;\n      }\n    }), () => m(\n      \"div\",\n      { class: \"relative group\", \"data-streamdown\": \"mermaid\" },\n      [\n        a.value ? m(\"div\", { class: \"flex justify-center py-8\" }, [\n          m(\"div\", {\n            class: \"h-5 w-5 border-2 border-gray-300 border-t-transparent rounded-full animate-spin\"\n          })\n        ]) : t.value ? m(\"div\", { innerHTML: t.value }) : m(\n          \"div\",\n          { class: \"text-red-500 text-sm\" },\n          r.value\n        ),\n        !a.value && r.value && t.value ? m(\n          \"div\",\n          { class: \"text-red-500 text-sm mt-2\" },\n          r.value\n        ) : null,\n        m(he, {\n          text: e.code,\n          \"data-streamdown\": \"copy-button\"\n        })\n      ]\n    );\n  }\n}), R = (e, t) => {\n  const n = [];\n  return Array.isArray(e) ? n.push(...e) : typeof e == \"string\" && n.push(e), t && n.push(t), n.join(\" \").trim();\n}, $ = (e, t = \"\", n) => (r, { slots: a }) => {\n  const c = R(r.class || r.className, t), l = { ...r, class: c || void 0 };\n  return n && (l[\"data-streamdown\"] = n), delete l.className, m(e, l, a.default ? a.default() : []);\n}, at = {\n  p: $(\"p\", \"mb-2\", \"p\"),\n  a: (e, { slots: t }) => {\n    const n = R(e.class || e.className, \"underline text-blue-600\"), r = { ...e, class: n || void 0, \"data-streamdown\": \"a\", target: \"_blank\", rel: \"noreferrer\" };\n    return delete r.className, m(\"a\", r, t.default ? t.default() : []);\n  },\n  code: $(\"code\", \"bg-muted px-1.5 py-0.5 font-mono text-sm\", \"inline-code\"),\n  ul: $(\"ul\", \"list-disc pl-6\", \"ul\"),\n  ol: $(\"ol\", \"list-decimal pl-6\", \"ol\"),\n  li: $(\"li\", \"\", \"li\"),\n  hr: $(\"hr\", \"my-6 border-border\", \"hr\"),\n  strong: $(\"strong\", \"\", \"strong\"),\n  em: $(\"em\", \"\", \"em\"),\n  h1: $(\"h1\", \"text-3xl font-bold\", \"h1\"),\n  h2: $(\"h2\", \"text-2xl font-bold\", \"h2\"),\n  h3: $(\"h3\", \"text-xl font-semibold\", \"h3\"),\n  h4: $(\"h4\", \"text-lg font-semibold\", \"h4\"),\n  h5: $(\"h5\", \"font-semibold\", \"h5\"),\n  h6: $(\"h6\", \"font-semibold\", \"h6\"),\n  blockquote: $(\"blockquote\", \"border-l-4 pl-4 italic\", \"blockquote\"),\n  table: (e, { slots: t }) => {\n    const n = R(e.class || e.className, \"w-full text-sm\"), r = { ...e, class: n || void 0, \"data-streamdown\": \"table\" };\n    delete r.className;\n    const a = m(\"table\", r, t.default ? t.default() : []);\n    return m(\"div\", { class: \"overflow-x-auto\", \"data-streamdown\": \"table-wrapper\" }, [a]);\n  },\n  thead: $(\"thead\", \"\", \"thead\"),\n  tbody: $(\"tbody\", \"\", \"tbody\"),\n  tr: $(\"tr\", \"\", \"tr\"),\n  th: $(\"th\", \"border px-2 py-1\", \"th\"),\n  td: $(\"td\", \"border px-2 py-1\", \"td\"),\n  img: (e) => {\n    const t = R(e.class || e.className, \"\"), n = { ...e, class: t || void 0, \"data-streamdown\": \"img\" };\n    return delete n.className, m(\"img\", n);\n  }\n}, st = (e) => {\n  const n = Ae.use({ gfm: !0 }).lexer(e).map((a) => a.raw), r = [];\n  for (let a = 0; a < n.length; a++) {\n    const c = n[a];\n    if (typeof c == \"string\") {\n      if (c.trim() === \"$$\" && r.length > 0) {\n        const l = r[r.length - 1];\n        if (l === void 0) {\n          r.push(c);\n          continue;\n        }\n        const g = l.trimStart().startsWith(\"$$\"), o = (l.match(/\\$\\$/g) || []).length;\n        if (g && o % 2 === 1) {\n          r[r.length - 1] = l + c;\n          continue;\n        }\n      }\n      if (r.length > 0 && c.trimEnd().endsWith(\"$$\")) {\n        const l = r[r.length - 1];\n        if (l === void 0) {\n          r.push(c);\n          continue;\n        }\n        const g = l.trimStart().startsWith(\"$$\"), o = (l.match(/\\$\\$/g) || []).length, p = (c.match(/\\$\\$/g) || []).length;\n        if (g && o % 2 === 1 && !c.trimStart().startsWith(\"$$\") && p === 1) {\n          r[r.length - 1] = l + c;\n          continue;\n        }\n      }\n      r.push(c);\n    }\n  }\n  return r;\n}, ot = /(!?\\[)([^\\]]*?)$/, it = /(\\*\\*)([^*]*?)$/, lt = /(__)([^_]*?)$/, ct = /(\\*\\*\\*)([^*]*?)$/, dt = /(\\*)([^*]*?)$/, ut = /(_)([^_]*?)$/, ht = /(`)([^`]*?)$/, ft = /(~~)([^~]*?)$/, U = (e) => {\n  const t = (e.match(/```/g) || []).length;\n  return t > 0 && t % 2 === 0 && e.includes(`\n`);\n}, mt = (e) => {\n  const t = e.match(ot);\n  if (t) {\n    const n = t[1];\n    if (n) {\n      const r = e.lastIndexOf(n);\n      if (r >= 0)\n        return e.substring(0, r);\n    }\n  }\n  return e;\n}, gt = (e) => U(e) ? e : e.match(it) && (e.match(/\\*\\*/g) || []).length % 2 === 1 ? `${e}**` : e, pt = (e) => e.match(lt) && (e.match(/__/g) || []).length % 2 === 1 ? `${e}__` : e, kt = (e) => e.split(\"\").reduce((t, n, r) => {\n  if (n === \"*\") {\n    const a = e[r - 1], c = e[r + 1];\n    if (a === \"\\\\\")\n      return t;\n    let l = r;\n    for (let o = r - 1; o >= 0; o--) {\n      if (e[o] === `\n`) {\n        l = o + 1;\n        break;\n      }\n      if (o === 0) {\n        l = 0;\n        break;\n      }\n    }\n    if (e.substring(l, r).trim() === \"\" && (c === \" \" || c === \"\t\"))\n      return t;\n    if (a !== \"*\" && c !== \"*\")\n      return t + 1;\n  }\n  return t;\n}, 0), yt = (e) => U(e) ? e : e.match(dt) && kt(e) % 2 === 1 ? `${e}*` : e, bt = (e, t) => {\n  let n = !1, r = !1;\n  for (let a = 0; a < e.length && a < t; a++) {\n    if (e[a] === \"\\\\\" && e[a + 1] === \"$\") {\n      a++;\n      continue;\n    }\n    e[a] === \"$\" && (e[a + 1] === \"$\" ? (r = !r, a++, n = !1) : r || (n = !n));\n  }\n  return n || r;\n}, wt = (e) => e.split(\"\").reduce((t, n, r) => {\n  if (n === \"_\") {\n    const a = e[r - 1], c = e[r + 1];\n    if (a === \"\\\\\" || bt(e, r))\n      return t;\n    if (a !== \"_\" && c !== \"_\")\n      return t + 1;\n  }\n  return t;\n}, 0), vt = (e) => U(e) ? e : e.match(ut) && wt(e) % 2 === 1 ? `${e}_` : e, $t = (e, t) => {\n  const n = e.substring(t, t + 3) === \"```\", r = t > 0 && e.substring(t - 1, t + 2) === \"```\", a = t > 1 && e.substring(t - 2, t + 1) === \"```\";\n  return n || r || a;\n}, Ct = (e) => {\n  let t = 0;\n  for (let n = 0; n < e.length; n++)\n    e[n] === \"`\" && !$t(e, n) && t++;\n  return t;\n}, St = (e) => {\n  if (e.match(/^```[^`\\n]*```?$/) && !e.includes(`\n`))\n    return e.endsWith(\"``\") && !e.endsWith(\"```\") ? `${e}\\`` : e;\n  const n = (e.match(/```/g) || []).length, r = n % 2 === 1;\n  return n > 0 && n % 2 === 0 && e.includes(`\n`) || (e.endsWith(\"```\\n\") || e.endsWith(\"```\")) && n % 2 === 0 ? e : e.match(ht) && !r && Ct(e) % 2 === 1 ? `${e}\\`` : e;\n}, Bt = (e) => e.match(ft) && (e.match(/~~/g) || []).length % 2 === 1 ? `${e}~~` : e, Lt = (e) => {\n  if ((e.match(/\\$\\$/g) || []).length % 2 === 0)\n    return e;\n  const n = (e.match(/\\\\begin\\{[^}]+\\}/g) || []).length, r = (e.match(/\\\\end\\{[^}]+\\}/g) || []).length;\n  if (n !== r) return e;\n  const a = e.indexOf(\"$$\");\n  return a !== -1 && e.indexOf(`\n`, a) !== -1 && !e.endsWith(`\n`) ? `${e}\n$$` : `${e}$$`;\n}, At = (e) => {\n  let t = 0;\n  const n = e.match(/\\*+/g) || [];\n  for (const r of n) {\n    const a = r.length;\n    a >= 3 && (t += Math.floor(a / 3));\n  }\n  return t;\n}, It = (e) => U(e) || /^\\*{4,}$/.test(e) ? e : e.match(ct) && At(e) % 2 === 1 ? `${e}***` : e, ie = (e) => {\n  if (!e || typeof e != \"string\")\n    return e;\n  let t = e;\n  return t.length, (t.match(/\\$\\$/g) || []).length, t = mt(t), t = It(t), t = gt(t), t = pt(t), t = yt(t), t = vt(t), t = St(t), t = Bt(t), t = Lt(t), t;\n}, Mt = /(\\\\begin\\{(?:b|p|B|v|V)?matrix\\})([\\s\\S]*?)(\\\\end\\{(?:b|p|B|v|V)?matrix\\})/g;\nfunction jt(e) {\n  return e.replace(\n    Mt,\n    (t, n, r, a, c) => {\n      let l = r.split(/\\n+/g).map((o) => o.trim()).filter((o) => o.length > 0 && o !== \"\\\\\");\n      if (l.some((o) => /\\\\\\\\/.test(o))) {\n        const o = [];\n        for (const p of l)\n          if (/\\\\\\\\/.test(p)) {\n            const L = p.split(/\\\\\\\\\\s*/).map((i) => i.trim()).filter((i) => i.length > 0 && i !== \"\\\\\");\n            for (const i of L) o.push(i);\n          } else\n            o.push(p);\n        l = o;\n      }\n      if (l.length === 0) return `${n}\n${a}`;\n      const g = l.map((o, p) => p < l.length - 1 ? /\\\\\\\\\\s*$/.test(o) ? o : /\\\\\\s*$/.test(o) ? o.replace(/\\\\\\s*$/, \" \\\\\\\\\") : o + \" \\\\\\\\\" : o.replace(/\\\\\\s*$/, \"\")).join(`\n`);\n      return `${n}\n${g}\n${a}`;\n    }\n  );\n}\nfunction Nt(e) {\n  return e.replace(/\\$\\$([\\s\\S]*?)\\$\\$/g, (t, n) => {\n    if (!/\\\\begin\\{(?:b|p|B|v|V)?matrix\\}/.test(n)) return t;\n    const r = /^\\s*\\n/.test(n), a = /\\n\\s*$/.test(n);\n    return r && a ? t : `$$\n` + n.trim().replace(/(\\\\begin\\{[^}]+\\})/, `$1\n`).replace(/(\\\\\\\\)\\s*(?=\\S)/g, `$1\n`).replace(/(\\\\end\\{[^}]+\\})/, `\n$1`).trim() + `\n$$`;\n  });\n}\nfunction Pt(e) {\n  const n = e.replace(/\\r\\n?/g, `\n`).split(`\n`), r = [];\n  let a = !1, c = \"\", l = 0, g = !1, o = \"\", p = \"\";\n  const L = (s) => {\n    r.push(s.length ? o + s : o);\n  }, i = (s) => o && s.startsWith(o) ? s.slice(o.length) : p && s.startsWith(p) ? s.slice(p.length) : s.trimStart();\n  for (const s of n) {\n    if (!g) {\n      const h = s.match(/^(\\s*(?:>\\s*)*)([`~]{3,})/);\n      if (h) {\n        const d = h[2];\n        if (!d) {\n          r.push(s);\n          continue;\n        }\n        if (a)\n          d[0] === c && d.length >= l && (a = !1, c = \"\", l = 0);\n        else {\n          if (!d.length) {\n            r.push(s);\n            continue;\n          }\n          a = !0, c = d[0], l = d.length;\n        }\n        r.push(s);\n        continue;\n      }\n    }\n    if (a) {\n      r.push(s);\n      continue;\n    }\n    if (!g) {\n      const h = s.match(/^(\\s*(?:>\\s*)*)\\\\\\[(.*)$/);\n      if (!h) {\n        r.push(s);\n        continue;\n      }\n      g = !0, p = h[1] ?? \"\", o = p.includes(\">\") && !/\\s$/.test(p) ? p + \" \" : p, r.length > 0 && r[r.length - 1]?.trim().length && r.push(o.includes(\">\") ? o : \"\"), r.push(o + \"$$\");\n      const d = h[2] ?? \"\", w = d.indexOf(\"\\\\]\");\n      if (w !== -1) {\n        const y = d.slice(0, w);\n        y.length > 0 && L(i(y).trimStart()), r.push(o + \"$$\"), g = !1;\n        const v = d.slice(w + 2);\n        v.length > 0 && r.push(o + v.trimStart());\n      } else d.trim().length > 0 && L(i(d).trimStart());\n      continue;\n    }\n    const u = s.indexOf(\"\\\\]\");\n    if (u !== -1) {\n      const h = s.slice(0, u);\n      h.length > 0 && L(i(h)), r.push(o + \"$$\"), g = !1;\n      const d = s.slice(u + 2);\n      d.length > 0 && r.push(o + d.trimStart());\n    } else\n      L(i(s));\n  }\n  const k = [];\n  let f = !1, C = \"\", B = 0;\n  for (const s of r) {\n    const u = s, h = u.match(/^(\\s*(?:>\\s*)*)([`~]{3,})/);\n    if (h) {\n      const d = h[2] ?? \"\";\n      f ? d[0] === C && d.length >= B && (f = !1, C = \"\", B = 0) : (f = !0, C = d[0] ?? \"\", B = d.length), k.push(u);\n      continue;\n    }\n    if (f) {\n      k.push(u);\n      continue;\n    }\n    if (/\\\\\\[.*?\\\\\\]/.test(u) && !/^\\s*\\\\\\[/.test(u)) {\n      const d = [], w = /\\\\\\[([^\\n]*?)\\\\\\]/g;\n      let y = 0, v;\n      for (; v = w.exec(u); ) {\n        const A = u.slice(y, v.index);\n        A.trim().length && d.push(A);\n        const x = (v[1] ?? \"\").trim();\n        d.push(\"$$\"), x.length && d.push(x), d.push(\"$$\"), y = v.index + v[0].length;\n      }\n      const N = u.slice(y);\n      N.trim().length && d.push(N);\n      for (const A of d) k.push(A === \"$$\" ? \"$$\" : A);\n    } else\n      k.push(u);\n  }\n  return k.join(`\n`);\n}\nconst Et = (e, t) => {\n  if (!t) return e;\n  try {\n    return new URL(e, t).toString();\n  } catch {\n    return e;\n  }\n}, fe = (e, t, n) => {\n  if (!e) return null;\n  let r = e.trim();\n  r = Et(r, n);\n  const a = r.toLowerCase();\n  return a.startsWith(\"javascript:\") || !t.some((c) => a.startsWith(c)) ? null : r;\n}, Dt = (e, t) => fe(e, t.allowedLinkPrefixes, t.defaultOrigin), Tt = (e, t) => fe(e, t.allowedImagePrefixes, t.defaultOrigin), Xt = _({\n  name: \"StreamMarkdown\",\n  props: {\n    content: { type: String, default: \"\" },\n    class: { type: String, default: \"\" },\n    className: { type: String, default: \"\" },\n    components: { type: Object, default: () => ({}) },\n    remarkPlugins: { type: Array, default: () => [] },\n    rehypePlugins: { type: Array, default: () => [] },\n    defaultOrigin: { type: String, default: void 0 },\n    allowedImagePrefixes: {\n      type: Array,\n      default: () => [\"https://\", \"http://\"]\n    },\n    allowedLinkPrefixes: {\n      type: Array,\n      default: () => [\"https://\", \"http://\"]\n    },\n    parseIncompleteMarkdown: { type: Boolean, default: !0 },\n    shikiTheme: {\n      type: [String, Object],\n      default: void 0\n    },\n    // --- CodeBlock pass-through customization ---\n    codeBlockActions: { type: Array, default: () => [] },\n    codeBlockShowLineNumbers: { type: Boolean, default: !1 },\n    codeBlockSelectable: { type: Boolean, default: !0 },\n    codeBlockHideCopy: { type: Boolean, default: !1 },\n    codeBlockHideDownload: { type: Boolean, default: !1 }\n  },\n  setup(e, { slots: t }) {\n    const n = (i) => i && typeof i == \"object\" && \"default\" in i ? i.default : i, r = e.remarkPlugins.some(\n      (i) => {\n        const k = Array.isArray(i) ? i[0] : i;\n        return n(k) === ee;\n      }\n    ), a = ye().use(n(be)).use(n(we));\n    r || a.use(n(ee), {\n      singleDollarTextMath: !1\n    }), e.remarkPlugins.forEach((i) => {\n      if (Array.isArray(i)) {\n        const [k, f] = i;\n        a.use(n(k), f);\n      } else\n        a.use(n(i));\n    }), a.use(n(ve), { allowDangerousHtml: !1 }).use(n($e)), e.rehypePlugins.forEach((i) => {\n      if (Array.isArray(i)) {\n        const [k, f] = i;\n        a.use(n(k), f);\n      } else\n        a.use(n(i));\n    });\n    const c = {\n      allowedImagePrefixes: e.allowedImagePrefixes,\n      allowedLinkPrefixes: e.allowedLinkPrefixes,\n      defaultOrigin: e.defaultOrigin\n    }, l = {\n      ...at,\n      ...e.components || {}\n    }, g = (i, k) => i.map((f) => L(f)).filter(Boolean);\n    function o(i) {\n      return i.type === \"text\" ? i.value : i.children ? i.children.map(o).join(\"\") : \"\";\n    }\n    const p = (i, k, f) => {\n      if (typeof i == \"string\")\n        return f && f.length ? m(i, k, f) : m(i, k);\n      if (!f || Array.isArray(f) && f.length === 0)\n        return m(i, k);\n      const B = Array.isArray(f) ? () => f : () => [f];\n      return m(i, k, { default: B });\n    }, L = (i, k) => {\n      if (!i) return null;\n      if (i.type === \"text\") return i.value;\n      if (i.type !== \"element\") return null;\n      const f = i, C = { ...f.properties || {} }, B = g(f.children || [], f.tagName), s = f.tagName;\n      if (s === \"a\") {\n        const h = Dt(\n          String(C.href || \"\"),\n          c\n        );\n        if (!h) return B;\n        C.href = h, C.target = \"_blank\", C.rel = \"noreferrer\";\n      }\n      if (s === \"img\") {\n        const h = Tt(\n          String(C.src || \"\"),\n          c\n        );\n        if (!h) return null;\n        C.src = h;\n      }\n      if (s === \"pre\" && f.children && f.children[0] && f.children[0].tagName === \"code\") {\n        const h = f.children[0], d = o(h), y = (h.properties?.className || []).find(\n          (A) => A.startsWith(\"language-\")\n        ), v = y ? y.replace(\"language-\", \"\") : \"\";\n        if (v === \"mermaid\")\n          return m(rt, { code: d });\n        const N = l.codeblock || se;\n        return m(N, {\n          code: d,\n          language: v,\n          theme: e.shikiTheme,\n          actions: e.codeBlockActions,\n          showLineNumbers: e.codeBlockShowLineNumbers,\n          selectable: e.codeBlockSelectable,\n          hideCopy: e.codeBlockHideCopy,\n          hideDownload: e.codeBlockHideDownload\n        });\n      }\n      const u = l[s];\n      return p(u || s, C, B);\n    };\n    return () => {\n      let i = e.content;\n      const k = t.default ? t.default() : [];\n      if (k && k.length > 0) {\n        const S = k.map(\n          (b) => typeof b.children == \"string\" ? b.children : \"\"\n        ).join(\"\");\n        S.trim() && (i = S);\n      }\n      let f = null;\n      if (e.parseIncompleteMarkdown && typeof i == \"string\" && i.length) {\n        const b = i.replace(/\\r\\n?/g, `\n`).split(`\n`);\n        let D = [];\n        for (let I = 0; I < b.length; I++) {\n          const X = b[I] ?? \"\";\n          /^\\s*```/.test(X) && D.push(I);\n        }\n        if (D.length > 0 && D.length % 2 === 1) {\n          const I = D[D.length - 1], z = (b[I] ?? \"\").replace(/^\\s*```+/, \"\");\n          let Y = \"\", H = \"\";\n          if (z.trim().length) {\n            const W = z.match(\n              /^([a-zA-Z0-9_-]+)(\\s+|$)(.*)$/\n            );\n            W ? (Y = (W[1] || \"\").trim(), H = (W[3] || \"\").trimEnd()) : H = z.trimEnd();\n          }\n          const Q = I + 1 < b.length ? b.slice(I + 1) : [];\n          H && Q.unshift(H), f = {\n            prefix: I > 0 ? b.slice(0, I).join(`\n`) : \"\",\n            code: Q.join(`\n`),\n            lang: Y\n          };\n        }\n      }\n      const C = (S) => {\n        let b = jt(S);\n        return b = Pt(b), b = Nt(b), b;\n      }, B = C(i);\n      f && (f.prefix = C(\n        f.prefix\n      ));\n      const s = f ? f.prefix : B, u = e.parseIncompleteMarkdown ? ie(s) : s;\n      let h = st(u);\n      const d = [];\n      let w = [], y = 0;\n      const v = () => {\n        w.length && (d.push(w.join(`\n\n`)), w = [], y = 0);\n      };\n      for (const S of h) {\n        const b = (S.match(/\\$\\$/g) || []).length;\n        if (w.length === 0)\n          if (b % 2 === 1) {\n            w.push(S), y += b;\n            continue;\n          } else {\n            d.push(S);\n            continue;\n          }\n        else\n          w.push(S), y += b, y % 2 === 0 && v();\n      }\n      v();\n      let A = d.map((S) => S).map(\n        (S) => (\n          // Use trimEnd() instead of trim() to preserve leading whitespace,\n          // which is important for markdown elements like code blocks and lists.\n          // Only trailing whitespace is removed to avoid breaking indented content.\n          e.parseIncompleteMarkdown ? ie(S.trimEnd()) : S\n        )\n      ).flatMap((S) => {\n        const b = a.runSync(a.parse(S));\n        return g(b.children);\n      });\n      if (f) {\n        const S = l.codeblock || se;\n        A.push(\n          m(S, {\n            code: f.code,\n            language: f.lang,\n            theme: e.shikiTheme,\n            actions: e.codeBlockActions,\n            showLineNumbers: e.codeBlockShowLineNumbers,\n            selectable: e.codeBlockSelectable,\n            hideCopy: e.codeBlockHideCopy,\n            hideDownload: e.codeBlockHideDownload,\n            \"data-open-fence\": \"true\",\n            \"data-streaming\": \"true\"\n          })\n        );\n      }\n      const x = [\n        \"streamdown-vue space-y-4\",\n        e.class,\n        e.className\n      ].filter(Boolean).join(\" \");\n      return m(\"div\", { class: x || void 0 }, A);\n    };\n  }\n});\nexport {\n  se as C,\n  Je as D,\n  Ke as G,\n  rt as M,\n  Xt as S,\n  he as a,\n  J as b,\n  ie as c,\n  _e as d,\n  Oe as e,\n  Kt as f,\n  Zt as g,\n  Jt as h,\n  et as l,\n  st as p,\n  Te as r,\n  tt as u\n};\n","/**\n * Throw a given error.\n *\n * @param {Error|null|undefined} [error]\n *   Maybe error.\n * @returns {asserts error is null|undefined}\n */\nexport function bail(error) {\n  if (error) {\n    throw error\n  }\n}\n","/**\n * @typedef {import('trough').Pipeline} Pipeline\n *\n * @typedef {import('unist').Node} Node\n *\n * @typedef {import('vfile').Compatible} Compatible\n * @typedef {import('vfile').Value} Value\n *\n * @typedef {import('../index.js').CompileResultMap} CompileResultMap\n * @typedef {import('../index.js').Data} Data\n * @typedef {import('../index.js').Settings} Settings\n */\n\n/**\n * @typedef {CompileResultMap[keyof CompileResultMap]} CompileResults\n *   Acceptable results from compilers.\n *\n *   To register custom results, add them to\n *   {@linkcode CompileResultMap}.\n */\n\n/**\n * @template {Node} [Tree=Node]\n *   The node that the compiler receives (default: `Node`).\n * @template {CompileResults} [Result=CompileResults]\n *   The thing that the compiler yields (default: `CompileResults`).\n * @callback Compiler\n *   A **compiler** handles the compiling of a syntax tree to something else\n *   (in most cases, text) (TypeScript type).\n *\n *   It is used in the stringify phase and called with a {@linkcode Node}\n *   and {@linkcode VFile} representation of the document to compile.\n *   It should return the textual representation of the given tree (typically\n *   `string`).\n *\n *   > **Note**: unified typically compiles by serializing: most compilers\n *   > return `string` (or `Uint8Array`).\n *   > Some compilers, such as the one configured with\n *   > [`rehype-react`][rehype-react], return other values (in this case, a\n *   > React tree).\n *   > If you’re using a compiler that doesn’t serialize, expect different\n *   > result values.\n *   >\n *   > To register custom results in TypeScript, add them to\n *   > {@linkcode CompileResultMap}.\n *\n *   [rehype-react]: https://github.com/rehypejs/rehype-react\n * @param {Tree} tree\n *   Tree to compile.\n * @param {VFile} file\n *   File associated with `tree`.\n * @returns {Result}\n *   New content: compiled text (`string` or `Uint8Array`, for `file.value`) or\n *   something else (for `file.result`).\n */\n\n/**\n * @template {Node} [Tree=Node]\n *   The node that the parser yields (default: `Node`)\n * @callback Parser\n *   A **parser** handles the parsing of text to a syntax tree.\n *\n *   It is used in the parse phase and is called with a `string` and\n *   {@linkcode VFile} of the document to parse.\n *   It must return the syntax tree representation of the given file\n *   ({@linkcode Node}).\n * @param {string} document\n *   Document to parse.\n * @param {VFile} file\n *   File associated with `document`.\n * @returns {Tree}\n *   Node representing the given file.\n */\n\n/**\n * @typedef {(\n *   Plugin<Array<any>, any, any> |\n *   PluginTuple<Array<any>, any, any> |\n *   Preset\n * )} Pluggable\n *   Union of the different ways to add plugins and settings.\n */\n\n/**\n * @typedef {Array<Pluggable>} PluggableList\n *   List of plugins and presets.\n */\n\n// Note: we can’t use `callback` yet as it messes up `this`:\n//  <https://github.com/microsoft/TypeScript/issues/55197>.\n/**\n * @template {Array<unknown>} [PluginParameters=[]]\n *   Arguments passed to the plugin (default: `[]`, the empty tuple).\n * @template {Node | string | undefined} [Input=Node]\n *   Value that is expected as input (default: `Node`).\n *\n *   *   If the plugin returns a {@linkcode Transformer}, this\n *       should be the node it expects.\n *   *   If the plugin sets a {@linkcode Parser}, this should be\n *       `string`.\n *   *   If the plugin sets a {@linkcode Compiler}, this should be the\n *       node it expects.\n * @template [Output=Input]\n *   Value that is yielded as output (default: `Input`).\n *\n *   *   If the plugin returns a {@linkcode Transformer}, this\n *       should be the node that that yields.\n *   *   If the plugin sets a {@linkcode Parser}, this should be the\n *       node that it yields.\n *   *   If the plugin sets a {@linkcode Compiler}, this should be\n *       result it yields.\n * @typedef {(\n *   (this: Processor, ...parameters: PluginParameters) =>\n *     Input extends string ? // Parser.\n *        Output extends Node | undefined ? undefined | void : never :\n *     Output extends CompileResults ? // Compiler.\n *        Input extends Node | undefined ? undefined | void : never :\n *     Transformer<\n *       Input extends Node ? Input : Node,\n *       Output extends Node ? Output : Node\n *     > | undefined | void\n * )} Plugin\n *   Single plugin.\n *\n *   Plugins configure the processors they are applied on in the following\n *   ways:\n *\n *   *   they change the processor, such as the parser, the compiler, or by\n *       configuring data\n *   *   they specify how to handle trees and files\n *\n *   In practice, they are functions that can receive options and configure the\n *   processor (`this`).\n *\n *   > **Note**: plugins are called when the processor is *frozen*, not when\n *   > they are applied.\n */\n\n/**\n * Tuple of a plugin and its configuration.\n *\n * The first item is a plugin, the rest are its parameters.\n *\n * @template {Array<unknown>} [TupleParameters=[]]\n *   Arguments passed to the plugin (default: `[]`, the empty tuple).\n * @template {Node | string | undefined} [Input=undefined]\n *   Value that is expected as input (optional).\n *\n *   *   If the plugin returns a {@linkcode Transformer}, this\n *       should be the node it expects.\n *   *   If the plugin sets a {@linkcode Parser}, this should be\n *       `string`.\n *   *   If the plugin sets a {@linkcode Compiler}, this should be the\n *       node it expects.\n * @template [Output=undefined] (optional).\n *   Value that is yielded as output.\n *\n *   *   If the plugin returns a {@linkcode Transformer}, this\n *       should be the node that that yields.\n *   *   If the plugin sets a {@linkcode Parser}, this should be the\n *       node that it yields.\n *   *   If the plugin sets a {@linkcode Compiler}, this should be\n *       result it yields.\n * @typedef {(\n *   [\n *     plugin: Plugin<TupleParameters, Input, Output>,\n *     ...parameters: TupleParameters\n *   ]\n * )} PluginTuple\n */\n\n/**\n * @typedef Preset\n *   Sharable configuration.\n *\n *   They can contain plugins and settings.\n * @property {PluggableList | undefined} [plugins]\n *   List of plugins and presets (optional).\n * @property {Settings | undefined} [settings]\n *   Shared settings for parsers and compilers (optional).\n */\n\n/**\n * @template {VFile} [File=VFile]\n *   The file that the callback receives (default: `VFile`).\n * @callback ProcessCallback\n *   Callback called when the process is done.\n *\n *   Called with either an error or a result.\n * @param {Error | undefined} [error]\n *   Fatal error (optional).\n * @param {File | undefined} [file]\n *   Processed file (optional).\n * @returns {undefined}\n *   Nothing.\n */\n\n/**\n * @template {Node} [Tree=Node]\n *   The tree that the callback receives (default: `Node`).\n * @callback RunCallback\n *   Callback called when transformers are done.\n *\n *   Called with either an error or results.\n * @param {Error | undefined} [error]\n *   Fatal error (optional).\n * @param {Tree | undefined} [tree]\n *   Transformed tree (optional).\n * @param {VFile | undefined} [file]\n *   File (optional).\n * @returns {undefined}\n *   Nothing.\n */\n\n/**\n * @template {Node} [Output=Node]\n *   Node type that the transformer yields (default: `Node`).\n * @callback TransformCallback\n *   Callback passed to transforms.\n *\n *   If the signature of a `transformer` accepts a third argument, the\n *   transformer may perform asynchronous operations, and must call it.\n * @param {Error | undefined} [error]\n *   Fatal error to stop the process (optional).\n * @param {Output | undefined} [tree]\n *   New, changed, tree (optional).\n * @param {VFile | undefined} [file]\n *   New, changed, file (optional).\n * @returns {undefined}\n *   Nothing.\n */\n\n/**\n * @template {Node} [Input=Node]\n *   Node type that the transformer expects (default: `Node`).\n * @template {Node} [Output=Input]\n *   Node type that the transformer yields (default: `Input`).\n * @callback Transformer\n *   Transformers handle syntax trees and files.\n *\n *   They are functions that are called each time a syntax tree and file are\n *   passed through the run phase.\n *   When an error occurs in them (either because it’s thrown, returned,\n *   rejected, or passed to `next`), the process stops.\n *\n *   The run phase is handled by [`trough`][trough], see its documentation for\n *   the exact semantics of these functions.\n *\n *   > **Note**: you should likely ignore `next`: don’t accept it.\n *   > it supports callback-style async work.\n *   > But promises are likely easier to reason about.\n *\n *   [trough]: https://github.com/wooorm/trough#function-fninput-next\n * @param {Input} tree\n *   Tree to handle.\n * @param {VFile} file\n *   File to handle.\n * @param {TransformCallback<Output>} next\n *   Callback.\n * @returns {(\n *   Promise<Output | undefined | void> |\n *   Promise<never> | // For some reason this is needed separately.\n *   Output |\n *   Error |\n *   undefined |\n *   void\n * )}\n *   If you accept `next`, nothing.\n *   Otherwise:\n *\n *   *   `Error` — fatal error to stop the process\n *   *   `Promise<undefined>` or `undefined` — the next transformer keeps using\n *       same tree\n *   *   `Promise<Node>` or `Node` — new, changed, tree\n */\n\n/**\n * @template {Node | undefined} ParseTree\n *   Output of `parse`.\n * @template {Node | undefined} HeadTree\n *   Input for `run`.\n * @template {Node | undefined} TailTree\n *   Output for `run`.\n * @template {Node | undefined} CompileTree\n *   Input of `stringify`.\n * @template {CompileResults | undefined} CompileResult\n *   Output of `stringify`.\n * @template {Node | string | undefined} Input\n *   Input of plugin.\n * @template Output\n *   Output of plugin (optional).\n * @typedef {(\n *   Input extends string\n *     ? Output extends Node | undefined\n *       ? // Parser.\n *         Processor<\n *           Output extends undefined ? ParseTree : Output,\n *           HeadTree,\n *           TailTree,\n *           CompileTree,\n *           CompileResult\n *         >\n *       : // Unknown.\n *         Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>\n *     : Output extends CompileResults\n *     ? Input extends Node | undefined\n *       ? // Compiler.\n *         Processor<\n *           ParseTree,\n *           HeadTree,\n *           TailTree,\n *           Input extends undefined ? CompileTree : Input,\n *           Output extends undefined ? CompileResult : Output\n *         >\n *       : // Unknown.\n *         Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>\n *     : Input extends Node | undefined\n *     ? Output extends Node | undefined\n *       ? // Transform.\n *         Processor<\n *           ParseTree,\n *           HeadTree extends undefined ? Input : HeadTree,\n *           Output extends undefined ? TailTree : Output,\n *           CompileTree,\n *           CompileResult\n *         >\n *       : // Unknown.\n *         Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>\n *     : // Unknown.\n *       Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>\n * )} UsePlugin\n *   Create a processor based on the input/output of a {@link Plugin plugin}.\n */\n\n/**\n * @template {CompileResults | undefined} Result\n *   Node type that the transformer yields.\n * @typedef {(\n *   Result extends Value | undefined ?\n *     VFile :\n *     VFile & {result: Result}\n *   )} VFileWithOutput\n *   Type to generate a {@linkcode VFile} corresponding to a compiler result.\n *\n *   If a result that is not acceptable on a `VFile` is used, that will\n *   be stored on the `result` field of {@linkcode VFile}.\n */\n\nimport {bail} from 'bail'\nimport extend from 'extend'\nimport {ok as assert} from 'devlop'\nimport isPlainObj from 'is-plain-obj'\nimport {trough} from 'trough'\nimport {VFile} from 'vfile'\nimport {CallableInstance} from './callable-instance.js'\n\n// To do: next major: drop `Compiler`, `Parser`: prefer lowercase.\n\n// To do: we could start yielding `never` in TS when a parser is missing and\n// `parse` is called.\n// Currently, we allow directly setting `processor.parser`, which is untyped.\n\nconst own = {}.hasOwnProperty\n\n/**\n * @template {Node | undefined} [ParseTree=undefined]\n *   Output of `parse` (optional).\n * @template {Node | undefined} [HeadTree=undefined]\n *   Input for `run` (optional).\n * @template {Node | undefined} [TailTree=undefined]\n *   Output for `run` (optional).\n * @template {Node | undefined} [CompileTree=undefined]\n *   Input of `stringify` (optional).\n * @template {CompileResults | undefined} [CompileResult=undefined]\n *   Output of `stringify` (optional).\n * @extends {CallableInstance<[], Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>>}\n */\nexport class Processor extends CallableInstance {\n  /**\n   * Create a processor.\n   */\n  constructor() {\n    // If `Processor()` is called (w/o new), `copy` is called instead.\n    super('copy')\n\n    /**\n     * Compiler to use (deprecated).\n     *\n     * @deprecated\n     *   Use `compiler` instead.\n     * @type {(\n     *   Compiler<\n     *     CompileTree extends undefined ? Node : CompileTree,\n     *     CompileResult extends undefined ? CompileResults : CompileResult\n     *   > |\n     *   undefined\n     * )}\n     */\n    this.Compiler = undefined\n\n    /**\n     * Parser to use (deprecated).\n     *\n     * @deprecated\n     *   Use `parser` instead.\n     * @type {(\n     *   Parser<ParseTree extends undefined ? Node : ParseTree> |\n     *   undefined\n     * )}\n     */\n    this.Parser = undefined\n\n    // Note: the following fields are considered private.\n    // However, they are needed for tests, and TSC generates an untyped\n    // `private freezeIndex` field for, which trips `type-coverage` up.\n    // Instead, we use `@deprecated` to visualize that they shouldn’t be used.\n    /**\n     * Internal list of configured plugins.\n     *\n     * @deprecated\n     *   This is a private internal property and should not be used.\n     * @type {Array<PluginTuple<Array<unknown>>>}\n     */\n    this.attachers = []\n\n    /**\n     * Compiler to use.\n     *\n     * @type {(\n     *   Compiler<\n     *     CompileTree extends undefined ? Node : CompileTree,\n     *     CompileResult extends undefined ? CompileResults : CompileResult\n     *   > |\n     *   undefined\n     * )}\n     */\n    this.compiler = undefined\n\n    /**\n     * Internal state to track where we are while freezing.\n     *\n     * @deprecated\n     *   This is a private internal property and should not be used.\n     * @type {number}\n     */\n    this.freezeIndex = -1\n\n    /**\n     * Internal state to track whether we’re frozen.\n     *\n     * @deprecated\n     *   This is a private internal property and should not be used.\n     * @type {boolean | undefined}\n     */\n    this.frozen = undefined\n\n    /**\n     * Internal state.\n     *\n     * @deprecated\n     *   This is a private internal property and should not be used.\n     * @type {Data}\n     */\n    this.namespace = {}\n\n    /**\n     * Parser to use.\n     *\n     * @type {(\n     *   Parser<ParseTree extends undefined ? Node : ParseTree> |\n     *   undefined\n     * )}\n     */\n    this.parser = undefined\n\n    /**\n     * Internal list of configured transformers.\n     *\n     * @deprecated\n     *   This is a private internal property and should not be used.\n     * @type {Pipeline}\n     */\n    this.transformers = trough()\n  }\n\n  /**\n   * Copy a processor.\n   *\n   * @deprecated\n   *   This is a private internal method and should not be used.\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *   New *unfrozen* processor ({@linkcode Processor}) that is\n   *   configured to work the same as its ancestor.\n   *   When the descendant processor is configured in the future it does not\n   *   affect the ancestral processor.\n   */\n  copy() {\n    // Cast as the type parameters will be the same after attaching.\n    const destination =\n      /** @type {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>} */ (\n        new Processor()\n      )\n    let index = -1\n\n    while (++index < this.attachers.length) {\n      const attacher = this.attachers[index]\n      destination.use(...attacher)\n    }\n\n    destination.data(extend(true, {}, this.namespace))\n\n    return destination\n  }\n\n  /**\n   * Configure the processor with info available to all plugins.\n   * Information is stored in an object.\n   *\n   * Typically, options can be given to a specific plugin, but sometimes it\n   * makes sense to have information shared with several plugins.\n   * For example, a list of HTML elements that are self-closing, which is\n   * needed during all phases.\n   *\n   * > **Note**: setting information cannot occur on *frozen* processors.\n   * > Call the processor first to create a new unfrozen processor.\n   *\n   * > **Note**: to register custom data in TypeScript, augment the\n   * > {@linkcode Data} interface.\n   *\n   * @example\n   *   This example show how to get and set info:\n   *\n   *   ```js\n   *   import {unified} from 'unified'\n   *\n   *   const processor = unified().data('alpha', 'bravo')\n   *\n   *   processor.data('alpha') // => 'bravo'\n   *\n   *   processor.data() // => {alpha: 'bravo'}\n   *\n   *   processor.data({charlie: 'delta'})\n   *\n   *   processor.data() // => {charlie: 'delta'}\n   *   ```\n   *\n   * @template {keyof Data} Key\n   *\n   * @overload\n   * @returns {Data}\n   *\n   * @overload\n   * @param {Data} dataset\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *\n   * @overload\n   * @param {Key} key\n   * @returns {Data[Key]}\n   *\n   * @overload\n   * @param {Key} key\n   * @param {Data[Key]} value\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *\n   * @param {Data | Key} [key]\n   *   Key to get or set, or entire dataset to set, or nothing to get the\n   *   entire dataset (optional).\n   * @param {Data[Key]} [value]\n   *   Value to set (optional).\n   * @returns {unknown}\n   *   The current processor when setting, the value at `key` when getting, or\n   *   the entire dataset when getting without key.\n   */\n  data(key, value) {\n    if (typeof key === 'string') {\n      // Set `key`.\n      if (arguments.length === 2) {\n        assertUnfrozen('data', this.frozen)\n        this.namespace[key] = value\n        return this\n      }\n\n      // Get `key`.\n      return (own.call(this.namespace, key) && this.namespace[key]) || undefined\n    }\n\n    // Set space.\n    if (key) {\n      assertUnfrozen('data', this.frozen)\n      this.namespace = key\n      return this\n    }\n\n    // Get space.\n    return this.namespace\n  }\n\n  /**\n   * Freeze a processor.\n   *\n   * Frozen processors are meant to be extended and not to be configured\n   * directly.\n   *\n   * When a processor is frozen it cannot be unfrozen.\n   * New processors working the same way can be created by calling the\n   * processor.\n   *\n   * It’s possible to freeze processors explicitly by calling `.freeze()`.\n   * Processors freeze automatically when `.parse()`, `.run()`, `.runSync()`,\n   * `.stringify()`, `.process()`, or `.processSync()` are called.\n   *\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *   The current processor.\n   */\n  freeze() {\n    if (this.frozen) {\n      return this\n    }\n\n    // Cast so that we can type plugins easier.\n    // Plugins are supposed to be usable on different processors, not just on\n    // this exact processor.\n    const self = /** @type {Processor} */ (/** @type {unknown} */ (this))\n\n    while (++this.freezeIndex < this.attachers.length) {\n      const [attacher, ...options] = this.attachers[this.freezeIndex]\n\n      if (options[0] === false) {\n        continue\n      }\n\n      if (options[0] === true) {\n        options[0] = undefined\n      }\n\n      const transformer = attacher.call(self, ...options)\n\n      if (typeof transformer === 'function') {\n        this.transformers.use(transformer)\n      }\n    }\n\n    this.frozen = true\n    this.freezeIndex = Number.POSITIVE_INFINITY\n\n    return this\n  }\n\n  /**\n   * Parse text to a syntax tree.\n   *\n   * > **Note**: `parse` freezes the processor if not already *frozen*.\n   *\n   * > **Note**: `parse` performs the parse phase, not the run phase or other\n   * > phases.\n   *\n   * @param {Compatible | undefined} [file]\n   *   file to parse (optional); typically `string` or `VFile`; any value\n   *   accepted as `x` in `new VFile(x)`.\n   * @returns {ParseTree extends undefined ? Node : ParseTree}\n   *   Syntax tree representing `file`.\n   */\n  parse(file) {\n    this.freeze()\n    const realFile = vfile(file)\n    const parser = this.parser || this.Parser\n    assertParser('parse', parser)\n    return parser(String(realFile), realFile)\n  }\n\n  /**\n   * Process the given file as configured on the processor.\n   *\n   * > **Note**: `process` freezes the processor if not already *frozen*.\n   *\n   * > **Note**: `process` performs the parse, run, and stringify phases.\n   *\n   * @overload\n   * @param {Compatible | undefined} file\n   * @param {ProcessCallback<VFileWithOutput<CompileResult>>} done\n   * @returns {undefined}\n   *\n   * @overload\n   * @param {Compatible | undefined} [file]\n   * @returns {Promise<VFileWithOutput<CompileResult>>}\n   *\n   * @param {Compatible | undefined} [file]\n   *   File (optional); typically `string` or `VFile`]; any value accepted as\n   *   `x` in `new VFile(x)`.\n   * @param {ProcessCallback<VFileWithOutput<CompileResult>> | undefined} [done]\n   *   Callback (optional).\n   * @returns {Promise<VFile> | undefined}\n   *   Nothing if `done` is given.\n   *   Otherwise a promise, rejected with a fatal error or resolved with the\n   *   processed file.\n   *\n   *   The parsed, transformed, and compiled value is available at\n   *   `file.value` (see note).\n   *\n   *   > **Note**: unified typically compiles by serializing: most\n   *   > compilers return `string` (or `Uint8Array`).\n   *   > Some compilers, such as the one configured with\n   *   > [`rehype-react`][rehype-react], return other values (in this case, a\n   *   > React tree).\n   *   > If you’re using a compiler that doesn’t serialize, expect different\n   *   > result values.\n   *   >\n   *   > To register custom results in TypeScript, add them to\n   *   > {@linkcode CompileResultMap}.\n   *\n   *   [rehype-react]: https://github.com/rehypejs/rehype-react\n   */\n  process(file, done) {\n    const self = this\n\n    this.freeze()\n    assertParser('process', this.parser || this.Parser)\n    assertCompiler('process', this.compiler || this.Compiler)\n\n    return done ? executor(undefined, done) : new Promise(executor)\n\n    // Note: `void`s needed for TS.\n    /**\n     * @param {((file: VFileWithOutput<CompileResult>) => undefined | void) | undefined} resolve\n     * @param {(error: Error | undefined) => undefined | void} reject\n     * @returns {undefined}\n     */\n    function executor(resolve, reject) {\n      const realFile = vfile(file)\n      // Assume `ParseTree` (the result of the parser) matches `HeadTree` (the\n      // input of the first transform).\n      const parseTree =\n        /** @type {HeadTree extends undefined ? Node : HeadTree} */ (\n          /** @type {unknown} */ (self.parse(realFile))\n        )\n\n      self.run(parseTree, realFile, function (error, tree, file) {\n        if (error || !tree || !file) {\n          return realDone(error)\n        }\n\n        // Assume `TailTree` (the output of the last transform) matches\n        // `CompileTree` (the input of the compiler).\n        const compileTree =\n          /** @type {CompileTree extends undefined ? Node : CompileTree} */ (\n            /** @type {unknown} */ (tree)\n          )\n\n        const compileResult = self.stringify(compileTree, file)\n\n        if (looksLikeAValue(compileResult)) {\n          file.value = compileResult\n        } else {\n          file.result = compileResult\n        }\n\n        realDone(error, /** @type {VFileWithOutput<CompileResult>} */ (file))\n      })\n\n      /**\n       * @param {Error | undefined} error\n       * @param {VFileWithOutput<CompileResult> | undefined} [file]\n       * @returns {undefined}\n       */\n      function realDone(error, file) {\n        if (error || !file) {\n          reject(error)\n        } else if (resolve) {\n          resolve(file)\n        } else {\n          assert(done, '`done` is defined if `resolve` is not')\n          done(undefined, file)\n        }\n      }\n    }\n  }\n\n  /**\n   * Process the given file as configured on the processor.\n   *\n   * An error is thrown if asynchronous transforms are configured.\n   *\n   * > **Note**: `processSync` freezes the processor if not already *frozen*.\n   *\n   * > **Note**: `processSync` performs the parse, run, and stringify phases.\n   *\n   * @param {Compatible | undefined} [file]\n   *   File (optional); typically `string` or `VFile`; any value accepted as\n   *   `x` in `new VFile(x)`.\n   * @returns {VFileWithOutput<CompileResult>}\n   *   The processed file.\n   *\n   *   The parsed, transformed, and compiled value is available at\n   *   `file.value` (see note).\n   *\n   *   > **Note**: unified typically compiles by serializing: most\n   *   > compilers return `string` (or `Uint8Array`).\n   *   > Some compilers, such as the one configured with\n   *   > [`rehype-react`][rehype-react], return other values (in this case, a\n   *   > React tree).\n   *   > If you’re using a compiler that doesn’t serialize, expect different\n   *   > result values.\n   *   >\n   *   > To register custom results in TypeScript, add them to\n   *   > {@linkcode CompileResultMap}.\n   *\n   *   [rehype-react]: https://github.com/rehypejs/rehype-react\n   */\n  processSync(file) {\n    /** @type {boolean} */\n    let complete = false\n    /** @type {VFileWithOutput<CompileResult> | undefined} */\n    let result\n\n    this.freeze()\n    assertParser('processSync', this.parser || this.Parser)\n    assertCompiler('processSync', this.compiler || this.Compiler)\n\n    this.process(file, realDone)\n    assertDone('processSync', 'process', complete)\n    assert(result, 'we either bailed on an error or have a tree')\n\n    return result\n\n    /**\n     * @type {ProcessCallback<VFileWithOutput<CompileResult>>}\n     */\n    function realDone(error, file) {\n      complete = true\n      bail(error)\n      result = file\n    }\n  }\n\n  /**\n   * Run *transformers* on a syntax tree.\n   *\n   * > **Note**: `run` freezes the processor if not already *frozen*.\n   *\n   * > **Note**: `run` performs the run phase, not other phases.\n   *\n   * @overload\n   * @param {HeadTree extends undefined ? Node : HeadTree} tree\n   * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done\n   * @returns {undefined}\n   *\n   * @overload\n   * @param {HeadTree extends undefined ? Node : HeadTree} tree\n   * @param {Compatible | undefined} file\n   * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done\n   * @returns {undefined}\n   *\n   * @overload\n   * @param {HeadTree extends undefined ? Node : HeadTree} tree\n   * @param {Compatible | undefined} [file]\n   * @returns {Promise<TailTree extends undefined ? Node : TailTree>}\n   *\n   * @param {HeadTree extends undefined ? Node : HeadTree} tree\n   *   Tree to transform and inspect.\n   * @param {(\n   *   RunCallback<TailTree extends undefined ? Node : TailTree> |\n   *   Compatible\n   * )} [file]\n   *   File associated with `node` (optional); any value accepted as `x` in\n   *   `new VFile(x)`.\n   * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} [done]\n   *   Callback (optional).\n   * @returns {Promise<TailTree extends undefined ? Node : TailTree> | undefined}\n   *   Nothing if `done` is given.\n   *   Otherwise, a promise rejected with a fatal error or resolved with the\n   *   transformed tree.\n   */\n  run(tree, file, done) {\n    assertNode(tree)\n    this.freeze()\n\n    const transformers = this.transformers\n\n    if (!done && typeof file === 'function') {\n      done = file\n      file = undefined\n    }\n\n    return done ? executor(undefined, done) : new Promise(executor)\n\n    // Note: `void`s needed for TS.\n    /**\n     * @param {(\n     *   ((tree: TailTree extends undefined ? Node : TailTree) => undefined | void) |\n     *   undefined\n     * )} resolve\n     * @param {(error: Error) => undefined | void} reject\n     * @returns {undefined}\n     */\n    function executor(resolve, reject) {\n      assert(\n        typeof file !== 'function',\n        '`file` can’t be a `done` anymore, we checked'\n      )\n      const realFile = vfile(file)\n      transformers.run(tree, realFile, realDone)\n\n      /**\n       * @param {Error | undefined} error\n       * @param {Node} outputTree\n       * @param {VFile} file\n       * @returns {undefined}\n       */\n      function realDone(error, outputTree, file) {\n        const resultingTree =\n          /** @type {TailTree extends undefined ? Node : TailTree} */ (\n            outputTree || tree\n          )\n\n        if (error) {\n          reject(error)\n        } else if (resolve) {\n          resolve(resultingTree)\n        } else {\n          assert(done, '`done` is defined if `resolve` is not')\n          done(undefined, resultingTree, file)\n        }\n      }\n    }\n  }\n\n  /**\n   * Run *transformers* on a syntax tree.\n   *\n   * An error is thrown if asynchronous transforms are configured.\n   *\n   * > **Note**: `runSync` freezes the processor if not already *frozen*.\n   *\n   * > **Note**: `runSync` performs the run phase, not other phases.\n   *\n   * @param {HeadTree extends undefined ? Node : HeadTree} tree\n   *   Tree to transform and inspect.\n   * @param {Compatible | undefined} [file]\n   *   File associated with `node` (optional); any value accepted as `x` in\n   *   `new VFile(x)`.\n   * @returns {TailTree extends undefined ? Node : TailTree}\n   *   Transformed tree.\n   */\n  runSync(tree, file) {\n    /** @type {boolean} */\n    let complete = false\n    /** @type {(TailTree extends undefined ? Node : TailTree) | undefined} */\n    let result\n\n    this.run(tree, file, realDone)\n\n    assertDone('runSync', 'run', complete)\n    assert(result, 'we either bailed on an error or have a tree')\n    return result\n\n    /**\n     * @type {RunCallback<TailTree extends undefined ? Node : TailTree>}\n     */\n    function realDone(error, tree) {\n      bail(error)\n      result = tree\n      complete = true\n    }\n  }\n\n  /**\n   * Compile a syntax tree.\n   *\n   * > **Note**: `stringify` freezes the processor if not already *frozen*.\n   *\n   * > **Note**: `stringify` performs the stringify phase, not the run phase\n   * > or other phases.\n   *\n   * @param {CompileTree extends undefined ? Node : CompileTree} tree\n   *   Tree to compile.\n   * @param {Compatible | undefined} [file]\n   *   File associated with `node` (optional); any value accepted as `x` in\n   *   `new VFile(x)`.\n   * @returns {CompileResult extends undefined ? Value : CompileResult}\n   *   Textual representation of the tree (see note).\n   *\n   *   > **Note**: unified typically compiles by serializing: most compilers\n   *   > return `string` (or `Uint8Array`).\n   *   > Some compilers, such as the one configured with\n   *   > [`rehype-react`][rehype-react], return other values (in this case, a\n   *   > React tree).\n   *   > If you’re using a compiler that doesn’t serialize, expect different\n   *   > result values.\n   *   >\n   *   > To register custom results in TypeScript, add them to\n   *   > {@linkcode CompileResultMap}.\n   *\n   *   [rehype-react]: https://github.com/rehypejs/rehype-react\n   */\n  stringify(tree, file) {\n    this.freeze()\n    const realFile = vfile(file)\n    const compiler = this.compiler || this.Compiler\n    assertCompiler('stringify', compiler)\n    assertNode(tree)\n\n    return compiler(tree, realFile)\n  }\n\n  /**\n   * Configure the processor to use a plugin, a list of usable values, or a\n   * preset.\n   *\n   * If the processor is already using a plugin, the previous plugin\n   * configuration is changed based on the options that are passed in.\n   * In other words, the plugin is not added a second time.\n   *\n   * > **Note**: `use` cannot be called on *frozen* processors.\n   * > Call the processor first to create a new unfrozen processor.\n   *\n   * @example\n   *   There are many ways to pass plugins to `.use()`.\n   *   This example gives an overview:\n   *\n   *   ```js\n   *   import {unified} from 'unified'\n   *\n   *   unified()\n   *     // Plugin with options:\n   *     .use(pluginA, {x: true, y: true})\n   *     // Passing the same plugin again merges configuration (to `{x: true, y: false, z: true}`):\n   *     .use(pluginA, {y: false, z: true})\n   *     // Plugins:\n   *     .use([pluginB, pluginC])\n   *     // Two plugins, the second with options:\n   *     .use([pluginD, [pluginE, {}]])\n   *     // Preset with plugins and settings:\n   *     .use({plugins: [pluginF, [pluginG, {}]], settings: {position: false}})\n   *     // Settings only:\n   *     .use({settings: {position: false}})\n   *   ```\n   *\n   * @template {Array<unknown>} [Parameters=[]]\n   * @template {Node | string | undefined} [Input=undefined]\n   * @template [Output=Input]\n   *\n   * @overload\n   * @param {Preset | null | undefined} [preset]\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *\n   * @overload\n   * @param {PluggableList} list\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *\n   * @overload\n   * @param {Plugin<Parameters, Input, Output>} plugin\n   * @param {...(Parameters | [boolean])} parameters\n   * @returns {UsePlugin<ParseTree, HeadTree, TailTree, CompileTree, CompileResult, Input, Output>}\n   *\n   * @param {PluggableList | Plugin | Preset | null | undefined} value\n   *   Usable value.\n   * @param {...unknown} parameters\n   *   Parameters, when a plugin is given as a usable value.\n   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}\n   *   Current processor.\n   */\n  use(value, ...parameters) {\n    const attachers = this.attachers\n    const namespace = this.namespace\n\n    assertUnfrozen('use', this.frozen)\n\n    if (value === null || value === undefined) {\n      // Empty.\n    } else if (typeof value === 'function') {\n      addPlugin(value, parameters)\n    } else if (typeof value === 'object') {\n      if (Array.isArray(value)) {\n        addList(value)\n      } else {\n        addPreset(value)\n      }\n    } else {\n      throw new TypeError('Expected usable value, not `' + value + '`')\n    }\n\n    return this\n\n    /**\n     * @param {Pluggable} value\n     * @returns {undefined}\n     */\n    function add(value) {\n      if (typeof value === 'function') {\n        addPlugin(value, [])\n      } else if (typeof value === 'object') {\n        if (Array.isArray(value)) {\n          const [plugin, ...parameters] =\n            /** @type {PluginTuple<Array<unknown>>} */ (value)\n          addPlugin(plugin, parameters)\n        } else {\n          addPreset(value)\n        }\n      } else {\n        throw new TypeError('Expected usable value, not `' + value + '`')\n      }\n    }\n\n    /**\n     * @param {Preset} result\n     * @returns {undefined}\n     */\n    function addPreset(result) {\n      if (!('plugins' in result) && !('settings' in result)) {\n        throw new Error(\n          'Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither'\n        )\n      }\n\n      addList(result.plugins)\n\n      if (result.settings) {\n        namespace.settings = extend(true, namespace.settings, result.settings)\n      }\n    }\n\n    /**\n     * @param {PluggableList | null | undefined} plugins\n     * @returns {undefined}\n     */\n    function addList(plugins) {\n      let index = -1\n\n      if (plugins === null || plugins === undefined) {\n        // Empty.\n      } else if (Array.isArray(plugins)) {\n        while (++index < plugins.length) {\n          const thing = plugins[index]\n          add(thing)\n        }\n      } else {\n        throw new TypeError('Expected a list of plugins, not `' + plugins + '`')\n      }\n    }\n\n    /**\n     * @param {Plugin} plugin\n     * @param {Array<unknown>} parameters\n     * @returns {undefined}\n     */\n    function addPlugin(plugin, parameters) {\n      let index = -1\n      let entryIndex = -1\n\n      while (++index < attachers.length) {\n        if (attachers[index][0] === plugin) {\n          entryIndex = index\n          break\n        }\n      }\n\n      if (entryIndex === -1) {\n        attachers.push([plugin, ...parameters])\n      }\n      // Only set if there was at least a `primary` value, otherwise we’d change\n      // `arguments.length`.\n      else if (parameters.length > 0) {\n        let [primary, ...rest] = parameters\n        const currentPrimary = attachers[entryIndex][1]\n        if (isPlainObj(currentPrimary) && isPlainObj(primary)) {\n          primary = extend(true, currentPrimary, primary)\n        }\n\n        attachers[entryIndex] = [plugin, primary, ...rest]\n      }\n    }\n  }\n}\n\n// Note: this returns a *callable* instance.\n// That’s why it’s documented as a function.\n/**\n * Create a new processor.\n *\n * @example\n *   This example shows how a new processor can be created (from `remark`) and linked\n *   to **stdin**(4) and **stdout**(4).\n *\n *   ```js\n *   import process from 'node:process'\n *   import concatStream from 'concat-stream'\n *   import {remark} from 'remark'\n *\n *   process.stdin.pipe(\n *     concatStream(function (buf) {\n *       process.stdout.write(String(remark().processSync(buf)))\n *     })\n *   )\n *   ```\n *\n * @returns\n *   New *unfrozen* processor (`processor`).\n *\n *   This processor is configured to work the same as its ancestor.\n *   When the descendant processor is configured in the future it does not\n *   affect the ancestral processor.\n */\nexport const unified = new Processor().freeze()\n\n/**\n * Assert a parser is available.\n *\n * @param {string} name\n * @param {unknown} value\n * @returns {asserts value is Parser}\n */\nfunction assertParser(name, value) {\n  if (typeof value !== 'function') {\n    throw new TypeError('Cannot `' + name + '` without `parser`')\n  }\n}\n\n/**\n * Assert a compiler is available.\n *\n * @param {string} name\n * @param {unknown} value\n * @returns {asserts value is Compiler}\n */\nfunction assertCompiler(name, value) {\n  if (typeof value !== 'function') {\n    throw new TypeError('Cannot `' + name + '` without `compiler`')\n  }\n}\n\n/**\n * Assert the processor is not frozen.\n *\n * @param {string} name\n * @param {unknown} frozen\n * @returns {asserts frozen is false}\n */\nfunction assertUnfrozen(name, frozen) {\n  if (frozen) {\n    throw new Error(\n      'Cannot call `' +\n        name +\n        '` on a frozen processor.\\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.'\n    )\n  }\n}\n\n/**\n * Assert `node` is a unist node.\n *\n * @param {unknown} node\n * @returns {asserts node is Node}\n */\nfunction assertNode(node) {\n  // `isPlainObj` unfortunately uses `any` instead of `unknown`.\n  // type-coverage:ignore-next-line\n  if (!isPlainObj(node) || typeof node.type !== 'string') {\n    throw new TypeError('Expected node, got `' + node + '`')\n    // Fine.\n  }\n}\n\n/**\n * Assert that `complete` is `true`.\n *\n * @param {string} name\n * @param {string} asyncName\n * @param {unknown} complete\n * @returns {asserts complete is true}\n */\nfunction assertDone(name, asyncName, complete) {\n  if (!complete) {\n    throw new Error(\n      '`' + name + '` finished async. Use `' + asyncName + '` instead'\n    )\n  }\n}\n\n/**\n * @param {Compatible | undefined} [value]\n * @returns {VFile}\n */\nfunction vfile(value) {\n  return looksLikeAVFile(value) ? value : new VFile(value)\n}\n\n/**\n * @param {Compatible | undefined} [value]\n * @returns {value is VFile}\n */\nfunction looksLikeAVFile(value) {\n  return Boolean(\n    value &&\n      typeof value === 'object' &&\n      'message' in value &&\n      'messages' in value\n  )\n}\n\n/**\n * @param {unknown} [value]\n * @returns {value is Value}\n */\nfunction looksLikeAValue(value) {\n  return typeof value === 'string' || isUint8Array(value)\n}\n\n/**\n * Assert `value` is an `Uint8Array`.\n *\n * @param {unknown} value\n *   thing.\n * @returns {value is Uint8Array}\n *   Whether `value` is an `Uint8Array`.\n */\nfunction isUint8Array(value) {\n  return Boolean(\n    value &&\n      typeof value === 'object' &&\n      'byteLength' in value &&\n      'byteOffset' in value\n  )\n}\n","export default function isPlainObject(value) {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);\n}\n","// To do: remove `void`s\n// To do: remove `null` from output of our APIs, allow it as user APIs.\n\n/**\n * @typedef {(error?: Error | null | undefined, ...output: Array<any>) => void} Callback\n *   Callback.\n *\n * @typedef {(...input: Array<any>) => any} Middleware\n *   Ware.\n *\n * @typedef Pipeline\n *   Pipeline.\n * @property {Run} run\n *   Run the pipeline.\n * @property {Use} use\n *   Add middleware.\n *\n * @typedef {(...input: Array<any>) => void} Run\n *   Call all middleware.\n *\n *   Calls `done` on completion with either an error or the output of the\n *   last middleware.\n *\n *   > 👉 **Note**: as the length of input defines whether async functions get a\n *   > `next` function,\n *   > it’s recommended to keep `input` at one value normally.\n\n *\n * @typedef {(fn: Middleware) => Pipeline} Use\n *   Add middleware.\n */\n\n/**\n * Create new middleware.\n *\n * @returns {Pipeline}\n *   Pipeline.\n */\nexport function trough() {\n  /** @type {Array<Middleware>} */\n  const fns = []\n  /** @type {Pipeline} */\n  const pipeline = {run, use}\n\n  return pipeline\n\n  /** @type {Run} */\n  function run(...values) {\n    let middlewareIndex = -1\n    /** @type {Callback} */\n    const callback = values.pop()\n\n    if (typeof callback !== 'function') {\n      throw new TypeError('Expected function as last argument, not ' + callback)\n    }\n\n    next(null, ...values)\n\n    /**\n     * Run the next `fn`, or we’re done.\n     *\n     * @param {Error | null | undefined} error\n     * @param {Array<any>} output\n     */\n    function next(error, ...output) {\n      const fn = fns[++middlewareIndex]\n      let index = -1\n\n      if (error) {\n        callback(error)\n        return\n      }\n\n      // Copy non-nullish input into values.\n      while (++index < values.length) {\n        if (output[index] === null || output[index] === undefined) {\n          output[index] = values[index]\n        }\n      }\n\n      // Save the newly created `output` for the next call.\n      values = output\n\n      // Next or done.\n      if (fn) {\n        wrap(fn, next)(...output)\n      } else {\n        callback(null, ...output)\n      }\n    }\n  }\n\n  /** @type {Use} */\n  function use(middelware) {\n    if (typeof middelware !== 'function') {\n      throw new TypeError(\n        'Expected `middelware` to be a function, not ' + middelware\n      )\n    }\n\n    fns.push(middelware)\n    return pipeline\n  }\n}\n\n/**\n * Wrap `middleware` into a uniform interface.\n *\n * You can pass all input to the resulting function.\n * `callback` is then called with the output of `middleware`.\n *\n * If `middleware` accepts more arguments than the later given in input,\n * an extra `done` function is passed to it after that input,\n * which must be called by `middleware`.\n *\n * The first value in `input` is the main input value.\n * All other input values are the rest input values.\n * The values given to `callback` are the input values,\n * merged with every non-nullish output value.\n *\n * * if `middleware` throws an error,\n *   returns a promise that is rejected,\n *   or calls the given `done` function with an error,\n *   `callback` is called with that error\n * * if `middleware` returns a value or returns a promise that is resolved,\n *   that value is the main output value\n * * if `middleware` calls `done`,\n *   all non-nullish values except for the first one (the error) overwrite the\n *   output values\n *\n * @param {Middleware} middleware\n *   Function to wrap.\n * @param {Callback} callback\n *   Callback called with the output of `middleware`.\n * @returns {Run}\n *   Wrapped middleware.\n */\nexport function wrap(middleware, callback) {\n  /** @type {boolean} */\n  let called\n\n  return wrapped\n\n  /**\n   * Call `middleware`.\n   * @this {any}\n   * @param {Array<any>} parameters\n   * @returns {void}\n   */\n  function wrapped(...parameters) {\n    const fnExpectsCallback = middleware.length > parameters.length\n    /** @type {any} */\n    let result\n\n    if (fnExpectsCallback) {\n      parameters.push(done)\n    }\n\n    try {\n      result = middleware.apply(this, parameters)\n    } catch (error) {\n      const exception = /** @type {Error} */ (error)\n\n      // Well, this is quite the pickle.\n      // `middleware` received a callback and called it synchronously, but that\n      // threw an error.\n      // The only thing left to do is to throw the thing instead.\n      if (fnExpectsCallback && called) {\n        throw exception\n      }\n\n      return done(exception)\n    }\n\n    if (!fnExpectsCallback) {\n      if (result && result.then && typeof result.then === 'function') {\n        result.then(then, done)\n      } else if (result instanceof Error) {\n        done(result)\n      } else {\n        then(result)\n      }\n    }\n  }\n\n  /**\n   * Call `callback`, only once.\n   *\n   * @type {Callback}\n   */\n  function done(error, ...output) {\n    if (!called) {\n      called = true\n      callback(error, ...output)\n    }\n  }\n\n  /**\n   * Call `done` with one value.\n   *\n   * @param {any} [value]\n   */\n  function then(value) {\n    done(null, value)\n  }\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Point} Point\n * @typedef {import('unist').Position} Position\n */\n\n/**\n * @typedef NodeLike\n * @property {string} type\n * @property {PositionLike | null | undefined} [position]\n *\n * @typedef PointLike\n * @property {number | null | undefined} [line]\n * @property {number | null | undefined} [column]\n * @property {number | null | undefined} [offset]\n *\n * @typedef PositionLike\n * @property {PointLike | null | undefined} [start]\n * @property {PointLike | null | undefined} [end]\n */\n\n/**\n * Serialize the positional info of a point, position (start and end points),\n * or node.\n *\n * @param {Node | NodeLike | Point | PointLike | Position | PositionLike | null | undefined} [value]\n *   Node, position, or point.\n * @returns {string}\n *   Pretty printed positional info of a node (`string`).\n *\n *   In the format of a range `ls:cs-le:ce` (when given `node` or `position`)\n *   or a point `l:c` (when given `point`), where `l` stands for line, `c` for\n *   column, `s` for `start`, and `e` for end.\n *   An empty string (`''`) is returned if the given value is neither `node`,\n *   `position`, nor `point`.\n */\nexport function stringifyPosition(value) {\n  // Nothing.\n  if (!value || typeof value !== 'object') {\n    return ''\n  }\n\n  // Node.\n  if ('position' in value || 'type' in value) {\n    return position(value.position)\n  }\n\n  // Position.\n  if ('start' in value || 'end' in value) {\n    return position(value)\n  }\n\n  // Point.\n  if ('line' in value || 'column' in value) {\n    return point(value)\n  }\n\n  // ?\n  return ''\n}\n\n/**\n * @param {Point | PointLike | null | undefined} point\n * @returns {string}\n */\nfunction point(point) {\n  return index(point && point.line) + ':' + index(point && point.column)\n}\n\n/**\n * @param {Position | PositionLike | null | undefined} pos\n * @returns {string}\n */\nfunction position(pos) {\n  return point(pos && pos.start) + '-' + point(pos && pos.end)\n}\n\n/**\n * @param {number | null | undefined} value\n * @returns {number}\n */\nfunction index(value) {\n  return value && typeof value === 'number' ? value : 1\n}\n","/**\n * @import {Node, Point, Position} from 'unist'\n */\n\n/**\n * @typedef {object & {type: string, position?: Position | undefined}} NodeLike\n *\n * @typedef Options\n *   Configuration.\n * @property {Array<Node> | null | undefined} [ancestors]\n *   Stack of (inclusive) ancestor nodes surrounding the message (optional).\n * @property {Error | null | undefined} [cause]\n *   Original error cause of the message (optional).\n * @property {Point | Position | null | undefined} [place]\n *   Place of message (optional).\n * @property {string | null | undefined} [ruleId]\n *   Category of message (optional, example: `'my-rule'`).\n * @property {string | null | undefined} [source]\n *   Namespace of who sent the message (optional, example: `'my-package'`).\n */\n\nimport {stringifyPosition} from 'unist-util-stringify-position'\n\n/**\n * Message.\n */\nexport class VFileMessage extends Error {\n  /**\n   * Create a message for `reason`.\n   *\n   * > 🪦 **Note**: also has obsolete signatures.\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Options | null | undefined} [options]\n   * @returns\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns\n   *\n   * @overload\n   * @param {string} reason\n   * @param {string | null | undefined} [origin]\n   * @returns\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {string | null | undefined} [origin]\n   * @returns\n   *\n   * @param {Error | VFileMessage | string} causeOrReason\n   *   Reason for message, should use markdown.\n   * @param {Node | NodeLike | Options | Point | Position | string | null | undefined} [optionsOrParentOrPlace]\n   *   Configuration (optional).\n   * @param {string | null | undefined} [origin]\n   *   Place in code where the message originates (example:\n   *   `'my-package:my-rule'` or `'my-rule'`).\n   * @returns\n   *   Instance of `VFileMessage`.\n   */\n  // eslint-disable-next-line complexity\n  constructor(causeOrReason, optionsOrParentOrPlace, origin) {\n    super()\n\n    if (typeof optionsOrParentOrPlace === 'string') {\n      origin = optionsOrParentOrPlace\n      optionsOrParentOrPlace = undefined\n    }\n\n    /** @type {string} */\n    let reason = ''\n    /** @type {Options} */\n    let options = {}\n    let legacyCause = false\n\n    if (optionsOrParentOrPlace) {\n      // Point.\n      if (\n        'line' in optionsOrParentOrPlace &&\n        'column' in optionsOrParentOrPlace\n      ) {\n        options = {place: optionsOrParentOrPlace}\n      }\n      // Position.\n      else if (\n        'start' in optionsOrParentOrPlace &&\n        'end' in optionsOrParentOrPlace\n      ) {\n        options = {place: optionsOrParentOrPlace}\n      }\n      // Node.\n      else if ('type' in optionsOrParentOrPlace) {\n        options = {\n          ancestors: [optionsOrParentOrPlace],\n          place: optionsOrParentOrPlace.position\n        }\n      }\n      // Options.\n      else {\n        options = {...optionsOrParentOrPlace}\n      }\n    }\n\n    if (typeof causeOrReason === 'string') {\n      reason = causeOrReason\n    }\n    // Error.\n    else if (!options.cause && causeOrReason) {\n      legacyCause = true\n      reason = causeOrReason.message\n      options.cause = causeOrReason\n    }\n\n    if (!options.ruleId && !options.source && typeof origin === 'string') {\n      const index = origin.indexOf(':')\n\n      if (index === -1) {\n        options.ruleId = origin\n      } else {\n        options.source = origin.slice(0, index)\n        options.ruleId = origin.slice(index + 1)\n      }\n    }\n\n    if (!options.place && options.ancestors && options.ancestors) {\n      const parent = options.ancestors[options.ancestors.length - 1]\n\n      if (parent) {\n        options.place = parent.position\n      }\n    }\n\n    const start =\n      options.place && 'start' in options.place\n        ? options.place.start\n        : options.place\n\n    /**\n     * Stack of ancestor nodes surrounding the message.\n     *\n     * @type {Array<Node> | undefined}\n     */\n    this.ancestors = options.ancestors || undefined\n\n    /**\n     * Original error cause of the message.\n     *\n     * @type {Error | undefined}\n     */\n    this.cause = options.cause || undefined\n\n    /**\n     * Starting column of message.\n     *\n     * @type {number | undefined}\n     */\n    this.column = start ? start.column : undefined\n\n    /**\n     * State of problem.\n     *\n     * * `true` — error, file not usable\n     * * `false` — warning, change may be needed\n     * * `undefined` — change likely not needed\n     *\n     * @type {boolean | null | undefined}\n     */\n    this.fatal = undefined\n\n    /**\n     * Path of a file (used throughout the `VFile` ecosystem).\n     *\n     * @type {string | undefined}\n     */\n    this.file = ''\n\n    // Field from `Error`.\n    /**\n     * Reason for message.\n     *\n     * @type {string}\n     */\n    this.message = reason\n\n    /**\n     * Starting line of error.\n     *\n     * @type {number | undefined}\n     */\n    this.line = start ? start.line : undefined\n\n    // Field from `Error`.\n    /**\n     * Serialized positional info of message.\n     *\n     * On normal errors, this would be something like `ParseError`, buit in\n     * `VFile` messages we use this space to show where an error happened.\n     */\n    this.name = stringifyPosition(options.place) || '1:1'\n\n    /**\n     * Place of message.\n     *\n     * @type {Point | Position | undefined}\n     */\n    this.place = options.place || undefined\n\n    /**\n     * Reason for message, should use markdown.\n     *\n     * @type {string}\n     */\n    this.reason = this.message\n\n    /**\n     * Category of message (example: `'my-rule'`).\n     *\n     * @type {string | undefined}\n     */\n    this.ruleId = options.ruleId || undefined\n\n    /**\n     * Namespace of message (example: `'my-package'`).\n     *\n     * @type {string | undefined}\n     */\n    this.source = options.source || undefined\n\n    // Field from `Error`.\n    /**\n     * Stack of message.\n     *\n     * This is used by normal errors to show where something happened in\n     * programming code, irrelevant for `VFile` messages,\n     *\n     * @type {string}\n     */\n    this.stack =\n      legacyCause && options.cause && typeof options.cause.stack === 'string'\n        ? options.cause.stack\n        : ''\n\n    // The following fields are “well known”.\n    // Not standard.\n    // Feel free to add other non-standard fields to your messages.\n\n    /**\n     * Specify the source value that’s being reported, which is deemed\n     * incorrect.\n     *\n     * @type {string | undefined}\n     */\n    this.actual = undefined\n\n    /**\n     * Suggest acceptable values that can be used instead of `actual`.\n     *\n     * @type {Array<string> | undefined}\n     */\n    this.expected = undefined\n\n    /**\n     * Long form description of the message (you should use markdown).\n     *\n     * @type {string | undefined}\n     */\n    this.note = undefined\n\n    /**\n     * Link to docs for the message.\n     *\n     * > 👉 **Note**: this must be an absolute URL that can be passed as `x`\n     * > to `new URL(x)`.\n     *\n     * @type {string | undefined}\n     */\n    this.url = undefined\n  }\n}\n\nVFileMessage.prototype.file = ''\nVFileMessage.prototype.name = ''\nVFileMessage.prototype.reason = ''\nVFileMessage.prototype.message = ''\nVFileMessage.prototype.stack = ''\nVFileMessage.prototype.column = undefined\nVFileMessage.prototype.line = undefined\nVFileMessage.prototype.ancestors = undefined\nVFileMessage.prototype.cause = undefined\nVFileMessage.prototype.fatal = undefined\nVFileMessage.prototype.place = undefined\nVFileMessage.prototype.ruleId = undefined\nVFileMessage.prototype.source = undefined\n","// A derivative work based on:\n// <https://github.com/browserify/path-browserify>.\n// Which is licensed:\n//\n// MIT License\n//\n// Copyright (c) 2013 James Halliday\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of\n// this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to\n// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n// the Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A derivative work based on:\n//\n// Parts of that are extracted from Node’s internal `path` module:\n// <https://github.com/nodejs/node/blob/master/lib/path.js>.\n// Which is licensed:\n//\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nexport const minpath = {basename, dirname, extname, join, sep: '/'}\n\n/* eslint-disable max-depth, complexity */\n\n/**\n * Get the basename from a path.\n *\n * @param {string} path\n *   File path.\n * @param {string | null | undefined} [extname]\n *   Extension to strip.\n * @returns {string}\n *   Stem or basename.\n */\nfunction basename(path, extname) {\n  if (extname !== undefined && typeof extname !== 'string') {\n    throw new TypeError('\"ext\" argument must be a string')\n  }\n\n  assertPath(path)\n  let start = 0\n  let end = -1\n  let index = path.length\n  /** @type {boolean | undefined} */\n  let seenNonSlash\n\n  if (\n    extname === undefined ||\n    extname.length === 0 ||\n    extname.length > path.length\n  ) {\n    while (index--) {\n      if (path.codePointAt(index) === 47 /* `/` */) {\n        // If we reached a path separator that was not part of a set of path\n        // separators at the end of the string, stop now.\n        if (seenNonSlash) {\n          start = index + 1\n          break\n        }\n      } else if (end < 0) {\n        // We saw the first non-path separator, mark this as the end of our\n        // path component.\n        seenNonSlash = true\n        end = index + 1\n      }\n    }\n\n    return end < 0 ? '' : path.slice(start, end)\n  }\n\n  if (extname === path) {\n    return ''\n  }\n\n  let firstNonSlashEnd = -1\n  let extnameIndex = extname.length - 1\n\n  while (index--) {\n    if (path.codePointAt(index) === 47 /* `/` */) {\n      // If we reached a path separator that was not part of a set of path\n      // separators at the end of the string, stop now.\n      if (seenNonSlash) {\n        start = index + 1\n        break\n      }\n    } else {\n      if (firstNonSlashEnd < 0) {\n        // We saw the first non-path separator, remember this index in case\n        // we need it if the extension ends up not matching.\n        seenNonSlash = true\n        firstNonSlashEnd = index + 1\n      }\n\n      if (extnameIndex > -1) {\n        // Try to match the explicit extension.\n        if (path.codePointAt(index) === extname.codePointAt(extnameIndex--)) {\n          if (extnameIndex < 0) {\n            // We matched the extension, so mark this as the end of our path\n            // component\n            end = index\n          }\n        } else {\n          // Extension does not match, so our result is the entire path\n          // component\n          extnameIndex = -1\n          end = firstNonSlashEnd\n        }\n      }\n    }\n  }\n\n  if (start === end) {\n    end = firstNonSlashEnd\n  } else if (end < 0) {\n    end = path.length\n  }\n\n  return path.slice(start, end)\n}\n\n/**\n * Get the dirname from a path.\n *\n * @param {string} path\n *   File path.\n * @returns {string}\n *   File path.\n */\nfunction dirname(path) {\n  assertPath(path)\n\n  if (path.length === 0) {\n    return '.'\n  }\n\n  let end = -1\n  let index = path.length\n  /** @type {boolean | undefined} */\n  let unmatchedSlash\n\n  // Prefix `--` is important to not run on `0`.\n  while (--index) {\n    if (path.codePointAt(index) === 47 /* `/` */) {\n      if (unmatchedSlash) {\n        end = index\n        break\n      }\n    } else if (!unmatchedSlash) {\n      // We saw the first non-path separator\n      unmatchedSlash = true\n    }\n  }\n\n  return end < 0\n    ? path.codePointAt(0) === 47 /* `/` */\n      ? '/'\n      : '.'\n    : end === 1 && path.codePointAt(0) === 47 /* `/` */\n      ? '//'\n      : path.slice(0, end)\n}\n\n/**\n * Get an extname from a path.\n *\n * @param {string} path\n *   File path.\n * @returns {string}\n *   Extname.\n */\nfunction extname(path) {\n  assertPath(path)\n\n  let index = path.length\n\n  let end = -1\n  let startPart = 0\n  let startDot = -1\n  // Track the state of characters (if any) we see before our first dot and\n  // after any path separator we find.\n  let preDotState = 0\n  /** @type {boolean | undefined} */\n  let unmatchedSlash\n\n  while (index--) {\n    const code = path.codePointAt(index)\n\n    if (code === 47 /* `/` */) {\n      // If we reached a path separator that was not part of a set of path\n      // separators at the end of the string, stop now.\n      if (unmatchedSlash) {\n        startPart = index + 1\n        break\n      }\n\n      continue\n    }\n\n    if (end < 0) {\n      // We saw the first non-path separator, mark this as the end of our\n      // extension.\n      unmatchedSlash = true\n      end = index + 1\n    }\n\n    if (code === 46 /* `.` */) {\n      // If this is our first dot, mark it as the start of our extension.\n      if (startDot < 0) {\n        startDot = index\n      } else if (preDotState !== 1) {\n        preDotState = 1\n      }\n    } else if (startDot > -1) {\n      // We saw a non-dot and non-path separator before our dot, so we should\n      // have a good chance at having a non-empty extension.\n      preDotState = -1\n    }\n  }\n\n  if (\n    startDot < 0 ||\n    end < 0 ||\n    // We saw a non-dot character immediately before the dot.\n    preDotState === 0 ||\n    // The (right-most) trimmed path component is exactly `..`.\n    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)\n  ) {\n    return ''\n  }\n\n  return path.slice(startDot, end)\n}\n\n/**\n * Join segments from a path.\n *\n * @param {Array<string>} segments\n *   Path segments.\n * @returns {string}\n *   File path.\n */\nfunction join(...segments) {\n  let index = -1\n  /** @type {string | undefined} */\n  let joined\n\n  while (++index < segments.length) {\n    assertPath(segments[index])\n\n    if (segments[index]) {\n      joined =\n        joined === undefined ? segments[index] : joined + '/' + segments[index]\n    }\n  }\n\n  return joined === undefined ? '.' : normalize(joined)\n}\n\n/**\n * Normalize a basic file path.\n *\n * @param {string} path\n *   File path.\n * @returns {string}\n *   File path.\n */\n// Note: `normalize` is not exposed as `path.normalize`, so some code is\n// manually removed from it.\nfunction normalize(path) {\n  assertPath(path)\n\n  const absolute = path.codePointAt(0) === 47 /* `/` */\n\n  // Normalize the path according to POSIX rules.\n  let value = normalizeString(path, !absolute)\n\n  if (value.length === 0 && !absolute) {\n    value = '.'\n  }\n\n  if (value.length > 0 && path.codePointAt(path.length - 1) === 47 /* / */) {\n    value += '/'\n  }\n\n  return absolute ? '/' + value : value\n}\n\n/**\n * Resolve `.` and `..` elements in a path with directory names.\n *\n * @param {string} path\n *   File path.\n * @param {boolean} allowAboveRoot\n *   Whether `..` can move above root.\n * @returns {string}\n *   File path.\n */\nfunction normalizeString(path, allowAboveRoot) {\n  let result = ''\n  let lastSegmentLength = 0\n  let lastSlash = -1\n  let dots = 0\n  let index = -1\n  /** @type {number | undefined} */\n  let code\n  /** @type {number} */\n  let lastSlashIndex\n\n  while (++index <= path.length) {\n    if (index < path.length) {\n      code = path.codePointAt(index)\n    } else if (code === 47 /* `/` */) {\n      break\n    } else {\n      code = 47 /* `/` */\n    }\n\n    if (code === 47 /* `/` */) {\n      if (lastSlash === index - 1 || dots === 1) {\n        // Empty.\n      } else if (lastSlash !== index - 1 && dots === 2) {\n        if (\n          result.length < 2 ||\n          lastSegmentLength !== 2 ||\n          result.codePointAt(result.length - 1) !== 46 /* `.` */ ||\n          result.codePointAt(result.length - 2) !== 46 /* `.` */\n        ) {\n          if (result.length > 2) {\n            lastSlashIndex = result.lastIndexOf('/')\n\n            if (lastSlashIndex !== result.length - 1) {\n              if (lastSlashIndex < 0) {\n                result = ''\n                lastSegmentLength = 0\n              } else {\n                result = result.slice(0, lastSlashIndex)\n                lastSegmentLength = result.length - 1 - result.lastIndexOf('/')\n              }\n\n              lastSlash = index\n              dots = 0\n              continue\n            }\n          } else if (result.length > 0) {\n            result = ''\n            lastSegmentLength = 0\n            lastSlash = index\n            dots = 0\n            continue\n          }\n        }\n\n        if (allowAboveRoot) {\n          result = result.length > 0 ? result + '/..' : '..'\n          lastSegmentLength = 2\n        }\n      } else {\n        if (result.length > 0) {\n          result += '/' + path.slice(lastSlash + 1, index)\n        } else {\n          result = path.slice(lastSlash + 1, index)\n        }\n\n        lastSegmentLength = index - lastSlash - 1\n      }\n\n      lastSlash = index\n      dots = 0\n    } else if (code === 46 /* `.` */ && dots > -1) {\n      dots++\n    } else {\n      dots = -1\n    }\n  }\n\n  return result\n}\n\n/**\n * Make sure `path` is a string.\n *\n * @param {string} path\n *   File path.\n * @returns {asserts path is string}\n *   Nothing.\n */\nfunction assertPath(path) {\n  if (typeof path !== 'string') {\n    throw new TypeError(\n      'Path must be a string. Received ' + JSON.stringify(path)\n    )\n  }\n}\n\n/* eslint-enable max-depth, complexity */\n","// Somewhat based on:\n// <https://github.com/defunctzombie/node-process/blob/master/browser.js>.\n// But I don’t think one tiny line of code can be copyrighted. 😅\nexport const minproc = {cwd}\n\nfunction cwd() {\n  return '/'\n}\n","/**\n * Checks if a value has the shape of a WHATWG URL object.\n *\n * Using a symbol or instanceof would not be able to recognize URL objects\n * coming from other implementations (e.g. in Electron), so instead we are\n * checking some well known properties for a lack of a better test.\n *\n * We use `href` and `protocol` as they are the only properties that are\n * easy to retrieve and calculate due to the lazy nature of the getters.\n *\n * We check for auth attribute to distinguish legacy url instance with\n * WHATWG URL instance.\n *\n * @param {unknown} fileUrlOrPath\n *   File path or URL.\n * @returns {fileUrlOrPath is URL}\n *   Whether it’s a URL.\n */\n// From: <https://github.com/nodejs/node/blob/6a3403c/lib/internal/url.js#L720>\nexport function isUrl(fileUrlOrPath) {\n  return Boolean(\n    fileUrlOrPath !== null &&\n      typeof fileUrlOrPath === 'object' &&\n      'href' in fileUrlOrPath &&\n      fileUrlOrPath.href &&\n      'protocol' in fileUrlOrPath &&\n      fileUrlOrPath.protocol &&\n      // @ts-expect-error: indexing is fine.\n      fileUrlOrPath.auth === undefined\n  )\n}\n","import {isUrl} from './minurl.shared.js'\n\nexport {isUrl} from './minurl.shared.js'\n\n// See: <https://github.com/nodejs/node/blob/6a3403c/lib/internal/url.js>\n\n/**\n * @param {URL | string} path\n *   File URL.\n * @returns {string}\n *   File URL.\n */\nexport function urlToPath(path) {\n  if (typeof path === 'string') {\n    path = new URL(path)\n  } else if (!isUrl(path)) {\n    /** @type {NodeJS.ErrnoException} */\n    const error = new TypeError(\n      'The \"path\" argument must be of type string or an instance of URL. Received `' +\n        path +\n        '`'\n    )\n    error.code = 'ERR_INVALID_ARG_TYPE'\n    throw error\n  }\n\n  if (path.protocol !== 'file:') {\n    /** @type {NodeJS.ErrnoException} */\n    const error = new TypeError('The URL must be of scheme file')\n    error.code = 'ERR_INVALID_URL_SCHEME'\n    throw error\n  }\n\n  return getPathFromURLPosix(path)\n}\n\n/**\n * Get a path from a POSIX URL.\n *\n * @param {URL} url\n *   URL.\n * @returns {string}\n *   File path.\n */\nfunction getPathFromURLPosix(url) {\n  if (url.hostname !== '') {\n    /** @type {NodeJS.ErrnoException} */\n    const error = new TypeError(\n      'File URL host must be \"localhost\" or empty on darwin'\n    )\n    error.code = 'ERR_INVALID_FILE_URL_HOST'\n    throw error\n  }\n\n  const pathname = url.pathname\n  let index = -1\n\n  while (++index < pathname.length) {\n    if (\n      pathname.codePointAt(index) === 37 /* `%` */ &&\n      pathname.codePointAt(index + 1) === 50 /* `2` */\n    ) {\n      const third = pathname.codePointAt(index + 2)\n      if (third === 70 /* `F` */ || third === 102 /* `f` */) {\n        /** @type {NodeJS.ErrnoException} */\n        const error = new TypeError(\n          'File URL path must not include encoded / characters'\n        )\n        error.code = 'ERR_INVALID_FILE_URL_PATH'\n        throw error\n      }\n    }\n  }\n\n  return decodeURIComponent(pathname)\n}\n","/**\n * @import {Node, Point, Position} from 'unist'\n * @import {Options as MessageOptions} from 'vfile-message'\n * @import {Compatible, Data, Map, Options, Value} from 'vfile'\n */\n\n/**\n * @typedef {object & {type: string, position?: Position | undefined}} NodeLike\n */\n\nimport {VFileMessage} from 'vfile-message'\nimport {minpath} from '#minpath'\nimport {minproc} from '#minproc'\nimport {urlToPath, isUrl} from '#minurl'\n\n/**\n * Order of setting (least specific to most), we need this because otherwise\n * `{stem: 'a', path: '~/b.js'}` would throw, as a path is needed before a\n * stem can be set.\n */\nconst order = /** @type {const} */ ([\n  'history',\n  'path',\n  'basename',\n  'stem',\n  'extname',\n  'dirname'\n])\n\nexport class VFile {\n  /**\n   * Create a new virtual file.\n   *\n   * `options` is treated as:\n   *\n   * *   `string` or `Uint8Array` — `{value: options}`\n   * *   `URL` — `{path: options}`\n   * *   `VFile` — shallow copies its data over to the new file\n   * *   `object` — all fields are shallow copied over to the new file\n   *\n   * Path related fields are set in the following order (least specific to\n   * most specific): `history`, `path`, `basename`, `stem`, `extname`,\n   * `dirname`.\n   *\n   * You cannot set `dirname` or `extname` without setting either `history`,\n   * `path`, `basename`, or `stem` too.\n   *\n   * @param {Compatible | null | undefined} [value]\n   *   File value.\n   * @returns\n   *   New instance.\n   */\n  constructor(value) {\n    /** @type {Options | VFile} */\n    let options\n\n    if (!value) {\n      options = {}\n    } else if (isUrl(value)) {\n      options = {path: value}\n    } else if (typeof value === 'string' || isUint8Array(value)) {\n      options = {value}\n    } else {\n      options = value\n    }\n\n    /* eslint-disable no-unused-expressions */\n\n    /**\n     * Base of `path` (default: `process.cwd()` or `'/'` in browsers).\n     *\n     * @type {string}\n     */\n    // Prevent calling `cwd` (which could be expensive) if it’s not needed;\n    // the empty string will be overridden in the next block.\n    this.cwd = 'cwd' in options ? '' : minproc.cwd()\n\n    /**\n     * Place to store custom info (default: `{}`).\n     *\n     * It’s OK to store custom data directly on the file but moving it to\n     * `data` is recommended.\n     *\n     * @type {Data}\n     */\n    this.data = {}\n\n    /**\n     * List of file paths the file moved between.\n     *\n     * The first is the original path and the last is the current path.\n     *\n     * @type {Array<string>}\n     */\n    this.history = []\n\n    /**\n     * List of messages associated with the file.\n     *\n     * @type {Array<VFileMessage>}\n     */\n    this.messages = []\n\n    /**\n     * Raw value.\n     *\n     * @type {Value}\n     */\n    this.value\n\n    // The below are non-standard, they are “well-known”.\n    // As in, used in several tools.\n    /**\n     * Source map.\n     *\n     * This type is equivalent to the `RawSourceMap` type from the `source-map`\n     * module.\n     *\n     * @type {Map | null | undefined}\n     */\n    this.map\n\n    /**\n     * Custom, non-string, compiled, representation.\n     *\n     * This is used by unified to store non-string results.\n     * One example is when turning markdown into React nodes.\n     *\n     * @type {unknown}\n     */\n    this.result\n\n    /**\n     * Whether a file was saved to disk.\n     *\n     * This is used by vfile reporters.\n     *\n     * @type {boolean}\n     */\n    this.stored\n    /* eslint-enable no-unused-expressions */\n\n    // Set path related properties in the correct order.\n    let index = -1\n\n    while (++index < order.length) {\n      const field = order[index]\n\n      // Note: we specifically use `in` instead of `hasOwnProperty` to accept\n      // `vfile`s too.\n      if (\n        field in options &&\n        options[field] !== undefined &&\n        options[field] !== null\n      ) {\n        // @ts-expect-error: TS doesn’t understand basic reality.\n        this[field] = field === 'history' ? [...options[field]] : options[field]\n      }\n    }\n\n    /** @type {string} */\n    let field\n\n    // Set non-path related properties.\n    for (field in options) {\n      // @ts-expect-error: fine to set other things.\n      if (!order.includes(field)) {\n        // @ts-expect-error: fine to set other things.\n        this[field] = options[field]\n      }\n    }\n  }\n\n  /**\n   * Get the basename (including extname) (example: `'index.min.js'`).\n   *\n   * @returns {string | undefined}\n   *   Basename.\n   */\n  get basename() {\n    return typeof this.path === 'string'\n      ? minpath.basename(this.path)\n      : undefined\n  }\n\n  /**\n   * Set basename (including extname) (`'index.min.js'`).\n   *\n   * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\\'`\n   * on windows).\n   * Cannot be nullified (use `file.path = file.dirname` instead).\n   *\n   * @param {string} basename\n   *   Basename.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  set basename(basename) {\n    assertNonEmpty(basename, 'basename')\n    assertPart(basename, 'basename')\n    this.path = minpath.join(this.dirname || '', basename)\n  }\n\n  /**\n   * Get the parent path (example: `'~'`).\n   *\n   * @returns {string | undefined}\n   *   Dirname.\n   */\n  get dirname() {\n    return typeof this.path === 'string'\n      ? minpath.dirname(this.path)\n      : undefined\n  }\n\n  /**\n   * Set the parent path (example: `'~'`).\n   *\n   * Cannot be set if there’s no `path` yet.\n   *\n   * @param {string | undefined} dirname\n   *   Dirname.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  set dirname(dirname) {\n    assertPath(this.basename, 'dirname')\n    this.path = minpath.join(dirname || '', this.basename)\n  }\n\n  /**\n   * Get the extname (including dot) (example: `'.js'`).\n   *\n   * @returns {string | undefined}\n   *   Extname.\n   */\n  get extname() {\n    return typeof this.path === 'string'\n      ? minpath.extname(this.path)\n      : undefined\n  }\n\n  /**\n   * Set the extname (including dot) (example: `'.js'`).\n   *\n   * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\\'`\n   * on windows).\n   * Cannot be set if there’s no `path` yet.\n   *\n   * @param {string | undefined} extname\n   *   Extname.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  set extname(extname) {\n    assertPart(extname, 'extname')\n    assertPath(this.dirname, 'extname')\n\n    if (extname) {\n      if (extname.codePointAt(0) !== 46 /* `.` */) {\n        throw new Error('`extname` must start with `.`')\n      }\n\n      if (extname.includes('.', 1)) {\n        throw new Error('`extname` cannot contain multiple dots')\n      }\n    }\n\n    this.path = minpath.join(this.dirname, this.stem + (extname || ''))\n  }\n\n  /**\n   * Get the full path (example: `'~/index.min.js'`).\n   *\n   * @returns {string}\n   *   Path.\n   */\n  get path() {\n    return this.history[this.history.length - 1]\n  }\n\n  /**\n   * Set the full path (example: `'~/index.min.js'`).\n   *\n   * Cannot be nullified.\n   * You can set a file URL (a `URL` object with a `file:` protocol) which will\n   * be turned into a path with `url.fileURLToPath`.\n   *\n   * @param {URL | string} path\n   *   Path.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  set path(path) {\n    if (isUrl(path)) {\n      path = urlToPath(path)\n    }\n\n    assertNonEmpty(path, 'path')\n\n    if (this.path !== path) {\n      this.history.push(path)\n    }\n  }\n\n  /**\n   * Get the stem (basename w/o extname) (example: `'index.min'`).\n   *\n   * @returns {string | undefined}\n   *   Stem.\n   */\n  get stem() {\n    return typeof this.path === 'string'\n      ? minpath.basename(this.path, this.extname)\n      : undefined\n  }\n\n  /**\n   * Set the stem (basename w/o extname) (example: `'index.min'`).\n   *\n   * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\\'`\n   * on windows).\n   * Cannot be nullified (use `file.path = file.dirname` instead).\n   *\n   * @param {string} stem\n   *   Stem.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  set stem(stem) {\n    assertNonEmpty(stem, 'stem')\n    assertPart(stem, 'stem')\n    this.path = minpath.join(this.dirname || '', stem + (this.extname || ''))\n  }\n\n  // Normal prototypal methods.\n  /**\n   * Create a fatal message for `reason` associated with the file.\n   *\n   * The `fatal` field of the message is set to `true` (error; file not usable)\n   * and the `file` field is set to the current file path.\n   * The message is added to the `messages` field on `file`.\n   *\n   * > 🪦 **Note**: also has obsolete signatures.\n   *\n   * @overload\n   * @param {string} reason\n   * @param {MessageOptions | null | undefined} [options]\n   * @returns {never}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns {never}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns {never}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {string | null | undefined} [origin]\n   * @returns {never}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns {never}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns {never}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {string | null | undefined} [origin]\n   * @returns {never}\n   *\n   * @param {Error | VFileMessage | string} causeOrReason\n   *   Reason for message, should use markdown.\n   * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]\n   *   Configuration (optional).\n   * @param {string | null | undefined} [origin]\n   *   Place in code where the message originates (example:\n   *   `'my-package:my-rule'` or `'my-rule'`).\n   * @returns {never}\n   *   Never.\n   * @throws {VFileMessage}\n   *   Message.\n   */\n  fail(causeOrReason, optionsOrParentOrPlace, origin) {\n    // @ts-expect-error: the overloads are fine.\n    const message = this.message(causeOrReason, optionsOrParentOrPlace, origin)\n\n    message.fatal = true\n\n    throw message\n  }\n\n  /**\n   * Create an info message for `reason` associated with the file.\n   *\n   * The `fatal` field of the message is set to `undefined` (info; change\n   * likely not needed) and the `file` field is set to the current file path.\n   * The message is added to the `messages` field on `file`.\n   *\n   * > 🪦 **Note**: also has obsolete signatures.\n   *\n   * @overload\n   * @param {string} reason\n   * @param {MessageOptions | null | undefined} [options]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @param {Error | VFileMessage | string} causeOrReason\n   *   Reason for message, should use markdown.\n   * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]\n   *   Configuration (optional).\n   * @param {string | null | undefined} [origin]\n   *   Place in code where the message originates (example:\n   *   `'my-package:my-rule'` or `'my-rule'`).\n   * @returns {VFileMessage}\n   *   Message.\n   */\n  info(causeOrReason, optionsOrParentOrPlace, origin) {\n    // @ts-expect-error: the overloads are fine.\n    const message = this.message(causeOrReason, optionsOrParentOrPlace, origin)\n\n    message.fatal = undefined\n\n    return message\n  }\n\n  /**\n   * Create a message for `reason` associated with the file.\n   *\n   * The `fatal` field of the message is set to `false` (warning; change may be\n   * needed) and the `file` field is set to the current file path.\n   * The message is added to the `messages` field on `file`.\n   *\n   * > 🪦 **Note**: also has obsolete signatures.\n   *\n   * @overload\n   * @param {string} reason\n   * @param {MessageOptions | null | undefined} [options]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {string} reason\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Node | NodeLike | null | undefined} parent\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {Point | Position | null | undefined} place\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @overload\n   * @param {Error | VFileMessage} cause\n   * @param {string | null | undefined} [origin]\n   * @returns {VFileMessage}\n   *\n   * @param {Error | VFileMessage | string} causeOrReason\n   *   Reason for message, should use markdown.\n   * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]\n   *   Configuration (optional).\n   * @param {string | null | undefined} [origin]\n   *   Place in code where the message originates (example:\n   *   `'my-package:my-rule'` or `'my-rule'`).\n   * @returns {VFileMessage}\n   *   Message.\n   */\n  message(causeOrReason, optionsOrParentOrPlace, origin) {\n    const message = new VFileMessage(\n      // @ts-expect-error: the overloads are fine.\n      causeOrReason,\n      optionsOrParentOrPlace,\n      origin\n    )\n\n    if (this.path) {\n      message.name = this.path + ':' + message.name\n      message.file = this.path\n    }\n\n    message.fatal = false\n\n    this.messages.push(message)\n\n    return message\n  }\n\n  /**\n   * Serialize the file.\n   *\n   * > **Note**: which encodings are supported depends on the engine.\n   * > For info on Node.js, see:\n   * > <https://nodejs.org/api/util.html#whatwg-supported-encodings>.\n   *\n   * @param {string | null | undefined} [encoding='utf8']\n   *   Character encoding to understand `value` as when it’s a `Uint8Array`\n   *   (default: `'utf-8'`).\n   * @returns {string}\n   *   Serialized file.\n   */\n  toString(encoding) {\n    if (this.value === undefined) {\n      return ''\n    }\n\n    if (typeof this.value === 'string') {\n      return this.value\n    }\n\n    const decoder = new TextDecoder(encoding || undefined)\n    return decoder.decode(this.value)\n  }\n}\n\n/**\n * Assert that `part` is not a path (as in, does not contain `path.sep`).\n *\n * @param {string | null | undefined} part\n *   File path part.\n * @param {string} name\n *   Part name.\n * @returns {undefined}\n *   Nothing.\n */\nfunction assertPart(part, name) {\n  if (part && part.includes(minpath.sep)) {\n    throw new Error(\n      '`' + name + '` cannot be a path: did not expect `' + minpath.sep + '`'\n    )\n  }\n}\n\n/**\n * Assert that `part` is not empty.\n *\n * @param {string | undefined} part\n *   Thing.\n * @param {string} name\n *   Part name.\n * @returns {asserts part is string}\n *   Nothing.\n */\nfunction assertNonEmpty(part, name) {\n  if (!part) {\n    throw new Error('`' + name + '` cannot be empty')\n  }\n}\n\n/**\n * Assert `path` exists.\n *\n * @param {string | undefined} path\n *   Path.\n * @param {string} name\n *   Dependency name.\n * @returns {asserts path is string}\n *   Nothing.\n */\nfunction assertPath(path, name) {\n  if (!path) {\n    throw new Error('Setting `' + name + '` requires `path` to be set too')\n  }\n}\n\n/**\n * Assert `value` is an `Uint8Array`.\n *\n * @param {unknown} value\n *   thing.\n * @returns {value is Uint8Array}\n *   Whether `value` is an `Uint8Array`.\n */\nfunction isUint8Array(value) {\n  return Boolean(\n    value &&\n      typeof value === 'object' &&\n      'byteLength' in value &&\n      'byteOffset' in value\n  )\n}\n","export const CallableInstance =\n  /**\n   * @type {new <Parameters extends Array<unknown>, Result>(property: string | symbol) => (...parameters: Parameters) => Result}\n   */\n  (\n    /** @type {unknown} */\n    (\n      /**\n       * @this {Function}\n       * @param {string | symbol} property\n       * @returns {(...parameters: Array<unknown>) => unknown}\n       */\n      function (property) {\n        const self = this\n        const constr = self.constructor\n        const proto = /** @type {Record<string | symbol, Function>} */ (\n          // Prototypes do exist.\n          // type-coverage:ignore-next-line\n          constr.prototype\n        )\n        const value = proto[property]\n        /** @type {(...parameters: Array<unknown>) => unknown} */\n        const apply = function () {\n          return value.apply(apply, arguments)\n        }\n\n        Object.setPrototypeOf(apply, proto)\n\n        // Not needed for us in `unified`: we only call this on the `copy`\n        // function,\n        // and we don't need to add its fields (`length`, `name`)\n        // over.\n        // See also: GH-246.\n        // const names = Object.getOwnPropertyNames(value)\n        //\n        // for (const p of names) {\n        //   const descriptor = Object.getOwnPropertyDescriptor(value, p)\n        //   if (descriptor) Object.defineProperty(apply, p, descriptor)\n        // }\n\n        return apply\n      }\n    )\n  )\n","/**\n * @typedef {import('mdast').Nodes} Nodes\n *\n * @typedef Options\n *   Configuration (optional).\n * @property {boolean | null | undefined} [includeImageAlt=true]\n *   Whether to use `alt` for `image`s (default: `true`).\n * @property {boolean | null | undefined} [includeHtml=true]\n *   Whether to use `value` of HTML (default: `true`).\n */\n\n/** @type {Options} */\nconst emptyOptions = {}\n\n/**\n * Get the text content of a node or list of nodes.\n *\n * Prefers the node’s plain-text fields, otherwise serializes its children,\n * and if the given value is an array, serialize the nodes in it.\n *\n * @param {unknown} [value]\n *   Thing to serialize, typically `Node`.\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {string}\n *   Serialized `value`.\n */\nexport function toString(value, options) {\n  const settings = options || emptyOptions\n  const includeImageAlt =\n    typeof settings.includeImageAlt === 'boolean'\n      ? settings.includeImageAlt\n      : true\n  const includeHtml =\n    typeof settings.includeHtml === 'boolean' ? settings.includeHtml : true\n\n  return one(value, includeImageAlt, includeHtml)\n}\n\n/**\n * One node or several nodes.\n *\n * @param {unknown} value\n *   Thing to serialize.\n * @param {boolean} includeImageAlt\n *   Include image `alt`s.\n * @param {boolean} includeHtml\n *   Include HTML.\n * @returns {string}\n *   Serialized node.\n */\nfunction one(value, includeImageAlt, includeHtml) {\n  if (node(value)) {\n    if ('value' in value) {\n      return value.type === 'html' && !includeHtml ? '' : value.value\n    }\n\n    if (includeImageAlt && 'alt' in value && value.alt) {\n      return value.alt\n    }\n\n    if ('children' in value) {\n      return all(value.children, includeImageAlt, includeHtml)\n    }\n  }\n\n  if (Array.isArray(value)) {\n    return all(value, includeImageAlt, includeHtml)\n  }\n\n  return ''\n}\n\n/**\n * Serialize a list of nodes.\n *\n * @param {Array<unknown>} values\n *   Thing to serialize.\n * @param {boolean} includeImageAlt\n *   Include image `alt`s.\n * @param {boolean} includeHtml\n *   Include HTML.\n * @returns {string}\n *   Serialized nodes.\n */\nfunction all(values, includeImageAlt, includeHtml) {\n  /** @type {Array<string>} */\n  const result = []\n  let index = -1\n\n  while (++index < values.length) {\n    result[index] = one(values[index], includeImageAlt, includeHtml)\n  }\n\n  return result.join('')\n}\n\n/**\n * Check if `value` looks like a node.\n *\n * @param {unknown} value\n *   Thing.\n * @returns {value is Nodes}\n *   Whether `value` is a node.\n */\nfunction node(value) {\n  return Boolean(value && typeof value === 'object')\n}\n","/// <reference lib=\"dom\" />\n\n/* global document */\n\nconst element = document.createElement('i')\n\n/**\n * @param {string} value\n * @returns {string | false}\n */\nexport function decodeNamedCharacterReference(value) {\n  const characterReference = '&' + value + ';'\n  element.innerHTML = characterReference\n  const character = element.textContent\n\n  // Some named character references do not require the closing semicolon\n  // (`&not`, for instance), which leads to situations where parsing the assumed\n  // named reference of `&notit;` will result in the string `¬it;`.\n  // When we encounter a trailing semicolon after parsing, and the character\n  // reference to decode was not a semicolon (`&semi;`), we can assume that the\n  // matching was not complete.\n  if (\n    character.charCodeAt(character.length - 1) === 59 /* `;` */ &&\n    value !== 'semi'\n  ) {\n    return false\n  }\n\n  // If the decoded string is equal to the input, the character reference was\n  // not valid.\n  return character === characterReference ? false : character\n}\n","/**\n * Like `Array#splice`, but smarter for giant arrays.\n *\n * `Array#splice` takes all items to be inserted as individual argument which\n * causes a stack overflow in V8 when trying to insert 100k items for instance.\n *\n * Otherwise, this does not return the removed items, and takes `items` as an\n * array instead of rest parameters.\n *\n * @template {unknown} T\n *   Item type.\n * @param {Array<T>} list\n *   List to operate on.\n * @param {number} start\n *   Index to remove/insert at (can be negative).\n * @param {number} remove\n *   Number of items to remove.\n * @param {Array<T>} items\n *   Items to inject into `list`.\n * @returns {undefined}\n *   Nothing.\n */\nexport function splice(list, start, remove, items) {\n  const end = list.length;\n  let chunkStart = 0;\n  /** @type {Array<unknown>} */\n  let parameters;\n\n  // Make start between zero and `end` (included).\n  if (start < 0) {\n    start = -start > end ? 0 : end + start;\n  } else {\n    start = start > end ? end : start;\n  }\n  remove = remove > 0 ? remove : 0;\n\n  // No need to chunk the items if there’s only a couple (10k) items.\n  if (items.length < 10000) {\n    parameters = Array.from(items);\n    parameters.unshift(start, remove);\n    // @ts-expect-error Hush, it’s fine.\n    list.splice(...parameters);\n  } else {\n    // Delete `remove` items starting from `start`\n    if (remove) list.splice(start, remove);\n\n    // Insert the items in chunks to not cause stack overflows.\n    while (chunkStart < items.length) {\n      parameters = items.slice(chunkStart, chunkStart + 10000);\n      parameters.unshift(start, 0);\n      // @ts-expect-error Hush, it’s fine.\n      list.splice(...parameters);\n      chunkStart += 10000;\n      start += 10000;\n    }\n  }\n}\n\n/**\n * Append `items` (an array) at the end of `list` (another array).\n * When `list` was empty, returns `items` instead.\n *\n * This prevents a potentially expensive operation when `list` is empty,\n * and adds items in batches to prevent V8 from hanging.\n *\n * @template {unknown} T\n *   Item type.\n * @param {Array<T>} list\n *   List to operate on.\n * @param {Array<T>} items\n *   Items to add to `list`.\n * @returns {Array<T>}\n *   Either `list` or `items`.\n */\nexport function push(list, items) {\n  if (list.length > 0) {\n    splice(list, list.length, 0, items);\n    return list;\n  }\n  return items;\n}","/**\n * @import {\n *   Extension,\n *   Handles,\n *   HtmlExtension,\n *   NormalizedExtension\n * } from 'micromark-util-types'\n */\n\nimport {splice} from 'micromark-util-chunked'\n\nconst hasOwnProperty = {}.hasOwnProperty\n\n/**\n * Combine multiple syntax extensions into one.\n *\n * @param {ReadonlyArray<Extension>} extensions\n *   List of syntax extensions.\n * @returns {NormalizedExtension}\n *   A single combined extension.\n */\nexport function combineExtensions(extensions) {\n  /** @type {NormalizedExtension} */\n  const all = {}\n  let index = -1\n\n  while (++index < extensions.length) {\n    syntaxExtension(all, extensions[index])\n  }\n\n  return all\n}\n\n/**\n * Merge `extension` into `all`.\n *\n * @param {NormalizedExtension} all\n *   Extension to merge into.\n * @param {Extension} extension\n *   Extension to merge.\n * @returns {undefined}\n *   Nothing.\n */\nfunction syntaxExtension(all, extension) {\n  /** @type {keyof Extension} */\n  let hook\n\n  for (hook in extension) {\n    const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined\n    /** @type {Record<string, unknown>} */\n    const left = maybe || (all[hook] = {})\n    /** @type {Record<string, unknown> | undefined} */\n    const right = extension[hook]\n    /** @type {string} */\n    let code\n\n    if (right) {\n      for (code in right) {\n        if (!hasOwnProperty.call(left, code)) left[code] = []\n        const value = right[code]\n        constructs(\n          // @ts-expect-error Looks like a list.\n          left[code],\n          Array.isArray(value) ? value : value ? [value] : []\n        )\n      }\n    }\n  }\n}\n\n/**\n * Merge `list` into `existing` (both lists of constructs).\n * Mutates `existing`.\n *\n * @param {Array<unknown>} existing\n *   List of constructs to merge into.\n * @param {Array<unknown>} list\n *   List of constructs to merge.\n * @returns {undefined}\n *   Nothing.\n */\nfunction constructs(existing, list) {\n  let index = -1\n  /** @type {Array<unknown>} */\n  const before = []\n\n  while (++index < list.length) {\n    // @ts-expect-error Looks like an object.\n    ;(list[index].add === 'after' ? existing : before).push(list[index])\n  }\n\n  splice(existing, 0, 0, before)\n}\n\n/**\n * Combine multiple HTML extensions into one.\n *\n * @param {ReadonlyArray<HtmlExtension>} htmlExtensions\n *   List of HTML extensions.\n * @returns {HtmlExtension}\n *   Single combined HTML extension.\n */\nexport function combineHtmlExtensions(htmlExtensions) {\n  /** @type {HtmlExtension} */\n  const handlers = {}\n  let index = -1\n\n  while (++index < htmlExtensions.length) {\n    htmlExtension(handlers, htmlExtensions[index])\n  }\n\n  return handlers\n}\n\n/**\n * Merge `extension` into `all`.\n *\n * @param {HtmlExtension} all\n *   Extension to merge into.\n * @param {HtmlExtension} extension\n *   Extension to merge.\n * @returns {undefined}\n *   Nothing.\n */\nfunction htmlExtension(all, extension) {\n  /** @type {keyof HtmlExtension} */\n  let hook\n\n  for (hook in extension) {\n    const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined\n    const left = maybe || (all[hook] = {})\n    const right = extension[hook]\n    /** @type {keyof Handles} */\n    let type\n\n    if (right) {\n      for (type in right) {\n        // @ts-expect-error assume document vs regular handler are managed correctly.\n        left[type] = right[type]\n      }\n    }\n  }\n}\n","/**\n * Turn the number (in string form as either hexa- or plain decimal) coming from\n * a numeric character reference into a character.\n *\n * Sort of like `String.fromCodePoint(Number.parseInt(value, base))`, but makes\n * non-characters and control characters safe.\n *\n * @param {string} value\n *   Value to decode.\n * @param {number} base\n *   Numeric base.\n * @returns {string}\n *   Character.\n */\nexport function decodeNumericCharacterReference(value, base) {\n  const code = Number.parseInt(value, base);\n  if (\n  // C0 except for HT, LF, FF, CR, space.\n  code < 9 || code === 11 || code > 13 && code < 32 ||\n  // Control character (DEL) of C0, and C1 controls.\n  code > 126 && code < 160 ||\n  // Lone high surrogates and low surrogates.\n  code > 55_295 && code < 57_344 ||\n  // Noncharacters.\n  code > 64_975 && code < 65_008 || /* eslint-disable no-bitwise */\n  (code & 65_535) === 65_535 || (code & 65_535) === 65_534 || /* eslint-enable no-bitwise */\n  // Out of range\n  code > 1_114_111) {\n    return \"\\uFFFD\";\n  }\n  return String.fromCodePoint(code);\n}","/**\n * Normalize an identifier (as found in references, definitions).\n *\n * Collapses markdown whitespace, trim, and then lower- and uppercase.\n *\n * Some characters are considered “uppercase”, such as U+03F4 (`ϴ`), but if their\n * lowercase counterpart (U+03B8 (`θ`)) is uppercased will result in a different\n * uppercase character (U+0398 (`Θ`)).\n * So, to get a canonical form, we perform both lower- and uppercase.\n *\n * Using uppercase last makes sure keys will never interact with default\n * prototypal values (such as `constructor`): nothing in the prototype of\n * `Object` is uppercase.\n *\n * @param {string} value\n *   Identifier to normalize.\n * @returns {string}\n *   Normalized identifier.\n */\nexport function normalizeIdentifier(value) {\n  return value\n  // Collapse markdown whitespace.\n  .replace(/[\\t\\n\\r ]+/g, \" \")\n  // Trim.\n  .replace(/^ | $/g, '')\n  // Some characters are considered “uppercase”, but if their lowercase\n  // counterpart is uppercased will result in a different uppercase\n  // character.\n  // Hence, to get that form, we perform both lower- and uppercase.\n  // Upper case makes sure keys will not interact with default prototypal\n  // methods: no method is uppercase.\n  .toLowerCase().toUpperCase();\n}","/**\n * @import {Code} from 'micromark-util-types'\n */\n\n/**\n * Check whether the character code represents an ASCII alpha (`a` through `z`,\n * case insensitive).\n *\n * An **ASCII alpha** is an ASCII upper alpha or ASCII lower alpha.\n *\n * An **ASCII upper alpha** is a character in the inclusive range U+0041 (`A`)\n * to U+005A (`Z`).\n *\n * An **ASCII lower alpha** is a character in the inclusive range U+0061 (`a`)\n * to U+007A (`z`).\n *\n * @param code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport const asciiAlpha = regexCheck(/[A-Za-z]/);\n\n/**\n * Check whether the character code represents an ASCII alphanumeric (`a`\n * through `z`, case insensitive, or `0` through `9`).\n *\n * An **ASCII alphanumeric** is an ASCII digit (see `asciiDigit`) or ASCII alpha\n * (see `asciiAlpha`).\n *\n * @param code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport const asciiAlphanumeric = regexCheck(/[\\dA-Za-z]/);\n\n/**\n * Check whether the character code represents an ASCII atext.\n *\n * atext is an ASCII alphanumeric (see `asciiAlphanumeric`), or a character in\n * the inclusive ranges U+0023 NUMBER SIGN (`#`) to U+0027 APOSTROPHE (`'`),\n * U+002A ASTERISK (`*`), U+002B PLUS SIGN (`+`), U+002D DASH (`-`), U+002F\n * SLASH (`/`), U+003D EQUALS TO (`=`), U+003F QUESTION MARK (`?`), U+005E\n * CARET (`^`) to U+0060 GRAVE ACCENT (`` ` ``), or U+007B LEFT CURLY BRACE\n * (`{`) to U+007E TILDE (`~`).\n *\n * See:\n * **\\[RFC5322]**:\n * [Internet Message Format](https://tools.ietf.org/html/rfc5322).\n * P. Resnick.\n * IETF.\n *\n * @param code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport const asciiAtext = regexCheck(/[#-'*+\\--9=?A-Z^-~]/);\n\n/**\n * Check whether a character code is an ASCII control character.\n *\n * An **ASCII control** is a character in the inclusive range U+0000 NULL (NUL)\n * to U+001F (US), or U+007F (DEL).\n *\n * @param {Code} code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport function asciiControl(code) {\n  return (\n    // Special whitespace codes (which have negative values), C0 and Control\n    // character DEL\n    code !== null && (code < 32 || code === 127)\n  );\n}\n\n/**\n * Check whether the character code represents an ASCII digit (`0` through `9`).\n *\n * An **ASCII digit** is a character in the inclusive range U+0030 (`0`) to\n * U+0039 (`9`).\n *\n * @param code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport const asciiDigit = regexCheck(/\\d/);\n\n/**\n * Check whether the character code represents an ASCII hex digit (`a` through\n * `f`, case insensitive, or `0` through `9`).\n *\n * An **ASCII hex digit** is an ASCII digit (see `asciiDigit`), ASCII upper hex\n * digit, or an ASCII lower hex digit.\n *\n * An **ASCII upper hex digit** is a character in the inclusive range U+0041\n * (`A`) to U+0046 (`F`).\n *\n * An **ASCII lower hex digit** is a character in the inclusive range U+0061\n * (`a`) to U+0066 (`f`).\n *\n * @param code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport const asciiHexDigit = regexCheck(/[\\dA-Fa-f]/);\n\n/**\n * Check whether the character code represents ASCII punctuation.\n *\n * An **ASCII punctuation** is a character in the inclusive ranges U+0021\n * EXCLAMATION MARK (`!`) to U+002F SLASH (`/`), U+003A COLON (`:`) to U+0040 AT\n * SIGN (`@`), U+005B LEFT SQUARE BRACKET (`[`) to U+0060 GRAVE ACCENT\n * (`` ` ``), or U+007B LEFT CURLY BRACE (`{`) to U+007E TILDE (`~`).\n *\n * @param code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport const asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/);\n\n/**\n * Check whether a character code is a markdown line ending.\n *\n * A **markdown line ending** is the virtual characters M-0003 CARRIAGE RETURN\n * LINE FEED (CRLF), M-0004 LINE FEED (LF) and M-0005 CARRIAGE RETURN (CR).\n *\n * In micromark, the actual character U+000A LINE FEED (LF) and U+000D CARRIAGE\n * RETURN (CR) are replaced by these virtual characters depending on whether\n * they occurred together.\n *\n * @param {Code} code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport function markdownLineEnding(code) {\n  return code !== null && code < -2;\n}\n\n/**\n * Check whether a character code is a markdown line ending (see\n * `markdownLineEnding`) or markdown space (see `markdownSpace`).\n *\n * @param {Code} code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport function markdownLineEndingOrSpace(code) {\n  return code !== null && (code < 0 || code === 32);\n}\n\n/**\n * Check whether a character code is a markdown space.\n *\n * A **markdown space** is the concrete character U+0020 SPACE (SP) and the\n * virtual characters M-0001 VIRTUAL SPACE (VS) and M-0002 HORIZONTAL TAB (HT).\n *\n * In micromark, the actual character U+0009 CHARACTER TABULATION (HT) is\n * replaced by one M-0002 HORIZONTAL TAB (HT) and between 0 and 3 M-0001 VIRTUAL\n * SPACE (VS) characters, depending on the column at which the tab occurred.\n *\n * @param {Code} code\n *   Code.\n * @returns {boolean}\n *   Whether it matches.\n */\nexport function markdownSpace(code) {\n  return code === -2 || code === -1 || code === 32;\n}\n\n// Size note: removing ASCII from the regex and using `asciiPunctuation` here\n// In fact adds to the bundle size.\n/**\n * Check whether the character code represents Unicode punctuation.\n *\n * A **Unicode punctuation** is a character in the Unicode `Pc` (Punctuation,\n * Connector), `Pd` (Punctuation, Dash), `Pe` (Punctuation, Close), `Pf`\n * (Punctuation, Final quote), `Pi` (Punctuation, Initial quote), `Po`\n * (Punctuation, Other), or `Ps` (Punctuation, Open) categories, or an ASCII\n * punctuation (see `asciiPunctuation`).\n *\n * See:\n * **\\[UNICODE]**:\n * [The Unicode Standard](https://www.unicode.org/versions/).\n * Unicode Consortium.\n *\n * @param code\n *   Code.\n * @returns\n *   Whether it matches.\n */\nexport const unicodePunctuation = regexCheck(/\\p{P}|\\p{S}/u);\n\n/**\n * Check whether the character code represents Unicode whitespace.\n *\n * Note that this does handle micromark specific markdown whitespace characters.\n * See `markdownLineEndingOrSpace` to check that.\n *\n * A **Unicode whitespace** is a character in the Unicode `Zs` (Separator,\n * Space) category, or U+0009 CHARACTER TABULATION (HT), U+000A LINE FEED (LF),\n * U+000C (FF), or U+000D CARRIAGE RETURN (CR) (**\\[UNICODE]**).\n *\n * See:\n * **\\[UNICODE]**:\n * [The Unicode Standard](https://www.unicode.org/versions/).\n * Unicode Consortium.\n *\n * @param code\n *   Code.\n * @returns\n *   Whether it matches.\n */\nexport const unicodeWhitespace = regexCheck(/\\s/);\n\n/**\n * Create a code check from a regex.\n *\n * @param {RegExp} regex\n *   Expression.\n * @returns {(code: Code) => boolean}\n *   Check.\n */\nfunction regexCheck(regex) {\n  return check;\n\n  /**\n   * Check whether a code matches the bound regex.\n   *\n   * @param {Code} code\n   *   Character code.\n   * @returns {boolean}\n   *   Whether the character code matches the bound regex.\n   */\n  function check(code) {\n    return code !== null && code > -1 && regex.test(String.fromCharCode(code));\n  }\n}","import { asciiAlphanumeric } from 'micromark-util-character';\nimport { encode } from 'micromark-util-encode';\n/**\n * Make a value safe for injection as a URL.\n *\n * This encodes unsafe characters with percent-encoding and skips already\n * encoded sequences (see `normalizeUri`).\n * Further unsafe characters are encoded as character references (see\n * `micromark-util-encode`).\n *\n * A regex of allowed protocols can be given, in which case the URL is\n * sanitized.\n * For example, `/^(https?|ircs?|mailto|xmpp)$/i` can be used for `a[href]`, or\n * `/^https?$/i` for `img[src]` (this is what `github.com` allows).\n * If the URL includes an unknown protocol (one not matched by `protocol`, such\n * as a dangerous example, `javascript:`), the value is ignored.\n *\n * @param {string | null | undefined} url\n *   URI to sanitize.\n * @param {RegExp | null | undefined} [protocol]\n *   Allowed protocols.\n * @returns {string}\n *   Sanitized URI.\n */\nexport function sanitizeUri(url, protocol) {\n  const value = encode(normalizeUri(url || ''));\n  if (!protocol) {\n    return value;\n  }\n  const colon = value.indexOf(':');\n  const questionMark = value.indexOf('?');\n  const numberSign = value.indexOf('#');\n  const slash = value.indexOf('/');\n  if (\n  // If there is no protocol, it’s relative.\n  colon < 0 ||\n  // If the first colon is after a `?`, `#`, or `/`, it’s not a protocol.\n  slash > -1 && colon > slash || questionMark > -1 && colon > questionMark || numberSign > -1 && colon > numberSign ||\n  // It is a protocol, it should be allowed.\n  protocol.test(value.slice(0, colon))) {\n    return value;\n  }\n  return '';\n}\n\n/**\n * Normalize a URL.\n *\n * Encode unsafe characters with percent-encoding, skipping already encoded\n * sequences.\n *\n * @param {string} value\n *   URI to normalize.\n * @returns {string}\n *   Normalized URI.\n */\nexport function normalizeUri(value) {\n  /** @type {Array<string>} */\n  const result = [];\n  let index = -1;\n  let start = 0;\n  let skip = 0;\n  while (++index < value.length) {\n    const code = value.charCodeAt(index);\n    /** @type {string} */\n    let replace = '';\n\n    // A correct percent encoded value.\n    if (code === 37 && asciiAlphanumeric(value.charCodeAt(index + 1)) && asciiAlphanumeric(value.charCodeAt(index + 2))) {\n      skip = 2;\n    }\n    // ASCII.\n    else if (code < 128) {\n      if (!/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(code))) {\n        replace = String.fromCharCode(code);\n      }\n    }\n    // Astral.\n    else if (code > 55_295 && code < 57_344) {\n      const next = value.charCodeAt(index + 1);\n\n      // A correct surrogate pair.\n      if (code < 56_320 && next > 56_319 && next < 57_344) {\n        replace = String.fromCharCode(code, next);\n        skip = 1;\n      }\n      // Lone surrogate.\n      else {\n        replace = \"\\uFFFD\";\n      }\n    }\n    // Unicode.\n    else {\n      replace = String.fromCharCode(code);\n    }\n    if (replace) {\n      result.push(value.slice(start, index), encodeURIComponent(replace));\n      start = index + skip + 1;\n      replace = '';\n    }\n    if (skip) {\n      index += skip;\n      skip = 0;\n    }\n  }\n  return result.join('') + value.slice(start);\n}","/**\n * @import {Effects, State, TokenType} from 'micromark-util-types'\n */\n\nimport { markdownSpace } from 'micromark-util-character';\n\n// To do: implement `spaceOrTab`, `spaceOrTabMinMax`, `spaceOrTabWithOptions`.\n\n/**\n * Parse spaces and tabs.\n *\n * There is no `nok` parameter:\n *\n * *   spaces in markdown are often optional, in which case this factory can be\n *     used and `ok` will be switched to whether spaces were found or not\n * *   one line ending or space can be detected with `markdownSpace(code)` right\n *     before using `factorySpace`\n *\n * ###### Examples\n *\n * Where `␉` represents a tab (plus how much it expands) and `␠` represents a\n * single space.\n *\n * ```markdown\n * ␉\n * ␠␠␠␠\n * ␉␠\n * ```\n *\n * @param {Effects} effects\n *   Context.\n * @param {State} ok\n *   State switched to when successful.\n * @param {TokenType} type\n *   Type (`' \\t'`).\n * @param {number | undefined} [max=Infinity]\n *   Max (exclusive).\n * @returns {State}\n *   Start state.\n */\nexport function factorySpace(effects, ok, type, max) {\n  const limit = max ? max - 1 : Number.POSITIVE_INFINITY;\n  let size = 0;\n  return start;\n\n  /** @type {State} */\n  function start(code) {\n    if (markdownSpace(code)) {\n      effects.enter(type);\n      return prefix(code);\n    }\n    return ok(code);\n  }\n\n  /** @type {State} */\n  function prefix(code) {\n    if (markdownSpace(code) && size++ < limit) {\n      effects.consume(code);\n      return prefix;\n    }\n    effects.exit(type);\n    return ok(code);\n  }\n}","/**\n * @import {\n *   InitialConstruct,\n *   Initializer,\n *   State,\n *   TokenizeContext,\n *   Token\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding } from 'micromark-util-character';\n/** @type {InitialConstruct} */\nexport const content = {\n  tokenize: initializeContent\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Initializer}\n *   Content.\n */\nfunction initializeContent(effects) {\n  const contentStart = effects.attempt(this.parser.constructs.contentInitial, afterContentStartConstruct, paragraphInitial);\n  /** @type {Token} */\n  let previous;\n  return contentStart;\n\n  /** @type {State} */\n  function afterContentStartConstruct(code) {\n    if (code === null) {\n      effects.consume(code);\n      return;\n    }\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return factorySpace(effects, contentStart, \"linePrefix\");\n  }\n\n  /** @type {State} */\n  function paragraphInitial(code) {\n    effects.enter(\"paragraph\");\n    return lineStart(code);\n  }\n\n  /** @type {State} */\n  function lineStart(code) {\n    const token = effects.enter(\"chunkText\", {\n      contentType: \"text\",\n      previous\n    });\n    if (previous) {\n      previous.next = token;\n    }\n    previous = token;\n    return data(code);\n  }\n\n  /** @type {State} */\n  function data(code) {\n    if (code === null) {\n      effects.exit(\"chunkText\");\n      effects.exit(\"paragraph\");\n      effects.consume(code);\n      return;\n    }\n    if (markdownLineEnding(code)) {\n      effects.consume(code);\n      effects.exit(\"chunkText\");\n      return lineStart;\n    }\n\n    // Data.\n    effects.consume(code);\n    return data;\n  }\n}","/**\n * @import {\n *   Construct,\n *   ContainerState,\n *   InitialConstruct,\n *   Initializer,\n *   Point,\n *   State,\n *   TokenizeContext,\n *   Tokenizer,\n *   Token\n * } from 'micromark-util-types'\n */\n\n/**\n * @typedef {[Construct, ContainerState]} StackItem\n *   Construct and its state.\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding } from 'micromark-util-character';\nimport { splice } from 'micromark-util-chunked';\n/** @type {InitialConstruct} */\nexport const document = {\n  tokenize: initializeDocument\n};\n\n/** @type {Construct} */\nconst containerConstruct = {\n  tokenize: tokenizeContainer\n};\n\n/**\n * @this {TokenizeContext}\n *   Self.\n * @type {Initializer}\n *   Initializer.\n */\nfunction initializeDocument(effects) {\n  const self = this;\n  /** @type {Array<StackItem>} */\n  const stack = [];\n  let continued = 0;\n  /** @type {TokenizeContext | undefined} */\n  let childFlow;\n  /** @type {Token | undefined} */\n  let childToken;\n  /** @type {number} */\n  let lineStartOffset;\n  return start;\n\n  /** @type {State} */\n  function start(code) {\n    // First we iterate through the open blocks, starting with the root\n    // document, and descending through last children down to the last open\n    // block.\n    // Each block imposes a condition that the line must satisfy if the block is\n    // to remain open.\n    // For example, a block quote requires a `>` character.\n    // A paragraph requires a non-blank line.\n    // In this phase we may match all or just some of the open blocks.\n    // But we cannot close unmatched blocks yet, because we may have a lazy\n    // continuation line.\n    if (continued < stack.length) {\n      const item = stack[continued];\n      self.containerState = item[1];\n      return effects.attempt(item[0].continuation, documentContinue, checkNewContainers)(code);\n    }\n\n    // Done.\n    return checkNewContainers(code);\n  }\n\n  /** @type {State} */\n  function documentContinue(code) {\n    continued++;\n\n    // Note: this field is called `_closeFlow` but it also closes containers.\n    // Perhaps a good idea to rename it but it’s already used in the wild by\n    // extensions.\n    if (self.containerState._closeFlow) {\n      self.containerState._closeFlow = undefined;\n      if (childFlow) {\n        closeFlow();\n      }\n\n      // Note: this algorithm for moving events around is similar to the\n      // algorithm when dealing with lazy lines in `writeToChild`.\n      const indexBeforeExits = self.events.length;\n      let indexBeforeFlow = indexBeforeExits;\n      /** @type {Point | undefined} */\n      let point;\n\n      // Find the flow chunk.\n      while (indexBeforeFlow--) {\n        if (self.events[indexBeforeFlow][0] === 'exit' && self.events[indexBeforeFlow][1].type === \"chunkFlow\") {\n          point = self.events[indexBeforeFlow][1].end;\n          break;\n        }\n      }\n      exitContainers(continued);\n\n      // Fix positions.\n      let index = indexBeforeExits;\n      while (index < self.events.length) {\n        self.events[index][1].end = {\n          ...point\n        };\n        index++;\n      }\n\n      // Inject the exits earlier (they’re still also at the end).\n      splice(self.events, indexBeforeFlow + 1, 0, self.events.slice(indexBeforeExits));\n\n      // Discard the duplicate exits.\n      self.events.length = index;\n      return checkNewContainers(code);\n    }\n    return start(code);\n  }\n\n  /** @type {State} */\n  function checkNewContainers(code) {\n    // Next, after consuming the continuation markers for existing blocks, we\n    // look for new block starts (e.g. `>` for a block quote).\n    // If we encounter a new block start, we close any blocks unmatched in\n    // step 1 before creating the new block as a child of the last matched\n    // block.\n    if (continued === stack.length) {\n      // No need to `check` whether there’s a container, of `exitContainers`\n      // would be moot.\n      // We can instead immediately `attempt` to parse one.\n      if (!childFlow) {\n        return documentContinued(code);\n      }\n\n      // If we have concrete content, such as block HTML or fenced code,\n      // we can’t have containers “pierce” into them, so we can immediately\n      // start.\n      if (childFlow.currentConstruct && childFlow.currentConstruct.concrete) {\n        return flowStart(code);\n      }\n\n      // If we do have flow, it could still be a blank line,\n      // but we’d be interrupting it w/ a new container if there’s a current\n      // construct.\n      // To do: next major: remove `_gfmTableDynamicInterruptHack` (no longer\n      // needed in micromark-extension-gfm-table@1.0.6).\n      self.interrupt = Boolean(childFlow.currentConstruct && !childFlow._gfmTableDynamicInterruptHack);\n    }\n\n    // Check if there is a new container.\n    self.containerState = {};\n    return effects.check(containerConstruct, thereIsANewContainer, thereIsNoNewContainer)(code);\n  }\n\n  /** @type {State} */\n  function thereIsANewContainer(code) {\n    if (childFlow) closeFlow();\n    exitContainers(continued);\n    return documentContinued(code);\n  }\n\n  /** @type {State} */\n  function thereIsNoNewContainer(code) {\n    self.parser.lazy[self.now().line] = continued !== stack.length;\n    lineStartOffset = self.now().offset;\n    return flowStart(code);\n  }\n\n  /** @type {State} */\n  function documentContinued(code) {\n    // Try new containers.\n    self.containerState = {};\n    return effects.attempt(containerConstruct, containerContinue, flowStart)(code);\n  }\n\n  /** @type {State} */\n  function containerContinue(code) {\n    continued++;\n    stack.push([self.currentConstruct, self.containerState]);\n    // Try another.\n    return documentContinued(code);\n  }\n\n  /** @type {State} */\n  function flowStart(code) {\n    if (code === null) {\n      if (childFlow) closeFlow();\n      exitContainers(0);\n      effects.consume(code);\n      return;\n    }\n    childFlow = childFlow || self.parser.flow(self.now());\n    effects.enter(\"chunkFlow\", {\n      _tokenizer: childFlow,\n      contentType: \"flow\",\n      previous: childToken\n    });\n    return flowContinue(code);\n  }\n\n  /** @type {State} */\n  function flowContinue(code) {\n    if (code === null) {\n      writeToChild(effects.exit(\"chunkFlow\"), true);\n      exitContainers(0);\n      effects.consume(code);\n      return;\n    }\n    if (markdownLineEnding(code)) {\n      effects.consume(code);\n      writeToChild(effects.exit(\"chunkFlow\"));\n      // Get ready for the next line.\n      continued = 0;\n      self.interrupt = undefined;\n      return start;\n    }\n    effects.consume(code);\n    return flowContinue;\n  }\n\n  /**\n   * @param {Token} token\n   *   Token.\n   * @param {boolean | undefined} [endOfFile]\n   *   Whether the token is at the end of the file (default: `false`).\n   * @returns {undefined}\n   *   Nothing.\n   */\n  function writeToChild(token, endOfFile) {\n    const stream = self.sliceStream(token);\n    if (endOfFile) stream.push(null);\n    token.previous = childToken;\n    if (childToken) childToken.next = token;\n    childToken = token;\n    childFlow.defineSkip(token.start);\n    childFlow.write(stream);\n\n    // Alright, so we just added a lazy line:\n    //\n    // ```markdown\n    // > a\n    // b.\n    //\n    // Or:\n    //\n    // > ~~~c\n    // d\n    //\n    // Or:\n    //\n    // > | e |\n    // f\n    // ```\n    //\n    // The construct in the second example (fenced code) does not accept lazy\n    // lines, so it marked itself as done at the end of its first line, and\n    // then the content construct parses `d`.\n    // Most constructs in markdown match on the first line: if the first line\n    // forms a construct, a non-lazy line can’t “unmake” it.\n    //\n    // The construct in the third example is potentially a GFM table, and\n    // those are *weird*.\n    // It *could* be a table, from the first line, if the following line\n    // matches a condition.\n    // In this case, that second line is lazy, which “unmakes” the first line\n    // and turns the whole into one content block.\n    //\n    // We’ve now parsed the non-lazy and the lazy line, and can figure out\n    // whether the lazy line started a new flow block.\n    // If it did, we exit the current containers between the two flow blocks.\n    if (self.parser.lazy[token.start.line]) {\n      let index = childFlow.events.length;\n      while (index--) {\n        if (\n        // The token starts before the line ending…\n        childFlow.events[index][1].start.offset < lineStartOffset && (\n        // …and either is not ended yet…\n        !childFlow.events[index][1].end ||\n        // …or ends after it.\n        childFlow.events[index][1].end.offset > lineStartOffset)) {\n          // Exit: there’s still something open, which means it’s a lazy line\n          // part of something.\n          return;\n        }\n      }\n\n      // Note: this algorithm for moving events around is similar to the\n      // algorithm when closing flow in `documentContinue`.\n      const indexBeforeExits = self.events.length;\n      let indexBeforeFlow = indexBeforeExits;\n      /** @type {boolean | undefined} */\n      let seen;\n      /** @type {Point | undefined} */\n      let point;\n\n      // Find the previous chunk (the one before the lazy line).\n      while (indexBeforeFlow--) {\n        if (self.events[indexBeforeFlow][0] === 'exit' && self.events[indexBeforeFlow][1].type === \"chunkFlow\") {\n          if (seen) {\n            point = self.events[indexBeforeFlow][1].end;\n            break;\n          }\n          seen = true;\n        }\n      }\n      exitContainers(continued);\n\n      // Fix positions.\n      index = indexBeforeExits;\n      while (index < self.events.length) {\n        self.events[index][1].end = {\n          ...point\n        };\n        index++;\n      }\n\n      // Inject the exits earlier (they’re still also at the end).\n      splice(self.events, indexBeforeFlow + 1, 0, self.events.slice(indexBeforeExits));\n\n      // Discard the duplicate exits.\n      self.events.length = index;\n    }\n  }\n\n  /**\n   * @param {number} size\n   *   Size.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  function exitContainers(size) {\n    let index = stack.length;\n\n    // Exit open containers.\n    while (index-- > size) {\n      const entry = stack[index];\n      self.containerState = entry[1];\n      entry[0].exit.call(self, effects);\n    }\n    stack.length = size;\n  }\n  function closeFlow() {\n    childFlow.write([null]);\n    childToken = undefined;\n    childFlow = undefined;\n    self.containerState._closeFlow = undefined;\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n *   Tokenizer.\n */\nfunction tokenizeContainer(effects, ok, nok) {\n  // Always populated by defaults.\n\n  return factorySpace(effects, effects.attempt(this.parser.constructs.document, ok, nok), \"linePrefix\", this.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4);\n}","/**\n * @import {Code} from 'micromark-util-types'\n */\n\nimport { markdownLineEndingOrSpace, unicodePunctuation, unicodeWhitespace } from 'micromark-util-character';\n/**\n * Classify whether a code represents whitespace, punctuation, or something\n * else.\n *\n * Used for attention (emphasis, strong), whose sequences can open or close\n * based on the class of surrounding characters.\n *\n * > 👉 **Note**: eof (`null`) is seen as whitespace.\n *\n * @param {Code} code\n *   Code.\n * @returns {typeof constants.characterGroupWhitespace | typeof constants.characterGroupPunctuation | undefined}\n *   Group.\n */\nexport function classifyCharacter(code) {\n  if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n    return 1;\n  }\n  if (unicodePunctuation(code)) {\n    return 2;\n  }\n}","/**\n * @import {Event, Resolver, TokenizeContext} from 'micromark-util-types'\n */\n\n/**\n * Call all `resolveAll`s.\n *\n * @param {ReadonlyArray<{resolveAll?: Resolver | undefined}>} constructs\n *   List of constructs, optionally with `resolveAll`s.\n * @param {Array<Event>} events\n *   List of events.\n * @param {TokenizeContext} context\n *   Context used by `tokenize`.\n * @returns {Array<Event>}\n *   Changed events.\n */\nexport function resolveAll(constructs, events, context) {\n  /** @type {Array<Resolver>} */\n  const called = []\n  let index = -1\n\n  while (++index < constructs.length) {\n    const resolve = constructs[index].resolveAll\n\n    if (resolve && !called.includes(resolve)) {\n      events = resolve(events, context)\n      called.push(resolve)\n    }\n  }\n\n  return events\n}\n","/**\n * @import {\n *   Code,\n *   Construct,\n *   Event,\n *   Point,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer,\n *   Token\n * } from 'micromark-util-types'\n */\n\nimport { push, splice } from 'micromark-util-chunked';\nimport { classifyCharacter } from 'micromark-util-classify-character';\nimport { resolveAll } from 'micromark-util-resolve-all';\n/** @type {Construct} */\nexport const attention = {\n  name: 'attention',\n  resolveAll: resolveAllAttention,\n  tokenize: tokenizeAttention\n};\n\n/**\n * Take all events and resolve attention to emphasis or strong.\n *\n * @type {Resolver}\n */\n// eslint-disable-next-line complexity\nfunction resolveAllAttention(events, context) {\n  let index = -1;\n  /** @type {number} */\n  let open;\n  /** @type {Token} */\n  let group;\n  /** @type {Token} */\n  let text;\n  /** @type {Token} */\n  let openingSequence;\n  /** @type {Token} */\n  let closingSequence;\n  /** @type {number} */\n  let use;\n  /** @type {Array<Event>} */\n  let nextEvents;\n  /** @type {number} */\n  let offset;\n\n  // Walk through all events.\n  //\n  // Note: performance of this is fine on an mb of normal markdown, but it’s\n  // a bottleneck for malicious stuff.\n  while (++index < events.length) {\n    // Find a token that can close.\n    if (events[index][0] === 'enter' && events[index][1].type === 'attentionSequence' && events[index][1]._close) {\n      open = index;\n\n      // Now walk back to find an opener.\n      while (open--) {\n        // Find a token that can open the closer.\n        if (events[open][0] === 'exit' && events[open][1].type === 'attentionSequence' && events[open][1]._open &&\n        // If the markers are the same:\n        context.sliceSerialize(events[open][1]).charCodeAt(0) === context.sliceSerialize(events[index][1]).charCodeAt(0)) {\n          // If the opening can close or the closing can open,\n          // and the close size *is not* a multiple of three,\n          // but the sum of the opening and closing size *is* multiple of three,\n          // then don’t match.\n          if ((events[open][1]._close || events[index][1]._open) && (events[index][1].end.offset - events[index][1].start.offset) % 3 && !((events[open][1].end.offset - events[open][1].start.offset + events[index][1].end.offset - events[index][1].start.offset) % 3)) {\n            continue;\n          }\n\n          // Number of markers to use from the sequence.\n          use = events[open][1].end.offset - events[open][1].start.offset > 1 && events[index][1].end.offset - events[index][1].start.offset > 1 ? 2 : 1;\n          const start = {\n            ...events[open][1].end\n          };\n          const end = {\n            ...events[index][1].start\n          };\n          movePoint(start, -use);\n          movePoint(end, use);\n          openingSequence = {\n            type: use > 1 ? \"strongSequence\" : \"emphasisSequence\",\n            start,\n            end: {\n              ...events[open][1].end\n            }\n          };\n          closingSequence = {\n            type: use > 1 ? \"strongSequence\" : \"emphasisSequence\",\n            start: {\n              ...events[index][1].start\n            },\n            end\n          };\n          text = {\n            type: use > 1 ? \"strongText\" : \"emphasisText\",\n            start: {\n              ...events[open][1].end\n            },\n            end: {\n              ...events[index][1].start\n            }\n          };\n          group = {\n            type: use > 1 ? \"strong\" : \"emphasis\",\n            start: {\n              ...openingSequence.start\n            },\n            end: {\n              ...closingSequence.end\n            }\n          };\n          events[open][1].end = {\n            ...openingSequence.start\n          };\n          events[index][1].start = {\n            ...closingSequence.end\n          };\n          nextEvents = [];\n\n          // If there are more markers in the opening, add them before.\n          if (events[open][1].end.offset - events[open][1].start.offset) {\n            nextEvents = push(nextEvents, [['enter', events[open][1], context], ['exit', events[open][1], context]]);\n          }\n\n          // Opening.\n          nextEvents = push(nextEvents, [['enter', group, context], ['enter', openingSequence, context], ['exit', openingSequence, context], ['enter', text, context]]);\n\n          // Always populated by defaults.\n\n          // Between.\n          nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + 1, index), context));\n\n          // Closing.\n          nextEvents = push(nextEvents, [['exit', text, context], ['enter', closingSequence, context], ['exit', closingSequence, context], ['exit', group, context]]);\n\n          // If there are more markers in the closing, add them after.\n          if (events[index][1].end.offset - events[index][1].start.offset) {\n            offset = 2;\n            nextEvents = push(nextEvents, [['enter', events[index][1], context], ['exit', events[index][1], context]]);\n          } else {\n            offset = 0;\n          }\n          splice(events, open - 1, index - open + 3, nextEvents);\n          index = open + nextEvents.length - offset - 2;\n          break;\n        }\n      }\n    }\n  }\n\n  // Remove remaining sequences.\n  index = -1;\n  while (++index < events.length) {\n    if (events[index][1].type === 'attentionSequence') {\n      events[index][1].type = 'data';\n    }\n  }\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeAttention(effects, ok) {\n  const attentionMarkers = this.parser.constructs.attentionMarkers.null;\n  const previous = this.previous;\n  const before = classifyCharacter(previous);\n\n  /** @type {NonNullable<Code>} */\n  let marker;\n  return start;\n\n  /**\n   * Before a sequence.\n   *\n   * ```markdown\n   * > | **\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    marker = code;\n    effects.enter('attentionSequence');\n    return inside(code);\n  }\n\n  /**\n   * In a sequence.\n   *\n   * ```markdown\n   * > | **\n   *     ^^\n   * ```\n   *\n   * @type {State}\n   */\n  function inside(code) {\n    if (code === marker) {\n      effects.consume(code);\n      return inside;\n    }\n    const token = effects.exit('attentionSequence');\n\n    // To do: next major: move this to resolver, just like `markdown-rs`.\n    const after = classifyCharacter(code);\n\n    // Always populated by defaults.\n\n    const open = !after || after === 2 && before || attentionMarkers.includes(code);\n    const close = !before || before === 2 && after || attentionMarkers.includes(previous);\n    token._open = Boolean(marker === 42 ? open : open && (before || !close));\n    token._close = Boolean(marker === 42 ? close : close && (after || !open));\n    return ok(code);\n  }\n}\n\n/**\n * Move a point a bit.\n *\n * Note: `move` only works inside lines! It’s not possible to move past other\n * chunks (replacement characters, tabs, or line endings).\n *\n * @param {Point} point\n *   Point.\n * @param {number} offset\n *   Amount to move.\n * @returns {undefined}\n *   Nothing.\n */\nfunction movePoint(point, offset) {\n  point.column += offset;\n  point.offset += offset;\n  point._bufferIndex += offset;\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { asciiAlphanumeric, asciiAlpha, asciiAtext, asciiControl } from 'micromark-util-character';\n/** @type {Construct} */\nexport const autolink = {\n  name: 'autolink',\n  tokenize: tokenizeAutolink\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeAutolink(effects, ok, nok) {\n  let size = 0;\n  return start;\n\n  /**\n   * Start of an autolink.\n   *\n   * ```markdown\n   * > | a<https://example.com>b\n   *      ^\n   * > | a<user@example.com>b\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"autolink\");\n    effects.enter(\"autolinkMarker\");\n    effects.consume(code);\n    effects.exit(\"autolinkMarker\");\n    effects.enter(\"autolinkProtocol\");\n    return open;\n  }\n\n  /**\n   * After `<`, at protocol or atext.\n   *\n   * ```markdown\n   * > | a<https://example.com>b\n   *       ^\n   * > | a<user@example.com>b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function open(code) {\n    if (asciiAlpha(code)) {\n      effects.consume(code);\n      return schemeOrEmailAtext;\n    }\n    if (code === 64) {\n      return nok(code);\n    }\n    return emailAtext(code);\n  }\n\n  /**\n   * At second byte of protocol or atext.\n   *\n   * ```markdown\n   * > | a<https://example.com>b\n   *        ^\n   * > | a<user@example.com>b\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function schemeOrEmailAtext(code) {\n    // ASCII alphanumeric and `+`, `-`, and `.`.\n    if (code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)) {\n      // Count the previous alphabetical from `open` too.\n      size = 1;\n      return schemeInsideOrEmailAtext(code);\n    }\n    return emailAtext(code);\n  }\n\n  /**\n   * In ambiguous protocol or atext.\n   *\n   * ```markdown\n   * > | a<https://example.com>b\n   *        ^\n   * > | a<user@example.com>b\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function schemeInsideOrEmailAtext(code) {\n    if (code === 58) {\n      effects.consume(code);\n      size = 0;\n      return urlInside;\n    }\n\n    // ASCII alphanumeric and `+`, `-`, and `.`.\n    if ((code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)) && size++ < 32) {\n      effects.consume(code);\n      return schemeInsideOrEmailAtext;\n    }\n    size = 0;\n    return emailAtext(code);\n  }\n\n  /**\n   * After protocol, in URL.\n   *\n   * ```markdown\n   * > | a<https://example.com>b\n   *             ^\n   * ```\n   *\n   * @type {State}\n   */\n  function urlInside(code) {\n    if (code === 62) {\n      effects.exit(\"autolinkProtocol\");\n      effects.enter(\"autolinkMarker\");\n      effects.consume(code);\n      effects.exit(\"autolinkMarker\");\n      effects.exit(\"autolink\");\n      return ok;\n    }\n\n    // ASCII control, space, or `<`.\n    if (code === null || code === 32 || code === 60 || asciiControl(code)) {\n      return nok(code);\n    }\n    effects.consume(code);\n    return urlInside;\n  }\n\n  /**\n   * In email atext.\n   *\n   * ```markdown\n   * > | a<user.name@example.com>b\n   *              ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailAtext(code) {\n    if (code === 64) {\n      effects.consume(code);\n      return emailAtSignOrDot;\n    }\n    if (asciiAtext(code)) {\n      effects.consume(code);\n      return emailAtext;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In label, after at-sign or dot.\n   *\n   * ```markdown\n   * > | a<user.name@example.com>b\n   *                 ^       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailAtSignOrDot(code) {\n    return asciiAlphanumeric(code) ? emailLabel(code) : nok(code);\n  }\n\n  /**\n   * In label, where `.` and `>` are allowed.\n   *\n   * ```markdown\n   * > | a<user.name@example.com>b\n   *                   ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailLabel(code) {\n    if (code === 46) {\n      effects.consume(code);\n      size = 0;\n      return emailAtSignOrDot;\n    }\n    if (code === 62) {\n      // Exit, then change the token type.\n      effects.exit(\"autolinkProtocol\").type = \"autolinkEmail\";\n      effects.enter(\"autolinkMarker\");\n      effects.consume(code);\n      effects.exit(\"autolinkMarker\");\n      effects.exit(\"autolink\");\n      return ok;\n    }\n    return emailValue(code);\n  }\n\n  /**\n   * In label, where `.` and `>` are *not* allowed.\n   *\n   * Though, this is also used in `emailLabel` to parse other values.\n   *\n   * ```markdown\n   * > | a<user.name@ex-ample.com>b\n   *                    ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailValue(code) {\n    // ASCII alphanumeric or `-`.\n    if ((code === 45 || asciiAlphanumeric(code)) && size++ < 63) {\n      const next = code === 45 ? emailValue : emailLabel;\n      effects.consume(code);\n      return next;\n    }\n    return nok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const blankLine = {\n  partial: true,\n  tokenize: tokenizeBlankLine\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeBlankLine(effects, ok, nok) {\n  return start;\n\n  /**\n   * Start of blank line.\n   *\n   * > 👉 **Note**: `␠` represents a space character.\n   *\n   * ```markdown\n   * > | ␠␠␊\n   *     ^\n   * > | ␊\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    return markdownSpace(code) ? factorySpace(effects, after, \"linePrefix\")(code) : after(code);\n  }\n\n  /**\n   * At eof/eol, after optional whitespace.\n   *\n   * > 👉 **Note**: `␠` represents a space character.\n   *\n   * ```markdown\n   * > | ␠␠␊\n   *       ^\n   * > | ␊\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    return code === null || markdownLineEnding(code) ? ok(code) : nok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   Exiter,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const blockQuote = {\n  continuation: {\n    tokenize: tokenizeBlockQuoteContinuation\n  },\n  exit,\n  name: 'blockQuote',\n  tokenize: tokenizeBlockQuoteStart\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeBlockQuoteStart(effects, ok, nok) {\n  const self = this;\n  return start;\n\n  /**\n   * Start of block quote.\n   *\n   * ```markdown\n   * > | > a\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    if (code === 62) {\n      const state = self.containerState;\n      if (!state.open) {\n        effects.enter(\"blockQuote\", {\n          _container: true\n        });\n        state.open = true;\n      }\n      effects.enter(\"blockQuotePrefix\");\n      effects.enter(\"blockQuoteMarker\");\n      effects.consume(code);\n      effects.exit(\"blockQuoteMarker\");\n      return after;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `>`, before optional whitespace.\n   *\n   * ```markdown\n   * > | > a\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    if (markdownSpace(code)) {\n      effects.enter(\"blockQuotePrefixWhitespace\");\n      effects.consume(code);\n      effects.exit(\"blockQuotePrefixWhitespace\");\n      effects.exit(\"blockQuotePrefix\");\n      return ok;\n    }\n    effects.exit(\"blockQuotePrefix\");\n    return ok(code);\n  }\n}\n\n/**\n * Start of block quote continuation.\n *\n * ```markdown\n *   | > a\n * > | > b\n *     ^\n * ```\n *\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeBlockQuoteContinuation(effects, ok, nok) {\n  const self = this;\n  return contStart;\n\n  /**\n   * Start of block quote continuation.\n   *\n   * Also used to parse the first block quote opening.\n   *\n   * ```markdown\n   *   | > a\n   * > | > b\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function contStart(code) {\n    if (markdownSpace(code)) {\n      // Always populated by defaults.\n\n      return factorySpace(effects, contBefore, \"linePrefix\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4)(code);\n    }\n    return contBefore(code);\n  }\n\n  /**\n   * At `>`, after optional whitespace.\n   *\n   * Also used to parse the first block quote opening.\n   *\n   * ```markdown\n   *   | > a\n   * > | > b\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function contBefore(code) {\n    return effects.attempt(blockQuote, ok, nok)(code);\n  }\n}\n\n/** @type {Exiter} */\nfunction exit(effects) {\n  effects.exit(\"blockQuote\");\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { asciiPunctuation } from 'micromark-util-character';\n/** @type {Construct} */\nexport const characterEscape = {\n  name: 'characterEscape',\n  tokenize: tokenizeCharacterEscape\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeCharacterEscape(effects, ok, nok) {\n  return start;\n\n  /**\n   * Start of character escape.\n   *\n   * ```markdown\n   * > | a\\*b\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"characterEscape\");\n    effects.enter(\"escapeMarker\");\n    effects.consume(code);\n    effects.exit(\"escapeMarker\");\n    return inside;\n  }\n\n  /**\n   * After `\\`, at punctuation.\n   *\n   * ```markdown\n   * > | a\\*b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function inside(code) {\n    // ASCII punctuation.\n    if (asciiPunctuation(code)) {\n      effects.enter(\"characterEscapeValue\");\n      effects.consume(code);\n      effects.exit(\"characterEscapeValue\");\n      effects.exit(\"characterEscape\");\n      return ok;\n    }\n    return nok(code);\n  }\n}","/**\n * @import {\n *   Code,\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { decodeNamedCharacterReference } from 'decode-named-character-reference';\nimport { asciiAlphanumeric, asciiDigit, asciiHexDigit } from 'micromark-util-character';\n/** @type {Construct} */\nexport const characterReference = {\n  name: 'characterReference',\n  tokenize: tokenizeCharacterReference\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeCharacterReference(effects, ok, nok) {\n  const self = this;\n  let size = 0;\n  /** @type {number} */\n  let max;\n  /** @type {(code: Code) => boolean} */\n  let test;\n  return start;\n\n  /**\n   * Start of character reference.\n   *\n   * ```markdown\n   * > | a&amp;b\n   *      ^\n   * > | a&#123;b\n   *      ^\n   * > | a&#x9;b\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"characterReference\");\n    effects.enter(\"characterReferenceMarker\");\n    effects.consume(code);\n    effects.exit(\"characterReferenceMarker\");\n    return open;\n  }\n\n  /**\n   * After `&`, at `#` for numeric references or alphanumeric for named\n   * references.\n   *\n   * ```markdown\n   * > | a&amp;b\n   *       ^\n   * > | a&#123;b\n   *       ^\n   * > | a&#x9;b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function open(code) {\n    if (code === 35) {\n      effects.enter(\"characterReferenceMarkerNumeric\");\n      effects.consume(code);\n      effects.exit(\"characterReferenceMarkerNumeric\");\n      return numeric;\n    }\n    effects.enter(\"characterReferenceValue\");\n    max = 31;\n    test = asciiAlphanumeric;\n    return value(code);\n  }\n\n  /**\n   * After `#`, at `x` for hexadecimals or digit for decimals.\n   *\n   * ```markdown\n   * > | a&#123;b\n   *        ^\n   * > | a&#x9;b\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function numeric(code) {\n    if (code === 88 || code === 120) {\n      effects.enter(\"characterReferenceMarkerHexadecimal\");\n      effects.consume(code);\n      effects.exit(\"characterReferenceMarkerHexadecimal\");\n      effects.enter(\"characterReferenceValue\");\n      max = 6;\n      test = asciiHexDigit;\n      return value;\n    }\n    effects.enter(\"characterReferenceValue\");\n    max = 7;\n    test = asciiDigit;\n    return value(code);\n  }\n\n  /**\n   * After markers (`&#x`, `&#`, or `&`), in value, before `;`.\n   *\n   * The character reference kind defines what and how many characters are\n   * allowed.\n   *\n   * ```markdown\n   * > | a&amp;b\n   *       ^^^\n   * > | a&#123;b\n   *        ^^^\n   * > | a&#x9;b\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function value(code) {\n    if (code === 59 && size) {\n      const token = effects.exit(\"characterReferenceValue\");\n      if (test === asciiAlphanumeric && !decodeNamedCharacterReference(self.sliceSerialize(token))) {\n        return nok(code);\n      }\n\n      // To do: `markdown-rs` uses a different name:\n      // `CharacterReferenceMarkerSemi`.\n      effects.enter(\"characterReferenceMarker\");\n      effects.consume(code);\n      effects.exit(\"characterReferenceMarker\");\n      effects.exit(\"characterReference\");\n      return ok;\n    }\n    if (test(code) && size++ < max) {\n      effects.consume(code);\n      return value;\n    }\n    return nok(code);\n  }\n}","/**\n * @import {\n *   Code,\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nconst nonLazyContinuation = {\n  partial: true,\n  tokenize: tokenizeNonLazyContinuation\n};\n\n/** @type {Construct} */\nexport const codeFenced = {\n  concrete: true,\n  name: 'codeFenced',\n  tokenize: tokenizeCodeFenced\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeCodeFenced(effects, ok, nok) {\n  const self = this;\n  /** @type {Construct} */\n  const closeStart = {\n    partial: true,\n    tokenize: tokenizeCloseStart\n  };\n  let initialPrefix = 0;\n  let sizeOpen = 0;\n  /** @type {NonNullable<Code>} */\n  let marker;\n  return start;\n\n  /**\n   * Start of code.\n   *\n   * ```markdown\n   * > | ~~~js\n   *     ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // To do: parse whitespace like `markdown-rs`.\n    return beforeSequenceOpen(code);\n  }\n\n  /**\n   * In opening fence, after prefix, at sequence.\n   *\n   * ```markdown\n   * > | ~~~js\n   *     ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function beforeSequenceOpen(code) {\n    const tail = self.events[self.events.length - 1];\n    initialPrefix = tail && tail[1].type === \"linePrefix\" ? tail[2].sliceSerialize(tail[1], true).length : 0;\n    marker = code;\n    effects.enter(\"codeFenced\");\n    effects.enter(\"codeFencedFence\");\n    effects.enter(\"codeFencedFenceSequence\");\n    return sequenceOpen(code);\n  }\n\n  /**\n   * In opening fence sequence.\n   *\n   * ```markdown\n   * > | ~~~js\n   *      ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function sequenceOpen(code) {\n    if (code === marker) {\n      sizeOpen++;\n      effects.consume(code);\n      return sequenceOpen;\n    }\n    if (sizeOpen < 3) {\n      return nok(code);\n    }\n    effects.exit(\"codeFencedFenceSequence\");\n    return markdownSpace(code) ? factorySpace(effects, infoBefore, \"whitespace\")(code) : infoBefore(code);\n  }\n\n  /**\n   * In opening fence, after the sequence (and optional whitespace), before info.\n   *\n   * ```markdown\n   * > | ~~~js\n   *        ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function infoBefore(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"codeFencedFence\");\n      return self.interrupt ? ok(code) : effects.check(nonLazyContinuation, atNonLazyBreak, after)(code);\n    }\n    effects.enter(\"codeFencedFenceInfo\");\n    effects.enter(\"chunkString\", {\n      contentType: \"string\"\n    });\n    return info(code);\n  }\n\n  /**\n   * In info.\n   *\n   * ```markdown\n   * > | ~~~js\n   *        ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function info(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"chunkString\");\n      effects.exit(\"codeFencedFenceInfo\");\n      return infoBefore(code);\n    }\n    if (markdownSpace(code)) {\n      effects.exit(\"chunkString\");\n      effects.exit(\"codeFencedFenceInfo\");\n      return factorySpace(effects, metaBefore, \"whitespace\")(code);\n    }\n    if (code === 96 && code === marker) {\n      return nok(code);\n    }\n    effects.consume(code);\n    return info;\n  }\n\n  /**\n   * In opening fence, after info and whitespace, before meta.\n   *\n   * ```markdown\n   * > | ~~~js eval\n   *           ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function metaBefore(code) {\n    if (code === null || markdownLineEnding(code)) {\n      return infoBefore(code);\n    }\n    effects.enter(\"codeFencedFenceMeta\");\n    effects.enter(\"chunkString\", {\n      contentType: \"string\"\n    });\n    return meta(code);\n  }\n\n  /**\n   * In meta.\n   *\n   * ```markdown\n   * > | ~~~js eval\n   *           ^\n   *   | alert(1)\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function meta(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"chunkString\");\n      effects.exit(\"codeFencedFenceMeta\");\n      return infoBefore(code);\n    }\n    if (code === 96 && code === marker) {\n      return nok(code);\n    }\n    effects.consume(code);\n    return meta;\n  }\n\n  /**\n   * At eol/eof in code, before a non-lazy closing fence or content.\n   *\n   * ```markdown\n   * > | ~~~js\n   *          ^\n   * > | alert(1)\n   *             ^\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function atNonLazyBreak(code) {\n    return effects.attempt(closeStart, after, contentBefore)(code);\n  }\n\n  /**\n   * Before code content, not a closing fence, at eol.\n   *\n   * ```markdown\n   *   | ~~~js\n   * > | alert(1)\n   *             ^\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function contentBefore(code) {\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return contentStart;\n  }\n\n  /**\n   * Before code content, not a closing fence.\n   *\n   * ```markdown\n   *   | ~~~js\n   * > | alert(1)\n   *     ^\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function contentStart(code) {\n    return initialPrefix > 0 && markdownSpace(code) ? factorySpace(effects, beforeContentChunk, \"linePrefix\", initialPrefix + 1)(code) : beforeContentChunk(code);\n  }\n\n  /**\n   * Before code content, after optional prefix.\n   *\n   * ```markdown\n   *   | ~~~js\n   * > | alert(1)\n   *     ^\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function beforeContentChunk(code) {\n    if (code === null || markdownLineEnding(code)) {\n      return effects.check(nonLazyContinuation, atNonLazyBreak, after)(code);\n    }\n    effects.enter(\"codeFlowValue\");\n    return contentChunk(code);\n  }\n\n  /**\n   * In code content.\n   *\n   * ```markdown\n   *   | ~~~js\n   * > | alert(1)\n   *     ^^^^^^^^\n   *   | ~~~\n   * ```\n   *\n   * @type {State}\n   */\n  function contentChunk(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"codeFlowValue\");\n      return beforeContentChunk(code);\n    }\n    effects.consume(code);\n    return contentChunk;\n  }\n\n  /**\n   * After code.\n   *\n   * ```markdown\n   *   | ~~~js\n   *   | alert(1)\n   * > | ~~~\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    effects.exit(\"codeFenced\");\n    return ok(code);\n  }\n\n  /**\n   * @this {TokenizeContext}\n   *   Context.\n   * @type {Tokenizer}\n   */\n  function tokenizeCloseStart(effects, ok, nok) {\n    let size = 0;\n    return startBefore;\n\n    /**\n     *\n     *\n     * @type {State}\n     */\n    function startBefore(code) {\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      return start;\n    }\n\n    /**\n     * Before closing fence, at optional whitespace.\n     *\n     * ```markdown\n     *   | ~~~js\n     *   | alert(1)\n     * > | ~~~\n     *     ^\n     * ```\n     *\n     * @type {State}\n     */\n    function start(code) {\n      // Always populated by defaults.\n\n      // To do: `enter` here or in next state?\n      effects.enter(\"codeFencedFence\");\n      return markdownSpace(code) ? factorySpace(effects, beforeSequenceClose, \"linePrefix\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4)(code) : beforeSequenceClose(code);\n    }\n\n    /**\n     * In closing fence, after optional whitespace, at sequence.\n     *\n     * ```markdown\n     *   | ~~~js\n     *   | alert(1)\n     * > | ~~~\n     *     ^\n     * ```\n     *\n     * @type {State}\n     */\n    function beforeSequenceClose(code) {\n      if (code === marker) {\n        effects.enter(\"codeFencedFenceSequence\");\n        return sequenceClose(code);\n      }\n      return nok(code);\n    }\n\n    /**\n     * In closing fence sequence.\n     *\n     * ```markdown\n     *   | ~~~js\n     *   | alert(1)\n     * > | ~~~\n     *     ^\n     * ```\n     *\n     * @type {State}\n     */\n    function sequenceClose(code) {\n      if (code === marker) {\n        size++;\n        effects.consume(code);\n        return sequenceClose;\n      }\n      if (size >= sizeOpen) {\n        effects.exit(\"codeFencedFenceSequence\");\n        return markdownSpace(code) ? factorySpace(effects, sequenceCloseAfter, \"whitespace\")(code) : sequenceCloseAfter(code);\n      }\n      return nok(code);\n    }\n\n    /**\n     * After closing fence sequence, after optional whitespace.\n     *\n     * ```markdown\n     *   | ~~~js\n     *   | alert(1)\n     * > | ~~~\n     *        ^\n     * ```\n     *\n     * @type {State}\n     */\n    function sequenceCloseAfter(code) {\n      if (code === null || markdownLineEnding(code)) {\n        effects.exit(\"codeFencedFence\");\n        return ok(code);\n      }\n      return nok(code);\n    }\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeNonLazyContinuation(effects, ok, nok) {\n  const self = this;\n  return start;\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function start(code) {\n    if (code === null) {\n      return nok(code);\n    }\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return lineStart;\n  }\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function lineStart(code) {\n    return self.parser.lazy[self.now().line] ? nok(code) : ok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const codeIndented = {\n  name: 'codeIndented',\n  tokenize: tokenizeCodeIndented\n};\n\n/** @type {Construct} */\nconst furtherStart = {\n  partial: true,\n  tokenize: tokenizeFurtherStart\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeCodeIndented(effects, ok, nok) {\n  const self = this;\n  return start;\n\n  /**\n   * Start of code (indented).\n   *\n   * > **Parsing note**: it is not needed to check if this first line is a\n   * > filled line (that it has a non-whitespace character), because blank lines\n   * > are parsed already, so we never run into that.\n   *\n   * ```markdown\n   * > |     aaa\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // To do: manually check if interrupting like `markdown-rs`.\n\n    effects.enter(\"codeIndented\");\n    // To do: use an improved `space_or_tab` function like `markdown-rs`,\n    // so that we can drop the next state.\n    return factorySpace(effects, afterPrefix, \"linePrefix\", 4 + 1)(code);\n  }\n\n  /**\n   * At start, after 1 or 4 spaces.\n   *\n   * ```markdown\n   * > |     aaa\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function afterPrefix(code) {\n    const tail = self.events[self.events.length - 1];\n    return tail && tail[1].type === \"linePrefix\" && tail[2].sliceSerialize(tail[1], true).length >= 4 ? atBreak(code) : nok(code);\n  }\n\n  /**\n   * At a break.\n   *\n   * ```markdown\n   * > |     aaa\n   *         ^  ^\n   * ```\n   *\n   * @type {State}\n   */\n  function atBreak(code) {\n    if (code === null) {\n      return after(code);\n    }\n    if (markdownLineEnding(code)) {\n      return effects.attempt(furtherStart, atBreak, after)(code);\n    }\n    effects.enter(\"codeFlowValue\");\n    return inside(code);\n  }\n\n  /**\n   * In code content.\n   *\n   * ```markdown\n   * > |     aaa\n   *         ^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function inside(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"codeFlowValue\");\n      return atBreak(code);\n    }\n    effects.consume(code);\n    return inside;\n  }\n\n  /** @type {State} */\n  function after(code) {\n    effects.exit(\"codeIndented\");\n    // To do: allow interrupting like `markdown-rs`.\n    // Feel free to interrupt.\n    // tokenizer.interrupt = false\n    return ok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeFurtherStart(effects, ok, nok) {\n  const self = this;\n  return furtherStart;\n\n  /**\n   * At eol, trying to parse another indent.\n   *\n   * ```markdown\n   * > |     aaa\n   *            ^\n   *   |     bbb\n   * ```\n   *\n   * @type {State}\n   */\n  function furtherStart(code) {\n    // To do: improve `lazy` / `pierce` handling.\n    // If this is a lazy line, it can’t be code.\n    if (self.parser.lazy[self.now().line]) {\n      return nok(code);\n    }\n    if (markdownLineEnding(code)) {\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      return furtherStart;\n    }\n\n    // To do: the code here in `micromark-js` is a bit different from\n    // `markdown-rs` because there it can attempt spaces.\n    // We can’t yet.\n    //\n    // To do: use an improved `space_or_tab` function like `markdown-rs`,\n    // so that we can drop the next state.\n    return factorySpace(effects, afterPrefix, \"linePrefix\", 4 + 1)(code);\n  }\n\n  /**\n   * At start, after 1 or 4 spaces.\n   *\n   * ```markdown\n   * > |     aaa\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function afterPrefix(code) {\n    const tail = self.events[self.events.length - 1];\n    return tail && tail[1].type === \"linePrefix\" && tail[2].sliceSerialize(tail[1], true).length >= 4 ? ok(code) : markdownLineEnding(code) ? furtherStart(code) : nok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   Previous,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer,\n *   Token\n * } from 'micromark-util-types'\n */\n\nimport { markdownLineEnding } from 'micromark-util-character';\n/** @type {Construct} */\nexport const codeText = {\n  name: 'codeText',\n  previous,\n  resolve: resolveCodeText,\n  tokenize: tokenizeCodeText\n};\n\n// To do: next major: don’t resolve, like `markdown-rs`.\n/** @type {Resolver} */\nfunction resolveCodeText(events) {\n  let tailExitIndex = events.length - 4;\n  let headEnterIndex = 3;\n  /** @type {number} */\n  let index;\n  /** @type {number | undefined} */\n  let enter;\n\n  // If we start and end with an EOL or a space.\n  if ((events[headEnterIndex][1].type === \"lineEnding\" || events[headEnterIndex][1].type === 'space') && (events[tailExitIndex][1].type === \"lineEnding\" || events[tailExitIndex][1].type === 'space')) {\n    index = headEnterIndex;\n\n    // And we have data.\n    while (++index < tailExitIndex) {\n      if (events[index][1].type === \"codeTextData\") {\n        // Then we have padding.\n        events[headEnterIndex][1].type = \"codeTextPadding\";\n        events[tailExitIndex][1].type = \"codeTextPadding\";\n        headEnterIndex += 2;\n        tailExitIndex -= 2;\n        break;\n      }\n    }\n  }\n\n  // Merge adjacent spaces and data.\n  index = headEnterIndex - 1;\n  tailExitIndex++;\n  while (++index <= tailExitIndex) {\n    if (enter === undefined) {\n      if (index !== tailExitIndex && events[index][1].type !== \"lineEnding\") {\n        enter = index;\n      }\n    } else if (index === tailExitIndex || events[index][1].type === \"lineEnding\") {\n      events[enter][1].type = \"codeTextData\";\n      if (index !== enter + 2) {\n        events[enter][1].end = events[index - 1][1].end;\n        events.splice(enter + 2, index - enter - 2);\n        tailExitIndex -= index - enter - 2;\n        index = enter + 2;\n      }\n      enter = undefined;\n    }\n  }\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Previous}\n */\nfunction previous(code) {\n  // If there is a previous code, there will always be a tail.\n  return code !== 96 || this.events[this.events.length - 1][1].type === \"characterEscape\";\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeCodeText(effects, ok, nok) {\n  const self = this;\n  let sizeOpen = 0;\n  /** @type {number} */\n  let size;\n  /** @type {Token} */\n  let token;\n  return start;\n\n  /**\n   * Start of code (text).\n   *\n   * ```markdown\n   * > | `a`\n   *     ^\n   * > | \\`a`\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"codeText\");\n    effects.enter(\"codeTextSequence\");\n    return sequenceOpen(code);\n  }\n\n  /**\n   * In opening sequence.\n   *\n   * ```markdown\n   * > | `a`\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function sequenceOpen(code) {\n    if (code === 96) {\n      effects.consume(code);\n      sizeOpen++;\n      return sequenceOpen;\n    }\n    effects.exit(\"codeTextSequence\");\n    return between(code);\n  }\n\n  /**\n   * Between something and something else.\n   *\n   * ```markdown\n   * > | `a`\n   *      ^^\n   * ```\n   *\n   * @type {State}\n   */\n  function between(code) {\n    // EOF.\n    if (code === null) {\n      return nok(code);\n    }\n\n    // To do: next major: don’t do spaces in resolve, but when compiling,\n    // like `markdown-rs`.\n    // Tabs don’t work, and virtual spaces don’t make sense.\n    if (code === 32) {\n      effects.enter('space');\n      effects.consume(code);\n      effects.exit('space');\n      return between;\n    }\n\n    // Closing fence? Could also be data.\n    if (code === 96) {\n      token = effects.enter(\"codeTextSequence\");\n      size = 0;\n      return sequenceClose(code);\n    }\n    if (markdownLineEnding(code)) {\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      return between;\n    }\n\n    // Data.\n    effects.enter(\"codeTextData\");\n    return data(code);\n  }\n\n  /**\n   * In data.\n   *\n   * ```markdown\n   * > | `a`\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function data(code) {\n    if (code === null || code === 32 || code === 96 || markdownLineEnding(code)) {\n      effects.exit(\"codeTextData\");\n      return between(code);\n    }\n    effects.consume(code);\n    return data;\n  }\n\n  /**\n   * In closing sequence.\n   *\n   * ```markdown\n   * > | `a`\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function sequenceClose(code) {\n    // More.\n    if (code === 96) {\n      effects.consume(code);\n      size++;\n      return sequenceClose;\n    }\n\n    // Done!\n    if (size === sizeOpen) {\n      effects.exit(\"codeTextSequence\");\n      effects.exit(\"codeText\");\n      return ok(code);\n    }\n\n    // More or less accents: mark as data.\n    token.type = \"codeTextData\";\n    return data(code);\n  }\n}","/**\n * Some of the internal operations of micromark do lots of editing\n * operations on very large arrays. This runs into problems with two\n * properties of most circa-2020 JavaScript interpreters:\n *\n *  - Array-length modifications at the high end of an array (push/pop) are\n *    expected to be common and are implemented in (amortized) time\n *    proportional to the number of elements added or removed, whereas\n *    other operations (shift/unshift and splice) are much less efficient.\n *  - Function arguments are passed on the stack, so adding tens of thousands\n *    of elements to an array with `arr.push(...newElements)` will frequently\n *    cause stack overflows. (see <https://stackoverflow.com/questions/22123769/rangeerror-maximum-call-stack-size-exceeded-why>)\n *\n * SpliceBuffers are an implementation of gap buffers, which are a\n * generalization of the \"queue made of two stacks\" idea. The splice buffer\n * maintains a cursor, and moving the cursor has cost proportional to the\n * distance the cursor moves, but inserting, deleting, or splicing in\n * new information at the cursor is as efficient as the push/pop operation.\n * This allows for an efficient sequence of splices (or pushes, pops, shifts,\n * or unshifts) as long such edits happen at the same part of the array or\n * generally sweep through the array from the beginning to the end.\n *\n * The interface for splice buffers also supports large numbers of inputs by\n * passing a single array argument rather passing multiple arguments on the\n * function call stack.\n *\n * @template T\n *   Item type.\n */\nexport class SpliceBuffer {\n  /**\n   * @param {ReadonlyArray<T> | null | undefined} [initial]\n   *   Initial items (optional).\n   * @returns\n   *   Splice buffer.\n   */\n  constructor(initial) {\n    /** @type {Array<T>} */\n    this.left = initial ? [...initial] : [];\n    /** @type {Array<T>} */\n    this.right = [];\n  }\n\n  /**\n   * Array access;\n   * does not move the cursor.\n   *\n   * @param {number} index\n   *   Index.\n   * @return {T}\n   *   Item.\n   */\n  get(index) {\n    if (index < 0 || index >= this.left.length + this.right.length) {\n      throw new RangeError('Cannot access index `' + index + '` in a splice buffer of size `' + (this.left.length + this.right.length) + '`');\n    }\n    if (index < this.left.length) return this.left[index];\n    return this.right[this.right.length - index + this.left.length - 1];\n  }\n\n  /**\n   * The length of the splice buffer, one greater than the largest index in the\n   * array.\n   */\n  get length() {\n    return this.left.length + this.right.length;\n  }\n\n  /**\n   * Remove and return `list[0]`;\n   * moves the cursor to `0`.\n   *\n   * @returns {T | undefined}\n   *   Item, optional.\n   */\n  shift() {\n    this.setCursor(0);\n    return this.right.pop();\n  }\n\n  /**\n   * Slice the buffer to get an array;\n   * does not move the cursor.\n   *\n   * @param {number} start\n   *   Start.\n   * @param {number | null | undefined} [end]\n   *   End (optional).\n   * @returns {Array<T>}\n   *   Array of items.\n   */\n  slice(start, end) {\n    /** @type {number} */\n    const stop = end === null || end === undefined ? Number.POSITIVE_INFINITY : end;\n    if (stop < this.left.length) {\n      return this.left.slice(start, stop);\n    }\n    if (start > this.left.length) {\n      return this.right.slice(this.right.length - stop + this.left.length, this.right.length - start + this.left.length).reverse();\n    }\n    return this.left.slice(start).concat(this.right.slice(this.right.length - stop + this.left.length).reverse());\n  }\n\n  /**\n   * Mimics the behavior of Array.prototype.splice() except for the change of\n   * interface necessary to avoid segfaults when patching in very large arrays.\n   *\n   * This operation moves cursor is moved to `start` and results in the cursor\n   * placed after any inserted items.\n   *\n   * @param {number} start\n   *   Start;\n   *   zero-based index at which to start changing the array;\n   *   negative numbers count backwards from the end of the array and values\n   *   that are out-of bounds are clamped to the appropriate end of the array.\n   * @param {number | null | undefined} [deleteCount=0]\n   *   Delete count (default: `0`);\n   *   maximum number of elements to delete, starting from start.\n   * @param {Array<T> | null | undefined} [items=[]]\n   *   Items to include in place of the deleted items (default: `[]`).\n   * @return {Array<T>}\n   *   Any removed items.\n   */\n  splice(start, deleteCount, items) {\n    /** @type {number} */\n    const count = deleteCount || 0;\n    this.setCursor(Math.trunc(start));\n    const removed = this.right.splice(this.right.length - count, Number.POSITIVE_INFINITY);\n    if (items) chunkedPush(this.left, items);\n    return removed.reverse();\n  }\n\n  /**\n   * Remove and return the highest-numbered item in the array, so\n   * `list[list.length - 1]`;\n   * Moves the cursor to `length`.\n   *\n   * @returns {T | undefined}\n   *   Item, optional.\n   */\n  pop() {\n    this.setCursor(Number.POSITIVE_INFINITY);\n    return this.left.pop();\n  }\n\n  /**\n   * Inserts a single item to the high-numbered side of the array;\n   * moves the cursor to `length`.\n   *\n   * @param {T} item\n   *   Item.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  push(item) {\n    this.setCursor(Number.POSITIVE_INFINITY);\n    this.left.push(item);\n  }\n\n  /**\n   * Inserts many items to the high-numbered side of the array.\n   * Moves the cursor to `length`.\n   *\n   * @param {Array<T>} items\n   *   Items.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  pushMany(items) {\n    this.setCursor(Number.POSITIVE_INFINITY);\n    chunkedPush(this.left, items);\n  }\n\n  /**\n   * Inserts a single item to the low-numbered side of the array;\n   * Moves the cursor to `0`.\n   *\n   * @param {T} item\n   *   Item.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  unshift(item) {\n    this.setCursor(0);\n    this.right.push(item);\n  }\n\n  /**\n   * Inserts many items to the low-numbered side of the array;\n   * moves the cursor to `0`.\n   *\n   * @param {Array<T>} items\n   *   Items.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  unshiftMany(items) {\n    this.setCursor(0);\n    chunkedPush(this.right, items.reverse());\n  }\n\n  /**\n   * Move the cursor to a specific position in the array. Requires\n   * time proportional to the distance moved.\n   *\n   * If `n < 0`, the cursor will end up at the beginning.\n   * If `n > length`, the cursor will end up at the end.\n   *\n   * @param {number} n\n   *   Position.\n   * @return {undefined}\n   *   Nothing.\n   */\n  setCursor(n) {\n    if (n === this.left.length || n > this.left.length && this.right.length === 0 || n < 0 && this.left.length === 0) return;\n    if (n < this.left.length) {\n      // Move cursor to the this.left\n      const removed = this.left.splice(n, Number.POSITIVE_INFINITY);\n      chunkedPush(this.right, removed.reverse());\n    } else {\n      // Move cursor to the this.right\n      const removed = this.right.splice(this.left.length + this.right.length - n, Number.POSITIVE_INFINITY);\n      chunkedPush(this.left, removed.reverse());\n    }\n  }\n}\n\n/**\n * Avoid stack overflow by pushing items onto the stack in segments\n *\n * @template T\n *   Item type.\n * @param {Array<T>} list\n *   List to inject into.\n * @param {ReadonlyArray<T>} right\n *   Items to inject.\n * @return {undefined}\n *   Nothing.\n */\nfunction chunkedPush(list, right) {\n  /** @type {number} */\n  let chunkStart = 0;\n  if (right.length < 10000) {\n    list.push(...right);\n  } else {\n    while (chunkStart < right.length) {\n      list.push(...right.slice(chunkStart, chunkStart + 10000));\n      chunkStart += 10000;\n    }\n  }\n}","/**\n * @import {Chunk, Event, Token} from 'micromark-util-types'\n */\n\nimport { splice } from 'micromark-util-chunked';\nimport { SpliceBuffer } from './lib/splice-buffer.js';\n\n// Hidden API exposed for testing.\nexport { SpliceBuffer } from './lib/splice-buffer.js';\n\n/**\n * Tokenize subcontent.\n *\n * @param {Array<Event>} eventsArray\n *   List of events.\n * @returns {boolean}\n *   Whether subtokens were found.\n */\n// eslint-disable-next-line complexity\nexport function subtokenize(eventsArray) {\n  /** @type {Record<string, number>} */\n  const jumps = {};\n  let index = -1;\n  /** @type {Event} */\n  let event;\n  /** @type {number | undefined} */\n  let lineIndex;\n  /** @type {number} */\n  let otherIndex;\n  /** @type {Event} */\n  let otherEvent;\n  /** @type {Array<Event>} */\n  let parameters;\n  /** @type {Array<Event>} */\n  let subevents;\n  /** @type {boolean | undefined} */\n  let more;\n  const events = new SpliceBuffer(eventsArray);\n  while (++index < events.length) {\n    while (index in jumps) {\n      index = jumps[index];\n    }\n    event = events.get(index);\n\n    // Add a hook for the GFM tasklist extension, which needs to know if text\n    // is in the first content of a list item.\n    if (index && event[1].type === \"chunkFlow\" && events.get(index - 1)[1].type === \"listItemPrefix\") {\n      subevents = event[1]._tokenizer.events;\n      otherIndex = 0;\n      if (otherIndex < subevents.length && subevents[otherIndex][1].type === \"lineEndingBlank\") {\n        otherIndex += 2;\n      }\n      if (otherIndex < subevents.length && subevents[otherIndex][1].type === \"content\") {\n        while (++otherIndex < subevents.length) {\n          if (subevents[otherIndex][1].type === \"content\") {\n            break;\n          }\n          if (subevents[otherIndex][1].type === \"chunkText\") {\n            subevents[otherIndex][1]._isInFirstContentOfListItem = true;\n            otherIndex++;\n          }\n        }\n      }\n    }\n\n    // Enter.\n    if (event[0] === 'enter') {\n      if (event[1].contentType) {\n        Object.assign(jumps, subcontent(events, index));\n        index = jumps[index];\n        more = true;\n      }\n    }\n    // Exit.\n    else if (event[1]._container) {\n      otherIndex = index;\n      lineIndex = undefined;\n      while (otherIndex--) {\n        otherEvent = events.get(otherIndex);\n        if (otherEvent[1].type === \"lineEnding\" || otherEvent[1].type === \"lineEndingBlank\") {\n          if (otherEvent[0] === 'enter') {\n            if (lineIndex) {\n              events.get(lineIndex)[1].type = \"lineEndingBlank\";\n            }\n            otherEvent[1].type = \"lineEnding\";\n            lineIndex = otherIndex;\n          }\n        } else if (otherEvent[1].type === \"linePrefix\" || otherEvent[1].type === \"listItemIndent\") {\n          // Move past.\n        } else {\n          break;\n        }\n      }\n      if (lineIndex) {\n        // Fix position.\n        event[1].end = {\n          ...events.get(lineIndex)[1].start\n        };\n\n        // Switch container exit w/ line endings.\n        parameters = events.slice(lineIndex, index);\n        parameters.unshift(event);\n        events.splice(lineIndex, index - lineIndex + 1, parameters);\n      }\n    }\n  }\n\n  // The changes to the `events` buffer must be copied back into the eventsArray\n  splice(eventsArray, 0, Number.POSITIVE_INFINITY, events.slice(0));\n  return !more;\n}\n\n/**\n * Tokenize embedded tokens.\n *\n * @param {SpliceBuffer<Event>} events\n *   Events.\n * @param {number} eventIndex\n *   Index.\n * @returns {Record<string, number>}\n *   Gaps.\n */\nfunction subcontent(events, eventIndex) {\n  const token = events.get(eventIndex)[1];\n  const context = events.get(eventIndex)[2];\n  let startPosition = eventIndex - 1;\n  /** @type {Array<number>} */\n  const startPositions = [];\n  let tokenizer = token._tokenizer;\n  if (!tokenizer) {\n    tokenizer = context.parser[token.contentType](token.start);\n    if (token._contentTypeTextTrailing) {\n      tokenizer._contentTypeTextTrailing = true;\n    }\n  }\n  const childEvents = tokenizer.events;\n  /** @type {Array<[number, number]>} */\n  const jumps = [];\n  /** @type {Record<string, number>} */\n  const gaps = {};\n  /** @type {Array<Chunk>} */\n  let stream;\n  /** @type {Token | undefined} */\n  let previous;\n  let index = -1;\n  /** @type {Token | undefined} */\n  let current = token;\n  let adjust = 0;\n  let start = 0;\n  const breaks = [start];\n\n  // Loop forward through the linked tokens to pass them in order to the\n  // subtokenizer.\n  while (current) {\n    // Find the position of the event for this token.\n    while (events.get(++startPosition)[1] !== current) {\n      // Empty.\n    }\n    startPositions.push(startPosition);\n    if (!current._tokenizer) {\n      stream = context.sliceStream(current);\n      if (!current.next) {\n        stream.push(null);\n      }\n      if (previous) {\n        tokenizer.defineSkip(current.start);\n      }\n      if (current._isInFirstContentOfListItem) {\n        tokenizer._gfmTasklistFirstContentOfListItem = true;\n      }\n      tokenizer.write(stream);\n      if (current._isInFirstContentOfListItem) {\n        tokenizer._gfmTasklistFirstContentOfListItem = undefined;\n      }\n    }\n\n    // Unravel the next token.\n    previous = current;\n    current = current.next;\n  }\n\n  // Now, loop back through all events (and linked tokens), to figure out which\n  // parts belong where.\n  current = token;\n  while (++index < childEvents.length) {\n    if (\n    // Find a void token that includes a break.\n    childEvents[index][0] === 'exit' && childEvents[index - 1][0] === 'enter' && childEvents[index][1].type === childEvents[index - 1][1].type && childEvents[index][1].start.line !== childEvents[index][1].end.line) {\n      start = index + 1;\n      breaks.push(start);\n      // Help GC.\n      current._tokenizer = undefined;\n      current.previous = undefined;\n      current = current.next;\n    }\n  }\n\n  // Help GC.\n  tokenizer.events = [];\n\n  // If there’s one more token (which is the cases for lines that end in an\n  // EOF), that’s perfect: the last point we found starts it.\n  // If there isn’t then make sure any remaining content is added to it.\n  if (current) {\n    // Help GC.\n    current._tokenizer = undefined;\n    current.previous = undefined;\n  } else {\n    breaks.pop();\n  }\n\n  // Now splice the events from the subtokenizer into the current events,\n  // moving back to front so that splice indices aren’t affected.\n  index = breaks.length;\n  while (index--) {\n    const slice = childEvents.slice(breaks[index], breaks[index + 1]);\n    const start = startPositions.pop();\n    jumps.push([start, start + slice.length - 1]);\n    events.splice(start, 2, slice);\n  }\n  jumps.reverse();\n  index = -1;\n  while (++index < jumps.length) {\n    gaps[adjust + jumps[index][0]] = adjust + jumps[index][1];\n    adjust += jumps[index][1] - jumps[index][0] - 1;\n  }\n  return gaps;\n}","/**\n * @import {\n *   Construct,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer,\n *   Token\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding } from 'micromark-util-character';\nimport { subtokenize } from 'micromark-util-subtokenize';\n/**\n * No name because it must not be turned off.\n * @type {Construct}\n */\nexport const content = {\n  resolve: resolveContent,\n  tokenize: tokenizeContent\n};\n\n/** @type {Construct} */\nconst continuationConstruct = {\n  partial: true,\n  tokenize: tokenizeContinuation\n};\n\n/**\n * Content is transparent: it’s parsed right now. That way, definitions are also\n * parsed right now: before text in paragraphs (specifically, media) are parsed.\n *\n * @type {Resolver}\n */\nfunction resolveContent(events) {\n  subtokenize(events);\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeContent(effects, ok) {\n  /** @type {Token | undefined} */\n  let previous;\n  return chunkStart;\n\n  /**\n   * Before a content chunk.\n   *\n   * ```markdown\n   * > | abc\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function chunkStart(code) {\n    effects.enter(\"content\");\n    previous = effects.enter(\"chunkContent\", {\n      contentType: \"content\"\n    });\n    return chunkInside(code);\n  }\n\n  /**\n   * In a content chunk.\n   *\n   * ```markdown\n   * > | abc\n   *     ^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function chunkInside(code) {\n    if (code === null) {\n      return contentEnd(code);\n    }\n\n    // To do: in `markdown-rs`, each line is parsed on its own, and everything\n    // is stitched together resolving.\n    if (markdownLineEnding(code)) {\n      return effects.check(continuationConstruct, contentContinue, contentEnd)(code);\n    }\n\n    // Data.\n    effects.consume(code);\n    return chunkInside;\n  }\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function contentEnd(code) {\n    effects.exit(\"chunkContent\");\n    effects.exit(\"content\");\n    return ok(code);\n  }\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function contentContinue(code) {\n    effects.consume(code);\n    effects.exit(\"chunkContent\");\n    previous.next = effects.enter(\"chunkContent\", {\n      contentType: \"content\",\n      previous\n    });\n    previous = previous.next;\n    return chunkInside;\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeContinuation(effects, ok, nok) {\n  const self = this;\n  return startLookahead;\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function startLookahead(code) {\n    effects.exit(\"chunkContent\");\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return factorySpace(effects, prefixed, \"linePrefix\");\n  }\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function prefixed(code) {\n    if (code === null || markdownLineEnding(code)) {\n      return nok(code);\n    }\n\n    // Always populated by defaults.\n\n    const tail = self.events[self.events.length - 1];\n    if (!self.parser.constructs.disable.null.includes('codeIndented') && tail && tail[1].type === \"linePrefix\" && tail[2].sliceSerialize(tail[1], true).length >= 4) {\n      return ok(code);\n    }\n    return effects.interrupt(self.parser.constructs.flow, nok, ok)(code);\n  }\n}","/**\n * @import {Effects, State, TokenType} from 'micromark-util-types'\n */\n\nimport { asciiControl, markdownLineEndingOrSpace, markdownLineEnding } from 'micromark-util-character';\n/**\n * Parse destinations.\n *\n * ###### Examples\n *\n * ```markdown\n * <a>\n * <a\\>b>\n * <a b>\n * <a)>\n * a\n * a\\)b\n * a(b)c\n * a(b)\n * ```\n *\n * @param {Effects} effects\n *   Context.\n * @param {State} ok\n *   State switched to when successful.\n * @param {State} nok\n *   State switched to when unsuccessful.\n * @param {TokenType} type\n *   Type for whole (`<a>` or `b`).\n * @param {TokenType} literalType\n *   Type when enclosed (`<a>`).\n * @param {TokenType} literalMarkerType\n *   Type for enclosing (`<` and `>`).\n * @param {TokenType} rawType\n *   Type when not enclosed (`b`).\n * @param {TokenType} stringType\n *   Type for the value (`a` or `b`).\n * @param {number | undefined} [max=Infinity]\n *   Depth of nested parens (inclusive).\n * @returns {State}\n *   Start state.\n */\nexport function factoryDestination(effects, ok, nok, type, literalType, literalMarkerType, rawType, stringType, max) {\n  const limit = max || Number.POSITIVE_INFINITY;\n  let balance = 0;\n  return start;\n\n  /**\n   * Start of destination.\n   *\n   * ```markdown\n   * > | <aa>\n   *     ^\n   * > | aa\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    if (code === 60) {\n      effects.enter(type);\n      effects.enter(literalType);\n      effects.enter(literalMarkerType);\n      effects.consume(code);\n      effects.exit(literalMarkerType);\n      return enclosedBefore;\n    }\n\n    // ASCII control, space, closing paren.\n    if (code === null || code === 32 || code === 41 || asciiControl(code)) {\n      return nok(code);\n    }\n    effects.enter(type);\n    effects.enter(rawType);\n    effects.enter(stringType);\n    effects.enter(\"chunkString\", {\n      contentType: \"string\"\n    });\n    return raw(code);\n  }\n\n  /**\n   * After `<`, at an enclosed destination.\n   *\n   * ```markdown\n   * > | <aa>\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function enclosedBefore(code) {\n    if (code === 62) {\n      effects.enter(literalMarkerType);\n      effects.consume(code);\n      effects.exit(literalMarkerType);\n      effects.exit(literalType);\n      effects.exit(type);\n      return ok;\n    }\n    effects.enter(stringType);\n    effects.enter(\"chunkString\", {\n      contentType: \"string\"\n    });\n    return enclosed(code);\n  }\n\n  /**\n   * In enclosed destination.\n   *\n   * ```markdown\n   * > | <aa>\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function enclosed(code) {\n    if (code === 62) {\n      effects.exit(\"chunkString\");\n      effects.exit(stringType);\n      return enclosedBefore(code);\n    }\n    if (code === null || code === 60 || markdownLineEnding(code)) {\n      return nok(code);\n    }\n    effects.consume(code);\n    return code === 92 ? enclosedEscape : enclosed;\n  }\n\n  /**\n   * After `\\`, at a special character.\n   *\n   * ```markdown\n   * > | <a\\*a>\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function enclosedEscape(code) {\n    if (code === 60 || code === 62 || code === 92) {\n      effects.consume(code);\n      return enclosed;\n    }\n    return enclosed(code);\n  }\n\n  /**\n   * In raw destination.\n   *\n   * ```markdown\n   * > | aa\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function raw(code) {\n    if (!balance && (code === null || code === 41 || markdownLineEndingOrSpace(code))) {\n      effects.exit(\"chunkString\");\n      effects.exit(stringType);\n      effects.exit(rawType);\n      effects.exit(type);\n      return ok(code);\n    }\n    if (balance < limit && code === 40) {\n      effects.consume(code);\n      balance++;\n      return raw;\n    }\n    if (code === 41) {\n      effects.consume(code);\n      balance--;\n      return raw;\n    }\n\n    // ASCII control (but *not* `\\0`) and space and `(`.\n    // Note: in `markdown-rs`, `\\0` exists in codes, in `micromark-js` it\n    // doesn’t.\n    if (code === null || code === 32 || code === 40 || asciiControl(code)) {\n      return nok(code);\n    }\n    effects.consume(code);\n    return code === 92 ? rawEscape : raw;\n  }\n\n  /**\n   * After `\\`, at special character.\n   *\n   * ```markdown\n   * > | a\\*a\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function rawEscape(code) {\n    if (code === 40 || code === 41 || code === 92) {\n      effects.consume(code);\n      return raw;\n    }\n    return raw(code);\n  }\n}","/**\n * @import {\n *   Effects,\n *   State,\n *   TokenizeContext,\n *   TokenType\n * } from 'micromark-util-types'\n */\n\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/**\n * Parse labels.\n *\n * > 👉 **Note**: labels in markdown are capped at 999 characters in the string.\n *\n * ###### Examples\n *\n * ```markdown\n * [a]\n * [a\n * b]\n * [a\\]b]\n * ```\n *\n * @this {TokenizeContext}\n *   Tokenize context.\n * @param {Effects} effects\n *   Context.\n * @param {State} ok\n *   State switched to when successful.\n * @param {State} nok\n *   State switched to when unsuccessful.\n * @param {TokenType} type\n *   Type of the whole label (`[a]`).\n * @param {TokenType} markerType\n *   Type for the markers (`[` and `]`).\n * @param {TokenType} stringType\n *   Type for the identifier (`a`).\n * @returns {State}\n *   Start state.\n */\nexport function factoryLabel(effects, ok, nok, type, markerType, stringType) {\n  const self = this;\n  let size = 0;\n  /** @type {boolean} */\n  let seen;\n  return start;\n\n  /**\n   * Start of label.\n   *\n   * ```markdown\n   * > | [a]\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(type);\n    effects.enter(markerType);\n    effects.consume(code);\n    effects.exit(markerType);\n    effects.enter(stringType);\n    return atBreak;\n  }\n\n  /**\n   * In label, at something, before something else.\n   *\n   * ```markdown\n   * > | [a]\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function atBreak(code) {\n    if (size > 999 || code === null || code === 91 || code === 93 && !seen ||\n    // To do: remove in the future once we’ve switched from\n    // `micromark-extension-footnote` to `micromark-extension-gfm-footnote`,\n    // which doesn’t need this.\n    // Hidden footnotes hook.\n    /* c8 ignore next 3 */\n    code === 94 && !size && '_hiddenFootnoteSupport' in self.parser.constructs) {\n      return nok(code);\n    }\n    if (code === 93) {\n      effects.exit(stringType);\n      effects.enter(markerType);\n      effects.consume(code);\n      effects.exit(markerType);\n      effects.exit(type);\n      return ok;\n    }\n\n    // To do: indent? Link chunks and EOLs together?\n    if (markdownLineEnding(code)) {\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      return atBreak;\n    }\n    effects.enter(\"chunkString\", {\n      contentType: \"string\"\n    });\n    return labelInside(code);\n  }\n\n  /**\n   * In label, in text.\n   *\n   * ```markdown\n   * > | [a]\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelInside(code) {\n    if (code === null || code === 91 || code === 93 || markdownLineEnding(code) || size++ > 999) {\n      effects.exit(\"chunkString\");\n      return atBreak(code);\n    }\n    effects.consume(code);\n    if (!seen) seen = !markdownSpace(code);\n    return code === 92 ? labelEscape : labelInside;\n  }\n\n  /**\n   * After `\\`, at a special character.\n   *\n   * ```markdown\n   * > | [a\\*a]\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelEscape(code) {\n    if (code === 91 || code === 92 || code === 93) {\n      effects.consume(code);\n      size++;\n      return labelInside;\n    }\n    return labelInside(code);\n  }\n}","/**\n * @import {\n *   Code,\n *   Effects,\n *   State,\n *   TokenType\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding } from 'micromark-util-character';\n/**\n * Parse titles.\n *\n * ###### Examples\n *\n * ```markdown\n * \"a\"\n * 'b'\n * (c)\n * \"a\n * b\"\n * 'a\n *     b'\n * (a\\)b)\n * ```\n *\n * @param {Effects} effects\n *   Context.\n * @param {State} ok\n *   State switched to when successful.\n * @param {State} nok\n *   State switched to when unsuccessful.\n * @param {TokenType} type\n *   Type of the whole title (`\"a\"`, `'b'`, `(c)`).\n * @param {TokenType} markerType\n *   Type for the markers (`\"`, `'`, `(`, and `)`).\n * @param {TokenType} stringType\n *   Type for the value (`a`).\n * @returns {State}\n *   Start state.\n */\nexport function factoryTitle(effects, ok, nok, type, markerType, stringType) {\n  /** @type {NonNullable<Code>} */\n  let marker;\n  return start;\n\n  /**\n   * Start of title.\n   *\n   * ```markdown\n   * > | \"a\"\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    if (code === 34 || code === 39 || code === 40) {\n      effects.enter(type);\n      effects.enter(markerType);\n      effects.consume(code);\n      effects.exit(markerType);\n      marker = code === 40 ? 41 : code;\n      return begin;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After opening marker.\n   *\n   * This is also used at the closing marker.\n   *\n   * ```markdown\n   * > | \"a\"\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function begin(code) {\n    if (code === marker) {\n      effects.enter(markerType);\n      effects.consume(code);\n      effects.exit(markerType);\n      effects.exit(type);\n      return ok;\n    }\n    effects.enter(stringType);\n    return atBreak(code);\n  }\n\n  /**\n   * At something, before something else.\n   *\n   * ```markdown\n   * > | \"a\"\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function atBreak(code) {\n    if (code === marker) {\n      effects.exit(stringType);\n      return begin(marker);\n    }\n    if (code === null) {\n      return nok(code);\n    }\n\n    // Note: blank lines can’t exist in content.\n    if (markdownLineEnding(code)) {\n      // To do: use `space_or_tab_eol_with_options`, connect.\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      return factorySpace(effects, atBreak, \"linePrefix\");\n    }\n    effects.enter(\"chunkString\", {\n      contentType: \"string\"\n    });\n    return inside(code);\n  }\n\n  /**\n   *\n   *\n   * @type {State}\n   */\n  function inside(code) {\n    if (code === marker || code === null || markdownLineEnding(code)) {\n      effects.exit(\"chunkString\");\n      return atBreak(code);\n    }\n    effects.consume(code);\n    return code === 92 ? escape : inside;\n  }\n\n  /**\n   * After `\\`, at a special character.\n   *\n   * ```markdown\n   * > | \"a\\*b\"\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function escape(code) {\n    if (code === marker || code === 92) {\n      effects.consume(code);\n      return inside;\n    }\n    return inside(code);\n  }\n}","/**\n * @import {Effects, State} from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/**\n * Parse spaces and tabs.\n *\n * There is no `nok` parameter:\n *\n * *   line endings or spaces in markdown are often optional, in which case this\n *     factory can be used and `ok` will be switched to whether spaces were found\n *     or not\n * *   one line ending or space can be detected with\n *     `markdownLineEndingOrSpace(code)` right before using `factoryWhitespace`\n *\n * @param {Effects} effects\n *   Context.\n * @param {State} ok\n *   State switched to when successful.\n * @returns {State}\n *   Start state.\n */\nexport function factoryWhitespace(effects, ok) {\n  /** @type {boolean} */\n  let seen;\n  return start;\n\n  /** @type {State} */\n  function start(code) {\n    if (markdownLineEnding(code)) {\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      seen = true;\n      return start;\n    }\n    if (markdownSpace(code)) {\n      return factorySpace(effects, start, seen ? \"linePrefix\" : \"lineSuffix\")(code);\n    }\n    return ok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factoryDestination } from 'micromark-factory-destination';\nimport { factoryLabel } from 'micromark-factory-label';\nimport { factorySpace } from 'micromark-factory-space';\nimport { factoryTitle } from 'micromark-factory-title';\nimport { factoryWhitespace } from 'micromark-factory-whitespace';\nimport { markdownLineEndingOrSpace, markdownLineEnding, markdownSpace } from 'micromark-util-character';\nimport { normalizeIdentifier } from 'micromark-util-normalize-identifier';\n/** @type {Construct} */\nexport const definition = {\n  name: 'definition',\n  tokenize: tokenizeDefinition\n};\n\n/** @type {Construct} */\nconst titleBefore = {\n  partial: true,\n  tokenize: tokenizeTitleBefore\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeDefinition(effects, ok, nok) {\n  const self = this;\n  /** @type {string} */\n  let identifier;\n  return start;\n\n  /**\n   * At start of a definition.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // Do not interrupt paragraphs (but do follow definitions).\n    // To do: do `interrupt` the way `markdown-rs` does.\n    // To do: parse whitespace the way `markdown-rs` does.\n    effects.enter(\"definition\");\n    return before(code);\n  }\n\n  /**\n   * After optional whitespace, at `[`.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function before(code) {\n    // To do: parse whitespace the way `markdown-rs` does.\n\n    return factoryLabel.call(self, effects, labelAfter,\n    // Note: we don’t need to reset the way `markdown-rs` does.\n    nok, \"definitionLabel\", \"definitionLabelMarker\", \"definitionLabelString\")(code);\n  }\n\n  /**\n   * After label.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelAfter(code) {\n    identifier = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));\n    if (code === 58) {\n      effects.enter(\"definitionMarker\");\n      effects.consume(code);\n      effects.exit(\"definitionMarker\");\n      return markerAfter;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After marker.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function markerAfter(code) {\n    // Note: whitespace is optional.\n    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, destinationBefore)(code) : destinationBefore(code);\n  }\n\n  /**\n   * Before destination.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function destinationBefore(code) {\n    return factoryDestination(effects, destinationAfter,\n    // Note: we don’t need to reset the way `markdown-rs` does.\n    nok, \"definitionDestination\", \"definitionDestinationLiteral\", \"definitionDestinationLiteralMarker\", \"definitionDestinationRaw\", \"definitionDestinationString\")(code);\n  }\n\n  /**\n   * After destination.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function destinationAfter(code) {\n    return effects.attempt(titleBefore, after, after)(code);\n  }\n\n  /**\n   * After definition.\n   *\n   * ```markdown\n   * > | [a]: b\n   *           ^\n   * > | [a]: b \"c\"\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    return markdownSpace(code) ? factorySpace(effects, afterWhitespace, \"whitespace\")(code) : afterWhitespace(code);\n  }\n\n  /**\n   * After definition, after optional whitespace.\n   *\n   * ```markdown\n   * > | [a]: b\n   *           ^\n   * > | [a]: b \"c\"\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function afterWhitespace(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"definition\");\n\n      // Note: we don’t care about uniqueness.\n      // It’s likely that that doesn’t happen very frequently.\n      // It is more likely that it wastes precious time.\n      self.parser.defined.push(identifier);\n\n      // To do: `markdown-rs` interrupt.\n      // // You’d be interrupting.\n      // tokenizer.interrupt = true\n      return ok(code);\n    }\n    return nok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeTitleBefore(effects, ok, nok) {\n  return titleBefore;\n\n  /**\n   * After destination, at whitespace.\n   *\n   * ```markdown\n   * > | [a]: b\n   *           ^\n   * > | [a]: b \"c\"\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function titleBefore(code) {\n    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, beforeMarker)(code) : nok(code);\n  }\n\n  /**\n   * At title.\n   *\n   * ```markdown\n   *   | [a]: b\n   * > | \"c\"\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function beforeMarker(code) {\n    return factoryTitle(effects, titleAfter, nok, \"definitionTitle\", \"definitionTitleMarker\", \"definitionTitleString\")(code);\n  }\n\n  /**\n   * After title.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function titleAfter(code) {\n    return markdownSpace(code) ? factorySpace(effects, titleAfterOptionalWhitespace, \"whitespace\")(code) : titleAfterOptionalWhitespace(code);\n  }\n\n  /**\n   * After title, after optional whitespace.\n   *\n   * ```markdown\n   * > | [a]: b \"c\"\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function titleAfterOptionalWhitespace(code) {\n    return code === null || markdownLineEnding(code) ? ok(code) : nok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { markdownLineEnding } from 'micromark-util-character';\n/** @type {Construct} */\nexport const hardBreakEscape = {\n  name: 'hardBreakEscape',\n  tokenize: tokenizeHardBreakEscape\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeHardBreakEscape(effects, ok, nok) {\n  return start;\n\n  /**\n   * Start of a hard break (escape).\n   *\n   * ```markdown\n   * > | a\\\n   *      ^\n   *   | b\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"hardBreakEscape\");\n    effects.consume(code);\n    return after;\n  }\n\n  /**\n   * After `\\`, at eol.\n   *\n   * ```markdown\n   * > | a\\\n   *       ^\n   *   | b\n   * ```\n   *\n   *  @type {State}\n   */\n  function after(code) {\n    if (markdownLineEnding(code)) {\n      effects.exit(\"hardBreakEscape\");\n      return ok(code);\n    }\n    return nok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer,\n *   Token\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEndingOrSpace, markdownLineEnding, markdownSpace } from 'micromark-util-character';\nimport { splice } from 'micromark-util-chunked';\n/** @type {Construct} */\nexport const headingAtx = {\n  name: 'headingAtx',\n  resolve: resolveHeadingAtx,\n  tokenize: tokenizeHeadingAtx\n};\n\n/** @type {Resolver} */\nfunction resolveHeadingAtx(events, context) {\n  let contentEnd = events.length - 2;\n  let contentStart = 3;\n  /** @type {Token} */\n  let content;\n  /** @type {Token} */\n  let text;\n\n  // Prefix whitespace, part of the opening.\n  if (events[contentStart][1].type === \"whitespace\") {\n    contentStart += 2;\n  }\n\n  // Suffix whitespace, part of the closing.\n  if (contentEnd - 2 > contentStart && events[contentEnd][1].type === \"whitespace\") {\n    contentEnd -= 2;\n  }\n  if (events[contentEnd][1].type === \"atxHeadingSequence\" && (contentStart === contentEnd - 1 || contentEnd - 4 > contentStart && events[contentEnd - 2][1].type === \"whitespace\")) {\n    contentEnd -= contentStart + 1 === contentEnd ? 2 : 4;\n  }\n  if (contentEnd > contentStart) {\n    content = {\n      type: \"atxHeadingText\",\n      start: events[contentStart][1].start,\n      end: events[contentEnd][1].end\n    };\n    text = {\n      type: \"chunkText\",\n      start: events[contentStart][1].start,\n      end: events[contentEnd][1].end,\n      contentType: \"text\"\n    };\n    splice(events, contentStart, contentEnd - contentStart + 1, [['enter', content, context], ['enter', text, context], ['exit', text, context], ['exit', content, context]]);\n  }\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeHeadingAtx(effects, ok, nok) {\n  let size = 0;\n  return start;\n\n  /**\n   * Start of a heading (atx).\n   *\n   * ```markdown\n   * > | ## aa\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // To do: parse indent like `markdown-rs`.\n    effects.enter(\"atxHeading\");\n    return before(code);\n  }\n\n  /**\n   * After optional whitespace, at `#`.\n   *\n   * ```markdown\n   * > | ## aa\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function before(code) {\n    effects.enter(\"atxHeadingSequence\");\n    return sequenceOpen(code);\n  }\n\n  /**\n   * In opening sequence.\n   *\n   * ```markdown\n   * > | ## aa\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function sequenceOpen(code) {\n    if (code === 35 && size++ < 6) {\n      effects.consume(code);\n      return sequenceOpen;\n    }\n\n    // Always at least one `#`.\n    if (code === null || markdownLineEndingOrSpace(code)) {\n      effects.exit(\"atxHeadingSequence\");\n      return atBreak(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * After something, before something else.\n   *\n   * ```markdown\n   * > | ## aa\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function atBreak(code) {\n    if (code === 35) {\n      effects.enter(\"atxHeadingSequence\");\n      return sequenceFurther(code);\n    }\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"atxHeading\");\n      // To do: interrupt like `markdown-rs`.\n      // // Feel free to interrupt.\n      // tokenizer.interrupt = false\n      return ok(code);\n    }\n    if (markdownSpace(code)) {\n      return factorySpace(effects, atBreak, \"whitespace\")(code);\n    }\n\n    // To do: generate `data` tokens, add the `text` token later.\n    // Needs edit map, see: `markdown.rs`.\n    effects.enter(\"atxHeadingText\");\n    return data(code);\n  }\n\n  /**\n   * In further sequence (after whitespace).\n   *\n   * Could be normal “visible” hashes in the heading or a final sequence.\n   *\n   * ```markdown\n   * > | ## aa ##\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function sequenceFurther(code) {\n    if (code === 35) {\n      effects.consume(code);\n      return sequenceFurther;\n    }\n    effects.exit(\"atxHeadingSequence\");\n    return atBreak(code);\n  }\n\n  /**\n   * In text.\n   *\n   * ```markdown\n   * > | ## aa\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function data(code) {\n    if (code === null || code === 35 || markdownLineEndingOrSpace(code)) {\n      effects.exit(\"atxHeadingText\");\n      return atBreak(code);\n    }\n    effects.consume(code);\n    return data;\n  }\n}","/**\n * List of lowercase HTML “block” tag names.\n *\n * The list, when parsing HTML (flow), results in more relaxed rules (condition\n * 6).\n * Because they are known blocks, the HTML-like syntax doesn’t have to be\n * strictly parsed.\n * For tag names not in this list, a more strict algorithm (condition 7) is used\n * to detect whether the HTML-like syntax is seen as HTML (flow) or not.\n *\n * This is copied from:\n * <https://spec.commonmark.org/0.30/#html-blocks>.\n *\n * > 👉 **Note**: `search` was added in `CommonMark@0.31`.\n */\nexport const htmlBlockNames = [\n  'address',\n  'article',\n  'aside',\n  'base',\n  'basefont',\n  'blockquote',\n  'body',\n  'caption',\n  'center',\n  'col',\n  'colgroup',\n  'dd',\n  'details',\n  'dialog',\n  'dir',\n  'div',\n  'dl',\n  'dt',\n  'fieldset',\n  'figcaption',\n  'figure',\n  'footer',\n  'form',\n  'frame',\n  'frameset',\n  'h1',\n  'h2',\n  'h3',\n  'h4',\n  'h5',\n  'h6',\n  'head',\n  'header',\n  'hr',\n  'html',\n  'iframe',\n  'legend',\n  'li',\n  'link',\n  'main',\n  'menu',\n  'menuitem',\n  'nav',\n  'noframes',\n  'ol',\n  'optgroup',\n  'option',\n  'p',\n  'param',\n  'search',\n  'section',\n  'summary',\n  'table',\n  'tbody',\n  'td',\n  'tfoot',\n  'th',\n  'thead',\n  'title',\n  'tr',\n  'track',\n  'ul'\n]\n\n/**\n * List of lowercase HTML “raw” tag names.\n *\n * The list, when parsing HTML (flow), results in HTML that can include lines\n * without exiting, until a closing tag also in this list is found (condition\n * 1).\n *\n * This module is copied from:\n * <https://spec.commonmark.org/0.30/#html-blocks>.\n *\n * > 👉 **Note**: `textarea` was added in `CommonMark@0.30`.\n */\nexport const htmlRawNames = ['pre', 'script', 'style', 'textarea']\n","/**\n * @import {\n *   Code,\n *   Construct,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { asciiAlphanumeric, asciiAlpha, markdownLineEndingOrSpace, markdownLineEnding, markdownSpace } from 'micromark-util-character';\nimport { htmlBlockNames, htmlRawNames } from 'micromark-util-html-tag-name';\nimport { blankLine } from './blank-line.js';\n\n/** @type {Construct} */\nexport const htmlFlow = {\n  concrete: true,\n  name: 'htmlFlow',\n  resolveTo: resolveToHtmlFlow,\n  tokenize: tokenizeHtmlFlow\n};\n\n/** @type {Construct} */\nconst blankLineBefore = {\n  partial: true,\n  tokenize: tokenizeBlankLineBefore\n};\nconst nonLazyContinuationStart = {\n  partial: true,\n  tokenize: tokenizeNonLazyContinuationStart\n};\n\n/** @type {Resolver} */\nfunction resolveToHtmlFlow(events) {\n  let index = events.length;\n  while (index--) {\n    if (events[index][0] === 'enter' && events[index][1].type === \"htmlFlow\") {\n      break;\n    }\n  }\n  if (index > 1 && events[index - 2][1].type === \"linePrefix\") {\n    // Add the prefix start to the HTML token.\n    events[index][1].start = events[index - 2][1].start;\n    // Add the prefix start to the HTML line token.\n    events[index + 1][1].start = events[index - 2][1].start;\n    // Remove the line prefix.\n    events.splice(index - 2, 2);\n  }\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeHtmlFlow(effects, ok, nok) {\n  const self = this;\n  /** @type {number} */\n  let marker;\n  /** @type {boolean} */\n  let closingTag;\n  /** @type {string} */\n  let buffer;\n  /** @type {number} */\n  let index;\n  /** @type {Code} */\n  let markerB;\n  return start;\n\n  /**\n   * Start of HTML (flow).\n   *\n   * ```markdown\n   * > | <x />\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // To do: parse indent like `markdown-rs`.\n    return before(code);\n  }\n\n  /**\n   * At `<`, after optional whitespace.\n   *\n   * ```markdown\n   * > | <x />\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function before(code) {\n    effects.enter(\"htmlFlow\");\n    effects.enter(\"htmlFlowData\");\n    effects.consume(code);\n    return open;\n  }\n\n  /**\n   * After `<`, at tag name or other stuff.\n   *\n   * ```markdown\n   * > | <x />\n   *      ^\n   * > | <!doctype>\n   *      ^\n   * > | <!--xxx-->\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function open(code) {\n    if (code === 33) {\n      effects.consume(code);\n      return declarationOpen;\n    }\n    if (code === 47) {\n      effects.consume(code);\n      closingTag = true;\n      return tagCloseStart;\n    }\n    if (code === 63) {\n      effects.consume(code);\n      marker = 3;\n      // To do:\n      // tokenizer.concrete = true\n      // To do: use `markdown-rs` style interrupt.\n      // While we’re in an instruction instead of a declaration, we’re on a `?`\n      // right now, so we do need to search for `>`, similar to declarations.\n      return self.interrupt ? ok : continuationDeclarationInside;\n    }\n\n    // ASCII alphabetical.\n    if (asciiAlpha(code)) {\n      // Always the case.\n      effects.consume(code);\n      buffer = String.fromCharCode(code);\n      return tagName;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `<!`, at declaration, comment, or CDATA.\n   *\n   * ```markdown\n   * > | <!doctype>\n   *       ^\n   * > | <!--xxx-->\n   *       ^\n   * > | <![CDATA[>&<]]>\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function declarationOpen(code) {\n    if (code === 45) {\n      effects.consume(code);\n      marker = 2;\n      return commentOpenInside;\n    }\n    if (code === 91) {\n      effects.consume(code);\n      marker = 5;\n      index = 0;\n      return cdataOpenInside;\n    }\n\n    // ASCII alphabetical.\n    if (asciiAlpha(code)) {\n      effects.consume(code);\n      marker = 4;\n      // // Do not form containers.\n      // tokenizer.concrete = true\n      return self.interrupt ? ok : continuationDeclarationInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `<!-`, inside a comment, at another `-`.\n   *\n   * ```markdown\n   * > | <!--xxx-->\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function commentOpenInside(code) {\n    if (code === 45) {\n      effects.consume(code);\n      // // Do not form containers.\n      // tokenizer.concrete = true\n      return self.interrupt ? ok : continuationDeclarationInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `<![`, inside CDATA, expecting `CDATA[`.\n   *\n   * ```markdown\n   * > | <![CDATA[>&<]]>\n   *        ^^^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function cdataOpenInside(code) {\n    const value = \"CDATA[\";\n    if (code === value.charCodeAt(index++)) {\n      effects.consume(code);\n      if (index === value.length) {\n        // // Do not form containers.\n        // tokenizer.concrete = true\n        return self.interrupt ? ok : continuation;\n      }\n      return cdataOpenInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `</`, in closing tag, at tag name.\n   *\n   * ```markdown\n   * > | </x>\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagCloseStart(code) {\n    if (asciiAlpha(code)) {\n      // Always the case.\n      effects.consume(code);\n      buffer = String.fromCharCode(code);\n      return tagName;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In tag name.\n   *\n   * ```markdown\n   * > | <ab>\n   *      ^^\n   * > | </ab>\n   *       ^^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagName(code) {\n    if (code === null || code === 47 || code === 62 || markdownLineEndingOrSpace(code)) {\n      const slash = code === 47;\n      const name = buffer.toLowerCase();\n      if (!slash && !closingTag && htmlRawNames.includes(name)) {\n        marker = 1;\n        // // Do not form containers.\n        // tokenizer.concrete = true\n        return self.interrupt ? ok(code) : continuation(code);\n      }\n      if (htmlBlockNames.includes(buffer.toLowerCase())) {\n        marker = 6;\n        if (slash) {\n          effects.consume(code);\n          return basicSelfClosing;\n        }\n\n        // // Do not form containers.\n        // tokenizer.concrete = true\n        return self.interrupt ? ok(code) : continuation(code);\n      }\n      marker = 7;\n      // Do not support complete HTML when interrupting.\n      return self.interrupt && !self.parser.lazy[self.now().line] ? nok(code) : closingTag ? completeClosingTagAfter(code) : completeAttributeNameBefore(code);\n    }\n\n    // ASCII alphanumerical and `-`.\n    if (code === 45 || asciiAlphanumeric(code)) {\n      effects.consume(code);\n      buffer += String.fromCharCode(code);\n      return tagName;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After closing slash of a basic tag name.\n   *\n   * ```markdown\n   * > | <div/>\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function basicSelfClosing(code) {\n    if (code === 62) {\n      effects.consume(code);\n      // // Do not form containers.\n      // tokenizer.concrete = true\n      return self.interrupt ? ok : continuation;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After closing slash of a complete tag name.\n   *\n   * ```markdown\n   * > | <x/>\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeClosingTagAfter(code) {\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return completeClosingTagAfter;\n    }\n    return completeEnd(code);\n  }\n\n  /**\n   * At an attribute name.\n   *\n   * At first, this state is used after a complete tag name, after whitespace,\n   * where it expects optional attributes or the end of the tag.\n   * It is also reused after attributes, when expecting more optional\n   * attributes.\n   *\n   * ```markdown\n   * > | <a />\n   *        ^\n   * > | <a :b>\n   *        ^\n   * > | <a _b>\n   *        ^\n   * > | <a b>\n   *        ^\n   * > | <a >\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeNameBefore(code) {\n    if (code === 47) {\n      effects.consume(code);\n      return completeEnd;\n    }\n\n    // ASCII alphanumerical and `:` and `_`.\n    if (code === 58 || code === 95 || asciiAlpha(code)) {\n      effects.consume(code);\n      return completeAttributeName;\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return completeAttributeNameBefore;\n    }\n    return completeEnd(code);\n  }\n\n  /**\n   * In attribute name.\n   *\n   * ```markdown\n   * > | <a :b>\n   *         ^\n   * > | <a _b>\n   *         ^\n   * > | <a b>\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeName(code) {\n    // ASCII alphanumerical and `-`, `.`, `:`, and `_`.\n    if (code === 45 || code === 46 || code === 58 || code === 95 || asciiAlphanumeric(code)) {\n      effects.consume(code);\n      return completeAttributeName;\n    }\n    return completeAttributeNameAfter(code);\n  }\n\n  /**\n   * After attribute name, at an optional initializer, the end of the tag, or\n   * whitespace.\n   *\n   * ```markdown\n   * > | <a b>\n   *         ^\n   * > | <a b=c>\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeNameAfter(code) {\n    if (code === 61) {\n      effects.consume(code);\n      return completeAttributeValueBefore;\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return completeAttributeNameAfter;\n    }\n    return completeAttributeNameBefore(code);\n  }\n\n  /**\n   * Before unquoted, double quoted, or single quoted attribute value, allowing\n   * whitespace.\n   *\n   * ```markdown\n   * > | <a b=c>\n   *          ^\n   * > | <a b=\"c\">\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeValueBefore(code) {\n    if (code === null || code === 60 || code === 61 || code === 62 || code === 96) {\n      return nok(code);\n    }\n    if (code === 34 || code === 39) {\n      effects.consume(code);\n      markerB = code;\n      return completeAttributeValueQuoted;\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return completeAttributeValueBefore;\n    }\n    return completeAttributeValueUnquoted(code);\n  }\n\n  /**\n   * In double or single quoted attribute value.\n   *\n   * ```markdown\n   * > | <a b=\"c\">\n   *           ^\n   * > | <a b='c'>\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeValueQuoted(code) {\n    if (code === markerB) {\n      effects.consume(code);\n      markerB = null;\n      return completeAttributeValueQuotedAfter;\n    }\n    if (code === null || markdownLineEnding(code)) {\n      return nok(code);\n    }\n    effects.consume(code);\n    return completeAttributeValueQuoted;\n  }\n\n  /**\n   * In unquoted attribute value.\n   *\n   * ```markdown\n   * > | <a b=c>\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeValueUnquoted(code) {\n    if (code === null || code === 34 || code === 39 || code === 47 || code === 60 || code === 61 || code === 62 || code === 96 || markdownLineEndingOrSpace(code)) {\n      return completeAttributeNameAfter(code);\n    }\n    effects.consume(code);\n    return completeAttributeValueUnquoted;\n  }\n\n  /**\n   * After double or single quoted attribute value, before whitespace or the\n   * end of the tag.\n   *\n   * ```markdown\n   * > | <a b=\"c\">\n   *            ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAttributeValueQuotedAfter(code) {\n    if (code === 47 || code === 62 || markdownSpace(code)) {\n      return completeAttributeNameBefore(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * In certain circumstances of a complete tag where only an `>` is allowed.\n   *\n   * ```markdown\n   * > | <a b=\"c\">\n   *             ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeEnd(code) {\n    if (code === 62) {\n      effects.consume(code);\n      return completeAfter;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `>` in a complete tag.\n   *\n   * ```markdown\n   * > | <x>\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function completeAfter(code) {\n    if (code === null || markdownLineEnding(code)) {\n      // // Do not form containers.\n      // tokenizer.concrete = true\n      return continuation(code);\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return completeAfter;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In continuation of any HTML kind.\n   *\n   * ```markdown\n   * > | <!--xxx-->\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuation(code) {\n    if (code === 45 && marker === 2) {\n      effects.consume(code);\n      return continuationCommentInside;\n    }\n    if (code === 60 && marker === 1) {\n      effects.consume(code);\n      return continuationRawTagOpen;\n    }\n    if (code === 62 && marker === 4) {\n      effects.consume(code);\n      return continuationClose;\n    }\n    if (code === 63 && marker === 3) {\n      effects.consume(code);\n      return continuationDeclarationInside;\n    }\n    if (code === 93 && marker === 5) {\n      effects.consume(code);\n      return continuationCdataInside;\n    }\n    if (markdownLineEnding(code) && (marker === 6 || marker === 7)) {\n      effects.exit(\"htmlFlowData\");\n      return effects.check(blankLineBefore, continuationAfter, continuationStart)(code);\n    }\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"htmlFlowData\");\n      return continuationStart(code);\n    }\n    effects.consume(code);\n    return continuation;\n  }\n\n  /**\n   * In continuation, at eol.\n   *\n   * ```markdown\n   * > | <x>\n   *        ^\n   *   | asd\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationStart(code) {\n    return effects.check(nonLazyContinuationStart, continuationStartNonLazy, continuationAfter)(code);\n  }\n\n  /**\n   * In continuation, at eol, before non-lazy content.\n   *\n   * ```markdown\n   * > | <x>\n   *        ^\n   *   | asd\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationStartNonLazy(code) {\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return continuationBefore;\n  }\n\n  /**\n   * In continuation, before non-lazy content.\n   *\n   * ```markdown\n   *   | <x>\n   * > | asd\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationBefore(code) {\n    if (code === null || markdownLineEnding(code)) {\n      return continuationStart(code);\n    }\n    effects.enter(\"htmlFlowData\");\n    return continuation(code);\n  }\n\n  /**\n   * In comment continuation, after one `-`, expecting another.\n   *\n   * ```markdown\n   * > | <!--xxx-->\n   *             ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationCommentInside(code) {\n    if (code === 45) {\n      effects.consume(code);\n      return continuationDeclarationInside;\n    }\n    return continuation(code);\n  }\n\n  /**\n   * In raw continuation, after `<`, at `/`.\n   *\n   * ```markdown\n   * > | <script>console.log(1)</script>\n   *                            ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationRawTagOpen(code) {\n    if (code === 47) {\n      effects.consume(code);\n      buffer = '';\n      return continuationRawEndTag;\n    }\n    return continuation(code);\n  }\n\n  /**\n   * In raw continuation, after `</`, in a raw tag name.\n   *\n   * ```markdown\n   * > | <script>console.log(1)</script>\n   *                             ^^^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationRawEndTag(code) {\n    if (code === 62) {\n      const name = buffer.toLowerCase();\n      if (htmlRawNames.includes(name)) {\n        effects.consume(code);\n        return continuationClose;\n      }\n      return continuation(code);\n    }\n    if (asciiAlpha(code) && buffer.length < 8) {\n      // Always the case.\n      effects.consume(code);\n      buffer += String.fromCharCode(code);\n      return continuationRawEndTag;\n    }\n    return continuation(code);\n  }\n\n  /**\n   * In cdata continuation, after `]`, expecting `]>`.\n   *\n   * ```markdown\n   * > | <![CDATA[>&<]]>\n   *                  ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationCdataInside(code) {\n    if (code === 93) {\n      effects.consume(code);\n      return continuationDeclarationInside;\n    }\n    return continuation(code);\n  }\n\n  /**\n   * In declaration or instruction continuation, at `>`.\n   *\n   * ```markdown\n   * > | <!-->\n   *         ^\n   * > | <?>\n   *       ^\n   * > | <!q>\n   *        ^\n   * > | <!--ab-->\n   *             ^\n   * > | <![CDATA[>&<]]>\n   *                   ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationDeclarationInside(code) {\n    if (code === 62) {\n      effects.consume(code);\n      return continuationClose;\n    }\n\n    // More dashes.\n    if (code === 45 && marker === 2) {\n      effects.consume(code);\n      return continuationDeclarationInside;\n    }\n    return continuation(code);\n  }\n\n  /**\n   * In closed continuation: everything we get until the eol/eof is part of it.\n   *\n   * ```markdown\n   * > | <!doctype>\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationClose(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"htmlFlowData\");\n      return continuationAfter(code);\n    }\n    effects.consume(code);\n    return continuationClose;\n  }\n\n  /**\n   * Done.\n   *\n   * ```markdown\n   * > | <!doctype>\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function continuationAfter(code) {\n    effects.exit(\"htmlFlow\");\n    // // Feel free to interrupt.\n    // tokenizer.interrupt = false\n    // // No longer concrete.\n    // tokenizer.concrete = false\n    return ok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeNonLazyContinuationStart(effects, ok, nok) {\n  const self = this;\n  return start;\n\n  /**\n   * At eol, before continuation.\n   *\n   * ```markdown\n   * > | * ```js\n   *            ^\n   *   | b\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    if (markdownLineEnding(code)) {\n      effects.enter(\"lineEnding\");\n      effects.consume(code);\n      effects.exit(\"lineEnding\");\n      return after;\n    }\n    return nok(code);\n  }\n\n  /**\n   * A continuation.\n   *\n   * ```markdown\n   *   | * ```js\n   * > | b\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    return self.parser.lazy[self.now().line] ? nok(code) : ok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeBlankLineBefore(effects, ok, nok) {\n  return start;\n\n  /**\n   * Before eol, expecting blank line.\n   *\n   * ```markdown\n   * > | <div>\n   *          ^\n   *   |\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return effects.attempt(blankLine, ok, nok);\n  }\n}","/**\n * @import {\n *   Code,\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { asciiAlphanumeric, asciiAlpha, markdownLineEndingOrSpace, markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const htmlText = {\n  name: 'htmlText',\n  tokenize: tokenizeHtmlText\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeHtmlText(effects, ok, nok) {\n  const self = this;\n  /** @type {NonNullable<Code> | undefined} */\n  let marker;\n  /** @type {number} */\n  let index;\n  /** @type {State} */\n  let returnState;\n  return start;\n\n  /**\n   * Start of HTML (text).\n   *\n   * ```markdown\n   * > | a <b> c\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"htmlText\");\n    effects.enter(\"htmlTextData\");\n    effects.consume(code);\n    return open;\n  }\n\n  /**\n   * After `<`, at tag name or other stuff.\n   *\n   * ```markdown\n   * > | a <b> c\n   *        ^\n   * > | a <!doctype> c\n   *        ^\n   * > | a <!--b--> c\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function open(code) {\n    if (code === 33) {\n      effects.consume(code);\n      return declarationOpen;\n    }\n    if (code === 47) {\n      effects.consume(code);\n      return tagCloseStart;\n    }\n    if (code === 63) {\n      effects.consume(code);\n      return instruction;\n    }\n\n    // ASCII alphabetical.\n    if (asciiAlpha(code)) {\n      effects.consume(code);\n      return tagOpen;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `<!`, at declaration, comment, or CDATA.\n   *\n   * ```markdown\n   * > | a <!doctype> c\n   *         ^\n   * > | a <!--b--> c\n   *         ^\n   * > | a <![CDATA[>&<]]> c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function declarationOpen(code) {\n    if (code === 45) {\n      effects.consume(code);\n      return commentOpenInside;\n    }\n    if (code === 91) {\n      effects.consume(code);\n      index = 0;\n      return cdataOpenInside;\n    }\n    if (asciiAlpha(code)) {\n      effects.consume(code);\n      return declaration;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In a comment, after `<!-`, at another `-`.\n   *\n   * ```markdown\n   * > | a <!--b--> c\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function commentOpenInside(code) {\n    if (code === 45) {\n      effects.consume(code);\n      return commentEnd;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In comment.\n   *\n   * ```markdown\n   * > | a <!--b--> c\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function comment(code) {\n    if (code === null) {\n      return nok(code);\n    }\n    if (code === 45) {\n      effects.consume(code);\n      return commentClose;\n    }\n    if (markdownLineEnding(code)) {\n      returnState = comment;\n      return lineEndingBefore(code);\n    }\n    effects.consume(code);\n    return comment;\n  }\n\n  /**\n   * In comment, after `-`.\n   *\n   * ```markdown\n   * > | a <!--b--> c\n   *             ^\n   * ```\n   *\n   * @type {State}\n   */\n  function commentClose(code) {\n    if (code === 45) {\n      effects.consume(code);\n      return commentEnd;\n    }\n    return comment(code);\n  }\n\n  /**\n   * In comment, after `--`.\n   *\n   * ```markdown\n   * > | a <!--b--> c\n   *              ^\n   * ```\n   *\n   * @type {State}\n   */\n  function commentEnd(code) {\n    return code === 62 ? end(code) : code === 45 ? commentClose(code) : comment(code);\n  }\n\n  /**\n   * After `<![`, in CDATA, expecting `CDATA[`.\n   *\n   * ```markdown\n   * > | a <![CDATA[>&<]]> b\n   *          ^^^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function cdataOpenInside(code) {\n    const value = \"CDATA[\";\n    if (code === value.charCodeAt(index++)) {\n      effects.consume(code);\n      return index === value.length ? cdata : cdataOpenInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In CDATA.\n   *\n   * ```markdown\n   * > | a <![CDATA[>&<]]> b\n   *                ^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function cdata(code) {\n    if (code === null) {\n      return nok(code);\n    }\n    if (code === 93) {\n      effects.consume(code);\n      return cdataClose;\n    }\n    if (markdownLineEnding(code)) {\n      returnState = cdata;\n      return lineEndingBefore(code);\n    }\n    effects.consume(code);\n    return cdata;\n  }\n\n  /**\n   * In CDATA, after `]`, at another `]`.\n   *\n   * ```markdown\n   * > | a <![CDATA[>&<]]> b\n   *                    ^\n   * ```\n   *\n   * @type {State}\n   */\n  function cdataClose(code) {\n    if (code === 93) {\n      effects.consume(code);\n      return cdataEnd;\n    }\n    return cdata(code);\n  }\n\n  /**\n   * In CDATA, after `]]`, at `>`.\n   *\n   * ```markdown\n   * > | a <![CDATA[>&<]]> b\n   *                     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function cdataEnd(code) {\n    if (code === 62) {\n      return end(code);\n    }\n    if (code === 93) {\n      effects.consume(code);\n      return cdataEnd;\n    }\n    return cdata(code);\n  }\n\n  /**\n   * In declaration.\n   *\n   * ```markdown\n   * > | a <!b> c\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function declaration(code) {\n    if (code === null || code === 62) {\n      return end(code);\n    }\n    if (markdownLineEnding(code)) {\n      returnState = declaration;\n      return lineEndingBefore(code);\n    }\n    effects.consume(code);\n    return declaration;\n  }\n\n  /**\n   * In instruction.\n   *\n   * ```markdown\n   * > | a <?b?> c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function instruction(code) {\n    if (code === null) {\n      return nok(code);\n    }\n    if (code === 63) {\n      effects.consume(code);\n      return instructionClose;\n    }\n    if (markdownLineEnding(code)) {\n      returnState = instruction;\n      return lineEndingBefore(code);\n    }\n    effects.consume(code);\n    return instruction;\n  }\n\n  /**\n   * In instruction, after `?`, at `>`.\n   *\n   * ```markdown\n   * > | a <?b?> c\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function instructionClose(code) {\n    return code === 62 ? end(code) : instruction(code);\n  }\n\n  /**\n   * After `</`, in closing tag, at tag name.\n   *\n   * ```markdown\n   * > | a </b> c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagCloseStart(code) {\n    // ASCII alphabetical.\n    if (asciiAlpha(code)) {\n      effects.consume(code);\n      return tagClose;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `</x`, in a tag name.\n   *\n   * ```markdown\n   * > | a </b> c\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagClose(code) {\n    // ASCII alphanumerical and `-`.\n    if (code === 45 || asciiAlphanumeric(code)) {\n      effects.consume(code);\n      return tagClose;\n    }\n    return tagCloseBetween(code);\n  }\n\n  /**\n   * In closing tag, after tag name.\n   *\n   * ```markdown\n   * > | a </b> c\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagCloseBetween(code) {\n    if (markdownLineEnding(code)) {\n      returnState = tagCloseBetween;\n      return lineEndingBefore(code);\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return tagCloseBetween;\n    }\n    return end(code);\n  }\n\n  /**\n   * After `<x`, in opening tag name.\n   *\n   * ```markdown\n   * > | a <b> c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpen(code) {\n    // ASCII alphanumerical and `-`.\n    if (code === 45 || asciiAlphanumeric(code)) {\n      effects.consume(code);\n      return tagOpen;\n    }\n    if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) {\n      return tagOpenBetween(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * In opening tag, after tag name.\n   *\n   * ```markdown\n   * > | a <b> c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenBetween(code) {\n    if (code === 47) {\n      effects.consume(code);\n      return end;\n    }\n\n    // ASCII alphabetical and `:` and `_`.\n    if (code === 58 || code === 95 || asciiAlpha(code)) {\n      effects.consume(code);\n      return tagOpenAttributeName;\n    }\n    if (markdownLineEnding(code)) {\n      returnState = tagOpenBetween;\n      return lineEndingBefore(code);\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return tagOpenBetween;\n    }\n    return end(code);\n  }\n\n  /**\n   * In attribute name.\n   *\n   * ```markdown\n   * > | a <b c> d\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenAttributeName(code) {\n    // ASCII alphabetical and `-`, `.`, `:`, and `_`.\n    if (code === 45 || code === 46 || code === 58 || code === 95 || asciiAlphanumeric(code)) {\n      effects.consume(code);\n      return tagOpenAttributeName;\n    }\n    return tagOpenAttributeNameAfter(code);\n  }\n\n  /**\n   * After attribute name, before initializer, the end of the tag, or\n   * whitespace.\n   *\n   * ```markdown\n   * > | a <b c> d\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenAttributeNameAfter(code) {\n    if (code === 61) {\n      effects.consume(code);\n      return tagOpenAttributeValueBefore;\n    }\n    if (markdownLineEnding(code)) {\n      returnState = tagOpenAttributeNameAfter;\n      return lineEndingBefore(code);\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return tagOpenAttributeNameAfter;\n    }\n    return tagOpenBetween(code);\n  }\n\n  /**\n   * Before unquoted, double quoted, or single quoted attribute value, allowing\n   * whitespace.\n   *\n   * ```markdown\n   * > | a <b c=d> e\n   *            ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenAttributeValueBefore(code) {\n    if (code === null || code === 60 || code === 61 || code === 62 || code === 96) {\n      return nok(code);\n    }\n    if (code === 34 || code === 39) {\n      effects.consume(code);\n      marker = code;\n      return tagOpenAttributeValueQuoted;\n    }\n    if (markdownLineEnding(code)) {\n      returnState = tagOpenAttributeValueBefore;\n      return lineEndingBefore(code);\n    }\n    if (markdownSpace(code)) {\n      effects.consume(code);\n      return tagOpenAttributeValueBefore;\n    }\n    effects.consume(code);\n    return tagOpenAttributeValueUnquoted;\n  }\n\n  /**\n   * In double or single quoted attribute value.\n   *\n   * ```markdown\n   * > | a <b c=\"d\"> e\n   *             ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenAttributeValueQuoted(code) {\n    if (code === marker) {\n      effects.consume(code);\n      marker = undefined;\n      return tagOpenAttributeValueQuotedAfter;\n    }\n    if (code === null) {\n      return nok(code);\n    }\n    if (markdownLineEnding(code)) {\n      returnState = tagOpenAttributeValueQuoted;\n      return lineEndingBefore(code);\n    }\n    effects.consume(code);\n    return tagOpenAttributeValueQuoted;\n  }\n\n  /**\n   * In unquoted attribute value.\n   *\n   * ```markdown\n   * > | a <b c=d> e\n   *            ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenAttributeValueUnquoted(code) {\n    if (code === null || code === 34 || code === 39 || code === 60 || code === 61 || code === 96) {\n      return nok(code);\n    }\n    if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) {\n      return tagOpenBetween(code);\n    }\n    effects.consume(code);\n    return tagOpenAttributeValueUnquoted;\n  }\n\n  /**\n   * After double or single quoted attribute value, before whitespace or the end\n   * of the tag.\n   *\n   * ```markdown\n   * > | a <b c=\"d\"> e\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function tagOpenAttributeValueQuotedAfter(code) {\n    if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) {\n      return tagOpenBetween(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * In certain circumstances of a tag where only an `>` is allowed.\n   *\n   * ```markdown\n   * > | a <b c=\"d\"> e\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function end(code) {\n    if (code === 62) {\n      effects.consume(code);\n      effects.exit(\"htmlTextData\");\n      effects.exit(\"htmlText\");\n      return ok;\n    }\n    return nok(code);\n  }\n\n  /**\n   * At eol.\n   *\n   * > 👉 **Note**: we can’t have blank lines in text, so no need to worry about\n   * > empty tokens.\n   *\n   * ```markdown\n   * > | a <!--a\n   *            ^\n   *   | b-->\n   * ```\n   *\n   * @type {State}\n   */\n  function lineEndingBefore(code) {\n    effects.exit(\"htmlTextData\");\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return lineEndingAfter;\n  }\n\n  /**\n   * After eol, at optional whitespace.\n   *\n   * > 👉 **Note**: we can’t have blank lines in text, so no need to worry about\n   * > empty tokens.\n   *\n   * ```markdown\n   *   | a <!--a\n   * > | b-->\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function lineEndingAfter(code) {\n    // Always populated by defaults.\n\n    return markdownSpace(code) ? factorySpace(effects, lineEndingAfterPrefix, \"linePrefix\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4)(code) : lineEndingAfterPrefix(code);\n  }\n\n  /**\n   * After eol, after optional whitespace.\n   *\n   * > 👉 **Note**: we can’t have blank lines in text, so no need to worry about\n   * > empty tokens.\n   *\n   * ```markdown\n   *   | a <!--a\n   * > | b-->\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function lineEndingAfterPrefix(code) {\n    effects.enter(\"htmlTextData\");\n    return returnState(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   Event,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer,\n *   Token\n * } from 'micromark-util-types'\n */\n\nimport { factoryDestination } from 'micromark-factory-destination';\nimport { factoryLabel } from 'micromark-factory-label';\nimport { factoryTitle } from 'micromark-factory-title';\nimport { factoryWhitespace } from 'micromark-factory-whitespace';\nimport { markdownLineEndingOrSpace } from 'micromark-util-character';\nimport { push, splice } from 'micromark-util-chunked';\nimport { normalizeIdentifier } from 'micromark-util-normalize-identifier';\nimport { resolveAll } from 'micromark-util-resolve-all';\n/** @type {Construct} */\nexport const labelEnd = {\n  name: 'labelEnd',\n  resolveAll: resolveAllLabelEnd,\n  resolveTo: resolveToLabelEnd,\n  tokenize: tokenizeLabelEnd\n};\n\n/** @type {Construct} */\nconst resourceConstruct = {\n  tokenize: tokenizeResource\n};\n/** @type {Construct} */\nconst referenceFullConstruct = {\n  tokenize: tokenizeReferenceFull\n};\n/** @type {Construct} */\nconst referenceCollapsedConstruct = {\n  tokenize: tokenizeReferenceCollapsed\n};\n\n/** @type {Resolver} */\nfunction resolveAllLabelEnd(events) {\n  let index = -1;\n  /** @type {Array<Event>} */\n  const newEvents = [];\n  while (++index < events.length) {\n    const token = events[index][1];\n    newEvents.push(events[index]);\n    if (token.type === \"labelImage\" || token.type === \"labelLink\" || token.type === \"labelEnd\") {\n      // Remove the marker.\n      const offset = token.type === \"labelImage\" ? 4 : 2;\n      token.type = \"data\";\n      index += offset;\n    }\n  }\n\n  // If the events are equal, we don't have to copy newEvents to events\n  if (events.length !== newEvents.length) {\n    splice(events, 0, events.length, newEvents);\n  }\n  return events;\n}\n\n/** @type {Resolver} */\nfunction resolveToLabelEnd(events, context) {\n  let index = events.length;\n  let offset = 0;\n  /** @type {Token} */\n  let token;\n  /** @type {number | undefined} */\n  let open;\n  /** @type {number | undefined} */\n  let close;\n  /** @type {Array<Event>} */\n  let media;\n\n  // Find an opening.\n  while (index--) {\n    token = events[index][1];\n    if (open) {\n      // If we see another link, or inactive link label, we’ve been here before.\n      if (token.type === \"link\" || token.type === \"labelLink\" && token._inactive) {\n        break;\n      }\n\n      // Mark other link openings as inactive, as we can’t have links in\n      // links.\n      if (events[index][0] === 'enter' && token.type === \"labelLink\") {\n        token._inactive = true;\n      }\n    } else if (close) {\n      if (events[index][0] === 'enter' && (token.type === \"labelImage\" || token.type === \"labelLink\") && !token._balanced) {\n        open = index;\n        if (token.type !== \"labelLink\") {\n          offset = 2;\n          break;\n        }\n      }\n    } else if (token.type === \"labelEnd\") {\n      close = index;\n    }\n  }\n  const group = {\n    type: events[open][1].type === \"labelLink\" ? \"link\" : \"image\",\n    start: {\n      ...events[open][1].start\n    },\n    end: {\n      ...events[events.length - 1][1].end\n    }\n  };\n  const label = {\n    type: \"label\",\n    start: {\n      ...events[open][1].start\n    },\n    end: {\n      ...events[close][1].end\n    }\n  };\n  const text = {\n    type: \"labelText\",\n    start: {\n      ...events[open + offset + 2][1].end\n    },\n    end: {\n      ...events[close - 2][1].start\n    }\n  };\n  media = [['enter', group, context], ['enter', label, context]];\n\n  // Opening marker.\n  media = push(media, events.slice(open + 1, open + offset + 3));\n\n  // Text open.\n  media = push(media, [['enter', text, context]]);\n\n  // Always populated by defaults.\n\n  // Between.\n  media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + offset + 4, close - 3), context));\n\n  // Text close, marker close, label close.\n  media = push(media, [['exit', text, context], events[close - 2], events[close - 1], ['exit', label, context]]);\n\n  // Reference, resource, or so.\n  media = push(media, events.slice(close + 1));\n\n  // Media close.\n  media = push(media, [['exit', group, context]]);\n  splice(events, open, events.length, media);\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeLabelEnd(effects, ok, nok) {\n  const self = this;\n  let index = self.events.length;\n  /** @type {Token} */\n  let labelStart;\n  /** @type {boolean} */\n  let defined;\n\n  // Find an opening.\n  while (index--) {\n    if ((self.events[index][1].type === \"labelImage\" || self.events[index][1].type === \"labelLink\") && !self.events[index][1]._balanced) {\n      labelStart = self.events[index][1];\n      break;\n    }\n  }\n  return start;\n\n  /**\n   * Start of label end.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *       ^\n   * > | [a][b] c\n   *       ^\n   * > | [a][] b\n   *       ^\n   * > | [a] b\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // If there is not an okay opening.\n    if (!labelStart) {\n      return nok(code);\n    }\n\n    // If the corresponding label (link) start is marked as inactive,\n    // it means we’d be wrapping a link, like this:\n    //\n    // ```markdown\n    // > | a [b [c](d) e](f) g.\n    //                  ^\n    // ```\n    //\n    // We can’t have that, so it’s just balanced brackets.\n    if (labelStart._inactive) {\n      return labelEndNok(code);\n    }\n    defined = self.parser.defined.includes(normalizeIdentifier(self.sliceSerialize({\n      start: labelStart.end,\n      end: self.now()\n    })));\n    effects.enter(\"labelEnd\");\n    effects.enter(\"labelMarker\");\n    effects.consume(code);\n    effects.exit(\"labelMarker\");\n    effects.exit(\"labelEnd\");\n    return after;\n  }\n\n  /**\n   * After `]`.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *       ^\n   * > | [a][b] c\n   *       ^\n   * > | [a][] b\n   *       ^\n   * > | [a] b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    // Note: `markdown-rs` also parses GFM footnotes here, which for us is in\n    // an extension.\n\n    // Resource (`[asd](fgh)`)?\n    if (code === 40) {\n      return effects.attempt(resourceConstruct, labelEndOk, defined ? labelEndOk : labelEndNok)(code);\n    }\n\n    // Full (`[asd][fgh]`) or collapsed (`[asd][]`) reference?\n    if (code === 91) {\n      return effects.attempt(referenceFullConstruct, labelEndOk, defined ? referenceNotFull : labelEndNok)(code);\n    }\n\n    // Shortcut (`[asd]`) reference?\n    return defined ? labelEndOk(code) : labelEndNok(code);\n  }\n\n  /**\n   * After `]`, at `[`, but not at a full reference.\n   *\n   * > 👉 **Note**: we only get here if the label is defined.\n   *\n   * ```markdown\n   * > | [a][] b\n   *        ^\n   * > | [a] b\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function referenceNotFull(code) {\n    return effects.attempt(referenceCollapsedConstruct, labelEndOk, labelEndNok)(code);\n  }\n\n  /**\n   * Done, we found something.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *           ^\n   * > | [a][b] c\n   *           ^\n   * > | [a][] b\n   *          ^\n   * > | [a] b\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelEndOk(code) {\n    // Note: `markdown-rs` does a bunch of stuff here.\n    return ok(code);\n  }\n\n  /**\n   * Done, it’s nothing.\n   *\n   * There was an okay opening, but we didn’t match anything.\n   *\n   * ```markdown\n   * > | [a](b c\n   *        ^\n   * > | [a][b c\n   *        ^\n   * > | [a] b\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelEndNok(code) {\n    labelStart._balanced = true;\n    return nok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeResource(effects, ok, nok) {\n  return resourceStart;\n\n  /**\n   * At a resource.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceStart(code) {\n    effects.enter(\"resource\");\n    effects.enter(\"resourceMarker\");\n    effects.consume(code);\n    effects.exit(\"resourceMarker\");\n    return resourceBefore;\n  }\n\n  /**\n   * In resource, after `(`, at optional whitespace.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceBefore(code) {\n    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceOpen)(code) : resourceOpen(code);\n  }\n\n  /**\n   * In resource, after optional whitespace, at `)` or a destination.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceOpen(code) {\n    if (code === 41) {\n      return resourceEnd(code);\n    }\n    return factoryDestination(effects, resourceDestinationAfter, resourceDestinationMissing, \"resourceDestination\", \"resourceDestinationLiteral\", \"resourceDestinationLiteralMarker\", \"resourceDestinationRaw\", \"resourceDestinationString\", 32)(code);\n  }\n\n  /**\n   * In resource, after destination, at optional whitespace.\n   *\n   * ```markdown\n   * > | [a](b) c\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceDestinationAfter(code) {\n    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceBetween)(code) : resourceEnd(code);\n  }\n\n  /**\n   * At invalid destination.\n   *\n   * ```markdown\n   * > | [a](<<) b\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceDestinationMissing(code) {\n    return nok(code);\n  }\n\n  /**\n   * In resource, after destination and whitespace, at `(` or title.\n   *\n   * ```markdown\n   * > | [a](b ) c\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceBetween(code) {\n    if (code === 34 || code === 39 || code === 40) {\n      return factoryTitle(effects, resourceTitleAfter, nok, \"resourceTitle\", \"resourceTitleMarker\", \"resourceTitleString\")(code);\n    }\n    return resourceEnd(code);\n  }\n\n  /**\n   * In resource, after title, at optional whitespace.\n   *\n   * ```markdown\n   * > | [a](b \"c\") d\n   *              ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceTitleAfter(code) {\n    return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceEnd)(code) : resourceEnd(code);\n  }\n\n  /**\n   * In resource, at `)`.\n   *\n   * ```markdown\n   * > | [a](b) d\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function resourceEnd(code) {\n    if (code === 41) {\n      effects.enter(\"resourceMarker\");\n      effects.consume(code);\n      effects.exit(\"resourceMarker\");\n      effects.exit(\"resource\");\n      return ok;\n    }\n    return nok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeReferenceFull(effects, ok, nok) {\n  const self = this;\n  return referenceFull;\n\n  /**\n   * In a reference (full), at the `[`.\n   *\n   * ```markdown\n   * > | [a][b] d\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function referenceFull(code) {\n    return factoryLabel.call(self, effects, referenceFullAfter, referenceFullMissing, \"reference\", \"referenceMarker\", \"referenceString\")(code);\n  }\n\n  /**\n   * In a reference (full), after `]`.\n   *\n   * ```markdown\n   * > | [a][b] d\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function referenceFullAfter(code) {\n    return self.parser.defined.includes(normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1))) ? ok(code) : nok(code);\n  }\n\n  /**\n   * In reference (full) that was missing.\n   *\n   * ```markdown\n   * > | [a][b d\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function referenceFullMissing(code) {\n    return nok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeReferenceCollapsed(effects, ok, nok) {\n  return referenceCollapsedStart;\n\n  /**\n   * In reference (collapsed), at `[`.\n   *\n   * > 👉 **Note**: we only get here if the label is defined.\n   *\n   * ```markdown\n   * > | [a][] d\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function referenceCollapsedStart(code) {\n    // We only attempt a collapsed label if there’s a `[`.\n\n    effects.enter(\"reference\");\n    effects.enter(\"referenceMarker\");\n    effects.consume(code);\n    effects.exit(\"referenceMarker\");\n    return referenceCollapsedOpen;\n  }\n\n  /**\n   * In reference (collapsed), at `]`.\n   *\n   * > 👉 **Note**: we only get here if the label is defined.\n   *\n   * ```markdown\n   * > | [a][] d\n   *         ^\n   * ```\n   *\n   *  @type {State}\n   */\n  function referenceCollapsedOpen(code) {\n    if (code === 93) {\n      effects.enter(\"referenceMarker\");\n      effects.consume(code);\n      effects.exit(\"referenceMarker\");\n      effects.exit(\"reference\");\n      return ok;\n    }\n    return nok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { labelEnd } from './label-end.js';\n\n/** @type {Construct} */\nexport const labelStartImage = {\n  name: 'labelStartImage',\n  resolveAll: labelEnd.resolveAll,\n  tokenize: tokenizeLabelStartImage\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeLabelStartImage(effects, ok, nok) {\n  const self = this;\n  return start;\n\n  /**\n   * Start of label (image) start.\n   *\n   * ```markdown\n   * > | a ![b] c\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"labelImage\");\n    effects.enter(\"labelImageMarker\");\n    effects.consume(code);\n    effects.exit(\"labelImageMarker\");\n    return open;\n  }\n\n  /**\n   * After `!`, at `[`.\n   *\n   * ```markdown\n   * > | a ![b] c\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function open(code) {\n    if (code === 91) {\n      effects.enter(\"labelMarker\");\n      effects.consume(code);\n      effects.exit(\"labelMarker\");\n      effects.exit(\"labelImage\");\n      return after;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After `![`.\n   *\n   * ```markdown\n   * > | a ![b] c\n   *         ^\n   * ```\n   *\n   * This is needed in because, when GFM footnotes are enabled, images never\n   * form when started with a `^`.\n   * Instead, links form:\n   *\n   * ```markdown\n   * ![^a](b)\n   *\n   * ![^a][b]\n   *\n   * [b]: c\n   * ```\n   *\n   * ```html\n   * <p>!<a href=\\\"b\\\">^a</a></p>\n   * <p>!<a href=\\\"c\\\">^a</a></p>\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    // To do: use a new field to do this, this is still needed for\n    // `micromark-extension-gfm-footnote`, but the `label-start-link`\n    // behavior isn’t.\n    // Hidden footnotes hook.\n    /* c8 ignore next 3 */\n    return code === 94 && '_hiddenFootnoteSupport' in self.parser.constructs ? nok(code) : ok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { labelEnd } from './label-end.js';\n\n/** @type {Construct} */\nexport const labelStartLink = {\n  name: 'labelStartLink',\n  resolveAll: labelEnd.resolveAll,\n  tokenize: tokenizeLabelStartLink\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeLabelStartLink(effects, ok, nok) {\n  const self = this;\n  return start;\n\n  /**\n   * Start of label (link) start.\n   *\n   * ```markdown\n   * > | a [b] c\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"labelLink\");\n    effects.enter(\"labelMarker\");\n    effects.consume(code);\n    effects.exit(\"labelMarker\");\n    effects.exit(\"labelLink\");\n    return after;\n  }\n\n  /** @type {State} */\n  function after(code) {\n    // To do: this isn’t needed in `micromark-extension-gfm-footnote`,\n    // remove.\n    // Hidden footnotes hook.\n    /* c8 ignore next 3 */\n    return code === 94 && '_hiddenFootnoteSupport' in self.parser.constructs ? nok(code) : ok(code);\n  }\n}","/**\n * @import {\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding } from 'micromark-util-character';\n/** @type {Construct} */\nexport const lineEnding = {\n  name: 'lineEnding',\n  tokenize: tokenizeLineEnding\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeLineEnding(effects, ok) {\n  return start;\n\n  /** @type {State} */\n  function start(code) {\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return factorySpace(effects, ok, \"linePrefix\");\n  }\n}","/**\n * @import {\n *   Code,\n *   Construct,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const thematicBreak = {\n  name: 'thematicBreak',\n  tokenize: tokenizeThematicBreak\n};\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeThematicBreak(effects, ok, nok) {\n  let size = 0;\n  /** @type {NonNullable<Code>} */\n  let marker;\n  return start;\n\n  /**\n   * Start of thematic break.\n   *\n   * ```markdown\n   * > | ***\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter(\"thematicBreak\");\n    // To do: parse indent like `markdown-rs`.\n    return before(code);\n  }\n\n  /**\n   * After optional whitespace, at marker.\n   *\n   * ```markdown\n   * > | ***\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function before(code) {\n    marker = code;\n    return atBreak(code);\n  }\n\n  /**\n   * After something, before something else.\n   *\n   * ```markdown\n   * > | ***\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function atBreak(code) {\n    if (code === marker) {\n      effects.enter(\"thematicBreakSequence\");\n      return sequence(code);\n    }\n    if (size >= 3 && (code === null || markdownLineEnding(code))) {\n      effects.exit(\"thematicBreak\");\n      return ok(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * In sequence.\n   *\n   * ```markdown\n   * > | ***\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function sequence(code) {\n    if (code === marker) {\n      effects.consume(code);\n      size++;\n      return sequence;\n    }\n    effects.exit(\"thematicBreakSequence\");\n    return markdownSpace(code) ? factorySpace(effects, atBreak, \"whitespace\")(code) : atBreak(code);\n  }\n}","/**\n * @import {\n *   Code,\n *   Construct,\n *   Exiter,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { asciiDigit, markdownSpace } from 'micromark-util-character';\nimport { blankLine } from './blank-line.js';\nimport { thematicBreak } from './thematic-break.js';\n\n/** @type {Construct} */\nexport const list = {\n  continuation: {\n    tokenize: tokenizeListContinuation\n  },\n  exit: tokenizeListEnd,\n  name: 'list',\n  tokenize: tokenizeListStart\n};\n\n/** @type {Construct} */\nconst listItemPrefixWhitespaceConstruct = {\n  partial: true,\n  tokenize: tokenizeListItemPrefixWhitespace\n};\n\n/** @type {Construct} */\nconst indentConstruct = {\n  partial: true,\n  tokenize: tokenizeIndent\n};\n\n// To do: `markdown-rs` parses list items on their own and later stitches them\n// together.\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeListStart(effects, ok, nok) {\n  const self = this;\n  const tail = self.events[self.events.length - 1];\n  let initialSize = tail && tail[1].type === \"linePrefix\" ? tail[2].sliceSerialize(tail[1], true).length : 0;\n  let size = 0;\n  return start;\n\n  /** @type {State} */\n  function start(code) {\n    const kind = self.containerState.type || (code === 42 || code === 43 || code === 45 ? \"listUnordered\" : \"listOrdered\");\n    if (kind === \"listUnordered\" ? !self.containerState.marker || code === self.containerState.marker : asciiDigit(code)) {\n      if (!self.containerState.type) {\n        self.containerState.type = kind;\n        effects.enter(kind, {\n          _container: true\n        });\n      }\n      if (kind === \"listUnordered\") {\n        effects.enter(\"listItemPrefix\");\n        return code === 42 || code === 45 ? effects.check(thematicBreak, nok, atMarker)(code) : atMarker(code);\n      }\n      if (!self.interrupt || code === 49) {\n        effects.enter(\"listItemPrefix\");\n        effects.enter(\"listItemValue\");\n        return inside(code);\n      }\n    }\n    return nok(code);\n  }\n\n  /** @type {State} */\n  function inside(code) {\n    if (asciiDigit(code) && ++size < 10) {\n      effects.consume(code);\n      return inside;\n    }\n    if ((!self.interrupt || size < 2) && (self.containerState.marker ? code === self.containerState.marker : code === 41 || code === 46)) {\n      effects.exit(\"listItemValue\");\n      return atMarker(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * @type {State}\n   **/\n  function atMarker(code) {\n    effects.enter(\"listItemMarker\");\n    effects.consume(code);\n    effects.exit(\"listItemMarker\");\n    self.containerState.marker = self.containerState.marker || code;\n    return effects.check(blankLine,\n    // Can’t be empty when interrupting.\n    self.interrupt ? nok : onBlank, effects.attempt(listItemPrefixWhitespaceConstruct, endOfPrefix, otherPrefix));\n  }\n\n  /** @type {State} */\n  function onBlank(code) {\n    self.containerState.initialBlankLine = true;\n    initialSize++;\n    return endOfPrefix(code);\n  }\n\n  /** @type {State} */\n  function otherPrefix(code) {\n    if (markdownSpace(code)) {\n      effects.enter(\"listItemPrefixWhitespace\");\n      effects.consume(code);\n      effects.exit(\"listItemPrefixWhitespace\");\n      return endOfPrefix;\n    }\n    return nok(code);\n  }\n\n  /** @type {State} */\n  function endOfPrefix(code) {\n    self.containerState.size = initialSize + self.sliceSerialize(effects.exit(\"listItemPrefix\"), true).length;\n    return ok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeListContinuation(effects, ok, nok) {\n  const self = this;\n  self.containerState._closeFlow = undefined;\n  return effects.check(blankLine, onBlank, notBlank);\n\n  /** @type {State} */\n  function onBlank(code) {\n    self.containerState.furtherBlankLines = self.containerState.furtherBlankLines || self.containerState.initialBlankLine;\n\n    // We have a blank line.\n    // Still, try to consume at most the items size.\n    return factorySpace(effects, ok, \"listItemIndent\", self.containerState.size + 1)(code);\n  }\n\n  /** @type {State} */\n  function notBlank(code) {\n    if (self.containerState.furtherBlankLines || !markdownSpace(code)) {\n      self.containerState.furtherBlankLines = undefined;\n      self.containerState.initialBlankLine = undefined;\n      return notInCurrentItem(code);\n    }\n    self.containerState.furtherBlankLines = undefined;\n    self.containerState.initialBlankLine = undefined;\n    return effects.attempt(indentConstruct, ok, notInCurrentItem)(code);\n  }\n\n  /** @type {State} */\n  function notInCurrentItem(code) {\n    // While we do continue, we signal that the flow should be closed.\n    self.containerState._closeFlow = true;\n    // As we’re closing flow, we’re no longer interrupting.\n    self.interrupt = undefined;\n    // Always populated by defaults.\n\n    return factorySpace(effects, effects.attempt(list, ok, nok), \"linePrefix\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4)(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeIndent(effects, ok, nok) {\n  const self = this;\n  return factorySpace(effects, afterPrefix, \"listItemIndent\", self.containerState.size + 1);\n\n  /** @type {State} */\n  function afterPrefix(code) {\n    const tail = self.events[self.events.length - 1];\n    return tail && tail[1].type === \"listItemIndent\" && tail[2].sliceSerialize(tail[1], true).length === self.containerState.size ? ok(code) : nok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Exiter}\n */\nfunction tokenizeListEnd(effects) {\n  effects.exit(this.containerState.type);\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeListItemPrefixWhitespace(effects, ok, nok) {\n  const self = this;\n\n  // Always populated by defaults.\n\n  return factorySpace(effects, afterPrefix, \"listItemPrefixWhitespace\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4 + 1);\n\n  /** @type {State} */\n  function afterPrefix(code) {\n    const tail = self.events[self.events.length - 1];\n    return !markdownSpace(code) && tail && tail[1].type === \"listItemPrefixWhitespace\" ? ok(code) : nok(code);\n  }\n}","/**\n * @import {\n *   Code,\n *   Construct,\n *   Resolver,\n *   State,\n *   TokenizeContext,\n *   Tokenizer\n * } from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownSpace } from 'micromark-util-character';\n/** @type {Construct} */\nexport const setextUnderline = {\n  name: 'setextUnderline',\n  resolveTo: resolveToSetextUnderline,\n  tokenize: tokenizeSetextUnderline\n};\n\n/** @type {Resolver} */\nfunction resolveToSetextUnderline(events, context) {\n  // To do: resolve like `markdown-rs`.\n  let index = events.length;\n  /** @type {number | undefined} */\n  let content;\n  /** @type {number | undefined} */\n  let text;\n  /** @type {number | undefined} */\n  let definition;\n\n  // Find the opening of the content.\n  // It’ll always exist: we don’t tokenize if it isn’t there.\n  while (index--) {\n    if (events[index][0] === 'enter') {\n      if (events[index][1].type === \"content\") {\n        content = index;\n        break;\n      }\n      if (events[index][1].type === \"paragraph\") {\n        text = index;\n      }\n    }\n    // Exit\n    else {\n      if (events[index][1].type === \"content\") {\n        // Remove the content end (if needed we’ll add it later)\n        events.splice(index, 1);\n      }\n      if (!definition && events[index][1].type === \"definition\") {\n        definition = index;\n      }\n    }\n  }\n  const heading = {\n    type: \"setextHeading\",\n    start: {\n      ...events[content][1].start\n    },\n    end: {\n      ...events[events.length - 1][1].end\n    }\n  };\n\n  // Change the paragraph to setext heading text.\n  events[text][1].type = \"setextHeadingText\";\n\n  // If we have definitions in the content, we’ll keep on having content,\n  // but we need move it.\n  if (definition) {\n    events.splice(text, 0, ['enter', heading, context]);\n    events.splice(definition + 1, 0, ['exit', events[content][1], context]);\n    events[content][1].end = {\n      ...events[definition][1].end\n    };\n  } else {\n    events[content][1] = heading;\n  }\n\n  // Add the heading exit at the end.\n  events.push(['exit', heading, context]);\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n *   Context.\n * @type {Tokenizer}\n */\nfunction tokenizeSetextUnderline(effects, ok, nok) {\n  const self = this;\n  /** @type {NonNullable<Code>} */\n  let marker;\n  return start;\n\n  /**\n   * At start of heading (setext) underline.\n   *\n   * ```markdown\n   *   | aa\n   * > | ==\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    let index = self.events.length;\n    /** @type {boolean | undefined} */\n    let paragraph;\n    // Find an opening.\n    while (index--) {\n      // Skip enter/exit of line ending, line prefix, and content.\n      // We can now either have a definition or a paragraph.\n      if (self.events[index][1].type !== \"lineEnding\" && self.events[index][1].type !== \"linePrefix\" && self.events[index][1].type !== \"content\") {\n        paragraph = self.events[index][1].type === \"paragraph\";\n        break;\n      }\n    }\n\n    // To do: handle lazy/pierce like `markdown-rs`.\n    // To do: parse indent like `markdown-rs`.\n    if (!self.parser.lazy[self.now().line] && (self.interrupt || paragraph)) {\n      effects.enter(\"setextHeadingLine\");\n      marker = code;\n      return before(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * After optional whitespace, at `-` or `=`.\n   *\n   * ```markdown\n   *   | aa\n   * > | ==\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function before(code) {\n    effects.enter(\"setextHeadingLineSequence\");\n    return inside(code);\n  }\n\n  /**\n   * In sequence.\n   *\n   * ```markdown\n   *   | aa\n   * > | ==\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function inside(code) {\n    if (code === marker) {\n      effects.consume(code);\n      return inside;\n    }\n    effects.exit(\"setextHeadingLineSequence\");\n    return markdownSpace(code) ? factorySpace(effects, after, \"lineSuffix\")(code) : after(code);\n  }\n\n  /**\n   * After sequence, after optional whitespace.\n   *\n   * ```markdown\n   *   | aa\n   * > | ==\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"setextHeadingLine\");\n      return ok(code);\n    }\n    return nok(code);\n  }\n}","/**\n * @import {\n *   InitialConstruct,\n *   Initializer,\n *   State,\n *   TokenizeContext\n * } from 'micromark-util-types'\n */\n\nimport { blankLine, content } from 'micromark-core-commonmark';\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding } from 'micromark-util-character';\n/** @type {InitialConstruct} */\nexport const flow = {\n  tokenize: initializeFlow\n};\n\n/**\n * @this {TokenizeContext}\n *   Self.\n * @type {Initializer}\n *   Initializer.\n */\nfunction initializeFlow(effects) {\n  const self = this;\n  const initial = effects.attempt(\n  // Try to parse a blank line.\n  blankLine, atBlankEnding,\n  // Try to parse initial flow (essentially, only code).\n  effects.attempt(this.parser.constructs.flowInitial, afterConstruct, factorySpace(effects, effects.attempt(this.parser.constructs.flow, afterConstruct, effects.attempt(content, afterConstruct)), \"linePrefix\")));\n  return initial;\n\n  /** @type {State} */\n  function atBlankEnding(code) {\n    if (code === null) {\n      effects.consume(code);\n      return;\n    }\n    effects.enter(\"lineEndingBlank\");\n    effects.consume(code);\n    effects.exit(\"lineEndingBlank\");\n    self.currentConstruct = undefined;\n    return initial;\n  }\n\n  /** @type {State} */\n  function afterConstruct(code) {\n    if (code === null) {\n      effects.consume(code);\n      return;\n    }\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    self.currentConstruct = undefined;\n    return initial;\n  }\n}","/**\n * @import {\n *   Code,\n *   InitialConstruct,\n *   Initializer,\n *   Resolver,\n *   State,\n *   TokenizeContext\n * } from 'micromark-util-types'\n */\n\nexport const resolver = {\n  resolveAll: createResolver()\n};\nexport const string = initializeFactory('string');\nexport const text = initializeFactory('text');\n\n/**\n * @param {'string' | 'text'} field\n *   Field.\n * @returns {InitialConstruct}\n *   Construct.\n */\nfunction initializeFactory(field) {\n  return {\n    resolveAll: createResolver(field === 'text' ? resolveAllLineSuffixes : undefined),\n    tokenize: initializeText\n  };\n\n  /**\n   * @this {TokenizeContext}\n   *   Context.\n   * @type {Initializer}\n   */\n  function initializeText(effects) {\n    const self = this;\n    const constructs = this.parser.constructs[field];\n    const text = effects.attempt(constructs, start, notText);\n    return start;\n\n    /** @type {State} */\n    function start(code) {\n      return atBreak(code) ? text(code) : notText(code);\n    }\n\n    /** @type {State} */\n    function notText(code) {\n      if (code === null) {\n        effects.consume(code);\n        return;\n      }\n      effects.enter(\"data\");\n      effects.consume(code);\n      return data;\n    }\n\n    /** @type {State} */\n    function data(code) {\n      if (atBreak(code)) {\n        effects.exit(\"data\");\n        return text(code);\n      }\n\n      // Data.\n      effects.consume(code);\n      return data;\n    }\n\n    /**\n     * @param {Code} code\n     *   Code.\n     * @returns {boolean}\n     *   Whether the code is a break.\n     */\n    function atBreak(code) {\n      if (code === null) {\n        return true;\n      }\n      const list = constructs[code];\n      let index = -1;\n      if (list) {\n        // Always populated by defaults.\n\n        while (++index < list.length) {\n          const item = list[index];\n          if (!item.previous || item.previous.call(self, self.previous)) {\n            return true;\n          }\n        }\n      }\n      return false;\n    }\n  }\n}\n\n/**\n * @param {Resolver | undefined} [extraResolver]\n *   Resolver.\n * @returns {Resolver}\n *   Resolver.\n */\nfunction createResolver(extraResolver) {\n  return resolveAllText;\n\n  /** @type {Resolver} */\n  function resolveAllText(events, context) {\n    let index = -1;\n    /** @type {number | undefined} */\n    let enter;\n\n    // A rather boring computation (to merge adjacent `data` events) which\n    // improves mm performance by 29%.\n    while (++index <= events.length) {\n      if (enter === undefined) {\n        if (events[index] && events[index][1].type === \"data\") {\n          enter = index;\n          index++;\n        }\n      } else if (!events[index] || events[index][1].type !== \"data\") {\n        // Don’t do anything if there is one data token.\n        if (index !== enter + 2) {\n          events[enter][1].end = events[index - 1][1].end;\n          events.splice(enter + 2, index - enter - 2);\n          index = enter + 2;\n        }\n        enter = undefined;\n      }\n    }\n    return extraResolver ? extraResolver(events, context) : events;\n  }\n}\n\n/**\n * A rather ugly set of instructions which again looks at chunks in the input\n * stream.\n * The reason to do this here is that it is *much* faster to parse in reverse.\n * And that we can’t hook into `null` to split the line suffix before an EOF.\n * To do: figure out if we can make this into a clean utility, or even in core.\n * As it will be useful for GFMs literal autolink extension (and maybe even\n * tables?)\n *\n * @type {Resolver}\n */\nfunction resolveAllLineSuffixes(events, context) {\n  let eventIndex = 0; // Skip first.\n\n  while (++eventIndex <= events.length) {\n    if ((eventIndex === events.length || events[eventIndex][1].type === \"lineEnding\") && events[eventIndex - 1][1].type === \"data\") {\n      const data = events[eventIndex - 1][1];\n      const chunks = context.sliceStream(data);\n      let index = chunks.length;\n      let bufferIndex = -1;\n      let size = 0;\n      /** @type {boolean | undefined} */\n      let tabs;\n      while (index--) {\n        const chunk = chunks[index];\n        if (typeof chunk === 'string') {\n          bufferIndex = chunk.length;\n          while (chunk.charCodeAt(bufferIndex - 1) === 32) {\n            size++;\n            bufferIndex--;\n          }\n          if (bufferIndex) break;\n          bufferIndex = -1;\n        }\n        // Number\n        else if (chunk === -2) {\n          tabs = true;\n          size++;\n        } else if (chunk === -1) {\n          // Empty\n        } else {\n          // Replacement character, exit.\n          index++;\n          break;\n        }\n      }\n\n      // Allow final trailing whitespace.\n      if (context._contentTypeTextTrailing && eventIndex === events.length) {\n        size = 0;\n      }\n      if (size) {\n        const token = {\n          type: eventIndex === events.length || tabs || size < 2 ? \"lineSuffix\" : \"hardBreakTrailing\",\n          start: {\n            _bufferIndex: index ? bufferIndex : data.start._bufferIndex + bufferIndex,\n            _index: data.start._index + index,\n            line: data.end.line,\n            column: data.end.column - size,\n            offset: data.end.offset - size\n          },\n          end: {\n            ...data.end\n          }\n        };\n        data.end = {\n          ...token.start\n        };\n        if (data.start.offset === data.end.offset) {\n          Object.assign(data, token);\n        } else {\n          events.splice(eventIndex, 0, ['enter', token, context], ['exit', token, context]);\n          eventIndex += 2;\n        }\n      }\n      eventIndex++;\n    }\n  }\n  return events;\n}","/**\n * @import {Extension} from 'micromark-util-types'\n */\n\nimport { attention, autolink, blockQuote, characterEscape, characterReference, codeFenced, codeIndented, codeText, definition, hardBreakEscape, headingAtx, htmlFlow, htmlText, labelEnd, labelStartImage, labelStartLink, lineEnding, list, setextUnderline, thematicBreak } from 'micromark-core-commonmark';\nimport { resolver as resolveText } from './initialize/text.js';\n\n/** @satisfies {Extension['document']} */\nexport const document = {\n  [42]: list,\n  [43]: list,\n  [45]: list,\n  [48]: list,\n  [49]: list,\n  [50]: list,\n  [51]: list,\n  [52]: list,\n  [53]: list,\n  [54]: list,\n  [55]: list,\n  [56]: list,\n  [57]: list,\n  [62]: blockQuote\n};\n\n/** @satisfies {Extension['contentInitial']} */\nexport const contentInitial = {\n  [91]: definition\n};\n\n/** @satisfies {Extension['flowInitial']} */\nexport const flowInitial = {\n  [-2]: codeIndented,\n  [-1]: codeIndented,\n  [32]: codeIndented\n};\n\n/** @satisfies {Extension['flow']} */\nexport const flow = {\n  [35]: headingAtx,\n  [42]: thematicBreak,\n  [45]: [setextUnderline, thematicBreak],\n  [60]: htmlFlow,\n  [61]: setextUnderline,\n  [95]: thematicBreak,\n  [96]: codeFenced,\n  [126]: codeFenced\n};\n\n/** @satisfies {Extension['string']} */\nexport const string = {\n  [38]: characterReference,\n  [92]: characterEscape\n};\n\n/** @satisfies {Extension['text']} */\nexport const text = {\n  [-5]: lineEnding,\n  [-4]: lineEnding,\n  [-3]: lineEnding,\n  [33]: labelStartImage,\n  [38]: characterReference,\n  [42]: attention,\n  [60]: [autolink, htmlText],\n  [91]: labelStartLink,\n  [92]: [hardBreakEscape, characterEscape],\n  [93]: labelEnd,\n  [95]: attention,\n  [96]: codeText\n};\n\n/** @satisfies {Extension['insideSpan']} */\nexport const insideSpan = {\n  null: [attention, resolveText]\n};\n\n/** @satisfies {Extension['attentionMarkers']} */\nexport const attentionMarkers = {\n  null: [42, 95]\n};\n\n/** @satisfies {Extension['disable']} */\nexport const disable = {\n  null: []\n};","/**\n * @import {\n *   Chunk,\n *   Code,\n *   ConstructRecord,\n *   Construct,\n *   Effects,\n *   InitialConstruct,\n *   ParseContext,\n *   Point,\n *   State,\n *   TokenizeContext,\n *   Token\n * } from 'micromark-util-types'\n */\n\n/**\n * @callback Restore\n *   Restore the state.\n * @returns {undefined}\n *   Nothing.\n *\n * @typedef Info\n *   Info.\n * @property {Restore} restore\n *   Restore.\n * @property {number} from\n *   From.\n *\n * @callback ReturnHandle\n *   Handle a successful run.\n * @param {Construct} construct\n *   Construct.\n * @param {Info} info\n *   Info.\n * @returns {undefined}\n *   Nothing.\n */\n\nimport { markdownLineEnding } from 'micromark-util-character';\nimport { push, splice } from 'micromark-util-chunked';\nimport { resolveAll } from 'micromark-util-resolve-all';\n/**\n * Create a tokenizer.\n * Tokenizers deal with one type of data (e.g., containers, flow, text).\n * The parser is the object dealing with it all.\n * `initialize` works like other constructs, except that only its `tokenize`\n * function is used, in which case it doesn’t receive an `ok` or `nok`.\n * `from` can be given to set the point before the first character, although\n * when further lines are indented, they must be set with `defineSkip`.\n *\n * @param {ParseContext} parser\n *   Parser.\n * @param {InitialConstruct} initialize\n *   Construct.\n * @param {Omit<Point, '_bufferIndex' | '_index'> | undefined} [from]\n *   Point (optional).\n * @returns {TokenizeContext}\n *   Context.\n */\nexport function createTokenizer(parser, initialize, from) {\n  /** @type {Point} */\n  let point = {\n    _bufferIndex: -1,\n    _index: 0,\n    line: from && from.line || 1,\n    column: from && from.column || 1,\n    offset: from && from.offset || 0\n  };\n  /** @type {Record<string, number>} */\n  const columnStart = {};\n  /** @type {Array<Construct>} */\n  const resolveAllConstructs = [];\n  /** @type {Array<Chunk>} */\n  let chunks = [];\n  /** @type {Array<Token>} */\n  let stack = [];\n  /** @type {boolean | undefined} */\n  let consumed = true;\n\n  /**\n   * Tools used for tokenizing.\n   *\n   * @type {Effects}\n   */\n  const effects = {\n    attempt: constructFactory(onsuccessfulconstruct),\n    check: constructFactory(onsuccessfulcheck),\n    consume,\n    enter,\n    exit,\n    interrupt: constructFactory(onsuccessfulcheck, {\n      interrupt: true\n    })\n  };\n\n  /**\n   * State and tools for resolving and serializing.\n   *\n   * @type {TokenizeContext}\n   */\n  const context = {\n    code: null,\n    containerState: {},\n    defineSkip,\n    events: [],\n    now,\n    parser,\n    previous: null,\n    sliceSerialize,\n    sliceStream,\n    write\n  };\n\n  /**\n   * The state function.\n   *\n   * @type {State | undefined}\n   */\n  let state = initialize.tokenize.call(context, effects);\n\n  /**\n   * Track which character we expect to be consumed, to catch bugs.\n   *\n   * @type {Code}\n   */\n  let expectedCode;\n  if (initialize.resolveAll) {\n    resolveAllConstructs.push(initialize);\n  }\n  return context;\n\n  /** @type {TokenizeContext['write']} */\n  function write(slice) {\n    chunks = push(chunks, slice);\n    main();\n\n    // Exit if we’re not done, resolve might change stuff.\n    if (chunks[chunks.length - 1] !== null) {\n      return [];\n    }\n    addResult(initialize, 0);\n\n    // Otherwise, resolve, and exit.\n    context.events = resolveAll(resolveAllConstructs, context.events, context);\n    return context.events;\n  }\n\n  //\n  // Tools.\n  //\n\n  /** @type {TokenizeContext['sliceSerialize']} */\n  function sliceSerialize(token, expandTabs) {\n    return serializeChunks(sliceStream(token), expandTabs);\n  }\n\n  /** @type {TokenizeContext['sliceStream']} */\n  function sliceStream(token) {\n    return sliceChunks(chunks, token);\n  }\n\n  /** @type {TokenizeContext['now']} */\n  function now() {\n    // This is a hot path, so we clone manually instead of `Object.assign({}, point)`\n    const {\n      _bufferIndex,\n      _index,\n      line,\n      column,\n      offset\n    } = point;\n    return {\n      _bufferIndex,\n      _index,\n      line,\n      column,\n      offset\n    };\n  }\n\n  /** @type {TokenizeContext['defineSkip']} */\n  function defineSkip(value) {\n    columnStart[value.line] = value.column;\n    accountForPotentialSkip();\n  }\n\n  //\n  // State management.\n  //\n\n  /**\n   * Main loop (note that `_index` and `_bufferIndex` in `point` are modified by\n   * `consume`).\n   * Here is where we walk through the chunks, which either include strings of\n   * several characters, or numerical character codes.\n   * The reason to do this in a loop instead of a call is so the stack can\n   * drain.\n   *\n   * @returns {undefined}\n   *   Nothing.\n   */\n  function main() {\n    /** @type {number} */\n    let chunkIndex;\n    while (point._index < chunks.length) {\n      const chunk = chunks[point._index];\n\n      // If we’re in a buffer chunk, loop through it.\n      if (typeof chunk === 'string') {\n        chunkIndex = point._index;\n        if (point._bufferIndex < 0) {\n          point._bufferIndex = 0;\n        }\n        while (point._index === chunkIndex && point._bufferIndex < chunk.length) {\n          go(chunk.charCodeAt(point._bufferIndex));\n        }\n      } else {\n        go(chunk);\n      }\n    }\n  }\n\n  /**\n   * Deal with one code.\n   *\n   * @param {Code} code\n   *   Code.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  function go(code) {\n    consumed = undefined;\n    expectedCode = code;\n    state = state(code);\n  }\n\n  /** @type {Effects['consume']} */\n  function consume(code) {\n    if (markdownLineEnding(code)) {\n      point.line++;\n      point.column = 1;\n      point.offset += code === -3 ? 2 : 1;\n      accountForPotentialSkip();\n    } else if (code !== -1) {\n      point.column++;\n      point.offset++;\n    }\n\n    // Not in a string chunk.\n    if (point._bufferIndex < 0) {\n      point._index++;\n    } else {\n      point._bufferIndex++;\n\n      // At end of string chunk.\n      if (point._bufferIndex ===\n      // Points w/ non-negative `_bufferIndex` reference\n      // strings.\n      /** @type {string} */\n      chunks[point._index].length) {\n        point._bufferIndex = -1;\n        point._index++;\n      }\n    }\n\n    // Expose the previous character.\n    context.previous = code;\n\n    // Mark as consumed.\n    consumed = true;\n  }\n\n  /** @type {Effects['enter']} */\n  function enter(type, fields) {\n    /** @type {Token} */\n    // @ts-expect-error Patch instead of assign required fields to help GC.\n    const token = fields || {};\n    token.type = type;\n    token.start = now();\n    context.events.push(['enter', token, context]);\n    stack.push(token);\n    return token;\n  }\n\n  /** @type {Effects['exit']} */\n  function exit(type) {\n    const token = stack.pop();\n    token.end = now();\n    context.events.push(['exit', token, context]);\n    return token;\n  }\n\n  /**\n   * Use results.\n   *\n   * @type {ReturnHandle}\n   */\n  function onsuccessfulconstruct(construct, info) {\n    addResult(construct, info.from);\n  }\n\n  /**\n   * Discard results.\n   *\n   * @type {ReturnHandle}\n   */\n  function onsuccessfulcheck(_, info) {\n    info.restore();\n  }\n\n  /**\n   * Factory to attempt/check/interrupt.\n   *\n   * @param {ReturnHandle} onreturn\n   *   Callback.\n   * @param {{interrupt?: boolean | undefined} | undefined} [fields]\n   *   Fields.\n   */\n  function constructFactory(onreturn, fields) {\n    return hook;\n\n    /**\n     * Handle either an object mapping codes to constructs, a list of\n     * constructs, or a single construct.\n     *\n     * @param {Array<Construct> | ConstructRecord | Construct} constructs\n     *   Constructs.\n     * @param {State} returnState\n     *   State.\n     * @param {State | undefined} [bogusState]\n     *   State.\n     * @returns {State}\n     *   State.\n     */\n    function hook(constructs, returnState, bogusState) {\n      /** @type {ReadonlyArray<Construct>} */\n      let listOfConstructs;\n      /** @type {number} */\n      let constructIndex;\n      /** @type {Construct} */\n      let currentConstruct;\n      /** @type {Info} */\n      let info;\n      return Array.isArray(constructs) ? /* c8 ignore next 1 */\n      handleListOfConstructs(constructs) : 'tokenize' in constructs ?\n      // Looks like a construct.\n      handleListOfConstructs([(/** @type {Construct} */constructs)]) : handleMapOfConstructs(constructs);\n\n      /**\n       * Handle a list of construct.\n       *\n       * @param {ConstructRecord} map\n       *   Constructs.\n       * @returns {State}\n       *   State.\n       */\n      function handleMapOfConstructs(map) {\n        return start;\n\n        /** @type {State} */\n        function start(code) {\n          const left = code !== null && map[code];\n          const all = code !== null && map.null;\n          const list = [\n          // To do: add more extension tests.\n          /* c8 ignore next 2 */\n          ...(Array.isArray(left) ? left : left ? [left] : []), ...(Array.isArray(all) ? all : all ? [all] : [])];\n          return handleListOfConstructs(list)(code);\n        }\n      }\n\n      /**\n       * Handle a list of construct.\n       *\n       * @param {ReadonlyArray<Construct>} list\n       *   Constructs.\n       * @returns {State}\n       *   State.\n       */\n      function handleListOfConstructs(list) {\n        listOfConstructs = list;\n        constructIndex = 0;\n        if (list.length === 0) {\n          return bogusState;\n        }\n        return handleConstruct(list[constructIndex]);\n      }\n\n      /**\n       * Handle a single construct.\n       *\n       * @param {Construct} construct\n       *   Construct.\n       * @returns {State}\n       *   State.\n       */\n      function handleConstruct(construct) {\n        return start;\n\n        /** @type {State} */\n        function start(code) {\n          // To do: not needed to store if there is no bogus state, probably?\n          // Currently doesn’t work because `inspect` in document does a check\n          // w/o a bogus, which doesn’t make sense. But it does seem to help perf\n          // by not storing.\n          info = store();\n          currentConstruct = construct;\n          if (!construct.partial) {\n            context.currentConstruct = construct;\n          }\n\n          // Always populated by defaults.\n\n          if (construct.name && context.parser.constructs.disable.null.includes(construct.name)) {\n            return nok(code);\n          }\n          return construct.tokenize.call(\n          // If we do have fields, create an object w/ `context` as its\n          // prototype.\n          // This allows a “live binding”, which is needed for `interrupt`.\n          fields ? Object.assign(Object.create(context), fields) : context, effects, ok, nok)(code);\n        }\n      }\n\n      /** @type {State} */\n      function ok(code) {\n        consumed = true;\n        onreturn(currentConstruct, info);\n        return returnState;\n      }\n\n      /** @type {State} */\n      function nok(code) {\n        consumed = true;\n        info.restore();\n        if (++constructIndex < listOfConstructs.length) {\n          return handleConstruct(listOfConstructs[constructIndex]);\n        }\n        return bogusState;\n      }\n    }\n  }\n\n  /**\n   * @param {Construct} construct\n   *   Construct.\n   * @param {number} from\n   *   From.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  function addResult(construct, from) {\n    if (construct.resolveAll && !resolveAllConstructs.includes(construct)) {\n      resolveAllConstructs.push(construct);\n    }\n    if (construct.resolve) {\n      splice(context.events, from, context.events.length - from, construct.resolve(context.events.slice(from), context));\n    }\n    if (construct.resolveTo) {\n      context.events = construct.resolveTo(context.events, context);\n    }\n  }\n\n  /**\n   * Store state.\n   *\n   * @returns {Info}\n   *   Info.\n   */\n  function store() {\n    const startPoint = now();\n    const startPrevious = context.previous;\n    const startCurrentConstruct = context.currentConstruct;\n    const startEventsIndex = context.events.length;\n    const startStack = Array.from(stack);\n    return {\n      from: startEventsIndex,\n      restore\n    };\n\n    /**\n     * Restore state.\n     *\n     * @returns {undefined}\n     *   Nothing.\n     */\n    function restore() {\n      point = startPoint;\n      context.previous = startPrevious;\n      context.currentConstruct = startCurrentConstruct;\n      context.events.length = startEventsIndex;\n      stack = startStack;\n      accountForPotentialSkip();\n    }\n  }\n\n  /**\n   * Move the current point a bit forward in the line when it’s on a column\n   * skip.\n   *\n   * @returns {undefined}\n   *   Nothing.\n   */\n  function accountForPotentialSkip() {\n    if (point.line in columnStart && point.column < 2) {\n      point.column = columnStart[point.line];\n      point.offset += columnStart[point.line] - 1;\n    }\n  }\n}\n\n/**\n * Get the chunks from a slice of chunks in the range of a token.\n *\n * @param {ReadonlyArray<Chunk>} chunks\n *   Chunks.\n * @param {Pick<Token, 'end' | 'start'>} token\n *   Token.\n * @returns {Array<Chunk>}\n *   Chunks.\n */\nfunction sliceChunks(chunks, token) {\n  const startIndex = token.start._index;\n  const startBufferIndex = token.start._bufferIndex;\n  const endIndex = token.end._index;\n  const endBufferIndex = token.end._bufferIndex;\n  /** @type {Array<Chunk>} */\n  let view;\n  if (startIndex === endIndex) {\n    // @ts-expect-error `_bufferIndex` is used on string chunks.\n    view = [chunks[startIndex].slice(startBufferIndex, endBufferIndex)];\n  } else {\n    view = chunks.slice(startIndex, endIndex);\n    if (startBufferIndex > -1) {\n      const head = view[0];\n      if (typeof head === 'string') {\n        view[0] = head.slice(startBufferIndex);\n        /* c8 ignore next 4 -- used to be used, no longer */\n      } else {\n        view.shift();\n      }\n    }\n    if (endBufferIndex > 0) {\n      // @ts-expect-error `_bufferIndex` is used on string chunks.\n      view.push(chunks[endIndex].slice(0, endBufferIndex));\n    }\n  }\n  return view;\n}\n\n/**\n * Get the string value of a slice of chunks.\n *\n * @param {ReadonlyArray<Chunk>} chunks\n *   Chunks.\n * @param {boolean | undefined} [expandTabs=false]\n *   Whether to expand tabs (default: `false`).\n * @returns {string}\n *   Result.\n */\nfunction serializeChunks(chunks, expandTabs) {\n  let index = -1;\n  /** @type {Array<string>} */\n  const result = [];\n  /** @type {boolean | undefined} */\n  let atTab;\n  while (++index < chunks.length) {\n    const chunk = chunks[index];\n    /** @type {string} */\n    let value;\n    if (typeof chunk === 'string') {\n      value = chunk;\n    } else switch (chunk) {\n      case -5:\n        {\n          value = \"\\r\";\n          break;\n        }\n      case -4:\n        {\n          value = \"\\n\";\n          break;\n        }\n      case -3:\n        {\n          value = \"\\r\" + \"\\n\";\n          break;\n        }\n      case -2:\n        {\n          value = expandTabs ? \" \" : \"\\t\";\n          break;\n        }\n      case -1:\n        {\n          if (!expandTabs && atTab) continue;\n          value = \" \";\n          break;\n        }\n      default:\n        {\n          // Currently only replacement character.\n          value = String.fromCharCode(chunk);\n        }\n    }\n    atTab = chunk === -2;\n    result.push(value);\n  }\n  return result.join('');\n}","/**\n * @import {\n *   Create,\n *   FullNormalizedExtension,\n *   InitialConstruct,\n *   ParseContext,\n *   ParseOptions\n * } from 'micromark-util-types'\n */\n\nimport { combineExtensions } from 'micromark-util-combine-extensions';\nimport { content } from './initialize/content.js';\nimport { document } from './initialize/document.js';\nimport { flow } from './initialize/flow.js';\nimport { string, text } from './initialize/text.js';\nimport * as defaultConstructs from './constructs.js';\nimport { createTokenizer } from './create-tokenizer.js';\n\n/**\n * @param {ParseOptions | null | undefined} [options]\n *   Configuration (optional).\n * @returns {ParseContext}\n *   Parser.\n */\nexport function parse(options) {\n  const settings = options || {};\n  const constructs = /** @type {FullNormalizedExtension} */\n  combineExtensions([defaultConstructs, ...(settings.extensions || [])]);\n\n  /** @type {ParseContext} */\n  const parser = {\n    constructs,\n    content: create(content),\n    defined: [],\n    document: create(document),\n    flow: create(flow),\n    lazy: {},\n    string: create(string),\n    text: create(text)\n  };\n  return parser;\n\n  /**\n   * @param {InitialConstruct} initial\n   *   Construct to start with.\n   * @returns {Create}\n   *   Create a tokenizer.\n   */\n  function create(initial) {\n    return creator;\n    /** @type {Create} */\n    function creator(from) {\n      return createTokenizer(parser, initial, from);\n    }\n  }\n}","/**\n * @import {Event} from 'micromark-util-types'\n */\n\nimport { subtokenize } from 'micromark-util-subtokenize';\n\n/**\n * @param {Array<Event>} events\n *   Events.\n * @returns {Array<Event>}\n *   Events.\n */\nexport function postprocess(events) {\n  while (!subtokenize(events)) {\n    // Empty\n  }\n  return events;\n}","/**\n * @import {Chunk, Code, Encoding, Value} from 'micromark-util-types'\n */\n\n/**\n * @callback Preprocessor\n *   Preprocess a value.\n * @param {Value} value\n *   Value.\n * @param {Encoding | null | undefined} [encoding]\n *   Encoding when `value` is a typed array (optional).\n * @param {boolean | null | undefined} [end=false]\n *   Whether this is the last chunk (default: `false`).\n * @returns {Array<Chunk>}\n *   Chunks.\n */\n\nconst search = /[\\0\\t\\n\\r]/g;\n\n/**\n * @returns {Preprocessor}\n *   Preprocess a value.\n */\nexport function preprocess() {\n  let column = 1;\n  let buffer = '';\n  /** @type {boolean | undefined} */\n  let start = true;\n  /** @type {boolean | undefined} */\n  let atCarriageReturn;\n  return preprocessor;\n\n  /** @type {Preprocessor} */\n  // eslint-disable-next-line complexity\n  function preprocessor(value, encoding, end) {\n    /** @type {Array<Chunk>} */\n    const chunks = [];\n    /** @type {RegExpMatchArray | null} */\n    let match;\n    /** @type {number} */\n    let next;\n    /** @type {number} */\n    let startPosition;\n    /** @type {number} */\n    let endPosition;\n    /** @type {Code} */\n    let code;\n    value = buffer + (typeof value === 'string' ? value.toString() : new TextDecoder(encoding || undefined).decode(value));\n    startPosition = 0;\n    buffer = '';\n    if (start) {\n      // To do: `markdown-rs` actually parses BOMs (byte order mark).\n      if (value.charCodeAt(0) === 65279) {\n        startPosition++;\n      }\n      start = undefined;\n    }\n    while (startPosition < value.length) {\n      search.lastIndex = startPosition;\n      match = search.exec(value);\n      endPosition = match && match.index !== undefined ? match.index : value.length;\n      code = value.charCodeAt(endPosition);\n      if (!match) {\n        buffer = value.slice(startPosition);\n        break;\n      }\n      if (code === 10 && startPosition === endPosition && atCarriageReturn) {\n        chunks.push(-3);\n        atCarriageReturn = undefined;\n      } else {\n        if (atCarriageReturn) {\n          chunks.push(-5);\n          atCarriageReturn = undefined;\n        }\n        if (startPosition < endPosition) {\n          chunks.push(value.slice(startPosition, endPosition));\n          column += endPosition - startPosition;\n        }\n        switch (code) {\n          case 0:\n            {\n              chunks.push(65533);\n              column++;\n              break;\n            }\n          case 9:\n            {\n              next = Math.ceil(column / 4) * 4;\n              chunks.push(-2);\n              while (column++ < next) chunks.push(-1);\n              break;\n            }\n          case 10:\n            {\n              chunks.push(-4);\n              column = 1;\n              break;\n            }\n          default:\n            {\n              atCarriageReturn = true;\n              column = 1;\n            }\n        }\n      }\n      startPosition = endPosition + 1;\n    }\n    if (end) {\n      if (atCarriageReturn) chunks.push(-5);\n      if (buffer) chunks.push(buffer);\n      chunks.push(null);\n    }\n    return chunks;\n  }\n}","import { decodeNamedCharacterReference } from 'decode-named-character-reference';\nimport { decodeNumericCharacterReference } from 'micromark-util-decode-numeric-character-reference';\nconst characterEscapeOrReference = /\\\\([!-/:-@[-`{-~])|&(#(?:\\d{1,7}|x[\\da-f]{1,6})|[\\da-z]{1,31});/gi;\n\n/**\n * Decode markdown strings (which occur in places such as fenced code info\n * strings, destinations, labels, and titles).\n *\n * The “string” content type allows character escapes and -references.\n * This decodes those.\n *\n * @param {string} value\n *   Value to decode.\n * @returns {string}\n *   Decoded value.\n */\nexport function decodeString(value) {\n  return value.replace(characterEscapeOrReference, decode);\n}\n\n/**\n * @param {string} $0\n *   Match.\n * @param {string} $1\n *   Character escape.\n * @param {string} $2\n *   Character reference.\n * @returns {string}\n *   Decoded value\n */\nfunction decode($0, $1, $2) {\n  if ($1) {\n    // Escape.\n    return $1;\n  }\n\n  // Reference.\n  const head = $2.charCodeAt(0);\n  if (head === 35) {\n    const head = $2.charCodeAt(1);\n    const hex = head === 120 || head === 88;\n    return decodeNumericCharacterReference($2.slice(hex ? 2 : 1), hex ? 16 : 10);\n  }\n  return decodeNamedCharacterReference($2) || $0;\n}","/**\n * @import {\n *   Break,\n *   Blockquote,\n *   Code,\n *   Definition,\n *   Emphasis,\n *   Heading,\n *   Html,\n *   Image,\n *   InlineCode,\n *   Link,\n *   ListItem,\n *   List,\n *   Nodes,\n *   Paragraph,\n *   PhrasingContent,\n *   ReferenceType,\n *   Root,\n *   Strong,\n *   Text,\n *   ThematicBreak\n * } from 'mdast'\n * @import {\n *   Encoding,\n *   Event,\n *   Token,\n *   Value\n * } from 'micromark-util-types'\n * @import {Point} from 'unist'\n * @import {\n *   CompileContext,\n *   CompileData,\n *   Config,\n *   Extension,\n *   Handle,\n *   OnEnterError,\n *   Options\n * } from './types.js'\n */\n\nimport { toString } from 'mdast-util-to-string';\nimport { parse, postprocess, preprocess } from 'micromark';\nimport { decodeNumericCharacterReference } from 'micromark-util-decode-numeric-character-reference';\nimport { decodeString } from 'micromark-util-decode-string';\nimport { normalizeIdentifier } from 'micromark-util-normalize-identifier';\nimport { decodeNamedCharacterReference } from 'decode-named-character-reference';\nimport { stringifyPosition } from 'unist-util-stringify-position';\nconst own = {}.hasOwnProperty;\n\n/**\n * Turn markdown into a syntax tree.\n *\n * @overload\n * @param {Value} value\n * @param {Encoding | null | undefined} [encoding]\n * @param {Options | null | undefined} [options]\n * @returns {Root}\n *\n * @overload\n * @param {Value} value\n * @param {Options | null | undefined} [options]\n * @returns {Root}\n *\n * @param {Value} value\n *   Markdown to parse.\n * @param {Encoding | Options | null | undefined} [encoding]\n *   Character encoding for when `value` is `Buffer`.\n * @param {Options | null | undefined} [options]\n *   Configuration.\n * @returns {Root}\n *   mdast tree.\n */\nexport function fromMarkdown(value, encoding, options) {\n  if (encoding && typeof encoding === 'object') {\n    options = encoding;\n    encoding = undefined;\n  }\n  return compiler(options)(postprocess(parse(options).document().write(preprocess()(value, encoding, true))));\n}\n\n/**\n * Note this compiler only understand complete buffering, not streaming.\n *\n * @param {Options | null | undefined} [options]\n */\nfunction compiler(options) {\n  /** @type {Config} */\n  const config = {\n    transforms: [],\n    canContainEols: ['emphasis', 'fragment', 'heading', 'paragraph', 'strong'],\n    enter: {\n      autolink: opener(link),\n      autolinkProtocol: onenterdata,\n      autolinkEmail: onenterdata,\n      atxHeading: opener(heading),\n      blockQuote: opener(blockQuote),\n      characterEscape: onenterdata,\n      characterReference: onenterdata,\n      codeFenced: opener(codeFlow),\n      codeFencedFenceInfo: buffer,\n      codeFencedFenceMeta: buffer,\n      codeIndented: opener(codeFlow, buffer),\n      codeText: opener(codeText, buffer),\n      codeTextData: onenterdata,\n      data: onenterdata,\n      codeFlowValue: onenterdata,\n      definition: opener(definition),\n      definitionDestinationString: buffer,\n      definitionLabelString: buffer,\n      definitionTitleString: buffer,\n      emphasis: opener(emphasis),\n      hardBreakEscape: opener(hardBreak),\n      hardBreakTrailing: opener(hardBreak),\n      htmlFlow: opener(html, buffer),\n      htmlFlowData: onenterdata,\n      htmlText: opener(html, buffer),\n      htmlTextData: onenterdata,\n      image: opener(image),\n      label: buffer,\n      link: opener(link),\n      listItem: opener(listItem),\n      listItemValue: onenterlistitemvalue,\n      listOrdered: opener(list, onenterlistordered),\n      listUnordered: opener(list),\n      paragraph: opener(paragraph),\n      reference: onenterreference,\n      referenceString: buffer,\n      resourceDestinationString: buffer,\n      resourceTitleString: buffer,\n      setextHeading: opener(heading),\n      strong: opener(strong),\n      thematicBreak: opener(thematicBreak)\n    },\n    exit: {\n      atxHeading: closer(),\n      atxHeadingSequence: onexitatxheadingsequence,\n      autolink: closer(),\n      autolinkEmail: onexitautolinkemail,\n      autolinkProtocol: onexitautolinkprotocol,\n      blockQuote: closer(),\n      characterEscapeValue: onexitdata,\n      characterReferenceMarkerHexadecimal: onexitcharacterreferencemarker,\n      characterReferenceMarkerNumeric: onexitcharacterreferencemarker,\n      characterReferenceValue: onexitcharacterreferencevalue,\n      characterReference: onexitcharacterreference,\n      codeFenced: closer(onexitcodefenced),\n      codeFencedFence: onexitcodefencedfence,\n      codeFencedFenceInfo: onexitcodefencedfenceinfo,\n      codeFencedFenceMeta: onexitcodefencedfencemeta,\n      codeFlowValue: onexitdata,\n      codeIndented: closer(onexitcodeindented),\n      codeText: closer(onexitcodetext),\n      codeTextData: onexitdata,\n      data: onexitdata,\n      definition: closer(),\n      definitionDestinationString: onexitdefinitiondestinationstring,\n      definitionLabelString: onexitdefinitionlabelstring,\n      definitionTitleString: onexitdefinitiontitlestring,\n      emphasis: closer(),\n      hardBreakEscape: closer(onexithardbreak),\n      hardBreakTrailing: closer(onexithardbreak),\n      htmlFlow: closer(onexithtmlflow),\n      htmlFlowData: onexitdata,\n      htmlText: closer(onexithtmltext),\n      htmlTextData: onexitdata,\n      image: closer(onexitimage),\n      label: onexitlabel,\n      labelText: onexitlabeltext,\n      lineEnding: onexitlineending,\n      link: closer(onexitlink),\n      listItem: closer(),\n      listOrdered: closer(),\n      listUnordered: closer(),\n      paragraph: closer(),\n      referenceString: onexitreferencestring,\n      resourceDestinationString: onexitresourcedestinationstring,\n      resourceTitleString: onexitresourcetitlestring,\n      resource: onexitresource,\n      setextHeading: closer(onexitsetextheading),\n      setextHeadingLineSequence: onexitsetextheadinglinesequence,\n      setextHeadingText: onexitsetextheadingtext,\n      strong: closer(),\n      thematicBreak: closer()\n    }\n  };\n  configure(config, (options || {}).mdastExtensions || []);\n\n  /** @type {CompileData} */\n  const data = {};\n  return compile;\n\n  /**\n   * Turn micromark events into an mdast tree.\n   *\n   * @param {Array<Event>} events\n   *   Events.\n   * @returns {Root}\n   *   mdast tree.\n   */\n  function compile(events) {\n    /** @type {Root} */\n    let tree = {\n      type: 'root',\n      children: []\n    };\n    /** @type {Omit<CompileContext, 'sliceSerialize'>} */\n    const context = {\n      stack: [tree],\n      tokenStack: [],\n      config,\n      enter,\n      exit,\n      buffer,\n      resume,\n      data\n    };\n    /** @type {Array<number>} */\n    const listStack = [];\n    let index = -1;\n    while (++index < events.length) {\n      // We preprocess lists to add `listItem` tokens, and to infer whether\n      // items the list itself are spread out.\n      if (events[index][1].type === \"listOrdered\" || events[index][1].type === \"listUnordered\") {\n        if (events[index][0] === 'enter') {\n          listStack.push(index);\n        } else {\n          const tail = listStack.pop();\n          index = prepareList(events, tail, index);\n        }\n      }\n    }\n    index = -1;\n    while (++index < events.length) {\n      const handler = config[events[index][0]];\n      if (own.call(handler, events[index][1].type)) {\n        handler[events[index][1].type].call(Object.assign({\n          sliceSerialize: events[index][2].sliceSerialize\n        }, context), events[index][1]);\n      }\n    }\n\n    // Handle tokens still being open.\n    if (context.tokenStack.length > 0) {\n      const tail = context.tokenStack[context.tokenStack.length - 1];\n      const handler = tail[1] || defaultOnError;\n      handler.call(context, undefined, tail[0]);\n    }\n\n    // Figure out `root` position.\n    tree.position = {\n      start: point(events.length > 0 ? events[0][1].start : {\n        line: 1,\n        column: 1,\n        offset: 0\n      }),\n      end: point(events.length > 0 ? events[events.length - 2][1].end : {\n        line: 1,\n        column: 1,\n        offset: 0\n      })\n    };\n\n    // Call transforms.\n    index = -1;\n    while (++index < config.transforms.length) {\n      tree = config.transforms[index](tree) || tree;\n    }\n    return tree;\n  }\n\n  /**\n   * @param {Array<Event>} events\n   * @param {number} start\n   * @param {number} length\n   * @returns {number}\n   */\n  function prepareList(events, start, length) {\n    let index = start - 1;\n    let containerBalance = -1;\n    let listSpread = false;\n    /** @type {Token | undefined} */\n    let listItem;\n    /** @type {number | undefined} */\n    let lineIndex;\n    /** @type {number | undefined} */\n    let firstBlankLineIndex;\n    /** @type {boolean | undefined} */\n    let atMarker;\n    while (++index <= length) {\n      const event = events[index];\n      switch (event[1].type) {\n        case \"listUnordered\":\n        case \"listOrdered\":\n        case \"blockQuote\":\n          {\n            if (event[0] === 'enter') {\n              containerBalance++;\n            } else {\n              containerBalance--;\n            }\n            atMarker = undefined;\n            break;\n          }\n        case \"lineEndingBlank\":\n          {\n            if (event[0] === 'enter') {\n              if (listItem && !atMarker && !containerBalance && !firstBlankLineIndex) {\n                firstBlankLineIndex = index;\n              }\n              atMarker = undefined;\n            }\n            break;\n          }\n        case \"linePrefix\":\n        case \"listItemValue\":\n        case \"listItemMarker\":\n        case \"listItemPrefix\":\n        case \"listItemPrefixWhitespace\":\n          {\n            // Empty.\n\n            break;\n          }\n        default:\n          {\n            atMarker = undefined;\n          }\n      }\n      if (!containerBalance && event[0] === 'enter' && event[1].type === \"listItemPrefix\" || containerBalance === -1 && event[0] === 'exit' && (event[1].type === \"listUnordered\" || event[1].type === \"listOrdered\")) {\n        if (listItem) {\n          let tailIndex = index;\n          lineIndex = undefined;\n          while (tailIndex--) {\n            const tailEvent = events[tailIndex];\n            if (tailEvent[1].type === \"lineEnding\" || tailEvent[1].type === \"lineEndingBlank\") {\n              if (tailEvent[0] === 'exit') continue;\n              if (lineIndex) {\n                events[lineIndex][1].type = \"lineEndingBlank\";\n                listSpread = true;\n              }\n              tailEvent[1].type = \"lineEnding\";\n              lineIndex = tailIndex;\n            } else if (tailEvent[1].type === \"linePrefix\" || tailEvent[1].type === \"blockQuotePrefix\" || tailEvent[1].type === \"blockQuotePrefixWhitespace\" || tailEvent[1].type === \"blockQuoteMarker\" || tailEvent[1].type === \"listItemIndent\") {\n              // Empty\n            } else {\n              break;\n            }\n          }\n          if (firstBlankLineIndex && (!lineIndex || firstBlankLineIndex < lineIndex)) {\n            listItem._spread = true;\n          }\n\n          // Fix position.\n          listItem.end = Object.assign({}, lineIndex ? events[lineIndex][1].start : event[1].end);\n          events.splice(lineIndex || index, 0, ['exit', listItem, event[2]]);\n          index++;\n          length++;\n        }\n\n        // Create a new list item.\n        if (event[1].type === \"listItemPrefix\") {\n          /** @type {Token} */\n          const item = {\n            type: 'listItem',\n            _spread: false,\n            start: Object.assign({}, event[1].start),\n            // @ts-expect-error: we’ll add `end` in a second.\n            end: undefined\n          };\n          listItem = item;\n          events.splice(index, 0, ['enter', item, event[2]]);\n          index++;\n          length++;\n          firstBlankLineIndex = undefined;\n          atMarker = true;\n        }\n      }\n    }\n    events[start][1]._spread = listSpread;\n    return length;\n  }\n\n  /**\n   * Create an opener handle.\n   *\n   * @param {(token: Token) => Nodes} create\n   *   Create a node.\n   * @param {Handle | undefined} [and]\n   *   Optional function to also run.\n   * @returns {Handle}\n   *   Handle.\n   */\n  function opener(create, and) {\n    return open;\n\n    /**\n     * @this {CompileContext}\n     * @param {Token} token\n     * @returns {undefined}\n     */\n    function open(token) {\n      enter.call(this, create(token), token);\n      if (and) and.call(this, token);\n    }\n  }\n\n  /**\n   * @type {CompileContext['buffer']}\n   */\n  function buffer() {\n    this.stack.push({\n      type: 'fragment',\n      children: []\n    });\n  }\n\n  /**\n   * @type {CompileContext['enter']}\n   */\n  function enter(node, token, errorHandler) {\n    const parent = this.stack[this.stack.length - 1];\n    /** @type {Array<Nodes>} */\n    const siblings = parent.children;\n    siblings.push(node);\n    this.stack.push(node);\n    this.tokenStack.push([token, errorHandler || undefined]);\n    node.position = {\n      start: point(token.start),\n      // @ts-expect-error: `end` will be patched later.\n      end: undefined\n    };\n  }\n\n  /**\n   * Create a closer handle.\n   *\n   * @param {Handle | undefined} [and]\n   *   Optional function to also run.\n   * @returns {Handle}\n   *   Handle.\n   */\n  function closer(and) {\n    return close;\n\n    /**\n     * @this {CompileContext}\n     * @param {Token} token\n     * @returns {undefined}\n     */\n    function close(token) {\n      if (and) and.call(this, token);\n      exit.call(this, token);\n    }\n  }\n\n  /**\n   * @type {CompileContext['exit']}\n   */\n  function exit(token, onExitError) {\n    const node = this.stack.pop();\n    const open = this.tokenStack.pop();\n    if (!open) {\n      throw new Error('Cannot close `' + token.type + '` (' + stringifyPosition({\n        start: token.start,\n        end: token.end\n      }) + '): it’s not open');\n    } else if (open[0].type !== token.type) {\n      if (onExitError) {\n        onExitError.call(this, token, open[0]);\n      } else {\n        const handler = open[1] || defaultOnError;\n        handler.call(this, token, open[0]);\n      }\n    }\n    node.position.end = point(token.end);\n  }\n\n  /**\n   * @type {CompileContext['resume']}\n   */\n  function resume() {\n    return toString(this.stack.pop());\n  }\n\n  //\n  // Handlers.\n  //\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onenterlistordered() {\n    this.data.expectingFirstListItemValue = true;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onenterlistitemvalue(token) {\n    if (this.data.expectingFirstListItemValue) {\n      const ancestor = this.stack[this.stack.length - 2];\n      ancestor.start = Number.parseInt(this.sliceSerialize(token), 10);\n      this.data.expectingFirstListItemValue = undefined;\n    }\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcodefencedfenceinfo() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.lang = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcodefencedfencemeta() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.meta = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcodefencedfence() {\n    // Exit if this is the closing fence.\n    if (this.data.flowCodeInside) return;\n    this.buffer();\n    this.data.flowCodeInside = true;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcodefenced() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.value = data.replace(/^(\\r?\\n|\\r)|(\\r?\\n|\\r)$/g, '');\n    this.data.flowCodeInside = undefined;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcodeindented() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.value = data.replace(/(\\r?\\n|\\r)$/g, '');\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitdefinitionlabelstring(token) {\n    const label = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.label = label;\n    node.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase();\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitdefinitiontitlestring() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.title = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitdefinitiondestinationstring() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.url = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitatxheadingsequence(token) {\n    const node = this.stack[this.stack.length - 1];\n    if (!node.depth) {\n      const depth = this.sliceSerialize(token).length;\n      node.depth = depth;\n    }\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitsetextheadingtext() {\n    this.data.setextHeadingSlurpLineEnding = true;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitsetextheadinglinesequence(token) {\n    const node = this.stack[this.stack.length - 1];\n    node.depth = this.sliceSerialize(token).codePointAt(0) === 61 ? 1 : 2;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitsetextheading() {\n    this.data.setextHeadingSlurpLineEnding = undefined;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onenterdata(token) {\n    const node = this.stack[this.stack.length - 1];\n    /** @type {Array<Nodes>} */\n    const siblings = node.children;\n    let tail = siblings[siblings.length - 1];\n    if (!tail || tail.type !== 'text') {\n      // Add a new text node.\n      tail = text();\n      tail.position = {\n        start: point(token.start),\n        // @ts-expect-error: we’ll add `end` later.\n        end: undefined\n      };\n      siblings.push(tail);\n    }\n    this.stack.push(tail);\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitdata(token) {\n    const tail = this.stack.pop();\n    tail.value += this.sliceSerialize(token);\n    tail.position.end = point(token.end);\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitlineending(token) {\n    const context = this.stack[this.stack.length - 1];\n    // If we’re at a hard break, include the line ending in there.\n    if (this.data.atHardBreak) {\n      const tail = context.children[context.children.length - 1];\n      tail.position.end = point(token.end);\n      this.data.atHardBreak = undefined;\n      return;\n    }\n    if (!this.data.setextHeadingSlurpLineEnding && config.canContainEols.includes(context.type)) {\n      onenterdata.call(this, token);\n      onexitdata.call(this, token);\n    }\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexithardbreak() {\n    this.data.atHardBreak = true;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexithtmlflow() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.value = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexithtmltext() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.value = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitcodetext() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.value = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitlink() {\n    const node = this.stack[this.stack.length - 1];\n    // Note: there are also `identifier` and `label` fields on this link node!\n    // These are used / cleaned here.\n\n    // To do: clean.\n    if (this.data.inReference) {\n      /** @type {ReferenceType} */\n      const referenceType = this.data.referenceType || 'shortcut';\n      node.type += 'Reference';\n      // @ts-expect-error: mutate.\n      node.referenceType = referenceType;\n      // @ts-expect-error: mutate.\n      delete node.url;\n      delete node.title;\n    } else {\n      // @ts-expect-error: mutate.\n      delete node.identifier;\n      // @ts-expect-error: mutate.\n      delete node.label;\n    }\n    this.data.referenceType = undefined;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitimage() {\n    const node = this.stack[this.stack.length - 1];\n    // Note: there are also `identifier` and `label` fields on this link node!\n    // These are used / cleaned here.\n\n    // To do: clean.\n    if (this.data.inReference) {\n      /** @type {ReferenceType} */\n      const referenceType = this.data.referenceType || 'shortcut';\n      node.type += 'Reference';\n      // @ts-expect-error: mutate.\n      node.referenceType = referenceType;\n      // @ts-expect-error: mutate.\n      delete node.url;\n      delete node.title;\n    } else {\n      // @ts-expect-error: mutate.\n      delete node.identifier;\n      // @ts-expect-error: mutate.\n      delete node.label;\n    }\n    this.data.referenceType = undefined;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitlabeltext(token) {\n    const string = this.sliceSerialize(token);\n    const ancestor = this.stack[this.stack.length - 2];\n    // @ts-expect-error: stash this on the node, as it might become a reference\n    // later.\n    ancestor.label = decodeString(string);\n    // @ts-expect-error: same as above.\n    ancestor.identifier = normalizeIdentifier(string).toLowerCase();\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitlabel() {\n    const fragment = this.stack[this.stack.length - 1];\n    const value = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    // Assume a reference.\n    this.data.inReference = true;\n    if (node.type === 'link') {\n      /** @type {Array<PhrasingContent>} */\n      const children = fragment.children;\n      node.children = children;\n    } else {\n      node.alt = value;\n    }\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitresourcedestinationstring() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.url = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitresourcetitlestring() {\n    const data = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    node.title = data;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitresource() {\n    this.data.inReference = undefined;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onenterreference() {\n    this.data.referenceType = 'collapsed';\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitreferencestring(token) {\n    const label = this.resume();\n    const node = this.stack[this.stack.length - 1];\n    // @ts-expect-error: stash this on the node, as it might become a reference\n    // later.\n    node.label = label;\n    // @ts-expect-error: same as above.\n    node.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase();\n    this.data.referenceType = 'full';\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n\n  function onexitcharacterreferencemarker(token) {\n    this.data.characterReferenceType = token.type;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcharacterreferencevalue(token) {\n    const data = this.sliceSerialize(token);\n    const type = this.data.characterReferenceType;\n    /** @type {string} */\n    let value;\n    if (type) {\n      value = decodeNumericCharacterReference(data, type === \"characterReferenceMarkerNumeric\" ? 10 : 16);\n      this.data.characterReferenceType = undefined;\n    } else {\n      const result = decodeNamedCharacterReference(data);\n      value = result;\n    }\n    const tail = this.stack[this.stack.length - 1];\n    tail.value += value;\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitcharacterreference(token) {\n    const tail = this.stack.pop();\n    tail.position.end = point(token.end);\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitautolinkprotocol(token) {\n    onexitdata.call(this, token);\n    const node = this.stack[this.stack.length - 1];\n    node.url = this.sliceSerialize(token);\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {Handle}\n   */\n  function onexitautolinkemail(token) {\n    onexitdata.call(this, token);\n    const node = this.stack[this.stack.length - 1];\n    node.url = 'mailto:' + this.sliceSerialize(token);\n  }\n\n  //\n  // Creaters.\n  //\n\n  /** @returns {Blockquote} */\n  function blockQuote() {\n    return {\n      type: 'blockquote',\n      children: []\n    };\n  }\n\n  /** @returns {Code} */\n  function codeFlow() {\n    return {\n      type: 'code',\n      lang: null,\n      meta: null,\n      value: ''\n    };\n  }\n\n  /** @returns {InlineCode} */\n  function codeText() {\n    return {\n      type: 'inlineCode',\n      value: ''\n    };\n  }\n\n  /** @returns {Definition} */\n  function definition() {\n    return {\n      type: 'definition',\n      identifier: '',\n      label: null,\n      title: null,\n      url: ''\n    };\n  }\n\n  /** @returns {Emphasis} */\n  function emphasis() {\n    return {\n      type: 'emphasis',\n      children: []\n    };\n  }\n\n  /** @returns {Heading} */\n  function heading() {\n    return {\n      type: 'heading',\n      // @ts-expect-error `depth` will be set later.\n      depth: 0,\n      children: []\n    };\n  }\n\n  /** @returns {Break} */\n  function hardBreak() {\n    return {\n      type: 'break'\n    };\n  }\n\n  /** @returns {Html} */\n  function html() {\n    return {\n      type: 'html',\n      value: ''\n    };\n  }\n\n  /** @returns {Image} */\n  function image() {\n    return {\n      type: 'image',\n      title: null,\n      url: '',\n      alt: null\n    };\n  }\n\n  /** @returns {Link} */\n  function link() {\n    return {\n      type: 'link',\n      title: null,\n      url: '',\n      children: []\n    };\n  }\n\n  /**\n   * @param {Token} token\n   * @returns {List}\n   */\n  function list(token) {\n    return {\n      type: 'list',\n      ordered: token.type === 'listOrdered',\n      start: null,\n      spread: token._spread,\n      children: []\n    };\n  }\n\n  /**\n   * @param {Token} token\n   * @returns {ListItem}\n   */\n  function listItem(token) {\n    return {\n      type: 'listItem',\n      spread: token._spread,\n      checked: null,\n      children: []\n    };\n  }\n\n  /** @returns {Paragraph} */\n  function paragraph() {\n    return {\n      type: 'paragraph',\n      children: []\n    };\n  }\n\n  /** @returns {Strong} */\n  function strong() {\n    return {\n      type: 'strong',\n      children: []\n    };\n  }\n\n  /** @returns {Text} */\n  function text() {\n    return {\n      type: 'text',\n      value: ''\n    };\n  }\n\n  /** @returns {ThematicBreak} */\n  function thematicBreak() {\n    return {\n      type: 'thematicBreak'\n    };\n  }\n}\n\n/**\n * Copy a point-like value.\n *\n * @param {Point} d\n *   Point-like value.\n * @returns {Point}\n *   unist point.\n */\nfunction point(d) {\n  return {\n    line: d.line,\n    column: d.column,\n    offset: d.offset\n  };\n}\n\n/**\n * @param {Config} combined\n * @param {Array<Array<Extension> | Extension>} extensions\n * @returns {undefined}\n */\nfunction configure(combined, extensions) {\n  let index = -1;\n  while (++index < extensions.length) {\n    const value = extensions[index];\n    if (Array.isArray(value)) {\n      configure(combined, value);\n    } else {\n      extension(combined, value);\n    }\n  }\n}\n\n/**\n * @param {Config} combined\n * @param {Extension} extension\n * @returns {undefined}\n */\nfunction extension(combined, extension) {\n  /** @type {keyof Extension} */\n  let key;\n  for (key in extension) {\n    if (own.call(extension, key)) {\n      switch (key) {\n        case 'canContainEols':\n          {\n            const right = extension[key];\n            if (right) {\n              combined[key].push(...right);\n            }\n            break;\n          }\n        case 'transforms':\n          {\n            const right = extension[key];\n            if (right) {\n              combined[key].push(...right);\n            }\n            break;\n          }\n        case 'enter':\n        case 'exit':\n          {\n            const right = extension[key];\n            if (right) {\n              Object.assign(combined[key], right);\n            }\n            break;\n          }\n        // No default\n      }\n    }\n  }\n}\n\n/** @type {OnEnterError} */\nfunction defaultOnError(left, right) {\n  if (left) {\n    throw new Error('Cannot close `' + left.type + '` (' + stringifyPosition({\n      start: left.start,\n      end: left.end\n    }) + '): a different token (`' + right.type + '`, ' + stringifyPosition({\n      start: right.start,\n      end: right.end\n    }) + ') is open');\n  } else {\n    throw new Error('Cannot close document, a token (`' + right.type + '`, ' + stringifyPosition({\n      start: right.start,\n      end: right.end\n    }) + ') is still open');\n  }\n}","/**\n * @typedef {import('mdast').Root} Root\n * @typedef {import('mdast-util-from-markdown').Options} FromMarkdownOptions\n * @typedef {import('unified').Parser<Root>} Parser\n * @typedef {import('unified').Processor<Root>} Processor\n */\n\n/**\n * @typedef {Omit<FromMarkdownOptions, 'extensions' | 'mdastExtensions'>} Options\n */\n\nimport {fromMarkdown} from 'mdast-util-from-markdown'\n\n/**\n * Aadd support for parsing from markdown.\n *\n * @param {Readonly<Options> | null | undefined} [options]\n *   Configuration (optional).\n * @returns {undefined}\n *   Nothing.\n */\nexport default function remarkParse(options) {\n  /** @type {Processor} */\n  // @ts-expect-error: TS in JSDoc generates wrong types if `this` is typed regularly.\n  const self = this\n\n  self.parser = parser\n\n  /**\n   * @type {Parser}\n   */\n  function parser(doc) {\n    return fromMarkdown(doc, {\n      ...self.data('settings'),\n      ...options,\n      // Note: these options are not in the readme.\n      // The goal is for them to be set by plugins on `data` instead of being\n      // passed by users.\n      extensions: self.data('micromarkExtensions') || [],\n      mdastExtensions: self.data('fromMarkdownExtensions') || []\n    })\n  }\n}\n","/**\n * Count how often a character (or substring) is used in a string.\n *\n * @param {string} value\n *   Value to search in.\n * @param {string} character\n *   Character (or substring) to look for.\n * @return {number}\n *   Number of times `character` occurred in `value`.\n */\nexport function ccount(value, character) {\n  const source = String(value)\n\n  if (typeof character !== 'string') {\n    throw new TypeError('Expected character')\n  }\n\n  let count = 0\n  let index = source.indexOf(character)\n\n  while (index !== -1) {\n    count++\n    index = source.indexOf(character, index + character.length)\n  }\n\n  return count\n}\n","export default function escapeStringRegexp(string) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\t// Escape characters with special meaning either inside or outside character sets.\n\t// Use a simple backslash escape when it’s always valid, and a `\\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.\n\treturn string\n\t\t.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&')\n\t\t.replace(/-/g, '\\\\x2d');\n}\n","/**\n * @import {Node, Parent} from 'unist'\n */\n\n/**\n * @template Fn\n * @template Fallback\n * @typedef {Fn extends (value: any) => value is infer Thing ? Thing : Fallback} Predicate\n */\n\n/**\n * @callback Check\n *   Check that an arbitrary value is a node.\n * @param {unknown} this\n *   The given context.\n * @param {unknown} [node]\n *   Anything (typically a node).\n * @param {number | null | undefined} [index]\n *   The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n *   The node’s parent.\n * @returns {boolean}\n *   Whether this is a node and passes a test.\n *\n * @typedef {Record<string, unknown> | Node} Props\n *   Object to check for equivalence.\n *\n *   Note: `Node` is included as it is common but is not indexable.\n *\n * @typedef {Array<Props | TestFunction | string> | ReadonlyArray<Props | TestFunction | string> | Props | TestFunction | string | null | undefined} Test\n *   Check for an arbitrary node.\n *\n * @callback TestFunction\n *   Check if a node passes a test.\n * @param {unknown} this\n *   The given context.\n * @param {Node} node\n *   A node.\n * @param {number | undefined} [index]\n *   The node’s position in its parent.\n * @param {Parent | undefined} [parent]\n *   The node’s parent.\n * @returns {boolean | undefined | void}\n *   Whether this node passes the test.\n *\n *   Note: `void` is included until TS sees no return as `undefined`.\n */\n\n/**\n * Check if `node` is a `Node` and whether it passes the given test.\n *\n * @param {unknown} node\n *   Thing to check, typically `Node`.\n * @param {Test} test\n *   A check for a specific node.\n * @param {number | null | undefined} index\n *   The node’s position in its parent.\n * @param {Parent | null | undefined} parent\n *   The node’s parent.\n * @param {unknown} context\n *   Context object (`this`) to pass to `test` functions.\n * @returns {boolean}\n *   Whether `node` is a node and passes a test.\n */\nexport const is =\n  // Note: overloads in JSDoc can’t yet use different `@template`s.\n  /**\n   * @type {(\n   *   (<Condition extends ReadonlyArray<string>>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition[number]}) &\n   *   (<Condition extends Array<string>>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition[number]}) &\n   *   (<Condition extends string>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &\n   *   (<Condition extends Props>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &\n   *   (<Condition extends TestFunction>(node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate<Condition, Node>) &\n   *   ((node?: null | undefined) => false) &\n   *   ((node: unknown, test?: null | undefined, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &\n   *   ((node: unknown, test?: Test, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => boolean)\n   * )}\n   */\n  (\n    /**\n     * @param {unknown} [node]\n     * @param {Test} [test]\n     * @param {number | null | undefined} [index]\n     * @param {Parent | null | undefined} [parent]\n     * @param {unknown} [context]\n     * @returns {boolean}\n     */\n    // eslint-disable-next-line max-params\n    function (node, test, index, parent, context) {\n      const check = convert(test)\n\n      if (\n        index !== undefined &&\n        index !== null &&\n        (typeof index !== 'number' ||\n          index < 0 ||\n          index === Number.POSITIVE_INFINITY)\n      ) {\n        throw new Error('Expected positive finite index')\n      }\n\n      if (\n        parent !== undefined &&\n        parent !== null &&\n        (!is(parent) || !parent.children)\n      ) {\n        throw new Error('Expected parent node')\n      }\n\n      if (\n        (parent === undefined || parent === null) !==\n        (index === undefined || index === null)\n      ) {\n        throw new Error('Expected both parent and index')\n      }\n\n      return looksLikeANode(node)\n        ? check.call(context, node, index, parent)\n        : false\n    }\n  )\n\n/**\n * Generate an assertion from a test.\n *\n * Useful if you’re going to test many nodes, for example when creating a\n * utility where something else passes a compatible test.\n *\n * The created function is a bit faster because it expects valid input only:\n * a `node`, `index`, and `parent`.\n *\n * @param {Test} test\n *   *   when nullish, checks if `node` is a `Node`.\n *   *   when `string`, works like passing `(node) => node.type === test`.\n *   *   when `function` checks if function passed the node is true.\n *   *   when `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n *   *   when `array`, checks if any one of the subtests pass.\n * @returns {Check}\n *   An assertion.\n */\nexport const convert =\n  // Note: overloads in JSDoc can’t yet use different `@template`s.\n  /**\n   * @type {(\n   *   (<Condition extends string>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &\n   *   (<Condition extends Props>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &\n   *   (<Condition extends TestFunction>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate<Condition, Node>) &\n   *   ((test?: null | undefined) => (node?: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &\n   *   ((test?: Test) => Check)\n   * )}\n   */\n  (\n    /**\n     * @param {Test} [test]\n     * @returns {Check}\n     */\n    function (test) {\n      if (test === null || test === undefined) {\n        return ok\n      }\n\n      if (typeof test === 'function') {\n        return castFactory(test)\n      }\n\n      if (typeof test === 'object') {\n        return Array.isArray(test)\n          ? anyFactory(test)\n          : // Cast because `ReadonlyArray` goes into the above but `isArray`\n            // narrows to `Array`.\n            propertiesFactory(/** @type {Props} */ (test))\n      }\n\n      if (typeof test === 'string') {\n        return typeFactory(test)\n      }\n\n      throw new Error('Expected function, string, or object as test')\n    }\n  )\n\n/**\n * @param {Array<Props | TestFunction | string>} tests\n * @returns {Check}\n */\nfunction anyFactory(tests) {\n  /** @type {Array<Check>} */\n  const checks = []\n  let index = -1\n\n  while (++index < tests.length) {\n    checks[index] = convert(tests[index])\n  }\n\n  return castFactory(any)\n\n  /**\n   * @this {unknown}\n   * @type {TestFunction}\n   */\n  function any(...parameters) {\n    let index = -1\n\n    while (++index < checks.length) {\n      if (checks[index].apply(this, parameters)) return true\n    }\n\n    return false\n  }\n}\n\n/**\n * Turn an object into a test for a node with a certain fields.\n *\n * @param {Props} check\n * @returns {Check}\n */\nfunction propertiesFactory(check) {\n  const checkAsRecord = /** @type {Record<string, unknown>} */ (check)\n\n  return castFactory(all)\n\n  /**\n   * @param {Node} node\n   * @returns {boolean}\n   */\n  function all(node) {\n    const nodeAsRecord = /** @type {Record<string, unknown>} */ (\n      /** @type {unknown} */ (node)\n    )\n\n    /** @type {string} */\n    let key\n\n    for (key in check) {\n      if (nodeAsRecord[key] !== checkAsRecord[key]) return false\n    }\n\n    return true\n  }\n}\n\n/**\n * Turn a string into a test for a node with a certain type.\n *\n * @param {string} check\n * @returns {Check}\n */\nfunction typeFactory(check) {\n  return castFactory(type)\n\n  /**\n   * @param {Node} node\n   */\n  function type(node) {\n    return node && node.type === check\n  }\n}\n\n/**\n * Turn a custom test into a test for a node that passes that test.\n *\n * @param {TestFunction} testFunction\n * @returns {Check}\n */\nfunction castFactory(testFunction) {\n  return check\n\n  /**\n   * @this {unknown}\n   * @type {Check}\n   */\n  function check(value, index, parent) {\n    return Boolean(\n      looksLikeANode(value) &&\n        testFunction.call(\n          this,\n          value,\n          typeof index === 'number' ? index : undefined,\n          parent || undefined\n        )\n    )\n  }\n}\n\nfunction ok() {\n  return true\n}\n\n/**\n * @param {unknown} value\n * @returns {value is Node}\n */\nfunction looksLikeANode(value) {\n  return value !== null && typeof value === 'object' && 'type' in value\n}\n","/**\n * @import {Node as UnistNode, Parent as UnistParent} from 'unist'\n */\n\n/**\n * @typedef {Exclude<import('unist-util-is').Test, undefined> | undefined} Test\n *   Test from `unist-util-is`.\n *\n *   Note: we have remove and add `undefined`, because otherwise when generating\n *   automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n *   which doesn’t work when publishing on npm.\n */\n\n/**\n * @typedef {(\n *   Fn extends (value: any) => value is infer Thing\n *   ? Thing\n *   : Fallback\n * )} Predicate\n *   Get the value of a type guard `Fn`.\n * @template Fn\n *   Value; typically function that is a type guard (such as `(x): x is Y`).\n * @template Fallback\n *   Value to yield if `Fn` is not a type guard.\n */\n\n/**\n * @typedef {(\n *   Check extends null | undefined // No test.\n *   ? Value\n *   : Value extends {type: Check} // String (type) test.\n *   ? Value\n *   : Value extends Check // Partial test.\n *   ? Value\n *   : Check extends Function // Function test.\n *   ? Predicate<Check, Value> extends Value\n *     ? Predicate<Check, Value>\n *     : never\n *   : never // Some other test?\n * )} MatchesOne\n *   Check whether a node matches a primitive check in the type system.\n * @template Value\n *   Value; typically unist `Node`.\n * @template Check\n *   Value; typically `unist-util-is`-compatible test, but not arrays.\n */\n\n/**\n * @typedef {(\n *   Check extends ReadonlyArray<infer T>\n *   ? MatchesOne<Value, T>\n *   : Check extends Array<infer T>\n *   ? MatchesOne<Value, T>\n *   : MatchesOne<Value, Check>\n * )} Matches\n *   Check whether a node matches a check in the type system.\n * @template Value\n *   Value; typically unist `Node`.\n * @template Check\n *   Value; typically `unist-util-is`-compatible test.\n */\n\n/**\n * @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10} Uint\n *   Number; capped reasonably.\n */\n\n/**\n * @typedef {I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10} Increment\n *   Increment a number in the type system.\n * @template {Uint} [I=0]\n *   Index.\n */\n\n/**\n * @typedef {(\n *   Node extends UnistParent\n *   ? Node extends {children: Array<infer Children>}\n *     ? Child extends Children ? Node : never\n *     : never\n *   : never\n * )} InternalParent\n *   Collect nodes that can be parents of `Child`.\n * @template {UnistNode} Node\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n */\n\n/**\n * @typedef {InternalParent<InclusiveDescendant<Tree>, Child>} Parent\n *   Collect nodes in `Tree` that can be parents of `Child`.\n * @template {UnistNode} Tree\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n */\n\n/**\n * @typedef {(\n *   Depth extends Max\n *   ? never\n *   :\n *     | InternalParent<Node, Child>\n *     | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>\n * )} InternalAncestor\n *   Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Node\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n * @template {Uint} [Max=10]\n *   Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n *   Current depth.\n */\n\n/**\n * @typedef {InternalAncestor<InclusiveDescendant<Tree>, Child>} Ancestor\n *   Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Tree\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n */\n\n/**\n * @typedef {(\n *   Tree extends UnistParent\n *     ? Depth extends Max\n *       ? Tree\n *       : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>\n *     : Tree\n * )} InclusiveDescendant\n *   Collect all (inclusive) descendants of `Tree`.\n *\n *   > 👉 **Note**: for performance reasons, this seems to be the fastest way to\n *   > recurse without actually running into an infinite loop, which the\n *   > previous version did.\n *   >\n *   > Practically, a max of `2` is typically enough assuming a `Root` is\n *   > passed, but it doesn’t improve performance.\n *   > It gets higher with `List > ListItem > Table > TableRow > TableCell`.\n *   > Using up to `10` doesn’t hurt or help either.\n * @template {UnistNode} Tree\n *   Tree type.\n * @template {Uint} [Max=10]\n *   Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n *   Current depth.\n */\n\n/**\n * @typedef {'skip' | boolean} Action\n *   Union of the action types.\n *\n * @typedef {number} Index\n *   Move to the sibling at `index` next (after node itself is completely\n *   traversed).\n *\n *   Useful if mutating the tree, such as removing the node the visitor is\n *   currently on, or any of its previous siblings.\n *   Results less than 0 or greater than or equal to `children.length` stop\n *   traversing the parent.\n *\n * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple\n *   List with one or two values, the first an action, the second an index.\n *\n * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult\n *   Any value that can be returned from a visitor.\n */\n\n/**\n * @callback Visitor\n *   Handle a node (matching `test`, if given).\n *\n *   Visitors are free to transform `node`.\n *   They can also transform the parent of node (the last of `ancestors`).\n *\n *   Replacing `node` itself, if `SKIP` is not returned, still causes its\n *   descendants to be walked (which is a bug).\n *\n *   When adding or removing previous siblings of `node` (or next siblings, in\n *   case of reverse), the `Visitor` should return a new `Index` to specify the\n *   sibling to traverse after `node` is traversed.\n *   Adding or removing next siblings of `node` (or previous siblings, in case\n *   of reverse) is handled as expected without needing to return a new `Index`.\n *\n *   Removing the children property of an ancestor still results in them being\n *   traversed.\n * @param {Visited} node\n *   Found node.\n * @param {Array<VisitedParents>} ancestors\n *   Ancestors of `node`.\n * @returns {VisitorResult}\n *   What to do next.\n *\n *   An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n *   An `Action` is treated as a tuple of `[Action]`.\n *\n *   Passing a tuple back only makes sense if the `Action` is `SKIP`.\n *   When the `Action` is `EXIT`, that action can be returned.\n *   When the `Action` is `CONTINUE`, `Index` can be returned.\n * @template {UnistNode} [Visited=UnistNode]\n *   Visited node type.\n * @template {UnistParent} [VisitedParents=UnistParent]\n *   Ancestor type.\n */\n\n/**\n * @typedef {Visitor<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>} BuildVisitor\n *   Build a typed `Visitor` function from a tree and a test.\n *\n *   It will infer which values are passed as `node` and which as `parents`.\n * @template {UnistNode} [Tree=UnistNode]\n *   Tree type.\n * @template {Test} [Check=Test]\n *   Test type.\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from 'unist-util-visit-parents/do-not-use-color'\n\n/** @type {Readonly<ActionTuple>} */\nconst empty = []\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip'\n\n/**\n * Visit nodes, with ancestral information.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @overload\n * @param {Tree} tree\n * @param {Check} check\n * @param {BuildVisitor<Tree, Check>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @overload\n * @param {Tree} tree\n * @param {BuildVisitor<Tree>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @param {UnistNode} tree\n *   Tree to traverse.\n * @param {Visitor | Test} test\n *   `unist-util-is`-compatible test\n * @param {Visitor | boolean | null | undefined} [visitor]\n *   Handle each node.\n * @param {boolean | null | undefined} [reverse]\n *   Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns {undefined}\n *   Nothing.\n *\n * @template {UnistNode} Tree\n *   Node type.\n * @template {Test} Check\n *   `unist-util-is`-compatible test.\n */\nexport function visitParents(tree, test, visitor, reverse) {\n  /** @type {Test} */\n  let check\n\n  if (typeof test === 'function' && typeof visitor !== 'function') {\n    reverse = visitor\n    // @ts-expect-error no visitor given, so `visitor` is test.\n    visitor = test\n  } else {\n    // @ts-expect-error visitor given, so `test` isn’t a visitor.\n    check = test\n  }\n\n  const is = convert(check)\n  const step = reverse ? -1 : 1\n\n  factory(tree, undefined, [])()\n\n  /**\n   * @param {UnistNode} node\n   * @param {number | undefined} index\n   * @param {Array<UnistParent>} parents\n   */\n  function factory(node, index, parents) {\n    const value = /** @type {Record<string, unknown>} */ (\n      node && typeof node === 'object' ? node : {}\n    )\n\n    if (typeof value.type === 'string') {\n      const name =\n        // `hast`\n        typeof value.tagName === 'string'\n          ? value.tagName\n          : // `xast`\n            typeof value.name === 'string'\n            ? value.name\n            : undefined\n\n      Object.defineProperty(visit, 'name', {\n        value:\n          'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'\n      })\n    }\n\n    return visit\n\n    function visit() {\n      /** @type {Readonly<ActionTuple>} */\n      let result = empty\n      /** @type {Readonly<ActionTuple>} */\n      let subresult\n      /** @type {number} */\n      let offset\n      /** @type {Array<UnistParent>} */\n      let grandparents\n\n      if (!test || is(node, index, parents[parents.length - 1] || undefined)) {\n        // @ts-expect-error: `visitor` is now a visitor.\n        result = toResult(visitor(node, parents))\n\n        if (result[0] === EXIT) {\n          return result\n        }\n      }\n\n      if ('children' in node && node.children) {\n        const nodeAsParent = /** @type {UnistParent} */ (node)\n\n        if (nodeAsParent.children && result[0] !== SKIP) {\n          offset = (reverse ? nodeAsParent.children.length : -1) + step\n          grandparents = parents.concat(nodeAsParent)\n\n          while (offset > -1 && offset < nodeAsParent.children.length) {\n            const child = nodeAsParent.children[offset]\n\n            subresult = factory(child, offset, grandparents)()\n\n            if (subresult[0] === EXIT) {\n              return subresult\n            }\n\n            offset =\n              typeof subresult[1] === 'number' ? subresult[1] : offset + step\n          }\n        }\n      }\n\n      return result\n    }\n  }\n}\n\n/**\n * Turn a return value into a clean result.\n *\n * @param {VisitorResult} value\n *   Valid return values from visitors.\n * @returns {Readonly<ActionTuple>}\n *   Clean result.\n */\nfunction toResult(value) {\n  if (Array.isArray(value)) {\n    return value\n  }\n\n  if (typeof value === 'number') {\n    return [CONTINUE, value]\n  }\n\n  return value === null || value === undefined ? empty : [value]\n}\n","/**\n * @import {Nodes, Parents, PhrasingContent, Root, Text} from 'mdast'\n * @import {BuildVisitor, Test, VisitorResult} from 'unist-util-visit-parents'\n */\n\n/**\n * @typedef RegExpMatchObject\n *   Info on the match.\n * @property {number} index\n *   The index of the search at which the result was found.\n * @property {string} input\n *   A copy of the search string in the text node.\n * @property {[...Array<Parents>, Text]} stack\n *   All ancestors of the text node, where the last node is the text itself.\n *\n * @typedef {RegExp | string} Find\n *   Pattern to find.\n *\n *   Strings are escaped and then turned into global expressions.\n *\n * @typedef {Array<FindAndReplaceTuple>} FindAndReplaceList\n *   Several find and replaces, in array form.\n *\n * @typedef {[Find, Replace?]} FindAndReplaceTuple\n *   Find and replace in tuple form.\n *\n * @typedef {ReplaceFunction | string | null | undefined} Replace\n *   Thing to replace with.\n *\n * @callback ReplaceFunction\n *   Callback called when a search matches.\n * @param {...any} parameters\n *   The parameters are the result of corresponding search expression:\n *\n *   * `value` (`string`) — whole match\n *   * `...capture` (`Array<string>`) — matches from regex capture groups\n *   * `match` (`RegExpMatchObject`) — info on the match\n * @returns {Array<PhrasingContent> | PhrasingContent | string | false | null | undefined}\n *   Thing to replace with.\n *\n *   * when `null`, `undefined`, `''`, remove the match\n *   * …or when `false`, do not replace at all\n *   * …or when `string`, replace with a text node of that value\n *   * …or when `Node` or `Array<Node>`, replace with those nodes\n *\n * @typedef {[RegExp, ReplaceFunction]} Pair\n *   Normalized find and replace.\n *\n * @typedef {Array<Pair>} Pairs\n *   All find and replaced.\n *\n * @typedef Options\n *   Configuration.\n * @property {Test | null | undefined} [ignore]\n *   Test for which nodes to ignore (optional).\n */\n\nimport escape from 'escape-string-regexp'\nimport {visitParents} from 'unist-util-visit-parents'\nimport {convert} from 'unist-util-is'\n\n/**\n * Find patterns in a tree and replace them.\n *\n * The algorithm searches the tree in *preorder* for complete values in `Text`\n * nodes.\n * Partial matches are not supported.\n *\n * @param {Nodes} tree\n *   Tree to change.\n * @param {FindAndReplaceList | FindAndReplaceTuple} list\n *   Patterns to find.\n * @param {Options | null | undefined} [options]\n *   Configuration (when `find` is not `Find`).\n * @returns {undefined}\n *   Nothing.\n */\nexport function findAndReplace(tree, list, options) {\n  const settings = options || {}\n  const ignored = convert(settings.ignore || [])\n  const pairs = toPairs(list)\n  let pairIndex = -1\n\n  while (++pairIndex < pairs.length) {\n    visitParents(tree, 'text', visitor)\n  }\n\n  /** @type {BuildVisitor<Root, 'text'>} */\n  function visitor(node, parents) {\n    let index = -1\n    /** @type {Parents | undefined} */\n    let grandparent\n\n    while (++index < parents.length) {\n      const parent = parents[index]\n      /** @type {Array<Nodes> | undefined} */\n      const siblings = grandparent ? grandparent.children : undefined\n\n      if (\n        ignored(\n          parent,\n          siblings ? siblings.indexOf(parent) : undefined,\n          grandparent\n        )\n      ) {\n        return\n      }\n\n      grandparent = parent\n    }\n\n    if (grandparent) {\n      return handler(node, parents)\n    }\n  }\n\n  /**\n   * Handle a text node which is not in an ignored parent.\n   *\n   * @param {Text} node\n   *   Text node.\n   * @param {Array<Parents>} parents\n   *   Parents.\n   * @returns {VisitorResult}\n   *   Result.\n   */\n  function handler(node, parents) {\n    const parent = parents[parents.length - 1]\n    const find = pairs[pairIndex][0]\n    const replace = pairs[pairIndex][1]\n    let start = 0\n    /** @type {Array<Nodes>} */\n    const siblings = parent.children\n    const index = siblings.indexOf(node)\n    let change = false\n    /** @type {Array<PhrasingContent>} */\n    let nodes = []\n\n    find.lastIndex = 0\n\n    let match = find.exec(node.value)\n\n    while (match) {\n      const position = match.index\n      /** @type {RegExpMatchObject} */\n      const matchObject = {\n        index: match.index,\n        input: match.input,\n        stack: [...parents, node]\n      }\n      let value = replace(...match, matchObject)\n\n      if (typeof value === 'string') {\n        value = value.length > 0 ? {type: 'text', value} : undefined\n      }\n\n      // It wasn’t a match after all.\n      if (value === false) {\n        // False acts as if there was no match.\n        // So we need to reset `lastIndex`, which currently being at the end of\n        // the current match, to the beginning.\n        find.lastIndex = position + 1\n      } else {\n        if (start !== position) {\n          nodes.push({\n            type: 'text',\n            value: node.value.slice(start, position)\n          })\n        }\n\n        if (Array.isArray(value)) {\n          nodes.push(...value)\n        } else if (value) {\n          nodes.push(value)\n        }\n\n        start = position + match[0].length\n        change = true\n      }\n\n      if (!find.global) {\n        break\n      }\n\n      match = find.exec(node.value)\n    }\n\n    if (change) {\n      if (start < node.value.length) {\n        nodes.push({type: 'text', value: node.value.slice(start)})\n      }\n\n      parent.children.splice(index, 1, ...nodes)\n    } else {\n      nodes = [node]\n    }\n\n    return index + nodes.length\n  }\n}\n\n/**\n * Turn a tuple or a list of tuples into pairs.\n *\n * @param {FindAndReplaceList | FindAndReplaceTuple} tupleOrList\n *   Schema.\n * @returns {Pairs}\n *   Clean pairs.\n */\nfunction toPairs(tupleOrList) {\n  /** @type {Pairs} */\n  const result = []\n\n  if (!Array.isArray(tupleOrList)) {\n    throw new TypeError('Expected find and replace tuple or list of tuples')\n  }\n\n  /** @type {FindAndReplaceList} */\n  // @ts-expect-error: correct.\n  const list =\n    !tupleOrList[0] || Array.isArray(tupleOrList[0])\n      ? tupleOrList\n      : [tupleOrList]\n\n  let index = -1\n\n  while (++index < list.length) {\n    const tuple = list[index]\n    result.push([toExpression(tuple[0]), toFunction(tuple[1])])\n  }\n\n  return result\n}\n\n/**\n * Turn a find into an expression.\n *\n * @param {Find} find\n *   Find.\n * @returns {RegExp}\n *   Expression.\n */\nfunction toExpression(find) {\n  return typeof find === 'string' ? new RegExp(escape(find), 'g') : find\n}\n\n/**\n * Turn a replace into a function.\n *\n * @param {Replace} replace\n *   Replace.\n * @returns {ReplaceFunction}\n *   Function.\n */\nfunction toFunction(replace) {\n  return typeof replace === 'function'\n    ? replace\n    : function () {\n        return replace\n      }\n}\n","/**\n * @import {RegExpMatchObject, ReplaceFunction} from 'mdast-util-find-and-replace'\n * @import {CompileContext, Extension as FromMarkdownExtension, Handle as FromMarkdownHandle, Transform as FromMarkdownTransform} from 'mdast-util-from-markdown'\n * @import {ConstructName, Options as ToMarkdownExtension} from 'mdast-util-to-markdown'\n * @import {Link, PhrasingContent} from 'mdast'\n */\n\nimport {ccount} from 'ccount'\nimport {ok as assert} from 'devlop'\nimport {unicodePunctuation, unicodeWhitespace} from 'micromark-util-character'\nimport {findAndReplace} from 'mdast-util-find-and-replace'\n\n/** @type {ConstructName} */\nconst inConstruct = 'phrasing'\n/** @type {Array<ConstructName>} */\nconst notInConstruct = ['autolink', 'link', 'image', 'label']\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM autolink\n * literals in markdown.\n *\n * @returns {FromMarkdownExtension}\n *   Extension for `mdast-util-to-markdown` to enable GFM autolink literals.\n */\nexport function gfmAutolinkLiteralFromMarkdown() {\n  return {\n    transforms: [transformGfmAutolinkLiterals],\n    enter: {\n      literalAutolink: enterLiteralAutolink,\n      literalAutolinkEmail: enterLiteralAutolinkValue,\n      literalAutolinkHttp: enterLiteralAutolinkValue,\n      literalAutolinkWww: enterLiteralAutolinkValue\n    },\n    exit: {\n      literalAutolink: exitLiteralAutolink,\n      literalAutolinkEmail: exitLiteralAutolinkEmail,\n      literalAutolinkHttp: exitLiteralAutolinkHttp,\n      literalAutolinkWww: exitLiteralAutolinkWww\n    }\n  }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM autolink\n * literals in markdown.\n *\n * @returns {ToMarkdownExtension}\n *   Extension for `mdast-util-to-markdown` to enable GFM autolink literals.\n */\nexport function gfmAutolinkLiteralToMarkdown() {\n  return {\n    unsafe: [\n      {\n        character: '@',\n        before: '[+\\\\-.\\\\w]',\n        after: '[\\\\-.\\\\w]',\n        inConstruct,\n        notInConstruct\n      },\n      {\n        character: '.',\n        before: '[Ww]',\n        after: '[\\\\-.\\\\w]',\n        inConstruct,\n        notInConstruct\n      },\n      {\n        character: ':',\n        before: '[ps]',\n        after: '\\\\/',\n        inConstruct,\n        notInConstruct\n      }\n    ]\n  }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterLiteralAutolink(token) {\n  this.enter({type: 'link', title: null, url: '', children: []}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterLiteralAutolinkValue(token) {\n  this.config.enter.autolinkProtocol.call(this, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolinkHttp(token) {\n  this.config.exit.autolinkProtocol.call(this, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolinkWww(token) {\n  this.config.exit.data.call(this, token)\n  const node = this.stack[this.stack.length - 1]\n  assert(node.type === 'link')\n  node.url = 'http://' + this.sliceSerialize(token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolinkEmail(token) {\n  this.config.exit.autolinkEmail.call(this, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitLiteralAutolink(token) {\n  this.exit(token)\n}\n\n/** @type {FromMarkdownTransform} */\nfunction transformGfmAutolinkLiterals(tree) {\n  findAndReplace(\n    tree,\n    [\n      [/(https?:\\/\\/|www(?=\\.))([-.\\w]+)([^ \\t\\r\\n]*)/gi, findUrl],\n      [/(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)/gu, findEmail]\n    ],\n    {ignore: ['link', 'linkReference']}\n  )\n}\n\n/**\n * @type {ReplaceFunction}\n * @param {string} _\n * @param {string} protocol\n * @param {string} domain\n * @param {string} path\n * @param {RegExpMatchObject} match\n * @returns {Array<PhrasingContent> | Link | false}\n */\n// eslint-disable-next-line max-params\nfunction findUrl(_, protocol, domain, path, match) {\n  let prefix = ''\n\n  // Not an expected previous character.\n  if (!previous(match)) {\n    return false\n  }\n\n  // Treat `www` as part of the domain.\n  if (/^w/i.test(protocol)) {\n    domain = protocol + domain\n    protocol = ''\n    prefix = 'http://'\n  }\n\n  if (!isCorrectDomain(domain)) {\n    return false\n  }\n\n  const parts = splitUrl(domain + path)\n\n  if (!parts[0]) return false\n\n  /** @type {Link} */\n  const result = {\n    type: 'link',\n    title: null,\n    url: prefix + protocol + parts[0],\n    children: [{type: 'text', value: protocol + parts[0]}]\n  }\n\n  if (parts[1]) {\n    return [result, {type: 'text', value: parts[1]}]\n  }\n\n  return result\n}\n\n/**\n * @type {ReplaceFunction}\n * @param {string} _\n * @param {string} atext\n * @param {string} label\n * @param {RegExpMatchObject} match\n * @returns {Link | false}\n */\nfunction findEmail(_, atext, label, match) {\n  if (\n    // Not an expected previous character.\n    !previous(match, true) ||\n    // Label ends in not allowed character.\n    /[-\\d_]$/.test(label)\n  ) {\n    return false\n  }\n\n  return {\n    type: 'link',\n    title: null,\n    url: 'mailto:' + atext + '@' + label,\n    children: [{type: 'text', value: atext + '@' + label}]\n  }\n}\n\n/**\n * @param {string} domain\n * @returns {boolean}\n */\nfunction isCorrectDomain(domain) {\n  const parts = domain.split('.')\n\n  if (\n    parts.length < 2 ||\n    (parts[parts.length - 1] &&\n      (/_/.test(parts[parts.length - 1]) ||\n        !/[a-zA-Z\\d]/.test(parts[parts.length - 1]))) ||\n    (parts[parts.length - 2] &&\n      (/_/.test(parts[parts.length - 2]) ||\n        !/[a-zA-Z\\d]/.test(parts[parts.length - 2])))\n  ) {\n    return false\n  }\n\n  return true\n}\n\n/**\n * @param {string} url\n * @returns {[string, string | undefined]}\n */\nfunction splitUrl(url) {\n  const trailExec = /[!\"&'),.:;<>?\\]}]+$/.exec(url)\n\n  if (!trailExec) {\n    return [url, undefined]\n  }\n\n  url = url.slice(0, trailExec.index)\n\n  let trail = trailExec[0]\n  let closingParenIndex = trail.indexOf(')')\n  const openingParens = ccount(url, '(')\n  let closingParens = ccount(url, ')')\n\n  while (closingParenIndex !== -1 && openingParens > closingParens) {\n    url += trail.slice(0, closingParenIndex + 1)\n    trail = trail.slice(closingParenIndex + 1)\n    closingParenIndex = trail.indexOf(')')\n    closingParens++\n  }\n\n  return [url, trail]\n}\n\n/**\n * @param {RegExpMatchObject} match\n * @param {boolean | null | undefined} [email=false]\n * @returns {boolean}\n */\nfunction previous(match, email) {\n  const code = match.input.charCodeAt(match.index - 1)\n\n  return (\n    (match.index === 0 ||\n      unicodeWhitespace(code) ||\n      unicodePunctuation(code)) &&\n    // If it’s an email, the previous character should not be a slash.\n    (!email || code !== 47)\n  )\n}\n","/**\n * @import {\n *   CompileContext,\n *   Extension as FromMarkdownExtension,\n *   Handle as FromMarkdownHandle\n * } from 'mdast-util-from-markdown'\n * @import {ToMarkdownOptions} from 'mdast-util-gfm-footnote'\n * @import {\n *   Handle as ToMarkdownHandle,\n *   Map,\n *   Options as ToMarkdownExtension\n * } from 'mdast-util-to-markdown'\n * @import {FootnoteDefinition, FootnoteReference} from 'mdast'\n */\n\nimport {ok as assert} from 'devlop'\nimport {normalizeIdentifier} from 'micromark-util-normalize-identifier'\n\nfootnoteReference.peek = footnoteReferencePeek\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteCallString() {\n  this.buffer()\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteCall(token) {\n  this.enter({type: 'footnoteReference', identifier: '', label: ''}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteDefinitionLabelString() {\n  this.buffer()\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterFootnoteDefinition(token) {\n  this.enter(\n    {type: 'footnoteDefinition', identifier: '', label: '', children: []},\n    token\n  )\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteCallString(token) {\n  const label = this.resume()\n  const node = this.stack[this.stack.length - 1]\n  assert(node.type === 'footnoteReference')\n  node.identifier = normalizeIdentifier(\n    this.sliceSerialize(token)\n  ).toLowerCase()\n  node.label = label\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteCall(token) {\n  this.exit(token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteDefinitionLabelString(token) {\n  const label = this.resume()\n  const node = this.stack[this.stack.length - 1]\n  assert(node.type === 'footnoteDefinition')\n  node.identifier = normalizeIdentifier(\n    this.sliceSerialize(token)\n  ).toLowerCase()\n  node.label = label\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitFootnoteDefinition(token) {\n  this.exit(token)\n}\n\n/** @type {ToMarkdownHandle} */\nfunction footnoteReferencePeek() {\n  return '['\n}\n\n/**\n * @type {ToMarkdownHandle}\n * @param {FootnoteReference} node\n */\nfunction footnoteReference(node, _, state, info) {\n  const tracker = state.createTracker(info)\n  let value = tracker.move('[^')\n  const exit = state.enter('footnoteReference')\n  const subexit = state.enter('reference')\n  value += tracker.move(\n    state.safe(state.associationId(node), {after: ']', before: value})\n  )\n  subexit()\n  exit()\n  value += tracker.move(']')\n  return value\n}\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM footnotes\n * in markdown.\n *\n * @returns {FromMarkdownExtension}\n *   Extension for `mdast-util-from-markdown`.\n */\nexport function gfmFootnoteFromMarkdown() {\n  return {\n    enter: {\n      gfmFootnoteCallString: enterFootnoteCallString,\n      gfmFootnoteCall: enterFootnoteCall,\n      gfmFootnoteDefinitionLabelString: enterFootnoteDefinitionLabelString,\n      gfmFootnoteDefinition: enterFootnoteDefinition\n    },\n    exit: {\n      gfmFootnoteCallString: exitFootnoteCallString,\n      gfmFootnoteCall: exitFootnoteCall,\n      gfmFootnoteDefinitionLabelString: exitFootnoteDefinitionLabelString,\n      gfmFootnoteDefinition: exitFootnoteDefinition\n    }\n  }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM footnotes\n * in markdown.\n *\n * @param {ToMarkdownOptions | null | undefined} [options]\n *   Configuration (optional).\n * @returns {ToMarkdownExtension}\n *   Extension for `mdast-util-to-markdown`.\n */\nexport function gfmFootnoteToMarkdown(options) {\n  // To do: next major: change default.\n  let firstLineBlank = false\n\n  if (options && options.firstLineBlank) {\n    firstLineBlank = true\n  }\n\n  return {\n    handlers: {footnoteDefinition, footnoteReference},\n    // This is on by default already.\n    unsafe: [{character: '[', inConstruct: ['label', 'phrasing', 'reference']}]\n  }\n\n  /**\n   * @type {ToMarkdownHandle}\n   * @param {FootnoteDefinition} node\n   */\n  function footnoteDefinition(node, _, state, info) {\n    const tracker = state.createTracker(info)\n    let value = tracker.move('[^')\n    const exit = state.enter('footnoteDefinition')\n    const subexit = state.enter('label')\n    value += tracker.move(\n      state.safe(state.associationId(node), {before: value, after: ']'})\n    )\n    subexit()\n\n    value += tracker.move(']:')\n\n    if (node.children && node.children.length > 0) {\n      tracker.shift(4)\n\n      value += tracker.move(\n        (firstLineBlank ? '\\n' : ' ') +\n          state.indentLines(\n            state.containerFlow(node, tracker.current()),\n            firstLineBlank ? mapAll : mapExceptFirst\n          )\n      )\n    }\n\n    exit()\n\n    return value\n  }\n}\n\n/** @type {Map} */\nfunction mapExceptFirst(line, index, blank) {\n  return index === 0 ? line : mapAll(line, index, blank)\n}\n\n/** @type {Map} */\nfunction mapAll(line, index, blank) {\n  return (blank ? '' : '    ') + line\n}\n","/**\n * @typedef {import('mdast').Delete} Delete\n *\n * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext\n * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension\n * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle\n *\n * @typedef {import('mdast-util-to-markdown').ConstructName} ConstructName\n * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension\n */\n\n/**\n * List of constructs that occur in phrasing (paragraphs, headings), but cannot\n * contain strikethrough.\n * So they sort of cancel each other out.\n * Note: could use a better name.\n *\n * Note: keep in sync with: <https://github.com/syntax-tree/mdast-util-to-markdown/blob/8ce8dbf/lib/unsafe.js#L14>\n *\n * @type {Array<ConstructName>}\n */\nconst constructsWithoutStrikethrough = [\n  'autolink',\n  'destinationLiteral',\n  'destinationRaw',\n  'reference',\n  'titleQuote',\n  'titleApostrophe'\n]\n\nhandleDelete.peek = peekDelete\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM\n * strikethrough in markdown.\n *\n * @returns {FromMarkdownExtension}\n *   Extension for `mdast-util-from-markdown` to enable GFM strikethrough.\n */\nexport function gfmStrikethroughFromMarkdown() {\n  return {\n    canContainEols: ['delete'],\n    enter: {strikethrough: enterStrikethrough},\n    exit: {strikethrough: exitStrikethrough}\n  }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM\n * strikethrough in markdown.\n *\n * @returns {ToMarkdownExtension}\n *   Extension for `mdast-util-to-markdown` to enable GFM strikethrough.\n */\nexport function gfmStrikethroughToMarkdown() {\n  return {\n    unsafe: [\n      {\n        character: '~',\n        inConstruct: 'phrasing',\n        notInConstruct: constructsWithoutStrikethrough\n      }\n    ],\n    handlers: {delete: handleDelete}\n  }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterStrikethrough(token) {\n  this.enter({type: 'delete', children: []}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitStrikethrough(token) {\n  this.exit(token)\n}\n\n/**\n * @type {ToMarkdownHandle}\n * @param {Delete} node\n */\nfunction handleDelete(node, _, state, info) {\n  const tracker = state.createTracker(info)\n  const exit = state.enter('strikethrough')\n  let value = tracker.move('~~')\n  value += state.containerPhrasing(node, {\n    ...tracker.current(),\n    before: value,\n    after: '~'\n  })\n  value += tracker.move('~~')\n  exit()\n  return value\n}\n\n/** @type {ToMarkdownHandle} */\nfunction peekDelete() {\n  return '~'\n}\n","// To do: next major: remove.\n/**\n * @typedef {Options} MarkdownTableOptions\n *   Configuration.\n */\n\n/**\n * @typedef Options\n *   Configuration.\n * @property {boolean | null | undefined} [alignDelimiters=true]\n *   Whether to align the delimiters (default: `true`);\n *   they are aligned by default:\n *\n *   ```markdown\n *   | Alpha | B     |\n *   | ----- | ----- |\n *   | C     | Delta |\n *   ```\n *\n *   Pass `false` to make them staggered:\n *\n *   ```markdown\n *   | Alpha | B |\n *   | - | - |\n *   | C | Delta |\n *   ```\n * @property {ReadonlyArray<string | null | undefined> | string | null | undefined} [align]\n *   How to align columns (default: `''`);\n *   one style for all columns or styles for their respective columns;\n *   each style is either `'l'` (left), `'r'` (right), or `'c'` (center);\n *   other values are treated as `''`, which doesn’t place the colon in the\n *   alignment row but does align left;\n *   *only the lowercased first character is used, so `Right` is fine.*\n * @property {boolean | null | undefined} [delimiterEnd=true]\n *   Whether to end each row with the delimiter (default: `true`).\n *\n *   > 👉 **Note**: please don’t use this: it could create fragile structures\n *   > that aren’t understandable to some markdown parsers.\n *\n *   When `true`, there are ending delimiters:\n *\n *   ```markdown\n *   | Alpha | B     |\n *   | ----- | ----- |\n *   | C     | Delta |\n *   ```\n *\n *   When `false`, there are no ending delimiters:\n *\n *   ```markdown\n *   | Alpha | B\n *   | ----- | -----\n *   | C     | Delta\n *   ```\n * @property {boolean | null | undefined} [delimiterStart=true]\n *   Whether to begin each row with the delimiter (default: `true`).\n *\n *   > 👉 **Note**: please don’t use this: it could create fragile structures\n *   > that aren’t understandable to some markdown parsers.\n *\n *   When `true`, there are starting delimiters:\n *\n *   ```markdown\n *   | Alpha | B     |\n *   | ----- | ----- |\n *   | C     | Delta |\n *   ```\n *\n *   When `false`, there are no starting delimiters:\n *\n *   ```markdown\n *   Alpha | B     |\n *   ----- | ----- |\n *   C     | Delta |\n *   ```\n * @property {boolean | null | undefined} [padding=true]\n *   Whether to add a space of padding between delimiters and cells\n *   (default: `true`).\n *\n *   When `true`, there is padding:\n *\n *   ```markdown\n *   | Alpha | B     |\n *   | ----- | ----- |\n *   | C     | Delta |\n *   ```\n *\n *   When `false`, there is no padding:\n *\n *   ```markdown\n *   |Alpha|B    |\n *   |-----|-----|\n *   |C    |Delta|\n *   ```\n * @property {((value: string) => number) | null | undefined} [stringLength]\n *   Function to detect the length of table cell content (optional);\n *   this is used when aligning the delimiters (`|`) between table cells;\n *   full-width characters and emoji mess up delimiter alignment when viewing\n *   the markdown source;\n *   to fix this, you can pass this function,\n *   which receives the cell content and returns its “visible” size;\n *   note that what is and isn’t visible depends on where the text is displayed.\n *\n *   Without such a function, the following:\n *\n *   ```js\n *   markdownTable([\n *     ['Alpha', 'Bravo'],\n *     ['中文', 'Charlie'],\n *     ['👩‍❤️‍👩', 'Delta']\n *   ])\n *   ```\n *\n *   Yields:\n *\n *   ```markdown\n *   | Alpha | Bravo |\n *   | - | - |\n *   | 中文 | Charlie |\n *   | 👩‍❤️‍👩 | Delta |\n *   ```\n *\n *   With [`string-width`](https://github.com/sindresorhus/string-width):\n *\n *   ```js\n *   import stringWidth from 'string-width'\n *\n *   markdownTable(\n *     [\n *       ['Alpha', 'Bravo'],\n *       ['中文', 'Charlie'],\n *       ['👩‍❤️‍👩', 'Delta']\n *     ],\n *     {stringLength: stringWidth}\n *   )\n *   ```\n *\n *   Yields:\n *\n *   ```markdown\n *   | Alpha | Bravo   |\n *   | ----- | ------- |\n *   | 中文  | Charlie |\n *   | 👩‍❤️‍👩    | Delta   |\n *   ```\n */\n\n/**\n * @param {string} value\n *   Cell value.\n * @returns {number}\n *   Cell size.\n */\nfunction defaultStringLength(value) {\n  return value.length\n}\n\n/**\n * Generate a markdown\n * ([GFM](https://docs.github.com/en/github/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables))\n * table.\n *\n * @param {ReadonlyArray<ReadonlyArray<string | null | undefined>>} table\n *   Table data (matrix of strings).\n * @param {Readonly<Options> | null | undefined} [options]\n *   Configuration (optional).\n * @returns {string}\n *   Result.\n */\nexport function markdownTable(table, options) {\n  const settings = options || {}\n  // To do: next major: change to spread.\n  const align = (settings.align || []).concat()\n  const stringLength = settings.stringLength || defaultStringLength\n  /** @type {Array<number>} Character codes as symbols for alignment per column. */\n  const alignments = []\n  /** @type {Array<Array<string>>} Cells per row. */\n  const cellMatrix = []\n  /** @type {Array<Array<number>>} Sizes of each cell per row. */\n  const sizeMatrix = []\n  /** @type {Array<number>} */\n  const longestCellByColumn = []\n  let mostCellsPerRow = 0\n  let rowIndex = -1\n\n  // This is a superfluous loop if we don’t align delimiters, but otherwise we’d\n  // do superfluous work when aligning, so optimize for aligning.\n  while (++rowIndex < table.length) {\n    /** @type {Array<string>} */\n    const row = []\n    /** @type {Array<number>} */\n    const sizes = []\n    let columnIndex = -1\n\n    if (table[rowIndex].length > mostCellsPerRow) {\n      mostCellsPerRow = table[rowIndex].length\n    }\n\n    while (++columnIndex < table[rowIndex].length) {\n      const cell = serialize(table[rowIndex][columnIndex])\n\n      if (settings.alignDelimiters !== false) {\n        const size = stringLength(cell)\n        sizes[columnIndex] = size\n\n        if (\n          longestCellByColumn[columnIndex] === undefined ||\n          size > longestCellByColumn[columnIndex]\n        ) {\n          longestCellByColumn[columnIndex] = size\n        }\n      }\n\n      row.push(cell)\n    }\n\n    cellMatrix[rowIndex] = row\n    sizeMatrix[rowIndex] = sizes\n  }\n\n  // Figure out which alignments to use.\n  let columnIndex = -1\n\n  if (typeof align === 'object' && 'length' in align) {\n    while (++columnIndex < mostCellsPerRow) {\n      alignments[columnIndex] = toAlignment(align[columnIndex])\n    }\n  } else {\n    const code = toAlignment(align)\n\n    while (++columnIndex < mostCellsPerRow) {\n      alignments[columnIndex] = code\n    }\n  }\n\n  // Inject the alignment row.\n  columnIndex = -1\n  /** @type {Array<string>} */\n  const row = []\n  /** @type {Array<number>} */\n  const sizes = []\n\n  while (++columnIndex < mostCellsPerRow) {\n    const code = alignments[columnIndex]\n    let before = ''\n    let after = ''\n\n    if (code === 99 /* `c` */) {\n      before = ':'\n      after = ':'\n    } else if (code === 108 /* `l` */) {\n      before = ':'\n    } else if (code === 114 /* `r` */) {\n      after = ':'\n    }\n\n    // There *must* be at least one hyphen-minus in each alignment cell.\n    let size =\n      settings.alignDelimiters === false\n        ? 1\n        : Math.max(\n            1,\n            longestCellByColumn[columnIndex] - before.length - after.length\n          )\n\n    const cell = before + '-'.repeat(size) + after\n\n    if (settings.alignDelimiters !== false) {\n      size = before.length + size + after.length\n\n      if (size > longestCellByColumn[columnIndex]) {\n        longestCellByColumn[columnIndex] = size\n      }\n\n      sizes[columnIndex] = size\n    }\n\n    row[columnIndex] = cell\n  }\n\n  // Inject the alignment row.\n  cellMatrix.splice(1, 0, row)\n  sizeMatrix.splice(1, 0, sizes)\n\n  rowIndex = -1\n  /** @type {Array<string>} */\n  const lines = []\n\n  while (++rowIndex < cellMatrix.length) {\n    const row = cellMatrix[rowIndex]\n    const sizes = sizeMatrix[rowIndex]\n    columnIndex = -1\n    /** @type {Array<string>} */\n    const line = []\n\n    while (++columnIndex < mostCellsPerRow) {\n      const cell = row[columnIndex] || ''\n      let before = ''\n      let after = ''\n\n      if (settings.alignDelimiters !== false) {\n        const size =\n          longestCellByColumn[columnIndex] - (sizes[columnIndex] || 0)\n        const code = alignments[columnIndex]\n\n        if (code === 114 /* `r` */) {\n          before = ' '.repeat(size)\n        } else if (code === 99 /* `c` */) {\n          if (size % 2) {\n            before = ' '.repeat(size / 2 + 0.5)\n            after = ' '.repeat(size / 2 - 0.5)\n          } else {\n            before = ' '.repeat(size / 2)\n            after = before\n          }\n        } else {\n          after = ' '.repeat(size)\n        }\n      }\n\n      if (settings.delimiterStart !== false && !columnIndex) {\n        line.push('|')\n      }\n\n      if (\n        settings.padding !== false &&\n        // Don’t add the opening space if we’re not aligning and the cell is\n        // empty: there will be a closing space.\n        !(settings.alignDelimiters === false && cell === '') &&\n        (settings.delimiterStart !== false || columnIndex)\n      ) {\n        line.push(' ')\n      }\n\n      if (settings.alignDelimiters !== false) {\n        line.push(before)\n      }\n\n      line.push(cell)\n\n      if (settings.alignDelimiters !== false) {\n        line.push(after)\n      }\n\n      if (settings.padding !== false) {\n        line.push(' ')\n      }\n\n      if (\n        settings.delimiterEnd !== false ||\n        columnIndex !== mostCellsPerRow - 1\n      ) {\n        line.push('|')\n      }\n    }\n\n    lines.push(\n      settings.delimiterEnd === false\n        ? line.join('').replace(/ +$/, '')\n        : line.join('')\n    )\n  }\n\n  return lines.join('\\n')\n}\n\n/**\n * @param {string | null | undefined} [value]\n *   Value to serialize.\n * @returns {string}\n *   Result.\n */\nfunction serialize(value) {\n  return value === null || value === undefined ? '' : String(value)\n}\n\n/**\n * @param {string | null | undefined} value\n *   Value.\n * @returns {number}\n *   Alignment.\n */\nfunction toAlignment(value) {\n  const code = typeof value === 'string' ? value.codePointAt(0) : 0\n\n  return code === 67 /* `C` */ || code === 99 /* `c` */\n    ? 99 /* `c` */\n    : code === 76 /* `L` */ || code === 108 /* `l` */\n      ? 108 /* `l` */\n      : code === 82 /* `R` */ || code === 114 /* `r` */\n        ? 114 /* `r` */\n        : 0\n}\n","/**\n * @callback Handler\n *   Handle a value, with a certain ID field set to a certain value.\n *   The ID field is passed to `zwitch`, and it’s value is this function’s\n *   place on the `handlers` record.\n * @param {...any} parameters\n *   Arbitrary parameters passed to the zwitch.\n *   The first will be an object with a certain ID field set to a certain value.\n * @returns {any}\n *   Anything!\n */\n\n/**\n * @callback UnknownHandler\n *   Handle values that do have a certain ID field, but it’s set to a value\n *   that is not listed in the `handlers` record.\n * @param {unknown} value\n *   An object with a certain ID field set to an unknown value.\n * @param {...any} rest\n *   Arbitrary parameters passed to the zwitch.\n * @returns {any}\n *   Anything!\n */\n\n/**\n * @callback InvalidHandler\n *   Handle values that do not have a certain ID field.\n * @param {unknown} value\n *   Any unknown value.\n * @param {...any} rest\n *   Arbitrary parameters passed to the zwitch.\n * @returns {void|null|undefined|never}\n *   This should crash or return nothing.\n */\n\n/**\n * @template {InvalidHandler} [Invalid=InvalidHandler]\n * @template {UnknownHandler} [Unknown=UnknownHandler]\n * @template {Record<string, Handler>} [Handlers=Record<string, Handler>]\n * @typedef Options\n *   Configuration (required).\n * @property {Invalid} [invalid]\n *   Handler to use for invalid values.\n * @property {Unknown} [unknown]\n *   Handler to use for unknown values.\n * @property {Handlers} [handlers]\n *   Handlers to use.\n */\n\nconst own = {}.hasOwnProperty\n\n/**\n * Handle values based on a field.\n *\n * @template {InvalidHandler} [Invalid=InvalidHandler]\n * @template {UnknownHandler} [Unknown=UnknownHandler]\n * @template {Record<string, Handler>} [Handlers=Record<string, Handler>]\n * @param {string} key\n *   Field to switch on.\n * @param {Options<Invalid, Unknown, Handlers>} [options]\n *   Configuration (required).\n * @returns {{unknown: Unknown, invalid: Invalid, handlers: Handlers, (...parameters: Parameters<Handlers[keyof Handlers]>): ReturnType<Handlers[keyof Handlers]>, (...parameters: Parameters<Unknown>): ReturnType<Unknown>}}\n */\nexport function zwitch(key, options) {\n  const settings = options || {}\n\n  /**\n   * Handle one value.\n   *\n   * Based on the bound `key`, a respective handler will be called.\n   * If `value` is not an object, or doesn’t have a `key` property, the special\n   * “invalid” handler will be called.\n   * If `value` has an unknown `key`, the special “unknown” handler will be\n   * called.\n   *\n   * All arguments, and the context object, are passed through to the handler,\n   * and it’s result is returned.\n   *\n   * @this {unknown}\n   *   Any context object.\n   * @param {unknown} [value]\n   *   Any value.\n   * @param {...unknown} parameters\n   *   Arbitrary parameters passed to the zwitch.\n   * @property {Handler} invalid\n   *   Handle for values that do not have a certain ID field.\n   * @property {Handler} unknown\n   *   Handle values that do have a certain ID field, but it’s set to a value\n   *   that is not listed in the `handlers` record.\n   * @property {Handlers} handlers\n   *   Record of handlers.\n   * @returns {unknown}\n   *   Anything.\n   */\n  function one(value, ...parameters) {\n    /** @type {Handler|undefined} */\n    let fn = one.invalid\n    const handlers = one.handlers\n\n    if (value && own.call(value, key)) {\n      // @ts-expect-error Indexable.\n      const id = String(value[key])\n      // @ts-expect-error Indexable.\n      fn = own.call(handlers, id) ? handlers[id] : one.unknown\n    }\n\n    if (fn) {\n      return fn.call(this, value, ...parameters)\n    }\n  }\n\n  one.handlers = settings.handlers || {}\n  one.invalid = settings.invalid\n  one.unknown = settings.unknown\n\n  // @ts-expect-error: matches!\n  return one\n}\n","/**\n * @import {Blockquote, Parents} from 'mdast'\n * @import {Info, Map, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {Blockquote} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function blockquote(node, _, state, info) {\n  const exit = state.enter('blockquote')\n  const tracker = state.createTracker(info)\n  tracker.move('> ')\n  tracker.shift(2)\n  const value = state.indentLines(\n    state.containerFlow(node, tracker.current()),\n    map\n  )\n  exit()\n  return value\n}\n\n/** @type {Map} */\nfunction map(line, _, blank) {\n  return '>' + (blank ? '' : ' ') + line\n}\n","/**\n * @import {ConstructName, Unsafe} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {Array<ConstructName>} stack\n * @param {Unsafe} pattern\n * @returns {boolean}\n */\nexport function patternInScope(stack, pattern) {\n  return (\n    listInScope(stack, pattern.inConstruct, true) &&\n    !listInScope(stack, pattern.notInConstruct, false)\n  )\n}\n\n/**\n * @param {Array<ConstructName>} stack\n * @param {Unsafe['inConstruct']} list\n * @param {boolean} none\n * @returns {boolean}\n */\nfunction listInScope(stack, list, none) {\n  if (typeof list === 'string') {\n    list = [list]\n  }\n\n  if (!list || list.length === 0) {\n    return none\n  }\n\n  let index = -1\n\n  while (++index < list.length) {\n    if (stack.includes(list[index])) {\n      return true\n    }\n  }\n\n  return false\n}\n","/**\n * @import {Break, Parents} from 'mdast'\n * @import {Info, State} from 'mdast-util-to-markdown'\n */\n\nimport {patternInScope} from '../util/pattern-in-scope.js'\n\n/**\n * @param {Break} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function hardBreak(_, _1, state, info) {\n  let index = -1\n\n  while (++index < state.unsafe.length) {\n    // If we can’t put eols in this construct (setext headings, tables), use a\n    // space instead.\n    if (\n      state.unsafe[index].character === '\\n' &&\n      patternInScope(state.stack, state.unsafe[index])\n    ) {\n      return /[ \\t]/.test(info.before) ? '' : ' '\n    }\n  }\n\n  return '\\\\\\n'\n}\n","/**\n * Get the count of the longest repeating streak of `substring` in `value`.\n *\n * @param {string} value\n *   Content to search in.\n * @param {string} substring\n *   Substring to look for, typically one character.\n * @returns {number}\n *   Count of most frequent adjacent `substring`s in `value`.\n */\nexport function longestStreak(value, substring) {\n  const source = String(value)\n  let index = source.indexOf(substring)\n  let expected = index\n  let count = 0\n  let max = 0\n\n  if (typeof substring !== 'string') {\n    throw new TypeError('Expected substring')\n  }\n\n  while (index !== -1) {\n    if (index === expected) {\n      if (++count > max) {\n        max = count\n      }\n    } else {\n      count = 1\n    }\n\n    expected = index + substring.length\n    index = source.indexOf(substring, expected)\n  }\n\n  return max\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Code} from 'mdast'\n */\n\n/**\n * @param {Code} node\n * @param {State} state\n * @returns {boolean}\n */\nexport function formatCodeAsIndented(node, state) {\n  return Boolean(\n    state.options.fences === false &&\n      node.value &&\n      // If there’s no info…\n      !node.lang &&\n      // And there’s a non-whitespace character…\n      /[^ \\r\\n]/.test(node.value) &&\n      // And the value doesn’t start or end in a blank…\n      !/^[\\t ]*(?:[\\r\\n]|$)|(?:^|[\\r\\n])[\\t ]*$/.test(node.value)\n  )\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['fence'], null | undefined>}\n */\nexport function checkFence(state) {\n  const marker = state.options.fence || '`'\n\n  if (marker !== '`' && marker !== '~') {\n    throw new Error(\n      'Cannot serialize code with `' +\n        marker +\n        '` for `options.fence`, expected `` ` `` or `~`'\n    )\n  }\n\n  return marker\n}\n","/**\n * @import {Info, Map, State} from 'mdast-util-to-markdown'\n * @import {Code, Parents} from 'mdast'\n */\n\nimport {longestStreak} from 'longest-streak'\nimport {formatCodeAsIndented} from '../util/format-code-as-indented.js'\nimport {checkFence} from '../util/check-fence.js'\n\n/**\n * @param {Code} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function code(node, _, state, info) {\n  const marker = checkFence(state)\n  const raw = node.value || ''\n  const suffix = marker === '`' ? 'GraveAccent' : 'Tilde'\n\n  if (formatCodeAsIndented(node, state)) {\n    const exit = state.enter('codeIndented')\n    const value = state.indentLines(raw, map)\n    exit()\n    return value\n  }\n\n  const tracker = state.createTracker(info)\n  const sequence = marker.repeat(Math.max(longestStreak(raw, marker) + 1, 3))\n  const exit = state.enter('codeFenced')\n  let value = tracker.move(sequence)\n\n  if (node.lang) {\n    const subexit = state.enter(`codeFencedLang${suffix}`)\n    value += tracker.move(\n      state.safe(node.lang, {\n        before: value,\n        after: ' ',\n        encode: ['`'],\n        ...tracker.current()\n      })\n    )\n    subexit()\n  }\n\n  if (node.lang && node.meta) {\n    const subexit = state.enter(`codeFencedMeta${suffix}`)\n    value += tracker.move(' ')\n    value += tracker.move(\n      state.safe(node.meta, {\n        before: value,\n        after: '\\n',\n        encode: ['`'],\n        ...tracker.current()\n      })\n    )\n    subexit()\n  }\n\n  value += tracker.move('\\n')\n\n  if (raw) {\n    value += tracker.move(raw + '\\n')\n  }\n\n  value += tracker.move(sequence)\n  exit()\n  return value\n}\n\n/** @type {Map} */\nfunction map(line, _, blank) {\n  return (blank ? '' : '    ') + line\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['quote'], null | undefined>}\n */\nexport function checkQuote(state) {\n  const marker = state.options.quote || '\"'\n\n  if (marker !== '\"' && marker !== \"'\") {\n    throw new Error(\n      'Cannot serialize title with `' +\n        marker +\n        '` for `options.quote`, expected `\"`, or `\\'`'\n    )\n  }\n\n  return marker\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Definition, Parents} from 'mdast'\n */\n\nimport {checkQuote} from '../util/check-quote.js'\n\n/**\n * @param {Definition} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function definition(node, _, state, info) {\n  const quote = checkQuote(state)\n  const suffix = quote === '\"' ? 'Quote' : 'Apostrophe'\n  const exit = state.enter('definition')\n  let subexit = state.enter('label')\n  const tracker = state.createTracker(info)\n  let value = tracker.move('[')\n  value += tracker.move(\n    state.safe(state.associationId(node), {\n      before: value,\n      after: ']',\n      ...tracker.current()\n    })\n  )\n  value += tracker.move(']: ')\n\n  subexit()\n\n  if (\n    // If there’s no url, or…\n    !node.url ||\n    // If there are control characters or whitespace.\n    /[\\0- \\u007F]/.test(node.url)\n  ) {\n    subexit = state.enter('destinationLiteral')\n    value += tracker.move('<')\n    value += tracker.move(\n      state.safe(node.url, {before: value, after: '>', ...tracker.current()})\n    )\n    value += tracker.move('>')\n  } else {\n    // No whitespace, raw is prettier.\n    subexit = state.enter('destinationRaw')\n    value += tracker.move(\n      state.safe(node.url, {\n        before: value,\n        after: node.title ? ' ' : '\\n',\n        ...tracker.current()\n      })\n    )\n  }\n\n  subexit()\n\n  if (node.title) {\n    subexit = state.enter(`title${suffix}`)\n    value += tracker.move(' ' + quote)\n    value += tracker.move(\n      state.safe(node.title, {\n        before: value,\n        after: quote,\n        ...tracker.current()\n      })\n    )\n    value += tracker.move(quote)\n    subexit()\n  }\n\n  exit()\n\n  return value\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['emphasis'], null | undefined>}\n */\nexport function checkEmphasis(state) {\n  const marker = state.options.emphasis || '*'\n\n  if (marker !== '*' && marker !== '_') {\n    throw new Error(\n      'Cannot serialize emphasis with `' +\n        marker +\n        '` for `options.emphasis`, expected `*`, or `_`'\n    )\n  }\n\n  return marker\n}\n","/**\n * Encode a code point as a character reference.\n *\n * @param {number} code\n *   Code point to encode.\n * @returns {string}\n *   Encoded character reference.\n */\nexport function encodeCharacterReference(code) {\n  return '&#x' + code.toString(16).toUpperCase() + ';'\n}\n","/**\n * @import {EncodeSides} from '../types.js'\n */\n\nimport {classifyCharacter} from 'micromark-util-classify-character'\n\n/**\n * Check whether to encode (as a character reference) the characters\n * surrounding an attention run.\n *\n * Which characters are around an attention run influence whether it works or\n * not.\n *\n * See <https://github.com/orgs/syntax-tree/discussions/60> for more info.\n * See this markdown in a particular renderer to see what works:\n *\n * ```markdown\n * |                         | A (letter inside) | B (punctuation inside) | C (whitespace inside) | D (nothing inside) |\n * | ----------------------- | ----------------- | ---------------------- | --------------------- | ------------------ |\n * | 1 (letter outside)      | x*y*z             | x*.*z                  | x* *z                 | x**z               |\n * | 2 (punctuation outside) | .*y*.             | .*.*.                  | .* *.                 | .**.               |\n * | 3 (whitespace outside)  | x *y* z           | x *.* z                | x * * z               | x ** z             |\n * | 4 (nothing outside)     | *x*               | *.*                    | * *                   | **                 |\n * ```\n *\n * @param {number} outside\n *   Code point on the outer side of the run.\n * @param {number} inside\n *   Code point on the inner side of the run.\n * @param {'*' | '_'} marker\n *   Marker of the run.\n *   Underscores are handled more strictly (they form less often) than\n *   asterisks.\n * @returns {EncodeSides}\n *   Whether to encode characters.\n */\n// Important: punctuation must never be encoded.\n// Punctuation is solely used by markdown constructs.\n// And by encoding itself.\n// Encoding them will break constructs or double encode things.\nexport function encodeInfo(outside, inside, marker) {\n  const outsideKind = classifyCharacter(outside)\n  const insideKind = classifyCharacter(inside)\n\n  // Letter outside:\n  if (outsideKind === undefined) {\n    return insideKind === undefined\n      ? // Letter inside:\n        // we have to encode *both* letters for `_` as it is looser.\n        // it already forms for `*` (and GFMs `~`).\n        marker === '_'\n        ? {inside: true, outside: true}\n        : {inside: false, outside: false}\n      : insideKind === 1\n        ? // Whitespace inside: encode both (letter, whitespace).\n          {inside: true, outside: true}\n        : // Punctuation inside: encode outer (letter)\n          {inside: false, outside: true}\n  }\n\n  // Whitespace outside:\n  if (outsideKind === 1) {\n    return insideKind === undefined\n      ? // Letter inside: already forms.\n        {inside: false, outside: false}\n      : insideKind === 1\n        ? // Whitespace inside: encode both (whitespace).\n          {inside: true, outside: true}\n        : // Punctuation inside: already forms.\n          {inside: false, outside: false}\n  }\n\n  // Punctuation outside:\n  return insideKind === undefined\n    ? // Letter inside: already forms.\n      {inside: false, outside: false}\n    : insideKind === 1\n      ? // Whitespace inside: encode inner (whitespace).\n        {inside: true, outside: false}\n      : // Punctuation inside: already forms.\n        {inside: false, outside: false}\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Emphasis, Parents} from 'mdast'\n */\n\nimport {checkEmphasis} from '../util/check-emphasis.js'\nimport {encodeCharacterReference} from '../util/encode-character-reference.js'\nimport {encodeInfo} from '../util/encode-info.js'\n\nemphasis.peek = emphasisPeek\n\n/**\n * @param {Emphasis} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function emphasis(node, _, state, info) {\n  const marker = checkEmphasis(state)\n  const exit = state.enter('emphasis')\n  const tracker = state.createTracker(info)\n  const before = tracker.move(marker)\n\n  let between = tracker.move(\n    state.containerPhrasing(node, {\n      after: marker,\n      before,\n      ...tracker.current()\n    })\n  )\n  const betweenHead = between.charCodeAt(0)\n  const open = encodeInfo(\n    info.before.charCodeAt(info.before.length - 1),\n    betweenHead,\n    marker\n  )\n\n  if (open.inside) {\n    between = encodeCharacterReference(betweenHead) + between.slice(1)\n  }\n\n  const betweenTail = between.charCodeAt(between.length - 1)\n  const close = encodeInfo(info.after.charCodeAt(0), betweenTail, marker)\n\n  if (close.inside) {\n    between = between.slice(0, -1) + encodeCharacterReference(betweenTail)\n  }\n\n  const after = tracker.move(marker)\n\n  exit()\n\n  state.attentionEncodeSurroundingInfo = {\n    after: close.outside,\n    before: open.outside\n  }\n  return before + between + after\n}\n\n/**\n * @param {Emphasis} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @returns {string}\n */\nfunction emphasisPeek(_, _1, state) {\n  return state.options.emphasis || '*'\n}\n","/**\n * @import {Node as UnistNode, Parent as UnistParent} from 'unist'\n * @import {VisitorResult} from 'unist-util-visit-parents'\n */\n\n/**\n * @typedef {Exclude<import('unist-util-is').Test, undefined> | undefined} Test\n *   Test from `unist-util-is`.\n *\n *   Note: we have remove and add `undefined`, because otherwise when generating\n *   automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n *   which doesn’t work when publishing on npm.\n */\n\n// To do: use types from `unist-util-visit-parents` when it’s released.\n\n/**\n * @typedef {(\n *   Fn extends (value: any) => value is infer Thing\n *   ? Thing\n *   : Fallback\n * )} Predicate\n *   Get the value of a type guard `Fn`.\n * @template Fn\n *   Value; typically function that is a type guard (such as `(x): x is Y`).\n * @template Fallback\n *   Value to yield if `Fn` is not a type guard.\n */\n\n/**\n * @typedef {(\n *   Check extends null | undefined // No test.\n *   ? Value\n *   : Value extends {type: Check} // String (type) test.\n *   ? Value\n *   : Value extends Check // Partial test.\n *   ? Value\n *   : Check extends Function // Function test.\n *   ? Predicate<Check, Value> extends Value\n *     ? Predicate<Check, Value>\n *     : never\n *   : never // Some other test?\n * )} MatchesOne\n *   Check whether a node matches a primitive check in the type system.\n * @template Value\n *   Value; typically unist `Node`.\n * @template Check\n *   Value; typically `unist-util-is`-compatible test, but not arrays.\n */\n\n/**\n * @typedef {(\n *   Check extends ReadonlyArray<any>\n *   ? MatchesOne<Value, Check[number]>\n *   : MatchesOne<Value, Check>\n * )} Matches\n *   Check whether a node matches a check in the type system.\n * @template Value\n *   Value; typically unist `Node`.\n * @template Check\n *   Value; typically `unist-util-is`-compatible test.\n */\n\n/**\n * @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10} Uint\n *   Number; capped reasonably.\n */\n\n/**\n * @typedef {I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10} Increment\n *   Increment a number in the type system.\n * @template {Uint} [I=0]\n *   Index.\n */\n\n/**\n * @typedef {(\n *   Node extends UnistParent\n *   ? Node extends {children: Array<infer Children>}\n *     ? Child extends Children ? Node : never\n *     : never\n *   : never\n * )} InternalParent\n *   Collect nodes that can be parents of `Child`.\n * @template {UnistNode} Node\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n */\n\n/**\n * @typedef {InternalParent<InclusiveDescendant<Tree>, Child>} Parent\n *   Collect nodes in `Tree` that can be parents of `Child`.\n * @template {UnistNode} Tree\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n */\n\n/**\n * @typedef {(\n *   Depth extends Max\n *   ? never\n *   :\n *     | InternalParent<Node, Child>\n *     | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>\n * )} InternalAncestor\n *   Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Node\n *   All node types in a tree.\n * @template {UnistNode} Child\n *   Node to search for.\n * @template {Uint} [Max=10]\n *   Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n *   Current depth.\n */\n\n/**\n * @typedef {(\n *   Tree extends UnistParent\n *     ? Depth extends Max\n *       ? Tree\n *       : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>\n *     : Tree\n * )} InclusiveDescendant\n *   Collect all (inclusive) descendants of `Tree`.\n *\n *   > 👉 **Note**: for performance reasons, this seems to be the fastest way to\n *   > recurse without actually running into an infinite loop, which the\n *   > previous version did.\n *   >\n *   > Practically, a max of `2` is typically enough assuming a `Root` is\n *   > passed, but it doesn’t improve performance.\n *   > It gets higher with `List > ListItem > Table > TableRow > TableCell`.\n *   > Using up to `10` doesn’t hurt or help either.\n * @template {UnistNode} Tree\n *   Tree type.\n * @template {Uint} [Max=10]\n *   Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n *   Current depth.\n */\n\n/**\n * @callback Visitor\n *   Handle a node (matching `test`, if given).\n *\n *   Visitors are free to transform `node`.\n *   They can also transform `parent`.\n *\n *   Replacing `node` itself, if `SKIP` is not returned, still causes its\n *   descendants to be walked (which is a bug).\n *\n *   When adding or removing previous siblings of `node` (or next siblings, in\n *   case of reverse), the `Visitor` should return a new `Index` to specify the\n *   sibling to traverse after `node` is traversed.\n *   Adding or removing next siblings of `node` (or previous siblings, in case\n *   of reverse) is handled as expected without needing to return a new `Index`.\n *\n *   Removing the children property of `parent` still results in them being\n *   traversed.\n * @param {Visited} node\n *   Found node.\n * @param {Visited extends UnistNode ? number | undefined : never} index\n *   Index of `node` in `parent`.\n * @param {Ancestor extends UnistParent ? Ancestor | undefined : never} parent\n *   Parent of `node`.\n * @returns {VisitorResult}\n *   What to do next.\n *\n *   An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n *   An `Action` is treated as a tuple of `[Action]`.\n *\n *   Passing a tuple back only makes sense if the `Action` is `SKIP`.\n *   When the `Action` is `EXIT`, that action can be returned.\n *   When the `Action` is `CONTINUE`, `Index` can be returned.\n * @template {UnistNode} [Visited=UnistNode]\n *   Visited node type.\n * @template {UnistParent} [Ancestor=UnistParent]\n *   Ancestor type.\n */\n\n/**\n * @typedef {Visitor<Visited, Parent<Ancestor, Visited>>} BuildVisitorFromMatch\n *   Build a typed `Visitor` function from a node and all possible parents.\n *\n *   It will infer which values are passed as `node` and which as `parent`.\n * @template {UnistNode} Visited\n *   Node type.\n * @template {UnistParent} Ancestor\n *   Parent type.\n */\n\n/**\n * @typedef {(\n *   BuildVisitorFromMatch<\n *     Matches<Descendant, Check>,\n *     Extract<Descendant, UnistParent>\n *   >\n * )} BuildVisitorFromDescendants\n *   Build a typed `Visitor` function from a list of descendants and a test.\n *\n *   It will infer which values are passed as `node` and which as `parent`.\n * @template {UnistNode} Descendant\n *   Node type.\n * @template {Test} Check\n *   Test type.\n */\n\n/**\n * @typedef {(\n *   BuildVisitorFromDescendants<\n *     InclusiveDescendant<Tree>,\n *     Check\n *   >\n * )} BuildVisitor\n *   Build a typed `Visitor` function from a tree and a test.\n *\n *   It will infer which values are passed as `node` and which as `parent`.\n * @template {UnistNode} [Tree=UnistNode]\n *   Node type.\n * @template {Test} [Check=Test]\n *   Test type.\n */\n\nimport {visitParents} from 'unist-util-visit-parents'\n\nexport {CONTINUE, EXIT, SKIP} from 'unist-util-visit-parents'\n\n/**\n * Visit nodes.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @overload\n * @param {Tree} tree\n * @param {Check} check\n * @param {BuildVisitor<Tree, Check>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @overload\n * @param {Tree} tree\n * @param {BuildVisitor<Tree>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @param {UnistNode} tree\n *   Tree to traverse.\n * @param {Visitor | Test} testOrVisitor\n *   `unist-util-is`-compatible test (optional, omit to pass a visitor).\n * @param {Visitor | boolean | null | undefined} [visitorOrReverse]\n *   Handle each node (when test is omitted, pass `reverse`).\n * @param {boolean | null | undefined} [maybeReverse=false]\n *   Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns {undefined}\n *   Nothing.\n *\n * @template {UnistNode} Tree\n *   Node type.\n * @template {Test} Check\n *   `unist-util-is`-compatible test.\n */\nexport function visit(tree, testOrVisitor, visitorOrReverse, maybeReverse) {\n  /** @type {boolean | null | undefined} */\n  let reverse\n  /** @type {Test} */\n  let test\n  /** @type {Visitor} */\n  let visitor\n\n  if (\n    typeof testOrVisitor === 'function' &&\n    typeof visitorOrReverse !== 'function'\n  ) {\n    test = undefined\n    visitor = testOrVisitor\n    reverse = visitorOrReverse\n  } else {\n    // @ts-expect-error: assume the overload with test was given.\n    test = testOrVisitor\n    // @ts-expect-error: assume the overload with test was given.\n    visitor = visitorOrReverse\n    reverse = maybeReverse\n  }\n\n  visitParents(tree, test, overload, reverse)\n\n  /**\n   * @param {UnistNode} node\n   * @param {Array<UnistParent>} parents\n   */\n  function overload(node, parents) {\n    const parent = parents[parents.length - 1]\n    const index = parent ? parent.children.indexOf(node) : undefined\n    return visitor(node, index, parent)\n  }\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Heading} from 'mdast'\n */\n\nimport {EXIT, visit} from 'unist-util-visit'\nimport {toString} from 'mdast-util-to-string'\n\n/**\n * @param {Heading} node\n * @param {State} state\n * @returns {boolean}\n */\nexport function formatHeadingAsSetext(node, state) {\n  let literalWithBreak = false\n\n  // Look for literals with a line break.\n  // Note that this also\n  visit(node, function (node) {\n    if (\n      ('value' in node && /\\r?\\n|\\r/.test(node.value)) ||\n      node.type === 'break'\n    ) {\n      literalWithBreak = true\n      return EXIT\n    }\n  })\n\n  return Boolean(\n    (!node.depth || node.depth < 3) &&\n      toString(node) &&\n      (state.options.setext || literalWithBreak)\n  )\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Heading, Parents} from 'mdast'\n */\n\nimport {encodeCharacterReference} from '../util/encode-character-reference.js'\nimport {formatHeadingAsSetext} from '../util/format-heading-as-setext.js'\n\n/**\n * @param {Heading} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function heading(node, _, state, info) {\n  const rank = Math.max(Math.min(6, node.depth || 1), 1)\n  const tracker = state.createTracker(info)\n\n  if (formatHeadingAsSetext(node, state)) {\n    const exit = state.enter('headingSetext')\n    const subexit = state.enter('phrasing')\n    const value = state.containerPhrasing(node, {\n      ...tracker.current(),\n      before: '\\n',\n      after: '\\n'\n    })\n    subexit()\n    exit()\n\n    return (\n      value +\n      '\\n' +\n      (rank === 1 ? '=' : '-').repeat(\n        // The whole size…\n        value.length -\n          // Minus the position of the character after the last EOL (or\n          // 0 if there is none)…\n          (Math.max(value.lastIndexOf('\\r'), value.lastIndexOf('\\n')) + 1)\n      )\n    )\n  }\n\n  const sequence = '#'.repeat(rank)\n  const exit = state.enter('headingAtx')\n  const subexit = state.enter('phrasing')\n\n  // Note: for proper tracking, we should reset the output positions when there\n  // is no content returned, because then the space is not output.\n  // Practically, in that case, there is no content, so it doesn’t matter that\n  // we’ve tracked one too many characters.\n  tracker.move(sequence + ' ')\n\n  let value = state.containerPhrasing(node, {\n    before: '# ',\n    after: '\\n',\n    ...tracker.current()\n  })\n\n  if (/^[\\t ]/.test(value)) {\n    // To do: what effect has the character reference on tracking?\n    value = encodeCharacterReference(value.charCodeAt(0)) + value.slice(1)\n  }\n\n  value = value ? sequence + ' ' + value : sequence\n\n  if (state.options.closeAtx) {\n    value += ' ' + sequence\n  }\n\n  subexit()\n  exit()\n\n  return value\n}\n","/**\n * @import {Html} from 'mdast'\n */\n\nhtml.peek = htmlPeek\n\n/**\n * @param {Html} node\n * @returns {string}\n */\nexport function html(node) {\n  return node.value || ''\n}\n\n/**\n * @returns {string}\n */\nfunction htmlPeek() {\n  return '<'\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Image, Parents} from 'mdast'\n */\n\nimport {checkQuote} from '../util/check-quote.js'\n\nimage.peek = imagePeek\n\n/**\n * @param {Image} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function image(node, _, state, info) {\n  const quote = checkQuote(state)\n  const suffix = quote === '\"' ? 'Quote' : 'Apostrophe'\n  const exit = state.enter('image')\n  let subexit = state.enter('label')\n  const tracker = state.createTracker(info)\n  let value = tracker.move('![')\n  value += tracker.move(\n    state.safe(node.alt, {before: value, after: ']', ...tracker.current()})\n  )\n  value += tracker.move('](')\n\n  subexit()\n\n  if (\n    // If there’s no url but there is a title…\n    (!node.url && node.title) ||\n    // If there are control characters or whitespace.\n    /[\\0- \\u007F]/.test(node.url)\n  ) {\n    subexit = state.enter('destinationLiteral')\n    value += tracker.move('<')\n    value += tracker.move(\n      state.safe(node.url, {before: value, after: '>', ...tracker.current()})\n    )\n    value += tracker.move('>')\n  } else {\n    // No whitespace, raw is prettier.\n    subexit = state.enter('destinationRaw')\n    value += tracker.move(\n      state.safe(node.url, {\n        before: value,\n        after: node.title ? ' ' : ')',\n        ...tracker.current()\n      })\n    )\n  }\n\n  subexit()\n\n  if (node.title) {\n    subexit = state.enter(`title${suffix}`)\n    value += tracker.move(' ' + quote)\n    value += tracker.move(\n      state.safe(node.title, {\n        before: value,\n        after: quote,\n        ...tracker.current()\n      })\n    )\n    value += tracker.move(quote)\n    subexit()\n  }\n\n  value += tracker.move(')')\n  exit()\n\n  return value\n}\n\n/**\n * @returns {string}\n */\nfunction imagePeek() {\n  return '!'\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {ImageReference, Parents} from 'mdast'\n */\n\nimageReference.peek = imageReferencePeek\n\n/**\n * @param {ImageReference} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function imageReference(node, _, state, info) {\n  const type = node.referenceType\n  const exit = state.enter('imageReference')\n  let subexit = state.enter('label')\n  const tracker = state.createTracker(info)\n  let value = tracker.move('![')\n  const alt = state.safe(node.alt, {\n    before: value,\n    after: ']',\n    ...tracker.current()\n  })\n  value += tracker.move(alt + '][')\n\n  subexit()\n  // Hide the fact that we’re in phrasing, because escapes don’t work.\n  const stack = state.stack\n  state.stack = []\n  subexit = state.enter('reference')\n  // Note: for proper tracking, we should reset the output positions when we end\n  // up making a `shortcut` reference, because then there is no brace output.\n  // Practically, in that case, there is no content, so it doesn’t matter that\n  // we’ve tracked one too many characters.\n  const reference = state.safe(state.associationId(node), {\n    before: value,\n    after: ']',\n    ...tracker.current()\n  })\n  subexit()\n  state.stack = stack\n  exit()\n\n  if (type === 'full' || !alt || alt !== reference) {\n    value += tracker.move(reference + ']')\n  } else if (type === 'shortcut') {\n    // Remove the unwanted `[`.\n    value = value.slice(0, -1)\n  } else {\n    value += tracker.move(']')\n  }\n\n  return value\n}\n\n/**\n * @returns {string}\n */\nfunction imageReferencePeek() {\n  return '!'\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {InlineCode, Parents} from 'mdast'\n */\n\ninlineCode.peek = inlineCodePeek\n\n/**\n * @param {InlineCode} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @returns {string}\n */\nexport function inlineCode(node, _, state) {\n  let value = node.value || ''\n  let sequence = '`'\n  let index = -1\n\n  // If there is a single grave accent on its own in the code, use a fence of\n  // two.\n  // If there are two in a row, use one.\n  while (new RegExp('(^|[^`])' + sequence + '([^`]|$)').test(value)) {\n    sequence += '`'\n  }\n\n  // If this is not just spaces or eols (tabs don’t count), and either the\n  // first or last character are a space, eol, or tick, then pad with spaces.\n  if (\n    /[^ \\r\\n]/.test(value) &&\n    ((/^[ \\r\\n]/.test(value) && /[ \\r\\n]$/.test(value)) || /^`|`$/.test(value))\n  ) {\n    value = ' ' + value + ' '\n  }\n\n  // We have a potential problem: certain characters after eols could result in\n  // blocks being seen.\n  // For example, if someone injected the string `'\\n# b'`, then that would\n  // result in an ATX heading.\n  // We can’t escape characters in `inlineCode`, but because eols are\n  // transformed to spaces when going from markdown to HTML anyway, we can swap\n  // them out.\n  while (++index < state.unsafe.length) {\n    const pattern = state.unsafe[index]\n    const expression = state.compilePattern(pattern)\n    /** @type {RegExpExecArray | null} */\n    let match\n\n    // Only look for `atBreak`s.\n    // Btw: note that `atBreak` patterns will always start the regex at LF or\n    // CR.\n    if (!pattern.atBreak) continue\n\n    while ((match = expression.exec(value))) {\n      let position = match.index\n\n      // Support CRLF (patterns only look for one of the characters).\n      if (\n        value.charCodeAt(position) === 10 /* `\\n` */ &&\n        value.charCodeAt(position - 1) === 13 /* `\\r` */\n      ) {\n        position--\n      }\n\n      value = value.slice(0, position) + ' ' + value.slice(match.index + 1)\n    }\n  }\n\n  return sequence + value + sequence\n}\n\n/**\n * @returns {string}\n */\nfunction inlineCodePeek() {\n  return '`'\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Link} from 'mdast'\n */\n\nimport {toString} from 'mdast-util-to-string'\n\n/**\n * @param {Link} node\n * @param {State} state\n * @returns {boolean}\n */\nexport function formatLinkAsAutolink(node, state) {\n  const raw = toString(node)\n\n  return Boolean(\n    !state.options.resourceLink &&\n      // If there’s a url…\n      node.url &&\n      // And there’s a no title…\n      !node.title &&\n      // And the content of `node` is a single text node…\n      node.children &&\n      node.children.length === 1 &&\n      node.children[0].type === 'text' &&\n      // And if the url is the same as the content…\n      (raw === node.url || 'mailto:' + raw === node.url) &&\n      // And that starts w/ a protocol…\n      /^[a-z][a-z+.-]+:/i.test(node.url) &&\n      // And that doesn’t contain ASCII control codes (character escapes and\n      // references don’t work), space, or angle brackets…\n      !/[\\0- <>\\u007F]/.test(node.url)\n  )\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Link, Parents} from 'mdast'\n * @import {Exit} from '../types.js'\n */\n\nimport {checkQuote} from '../util/check-quote.js'\nimport {formatLinkAsAutolink} from '../util/format-link-as-autolink.js'\n\nlink.peek = linkPeek\n\n/**\n * @param {Link} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function link(node, _, state, info) {\n  const quote = checkQuote(state)\n  const suffix = quote === '\"' ? 'Quote' : 'Apostrophe'\n  const tracker = state.createTracker(info)\n  /** @type {Exit} */\n  let exit\n  /** @type {Exit} */\n  let subexit\n\n  if (formatLinkAsAutolink(node, state)) {\n    // Hide the fact that we’re in phrasing, because escapes don’t work.\n    const stack = state.stack\n    state.stack = []\n    exit = state.enter('autolink')\n    let value = tracker.move('<')\n    value += tracker.move(\n      state.containerPhrasing(node, {\n        before: value,\n        after: '>',\n        ...tracker.current()\n      })\n    )\n    value += tracker.move('>')\n    exit()\n    state.stack = stack\n    return value\n  }\n\n  exit = state.enter('link')\n  subexit = state.enter('label')\n  let value = tracker.move('[')\n  value += tracker.move(\n    state.containerPhrasing(node, {\n      before: value,\n      after: '](',\n      ...tracker.current()\n    })\n  )\n  value += tracker.move('](')\n  subexit()\n\n  if (\n    // If there’s no url but there is a title…\n    (!node.url && node.title) ||\n    // If there are control characters or whitespace.\n    /[\\0- \\u007F]/.test(node.url)\n  ) {\n    subexit = state.enter('destinationLiteral')\n    value += tracker.move('<')\n    value += tracker.move(\n      state.safe(node.url, {before: value, after: '>', ...tracker.current()})\n    )\n    value += tracker.move('>')\n  } else {\n    // No whitespace, raw is prettier.\n    subexit = state.enter('destinationRaw')\n    value += tracker.move(\n      state.safe(node.url, {\n        before: value,\n        after: node.title ? ' ' : ')',\n        ...tracker.current()\n      })\n    )\n  }\n\n  subexit()\n\n  if (node.title) {\n    subexit = state.enter(`title${suffix}`)\n    value += tracker.move(' ' + quote)\n    value += tracker.move(\n      state.safe(node.title, {\n        before: value,\n        after: quote,\n        ...tracker.current()\n      })\n    )\n    value += tracker.move(quote)\n    subexit()\n  }\n\n  value += tracker.move(')')\n\n  exit()\n  return value\n}\n\n/**\n * @param {Link} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @returns {string}\n */\nfunction linkPeek(node, _, state) {\n  return formatLinkAsAutolink(node, state) ? '<' : '['\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {LinkReference, Parents} from 'mdast'\n */\n\nlinkReference.peek = linkReferencePeek\n\n/**\n * @param {LinkReference} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function linkReference(node, _, state, info) {\n  const type = node.referenceType\n  const exit = state.enter('linkReference')\n  let subexit = state.enter('label')\n  const tracker = state.createTracker(info)\n  let value = tracker.move('[')\n  const text = state.containerPhrasing(node, {\n    before: value,\n    after: ']',\n    ...tracker.current()\n  })\n  value += tracker.move(text + '][')\n\n  subexit()\n  // Hide the fact that we’re in phrasing, because escapes don’t work.\n  const stack = state.stack\n  state.stack = []\n  subexit = state.enter('reference')\n  // Note: for proper tracking, we should reset the output positions when we end\n  // up making a `shortcut` reference, because then there is no brace output.\n  // Practically, in that case, there is no content, so it doesn’t matter that\n  // we’ve tracked one too many characters.\n  const reference = state.safe(state.associationId(node), {\n    before: value,\n    after: ']',\n    ...tracker.current()\n  })\n  subexit()\n  state.stack = stack\n  exit()\n\n  if (type === 'full' || !text || text !== reference) {\n    value += tracker.move(reference + ']')\n  } else if (type === 'shortcut') {\n    // Remove the unwanted `[`.\n    value = value.slice(0, -1)\n  } else {\n    value += tracker.move(']')\n  }\n\n  return value\n}\n\n/**\n * @returns {string}\n */\nfunction linkReferencePeek() {\n  return '['\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['bullet'], null | undefined>}\n */\nexport function checkBullet(state) {\n  const marker = state.options.bullet || '*'\n\n  if (marker !== '*' && marker !== '+' && marker !== '-') {\n    throw new Error(\n      'Cannot serialize items with `' +\n        marker +\n        '` for `options.bullet`, expected `*`, `+`, or `-`'\n    )\n  }\n\n  return marker\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\nimport {checkBullet} from './check-bullet.js'\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['bullet'], null | undefined>}\n */\nexport function checkBulletOther(state) {\n  const bullet = checkBullet(state)\n  const bulletOther = state.options.bulletOther\n\n  if (!bulletOther) {\n    return bullet === '*' ? '-' : '*'\n  }\n\n  if (bulletOther !== '*' && bulletOther !== '+' && bulletOther !== '-') {\n    throw new Error(\n      'Cannot serialize items with `' +\n        bulletOther +\n        '` for `options.bulletOther`, expected `*`, `+`, or `-`'\n    )\n  }\n\n  if (bulletOther === bullet) {\n    throw new Error(\n      'Expected `bullet` (`' +\n        bullet +\n        '`) and `bulletOther` (`' +\n        bulletOther +\n        '`) to be different'\n    )\n  }\n\n  return bulletOther\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['bulletOrdered'], null | undefined>}\n */\nexport function checkBulletOrdered(state) {\n  const marker = state.options.bulletOrdered || '.'\n\n  if (marker !== '.' && marker !== ')') {\n    throw new Error(\n      'Cannot serialize items with `' +\n        marker +\n        '` for `options.bulletOrdered`, expected `.` or `)`'\n    )\n  }\n\n  return marker\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['rule'], null | undefined>}\n */\nexport function checkRule(state) {\n  const marker = state.options.rule || '*'\n\n  if (marker !== '*' && marker !== '-' && marker !== '_') {\n    throw new Error(\n      'Cannot serialize rules with `' +\n        marker +\n        '` for `options.rule`, expected `*`, `-`, or `_`'\n    )\n  }\n\n  return marker\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {List, Parents} from 'mdast'\n */\n\nimport {checkBullet} from '../util/check-bullet.js'\nimport {checkBulletOther} from '../util/check-bullet-other.js'\nimport {checkBulletOrdered} from '../util/check-bullet-ordered.js'\nimport {checkRule} from '../util/check-rule.js'\n\n/**\n * @param {List} node\n * @param {Parents | undefined} parent\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function list(node, parent, state, info) {\n  const exit = state.enter('list')\n  const bulletCurrent = state.bulletCurrent\n  /** @type {string} */\n  let bullet = node.ordered ? checkBulletOrdered(state) : checkBullet(state)\n  /** @type {string} */\n  const bulletOther = node.ordered\n    ? bullet === '.'\n      ? ')'\n      : '.'\n    : checkBulletOther(state)\n  let useDifferentMarker =\n    parent && state.bulletLastUsed ? bullet === state.bulletLastUsed : false\n\n  if (!node.ordered) {\n    const firstListItem = node.children ? node.children[0] : undefined\n\n    // If there’s an empty first list item directly in two list items,\n    // we have to use a different bullet:\n    //\n    // ```markdown\n    // * - *\n    // ```\n    //\n    // …because otherwise it would become one big thematic break.\n    if (\n      // Bullet could be used as a thematic break marker:\n      (bullet === '*' || bullet === '-') &&\n      // Empty first list item:\n      firstListItem &&\n      (!firstListItem.children || !firstListItem.children[0]) &&\n      // Directly in two other list items:\n      state.stack[state.stack.length - 1] === 'list' &&\n      state.stack[state.stack.length - 2] === 'listItem' &&\n      state.stack[state.stack.length - 3] === 'list' &&\n      state.stack[state.stack.length - 4] === 'listItem' &&\n      // That are each the first child.\n      state.indexStack[state.indexStack.length - 1] === 0 &&\n      state.indexStack[state.indexStack.length - 2] === 0 &&\n      state.indexStack[state.indexStack.length - 3] === 0\n    ) {\n      useDifferentMarker = true\n    }\n\n    // If there’s a thematic break at the start of the first list item,\n    // we have to use a different bullet:\n    //\n    // ```markdown\n    // * ---\n    // ```\n    //\n    // …because otherwise it would become one big thematic break.\n    if (checkRule(state) === bullet && firstListItem) {\n      let index = -1\n\n      while (++index < node.children.length) {\n        const item = node.children[index]\n\n        if (\n          item &&\n          item.type === 'listItem' &&\n          item.children &&\n          item.children[0] &&\n          item.children[0].type === 'thematicBreak'\n        ) {\n          useDifferentMarker = true\n          break\n        }\n      }\n    }\n  }\n\n  if (useDifferentMarker) {\n    bullet = bulletOther\n  }\n\n  state.bulletCurrent = bullet\n  const value = state.containerFlow(node, info)\n  state.bulletLastUsed = bullet\n  state.bulletCurrent = bulletCurrent\n  exit()\n  return value\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['listItemIndent'], null | undefined>}\n */\nexport function checkListItemIndent(state) {\n  const style = state.options.listItemIndent || 'one'\n\n  if (style !== 'tab' && style !== 'one' && style !== 'mixed') {\n    throw new Error(\n      'Cannot serialize items with `' +\n        style +\n        '` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`'\n    )\n  }\n\n  return style\n}\n","/**\n * @import {Info, Map, State} from 'mdast-util-to-markdown'\n * @import {ListItem, Parents} from 'mdast'\n */\n\nimport {checkBullet} from '../util/check-bullet.js'\nimport {checkListItemIndent} from '../util/check-list-item-indent.js'\n\n/**\n * @param {ListItem} node\n * @param {Parents | undefined} parent\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function listItem(node, parent, state, info) {\n  const listItemIndent = checkListItemIndent(state)\n  let bullet = state.bulletCurrent || checkBullet(state)\n\n  // Add the marker value for ordered lists.\n  if (parent && parent.type === 'list' && parent.ordered) {\n    bullet =\n      (typeof parent.start === 'number' && parent.start > -1\n        ? parent.start\n        : 1) +\n      (state.options.incrementListMarker === false\n        ? 0\n        : parent.children.indexOf(node)) +\n      bullet\n  }\n\n  let size = bullet.length + 1\n\n  if (\n    listItemIndent === 'tab' ||\n    (listItemIndent === 'mixed' &&\n      ((parent && parent.type === 'list' && parent.spread) || node.spread))\n  ) {\n    size = Math.ceil(size / 4) * 4\n  }\n\n  const tracker = state.createTracker(info)\n  tracker.move(bullet + ' '.repeat(size - bullet.length))\n  tracker.shift(size)\n  const exit = state.enter('listItem')\n  const value = state.indentLines(\n    state.containerFlow(node, tracker.current()),\n    map\n  )\n  exit()\n\n  return value\n\n  /** @type {Map} */\n  function map(line, index, blank) {\n    if (index) {\n      return (blank ? '' : ' '.repeat(size)) + line\n    }\n\n    return (blank ? bullet : bullet + ' '.repeat(size - bullet.length)) + line\n  }\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Paragraph, Parents} from 'mdast'\n */\n\n/**\n * @param {Paragraph} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function paragraph(node, _, state, info) {\n  const exit = state.enter('paragraph')\n  const subexit = state.enter('phrasing')\n  const value = state.containerPhrasing(node, info)\n  subexit()\n  exit()\n  return value\n}\n","/**\n * @typedef {import('mdast').Html} Html\n * @typedef {import('mdast').PhrasingContent} PhrasingContent\n */\n\nimport {convert} from 'unist-util-is'\n\n/**\n * Check if the given value is *phrasing content*.\n *\n * > 👉 **Note**: Excludes `html`, which can be both phrasing or flow.\n *\n * @param node\n *   Thing to check, typically `Node`.\n * @returns\n *   Whether `value` is phrasing content.\n */\n\nexport const phrasing =\n  /** @type {(node?: unknown) => node is Exclude<PhrasingContent, Html>} */\n  (\n    convert([\n      'break',\n      'delete',\n      'emphasis',\n      // To do: next major: removed since footnotes were added to GFM.\n      'footnote',\n      'footnoteReference',\n      'image',\n      'imageReference',\n      'inlineCode',\n      // Enabled by `mdast-util-math`:\n      'inlineMath',\n      'link',\n      'linkReference',\n      // Enabled by `mdast-util-mdx`:\n      'mdxJsxTextElement',\n      // Enabled by `mdast-util-mdx`:\n      'mdxTextExpression',\n      'strong',\n      'text',\n      // Enabled by `mdast-util-directive`:\n      'textDirective'\n    ])\n  )\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Parents, Root} from 'mdast'\n */\n\nimport {phrasing} from 'mdast-util-phrasing'\n\n/**\n * @param {Root} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function root(node, _, state, info) {\n  // Note: `html` nodes are ambiguous.\n  const hasPhrasing = node.children.some(function (d) {\n    return phrasing(d)\n  })\n\n  const container = hasPhrasing ? state.containerPhrasing : state.containerFlow\n  return container.call(state, node, info)\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['strong'], null | undefined>}\n */\nexport function checkStrong(state) {\n  const marker = state.options.strong || '*'\n\n  if (marker !== '*' && marker !== '_') {\n    throw new Error(\n      'Cannot serialize strong with `' +\n        marker +\n        '` for `options.strong`, expected `*`, or `_`'\n    )\n  }\n\n  return marker\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Parents, Strong} from 'mdast'\n */\n\nimport {checkStrong} from '../util/check-strong.js'\nimport {encodeCharacterReference} from '../util/encode-character-reference.js'\nimport {encodeInfo} from '../util/encode-info.js'\n\nstrong.peek = strongPeek\n\n/**\n * @param {Strong} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function strong(node, _, state, info) {\n  const marker = checkStrong(state)\n  const exit = state.enter('strong')\n  const tracker = state.createTracker(info)\n  const before = tracker.move(marker + marker)\n\n  let between = tracker.move(\n    state.containerPhrasing(node, {\n      after: marker,\n      before,\n      ...tracker.current()\n    })\n  )\n  const betweenHead = between.charCodeAt(0)\n  const open = encodeInfo(\n    info.before.charCodeAt(info.before.length - 1),\n    betweenHead,\n    marker\n  )\n\n  if (open.inside) {\n    between = encodeCharacterReference(betweenHead) + between.slice(1)\n  }\n\n  const betweenTail = between.charCodeAt(between.length - 1)\n  const close = encodeInfo(info.after.charCodeAt(0), betweenTail, marker)\n\n  if (close.inside) {\n    between = between.slice(0, -1) + encodeCharacterReference(betweenTail)\n  }\n\n  const after = tracker.move(marker + marker)\n\n  exit()\n\n  state.attentionEncodeSurroundingInfo = {\n    after: close.outside,\n    before: open.outside\n  }\n  return before + between + after\n}\n\n/**\n * @param {Strong} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @returns {string}\n */\nfunction strongPeek(_, _1, state) {\n  return state.options.strong || '*'\n}\n","/**\n * @import {Info, State} from 'mdast-util-to-markdown'\n * @import {Parents, Text} from 'mdast'\n */\n\n/**\n * @param {Text} node\n * @param {Parents | undefined} _\n * @param {State} state\n * @param {Info} info\n * @returns {string}\n */\nexport function text(node, _, state, info) {\n  return state.safe(node.value, info)\n}\n","/**\n * @import {Options, State} from 'mdast-util-to-markdown'\n */\n\n/**\n * @param {State} state\n * @returns {Exclude<Options['ruleRepetition'], null | undefined>}\n */\nexport function checkRuleRepetition(state) {\n  const repetition = state.options.ruleRepetition || 3\n\n  if (repetition < 3) {\n    throw new Error(\n      'Cannot serialize rules with repetition `' +\n        repetition +\n        '` for `options.ruleRepetition`, expected `3` or more'\n    )\n  }\n\n  return repetition\n}\n","/**\n * @import {State} from 'mdast-util-to-markdown'\n * @import {Parents, ThematicBreak} from 'mdast'\n */\n\nimport {checkRuleRepetition} from '../util/check-rule-repetition.js'\nimport {checkRule} from '../util/check-rule.js'\n\n/**\n * @param {ThematicBreak} _\n * @param {Parents | undefined} _1\n * @param {State} state\n * @returns {string}\n */\nexport function thematicBreak(_, _1, state) {\n  const value = (\n    checkRule(state) + (state.options.ruleSpaces ? ' ' : '')\n  ).repeat(checkRuleRepetition(state))\n\n  return state.options.ruleSpaces ? value.slice(0, -1) : value\n}\n","import {blockquote} from './blockquote.js'\nimport {hardBreak} from './break.js'\nimport {code} from './code.js'\nimport {definition} from './definition.js'\nimport {emphasis} from './emphasis.js'\nimport {heading} from './heading.js'\nimport {html} from './html.js'\nimport {image} from './image.js'\nimport {imageReference} from './image-reference.js'\nimport {inlineCode} from './inline-code.js'\nimport {link} from './link.js'\nimport {linkReference} from './link-reference.js'\nimport {list} from './list.js'\nimport {listItem} from './list-item.js'\nimport {paragraph} from './paragraph.js'\nimport {root} from './root.js'\nimport {strong} from './strong.js'\nimport {text} from './text.js'\nimport {thematicBreak} from './thematic-break.js'\n\n/**\n * Default (CommonMark) handlers.\n */\nexport const handle = {\n  blockquote,\n  break: hardBreak,\n  code,\n  definition,\n  emphasis,\n  hardBreak,\n  heading,\n  html,\n  image,\n  imageReference,\n  inlineCode,\n  link,\n  linkReference,\n  list,\n  listItem,\n  paragraph,\n  root,\n  strong,\n  text,\n  thematicBreak\n}\n","/**\n * @typedef {import('mdast').InlineCode} InlineCode\n * @typedef {import('mdast').Table} Table\n * @typedef {import('mdast').TableCell} TableCell\n * @typedef {import('mdast').TableRow} TableRow\n *\n * @typedef {import('markdown-table').Options} MarkdownTableOptions\n *\n * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext\n * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension\n * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle\n *\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension\n * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').State} State\n * @typedef {import('mdast-util-to-markdown').Info} Info\n */\n\n/**\n * @typedef Options\n *   Configuration.\n * @property {boolean | null | undefined} [tableCellPadding=true]\n *   Whether to add a space of padding between delimiters and cells (default:\n *   `true`).\n * @property {boolean | null | undefined} [tablePipeAlign=true]\n *   Whether to align the delimiters (default: `true`).\n * @property {MarkdownTableOptions['stringLength'] | null | undefined} [stringLength]\n *   Function to detect the length of table cell content, used when aligning\n *   the delimiters between cells (optional).\n */\n\nimport {ok as assert} from 'devlop'\nimport {markdownTable} from 'markdown-table'\nimport {defaultHandlers} from 'mdast-util-to-markdown'\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM tables in\n * markdown.\n *\n * @returns {FromMarkdownExtension}\n *   Extension for `mdast-util-from-markdown` to enable GFM tables.\n */\nexport function gfmTableFromMarkdown() {\n  return {\n    enter: {\n      table: enterTable,\n      tableData: enterCell,\n      tableHeader: enterCell,\n      tableRow: enterRow\n    },\n    exit: {\n      codeText: exitCodeText,\n      table: exitTable,\n      tableData: exit,\n      tableHeader: exit,\n      tableRow: exit\n    }\n  }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterTable(token) {\n  const align = token._align\n  assert(align, 'expected `_align` on table')\n  this.enter(\n    {\n      type: 'table',\n      align: align.map(function (d) {\n        return d === 'none' ? null : d\n      }),\n      children: []\n    },\n    token\n  )\n  this.data.inTable = true\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitTable(token) {\n  this.exit(token)\n  this.data.inTable = undefined\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterRow(token) {\n  this.enter({type: 'tableRow', children: []}, token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exit(token) {\n  this.exit(token)\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction enterCell(token) {\n  this.enter({type: 'tableCell', children: []}, token)\n}\n\n// Overwrite the default code text data handler to unescape escaped pipes when\n// they are in tables.\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitCodeText(token) {\n  let value = this.resume()\n\n  if (this.data.inTable) {\n    value = value.replace(/\\\\([\\\\|])/g, replace)\n  }\n\n  const node = this.stack[this.stack.length - 1]\n  assert(node.type === 'inlineCode')\n  node.value = value\n  this.exit(token)\n}\n\n/**\n * @param {string} $0\n * @param {string} $1\n * @returns {string}\n */\nfunction replace($0, $1) {\n  // Pipes work, backslashes don’t (but can’t escape pipes).\n  return $1 === '|' ? $1 : $0\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM tables in\n * markdown.\n *\n * @param {Options | null | undefined} [options]\n *   Configuration.\n * @returns {ToMarkdownExtension}\n *   Extension for `mdast-util-to-markdown` to enable GFM tables.\n */\nexport function gfmTableToMarkdown(options) {\n  const settings = options || {}\n  const padding = settings.tableCellPadding\n  const alignDelimiters = settings.tablePipeAlign\n  const stringLength = settings.stringLength\n  const around = padding ? ' ' : '|'\n\n  return {\n    unsafe: [\n      {character: '\\r', inConstruct: 'tableCell'},\n      {character: '\\n', inConstruct: 'tableCell'},\n      // A pipe, when followed by a tab or space (padding), or a dash or colon\n      // (unpadded delimiter row), could result in a table.\n      {atBreak: true, character: '|', after: '[\\t :-]'},\n      // A pipe in a cell must be encoded.\n      {character: '|', inConstruct: 'tableCell'},\n      // A colon must be followed by a dash, in which case it could start a\n      // delimiter row.\n      {atBreak: true, character: ':', after: '-'},\n      // A delimiter row can also start with a dash, when followed by more\n      // dashes, a colon, or a pipe.\n      // This is a stricter version than the built in check for lists, thematic\n      // breaks, and setex heading underlines though:\n      // <https://github.com/syntax-tree/mdast-util-to-markdown/blob/51a2038/lib/unsafe.js#L57>\n      {atBreak: true, character: '-', after: '[:|-]'}\n    ],\n    handlers: {\n      inlineCode: inlineCodeWithTable,\n      table: handleTable,\n      tableCell: handleTableCell,\n      tableRow: handleTableRow\n    }\n  }\n\n  /**\n   * @type {ToMarkdownHandle}\n   * @param {Table} node\n   */\n  function handleTable(node, _, state, info) {\n    return serializeData(handleTableAsData(node, state, info), node.align)\n  }\n\n  /**\n   * This function isn’t really used normally, because we handle rows at the\n   * table level.\n   * But, if someone passes in a table row, this ensures we make somewhat sense.\n   *\n   * @type {ToMarkdownHandle}\n   * @param {TableRow} node\n   */\n  function handleTableRow(node, _, state, info) {\n    const row = handleTableRowAsData(node, state, info)\n    const value = serializeData([row])\n    // `markdown-table` will always add an align row\n    return value.slice(0, value.indexOf('\\n'))\n  }\n\n  /**\n   * @type {ToMarkdownHandle}\n   * @param {TableCell} node\n   */\n  function handleTableCell(node, _, state, info) {\n    const exit = state.enter('tableCell')\n    const subexit = state.enter('phrasing')\n    const value = state.containerPhrasing(node, {\n      ...info,\n      before: around,\n      after: around\n    })\n    subexit()\n    exit()\n    return value\n  }\n\n  /**\n   * @param {Array<Array<string>>} matrix\n   * @param {Array<string | null | undefined> | null | undefined} [align]\n   */\n  function serializeData(matrix, align) {\n    return markdownTable(matrix, {\n      align,\n      // @ts-expect-error: `markdown-table` types should support `null`.\n      alignDelimiters,\n      // @ts-expect-error: `markdown-table` types should support `null`.\n      padding,\n      // @ts-expect-error: `markdown-table` types should support `null`.\n      stringLength\n    })\n  }\n\n  /**\n   * @param {Table} node\n   * @param {State} state\n   * @param {Info} info\n   */\n  function handleTableAsData(node, state, info) {\n    const children = node.children\n    let index = -1\n    /** @type {Array<Array<string>>} */\n    const result = []\n    const subexit = state.enter('table')\n\n    while (++index < children.length) {\n      result[index] = handleTableRowAsData(children[index], state, info)\n    }\n\n    subexit()\n\n    return result\n  }\n\n  /**\n   * @param {TableRow} node\n   * @param {State} state\n   * @param {Info} info\n   */\n  function handleTableRowAsData(node, state, info) {\n    const children = node.children\n    let index = -1\n    /** @type {Array<string>} */\n    const result = []\n    const subexit = state.enter('tableRow')\n\n    while (++index < children.length) {\n      // Note: the positional info as used here is incorrect.\n      // Making it correct would be impossible due to aligning cells?\n      // And it would need copy/pasting `markdown-table` into this project.\n      result[index] = handleTableCell(children[index], node, state, info)\n    }\n\n    subexit()\n\n    return result\n  }\n\n  /**\n   * @type {ToMarkdownHandle}\n   * @param {InlineCode} node\n   */\n  function inlineCodeWithTable(node, parent, state) {\n    let value = defaultHandlers.inlineCode(node, parent, state)\n\n    if (state.stack.includes('tableCell')) {\n      value = value.replace(/\\|/g, '\\\\$&')\n    }\n\n    return value\n  }\n}\n","/**\n * @typedef {import('mdast').ListItem} ListItem\n * @typedef {import('mdast').Paragraph} Paragraph\n * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext\n * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension\n * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension\n * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle\n */\n\nimport {ok as assert} from 'devlop'\nimport {defaultHandlers} from 'mdast-util-to-markdown'\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM task\n * list items in markdown.\n *\n * @returns {FromMarkdownExtension}\n *   Extension for `mdast-util-from-markdown` to enable GFM task list items.\n */\nexport function gfmTaskListItemFromMarkdown() {\n  return {\n    exit: {\n      taskListCheckValueChecked: exitCheck,\n      taskListCheckValueUnchecked: exitCheck,\n      paragraph: exitParagraphWithTaskListItem\n    }\n  }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM task list\n * items in markdown.\n *\n * @returns {ToMarkdownExtension}\n *   Extension for `mdast-util-to-markdown` to enable GFM task list items.\n */\nexport function gfmTaskListItemToMarkdown() {\n  return {\n    unsafe: [{atBreak: true, character: '-', after: '[:|-]'}],\n    handlers: {listItem: listItemWithTaskListItem}\n  }\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitCheck(token) {\n  // We’re always in a paragraph, in a list item.\n  const node = this.stack[this.stack.length - 2]\n  assert(node.type === 'listItem')\n  node.checked = token.type === 'taskListCheckValueChecked'\n}\n\n/**\n * @this {CompileContext}\n * @type {FromMarkdownHandle}\n */\nfunction exitParagraphWithTaskListItem(token) {\n  const parent = this.stack[this.stack.length - 2]\n\n  if (\n    parent &&\n    parent.type === 'listItem' &&\n    typeof parent.checked === 'boolean'\n  ) {\n    const node = this.stack[this.stack.length - 1]\n    assert(node.type === 'paragraph')\n    const head = node.children[0]\n\n    if (head && head.type === 'text') {\n      const siblings = parent.children\n      let index = -1\n      /** @type {Paragraph | undefined} */\n      let firstParaghraph\n\n      while (++index < siblings.length) {\n        const sibling = siblings[index]\n        if (sibling.type === 'paragraph') {\n          firstParaghraph = sibling\n          break\n        }\n      }\n\n      if (firstParaghraph === node) {\n        // Must start with a space or a tab.\n        head.value = head.value.slice(1)\n\n        if (head.value.length === 0) {\n          node.children.shift()\n        } else if (\n          node.position &&\n          head.position &&\n          typeof head.position.start.offset === 'number'\n        ) {\n          head.position.start.column++\n          head.position.start.offset++\n          node.position.start = Object.assign({}, head.position.start)\n        }\n      }\n    }\n  }\n\n  this.exit(token)\n}\n\n/**\n * @type {ToMarkdownHandle}\n * @param {ListItem} node\n */\nfunction listItemWithTaskListItem(node, parent, state, info) {\n  const head = node.children[0]\n  const checkable =\n    typeof node.checked === 'boolean' && head && head.type === 'paragraph'\n  const checkbox = '[' + (node.checked ? 'x' : ' ') + '] '\n  const tracker = state.createTracker(info)\n\n  if (checkable) {\n    tracker.move(checkbox)\n  }\n\n  let value = defaultHandlers.listItem(node, parent, state, {\n    ...info,\n    ...tracker.current()\n  })\n\n  if (checkable) {\n    value = value.replace(/^(?:[*+-]|\\d+\\.)([\\r\\n]| {1,3})/, check)\n  }\n\n  return value\n\n  /**\n   * @param {string} $0\n   * @returns {string}\n   */\n  function check($0) {\n    return $0 + checkbox\n  }\n}\n","/**\n * @import {Extension as FromMarkdownExtension} from 'mdast-util-from-markdown'\n * @import {Options} from 'mdast-util-gfm'\n * @import {Options as ToMarkdownExtension} from 'mdast-util-to-markdown'\n */\n\nimport {\n  gfmAutolinkLiteralFromMarkdown,\n  gfmAutolinkLiteralToMarkdown\n} from 'mdast-util-gfm-autolink-literal'\nimport {\n  gfmFootnoteFromMarkdown,\n  gfmFootnoteToMarkdown\n} from 'mdast-util-gfm-footnote'\nimport {\n  gfmStrikethroughFromMarkdown,\n  gfmStrikethroughToMarkdown\n} from 'mdast-util-gfm-strikethrough'\nimport {gfmTableFromMarkdown, gfmTableToMarkdown} from 'mdast-util-gfm-table'\nimport {\n  gfmTaskListItemFromMarkdown,\n  gfmTaskListItemToMarkdown\n} from 'mdast-util-gfm-task-list-item'\n\n/**\n * Create an extension for `mdast-util-from-markdown` to enable GFM (autolink\n * literals, footnotes, strikethrough, tables, tasklists).\n *\n * @returns {Array<FromMarkdownExtension>}\n *   Extension for `mdast-util-from-markdown` to enable GFM (autolink literals,\n *   footnotes, strikethrough, tables, tasklists).\n */\nexport function gfmFromMarkdown() {\n  return [\n    gfmAutolinkLiteralFromMarkdown(),\n    gfmFootnoteFromMarkdown(),\n    gfmStrikethroughFromMarkdown(),\n    gfmTableFromMarkdown(),\n    gfmTaskListItemFromMarkdown()\n  ]\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown` to enable GFM (autolink\n * literals, footnotes, strikethrough, tables, tasklists).\n *\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {ToMarkdownExtension}\n *   Extension for `mdast-util-to-markdown` to enable GFM (autolink literals,\n *   footnotes, strikethrough, tables, tasklists).\n */\nexport function gfmToMarkdown(options) {\n  return {\n    extensions: [\n      gfmAutolinkLiteralToMarkdown(),\n      gfmFootnoteToMarkdown(options),\n      gfmStrikethroughToMarkdown(),\n      gfmTableToMarkdown(options),\n      gfmTaskListItemToMarkdown()\n    ]\n  }\n}\n","/**\n * @import {Code, ConstructRecord, Event, Extension, Previous, State, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { asciiAlpha, asciiAlphanumeric, asciiControl, markdownLineEndingOrSpace, unicodePunctuation, unicodeWhitespace } from 'micromark-util-character';\nconst wwwPrefix = {\n  tokenize: tokenizeWwwPrefix,\n  partial: true\n};\nconst domain = {\n  tokenize: tokenizeDomain,\n  partial: true\n};\nconst path = {\n  tokenize: tokenizePath,\n  partial: true\n};\nconst trail = {\n  tokenize: tokenizeTrail,\n  partial: true\n};\nconst emailDomainDotTrail = {\n  tokenize: tokenizeEmailDomainDotTrail,\n  partial: true\n};\nconst wwwAutolink = {\n  name: 'wwwAutolink',\n  tokenize: tokenizeWwwAutolink,\n  previous: previousWww\n};\nconst protocolAutolink = {\n  name: 'protocolAutolink',\n  tokenize: tokenizeProtocolAutolink,\n  previous: previousProtocol\n};\nconst emailAutolink = {\n  name: 'emailAutolink',\n  tokenize: tokenizeEmailAutolink,\n  previous: previousEmail\n};\n\n/** @type {ConstructRecord} */\nconst text = {};\n\n/**\n * Create an extension for `micromark` to support GitHub autolink literal\n * syntax.\n *\n * @returns {Extension}\n *   Extension for `micromark` that can be passed in `extensions` to enable GFM\n *   autolink literal syntax.\n */\nexport function gfmAutolinkLiteral() {\n  return {\n    text\n  };\n}\n\n/** @type {Code} */\nlet code = 48;\n\n// Add alphanumerics.\nwhile (code < 123) {\n  text[code] = emailAutolink;\n  code++;\n  if (code === 58) code = 65;else if (code === 91) code = 97;\n}\ntext[43] = emailAutolink;\ntext[45] = emailAutolink;\ntext[46] = emailAutolink;\ntext[95] = emailAutolink;\ntext[72] = [emailAutolink, protocolAutolink];\ntext[104] = [emailAutolink, protocolAutolink];\ntext[87] = [emailAutolink, wwwAutolink];\ntext[119] = [emailAutolink, wwwAutolink];\n\n// To do: perform email autolink literals on events, afterwards.\n// That’s where `markdown-rs` and `cmark-gfm` perform it.\n// It should look for `@`, then for atext backwards, and then for a label\n// forwards.\n// To do: `mailto:`, `xmpp:` protocol as prefix.\n\n/**\n * Email autolink literal.\n *\n * ```markdown\n * > | a contact@example.org b\n *       ^^^^^^^^^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeEmailAutolink(effects, ok, nok) {\n  const self = this;\n  /** @type {boolean | undefined} */\n  let dot;\n  /** @type {boolean} */\n  let data;\n  return start;\n\n  /**\n   * Start of email autolink literal.\n   *\n   * ```markdown\n   * > | a contact@example.org b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    if (!gfmAtext(code) || !previousEmail.call(self, self.previous) || previousUnbalanced(self.events)) {\n      return nok(code);\n    }\n    effects.enter('literalAutolink');\n    effects.enter('literalAutolinkEmail');\n    return atext(code);\n  }\n\n  /**\n   * In email atext.\n   *\n   * ```markdown\n   * > | a contact@example.org b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function atext(code) {\n    if (gfmAtext(code)) {\n      effects.consume(code);\n      return atext;\n    }\n    if (code === 64) {\n      effects.consume(code);\n      return emailDomain;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In email domain.\n   *\n   * The reference code is a bit overly complex as it handles the `@`, of which\n   * there may be just one.\n   * Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L318>\n   *\n   * ```markdown\n   * > | a contact@example.org b\n   *               ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailDomain(code) {\n    // Dot followed by alphanumerical (not `-` or `_`).\n    if (code === 46) {\n      return effects.check(emailDomainDotTrail, emailDomainAfter, emailDomainDot)(code);\n    }\n\n    // Alphanumerical, `-`, and `_`.\n    if (code === 45 || code === 95 || asciiAlphanumeric(code)) {\n      data = true;\n      effects.consume(code);\n      return emailDomain;\n    }\n\n    // To do: `/` if xmpp.\n\n    // Note: normally we’d truncate trailing punctuation from the link.\n    // However, email autolink literals cannot contain any of those markers,\n    // except for `.`, but that can only occur if it isn’t trailing.\n    // So we can ignore truncating!\n    return emailDomainAfter(code);\n  }\n\n  /**\n   * In email domain, on dot that is not a trail.\n   *\n   * ```markdown\n   * > | a contact@example.org b\n   *                      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailDomainDot(code) {\n    effects.consume(code);\n    dot = true;\n    return emailDomain;\n  }\n\n  /**\n   * After email domain.\n   *\n   * ```markdown\n   * > | a contact@example.org b\n   *                          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function emailDomainAfter(code) {\n    // Domain must not be empty, must include a dot, and must end in alphabetical.\n    // Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L332>.\n    if (data && dot && asciiAlpha(self.previous)) {\n      effects.exit('literalAutolinkEmail');\n      effects.exit('literalAutolink');\n      return ok(code);\n    }\n    return nok(code);\n  }\n}\n\n/**\n * `www` autolink literal.\n *\n * ```markdown\n * > | a www.example.org b\n *       ^^^^^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeWwwAutolink(effects, ok, nok) {\n  const self = this;\n  return wwwStart;\n\n  /**\n   * Start of www autolink literal.\n   *\n   * ```markdown\n   * > | www.example.com/a?b#c\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function wwwStart(code) {\n    if (code !== 87 && code !== 119 || !previousWww.call(self, self.previous) || previousUnbalanced(self.events)) {\n      return nok(code);\n    }\n    effects.enter('literalAutolink');\n    effects.enter('literalAutolinkWww');\n    // Note: we *check*, so we can discard the `www.` we parsed.\n    // If it worked, we consider it as a part of the domain.\n    return effects.check(wwwPrefix, effects.attempt(domain, effects.attempt(path, wwwAfter), nok), nok)(code);\n  }\n\n  /**\n   * After a www autolink literal.\n   *\n   * ```markdown\n   * > | www.example.com/a?b#c\n   *                          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function wwwAfter(code) {\n    effects.exit('literalAutolinkWww');\n    effects.exit('literalAutolink');\n    return ok(code);\n  }\n}\n\n/**\n * Protocol autolink literal.\n *\n * ```markdown\n * > | a https://example.org b\n *       ^^^^^^^^^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeProtocolAutolink(effects, ok, nok) {\n  const self = this;\n  let buffer = '';\n  let seen = false;\n  return protocolStart;\n\n  /**\n   * Start of protocol autolink literal.\n   *\n   * ```markdown\n   * > | https://example.com/a?b#c\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function protocolStart(code) {\n    if ((code === 72 || code === 104) && previousProtocol.call(self, self.previous) && !previousUnbalanced(self.events)) {\n      effects.enter('literalAutolink');\n      effects.enter('literalAutolinkHttp');\n      buffer += String.fromCodePoint(code);\n      effects.consume(code);\n      return protocolPrefixInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In protocol.\n   *\n   * ```markdown\n   * > | https://example.com/a?b#c\n   *     ^^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function protocolPrefixInside(code) {\n    // `5` is size of `https`\n    if (asciiAlpha(code) && buffer.length < 5) {\n      // @ts-expect-error: definitely number.\n      buffer += String.fromCodePoint(code);\n      effects.consume(code);\n      return protocolPrefixInside;\n    }\n    if (code === 58) {\n      const protocol = buffer.toLowerCase();\n      if (protocol === 'http' || protocol === 'https') {\n        effects.consume(code);\n        return protocolSlashesInside;\n      }\n    }\n    return nok(code);\n  }\n\n  /**\n   * In slashes.\n   *\n   * ```markdown\n   * > | https://example.com/a?b#c\n   *           ^^\n   * ```\n   *\n   * @type {State}\n   */\n  function protocolSlashesInside(code) {\n    if (code === 47) {\n      effects.consume(code);\n      if (seen) {\n        return afterProtocol;\n      }\n      seen = true;\n      return protocolSlashesInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After protocol, before domain.\n   *\n   * ```markdown\n   * > | https://example.com/a?b#c\n   *             ^\n   * ```\n   *\n   * @type {State}\n   */\n  function afterProtocol(code) {\n    // To do: this is different from `markdown-rs`:\n    // https://github.com/wooorm/markdown-rs/blob/b3a921c761309ae00a51fe348d8a43adbc54b518/src/construct/gfm_autolink_literal.rs#L172-L182\n    return code === null || asciiControl(code) || markdownLineEndingOrSpace(code) || unicodeWhitespace(code) || unicodePunctuation(code) ? nok(code) : effects.attempt(domain, effects.attempt(path, protocolAfter), nok)(code);\n  }\n\n  /**\n   * After a protocol autolink literal.\n   *\n   * ```markdown\n   * > | https://example.com/a?b#c\n   *                              ^\n   * ```\n   *\n   * @type {State}\n   */\n  function protocolAfter(code) {\n    effects.exit('literalAutolinkHttp');\n    effects.exit('literalAutolink');\n    return ok(code);\n  }\n}\n\n/**\n * `www` prefix.\n *\n * ```markdown\n * > | a www.example.org b\n *       ^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeWwwPrefix(effects, ok, nok) {\n  let size = 0;\n  return wwwPrefixInside;\n\n  /**\n   * In www prefix.\n   *\n   * ```markdown\n   * > | www.example.com\n   *     ^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function wwwPrefixInside(code) {\n    if ((code === 87 || code === 119) && size < 3) {\n      size++;\n      effects.consume(code);\n      return wwwPrefixInside;\n    }\n    if (code === 46 && size === 3) {\n      effects.consume(code);\n      return wwwPrefixAfter;\n    }\n    return nok(code);\n  }\n\n  /**\n   * After www prefix.\n   *\n   * ```markdown\n   * > | www.example.com\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function wwwPrefixAfter(code) {\n    // If there is *anything*, we can link.\n    return code === null ? nok(code) : ok(code);\n  }\n}\n\n/**\n * Domain.\n *\n * ```markdown\n * > | a https://example.org b\n *               ^^^^^^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeDomain(effects, ok, nok) {\n  /** @type {boolean | undefined} */\n  let underscoreInLastSegment;\n  /** @type {boolean | undefined} */\n  let underscoreInLastLastSegment;\n  /** @type {boolean | undefined} */\n  let seen;\n  return domainInside;\n\n  /**\n   * In domain.\n   *\n   * ```markdown\n   * > | https://example.com/a\n   *             ^^^^^^^^^^^\n   * ```\n   *\n   * @type {State}\n   */\n  function domainInside(code) {\n    // Check whether this marker, which is a trailing punctuation\n    // marker, optionally followed by more trailing markers, and then\n    // followed by an end.\n    if (code === 46 || code === 95) {\n      return effects.check(trail, domainAfter, domainAtPunctuation)(code);\n    }\n\n    // GH documents that only alphanumerics (other than `-`, `.`, and `_`) can\n    // occur, which sounds like ASCII only, but they also support `www.點看.com`,\n    // so that’s Unicode.\n    // Instead of some new production for Unicode alphanumerics, markdown\n    // already has that for Unicode punctuation and whitespace, so use those.\n    // Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L12>.\n    if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code) || code !== 45 && unicodePunctuation(code)) {\n      return domainAfter(code);\n    }\n    seen = true;\n    effects.consume(code);\n    return domainInside;\n  }\n\n  /**\n   * In domain, at potential trailing punctuation, that was not trailing.\n   *\n   * ```markdown\n   * > | https://example.com\n   *                    ^\n   * ```\n   *\n   * @type {State}\n   */\n  function domainAtPunctuation(code) {\n    // There is an underscore in the last segment of the domain\n    if (code === 95) {\n      underscoreInLastSegment = true;\n    }\n    // Otherwise, it’s a `.`: save the last segment underscore in the\n    // penultimate segment slot.\n    else {\n      underscoreInLastLastSegment = underscoreInLastSegment;\n      underscoreInLastSegment = undefined;\n    }\n    effects.consume(code);\n    return domainInside;\n  }\n\n  /**\n   * After domain.\n   *\n   * ```markdown\n   * > | https://example.com/a\n   *                        ^\n   * ```\n   *\n   * @type {State} */\n  function domainAfter(code) {\n    // Note: that’s GH says a dot is needed, but it’s not true:\n    // <https://github.com/github/cmark-gfm/issues/279>\n    if (underscoreInLastLastSegment || underscoreInLastSegment || !seen) {\n      return nok(code);\n    }\n    return ok(code);\n  }\n}\n\n/**\n * Path.\n *\n * ```markdown\n * > | a https://example.org/stuff b\n *                          ^^^^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizePath(effects, ok) {\n  let sizeOpen = 0;\n  let sizeClose = 0;\n  return pathInside;\n\n  /**\n   * In path.\n   *\n   * ```markdown\n   * > | https://example.com/a\n   *                        ^^\n   * ```\n   *\n   * @type {State}\n   */\n  function pathInside(code) {\n    if (code === 40) {\n      sizeOpen++;\n      effects.consume(code);\n      return pathInside;\n    }\n\n    // To do: `markdown-rs` also needs this.\n    // If this is a paren, and there are less closings than openings,\n    // we don’t check for a trail.\n    if (code === 41 && sizeClose < sizeOpen) {\n      return pathAtPunctuation(code);\n    }\n\n    // Check whether this trailing punctuation marker is optionally\n    // followed by more trailing markers, and then followed\n    // by an end.\n    if (code === 33 || code === 34 || code === 38 || code === 39 || code === 41 || code === 42 || code === 44 || code === 46 || code === 58 || code === 59 || code === 60 || code === 63 || code === 93 || code === 95 || code === 126) {\n      return effects.check(trail, ok, pathAtPunctuation)(code);\n    }\n    if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n      return ok(code);\n    }\n    effects.consume(code);\n    return pathInside;\n  }\n\n  /**\n   * In path, at potential trailing punctuation, that was not trailing.\n   *\n   * ```markdown\n   * > | https://example.com/a\"b\n   *                          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function pathAtPunctuation(code) {\n    // Count closing parens.\n    if (code === 41) {\n      sizeClose++;\n    }\n    effects.consume(code);\n    return pathInside;\n  }\n}\n\n/**\n * Trail.\n *\n * This calls `ok` if this *is* the trail, followed by an end, which means\n * the entire trail is not part of the link.\n * It calls `nok` if this *is* part of the link.\n *\n * ```markdown\n * > | https://example.com\").\n *                        ^^^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeTrail(effects, ok, nok) {\n  return trail;\n\n  /**\n   * In trail of domain or path.\n   *\n   * ```markdown\n   * > | https://example.com\").\n   *                        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function trail(code) {\n    // Regular trailing punctuation.\n    if (code === 33 || code === 34 || code === 39 || code === 41 || code === 42 || code === 44 || code === 46 || code === 58 || code === 59 || code === 63 || code === 95 || code === 126) {\n      effects.consume(code);\n      return trail;\n    }\n\n    // `&` followed by one or more alphabeticals and then a `;`, is\n    // as a whole considered as trailing punctuation.\n    // In all other cases, it is considered as continuation of the URL.\n    if (code === 38) {\n      effects.consume(code);\n      return trailCharacterReferenceStart;\n    }\n\n    // Needed because we allow literals after `[`, as we fix:\n    // <https://github.com/github/cmark-gfm/issues/278>.\n    // Check that it is not followed by `(` or `[`.\n    if (code === 93) {\n      effects.consume(code);\n      return trailBracketAfter;\n    }\n    if (\n    // `<` is an end.\n    code === 60 ||\n    // So is whitespace.\n    code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n      return ok(code);\n    }\n    return nok(code);\n  }\n\n  /**\n   * In trail, after `]`.\n   *\n   * > 👉 **Note**: this deviates from `cmark-gfm` to fix a bug.\n   * > See end of <https://github.com/github/cmark-gfm/issues/278> for more.\n   *\n   * ```markdown\n   * > | https://example.com](\n   *                         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function trailBracketAfter(code) {\n    // Whitespace or something that could start a resource or reference is the end.\n    // Switch back to trail otherwise.\n    if (code === null || code === 40 || code === 91 || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {\n      return ok(code);\n    }\n    return trail(code);\n  }\n\n  /**\n   * In character-reference like trail, after `&`.\n   *\n   * ```markdown\n   * > | https://example.com&amp;).\n   *                         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function trailCharacterReferenceStart(code) {\n    // When non-alpha, it’s not a trail.\n    return asciiAlpha(code) ? trailCharacterReferenceInside(code) : nok(code);\n  }\n\n  /**\n   * In character-reference like trail.\n   *\n   * ```markdown\n   * > | https://example.com&amp;).\n   *                         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function trailCharacterReferenceInside(code) {\n    // Switch back to trail if this is well-formed.\n    if (code === 59) {\n      effects.consume(code);\n      return trail;\n    }\n    if (asciiAlpha(code)) {\n      effects.consume(code);\n      return trailCharacterReferenceInside;\n    }\n\n    // It’s not a trail.\n    return nok(code);\n  }\n}\n\n/**\n * Dot in email domain trail.\n *\n * This calls `ok` if this *is* the trail, followed by an end, which means\n * the trail is not part of the link.\n * It calls `nok` if this *is* part of the link.\n *\n * ```markdown\n * > | contact@example.org.\n *                        ^\n * ```\n *\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeEmailDomainDotTrail(effects, ok, nok) {\n  return start;\n\n  /**\n   * Dot.\n   *\n   * ```markdown\n   * > | contact@example.org.\n   *                    ^   ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    // Must be dot.\n    effects.consume(code);\n    return after;\n  }\n\n  /**\n   * After dot.\n   *\n   * ```markdown\n   * > | contact@example.org.\n   *                     ^   ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    // Not a trail if alphanumeric.\n    return asciiAlphanumeric(code) ? nok(code) : ok(code);\n  }\n}\n\n/**\n * See:\n * <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L156>.\n *\n * @type {Previous}\n */\nfunction previousWww(code) {\n  return code === null || code === 40 || code === 42 || code === 95 || code === 91 || code === 93 || code === 126 || markdownLineEndingOrSpace(code);\n}\n\n/**\n * See:\n * <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L214>.\n *\n * @type {Previous}\n */\nfunction previousProtocol(code) {\n  return !asciiAlpha(code);\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Previous}\n */\nfunction previousEmail(code) {\n  // Do not allow a slash “inside” atext.\n  // The reference code is a bit weird, but that’s what it results in.\n  // Source: <https://github.com/github/cmark-gfm/blob/ef1cfcb/extensions/autolink.c#L307>.\n  // Other than slash, every preceding character is allowed.\n  return !(code === 47 || gfmAtext(code));\n}\n\n/**\n * @param {Code} code\n * @returns {boolean}\n */\nfunction gfmAtext(code) {\n  return code === 43 || code === 45 || code === 46 || code === 95 || asciiAlphanumeric(code);\n}\n\n/**\n * @param {Array<Event>} events\n * @returns {boolean}\n */\nfunction previousUnbalanced(events) {\n  let index = events.length;\n  let result = false;\n  while (index--) {\n    const token = events[index][1];\n    if ((token.type === 'labelLink' || token.type === 'labelImage') && !token._balanced) {\n      result = true;\n      break;\n    }\n\n    // If we’ve seen this token, and it was marked as not having any unbalanced\n    // bracket before it, we can exit.\n    if (token._gfmAutolinkLiteralWalkedInto) {\n      result = false;\n      break;\n    }\n  }\n  if (events.length > 0 && !result) {\n    // Mark the last token as “walked into” w/o finding\n    // anything.\n    events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = true;\n  }\n  return result;\n}","/**\n * @import {Event, Exiter, Extension, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { blankLine } from 'micromark-core-commonmark';\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEndingOrSpace } from 'micromark-util-character';\nimport { normalizeIdentifier } from 'micromark-util-normalize-identifier';\nconst indent = {\n  tokenize: tokenizeIndent,\n  partial: true\n};\n\n// To do: micromark should support a `_hiddenGfmFootnoteSupport`, which only\n// affects label start (image).\n// That will let us drop `tokenizePotentialGfmFootnote*`.\n// It currently has a `_hiddenFootnoteSupport`, which affects that and more.\n// That can be removed when `micromark-extension-footnote` is archived.\n\n/**\n * Create an extension for `micromark` to enable GFM footnote syntax.\n *\n * @returns {Extension}\n *   Extension for `micromark` that can be passed in `extensions` to\n *   enable GFM footnote syntax.\n */\nexport function gfmFootnote() {\n  /** @type {Extension} */\n  return {\n    document: {\n      [91]: {\n        name: 'gfmFootnoteDefinition',\n        tokenize: tokenizeDefinitionStart,\n        continuation: {\n          tokenize: tokenizeDefinitionContinuation\n        },\n        exit: gfmFootnoteDefinitionEnd\n      }\n    },\n    text: {\n      [91]: {\n        name: 'gfmFootnoteCall',\n        tokenize: tokenizeGfmFootnoteCall\n      },\n      [93]: {\n        name: 'gfmPotentialFootnoteCall',\n        add: 'after',\n        tokenize: tokenizePotentialGfmFootnoteCall,\n        resolveTo: resolveToPotentialGfmFootnoteCall\n      }\n    }\n  };\n}\n\n// To do: remove after micromark update.\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizePotentialGfmFootnoteCall(effects, ok, nok) {\n  const self = this;\n  let index = self.events.length;\n  const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);\n  /** @type {Token} */\n  let labelStart;\n\n  // Find an opening.\n  while (index--) {\n    const token = self.events[index][1];\n    if (token.type === \"labelImage\") {\n      labelStart = token;\n      break;\n    }\n\n    // Exit if we’ve walked far enough.\n    if (token.type === 'gfmFootnoteCall' || token.type === \"labelLink\" || token.type === \"label\" || token.type === \"image\" || token.type === \"link\") {\n      break;\n    }\n  }\n  return start;\n\n  /**\n   * @type {State}\n   */\n  function start(code) {\n    if (!labelStart || !labelStart._balanced) {\n      return nok(code);\n    }\n    const id = normalizeIdentifier(self.sliceSerialize({\n      start: labelStart.end,\n      end: self.now()\n    }));\n    if (id.codePointAt(0) !== 94 || !defined.includes(id.slice(1))) {\n      return nok(code);\n    }\n    effects.enter('gfmFootnoteCallLabelMarker');\n    effects.consume(code);\n    effects.exit('gfmFootnoteCallLabelMarker');\n    return ok(code);\n  }\n}\n\n// To do: remove after micromark update.\n/** @type {Resolver} */\nfunction resolveToPotentialGfmFootnoteCall(events, context) {\n  let index = events.length;\n  /** @type {Token | undefined} */\n  let labelStart;\n\n  // Find an opening.\n  while (index--) {\n    if (events[index][1].type === \"labelImage\" && events[index][0] === 'enter') {\n      labelStart = events[index][1];\n      break;\n    }\n  }\n  // Change the `labelImageMarker` to a `data`.\n  events[index + 1][1].type = \"data\";\n  events[index + 3][1].type = 'gfmFootnoteCallLabelMarker';\n\n  // The whole (without `!`):\n  /** @type {Token} */\n  const call = {\n    type: 'gfmFootnoteCall',\n    start: Object.assign({}, events[index + 3][1].start),\n    end: Object.assign({}, events[events.length - 1][1].end)\n  };\n  // The `^` marker\n  /** @type {Token} */\n  const marker = {\n    type: 'gfmFootnoteCallMarker',\n    start: Object.assign({}, events[index + 3][1].end),\n    end: Object.assign({}, events[index + 3][1].end)\n  };\n  // Increment the end 1 character.\n  marker.end.column++;\n  marker.end.offset++;\n  marker.end._bufferIndex++;\n  /** @type {Token} */\n  const string = {\n    type: 'gfmFootnoteCallString',\n    start: Object.assign({}, marker.end),\n    end: Object.assign({}, events[events.length - 1][1].start)\n  };\n  /** @type {Token} */\n  const chunk = {\n    type: \"chunkString\",\n    contentType: 'string',\n    start: Object.assign({}, string.start),\n    end: Object.assign({}, string.end)\n  };\n\n  /** @type {Array<Event>} */\n  const replacement = [\n  // Take the `labelImageMarker` (now `data`, the `!`)\n  events[index + 1], events[index + 2], ['enter', call, context],\n  // The `[`\n  events[index + 3], events[index + 4],\n  // The `^`.\n  ['enter', marker, context], ['exit', marker, context],\n  // Everything in between.\n  ['enter', string, context], ['enter', chunk, context], ['exit', chunk, context], ['exit', string, context],\n  // The ending (`]`, properly parsed and labelled).\n  events[events.length - 2], events[events.length - 1], ['exit', call, context]];\n  events.splice(index, events.length - index + 1, ...replacement);\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeGfmFootnoteCall(effects, ok, nok) {\n  const self = this;\n  const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);\n  let size = 0;\n  /** @type {boolean} */\n  let data;\n\n  // Note: the implementation of `markdown-rs` is different, because it houses\n  // core *and* extensions in one project.\n  // Therefore, it can include footnote logic inside `label-end`.\n  // We can’t do that, but luckily, we can parse footnotes in a simpler way than\n  // needed for labels.\n  return start;\n\n  /**\n   * Start of footnote label.\n   *\n   * ```markdown\n   * > | a [^b] c\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter('gfmFootnoteCall');\n    effects.enter('gfmFootnoteCallLabelMarker');\n    effects.consume(code);\n    effects.exit('gfmFootnoteCallLabelMarker');\n    return callStart;\n  }\n\n  /**\n   * After `[`, at `^`.\n   *\n   * ```markdown\n   * > | a [^b] c\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function callStart(code) {\n    if (code !== 94) return nok(code);\n    effects.enter('gfmFootnoteCallMarker');\n    effects.consume(code);\n    effects.exit('gfmFootnoteCallMarker');\n    effects.enter('gfmFootnoteCallString');\n    effects.enter('chunkString').contentType = 'string';\n    return callData;\n  }\n\n  /**\n   * In label.\n   *\n   * ```markdown\n   * > | a [^b] c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function callData(code) {\n    if (\n    // Too long.\n    size > 999 ||\n    // Closing brace with nothing.\n    code === 93 && !data ||\n    // Space or tab is not supported by GFM for some reason.\n    // `\\n` and `[` not being supported makes sense.\n    code === null || code === 91 || markdownLineEndingOrSpace(code)) {\n      return nok(code);\n    }\n    if (code === 93) {\n      effects.exit('chunkString');\n      const token = effects.exit('gfmFootnoteCallString');\n      if (!defined.includes(normalizeIdentifier(self.sliceSerialize(token)))) {\n        return nok(code);\n      }\n      effects.enter('gfmFootnoteCallLabelMarker');\n      effects.consume(code);\n      effects.exit('gfmFootnoteCallLabelMarker');\n      effects.exit('gfmFootnoteCall');\n      return ok;\n    }\n    if (!markdownLineEndingOrSpace(code)) {\n      data = true;\n    }\n    size++;\n    effects.consume(code);\n    return code === 92 ? callEscape : callData;\n  }\n\n  /**\n   * On character after escape.\n   *\n   * ```markdown\n   * > | a [^b\\c] d\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function callEscape(code) {\n    if (code === 91 || code === 92 || code === 93) {\n      effects.consume(code);\n      size++;\n      return callData;\n    }\n    return callData(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeDefinitionStart(effects, ok, nok) {\n  const self = this;\n  const defined = self.parser.gfmFootnotes || (self.parser.gfmFootnotes = []);\n  /** @type {string} */\n  let identifier;\n  let size = 0;\n  /** @type {boolean | undefined} */\n  let data;\n  return start;\n\n  /**\n   * Start of GFM footnote definition.\n   *\n   * ```markdown\n   * > | [^a]: b\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter('gfmFootnoteDefinition')._container = true;\n    effects.enter('gfmFootnoteDefinitionLabel');\n    effects.enter('gfmFootnoteDefinitionLabelMarker');\n    effects.consume(code);\n    effects.exit('gfmFootnoteDefinitionLabelMarker');\n    return labelAtMarker;\n  }\n\n  /**\n   * In label, at caret.\n   *\n   * ```markdown\n   * > | [^a]: b\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelAtMarker(code) {\n    if (code === 94) {\n      effects.enter('gfmFootnoteDefinitionMarker');\n      effects.consume(code);\n      effects.exit('gfmFootnoteDefinitionMarker');\n      effects.enter('gfmFootnoteDefinitionLabelString');\n      effects.enter('chunkString').contentType = 'string';\n      return labelInside;\n    }\n    return nok(code);\n  }\n\n  /**\n   * In label.\n   *\n   * > 👉 **Note**: `cmark-gfm` prevents whitespace from occurring in footnote\n   * > definition labels.\n   *\n   * ```markdown\n   * > | [^a]: b\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelInside(code) {\n    if (\n    // Too long.\n    size > 999 ||\n    // Closing brace with nothing.\n    code === 93 && !data ||\n    // Space or tab is not supported by GFM for some reason.\n    // `\\n` and `[` not being supported makes sense.\n    code === null || code === 91 || markdownLineEndingOrSpace(code)) {\n      return nok(code);\n    }\n    if (code === 93) {\n      effects.exit('chunkString');\n      const token = effects.exit('gfmFootnoteDefinitionLabelString');\n      identifier = normalizeIdentifier(self.sliceSerialize(token));\n      effects.enter('gfmFootnoteDefinitionLabelMarker');\n      effects.consume(code);\n      effects.exit('gfmFootnoteDefinitionLabelMarker');\n      effects.exit('gfmFootnoteDefinitionLabel');\n      return labelAfter;\n    }\n    if (!markdownLineEndingOrSpace(code)) {\n      data = true;\n    }\n    size++;\n    effects.consume(code);\n    return code === 92 ? labelEscape : labelInside;\n  }\n\n  /**\n   * After `\\`, at a special character.\n   *\n   * > 👉 **Note**: `cmark-gfm` currently does not support escaped brackets:\n   * > <https://github.com/github/cmark-gfm/issues/240>\n   *\n   * ```markdown\n   * > | [^a\\*b]: c\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelEscape(code) {\n    if (code === 91 || code === 92 || code === 93) {\n      effects.consume(code);\n      size++;\n      return labelInside;\n    }\n    return labelInside(code);\n  }\n\n  /**\n   * After definition label.\n   *\n   * ```markdown\n   * > | [^a]: b\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function labelAfter(code) {\n    if (code === 58) {\n      effects.enter('definitionMarker');\n      effects.consume(code);\n      effects.exit('definitionMarker');\n      if (!defined.includes(identifier)) {\n        defined.push(identifier);\n      }\n\n      // Any whitespace after the marker is eaten, forming indented code\n      // is not possible.\n      // No space is also fine, just like a block quote marker.\n      return factorySpace(effects, whitespaceAfter, 'gfmFootnoteDefinitionWhitespace');\n    }\n    return nok(code);\n  }\n\n  /**\n   * After definition prefix.\n   *\n   * ```markdown\n   * > | [^a]: b\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function whitespaceAfter(code) {\n    // `markdown-rs` has a wrapping token for the prefix that is closed here.\n    return ok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeDefinitionContinuation(effects, ok, nok) {\n  /// Start of footnote definition continuation.\n  ///\n  /// ```markdown\n  ///   | [^a]: b\n  /// > |     c\n  ///     ^\n  /// ```\n  //\n  // Either a blank line, which is okay, or an indented thing.\n  return effects.check(blankLine, ok, effects.attempt(indent, ok, nok));\n}\n\n/** @type {Exiter} */\nfunction gfmFootnoteDefinitionEnd(effects) {\n  effects.exit('gfmFootnoteDefinition');\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeIndent(effects, ok, nok) {\n  const self = this;\n  return factorySpace(effects, afterPrefix, 'gfmFootnoteDefinitionIndent', 4 + 1);\n\n  /**\n   * @type {State}\n   */\n  function afterPrefix(code) {\n    const tail = self.events[self.events.length - 1];\n    return tail && tail[1].type === 'gfmFootnoteDefinitionIndent' && tail[2].sliceSerialize(tail[1], true).length === 4 ? ok(code) : nok(code);\n  }\n}","/**\n * @import {Options} from 'micromark-extension-gfm-strikethrough'\n * @import {Event, Extension, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { splice } from 'micromark-util-chunked';\nimport { classifyCharacter } from 'micromark-util-classify-character';\nimport { resolveAll } from 'micromark-util-resolve-all';\n/**\n * Create an extension for `micromark` to enable GFM strikethrough syntax.\n *\n * @param {Options | null | undefined} [options={}]\n *   Configuration.\n * @returns {Extension}\n *   Extension for `micromark` that can be passed in `extensions`, to\n *   enable GFM strikethrough syntax.\n */\nexport function gfmStrikethrough(options) {\n  const options_ = options || {};\n  let single = options_.singleTilde;\n  const tokenizer = {\n    name: 'strikethrough',\n    tokenize: tokenizeStrikethrough,\n    resolveAll: resolveAllStrikethrough\n  };\n  if (single === null || single === undefined) {\n    single = true;\n  }\n  return {\n    text: {\n      [126]: tokenizer\n    },\n    insideSpan: {\n      null: [tokenizer]\n    },\n    attentionMarkers: {\n      null: [126]\n    }\n  };\n\n  /**\n   * Take events and resolve strikethrough.\n   *\n   * @type {Resolver}\n   */\n  function resolveAllStrikethrough(events, context) {\n    let index = -1;\n\n    // Walk through all events.\n    while (++index < events.length) {\n      // Find a token that can close.\n      if (events[index][0] === 'enter' && events[index][1].type === 'strikethroughSequenceTemporary' && events[index][1]._close) {\n        let open = index;\n\n        // Now walk back to find an opener.\n        while (open--) {\n          // Find a token that can open the closer.\n          if (events[open][0] === 'exit' && events[open][1].type === 'strikethroughSequenceTemporary' && events[open][1]._open &&\n          // If the sizes are the same:\n          events[index][1].end.offset - events[index][1].start.offset === events[open][1].end.offset - events[open][1].start.offset) {\n            events[index][1].type = 'strikethroughSequence';\n            events[open][1].type = 'strikethroughSequence';\n\n            /** @type {Token} */\n            const strikethrough = {\n              type: 'strikethrough',\n              start: Object.assign({}, events[open][1].start),\n              end: Object.assign({}, events[index][1].end)\n            };\n\n            /** @type {Token} */\n            const text = {\n              type: 'strikethroughText',\n              start: Object.assign({}, events[open][1].end),\n              end: Object.assign({}, events[index][1].start)\n            };\n\n            // Opening.\n            /** @type {Array<Event>} */\n            const nextEvents = [['enter', strikethrough, context], ['enter', events[open][1], context], ['exit', events[open][1], context], ['enter', text, context]];\n            const insideSpan = context.parser.constructs.insideSpan.null;\n            if (insideSpan) {\n              // Between.\n              splice(nextEvents, nextEvents.length, 0, resolveAll(insideSpan, events.slice(open + 1, index), context));\n            }\n\n            // Closing.\n            splice(nextEvents, nextEvents.length, 0, [['exit', text, context], ['enter', events[index][1], context], ['exit', events[index][1], context], ['exit', strikethrough, context]]);\n            splice(events, open - 1, index - open + 3, nextEvents);\n            index = open + nextEvents.length - 2;\n            break;\n          }\n        }\n      }\n    }\n    index = -1;\n    while (++index < events.length) {\n      if (events[index][1].type === 'strikethroughSequenceTemporary') {\n        events[index][1].type = \"data\";\n      }\n    }\n    return events;\n  }\n\n  /**\n   * @this {TokenizeContext}\n   * @type {Tokenizer}\n   */\n  function tokenizeStrikethrough(effects, ok, nok) {\n    const previous = this.previous;\n    const events = this.events;\n    let size = 0;\n    return start;\n\n    /** @type {State} */\n    function start(code) {\n      if (previous === 126 && events[events.length - 1][1].type !== \"characterEscape\") {\n        return nok(code);\n      }\n      effects.enter('strikethroughSequenceTemporary');\n      return more(code);\n    }\n\n    /** @type {State} */\n    function more(code) {\n      const before = classifyCharacter(previous);\n      if (code === 126) {\n        // If this is the third marker, exit.\n        if (size > 1) return nok(code);\n        effects.consume(code);\n        size++;\n        return more;\n      }\n      if (size < 2 && !single) return nok(code);\n      const token = effects.exit('strikethroughSequenceTemporary');\n      const after = classifyCharacter(code);\n      token._open = !after || after === 2 && Boolean(before);\n      token._close = !before || before === 2 && Boolean(after);\n      return ok(code);\n    }\n  }\n}","/**\n * @import {Event} from 'micromark-util-types'\n */\n\n// Port of `edit_map.rs` from `markdown-rs`.\n// This should move to `markdown-js` later.\n\n// Deal with several changes in events, batching them together.\n//\n// Preferably, changes should be kept to a minimum.\n// Sometimes, it’s needed to change the list of events, because parsing can be\n// messy, and it helps to expose a cleaner interface of events to the compiler\n// and other users.\n// It can also help to merge many adjacent similar events.\n// And, in other cases, it’s needed to parse subcontent: pass some events\n// through another tokenizer and inject the result.\n\n/**\n * @typedef {[number, number, Array<Event>]} Change\n * @typedef {[number, number, number]} Jump\n */\n\n/**\n * Tracks a bunch of edits.\n */\nexport class EditMap {\n  /**\n   * Create a new edit map.\n   */\n  constructor() {\n    /**\n     * Record of changes.\n     *\n     * @type {Array<Change>}\n     */\n    this.map = [];\n  }\n\n  /**\n   * Create an edit: a remove and/or add at a certain place.\n   *\n   * @param {number} index\n   * @param {number} remove\n   * @param {Array<Event>} add\n   * @returns {undefined}\n   */\n  add(index, remove, add) {\n    addImplementation(this, index, remove, add);\n  }\n\n  // To do: add this when moving to `micromark`.\n  // /**\n  //  * Create an edit: but insert `add` before existing additions.\n  //  *\n  //  * @param {number} index\n  //  * @param {number} remove\n  //  * @param {Array<Event>} add\n  //  * @returns {undefined}\n  //  */\n  // addBefore(index, remove, add) {\n  //   addImplementation(this, index, remove, add, true)\n  // }\n\n  /**\n   * Done, change the events.\n   *\n   * @param {Array<Event>} events\n   * @returns {undefined}\n   */\n  consume(events) {\n    this.map.sort(function (a, b) {\n      return a[0] - b[0];\n    });\n\n    /* c8 ignore next 3 -- `resolve` is never called without tables, so without edits. */\n    if (this.map.length === 0) {\n      return;\n    }\n\n    // To do: if links are added in events, like they are in `markdown-rs`,\n    // this is needed.\n    // // Calculate jumps: where items in the current list move to.\n    // /** @type {Array<Jump>} */\n    // const jumps = []\n    // let index = 0\n    // let addAcc = 0\n    // let removeAcc = 0\n    // while (index < this.map.length) {\n    //   const [at, remove, add] = this.map[index]\n    //   removeAcc += remove\n    //   addAcc += add.length\n    //   jumps.push([at, removeAcc, addAcc])\n    //   index += 1\n    // }\n    //\n    // . shiftLinks(events, jumps)\n\n    let index = this.map.length;\n    /** @type {Array<Array<Event>>} */\n    const vecs = [];\n    while (index > 0) {\n      index -= 1;\n      vecs.push(events.slice(this.map[index][0] + this.map[index][1]), this.map[index][2]);\n\n      // Truncate rest.\n      events.length = this.map[index][0];\n    }\n    vecs.push(events.slice());\n    events.length = 0;\n    let slice = vecs.pop();\n    while (slice) {\n      for (const element of slice) {\n        events.push(element);\n      }\n      slice = vecs.pop();\n    }\n\n    // Truncate everything.\n    this.map.length = 0;\n  }\n}\n\n/**\n * Create an edit.\n *\n * @param {EditMap} editMap\n * @param {number} at\n * @param {number} remove\n * @param {Array<Event>} add\n * @returns {undefined}\n */\nfunction addImplementation(editMap, at, remove, add) {\n  let index = 0;\n\n  /* c8 ignore next 3 -- `resolve` is never called without tables, so without edits. */\n  if (remove === 0 && add.length === 0) {\n    return;\n  }\n  while (index < editMap.map.length) {\n    if (editMap.map[index][0] === at) {\n      editMap.map[index][1] += remove;\n\n      // To do: before not used by tables, use when moving to micromark.\n      // if (before) {\n      //   add.push(...editMap.map[index][2])\n      //   editMap.map[index][2] = add\n      // } else {\n      editMap.map[index][2].push(...add);\n      // }\n\n      return;\n    }\n    index += 1;\n  }\n  editMap.map.push([at, remove, add]);\n}\n\n// /**\n//  * Shift `previous` and `next` links according to `jumps`.\n//  *\n//  * This fixes links in case there are events removed or added between them.\n//  *\n//  * @param {Array<Event>} events\n//  * @param {Array<Jump>} jumps\n//  */\n// function shiftLinks(events, jumps) {\n//   let jumpIndex = 0\n//   let index = 0\n//   let add = 0\n//   let rm = 0\n\n//   while (index < events.length) {\n//     const rmCurr = rm\n\n//     while (jumpIndex < jumps.length && jumps[jumpIndex][0] <= index) {\n//       add = jumps[jumpIndex][2]\n//       rm = jumps[jumpIndex][1]\n//       jumpIndex += 1\n//     }\n\n//     // Ignore items that will be removed.\n//     if (rm > rmCurr) {\n//       index += rm - rmCurr\n//     } else {\n//       // ?\n//       // if let Some(link) = &events[index].link {\n//       //     if let Some(next) = link.next {\n//       //         events[next].link.as_mut().unwrap().previous = Some(index + add - rm);\n//       //         while jumpIndex < jumps.len() && jumps[jumpIndex].0 <= next {\n//       //             add = jumps[jumpIndex].2;\n//       //             rm = jumps[jumpIndex].1;\n//       //             jumpIndex += 1;\n//       //         }\n//       //         events[index].link.as_mut().unwrap().next = Some(next + add - rm);\n//       //         index = next;\n//       //         continue;\n//       //     }\n//       // }\n//       index += 1\n//     }\n//   }\n// }","/**\n * @import {Event} from 'micromark-util-types'\n */\n\n/**\n * @typedef {'center' | 'left' | 'none' | 'right'} Align\n */\n\n/**\n * Figure out the alignment of a GFM table.\n *\n * @param {Readonly<Array<Event>>} events\n *   List of events.\n * @param {number} index\n *   Table enter event.\n * @returns {Array<Align>}\n *   List of aligns.\n */\nexport function gfmTableAlign(events, index) {\n  let inDelimiterRow = false;\n  /** @type {Array<Align>} */\n  const align = [];\n  while (index < events.length) {\n    const event = events[index];\n    if (inDelimiterRow) {\n      if (event[0] === 'enter') {\n        // Start of alignment value: set a new column.\n        // To do: `markdown-rs` uses `tableDelimiterCellValue`.\n        if (event[1].type === 'tableContent') {\n          align.push(events[index + 1][1].type === 'tableDelimiterMarker' ? 'left' : 'none');\n        }\n      }\n      // Exits:\n      // End of alignment value: change the column.\n      // To do: `markdown-rs` uses `tableDelimiterCellValue`.\n      else if (event[1].type === 'tableContent') {\n        if (events[index - 1][1].type === 'tableDelimiterMarker') {\n          const alignIndex = align.length - 1;\n          align[alignIndex] = align[alignIndex] === 'left' ? 'center' : 'right';\n        }\n      }\n      // Done!\n      else if (event[1].type === 'tableDelimiterRow') {\n        break;\n      }\n    } else if (event[0] === 'enter' && event[1].type === 'tableDelimiterRow') {\n      inDelimiterRow = true;\n    }\n    index += 1;\n  }\n  return align;\n}","/**\n * @import {Event, Extension, Point, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\n/**\n * @typedef {[number, number, number, number]} Range\n *   Cell info.\n *\n * @typedef {0 | 1 | 2 | 3} RowKind\n *   Where we are: `1` for head row, `2` for delimiter row, `3` for body row.\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownLineEndingOrSpace, markdownSpace } from 'micromark-util-character';\nimport { EditMap } from './edit-map.js';\nimport { gfmTableAlign } from './infer.js';\n\n/**\n * Create an HTML extension for `micromark` to support GitHub tables syntax.\n *\n * @returns {Extension}\n *   Extension for `micromark` that can be passed in `extensions` to enable GFM\n *   table syntax.\n */\nexport function gfmTable() {\n  return {\n    flow: {\n      null: {\n        name: 'table',\n        tokenize: tokenizeTable,\n        resolveAll: resolveTable\n      }\n    }\n  };\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeTable(effects, ok, nok) {\n  const self = this;\n  let size = 0;\n  let sizeB = 0;\n  /** @type {boolean | undefined} */\n  let seen;\n  return start;\n\n  /**\n   * Start of a GFM table.\n   *\n   * If there is a valid table row or table head before, then we try to parse\n   * another row.\n   * Otherwise, we try to parse a head.\n   *\n   * ```markdown\n   * > | | a |\n   *     ^\n   *   | | - |\n   * > | | b |\n   *     ^\n   * ```\n   * @type {State}\n   */\n  function start(code) {\n    let index = self.events.length - 1;\n    while (index > -1) {\n      const type = self.events[index][1].type;\n      if (type === \"lineEnding\" ||\n      // Note: markdown-rs uses `whitespace` instead of `linePrefix`\n      type === \"linePrefix\") index--;else break;\n    }\n    const tail = index > -1 ? self.events[index][1].type : null;\n    const next = tail === 'tableHead' || tail === 'tableRow' ? bodyRowStart : headRowBefore;\n\n    // Don’t allow lazy body rows.\n    if (next === bodyRowStart && self.parser.lazy[self.now().line]) {\n      return nok(code);\n    }\n    return next(code);\n  }\n\n  /**\n   * Before table head row.\n   *\n   * ```markdown\n   * > | | a |\n   *     ^\n   *   | | - |\n   *   | | b |\n   * ```\n   *\n   * @type {State}\n   */\n  function headRowBefore(code) {\n    effects.enter('tableHead');\n    effects.enter('tableRow');\n    return headRowStart(code);\n  }\n\n  /**\n   * Before table head row, after whitespace.\n   *\n   * ```markdown\n   * > | | a |\n   *     ^\n   *   | | - |\n   *   | | b |\n   * ```\n   *\n   * @type {State}\n   */\n  function headRowStart(code) {\n    if (code === 124) {\n      return headRowBreak(code);\n    }\n\n    // To do: micromark-js should let us parse our own whitespace in extensions,\n    // like `markdown-rs`:\n    //\n    // ```js\n    // // 4+ spaces.\n    // if (markdownSpace(code)) {\n    //   return nok(code)\n    // }\n    // ```\n\n    seen = true;\n    // Count the first character, that isn’t a pipe, double.\n    sizeB += 1;\n    return headRowBreak(code);\n  }\n\n  /**\n   * At break in table head row.\n   *\n   * ```markdown\n   * > | | a |\n   *     ^\n   *       ^\n   *         ^\n   *   | | - |\n   *   | | b |\n   * ```\n   *\n   * @type {State}\n   */\n  function headRowBreak(code) {\n    if (code === null) {\n      // Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.\n      return nok(code);\n    }\n    if (markdownLineEnding(code)) {\n      // If anything other than one pipe (ignoring whitespace) was used, it’s fine.\n      if (sizeB > 1) {\n        sizeB = 0;\n        // To do: check if this works.\n        // Feel free to interrupt:\n        self.interrupt = true;\n        effects.exit('tableRow');\n        effects.enter(\"lineEnding\");\n        effects.consume(code);\n        effects.exit(\"lineEnding\");\n        return headDelimiterStart;\n      }\n\n      // Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.\n      return nok(code);\n    }\n    if (markdownSpace(code)) {\n      // To do: check if this is fine.\n      // effects.attempt(State::Next(StateName::GfmTableHeadRowBreak), State::Nok)\n      // State::Retry(space_or_tab(tokenizer))\n      return factorySpace(effects, headRowBreak, \"whitespace\")(code);\n    }\n    sizeB += 1;\n    if (seen) {\n      seen = false;\n      // Header cell count.\n      size += 1;\n    }\n    if (code === 124) {\n      effects.enter('tableCellDivider');\n      effects.consume(code);\n      effects.exit('tableCellDivider');\n      // Whether a delimiter was seen.\n      seen = true;\n      return headRowBreak;\n    }\n\n    // Anything else is cell data.\n    effects.enter(\"data\");\n    return headRowData(code);\n  }\n\n  /**\n   * In table head row data.\n   *\n   * ```markdown\n   * > | | a |\n   *       ^\n   *   | | - |\n   *   | | b |\n   * ```\n   *\n   * @type {State}\n   */\n  function headRowData(code) {\n    if (code === null || code === 124 || markdownLineEndingOrSpace(code)) {\n      effects.exit(\"data\");\n      return headRowBreak(code);\n    }\n    effects.consume(code);\n    return code === 92 ? headRowEscape : headRowData;\n  }\n\n  /**\n   * In table head row escape.\n   *\n   * ```markdown\n   * > | | a\\-b |\n   *         ^\n   *   | | ---- |\n   *   | | c    |\n   * ```\n   *\n   * @type {State}\n   */\n  function headRowEscape(code) {\n    if (code === 92 || code === 124) {\n      effects.consume(code);\n      return headRowData;\n    }\n    return headRowData(code);\n  }\n\n  /**\n   * Before delimiter row.\n   *\n   * ```markdown\n   *   | | a |\n   * > | | - |\n   *     ^\n   *   | | b |\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterStart(code) {\n    // Reset `interrupt`.\n    self.interrupt = false;\n\n    // Note: in `markdown-rs`, we need to handle piercing here too.\n    if (self.parser.lazy[self.now().line]) {\n      return nok(code);\n    }\n    effects.enter('tableDelimiterRow');\n    // Track if we’ve seen a `:` or `|`.\n    seen = false;\n    if (markdownSpace(code)) {\n      return factorySpace(effects, headDelimiterBefore, \"linePrefix\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4)(code);\n    }\n    return headDelimiterBefore(code);\n  }\n\n  /**\n   * Before delimiter row, after optional whitespace.\n   *\n   * Reused when a `|` is found later, to parse another cell.\n   *\n   * ```markdown\n   *   | | a |\n   * > | | - |\n   *     ^\n   *   | | b |\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterBefore(code) {\n    if (code === 45 || code === 58) {\n      return headDelimiterValueBefore(code);\n    }\n    if (code === 124) {\n      seen = true;\n      // If we start with a pipe, we open a cell marker.\n      effects.enter('tableCellDivider');\n      effects.consume(code);\n      effects.exit('tableCellDivider');\n      return headDelimiterCellBefore;\n    }\n\n    // More whitespace / empty row not allowed at start.\n    return headDelimiterNok(code);\n  }\n\n  /**\n   * After `|`, before delimiter cell.\n   *\n   * ```markdown\n   *   | | a |\n   * > | | - |\n   *      ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterCellBefore(code) {\n    if (markdownSpace(code)) {\n      return factorySpace(effects, headDelimiterValueBefore, \"whitespace\")(code);\n    }\n    return headDelimiterValueBefore(code);\n  }\n\n  /**\n   * Before delimiter cell value.\n   *\n   * ```markdown\n   *   | | a |\n   * > | | - |\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterValueBefore(code) {\n    // Align: left.\n    if (code === 58) {\n      sizeB += 1;\n      seen = true;\n      effects.enter('tableDelimiterMarker');\n      effects.consume(code);\n      effects.exit('tableDelimiterMarker');\n      return headDelimiterLeftAlignmentAfter;\n    }\n\n    // Align: none.\n    if (code === 45) {\n      sizeB += 1;\n      // To do: seems weird that this *isn’t* left aligned, but that state is used?\n      return headDelimiterLeftAlignmentAfter(code);\n    }\n    if (code === null || markdownLineEnding(code)) {\n      return headDelimiterCellAfter(code);\n    }\n    return headDelimiterNok(code);\n  }\n\n  /**\n   * After delimiter cell left alignment marker.\n   *\n   * ```markdown\n   *   | | a  |\n   * > | | :- |\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterLeftAlignmentAfter(code) {\n    if (code === 45) {\n      effects.enter('tableDelimiterFiller');\n      return headDelimiterFiller(code);\n    }\n\n    // Anything else is not ok after the left-align colon.\n    return headDelimiterNok(code);\n  }\n\n  /**\n   * In delimiter cell filler.\n   *\n   * ```markdown\n   *   | | a |\n   * > | | - |\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterFiller(code) {\n    if (code === 45) {\n      effects.consume(code);\n      return headDelimiterFiller;\n    }\n\n    // Align is `center` if it was `left`, `right` otherwise.\n    if (code === 58) {\n      seen = true;\n      effects.exit('tableDelimiterFiller');\n      effects.enter('tableDelimiterMarker');\n      effects.consume(code);\n      effects.exit('tableDelimiterMarker');\n      return headDelimiterRightAlignmentAfter;\n    }\n    effects.exit('tableDelimiterFiller');\n    return headDelimiterRightAlignmentAfter(code);\n  }\n\n  /**\n   * After delimiter cell right alignment marker.\n   *\n   * ```markdown\n   *   | |  a |\n   * > | | -: |\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterRightAlignmentAfter(code) {\n    if (markdownSpace(code)) {\n      return factorySpace(effects, headDelimiterCellAfter, \"whitespace\")(code);\n    }\n    return headDelimiterCellAfter(code);\n  }\n\n  /**\n   * After delimiter cell.\n   *\n   * ```markdown\n   *   | |  a |\n   * > | | -: |\n   *          ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterCellAfter(code) {\n    if (code === 124) {\n      return headDelimiterBefore(code);\n    }\n    if (code === null || markdownLineEnding(code)) {\n      // Exit when:\n      // * there was no `:` or `|` at all (it’s a thematic break or setext\n      //   underline instead)\n      // * the header cell count is not the delimiter cell count\n      if (!seen || size !== sizeB) {\n        return headDelimiterNok(code);\n      }\n\n      // Note: in markdown-rs`, a reset is needed here.\n      effects.exit('tableDelimiterRow');\n      effects.exit('tableHead');\n      // To do: in `markdown-rs`, resolvers need to be registered manually.\n      // effects.register_resolver(ResolveName::GfmTable)\n      return ok(code);\n    }\n    return headDelimiterNok(code);\n  }\n\n  /**\n   * In delimiter row, at a disallowed byte.\n   *\n   * ```markdown\n   *   | | a |\n   * > | | x |\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function headDelimiterNok(code) {\n    // Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.\n    return nok(code);\n  }\n\n  /**\n   * Before table body row.\n   *\n   * ```markdown\n   *   | | a |\n   *   | | - |\n   * > | | b |\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function bodyRowStart(code) {\n    // Note: in `markdown-rs` we need to manually take care of a prefix,\n    // but in `micromark-js` that is done for us, so if we’re here, we’re\n    // never at whitespace.\n    effects.enter('tableRow');\n    return bodyRowBreak(code);\n  }\n\n  /**\n   * At break in table body row.\n   *\n   * ```markdown\n   *   | | a |\n   *   | | - |\n   * > | | b |\n   *     ^\n   *       ^\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function bodyRowBreak(code) {\n    if (code === 124) {\n      effects.enter('tableCellDivider');\n      effects.consume(code);\n      effects.exit('tableCellDivider');\n      return bodyRowBreak;\n    }\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit('tableRow');\n      return ok(code);\n    }\n    if (markdownSpace(code)) {\n      return factorySpace(effects, bodyRowBreak, \"whitespace\")(code);\n    }\n\n    // Anything else is cell content.\n    effects.enter(\"data\");\n    return bodyRowData(code);\n  }\n\n  /**\n   * In table body row data.\n   *\n   * ```markdown\n   *   | | a |\n   *   | | - |\n   * > | | b |\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function bodyRowData(code) {\n    if (code === null || code === 124 || markdownLineEndingOrSpace(code)) {\n      effects.exit(\"data\");\n      return bodyRowBreak(code);\n    }\n    effects.consume(code);\n    return code === 92 ? bodyRowEscape : bodyRowData;\n  }\n\n  /**\n   * In table body row escape.\n   *\n   * ```markdown\n   *   | | a    |\n   *   | | ---- |\n   * > | | b\\-c |\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function bodyRowEscape(code) {\n    if (code === 92 || code === 124) {\n      effects.consume(code);\n      return bodyRowData;\n    }\n    return bodyRowData(code);\n  }\n}\n\n/** @type {Resolver} */\n\nfunction resolveTable(events, context) {\n  let index = -1;\n  let inFirstCellAwaitingPipe = true;\n  /** @type {RowKind} */\n  let rowKind = 0;\n  /** @type {Range} */\n  let lastCell = [0, 0, 0, 0];\n  /** @type {Range} */\n  let cell = [0, 0, 0, 0];\n  let afterHeadAwaitingFirstBodyRow = false;\n  let lastTableEnd = 0;\n  /** @type {Token | undefined} */\n  let currentTable;\n  /** @type {Token | undefined} */\n  let currentBody;\n  /** @type {Token | undefined} */\n  let currentCell;\n  const map = new EditMap();\n  while (++index < events.length) {\n    const event = events[index];\n    const token = event[1];\n    if (event[0] === 'enter') {\n      // Start of head.\n      if (token.type === 'tableHead') {\n        afterHeadAwaitingFirstBodyRow = false;\n\n        // Inject previous (body end and) table end.\n        if (lastTableEnd !== 0) {\n          flushTableEnd(map, context, lastTableEnd, currentTable, currentBody);\n          currentBody = undefined;\n          lastTableEnd = 0;\n        }\n\n        // Inject table start.\n        currentTable = {\n          type: 'table',\n          start: Object.assign({}, token.start),\n          // Note: correct end is set later.\n          end: Object.assign({}, token.end)\n        };\n        map.add(index, 0, [['enter', currentTable, context]]);\n      } else if (token.type === 'tableRow' || token.type === 'tableDelimiterRow') {\n        inFirstCellAwaitingPipe = true;\n        currentCell = undefined;\n        lastCell = [0, 0, 0, 0];\n        cell = [0, index + 1, 0, 0];\n\n        // Inject table body start.\n        if (afterHeadAwaitingFirstBodyRow) {\n          afterHeadAwaitingFirstBodyRow = false;\n          currentBody = {\n            type: 'tableBody',\n            start: Object.assign({}, token.start),\n            // Note: correct end is set later.\n            end: Object.assign({}, token.end)\n          };\n          map.add(index, 0, [['enter', currentBody, context]]);\n        }\n        rowKind = token.type === 'tableDelimiterRow' ? 2 : currentBody ? 3 : 1;\n      }\n      // Cell data.\n      else if (rowKind && (token.type === \"data\" || token.type === 'tableDelimiterMarker' || token.type === 'tableDelimiterFiller')) {\n        inFirstCellAwaitingPipe = false;\n\n        // First value in cell.\n        if (cell[2] === 0) {\n          if (lastCell[1] !== 0) {\n            cell[0] = cell[1];\n            currentCell = flushCell(map, context, lastCell, rowKind, undefined, currentCell);\n            lastCell = [0, 0, 0, 0];\n          }\n          cell[2] = index;\n        }\n      } else if (token.type === 'tableCellDivider') {\n        if (inFirstCellAwaitingPipe) {\n          inFirstCellAwaitingPipe = false;\n        } else {\n          if (lastCell[1] !== 0) {\n            cell[0] = cell[1];\n            currentCell = flushCell(map, context, lastCell, rowKind, undefined, currentCell);\n          }\n          lastCell = cell;\n          cell = [lastCell[1], index, 0, 0];\n        }\n      }\n    }\n    // Exit events.\n    else if (token.type === 'tableHead') {\n      afterHeadAwaitingFirstBodyRow = true;\n      lastTableEnd = index;\n    } else if (token.type === 'tableRow' || token.type === 'tableDelimiterRow') {\n      lastTableEnd = index;\n      if (lastCell[1] !== 0) {\n        cell[0] = cell[1];\n        currentCell = flushCell(map, context, lastCell, rowKind, index, currentCell);\n      } else if (cell[1] !== 0) {\n        currentCell = flushCell(map, context, cell, rowKind, index, currentCell);\n      }\n      rowKind = 0;\n    } else if (rowKind && (token.type === \"data\" || token.type === 'tableDelimiterMarker' || token.type === 'tableDelimiterFiller')) {\n      cell[3] = index;\n    }\n  }\n  if (lastTableEnd !== 0) {\n    flushTableEnd(map, context, lastTableEnd, currentTable, currentBody);\n  }\n  map.consume(context.events);\n\n  // To do: move this into `html`, when events are exposed there.\n  // That’s what `markdown-rs` does.\n  // That needs updates to `mdast-util-gfm-table`.\n  index = -1;\n  while (++index < context.events.length) {\n    const event = context.events[index];\n    if (event[0] === 'enter' && event[1].type === 'table') {\n      event[1]._align = gfmTableAlign(context.events, index);\n    }\n  }\n  return events;\n}\n\n/**\n * Generate a cell.\n *\n * @param {EditMap} map\n * @param {Readonly<TokenizeContext>} context\n * @param {Readonly<Range>} range\n * @param {RowKind} rowKind\n * @param {number | undefined} rowEnd\n * @param {Token | undefined} previousCell\n * @returns {Token | undefined}\n */\n// eslint-disable-next-line max-params\nfunction flushCell(map, context, range, rowKind, rowEnd, previousCell) {\n  // `markdown-rs` uses:\n  // rowKind === 2 ? 'tableDelimiterCell' : 'tableCell'\n  const groupName = rowKind === 1 ? 'tableHeader' : rowKind === 2 ? 'tableDelimiter' : 'tableData';\n  // `markdown-rs` uses:\n  // rowKind === 2 ? 'tableDelimiterCellValue' : 'tableCellText'\n  const valueName = 'tableContent';\n\n  // Insert an exit for the previous cell, if there is one.\n  //\n  // ```markdown\n  // > | | aa | bb | cc |\n  //          ^-- exit\n  //           ^^^^-- this cell\n  // ```\n  if (range[0] !== 0) {\n    previousCell.end = Object.assign({}, getPoint(context.events, range[0]));\n    map.add(range[0], 0, [['exit', previousCell, context]]);\n  }\n\n  // Insert enter of this cell.\n  //\n  // ```markdown\n  // > | | aa | bb | cc |\n  //           ^-- enter\n  //           ^^^^-- this cell\n  // ```\n  const now = getPoint(context.events, range[1]);\n  previousCell = {\n    type: groupName,\n    start: Object.assign({}, now),\n    // Note: correct end is set later.\n    end: Object.assign({}, now)\n  };\n  map.add(range[1], 0, [['enter', previousCell, context]]);\n\n  // Insert text start at first data start and end at last data end, and\n  // remove events between.\n  //\n  // ```markdown\n  // > | | aa | bb | cc |\n  //            ^-- enter\n  //             ^-- exit\n  //           ^^^^-- this cell\n  // ```\n  if (range[2] !== 0) {\n    const relatedStart = getPoint(context.events, range[2]);\n    const relatedEnd = getPoint(context.events, range[3]);\n    /** @type {Token} */\n    const valueToken = {\n      type: valueName,\n      start: Object.assign({}, relatedStart),\n      end: Object.assign({}, relatedEnd)\n    };\n    map.add(range[2], 0, [['enter', valueToken, context]]);\n    if (rowKind !== 2) {\n      // Fix positional info on remaining events\n      const start = context.events[range[2]];\n      const end = context.events[range[3]];\n      start[1].end = Object.assign({}, end[1].end);\n      start[1].type = \"chunkText\";\n      start[1].contentType = \"text\";\n\n      // Remove if needed.\n      if (range[3] > range[2] + 1) {\n        const a = range[2] + 1;\n        const b = range[3] - range[2] - 1;\n        map.add(a, b, []);\n      }\n    }\n    map.add(range[3] + 1, 0, [['exit', valueToken, context]]);\n  }\n\n  // Insert an exit for the last cell, if at the row end.\n  //\n  // ```markdown\n  // > | | aa | bb | cc |\n  //                    ^-- exit\n  //               ^^^^^^-- this cell (the last one contains two “between” parts)\n  // ```\n  if (rowEnd !== undefined) {\n    previousCell.end = Object.assign({}, getPoint(context.events, rowEnd));\n    map.add(rowEnd, 0, [['exit', previousCell, context]]);\n    previousCell = undefined;\n  }\n  return previousCell;\n}\n\n/**\n * Generate table end (and table body end).\n *\n * @param {Readonly<EditMap>} map\n * @param {Readonly<TokenizeContext>} context\n * @param {number} index\n * @param {Token} table\n * @param {Token | undefined} tableBody\n */\n// eslint-disable-next-line max-params\nfunction flushTableEnd(map, context, index, table, tableBody) {\n  /** @type {Array<Event>} */\n  const exits = [];\n  const related = getPoint(context.events, index);\n  if (tableBody) {\n    tableBody.end = Object.assign({}, related);\n    exits.push(['exit', tableBody, context]);\n  }\n  table.end = Object.assign({}, related);\n  exits.push(['exit', table, context]);\n  map.add(index + 1, 0, exits);\n}\n\n/**\n * @param {Readonly<Array<Event>>} events\n * @param {number} index\n * @returns {Readonly<Point>}\n */\nfunction getPoint(events, index) {\n  const event = events[index];\n  const side = event[0] === 'enter' ? 'start' : 'end';\n  return event[1][side];\n}","/**\n * @import {Extension, State, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding, markdownLineEndingOrSpace, markdownSpace } from 'micromark-util-character';\nconst tasklistCheck = {\n  name: 'tasklistCheck',\n  tokenize: tokenizeTasklistCheck\n};\n\n/**\n * Create an HTML extension for `micromark` to support GFM task list items\n * syntax.\n *\n * @returns {Extension}\n *   Extension for `micromark` that can be passed in `htmlExtensions` to\n *   support GFM task list items when serializing to HTML.\n */\nexport function gfmTaskListItem() {\n  return {\n    text: {\n      [91]: tasklistCheck\n    }\n  };\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeTasklistCheck(effects, ok, nok) {\n  const self = this;\n  return open;\n\n  /**\n   * At start of task list item check.\n   *\n   * ```markdown\n   * > | * [x] y.\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function open(code) {\n    if (\n    // Exit if there’s stuff before.\n    self.previous !== null ||\n    // Exit if not in the first content that is the first child of a list\n    // item.\n    !self._gfmTasklistFirstContentOfListItem) {\n      return nok(code);\n    }\n    effects.enter('taskListCheck');\n    effects.enter('taskListCheckMarker');\n    effects.consume(code);\n    effects.exit('taskListCheckMarker');\n    return inside;\n  }\n\n  /**\n   * In task list item check.\n   *\n   * ```markdown\n   * > | * [x] y.\n   *        ^\n   * ```\n   *\n   * @type {State}\n   */\n  function inside(code) {\n    // Currently we match how GH works in files.\n    // To match how GH works in comments, use `markdownSpace` (`[\\t ]`) instead\n    // of `markdownLineEndingOrSpace` (`[\\t\\n\\r ]`).\n    if (markdownLineEndingOrSpace(code)) {\n      effects.enter('taskListCheckValueUnchecked');\n      effects.consume(code);\n      effects.exit('taskListCheckValueUnchecked');\n      return close;\n    }\n    if (code === 88 || code === 120) {\n      effects.enter('taskListCheckValueChecked');\n      effects.consume(code);\n      effects.exit('taskListCheckValueChecked');\n      return close;\n    }\n    return nok(code);\n  }\n\n  /**\n   * At close of task list item check.\n   *\n   * ```markdown\n   * > | * [x] y.\n   *         ^\n   * ```\n   *\n   * @type {State}\n   */\n  function close(code) {\n    if (code === 93) {\n      effects.enter('taskListCheckMarker');\n      effects.consume(code);\n      effects.exit('taskListCheckMarker');\n      effects.exit('taskListCheck');\n      return after;\n    }\n    return nok(code);\n  }\n\n  /**\n   * @type {State}\n   */\n  function after(code) {\n    // EOL in paragraph means there must be something else after it.\n    if (markdownLineEnding(code)) {\n      return ok(code);\n    }\n\n    // Space or tab?\n    // Check what comes after.\n    if (markdownSpace(code)) {\n      return effects.check({\n        tokenize: spaceThenNonSpace\n      }, ok, nok)(code);\n    }\n\n    // EOF, or non-whitespace, both wrong.\n    return nok(code);\n  }\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction spaceThenNonSpace(effects, ok, nok) {\n  return factorySpace(effects, after, \"whitespace\");\n\n  /**\n   * After whitespace, after task list item check.\n   *\n   * ```markdown\n   * > | * [x] y.\n   *           ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    // EOF means there was nothing, so bad.\n    // EOL means there’s content after it, so good.\n    // Impossible to have more spaces.\n    // Anything else is good.\n    return code === null ? nok(code) : ok(code);\n  }\n}","/**\n * @typedef {import('micromark-extension-gfm-footnote').HtmlOptions} HtmlOptions\n * @typedef {import('micromark-extension-gfm-strikethrough').Options} Options\n * @typedef {import('micromark-util-types').Extension} Extension\n * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension\n */\n\nimport {\n  combineExtensions,\n  combineHtmlExtensions\n} from 'micromark-util-combine-extensions'\nimport {\n  gfmAutolinkLiteral,\n  gfmAutolinkLiteralHtml\n} from 'micromark-extension-gfm-autolink-literal'\nimport {gfmFootnote, gfmFootnoteHtml} from 'micromark-extension-gfm-footnote'\nimport {\n  gfmStrikethrough,\n  gfmStrikethroughHtml\n} from 'micromark-extension-gfm-strikethrough'\nimport {gfmTable, gfmTableHtml} from 'micromark-extension-gfm-table'\nimport {gfmTagfilterHtml} from 'micromark-extension-gfm-tagfilter'\nimport {\n  gfmTaskListItem,\n  gfmTaskListItemHtml\n} from 'micromark-extension-gfm-task-list-item'\n\n/**\n * Create an extension for `micromark` to enable GFM syntax.\n *\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n *\n *   Passed to `micromark-extens-gfm-strikethrough`.\n * @returns {Extension}\n *   Extension for `micromark` that can be passed in `extensions` to enable GFM\n *   syntax.\n */\nexport function gfm(options) {\n  return combineExtensions([\n    gfmAutolinkLiteral(),\n    gfmFootnote(),\n    gfmStrikethrough(options),\n    gfmTable(),\n    gfmTaskListItem()\n  ])\n}\n\n/**\n * Create an extension for `micromark` to support GFM when serializing to HTML.\n *\n * @param {HtmlOptions | null | undefined} [options]\n *   Configuration (optional).\n *\n *   Passed to `micromark-extens-gfm-footnote`.\n * @returns {HtmlExtension}\n *   Extension for `micromark` that can be passed in `htmlExtensions` to\n *   support GFM when serializing to HTML.\n */\nexport function gfmHtml(options) {\n  return combineHtmlExtensions([\n    gfmAutolinkLiteralHtml(),\n    gfmFootnoteHtml(options),\n    gfmStrikethroughHtml(),\n    gfmTableHtml(),\n    gfmTagfilterHtml(),\n    gfmTaskListItemHtml()\n  ])\n}\n","/**\n * @import {Root} from 'mdast'\n * @import {Options} from 'remark-gfm'\n * @import {} from 'remark-parse'\n * @import {} from 'remark-stringify'\n * @import {Processor} from 'unified'\n */\n\nimport {gfmFromMarkdown, gfmToMarkdown} from 'mdast-util-gfm'\nimport {gfm} from 'micromark-extension-gfm'\n\n/** @type {Options} */\nconst emptyOptions = {}\n\n/**\n * Add support GFM (autolink literals, footnotes, strikethrough, tables,\n * tasklists).\n *\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {undefined}\n *   Nothing.\n */\nexport default function remarkGfm(options) {\n  // @ts-expect-error: TS is wrong about `this`.\n  // eslint-disable-next-line unicorn/no-this-assignment\n  const self = /** @type {Processor<Root>} */ (this)\n  const settings = options || emptyOptions\n  const data = self.data()\n\n  const micromarkExtensions =\n    data.micromarkExtensions || (data.micromarkExtensions = [])\n  const fromMarkdownExtensions =\n    data.fromMarkdownExtensions || (data.fromMarkdownExtensions = [])\n  const toMarkdownExtensions =\n    data.toMarkdownExtensions || (data.toMarkdownExtensions = [])\n\n  micromarkExtensions.push(gfm(settings))\n  fromMarkdownExtensions.push(gfmFromMarkdown())\n  toMarkdownExtensions.push(gfmToMarkdown(settings))\n}\n","/**\n * @typedef {import('hast').Element} HastElement\n * @typedef {import('hast').ElementContent} HastElementContent\n * @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext\n * @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension\n * @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle\n * @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension\n * @typedef {import('../index.js').InlineMath} InlineMath\n * @typedef {import('../index.js').Math} Math\n *\n * @typedef ToOptions\n *   Configuration.\n * @property {boolean | null | undefined} [singleDollarTextMath=true]\n *   Whether to support math (text) with a single dollar (default: `true`).\n *\n *   Single dollars work in Pandoc and many other places, but often interfere\n *   with “normal” dollars in text.\n *   If you turn this off, you can still use two or more dollars for text math.\n */\n\nimport {ok as assert} from 'devlop'\nimport {longestStreak} from 'longest-streak'\n\n/**\n * Create an extension for `mdast-util-from-markdown`.\n *\n * @returns {FromMarkdownExtension}\n *   Extension for `mdast-util-from-markdown`.\n */\nexport function mathFromMarkdown() {\n  return {\n    enter: {\n      mathFlow: enterMathFlow,\n      mathFlowFenceMeta: enterMathFlowMeta,\n      mathText: enterMathText\n    },\n    exit: {\n      mathFlow: exitMathFlow,\n      mathFlowFence: exitMathFlowFence,\n      mathFlowFenceMeta: exitMathFlowMeta,\n      mathFlowValue: exitMathData,\n      mathText: exitMathText,\n      mathTextData: exitMathData\n    }\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {FromMarkdownHandle}\n   */\n  function enterMathFlow(token) {\n    /** @type {HastElement} */\n    const code = {\n      type: 'element',\n      tagName: 'code',\n      properties: {className: ['language-math', 'math-display']},\n      children: []\n    }\n    this.enter(\n      {\n        type: 'math',\n        meta: null,\n        value: '',\n        data: {hName: 'pre', hChildren: [code]}\n      },\n      token\n    )\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {FromMarkdownHandle}\n   */\n  function enterMathFlowMeta() {\n    this.buffer()\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {FromMarkdownHandle}\n   */\n  function exitMathFlowMeta() {\n    const data = this.resume()\n    const node = this.stack[this.stack.length - 1]\n    assert(node.type === 'math')\n    node.meta = data\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {FromMarkdownHandle}\n   */\n  function exitMathFlowFence() {\n    // Exit if this is the closing fence.\n    if (this.data.mathFlowInside) return\n    this.buffer()\n    this.data.mathFlowInside = true\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {FromMarkdownHandle}\n   */\n  function exitMathFlow(token) {\n    const data = this.resume().replace(/^(\\r?\\n|\\r)|(\\r?\\n|\\r)$/g, '')\n    const node = this.stack[this.stack.length - 1]\n    assert(node.type === 'math')\n    this.exit(token)\n    node.value = data\n    // @ts-expect-error: we defined it in `enterMathFlow`.\n    const code = /** @type {HastElement} */ (node.data.hChildren[0])\n    assert(code.type === 'element')\n    assert(code.tagName === 'code')\n    code.children.push({type: 'text', value: data})\n    this.data.mathFlowInside = undefined\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {FromMarkdownHandle}\n   */\n  function enterMathText(token) {\n    this.enter(\n      {\n        type: 'inlineMath',\n        value: '',\n        data: {\n          hName: 'code',\n          hProperties: {className: ['language-math', 'math-inline']},\n          hChildren: []\n        }\n      },\n      token\n    )\n    this.buffer()\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {FromMarkdownHandle}\n   */\n  function exitMathText(token) {\n    const data = this.resume()\n    const node = this.stack[this.stack.length - 1]\n    assert(node.type === 'inlineMath')\n    this.exit(token)\n    node.value = data\n    const children = /** @type {Array<HastElementContent>} */ (\n      // @ts-expect-error: we defined it in `enterMathFlow`.\n      node.data.hChildren\n    )\n    children.push({type: 'text', value: data})\n  }\n\n  /**\n   * @this {CompileContext}\n   * @type {FromMarkdownHandle}\n   */\n  function exitMathData(token) {\n    this.config.enter.data.call(this, token)\n    this.config.exit.data.call(this, token)\n  }\n}\n\n/**\n * Create an extension for `mdast-util-to-markdown`.\n *\n * @param {ToOptions | null | undefined} [options]\n *   Configuration (optional).\n * @returns {ToMarkdownExtension}\n *   Extension for `mdast-util-to-markdown`.\n */\nexport function mathToMarkdown(options) {\n  let single = (options || {}).singleDollarTextMath\n\n  if (single === null || single === undefined) {\n    single = true\n  }\n\n  inlineMath.peek = inlineMathPeek\n\n  return {\n    unsafe: [\n      {character: '\\r', inConstruct: 'mathFlowMeta'},\n      {character: '\\n', inConstruct: 'mathFlowMeta'},\n      {\n        character: '$',\n        after: single ? undefined : '\\\\$',\n        inConstruct: 'phrasing'\n      },\n      {character: '$', inConstruct: 'mathFlowMeta'},\n      {atBreak: true, character: '$', after: '\\\\$'}\n    ],\n    handlers: {math, inlineMath}\n  }\n\n  /**\n   * @type {ToMarkdownHandle}\n   * @param {Math} node\n   */\n  // Note: fixing this code? Please also fix the similar code for code:\n  // <https://github.com/syntax-tree/mdast-util-to-markdown/blob/main/lib/handle/code.js>\n  function math(node, _, state, info) {\n    const raw = node.value || ''\n    const tracker = state.createTracker(info)\n    const sequence = '$'.repeat(Math.max(longestStreak(raw, '$') + 1, 2))\n    const exit = state.enter('mathFlow')\n    let value = tracker.move(sequence)\n\n    if (node.meta) {\n      const subexit = state.enter('mathFlowMeta')\n      value += tracker.move(\n        state.safe(node.meta, {\n          after: '\\n',\n          before: value,\n          encode: ['$'],\n          ...tracker.current()\n        })\n      )\n      subexit()\n    }\n\n    value += tracker.move('\\n')\n\n    if (raw) {\n      value += tracker.move(raw + '\\n')\n    }\n\n    value += tracker.move(sequence)\n    exit()\n    return value\n  }\n\n  /**\n   * @type {ToMarkdownHandle}\n   * @param {InlineMath} node\n   */\n  // Note: fixing this code? Please also fix the similar code for inline code:\n  // <https://github.com/syntax-tree/mdast-util-to-markdown/blob/main/lib/handle/inline-code.js>\n  function inlineMath(node, _, state) {\n    let value = node.value || ''\n    let size = 1\n\n    if (!single) size++\n\n    // If there is a single dollar sign on its own in the math, use a fence of\n    // two.\n    // If there are two in a row, use one.\n    while (\n      new RegExp('(^|[^$])' + '\\\\$'.repeat(size) + '([^$]|$)').test(value)\n    ) {\n      size++\n    }\n\n    const sequence = '$'.repeat(size)\n\n    // If this is not just spaces or eols (tabs don’t count), and either the\n    // first and last character are a space or eol, or the first or last\n    // character are dollar signs, then pad with spaces.\n    if (\n      // Contains non-space.\n      /[^ \\r\\n]/.test(value) &&\n      // Starts with space and ends with space.\n      ((/^[ \\r\\n]/.test(value) && /[ \\r\\n]$/.test(value)) ||\n        // Starts or ends with dollar.\n        /^\\$|\\$$/.test(value))\n    ) {\n      value = ' ' + value + ' '\n    }\n\n    let index = -1\n\n    // We have a potential problem: certain characters after eols could result in\n    // blocks being seen.\n    // For example, if someone injected the string `'\\n# b'`, then that would\n    // result in an ATX heading.\n    // We can’t escape characters in `inlineMath`, but because eols are\n    // transformed to spaces when going from markdown to HTML anyway, we can swap\n    // them out.\n    while (++index < state.unsafe.length) {\n      const pattern = state.unsafe[index]\n\n      // Only look for `atBreak`s.\n      // Btw: note that `atBreak` patterns will always start the regex at LF or\n      // CR.\n      if (!pattern.atBreak) continue\n\n      const expression = state.compilePattern(pattern)\n      /** @type {RegExpExecArray | null} */\n      let match\n\n      while ((match = expression.exec(value))) {\n        let position = match.index\n\n        // Support CRLF (patterns only look for one of the characters).\n        if (\n          value.codePointAt(position) === 10 /* `\\n` */ &&\n          value.codePointAt(position - 1) === 13 /* `\\r` */\n        ) {\n          position--\n        }\n\n        value = value.slice(0, position) + ' ' + value.slice(match.index + 1)\n      }\n    }\n\n    return sequence + value + sequence\n  }\n\n  /**\n   * @returns {string}\n   */\n  function inlineMathPeek() {\n    return '$'\n  }\n}\n","/**\n * @import {Construct, State, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\nimport { factorySpace } from 'micromark-factory-space';\nimport { markdownLineEnding } from 'micromark-util-character';\n/** @type {Construct} */\nexport const mathFlow = {\n  tokenize: tokenizeMathFenced,\n  concrete: true,\n  name: 'mathFlow'\n};\n\n/** @type {Construct} */\nconst nonLazyContinuation = {\n  tokenize: tokenizeNonLazyContinuation,\n  partial: true\n};\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeMathFenced(effects, ok, nok) {\n  const self = this;\n  const tail = self.events[self.events.length - 1];\n  const initialSize = tail && tail[1].type === \"linePrefix\" ? tail[2].sliceSerialize(tail[1], true).length : 0;\n  let sizeOpen = 0;\n  return start;\n\n  /**\n   * Start of math.\n   *\n   * ```markdown\n   * > | $$\n   *     ^\n   *   | \\frac{1}{2}\n   *   | $$\n   * ```\n   *\n   * @type {State}\n   */\n  function start(code) {\n    effects.enter('mathFlow');\n    effects.enter('mathFlowFence');\n    effects.enter('mathFlowFenceSequence');\n    return sequenceOpen(code);\n  }\n\n  /**\n   * In opening fence sequence.\n   *\n   * ```markdown\n   * > | $$\n   *      ^\n   *   | \\frac{1}{2}\n   *   | $$\n   * ```\n   *\n   * @type {State}\n   */\n  function sequenceOpen(code) {\n    if (code === 36) {\n      effects.consume(code);\n      sizeOpen++;\n      return sequenceOpen;\n    }\n    if (sizeOpen < 2) {\n      return nok(code);\n    }\n    effects.exit('mathFlowFenceSequence');\n    return factorySpace(effects, metaBefore, \"whitespace\")(code);\n  }\n\n  /**\n   * In opening fence, before meta.\n   *\n   * ```markdown\n   * > | $$asciimath\n   *       ^\n   *   | x < y\n   *   | $$\n   * ```\n   *\n   * @type {State}\n   */\n\n  function metaBefore(code) {\n    if (code === null || markdownLineEnding(code)) {\n      return metaAfter(code);\n    }\n    effects.enter('mathFlowFenceMeta');\n    effects.enter(\"chunkString\", {\n      contentType: \"string\"\n    });\n    return meta(code);\n  }\n\n  /**\n   * In meta.\n   *\n   * ```markdown\n   * > | $$asciimath\n   *        ^\n   *   | x < y\n   *   | $$\n   * ```\n   *\n   * @type {State}\n   */\n  function meta(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit(\"chunkString\");\n      effects.exit('mathFlowFenceMeta');\n      return metaAfter(code);\n    }\n    if (code === 36) {\n      return nok(code);\n    }\n    effects.consume(code);\n    return meta;\n  }\n\n  /**\n   * After meta.\n   *\n   * ```markdown\n   * > | $$\n   *       ^\n   *   | \\frac{1}{2}\n   *   | $$\n   * ```\n   *\n   * @type {State}\n   */\n  function metaAfter(code) {\n    // Guaranteed to be eol/eof.\n    effects.exit('mathFlowFence');\n    if (self.interrupt) {\n      return ok(code);\n    }\n    return effects.attempt(nonLazyContinuation, beforeNonLazyContinuation, after)(code);\n  }\n\n  /**\n   * After eol/eof in math, at a non-lazy closing fence or content.\n   *\n   * ```markdown\n   *   | $$\n   * > | \\frac{1}{2}\n   *     ^\n   * > | $$\n   *     ^\n   * ```\n   *\n   * @type {State}\n   */\n  function beforeNonLazyContinuation(code) {\n    return effects.attempt({\n      tokenize: tokenizeClosingFence,\n      partial: true\n    }, after, contentStart)(code);\n  }\n\n  /**\n   * Before math content, definitely not before a closing fence.\n   *\n   * ```markdown\n   *   | $$\n   * > | \\frac{1}{2}\n   *     ^\n   *   | $$\n   * ```\n   *\n   * @type {State}\n   */\n  function contentStart(code) {\n    return (initialSize ? factorySpace(effects, beforeContentChunk, \"linePrefix\", initialSize + 1) : beforeContentChunk)(code);\n  }\n\n  /**\n   * Before math content, after optional prefix.\n   *\n   * ```markdown\n   *   | $$\n   * > | \\frac{1}{2}\n   *     ^\n   *   | $$\n   * ```\n   *\n   * @type {State}\n   */\n  function beforeContentChunk(code) {\n    if (code === null) {\n      return after(code);\n    }\n    if (markdownLineEnding(code)) {\n      return effects.attempt(nonLazyContinuation, beforeNonLazyContinuation, after)(code);\n    }\n    effects.enter('mathFlowValue');\n    return contentChunk(code);\n  }\n\n  /**\n   * In math content.\n   *\n   * ```markdown\n   *   | $$\n   * > | \\frac{1}{2}\n   *      ^\n   *   | $$\n   * ```\n   *\n   * @type {State}\n   */\n  function contentChunk(code) {\n    if (code === null || markdownLineEnding(code)) {\n      effects.exit('mathFlowValue');\n      return beforeContentChunk(code);\n    }\n    effects.consume(code);\n    return contentChunk;\n  }\n\n  /**\n   * After math (ha!).\n   *\n   * ```markdown\n   *   | $$\n   *   | \\frac{1}{2}\n   * > | $$\n   *       ^\n   * ```\n   *\n   * @type {State}\n   */\n  function after(code) {\n    effects.exit('mathFlow');\n    return ok(code);\n  }\n\n  /** @type {Tokenizer} */\n  function tokenizeClosingFence(effects, ok, nok) {\n    let size = 0;\n    /**\n     * Before closing fence, at optional whitespace.\n     *\n     * ```markdown\n     *   | $$\n     *   | \\frac{1}{2}\n     * > | $$\n     *     ^\n     * ```\n     */\n    return factorySpace(effects, beforeSequenceClose, \"linePrefix\", self.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4);\n\n    /**\n     * In closing fence, after optional whitespace, at sequence.\n     *\n     * ```markdown\n     *   | $$\n     *   | \\frac{1}{2}\n     * > | $$\n     *     ^\n     * ```\n     *\n     * @type {State}\n     */\n    function beforeSequenceClose(code) {\n      effects.enter('mathFlowFence');\n      effects.enter('mathFlowFenceSequence');\n      return sequenceClose(code);\n    }\n\n    /**\n     * In closing fence sequence.\n     *\n     * ```markdown\n     *   | $$\n     *   | \\frac{1}{2}\n     * > | $$\n     *      ^\n     * ```\n     *\n     * @type {State}\n     */\n    function sequenceClose(code) {\n      if (code === 36) {\n        size++;\n        effects.consume(code);\n        return sequenceClose;\n      }\n      if (size < sizeOpen) {\n        return nok(code);\n      }\n      effects.exit('mathFlowFenceSequence');\n      return factorySpace(effects, afterSequenceClose, \"whitespace\")(code);\n    }\n\n    /**\n     * After closing fence sequence, after optional whitespace.\n     *\n     * ```markdown\n     *   | $$\n     *   | \\frac{1}{2}\n     * > | $$\n     *       ^\n     * ```\n     *\n     * @type {State}\n     */\n    function afterSequenceClose(code) {\n      if (code === null || markdownLineEnding(code)) {\n        effects.exit('mathFlowFence');\n        return ok(code);\n      }\n      return nok(code);\n    }\n  }\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Tokenizer}\n */\nfunction tokenizeNonLazyContinuation(effects, ok, nok) {\n  const self = this;\n  return start;\n\n  /** @type {State} */\n  function start(code) {\n    if (code === null) {\n      return ok(code);\n    }\n    effects.enter(\"lineEnding\");\n    effects.consume(code);\n    effects.exit(\"lineEnding\");\n    return lineStart;\n  }\n\n  /** @type {State} */\n  function lineStart(code) {\n    return self.parser.lazy[self.now().line] ? nok(code) : ok(code);\n  }\n}","/**\n * @import {Options} from 'micromark-extension-math'\n * @import {Construct, Previous, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'\n */\n\n// To do: next major: clean spaces in HTML compiler.\n// This has to be coordinated together with `mdast-util-math`.\n\nimport { markdownLineEnding } from 'micromark-util-character';\n/**\n * @param {Options | null | undefined} [options={}]\n *   Configuration (default: `{}`).\n * @returns {Construct}\n *   Construct.\n */\nexport function mathText(options) {\n  const options_ = options || {};\n  let single = options_.singleDollarTextMath;\n  if (single === null || single === undefined) {\n    single = true;\n  }\n  return {\n    tokenize: tokenizeMathText,\n    resolve: resolveMathText,\n    previous,\n    name: 'mathText'\n  };\n\n  /**\n   * @this {TokenizeContext}\n   * @type {Tokenizer}\n   */\n  function tokenizeMathText(effects, ok, nok) {\n    const self = this;\n    let sizeOpen = 0;\n    /** @type {number} */\n    let size;\n    /** @type {Token} */\n    let token;\n    return start;\n\n    /**\n     * Start of math (text).\n     *\n     * ```markdown\n     * > | $a$\n     *     ^\n     * > | \\$a$\n     *      ^\n     * ```\n     *\n     * @type {State}\n     */\n    function start(code) {\n      effects.enter('mathText');\n      effects.enter('mathTextSequence');\n      return sequenceOpen(code);\n    }\n\n    /**\n     * In opening sequence.\n     *\n     * ```markdown\n     * > | $a$\n     *     ^\n     * ```\n     *\n     * @type {State}\n     */\n\n    function sequenceOpen(code) {\n      if (code === 36) {\n        effects.consume(code);\n        sizeOpen++;\n        return sequenceOpen;\n      }\n\n      // Not enough markers in the sequence.\n      if (sizeOpen < 2 && !single) {\n        return nok(code);\n      }\n      effects.exit('mathTextSequence');\n      return between(code);\n    }\n\n    /**\n     * Between something and something else.\n     *\n     * ```markdown\n     * > | $a$\n     *      ^^\n     * ```\n     *\n     * @type {State}\n     */\n    function between(code) {\n      if (code === null) {\n        return nok(code);\n      }\n      if (code === 36) {\n        token = effects.enter('mathTextSequence');\n        size = 0;\n        return sequenceClose(code);\n      }\n\n      // Tabs don’t work, and virtual spaces don’t make sense.\n      if (code === 32) {\n        effects.enter('space');\n        effects.consume(code);\n        effects.exit('space');\n        return between;\n      }\n      if (markdownLineEnding(code)) {\n        effects.enter(\"lineEnding\");\n        effects.consume(code);\n        effects.exit(\"lineEnding\");\n        return between;\n      }\n\n      // Data.\n      effects.enter('mathTextData');\n      return data(code);\n    }\n\n    /**\n     * In data.\n     *\n     * ```markdown\n     * > | $a$\n     *      ^\n     * ```\n     *\n     * @type {State}\n     */\n    function data(code) {\n      if (code === null || code === 32 || code === 36 || markdownLineEnding(code)) {\n        effects.exit('mathTextData');\n        return between(code);\n      }\n      effects.consume(code);\n      return data;\n    }\n\n    /**\n     * In closing sequence.\n     *\n     * ```markdown\n     * > | `a`\n     *       ^\n     * ```\n     *\n     * @type {State}\n     */\n\n    function sequenceClose(code) {\n      // More.\n      if (code === 36) {\n        effects.consume(code);\n        size++;\n        return sequenceClose;\n      }\n\n      // Done!\n      if (size === sizeOpen) {\n        effects.exit('mathTextSequence');\n        effects.exit('mathText');\n        return ok(code);\n      }\n\n      // More or less accents: mark as data.\n      token.type = 'mathTextData';\n      return data(code);\n    }\n  }\n}\n\n/** @type {Resolver} */\nfunction resolveMathText(events) {\n  let tailExitIndex = events.length - 4;\n  let headEnterIndex = 3;\n  /** @type {number} */\n  let index;\n  /** @type {number | undefined} */\n  let enter;\n\n  // If we start and end with an EOL or a space.\n  if ((events[headEnterIndex][1].type === \"lineEnding\" || events[headEnterIndex][1].type === 'space') && (events[tailExitIndex][1].type === \"lineEnding\" || events[tailExitIndex][1].type === 'space')) {\n    index = headEnterIndex;\n\n    // And we have data.\n    while (++index < tailExitIndex) {\n      if (events[index][1].type === 'mathTextData') {\n        // Then we have padding.\n        events[tailExitIndex][1].type = 'mathTextPadding';\n        events[headEnterIndex][1].type = 'mathTextPadding';\n        headEnterIndex += 2;\n        tailExitIndex -= 2;\n        break;\n      }\n    }\n  }\n\n  // Merge adjacent spaces and data.\n  index = headEnterIndex - 1;\n  tailExitIndex++;\n  while (++index <= tailExitIndex) {\n    if (enter === undefined) {\n      if (index !== tailExitIndex && events[index][1].type !== \"lineEnding\") {\n        enter = index;\n      }\n    } else if (index === tailExitIndex || events[index][1].type === \"lineEnding\") {\n      events[enter][1].type = 'mathTextData';\n      if (index !== enter + 2) {\n        events[enter][1].end = events[index - 1][1].end;\n        events.splice(enter + 2, index - enter - 2);\n        tailExitIndex -= index - enter - 2;\n        index = enter + 2;\n      }\n      enter = undefined;\n    }\n  }\n  return events;\n}\n\n/**\n * @this {TokenizeContext}\n * @type {Previous}\n */\nfunction previous(code) {\n  // If there is a previous code, there will always be a tail.\n  return code !== 36 || this.events[this.events.length - 1][1].type === \"characterEscape\";\n}","/**\n * @import {Options} from 'micromark-extension-math'\n * @import {Extension} from 'micromark-util-types'\n */\n\nimport { mathFlow } from './math-flow.js';\nimport { mathText } from './math-text.js';\n\n/**\n * Create an extension for `micromark` to enable math syntax.\n *\n * @param {Options | null | undefined} [options={}]\n *   Configuration (default: `{}`).\n * @returns {Extension}\n *   Extension for `micromark` that can be passed in `extensions`, to\n *   enable math syntax.\n */\nexport function math(options) {\n  return {\n    flow: {\n      [36]: mathFlow\n    },\n    text: {\n      [36]: mathText(options)\n    }\n  };\n}","/// <reference types=\"mdast-util-math\" />\n/// <reference types=\"remark-parse\" />\n/// <reference types=\"remark-stringify\" />\n\n/**\n * @typedef {import('mdast').Root} Root\n * @typedef {import('mdast-util-math').ToOptions} Options\n * @typedef {import('unified').Processor<Root>} Processor\n */\n\nimport {mathFromMarkdown, mathToMarkdown} from 'mdast-util-math'\nimport {math} from 'micromark-extension-math'\n\n/** @type {Readonly<Options>} */\nconst emptyOptions = {}\n\n/**\n * Add support for math.\n *\n * @param {Readonly<Options> | null | undefined} [options]\n *   Configuration (optional).\n * @returns {undefined}\n *   Nothing.\n */\nexport default function remarkMath(options) {\n  // @ts-expect-error: TS is wrong about `this`.\n  // eslint-disable-next-line unicorn/no-this-assignment\n  const self = /** @type {Processor} */ (this)\n  const settings = options || emptyOptions\n  const data = self.data()\n\n  const micromarkExtensions =\n    data.micromarkExtensions || (data.micromarkExtensions = [])\n  const fromMarkdownExtensions =\n    data.fromMarkdownExtensions || (data.fromMarkdownExtensions = [])\n  const toMarkdownExtensions =\n    data.toMarkdownExtensions || (data.toMarkdownExtensions = [])\n\n  micromarkExtensions.push(math(settings))\n  fromMarkdownExtensions.push(mathFromMarkdown())\n  toMarkdownExtensions.push(mathToMarkdown(settings))\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Blockquote} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `blockquote` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Blockquote} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function blockquote(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'blockquote',\n    properties: {},\n    children: state.wrap(state.all(node), true)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element, Text} from 'hast'\n * @import {Break} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `break` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Break} node\n *   mdast node.\n * @returns {Array<Element | Text>}\n *   hast element content.\n */\nexport function hardBreak(state, node) {\n  /** @type {Element} */\n  const result = {type: 'element', tagName: 'br', properties: {}, children: []}\n  state.patch(node, result)\n  return [state.applyData(node, result), {type: 'text', value: '\\n'}]\n}\n","/**\n * @import {Element, Properties} from 'hast'\n * @import {Code} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `code` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Code} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function code(state, node) {\n  const value = node.value ? node.value + '\\n' : ''\n  /** @type {Properties} */\n  const properties = {}\n  // Someone can write `js&#x20;python&#x9;ruby`.\n  const language = node.lang ? node.lang.split(/\\s+/) : []\n\n  // GH/CM still drop the non-first languages.\n  if (language.length > 0) {\n    properties.className = ['language-' + language[0]]\n  }\n\n  // Create `<code>`.\n  /** @type {Element} */\n  let result = {\n    type: 'element',\n    tagName: 'code',\n    properties,\n    children: [{type: 'text', value}]\n  }\n\n  if (node.meta) {\n    result.data = {meta: node.meta}\n  }\n\n  state.patch(node, result)\n  result = state.applyData(node, result)\n\n  // Create `<pre>`.\n  result = {type: 'element', tagName: 'pre', properties: {}, children: [result]}\n  state.patch(node, result)\n  return result\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Delete} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `delete` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Delete} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function strikethrough(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'del',\n    properties: {},\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Emphasis} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `emphasis` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Emphasis} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function emphasis(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'em',\n    properties: {},\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {FootnoteReference} from 'mdast'\n * @import {State} from '../state.js'\n */\n\nimport {normalizeUri} from 'micromark-util-sanitize-uri'\n\n/**\n * Turn an mdast `footnoteReference` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {FootnoteReference} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function footnoteReference(state, node) {\n  const clobberPrefix =\n    typeof state.options.clobberPrefix === 'string'\n      ? state.options.clobberPrefix\n      : 'user-content-'\n  const id = String(node.identifier).toUpperCase()\n  const safeId = normalizeUri(id.toLowerCase())\n  const index = state.footnoteOrder.indexOf(id)\n  /** @type {number} */\n  let counter\n\n  let reuseCounter = state.footnoteCounts.get(id)\n\n  if (reuseCounter === undefined) {\n    reuseCounter = 0\n    state.footnoteOrder.push(id)\n    counter = state.footnoteOrder.length\n  } else {\n    counter = index + 1\n  }\n\n  reuseCounter += 1\n  state.footnoteCounts.set(id, reuseCounter)\n\n  /** @type {Element} */\n  const link = {\n    type: 'element',\n    tagName: 'a',\n    properties: {\n      href: '#' + clobberPrefix + 'fn-' + safeId,\n      id:\n        clobberPrefix +\n        'fnref-' +\n        safeId +\n        (reuseCounter > 1 ? '-' + reuseCounter : ''),\n      dataFootnoteRef: true,\n      ariaDescribedBy: ['footnote-label']\n    },\n    children: [{type: 'text', value: String(counter)}]\n  }\n  state.patch(node, link)\n\n  /** @type {Element} */\n  const sup = {\n    type: 'element',\n    tagName: 'sup',\n    properties: {},\n    children: [link]\n  }\n  state.patch(node, sup)\n  return state.applyData(node, sup)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Heading} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `heading` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Heading} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function heading(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'h' + node.depth,\n    properties: {},\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Html} from 'mdast'\n * @import {State} from '../state.js'\n * @import {Raw} from '../../index.js'\n */\n\n/**\n * Turn an mdast `html` node into hast (`raw` node in dangerous mode, otherwise\n * nothing).\n *\n * @param {State} state\n *   Info passed around.\n * @param {Html} node\n *   mdast node.\n * @returns {Element | Raw | undefined}\n *   hast node.\n */\nexport function html(state, node) {\n  if (state.options.allowDangerousHtml) {\n    /** @type {Raw} */\n    const result = {type: 'raw', value: node.value}\n    state.patch(node, result)\n    return state.applyData(node, result)\n  }\n\n  return undefined\n}\n","/**\n * @import {ElementContent} from 'hast'\n * @import {Reference, Nodes} from 'mdast'\n * @import {State} from './state.js'\n */\n\n/**\n * Return the content of a reference without definition as plain text.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Extract<Nodes, Reference>} node\n *   Reference node (image, link).\n * @returns {Array<ElementContent>}\n *   hast content.\n */\nexport function revert(state, node) {\n  const subtype = node.referenceType\n  let suffix = ']'\n\n  if (subtype === 'collapsed') {\n    suffix += '[]'\n  } else if (subtype === 'full') {\n    suffix += '[' + (node.label || node.identifier) + ']'\n  }\n\n  if (node.type === 'imageReference') {\n    return [{type: 'text', value: '![' + node.alt + suffix}]\n  }\n\n  const contents = state.all(node)\n  const head = contents[0]\n\n  if (head && head.type === 'text') {\n    head.value = '[' + head.value\n  } else {\n    contents.unshift({type: 'text', value: '['})\n  }\n\n  const tail = contents[contents.length - 1]\n\n  if (tail && tail.type === 'text') {\n    tail.value += suffix\n  } else {\n    contents.push({type: 'text', value: suffix})\n  }\n\n  return contents\n}\n","/**\n * @import {ElementContent, Element, Properties} from 'hast'\n * @import {ImageReference} from 'mdast'\n * @import {State} from '../state.js'\n */\n\nimport {normalizeUri} from 'micromark-util-sanitize-uri'\nimport {revert} from '../revert.js'\n\n/**\n * Turn an mdast `imageReference` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {ImageReference} node\n *   mdast node.\n * @returns {Array<ElementContent> | ElementContent}\n *   hast node.\n */\nexport function imageReference(state, node) {\n  const id = String(node.identifier).toUpperCase()\n  const definition = state.definitionById.get(id)\n\n  if (!definition) {\n    return revert(state, node)\n  }\n\n  /** @type {Properties} */\n  const properties = {src: normalizeUri(definition.url || ''), alt: node.alt}\n\n  if (definition.title !== null && definition.title !== undefined) {\n    properties.title = definition.title\n  }\n\n  /** @type {Element} */\n  const result = {type: 'element', tagName: 'img', properties, children: []}\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element, Properties} from 'hast'\n * @import {Image} from 'mdast'\n * @import {State} from '../state.js'\n */\n\nimport {normalizeUri} from 'micromark-util-sanitize-uri'\n\n/**\n * Turn an mdast `image` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Image} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function image(state, node) {\n  /** @type {Properties} */\n  const properties = {src: normalizeUri(node.url)}\n\n  if (node.alt !== null && node.alt !== undefined) {\n    properties.alt = node.alt\n  }\n\n  if (node.title !== null && node.title !== undefined) {\n    properties.title = node.title\n  }\n\n  /** @type {Element} */\n  const result = {type: 'element', tagName: 'img', properties, children: []}\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element, Text} from 'hast'\n * @import {InlineCode} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `inlineCode` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {InlineCode} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function inlineCode(state, node) {\n  /** @type {Text} */\n  const text = {type: 'text', value: node.value.replace(/\\r?\\n|\\r/g, ' ')}\n  state.patch(node, text)\n\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'code',\n    properties: {},\n    children: [text]\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {ElementContent, Element, Properties} from 'hast'\n * @import {LinkReference} from 'mdast'\n * @import {State} from '../state.js'\n */\n\nimport {normalizeUri} from 'micromark-util-sanitize-uri'\nimport {revert} from '../revert.js'\n\n/**\n * Turn an mdast `linkReference` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {LinkReference} node\n *   mdast node.\n * @returns {Array<ElementContent> | ElementContent}\n *   hast node.\n */\nexport function linkReference(state, node) {\n  const id = String(node.identifier).toUpperCase()\n  const definition = state.definitionById.get(id)\n\n  if (!definition) {\n    return revert(state, node)\n  }\n\n  /** @type {Properties} */\n  const properties = {href: normalizeUri(definition.url || '')}\n\n  if (definition.title !== null && definition.title !== undefined) {\n    properties.title = definition.title\n  }\n\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'a',\n    properties,\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element, Properties} from 'hast'\n * @import {Link} from 'mdast'\n * @import {State} from '../state.js'\n */\n\nimport {normalizeUri} from 'micromark-util-sanitize-uri'\n\n/**\n * Turn an mdast `link` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Link} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function link(state, node) {\n  /** @type {Properties} */\n  const properties = {href: normalizeUri(node.url)}\n\n  if (node.title !== null && node.title !== undefined) {\n    properties.title = node.title\n  }\n\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'a',\n    properties,\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {ElementContent, Element, Properties} from 'hast'\n * @import {ListItem, Parents} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `listItem` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {ListItem} node\n *   mdast node.\n * @param {Parents | undefined} parent\n *   Parent of `node`.\n * @returns {Element}\n *   hast node.\n */\nexport function listItem(state, node, parent) {\n  const results = state.all(node)\n  const loose = parent ? listLoose(parent) : listItemLoose(node)\n  /** @type {Properties} */\n  const properties = {}\n  /** @type {Array<ElementContent>} */\n  const children = []\n\n  if (typeof node.checked === 'boolean') {\n    const head = results[0]\n    /** @type {Element} */\n    let paragraph\n\n    if (head && head.type === 'element' && head.tagName === 'p') {\n      paragraph = head\n    } else {\n      paragraph = {type: 'element', tagName: 'p', properties: {}, children: []}\n      results.unshift(paragraph)\n    }\n\n    if (paragraph.children.length > 0) {\n      paragraph.children.unshift({type: 'text', value: ' '})\n    }\n\n    paragraph.children.unshift({\n      type: 'element',\n      tagName: 'input',\n      properties: {type: 'checkbox', checked: node.checked, disabled: true},\n      children: []\n    })\n\n    // According to github-markdown-css, this class hides bullet.\n    // See: <https://github.com/sindresorhus/github-markdown-css>.\n    properties.className = ['task-list-item']\n  }\n\n  let index = -1\n\n  while (++index < results.length) {\n    const child = results[index]\n\n    // Add eols before nodes, except if this is a loose, first paragraph.\n    if (\n      loose ||\n      index !== 0 ||\n      child.type !== 'element' ||\n      child.tagName !== 'p'\n    ) {\n      children.push({type: 'text', value: '\\n'})\n    }\n\n    if (child.type === 'element' && child.tagName === 'p' && !loose) {\n      children.push(...child.children)\n    } else {\n      children.push(child)\n    }\n  }\n\n  const tail = results[results.length - 1]\n\n  // Add a final eol.\n  if (tail && (loose || tail.type !== 'element' || tail.tagName !== 'p')) {\n    children.push({type: 'text', value: '\\n'})\n  }\n\n  /** @type {Element} */\n  const result = {type: 'element', tagName: 'li', properties, children}\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n\n/**\n * @param {Parents} node\n * @return {Boolean}\n */\nfunction listLoose(node) {\n  let loose = false\n  if (node.type === 'list') {\n    loose = node.spread || false\n    const children = node.children\n    let index = -1\n\n    while (!loose && ++index < children.length) {\n      loose = listItemLoose(children[index])\n    }\n  }\n\n  return loose\n}\n\n/**\n * @param {ListItem} node\n * @return {Boolean}\n */\nfunction listItemLoose(node) {\n  const spread = node.spread\n\n  return spread === null || spread === undefined\n    ? node.children.length > 1\n    : spread\n}\n","/**\n * @import {Element, Properties} from 'hast'\n * @import {List} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `list` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {List} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function list(state, node) {\n  /** @type {Properties} */\n  const properties = {}\n  const results = state.all(node)\n  let index = -1\n\n  if (typeof node.start === 'number' && node.start !== 1) {\n    properties.start = node.start\n  }\n\n  // Like GitHub, add a class for custom styling.\n  while (++index < results.length) {\n    const child = results[index]\n\n    if (\n      child.type === 'element' &&\n      child.tagName === 'li' &&\n      child.properties &&\n      Array.isArray(child.properties.className) &&\n      child.properties.className.includes('task-list-item')\n    ) {\n      properties.className = ['contains-task-list']\n      break\n    }\n  }\n\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: node.ordered ? 'ol' : 'ul',\n    properties,\n    children: state.wrap(results, true)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Paragraph} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `paragraph` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Paragraph} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function paragraph(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'p',\n    properties: {},\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Parents as HastParents, Root as HastRoot} from 'hast'\n * @import {Root as MdastRoot} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `root` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {MdastRoot} node\n *   mdast node.\n * @returns {HastParents}\n *   hast node.\n */\nexport function root(state, node) {\n  /** @type {HastRoot} */\n  const result = {type: 'root', children: state.wrap(state.all(node))}\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {Strong} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `strong` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Strong} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function strong(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'strong',\n    properties: {},\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Point} Point\n * @typedef {import('unist').Position} Position\n */\n\n/**\n * @typedef NodeLike\n * @property {string} type\n * @property {PositionLike | null | undefined} [position]\n *\n * @typedef PositionLike\n * @property {PointLike | null | undefined} [start]\n * @property {PointLike | null | undefined} [end]\n *\n * @typedef PointLike\n * @property {number | null | undefined} [line]\n * @property {number | null | undefined} [column]\n * @property {number | null | undefined} [offset]\n */\n\n/**\n * Get the ending point of `node`.\n *\n * @param node\n *   Node.\n * @returns\n *   Point.\n */\nexport const pointEnd = point('end')\n\n/**\n * Get the starting point of `node`.\n *\n * @param node\n *   Node.\n * @returns\n *   Point.\n */\nexport const pointStart = point('start')\n\n/**\n * Get the positional info of `node`.\n *\n * @param {'end' | 'start'} type\n *   Side.\n * @returns\n *   Getter.\n */\nfunction point(type) {\n  return point\n\n  /**\n   * Get the point info of `node` at a bound side.\n   *\n   * @param {Node | NodeLike | null | undefined} [node]\n   * @returns {Point | undefined}\n   */\n  function point(node) {\n    const point = (node && node.position && node.position[type]) || {}\n\n    if (\n      typeof point.line === 'number' &&\n      point.line > 0 &&\n      typeof point.column === 'number' &&\n      point.column > 0\n    ) {\n      return {\n        line: point.line,\n        column: point.column,\n        offset:\n          typeof point.offset === 'number' && point.offset > -1\n            ? point.offset\n            : undefined\n      }\n    }\n  }\n}\n\n/**\n * Get the positional info of `node`.\n *\n * @param {Node | NodeLike | null | undefined} [node]\n *   Node.\n * @returns {Position | undefined}\n *   Position.\n */\nexport function position(node) {\n  const start = pointStart(node)\n  const end = pointEnd(node)\n\n  if (start && end) {\n    return {start, end}\n  }\n}\n","/**\n * @import {Table} from 'mdast'\n * @import {Element} from 'hast'\n * @import {State} from '../state.js'\n */\n\nimport {pointEnd, pointStart} from 'unist-util-position'\n\n/**\n * Turn an mdast `table` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {Table} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function table(state, node) {\n  const rows = state.all(node)\n  const firstRow = rows.shift()\n  /** @type {Array<Element>} */\n  const tableContent = []\n\n  if (firstRow) {\n    /** @type {Element} */\n    const head = {\n      type: 'element',\n      tagName: 'thead',\n      properties: {},\n      children: state.wrap([firstRow], true)\n    }\n    state.patch(node.children[0], head)\n    tableContent.push(head)\n  }\n\n  if (rows.length > 0) {\n    /** @type {Element} */\n    const body = {\n      type: 'element',\n      tagName: 'tbody',\n      properties: {},\n      children: state.wrap(rows, true)\n    }\n\n    const start = pointStart(node.children[1])\n    const end = pointEnd(node.children[node.children.length - 1])\n    if (start && end) body.position = {start, end}\n    tableContent.push(body)\n  }\n\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'table',\n    properties: {},\n    children: state.wrap(tableContent, true)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element, ElementContent, Properties} from 'hast'\n * @import {Parents, TableRow} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `tableRow` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {TableRow} node\n *   mdast node.\n * @param {Parents | undefined} parent\n *   Parent of `node`.\n * @returns {Element}\n *   hast node.\n */\nexport function tableRow(state, node, parent) {\n  const siblings = parent ? parent.children : undefined\n  // Generate a body row when without parent.\n  const rowIndex = siblings ? siblings.indexOf(node) : 1\n  const tagName = rowIndex === 0 ? 'th' : 'td'\n  // To do: option to use `style`?\n  const align = parent && parent.type === 'table' ? parent.align : undefined\n  const length = align ? align.length : node.children.length\n  let cellIndex = -1\n  /** @type {Array<ElementContent>} */\n  const cells = []\n\n  while (++cellIndex < length) {\n    // Note: can also be undefined.\n    const cell = node.children[cellIndex]\n    /** @type {Properties} */\n    const properties = {}\n    const alignValue = align ? align[cellIndex] : undefined\n\n    if (alignValue) {\n      properties.align = alignValue\n    }\n\n    /** @type {Element} */\n    let result = {type: 'element', tagName, properties, children: []}\n\n    if (cell) {\n      result.children = state.all(cell)\n      state.patch(cell, result)\n      result = state.applyData(cell, result)\n    }\n\n    cells.push(result)\n  }\n\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'tr',\n    properties: {},\n    children: state.wrap(cells, true)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {TableCell} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `tableCell` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {TableCell} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function tableCell(state, node) {\n  // Note: this function is normally not called: see `table-row` for how rows\n  // and their cells are compiled.\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'td', // Assume body cell.\n    properties: {},\n    children: state.all(node)\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","const tab = 9 /* `\\t` */\nconst space = 32 /* ` ` */\n\n/**\n * Remove initial and final spaces and tabs at the line breaks in `value`.\n * Does not trim initial and final spaces and tabs of the value itself.\n *\n * @param {string} value\n *   Value to trim.\n * @returns {string}\n *   Trimmed value.\n */\nexport function trimLines(value) {\n  const source = String(value)\n  const search = /\\r?\\n|\\r/g\n  let match = search.exec(source)\n  let last = 0\n  /** @type {Array<string>} */\n  const lines = []\n\n  while (match) {\n    lines.push(\n      trimLine(source.slice(last, match.index), last > 0, true),\n      match[0]\n    )\n\n    last = match.index + match[0].length\n    match = search.exec(source)\n  }\n\n  lines.push(trimLine(source.slice(last), last > 0, false))\n\n  return lines.join('')\n}\n\n/**\n * @param {string} value\n *   Line to trim.\n * @param {boolean} start\n *   Whether to trim the start of the line.\n * @param {boolean} end\n *   Whether to trim the end of the line.\n * @returns {string}\n *   Trimmed line.\n */\nfunction trimLine(value, start, end) {\n  let startIndex = 0\n  let endIndex = value.length\n\n  if (start) {\n    let code = value.codePointAt(startIndex)\n\n    while (code === tab || code === space) {\n      startIndex++\n      code = value.codePointAt(startIndex)\n    }\n  }\n\n  if (end) {\n    let code = value.codePointAt(endIndex - 1)\n\n    while (code === tab || code === space) {\n      endIndex--\n      code = value.codePointAt(endIndex - 1)\n    }\n  }\n\n  return endIndex > startIndex ? value.slice(startIndex, endIndex) : ''\n}\n","/**\n * @import {Element as HastElement, Text as HastText} from 'hast'\n * @import {Text as MdastText} from 'mdast'\n * @import {State} from '../state.js'\n */\n\nimport {trimLines} from 'trim-lines'\n\n/**\n * Turn an mdast `text` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {MdastText} node\n *   mdast node.\n * @returns {HastElement | HastText}\n *   hast node.\n */\nexport function text(state, node) {\n  /** @type {HastText} */\n  const result = {type: 'text', value: trimLines(String(node.value))}\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Element} from 'hast'\n * @import {ThematicBreak} from 'mdast'\n * @import {State} from '../state.js'\n */\n\n/**\n * Turn an mdast `thematicBreak` node into hast.\n *\n * @param {State} state\n *   Info passed around.\n * @param {ThematicBreak} node\n *   mdast node.\n * @returns {Element}\n *   hast node.\n */\nexport function thematicBreak(state, node) {\n  /** @type {Element} */\n  const result = {\n    type: 'element',\n    tagName: 'hr',\n    properties: {},\n    children: []\n  }\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n","/**\n * @import {Handlers} from '../state.js'\n */\n\nimport {blockquote} from './blockquote.js'\nimport {hardBreak} from './break.js'\nimport {code} from './code.js'\nimport {strikethrough} from './delete.js'\nimport {emphasis} from './emphasis.js'\nimport {footnoteReference} from './footnote-reference.js'\nimport {heading} from './heading.js'\nimport {html} from './html.js'\nimport {imageReference} from './image-reference.js'\nimport {image} from './image.js'\nimport {inlineCode} from './inline-code.js'\nimport {linkReference} from './link-reference.js'\nimport {link} from './link.js'\nimport {listItem} from './list-item.js'\nimport {list} from './list.js'\nimport {paragraph} from './paragraph.js'\nimport {root} from './root.js'\nimport {strong} from './strong.js'\nimport {table} from './table.js'\nimport {tableRow} from './table-row.js'\nimport {tableCell} from './table-cell.js'\nimport {text} from './text.js'\nimport {thematicBreak} from './thematic-break.js'\n\n/**\n * Default handlers for nodes.\n *\n * @satisfies {Handlers}\n */\nexport const handlers = {\n  blockquote,\n  break: hardBreak,\n  code,\n  delete: strikethrough,\n  emphasis,\n  footnoteReference,\n  heading,\n  html,\n  imageReference,\n  image,\n  inlineCode,\n  linkReference,\n  link,\n  listItem,\n  list,\n  paragraph,\n  // @ts-expect-error: root is different, but hard to type.\n  root,\n  strong,\n  table,\n  tableCell,\n  tableRow,\n  text,\n  thematicBreak,\n  toml: ignore,\n  yaml: ignore,\n  definition: ignore,\n  footnoteDefinition: ignore\n}\n\n// Return nothing for nodes that are ignored.\nfunction ignore() {\n  return undefined\n}\n","import {\n  VOID, PRIMITIVE,\n  ARRAY, OBJECT,\n  DATE, REGEXP, MAP, SET,\n  ERROR, BIGINT\n} from './types.js';\n\nconst env = typeof self === 'object' ? self : globalThis;\n\nconst guard = (name, init) => {\n  switch (name) {\n    case 'Function':\n    case 'SharedWorker':\n    case 'Worker':\n    case 'eval':\n    case 'setInterval':\n    case 'setTimeout':\n      throw new TypeError('unable to deserialize ' + name);\n  }\n  return new env[name](init);\n};\n\nconst deserializer = ($, _) => {\n  const as = (out, index) => {\n    $.set(index, out);\n    return out;\n  };\n\n  const unpair = index => {\n    if ($.has(index))\n      return $.get(index);\n\n    const [type, value] = _[index];\n    switch (type) {\n      case PRIMITIVE:\n      case VOID:\n        return as(value, index);\n      case ARRAY: {\n        const arr = as([], index);\n        for (const index of value)\n          arr.push(unpair(index));\n        return arr;\n      }\n      case OBJECT: {\n        const object = as({}, index);\n        for (const [key, index] of value)\n          object[unpair(key)] = unpair(index);\n        return object;\n      }\n      case DATE:\n        return as(new Date(value), index);\n      case REGEXP: {\n        const {source, flags} = value;\n        return as(new RegExp(source, flags), index);\n      }\n      case MAP: {\n        const map = as(new Map, index);\n        for (const [key, index] of value)\n          map.set(unpair(key), unpair(index));\n        return map;\n      }\n      case SET: {\n        const set = as(new Set, index);\n        for (const index of value)\n          set.add(unpair(index));\n        return set;\n      }\n      case ERROR: {\n        const {name, message} = value;\n        return as(\n          typeof env[name] === 'function' ?\n            guard(name, message) :\n            new Error(message),\n          index\n        );\n      }\n      case BIGINT:\n        return as(BigInt(value), index);\n      case 'BigInt':\n        return as(Object(BigInt(value)), index);\n      case 'ArrayBuffer':\n        return as(new Uint8Array(value).buffer, value);\n      case 'DataView': {\n        const { buffer } = new Uint8Array(value);\n        return as(new DataView(buffer), value);\n      }\n    }\n    return as(guard(type, value), index);\n  };\n\n  return unpair;\n};\n\n/**\n * @typedef {Array<string,any>} Record a type representation\n */\n\n/**\n * Returns a deserialized value from a serialized array of Records.\n * @param {Record[]} serialized a previously serialized value.\n * @returns {any}\n */\nexport const deserialize = serialized => deserializer(new Map, serialized)(0);\n","import {\n  VOID, PRIMITIVE,\n  ARRAY, OBJECT,\n  DATE, REGEXP, MAP, SET,\n  ERROR, BIGINT\n} from './types.js';\n\nconst EMPTY = '';\n\nconst {toString} = {};\nconst {keys} = Object;\n\nconst typeOf = value => {\n  const type = typeof value;\n  if (type !== 'object' || !value)\n    return [PRIMITIVE, type];\n\n  const asString = toString.call(value).slice(8, -1);\n  switch (asString) {\n    case 'Array':\n      return [ARRAY, EMPTY];\n    case 'Object':\n      return [OBJECT, EMPTY];\n    case 'Date':\n      return [DATE, EMPTY];\n    case 'RegExp':\n      return [REGEXP, EMPTY];\n    case 'Map':\n      return [MAP, EMPTY];\n    case 'Set':\n      return [SET, EMPTY];\n    case 'DataView':\n      return [ARRAY, asString];\n  }\n\n  if (asString.includes('Array'))\n    return [ARRAY, asString];\n\n  if (value instanceof Error)\n    return [ERROR, value.name || 'Error'];\n\n  return [OBJECT, asString];\n};\n\nconst shouldSkip = ([TYPE, type]) => (\n  TYPE === PRIMITIVE &&\n  (type === 'function' || type === 'symbol')\n);\n\nconst serializer = (strict, json, $, _) => {\n\n  const as = (out, value) => {\n    const index = _.push(out) - 1;\n    $.set(value, index);\n    return index;\n  };\n\n  const pair = value => {\n    if ($.has(value))\n      return $.get(value);\n\n    let [TYPE, type] = typeOf(value);\n    switch (TYPE) {\n      case PRIMITIVE: {\n        let entry = value;\n        switch (type) {\n          case 'bigint':\n            TYPE = BIGINT;\n            entry = value.toString();\n            break;\n          case 'function':\n          case 'symbol':\n            if (strict)\n              throw new TypeError('unable to serialize ' + type);\n            entry = null;\n            break;\n          case 'undefined':\n            return as([VOID], value);\n        }\n        return as([TYPE, entry], value);\n      }\n      case ARRAY: {\n        if (type) {\n          let spread = value;\n          if (type === 'DataView') {\n            spread = new Uint8Array(value.buffer);\n          }\n          else if (type === 'ArrayBuffer') {\n            spread = new Uint8Array(value);\n          }\n          return as([type, [...spread]], value);\n        }\n\n        const arr = [];\n        const index = as([TYPE, arr], value);\n        for (const entry of value)\n          arr.push(pair(entry));\n        return index;\n      }\n      case OBJECT: {\n        if (type) {\n          switch (type) {\n            case 'BigInt':\n              return as([type, value.toString()], value);\n            case 'Boolean':\n            case 'Number':\n            case 'String':\n              return as([type, value.valueOf()], value);\n          }\n        }\n\n        if (json && ('toJSON' in value))\n          return pair(value.toJSON());\n\n        const entries = [];\n        const index = as([TYPE, entries], value);\n        for (const key of keys(value)) {\n          if (strict || !shouldSkip(typeOf(value[key])))\n            entries.push([pair(key), pair(value[key])]);\n        }\n        return index;\n      }\n      case DATE:\n        return as([TYPE, isNaN(value.getTime()) ? EMPTY : value.toISOString()], value);\n      case REGEXP: {\n        const {source, flags} = value;\n        return as([TYPE, {source, flags}], value);\n      }\n      case MAP: {\n        const entries = [];\n        const index = as([TYPE, entries], value);\n        for (const [key, entry] of value) {\n          if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry))))\n            entries.push([pair(key), pair(entry)]);\n        }\n        return index;\n      }\n      case SET: {\n        const entries = [];\n        const index = as([TYPE, entries], value);\n        for (const entry of value) {\n          if (strict || !shouldSkip(typeOf(entry)))\n            entries.push(pair(entry));\n        }\n        return index;\n      }\n    }\n\n    const {message} = value;\n    return as([TYPE, {name: type, message}], value);\n  };\n\n  return pair;\n};\n\n/**\n * @typedef {Array<string,any>} Record a type representation\n */\n\n/**\n * Returns an array of serialized Records.\n * @param {any} value a serializable value.\n * @param {{json?: boolean, lossy?: boolean}?} options an object with a `lossy` or `json` property that,\n *  if `true`, will not throw errors on incompatible types, and behave more\n *  like JSON stringify would behave. Symbol and Function will be discarded.\n * @returns {Record[]}\n */\n export const serialize = (value, {json, lossy} = {}) => {\n  const _ = [];\n  return serializer(!(json || lossy), !!json, new Map, _)(value), _;\n};\n","import {deserialize} from './deserialize.js';\nimport {serialize} from './serialize.js';\n\n/**\n * @typedef {Array<string,any>} Record a type representation\n */\n\n/**\n * Returns an array of serialized Records.\n * @param {any} any a serializable value.\n * @param {{transfer?: any[], json?: boolean, lossy?: boolean}?} options an object with\n * a transfer option (ignored when polyfilled) and/or non standard fields that\n * fallback to the polyfill if present.\n * @returns {Record[]}\n */\nexport default typeof structuredClone === \"function\" ?\n  /* c8 ignore start */\n  (any, options) => (\n    options && ('json' in options || 'lossy' in options) ?\n      deserialize(serialize(any, options)) : structuredClone(any)\n  ) :\n  (any, options) => deserialize(serialize(any, options));\n  /* c8 ignore stop */\n\nexport {deserialize, serialize};\n","/**\n * @import {ElementContent, Element} from 'hast'\n * @import {State} from './state.js'\n */\n\n/**\n * @callback FootnoteBackContentTemplate\n *   Generate content for the backreference dynamically.\n *\n *   For the following markdown:\n *\n *   ```markdown\n *   Alpha[^micromark], bravo[^micromark], and charlie[^remark].\n *\n *   [^remark]: things about remark\n *   [^micromark]: things about micromark\n *   ```\n *\n *   This function will be called with:\n *\n *   *  `0` and `0` for the backreference from `things about micromark` to\n *      `alpha`, as it is the first used definition, and the first call to it\n *   *  `0` and `1` for the backreference from `things about micromark` to\n *      `bravo`, as it is the first used definition, and the second call to it\n *   *  `1` and `0` for the backreference from `things about remark` to\n *      `charlie`, as it is the second used definition\n * @param {number} referenceIndex\n *   Index of the definition in the order that they are first referenced,\n *   0-indexed.\n * @param {number} rereferenceIndex\n *   Index of calls to the same definition, 0-indexed.\n * @returns {Array<ElementContent> | ElementContent | string}\n *   Content for the backreference when linking back from definitions to their\n *   reference.\n *\n * @callback FootnoteBackLabelTemplate\n *   Generate a back label dynamically.\n *\n *   For the following markdown:\n *\n *   ```markdown\n *   Alpha[^micromark], bravo[^micromark], and charlie[^remark].\n *\n *   [^remark]: things about remark\n *   [^micromark]: things about micromark\n *   ```\n *\n *   This function will be called with:\n *\n *   *  `0` and `0` for the backreference from `things about micromark` to\n *      `alpha`, as it is the first used definition, and the first call to it\n *   *  `0` and `1` for the backreference from `things about micromark` to\n *      `bravo`, as it is the first used definition, and the second call to it\n *   *  `1` and `0` for the backreference from `things about remark` to\n *      `charlie`, as it is the second used definition\n * @param {number} referenceIndex\n *   Index of the definition in the order that they are first referenced,\n *   0-indexed.\n * @param {number} rereferenceIndex\n *   Index of calls to the same definition, 0-indexed.\n * @returns {string}\n *   Back label to use when linking back from definitions to their reference.\n */\n\nimport structuredClone from '@ungap/structured-clone'\nimport {normalizeUri} from 'micromark-util-sanitize-uri'\n\n/**\n * Generate the default content that GitHub uses on backreferences.\n *\n * @param {number} _\n *   Index of the definition in the order that they are first referenced,\n *   0-indexed.\n * @param {number} rereferenceIndex\n *   Index of calls to the same definition, 0-indexed.\n * @returns {Array<ElementContent>}\n *   Content.\n */\nexport function defaultFootnoteBackContent(_, rereferenceIndex) {\n  /** @type {Array<ElementContent>} */\n  const result = [{type: 'text', value: '↩'}]\n\n  if (rereferenceIndex > 1) {\n    result.push({\n      type: 'element',\n      tagName: 'sup',\n      properties: {},\n      children: [{type: 'text', value: String(rereferenceIndex)}]\n    })\n  }\n\n  return result\n}\n\n/**\n * Generate the default label that GitHub uses on backreferences.\n *\n * @param {number} referenceIndex\n *   Index of the definition in the order that they are first referenced,\n *   0-indexed.\n * @param {number} rereferenceIndex\n *   Index of calls to the same definition, 0-indexed.\n * @returns {string}\n *   Label.\n */\nexport function defaultFootnoteBackLabel(referenceIndex, rereferenceIndex) {\n  return (\n    'Back to reference ' +\n    (referenceIndex + 1) +\n    (rereferenceIndex > 1 ? '-' + rereferenceIndex : '')\n  )\n}\n\n/**\n * Generate a hast footer for called footnote definitions.\n *\n * @param {State} state\n *   Info passed around.\n * @returns {Element | undefined}\n *   `section` element or `undefined`.\n */\n// eslint-disable-next-line complexity\nexport function footer(state) {\n  const clobberPrefix =\n    typeof state.options.clobberPrefix === 'string'\n      ? state.options.clobberPrefix\n      : 'user-content-'\n  const footnoteBackContent =\n    state.options.footnoteBackContent || defaultFootnoteBackContent\n  const footnoteBackLabel =\n    state.options.footnoteBackLabel || defaultFootnoteBackLabel\n  const footnoteLabel = state.options.footnoteLabel || 'Footnotes'\n  const footnoteLabelTagName = state.options.footnoteLabelTagName || 'h2'\n  const footnoteLabelProperties = state.options.footnoteLabelProperties || {\n    className: ['sr-only']\n  }\n  /** @type {Array<ElementContent>} */\n  const listItems = []\n  let referenceIndex = -1\n\n  while (++referenceIndex < state.footnoteOrder.length) {\n    const definition = state.footnoteById.get(\n      state.footnoteOrder[referenceIndex]\n    )\n\n    if (!definition) {\n      continue\n    }\n\n    const content = state.all(definition)\n    const id = String(definition.identifier).toUpperCase()\n    const safeId = normalizeUri(id.toLowerCase())\n    let rereferenceIndex = 0\n    /** @type {Array<ElementContent>} */\n    const backReferences = []\n    const counts = state.footnoteCounts.get(id)\n\n    // eslint-disable-next-line no-unmodified-loop-condition\n    while (counts !== undefined && ++rereferenceIndex <= counts) {\n      if (backReferences.length > 0) {\n        backReferences.push({type: 'text', value: ' '})\n      }\n\n      let children =\n        typeof footnoteBackContent === 'string'\n          ? footnoteBackContent\n          : footnoteBackContent(referenceIndex, rereferenceIndex)\n\n      if (typeof children === 'string') {\n        children = {type: 'text', value: children}\n      }\n\n      backReferences.push({\n        type: 'element',\n        tagName: 'a',\n        properties: {\n          href:\n            '#' +\n            clobberPrefix +\n            'fnref-' +\n            safeId +\n            (rereferenceIndex > 1 ? '-' + rereferenceIndex : ''),\n          dataFootnoteBackref: '',\n          ariaLabel:\n            typeof footnoteBackLabel === 'string'\n              ? footnoteBackLabel\n              : footnoteBackLabel(referenceIndex, rereferenceIndex),\n          className: ['data-footnote-backref']\n        },\n        children: Array.isArray(children) ? children : [children]\n      })\n    }\n\n    const tail = content[content.length - 1]\n\n    if (tail && tail.type === 'element' && tail.tagName === 'p') {\n      const tailTail = tail.children[tail.children.length - 1]\n      if (tailTail && tailTail.type === 'text') {\n        tailTail.value += ' '\n      } else {\n        tail.children.push({type: 'text', value: ' '})\n      }\n\n      tail.children.push(...backReferences)\n    } else {\n      content.push(...backReferences)\n    }\n\n    /** @type {Element} */\n    const listItem = {\n      type: 'element',\n      tagName: 'li',\n      properties: {id: clobberPrefix + 'fn-' + safeId},\n      children: state.wrap(content, true)\n    }\n\n    state.patch(definition, listItem)\n\n    listItems.push(listItem)\n  }\n\n  if (listItems.length === 0) {\n    return\n  }\n\n  return {\n    type: 'element',\n    tagName: 'section',\n    properties: {dataFootnotes: true, className: ['footnotes']},\n    children: [\n      {\n        type: 'element',\n        tagName: footnoteLabelTagName,\n        properties: {\n          ...structuredClone(footnoteLabelProperties),\n          id: 'footnote-label'\n        },\n        children: [{type: 'text', value: footnoteLabel}]\n      },\n      {type: 'text', value: '\\n'},\n      {\n        type: 'element',\n        tagName: 'ol',\n        properties: {},\n        children: state.wrap(listItems, true)\n      },\n      {type: 'text', value: '\\n'}\n    ]\n  }\n}\n","/**\n * @import {\n *   ElementContent as HastElementContent,\n *   Element as HastElement,\n *   Nodes as HastNodes,\n *   Properties as HastProperties,\n *   RootContent as HastRootContent,\n *   Text as HastText\n * } from 'hast'\n * @import {\n *   Definition as MdastDefinition,\n *   FootnoteDefinition as MdastFootnoteDefinition,\n *   Nodes as MdastNodes,\n *   Parents as MdastParents\n * } from 'mdast'\n * @import {VFile} from 'vfile'\n * @import {\n *   FootnoteBackContentTemplate,\n *   FootnoteBackLabelTemplate\n * } from './footer.js'\n */\n\n/**\n * @callback Handler\n *   Handle a node.\n * @param {State} state\n *   Info passed around.\n * @param {any} node\n *   mdast node to handle.\n * @param {MdastParents | undefined} parent\n *   Parent of `node`.\n * @returns {Array<HastElementContent> | HastElementContent | undefined}\n *   hast node.\n *\n * @typedef {Partial<Record<MdastNodes['type'], Handler>>} Handlers\n *   Handle nodes.\n *\n * @typedef Options\n *   Configuration (optional).\n * @property {boolean | null | undefined} [allowDangerousHtml=false]\n *   Whether to persist raw HTML in markdown in the hast tree (default:\n *   `false`).\n * @property {string | null | undefined} [clobberPrefix='user-content-']\n *   Prefix to use before the `id` property on footnotes to prevent them from\n *   *clobbering* (default: `'user-content-'`).\n *\n *   Pass `''` for trusted markdown and when you are careful with\n *   polyfilling.\n *   You could pass a different prefix.\n *\n *   DOM clobbering is this:\n *\n *   ```html\n *   <p id=\"x\"></p>\n *   <script>alert(x) // `x` now refers to the `p#x` DOM element</script>\n *   ```\n *\n *   The above example shows that elements are made available by browsers, by\n *   their ID, on the `window` object.\n *   This is a security risk because you might be expecting some other variable\n *   at that place.\n *   It can also break polyfills.\n *   Using a prefix solves these problems.\n * @property {VFile | null | undefined} [file]\n *   Corresponding virtual file representing the input document (optional).\n * @property {FootnoteBackContentTemplate | string | null | undefined} [footnoteBackContent]\n *   Content of the backreference back to references (default: `defaultFootnoteBackContent`).\n *\n *   The default value is:\n *\n *   ```js\n *   function defaultFootnoteBackContent(_, rereferenceIndex) {\n *     const result = [{type: 'text', value: '↩'}]\n *\n *     if (rereferenceIndex > 1) {\n *       result.push({\n *         type: 'element',\n *         tagName: 'sup',\n *         properties: {},\n *         children: [{type: 'text', value: String(rereferenceIndex)}]\n *       })\n *     }\n *\n *     return result\n *   }\n *   ```\n *\n *   This content is used in the `a` element of each backreference (the `↩`\n *   links).\n * @property {FootnoteBackLabelTemplate | string | null | undefined} [footnoteBackLabel]\n *   Label to describe the backreference back to references (default:\n *   `defaultFootnoteBackLabel`).\n *\n *   The default value is:\n *\n *   ```js\n *   function defaultFootnoteBackLabel(referenceIndex, rereferenceIndex) {\n *    return (\n *      'Back to reference ' +\n *      (referenceIndex + 1) +\n *      (rereferenceIndex > 1 ? '-' + rereferenceIndex : '')\n *    )\n *   }\n *   ```\n *\n *   Change it when the markdown is not in English.\n *\n *   This label is used in the `ariaLabel` property on each backreference\n *   (the `↩` links).\n *   It affects users of assistive technology.\n * @property {string | null | undefined} [footnoteLabel='Footnotes']\n *   Textual label to use for the footnotes section (default: `'Footnotes'`).\n *\n *   Change it when the markdown is not in English.\n *\n *   This label is typically hidden visually (assuming a `sr-only` CSS class\n *   is defined that does that) and so affects screen readers only.\n *   If you do have such a class, but want to show this section to everyone,\n *   pass different properties with the `footnoteLabelProperties` option.\n * @property {HastProperties | null | undefined} [footnoteLabelProperties={className: ['sr-only']}]\n *   Properties to use on the footnote label (default: `{className:\n *   ['sr-only']}`).\n *\n *   Change it to show the label and add other properties.\n *\n *   This label is typically hidden visually (assuming an `sr-only` CSS class\n *   is defined that does that) and so affects screen readers only.\n *   If you do have such a class, but want to show this section to everyone,\n *   pass an empty string.\n *   You can also add different properties.\n *\n *   > **Note**: `id: 'footnote-label'` is always added, because footnote\n *   > calls use it with `aria-describedby` to provide an accessible label.\n * @property {string | null | undefined} [footnoteLabelTagName='h2']\n *   HTML tag name to use for the footnote label element (default: `'h2'`).\n *\n *   Change it to match your document structure.\n *\n *   This label is typically hidden visually (assuming a `sr-only` CSS class\n *   is defined that does that) and so affects screen readers only.\n *   If you do have such a class, but want to show this section to everyone,\n *   pass different properties with the `footnoteLabelProperties` option.\n * @property {Handlers | null | undefined} [handlers]\n *   Extra handlers for nodes (optional).\n * @property {Array<MdastNodes['type']> | null | undefined} [passThrough]\n *   List of custom mdast node types to pass through (keep) in hast (note that\n *   the node itself is passed, but eventual children are transformed)\n *   (optional).\n * @property {Handler | null | undefined} [unknownHandler]\n *   Handler for all unknown nodes (optional).\n *\n * @typedef State\n *   Info passed around.\n * @property {(node: MdastNodes) => Array<HastElementContent>} all\n *   Transform the children of an mdast parent to hast.\n * @property {<Type extends HastNodes>(from: MdastNodes, to: Type) => HastElement | Type} applyData\n *   Honor the `data` of `from`, and generate an element instead of `node`.\n * @property {Map<string, MdastDefinition>} definitionById\n *   Definitions by their identifier.\n * @property {Map<string, MdastFootnoteDefinition>} footnoteById\n *   Footnote definitions by their identifier.\n * @property {Map<string, number>} footnoteCounts\n *   Counts for how often the same footnote was called.\n * @property {Array<string>} footnoteOrder\n *   Identifiers of order when footnote calls first appear in tree order.\n * @property {Handlers} handlers\n *   Applied handlers.\n * @property {(node: MdastNodes, parent: MdastParents | undefined) => Array<HastElementContent> | HastElementContent | undefined} one\n *   Transform an mdast node to hast.\n * @property {Options} options\n *   Configuration.\n * @property {(from: MdastNodes, node: HastNodes) => undefined} patch\n *   Copy a node’s positional info.\n * @property {<Type extends HastRootContent>(nodes: Array<Type>, loose?: boolean | undefined) => Array<HastText | Type>} wrap\n *   Wrap `nodes` with line endings between each node, adds initial/final line endings when `loose`.\n */\n\nimport structuredClone from '@ungap/structured-clone'\nimport {visit} from 'unist-util-visit'\nimport {position} from 'unist-util-position'\nimport {handlers as defaultHandlers} from './handlers/index.js'\n\nconst own = {}.hasOwnProperty\n\n/** @type {Options} */\nconst emptyOptions = {}\n\n/**\n * Create `state` from an mdast tree.\n *\n * @param {MdastNodes} tree\n *   mdast node to transform.\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {State}\n *   `state` function.\n */\nexport function createState(tree, options) {\n  const settings = options || emptyOptions\n  /** @type {Map<string, MdastDefinition>} */\n  const definitionById = new Map()\n  /** @type {Map<string, MdastFootnoteDefinition>} */\n  const footnoteById = new Map()\n  /** @type {Map<string, number>} */\n  const footnoteCounts = new Map()\n  /** @type {Handlers} */\n  // @ts-expect-error: the root handler returns a root.\n  // Hard to type.\n  const handlers = {...defaultHandlers, ...settings.handlers}\n\n  /** @type {State} */\n  const state = {\n    all,\n    applyData,\n    definitionById,\n    footnoteById,\n    footnoteCounts,\n    footnoteOrder: [],\n    handlers,\n    one,\n    options: settings,\n    patch,\n    wrap\n  }\n\n  visit(tree, function (node) {\n    if (node.type === 'definition' || node.type === 'footnoteDefinition') {\n      const map = node.type === 'definition' ? definitionById : footnoteById\n      const id = String(node.identifier).toUpperCase()\n\n      // Mimick CM behavior of link definitions.\n      // See: <https://github.com/syntax-tree/mdast-util-definitions/blob/9032189/lib/index.js#L20-L21>.\n      if (!map.has(id)) {\n        // @ts-expect-error: node type matches map.\n        map.set(id, node)\n      }\n    }\n  })\n\n  return state\n\n  /**\n   * Transform an mdast node into a hast node.\n   *\n   * @param {MdastNodes} node\n   *   mdast node.\n   * @param {MdastParents | undefined} [parent]\n   *   Parent of `node`.\n   * @returns {Array<HastElementContent> | HastElementContent | undefined}\n   *   Resulting hast node.\n   */\n  function one(node, parent) {\n    const type = node.type\n    const handle = state.handlers[type]\n\n    if (own.call(state.handlers, type) && handle) {\n      return handle(state, node, parent)\n    }\n\n    if (state.options.passThrough && state.options.passThrough.includes(type)) {\n      if ('children' in node) {\n        const {children, ...shallow} = node\n        const result = structuredClone(shallow)\n        // @ts-expect-error: TS doesn’t understand…\n        result.children = state.all(node)\n        // @ts-expect-error: TS doesn’t understand…\n        return result\n      }\n\n      // @ts-expect-error: it’s custom.\n      return structuredClone(node)\n    }\n\n    const unknown = state.options.unknownHandler || defaultUnknownHandler\n\n    return unknown(state, node, parent)\n  }\n\n  /**\n   * Transform the children of an mdast node into hast nodes.\n   *\n   * @param {MdastNodes} parent\n   *   mdast node to compile\n   * @returns {Array<HastElementContent>}\n   *   Resulting hast nodes.\n   */\n  function all(parent) {\n    /** @type {Array<HastElementContent>} */\n    const values = []\n\n    if ('children' in parent) {\n      const nodes = parent.children\n      let index = -1\n      while (++index < nodes.length) {\n        const result = state.one(nodes[index], parent)\n\n        // To do: see if we van clean this? Can we merge texts?\n        if (result) {\n          if (index && nodes[index - 1].type === 'break') {\n            if (!Array.isArray(result) && result.type === 'text') {\n              result.value = trimMarkdownSpaceStart(result.value)\n            }\n\n            if (!Array.isArray(result) && result.type === 'element') {\n              const head = result.children[0]\n\n              if (head && head.type === 'text') {\n                head.value = trimMarkdownSpaceStart(head.value)\n              }\n            }\n          }\n\n          if (Array.isArray(result)) {\n            values.push(...result)\n          } else {\n            values.push(result)\n          }\n        }\n      }\n    }\n\n    return values\n  }\n}\n\n/**\n * Copy a node’s positional info.\n *\n * @param {MdastNodes} from\n *   mdast node to copy from.\n * @param {HastNodes} to\n *   hast node to copy into.\n * @returns {undefined}\n *   Nothing.\n */\nfunction patch(from, to) {\n  if (from.position) to.position = position(from)\n}\n\n/**\n * Honor the `data` of `from` and maybe generate an element instead of `to`.\n *\n * @template {HastNodes} Type\n *   Node type.\n * @param {MdastNodes} from\n *   mdast node to use data from.\n * @param {Type} to\n *   hast node to change.\n * @returns {HastElement | Type}\n *   Nothing.\n */\nfunction applyData(from, to) {\n  /** @type {HastElement | Type} */\n  let result = to\n\n  // Handle `data.hName`, `data.hProperties, `data.hChildren`.\n  if (from && from.data) {\n    const hName = from.data.hName\n    const hChildren = from.data.hChildren\n    const hProperties = from.data.hProperties\n\n    if (typeof hName === 'string') {\n      // Transforming the node resulted in an element with a different name\n      // than wanted:\n      if (result.type === 'element') {\n        result.tagName = hName\n      }\n      // Transforming the node resulted in a non-element, which happens for\n      // raw, text, and root nodes (unless custom handlers are passed).\n      // The intent of `hName` is to create an element, but likely also to keep\n      // the content around (otherwise: pass `hChildren`).\n      else {\n        /** @type {Array<HastElementContent>} */\n        // @ts-expect-error: assume no doctypes in `root`.\n        const children = 'children' in result ? result.children : [result]\n        result = {type: 'element', tagName: hName, properties: {}, children}\n      }\n    }\n\n    if (result.type === 'element' && hProperties) {\n      Object.assign(result.properties, structuredClone(hProperties))\n    }\n\n    if (\n      'children' in result &&\n      result.children &&\n      hChildren !== null &&\n      hChildren !== undefined\n    ) {\n      result.children = hChildren\n    }\n  }\n\n  return result\n}\n\n/**\n * Transform an unknown node.\n *\n * @param {State} state\n *   Info passed around.\n * @param {MdastNodes} node\n *   Unknown mdast node.\n * @returns {HastElement | HastText}\n *   Resulting hast node.\n */\nfunction defaultUnknownHandler(state, node) {\n  const data = node.data || {}\n  /** @type {HastElement | HastText} */\n  const result =\n    'value' in node &&\n    !(own.call(data, 'hProperties') || own.call(data, 'hChildren'))\n      ? {type: 'text', value: node.value}\n      : {\n          type: 'element',\n          tagName: 'div',\n          properties: {},\n          children: state.all(node)\n        }\n\n  state.patch(node, result)\n  return state.applyData(node, result)\n}\n\n/**\n * Wrap `nodes` with line endings between each node.\n *\n * @template {HastRootContent} Type\n *   Node type.\n * @param {Array<Type>} nodes\n *   List of nodes to wrap.\n * @param {boolean | undefined} [loose=false]\n *   Whether to add line endings at start and end (default: `false`).\n * @returns {Array<HastText | Type>}\n *   Wrapped nodes.\n */\nexport function wrap(nodes, loose) {\n  /** @type {Array<HastText | Type>} */\n  const result = []\n  let index = -1\n\n  if (loose) {\n    result.push({type: 'text', value: '\\n'})\n  }\n\n  while (++index < nodes.length) {\n    if (index) result.push({type: 'text', value: '\\n'})\n    result.push(nodes[index])\n  }\n\n  if (loose && nodes.length > 0) {\n    result.push({type: 'text', value: '\\n'})\n  }\n\n  return result\n}\n\n/**\n * Trim spaces and tabs at the start of `value`.\n *\n * @param {string} value\n *   Value to trim.\n * @returns {string}\n *   Result.\n */\nfunction trimMarkdownSpaceStart(value) {\n  let index = 0\n  let code = value.charCodeAt(index)\n\n  while (code === 9 || code === 32) {\n    index++\n    code = value.charCodeAt(index)\n  }\n\n  return value.slice(index)\n}\n","/**\n * @import {Nodes as HastNodes} from 'hast'\n * @import {Nodes as MdastNodes} from 'mdast'\n * @import {Options} from './state.js'\n */\n\nimport {ok as assert} from 'devlop'\nimport {footer} from './footer.js'\nimport {createState} from './state.js'\n\n/**\n * Transform mdast to hast.\n *\n * ##### Notes\n *\n * ###### HTML\n *\n * Raw HTML is available in mdast as `html` nodes and can be embedded in hast\n * as semistandard `raw` nodes.\n * Most utilities ignore `raw` nodes but two notable ones don’t:\n *\n * *   `hast-util-to-html` also has an option `allowDangerousHtml` which will\n *     output the raw HTML.\n *     This is typically discouraged as noted by the option name but is useful\n *     if you completely trust authors\n * *   `hast-util-raw` can handle the raw embedded HTML strings by parsing them\n *     into standard hast nodes (`element`, `text`, etc).\n *     This is a heavy task as it needs a full HTML parser, but it is the only\n *     way to support untrusted content\n *\n * ###### Footnotes\n *\n * Many options supported here relate to footnotes.\n * Footnotes are not specified by CommonMark, which we follow by default.\n * They are supported by GitHub, so footnotes can be enabled in markdown with\n * `mdast-util-gfm`.\n *\n * The options `footnoteBackLabel` and `footnoteLabel` define natural language\n * that explains footnotes, which is hidden for sighted users but shown to\n * assistive technology.\n * When your page is not in English, you must define translated values.\n *\n * Back references use ARIA attributes, but the section label itself uses a\n * heading that is hidden with an `sr-only` class.\n * To show it to sighted users, define different attributes in\n * `footnoteLabelProperties`.\n *\n * ###### Clobbering\n *\n * Footnotes introduces a problem, as it links footnote calls to footnote\n * definitions on the page through `id` attributes generated from user content,\n * which results in DOM clobbering.\n *\n * DOM clobbering is this:\n *\n * ```html\n * <p id=x></p>\n * <script>alert(x) // `x` now refers to the DOM `p#x` element</script>\n * ```\n *\n * Elements by their ID are made available by browsers on the `window` object,\n * which is a security risk.\n * Using a prefix solves this problem.\n *\n * More information on how to handle clobbering and the prefix is explained in\n * Example: headings (DOM clobbering) in `rehype-sanitize`.\n *\n * ###### Unknown nodes\n *\n * Unknown nodes are nodes with a type that isn’t in `handlers` or `passThrough`.\n * The default behavior for unknown nodes is:\n *\n * *   when the node has a `value` (and doesn’t have `data.hName`,\n *     `data.hProperties`, or `data.hChildren`, see later), create a hast `text`\n *     node\n * *   otherwise, create a `<div>` element (which could be changed with\n *     `data.hName`), with its children mapped from mdast to hast as well\n *\n * This behavior can be changed by passing an `unknownHandler`.\n *\n * @param {MdastNodes} tree\n *   mdast tree.\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {HastNodes}\n *   hast tree.\n */\nexport function toHast(tree, options) {\n  const state = createState(tree, options)\n  const node = state.one(tree, undefined)\n  const foot = footer(state)\n  /** @type {HastNodes} */\n  const result = Array.isArray(node)\n    ? {type: 'root', children: node}\n    : node || {type: 'root', children: []}\n\n  if (foot) {\n    // If there’s a footer, there were definitions, meaning block\n    // content.\n    // So `result` is a parent node.\n    assert('children' in result)\n    result.children.push({type: 'text', value: '\\n'}, foot)\n  }\n\n  return result\n}\n","/**\n * @import {Root as HastRoot} from 'hast'\n * @import {Root as MdastRoot} from 'mdast'\n * @import {Options as ToHastOptions} from 'mdast-util-to-hast'\n * @import {Processor} from 'unified'\n * @import {VFile} from 'vfile'\n */\n\n/**\n * @typedef {Omit<ToHastOptions, 'file'>} Options\n *\n * @callback TransformBridge\n *   Bridge-mode.\n *\n *   Runs the destination with the new hast tree.\n *   Discards result.\n * @param {MdastRoot} tree\n *   Tree.\n * @param {VFile} file\n *   File.\n * @returns {Promise<undefined>}\n *   Nothing.\n *\n * @callback TransformMutate\n *  Mutate-mode.\n *\n *  Further transformers run on the hast tree.\n * @param {MdastRoot} tree\n *   Tree.\n * @param {VFile} file\n *   File.\n * @returns {HastRoot}\n *   Tree (hast).\n */\n\nimport {toHast} from 'mdast-util-to-hast'\n\n/**\n * Turn markdown into HTML.\n *\n * ##### Notes\n *\n * ###### Signature\n *\n * * if a processor is given,\n *   runs the (rehype) plugins used on it with a hast tree,\n *   then discards the result (*bridge mode*)\n * * otherwise,\n *   returns a hast tree,\n *   the plugins used after `remarkRehype` are rehype plugins (*mutate mode*)\n *\n * > 👉 **Note**:\n * > It’s highly unlikely that you want to pass a `processor`.\n *\n * ###### HTML\n *\n * Raw HTML is available in mdast as `html` nodes and can be embedded in hast\n * as semistandard `raw` nodes.\n * Most plugins ignore `raw` nodes but two notable ones don’t:\n *\n * * `rehype-stringify` also has an option `allowDangerousHtml` which will\n *   output the raw HTML.\n *   This is typically discouraged as noted by the option name but is useful if\n *   you completely trust authors\n * * `rehype-raw` can handle the raw embedded HTML strings by parsing them\n *   into standard hast nodes (`element`, `text`, etc);\n *   this is a heavy task as it needs a full HTML parser,\n *   but it is the only way to support untrusted content\n *\n * ###### Footnotes\n *\n * Many options supported here relate to footnotes.\n * Footnotes are not specified by CommonMark,\n * which we follow by default.\n * They are supported by GitHub,\n * so footnotes can be enabled in markdown with `remark-gfm`.\n *\n * The options `footnoteBackLabel` and `footnoteLabel` define natural language\n * that explains footnotes,\n * which is hidden for sighted users but shown to assistive technology.\n * When your page is not in English,\n * you must define translated values.\n *\n * Back references use ARIA attributes,\n * but the section label itself uses a heading that is hidden with an\n * `sr-only` class.\n * To show it to sighted users,\n * define different attributes in `footnoteLabelProperties`.\n *\n * ###### Clobbering\n *\n * Footnotes introduces a problem,\n * as it links footnote calls to footnote definitions on the page through `id`\n * attributes generated from user content,\n * which results in DOM clobbering.\n *\n * DOM clobbering is this:\n *\n * ```html\n * <p id=x></p>\n * <script>alert(x) // `x` now refers to the DOM `p#x` element</script>\n * ```\n *\n * Elements by their ID are made available by browsers on the `window` object,\n * which is a security risk.\n * Using a prefix solves this problem.\n *\n * More information on how to handle clobbering and the prefix is explained in\n * *Example: headings (DOM clobbering)* in `rehype-sanitize`.\n *\n * ###### Unknown nodes\n *\n * Unknown nodes are nodes with a type that isn’t in `handlers` or `passThrough`.\n * The default behavior for unknown nodes is:\n *\n * * when the node has a `value`\n *   (and doesn’t have `data.hName`, `data.hProperties`, or `data.hChildren`,\n *   see later),\n *   create a hast `text` node\n * * otherwise,\n *   create a `<div>` element (which could be changed with `data.hName`),\n *   with its children mapped from mdast to hast as well\n *\n * This behavior can be changed by passing an `unknownHandler`.\n *\n * @overload\n * @param {Processor} processor\n * @param {Readonly<Options> | null | undefined} [options]\n * @returns {TransformBridge}\n *\n * @overload\n * @param {Readonly<Options> | null | undefined} [options]\n * @returns {TransformMutate}\n *\n * @overload\n * @param {Readonly<Options> | Processor | null | undefined} [destination]\n * @param {Readonly<Options> | null | undefined} [options]\n * @returns {TransformBridge | TransformMutate}\n *\n * @param {Readonly<Options> | Processor | null | undefined} [destination]\n *   Processor or configuration (optional).\n * @param {Readonly<Options> | null | undefined} [options]\n *   When a processor was given,\n *   configuration (optional).\n * @returns {TransformBridge | TransformMutate}\n *   Transform.\n */\nexport default function remarkRehype(destination, options) {\n  if (destination && 'run' in destination) {\n    /**\n     * @type {TransformBridge}\n     */\n    return async function (tree, file) {\n      // Cast because root in -> root out.\n      const hastTree = /** @type {HastRoot} */ (\n        toHast(tree, {file, ...options})\n      )\n      await destination.run(hastTree, file)\n    }\n  }\n\n  /**\n   * @type {TransformMutate}\n   */\n  return function (tree, file) {\n    // Cast because root in -> root out.\n    // To do: in the future, disallow ` || options` fallback.\n    // With `unified-engine`, `destination` can be `undefined` but\n    // `options` will be the file set.\n    // We should not pass that as `options`.\n    return /** @type {HastRoot} */ (\n      toHast(tree, {file, ...(destination || options)})\n    )\n  }\n}\n","/**\n * @import {Schema as SchemaType, Space} from 'property-information'\n */\n\n/** @type {SchemaType} */\nexport class Schema {\n  /**\n   * @param {SchemaType['property']} property\n   *   Property.\n   * @param {SchemaType['normal']} normal\n   *   Normal.\n   * @param {Space | undefined} [space]\n   *   Space.\n   * @returns\n   *   Schema.\n   */\n  constructor(property, normal, space) {\n    this.normal = normal\n    this.property = property\n\n    if (space) {\n      this.space = space\n    }\n  }\n}\n\nSchema.prototype.normal = {}\nSchema.prototype.property = {}\nSchema.prototype.space = undefined\n","/**\n * @import {Info, Space} from 'property-information'\n */\n\nimport {Schema} from './schema.js'\n\n/**\n * @param {ReadonlyArray<Schema>} definitions\n *   Definitions.\n * @param {Space | undefined} [space]\n *   Space.\n * @returns {Schema}\n *   Schema.\n */\nexport function merge(definitions, space) {\n  /** @type {Record<string, Info>} */\n  const property = {}\n  /** @type {Record<string, string>} */\n  const normal = {}\n\n  for (const definition of definitions) {\n    Object.assign(property, definition.property)\n    Object.assign(normal, definition.normal)\n  }\n\n  return new Schema(property, normal, space)\n}\n","/**\n * Get the cleaned case insensitive form of an attribute or property.\n *\n * @param {string} value\n *   An attribute-like or property-like name.\n * @returns {string}\n *   Value that can be used to look up the properly cased property on a\n *   `Schema`.\n */\nexport function normalize(value) {\n  return value.toLowerCase()\n}\n","/**\n * @import {Info as InfoType} from 'property-information'\n */\n\n/** @type {InfoType} */\nexport class Info {\n  /**\n   * @param {string} property\n   *   Property.\n   * @param {string} attribute\n   *   Attribute.\n   * @returns\n   *   Info.\n   */\n  constructor(property, attribute) {\n    this.attribute = attribute\n    this.property = property\n  }\n}\n\nInfo.prototype.attribute = ''\nInfo.prototype.booleanish = false\nInfo.prototype.boolean = false\nInfo.prototype.commaOrSpaceSeparated = false\nInfo.prototype.commaSeparated = false\nInfo.prototype.defined = false\nInfo.prototype.mustUseProperty = false\nInfo.prototype.number = false\nInfo.prototype.overloadedBoolean = false\nInfo.prototype.property = ''\nInfo.prototype.spaceSeparated = false\nInfo.prototype.space = undefined\n","let powers = 0\n\nexport const boolean = increment()\nexport const booleanish = increment()\nexport const overloadedBoolean = increment()\nexport const number = increment()\nexport const spaceSeparated = increment()\nexport const commaSeparated = increment()\nexport const commaOrSpaceSeparated = increment()\n\nfunction increment() {\n  return 2 ** ++powers\n}\n","/**\n * @import {Space} from 'property-information'\n */\n\nimport {Info} from './info.js'\nimport * as types from './types.js'\n\nconst checks = /** @type {ReadonlyArray<keyof typeof types>} */ (\n  Object.keys(types)\n)\n\nexport class DefinedInfo extends Info {\n  /**\n   * @constructor\n   * @param {string} property\n   *   Property.\n   * @param {string} attribute\n   *   Attribute.\n   * @param {number | null | undefined} [mask]\n   *   Mask.\n   * @param {Space | undefined} [space]\n   *   Space.\n   * @returns\n   *   Info.\n   */\n  constructor(property, attribute, mask, space) {\n    let index = -1\n\n    super(property, attribute)\n\n    mark(this, 'space', space)\n\n    if (typeof mask === 'number') {\n      while (++index < checks.length) {\n        const check = checks[index]\n        mark(this, checks[index], (mask & types[check]) === types[check])\n      }\n    }\n  }\n}\n\nDefinedInfo.prototype.defined = true\n\n/**\n * @template {keyof DefinedInfo} Key\n *   Key type.\n * @param {DefinedInfo} values\n *   Info.\n * @param {Key} key\n *   Key.\n * @param {DefinedInfo[Key]} value\n *   Value.\n * @returns {undefined}\n *   Nothing.\n */\nfunction mark(values, key, value) {\n  if (value) {\n    values[key] = value\n  }\n}\n","/**\n * @import {Info, Space} from 'property-information'\n */\n\n/**\n * @typedef Definition\n *   Definition of a schema.\n * @property {Record<string, string> | undefined} [attributes]\n *   Normalzed names to special attribute case.\n * @property {ReadonlyArray<string> | undefined} [mustUseProperty]\n *   Normalized names that must be set as properties.\n * @property {Record<string, number | null>} properties\n *   Property names to their types.\n * @property {Space | undefined} [space]\n *   Space.\n * @property {Transform} transform\n *   Transform a property name.\n */\n\n/**\n * @callback Transform\n *   Transform.\n * @param {Record<string, string>} attributes\n *   Attributes.\n * @param {string} property\n *   Property.\n * @returns {string}\n *   Attribute.\n */\n\nimport {normalize} from '../normalize.js'\nimport {DefinedInfo} from './defined-info.js'\nimport {Schema} from './schema.js'\n\n/**\n * @param {Definition} definition\n *   Definition.\n * @returns {Schema}\n *   Schema.\n */\nexport function create(definition) {\n  /** @type {Record<string, Info>} */\n  const properties = {}\n  /** @type {Record<string, string>} */\n  const normals = {}\n\n  for (const [property, value] of Object.entries(definition.properties)) {\n    const info = new DefinedInfo(\n      property,\n      definition.transform(definition.attributes || {}, property),\n      value,\n      definition.space\n    )\n\n    if (\n      definition.mustUseProperty &&\n      definition.mustUseProperty.includes(property)\n    ) {\n      info.mustUseProperty = true\n    }\n\n    properties[property] = info\n\n    normals[normalize(property)] = property\n    normals[normalize(info.attribute)] = property\n  }\n\n  return new Schema(properties, normals, definition.space)\n}\n","import {create} from './util/create.js'\nimport {booleanish, number, spaceSeparated} from './util/types.js'\n\nexport const aria = create({\n  properties: {\n    ariaActiveDescendant: null,\n    ariaAtomic: booleanish,\n    ariaAutoComplete: null,\n    ariaBusy: booleanish,\n    ariaChecked: booleanish,\n    ariaColCount: number,\n    ariaColIndex: number,\n    ariaColSpan: number,\n    ariaControls: spaceSeparated,\n    ariaCurrent: null,\n    ariaDescribedBy: spaceSeparated,\n    ariaDetails: null,\n    ariaDisabled: booleanish,\n    ariaDropEffect: spaceSeparated,\n    ariaErrorMessage: null,\n    ariaExpanded: booleanish,\n    ariaFlowTo: spaceSeparated,\n    ariaGrabbed: booleanish,\n    ariaHasPopup: null,\n    ariaHidden: booleanish,\n    ariaInvalid: null,\n    ariaKeyShortcuts: null,\n    ariaLabel: null,\n    ariaLabelledBy: spaceSeparated,\n    ariaLevel: number,\n    ariaLive: null,\n    ariaModal: booleanish,\n    ariaMultiLine: booleanish,\n    ariaMultiSelectable: booleanish,\n    ariaOrientation: null,\n    ariaOwns: spaceSeparated,\n    ariaPlaceholder: null,\n    ariaPosInSet: number,\n    ariaPressed: booleanish,\n    ariaReadOnly: booleanish,\n    ariaRelevant: null,\n    ariaRequired: booleanish,\n    ariaRoleDescription: spaceSeparated,\n    ariaRowCount: number,\n    ariaRowIndex: number,\n    ariaRowSpan: number,\n    ariaSelected: booleanish,\n    ariaSetSize: number,\n    ariaSort: null,\n    ariaValueMax: number,\n    ariaValueMin: number,\n    ariaValueNow: number,\n    ariaValueText: null,\n    role: null\n  },\n  transform(_, property) {\n    return property === 'role'\n      ? property\n      : 'aria-' + property.slice(4).toLowerCase()\n  }\n})\n","/**\n * @param {Record<string, string>} attributes\n *   Attributes.\n * @param {string} attribute\n *   Attribute.\n * @returns {string}\n *   Transformed attribute.\n */\nexport function caseSensitiveTransform(attributes, attribute) {\n  return attribute in attributes ? attributes[attribute] : attribute\n}\n","import {caseSensitiveTransform} from './case-sensitive-transform.js'\n\n/**\n * @param {Record<string, string>} attributes\n *   Attributes.\n * @param {string} property\n *   Property.\n * @returns {string}\n *   Transformed property.\n */\nexport function caseInsensitiveTransform(attributes, property) {\n  return caseSensitiveTransform(attributes, property.toLowerCase())\n}\n","import {caseInsensitiveTransform} from './util/case-insensitive-transform.js'\nimport {create} from './util/create.js'\nimport {\n  booleanish,\n  boolean,\n  commaSeparated,\n  number,\n  overloadedBoolean,\n  spaceSeparated\n} from './util/types.js'\n\nexport const html = create({\n  attributes: {\n    acceptcharset: 'accept-charset',\n    classname: 'class',\n    htmlfor: 'for',\n    httpequiv: 'http-equiv'\n  },\n  mustUseProperty: ['checked', 'multiple', 'muted', 'selected'],\n  properties: {\n    // Standard Properties.\n    abbr: null,\n    accept: commaSeparated,\n    acceptCharset: spaceSeparated,\n    accessKey: spaceSeparated,\n    action: null,\n    allow: null,\n    allowFullScreen: boolean,\n    allowPaymentRequest: boolean,\n    allowUserMedia: boolean,\n    alpha: boolean,\n    alt: null,\n    as: null,\n    async: boolean,\n    autoCapitalize: null,\n    autoComplete: spaceSeparated,\n    autoFocus: boolean,\n    autoPlay: boolean,\n    blocking: spaceSeparated,\n    capture: null,\n    charSet: null,\n    checked: boolean,\n    cite: null,\n    className: spaceSeparated,\n    closedBy: null,\n    colorSpace: null,\n    cols: number,\n    colSpan: number,\n    command: null,\n    commandFor: null,\n    content: null,\n    contentEditable: booleanish,\n    controls: boolean,\n    controlsList: spaceSeparated,\n    coords: number | commaSeparated,\n    crossOrigin: null,\n    data: null,\n    dateTime: null,\n    decoding: null,\n    default: boolean,\n    defer: boolean,\n    dir: null,\n    dirName: null,\n    disabled: boolean,\n    download: overloadedBoolean,\n    draggable: booleanish,\n    encType: null,\n    enterKeyHint: null,\n    fetchPriority: null,\n    form: null,\n    formAction: null,\n    formEncType: null,\n    formMethod: null,\n    formNoValidate: boolean,\n    formTarget: null,\n    headers: spaceSeparated,\n    height: number,\n    hidden: overloadedBoolean,\n    high: number,\n    href: null,\n    hrefLang: null,\n    htmlFor: spaceSeparated,\n    httpEquiv: spaceSeparated,\n    id: null,\n    imageSizes: null,\n    imageSrcSet: null,\n    inert: boolean,\n    inputMode: null,\n    integrity: null,\n    is: null,\n    isMap: boolean,\n    itemId: null,\n    itemProp: spaceSeparated,\n    itemRef: spaceSeparated,\n    itemScope: boolean,\n    itemType: spaceSeparated,\n    kind: null,\n    label: null,\n    lang: null,\n    language: null,\n    list: null,\n    loading: null,\n    loop: boolean,\n    low: number,\n    manifest: null,\n    max: null,\n    maxLength: number,\n    media: null,\n    method: null,\n    min: null,\n    minLength: number,\n    multiple: boolean,\n    muted: boolean,\n    name: null,\n    nonce: null,\n    noModule: boolean,\n    noValidate: boolean,\n    onAbort: null,\n    onAfterPrint: null,\n    onAuxClick: null,\n    onBeforeMatch: null,\n    onBeforePrint: null,\n    onBeforeToggle: null,\n    onBeforeUnload: null,\n    onBlur: null,\n    onCancel: null,\n    onCanPlay: null,\n    onCanPlayThrough: null,\n    onChange: null,\n    onClick: null,\n    onClose: null,\n    onContextLost: null,\n    onContextMenu: null,\n    onContextRestored: null,\n    onCopy: null,\n    onCueChange: null,\n    onCut: null,\n    onDblClick: null,\n    onDrag: null,\n    onDragEnd: null,\n    onDragEnter: null,\n    onDragExit: null,\n    onDragLeave: null,\n    onDragOver: null,\n    onDragStart: null,\n    onDrop: null,\n    onDurationChange: null,\n    onEmptied: null,\n    onEnded: null,\n    onError: null,\n    onFocus: null,\n    onFormData: null,\n    onHashChange: null,\n    onInput: null,\n    onInvalid: null,\n    onKeyDown: null,\n    onKeyPress: null,\n    onKeyUp: null,\n    onLanguageChange: null,\n    onLoad: null,\n    onLoadedData: null,\n    onLoadedMetadata: null,\n    onLoadEnd: null,\n    onLoadStart: null,\n    onMessage: null,\n    onMessageError: null,\n    onMouseDown: null,\n    onMouseEnter: null,\n    onMouseLeave: null,\n    onMouseMove: null,\n    onMouseOut: null,\n    onMouseOver: null,\n    onMouseUp: null,\n    onOffline: null,\n    onOnline: null,\n    onPageHide: null,\n    onPageShow: null,\n    onPaste: null,\n    onPause: null,\n    onPlay: null,\n    onPlaying: null,\n    onPopState: null,\n    onProgress: null,\n    onRateChange: null,\n    onRejectionHandled: null,\n    onReset: null,\n    onResize: null,\n    onScroll: null,\n    onScrollEnd: null,\n    onSecurityPolicyViolation: null,\n    onSeeked: null,\n    onSeeking: null,\n    onSelect: null,\n    onSlotChange: null,\n    onStalled: null,\n    onStorage: null,\n    onSubmit: null,\n    onSuspend: null,\n    onTimeUpdate: null,\n    onToggle: null,\n    onUnhandledRejection: null,\n    onUnload: null,\n    onVolumeChange: null,\n    onWaiting: null,\n    onWheel: null,\n    open: boolean,\n    optimum: number,\n    pattern: null,\n    ping: spaceSeparated,\n    placeholder: null,\n    playsInline: boolean,\n    popover: null,\n    popoverTarget: null,\n    popoverTargetAction: null,\n    poster: null,\n    preload: null,\n    readOnly: boolean,\n    referrerPolicy: null,\n    rel: spaceSeparated,\n    required: boolean,\n    reversed: boolean,\n    rows: number,\n    rowSpan: number,\n    sandbox: spaceSeparated,\n    scope: null,\n    scoped: boolean,\n    seamless: boolean,\n    selected: boolean,\n    shadowRootClonable: boolean,\n    shadowRootCustomElementRegistry: boolean,\n    shadowRootDelegatesFocus: boolean,\n    shadowRootMode: null,\n    shadowRootSerializable: boolean,\n    shape: null,\n    size: number,\n    sizes: null,\n    slot: null,\n    span: number,\n    spellCheck: booleanish,\n    src: null,\n    srcDoc: null,\n    srcLang: null,\n    srcSet: null,\n    start: number,\n    step: null,\n    style: null,\n    tabIndex: number,\n    target: null,\n    title: null,\n    translate: null,\n    type: null,\n    typeMustMatch: boolean,\n    useMap: null,\n    value: booleanish,\n    width: number,\n    wrap: null,\n    writingSuggestions: null,\n\n    // Legacy.\n    // See: https://html.spec.whatwg.org/#other-elements,-attributes-and-apis\n    align: null, // Several. Use CSS `text-align` instead,\n    aLink: null, // `<body>`. Use CSS `a:active {color}` instead\n    archive: spaceSeparated, // `<object>`. List of URIs to archives\n    axis: null, // `<td>` and `<th>`. Use `scope` on `<th>`\n    background: null, // `<body>`. Use CSS `background-image` instead\n    bgColor: null, // `<body>` and table elements. Use CSS `background-color` instead\n    border: number, // `<table>`. Use CSS `border-width` instead,\n    borderColor: null, // `<table>`. Use CSS `border-color` instead,\n    bottomMargin: number, // `<body>`\n    cellPadding: null, // `<table>`\n    cellSpacing: null, // `<table>`\n    char: null, // Several table elements. When `align=char`, sets the character to align on\n    charOff: null, // Several table elements. When `char`, offsets the alignment\n    classId: null, // `<object>`\n    clear: null, // `<br>`. Use CSS `clear` instead\n    code: null, // `<object>`\n    codeBase: null, // `<object>`\n    codeType: null, // `<object>`\n    color: null, // `<font>` and `<hr>`. Use CSS instead\n    compact: boolean, // Lists. Use CSS to reduce space between items instead\n    declare: boolean, // `<object>`\n    event: null, // `<script>`\n    face: null, // `<font>`. Use CSS instead\n    frame: null, // `<table>`\n    frameBorder: null, // `<iframe>`. Use CSS `border` instead\n    hSpace: number, // `<img>` and `<object>`\n    leftMargin: number, // `<body>`\n    link: null, // `<body>`. Use CSS `a:link {color: *}` instead\n    longDesc: null, // `<frame>`, `<iframe>`, and `<img>`. Use an `<a>`\n    lowSrc: null, // `<img>`. Use a `<picture>`\n    marginHeight: number, // `<body>`\n    marginWidth: number, // `<body>`\n    noResize: boolean, // `<frame>`\n    noHref: boolean, // `<area>`. Use no href instead of an explicit `nohref`\n    noShade: boolean, // `<hr>`. Use background-color and height instead of borders\n    noWrap: boolean, // `<td>` and `<th>`\n    object: null, // `<applet>`\n    profile: null, // `<head>`\n    prompt: null, // `<isindex>`\n    rev: null, // `<link>`\n    rightMargin: number, // `<body>`\n    rules: null, // `<table>`\n    scheme: null, // `<meta>`\n    scrolling: booleanish, // `<frame>`. Use overflow in the child context\n    standby: null, // `<object>`\n    summary: null, // `<table>`\n    text: null, // `<body>`. Use CSS `color` instead\n    topMargin: number, // `<body>`\n    valueType: null, // `<param>`\n    version: null, // `<html>`. Use a doctype.\n    vAlign: null, // Several. Use CSS `vertical-align` instead\n    vLink: null, // `<body>`. Use CSS `a:visited {color}` instead\n    vSpace: number, // `<img>` and `<object>`\n\n    // Non-standard Properties.\n    allowTransparency: null,\n    autoCorrect: null,\n    autoSave: null,\n    credentialless: boolean,\n    disablePictureInPicture: boolean,\n    disableRemotePlayback: boolean,\n    exportParts: commaSeparated,\n    part: spaceSeparated,\n    prefix: null,\n    property: null,\n    results: number,\n    security: null,\n    unselectable: null\n  },\n  space: 'html',\n  transform: caseInsensitiveTransform\n})\n","import {caseSensitiveTransform} from './util/case-sensitive-transform.js'\nimport {create} from './util/create.js'\nimport {\n  boolean,\n  commaOrSpaceSeparated,\n  commaSeparated,\n  number,\n  spaceSeparated\n} from './util/types.js'\n\nexport const svg = create({\n  attributes: {\n    accentHeight: 'accent-height',\n    alignmentBaseline: 'alignment-baseline',\n    arabicForm: 'arabic-form',\n    baselineShift: 'baseline-shift',\n    capHeight: 'cap-height',\n    className: 'class',\n    clipPath: 'clip-path',\n    clipRule: 'clip-rule',\n    colorInterpolation: 'color-interpolation',\n    colorInterpolationFilters: 'color-interpolation-filters',\n    colorProfile: 'color-profile',\n    colorRendering: 'color-rendering',\n    crossOrigin: 'crossorigin',\n    dataType: 'datatype',\n    dominantBaseline: 'dominant-baseline',\n    enableBackground: 'enable-background',\n    fillOpacity: 'fill-opacity',\n    fillRule: 'fill-rule',\n    floodColor: 'flood-color',\n    floodOpacity: 'flood-opacity',\n    fontFamily: 'font-family',\n    fontSize: 'font-size',\n    fontSizeAdjust: 'font-size-adjust',\n    fontStretch: 'font-stretch',\n    fontStyle: 'font-style',\n    fontVariant: 'font-variant',\n    fontWeight: 'font-weight',\n    glyphName: 'glyph-name',\n    glyphOrientationHorizontal: 'glyph-orientation-horizontal',\n    glyphOrientationVertical: 'glyph-orientation-vertical',\n    hrefLang: 'hreflang',\n    horizAdvX: 'horiz-adv-x',\n    horizOriginX: 'horiz-origin-x',\n    horizOriginY: 'horiz-origin-y',\n    imageRendering: 'image-rendering',\n    letterSpacing: 'letter-spacing',\n    lightingColor: 'lighting-color',\n    markerEnd: 'marker-end',\n    markerMid: 'marker-mid',\n    markerStart: 'marker-start',\n    maskType: 'mask-type',\n    navDown: 'nav-down',\n    navDownLeft: 'nav-down-left',\n    navDownRight: 'nav-down-right',\n    navLeft: 'nav-left',\n    navNext: 'nav-next',\n    navPrev: 'nav-prev',\n    navRight: 'nav-right',\n    navUp: 'nav-up',\n    navUpLeft: 'nav-up-left',\n    navUpRight: 'nav-up-right',\n    onAbort: 'onabort',\n    onActivate: 'onactivate',\n    onAfterPrint: 'onafterprint',\n    onBeforePrint: 'onbeforeprint',\n    onBegin: 'onbegin',\n    onCancel: 'oncancel',\n    onCanPlay: 'oncanplay',\n    onCanPlayThrough: 'oncanplaythrough',\n    onChange: 'onchange',\n    onClick: 'onclick',\n    onClose: 'onclose',\n    onCopy: 'oncopy',\n    onCueChange: 'oncuechange',\n    onCut: 'oncut',\n    onDblClick: 'ondblclick',\n    onDrag: 'ondrag',\n    onDragEnd: 'ondragend',\n    onDragEnter: 'ondragenter',\n    onDragExit: 'ondragexit',\n    onDragLeave: 'ondragleave',\n    onDragOver: 'ondragover',\n    onDragStart: 'ondragstart',\n    onDrop: 'ondrop',\n    onDurationChange: 'ondurationchange',\n    onEmptied: 'onemptied',\n    onEnd: 'onend',\n    onEnded: 'onended',\n    onError: 'onerror',\n    onFocus: 'onfocus',\n    onFocusIn: 'onfocusin',\n    onFocusOut: 'onfocusout',\n    onHashChange: 'onhashchange',\n    onInput: 'oninput',\n    onInvalid: 'oninvalid',\n    onKeyDown: 'onkeydown',\n    onKeyPress: 'onkeypress',\n    onKeyUp: 'onkeyup',\n    onLoad: 'onload',\n    onLoadedData: 'onloadeddata',\n    onLoadedMetadata: 'onloadedmetadata',\n    onLoadStart: 'onloadstart',\n    onMessage: 'onmessage',\n    onMouseDown: 'onmousedown',\n    onMouseEnter: 'onmouseenter',\n    onMouseLeave: 'onmouseleave',\n    onMouseMove: 'onmousemove',\n    onMouseOut: 'onmouseout',\n    onMouseOver: 'onmouseover',\n    onMouseUp: 'onmouseup',\n    onMouseWheel: 'onmousewheel',\n    onOffline: 'onoffline',\n    onOnline: 'ononline',\n    onPageHide: 'onpagehide',\n    onPageShow: 'onpageshow',\n    onPaste: 'onpaste',\n    onPause: 'onpause',\n    onPlay: 'onplay',\n    onPlaying: 'onplaying',\n    onPopState: 'onpopstate',\n    onProgress: 'onprogress',\n    onRateChange: 'onratechange',\n    onRepeat: 'onrepeat',\n    onReset: 'onreset',\n    onResize: 'onresize',\n    onScroll: 'onscroll',\n    onSeeked: 'onseeked',\n    onSeeking: 'onseeking',\n    onSelect: 'onselect',\n    onShow: 'onshow',\n    onStalled: 'onstalled',\n    onStorage: 'onstorage',\n    onSubmit: 'onsubmit',\n    onSuspend: 'onsuspend',\n    onTimeUpdate: 'ontimeupdate',\n    onToggle: 'ontoggle',\n    onUnload: 'onunload',\n    onVolumeChange: 'onvolumechange',\n    onWaiting: 'onwaiting',\n    onZoom: 'onzoom',\n    overlinePosition: 'overline-position',\n    overlineThickness: 'overline-thickness',\n    paintOrder: 'paint-order',\n    panose1: 'panose-1',\n    pointerEvents: 'pointer-events',\n    referrerPolicy: 'referrerpolicy',\n    renderingIntent: 'rendering-intent',\n    shapeRendering: 'shape-rendering',\n    stopColor: 'stop-color',\n    stopOpacity: 'stop-opacity',\n    strikethroughPosition: 'strikethrough-position',\n    strikethroughThickness: 'strikethrough-thickness',\n    strokeDashArray: 'stroke-dasharray',\n    strokeDashOffset: 'stroke-dashoffset',\n    strokeLineCap: 'stroke-linecap',\n    strokeLineJoin: 'stroke-linejoin',\n    strokeMiterLimit: 'stroke-miterlimit',\n    strokeOpacity: 'stroke-opacity',\n    strokeWidth: 'stroke-width',\n    tabIndex: 'tabindex',\n    textAnchor: 'text-anchor',\n    textDecoration: 'text-decoration',\n    textRendering: 'text-rendering',\n    transformOrigin: 'transform-origin',\n    typeOf: 'typeof',\n    underlinePosition: 'underline-position',\n    underlineThickness: 'underline-thickness',\n    unicodeBidi: 'unicode-bidi',\n    unicodeRange: 'unicode-range',\n    unitsPerEm: 'units-per-em',\n    vAlphabetic: 'v-alphabetic',\n    vHanging: 'v-hanging',\n    vIdeographic: 'v-ideographic',\n    vMathematical: 'v-mathematical',\n    vectorEffect: 'vector-effect',\n    vertAdvY: 'vert-adv-y',\n    vertOriginX: 'vert-origin-x',\n    vertOriginY: 'vert-origin-y',\n    wordSpacing: 'word-spacing',\n    writingMode: 'writing-mode',\n    xHeight: 'x-height',\n    // These were camelcased in Tiny. Now lowercased in SVG 2\n    playbackOrder: 'playbackorder',\n    timelineBegin: 'timelinebegin'\n  },\n  properties: {\n    about: commaOrSpaceSeparated,\n    accentHeight: number,\n    accumulate: null,\n    additive: null,\n    alignmentBaseline: null,\n    alphabetic: number,\n    amplitude: number,\n    arabicForm: null,\n    ascent: number,\n    attributeName: null,\n    attributeType: null,\n    azimuth: number,\n    bandwidth: null,\n    baselineShift: null,\n    baseFrequency: null,\n    baseProfile: null,\n    bbox: null,\n    begin: null,\n    bias: number,\n    by: null,\n    calcMode: null,\n    capHeight: number,\n    className: spaceSeparated,\n    clip: null,\n    clipPath: null,\n    clipPathUnits: null,\n    clipRule: null,\n    color: null,\n    colorInterpolation: null,\n    colorInterpolationFilters: null,\n    colorProfile: null,\n    colorRendering: null,\n    content: null,\n    contentScriptType: null,\n    contentStyleType: null,\n    crossOrigin: null,\n    cursor: null,\n    cx: null,\n    cy: null,\n    d: null,\n    dataType: null,\n    defaultAction: null,\n    descent: number,\n    diffuseConstant: number,\n    direction: null,\n    display: null,\n    dur: null,\n    divisor: number,\n    dominantBaseline: null,\n    download: boolean,\n    dx: null,\n    dy: null,\n    edgeMode: null,\n    editable: null,\n    elevation: number,\n    enableBackground: null,\n    end: null,\n    event: null,\n    exponent: number,\n    externalResourcesRequired: null,\n    fill: null,\n    fillOpacity: number,\n    fillRule: null,\n    filter: null,\n    filterRes: null,\n    filterUnits: null,\n    floodColor: null,\n    floodOpacity: null,\n    focusable: null,\n    focusHighlight: null,\n    fontFamily: null,\n    fontSize: null,\n    fontSizeAdjust: null,\n    fontStretch: null,\n    fontStyle: null,\n    fontVariant: null,\n    fontWeight: null,\n    format: null,\n    fr: null,\n    from: null,\n    fx: null,\n    fy: null,\n    g1: commaSeparated,\n    g2: commaSeparated,\n    glyphName: commaSeparated,\n    glyphOrientationHorizontal: null,\n    glyphOrientationVertical: null,\n    glyphRef: null,\n    gradientTransform: null,\n    gradientUnits: null,\n    handler: null,\n    hanging: number,\n    hatchContentUnits: null,\n    hatchUnits: null,\n    height: null,\n    href: null,\n    hrefLang: null,\n    horizAdvX: number,\n    horizOriginX: number,\n    horizOriginY: number,\n    id: null,\n    ideographic: number,\n    imageRendering: null,\n    initialVisibility: null,\n    in: null,\n    in2: null,\n    intercept: number,\n    k: number,\n    k1: number,\n    k2: number,\n    k3: number,\n    k4: number,\n    kernelMatrix: commaOrSpaceSeparated,\n    kernelUnitLength: null,\n    keyPoints: null, // SEMI_COLON_SEPARATED\n    keySplines: null, // SEMI_COLON_SEPARATED\n    keyTimes: null, // SEMI_COLON_SEPARATED\n    kerning: null,\n    lang: null,\n    lengthAdjust: null,\n    letterSpacing: null,\n    lightingColor: null,\n    limitingConeAngle: number,\n    local: null,\n    markerEnd: null,\n    markerMid: null,\n    markerStart: null,\n    markerHeight: null,\n    markerUnits: null,\n    markerWidth: null,\n    mask: null,\n    maskContentUnits: null,\n    maskType: null,\n    maskUnits: null,\n    mathematical: null,\n    max: null,\n    media: null,\n    mediaCharacterEncoding: null,\n    mediaContentEncodings: null,\n    mediaSize: number,\n    mediaTime: null,\n    method: null,\n    min: null,\n    mode: null,\n    name: null,\n    navDown: null,\n    navDownLeft: null,\n    navDownRight: null,\n    navLeft: null,\n    navNext: null,\n    navPrev: null,\n    navRight: null,\n    navUp: null,\n    navUpLeft: null,\n    navUpRight: null,\n    numOctaves: null,\n    observer: null,\n    offset: null,\n    onAbort: null,\n    onActivate: null,\n    onAfterPrint: null,\n    onBeforePrint: null,\n    onBegin: null,\n    onCancel: null,\n    onCanPlay: null,\n    onCanPlayThrough: null,\n    onChange: null,\n    onClick: null,\n    onClose: null,\n    onCopy: null,\n    onCueChange: null,\n    onCut: null,\n    onDblClick: null,\n    onDrag: null,\n    onDragEnd: null,\n    onDragEnter: null,\n    onDragExit: null,\n    onDragLeave: null,\n    onDragOver: null,\n    onDragStart: null,\n    onDrop: null,\n    onDurationChange: null,\n    onEmptied: null,\n    onEnd: null,\n    onEnded: null,\n    onError: null,\n    onFocus: null,\n    onFocusIn: null,\n    onFocusOut: null,\n    onHashChange: null,\n    onInput: null,\n    onInvalid: null,\n    onKeyDown: null,\n    onKeyPress: null,\n    onKeyUp: null,\n    onLoad: null,\n    onLoadedData: null,\n    onLoadedMetadata: null,\n    onLoadStart: null,\n    onMessage: null,\n    onMouseDown: null,\n    onMouseEnter: null,\n    onMouseLeave: null,\n    onMouseMove: null,\n    onMouseOut: null,\n    onMouseOver: null,\n    onMouseUp: null,\n    onMouseWheel: null,\n    onOffline: null,\n    onOnline: null,\n    onPageHide: null,\n    onPageShow: null,\n    onPaste: null,\n    onPause: null,\n    onPlay: null,\n    onPlaying: null,\n    onPopState: null,\n    onProgress: null,\n    onRateChange: null,\n    onRepeat: null,\n    onReset: null,\n    onResize: null,\n    onScroll: null,\n    onSeeked: null,\n    onSeeking: null,\n    onSelect: null,\n    onShow: null,\n    onStalled: null,\n    onStorage: null,\n    onSubmit: null,\n    onSuspend: null,\n    onTimeUpdate: null,\n    onToggle: null,\n    onUnload: null,\n    onVolumeChange: null,\n    onWaiting: null,\n    onZoom: null,\n    opacity: null,\n    operator: null,\n    order: null,\n    orient: null,\n    orientation: null,\n    origin: null,\n    overflow: null,\n    overlay: null,\n    overlinePosition: number,\n    overlineThickness: number,\n    paintOrder: null,\n    panose1: null,\n    path: null,\n    pathLength: number,\n    patternContentUnits: null,\n    patternTransform: null,\n    patternUnits: null,\n    phase: null,\n    ping: spaceSeparated,\n    pitch: null,\n    playbackOrder: null,\n    pointerEvents: null,\n    points: null,\n    pointsAtX: number,\n    pointsAtY: number,\n    pointsAtZ: number,\n    preserveAlpha: null,\n    preserveAspectRatio: null,\n    primitiveUnits: null,\n    propagate: null,\n    property: commaOrSpaceSeparated,\n    r: null,\n    radius: null,\n    referrerPolicy: null,\n    refX: null,\n    refY: null,\n    rel: commaOrSpaceSeparated,\n    rev: commaOrSpaceSeparated,\n    renderingIntent: null,\n    repeatCount: null,\n    repeatDur: null,\n    requiredExtensions: commaOrSpaceSeparated,\n    requiredFeatures: commaOrSpaceSeparated,\n    requiredFonts: commaOrSpaceSeparated,\n    requiredFormats: commaOrSpaceSeparated,\n    resource: null,\n    restart: null,\n    result: null,\n    rotate: null,\n    rx: null,\n    ry: null,\n    scale: null,\n    seed: null,\n    shapeRendering: null,\n    side: null,\n    slope: null,\n    snapshotTime: null,\n    specularConstant: number,\n    specularExponent: number,\n    spreadMethod: null,\n    spacing: null,\n    startOffset: null,\n    stdDeviation: null,\n    stemh: null,\n    stemv: null,\n    stitchTiles: null,\n    stopColor: null,\n    stopOpacity: null,\n    strikethroughPosition: number,\n    strikethroughThickness: number,\n    string: null,\n    stroke: null,\n    strokeDashArray: commaOrSpaceSeparated,\n    strokeDashOffset: null,\n    strokeLineCap: null,\n    strokeLineJoin: null,\n    strokeMiterLimit: number,\n    strokeOpacity: number,\n    strokeWidth: null,\n    style: null,\n    surfaceScale: number,\n    syncBehavior: null,\n    syncBehaviorDefault: null,\n    syncMaster: null,\n    syncTolerance: null,\n    syncToleranceDefault: null,\n    systemLanguage: commaOrSpaceSeparated,\n    tabIndex: number,\n    tableValues: null,\n    target: null,\n    targetX: number,\n    targetY: number,\n    textAnchor: null,\n    textDecoration: null,\n    textRendering: null,\n    textLength: null,\n    timelineBegin: null,\n    title: null,\n    transformBehavior: null,\n    type: null,\n    typeOf: commaOrSpaceSeparated,\n    to: null,\n    transform: null,\n    transformOrigin: null,\n    u1: null,\n    u2: null,\n    underlinePosition: number,\n    underlineThickness: number,\n    unicode: null,\n    unicodeBidi: null,\n    unicodeRange: null,\n    unitsPerEm: number,\n    values: null,\n    vAlphabetic: number,\n    vMathematical: number,\n    vectorEffect: null,\n    vHanging: number,\n    vIdeographic: number,\n    version: null,\n    vertAdvY: number,\n    vertOriginX: number,\n    vertOriginY: number,\n    viewBox: null,\n    viewTarget: null,\n    visibility: null,\n    width: null,\n    widths: null,\n    wordSpacing: null,\n    writingMode: null,\n    x: null,\n    x1: null,\n    x2: null,\n    xChannelSelector: null,\n    xHeight: number,\n    y: null,\n    y1: null,\n    y2: null,\n    yChannelSelector: null,\n    z: null,\n    zoomAndPan: null\n  },\n  space: 'svg',\n  transform: caseSensitiveTransform\n})\n","import {create} from './util/create.js'\n\nexport const xlink = create({\n  properties: {\n    xLinkActuate: null,\n    xLinkArcRole: null,\n    xLinkHref: null,\n    xLinkRole: null,\n    xLinkShow: null,\n    xLinkTitle: null,\n    xLinkType: null\n  },\n  space: 'xlink',\n  transform(_, property) {\n    return 'xlink:' + property.slice(5).toLowerCase()\n  }\n})\n","import {create} from './util/create.js'\nimport {caseInsensitiveTransform} from './util/case-insensitive-transform.js'\n\nexport const xmlns = create({\n  attributes: {xmlnsxlink: 'xmlns:xlink'},\n  properties: {xmlnsXLink: null, xmlns: null},\n  space: 'xmlns',\n  transform: caseInsensitiveTransform\n})\n","import {create} from './util/create.js'\n\nexport const xml = create({\n  properties: {xmlBase: null, xmlLang: null, xmlSpace: null},\n  space: 'xml',\n  transform(_, property) {\n    return 'xml:' + property.slice(3).toLowerCase()\n  }\n})\n","/**\n * @import {Schema} from 'property-information'\n */\n\nimport {DefinedInfo} from './util/defined-info.js'\nimport {Info} from './util/info.js'\nimport {normalize} from './normalize.js'\n\nconst cap = /[A-Z]/g\nconst dash = /-[a-z]/g\nconst valid = /^data[-\\w.:]+$/i\n\n/**\n * Look up info on a property.\n *\n * In most cases the given `schema` contains info on the property.\n * All standard,\n * most legacy,\n * and some non-standard properties are supported.\n * For these cases,\n * the returned `Info` has hints about the value of the property.\n *\n * `name` can also be a valid data attribute or property,\n * in which case an `Info` object with the correctly cased `attribute` and\n * `property` is returned.\n *\n * `name` can be an unknown attribute,\n * in which case an `Info` object with `attribute` and `property` set to the\n * given name is returned.\n * It is not recommended to provide unsupported legacy or recently specced\n * properties.\n *\n *\n * @param {Schema} schema\n *   Schema;\n *   either the `html` or `svg` export.\n * @param {string} value\n *   An attribute-like or property-like name;\n *   it will be passed through `normalize` to hopefully find the correct info.\n * @returns {Info}\n *   Info.\n */\nexport function find(schema, value) {\n  const normal = normalize(value)\n  let property = value\n  let Type = Info\n\n  if (normal in schema.normal) {\n    return schema.property[schema.normal[normal]]\n  }\n\n  if (normal.length > 4 && normal.slice(0, 4) === 'data' && valid.test(value)) {\n    // Attribute or property.\n    if (value.charAt(4) === '-') {\n      // Turn it into a property.\n      const rest = value.slice(5).replace(dash, camelcase)\n      property = 'data' + rest.charAt(0).toUpperCase() + rest.slice(1)\n    } else {\n      // Turn it into an attribute.\n      const rest = value.slice(4)\n\n      if (!dash.test(rest)) {\n        let dashes = rest.replace(cap, kebab)\n\n        if (dashes.charAt(0) !== '-') {\n          dashes = '-' + dashes\n        }\n\n        value = 'data' + dashes\n      }\n    }\n\n    Type = DefinedInfo\n  }\n\n  return new Type(property, value)\n}\n\n/**\n * @param {string} $0\n *   Value.\n * @returns {string}\n *   Kebab.\n */\nfunction kebab($0) {\n  return '-' + $0.toLowerCase()\n}\n\n/**\n * @param {string} $0\n *   Value.\n * @returns {string}\n *   Camel.\n */\nfunction camelcase($0) {\n  return $0.charAt(1).toUpperCase()\n}\n","// Note: types exposed from `index.d.ts`.\nimport {merge} from './lib/util/merge.js'\nimport {aria} from './lib/aria.js'\nimport {html as htmlBase} from './lib/html.js'\nimport {svg as svgBase} from './lib/svg.js'\nimport {xlink} from './lib/xlink.js'\nimport {xmlns} from './lib/xmlns.js'\nimport {xml} from './lib/xml.js'\n\nexport {hastToReact} from './lib/hast-to-react.js'\n\nexport const html = merge([aria, htmlBase, xlink, xmlns, xml], 'html')\n\nexport {find} from './lib/find.js'\nexport {normalize} from './lib/normalize.js'\n\nexport const svg = merge([aria, svgBase, xlink, xmlns, xml], 'svg')\n","/**\n * @typedef Options\n *   Configuration for `stringify`.\n * @property {boolean} [padLeft=true]\n *   Whether to pad a space before a token.\n * @property {boolean} [padRight=false]\n *   Whether to pad a space after a token.\n */\n\n/**\n * @typedef {Options} StringifyOptions\n *   Please use `StringifyOptions` instead.\n */\n\n/**\n * Parse comma-separated tokens to an array.\n *\n * @param {string} value\n *   Comma-separated tokens.\n * @returns {Array<string>}\n *   List of tokens.\n */\nexport function parse(value) {\n  /** @type {Array<string>} */\n  const tokens = []\n  const input = String(value || '')\n  let index = input.indexOf(',')\n  let start = 0\n  /** @type {boolean} */\n  let end = false\n\n  while (!end) {\n    if (index === -1) {\n      index = input.length\n      end = true\n    }\n\n    const token = input.slice(start, index).trim()\n\n    if (token || !end) {\n      tokens.push(token)\n    }\n\n    start = index + 1\n    index = input.indexOf(',', start)\n  }\n\n  return tokens\n}\n\n/**\n * Serialize an array of strings or numbers to comma-separated tokens.\n *\n * @param {Array<string|number>} values\n *   List of tokens.\n * @param {Options} [options]\n *   Configuration for `stringify` (optional).\n * @returns {string}\n *   Comma-separated tokens.\n */\nexport function stringify(values, options) {\n  const settings = options || {}\n\n  // Ensure the last empty entry is seen.\n  const input = values[values.length - 1] === '' ? [...values, ''] : values\n\n  return input\n    .join(\n      (settings.padRight ? ' ' : '') +\n        ',' +\n        (settings.padLeft === false ? '' : ' ')\n    )\n    .trim()\n}\n","/**\n * @typedef {import('hast').Element} Element\n * @typedef {import('hast').Properties} Properties\n */\n\n/**\n * @template {string} SimpleSelector\n *   Selector type.\n * @template {string} DefaultTagName\n *   Default tag name.\n * @typedef {(\n *   SimpleSelector extends ''\n *     ? DefaultTagName\n *     : SimpleSelector extends `${infer TagName}.${infer Rest}`\n *     ? ExtractTagName<TagName, DefaultTagName>\n *     : SimpleSelector extends `${infer TagName}#${infer Rest}`\n *     ? ExtractTagName<TagName, DefaultTagName>\n *     : SimpleSelector extends string\n *     ? SimpleSelector\n *     : DefaultTagName\n * )} ExtractTagName\n *   Extract tag name from a simple selector.\n */\n\nconst search = /[#.]/g\n\n/**\n * Create a hast element from a simple CSS selector.\n *\n * @template {string} Selector\n *   Type of selector.\n * @template {string} [DefaultTagName='div']\n *   Type of default tag name (default: `'div'`).\n * @param {Selector | null | undefined} [selector]\n *   Simple CSS selector (optional).\n *\n *   Can contain a tag name (`foo`), classes (`.bar`), and an ID (`#baz`).\n *   Multiple classes are allowed.\n *   Uses the last ID if multiple IDs are found.\n * @param {DefaultTagName | null | undefined} [defaultTagName='div']\n *   Tag name to use if `selector` does not specify one (default: `'div'`).\n * @returns {Element & {tagName: ExtractTagName<Selector, DefaultTagName>}}\n *   Built element.\n */\nexport function parseSelector(selector, defaultTagName) {\n  const value = selector || ''\n  /** @type {Properties} */\n  const props = {}\n  let start = 0\n  /** @type {string | undefined} */\n  let previous\n  /** @type {string | undefined} */\n  let tagName\n\n  while (start < value.length) {\n    search.lastIndex = start\n    const match = search.exec(value)\n    const subvalue = value.slice(start, match ? match.index : value.length)\n\n    if (subvalue) {\n      if (!previous) {\n        tagName = subvalue\n      } else if (previous === '#') {\n        props.id = subvalue\n      } else if (Array.isArray(props.className)) {\n        props.className.push(subvalue)\n      } else {\n        props.className = [subvalue]\n      }\n\n      start += subvalue.length\n    }\n\n    if (match) {\n      previous = match[0]\n      start++\n    }\n  }\n\n  return {\n    type: 'element',\n    // @ts-expect-error: tag name is parsed.\n    tagName: tagName || defaultTagName || 'div',\n    properties: props,\n    children: []\n  }\n}\n","/**\n * Parse space-separated tokens to an array of strings.\n *\n * @param {string} value\n *   Space-separated tokens.\n * @returns {Array<string>}\n *   List of tokens.\n */\nexport function parse(value) {\n  const input = String(value || '').trim()\n  return input ? input.split(/[ \\t\\n\\r\\f]+/g) : []\n}\n\n/**\n * Serialize an array of strings as space separated-tokens.\n *\n * @param {Array<string|number>} values\n *   List of tokens.\n * @returns {string}\n *   Space-separated tokens.\n */\nexport function stringify(values) {\n  return values.join(' ').trim()\n}\n","/**\n * @import {Element, Nodes, RootContent, Root} from 'hast'\n * @import {Info, Schema} from 'property-information'\n */\n\n/**\n * @typedef {Array<Nodes | PrimitiveChild>} ArrayChildNested\n *   List of children (deep).\n */\n\n/**\n * @typedef {Array<ArrayChildNested | Nodes | PrimitiveChild>} ArrayChild\n *   List of children.\n */\n\n/**\n * @typedef {Array<number | string>} ArrayValue\n *   List of property values for space- or comma separated values (such as `className`).\n */\n\n/**\n * @typedef {ArrayChild | Nodes | PrimitiveChild} Child\n *   Acceptable child value.\n */\n\n/**\n * @typedef {number | string | null | undefined} PrimitiveChild\n *   Primitive children, either ignored (nullish), or turned into text nodes.\n */\n\n/**\n * @typedef {boolean | number | string | null | undefined} PrimitiveValue\n *   Primitive property value.\n */\n\n/**\n * @typedef {Record<string, PropertyValue | Style>} Properties\n *   Acceptable value for element properties.\n */\n\n/**\n * @typedef {ArrayValue | PrimitiveValue} PropertyValue\n *   Primitive value or list value.\n */\n\n/**\n * @typedef {Element | Root} Result\n *   Result from a `h` (or `s`) call.\n */\n\n/**\n * @typedef {number | string} StyleValue\n *   Value for a CSS style field.\n */\n\n/**\n * @typedef {Record<string, StyleValue>} Style\n *   Supported value of a `style` prop.\n */\n\nimport {parse as parseCommas} from 'comma-separated-tokens'\nimport {parseSelector} from 'hast-util-parse-selector'\nimport {find, normalize} from 'property-information'\nimport {parse as parseSpaces} from 'space-separated-tokens'\n\n/**\n * @param {Schema} schema\n *   Schema to use.\n * @param {string} defaultTagName\n *   Default tag name.\n * @param {ReadonlyArray<string> | undefined} [caseSensitive]\n *   Case-sensitive tag names (default: `undefined`).\n * @returns\n *   `h`.\n */\nexport function createH(schema, defaultTagName, caseSensitive) {\n  const adjust = caseSensitive ? createAdjustMap(caseSensitive) : undefined\n\n  /**\n   * Hyperscript compatible DSL for creating virtual hast trees.\n   *\n   * @overload\n   * @param {null | undefined} [selector]\n   * @param {...Child} children\n   * @returns {Root}\n   *\n   * @overload\n   * @param {string} selector\n   * @param {Properties} properties\n   * @param {...Child} children\n   * @returns {Element}\n   *\n   * @overload\n   * @param {string} selector\n   * @param {...Child} children\n   * @returns {Element}\n   *\n   * @param {string | null | undefined} [selector]\n   *   Selector.\n   * @param {Child | Properties | null | undefined} [properties]\n   *   Properties (or first child) (default: `undefined`).\n   * @param {...Child} children\n   *   Children.\n   * @returns {Result}\n   *   Result.\n   */\n  function h(selector, properties, ...children) {\n    /** @type {Result} */\n    let node\n\n    if (selector === null || selector === undefined) {\n      node = {type: 'root', children: []}\n      // Properties are not supported for roots.\n      const child = /** @type {Child} */ (properties)\n      children.unshift(child)\n    } else {\n      node = parseSelector(selector, defaultTagName)\n      // Normalize the name.\n      const lower = node.tagName.toLowerCase()\n      const adjusted = adjust ? adjust.get(lower) : undefined\n      node.tagName = adjusted || lower\n\n      // Handle properties.\n      if (isChild(properties)) {\n        children.unshift(properties)\n      } else {\n        for (const [key, value] of Object.entries(properties)) {\n          addProperty(schema, node.properties, key, value)\n        }\n      }\n    }\n\n    // Handle children.\n    for (const child of children) {\n      addChild(node.children, child)\n    }\n\n    if (node.type === 'element' && node.tagName === 'template') {\n      node.content = {type: 'root', children: node.children}\n      node.children = []\n    }\n\n    return node\n  }\n\n  return h\n}\n\n/**\n * Check if something is properties or a child.\n *\n * @param {Child | Properties} value\n *   Value to check.\n * @returns {value is Child}\n *   Whether `value` is definitely a child.\n */\nfunction isChild(value) {\n  // Never properties if not an object.\n  if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n    return true\n  }\n\n  // Never node without `type`; that’s the main discriminator.\n  if (typeof value.type !== 'string') return false\n\n  // Slower check: never property value if object or array with\n  // non-number/strings.\n  const record = /** @type {Record<string, unknown>} */ (value)\n  const keys = Object.keys(value)\n\n  for (const key of keys) {\n    const value = record[key]\n\n    if (value && typeof value === 'object') {\n      if (!Array.isArray(value)) return true\n\n      const list = /** @type {ReadonlyArray<unknown>} */ (value)\n\n      for (const item of list) {\n        if (typeof item !== 'number' && typeof item !== 'string') {\n          return true\n        }\n      }\n    }\n  }\n\n  // Also see empty `children` as a node.\n  if ('children' in value && Array.isArray(value.children)) {\n    return true\n  }\n\n  // Default to properties, someone can always pass an empty object,\n  // put `data: {}` in a node,\n  // or wrap it in an array.\n  return false\n}\n\n/**\n * @param {Schema} schema\n *   Schema.\n * @param {Properties} properties\n *   Properties object.\n * @param {string} key\n *   Property name.\n * @param {PropertyValue | Style} value\n *   Property value.\n * @returns {undefined}\n *   Nothing.\n */\nfunction addProperty(schema, properties, key, value) {\n  const info = find(schema, key)\n  /** @type {PropertyValue} */\n  let result\n\n  // Ignore nullish and NaN values.\n  if (value === null || value === undefined) return\n\n  if (typeof value === 'number') {\n    // Ignore NaN.\n    if (Number.isNaN(value)) return\n\n    result = value\n  }\n  // Booleans.\n  else if (typeof value === 'boolean') {\n    result = value\n  }\n  // Handle list values.\n  else if (typeof value === 'string') {\n    if (info.spaceSeparated) {\n      result = parseSpaces(value)\n    } else if (info.commaSeparated) {\n      result = parseCommas(value)\n    } else if (info.commaOrSpaceSeparated) {\n      result = parseSpaces(parseCommas(value).join(' '))\n    } else {\n      result = parsePrimitive(info, info.property, value)\n    }\n  } else if (Array.isArray(value)) {\n    result = [...value]\n  } else {\n    result = info.property === 'style' ? style(value) : String(value)\n  }\n\n  if (Array.isArray(result)) {\n    /** @type {Array<number | string>} */\n    const finalResult = []\n\n    for (const item of result) {\n      // Assume no booleans in array.\n      finalResult.push(\n        /** @type {number | string} */ (\n          parsePrimitive(info, info.property, item)\n        )\n      )\n    }\n\n    result = finalResult\n  }\n\n  // Class names (which can be added both on the `selector` and here).\n  if (info.property === 'className' && Array.isArray(properties.className)) {\n    // Assume no booleans in `className`.\n    result = properties.className.concat(\n      /** @type {Array<number | string> | number | string} */ (result)\n    )\n  }\n\n  properties[info.property] = result\n}\n\n/**\n * @param {Array<RootContent>} nodes\n *   Children.\n * @param {Child} value\n *   Child.\n * @returns {undefined}\n *   Nothing.\n */\nfunction addChild(nodes, value) {\n  if (value === null || value === undefined) {\n    // Empty.\n  } else if (typeof value === 'number' || typeof value === 'string') {\n    nodes.push({type: 'text', value: String(value)})\n  } else if (Array.isArray(value)) {\n    for (const child of value) {\n      addChild(nodes, child)\n    }\n  } else if (typeof value === 'object' && 'type' in value) {\n    if (value.type === 'root') {\n      addChild(nodes, value.children)\n    } else {\n      nodes.push(value)\n    }\n  } else {\n    throw new Error('Expected node, nodes, or string, got `' + value + '`')\n  }\n}\n\n/**\n * Parse a single primitives.\n *\n * @param {Info} info\n *   Property information.\n * @param {string} name\n *   Property name.\n * @param {PrimitiveValue} value\n *   Property value.\n * @returns {PrimitiveValue}\n *   Property value.\n */\nfunction parsePrimitive(info, name, value) {\n  if (typeof value === 'string') {\n    if (info.number && value && !Number.isNaN(Number(value))) {\n      return Number(value)\n    }\n\n    if (\n      (info.boolean || info.overloadedBoolean) &&\n      (value === '' || normalize(value) === normalize(name))\n    ) {\n      return true\n    }\n  }\n\n  return value\n}\n\n/**\n * Serialize a `style` object as a string.\n *\n * @param {Style} styles\n *   Style object.\n * @returns {string}\n *   CSS string.\n */\nfunction style(styles) {\n  /** @type {Array<string>} */\n  const result = []\n\n  for (const [key, value] of Object.entries(styles)) {\n    result.push([key, value].join(': '))\n  }\n\n  return result.join('; ')\n}\n\n/**\n * Create a map to adjust casing.\n *\n * @param {ReadonlyArray<string>} values\n *   List of properly cased keys.\n * @returns {Map<string, string>}\n *   Map of lowercase keys to uppercase keys.\n */\nfunction createAdjustMap(values) {\n  /** @type {Map<string, string>} */\n  const result = new Map()\n\n  for (const value of values) {\n    result.set(value.toLowerCase(), value)\n  }\n\n  return result\n}\n","/**\n * List of case-sensitive SVG tag names.\n *\n * @type {ReadonlyArray<string>}\n */\nexport const svgCaseSensitiveTagNames = [\n  'altGlyph',\n  'altGlyphDef',\n  'altGlyphItem',\n  'animateColor',\n  'animateMotion',\n  'animateTransform',\n  'clipPath',\n  'feBlend',\n  'feColorMatrix',\n  'feComponentTransfer',\n  'feComposite',\n  'feConvolveMatrix',\n  'feDiffuseLighting',\n  'feDisplacementMap',\n  'feDistantLight',\n  'feDropShadow',\n  'feFlood',\n  'feFuncA',\n  'feFuncB',\n  'feFuncG',\n  'feFuncR',\n  'feGaussianBlur',\n  'feImage',\n  'feMerge',\n  'feMergeNode',\n  'feMorphology',\n  'feOffset',\n  'fePointLight',\n  'feSpecularLighting',\n  'feSpotLight',\n  'feTile',\n  'feTurbulence',\n  'foreignObject',\n  'glyphRef',\n  'linearGradient',\n  'radialGradient',\n  'solidColor',\n  'textArea',\n  'textPath'\n]\n","// Register the JSX namespace on `h`.\n/**\n * @typedef {import('./jsx-classic.js').Element} h.JSX.Element\n * @typedef {import('./jsx-classic.js').ElementChildrenAttribute} h.JSX.ElementChildrenAttribute\n * @typedef {import('./jsx-classic.js').IntrinsicAttributes} h.JSX.IntrinsicAttributes\n * @typedef {import('./jsx-classic.js').IntrinsicElements} h.JSX.IntrinsicElements\n */\n\n// Register the JSX namespace on `s`.\n/**\n * @typedef {import('./jsx-classic.js').Element} s.JSX.Element\n * @typedef {import('./jsx-classic.js').ElementChildrenAttribute} s.JSX.ElementChildrenAttribute\n * @typedef {import('./jsx-classic.js').IntrinsicAttributes} s.JSX.IntrinsicAttributes\n * @typedef {import('./jsx-classic.js').IntrinsicElements} s.JSX.IntrinsicElements\n */\n\nimport {html, svg} from 'property-information'\nimport {createH} from './create-h.js'\nimport {svgCaseSensitiveTagNames} from './svg-case-sensitive-tag-names.js'\n\n// Note: this explicit type is needed, otherwise TS creates broken types.\n/** @type {ReturnType<createH>} */\nexport const h = createH(html, 'div')\n\n// Note: this explicit type is needed, otherwise TS creates broken types.\n/** @type {ReturnType<createH>} */\nexport const s = createH(svg, 'g', svgCaseSensitiveTagNames)\n","/**\n * Map of web namespaces.\n *\n * @type {Record<string, string>}\n */\nexport const webNamespaces = {\n  html: 'http://www.w3.org/1999/xhtml',\n  mathml: 'http://www.w3.org/1998/Math/MathML',\n  svg: 'http://www.w3.org/2000/svg',\n  xlink: 'http://www.w3.org/1999/xlink',\n  xml: 'http://www.w3.org/XML/1998/namespace',\n  xmlns: 'http://www.w3.org/2000/xmlns/'\n}\n","/**\n * @import {\n *   Comment as HastComment,\n *   Doctype as HastDoctype,\n *   Element as HastElement,\n *   Nodes as HastNodes,\n *   RootContent as HastRootContent,\n *   Root as HastRoot,\n *   Text as HastText,\n * } from 'hast'\n */\n\n/**\n * @callback AfterTransform\n *   Callback called when each node is transformed.\n * @param {Node} domNode\n *   DOM node that was handled.\n * @param {HastNodes} hastNode\n *   Corresponding hast node.\n * @returns {undefined | void}\n *   Nothing.\n *\n *   Note: `void` included until TS infers `undefined` nicely.\n *\n * @typedef Options\n *   Configuration.\n * @property {AfterTransform | null | undefined} [afterTransform]\n *   Callback called when each node is transformed (optional).\n */\n\nimport {h, s} from 'hastscript'\nimport {webNamespaces} from 'web-namespaces'\n\n/**\n * Transform a DOM tree to a hast tree.\n *\n * @param {Node} tree\n *   DOM tree to transform.\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {HastNodes}\n *   Equivalent hast node.\n */\nexport function fromDom(tree, options) {\n  return transform(tree, options || {}) || {type: 'root', children: []}\n}\n\n/**\n * @param {Node} node\n *   DOM node to transform.\n * @param {Options} options\n *   Configuration.\n * @returns {HastNodes | undefined}\n *   Equivalent hast node.\n *\n *   Note that certain legacy DOM nodes (i.e., Attr nodes (2),  CDATA, processing instructions)\n */\nfunction transform(node, options) {\n  const transformed = one(node, options)\n  if (transformed && options.afterTransform)\n    options.afterTransform(node, transformed)\n  return transformed\n}\n\n/**\n * @param {Node} node\n *   DOM node to transform.\n * @param {Options} options\n *   Configuration.\n * @returns {HastNodes | undefined}\n *   Equivalent hast node.\n */\nfunction one(node, options) {\n  switch (node.nodeType) {\n    case 1 /* Element */: {\n      const domNode = /** @type {Element} */ (node)\n      return element(domNode, options)\n    }\n\n    // Ignore: Attr (2).\n\n    case 3 /* Text */: {\n      const domNode = /** @type {Text} */ (node)\n      return text(domNode)\n    }\n\n    // Ignore: CDATA (4).\n    // Removed: Entity reference (5)\n    // Removed: Entity (6)\n    // Ignore: Processing instruction (7).\n\n    case 8 /* Comment */: {\n      const domNode = /** @type {Comment} */ (node)\n      return comment(domNode)\n    }\n\n    case 9 /* Document */: {\n      const domNode = /** @type {Document} */ (node)\n      return root(domNode, options)\n    }\n\n    case 10 /* Document type */: {\n      return doctype()\n    }\n\n    case 11 /* Document fragment */: {\n      const domNode = /** @type {DocumentFragment} */ (node)\n      return root(domNode, options)\n    }\n\n    default: {\n      return undefined\n    }\n  }\n}\n\n/**\n * Transform a document.\n *\n * @param {Document | DocumentFragment} node\n *   DOM node to transform.\n * @param {Options} options\n *   Configuration.\n * @returns {HastRoot}\n *   Equivalent hast node.\n */\nfunction root(node, options) {\n  return {type: 'root', children: all(node, options)}\n}\n\n/**\n * Transform a doctype.\n *\n * @returns {HastDoctype}\n *   Equivalent hast node.\n */\nfunction doctype() {\n  return {type: 'doctype'}\n}\n\n/**\n * Transform a text.\n *\n * @param {Text} node\n *   DOM node to transform.\n * @returns {HastText}\n *   Equivalent hast node.\n */\nfunction text(node) {\n  return {type: 'text', value: node.nodeValue || ''}\n}\n\n/**\n * Transform a comment.\n *\n * @param {Comment} node\n *   DOM node to transform.\n * @returns {HastComment}\n *   Equivalent hast node.\n */\nfunction comment(node) {\n  return {type: 'comment', value: node.nodeValue || ''}\n}\n\n/**\n * Transform an element.\n *\n * @param {Element} node\n *   DOM node to transform.\n * @param {Options} options\n *   Configuration.\n * @returns {HastElement}\n *   Equivalent hast node.\n */\nfunction element(node, options) {\n  const space = node.namespaceURI\n  const x = space === webNamespaces.svg ? s : h\n  const tagName =\n    space === webNamespaces.html ? node.tagName.toLowerCase() : node.tagName\n  /** @type {DocumentFragment | Element} */\n  const content =\n    // @ts-expect-error: DOM types are wrong, content can exist.\n    space === webNamespaces.html && tagName === 'template' ? node.content : node\n  const attributes = node.getAttributeNames()\n  /** @type {Record<string, string>} */\n  const properties = {}\n  let index = -1\n\n  while (++index < attributes.length) {\n    properties[attributes[index]] = node.getAttribute(attributes[index]) || ''\n  }\n\n  return x(tagName, properties, all(content, options))\n}\n\n/**\n * Transform child nodes in a parent.\n *\n * @param {Document | DocumentFragment | Element} node\n *   DOM node to transform.\n * @param {Options} options\n *   Configuration.\n * @returns {Array<HastRootContent>}\n *   Equivalent hast nodes.\n */\nfunction all(node, options) {\n  const nodes = node.childNodes\n  /** @type {Array<HastRootContent>} */\n  const children = []\n  let index = -1\n\n  while (++index < nodes.length) {\n    const child = transform(nodes[index], options)\n\n    if (child !== undefined) {\n      // @ts-expect-error Assume no document inside document.\n      children.push(child)\n    }\n  }\n\n  return children\n}\n","/**\n * @typedef {import('hast').Root} Root\n *\n * @typedef {typeof import('./index.js').fromHtmlIsomorphic} FromHtmlIsomorphic\n */\n\nimport {fromDom} from 'hast-util-from-dom'\n\nconst parser = new DOMParser()\n\n/** @type {FromHtmlIsomorphic} */\nexport function fromHtmlIsomorphic(value, options) {\n  const node = options?.fragment\n    ? parseFragment(value)\n    : parser.parseFromString(value, 'text/html')\n\n  return /** @type {Root} */ (fromDom(node))\n}\n\n/**\n * Parse as a fragment.\n *\n * @param {string} value\n * @returns {DocumentFragment}\n */\nfunction parseFragment(value) {\n  const template = document.createElement('template')\n  template.innerHTML = value\n  return template.content\n}\n","/**\n * @typedef {import('unist').Node} UnistNode\n * @typedef {import('unist').Parent} UnistParent\n */\n\n/**\n * @typedef {Exclude<import('unist-util-is').Test, undefined> | undefined} Test\n *   Test from `unist-util-is`.\n *\n *   Note: we have remove and add `undefined`, because otherwise when generating\n *   automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n *   which doesn’t work when publishing on npm.\n */\n\n/**\n * @typedef {(\n *   Fn extends (value: any) => value is infer Thing\n *   ? Thing\n *   : Fallback\n * )} Predicate\n *   Get the value of a type guard `Fn`.\n * @template Fn\n *   Value; typically function that is a type guard (such as `(x): x is Y`).\n * @template Fallback\n *   Value to yield if `Fn` is not a type guard.\n */\n\n/**\n * @typedef {(\n *   Check extends null | undefined // No test.\n *   ? Value\n *   : Value extends {type: Check} // String (type) test.\n *   ? Value\n *   : Value extends Check // Partial test.\n *   ? Value\n *   : Check extends Function // Function test.\n *   ? Predicate<Check, Value> extends Value\n *     ? Predicate<Check, Value>\n *     : never\n *   : never // Some other test?\n * )} MatchesOne\n *   Check whether a node matches a primitive check in the type system.\n * @template Value\n *   Value; typically unist `Node`.\n * @template Check\n *   Value; typically `unist-util-is`-compatible test, but not arrays.\n */\n\n/**\n * @typedef {(\n *   Check extends Array<any>\n *   ? MatchesOne<Value, Check[keyof Check]>\n *   : MatchesOne<Value, Check>\n * )} Matches\n *   Check whether a node matches a check in the type system.\n * @template Value\n *   Value; typically unist `Node`.\n * @template Check\n *   Value; typically `unist-util-is`-compatible test.\n */\n\n/**\n * @typedef {(\n *   Kind extends {children: Array<infer Child>}\n *   ? Child\n *   : never\n * )} Child\n *   Collect nodes that can be parents of `Child`.\n * @template {UnistNode} Kind\n *   All node types.\n */\n\nimport {convert} from 'unist-util-is'\n\n/**\n * Find the first node in `parent` after another `node` or after an index,\n * that passes `test`.\n *\n * @param parent\n *   Parent node.\n * @param index\n *   Child node or index.\n * @param [test=undefined]\n *   Test for child to look for (optional).\n * @returns\n *   A child (matching `test`, if given) or `undefined`.\n */\nexport const findAfter =\n  // Note: overloads like this are needed to support optional generics.\n  /**\n   * @type {(\n   *   (<Kind extends UnistParent, Check extends Test>(parent: Kind, index: Child<Kind> | number, test: Check) => Matches<Child<Kind>, Check> | undefined) &\n   *   (<Kind extends UnistParent>(parent: Kind, index: Child<Kind> | number, test?: null | undefined) => Child<Kind> | undefined)\n   * )}\n   */\n  (\n    /**\n     * @param {UnistParent} parent\n     * @param {UnistNode | number} index\n     * @param {Test} [test]\n     * @returns {UnistNode | undefined}\n     */\n    function (parent, index, test) {\n      const is = convert(test)\n\n      if (!parent || !parent.type || !parent.children) {\n        throw new Error('Expected parent node')\n      }\n\n      if (typeof index === 'number') {\n        if (index < 0 || index === Number.POSITIVE_INFINITY) {\n          throw new Error('Expected positive finite number as index')\n        }\n      } else {\n        index = parent.children.indexOf(index)\n\n        if (index < 0) {\n          throw new Error('Expected child node or index')\n        }\n      }\n\n      while (++index < parent.children.length) {\n        if (is(parent.children[index], index, parent)) {\n          return parent.children[index]\n        }\n      }\n\n      return undefined\n    }\n  )\n","/**\n * @typedef {import('hast').Element} Element\n * @typedef {import('hast').Parents} Parents\n */\n\n/**\n * @template Fn\n * @template Fallback\n * @typedef {Fn extends (value: any) => value is infer Thing ? Thing : Fallback} Predicate\n */\n\n/**\n * @callback Check\n *   Check that an arbitrary value is an element.\n * @param {unknown} this\n *   Context object (`this`) to call `test` with\n * @param {unknown} [element]\n *   Anything (typically a node).\n * @param {number | null | undefined} [index]\n *   Position of `element` in its parent.\n * @param {Parents | null | undefined} [parent]\n *   Parent of `element`.\n * @returns {boolean}\n *   Whether this is an element and passes a test.\n *\n * @typedef {Array<TestFunction | string> | TestFunction | string | null | undefined} Test\n *   Check for an arbitrary element.\n *\n *   * when `string`, checks that the element has that tag name\n *   * when `function`, see `TestFunction`\n *   * when `Array`, checks if one of the subtests pass\n *\n * @callback TestFunction\n *   Check if an element passes a test.\n * @param {unknown} this\n *   The given context.\n * @param {Element} element\n *   An element.\n * @param {number | undefined} [index]\n *   Position of `element` in its parent.\n * @param {Parents | undefined} [parent]\n *   Parent of `element`.\n * @returns {boolean | undefined | void}\n *   Whether this element passes the test.\n *\n *   Note: `void` is included until TS sees no return as `undefined`.\n */\n\n/**\n * Check if `element` is an `Element` and whether it passes the given test.\n *\n * @param element\n *   Thing to check, typically `element`.\n * @param test\n *   Check for a specific element.\n * @param index\n *   Position of `element` in its parent.\n * @param parent\n *   Parent of `element`.\n * @param context\n *   Context object (`this`) to call `test` with.\n * @returns\n *   Whether `element` is an `Element` and passes a test.\n * @throws\n *   When an incorrect `test`, `index`, or `parent` is given; there is no error\n *   thrown when `element` is not a node or not an element.\n */\nexport const isElement =\n  // Note: overloads in JSDoc can’t yet use different `@template`s.\n  /**\n   * @type {(\n   *   (<Condition extends TestFunction>(element: unknown, test: Condition, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => element is Element & Predicate<Condition, Element>) &\n   *   (<Condition extends string>(element: unknown, test: Condition, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => element is Element & {tagName: Condition}) &\n   *   ((element?: null | undefined) => false) &\n   *   ((element: unknown, test?: null | undefined, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => element is Element) &\n   *   ((element: unknown, test?: Test, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => boolean)\n   * )}\n   */\n  (\n    /**\n     * @param {unknown} [element]\n     * @param {Test | undefined} [test]\n     * @param {number | null | undefined} [index]\n     * @param {Parents | null | undefined} [parent]\n     * @param {unknown} [context]\n     * @returns {boolean}\n     */\n    // eslint-disable-next-line max-params\n    function (element, test, index, parent, context) {\n      const check = convertElement(test)\n\n      if (\n        index !== null &&\n        index !== undefined &&\n        (typeof index !== 'number' ||\n          index < 0 ||\n          index === Number.POSITIVE_INFINITY)\n      ) {\n        throw new Error('Expected positive finite `index`')\n      }\n\n      if (\n        parent !== null &&\n        parent !== undefined &&\n        (!parent.type || !parent.children)\n      ) {\n        throw new Error('Expected valid `parent`')\n      }\n\n      if (\n        (index === null || index === undefined) !==\n        (parent === null || parent === undefined)\n      ) {\n        throw new Error('Expected both `index` and `parent`')\n      }\n\n      return looksLikeAnElement(element)\n        ? check.call(context, element, index, parent)\n        : false\n    }\n  )\n\n/**\n * Generate a check from a test.\n *\n * Useful if you’re going to test many nodes, for example when creating a\n * utility where something else passes a compatible test.\n *\n * The created function is a bit faster because it expects valid input only:\n * an `element`, `index`, and `parent`.\n *\n * @param test\n *   A test for a specific element.\n * @returns\n *   A check.\n */\nexport const convertElement =\n  // Note: overloads in JSDoc can’t yet use different `@template`s.\n  /**\n   * @type {(\n   *   (<Condition extends TestFunction>(test: Condition) => (element: unknown, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => element is Element & Predicate<Condition, Element>) &\n   *   (<Condition extends string>(test: Condition) => (element: unknown, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => element is Element & {tagName: Condition}) &\n   *   ((test?: null | undefined) => (element?: unknown, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => element is Element) &\n   *   ((test?: Test) => Check)\n   * )}\n   */\n  (\n    /**\n     * @param {Test | null | undefined} [test]\n     * @returns {Check}\n     */\n    function (test) {\n      if (test === null || test === undefined) {\n        return element\n      }\n\n      if (typeof test === 'string') {\n        return tagNameFactory(test)\n      }\n\n      // Assume array.\n      if (typeof test === 'object') {\n        return anyFactory(test)\n      }\n\n      if (typeof test === 'function') {\n        return castFactory(test)\n      }\n\n      throw new Error('Expected function, string, or array as `test`')\n    }\n  )\n\n/**\n * Handle multiple tests.\n *\n * @param {Array<TestFunction | string>} tests\n * @returns {Check}\n */\nfunction anyFactory(tests) {\n  /** @type {Array<Check>} */\n  const checks = []\n  let index = -1\n\n  while (++index < tests.length) {\n    checks[index] = convertElement(tests[index])\n  }\n\n  return castFactory(any)\n\n  /**\n   * @this {unknown}\n   * @type {TestFunction}\n   */\n  function any(...parameters) {\n    let index = -1\n\n    while (++index < checks.length) {\n      if (checks[index].apply(this, parameters)) return true\n    }\n\n    return false\n  }\n}\n\n/**\n * Turn a string into a test for an element with a certain type.\n *\n * @param {string} check\n * @returns {Check}\n */\nfunction tagNameFactory(check) {\n  return castFactory(tagName)\n\n  /**\n   * @param {Element} element\n   * @returns {boolean}\n   */\n  function tagName(element) {\n    return element.tagName === check\n  }\n}\n\n/**\n * Turn a custom test into a test for an element that passes that test.\n *\n * @param {TestFunction} testFunction\n * @returns {Check}\n */\nfunction castFactory(testFunction) {\n  return check\n\n  /**\n   * @this {unknown}\n   * @type {Check}\n   */\n  function check(value, index, parent) {\n    return Boolean(\n      looksLikeAnElement(value) &&\n        testFunction.call(\n          this,\n          value,\n          typeof index === 'number' ? index : undefined,\n          parent || undefined\n        )\n    )\n  }\n}\n\n/**\n * Make sure something is an element.\n *\n * @param {unknown} element\n * @returns {element is Element}\n */\nfunction element(element) {\n  return Boolean(\n    element &&\n      typeof element === 'object' &&\n      'type' in element &&\n      element.type === 'element' &&\n      'tagName' in element &&\n      typeof element.tagName === 'string'\n  )\n}\n\n/**\n * @param {unknown} value\n * @returns {value is Element}\n */\nfunction looksLikeAnElement(value) {\n  return (\n    value !== null &&\n    typeof value === 'object' &&\n    'type' in value &&\n    'tagName' in value\n  )\n}\n","/**\n * @typedef {import('hast').Comment} Comment\n * @typedef {import('hast').Element} Element\n * @typedef {import('hast').Nodes} Nodes\n * @typedef {import('hast').Parents} Parents\n * @typedef {import('hast').Text} Text\n * @typedef {import('hast-util-is-element').TestFunction} TestFunction\n */\n\n/**\n * @typedef {'normal' | 'nowrap' | 'pre' | 'pre-wrap'} Whitespace\n *   Valid and useful whitespace values (from CSS).\n *\n * @typedef {0 | 1 | 2} BreakNumber\n *   Specific break:\n *\n *   *   `0` — space\n *   *   `1` — line ending\n *   *   `2` — blank line\n *\n * @typedef {'\\n'} BreakForce\n *   Forced break.\n *\n * @typedef {boolean} BreakValue\n *   Whether there was a break.\n *\n * @typedef {BreakNumber | BreakValue | undefined} BreakBefore\n *   Any value for a break before.\n *\n * @typedef {BreakForce | BreakNumber | BreakValue | undefined} BreakAfter\n *   Any value for a break after.\n *\n * @typedef CollectionInfo\n *   Info on current collection.\n * @property {BreakAfter} breakAfter\n *   Whether there was a break after.\n * @property {BreakBefore} breakBefore\n *   Whether there was a break before.\n * @property {Whitespace} whitespace\n *   Current whitespace setting.\n *\n * @typedef Options\n *   Configuration.\n * @property {Whitespace | null | undefined} [whitespace='normal']\n *   Initial CSS whitespace setting to use (default: `'normal'`).\n */\n\nimport {findAfter} from 'unist-util-find-after'\nimport {convertElement} from 'hast-util-is-element'\n\nconst searchLineFeeds = /\\n/g\nconst searchTabOrSpaces = /[\\t ]+/g\n\nconst br = convertElement('br')\nconst cell = convertElement(isCell)\nconst p = convertElement('p')\nconst row = convertElement('tr')\n\n// Note that we don’t need to include void elements here as they don’t have text.\n// See: <https://github.com/wooorm/html-void-elements>\nconst notRendered = convertElement([\n  // List from: <https://html.spec.whatwg.org/multipage/rendering.html#hidden-elements>\n  'datalist',\n  'head',\n  'noembed',\n  'noframes',\n  'noscript', // Act as if we support scripting.\n  'rp',\n  'script',\n  'style',\n  'template',\n  'title',\n  // Hidden attribute.\n  hidden,\n  // From: <https://html.spec.whatwg.org/multipage/rendering.html#flow-content-3>\n  closedDialog\n])\n\n// See: <https://html.spec.whatwg.org/multipage/rendering.html#the-css-user-agent-style-sheet-and-presentational-hints>\nconst blockOrCaption = convertElement([\n  'address', // Flow content\n  'article', // Sections and headings\n  'aside', // Sections and headings\n  'blockquote', // Flow content\n  'body', // Page\n  'caption', // `table-caption`\n  'center', // Flow content (legacy)\n  'dd', // Lists\n  'dialog', // Flow content\n  'dir', // Lists (legacy)\n  'dl', // Lists\n  'dt', // Lists\n  'div', // Flow content\n  'figure', // Flow content\n  'figcaption', // Flow content\n  'footer', // Flow content\n  'form,', // Flow content\n  'h1', // Sections and headings\n  'h2', // Sections and headings\n  'h3', // Sections and headings\n  'h4', // Sections and headings\n  'h5', // Sections and headings\n  'h6', // Sections and headings\n  'header', // Flow content\n  'hgroup', // Sections and headings\n  'hr', // Flow content\n  'html', // Page\n  'legend', // Flow content\n  'li', // Lists (as `display: list-item`)\n  'listing', // Flow content (legacy)\n  'main', // Flow content\n  'menu', // Lists\n  'nav', // Sections and headings\n  'ol', // Lists\n  'p', // Flow content\n  'plaintext', // Flow content (legacy)\n  'pre', // Flow content\n  'section', // Sections and headings\n  'ul', // Lists\n  'xmp' // Flow content (legacy)\n])\n\n/**\n * Get the plain-text value of a node.\n *\n * ###### Algorithm\n *\n * *   if `tree` is a comment, returns its `value`\n * *   if `tree` is a text, applies normal whitespace collapsing to its\n *     `value`, as defined by the CSS Text spec\n * *   if `tree` is a root or element, applies an algorithm similar to the\n *     `innerText` getter as defined by HTML\n *\n * ###### Notes\n *\n * > 👉 **Note**: the algorithm acts as if `tree` is being rendered, and as if\n * > we’re a CSS-supporting user agent, with scripting enabled.\n *\n * *   if `tree` is an element that is not displayed (such as a `head`), we’ll\n *     still use the `innerText` algorithm instead of switching to `textContent`\n * *   if descendants of `tree` are elements that are not displayed, they are\n *     ignored\n * *   CSS is not considered, except for the default user agent style sheet\n * *   a line feed is collapsed instead of ignored in cases where Fullwidth, Wide,\n *     or Halfwidth East Asian Width characters are used, the same goes for a case\n *     with Chinese, Japanese, or Yi writing systems\n * *   replaced elements (such as `audio`) are treated like non-replaced elements\n *\n * @param {Nodes} tree\n *   Tree to turn into text.\n * @param {Readonly<Options> | null | undefined} [options]\n *   Configuration (optional).\n * @returns {string}\n *   Serialized `tree`.\n */\nexport function toText(tree, options) {\n  const options_ = options || {}\n  const children = 'children' in tree ? tree.children : []\n  const block = blockOrCaption(tree)\n  const whitespace = inferWhitespace(tree, {\n    whitespace: options_.whitespace || 'normal',\n    breakBefore: false,\n    breakAfter: false\n  })\n\n  /** @type {Array<BreakNumber | string>} */\n  const results = []\n\n  // Treat `text` and `comment` as having normal white-space.\n  // This deviates from the spec as in the DOM the node’s `.data` has to be\n  // returned.\n  // If you want that behavior use `hast-util-to-string`.\n  // All other nodes are later handled as if they are `element`s (so the\n  // algorithm also works on a `root`).\n  // Nodes without children are treated as a void element, so `doctype` is thus\n  // ignored.\n  if (tree.type === 'text' || tree.type === 'comment') {\n    results.push(\n      ...collectText(tree, {\n        whitespace,\n        breakBefore: true,\n        breakAfter: true\n      })\n    )\n  }\n\n  // 1.  If this element is not being rendered, or if the user agent is a\n  //     non-CSS user agent, then return the same value as the textContent IDL\n  //     attribute on this element.\n  //\n  //     Note: we’re not supporting stylesheets so we’re acting as if the node\n  //     is rendered.\n  //\n  //     If you want that behavior use `hast-util-to-string`.\n  //     Important: we’ll have to account for this later though.\n\n  // 2.  Let results be a new empty list.\n  let index = -1\n\n  // 3.  For each child node node of this element:\n  while (++index < children.length) {\n    // 3.1. Let current be the list resulting in running the inner text\n    //      collection steps with node.\n    //      Each item in results will either be a JavaScript string or a\n    //      positive integer (a required line break count).\n    // 3.2. For each item item in current, append item to results.\n    results.push(\n      ...renderedTextCollection(\n        children[index],\n        // @ts-expect-error: `tree` is a parent if we’re here.\n        tree,\n        {\n          whitespace,\n          breakBefore: index ? undefined : block,\n          breakAfter:\n            index < children.length - 1 ? br(children[index + 1]) : block\n        }\n      )\n    )\n  }\n\n  // 4.  Remove any items from results that are the empty string.\n  // 5.  Remove any runs of consecutive required line break count items at the\n  //     start or end of results.\n  // 6.  Replace each remaining run of consecutive required line break count\n  //     items with a string consisting of as many U+000A LINE FEED (LF)\n  //     characters as the maximum of the values in the required line break\n  //     count items.\n  /** @type {Array<string>} */\n  const result = []\n  /** @type {number | undefined} */\n  let count\n\n  index = -1\n\n  while (++index < results.length) {\n    const value = results[index]\n\n    if (typeof value === 'number') {\n      if (count !== undefined && value > count) count = value\n    } else if (value) {\n      if (count !== undefined && count > -1) {\n        result.push('\\n'.repeat(count) || ' ')\n      }\n\n      count = -1\n      result.push(value)\n    }\n  }\n\n  // 7.  Return the concatenation of the string items in results.\n  return result.join('')\n}\n\n/**\n * <https://html.spec.whatwg.org/multipage/dom.html#rendered-text-collection-steps>\n *\n * @param {Nodes} node\n * @param {Parents} parent\n * @param {CollectionInfo} info\n * @returns {Array<BreakNumber | string>}\n */\nfunction renderedTextCollection(node, parent, info) {\n  if (node.type === 'element') {\n    return collectElement(node, parent, info)\n  }\n\n  if (node.type === 'text') {\n    return info.whitespace === 'normal'\n      ? collectText(node, info)\n      : collectPreText(node)\n  }\n\n  return []\n}\n\n/**\n * Collect an element.\n *\n * @param {Element} node\n *   Element node.\n * @param {Parents} parent\n * @param {CollectionInfo} info\n *   Info on current collection.\n * @returns {Array<BreakNumber | string>}\n */\nfunction collectElement(node, parent, info) {\n  // First we infer the `white-space` property.\n  const whitespace = inferWhitespace(node, info)\n  const children = node.children || []\n  let index = -1\n  /** @type {Array<BreakNumber | string>} */\n  let items = []\n\n  // We’re ignoring point 3, and exiting without any content here, because we\n  // deviated from the spec in `toText` at step 3.\n  if (notRendered(node)) {\n    return items\n  }\n\n  /** @type {BreakNumber | undefined} */\n  let prefix\n  /** @type {BreakForce | BreakNumber | undefined} */\n  let suffix\n  // Note: we first detect if there is going to be a break before or after the\n  // contents, as that changes the white-space handling.\n\n  // 2.  If node’s computed value of `visibility` is not `visible`, then return\n  //     items.\n  //\n  //     Note: Ignored, as everything is visible by default user agent styles.\n\n  // 3.  If node is not being rendered, then return items. [...]\n  //\n  //     Note: We already did this above.\n\n  // See `collectText` for step 4.\n\n  // 5.  If node is a `<br>` element, then append a string containing a single\n  //     U+000A LINE FEED (LF) character to items.\n  if (br(node)) {\n    suffix = '\\n'\n  }\n\n  // 7.  If node’s computed value of `display` is `table-row`, and node’s CSS\n  //     box is not the last `table-row` box of the nearest ancestor `table`\n  //     box, then append a string containing a single U+000A LINE FEED (LF)\n  //     character to items.\n  //\n  //     See: <https://html.spec.whatwg.org/multipage/rendering.html#tables-2>\n  //     Note: needs further investigation as this does not account for implicit\n  //     rows.\n  else if (\n    row(node) &&\n    // @ts-expect-error: something up with types of parents.\n    findAfter(parent, node, row)\n  ) {\n    suffix = '\\n'\n  }\n\n  // 8.  If node is a `<p>` element, then append 2 (a required line break count)\n  //     at the beginning and end of items.\n  else if (p(node)) {\n    prefix = 2\n    suffix = 2\n  }\n\n  // 9.  If node’s used value of `display` is block-level or `table-caption`,\n  //     then append 1 (a required line break count) at the beginning and end of\n  //     items.\n  else if (blockOrCaption(node)) {\n    prefix = 1\n    suffix = 1\n  }\n\n  // 1.  Let items be the result of running the inner text collection steps with\n  //     each child node of node in tree order, and then concatenating the\n  //     results to a single list.\n  while (++index < children.length) {\n    items = items.concat(\n      renderedTextCollection(children[index], node, {\n        whitespace,\n        breakBefore: index ? undefined : prefix,\n        breakAfter:\n          index < children.length - 1 ? br(children[index + 1]) : suffix\n      })\n    )\n  }\n\n  // 6.  If node’s computed value of `display` is `table-cell`, and node’s CSS\n  //     box is not the last `table-cell` box of its enclosing `table-row` box,\n  //     then append a string containing a single U+0009 CHARACTER TABULATION\n  //     (tab) character to items.\n  //\n  //     See: <https://html.spec.whatwg.org/multipage/rendering.html#tables-2>\n  if (\n    cell(node) &&\n    // @ts-expect-error: something up with types of parents.\n    findAfter(parent, node, cell)\n  ) {\n    items.push('\\t')\n  }\n\n  // Add the pre- and suffix.\n  if (prefix) items.unshift(prefix)\n  if (suffix) items.push(suffix)\n\n  return items\n}\n\n/**\n * 4.  If node is a Text node, then for each CSS text box produced by node,\n *     in content order, compute the text of the box after application of the\n *     CSS `white-space` processing rules and `text-transform` rules, set\n *     items to the list of the resulting strings, and return items.\n *     The CSS `white-space` processing rules are slightly modified:\n *     collapsible spaces at the end of lines are always collapsed, but they\n *     are only removed if the line is the last line of the block, or it ends\n *     with a br element.\n *     Soft hyphens should be preserved.\n *\n *     Note: See `collectText` and `collectPreText`.\n *     Note: we don’t deal with `text-transform`, no element has that by\n *     default.\n *\n * See: <https://drafts.csswg.org/css-text/#white-space-phase-1>\n *\n * @param {Comment | Text} node\n *   Text node.\n * @param {CollectionInfo} info\n *   Info on current collection.\n * @returns {Array<BreakNumber | string>}\n *   Result.\n */\nfunction collectText(node, info) {\n  const value = String(node.value)\n  /** @type {Array<string>} */\n  const lines = []\n  /** @type {Array<BreakNumber | string>} */\n  const result = []\n  let start = 0\n\n  while (start <= value.length) {\n    searchLineFeeds.lastIndex = start\n\n    const match = searchLineFeeds.exec(value)\n    const end = match && 'index' in match ? match.index : value.length\n\n    lines.push(\n      // Any sequence of collapsible spaces and tabs immediately preceding or\n      // following a segment break is removed.\n      trimAndCollapseSpacesAndTabs(\n        // […] ignoring bidi formatting characters (characters with the\n        // Bidi_Control property [UAX9]: ALM, LTR, RTL, LRE-RLO, LRI-PDI) as if\n        // they were not there.\n        value\n          .slice(start, end)\n          .replace(/[\\u061C\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u2069]/g, ''),\n        start === 0 ? info.breakBefore : true,\n        end === value.length ? info.breakAfter : true\n      )\n    )\n\n    start = end + 1\n  }\n\n  // Collapsible segment breaks are transformed for rendering according to the\n  // segment break transformation rules.\n  // So here we jump to 4.1.2 of [CSSTEXT]:\n  // Any collapsible segment break immediately following another collapsible\n  // segment break is removed\n  let index = -1\n  /** @type {BreakNumber | undefined} */\n  let join\n\n  while (++index < lines.length) {\n    // *   If the character immediately before or immediately after the segment\n    //     break is the zero-width space character (U+200B), then the break is\n    //     removed, leaving behind the zero-width space.\n    if (\n      lines[index].charCodeAt(lines[index].length - 1) === 0x20_0b /* ZWSP */ ||\n      (index < lines.length - 1 &&\n        lines[index + 1].charCodeAt(0) === 0x20_0b) /* ZWSP */\n    ) {\n      result.push(lines[index])\n      join = undefined\n    }\n\n    // *   Otherwise, if the East Asian Width property [UAX11] of both the\n    //     character before and after the segment break is Fullwidth, Wide, or\n    //     Halfwidth (not Ambiguous), and neither side is Hangul, then the\n    //     segment break is removed.\n    //\n    //     Note: ignored.\n    // *   Otherwise, if the writing system of the segment break is Chinese,\n    //     Japanese, or Yi, and the character before or after the segment break\n    //     is punctuation or a symbol (Unicode general category P* or S*) and\n    //     has an East Asian Width property of Ambiguous, and the character on\n    //     the other side of the segment break is Fullwidth, Wide, or Halfwidth,\n    //     and not Hangul, then the segment break is removed.\n    //\n    //     Note: ignored.\n\n    // *   Otherwise, the segment break is converted to a space (U+0020).\n    else if (lines[index]) {\n      if (typeof join === 'number') result.push(join)\n      result.push(lines[index])\n      join = 0\n    } else if (index === 0 || index === lines.length - 1) {\n      // If this line is empty, and it’s the first or last, add a space.\n      // Note that this function is only called in normal whitespace, so we\n      // don’t worry about `pre`.\n      result.push(0)\n    }\n  }\n\n  return result\n}\n\n/**\n * Collect a text node as “pre” whitespace.\n *\n * @param {Text} node\n *   Text node.\n * @returns {Array<BreakNumber | string>}\n *   Result.\n */\nfunction collectPreText(node) {\n  return [String(node.value)]\n}\n\n/**\n * 3.  Every collapsible tab is converted to a collapsible space (U+0020).\n * 4.  Any collapsible space immediately following another collapsible\n *     space—even one outside the boundary of the inline containing that\n *     space, provided both spaces are within the same inline formatting\n *     context—is collapsed to have zero advance width. (It is invisible,\n *     but retains its soft wrap opportunity, if any.)\n *\n * @param {string} value\n *   Value to collapse.\n * @param {BreakBefore} breakBefore\n *   Whether there was a break before.\n * @param {BreakAfter} breakAfter\n *   Whether there was a break after.\n * @returns {string}\n *   Result.\n */\nfunction trimAndCollapseSpacesAndTabs(value, breakBefore, breakAfter) {\n  /** @type {Array<string>} */\n  const result = []\n  let start = 0\n  /** @type {number | undefined} */\n  let end\n\n  while (start < value.length) {\n    searchTabOrSpaces.lastIndex = start\n    const match = searchTabOrSpaces.exec(value)\n    end = match ? match.index : value.length\n\n    // If we’re not directly after a segment break, but there was white space,\n    // add an empty value that will be turned into a space.\n    if (!start && !end && match && !breakBefore) {\n      result.push('')\n    }\n\n    if (start !== end) {\n      result.push(value.slice(start, end))\n    }\n\n    start = match ? end + match[0].length : end\n  }\n\n  // If we reached the end, there was trailing white space, and there’s no\n  // segment break after this node, add an empty value that will be turned\n  // into a space.\n  if (start !== end && !breakAfter) {\n    result.push('')\n  }\n\n  return result.join(' ')\n}\n\n/**\n * Figure out the whitespace of a node.\n *\n * We don’t support void elements here (so `nobr wbr` -> `normal` is ignored).\n *\n * @param {Nodes} node\n *   Node (typically `Element`).\n * @param {CollectionInfo} info\n *   Info on current collection.\n * @returns {Whitespace}\n *   Applied whitespace.\n */\nfunction inferWhitespace(node, info) {\n  if (node.type === 'element') {\n    const properties = node.properties || {}\n    switch (node.tagName) {\n      case 'listing':\n      case 'plaintext':\n      case 'xmp': {\n        return 'pre'\n      }\n\n      case 'nobr': {\n        return 'nowrap'\n      }\n\n      case 'pre': {\n        return properties.wrap ? 'pre-wrap' : 'pre'\n      }\n\n      case 'td':\n      case 'th': {\n        return properties.noWrap ? 'nowrap' : info.whitespace\n      }\n\n      case 'textarea': {\n        return 'pre-wrap'\n      }\n\n      default:\n    }\n  }\n\n  return info.whitespace\n}\n\n/**\n * @type {TestFunction}\n * @param {Element} node\n * @returns {node is {properties: {hidden: true}}}\n */\nfunction hidden(node) {\n  return Boolean((node.properties || {}).hidden)\n}\n\n/**\n * @type {TestFunction}\n * @param {Element} node\n * @returns {node is {tagName: 'td' | 'th'}}\n */\nfunction isCell(node) {\n  return node.tagName === 'td' || node.tagName === 'th'\n}\n\n/**\n * @type {TestFunction}\n */\nfunction closedDialog(node) {\n  return node.tagName === 'dialog' && !(node.properties || {}).open\n}\n","/**\n * @import {ElementContent, Root} from 'hast'\n * @import {KatexOptions} from 'katex'\n * @import {VFile} from 'vfile'\n */\n\n/**\n * @typedef {Omit<KatexOptions, 'displayMode' | 'throwOnError'>} Options\n */\n\nimport {fromHtmlIsomorphic} from 'hast-util-from-html-isomorphic'\nimport {toText} from 'hast-util-to-text'\nimport katex from 'katex'\nimport {SKIP, visitParents} from 'unist-util-visit-parents'\n\n/** @type {Readonly<Options>} */\nconst emptyOptions = {}\n/** @type {ReadonlyArray<unknown>} */\nconst emptyClasses = []\n\n/**\n * Render elements with a `language-math` (or `math-display`, `math-inline`)\n * class with KaTeX.\n *\n * @param {Readonly<Options> | null | undefined} [options]\n *   Configuration (optional).\n * @returns\n *   Transform.\n */\nexport default function rehypeKatex(options) {\n  const settings = options || emptyOptions\n\n  /**\n   * Transform.\n   *\n   * @param {Root} tree\n   *   Tree.\n   * @param {VFile} file\n   *   File.\n   * @returns {undefined}\n   *   Nothing.\n   */\n  return function (tree, file) {\n    visitParents(tree, 'element', function (element, parents) {\n      const classes = Array.isArray(element.properties.className)\n        ? element.properties.className\n        : emptyClasses\n      // This class can be generated from markdown with ` ```math `.\n      const languageMath = classes.includes('language-math')\n      // This class is used by `remark-math` for flow math (block, `$$\\nmath\\n$$`).\n      const mathDisplay = classes.includes('math-display')\n      // This class is used by `remark-math` for text math (inline, `$math$`).\n      const mathInline = classes.includes('math-inline')\n      let displayMode = mathDisplay\n\n      // Any class is fine.\n      if (!languageMath && !mathDisplay && !mathInline) {\n        return\n      }\n\n      let parent = parents[parents.length - 1]\n      let scope = element\n\n      // If this was generated with ` ```math `, replace the `<pre>` and use\n      // display.\n      if (\n        element.tagName === 'code' &&\n        languageMath &&\n        parent &&\n        parent.type === 'element' &&\n        parent.tagName === 'pre'\n      ) {\n        scope = parent\n        parent = parents[parents.length - 2]\n        displayMode = true\n      }\n\n      /* c8 ignore next -- verbose to test. */\n      if (!parent) return\n\n      const value = toText(scope, {whitespace: 'pre'})\n\n      /** @type {Array<ElementContent> | string | undefined} */\n      let result\n\n      try {\n        result = katex.renderToString(value, {\n          ...settings,\n          displayMode,\n          throwOnError: true\n        })\n      } catch (error) {\n        const cause = /** @type {Error} */ (error)\n        const ruleId = cause.name.toLowerCase()\n\n        file.message('Could not render math with KaTeX', {\n          ancestors: [...parents, element],\n          cause,\n          place: element.position,\n          ruleId,\n          source: 'rehype-katex'\n        })\n\n        // KaTeX *should* handle `ParseError` itself, but not others.\n        // it doesn’t always:\n        // <https://github.com/remarkjs/react-markdown/issues/853>\n        try {\n          result = katex.renderToString(value, {\n            ...settings,\n            displayMode,\n            strict: 'ignore',\n            throwOnError: false\n          })\n        } catch {\n          // Generate similar markup if this is an other error.\n          // See: <https://github.com/KaTeX/KaTeX/blob/5dc7af0/docs/error.md>.\n          result = [\n            {\n              type: 'element',\n              tagName: 'span',\n              properties: {\n                className: ['katex-error'],\n                style: 'color:' + (settings.errorColor || '#cc0000'),\n                title: String(error)\n              },\n              children: [{type: 'text', value}]\n            }\n          ]\n        }\n      }\n\n      if (typeof result === 'string') {\n        const root = fromHtmlIsomorphic(result, {fragment: true})\n        // Cast as we don’t expect `doctypes` in KaTeX result.\n        result = /** @type {Array<ElementContent>} */ (root.children)\n      }\n\n      const index = parent.children.indexOf(scope)\n      parent.children.splice(index, 1, ...result)\n      return SKIP\n    })\n  }\n}\n","class ShikiError extends Error {\n  constructor(message) {\n    super(message);\n    this.name = \"ShikiError\";\n  }\n}\n\nexport { ShikiError };\n","// src/utils.ts\nfunction clone(something) {\n  return doClone(something);\n}\nfunction doClone(something) {\n  if (Array.isArray(something)) {\n    return cloneArray(something);\n  }\n  if (something instanceof RegExp) {\n    return something;\n  }\n  if (typeof something === \"object\") {\n    return cloneObj(something);\n  }\n  return something;\n}\nfunction cloneArray(arr) {\n  let r = [];\n  for (let i = 0, len = arr.length; i < len; i++) {\n    r[i] = doClone(arr[i]);\n  }\n  return r;\n}\nfunction cloneObj(obj) {\n  let r = {};\n  for (let key in obj) {\n    r[key] = doClone(obj[key]);\n  }\n  return r;\n}\nfunction mergeObjects(target, ...sources) {\n  sources.forEach((source) => {\n    for (let key in source) {\n      target[key] = source[key];\n    }\n  });\n  return target;\n}\nfunction basename(path) {\n  const idx = ~path.lastIndexOf(\"/\") || ~path.lastIndexOf(\"\\\\\");\n  if (idx === 0) {\n    return path;\n  } else if (~idx === path.length - 1) {\n    return basename(path.substring(0, path.length - 1));\n  } else {\n    return path.substr(~idx + 1);\n  }\n}\nvar CAPTURING_REGEX_SOURCE = /\\$(\\d+)|\\${(\\d+):\\/(downcase|upcase)}/g;\nvar RegexSource = class {\n  static hasCaptures(regexSource) {\n    if (regexSource === null) {\n      return false;\n    }\n    CAPTURING_REGEX_SOURCE.lastIndex = 0;\n    return CAPTURING_REGEX_SOURCE.test(regexSource);\n  }\n  static replaceCaptures(regexSource, captureSource, captureIndices) {\n    return regexSource.replace(CAPTURING_REGEX_SOURCE, (match, index, commandIndex, command) => {\n      let capture = captureIndices[parseInt(index || commandIndex, 10)];\n      if (capture) {\n        let result = captureSource.substring(capture.start, capture.end);\n        while (result[0] === \".\") {\n          result = result.substring(1);\n        }\n        switch (command) {\n          case \"downcase\":\n            return result.toLowerCase();\n          case \"upcase\":\n            return result.toUpperCase();\n          default:\n            return result;\n        }\n      } else {\n        return match;\n      }\n    });\n  }\n};\nfunction strcmp(a, b) {\n  if (a < b) {\n    return -1;\n  }\n  if (a > b) {\n    return 1;\n  }\n  return 0;\n}\nfunction strArrCmp(a, b) {\n  if (a === null && b === null) {\n    return 0;\n  }\n  if (!a) {\n    return -1;\n  }\n  if (!b) {\n    return 1;\n  }\n  let len1 = a.length;\n  let len2 = b.length;\n  if (len1 === len2) {\n    for (let i = 0; i < len1; i++) {\n      let res = strcmp(a[i], b[i]);\n      if (res !== 0) {\n        return res;\n      }\n    }\n    return 0;\n  }\n  return len1 - len2;\n}\nfunction isValidHexColor(hex) {\n  if (/^#[0-9a-f]{6}$/i.test(hex)) {\n    return true;\n  }\n  if (/^#[0-9a-f]{8}$/i.test(hex)) {\n    return true;\n  }\n  if (/^#[0-9a-f]{3}$/i.test(hex)) {\n    return true;\n  }\n  if (/^#[0-9a-f]{4}$/i.test(hex)) {\n    return true;\n  }\n  return false;\n}\nfunction escapeRegExpCharacters(value) {\n  return value.replace(/[\\-\\\\\\{\\}\\*\\+\\?\\|\\^\\$\\.\\,\\[\\]\\(\\)\\#\\s]/g, \"\\\\$&\");\n}\nvar CachedFn = class {\n  constructor(fn) {\n    this.fn = fn;\n  }\n  cache = /* @__PURE__ */ new Map();\n  get(key) {\n    if (this.cache.has(key)) {\n      return this.cache.get(key);\n    }\n    const value = this.fn(key);\n    this.cache.set(key, value);\n    return value;\n  }\n};\n\n// src/theme.ts\nvar Theme = class {\n  constructor(_colorMap, _defaults, _root) {\n    this._colorMap = _colorMap;\n    this._defaults = _defaults;\n    this._root = _root;\n  }\n  static createFromRawTheme(source, colorMap) {\n    return this.createFromParsedTheme(parseTheme(source), colorMap);\n  }\n  static createFromParsedTheme(source, colorMap) {\n    return resolveParsedThemeRules(source, colorMap);\n  }\n  _cachedMatchRoot = new CachedFn(\n    (scopeName) => this._root.match(scopeName)\n  );\n  getColorMap() {\n    return this._colorMap.getColorMap();\n  }\n  getDefaults() {\n    return this._defaults;\n  }\n  match(scopePath) {\n    if (scopePath === null) {\n      return this._defaults;\n    }\n    const scopeName = scopePath.scopeName;\n    const matchingTrieElements = this._cachedMatchRoot.get(scopeName);\n    const effectiveRule = matchingTrieElements.find(\n      (v) => _scopePathMatchesParentScopes(scopePath.parent, v.parentScopes)\n    );\n    if (!effectiveRule) {\n      return null;\n    }\n    return new StyleAttributes(\n      effectiveRule.fontStyle,\n      effectiveRule.foreground,\n      effectiveRule.background\n    );\n  }\n};\nvar ScopeStack = class _ScopeStack {\n  constructor(parent, scopeName) {\n    this.parent = parent;\n    this.scopeName = scopeName;\n  }\n  static push(path, scopeNames) {\n    for (const name of scopeNames) {\n      path = new _ScopeStack(path, name);\n    }\n    return path;\n  }\n  static from(...segments) {\n    let result = null;\n    for (let i = 0; i < segments.length; i++) {\n      result = new _ScopeStack(result, segments[i]);\n    }\n    return result;\n  }\n  push(scopeName) {\n    return new _ScopeStack(this, scopeName);\n  }\n  getSegments() {\n    let item = this;\n    const result = [];\n    while (item) {\n      result.push(item.scopeName);\n      item = item.parent;\n    }\n    result.reverse();\n    return result;\n  }\n  toString() {\n    return this.getSegments().join(\" \");\n  }\n  extends(other) {\n    if (this === other) {\n      return true;\n    }\n    if (this.parent === null) {\n      return false;\n    }\n    return this.parent.extends(other);\n  }\n  getExtensionIfDefined(base) {\n    const result = [];\n    let item = this;\n    while (item && item !== base) {\n      result.push(item.scopeName);\n      item = item.parent;\n    }\n    return item === base ? result.reverse() : void 0;\n  }\n};\nfunction _scopePathMatchesParentScopes(scopePath, parentScopes) {\n  if (parentScopes.length === 0) {\n    return true;\n  }\n  for (let index = 0; index < parentScopes.length; index++) {\n    let scopePattern = parentScopes[index];\n    let scopeMustMatch = false;\n    if (scopePattern === \">\") {\n      if (index === parentScopes.length - 1) {\n        return false;\n      }\n      scopePattern = parentScopes[++index];\n      scopeMustMatch = true;\n    }\n    while (scopePath) {\n      if (_matchesScope(scopePath.scopeName, scopePattern)) {\n        break;\n      }\n      if (scopeMustMatch) {\n        return false;\n      }\n      scopePath = scopePath.parent;\n    }\n    if (!scopePath) {\n      return false;\n    }\n    scopePath = scopePath.parent;\n  }\n  return true;\n}\nfunction _matchesScope(scopeName, scopePattern) {\n  return scopePattern === scopeName || scopeName.startsWith(scopePattern) && scopeName[scopePattern.length] === \".\";\n}\nvar StyleAttributes = class {\n  constructor(fontStyle, foregroundId, backgroundId) {\n    this.fontStyle = fontStyle;\n    this.foregroundId = foregroundId;\n    this.backgroundId = backgroundId;\n  }\n};\nfunction parseTheme(source) {\n  if (!source) {\n    return [];\n  }\n  if (!source.settings || !Array.isArray(source.settings)) {\n    return [];\n  }\n  let settings = source.settings;\n  let result = [], resultLen = 0;\n  for (let i = 0, len = settings.length; i < len; i++) {\n    let entry = settings[i];\n    if (!entry.settings) {\n      continue;\n    }\n    let scopes;\n    if (typeof entry.scope === \"string\") {\n      let _scope = entry.scope;\n      _scope = _scope.replace(/^[,]+/, \"\");\n      _scope = _scope.replace(/[,]+$/, \"\");\n      scopes = _scope.split(\",\");\n    } else if (Array.isArray(entry.scope)) {\n      scopes = entry.scope;\n    } else {\n      scopes = [\"\"];\n    }\n    let fontStyle = -1 /* NotSet */;\n    if (typeof entry.settings.fontStyle === \"string\") {\n      fontStyle = 0 /* None */;\n      let segments = entry.settings.fontStyle.split(\" \");\n      for (let j = 0, lenJ = segments.length; j < lenJ; j++) {\n        let segment = segments[j];\n        switch (segment) {\n          case \"italic\":\n            fontStyle = fontStyle | 1 /* Italic */;\n            break;\n          case \"bold\":\n            fontStyle = fontStyle | 2 /* Bold */;\n            break;\n          case \"underline\":\n            fontStyle = fontStyle | 4 /* Underline */;\n            break;\n          case \"strikethrough\":\n            fontStyle = fontStyle | 8 /* Strikethrough */;\n            break;\n        }\n      }\n    }\n    let foreground = null;\n    if (typeof entry.settings.foreground === \"string\" && isValidHexColor(entry.settings.foreground)) {\n      foreground = entry.settings.foreground;\n    }\n    let background = null;\n    if (typeof entry.settings.background === \"string\" && isValidHexColor(entry.settings.background)) {\n      background = entry.settings.background;\n    }\n    for (let j = 0, lenJ = scopes.length; j < lenJ; j++) {\n      let _scope = scopes[j].trim();\n      let segments = _scope.split(\" \");\n      let scope = segments[segments.length - 1];\n      let parentScopes = null;\n      if (segments.length > 1) {\n        parentScopes = segments.slice(0, segments.length - 1);\n        parentScopes.reverse();\n      }\n      result[resultLen++] = new ParsedThemeRule(\n        scope,\n        parentScopes,\n        i,\n        fontStyle,\n        foreground,\n        background\n      );\n    }\n  }\n  return result;\n}\nvar ParsedThemeRule = class {\n  constructor(scope, parentScopes, index, fontStyle, foreground, background) {\n    this.scope = scope;\n    this.parentScopes = parentScopes;\n    this.index = index;\n    this.fontStyle = fontStyle;\n    this.foreground = foreground;\n    this.background = background;\n  }\n};\nvar FontStyle = /* @__PURE__ */ ((FontStyle2) => {\n  FontStyle2[FontStyle2[\"NotSet\"] = -1] = \"NotSet\";\n  FontStyle2[FontStyle2[\"None\"] = 0] = \"None\";\n  FontStyle2[FontStyle2[\"Italic\"] = 1] = \"Italic\";\n  FontStyle2[FontStyle2[\"Bold\"] = 2] = \"Bold\";\n  FontStyle2[FontStyle2[\"Underline\"] = 4] = \"Underline\";\n  FontStyle2[FontStyle2[\"Strikethrough\"] = 8] = \"Strikethrough\";\n  return FontStyle2;\n})(FontStyle || {});\nfunction resolveParsedThemeRules(parsedThemeRules, _colorMap) {\n  parsedThemeRules.sort((a, b) => {\n    let r = strcmp(a.scope, b.scope);\n    if (r !== 0) {\n      return r;\n    }\n    r = strArrCmp(a.parentScopes, b.parentScopes);\n    if (r !== 0) {\n      return r;\n    }\n    return a.index - b.index;\n  });\n  let defaultFontStyle = 0 /* None */;\n  let defaultForeground = \"#000000\";\n  let defaultBackground = \"#ffffff\";\n  while (parsedThemeRules.length >= 1 && parsedThemeRules[0].scope === \"\") {\n    let incomingDefaults = parsedThemeRules.shift();\n    if (incomingDefaults.fontStyle !== -1 /* NotSet */) {\n      defaultFontStyle = incomingDefaults.fontStyle;\n    }\n    if (incomingDefaults.foreground !== null) {\n      defaultForeground = incomingDefaults.foreground;\n    }\n    if (incomingDefaults.background !== null) {\n      defaultBackground = incomingDefaults.background;\n    }\n  }\n  let colorMap = new ColorMap(_colorMap);\n  let defaults = new StyleAttributes(defaultFontStyle, colorMap.getId(defaultForeground), colorMap.getId(defaultBackground));\n  let root = new ThemeTrieElement(new ThemeTrieElementRule(0, null, -1 /* NotSet */, 0, 0), []);\n  for (let i = 0, len = parsedThemeRules.length; i < len; i++) {\n    let rule = parsedThemeRules[i];\n    root.insert(0, rule.scope, rule.parentScopes, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background));\n  }\n  return new Theme(colorMap, defaults, root);\n}\nvar ColorMap = class {\n  _isFrozen;\n  _lastColorId;\n  _id2color;\n  _color2id;\n  constructor(_colorMap) {\n    this._lastColorId = 0;\n    this._id2color = [];\n    this._color2id = /* @__PURE__ */ Object.create(null);\n    if (Array.isArray(_colorMap)) {\n      this._isFrozen = true;\n      for (let i = 0, len = _colorMap.length; i < len; i++) {\n        this._color2id[_colorMap[i]] = i;\n        this._id2color[i] = _colorMap[i];\n      }\n    } else {\n      this._isFrozen = false;\n    }\n  }\n  getId(color) {\n    if (color === null) {\n      return 0;\n    }\n    color = color.toUpperCase();\n    let value = this._color2id[color];\n    if (value) {\n      return value;\n    }\n    if (this._isFrozen) {\n      throw new Error(`Missing color in color map - ${color}`);\n    }\n    value = ++this._lastColorId;\n    this._color2id[color] = value;\n    this._id2color[value] = color;\n    return value;\n  }\n  getColorMap() {\n    return this._id2color.slice(0);\n  }\n};\nvar emptyParentScopes = Object.freeze([]);\nvar ThemeTrieElementRule = class _ThemeTrieElementRule {\n  scopeDepth;\n  parentScopes;\n  fontStyle;\n  foreground;\n  background;\n  constructor(scopeDepth, parentScopes, fontStyle, foreground, background) {\n    this.scopeDepth = scopeDepth;\n    this.parentScopes = parentScopes || emptyParentScopes;\n    this.fontStyle = fontStyle;\n    this.foreground = foreground;\n    this.background = background;\n  }\n  clone() {\n    return new _ThemeTrieElementRule(this.scopeDepth, this.parentScopes, this.fontStyle, this.foreground, this.background);\n  }\n  static cloneArr(arr) {\n    let r = [];\n    for (let i = 0, len = arr.length; i < len; i++) {\n      r[i] = arr[i].clone();\n    }\n    return r;\n  }\n  acceptOverwrite(scopeDepth, fontStyle, foreground, background) {\n    if (this.scopeDepth > scopeDepth) {\n      console.log(\"how did this happen?\");\n    } else {\n      this.scopeDepth = scopeDepth;\n    }\n    if (fontStyle !== -1 /* NotSet */) {\n      this.fontStyle = fontStyle;\n    }\n    if (foreground !== 0) {\n      this.foreground = foreground;\n    }\n    if (background !== 0) {\n      this.background = background;\n    }\n  }\n};\nvar ThemeTrieElement = class _ThemeTrieElement {\n  constructor(_mainRule, rulesWithParentScopes = [], _children = {}) {\n    this._mainRule = _mainRule;\n    this._children = _children;\n    this._rulesWithParentScopes = rulesWithParentScopes;\n  }\n  _rulesWithParentScopes;\n  static _cmpBySpecificity(a, b) {\n    if (a.scopeDepth !== b.scopeDepth) {\n      return b.scopeDepth - a.scopeDepth;\n    }\n    let aParentIndex = 0;\n    let bParentIndex = 0;\n    while (true) {\n      if (a.parentScopes[aParentIndex] === \">\") {\n        aParentIndex++;\n      }\n      if (b.parentScopes[bParentIndex] === \">\") {\n        bParentIndex++;\n      }\n      if (aParentIndex >= a.parentScopes.length || bParentIndex >= b.parentScopes.length) {\n        break;\n      }\n      const parentScopeLengthDiff = b.parentScopes[bParentIndex].length - a.parentScopes[aParentIndex].length;\n      if (parentScopeLengthDiff !== 0) {\n        return parentScopeLengthDiff;\n      }\n      aParentIndex++;\n      bParentIndex++;\n    }\n    return b.parentScopes.length - a.parentScopes.length;\n  }\n  match(scope) {\n    if (scope !== \"\") {\n      let dotIndex = scope.indexOf(\".\");\n      let head;\n      let tail;\n      if (dotIndex === -1) {\n        head = scope;\n        tail = \"\";\n      } else {\n        head = scope.substring(0, dotIndex);\n        tail = scope.substring(dotIndex + 1);\n      }\n      if (this._children.hasOwnProperty(head)) {\n        return this._children[head].match(tail);\n      }\n    }\n    const rules = this._rulesWithParentScopes.concat(this._mainRule);\n    rules.sort(_ThemeTrieElement._cmpBySpecificity);\n    return rules;\n  }\n  insert(scopeDepth, scope, parentScopes, fontStyle, foreground, background) {\n    if (scope === \"\") {\n      this._doInsertHere(scopeDepth, parentScopes, fontStyle, foreground, background);\n      return;\n    }\n    let dotIndex = scope.indexOf(\".\");\n    let head;\n    let tail;\n    if (dotIndex === -1) {\n      head = scope;\n      tail = \"\";\n    } else {\n      head = scope.substring(0, dotIndex);\n      tail = scope.substring(dotIndex + 1);\n    }\n    let child;\n    if (this._children.hasOwnProperty(head)) {\n      child = this._children[head];\n    } else {\n      child = new _ThemeTrieElement(this._mainRule.clone(), ThemeTrieElementRule.cloneArr(this._rulesWithParentScopes));\n      this._children[head] = child;\n    }\n    child.insert(scopeDepth + 1, tail, parentScopes, fontStyle, foreground, background);\n  }\n  _doInsertHere(scopeDepth, parentScopes, fontStyle, foreground, background) {\n    if (parentScopes === null) {\n      this._mainRule.acceptOverwrite(scopeDepth, fontStyle, foreground, background);\n      return;\n    }\n    for (let i = 0, len = this._rulesWithParentScopes.length; i < len; i++) {\n      let rule = this._rulesWithParentScopes[i];\n      if (strArrCmp(rule.parentScopes, parentScopes) === 0) {\n        rule.acceptOverwrite(scopeDepth, fontStyle, foreground, background);\n        return;\n      }\n    }\n    if (fontStyle === -1 /* NotSet */) {\n      fontStyle = this._mainRule.fontStyle;\n    }\n    if (foreground === 0) {\n      foreground = this._mainRule.foreground;\n    }\n    if (background === 0) {\n      background = this._mainRule.background;\n    }\n    this._rulesWithParentScopes.push(new ThemeTrieElementRule(scopeDepth, parentScopes, fontStyle, foreground, background));\n  }\n};\n\n// src/encodedTokenAttributes.ts\nvar EncodedTokenMetadata = class _EncodedTokenMetadata {\n  static toBinaryStr(encodedTokenAttributes) {\n    return encodedTokenAttributes.toString(2).padStart(32, \"0\");\n  }\n  static print(encodedTokenAttributes) {\n    const languageId = _EncodedTokenMetadata.getLanguageId(encodedTokenAttributes);\n    const tokenType = _EncodedTokenMetadata.getTokenType(encodedTokenAttributes);\n    const fontStyle = _EncodedTokenMetadata.getFontStyle(encodedTokenAttributes);\n    const foreground = _EncodedTokenMetadata.getForeground(encodedTokenAttributes);\n    const background = _EncodedTokenMetadata.getBackground(encodedTokenAttributes);\n    console.log({\n      languageId,\n      tokenType,\n      fontStyle,\n      foreground,\n      background\n    });\n  }\n  static getLanguageId(encodedTokenAttributes) {\n    return (encodedTokenAttributes & 255 /* LANGUAGEID_MASK */) >>> 0 /* LANGUAGEID_OFFSET */;\n  }\n  static getTokenType(encodedTokenAttributes) {\n    return (encodedTokenAttributes & 768 /* TOKEN_TYPE_MASK */) >>> 8 /* TOKEN_TYPE_OFFSET */;\n  }\n  static containsBalancedBrackets(encodedTokenAttributes) {\n    return (encodedTokenAttributes & 1024 /* BALANCED_BRACKETS_MASK */) !== 0;\n  }\n  static getFontStyle(encodedTokenAttributes) {\n    return (encodedTokenAttributes & 30720 /* FONT_STYLE_MASK */) >>> 11 /* FONT_STYLE_OFFSET */;\n  }\n  static getForeground(encodedTokenAttributes) {\n    return (encodedTokenAttributes & 16744448 /* FOREGROUND_MASK */) >>> 15 /* FOREGROUND_OFFSET */;\n  }\n  static getBackground(encodedTokenAttributes) {\n    return (encodedTokenAttributes & 4278190080 /* BACKGROUND_MASK */) >>> 24 /* BACKGROUND_OFFSET */;\n  }\n  /**\n   * Updates the fields in `metadata`.\n   * A value of `0`, `NotSet` or `null` indicates that the corresponding field should be left as is.\n   */\n  static set(encodedTokenAttributes, languageId, tokenType, containsBalancedBrackets, fontStyle, foreground, background) {\n    let _languageId = _EncodedTokenMetadata.getLanguageId(encodedTokenAttributes);\n    let _tokenType = _EncodedTokenMetadata.getTokenType(encodedTokenAttributes);\n    let _containsBalancedBracketsBit = _EncodedTokenMetadata.containsBalancedBrackets(encodedTokenAttributes) ? 1 : 0;\n    let _fontStyle = _EncodedTokenMetadata.getFontStyle(encodedTokenAttributes);\n    let _foreground = _EncodedTokenMetadata.getForeground(encodedTokenAttributes);\n    let _background = _EncodedTokenMetadata.getBackground(encodedTokenAttributes);\n    if (languageId !== 0) {\n      _languageId = languageId;\n    }\n    if (tokenType !== 8 /* NotSet */) {\n      _tokenType = fromOptionalTokenType(tokenType);\n    }\n    if (containsBalancedBrackets !== null) {\n      _containsBalancedBracketsBit = containsBalancedBrackets ? 1 : 0;\n    }\n    if (fontStyle !== -1 /* NotSet */) {\n      _fontStyle = fontStyle;\n    }\n    if (foreground !== 0) {\n      _foreground = foreground;\n    }\n    if (background !== 0) {\n      _background = background;\n    }\n    return (_languageId << 0 /* LANGUAGEID_OFFSET */ | _tokenType << 8 /* TOKEN_TYPE_OFFSET */ | _containsBalancedBracketsBit << 10 /* BALANCED_BRACKETS_OFFSET */ | _fontStyle << 11 /* FONT_STYLE_OFFSET */ | _foreground << 15 /* FOREGROUND_OFFSET */ | _background << 24 /* BACKGROUND_OFFSET */) >>> 0;\n  }\n};\nfunction toOptionalTokenType(standardType) {\n  return standardType;\n}\nfunction fromOptionalTokenType(standardType) {\n  return standardType;\n}\n\n// src/matcher.ts\nfunction createMatchers(selector, matchesName) {\n  const results = [];\n  const tokenizer = newTokenizer(selector);\n  let token = tokenizer.next();\n  while (token !== null) {\n    let priority = 0;\n    if (token.length === 2 && token.charAt(1) === \":\") {\n      switch (token.charAt(0)) {\n        case \"R\":\n          priority = 1;\n          break;\n        case \"L\":\n          priority = -1;\n          break;\n        default:\n          console.log(`Unknown priority ${token} in scope selector`);\n      }\n      token = tokenizer.next();\n    }\n    let matcher = parseConjunction();\n    results.push({ matcher, priority });\n    if (token !== \",\") {\n      break;\n    }\n    token = tokenizer.next();\n  }\n  return results;\n  function parseOperand() {\n    if (token === \"-\") {\n      token = tokenizer.next();\n      const expressionToNegate = parseOperand();\n      return (matcherInput) => !!expressionToNegate && !expressionToNegate(matcherInput);\n    }\n    if (token === \"(\") {\n      token = tokenizer.next();\n      const expressionInParents = parseInnerExpression();\n      if (token === \")\") {\n        token = tokenizer.next();\n      }\n      return expressionInParents;\n    }\n    if (isIdentifier(token)) {\n      const identifiers = [];\n      do {\n        identifiers.push(token);\n        token = tokenizer.next();\n      } while (isIdentifier(token));\n      return (matcherInput) => matchesName(identifiers, matcherInput);\n    }\n    return null;\n  }\n  function parseConjunction() {\n    const matchers = [];\n    let matcher = parseOperand();\n    while (matcher) {\n      matchers.push(matcher);\n      matcher = parseOperand();\n    }\n    return (matcherInput) => matchers.every((matcher2) => matcher2(matcherInput));\n  }\n  function parseInnerExpression() {\n    const matchers = [];\n    let matcher = parseConjunction();\n    while (matcher) {\n      matchers.push(matcher);\n      if (token === \"|\" || token === \",\") {\n        do {\n          token = tokenizer.next();\n        } while (token === \"|\" || token === \",\");\n      } else {\n        break;\n      }\n      matcher = parseConjunction();\n    }\n    return (matcherInput) => matchers.some((matcher2) => matcher2(matcherInput));\n  }\n}\nfunction isIdentifier(token) {\n  return !!token && !!token.match(/[\\w\\.:]+/);\n}\nfunction newTokenizer(input) {\n  let regex = /([LR]:|[\\w\\.:][\\w\\.:\\-]*|[\\,\\|\\-\\(\\)])/g;\n  let match = regex.exec(input);\n  return {\n    next: () => {\n      if (!match) {\n        return null;\n      }\n      const res = match[0];\n      match = regex.exec(input);\n      return res;\n    }\n  };\n}\n\n// src/onigLib.ts\nvar FindOption = /* @__PURE__ */ ((FindOption2) => {\n  FindOption2[FindOption2[\"None\"] = 0] = \"None\";\n  FindOption2[FindOption2[\"NotBeginString\"] = 1] = \"NotBeginString\";\n  FindOption2[FindOption2[\"NotEndString\"] = 2] = \"NotEndString\";\n  FindOption2[FindOption2[\"NotBeginPosition\"] = 4] = \"NotBeginPosition\";\n  FindOption2[FindOption2[\"DebugCall\"] = 8] = \"DebugCall\";\n  return FindOption2;\n})(FindOption || {});\nfunction disposeOnigString(str) {\n  if (typeof str.dispose === \"function\") {\n    str.dispose();\n  }\n}\n\n// src/grammar/grammarDependencies.ts\nvar TopLevelRuleReference = class {\n  constructor(scopeName) {\n    this.scopeName = scopeName;\n  }\n  toKey() {\n    return this.scopeName;\n  }\n};\nvar TopLevelRepositoryRuleReference = class {\n  constructor(scopeName, ruleName) {\n    this.scopeName = scopeName;\n    this.ruleName = ruleName;\n  }\n  toKey() {\n    return `${this.scopeName}#${this.ruleName}`;\n  }\n};\nvar ExternalReferenceCollector = class {\n  _references = [];\n  _seenReferenceKeys = /* @__PURE__ */ new Set();\n  get references() {\n    return this._references;\n  }\n  visitedRule = /* @__PURE__ */ new Set();\n  add(reference) {\n    const key = reference.toKey();\n    if (this._seenReferenceKeys.has(key)) {\n      return;\n    }\n    this._seenReferenceKeys.add(key);\n    this._references.push(reference);\n  }\n};\nvar ScopeDependencyProcessor = class {\n  constructor(repo, initialScopeName) {\n    this.repo = repo;\n    this.initialScopeName = initialScopeName;\n    this.seenFullScopeRequests.add(this.initialScopeName);\n    this.Q = [new TopLevelRuleReference(this.initialScopeName)];\n  }\n  seenFullScopeRequests = /* @__PURE__ */ new Set();\n  seenPartialScopeRequests = /* @__PURE__ */ new Set();\n  Q;\n  processQueue() {\n    const q = this.Q;\n    this.Q = [];\n    const deps = new ExternalReferenceCollector();\n    for (const dep of q) {\n      collectReferencesOfReference(dep, this.initialScopeName, this.repo, deps);\n    }\n    for (const dep of deps.references) {\n      if (dep instanceof TopLevelRuleReference) {\n        if (this.seenFullScopeRequests.has(dep.scopeName)) {\n          continue;\n        }\n        this.seenFullScopeRequests.add(dep.scopeName);\n        this.Q.push(dep);\n      } else {\n        if (this.seenFullScopeRequests.has(dep.scopeName)) {\n          continue;\n        }\n        if (this.seenPartialScopeRequests.has(dep.toKey())) {\n          continue;\n        }\n        this.seenPartialScopeRequests.add(dep.toKey());\n        this.Q.push(dep);\n      }\n    }\n  }\n};\nfunction collectReferencesOfReference(reference, baseGrammarScopeName, repo, result) {\n  const selfGrammar = repo.lookup(reference.scopeName);\n  if (!selfGrammar) {\n    if (reference.scopeName === baseGrammarScopeName) {\n      throw new Error(`No grammar provided for <${baseGrammarScopeName}>`);\n    }\n    return;\n  }\n  const baseGrammar = repo.lookup(baseGrammarScopeName);\n  if (reference instanceof TopLevelRuleReference) {\n    collectExternalReferencesInTopLevelRule({ baseGrammar, selfGrammar }, result);\n  } else {\n    collectExternalReferencesInTopLevelRepositoryRule(\n      reference.ruleName,\n      { baseGrammar, selfGrammar, repository: selfGrammar.repository },\n      result\n    );\n  }\n  const injections = repo.injections(reference.scopeName);\n  if (injections) {\n    for (const injection of injections) {\n      result.add(new TopLevelRuleReference(injection));\n    }\n  }\n}\nfunction collectExternalReferencesInTopLevelRepositoryRule(ruleName, context, result) {\n  if (context.repository && context.repository[ruleName]) {\n    const rule = context.repository[ruleName];\n    collectExternalReferencesInRules([rule], context, result);\n  }\n}\nfunction collectExternalReferencesInTopLevelRule(context, result) {\n  if (context.selfGrammar.patterns && Array.isArray(context.selfGrammar.patterns)) {\n    collectExternalReferencesInRules(\n      context.selfGrammar.patterns,\n      { ...context, repository: context.selfGrammar.repository },\n      result\n    );\n  }\n  if (context.selfGrammar.injections) {\n    collectExternalReferencesInRules(\n      Object.values(context.selfGrammar.injections),\n      { ...context, repository: context.selfGrammar.repository },\n      result\n    );\n  }\n}\nfunction collectExternalReferencesInRules(rules, context, result) {\n  for (const rule of rules) {\n    if (result.visitedRule.has(rule)) {\n      continue;\n    }\n    result.visitedRule.add(rule);\n    const patternRepository = rule.repository ? mergeObjects({}, context.repository, rule.repository) : context.repository;\n    if (Array.isArray(rule.patterns)) {\n      collectExternalReferencesInRules(rule.patterns, { ...context, repository: patternRepository }, result);\n    }\n    const include = rule.include;\n    if (!include) {\n      continue;\n    }\n    const reference = parseInclude(include);\n    switch (reference.kind) {\n      case 0 /* Base */:\n        collectExternalReferencesInTopLevelRule({ ...context, selfGrammar: context.baseGrammar }, result);\n        break;\n      case 1 /* Self */:\n        collectExternalReferencesInTopLevelRule(context, result);\n        break;\n      case 2 /* RelativeReference */:\n        collectExternalReferencesInTopLevelRepositoryRule(reference.ruleName, { ...context, repository: patternRepository }, result);\n        break;\n      case 3 /* TopLevelReference */:\n      case 4 /* TopLevelRepositoryReference */:\n        const selfGrammar = reference.scopeName === context.selfGrammar.scopeName ? context.selfGrammar : reference.scopeName === context.baseGrammar.scopeName ? context.baseGrammar : void 0;\n        if (selfGrammar) {\n          const newContext = { baseGrammar: context.baseGrammar, selfGrammar, repository: patternRepository };\n          if (reference.kind === 4 /* TopLevelRepositoryReference */) {\n            collectExternalReferencesInTopLevelRepositoryRule(reference.ruleName, newContext, result);\n          } else {\n            collectExternalReferencesInTopLevelRule(newContext, result);\n          }\n        } else {\n          if (reference.kind === 4 /* TopLevelRepositoryReference */) {\n            result.add(new TopLevelRepositoryRuleReference(reference.scopeName, reference.ruleName));\n          } else {\n            result.add(new TopLevelRuleReference(reference.scopeName));\n          }\n        }\n        break;\n    }\n  }\n}\nvar BaseReference = class {\n  kind = 0 /* Base */;\n};\nvar SelfReference = class {\n  kind = 1 /* Self */;\n};\nvar RelativeReference = class {\n  constructor(ruleName) {\n    this.ruleName = ruleName;\n  }\n  kind = 2 /* RelativeReference */;\n};\nvar TopLevelReference = class {\n  constructor(scopeName) {\n    this.scopeName = scopeName;\n  }\n  kind = 3 /* TopLevelReference */;\n};\nvar TopLevelRepositoryReference = class {\n  constructor(scopeName, ruleName) {\n    this.scopeName = scopeName;\n    this.ruleName = ruleName;\n  }\n  kind = 4 /* TopLevelRepositoryReference */;\n};\nfunction parseInclude(include) {\n  if (include === \"$base\") {\n    return new BaseReference();\n  } else if (include === \"$self\") {\n    return new SelfReference();\n  }\n  const indexOfSharp = include.indexOf(\"#\");\n  if (indexOfSharp === -1) {\n    return new TopLevelReference(include);\n  } else if (indexOfSharp === 0) {\n    return new RelativeReference(include.substring(1));\n  } else {\n    const scopeName = include.substring(0, indexOfSharp);\n    const ruleName = include.substring(indexOfSharp + 1);\n    return new TopLevelRepositoryReference(scopeName, ruleName);\n  }\n}\n\n// src/rule.ts\nvar HAS_BACK_REFERENCES = /\\\\(\\d+)/;\nvar BACK_REFERENCING_END = /\\\\(\\d+)/g;\nvar ruleIdSymbol = Symbol(\"RuleId\");\nvar endRuleId = -1;\nvar whileRuleId = -2;\nfunction ruleIdFromNumber(id) {\n  return id;\n}\nfunction ruleIdToNumber(id) {\n  return id;\n}\nvar Rule = class {\n  $location;\n  id;\n  _nameIsCapturing;\n  _name;\n  _contentNameIsCapturing;\n  _contentName;\n  constructor($location, id, name, contentName) {\n    this.$location = $location;\n    this.id = id;\n    this._name = name || null;\n    this._nameIsCapturing = RegexSource.hasCaptures(this._name);\n    this._contentName = contentName || null;\n    this._contentNameIsCapturing = RegexSource.hasCaptures(this._contentName);\n  }\n  get debugName() {\n    const location = this.$location ? `${basename(this.$location.filename)}:${this.$location.line}` : \"unknown\";\n    return `${this.constructor.name}#${this.id} @ ${location}`;\n  }\n  getName(lineText, captureIndices) {\n    if (!this._nameIsCapturing || this._name === null || lineText === null || captureIndices === null) {\n      return this._name;\n    }\n    return RegexSource.replaceCaptures(this._name, lineText, captureIndices);\n  }\n  getContentName(lineText, captureIndices) {\n    if (!this._contentNameIsCapturing || this._contentName === null) {\n      return this._contentName;\n    }\n    return RegexSource.replaceCaptures(this._contentName, lineText, captureIndices);\n  }\n};\nvar CaptureRule = class extends Rule {\n  retokenizeCapturedWithRuleId;\n  constructor($location, id, name, contentName, retokenizeCapturedWithRuleId) {\n    super($location, id, name, contentName);\n    this.retokenizeCapturedWithRuleId = retokenizeCapturedWithRuleId;\n  }\n  dispose() {\n  }\n  collectPatterns(grammar, out) {\n    throw new Error(\"Not supported!\");\n  }\n  compile(grammar, endRegexSource) {\n    throw new Error(\"Not supported!\");\n  }\n  compileAG(grammar, endRegexSource, allowA, allowG) {\n    throw new Error(\"Not supported!\");\n  }\n};\nvar MatchRule = class extends Rule {\n  _match;\n  captures;\n  _cachedCompiledPatterns;\n  constructor($location, id, name, match, captures) {\n    super($location, id, name, null);\n    this._match = new RegExpSource(match, this.id);\n    this.captures = captures;\n    this._cachedCompiledPatterns = null;\n  }\n  dispose() {\n    if (this._cachedCompiledPatterns) {\n      this._cachedCompiledPatterns.dispose();\n      this._cachedCompiledPatterns = null;\n    }\n  }\n  get debugMatchRegExp() {\n    return `${this._match.source}`;\n  }\n  collectPatterns(grammar, out) {\n    out.push(this._match);\n  }\n  compile(grammar, endRegexSource) {\n    return this._getCachedCompiledPatterns(grammar).compile(grammar);\n  }\n  compileAG(grammar, endRegexSource, allowA, allowG) {\n    return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);\n  }\n  _getCachedCompiledPatterns(grammar) {\n    if (!this._cachedCompiledPatterns) {\n      this._cachedCompiledPatterns = new RegExpSourceList();\n      this.collectPatterns(grammar, this._cachedCompiledPatterns);\n    }\n    return this._cachedCompiledPatterns;\n  }\n};\nvar IncludeOnlyRule = class extends Rule {\n  hasMissingPatterns;\n  patterns;\n  _cachedCompiledPatterns;\n  constructor($location, id, name, contentName, patterns) {\n    super($location, id, name, contentName);\n    this.patterns = patterns.patterns;\n    this.hasMissingPatterns = patterns.hasMissingPatterns;\n    this._cachedCompiledPatterns = null;\n  }\n  dispose() {\n    if (this._cachedCompiledPatterns) {\n      this._cachedCompiledPatterns.dispose();\n      this._cachedCompiledPatterns = null;\n    }\n  }\n  collectPatterns(grammar, out) {\n    for (const pattern of this.patterns) {\n      const rule = grammar.getRule(pattern);\n      rule.collectPatterns(grammar, out);\n    }\n  }\n  compile(grammar, endRegexSource) {\n    return this._getCachedCompiledPatterns(grammar).compile(grammar);\n  }\n  compileAG(grammar, endRegexSource, allowA, allowG) {\n    return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);\n  }\n  _getCachedCompiledPatterns(grammar) {\n    if (!this._cachedCompiledPatterns) {\n      this._cachedCompiledPatterns = new RegExpSourceList();\n      this.collectPatterns(grammar, this._cachedCompiledPatterns);\n    }\n    return this._cachedCompiledPatterns;\n  }\n};\nvar BeginEndRule = class extends Rule {\n  _begin;\n  beginCaptures;\n  _end;\n  endHasBackReferences;\n  endCaptures;\n  applyEndPatternLast;\n  hasMissingPatterns;\n  patterns;\n  _cachedCompiledPatterns;\n  constructor($location, id, name, contentName, begin, beginCaptures, end, endCaptures, applyEndPatternLast, patterns) {\n    super($location, id, name, contentName);\n    this._begin = new RegExpSource(begin, this.id);\n    this.beginCaptures = beginCaptures;\n    this._end = new RegExpSource(end ? end : \"\\uFFFF\", -1);\n    this.endHasBackReferences = this._end.hasBackReferences;\n    this.endCaptures = endCaptures;\n    this.applyEndPatternLast = applyEndPatternLast || false;\n    this.patterns = patterns.patterns;\n    this.hasMissingPatterns = patterns.hasMissingPatterns;\n    this._cachedCompiledPatterns = null;\n  }\n  dispose() {\n    if (this._cachedCompiledPatterns) {\n      this._cachedCompiledPatterns.dispose();\n      this._cachedCompiledPatterns = null;\n    }\n  }\n  get debugBeginRegExp() {\n    return `${this._begin.source}`;\n  }\n  get debugEndRegExp() {\n    return `${this._end.source}`;\n  }\n  getEndWithResolvedBackReferences(lineText, captureIndices) {\n    return this._end.resolveBackReferences(lineText, captureIndices);\n  }\n  collectPatterns(grammar, out) {\n    out.push(this._begin);\n  }\n  compile(grammar, endRegexSource) {\n    return this._getCachedCompiledPatterns(grammar, endRegexSource).compile(grammar);\n  }\n  compileAG(grammar, endRegexSource, allowA, allowG) {\n    return this._getCachedCompiledPatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG);\n  }\n  _getCachedCompiledPatterns(grammar, endRegexSource) {\n    if (!this._cachedCompiledPatterns) {\n      this._cachedCompiledPatterns = new RegExpSourceList();\n      for (const pattern of this.patterns) {\n        const rule = grammar.getRule(pattern);\n        rule.collectPatterns(grammar, this._cachedCompiledPatterns);\n      }\n      if (this.applyEndPatternLast) {\n        this._cachedCompiledPatterns.push(this._end.hasBackReferences ? this._end.clone() : this._end);\n      } else {\n        this._cachedCompiledPatterns.unshift(this._end.hasBackReferences ? this._end.clone() : this._end);\n      }\n    }\n    if (this._end.hasBackReferences) {\n      if (this.applyEndPatternLast) {\n        this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length() - 1, endRegexSource);\n      } else {\n        this._cachedCompiledPatterns.setSource(0, endRegexSource);\n      }\n    }\n    return this._cachedCompiledPatterns;\n  }\n};\nvar BeginWhileRule = class extends Rule {\n  _begin;\n  beginCaptures;\n  whileCaptures;\n  _while;\n  whileHasBackReferences;\n  hasMissingPatterns;\n  patterns;\n  _cachedCompiledPatterns;\n  _cachedCompiledWhilePatterns;\n  constructor($location, id, name, contentName, begin, beginCaptures, _while, whileCaptures, patterns) {\n    super($location, id, name, contentName);\n    this._begin = new RegExpSource(begin, this.id);\n    this.beginCaptures = beginCaptures;\n    this.whileCaptures = whileCaptures;\n    this._while = new RegExpSource(_while, whileRuleId);\n    this.whileHasBackReferences = this._while.hasBackReferences;\n    this.patterns = patterns.patterns;\n    this.hasMissingPatterns = patterns.hasMissingPatterns;\n    this._cachedCompiledPatterns = null;\n    this._cachedCompiledWhilePatterns = null;\n  }\n  dispose() {\n    if (this._cachedCompiledPatterns) {\n      this._cachedCompiledPatterns.dispose();\n      this._cachedCompiledPatterns = null;\n    }\n    if (this._cachedCompiledWhilePatterns) {\n      this._cachedCompiledWhilePatterns.dispose();\n      this._cachedCompiledWhilePatterns = null;\n    }\n  }\n  get debugBeginRegExp() {\n    return `${this._begin.source}`;\n  }\n  get debugWhileRegExp() {\n    return `${this._while.source}`;\n  }\n  getWhileWithResolvedBackReferences(lineText, captureIndices) {\n    return this._while.resolveBackReferences(lineText, captureIndices);\n  }\n  collectPatterns(grammar, out) {\n    out.push(this._begin);\n  }\n  compile(grammar, endRegexSource) {\n    return this._getCachedCompiledPatterns(grammar).compile(grammar);\n  }\n  compileAG(grammar, endRegexSource, allowA, allowG) {\n    return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);\n  }\n  _getCachedCompiledPatterns(grammar) {\n    if (!this._cachedCompiledPatterns) {\n      this._cachedCompiledPatterns = new RegExpSourceList();\n      for (const pattern of this.patterns) {\n        const rule = grammar.getRule(pattern);\n        rule.collectPatterns(grammar, this._cachedCompiledPatterns);\n      }\n    }\n    return this._cachedCompiledPatterns;\n  }\n  compileWhile(grammar, endRegexSource) {\n    return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compile(grammar);\n  }\n  compileWhileAG(grammar, endRegexSource, allowA, allowG) {\n    return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG);\n  }\n  _getCachedCompiledWhilePatterns(grammar, endRegexSource) {\n    if (!this._cachedCompiledWhilePatterns) {\n      this._cachedCompiledWhilePatterns = new RegExpSourceList();\n      this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences ? this._while.clone() : this._while);\n    }\n    if (this._while.hasBackReferences) {\n      this._cachedCompiledWhilePatterns.setSource(0, endRegexSource ? endRegexSource : \"\\uFFFF\");\n    }\n    return this._cachedCompiledWhilePatterns;\n  }\n};\nvar RuleFactory = class _RuleFactory {\n  static createCaptureRule(helper, $location, name, contentName, retokenizeCapturedWithRuleId) {\n    return helper.registerRule((id) => {\n      return new CaptureRule($location, id, name, contentName, retokenizeCapturedWithRuleId);\n    });\n  }\n  static getCompiledRuleId(desc, helper, repository) {\n    if (!desc.id) {\n      helper.registerRule((id) => {\n        desc.id = id;\n        if (desc.match) {\n          return new MatchRule(\n            desc.$vscodeTextmateLocation,\n            desc.id,\n            desc.name,\n            desc.match,\n            _RuleFactory._compileCaptures(desc.captures, helper, repository)\n          );\n        }\n        if (typeof desc.begin === \"undefined\") {\n          if (desc.repository) {\n            repository = mergeObjects({}, repository, desc.repository);\n          }\n          let patterns = desc.patterns;\n          if (typeof patterns === \"undefined\" && desc.include) {\n            patterns = [{ include: desc.include }];\n          }\n          return new IncludeOnlyRule(\n            desc.$vscodeTextmateLocation,\n            desc.id,\n            desc.name,\n            desc.contentName,\n            _RuleFactory._compilePatterns(patterns, helper, repository)\n          );\n        }\n        if (desc.while) {\n          return new BeginWhileRule(\n            desc.$vscodeTextmateLocation,\n            desc.id,\n            desc.name,\n            desc.contentName,\n            desc.begin,\n            _RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository),\n            desc.while,\n            _RuleFactory._compileCaptures(desc.whileCaptures || desc.captures, helper, repository),\n            _RuleFactory._compilePatterns(desc.patterns, helper, repository)\n          );\n        }\n        return new BeginEndRule(\n          desc.$vscodeTextmateLocation,\n          desc.id,\n          desc.name,\n          desc.contentName,\n          desc.begin,\n          _RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository),\n          desc.end,\n          _RuleFactory._compileCaptures(desc.endCaptures || desc.captures, helper, repository),\n          desc.applyEndPatternLast,\n          _RuleFactory._compilePatterns(desc.patterns, helper, repository)\n        );\n      });\n    }\n    return desc.id;\n  }\n  static _compileCaptures(captures, helper, repository) {\n    let r = [];\n    if (captures) {\n      let maximumCaptureId = 0;\n      for (const captureId in captures) {\n        if (captureId === \"$vscodeTextmateLocation\") {\n          continue;\n        }\n        const numericCaptureId = parseInt(captureId, 10);\n        if (numericCaptureId > maximumCaptureId) {\n          maximumCaptureId = numericCaptureId;\n        }\n      }\n      for (let i = 0; i <= maximumCaptureId; i++) {\n        r[i] = null;\n      }\n      for (const captureId in captures) {\n        if (captureId === \"$vscodeTextmateLocation\") {\n          continue;\n        }\n        const numericCaptureId = parseInt(captureId, 10);\n        let retokenizeCapturedWithRuleId = 0;\n        if (captures[captureId].patterns) {\n          retokenizeCapturedWithRuleId = _RuleFactory.getCompiledRuleId(captures[captureId], helper, repository);\n        }\n        r[numericCaptureId] = _RuleFactory.createCaptureRule(helper, captures[captureId].$vscodeTextmateLocation, captures[captureId].name, captures[captureId].contentName, retokenizeCapturedWithRuleId);\n      }\n    }\n    return r;\n  }\n  static _compilePatterns(patterns, helper, repository) {\n    let r = [];\n    if (patterns) {\n      for (let i = 0, len = patterns.length; i < len; i++) {\n        const pattern = patterns[i];\n        let ruleId = -1;\n        if (pattern.include) {\n          const reference = parseInclude(pattern.include);\n          switch (reference.kind) {\n            case 0 /* Base */:\n            case 1 /* Self */:\n              ruleId = _RuleFactory.getCompiledRuleId(repository[pattern.include], helper, repository);\n              break;\n            case 2 /* RelativeReference */:\n              let localIncludedRule = repository[reference.ruleName];\n              if (localIncludedRule) {\n                ruleId = _RuleFactory.getCompiledRuleId(localIncludedRule, helper, repository);\n              } else {\n              }\n              break;\n            case 3 /* TopLevelReference */:\n            case 4 /* TopLevelRepositoryReference */:\n              const externalGrammarName = reference.scopeName;\n              const externalGrammarInclude = reference.kind === 4 /* TopLevelRepositoryReference */ ? reference.ruleName : null;\n              const externalGrammar = helper.getExternalGrammar(externalGrammarName, repository);\n              if (externalGrammar) {\n                if (externalGrammarInclude) {\n                  let externalIncludedRule = externalGrammar.repository[externalGrammarInclude];\n                  if (externalIncludedRule) {\n                    ruleId = _RuleFactory.getCompiledRuleId(externalIncludedRule, helper, externalGrammar.repository);\n                  } else {\n                  }\n                } else {\n                  ruleId = _RuleFactory.getCompiledRuleId(externalGrammar.repository.$self, helper, externalGrammar.repository);\n                }\n              } else {\n              }\n              break;\n          }\n        } else {\n          ruleId = _RuleFactory.getCompiledRuleId(pattern, helper, repository);\n        }\n        if (ruleId !== -1) {\n          const rule = helper.getRule(ruleId);\n          let skipRule = false;\n          if (rule instanceof IncludeOnlyRule || rule instanceof BeginEndRule || rule instanceof BeginWhileRule) {\n            if (rule.hasMissingPatterns && rule.patterns.length === 0) {\n              skipRule = true;\n            }\n          }\n          if (skipRule) {\n            continue;\n          }\n          r.push(ruleId);\n        }\n      }\n    }\n    return {\n      patterns: r,\n      hasMissingPatterns: (patterns ? patterns.length : 0) !== r.length\n    };\n  }\n};\nvar RegExpSource = class _RegExpSource {\n  source;\n  ruleId;\n  hasAnchor;\n  hasBackReferences;\n  _anchorCache;\n  constructor(regExpSource, ruleId) {\n    if (regExpSource && typeof regExpSource === \"string\") {\n      const len = regExpSource.length;\n      let lastPushedPos = 0;\n      let output = [];\n      let hasAnchor = false;\n      for (let pos = 0; pos < len; pos++) {\n        const ch = regExpSource.charAt(pos);\n        if (ch === \"\\\\\") {\n          if (pos + 1 < len) {\n            const nextCh = regExpSource.charAt(pos + 1);\n            if (nextCh === \"z\") {\n              output.push(regExpSource.substring(lastPushedPos, pos));\n              output.push(\"$(?!\\\\n)(?<!\\\\n)\");\n              lastPushedPos = pos + 2;\n            } else if (nextCh === \"A\" || nextCh === \"G\") {\n              hasAnchor = true;\n            }\n            pos++;\n          }\n        }\n      }\n      this.hasAnchor = hasAnchor;\n      if (lastPushedPos === 0) {\n        this.source = regExpSource;\n      } else {\n        output.push(regExpSource.substring(lastPushedPos, len));\n        this.source = output.join(\"\");\n      }\n    } else {\n      this.hasAnchor = false;\n      this.source = regExpSource;\n    }\n    if (this.hasAnchor) {\n      this._anchorCache = this._buildAnchorCache();\n    } else {\n      this._anchorCache = null;\n    }\n    this.ruleId = ruleId;\n    if (typeof this.source === \"string\") {\n      this.hasBackReferences = HAS_BACK_REFERENCES.test(this.source);\n    } else {\n      this.hasBackReferences = false;\n    }\n  }\n  clone() {\n    return new _RegExpSource(this.source, this.ruleId);\n  }\n  setSource(newSource) {\n    if (this.source === newSource) {\n      return;\n    }\n    this.source = newSource;\n    if (this.hasAnchor) {\n      this._anchorCache = this._buildAnchorCache();\n    }\n  }\n  resolveBackReferences(lineText, captureIndices) {\n    if (typeof this.source !== \"string\") {\n      throw new Error(\"This method should only be called if the source is a string\");\n    }\n    let capturedValues = captureIndices.map((capture) => {\n      return lineText.substring(capture.start, capture.end);\n    });\n    BACK_REFERENCING_END.lastIndex = 0;\n    return this.source.replace(BACK_REFERENCING_END, (match, g1) => {\n      return escapeRegExpCharacters(capturedValues[parseInt(g1, 10)] || \"\");\n    });\n  }\n  _buildAnchorCache() {\n    if (typeof this.source !== \"string\") {\n      throw new Error(\"This method should only be called if the source is a string\");\n    }\n    let A0_G0_result = [];\n    let A0_G1_result = [];\n    let A1_G0_result = [];\n    let A1_G1_result = [];\n    let pos, len, ch, nextCh;\n    for (pos = 0, len = this.source.length; pos < len; pos++) {\n      ch = this.source.charAt(pos);\n      A0_G0_result[pos] = ch;\n      A0_G1_result[pos] = ch;\n      A1_G0_result[pos] = ch;\n      A1_G1_result[pos] = ch;\n      if (ch === \"\\\\\") {\n        if (pos + 1 < len) {\n          nextCh = this.source.charAt(pos + 1);\n          if (nextCh === \"A\") {\n            A0_G0_result[pos + 1] = \"\\uFFFF\";\n            A0_G1_result[pos + 1] = \"\\uFFFF\";\n            A1_G0_result[pos + 1] = \"A\";\n            A1_G1_result[pos + 1] = \"A\";\n          } else if (nextCh === \"G\") {\n            A0_G0_result[pos + 1] = \"\\uFFFF\";\n            A0_G1_result[pos + 1] = \"G\";\n            A1_G0_result[pos + 1] = \"\\uFFFF\";\n            A1_G1_result[pos + 1] = \"G\";\n          } else {\n            A0_G0_result[pos + 1] = nextCh;\n            A0_G1_result[pos + 1] = nextCh;\n            A1_G0_result[pos + 1] = nextCh;\n            A1_G1_result[pos + 1] = nextCh;\n          }\n          pos++;\n        }\n      }\n    }\n    return {\n      A0_G0: A0_G0_result.join(\"\"),\n      A0_G1: A0_G1_result.join(\"\"),\n      A1_G0: A1_G0_result.join(\"\"),\n      A1_G1: A1_G1_result.join(\"\")\n    };\n  }\n  resolveAnchors(allowA, allowG) {\n    if (!this.hasAnchor || !this._anchorCache || typeof this.source !== \"string\") {\n      return this.source;\n    }\n    if (allowA) {\n      if (allowG) {\n        return this._anchorCache.A1_G1;\n      } else {\n        return this._anchorCache.A1_G0;\n      }\n    } else {\n      if (allowG) {\n        return this._anchorCache.A0_G1;\n      } else {\n        return this._anchorCache.A0_G0;\n      }\n    }\n  }\n};\nvar RegExpSourceList = class {\n  _items;\n  _hasAnchors;\n  _cached;\n  _anchorCache;\n  constructor() {\n    this._items = [];\n    this._hasAnchors = false;\n    this._cached = null;\n    this._anchorCache = {\n      A0_G0: null,\n      A0_G1: null,\n      A1_G0: null,\n      A1_G1: null\n    };\n  }\n  dispose() {\n    this._disposeCaches();\n  }\n  _disposeCaches() {\n    if (this._cached) {\n      this._cached.dispose();\n      this._cached = null;\n    }\n    if (this._anchorCache.A0_G0) {\n      this._anchorCache.A0_G0.dispose();\n      this._anchorCache.A0_G0 = null;\n    }\n    if (this._anchorCache.A0_G1) {\n      this._anchorCache.A0_G1.dispose();\n      this._anchorCache.A0_G1 = null;\n    }\n    if (this._anchorCache.A1_G0) {\n      this._anchorCache.A1_G0.dispose();\n      this._anchorCache.A1_G0 = null;\n    }\n    if (this._anchorCache.A1_G1) {\n      this._anchorCache.A1_G1.dispose();\n      this._anchorCache.A1_G1 = null;\n    }\n  }\n  push(item) {\n    this._items.push(item);\n    this._hasAnchors = this._hasAnchors || item.hasAnchor;\n  }\n  unshift(item) {\n    this._items.unshift(item);\n    this._hasAnchors = this._hasAnchors || item.hasAnchor;\n  }\n  length() {\n    return this._items.length;\n  }\n  setSource(index, newSource) {\n    if (this._items[index].source !== newSource) {\n      this._disposeCaches();\n      this._items[index].setSource(newSource);\n    }\n  }\n  compile(onigLib) {\n    if (!this._cached) {\n      let regExps = this._items.map((e) => e.source);\n      this._cached = new CompiledRule(onigLib, regExps, this._items.map((e) => e.ruleId));\n    }\n    return this._cached;\n  }\n  compileAG(onigLib, allowA, allowG) {\n    if (!this._hasAnchors) {\n      return this.compile(onigLib);\n    } else {\n      if (allowA) {\n        if (allowG) {\n          if (!this._anchorCache.A1_G1) {\n            this._anchorCache.A1_G1 = this._resolveAnchors(onigLib, allowA, allowG);\n          }\n          return this._anchorCache.A1_G1;\n        } else {\n          if (!this._anchorCache.A1_G0) {\n            this._anchorCache.A1_G0 = this._resolveAnchors(onigLib, allowA, allowG);\n          }\n          return this._anchorCache.A1_G0;\n        }\n      } else {\n        if (allowG) {\n          if (!this._anchorCache.A0_G1) {\n            this._anchorCache.A0_G1 = this._resolveAnchors(onigLib, allowA, allowG);\n          }\n          return this._anchorCache.A0_G1;\n        } else {\n          if (!this._anchorCache.A0_G0) {\n            this._anchorCache.A0_G0 = this._resolveAnchors(onigLib, allowA, allowG);\n          }\n          return this._anchorCache.A0_G0;\n        }\n      }\n    }\n  }\n  _resolveAnchors(onigLib, allowA, allowG) {\n    let regExps = this._items.map((e) => e.resolveAnchors(allowA, allowG));\n    return new CompiledRule(onigLib, regExps, this._items.map((e) => e.ruleId));\n  }\n};\nvar CompiledRule = class {\n  constructor(onigLib, regExps, rules) {\n    this.regExps = regExps;\n    this.rules = rules;\n    this.scanner = onigLib.createOnigScanner(regExps);\n  }\n  scanner;\n  dispose() {\n    if (typeof this.scanner.dispose === \"function\") {\n      this.scanner.dispose();\n    }\n  }\n  toString() {\n    const r = [];\n    for (let i = 0, len = this.rules.length; i < len; i++) {\n      r.push(\"   - \" + this.rules[i] + \": \" + this.regExps[i]);\n    }\n    return r.join(\"\\n\");\n  }\n  findNextMatchSync(string, startPosition, options) {\n    const result = this.scanner.findNextMatchSync(string, startPosition, options);\n    if (!result) {\n      return null;\n    }\n    return {\n      ruleId: this.rules[result.index],\n      captureIndices: result.captureIndices\n    };\n  }\n};\n\n// src/grammar/basicScopesAttributeProvider.ts\nvar BasicScopeAttributes = class {\n  constructor(languageId, tokenType) {\n    this.languageId = languageId;\n    this.tokenType = tokenType;\n  }\n};\nvar BasicScopeAttributesProvider = class _BasicScopeAttributesProvider {\n  _defaultAttributes;\n  _embeddedLanguagesMatcher;\n  constructor(initialLanguageId, embeddedLanguages) {\n    this._defaultAttributes = new BasicScopeAttributes(initialLanguageId, 8 /* NotSet */);\n    this._embeddedLanguagesMatcher = new ScopeMatcher(Object.entries(embeddedLanguages || {}));\n  }\n  getDefaultAttributes() {\n    return this._defaultAttributes;\n  }\n  getBasicScopeAttributes(scopeName) {\n    if (scopeName === null) {\n      return _BasicScopeAttributesProvider._NULL_SCOPE_METADATA;\n    }\n    return this._getBasicScopeAttributes.get(scopeName);\n  }\n  static _NULL_SCOPE_METADATA = new BasicScopeAttributes(0, 0);\n  _getBasicScopeAttributes = new CachedFn((scopeName) => {\n    const languageId = this._scopeToLanguage(scopeName);\n    const standardTokenType = this._toStandardTokenType(scopeName);\n    return new BasicScopeAttributes(languageId, standardTokenType);\n  });\n  /**\n   * Given a produced TM scope, return the language that token describes or null if unknown.\n   * e.g. source.html => html, source.css.embedded.html => css, punctuation.definition.tag.html => null\n   */\n  _scopeToLanguage(scope) {\n    return this._embeddedLanguagesMatcher.match(scope) || 0;\n  }\n  _toStandardTokenType(scopeName) {\n    const m = scopeName.match(_BasicScopeAttributesProvider.STANDARD_TOKEN_TYPE_REGEXP);\n    if (!m) {\n      return 8 /* NotSet */;\n    }\n    switch (m[1]) {\n      case \"comment\":\n        return 1 /* Comment */;\n      case \"string\":\n        return 2 /* String */;\n      case \"regex\":\n        return 3 /* RegEx */;\n      case \"meta.embedded\":\n        return 0 /* Other */;\n    }\n    throw new Error(\"Unexpected match for standard token type!\");\n  }\n  static STANDARD_TOKEN_TYPE_REGEXP = /\\b(comment|string|regex|meta\\.embedded)\\b/;\n};\nvar ScopeMatcher = class {\n  values;\n  scopesRegExp;\n  constructor(values) {\n    if (values.length === 0) {\n      this.values = null;\n      this.scopesRegExp = null;\n    } else {\n      this.values = new Map(values);\n      const escapedScopes = values.map(\n        ([scopeName, value]) => escapeRegExpCharacters(scopeName)\n      );\n      escapedScopes.sort();\n      escapedScopes.reverse();\n      this.scopesRegExp = new RegExp(\n        `^((${escapedScopes.join(\")|(\")}))($|\\\\.)`,\n        \"\"\n      );\n    }\n  }\n  match(scope) {\n    if (!this.scopesRegExp) {\n      return void 0;\n    }\n    const m = scope.match(this.scopesRegExp);\n    if (!m) {\n      return void 0;\n    }\n    return this.values.get(m[1]);\n  }\n};\n\n// src/debug.ts\nvar DebugFlags = {\n  InDebugMode: typeof process !== \"undefined\" && !!process.env[\"VSCODE_TEXTMATE_DEBUG\"]\n};\nvar UseOnigurumaFindOptions = false;\n\n// src/grammar/tokenizeString.ts\nvar TokenizeStringResult = class {\n  constructor(stack, stoppedEarly) {\n    this.stack = stack;\n    this.stoppedEarly = stoppedEarly;\n  }\n};\nfunction _tokenizeString(grammar, lineText, isFirstLine, linePos, stack, lineTokens, checkWhileConditions, timeLimit) {\n  const lineLength = lineText.content.length;\n  let STOP = false;\n  let anchorPosition = -1;\n  if (checkWhileConditions) {\n    const whileCheckResult = _checkWhileConditions(\n      grammar,\n      lineText,\n      isFirstLine,\n      linePos,\n      stack,\n      lineTokens\n    );\n    stack = whileCheckResult.stack;\n    linePos = whileCheckResult.linePos;\n    isFirstLine = whileCheckResult.isFirstLine;\n    anchorPosition = whileCheckResult.anchorPosition;\n  }\n  const startTime = Date.now();\n  while (!STOP) {\n    if (timeLimit !== 0) {\n      const elapsedTime = Date.now() - startTime;\n      if (elapsedTime > timeLimit) {\n        return new TokenizeStringResult(stack, true);\n      }\n    }\n    scanNext();\n  }\n  return new TokenizeStringResult(stack, false);\n  function scanNext() {\n    if (false) {\n      console.log(\"\");\n      console.log(\n        `@@scanNext ${linePos}: |${lineText.content.substr(linePos).replace(/\\n$/, \"\\\\n\")}|`\n      );\n    }\n    const r = matchRuleOrInjections(\n      grammar,\n      lineText,\n      isFirstLine,\n      linePos,\n      stack,\n      anchorPosition\n    );\n    if (!r) {\n      lineTokens.produce(stack, lineLength);\n      STOP = true;\n      return;\n    }\n    const captureIndices = r.captureIndices;\n    const matchedRuleId = r.matchedRuleId;\n    const hasAdvanced = captureIndices && captureIndices.length > 0 ? captureIndices[0].end > linePos : false;\n    if (matchedRuleId === endRuleId) {\n      const poppedRule = stack.getRule(grammar);\n      if (false) {\n        console.log(\n          \"  popping \" + poppedRule.debugName + \" - \" + poppedRule.debugEndRegExp\n        );\n      }\n      lineTokens.produce(stack, captureIndices[0].start);\n      stack = stack.withContentNameScopesList(stack.nameScopesList);\n      handleCaptures(\n        grammar,\n        lineText,\n        isFirstLine,\n        stack,\n        lineTokens,\n        poppedRule.endCaptures,\n        captureIndices\n      );\n      lineTokens.produce(stack, captureIndices[0].end);\n      const popped = stack;\n      stack = stack.parent;\n      anchorPosition = popped.getAnchorPos();\n      if (!hasAdvanced && popped.getEnterPos() === linePos) {\n        if (false) {\n          console.error(\n            \"[1] - Grammar is in an endless loop - Grammar pushed & popped a rule without advancing\"\n          );\n        }\n        stack = popped;\n        lineTokens.produce(stack, lineLength);\n        STOP = true;\n        return;\n      }\n    } else {\n      const _rule = grammar.getRule(matchedRuleId);\n      lineTokens.produce(stack, captureIndices[0].start);\n      const beforePush = stack;\n      const scopeName = _rule.getName(lineText.content, captureIndices);\n      const nameScopesList = stack.contentNameScopesList.pushAttributed(\n        scopeName,\n        grammar\n      );\n      stack = stack.push(\n        matchedRuleId,\n        linePos,\n        anchorPosition,\n        captureIndices[0].end === lineLength,\n        null,\n        nameScopesList,\n        nameScopesList\n      );\n      if (_rule instanceof BeginEndRule) {\n        const pushedRule = _rule;\n        if (false) {\n          console.log(\n            \"  pushing \" + pushedRule.debugName + \" - \" + pushedRule.debugBeginRegExp\n          );\n        }\n        handleCaptures(\n          grammar,\n          lineText,\n          isFirstLine,\n          stack,\n          lineTokens,\n          pushedRule.beginCaptures,\n          captureIndices\n        );\n        lineTokens.produce(stack, captureIndices[0].end);\n        anchorPosition = captureIndices[0].end;\n        const contentName = pushedRule.getContentName(\n          lineText.content,\n          captureIndices\n        );\n        const contentNameScopesList = nameScopesList.pushAttributed(\n          contentName,\n          grammar\n        );\n        stack = stack.withContentNameScopesList(contentNameScopesList);\n        if (pushedRule.endHasBackReferences) {\n          stack = stack.withEndRule(\n            pushedRule.getEndWithResolvedBackReferences(\n              lineText.content,\n              captureIndices\n            )\n          );\n        }\n        if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {\n          if (false) {\n            console.error(\n              \"[2] - Grammar is in an endless loop - Grammar pushed the same rule without advancing\"\n            );\n          }\n          stack = stack.pop();\n          lineTokens.produce(stack, lineLength);\n          STOP = true;\n          return;\n        }\n      } else if (_rule instanceof BeginWhileRule) {\n        const pushedRule = _rule;\n        if (false) {\n          console.log(\"  pushing \" + pushedRule.debugName);\n        }\n        handleCaptures(\n          grammar,\n          lineText,\n          isFirstLine,\n          stack,\n          lineTokens,\n          pushedRule.beginCaptures,\n          captureIndices\n        );\n        lineTokens.produce(stack, captureIndices[0].end);\n        anchorPosition = captureIndices[0].end;\n        const contentName = pushedRule.getContentName(\n          lineText.content,\n          captureIndices\n        );\n        const contentNameScopesList = nameScopesList.pushAttributed(\n          contentName,\n          grammar\n        );\n        stack = stack.withContentNameScopesList(contentNameScopesList);\n        if (pushedRule.whileHasBackReferences) {\n          stack = stack.withEndRule(\n            pushedRule.getWhileWithResolvedBackReferences(\n              lineText.content,\n              captureIndices\n            )\n          );\n        }\n        if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {\n          if (false) {\n            console.error(\n              \"[3] - Grammar is in an endless loop - Grammar pushed the same rule without advancing\"\n            );\n          }\n          stack = stack.pop();\n          lineTokens.produce(stack, lineLength);\n          STOP = true;\n          return;\n        }\n      } else {\n        const matchingRule = _rule;\n        if (false) {\n          console.log(\n            \"  matched \" + matchingRule.debugName + \" - \" + matchingRule.debugMatchRegExp\n          );\n        }\n        handleCaptures(\n          grammar,\n          lineText,\n          isFirstLine,\n          stack,\n          lineTokens,\n          matchingRule.captures,\n          captureIndices\n        );\n        lineTokens.produce(stack, captureIndices[0].end);\n        stack = stack.pop();\n        if (!hasAdvanced) {\n          if (false) {\n            console.error(\n              \"[4] - Grammar is in an endless loop - Grammar is not advancing, nor is it pushing/popping\"\n            );\n          }\n          stack = stack.safePop();\n          lineTokens.produce(stack, lineLength);\n          STOP = true;\n          return;\n        }\n      }\n    }\n    if (captureIndices[0].end > linePos) {\n      linePos = captureIndices[0].end;\n      isFirstLine = false;\n    }\n  }\n}\nfunction _checkWhileConditions(grammar, lineText, isFirstLine, linePos, stack, lineTokens) {\n  let anchorPosition = stack.beginRuleCapturedEOL ? 0 : -1;\n  const whileRules = [];\n  for (let node = stack; node; node = node.pop()) {\n    const nodeRule = node.getRule(grammar);\n    if (nodeRule instanceof BeginWhileRule) {\n      whileRules.push({\n        rule: nodeRule,\n        stack: node\n      });\n    }\n  }\n  for (let whileRule = whileRules.pop(); whileRule; whileRule = whileRules.pop()) {\n    const { ruleScanner, findOptions } = prepareRuleWhileSearch(whileRule.rule, grammar, whileRule.stack.endRule, isFirstLine, linePos === anchorPosition);\n    const r = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);\n    if (false) {\n      console.log(\"  scanning for while rule\");\n      console.log(ruleScanner.toString());\n    }\n    if (r) {\n      const matchedRuleId = r.ruleId;\n      if (matchedRuleId !== whileRuleId) {\n        stack = whileRule.stack.pop();\n        break;\n      }\n      if (r.captureIndices && r.captureIndices.length) {\n        lineTokens.produce(whileRule.stack, r.captureIndices[0].start);\n        handleCaptures(grammar, lineText, isFirstLine, whileRule.stack, lineTokens, whileRule.rule.whileCaptures, r.captureIndices);\n        lineTokens.produce(whileRule.stack, r.captureIndices[0].end);\n        anchorPosition = r.captureIndices[0].end;\n        if (r.captureIndices[0].end > linePos) {\n          linePos = r.captureIndices[0].end;\n          isFirstLine = false;\n        }\n      }\n    } else {\n      if (false) {\n        console.log(\"  popping \" + whileRule.rule.debugName + \" - \" + whileRule.rule.debugWhileRegExp);\n      }\n      stack = whileRule.stack.pop();\n      break;\n    }\n  }\n  return { stack, linePos, anchorPosition, isFirstLine };\n}\nfunction matchRuleOrInjections(grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {\n  const matchResult = matchRule(grammar, lineText, isFirstLine, linePos, stack, anchorPosition);\n  const injections = grammar.getInjections();\n  if (injections.length === 0) {\n    return matchResult;\n  }\n  const injectionResult = matchInjections(injections, grammar, lineText, isFirstLine, linePos, stack, anchorPosition);\n  if (!injectionResult) {\n    return matchResult;\n  }\n  if (!matchResult) {\n    return injectionResult;\n  }\n  const matchResultScore = matchResult.captureIndices[0].start;\n  const injectionResultScore = injectionResult.captureIndices[0].start;\n  if (injectionResultScore < matchResultScore || injectionResult.priorityMatch && injectionResultScore === matchResultScore) {\n    return injectionResult;\n  }\n  return matchResult;\n}\nfunction matchRule(grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {\n  const rule = stack.getRule(grammar);\n  const { ruleScanner, findOptions } = prepareRuleSearch(rule, grammar, stack.endRule, isFirstLine, linePos === anchorPosition);\n  const r = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);\n  if (r) {\n    return {\n      captureIndices: r.captureIndices,\n      matchedRuleId: r.ruleId\n    };\n  }\n  return null;\n}\nfunction matchInjections(injections, grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {\n  let bestMatchRating = Number.MAX_VALUE;\n  let bestMatchCaptureIndices = null;\n  let bestMatchRuleId;\n  let bestMatchResultPriority = 0;\n  const scopes = stack.contentNameScopesList.getScopeNames();\n  for (let i = 0, len = injections.length; i < len; i++) {\n    const injection = injections[i];\n    if (!injection.matcher(scopes)) {\n      continue;\n    }\n    const rule = grammar.getRule(injection.ruleId);\n    const { ruleScanner, findOptions } = prepareRuleSearch(rule, grammar, null, isFirstLine, linePos === anchorPosition);\n    const matchResult = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);\n    if (!matchResult) {\n      continue;\n    }\n    if (false) {\n      console.log(`  matched injection: ${injection.debugSelector}`);\n      console.log(ruleScanner.toString());\n    }\n    const matchRating = matchResult.captureIndices[0].start;\n    if (matchRating >= bestMatchRating) {\n      continue;\n    }\n    bestMatchRating = matchRating;\n    bestMatchCaptureIndices = matchResult.captureIndices;\n    bestMatchRuleId = matchResult.ruleId;\n    bestMatchResultPriority = injection.priority;\n    if (bestMatchRating === linePos) {\n      break;\n    }\n  }\n  if (bestMatchCaptureIndices) {\n    return {\n      priorityMatch: bestMatchResultPriority === -1,\n      captureIndices: bestMatchCaptureIndices,\n      matchedRuleId: bestMatchRuleId\n    };\n  }\n  return null;\n}\nfunction prepareRuleSearch(rule, grammar, endRegexSource, allowA, allowG) {\n  if (UseOnigurumaFindOptions) {\n    const ruleScanner2 = rule.compile(grammar, endRegexSource);\n    const findOptions = getFindOptions(allowA, allowG);\n    return { ruleScanner: ruleScanner2, findOptions };\n  }\n  const ruleScanner = rule.compileAG(grammar, endRegexSource, allowA, allowG);\n  return { ruleScanner, findOptions: 0 /* None */ };\n}\nfunction prepareRuleWhileSearch(rule, grammar, endRegexSource, allowA, allowG) {\n  if (UseOnigurumaFindOptions) {\n    const ruleScanner2 = rule.compileWhile(grammar, endRegexSource);\n    const findOptions = getFindOptions(allowA, allowG);\n    return { ruleScanner: ruleScanner2, findOptions };\n  }\n  const ruleScanner = rule.compileWhileAG(grammar, endRegexSource, allowA, allowG);\n  return { ruleScanner, findOptions: 0 /* None */ };\n}\nfunction getFindOptions(allowA, allowG) {\n  let options = 0 /* None */;\n  if (!allowA) {\n    options |= 1 /* NotBeginString */;\n  }\n  if (!allowG) {\n    options |= 4 /* NotBeginPosition */;\n  }\n  return options;\n}\nfunction handleCaptures(grammar, lineText, isFirstLine, stack, lineTokens, captures, captureIndices) {\n  if (captures.length === 0) {\n    return;\n  }\n  const lineTextContent = lineText.content;\n  const len = Math.min(captures.length, captureIndices.length);\n  const localStack = [];\n  const maxEnd = captureIndices[0].end;\n  for (let i = 0; i < len; i++) {\n    const captureRule = captures[i];\n    if (captureRule === null) {\n      continue;\n    }\n    const captureIndex = captureIndices[i];\n    if (captureIndex.length === 0) {\n      continue;\n    }\n    if (captureIndex.start > maxEnd) {\n      break;\n    }\n    while (localStack.length > 0 && localStack[localStack.length - 1].endPos <= captureIndex.start) {\n      lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos);\n      localStack.pop();\n    }\n    if (localStack.length > 0) {\n      lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, captureIndex.start);\n    } else {\n      lineTokens.produce(stack, captureIndex.start);\n    }\n    if (captureRule.retokenizeCapturedWithRuleId) {\n      const scopeName = captureRule.getName(lineTextContent, captureIndices);\n      const nameScopesList = stack.contentNameScopesList.pushAttributed(scopeName, grammar);\n      const contentName = captureRule.getContentName(lineTextContent, captureIndices);\n      const contentNameScopesList = nameScopesList.pushAttributed(contentName, grammar);\n      const stackClone = stack.push(captureRule.retokenizeCapturedWithRuleId, captureIndex.start, -1, false, null, nameScopesList, contentNameScopesList);\n      const onigSubStr = grammar.createOnigString(lineTextContent.substring(0, captureIndex.end));\n      _tokenizeString(\n        grammar,\n        onigSubStr,\n        isFirstLine && captureIndex.start === 0,\n        captureIndex.start,\n        stackClone,\n        lineTokens,\n        false,\n        /* no time limit */\n        0\n      );\n      disposeOnigString(onigSubStr);\n      continue;\n    }\n    const captureRuleScopeName = captureRule.getName(lineTextContent, captureIndices);\n    if (captureRuleScopeName !== null) {\n      const base = localStack.length > 0 ? localStack[localStack.length - 1].scopes : stack.contentNameScopesList;\n      const captureRuleScopesList = base.pushAttributed(captureRuleScopeName, grammar);\n      localStack.push(new LocalStackElement(captureRuleScopesList, captureIndex.end));\n    }\n  }\n  while (localStack.length > 0) {\n    lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos);\n    localStack.pop();\n  }\n}\nvar LocalStackElement = class {\n  scopes;\n  endPos;\n  constructor(scopes, endPos) {\n    this.scopes = scopes;\n    this.endPos = endPos;\n  }\n};\n\n// src/grammar/grammar.ts\nfunction createGrammar(scopeName, grammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, grammarRepository, onigLib) {\n  return new Grammar(\n    scopeName,\n    grammar,\n    initialLanguage,\n    embeddedLanguages,\n    tokenTypes,\n    balancedBracketSelectors,\n    grammarRepository,\n    onigLib\n  );\n}\nfunction collectInjections(result, selector, rule, ruleFactoryHelper, grammar) {\n  const matchers = createMatchers(selector, nameMatcher);\n  const ruleId = RuleFactory.getCompiledRuleId(rule, ruleFactoryHelper, grammar.repository);\n  for (const matcher of matchers) {\n    result.push({\n      debugSelector: selector,\n      matcher: matcher.matcher,\n      ruleId,\n      grammar,\n      priority: matcher.priority\n    });\n  }\n}\nfunction nameMatcher(identifers, scopes) {\n  if (scopes.length < identifers.length) {\n    return false;\n  }\n  let lastIndex = 0;\n  return identifers.every((identifier) => {\n    for (let i = lastIndex; i < scopes.length; i++) {\n      if (scopesAreMatching(scopes[i], identifier)) {\n        lastIndex = i + 1;\n        return true;\n      }\n    }\n    return false;\n  });\n}\nfunction scopesAreMatching(thisScopeName, scopeName) {\n  if (!thisScopeName) {\n    return false;\n  }\n  if (thisScopeName === scopeName) {\n    return true;\n  }\n  const len = scopeName.length;\n  return thisScopeName.length > len && thisScopeName.substr(0, len) === scopeName && thisScopeName[len] === \".\";\n}\nvar Grammar = class {\n  constructor(_rootScopeName, grammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, grammarRepository, _onigLib) {\n    this._rootScopeName = _rootScopeName;\n    this.balancedBracketSelectors = balancedBracketSelectors;\n    this._onigLib = _onigLib;\n    this._basicScopeAttributesProvider = new BasicScopeAttributesProvider(\n      initialLanguage,\n      embeddedLanguages\n    );\n    this._rootId = -1;\n    this._lastRuleId = 0;\n    this._ruleId2desc = [null];\n    this._includedGrammars = {};\n    this._grammarRepository = grammarRepository;\n    this._grammar = initGrammar(grammar, null);\n    this._injections = null;\n    this._tokenTypeMatchers = [];\n    if (tokenTypes) {\n      for (const selector of Object.keys(tokenTypes)) {\n        const matchers = createMatchers(selector, nameMatcher);\n        for (const matcher of matchers) {\n          this._tokenTypeMatchers.push({\n            matcher: matcher.matcher,\n            type: tokenTypes[selector]\n          });\n        }\n      }\n    }\n  }\n  _rootId;\n  _lastRuleId;\n  _ruleId2desc;\n  _includedGrammars;\n  _grammarRepository;\n  _grammar;\n  _injections;\n  _basicScopeAttributesProvider;\n  _tokenTypeMatchers;\n  get themeProvider() {\n    return this._grammarRepository;\n  }\n  dispose() {\n    for (const rule of this._ruleId2desc) {\n      if (rule) {\n        rule.dispose();\n      }\n    }\n  }\n  createOnigScanner(sources) {\n    return this._onigLib.createOnigScanner(sources);\n  }\n  createOnigString(sources) {\n    return this._onigLib.createOnigString(sources);\n  }\n  getMetadataForScope(scope) {\n    return this._basicScopeAttributesProvider.getBasicScopeAttributes(scope);\n  }\n  _collectInjections() {\n    const grammarRepository = {\n      lookup: (scopeName2) => {\n        if (scopeName2 === this._rootScopeName) {\n          return this._grammar;\n        }\n        return this.getExternalGrammar(scopeName2);\n      },\n      injections: (scopeName2) => {\n        return this._grammarRepository.injections(scopeName2);\n      }\n    };\n    const result = [];\n    const scopeName = this._rootScopeName;\n    const grammar = grammarRepository.lookup(scopeName);\n    if (grammar) {\n      const rawInjections = grammar.injections;\n      if (rawInjections) {\n        for (let expression in rawInjections) {\n          collectInjections(\n            result,\n            expression,\n            rawInjections[expression],\n            this,\n            grammar\n          );\n        }\n      }\n      const injectionScopeNames = this._grammarRepository.injections(scopeName);\n      if (injectionScopeNames) {\n        injectionScopeNames.forEach((injectionScopeName) => {\n          const injectionGrammar = this.getExternalGrammar(injectionScopeName);\n          if (injectionGrammar) {\n            const selector = injectionGrammar.injectionSelector;\n            if (selector) {\n              collectInjections(\n                result,\n                selector,\n                injectionGrammar,\n                this,\n                injectionGrammar\n              );\n            }\n          }\n        });\n      }\n    }\n    result.sort((i1, i2) => i1.priority - i2.priority);\n    return result;\n  }\n  getInjections() {\n    if (this._injections === null) {\n      this._injections = this._collectInjections();\n    }\n    return this._injections;\n  }\n  registerRule(factory) {\n    const id = ++this._lastRuleId;\n    const result = factory(ruleIdFromNumber(id));\n    this._ruleId2desc[id] = result;\n    return result;\n  }\n  getRule(ruleId) {\n    return this._ruleId2desc[ruleIdToNumber(ruleId)];\n  }\n  getExternalGrammar(scopeName, repository) {\n    if (this._includedGrammars[scopeName]) {\n      return this._includedGrammars[scopeName];\n    } else if (this._grammarRepository) {\n      const rawIncludedGrammar = this._grammarRepository.lookup(scopeName);\n      if (rawIncludedGrammar) {\n        this._includedGrammars[scopeName] = initGrammar(\n          rawIncludedGrammar,\n          repository && repository.$base\n        );\n        return this._includedGrammars[scopeName];\n      }\n    }\n    return void 0;\n  }\n  tokenizeLine(lineText, prevState, timeLimit = 0) {\n    const r = this._tokenize(lineText, prevState, false, timeLimit);\n    return {\n      tokens: r.lineTokens.getResult(r.ruleStack, r.lineLength),\n      ruleStack: r.ruleStack,\n      stoppedEarly: r.stoppedEarly\n    };\n  }\n  tokenizeLine2(lineText, prevState, timeLimit = 0) {\n    const r = this._tokenize(lineText, prevState, true, timeLimit);\n    return {\n      tokens: r.lineTokens.getBinaryResult(r.ruleStack, r.lineLength),\n      ruleStack: r.ruleStack,\n      stoppedEarly: r.stoppedEarly\n    };\n  }\n  _tokenize(lineText, prevState, emitBinaryTokens, timeLimit) {\n    if (this._rootId === -1) {\n      this._rootId = RuleFactory.getCompiledRuleId(\n        this._grammar.repository.$self,\n        this,\n        this._grammar.repository\n      );\n      this.getInjections();\n    }\n    let isFirstLine;\n    if (!prevState || prevState === StateStackImpl.NULL) {\n      isFirstLine = true;\n      const rawDefaultMetadata = this._basicScopeAttributesProvider.getDefaultAttributes();\n      const defaultStyle = this.themeProvider.getDefaults();\n      const defaultMetadata = EncodedTokenMetadata.set(\n        0,\n        rawDefaultMetadata.languageId,\n        rawDefaultMetadata.tokenType,\n        null,\n        defaultStyle.fontStyle,\n        defaultStyle.foregroundId,\n        defaultStyle.backgroundId\n      );\n      const rootScopeName = this.getRule(this._rootId).getName(\n        null,\n        null\n      );\n      let scopeList;\n      if (rootScopeName) {\n        scopeList = AttributedScopeStack.createRootAndLookUpScopeName(\n          rootScopeName,\n          defaultMetadata,\n          this\n        );\n      } else {\n        scopeList = AttributedScopeStack.createRoot(\n          \"unknown\",\n          defaultMetadata\n        );\n      }\n      prevState = new StateStackImpl(\n        null,\n        this._rootId,\n        -1,\n        -1,\n        false,\n        null,\n        scopeList,\n        scopeList\n      );\n    } else {\n      isFirstLine = false;\n      prevState.reset();\n    }\n    lineText = lineText + \"\\n\";\n    const onigLineText = this.createOnigString(lineText);\n    const lineLength = onigLineText.content.length;\n    const lineTokens = new LineTokens(\n      emitBinaryTokens,\n      lineText,\n      this._tokenTypeMatchers,\n      this.balancedBracketSelectors\n    );\n    const r = _tokenizeString(\n      this,\n      onigLineText,\n      isFirstLine,\n      0,\n      prevState,\n      lineTokens,\n      true,\n      timeLimit\n    );\n    disposeOnigString(onigLineText);\n    return {\n      lineLength,\n      lineTokens,\n      ruleStack: r.stack,\n      stoppedEarly: r.stoppedEarly\n    };\n  }\n};\nfunction initGrammar(grammar, base) {\n  grammar = clone(grammar);\n  grammar.repository = grammar.repository || {};\n  grammar.repository.$self = {\n    $vscodeTextmateLocation: grammar.$vscodeTextmateLocation,\n    patterns: grammar.patterns,\n    name: grammar.scopeName\n  };\n  grammar.repository.$base = base || grammar.repository.$self;\n  return grammar;\n}\nvar AttributedScopeStack = class _AttributedScopeStack {\n  /**\n   * Invariant:\n   * ```\n   * if (parent && !scopePath.extends(parent.scopePath)) {\n   * \tthrow new Error();\n   * }\n   * ```\n   */\n  constructor(parent, scopePath, tokenAttributes) {\n    this.parent = parent;\n    this.scopePath = scopePath;\n    this.tokenAttributes = tokenAttributes;\n  }\n  static fromExtension(namesScopeList, contentNameScopesList) {\n    let current = namesScopeList;\n    let scopeNames = namesScopeList?.scopePath ?? null;\n    for (const frame of contentNameScopesList) {\n      scopeNames = ScopeStack.push(scopeNames, frame.scopeNames);\n      current = new _AttributedScopeStack(current, scopeNames, frame.encodedTokenAttributes);\n    }\n    return current;\n  }\n  static createRoot(scopeName, tokenAttributes) {\n    return new _AttributedScopeStack(null, new ScopeStack(null, scopeName), tokenAttributes);\n  }\n  static createRootAndLookUpScopeName(scopeName, tokenAttributes, grammar) {\n    const rawRootMetadata = grammar.getMetadataForScope(scopeName);\n    const scopePath = new ScopeStack(null, scopeName);\n    const rootStyle = grammar.themeProvider.themeMatch(scopePath);\n    const resolvedTokenAttributes = _AttributedScopeStack.mergeAttributes(\n      tokenAttributes,\n      rawRootMetadata,\n      rootStyle\n    );\n    return new _AttributedScopeStack(null, scopePath, resolvedTokenAttributes);\n  }\n  get scopeName() {\n    return this.scopePath.scopeName;\n  }\n  toString() {\n    return this.getScopeNames().join(\" \");\n  }\n  equals(other) {\n    return _AttributedScopeStack.equals(this, other);\n  }\n  static equals(a, b) {\n    do {\n      if (a === b) {\n        return true;\n      }\n      if (!a && !b) {\n        return true;\n      }\n      if (!a || !b) {\n        return false;\n      }\n      if (a.scopeName !== b.scopeName || a.tokenAttributes !== b.tokenAttributes) {\n        return false;\n      }\n      a = a.parent;\n      b = b.parent;\n    } while (true);\n  }\n  static mergeAttributes(existingTokenAttributes, basicScopeAttributes, styleAttributes) {\n    let fontStyle = -1 /* NotSet */;\n    let foreground = 0;\n    let background = 0;\n    if (styleAttributes !== null) {\n      fontStyle = styleAttributes.fontStyle;\n      foreground = styleAttributes.foregroundId;\n      background = styleAttributes.backgroundId;\n    }\n    return EncodedTokenMetadata.set(\n      existingTokenAttributes,\n      basicScopeAttributes.languageId,\n      basicScopeAttributes.tokenType,\n      null,\n      fontStyle,\n      foreground,\n      background\n    );\n  }\n  pushAttributed(scopePath, grammar) {\n    if (scopePath === null) {\n      return this;\n    }\n    if (scopePath.indexOf(\" \") === -1) {\n      return _AttributedScopeStack._pushAttributed(this, scopePath, grammar);\n    }\n    const scopes = scopePath.split(/ /g);\n    let result = this;\n    for (const scope of scopes) {\n      result = _AttributedScopeStack._pushAttributed(result, scope, grammar);\n    }\n    return result;\n  }\n  static _pushAttributed(target, scopeName, grammar) {\n    const rawMetadata = grammar.getMetadataForScope(scopeName);\n    const newPath = target.scopePath.push(scopeName);\n    const scopeThemeMatchResult = grammar.themeProvider.themeMatch(newPath);\n    const metadata = _AttributedScopeStack.mergeAttributes(\n      target.tokenAttributes,\n      rawMetadata,\n      scopeThemeMatchResult\n    );\n    return new _AttributedScopeStack(target, newPath, metadata);\n  }\n  getScopeNames() {\n    return this.scopePath.getSegments();\n  }\n  getExtensionIfDefined(base) {\n    const result = [];\n    let self = this;\n    while (self && self !== base) {\n      result.push({\n        encodedTokenAttributes: self.tokenAttributes,\n        scopeNames: self.scopePath.getExtensionIfDefined(self.parent?.scopePath ?? null)\n      });\n      self = self.parent;\n    }\n    return self === base ? result.reverse() : void 0;\n  }\n};\nvar StateStackImpl = class _StateStackImpl {\n  /**\n   * Invariant:\n   * ```\n   * if (contentNameScopesList !== nameScopesList && contentNameScopesList?.parent !== nameScopesList) {\n   * \tthrow new Error();\n   * }\n   * if (this.parent && !nameScopesList.extends(this.parent.contentNameScopesList)) {\n   * \tthrow new Error();\n   * }\n   * ```\n   */\n  constructor(parent, ruleId, enterPos, anchorPos, beginRuleCapturedEOL, endRule, nameScopesList, contentNameScopesList) {\n    this.parent = parent;\n    this.ruleId = ruleId;\n    this.beginRuleCapturedEOL = beginRuleCapturedEOL;\n    this.endRule = endRule;\n    this.nameScopesList = nameScopesList;\n    this.contentNameScopesList = contentNameScopesList;\n    this.depth = this.parent ? this.parent.depth + 1 : 1;\n    this._enterPos = enterPos;\n    this._anchorPos = anchorPos;\n  }\n  _stackElementBrand = void 0;\n  // TODO remove me\n  static NULL = new _StateStackImpl(\n    null,\n    0,\n    0,\n    0,\n    false,\n    null,\n    null,\n    null\n  );\n  /**\n   * The position on the current line where this state was pushed.\n   * This is relevant only while tokenizing a line, to detect endless loops.\n   * Its value is meaningless across lines.\n   */\n  _enterPos;\n  /**\n   * The captured anchor position when this stack element was pushed.\n   * This is relevant only while tokenizing a line, to restore the anchor position when popping.\n   * Its value is meaningless across lines.\n   */\n  _anchorPos;\n  /**\n   * The depth of the stack.\n   */\n  depth;\n  equals(other) {\n    if (other === null) {\n      return false;\n    }\n    return _StateStackImpl._equals(this, other);\n  }\n  static _equals(a, b) {\n    if (a === b) {\n      return true;\n    }\n    if (!this._structuralEquals(a, b)) {\n      return false;\n    }\n    return AttributedScopeStack.equals(a.contentNameScopesList, b.contentNameScopesList);\n  }\n  /**\n   * A structural equals check. Does not take into account `scopes`.\n   */\n  static _structuralEquals(a, b) {\n    do {\n      if (a === b) {\n        return true;\n      }\n      if (!a && !b) {\n        return true;\n      }\n      if (!a || !b) {\n        return false;\n      }\n      if (a.depth !== b.depth || a.ruleId !== b.ruleId || a.endRule !== b.endRule) {\n        return false;\n      }\n      a = a.parent;\n      b = b.parent;\n    } while (true);\n  }\n  clone() {\n    return this;\n  }\n  static _reset(el) {\n    while (el) {\n      el._enterPos = -1;\n      el._anchorPos = -1;\n      el = el.parent;\n    }\n  }\n  reset() {\n    _StateStackImpl._reset(this);\n  }\n  pop() {\n    return this.parent;\n  }\n  safePop() {\n    if (this.parent) {\n      return this.parent;\n    }\n    return this;\n  }\n  push(ruleId, enterPos, anchorPos, beginRuleCapturedEOL, endRule, nameScopesList, contentNameScopesList) {\n    return new _StateStackImpl(\n      this,\n      ruleId,\n      enterPos,\n      anchorPos,\n      beginRuleCapturedEOL,\n      endRule,\n      nameScopesList,\n      contentNameScopesList\n    );\n  }\n  getEnterPos() {\n    return this._enterPos;\n  }\n  getAnchorPos() {\n    return this._anchorPos;\n  }\n  getRule(grammar) {\n    return grammar.getRule(this.ruleId);\n  }\n  toString() {\n    const r = [];\n    this._writeString(r, 0);\n    return \"[\" + r.join(\",\") + \"]\";\n  }\n  _writeString(res, outIndex) {\n    if (this.parent) {\n      outIndex = this.parent._writeString(res, outIndex);\n    }\n    res[outIndex++] = `(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`;\n    return outIndex;\n  }\n  withContentNameScopesList(contentNameScopeStack) {\n    if (this.contentNameScopesList === contentNameScopeStack) {\n      return this;\n    }\n    return this.parent.push(\n      this.ruleId,\n      this._enterPos,\n      this._anchorPos,\n      this.beginRuleCapturedEOL,\n      this.endRule,\n      this.nameScopesList,\n      contentNameScopeStack\n    );\n  }\n  withEndRule(endRule) {\n    if (this.endRule === endRule) {\n      return this;\n    }\n    return new _StateStackImpl(\n      this.parent,\n      this.ruleId,\n      this._enterPos,\n      this._anchorPos,\n      this.beginRuleCapturedEOL,\n      endRule,\n      this.nameScopesList,\n      this.contentNameScopesList\n    );\n  }\n  // Used to warn of endless loops\n  hasSameRuleAs(other) {\n    let el = this;\n    while (el && el._enterPos === other._enterPos) {\n      if (el.ruleId === other.ruleId) {\n        return true;\n      }\n      el = el.parent;\n    }\n    return false;\n  }\n  toStateStackFrame() {\n    return {\n      ruleId: ruleIdToNumber(this.ruleId),\n      beginRuleCapturedEOL: this.beginRuleCapturedEOL,\n      endRule: this.endRule,\n      nameScopesList: this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList ?? null) ?? [],\n      contentNameScopesList: this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList) ?? []\n    };\n  }\n  static pushFrame(self, frame) {\n    const namesScopeList = AttributedScopeStack.fromExtension(self?.nameScopesList ?? null, frame.nameScopesList);\n    return new _StateStackImpl(\n      self,\n      ruleIdFromNumber(frame.ruleId),\n      frame.enterPos ?? -1,\n      frame.anchorPos ?? -1,\n      frame.beginRuleCapturedEOL,\n      frame.endRule,\n      namesScopeList,\n      AttributedScopeStack.fromExtension(namesScopeList, frame.contentNameScopesList)\n    );\n  }\n};\nvar BalancedBracketSelectors = class {\n  balancedBracketScopes;\n  unbalancedBracketScopes;\n  allowAny = false;\n  constructor(balancedBracketScopes, unbalancedBracketScopes) {\n    this.balancedBracketScopes = balancedBracketScopes.flatMap(\n      (selector) => {\n        if (selector === \"*\") {\n          this.allowAny = true;\n          return [];\n        }\n        return createMatchers(selector, nameMatcher).map((m) => m.matcher);\n      }\n    );\n    this.unbalancedBracketScopes = unbalancedBracketScopes.flatMap(\n      (selector) => createMatchers(selector, nameMatcher).map((m) => m.matcher)\n    );\n  }\n  get matchesAlways() {\n    return this.allowAny && this.unbalancedBracketScopes.length === 0;\n  }\n  get matchesNever() {\n    return this.balancedBracketScopes.length === 0 && !this.allowAny;\n  }\n  match(scopes) {\n    for (const excluder of this.unbalancedBracketScopes) {\n      if (excluder(scopes)) {\n        return false;\n      }\n    }\n    for (const includer of this.balancedBracketScopes) {\n      if (includer(scopes)) {\n        return true;\n      }\n    }\n    return this.allowAny;\n  }\n};\nvar LineTokens = class {\n  constructor(emitBinaryTokens, lineText, tokenTypeOverrides, balancedBracketSelectors) {\n    this.balancedBracketSelectors = balancedBracketSelectors;\n    this._emitBinaryTokens = emitBinaryTokens;\n    this._tokenTypeOverrides = tokenTypeOverrides;\n    if (false) {\n      this._lineText = lineText;\n    } else {\n      this._lineText = null;\n    }\n    this._tokens = [];\n    this._binaryTokens = [];\n    this._lastTokenEndIndex = 0;\n  }\n  _emitBinaryTokens;\n  /**\n   * defined only if `false`.\n   */\n  _lineText;\n  /**\n   * used only if `_emitBinaryTokens` is false.\n   */\n  _tokens;\n  /**\n   * used only if `_emitBinaryTokens` is true.\n   */\n  _binaryTokens;\n  _lastTokenEndIndex;\n  _tokenTypeOverrides;\n  produce(stack, endIndex) {\n    this.produceFromScopes(stack.contentNameScopesList, endIndex);\n  }\n  produceFromScopes(scopesList, endIndex) {\n    if (this._lastTokenEndIndex >= endIndex) {\n      return;\n    }\n    if (this._emitBinaryTokens) {\n      let metadata = scopesList?.tokenAttributes ?? 0;\n      let containsBalancedBrackets = false;\n      if (this.balancedBracketSelectors?.matchesAlways) {\n        containsBalancedBrackets = true;\n      }\n      if (this._tokenTypeOverrides.length > 0 || this.balancedBracketSelectors && !this.balancedBracketSelectors.matchesAlways && !this.balancedBracketSelectors.matchesNever) {\n        const scopes2 = scopesList?.getScopeNames() ?? [];\n        for (const tokenType of this._tokenTypeOverrides) {\n          if (tokenType.matcher(scopes2)) {\n            metadata = EncodedTokenMetadata.set(\n              metadata,\n              0,\n              toOptionalTokenType(tokenType.type),\n              null,\n              -1 /* NotSet */,\n              0,\n              0\n            );\n          }\n        }\n        if (this.balancedBracketSelectors) {\n          containsBalancedBrackets = this.balancedBracketSelectors.match(scopes2);\n        }\n      }\n      if (containsBalancedBrackets) {\n        metadata = EncodedTokenMetadata.set(\n          metadata,\n          0,\n          8 /* NotSet */,\n          containsBalancedBrackets,\n          -1 /* NotSet */,\n          0,\n          0\n        );\n      }\n      if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 1] === metadata) {\n        this._lastTokenEndIndex = endIndex;\n        return;\n      }\n      this._binaryTokens.push(this._lastTokenEndIndex);\n      this._binaryTokens.push(metadata);\n      this._lastTokenEndIndex = endIndex;\n      return;\n    }\n    const scopes = scopesList?.getScopeNames() ?? [];\n    this._tokens.push({\n      startIndex: this._lastTokenEndIndex,\n      endIndex,\n      // value: lineText.substring(lastTokenEndIndex, endIndex),\n      scopes\n    });\n    this._lastTokenEndIndex = endIndex;\n  }\n  getResult(stack, lineLength) {\n    if (this._tokens.length > 0 && this._tokens[this._tokens.length - 1].startIndex === lineLength - 1) {\n      this._tokens.pop();\n    }\n    if (this._tokens.length === 0) {\n      this._lastTokenEndIndex = -1;\n      this.produce(stack, lineLength);\n      this._tokens[this._tokens.length - 1].startIndex = 0;\n    }\n    return this._tokens;\n  }\n  getBinaryResult(stack, lineLength) {\n    if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 2] === lineLength - 1) {\n      this._binaryTokens.pop();\n      this._binaryTokens.pop();\n    }\n    if (this._binaryTokens.length === 0) {\n      this._lastTokenEndIndex = -1;\n      this.produce(stack, lineLength);\n      this._binaryTokens[this._binaryTokens.length - 2] = 0;\n    }\n    const result = new Uint32Array(this._binaryTokens.length);\n    for (let i = 0, len = this._binaryTokens.length; i < len; i++) {\n      result[i] = this._binaryTokens[i];\n    }\n    return result;\n  }\n};\n\n// src/registry.ts\nvar SyncRegistry = class {\n  constructor(theme, _onigLib) {\n    this._onigLib = _onigLib;\n    this._theme = theme;\n  }\n  _grammars = /* @__PURE__ */ new Map();\n  _rawGrammars = /* @__PURE__ */ new Map();\n  _injectionGrammars = /* @__PURE__ */ new Map();\n  _theme;\n  dispose() {\n    for (const grammar of this._grammars.values()) {\n      grammar.dispose();\n    }\n  }\n  setTheme(theme) {\n    this._theme = theme;\n  }\n  getColorMap() {\n    return this._theme.getColorMap();\n  }\n  /**\n   * Add `grammar` to registry and return a list of referenced scope names\n   */\n  addGrammar(grammar, injectionScopeNames) {\n    this._rawGrammars.set(grammar.scopeName, grammar);\n    if (injectionScopeNames) {\n      this._injectionGrammars.set(grammar.scopeName, injectionScopeNames);\n    }\n  }\n  /**\n   * Lookup a raw grammar.\n   */\n  lookup(scopeName) {\n    return this._rawGrammars.get(scopeName);\n  }\n  /**\n   * Returns the injections for the given grammar\n   */\n  injections(targetScope) {\n    return this._injectionGrammars.get(targetScope);\n  }\n  /**\n   * Get the default theme settings\n   */\n  getDefaults() {\n    return this._theme.getDefaults();\n  }\n  /**\n   * Match a scope in the theme.\n   */\n  themeMatch(scopePath) {\n    return this._theme.match(scopePath);\n  }\n  /**\n   * Lookup a grammar.\n   */\n  grammarForScopeName(scopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors) {\n    if (!this._grammars.has(scopeName)) {\n      let rawGrammar = this._rawGrammars.get(scopeName);\n      if (!rawGrammar) {\n        return null;\n      }\n      this._grammars.set(scopeName, createGrammar(\n        scopeName,\n        rawGrammar,\n        initialLanguage,\n        embeddedLanguages,\n        tokenTypes,\n        balancedBracketSelectors,\n        this,\n        this._onigLib\n      ));\n    }\n    return this._grammars.get(scopeName);\n  }\n};\n\n// src/index.ts\nvar Registry = class {\n  _options;\n  _syncRegistry;\n  _ensureGrammarCache;\n  constructor(options) {\n    this._options = options;\n    this._syncRegistry = new SyncRegistry(\n      Theme.createFromRawTheme(options.theme, options.colorMap),\n      options.onigLib\n    );\n    this._ensureGrammarCache = /* @__PURE__ */ new Map();\n  }\n  dispose() {\n    this._syncRegistry.dispose();\n  }\n  /**\n   * Change the theme. Once called, no previous `ruleStack` should be used anymore.\n   */\n  setTheme(theme, colorMap) {\n    this._syncRegistry.setTheme(Theme.createFromRawTheme(theme, colorMap));\n  }\n  /**\n   * Returns a lookup array for color ids.\n   */\n  getColorMap() {\n    return this._syncRegistry.getColorMap();\n  }\n  /**\n   * Load the grammar for `scopeName` and all referenced included grammars asynchronously.\n   * Please do not use language id 0.\n   */\n  loadGrammarWithEmbeddedLanguages(initialScopeName, initialLanguage, embeddedLanguages) {\n    return this.loadGrammarWithConfiguration(initialScopeName, initialLanguage, { embeddedLanguages });\n  }\n  /**\n   * Load the grammar for `scopeName` and all referenced included grammars asynchronously.\n   * Please do not use language id 0.\n   */\n  loadGrammarWithConfiguration(initialScopeName, initialLanguage, configuration) {\n    return this._loadGrammar(\n      initialScopeName,\n      initialLanguage,\n      configuration.embeddedLanguages,\n      configuration.tokenTypes,\n      new BalancedBracketSelectors(\n        configuration.balancedBracketSelectors || [],\n        configuration.unbalancedBracketSelectors || []\n      )\n    );\n  }\n  /**\n   * Load the grammar for `scopeName` and all referenced included grammars asynchronously.\n   */\n  loadGrammar(initialScopeName) {\n    return this._loadGrammar(initialScopeName, 0, null, null, null);\n  }\n  _loadGrammar(initialScopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors) {\n    const dependencyProcessor = new ScopeDependencyProcessor(this._syncRegistry, initialScopeName);\n    while (dependencyProcessor.Q.length > 0) {\n      dependencyProcessor.Q.map((request) => this._loadSingleGrammar(request.scopeName));\n      dependencyProcessor.processQueue();\n    }\n    return this._grammarForScopeName(\n      initialScopeName,\n      initialLanguage,\n      embeddedLanguages,\n      tokenTypes,\n      balancedBracketSelectors\n    );\n  }\n  _loadSingleGrammar(scopeName) {\n    if (!this._ensureGrammarCache.has(scopeName)) {\n      this._doLoadSingleGrammar(scopeName);\n      this._ensureGrammarCache.set(scopeName, true);\n    }\n  }\n  _doLoadSingleGrammar(scopeName) {\n    const grammar = this._options.loadGrammar(scopeName);\n    if (grammar) {\n      const injections = typeof this._options.getInjections === \"function\" ? this._options.getInjections(scopeName) : void 0;\n      this._syncRegistry.addGrammar(grammar, injections);\n    }\n  }\n  /**\n   * Adds a rawGrammar.\n   */\n  addGrammar(rawGrammar, injections = [], initialLanguage = 0, embeddedLanguages = null) {\n    this._syncRegistry.addGrammar(rawGrammar, injections);\n    return this._grammarForScopeName(rawGrammar.scopeName, initialLanguage, embeddedLanguages);\n  }\n  /**\n   * Get the grammar for `scopeName`. The grammar must first be created via `loadGrammar` or `addGrammar`.\n   */\n  _grammarForScopeName(scopeName, initialLanguage = 0, embeddedLanguages = null, tokenTypes = null, balancedBracketSelectors = null) {\n    return this._syncRegistry.grammarForScopeName(\n      scopeName,\n      initialLanguage,\n      embeddedLanguages,\n      tokenTypes,\n      balancedBracketSelectors\n    );\n  }\n};\nvar INITIAL = StateStackImpl.NULL;\nexport {\n  EncodedTokenMetadata,\n  FindOption,\n  FontStyle,\n  INITIAL,\n  Registry,\n  Theme,\n  disposeOnigString\n};\n","/**\n * List of HTML void tag names.\n *\n * @type {Array<string>}\n */\nexport const htmlVoidElements = [\n  'area',\n  'base',\n  'basefont',\n  'bgsound',\n  'br',\n  'col',\n  'command',\n  'embed',\n  'frame',\n  'hr',\n  'image',\n  'img',\n  'input',\n  'keygen',\n  'link',\n  'meta',\n  'param',\n  'source',\n  'track',\n  'wbr'\n]\n","/**\n * @typedef CoreOptions\n * @property {ReadonlyArray<string>} [subset=[]]\n *   Whether to only escape the given subset of characters.\n * @property {boolean} [escapeOnly=false]\n *   Whether to only escape possibly dangerous characters.\n *   Those characters are `\"`, `&`, `'`, `<`, `>`, and `` ` ``.\n *\n * @typedef FormatOptions\n * @property {(code: number, next: number, options: CoreWithFormatOptions) => string} format\n *   Format strategy.\n *\n * @typedef {CoreOptions & FormatOptions & import('./util/format-smart.js').FormatSmartOptions} CoreWithFormatOptions\n */\n\nconst defaultSubsetRegex = /[\"&'<>`]/g\nconst surrogatePairsRegex = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g\nconst controlCharactersRegex =\n  // eslint-disable-next-line no-control-regex, unicorn/no-hex-escape\n  /[\\x01-\\t\\v\\f\\x0E-\\x1F\\x7F\\x81\\x8D\\x8F\\x90\\x9D\\xA0-\\uFFFF]/g\nconst regexEscapeRegex = /[|\\\\{}()[\\]^$+*?.]/g\n\n/** @type {WeakMap<ReadonlyArray<string>, RegExp>} */\nconst subsetToRegexCache = new WeakMap()\n\n/**\n * Encode certain characters in `value`.\n *\n * @param {string} value\n * @param {CoreWithFormatOptions} options\n * @returns {string}\n */\nexport function core(value, options) {\n  value = value.replace(\n    options.subset\n      ? charactersToExpressionCached(options.subset)\n      : defaultSubsetRegex,\n    basic\n  )\n\n  if (options.subset || options.escapeOnly) {\n    return value\n  }\n\n  return (\n    value\n      // Surrogate pairs.\n      .replace(surrogatePairsRegex, surrogate)\n      // BMP control characters (C0 except for LF, CR, SP; DEL; and some more\n      // non-ASCII ones).\n      .replace(controlCharactersRegex, basic)\n  )\n\n  /**\n   * @param {string} pair\n   * @param {number} index\n   * @param {string} all\n   */\n  function surrogate(pair, index, all) {\n    return options.format(\n      (pair.charCodeAt(0) - 0xd800) * 0x400 +\n        pair.charCodeAt(1) -\n        0xdc00 +\n        0x10000,\n      all.charCodeAt(index + 2),\n      options\n    )\n  }\n\n  /**\n   * @param {string} character\n   * @param {number} index\n   * @param {string} all\n   */\n  function basic(character, index, all) {\n    return options.format(\n      character.charCodeAt(0),\n      all.charCodeAt(index + 1),\n      options\n    )\n  }\n}\n\n/**\n * A wrapper function that caches the result of `charactersToExpression` with a WeakMap.\n * This can improve performance when tooling calls `charactersToExpression` repeatedly\n * with the same subset.\n *\n * @param {ReadonlyArray<string>} subset\n * @returns {RegExp}\n */\nfunction charactersToExpressionCached(subset) {\n  let cached = subsetToRegexCache.get(subset)\n\n  if (!cached) {\n    cached = charactersToExpression(subset)\n    subsetToRegexCache.set(subset, cached)\n  }\n\n  return cached\n}\n\n/**\n * @param {ReadonlyArray<string>} subset\n * @returns {RegExp}\n */\nfunction charactersToExpression(subset) {\n  /** @type {Array<string>} */\n  const groups = []\n  let index = -1\n\n  while (++index < subset.length) {\n    groups.push(subset[index].replace(regexEscapeRegex, '\\\\$&'))\n  }\n\n  return new RegExp('(?:' + groups.join('|') + ')', 'g')\n}\n","const hexadecimalRegex = /[\\dA-Fa-f]/\n\n/**\n * Configurable ways to encode characters as hexadecimal references.\n *\n * @param {number} code\n * @param {number} next\n * @param {boolean|undefined} omit\n * @returns {string}\n */\nexport function toHexadecimal(code, next, omit) {\n  const value = '&#x' + code.toString(16).toUpperCase()\n  return omit && next && !hexadecimalRegex.test(String.fromCharCode(next))\n    ? value\n    : value + ';'\n}\n","const decimalRegex = /\\d/\n\n/**\n * Configurable ways to encode characters as decimal references.\n *\n * @param {number} code\n * @param {number} next\n * @param {boolean|undefined} omit\n * @returns {string}\n */\nexport function toDecimal(code, next, omit) {\n  const value = '&#' + String(code)\n  return omit && next && !decimalRegex.test(String.fromCharCode(next))\n    ? value\n    : value + ';'\n}\n","/**\n * List of legacy HTML named character references that don’t need a trailing semicolon.\n *\n * @type {Array<string>}\n */\nexport const characterEntitiesLegacy = [\n  'AElig',\n  'AMP',\n  'Aacute',\n  'Acirc',\n  'Agrave',\n  'Aring',\n  'Atilde',\n  'Auml',\n  'COPY',\n  'Ccedil',\n  'ETH',\n  'Eacute',\n  'Ecirc',\n  'Egrave',\n  'Euml',\n  'GT',\n  'Iacute',\n  'Icirc',\n  'Igrave',\n  'Iuml',\n  'LT',\n  'Ntilde',\n  'Oacute',\n  'Ocirc',\n  'Ograve',\n  'Oslash',\n  'Otilde',\n  'Ouml',\n  'QUOT',\n  'REG',\n  'THORN',\n  'Uacute',\n  'Ucirc',\n  'Ugrave',\n  'Uuml',\n  'Yacute',\n  'aacute',\n  'acirc',\n  'acute',\n  'aelig',\n  'agrave',\n  'amp',\n  'aring',\n  'atilde',\n  'auml',\n  'brvbar',\n  'ccedil',\n  'cedil',\n  'cent',\n  'copy',\n  'curren',\n  'deg',\n  'divide',\n  'eacute',\n  'ecirc',\n  'egrave',\n  'eth',\n  'euml',\n  'frac12',\n  'frac14',\n  'frac34',\n  'gt',\n  'iacute',\n  'icirc',\n  'iexcl',\n  'igrave',\n  'iquest',\n  'iuml',\n  'laquo',\n  'lt',\n  'macr',\n  'micro',\n  'middot',\n  'nbsp',\n  'not',\n  'ntilde',\n  'oacute',\n  'ocirc',\n  'ograve',\n  'ordf',\n  'ordm',\n  'oslash',\n  'otilde',\n  'ouml',\n  'para',\n  'plusmn',\n  'pound',\n  'quot',\n  'raquo',\n  'reg',\n  'sect',\n  'shy',\n  'sup1',\n  'sup2',\n  'sup3',\n  'szlig',\n  'thorn',\n  'times',\n  'uacute',\n  'ucirc',\n  'ugrave',\n  'uml',\n  'uuml',\n  'yacute',\n  'yen',\n  'yuml'\n]\n","/**\n * Map of named character references from HTML 4.\n *\n * @type {Record<string, string>}\n */\nexport const characterEntitiesHtml4 = {\n  nbsp: ' ',\n  iexcl: '¡',\n  cent: '¢',\n  pound: '£',\n  curren: '¤',\n  yen: '¥',\n  brvbar: '¦',\n  sect: '§',\n  uml: '¨',\n  copy: '©',\n  ordf: 'ª',\n  laquo: '«',\n  not: '¬',\n  shy: '­',\n  reg: '®',\n  macr: '¯',\n  deg: '°',\n  plusmn: '±',\n  sup2: '²',\n  sup3: '³',\n  acute: '´',\n  micro: 'µ',\n  para: '¶',\n  middot: '·',\n  cedil: '¸',\n  sup1: '¹',\n  ordm: 'º',\n  raquo: '»',\n  frac14: '¼',\n  frac12: '½',\n  frac34: '¾',\n  iquest: '¿',\n  Agrave: 'À',\n  Aacute: 'Á',\n  Acirc: 'Â',\n  Atilde: 'Ã',\n  Auml: 'Ä',\n  Aring: 'Å',\n  AElig: 'Æ',\n  Ccedil: 'Ç',\n  Egrave: 'È',\n  Eacute: 'É',\n  Ecirc: 'Ê',\n  Euml: 'Ë',\n  Igrave: 'Ì',\n  Iacute: 'Í',\n  Icirc: 'Î',\n  Iuml: 'Ï',\n  ETH: 'Ð',\n  Ntilde: 'Ñ',\n  Ograve: 'Ò',\n  Oacute: 'Ó',\n  Ocirc: 'Ô',\n  Otilde: 'Õ',\n  Ouml: 'Ö',\n  times: '×',\n  Oslash: 'Ø',\n  Ugrave: 'Ù',\n  Uacute: 'Ú',\n  Ucirc: 'Û',\n  Uuml: 'Ü',\n  Yacute: 'Ý',\n  THORN: 'Þ',\n  szlig: 'ß',\n  agrave: 'à',\n  aacute: 'á',\n  acirc: 'â',\n  atilde: 'ã',\n  auml: 'ä',\n  aring: 'å',\n  aelig: 'æ',\n  ccedil: 'ç',\n  egrave: 'è',\n  eacute: 'é',\n  ecirc: 'ê',\n  euml: 'ë',\n  igrave: 'ì',\n  iacute: 'í',\n  icirc: 'î',\n  iuml: 'ï',\n  eth: 'ð',\n  ntilde: 'ñ',\n  ograve: 'ò',\n  oacute: 'ó',\n  ocirc: 'ô',\n  otilde: 'õ',\n  ouml: 'ö',\n  divide: '÷',\n  oslash: 'ø',\n  ugrave: 'ù',\n  uacute: 'ú',\n  ucirc: 'û',\n  uuml: 'ü',\n  yacute: 'ý',\n  thorn: 'þ',\n  yuml: 'ÿ',\n  fnof: 'ƒ',\n  Alpha: 'Α',\n  Beta: 'Β',\n  Gamma: 'Γ',\n  Delta: 'Δ',\n  Epsilon: 'Ε',\n  Zeta: 'Ζ',\n  Eta: 'Η',\n  Theta: 'Θ',\n  Iota: 'Ι',\n  Kappa: 'Κ',\n  Lambda: 'Λ',\n  Mu: 'Μ',\n  Nu: 'Ν',\n  Xi: 'Ξ',\n  Omicron: 'Ο',\n  Pi: 'Π',\n  Rho: 'Ρ',\n  Sigma: 'Σ',\n  Tau: 'Τ',\n  Upsilon: 'Υ',\n  Phi: 'Φ',\n  Chi: 'Χ',\n  Psi: 'Ψ',\n  Omega: 'Ω',\n  alpha: 'α',\n  beta: 'β',\n  gamma: 'γ',\n  delta: 'δ',\n  epsilon: 'ε',\n  zeta: 'ζ',\n  eta: 'η',\n  theta: 'θ',\n  iota: 'ι',\n  kappa: 'κ',\n  lambda: 'λ',\n  mu: 'μ',\n  nu: 'ν',\n  xi: 'ξ',\n  omicron: 'ο',\n  pi: 'π',\n  rho: 'ρ',\n  sigmaf: 'ς',\n  sigma: 'σ',\n  tau: 'τ',\n  upsilon: 'υ',\n  phi: 'φ',\n  chi: 'χ',\n  psi: 'ψ',\n  omega: 'ω',\n  thetasym: 'ϑ',\n  upsih: 'ϒ',\n  piv: 'ϖ',\n  bull: '•',\n  hellip: '…',\n  prime: '′',\n  Prime: '″',\n  oline: '‾',\n  frasl: '⁄',\n  weierp: '℘',\n  image: 'ℑ',\n  real: 'ℜ',\n  trade: '™',\n  alefsym: 'ℵ',\n  larr: '←',\n  uarr: '↑',\n  rarr: '→',\n  darr: '↓',\n  harr: '↔',\n  crarr: '↵',\n  lArr: '⇐',\n  uArr: '⇑',\n  rArr: '⇒',\n  dArr: '⇓',\n  hArr: '⇔',\n  forall: '∀',\n  part: '∂',\n  exist: '∃',\n  empty: '∅',\n  nabla: '∇',\n  isin: '∈',\n  notin: '∉',\n  ni: '∋',\n  prod: '∏',\n  sum: '∑',\n  minus: '−',\n  lowast: '∗',\n  radic: '√',\n  prop: '∝',\n  infin: '∞',\n  ang: '∠',\n  and: '∧',\n  or: '∨',\n  cap: '∩',\n  cup: '∪',\n  int: '∫',\n  there4: '∴',\n  sim: '∼',\n  cong: '≅',\n  asymp: '≈',\n  ne: '≠',\n  equiv: '≡',\n  le: '≤',\n  ge: '≥',\n  sub: '⊂',\n  sup: '⊃',\n  nsub: '⊄',\n  sube: '⊆',\n  supe: '⊇',\n  oplus: '⊕',\n  otimes: '⊗',\n  perp: '⊥',\n  sdot: '⋅',\n  lceil: '⌈',\n  rceil: '⌉',\n  lfloor: '⌊',\n  rfloor: '⌋',\n  lang: '〈',\n  rang: '〉',\n  loz: '◊',\n  spades: '♠',\n  clubs: '♣',\n  hearts: '♥',\n  diams: '♦',\n  quot: '\"',\n  amp: '&',\n  lt: '<',\n  gt: '>',\n  OElig: 'Œ',\n  oelig: 'œ',\n  Scaron: 'Š',\n  scaron: 'š',\n  Yuml: 'Ÿ',\n  circ: 'ˆ',\n  tilde: '˜',\n  ensp: ' ',\n  emsp: ' ',\n  thinsp: ' ',\n  zwnj: '‌',\n  zwj: '‍',\n  lrm: '‎',\n  rlm: '‏',\n  ndash: '–',\n  mdash: '—',\n  lsquo: '‘',\n  rsquo: '’',\n  sbquo: '‚',\n  ldquo: '“',\n  rdquo: '”',\n  bdquo: '„',\n  dagger: '†',\n  Dagger: '‡',\n  permil: '‰',\n  lsaquo: '‹',\n  rsaquo: '›',\n  euro: '€'\n}\n","/**\n * List of legacy (that don’t need a trailing `;`) named references which could,\n * depending on what follows them, turn into a different meaning\n *\n * @type {Array<string>}\n */\nexport const dangerous = [\n  'cent',\n  'copy',\n  'divide',\n  'gt',\n  'lt',\n  'not',\n  'para',\n  'times'\n]\n","import {characterEntitiesLegacy} from 'character-entities-legacy'\nimport {characterEntitiesHtml4} from 'character-entities-html4'\nimport {dangerous} from '../constant/dangerous.js'\n\nconst own = {}.hasOwnProperty\n\n/**\n * `characterEntitiesHtml4` but inverted.\n *\n * @type {Record<string, string>}\n */\nconst characters = {}\n\n/** @type {string} */\nlet key\n\nfor (key in characterEntitiesHtml4) {\n  if (own.call(characterEntitiesHtml4, key)) {\n    characters[characterEntitiesHtml4[key]] = key\n  }\n}\n\nconst notAlphanumericRegex = /[^\\dA-Za-z]/\n\n/**\n * Configurable ways to encode characters as named references.\n *\n * @param {number} code\n * @param {number} next\n * @param {boolean|undefined} omit\n * @param {boolean|undefined} attribute\n * @returns {string}\n */\nexport function toNamed(code, next, omit, attribute) {\n  const character = String.fromCharCode(code)\n\n  if (own.call(characters, character)) {\n    const name = characters[character]\n    const value = '&' + name\n\n    if (\n      omit &&\n      characterEntitiesLegacy.includes(name) &&\n      !dangerous.includes(name) &&\n      (!attribute ||\n        (next &&\n          next !== 61 /* `=` */ &&\n          notAlphanumericRegex.test(String.fromCharCode(next))))\n    ) {\n      return value\n    }\n\n    return value + ';'\n  }\n\n  return ''\n}\n","/**\n * @typedef FormatSmartOptions\n * @property {boolean} [useNamedReferences=false]\n *   Prefer named character references (`&amp;`) where possible.\n * @property {boolean} [useShortestReferences=false]\n *   Prefer the shortest possible reference, if that results in less bytes.\n *   **Note**: `useNamedReferences` can be omitted when using `useShortestReferences`.\n * @property {boolean} [omitOptionalSemicolons=false]\n *   Whether to omit semicolons when possible.\n *   **Note**: This creates what HTML calls “parse errors” but is otherwise still valid HTML — don’t use this except when building a minifier.\n *   Omitting semicolons is possible for certain named and numeric references in some cases.\n * @property {boolean} [attribute=false]\n *   Create character references which don’t fail in attributes.\n *   **Note**: `attribute` only applies when operating dangerously with\n *   `omitOptionalSemicolons: true`.\n */\n\nimport {toHexadecimal} from './to-hexadecimal.js'\nimport {toDecimal} from './to-decimal.js'\nimport {toNamed} from './to-named.js'\n\n/**\n * Configurable ways to encode a character yielding pretty or small results.\n *\n * @param {number} code\n * @param {number} next\n * @param {FormatSmartOptions} options\n * @returns {string}\n */\nexport function formatSmart(code, next, options) {\n  let numeric = toHexadecimal(code, next, options.omitOptionalSemicolons)\n  /** @type {string|undefined} */\n  let named\n\n  if (options.useNamedReferences || options.useShortestReferences) {\n    named = toNamed(\n      code,\n      next,\n      options.omitOptionalSemicolons,\n      options.attribute\n    )\n  }\n\n  // Use the shortest numeric reference when requested.\n  // A simple algorithm would use decimal for all code points under 100, as\n  // those are shorter than hexadecimal:\n  //\n  // * `&#99;` vs `&#x63;` (decimal shorter)\n  // * `&#100;` vs `&#x64;` (equal)\n  //\n  // However, because we take `next` into consideration when `omit` is used,\n  // And it would be possible that decimals are shorter on bigger values as\n  // well if `next` is hexadecimal but not decimal, we instead compare both.\n  if (\n    (options.useShortestReferences || !named) &&\n    options.useShortestReferences\n  ) {\n    const decimal = toDecimal(code, next, options.omitOptionalSemicolons)\n\n    if (decimal.length < numeric.length) {\n      numeric = decimal\n    }\n  }\n\n  return named &&\n    (!options.useShortestReferences || named.length < numeric.length)\n    ? named\n    : numeric\n}\n","/**\n * @typedef {import('./core.js').CoreOptions & import('./util/format-smart.js').FormatSmartOptions} Options\n * @typedef {import('./core.js').CoreOptions} LightOptions\n */\n\nimport {core} from './core.js'\nimport {formatSmart} from './util/format-smart.js'\nimport {formatBasic} from './util/format-basic.js'\n\n/**\n * Encode special characters in `value`.\n *\n * @param {string} value\n *   Value to encode.\n * @param {Options} [options]\n *   Configuration.\n * @returns {string}\n *   Encoded value.\n */\nexport function stringifyEntities(value, options) {\n  return core(value, Object.assign({format: formatSmart}, options))\n}\n\n/**\n * Encode special characters in `value` as hexadecimals.\n *\n * @param {string} value\n *   Value to encode.\n * @param {LightOptions} [options]\n *   Configuration.\n * @returns {string}\n *   Encoded value.\n */\nexport function stringifyEntitiesLight(value, options) {\n  return core(value, Object.assign({format: formatBasic}, options))\n}\n","/**\n * @import {Comment, Parents} from 'hast'\n * @import {State} from '../index.js'\n */\n\nimport {stringifyEntities} from 'stringify-entities'\n\nconst htmlCommentRegex = /^>|^->|<!--|-->|--!>|<!-$/g\n\n// Declare arrays as variables so it can be cached by `stringifyEntities`\nconst bogusCommentEntitySubset = ['>']\nconst commentEntitySubset = ['<', '>']\n\n/**\n * Serialize a comment.\n *\n * @param {Comment} node\n *   Node to handle.\n * @param {number | undefined} _1\n *   Index of `node` in `parent.\n * @param {Parents | undefined} _2\n *   Parent of `node`.\n * @param {State} state\n *   Info passed around about the current state.\n * @returns {string}\n *   Serialized node.\n */\nexport function comment(node, _1, _2, state) {\n  // See: <https://html.spec.whatwg.org/multipage/syntax.html#comments>\n  return state.settings.bogusComments\n    ? '<?' +\n        stringifyEntities(\n          node.value,\n          Object.assign({}, state.settings.characterReferences, {\n            subset: bogusCommentEntitySubset\n          })\n        ) +\n        '>'\n    : '<!--' + node.value.replace(htmlCommentRegex, encode) + '-->'\n\n  /**\n   * @param {string} $0\n   */\n  function encode($0) {\n    return stringifyEntities(\n      $0,\n      Object.assign({}, state.settings.characterReferences, {\n        subset: commentEntitySubset\n      })\n    )\n  }\n}\n","/**\n * @import {Doctype, Parents} from 'hast'\n * @import {State} from '../index.js'\n */\n\n/**\n * Serialize a doctype.\n *\n * @param {Doctype} _1\n *   Node to handle.\n * @param {number | undefined} _2\n *   Index of `node` in `parent.\n * @param {Parents | undefined} _3\n *   Parent of `node`.\n * @param {State} state\n *   Info passed around about the current state.\n * @returns {string}\n *   Serialized node.\n */\nexport function doctype(_1, _2, _3, state) {\n  return (\n    '<!' +\n    (state.settings.upperDoctype ? 'DOCTYPE' : 'doctype') +\n    (state.settings.tightDoctype ? '' : ' ') +\n    'html>'\n  )\n}\n","/**\n * @typedef {import('hast').Nodes} Nodes\n */\n\n// HTML whitespace expression.\n// See <https://infra.spec.whatwg.org/#ascii-whitespace>.\nconst re = /[ \\t\\n\\f\\r]/g\n\n/**\n * Check if the given value is *inter-element whitespace*.\n *\n * @param {Nodes | string} thing\n *   Thing to check (`Node` or `string`).\n * @returns {boolean}\n *   Whether the `value` is inter-element whitespace (`boolean`): consisting of\n *   zero or more of space, tab (`\\t`), line feed (`\\n`), carriage return\n *   (`\\r`), or form feed (`\\f`); if a node is passed it must be a `Text` node,\n *   whose `value` field is checked.\n */\nexport function whitespace(thing) {\n  return typeof thing === 'object'\n    ? thing.type === 'text'\n      ? empty(thing.value)\n      : false\n    : empty(thing)\n}\n\n/**\n * @param {string} value\n * @returns {boolean}\n */\nfunction empty(value) {\n  return value.replace(re, '') === ''\n}\n","/**\n * @import {Parents, RootContent} from 'hast'\n */\n\nimport {whitespace} from 'hast-util-whitespace'\n\nexport const siblingAfter = siblings(1)\nexport const siblingBefore = siblings(-1)\n\n/** @type {Array<RootContent>} */\nconst emptyChildren = []\n\n/**\n * Factory to check siblings in a direction.\n *\n * @param {number} increment\n */\nfunction siblings(increment) {\n  return sibling\n\n  /**\n   * Find applicable siblings in a direction.\n   *\n   * @template {Parents} Parent\n   *   Parent type.\n   * @param {Parent | undefined} parent\n   *   Parent.\n   * @param {number | undefined} index\n   *   Index of child in `parent`.\n   * @param {boolean | undefined} [includeWhitespace=false]\n   *   Whether to include whitespace (default: `false`).\n   * @returns {Parent extends {children: Array<infer Child>} ? Child | undefined : never}\n   *   Child of parent.\n   */\n  function sibling(parent, index, includeWhitespace) {\n    const siblings = parent ? parent.children : emptyChildren\n    let offset = (index || 0) + increment\n    let next = siblings[offset]\n\n    if (!includeWhitespace) {\n      while (next && whitespace(next)) {\n        offset += increment\n        next = siblings[offset]\n      }\n    }\n\n    // @ts-expect-error: it’s a correct child.\n    return next\n  }\n}\n","/**\n * @import {Element, Parents} from 'hast'\n */\n\n/**\n * @callback OmitHandle\n *   Check if a tag can be omitted.\n * @param {Element} element\n *   Element to check.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether to omit a tag.\n *\n */\n\nconst own = {}.hasOwnProperty\n\n/**\n * Factory to check if a given node can have a tag omitted.\n *\n * @param {Record<string, OmitHandle>} handlers\n *   Omission handlers, where each key is a tag name, and each value is the\n *   corresponding handler.\n * @returns {OmitHandle}\n *   Whether to omit a tag of an element.\n */\nexport function omission(handlers) {\n  return omit\n\n  /**\n   * Check if a given node can have a tag omitted.\n   *\n   * @type {OmitHandle}\n   */\n  function omit(node, index, parent) {\n    return (\n      own.call(handlers, node.tagName) &&\n      handlers[node.tagName](node, index, parent)\n    )\n  }\n}\n","/**\n * @import {Element, Parents} from 'hast'\n */\n\nimport {whitespace} from 'hast-util-whitespace'\nimport {siblingAfter} from './util/siblings.js'\nimport {omission} from './omission.js'\n\nexport const closing = omission({\n  body,\n  caption: headOrColgroupOrCaption,\n  colgroup: headOrColgroupOrCaption,\n  dd,\n  dt,\n  head: headOrColgroupOrCaption,\n  html,\n  li,\n  optgroup,\n  option,\n  p,\n  rp: rubyElement,\n  rt: rubyElement,\n  tbody,\n  td: cells,\n  tfoot,\n  th: cells,\n  thead,\n  tr\n})\n\n/**\n * Macro for `</head>`, `</colgroup>`, and `</caption>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction headOrColgroupOrCaption(_, index, parent) {\n  const next = siblingAfter(parent, index, true)\n  return (\n    !next ||\n    (next.type !== 'comment' &&\n      !(next.type === 'text' && whitespace(next.value.charAt(0))))\n  )\n}\n\n/**\n * Whether to omit `</html>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction html(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return !next || next.type !== 'comment'\n}\n\n/**\n * Whether to omit `</body>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction body(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return !next || next.type !== 'comment'\n}\n\n/**\n * Whether to omit `</p>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction p(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return next\n    ? next.type === 'element' &&\n        (next.tagName === 'address' ||\n          next.tagName === 'article' ||\n          next.tagName === 'aside' ||\n          next.tagName === 'blockquote' ||\n          next.tagName === 'details' ||\n          next.tagName === 'div' ||\n          next.tagName === 'dl' ||\n          next.tagName === 'fieldset' ||\n          next.tagName === 'figcaption' ||\n          next.tagName === 'figure' ||\n          next.tagName === 'footer' ||\n          next.tagName === 'form' ||\n          next.tagName === 'h1' ||\n          next.tagName === 'h2' ||\n          next.tagName === 'h3' ||\n          next.tagName === 'h4' ||\n          next.tagName === 'h5' ||\n          next.tagName === 'h6' ||\n          next.tagName === 'header' ||\n          next.tagName === 'hgroup' ||\n          next.tagName === 'hr' ||\n          next.tagName === 'main' ||\n          next.tagName === 'menu' ||\n          next.tagName === 'nav' ||\n          next.tagName === 'ol' ||\n          next.tagName === 'p' ||\n          next.tagName === 'pre' ||\n          next.tagName === 'section' ||\n          next.tagName === 'table' ||\n          next.tagName === 'ul')\n    : !parent ||\n        // Confusing parent.\n        !(\n          parent.type === 'element' &&\n          (parent.tagName === 'a' ||\n            parent.tagName === 'audio' ||\n            parent.tagName === 'del' ||\n            parent.tagName === 'ins' ||\n            parent.tagName === 'map' ||\n            parent.tagName === 'noscript' ||\n            parent.tagName === 'video')\n        )\n}\n\n/**\n * Whether to omit `</li>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction li(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return !next || (next.type === 'element' && next.tagName === 'li')\n}\n\n/**\n * Whether to omit `</dt>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction dt(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return Boolean(\n    next &&\n      next.type === 'element' &&\n      (next.tagName === 'dt' || next.tagName === 'dd')\n  )\n}\n\n/**\n * Whether to omit `</dd>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction dd(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return (\n    !next ||\n    (next.type === 'element' &&\n      (next.tagName === 'dt' || next.tagName === 'dd'))\n  )\n}\n\n/**\n * Whether to omit `</rt>` or `</rp>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction rubyElement(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return (\n    !next ||\n    (next.type === 'element' &&\n      (next.tagName === 'rp' || next.tagName === 'rt'))\n  )\n}\n\n/**\n * Whether to omit `</optgroup>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction optgroup(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return !next || (next.type === 'element' && next.tagName === 'optgroup')\n}\n\n/**\n * Whether to omit `</option>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction option(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return (\n    !next ||\n    (next.type === 'element' &&\n      (next.tagName === 'option' || next.tagName === 'optgroup'))\n  )\n}\n\n/**\n * Whether to omit `</thead>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction thead(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return Boolean(\n    next &&\n      next.type === 'element' &&\n      (next.tagName === 'tbody' || next.tagName === 'tfoot')\n  )\n}\n\n/**\n * Whether to omit `</tbody>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction tbody(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return (\n    !next ||\n    (next.type === 'element' &&\n      (next.tagName === 'tbody' || next.tagName === 'tfoot'))\n  )\n}\n\n/**\n * Whether to omit `</tfoot>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction tfoot(_, index, parent) {\n  return !siblingAfter(parent, index)\n}\n\n/**\n * Whether to omit `</tr>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction tr(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return !next || (next.type === 'element' && next.tagName === 'tr')\n}\n\n/**\n * Whether to omit `</td>` or `</th>`.\n *\n * @param {Element} _\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the closing tag can be omitted.\n */\nfunction cells(_, index, parent) {\n  const next = siblingAfter(parent, index)\n  return (\n    !next ||\n    (next.type === 'element' &&\n      (next.tagName === 'td' || next.tagName === 'th'))\n  )\n}\n","/**\n * @import {Element, Parents} from 'hast'\n */\n\nimport {whitespace} from 'hast-util-whitespace'\nimport {siblingAfter, siblingBefore} from './util/siblings.js'\nimport {closing} from './closing.js'\nimport {omission} from './omission.js'\n\nexport const opening = omission({\n  body,\n  colgroup,\n  head,\n  html,\n  tbody\n})\n\n/**\n * Whether to omit `<html>`.\n *\n * @param {Element} node\n *   Element.\n * @returns {boolean}\n *   Whether the opening tag can be omitted.\n */\nfunction html(node) {\n  const head = siblingAfter(node, -1)\n  return !head || head.type !== 'comment'\n}\n\n/**\n * Whether to omit `<head>`.\n *\n * @param {Element} node\n *   Element.\n * @returns {boolean}\n *   Whether the opening tag can be omitted.\n */\nfunction head(node) {\n  /** @type {Set<string>} */\n  const seen = new Set()\n\n  // Whether `srcdoc` or not,\n  // make sure the content model at least doesn’t have too many `base`s/`title`s.\n  for (const child of node.children) {\n    if (\n      child.type === 'element' &&\n      (child.tagName === 'base' || child.tagName === 'title')\n    ) {\n      if (seen.has(child.tagName)) return false\n      seen.add(child.tagName)\n    }\n  }\n\n  // “May be omitted if the element is empty,\n  // or if the first thing inside the head element is an element.”\n  const child = node.children[0]\n  return !child || child.type === 'element'\n}\n\n/**\n * Whether to omit `<body>`.\n *\n * @param {Element} node\n *   Element.\n * @returns {boolean}\n *   Whether the opening tag can be omitted.\n */\nfunction body(node) {\n  const head = siblingAfter(node, -1, true)\n\n  return (\n    !head ||\n    (head.type !== 'comment' &&\n      !(head.type === 'text' && whitespace(head.value.charAt(0))) &&\n      !(\n        head.type === 'element' &&\n        (head.tagName === 'meta' ||\n          head.tagName === 'link' ||\n          head.tagName === 'script' ||\n          head.tagName === 'style' ||\n          head.tagName === 'template')\n      ))\n  )\n}\n\n/**\n * Whether to omit `<colgroup>`.\n * The spec describes some logic for the opening tag, but it’s easier to\n * implement in the closing tag, to the same effect, so we handle it there\n * instead.\n *\n * @param {Element} node\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the opening tag can be omitted.\n */\nfunction colgroup(node, index, parent) {\n  const previous = siblingBefore(parent, index)\n  const head = siblingAfter(node, -1, true)\n\n  // Previous colgroup was already omitted.\n  if (\n    parent &&\n    previous &&\n    previous.type === 'element' &&\n    previous.tagName === 'colgroup' &&\n    closing(previous, parent.children.indexOf(previous), parent)\n  ) {\n    return false\n  }\n\n  return Boolean(head && head.type === 'element' && head.tagName === 'col')\n}\n\n/**\n * Whether to omit `<tbody>`.\n *\n * @param {Element} node\n *   Element.\n * @param {number | undefined} index\n *   Index of element in parent.\n * @param {Parents | undefined} parent\n *   Parent of element.\n * @returns {boolean}\n *   Whether the opening tag can be omitted.\n */\nfunction tbody(node, index, parent) {\n  const previous = siblingBefore(parent, index)\n  const head = siblingAfter(node, -1)\n\n  // Previous table section was already omitted.\n  if (\n    parent &&\n    previous &&\n    previous.type === 'element' &&\n    (previous.tagName === 'thead' || previous.tagName === 'tbody') &&\n    closing(previous, parent.children.indexOf(previous), parent)\n  ) {\n    return false\n  }\n\n  return Boolean(head && head.type === 'element' && head.tagName === 'tr')\n}\n","/**\n * @import {Element, Parents, Properties} from 'hast'\n * @import {State} from '../index.js'\n */\n\nimport {ccount} from 'ccount'\nimport {stringify as commas} from 'comma-separated-tokens'\nimport {find, svg} from 'property-information'\nimport {stringify as spaces} from 'space-separated-tokens'\nimport {stringifyEntities} from 'stringify-entities'\nimport {closing} from '../omission/closing.js'\nimport {opening} from '../omission/opening.js'\n\n/**\n * Maps of subsets.\n *\n * Each value is a matrix of tuples.\n * The value at `0` causes parse errors, the value at `1` is valid.\n * Of both, the value at `0` is unsafe, and the value at `1` is safe.\n *\n * @type {Record<'double' | 'name' | 'single' | 'unquoted', Array<[Array<string>, Array<string>]>>}\n */\nconst constants = {\n  // See: <https://html.spec.whatwg.org/#attribute-name-state>.\n  name: [\n    ['\\t\\n\\f\\r &/=>'.split(''), '\\t\\n\\f\\r \"&\\'/=>`'.split('')],\n    ['\\0\\t\\n\\f\\r \"&\\'/<=>'.split(''), '\\0\\t\\n\\f\\r \"&\\'/<=>`'.split('')]\n  ],\n  // See: <https://html.spec.whatwg.org/#attribute-value-(unquoted)-state>.\n  unquoted: [\n    ['\\t\\n\\f\\r &>'.split(''), '\\0\\t\\n\\f\\r \"&\\'<=>`'.split('')],\n    ['\\0\\t\\n\\f\\r \"&\\'<=>`'.split(''), '\\0\\t\\n\\f\\r \"&\\'<=>`'.split('')]\n  ],\n  // See: <https://html.spec.whatwg.org/#attribute-value-(single-quoted)-state>.\n  single: [\n    [\"&'\".split(''), '\"&\\'`'.split('')],\n    [\"\\0&'\".split(''), '\\0\"&\\'`'.split('')]\n  ],\n  // See: <https://html.spec.whatwg.org/#attribute-value-(double-quoted)-state>.\n  double: [\n    ['\"&'.split(''), '\"&\\'`'.split('')],\n    ['\\0\"&'.split(''), '\\0\"&\\'`'.split('')]\n  ]\n}\n\n/**\n * Serialize an element node.\n *\n * @param {Element} node\n *   Node to handle.\n * @param {number | undefined} index\n *   Index of `node` in `parent.\n * @param {Parents | undefined} parent\n *   Parent of `node`.\n * @param {State} state\n *   Info passed around about the current state.\n * @returns {string}\n *   Serialized node.\n */\nexport function element(node, index, parent, state) {\n  const schema = state.schema\n  const omit = schema.space === 'svg' ? false : state.settings.omitOptionalTags\n  let selfClosing =\n    schema.space === 'svg'\n      ? state.settings.closeEmptyElements\n      : state.settings.voids.includes(node.tagName.toLowerCase())\n  /** @type {Array<string>} */\n  const parts = []\n  /** @type {string} */\n  let last\n\n  if (schema.space === 'html' && node.tagName === 'svg') {\n    state.schema = svg\n  }\n\n  const attributes = serializeAttributes(state, node.properties)\n\n  const content = state.all(\n    schema.space === 'html' && node.tagName === 'template' ? node.content : node\n  )\n\n  state.schema = schema\n\n  // If the node is categorised as void, but it has children, remove the\n  // categorisation.\n  // This enables for example `menuitem`s, which are void in W3C HTML but not\n  // void in WHATWG HTML, to be stringified properly.\n  // Note: `menuitem` has since been removed from the HTML spec, and so is no\n  // longer void.\n  if (content) selfClosing = false\n\n  if (attributes || !omit || !opening(node, index, parent)) {\n    parts.push('<', node.tagName, attributes ? ' ' + attributes : '')\n\n    if (\n      selfClosing &&\n      (schema.space === 'svg' || state.settings.closeSelfClosing)\n    ) {\n      last = attributes.charAt(attributes.length - 1)\n      if (\n        !state.settings.tightSelfClosing ||\n        last === '/' ||\n        (last && last !== '\"' && last !== \"'\")\n      ) {\n        parts.push(' ')\n      }\n\n      parts.push('/')\n    }\n\n    parts.push('>')\n  }\n\n  parts.push(content)\n\n  if (!selfClosing && (!omit || !closing(node, index, parent))) {\n    parts.push('</' + node.tagName + '>')\n  }\n\n  return parts.join('')\n}\n\n/**\n * @param {State} state\n * @param {Properties | null | undefined} properties\n * @returns {string}\n */\nfunction serializeAttributes(state, properties) {\n  /** @type {Array<string>} */\n  const values = []\n  let index = -1\n  /** @type {string} */\n  let key\n\n  if (properties) {\n    for (key in properties) {\n      if (properties[key] !== null && properties[key] !== undefined) {\n        const value = serializeAttribute(state, key, properties[key])\n        if (value) values.push(value)\n      }\n    }\n  }\n\n  while (++index < values.length) {\n    const last = state.settings.tightAttributes\n      ? values[index].charAt(values[index].length - 1)\n      : undefined\n\n    // In tight mode, don’t add a space after quoted attributes.\n    if (index !== values.length - 1 && last !== '\"' && last !== \"'\") {\n      values[index] += ' '\n    }\n  }\n\n  return values.join('')\n}\n\n/**\n * @param {State} state\n * @param {string} key\n * @param {Properties[keyof Properties]} value\n * @returns {string}\n */\nfunction serializeAttribute(state, key, value) {\n  const info = find(state.schema, key)\n  const x =\n    state.settings.allowParseErrors && state.schema.space === 'html' ? 0 : 1\n  const y = state.settings.allowDangerousCharacters ? 0 : 1\n  let quote = state.quote\n  /** @type {string | undefined} */\n  let result\n\n  if (info.overloadedBoolean && (value === info.attribute || value === '')) {\n    value = true\n  } else if (\n    (info.boolean || info.overloadedBoolean) &&\n    (typeof value !== 'string' || value === info.attribute || value === '')\n  ) {\n    value = Boolean(value)\n  }\n\n  if (\n    value === null ||\n    value === undefined ||\n    value === false ||\n    (typeof value === 'number' && Number.isNaN(value))\n  ) {\n    return ''\n  }\n\n  const name = stringifyEntities(\n    info.attribute,\n    Object.assign({}, state.settings.characterReferences, {\n      // Always encode without parse errors in non-HTML.\n      subset: constants.name[x][y]\n    })\n  )\n\n  // No value.\n  // There is currently only one boolean property in SVG: `[download]` on\n  // `<a>`.\n  // This property does not seem to work in browsers (Firefox, Safari, Chrome),\n  // so I can’t test if dropping the value works.\n  // But I assume that it should:\n  //\n  // ```html\n  // <!doctype html>\n  // <svg viewBox=\"0 0 100 100\">\n  //   <a href=https://example.com download>\n  //     <circle cx=50 cy=40 r=35 />\n  //   </a>\n  // </svg>\n  // ```\n  //\n  // See: <https://github.com/wooorm/property-information/blob/main/lib/svg.js>\n  if (value === true) return name\n\n  // `spaces` doesn’t accept a second argument, but it’s given here just to\n  // keep the code cleaner.\n  value = Array.isArray(value)\n    ? (info.commaSeparated ? commas : spaces)(value, {\n        padLeft: !state.settings.tightCommaSeparatedLists\n      })\n    : String(value)\n\n  if (state.settings.collapseEmptyAttributes && !value) return name\n\n  // Check unquoted value.\n  if (state.settings.preferUnquoted) {\n    result = stringifyEntities(\n      value,\n      Object.assign({}, state.settings.characterReferences, {\n        attribute: true,\n        subset: constants.unquoted[x][y]\n      })\n    )\n  }\n\n  // If we don’t want unquoted, or if `value` contains character references when\n  // unquoted…\n  if (result !== value) {\n    // If the alternative is less common than `quote`, switch.\n    if (\n      state.settings.quoteSmart &&\n      ccount(value, quote) > ccount(value, state.alternative)\n    ) {\n      quote = state.alternative\n    }\n\n    result =\n      quote +\n      stringifyEntities(\n        value,\n        Object.assign({}, state.settings.characterReferences, {\n          // Always encode without parse errors in non-HTML.\n          subset: (quote === \"'\" ? constants.single : constants.double)[x][y],\n          attribute: true\n        })\n      ) +\n      quote\n  }\n\n  // Don’t add a `=` for unquoted empties.\n  return name + (result ? '=' + result : result)\n}\n","/**\n * @import {Parents, Text} from 'hast'\n * @import {Raw} from 'mdast-util-to-hast'\n * @import {State} from '../index.js'\n */\n\nimport {stringifyEntities} from 'stringify-entities'\n\n// Declare array as variable so it can be cached by `stringifyEntities`\nconst textEntitySubset = ['<', '&']\n\n/**\n * Serialize a text node.\n *\n * @param {Raw | Text} node\n *   Node to handle.\n * @param {number | undefined} _\n *   Index of `node` in `parent.\n * @param {Parents | undefined} parent\n *   Parent of `node`.\n * @param {State} state\n *   Info passed around about the current state.\n * @returns {string}\n *   Serialized node.\n */\nexport function text(node, _, parent, state) {\n  // Check if content of `node` should be escaped.\n  return parent &&\n    parent.type === 'element' &&\n    (parent.tagName === 'script' || parent.tagName === 'style')\n    ? node.value\n    : stringifyEntities(\n        node.value,\n        Object.assign({}, state.settings.characterReferences, {\n          subset: textEntitySubset\n        })\n      )\n}\n","/**\n * @import {Parents} from 'hast'\n * @import {Raw} from 'mdast-util-to-hast'\n * @import {State} from '../index.js'\n */\n\nimport {text} from './text.js'\n\n/**\n * Serialize a raw node.\n *\n * @param {Raw} node\n *   Node to handle.\n * @param {number | undefined} index\n *   Index of `node` in `parent.\n * @param {Parents | undefined} parent\n *   Parent of `node`.\n * @param {State} state\n *   Info passed around about the current state.\n * @returns {string}\n *   Serialized node.\n */\nexport function raw(node, index, parent, state) {\n  return state.settings.allowDangerousHtml\n    ? node.value\n    : text(node, index, parent, state)\n}\n","/**\n * @import {Parents, Root} from 'hast'\n * @import {State} from '../index.js'\n */\n\n/**\n * Serialize a root.\n *\n * @param {Root} node\n *   Node to handle.\n * @param {number | undefined} _1\n *   Index of `node` in `parent.\n * @param {Parents | undefined} _2\n *   Parent of `node`.\n * @param {State} state\n *   Info passed around about the current state.\n * @returns {string}\n *   Serialized node.\n */\nexport function root(node, _1, _2, state) {\n  return state.all(node)\n}\n","/**\n * @import {Nodes, Parents} from 'hast'\n * @import {State} from '../index.js'\n */\n\nimport {zwitch} from 'zwitch'\nimport {comment} from './comment.js'\nimport {doctype} from './doctype.js'\nimport {element} from './element.js'\nimport {raw} from './raw.js'\nimport {root} from './root.js'\nimport {text} from './text.js'\n\n/**\n * @type {(node: Nodes, index: number | undefined, parent: Parents | undefined, state: State) => string}\n */\nexport const handle = zwitch('type', {\n  invalid,\n  unknown,\n  handlers: {comment, doctype, element, raw, root, text}\n})\n\n/**\n * Fail when a non-node is found in the tree.\n *\n * @param {unknown} node\n *   Unknown value.\n * @returns {never}\n *   Never.\n */\nfunction invalid(node) {\n  throw new Error('Expected node, not `' + node + '`')\n}\n\n/**\n * Fail when a node with an unknown type is found in the tree.\n *\n * @param {unknown} node_\n *  Unknown node.\n * @returns {never}\n *   Never.\n */\nfunction unknown(node_) {\n  // `type` is guaranteed by runtime JS.\n  const node = /** @type {Nodes} */ (node_)\n  throw new Error('Cannot compile unknown node `' + node.type + '`')\n}\n","/**\n * @import {Nodes, Parents, RootContent} from 'hast'\n * @import {Schema} from 'property-information'\n * @import {Options as StringifyEntitiesOptions} from 'stringify-entities'\n */\n\n/**\n * @typedef {Omit<StringifyEntitiesOptions, 'attribute' | 'escapeOnly' | 'subset'>} CharacterReferences\n *\n * @typedef Options\n *   Configuration.\n * @property {boolean | null | undefined} [allowDangerousCharacters=false]\n *   Do not encode some characters which cause XSS vulnerabilities in older\n *   browsers (default: `false`).\n *\n *   > ⚠️ **Danger**: only set this if you completely trust the content.\n * @property {boolean | null | undefined} [allowDangerousHtml=false]\n *   Allow `raw` nodes and insert them as raw HTML (default: `false`).\n *\n *   When `false`, `Raw` nodes are encoded.\n *\n *   > ⚠️ **Danger**: only set this if you completely trust the content.\n * @property {boolean | null | undefined} [allowParseErrors=false]\n *   Do not encode characters which cause parse errors (even though they work),\n *   to save bytes (default: `false`).\n *\n *   Not used in the SVG space.\n *\n *   > 👉 **Note**: intentionally creates parse errors in markup (how parse\n *   > errors are handled is well defined, so this works but isn’t pretty).\n * @property {boolean | null | undefined} [bogusComments=false]\n *   Use “bogus comments” instead of comments to save byes: `<?charlie>`\n *   instead of `<!--charlie-->` (default: `false`).\n *\n *   > 👉 **Note**: intentionally creates parse errors in markup (how parse\n *   > errors are handled is well defined, so this works but isn’t pretty).\n * @property {CharacterReferences | null | undefined} [characterReferences]\n *   Configure how to serialize character references (optional).\n * @property {boolean | null | undefined} [closeEmptyElements=false]\n *   Close SVG elements without any content with slash (`/`) on the opening tag\n *   instead of an end tag: `<circle />` instead of `<circle></circle>`\n *   (default: `false`).\n *\n *   See `tightSelfClosing` to control whether a space is used before the\n *   slash.\n *\n *   Not used in the HTML space.\n * @property {boolean | null | undefined} [closeSelfClosing=false]\n *   Close self-closing nodes with an extra slash (`/`): `<img />` instead of\n *   `<img>` (default: `false`).\n *\n *   See `tightSelfClosing` to control whether a space is used before the\n *   slash.\n *\n *   Not used in the SVG space.\n * @property {boolean | null | undefined} [collapseEmptyAttributes=false]\n *   Collapse empty attributes: get `class` instead of `class=\"\"` (default:\n *   `false`).\n *\n *   Not used in the SVG space.\n *\n *   > 👉 **Note**: boolean attributes (such as `hidden`) are always collapsed.\n * @property {boolean | null | undefined} [omitOptionalTags=false]\n *   Omit optional opening and closing tags (default: `false`).\n *\n *   For example, in `<ol><li>one</li><li>two</li></ol>`, both `</li>` closing\n *   tags can be omitted.\n *   The first because it’s followed by another `li`, the last because it’s\n *   followed by nothing.\n *\n *   Not used in the SVG space.\n * @property {boolean | null | undefined} [preferUnquoted=false]\n *   Leave attributes unquoted if that results in less bytes (default: `false`).\n *\n *   Not used in the SVG space.\n * @property {boolean | null | undefined} [quoteSmart=false]\n *   Use the other quote if that results in less bytes (default: `false`).\n * @property {Quote | null | undefined} [quote='\"']\n *   Preferred quote to use (default: `'\"'`).\n * @property {Space | null | undefined} [space='html']\n *   When an `<svg>` element is found in the HTML space, this package already\n *   automatically switches to and from the SVG space when entering and exiting\n *   it (default: `'html'`).\n *\n *   > 👉 **Note**: hast is not XML.\n *   > It supports SVG as embedded in HTML.\n *   > It does not support the features available in XML.\n *   > Passing SVG might break but fragments of modern SVG should be fine.\n *   > Use [`xast`][xast] if you need to support SVG as XML.\n * @property {boolean | null | undefined} [tightAttributes=false]\n *   Join attributes together, without whitespace, if possible: get\n *   `class=\"a b\"title=\"c d\"` instead of `class=\"a b\" title=\"c d\"` to save\n *   bytes (default: `false`).\n *\n *   Not used in the SVG space.\n *\n *   > 👉 **Note**: intentionally creates parse errors in markup (how parse\n *   > errors are handled is well defined, so this works but isn’t pretty).\n * @property {boolean | null | undefined} [tightCommaSeparatedLists=false]\n *   Join known comma-separated attribute values with just a comma (`,`),\n *   instead of padding them on the right as well (`,␠`, where `␠` represents a\n *   space) (default: `false`).\n * @property {boolean | null | undefined} [tightDoctype=false]\n *   Drop unneeded spaces in doctypes: `<!doctypehtml>` instead of\n *   `<!doctype html>` to save bytes (default: `false`).\n *\n *   > 👉 **Note**: intentionally creates parse errors in markup (how parse\n *   > errors are handled is well defined, so this works but isn’t pretty).\n * @property {boolean | null | undefined} [tightSelfClosing=false]\n *   Do not use an extra space when closing self-closing elements: `<img/>`\n *   instead of `<img />` (default: `false`).\n *\n *   > 👉 **Note**: only used if `closeSelfClosing: true` or\n *   > `closeEmptyElements: true`.\n * @property {boolean | null | undefined} [upperDoctype=false]\n *   Use a `<!DOCTYPE…` instead of `<!doctype…` (default: `false`).\n *\n *   Useless except for XHTML.\n * @property {ReadonlyArray<string> | null | undefined} [voids]\n *   Tag names of elements to serialize without closing tag (default: `html-void-elements`).\n *\n *   Not used in the SVG space.\n *\n *   > 👉 **Note**: It’s highly unlikely that you want to pass this, because\n *   > hast is not for XML, and HTML will not add more void elements.\n *\n * @typedef {'\"' | \"'\"} Quote\n *   HTML quotes for attribute values.\n *\n * @typedef {Omit<Required<{[key in keyof Options]: Exclude<Options[key], null | undefined>}>, 'space' | 'quote'>} Settings\n *\n * @typedef {'html' | 'svg'} Space\n *   Namespace.\n *\n * @typedef State\n *   Info passed around about the current state.\n * @property {(node: Parents | undefined) => string} all\n *   Serialize the children of a parent node.\n * @property {Quote} alternative\n *   Alternative quote.\n * @property {(node: Nodes, index: number | undefined, parent: Parents | undefined) => string} one\n *   Serialize one node.\n * @property {Quote} quote\n *   Preferred quote.\n * @property {Schema} schema\n *   Current schema.\n * @property {Settings} settings\n *   User configuration.\n */\n\nimport {htmlVoidElements} from 'html-void-elements'\nimport {html, svg} from 'property-information'\nimport {handle} from './handle/index.js'\n\n/** @type {Options} */\nconst emptyOptions = {}\n\n/** @type {CharacterReferences} */\nconst emptyCharacterReferences = {}\n\n/** @type {Array<never>} */\nconst emptyChildren = []\n\n/**\n * Serialize hast as HTML.\n *\n * @param {Array<RootContent> | Nodes} tree\n *   Tree to serialize.\n * @param {Options | null | undefined} [options]\n *   Configuration (optional).\n * @returns {string}\n *   Serialized HTML.\n */\nexport function toHtml(tree, options) {\n  const options_ = options || emptyOptions\n  const quote = options_.quote || '\"'\n  const alternative = quote === '\"' ? \"'\" : '\"'\n\n  if (quote !== '\"' && quote !== \"'\") {\n    throw new Error('Invalid quote `' + quote + '`, expected `\\'` or `\"`')\n  }\n\n  /** @type {State} */\n  const state = {\n    one,\n    all,\n    settings: {\n      omitOptionalTags: options_.omitOptionalTags || false,\n      allowParseErrors: options_.allowParseErrors || false,\n      allowDangerousCharacters: options_.allowDangerousCharacters || false,\n      quoteSmart: options_.quoteSmart || false,\n      preferUnquoted: options_.preferUnquoted || false,\n      tightAttributes: options_.tightAttributes || false,\n      upperDoctype: options_.upperDoctype || false,\n      tightDoctype: options_.tightDoctype || false,\n      bogusComments: options_.bogusComments || false,\n      tightCommaSeparatedLists: options_.tightCommaSeparatedLists || false,\n      tightSelfClosing: options_.tightSelfClosing || false,\n      collapseEmptyAttributes: options_.collapseEmptyAttributes || false,\n      allowDangerousHtml: options_.allowDangerousHtml || false,\n      voids: options_.voids || htmlVoidElements,\n      characterReferences:\n        options_.characterReferences || emptyCharacterReferences,\n      closeSelfClosing: options_.closeSelfClosing || false,\n      closeEmptyElements: options_.closeEmptyElements || false\n    },\n    schema: options_.space === 'svg' ? svg : html,\n    quote,\n    alternative\n  }\n\n  return state.one(\n    Array.isArray(tree) ? {type: 'root', children: tree} : tree,\n    undefined,\n    undefined\n  )\n}\n\n/**\n * Serialize a node.\n *\n * @this {State}\n *   Info passed around about the current state.\n * @param {Nodes} node\n *   Node to handle.\n * @param {number | undefined} index\n *   Index of `node` in `parent.\n * @param {Parents | undefined} parent\n *   Parent of `node`.\n * @returns {string}\n *   Serialized node.\n */\nfunction one(node, index, parent) {\n  return handle(node, index, parent, this)\n}\n\n/**\n * Serialize all children of `parent`.\n *\n * @this {State}\n *   Info passed around about the current state.\n * @param {Parents | undefined} parent\n *   Parent whose children to serialize.\n * @returns {string}\n */\nexport function all(parent) {\n  /** @type {Array<string>} */\n  const results = []\n  const children = (parent && parent.children) || emptyChildren\n  let index = -1\n\n  while (++index < children.length) {\n    results[index] = this.one(children[index], index, parent)\n  }\n\n  return results.join('')\n}\n","import { ShikiError as ShikiError$1 } from '@shikijs/types';\nexport * from '@shikijs/types';\nimport { FontStyle, INITIAL, EncodedTokenMetadata, Registry as Registry$1, Theme } from '@shikijs/vscode-textmate';\nimport { toHtml } from 'hast-util-to-html';\n\nfunction resolveColorReplacements(theme, options) {\n  const replacements = typeof theme === \"string\" ? {} : { ...theme.colorReplacements };\n  const themeName = typeof theme === \"string\" ? theme : theme.name;\n  for (const [key, value] of Object.entries(options?.colorReplacements || {})) {\n    if (typeof value === \"string\")\n      replacements[key] = value;\n    else if (key === themeName)\n      Object.assign(replacements, value);\n  }\n  return replacements;\n}\nfunction applyColorReplacements(color, replacements) {\n  if (!color)\n    return color;\n  return replacements?.[color?.toLowerCase()] || color;\n}\n\nfunction toArray(x) {\n  return Array.isArray(x) ? x : [x];\n}\nasync function normalizeGetter(p) {\n  return Promise.resolve(typeof p === \"function\" ? p() : p).then((r) => r.default || r);\n}\nfunction isPlainLang(lang) {\n  return !lang || [\"plaintext\", \"txt\", \"text\", \"plain\"].includes(lang);\n}\nfunction isSpecialLang(lang) {\n  return lang === \"ansi\" || isPlainLang(lang);\n}\nfunction isNoneTheme(theme) {\n  return theme === \"none\";\n}\nfunction isSpecialTheme(theme) {\n  return isNoneTheme(theme);\n}\n\nfunction addClassToHast(node, className) {\n  if (!className)\n    return node;\n  node.properties ||= {};\n  node.properties.class ||= [];\n  if (typeof node.properties.class === \"string\")\n    node.properties.class = node.properties.class.split(/\\s+/g);\n  if (!Array.isArray(node.properties.class))\n    node.properties.class = [];\n  const targets = Array.isArray(className) ? className : className.split(/\\s+/g);\n  for (const c of targets) {\n    if (c && !node.properties.class.includes(c))\n      node.properties.class.push(c);\n  }\n  return node;\n}\n\nfunction splitLines(code, preserveEnding = false) {\n  if (code.length === 0) {\n    return [[\"\", 0]];\n  }\n  const parts = code.split(/(\\r?\\n)/g);\n  let index = 0;\n  const lines = [];\n  for (let i = 0; i < parts.length; i += 2) {\n    const line = preserveEnding ? parts[i] + (parts[i + 1] || \"\") : parts[i];\n    lines.push([line, index]);\n    index += parts[i].length;\n    index += parts[i + 1]?.length || 0;\n  }\n  return lines;\n}\nfunction createPositionConverter(code) {\n  const lines = splitLines(code, true).map(([line]) => line);\n  function indexToPos(index) {\n    if (index === code.length) {\n      return {\n        line: lines.length - 1,\n        character: lines[lines.length - 1].length\n      };\n    }\n    let character = index;\n    let line = 0;\n    for (const lineText of lines) {\n      if (character < lineText.length)\n        break;\n      character -= lineText.length;\n      line++;\n    }\n    return { line, character };\n  }\n  function posToIndex(line, character) {\n    let index = 0;\n    for (let i = 0; i < line; i++)\n      index += lines[i].length;\n    index += character;\n    return index;\n  }\n  return {\n    lines,\n    indexToPos,\n    posToIndex\n  };\n}\nfunction guessEmbeddedLanguages(code, _lang, highlighter) {\n  const langs = /* @__PURE__ */ new Set();\n  for (const match of code.matchAll(/:?lang=[\"']([^\"']+)[\"']/g)) {\n    const lang = match[1].toLowerCase().trim();\n    if (lang)\n      langs.add(lang);\n  }\n  for (const match of code.matchAll(/(?:```|~~~)([\\w-]+)/g)) {\n    const lang = match[1].toLowerCase().trim();\n    if (lang)\n      langs.add(lang);\n  }\n  for (const match of code.matchAll(/\\\\begin\\{([\\w-]+)\\}/g)) {\n    const lang = match[1].toLowerCase().trim();\n    if (lang)\n      langs.add(lang);\n  }\n  for (const match of code.matchAll(/<script\\s+(?:type|lang)=[\"']([^\"']+)[\"']/gi)) {\n    const fullType = match[1].toLowerCase().trim();\n    const lang = fullType.includes(\"/\") ? fullType.split(\"/\").pop() : fullType;\n    if (lang)\n      langs.add(lang);\n  }\n  if (!highlighter)\n    return Array.from(langs);\n  const bundle = highlighter.getBundledLanguages();\n  return Array.from(langs).filter((l) => l && bundle[l]);\n}\n\nconst DEFAULT_COLOR_LIGHT_DARK = \"light-dark()\";\nconst COLOR_KEYS = [\"color\", \"background-color\"];\n\nfunction splitToken(token, offsets) {\n  let lastOffset = 0;\n  const tokens = [];\n  for (const offset of offsets) {\n    if (offset > lastOffset) {\n      tokens.push({\n        ...token,\n        content: token.content.slice(lastOffset, offset),\n        offset: token.offset + lastOffset\n      });\n    }\n    lastOffset = offset;\n  }\n  if (lastOffset < token.content.length) {\n    tokens.push({\n      ...token,\n      content: token.content.slice(lastOffset),\n      offset: token.offset + lastOffset\n    });\n  }\n  return tokens;\n}\nfunction splitTokens(tokens, breakpoints) {\n  const sorted = Array.from(breakpoints instanceof Set ? breakpoints : new Set(breakpoints)).sort((a, b) => a - b);\n  if (!sorted.length)\n    return tokens;\n  return tokens.map((line) => {\n    return line.flatMap((token) => {\n      const breakpointsInToken = sorted.filter((i) => token.offset < i && i < token.offset + token.content.length).map((i) => i - token.offset).sort((a, b) => a - b);\n      if (!breakpointsInToken.length)\n        return token;\n      return splitToken(token, breakpointsInToken);\n    });\n  });\n}\nfunction flatTokenVariants(merged, variantsOrder, cssVariablePrefix, defaultColor, colorsRendering = \"css-vars\") {\n  const token = {\n    content: merged.content,\n    explanation: merged.explanation,\n    offset: merged.offset\n  };\n  const styles = variantsOrder.map((t) => getTokenStyleObject(merged.variants[t]));\n  const styleKeys = new Set(styles.flatMap((t) => Object.keys(t)));\n  const mergedStyles = {};\n  const varKey = (idx, key) => {\n    const keyName = key === \"color\" ? \"\" : key === \"background-color\" ? \"-bg\" : `-${key}`;\n    return cssVariablePrefix + variantsOrder[idx] + (key === \"color\" ? \"\" : keyName);\n  };\n  styles.forEach((cur, idx) => {\n    for (const key of styleKeys) {\n      const value = cur[key] || \"inherit\";\n      if (idx === 0 && defaultColor && COLOR_KEYS.includes(key)) {\n        if (defaultColor === DEFAULT_COLOR_LIGHT_DARK && styles.length > 1) {\n          const lightIndex = variantsOrder.findIndex((t) => t === \"light\");\n          const darkIndex = variantsOrder.findIndex((t) => t === \"dark\");\n          if (lightIndex === -1 || darkIndex === -1)\n            throw new ShikiError$1('When using `defaultColor: \"light-dark()\"`, you must provide both `light` and `dark` themes');\n          const lightValue = styles[lightIndex][key] || \"inherit\";\n          const darkValue = styles[darkIndex][key] || \"inherit\";\n          mergedStyles[key] = `light-dark(${lightValue}, ${darkValue})`;\n          if (colorsRendering === \"css-vars\")\n            mergedStyles[varKey(idx, key)] = value;\n        } else {\n          mergedStyles[key] = value;\n        }\n      } else {\n        if (colorsRendering === \"css-vars\")\n          mergedStyles[varKey(idx, key)] = value;\n      }\n    }\n  });\n  token.htmlStyle = mergedStyles;\n  return token;\n}\nfunction getTokenStyleObject(token) {\n  const styles = {};\n  if (token.color)\n    styles.color = token.color;\n  if (token.bgColor)\n    styles[\"background-color\"] = token.bgColor;\n  if (token.fontStyle) {\n    if (token.fontStyle & FontStyle.Italic)\n      styles[\"font-style\"] = \"italic\";\n    if (token.fontStyle & FontStyle.Bold)\n      styles[\"font-weight\"] = \"bold\";\n    const decorations = [];\n    if (token.fontStyle & FontStyle.Underline)\n      decorations.push(\"underline\");\n    if (token.fontStyle & FontStyle.Strikethrough)\n      decorations.push(\"line-through\");\n    if (decorations.length)\n      styles[\"text-decoration\"] = decorations.join(\" \");\n  }\n  return styles;\n}\nfunction stringifyTokenStyle(token) {\n  if (typeof token === \"string\")\n    return token;\n  return Object.entries(token).map(([key, value]) => `${key}:${value}`).join(\";\");\n}\n\nconst _grammarStateMap = /* @__PURE__ */ new WeakMap();\nfunction setLastGrammarStateToMap(keys, state) {\n  _grammarStateMap.set(keys, state);\n}\nfunction getLastGrammarStateFromMap(keys) {\n  return _grammarStateMap.get(keys);\n}\nclass GrammarState {\n  /**\n   * Theme to Stack mapping\n   */\n  _stacks = {};\n  lang;\n  get themes() {\n    return Object.keys(this._stacks);\n  }\n  get theme() {\n    return this.themes[0];\n  }\n  get _stack() {\n    return this._stacks[this.theme];\n  }\n  /**\n   * Static method to create a initial grammar state.\n   */\n  static initial(lang, themes) {\n    return new GrammarState(\n      Object.fromEntries(toArray(themes).map((theme) => [theme, INITIAL])),\n      lang\n    );\n  }\n  constructor(...args) {\n    if (args.length === 2) {\n      const [stacksMap, lang] = args;\n      this.lang = lang;\n      this._stacks = stacksMap;\n    } else {\n      const [stack, lang, theme] = args;\n      this.lang = lang;\n      this._stacks = { [theme]: stack };\n    }\n  }\n  /**\n   * Get the internal stack object.\n   * @internal\n   */\n  getInternalStack(theme = this.theme) {\n    return this._stacks[theme];\n  }\n  getScopes(theme = this.theme) {\n    return getScopes(this._stacks[theme]);\n  }\n  toJSON() {\n    return {\n      lang: this.lang,\n      theme: this.theme,\n      themes: this.themes,\n      scopes: this.getScopes()\n    };\n  }\n}\nfunction getScopes(stack) {\n  const scopes = [];\n  const visited = /* @__PURE__ */ new Set();\n  function pushScope(stack2) {\n    if (visited.has(stack2))\n      return;\n    visited.add(stack2);\n    const name = stack2?.nameScopesList?.scopeName;\n    if (name)\n      scopes.push(name);\n    if (stack2.parent)\n      pushScope(stack2.parent);\n  }\n  pushScope(stack);\n  return scopes;\n}\nfunction getGrammarStack(state, theme) {\n  if (!(state instanceof GrammarState))\n    throw new ShikiError$1(\"Invalid grammar state\");\n  return state.getInternalStack(theme);\n}\n\nfunction transformerDecorations() {\n  const map = /* @__PURE__ */ new WeakMap();\n  function getContext(shiki) {\n    if (!map.has(shiki.meta)) {\n      let normalizePosition = function(p) {\n        if (typeof p === \"number\") {\n          if (p < 0 || p > shiki.source.length)\n            throw new ShikiError$1(`Invalid decoration offset: ${p}. Code length: ${shiki.source.length}`);\n          return {\n            ...converter.indexToPos(p),\n            offset: p\n          };\n        } else {\n          const line = converter.lines[p.line];\n          if (line === void 0)\n            throw new ShikiError$1(`Invalid decoration position ${JSON.stringify(p)}. Lines length: ${converter.lines.length}`);\n          let character = p.character;\n          if (character < 0)\n            character = line.length + character;\n          if (character < 0 || character > line.length)\n            throw new ShikiError$1(`Invalid decoration position ${JSON.stringify(p)}. Line ${p.line} length: ${line.length}`);\n          return {\n            ...p,\n            character,\n            offset: converter.posToIndex(p.line, character)\n          };\n        }\n      };\n      const converter = createPositionConverter(shiki.source);\n      const decorations = (shiki.options.decorations || []).map((d) => ({\n        ...d,\n        start: normalizePosition(d.start),\n        end: normalizePosition(d.end)\n      }));\n      verifyIntersections(decorations);\n      map.set(shiki.meta, {\n        decorations,\n        converter,\n        source: shiki.source\n      });\n    }\n    return map.get(shiki.meta);\n  }\n  return {\n    name: \"shiki:decorations\",\n    tokens(tokens) {\n      if (!this.options.decorations?.length)\n        return;\n      const ctx = getContext(this);\n      const breakpoints = ctx.decorations.flatMap((d) => [d.start.offset, d.end.offset]);\n      const splitted = splitTokens(tokens, breakpoints);\n      return splitted;\n    },\n    code(codeEl) {\n      if (!this.options.decorations?.length)\n        return;\n      const ctx = getContext(this);\n      const lines = Array.from(codeEl.children).filter((i) => i.type === \"element\" && i.tagName === \"span\");\n      if (lines.length !== ctx.converter.lines.length)\n        throw new ShikiError$1(`Number of lines in code element (${lines.length}) does not match the number of lines in the source (${ctx.converter.lines.length}). Failed to apply decorations.`);\n      function applyLineSection(line, start, end, decoration) {\n        const lineEl = lines[line];\n        let text = \"\";\n        let startIndex = -1;\n        let endIndex = -1;\n        if (start === 0)\n          startIndex = 0;\n        if (end === 0)\n          endIndex = 0;\n        if (end === Number.POSITIVE_INFINITY)\n          endIndex = lineEl.children.length;\n        if (startIndex === -1 || endIndex === -1) {\n          for (let i = 0; i < lineEl.children.length; i++) {\n            text += stringify(lineEl.children[i]);\n            if (startIndex === -1 && text.length === start)\n              startIndex = i + 1;\n            if (endIndex === -1 && text.length === end)\n              endIndex = i + 1;\n          }\n        }\n        if (startIndex === -1)\n          throw new ShikiError$1(`Failed to find start index for decoration ${JSON.stringify(decoration.start)}`);\n        if (endIndex === -1)\n          throw new ShikiError$1(`Failed to find end index for decoration ${JSON.stringify(decoration.end)}`);\n        const children = lineEl.children.slice(startIndex, endIndex);\n        if (!decoration.alwaysWrap && children.length === lineEl.children.length) {\n          applyDecoration(lineEl, decoration, \"line\");\n        } else if (!decoration.alwaysWrap && children.length === 1 && children[0].type === \"element\") {\n          applyDecoration(children[0], decoration, \"token\");\n        } else {\n          const wrapper = {\n            type: \"element\",\n            tagName: \"span\",\n            properties: {},\n            children\n          };\n          applyDecoration(wrapper, decoration, \"wrapper\");\n          lineEl.children.splice(startIndex, children.length, wrapper);\n        }\n      }\n      function applyLine(line, decoration) {\n        lines[line] = applyDecoration(lines[line], decoration, \"line\");\n      }\n      function applyDecoration(el, decoration, type) {\n        const properties = decoration.properties || {};\n        const transform = decoration.transform || ((i) => i);\n        el.tagName = decoration.tagName || \"span\";\n        el.properties = {\n          ...el.properties,\n          ...properties,\n          class: el.properties.class\n        };\n        if (decoration.properties?.class)\n          addClassToHast(el, decoration.properties.class);\n        el = transform(el, type) || el;\n        return el;\n      }\n      const lineApplies = [];\n      const sorted = ctx.decorations.sort((a, b) => b.start.offset - a.start.offset || a.end.offset - b.end.offset);\n      for (const decoration of sorted) {\n        const { start, end } = decoration;\n        if (start.line === end.line) {\n          applyLineSection(start.line, start.character, end.character, decoration);\n        } else if (start.line < end.line) {\n          applyLineSection(start.line, start.character, Number.POSITIVE_INFINITY, decoration);\n          for (let i = start.line + 1; i < end.line; i++)\n            lineApplies.unshift(() => applyLine(i, decoration));\n          applyLineSection(end.line, 0, end.character, decoration);\n        }\n      }\n      lineApplies.forEach((i) => i());\n    }\n  };\n}\nfunction verifyIntersections(items) {\n  for (let i = 0; i < items.length; i++) {\n    const foo = items[i];\n    if (foo.start.offset > foo.end.offset)\n      throw new ShikiError$1(`Invalid decoration range: ${JSON.stringify(foo.start)} - ${JSON.stringify(foo.end)}`);\n    for (let j = i + 1; j < items.length; j++) {\n      const bar = items[j];\n      const isFooHasBarStart = foo.start.offset <= bar.start.offset && bar.start.offset < foo.end.offset;\n      const isFooHasBarEnd = foo.start.offset < bar.end.offset && bar.end.offset <= foo.end.offset;\n      const isBarHasFooStart = bar.start.offset <= foo.start.offset && foo.start.offset < bar.end.offset;\n      const isBarHasFooEnd = bar.start.offset < foo.end.offset && foo.end.offset <= bar.end.offset;\n      if (isFooHasBarStart || isFooHasBarEnd || isBarHasFooStart || isBarHasFooEnd) {\n        if (isFooHasBarStart && isFooHasBarEnd)\n          continue;\n        if (isBarHasFooStart && isBarHasFooEnd)\n          continue;\n        if (isBarHasFooStart && foo.start.offset === foo.end.offset)\n          continue;\n        if (isFooHasBarEnd && bar.start.offset === bar.end.offset)\n          continue;\n        throw new ShikiError$1(`Decorations ${JSON.stringify(foo.start)} and ${JSON.stringify(bar.start)} intersect.`);\n      }\n    }\n  }\n}\nfunction stringify(el) {\n  if (el.type === \"text\")\n    return el.value;\n  if (el.type === \"element\")\n    return el.children.map(stringify).join(\"\");\n  return \"\";\n}\n\nconst builtInTransformers = [\n  /* @__PURE__ */ transformerDecorations()\n];\nfunction getTransformers(options) {\n  const transformers = sortTransformersByEnforcement(options.transformers || []);\n  return [\n    ...transformers.pre,\n    ...transformers.normal,\n    ...transformers.post,\n    ...builtInTransformers\n  ];\n}\nfunction sortTransformersByEnforcement(transformers) {\n  const pre = [];\n  const post = [];\n  const normal = [];\n  for (const transformer of transformers) {\n    switch (transformer.enforce) {\n      case \"pre\":\n        pre.push(transformer);\n        break;\n      case \"post\":\n        post.push(transformer);\n        break;\n      default:\n        normal.push(transformer);\n    }\n  }\n  return { pre, post, normal };\n}\n\n// src/colors.ts\nvar namedColors = [\n  \"black\",\n  \"red\",\n  \"green\",\n  \"yellow\",\n  \"blue\",\n  \"magenta\",\n  \"cyan\",\n  \"white\",\n  \"brightBlack\",\n  \"brightRed\",\n  \"brightGreen\",\n  \"brightYellow\",\n  \"brightBlue\",\n  \"brightMagenta\",\n  \"brightCyan\",\n  \"brightWhite\"\n];\n\n// src/decorations.ts\nvar decorations = {\n  1: \"bold\",\n  2: \"dim\",\n  3: \"italic\",\n  4: \"underline\",\n  7: \"reverse\",\n  8: \"hidden\",\n  9: \"strikethrough\"\n};\n\n// src/parser.ts\nfunction findSequence(value, position) {\n  const nextEscape = value.indexOf(\"\\x1B\", position);\n  if (nextEscape !== -1) {\n    if (value[nextEscape + 1] === \"[\") {\n      const nextClose = value.indexOf(\"m\", nextEscape);\n      if (nextClose !== -1) {\n        return {\n          sequence: value.substring(nextEscape + 2, nextClose).split(\";\"),\n          startPosition: nextEscape,\n          position: nextClose + 1\n        };\n      }\n    }\n  }\n  return {\n    position: value.length\n  };\n}\nfunction parseColor(sequence) {\n  const colorMode = sequence.shift();\n  if (colorMode === \"2\") {\n    const rgb = sequence.splice(0, 3).map((x) => Number.parseInt(x));\n    if (rgb.length !== 3 || rgb.some((x) => Number.isNaN(x)))\n      return;\n    return {\n      type: \"rgb\",\n      rgb\n    };\n  } else if (colorMode === \"5\") {\n    const index = sequence.shift();\n    if (index) {\n      return { type: \"table\", index: Number(index) };\n    }\n  }\n}\nfunction parseSequence(sequence) {\n  const commands = [];\n  while (sequence.length > 0) {\n    const code = sequence.shift();\n    if (!code)\n      continue;\n    const codeInt = Number.parseInt(code);\n    if (Number.isNaN(codeInt))\n      continue;\n    if (codeInt === 0) {\n      commands.push({ type: \"resetAll\" });\n    } else if (codeInt <= 9) {\n      const decoration = decorations[codeInt];\n      if (decoration) {\n        commands.push({\n          type: \"setDecoration\",\n          value: decorations[codeInt]\n        });\n      }\n    } else if (codeInt <= 29) {\n      const decoration = decorations[codeInt - 20];\n      if (decoration) {\n        commands.push({\n          type: \"resetDecoration\",\n          value: decoration\n        });\n        if (decoration === \"dim\") {\n          commands.push({\n            type: \"resetDecoration\",\n            value: \"bold\"\n          });\n        }\n      }\n    } else if (codeInt <= 37) {\n      commands.push({\n        type: \"setForegroundColor\",\n        value: { type: \"named\", name: namedColors[codeInt - 30] }\n      });\n    } else if (codeInt === 38) {\n      const color = parseColor(sequence);\n      if (color) {\n        commands.push({\n          type: \"setForegroundColor\",\n          value: color\n        });\n      }\n    } else if (codeInt === 39) {\n      commands.push({\n        type: \"resetForegroundColor\"\n      });\n    } else if (codeInt <= 47) {\n      commands.push({\n        type: \"setBackgroundColor\",\n        value: { type: \"named\", name: namedColors[codeInt - 40] }\n      });\n    } else if (codeInt === 48) {\n      const color = parseColor(sequence);\n      if (color) {\n        commands.push({\n          type: \"setBackgroundColor\",\n          value: color\n        });\n      }\n    } else if (codeInt === 49) {\n      commands.push({\n        type: \"resetBackgroundColor\"\n      });\n    } else if (codeInt === 53) {\n      commands.push({\n        type: \"setDecoration\",\n        value: \"overline\"\n      });\n    } else if (codeInt === 55) {\n      commands.push({\n        type: \"resetDecoration\",\n        value: \"overline\"\n      });\n    } else if (codeInt >= 90 && codeInt <= 97) {\n      commands.push({\n        type: \"setForegroundColor\",\n        value: { type: \"named\", name: namedColors[codeInt - 90 + 8] }\n      });\n    } else if (codeInt >= 100 && codeInt <= 107) {\n      commands.push({\n        type: \"setBackgroundColor\",\n        value: { type: \"named\", name: namedColors[codeInt - 100 + 8] }\n      });\n    }\n  }\n  return commands;\n}\nfunction createAnsiSequenceParser() {\n  let foreground = null;\n  let background = null;\n  let decorations2 = /* @__PURE__ */ new Set();\n  return {\n    parse(value) {\n      const tokens = [];\n      let position = 0;\n      do {\n        const findResult = findSequence(value, position);\n        const text = findResult.sequence ? value.substring(position, findResult.startPosition) : value.substring(position);\n        if (text.length > 0) {\n          tokens.push({\n            value: text,\n            foreground,\n            background,\n            decorations: new Set(decorations2)\n          });\n        }\n        if (findResult.sequence) {\n          const commands = parseSequence(findResult.sequence);\n          for (const styleToken of commands) {\n            if (styleToken.type === \"resetAll\") {\n              foreground = null;\n              background = null;\n              decorations2.clear();\n            } else if (styleToken.type === \"resetForegroundColor\") {\n              foreground = null;\n            } else if (styleToken.type === \"resetBackgroundColor\") {\n              background = null;\n            } else if (styleToken.type === \"resetDecoration\") {\n              decorations2.delete(styleToken.value);\n            }\n          }\n          for (const styleToken of commands) {\n            if (styleToken.type === \"setForegroundColor\") {\n              foreground = styleToken.value;\n            } else if (styleToken.type === \"setBackgroundColor\") {\n              background = styleToken.value;\n            } else if (styleToken.type === \"setDecoration\") {\n              decorations2.add(styleToken.value);\n            }\n          }\n        }\n        position = findResult.position;\n      } while (position < value.length);\n      return tokens;\n    }\n  };\n}\n\n// src/palette.ts\nvar defaultNamedColorsMap = {\n  black: \"#000000\",\n  red: \"#bb0000\",\n  green: \"#00bb00\",\n  yellow: \"#bbbb00\",\n  blue: \"#0000bb\",\n  magenta: \"#ff00ff\",\n  cyan: \"#00bbbb\",\n  white: \"#eeeeee\",\n  brightBlack: \"#555555\",\n  brightRed: \"#ff5555\",\n  brightGreen: \"#00ff00\",\n  brightYellow: \"#ffff55\",\n  brightBlue: \"#5555ff\",\n  brightMagenta: \"#ff55ff\",\n  brightCyan: \"#55ffff\",\n  brightWhite: \"#ffffff\"\n};\nfunction createColorPalette(namedColorsMap = defaultNamedColorsMap) {\n  function namedColor(name) {\n    return namedColorsMap[name];\n  }\n  function rgbColor(rgb) {\n    return `#${rgb.map((x) => Math.max(0, Math.min(x, 255)).toString(16).padStart(2, \"0\")).join(\"\")}`;\n  }\n  let colorTable;\n  function getColorTable() {\n    if (colorTable) {\n      return colorTable;\n    }\n    colorTable = [];\n    for (let i = 0; i < namedColors.length; i++) {\n      colorTable.push(namedColor(namedColors[i]));\n    }\n    let levels = [0, 95, 135, 175, 215, 255];\n    for (let r = 0; r < 6; r++) {\n      for (let g = 0; g < 6; g++) {\n        for (let b = 0; b < 6; b++) {\n          colorTable.push(rgbColor([levels[r], levels[g], levels[b]]));\n        }\n      }\n    }\n    let level = 8;\n    for (let i = 0; i < 24; i++, level += 10) {\n      colorTable.push(rgbColor([level, level, level]));\n    }\n    return colorTable;\n  }\n  function tableColor(index) {\n    return getColorTable()[index];\n  }\n  function value(color) {\n    switch (color.type) {\n      case \"named\":\n        return namedColor(color.name);\n      case \"rgb\":\n        return rgbColor(color.rgb);\n      case \"table\":\n        return tableColor(color.index);\n    }\n  }\n  return {\n    value\n  };\n}\n\nconst defaultAnsiColors = {\n  black: \"#000000\",\n  red: \"#cd3131\",\n  green: \"#0DBC79\",\n  yellow: \"#E5E510\",\n  blue: \"#2472C8\",\n  magenta: \"#BC3FBC\",\n  cyan: \"#11A8CD\",\n  white: \"#E5E5E5\",\n  brightBlack: \"#666666\",\n  brightRed: \"#F14C4C\",\n  brightGreen: \"#23D18B\",\n  brightYellow: \"#F5F543\",\n  brightBlue: \"#3B8EEA\",\n  brightMagenta: \"#D670D6\",\n  brightCyan: \"#29B8DB\",\n  brightWhite: \"#FFFFFF\"\n};\nfunction tokenizeAnsiWithTheme(theme, fileContents, options) {\n  const colorReplacements = resolveColorReplacements(theme, options);\n  const lines = splitLines(fileContents);\n  const ansiPalette = Object.fromEntries(\n    namedColors.map((name) => {\n      const key = `terminal.ansi${name[0].toUpperCase()}${name.substring(1)}`;\n      const themeColor = theme.colors?.[key];\n      return [name, themeColor || defaultAnsiColors[name]];\n    })\n  );\n  const colorPalette = createColorPalette(ansiPalette);\n  const parser = createAnsiSequenceParser();\n  return lines.map(\n    (line) => parser.parse(line[0]).map((token) => {\n      let color;\n      let bgColor;\n      if (token.decorations.has(\"reverse\")) {\n        color = token.background ? colorPalette.value(token.background) : theme.bg;\n        bgColor = token.foreground ? colorPalette.value(token.foreground) : theme.fg;\n      } else {\n        color = token.foreground ? colorPalette.value(token.foreground) : theme.fg;\n        bgColor = token.background ? colorPalette.value(token.background) : void 0;\n      }\n      color = applyColorReplacements(color, colorReplacements);\n      bgColor = applyColorReplacements(bgColor, colorReplacements);\n      if (token.decorations.has(\"dim\"))\n        color = dimColor(color);\n      let fontStyle = FontStyle.None;\n      if (token.decorations.has(\"bold\"))\n        fontStyle |= FontStyle.Bold;\n      if (token.decorations.has(\"italic\"))\n        fontStyle |= FontStyle.Italic;\n      if (token.decorations.has(\"underline\"))\n        fontStyle |= FontStyle.Underline;\n      if (token.decorations.has(\"strikethrough\"))\n        fontStyle |= FontStyle.Strikethrough;\n      return {\n        content: token.value,\n        offset: line[1],\n        // TODO: more accurate offset? might need to fork ansi-sequence-parser\n        color,\n        bgColor,\n        fontStyle\n      };\n    })\n  );\n}\nfunction dimColor(color) {\n  const hexMatch = color.match(/#([0-9a-f]{3,8})/i);\n  if (hexMatch) {\n    const hex = hexMatch[1];\n    if (hex.length === 8) {\n      const alpha = Math.round(Number.parseInt(hex.slice(6, 8), 16) / 2).toString(16).padStart(2, \"0\");\n      return `#${hex.slice(0, 6)}${alpha}`;\n    } else if (hex.length === 6) {\n      return `#${hex}80`;\n    } else if (hex.length === 4) {\n      const r = hex[0];\n      const g = hex[1];\n      const b = hex[2];\n      const a = hex[3];\n      const alpha = Math.round(Number.parseInt(`${a}${a}`, 16) / 2).toString(16).padStart(2, \"0\");\n      return `#${r}${r}${g}${g}${b}${b}${alpha}`;\n    } else if (hex.length === 3) {\n      const r = hex[0];\n      const g = hex[1];\n      const b = hex[2];\n      return `#${r}${r}${g}${g}${b}${b}80`;\n    }\n  }\n  const cssVarMatch = color.match(/var\\((--[\\w-]+-ansi-[\\w-]+)\\)/);\n  if (cssVarMatch)\n    return `var(${cssVarMatch[1]}-dim)`;\n  return color;\n}\n\nfunction codeToTokensBase(internal, code, options = {}) {\n  const {\n    theme: themeName = internal.getLoadedThemes()[0]\n  } = options;\n  const lang = internal.resolveLangAlias(options.lang || \"text\");\n  if (isPlainLang(lang) || isNoneTheme(themeName))\n    return splitLines(code).map((line) => [{ content: line[0], offset: line[1] }]);\n  const { theme, colorMap } = internal.setTheme(themeName);\n  if (lang === \"ansi\")\n    return tokenizeAnsiWithTheme(theme, code, options);\n  const _grammar = internal.getLanguage(options.lang || \"text\");\n  if (options.grammarState) {\n    if (options.grammarState.lang !== _grammar.name) {\n      throw new ShikiError$1(`Grammar state language \"${options.grammarState.lang}\" does not match highlight language \"${_grammar.name}\"`);\n    }\n    if (!options.grammarState.themes.includes(theme.name)) {\n      throw new ShikiError$1(`Grammar state themes \"${options.grammarState.themes}\" do not contain highlight theme \"${theme.name}\"`);\n    }\n  }\n  return tokenizeWithTheme(code, _grammar, theme, colorMap, options);\n}\nfunction getLastGrammarState(...args) {\n  if (args.length === 2) {\n    return getLastGrammarStateFromMap(args[1]);\n  }\n  const [internal, code, options = {}] = args;\n  const {\n    lang = \"text\",\n    theme: themeName = internal.getLoadedThemes()[0]\n  } = options;\n  if (isPlainLang(lang) || isNoneTheme(themeName))\n    throw new ShikiError$1(\"Plain language does not have grammar state\");\n  if (lang === \"ansi\")\n    throw new ShikiError$1(\"ANSI language does not have grammar state\");\n  const { theme, colorMap } = internal.setTheme(themeName);\n  const _grammar = internal.getLanguage(lang);\n  return new GrammarState(\n    _tokenizeWithTheme(code, _grammar, theme, colorMap, options).stateStack,\n    _grammar.name,\n    theme.name\n  );\n}\nfunction tokenizeWithTheme(code, grammar, theme, colorMap, options) {\n  const result = _tokenizeWithTheme(code, grammar, theme, colorMap, options);\n  const grammarState = new GrammarState(\n    result.stateStack,\n    grammar.name,\n    theme.name\n  );\n  setLastGrammarStateToMap(result.tokens, grammarState);\n  return result.tokens;\n}\nfunction _tokenizeWithTheme(code, grammar, theme, colorMap, options) {\n  const colorReplacements = resolveColorReplacements(theme, options);\n  const {\n    tokenizeMaxLineLength = 0,\n    tokenizeTimeLimit = 500\n  } = options;\n  const lines = splitLines(code);\n  let stateStack = options.grammarState ? getGrammarStack(options.grammarState, theme.name) ?? INITIAL : options.grammarContextCode != null ? _tokenizeWithTheme(\n    options.grammarContextCode,\n    grammar,\n    theme,\n    colorMap,\n    {\n      ...options,\n      grammarState: void 0,\n      grammarContextCode: void 0\n    }\n  ).stateStack : INITIAL;\n  let actual = [];\n  const final = [];\n  for (let i = 0, len = lines.length; i < len; i++) {\n    const [line, lineOffset] = lines[i];\n    if (line === \"\") {\n      actual = [];\n      final.push([]);\n      continue;\n    }\n    if (tokenizeMaxLineLength > 0 && line.length >= tokenizeMaxLineLength) {\n      actual = [];\n      final.push([{\n        content: line,\n        offset: lineOffset,\n        color: \"\",\n        fontStyle: 0\n      }]);\n      continue;\n    }\n    let resultWithScopes;\n    let tokensWithScopes;\n    let tokensWithScopesIndex;\n    if (options.includeExplanation) {\n      resultWithScopes = grammar.tokenizeLine(line, stateStack, tokenizeTimeLimit);\n      tokensWithScopes = resultWithScopes.tokens;\n      tokensWithScopesIndex = 0;\n    }\n    const result = grammar.tokenizeLine2(line, stateStack, tokenizeTimeLimit);\n    const tokensLength = result.tokens.length / 2;\n    for (let j = 0; j < tokensLength; j++) {\n      const startIndex = result.tokens[2 * j];\n      const nextStartIndex = j + 1 < tokensLength ? result.tokens[2 * j + 2] : line.length;\n      if (startIndex === nextStartIndex)\n        continue;\n      const metadata = result.tokens[2 * j + 1];\n      const color = applyColorReplacements(\n        colorMap[EncodedTokenMetadata.getForeground(metadata)],\n        colorReplacements\n      );\n      const fontStyle = EncodedTokenMetadata.getFontStyle(metadata);\n      const token = {\n        content: line.substring(startIndex, nextStartIndex),\n        offset: lineOffset + startIndex,\n        color,\n        fontStyle\n      };\n      if (options.includeExplanation) {\n        const themeSettingsSelectors = [];\n        if (options.includeExplanation !== \"scopeName\") {\n          for (const setting of theme.settings) {\n            let selectors;\n            switch (typeof setting.scope) {\n              case \"string\":\n                selectors = setting.scope.split(/,/).map((scope) => scope.trim());\n                break;\n              case \"object\":\n                selectors = setting.scope;\n                break;\n              default:\n                continue;\n            }\n            themeSettingsSelectors.push({\n              settings: setting,\n              selectors: selectors.map((selector) => selector.split(/ /))\n            });\n          }\n        }\n        token.explanation = [];\n        let offset = 0;\n        while (startIndex + offset < nextStartIndex) {\n          const tokenWithScopes = tokensWithScopes[tokensWithScopesIndex];\n          const tokenWithScopesText = line.substring(\n            tokenWithScopes.startIndex,\n            tokenWithScopes.endIndex\n          );\n          offset += tokenWithScopesText.length;\n          token.explanation.push({\n            content: tokenWithScopesText,\n            scopes: options.includeExplanation === \"scopeName\" ? explainThemeScopesNameOnly(\n              tokenWithScopes.scopes\n            ) : explainThemeScopesFull(\n              themeSettingsSelectors,\n              tokenWithScopes.scopes\n            )\n          });\n          tokensWithScopesIndex += 1;\n        }\n      }\n      actual.push(token);\n    }\n    final.push(actual);\n    actual = [];\n    stateStack = result.ruleStack;\n  }\n  return {\n    tokens: final,\n    stateStack\n  };\n}\nfunction explainThemeScopesNameOnly(scopes) {\n  return scopes.map((scope) => ({ scopeName: scope }));\n}\nfunction explainThemeScopesFull(themeSelectors, scopes) {\n  const result = [];\n  for (let i = 0, len = scopes.length; i < len; i++) {\n    const scope = scopes[i];\n    result[i] = {\n      scopeName: scope,\n      themeMatches: explainThemeScope(themeSelectors, scope, scopes.slice(0, i))\n    };\n  }\n  return result;\n}\nfunction matchesOne(selector, scope) {\n  return selector === scope || scope.substring(0, selector.length) === selector && scope[selector.length] === \".\";\n}\nfunction matches(selectors, scope, parentScopes) {\n  if (!matchesOne(selectors[selectors.length - 1], scope))\n    return false;\n  let selectorParentIndex = selectors.length - 2;\n  let parentIndex = parentScopes.length - 1;\n  while (selectorParentIndex >= 0 && parentIndex >= 0) {\n    if (matchesOne(selectors[selectorParentIndex], parentScopes[parentIndex]))\n      selectorParentIndex -= 1;\n    parentIndex -= 1;\n  }\n  if (selectorParentIndex === -1)\n    return true;\n  return false;\n}\nfunction explainThemeScope(themeSettingsSelectors, scope, parentScopes) {\n  const result = [];\n  for (const { selectors, settings } of themeSettingsSelectors) {\n    for (const selectorPieces of selectors) {\n      if (matches(selectorPieces, scope, parentScopes)) {\n        result.push(settings);\n        break;\n      }\n    }\n  }\n  return result;\n}\n\nfunction codeToTokensWithThemes(internal, code, options) {\n  const themes = Object.entries(options.themes).filter((i) => i[1]).map((i) => ({ color: i[0], theme: i[1] }));\n  const themedTokens = themes.map((t) => {\n    const tokens2 = codeToTokensBase(internal, code, {\n      ...options,\n      theme: t.theme\n    });\n    const state = getLastGrammarStateFromMap(tokens2);\n    const theme = typeof t.theme === \"string\" ? t.theme : t.theme.name;\n    return {\n      tokens: tokens2,\n      state,\n      theme\n    };\n  });\n  const tokens = syncThemesTokenization(\n    ...themedTokens.map((i) => i.tokens)\n  );\n  const mergedTokens = tokens[0].map(\n    (line, lineIdx) => line.map((_token, tokenIdx) => {\n      const mergedToken = {\n        content: _token.content,\n        variants: {},\n        offset: _token.offset\n      };\n      if (\"includeExplanation\" in options && options.includeExplanation) {\n        mergedToken.explanation = _token.explanation;\n      }\n      tokens.forEach((t, themeIdx) => {\n        const {\n          content: _,\n          explanation: __,\n          offset: ___,\n          ...styles\n        } = t[lineIdx][tokenIdx];\n        mergedToken.variants[themes[themeIdx].color] = styles;\n      });\n      return mergedToken;\n    })\n  );\n  const mergedGrammarState = themedTokens[0].state ? new GrammarState(\n    Object.fromEntries(themedTokens.map((s) => [s.theme, s.state?.getInternalStack(s.theme)])),\n    themedTokens[0].state.lang\n  ) : void 0;\n  if (mergedGrammarState)\n    setLastGrammarStateToMap(mergedTokens, mergedGrammarState);\n  return mergedTokens;\n}\nfunction syncThemesTokenization(...themes) {\n  const outThemes = themes.map(() => []);\n  const count = themes.length;\n  for (let i = 0; i < themes[0].length; i++) {\n    const lines = themes.map((t) => t[i]);\n    const outLines = outThemes.map(() => []);\n    outThemes.forEach((t, i2) => t.push(outLines[i2]));\n    const indexes = lines.map(() => 0);\n    const current = lines.map((l) => l[0]);\n    while (current.every((t) => t)) {\n      const minLength = Math.min(...current.map((t) => t.content.length));\n      for (let n = 0; n < count; n++) {\n        const token = current[n];\n        if (token.content.length === minLength) {\n          outLines[n].push(token);\n          indexes[n] += 1;\n          current[n] = lines[n][indexes[n]];\n        } else {\n          outLines[n].push({\n            ...token,\n            content: token.content.slice(0, minLength)\n          });\n          current[n] = {\n            ...token,\n            content: token.content.slice(minLength),\n            offset: token.offset + minLength\n          };\n        }\n      }\n    }\n  }\n  return outThemes;\n}\n\nfunction codeToTokens(internal, code, options) {\n  let bg;\n  let fg;\n  let tokens;\n  let themeName;\n  let rootStyle;\n  let grammarState;\n  if (\"themes\" in options) {\n    const {\n      defaultColor = \"light\",\n      cssVariablePrefix = \"--shiki-\",\n      colorsRendering = \"css-vars\"\n    } = options;\n    const themes = Object.entries(options.themes).filter((i) => i[1]).map((i) => ({ color: i[0], theme: i[1] })).sort((a, b) => a.color === defaultColor ? -1 : b.color === defaultColor ? 1 : 0);\n    if (themes.length === 0)\n      throw new ShikiError$1(\"`themes` option must not be empty\");\n    const themeTokens = codeToTokensWithThemes(\n      internal,\n      code,\n      options\n    );\n    grammarState = getLastGrammarStateFromMap(themeTokens);\n    if (defaultColor && DEFAULT_COLOR_LIGHT_DARK !== defaultColor && !themes.find((t) => t.color === defaultColor))\n      throw new ShikiError$1(`\\`themes\\` option must contain the defaultColor key \\`${defaultColor}\\``);\n    const themeRegs = themes.map((t) => internal.getTheme(t.theme));\n    const themesOrder = themes.map((t) => t.color);\n    tokens = themeTokens.map((line) => line.map((token) => flatTokenVariants(token, themesOrder, cssVariablePrefix, defaultColor, colorsRendering)));\n    if (grammarState)\n      setLastGrammarStateToMap(tokens, grammarState);\n    const themeColorReplacements = themes.map((t) => resolveColorReplacements(t.theme, options));\n    fg = mapThemeColors(themes, themeRegs, themeColorReplacements, cssVariablePrefix, defaultColor, \"fg\", colorsRendering);\n    bg = mapThemeColors(themes, themeRegs, themeColorReplacements, cssVariablePrefix, defaultColor, \"bg\", colorsRendering);\n    themeName = `shiki-themes ${themeRegs.map((t) => t.name).join(\" \")}`;\n    rootStyle = defaultColor ? void 0 : [fg, bg].join(\";\");\n  } else if (\"theme\" in options) {\n    const colorReplacements = resolveColorReplacements(options.theme, options);\n    tokens = codeToTokensBase(\n      internal,\n      code,\n      options\n    );\n    const _theme = internal.getTheme(options.theme);\n    bg = applyColorReplacements(_theme.bg, colorReplacements);\n    fg = applyColorReplacements(_theme.fg, colorReplacements);\n    themeName = _theme.name;\n    grammarState = getLastGrammarStateFromMap(tokens);\n  } else {\n    throw new ShikiError$1(\"Invalid options, either `theme` or `themes` must be provided\");\n  }\n  return {\n    tokens,\n    fg,\n    bg,\n    themeName,\n    rootStyle,\n    grammarState\n  };\n}\nfunction mapThemeColors(themes, themeRegs, themeColorReplacements, cssVariablePrefix, defaultColor, property, colorsRendering) {\n  return themes.map((t, idx) => {\n    const value = applyColorReplacements(themeRegs[idx][property], themeColorReplacements[idx]) || \"inherit\";\n    const cssVar = `${cssVariablePrefix + t.color}${property === \"bg\" ? \"-bg\" : \"\"}:${value}`;\n    if (idx === 0 && defaultColor) {\n      if (defaultColor === DEFAULT_COLOR_LIGHT_DARK && themes.length > 1) {\n        const lightIndex = themes.findIndex((t2) => t2.color === \"light\");\n        const darkIndex = themes.findIndex((t2) => t2.color === \"dark\");\n        if (lightIndex === -1 || darkIndex === -1)\n          throw new ShikiError$1('When using `defaultColor: \"light-dark()\"`, you must provide both `light` and `dark` themes');\n        const lightValue = applyColorReplacements(themeRegs[lightIndex][property], themeColorReplacements[lightIndex]) || \"inherit\";\n        const darkValue = applyColorReplacements(themeRegs[darkIndex][property], themeColorReplacements[darkIndex]) || \"inherit\";\n        return `light-dark(${lightValue}, ${darkValue});${cssVar}`;\n      }\n      return value;\n    }\n    if (colorsRendering === \"css-vars\") {\n      return cssVar;\n    }\n    return null;\n  }).filter((i) => !!i).join(\";\");\n}\n\nfunction codeToHast(internal, code, options, transformerContext = {\n  meta: {},\n  options,\n  codeToHast: (_code, _options) => codeToHast(internal, _code, _options),\n  codeToTokens: (_code, _options) => codeToTokens(internal, _code, _options)\n}) {\n  let input = code;\n  for (const transformer of getTransformers(options))\n    input = transformer.preprocess?.call(transformerContext, input, options) || input;\n  let {\n    tokens,\n    fg,\n    bg,\n    themeName,\n    rootStyle,\n    grammarState\n  } = codeToTokens(internal, input, options);\n  const {\n    mergeWhitespaces = true,\n    mergeSameStyleTokens = false\n  } = options;\n  if (mergeWhitespaces === true)\n    tokens = mergeWhitespaceTokens(tokens);\n  else if (mergeWhitespaces === \"never\")\n    tokens = splitWhitespaceTokens(tokens);\n  if (mergeSameStyleTokens) {\n    tokens = mergeAdjacentStyledTokens(tokens);\n  }\n  const contextSource = {\n    ...transformerContext,\n    get source() {\n      return input;\n    }\n  };\n  for (const transformer of getTransformers(options))\n    tokens = transformer.tokens?.call(contextSource, tokens) || tokens;\n  return tokensToHast(\n    tokens,\n    {\n      ...options,\n      fg,\n      bg,\n      themeName,\n      rootStyle: options.rootStyle === false ? false : options.rootStyle ?? rootStyle\n    },\n    contextSource,\n    grammarState\n  );\n}\nfunction tokensToHast(tokens, options, transformerContext, grammarState = getLastGrammarStateFromMap(tokens)) {\n  const transformers = getTransformers(options);\n  const lines = [];\n  const root = {\n    type: \"root\",\n    children: []\n  };\n  const {\n    structure = \"classic\",\n    tabindex = \"0\"\n  } = options;\n  const properties = {\n    class: `shiki ${options.themeName || \"\"}`\n  };\n  if (options.rootStyle !== false) {\n    if (options.rootStyle != null)\n      properties.style = options.rootStyle;\n    else\n      properties.style = `background-color:${options.bg};color:${options.fg}`;\n  }\n  if (tabindex !== false && tabindex != null)\n    properties.tabindex = tabindex.toString();\n  for (const [key, value] of Object.entries(options.meta || {})) {\n    if (!key.startsWith(\"_\"))\n      properties[key] = value;\n  }\n  let preNode = {\n    type: \"element\",\n    tagName: \"pre\",\n    properties,\n    children: [],\n    data: options.data\n  };\n  let codeNode = {\n    type: \"element\",\n    tagName: \"code\",\n    properties: {},\n    children: lines\n  };\n  const lineNodes = [];\n  const context = {\n    ...transformerContext,\n    structure,\n    addClassToHast,\n    get source() {\n      return transformerContext.source;\n    },\n    get tokens() {\n      return tokens;\n    },\n    get options() {\n      return options;\n    },\n    get root() {\n      return root;\n    },\n    get pre() {\n      return preNode;\n    },\n    get code() {\n      return codeNode;\n    },\n    get lines() {\n      return lineNodes;\n    }\n  };\n  tokens.forEach((line, idx) => {\n    if (idx) {\n      if (structure === \"inline\")\n        root.children.push({ type: \"element\", tagName: \"br\", properties: {}, children: [] });\n      else if (structure === \"classic\")\n        lines.push({ type: \"text\", value: \"\\n\" });\n    }\n    let lineNode = {\n      type: \"element\",\n      tagName: \"span\",\n      properties: { class: \"line\" },\n      children: []\n    };\n    let col = 0;\n    for (const token of line) {\n      let tokenNode = {\n        type: \"element\",\n        tagName: \"span\",\n        properties: {\n          ...token.htmlAttrs\n        },\n        children: [{ type: \"text\", value: token.content }]\n      };\n      const style = stringifyTokenStyle(token.htmlStyle || getTokenStyleObject(token));\n      if (style)\n        tokenNode.properties.style = style;\n      for (const transformer of transformers)\n        tokenNode = transformer?.span?.call(context, tokenNode, idx + 1, col, lineNode, token) || tokenNode;\n      if (structure === \"inline\")\n        root.children.push(tokenNode);\n      else if (structure === \"classic\")\n        lineNode.children.push(tokenNode);\n      col += token.content.length;\n    }\n    if (structure === \"classic\") {\n      for (const transformer of transformers)\n        lineNode = transformer?.line?.call(context, lineNode, idx + 1) || lineNode;\n      lineNodes.push(lineNode);\n      lines.push(lineNode);\n    } else if (structure === \"inline\") {\n      lineNodes.push(lineNode);\n    }\n  });\n  if (structure === \"classic\") {\n    for (const transformer of transformers)\n      codeNode = transformer?.code?.call(context, codeNode) || codeNode;\n    preNode.children.push(codeNode);\n    for (const transformer of transformers)\n      preNode = transformer?.pre?.call(context, preNode) || preNode;\n    root.children.push(preNode);\n  } else if (structure === \"inline\") {\n    const syntheticLines = [];\n    let currentLine = {\n      type: \"element\",\n      tagName: \"span\",\n      properties: { class: \"line\" },\n      children: []\n    };\n    for (const child of root.children) {\n      if (child.type === \"element\" && child.tagName === \"br\") {\n        syntheticLines.push(currentLine);\n        currentLine = {\n          type: \"element\",\n          tagName: \"span\",\n          properties: { class: \"line\" },\n          children: []\n        };\n      } else if (child.type === \"element\" || child.type === \"text\") {\n        currentLine.children.push(child);\n      }\n    }\n    syntheticLines.push(currentLine);\n    const syntheticCode = {\n      type: \"element\",\n      tagName: \"code\",\n      properties: {},\n      children: syntheticLines\n    };\n    let transformedCode = syntheticCode;\n    for (const transformer of transformers)\n      transformedCode = transformer?.code?.call(context, transformedCode) || transformedCode;\n    root.children = [];\n    for (let i = 0; i < transformedCode.children.length; i++) {\n      if (i > 0)\n        root.children.push({ type: \"element\", tagName: \"br\", properties: {}, children: [] });\n      const line = transformedCode.children[i];\n      if (line.type === \"element\")\n        root.children.push(...line.children);\n    }\n  }\n  let result = root;\n  for (const transformer of transformers)\n    result = transformer?.root?.call(context, result) || result;\n  if (grammarState)\n    setLastGrammarStateToMap(result, grammarState);\n  return result;\n}\nfunction mergeWhitespaceTokens(tokens) {\n  return tokens.map((line) => {\n    const newLine = [];\n    let carryOnContent = \"\";\n    let firstOffset;\n    line.forEach((token, idx) => {\n      const isDecorated = token.fontStyle && (token.fontStyle & FontStyle.Underline || token.fontStyle & FontStyle.Strikethrough);\n      const couldMerge = !isDecorated;\n      if (couldMerge && token.content.match(/^\\s+$/) && line[idx + 1]) {\n        if (firstOffset === void 0)\n          firstOffset = token.offset;\n        carryOnContent += token.content;\n      } else {\n        if (carryOnContent) {\n          if (couldMerge) {\n            newLine.push({\n              ...token,\n              offset: firstOffset,\n              content: carryOnContent + token.content\n            });\n          } else {\n            newLine.push(\n              {\n                content: carryOnContent,\n                offset: firstOffset\n              },\n              token\n            );\n          }\n          firstOffset = void 0;\n          carryOnContent = \"\";\n        } else {\n          newLine.push(token);\n        }\n      }\n    });\n    return newLine;\n  });\n}\nfunction splitWhitespaceTokens(tokens) {\n  return tokens.map((line) => {\n    return line.flatMap((token) => {\n      if (token.content.match(/^\\s+$/))\n        return token;\n      const match = token.content.match(/^(\\s*)(.*?)(\\s*)$/);\n      if (!match)\n        return token;\n      const [, leading, content, trailing] = match;\n      if (!leading && !trailing)\n        return token;\n      const expanded = [{\n        ...token,\n        offset: token.offset + leading.length,\n        content\n      }];\n      if (leading) {\n        expanded.unshift({\n          content: leading,\n          offset: token.offset\n        });\n      }\n      if (trailing) {\n        expanded.push({\n          content: trailing,\n          offset: token.offset + leading.length + content.length\n        });\n      }\n      return expanded;\n    });\n  });\n}\nfunction mergeAdjacentStyledTokens(tokens) {\n  return tokens.map((line) => {\n    const newLine = [];\n    for (const token of line) {\n      if (newLine.length === 0) {\n        newLine.push({ ...token });\n        continue;\n      }\n      const prevToken = newLine[newLine.length - 1];\n      const prevStyle = stringifyTokenStyle(prevToken.htmlStyle || getTokenStyleObject(prevToken));\n      const currentStyle = stringifyTokenStyle(token.htmlStyle || getTokenStyleObject(token));\n      const isPrevDecorated = prevToken.fontStyle && (prevToken.fontStyle & FontStyle.Underline || prevToken.fontStyle & FontStyle.Strikethrough);\n      const isDecorated = token.fontStyle && (token.fontStyle & FontStyle.Underline || token.fontStyle & FontStyle.Strikethrough);\n      if (!isPrevDecorated && !isDecorated && prevStyle === currentStyle) {\n        prevToken.content += token.content;\n      } else {\n        newLine.push({ ...token });\n      }\n    }\n    return newLine;\n  });\n}\n\nconst hastToHtml = toHtml;\nfunction codeToHtml(internal, code, options) {\n  const context = {\n    meta: {},\n    options,\n    codeToHast: (_code, _options) => codeToHast(internal, _code, _options),\n    codeToTokens: (_code, _options) => codeToTokens(internal, _code, _options)\n  };\n  let result = hastToHtml(codeToHast(internal, code, options, context));\n  for (const transformer of getTransformers(options))\n    result = transformer.postprocess?.call(context, result, options) || result;\n  return result;\n}\n\nconst VSCODE_FALLBACK_EDITOR_FG = { light: \"#333333\", dark: \"#bbbbbb\" };\nconst VSCODE_FALLBACK_EDITOR_BG = { light: \"#fffffe\", dark: \"#1e1e1e\" };\nconst RESOLVED_KEY = \"__shiki_resolved\";\nfunction normalizeTheme(rawTheme) {\n  if (rawTheme?.[RESOLVED_KEY])\n    return rawTheme;\n  const theme = {\n    ...rawTheme\n  };\n  if (theme.tokenColors && !theme.settings) {\n    theme.settings = theme.tokenColors;\n    delete theme.tokenColors;\n  }\n  theme.type ||= \"dark\";\n  theme.colorReplacements = { ...theme.colorReplacements };\n  theme.settings ||= [];\n  let { bg, fg } = theme;\n  if (!bg || !fg) {\n    const globalSetting = theme.settings ? theme.settings.find((s) => !s.name && !s.scope) : void 0;\n    if (globalSetting?.settings?.foreground)\n      fg = globalSetting.settings.foreground;\n    if (globalSetting?.settings?.background)\n      bg = globalSetting.settings.background;\n    if (!fg && theme?.colors?.[\"editor.foreground\"])\n      fg = theme.colors[\"editor.foreground\"];\n    if (!bg && theme?.colors?.[\"editor.background\"])\n      bg = theme.colors[\"editor.background\"];\n    if (!fg)\n      fg = theme.type === \"light\" ? VSCODE_FALLBACK_EDITOR_FG.light : VSCODE_FALLBACK_EDITOR_FG.dark;\n    if (!bg)\n      bg = theme.type === \"light\" ? VSCODE_FALLBACK_EDITOR_BG.light : VSCODE_FALLBACK_EDITOR_BG.dark;\n    theme.fg = fg;\n    theme.bg = bg;\n  }\n  if (!(theme.settings[0] && theme.settings[0].settings && !theme.settings[0].scope)) {\n    theme.settings.unshift({\n      settings: {\n        foreground: theme.fg,\n        background: theme.bg\n      }\n    });\n  }\n  let replacementCount = 0;\n  const replacementMap = /* @__PURE__ */ new Map();\n  function getReplacementColor(value) {\n    if (replacementMap.has(value))\n      return replacementMap.get(value);\n    replacementCount += 1;\n    const hex = `#${replacementCount.toString(16).padStart(8, \"0\").toLowerCase()}`;\n    if (theme.colorReplacements?.[`#${hex}`])\n      return getReplacementColor(value);\n    replacementMap.set(value, hex);\n    return hex;\n  }\n  theme.settings = theme.settings.map((setting) => {\n    const replaceFg = setting.settings?.foreground && !setting.settings.foreground.startsWith(\"#\");\n    const replaceBg = setting.settings?.background && !setting.settings.background.startsWith(\"#\");\n    if (!replaceFg && !replaceBg)\n      return setting;\n    const clone = {\n      ...setting,\n      settings: {\n        ...setting.settings\n      }\n    };\n    if (replaceFg) {\n      const replacement = getReplacementColor(setting.settings.foreground);\n      theme.colorReplacements[replacement] = setting.settings.foreground;\n      clone.settings.foreground = replacement;\n    }\n    if (replaceBg) {\n      const replacement = getReplacementColor(setting.settings.background);\n      theme.colorReplacements[replacement] = setting.settings.background;\n      clone.settings.background = replacement;\n    }\n    return clone;\n  });\n  for (const key of Object.keys(theme.colors || {})) {\n    if (key === \"editor.foreground\" || key === \"editor.background\" || key.startsWith(\"terminal.ansi\")) {\n      if (!theme.colors[key]?.startsWith(\"#\")) {\n        const replacement = getReplacementColor(theme.colors[key]);\n        theme.colorReplacements[replacement] = theme.colors[key];\n        theme.colors[key] = replacement;\n      }\n    }\n  }\n  Object.defineProperty(theme, RESOLVED_KEY, {\n    enumerable: false,\n    writable: false,\n    value: true\n  });\n  return theme;\n}\n\nasync function resolveLangs(langs) {\n  return Array.from(new Set((await Promise.all(\n    langs.filter((l) => !isSpecialLang(l)).map(async (lang) => await normalizeGetter(lang).then((r) => Array.isArray(r) ? r : [r]))\n  )).flat()));\n}\nasync function resolveThemes(themes) {\n  const resolved = await Promise.all(\n    themes.map(\n      async (theme) => isSpecialTheme(theme) ? null : normalizeTheme(await normalizeGetter(theme))\n    )\n  );\n  return resolved.filter((i) => !!i);\n}\n\nlet _emitDeprecation = 3;\nlet _emitError = false;\nfunction enableDeprecationWarnings(emitDeprecation = true, emitError = false) {\n  _emitDeprecation = emitDeprecation;\n  _emitError = emitError;\n}\nfunction warnDeprecated(message, version = 3) {\n  if (!_emitDeprecation)\n    return;\n  if (typeof _emitDeprecation === \"number\" && version > _emitDeprecation)\n    return;\n  if (_emitError) {\n    throw new Error(`[SHIKI DEPRECATE]: ${message}`);\n  } else {\n    console.trace(`[SHIKI DEPRECATE]: ${message}`);\n  }\n}\n\nclass ShikiError extends Error {\n  constructor(message) {\n    super(message);\n    this.name = \"ShikiError\";\n  }\n}\n\nfunction resolveLangAlias(name, alias) {\n  if (!alias)\n    return name;\n  if (alias[name]) {\n    const resolved = /* @__PURE__ */ new Set([name]);\n    while (alias[name]) {\n      name = alias[name];\n      if (resolved.has(name))\n        throw new ShikiError(`Circular alias \\`${Array.from(resolved).join(\" -> \")} -> ${name}\\``);\n      resolved.add(name);\n    }\n  }\n  return name;\n}\n\nclass Registry extends Registry$1 {\n  constructor(_resolver, _themes, _langs, _alias = {}) {\n    super(_resolver);\n    this._resolver = _resolver;\n    this._themes = _themes;\n    this._langs = _langs;\n    this._alias = _alias;\n    this._themes.map((t) => this.loadTheme(t));\n    this.loadLanguages(this._langs);\n  }\n  _resolvedThemes = /* @__PURE__ */ new Map();\n  _resolvedGrammars = /* @__PURE__ */ new Map();\n  _langMap = /* @__PURE__ */ new Map();\n  _langGraph = /* @__PURE__ */ new Map();\n  _textmateThemeCache = /* @__PURE__ */ new WeakMap();\n  _loadedThemesCache = null;\n  _loadedLanguagesCache = null;\n  getTheme(theme) {\n    if (typeof theme === \"string\")\n      return this._resolvedThemes.get(theme);\n    else\n      return this.loadTheme(theme);\n  }\n  loadTheme(theme) {\n    const _theme = normalizeTheme(theme);\n    if (_theme.name) {\n      this._resolvedThemes.set(_theme.name, _theme);\n      this._loadedThemesCache = null;\n    }\n    return _theme;\n  }\n  getLoadedThemes() {\n    if (!this._loadedThemesCache)\n      this._loadedThemesCache = [...this._resolvedThemes.keys()];\n    return this._loadedThemesCache;\n  }\n  // Override and re-implement this method to cache the textmate themes as `TextMateTheme.createFromRawTheme`\n  // is expensive. Themes can switch often especially for dual-theme support.\n  //\n  // The parent class also accepts `colorMap` as the second parameter, but since we don't use that,\n  // we omit here so it's easier to cache the themes.\n  setTheme(theme) {\n    let textmateTheme = this._textmateThemeCache.get(theme);\n    if (!textmateTheme) {\n      textmateTheme = Theme.createFromRawTheme(theme);\n      this._textmateThemeCache.set(theme, textmateTheme);\n    }\n    this._syncRegistry.setTheme(textmateTheme);\n  }\n  getGrammar(name) {\n    name = resolveLangAlias(name, this._alias);\n    return this._resolvedGrammars.get(name);\n  }\n  loadLanguage(lang) {\n    if (this.getGrammar(lang.name))\n      return;\n    const embeddedLazilyBy = new Set(\n      [...this._langMap.values()].filter((i) => i.embeddedLangsLazy?.includes(lang.name))\n    );\n    this._resolver.addLanguage(lang);\n    const grammarConfig = {\n      balancedBracketSelectors: lang.balancedBracketSelectors || [\"*\"],\n      unbalancedBracketSelectors: lang.unbalancedBracketSelectors || []\n    };\n    this._syncRegistry._rawGrammars.set(lang.scopeName, lang);\n    const g = this.loadGrammarWithConfiguration(lang.scopeName, 1, grammarConfig);\n    g.name = lang.name;\n    this._resolvedGrammars.set(lang.name, g);\n    if (lang.aliases) {\n      lang.aliases.forEach((alias) => {\n        this._alias[alias] = lang.name;\n      });\n    }\n    this._loadedLanguagesCache = null;\n    if (embeddedLazilyBy.size) {\n      for (const e of embeddedLazilyBy) {\n        this._resolvedGrammars.delete(e.name);\n        this._loadedLanguagesCache = null;\n        this._syncRegistry?._injectionGrammars?.delete(e.scopeName);\n        this._syncRegistry?._grammars?.delete(e.scopeName);\n        this.loadLanguage(this._langMap.get(e.name));\n      }\n    }\n  }\n  dispose() {\n    super.dispose();\n    this._resolvedThemes.clear();\n    this._resolvedGrammars.clear();\n    this._langMap.clear();\n    this._langGraph.clear();\n    this._loadedThemesCache = null;\n  }\n  loadLanguages(langs) {\n    for (const lang of langs)\n      this.resolveEmbeddedLanguages(lang);\n    const langsGraphArray = Array.from(this._langGraph.entries());\n    const missingLangs = langsGraphArray.filter(([_, lang]) => !lang);\n    if (missingLangs.length) {\n      const dependents = langsGraphArray.filter(([_, lang]) => {\n        if (!lang)\n          return false;\n        const embedded = lang.embeddedLanguages || lang.embeddedLangs;\n        return embedded?.some((l) => missingLangs.map(([name]) => name).includes(l));\n      }).filter((lang) => !missingLangs.includes(lang));\n      throw new ShikiError(`Missing languages ${missingLangs.map(([name]) => `\\`${name}\\``).join(\", \")}, required by ${dependents.map(([name]) => `\\`${name}\\``).join(\", \")}`);\n    }\n    for (const [_, lang] of langsGraphArray)\n      this._resolver.addLanguage(lang);\n    for (const [_, lang] of langsGraphArray)\n      this.loadLanguage(lang);\n  }\n  getLoadedLanguages() {\n    if (!this._loadedLanguagesCache) {\n      this._loadedLanguagesCache = [\n        .../* @__PURE__ */ new Set([...this._resolvedGrammars.keys(), ...Object.keys(this._alias)])\n      ];\n    }\n    return this._loadedLanguagesCache;\n  }\n  resolveEmbeddedLanguages(lang) {\n    this._langMap.set(lang.name, lang);\n    this._langGraph.set(lang.name, lang);\n    const embedded = lang.embeddedLanguages ?? lang.embeddedLangs;\n    if (embedded) {\n      for (const embeddedLang of embedded)\n        this._langGraph.set(embeddedLang, this._langMap.get(embeddedLang));\n    }\n  }\n}\n\nclass Resolver {\n  _langs = /* @__PURE__ */ new Map();\n  _scopeToLang = /* @__PURE__ */ new Map();\n  _injections = /* @__PURE__ */ new Map();\n  _onigLib;\n  constructor(engine, langs) {\n    this._onigLib = {\n      createOnigScanner: (patterns) => engine.createScanner(patterns),\n      createOnigString: (s) => engine.createString(s)\n    };\n    langs.forEach((i) => this.addLanguage(i));\n  }\n  get onigLib() {\n    return this._onigLib;\n  }\n  getLangRegistration(langIdOrAlias) {\n    return this._langs.get(langIdOrAlias);\n  }\n  loadGrammar(scopeName) {\n    return this._scopeToLang.get(scopeName);\n  }\n  addLanguage(l) {\n    this._langs.set(l.name, l);\n    if (l.aliases) {\n      l.aliases.forEach((a) => {\n        this._langs.set(a, l);\n      });\n    }\n    this._scopeToLang.set(l.scopeName, l);\n    if (l.injectTo) {\n      l.injectTo.forEach((i) => {\n        if (!this._injections.get(i))\n          this._injections.set(i, []);\n        this._injections.get(i).push(l.scopeName);\n      });\n    }\n  }\n  getInjections(scopeName) {\n    const scopeParts = scopeName.split(\".\");\n    let injections = [];\n    for (let i = 1; i <= scopeParts.length; i++) {\n      const subScopeName = scopeParts.slice(0, i).join(\".\");\n      injections = [...injections, ...this._injections.get(subScopeName) || []];\n    }\n    return injections;\n  }\n}\n\nlet instancesCount = 0;\nfunction createShikiInternalSync(options) {\n  instancesCount += 1;\n  if (options.warnings !== false && instancesCount >= 10 && instancesCount % 10 === 0)\n    console.warn(`[Shiki] ${instancesCount} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \\`highlighter.dispose()\\` to release unused instances.`);\n  let isDisposed = false;\n  if (!options.engine)\n    throw new ShikiError(\"`engine` option is required for synchronous mode\");\n  const langs = (options.langs || []).flat(1);\n  const themes = (options.themes || []).flat(1).map(normalizeTheme);\n  const resolver = new Resolver(options.engine, langs);\n  const _registry = new Registry(resolver, themes, langs, options.langAlias);\n  let _lastTheme;\n  function resolveLangAlias$1(name) {\n    return resolveLangAlias(name, options.langAlias);\n  }\n  function getLanguage(name) {\n    ensureNotDisposed();\n    const _lang = _registry.getGrammar(typeof name === \"string\" ? name : name.name);\n    if (!_lang)\n      throw new ShikiError(`Language \\`${name}\\` not found, you may need to load it first`);\n    return _lang;\n  }\n  function getTheme(name) {\n    if (name === \"none\")\n      return { bg: \"\", fg: \"\", name: \"none\", settings: [], type: \"dark\" };\n    ensureNotDisposed();\n    const _theme = _registry.getTheme(name);\n    if (!_theme)\n      throw new ShikiError(`Theme \\`${name}\\` not found, you may need to load it first`);\n    return _theme;\n  }\n  function setTheme(name) {\n    ensureNotDisposed();\n    const theme = getTheme(name);\n    if (_lastTheme !== name) {\n      _registry.setTheme(theme);\n      _lastTheme = name;\n    }\n    const colorMap = _registry.getColorMap();\n    return {\n      theme,\n      colorMap\n    };\n  }\n  function getLoadedThemes() {\n    ensureNotDisposed();\n    return _registry.getLoadedThemes();\n  }\n  function getLoadedLanguages() {\n    ensureNotDisposed();\n    return _registry.getLoadedLanguages();\n  }\n  function loadLanguageSync(...langs2) {\n    ensureNotDisposed();\n    _registry.loadLanguages(langs2.flat(1));\n  }\n  async function loadLanguage(...langs2) {\n    return loadLanguageSync(await resolveLangs(langs2));\n  }\n  function loadThemeSync(...themes2) {\n    ensureNotDisposed();\n    for (const theme of themes2.flat(1)) {\n      _registry.loadTheme(theme);\n    }\n  }\n  async function loadTheme(...themes2) {\n    ensureNotDisposed();\n    return loadThemeSync(await resolveThemes(themes2));\n  }\n  function ensureNotDisposed() {\n    if (isDisposed)\n      throw new ShikiError(\"Shiki instance has been disposed\");\n  }\n  function dispose() {\n    if (isDisposed)\n      return;\n    isDisposed = true;\n    _registry.dispose();\n    instancesCount -= 1;\n  }\n  return {\n    setTheme,\n    getTheme,\n    getLanguage,\n    getLoadedThemes,\n    getLoadedLanguages,\n    resolveLangAlias: resolveLangAlias$1,\n    loadLanguage,\n    loadLanguageSync,\n    loadTheme,\n    loadThemeSync,\n    dispose,\n    [Symbol.dispose]: dispose\n  };\n}\n\nasync function createShikiInternal(options) {\n  if (!options.engine) {\n    warnDeprecated(\"`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.\");\n  }\n  const [\n    themes,\n    langs,\n    engine\n  ] = await Promise.all([\n    resolveThemes(options.themes || []),\n    resolveLangs(options.langs || []),\n    options.engine\n  ]);\n  return createShikiInternalSync({\n    ...options,\n    themes,\n    langs,\n    engine\n  });\n}\n\nasync function createHighlighterCore(options) {\n  const internal = await createShikiInternal(options);\n  return {\n    getLastGrammarState: (...args) => getLastGrammarState(internal, ...args),\n    codeToTokensBase: (code, options2) => codeToTokensBase(internal, code, options2),\n    codeToTokensWithThemes: (code, options2) => codeToTokensWithThemes(internal, code, options2),\n    codeToTokens: (code, options2) => codeToTokens(internal, code, options2),\n    codeToHast: (code, options2) => codeToHast(internal, code, options2),\n    codeToHtml: (code, options2) => codeToHtml(internal, code, options2),\n    getBundledLanguages: () => ({}),\n    getBundledThemes: () => ({}),\n    ...internal,\n    getInternalContext: () => internal\n  };\n}\nfunction createHighlighterCoreSync(options) {\n  const internal = createShikiInternalSync(options);\n  return {\n    getLastGrammarState: (...args) => getLastGrammarState(internal, ...args),\n    codeToTokensBase: (code, options2) => codeToTokensBase(internal, code, options2),\n    codeToTokensWithThemes: (code, options2) => codeToTokensWithThemes(internal, code, options2),\n    codeToTokens: (code, options2) => codeToTokens(internal, code, options2),\n    codeToHast: (code, options2) => codeToHast(internal, code, options2),\n    codeToHtml: (code, options2) => codeToHtml(internal, code, options2),\n    getBundledLanguages: () => ({}),\n    getBundledThemes: () => ({}),\n    ...internal,\n    getInternalContext: () => internal\n  };\n}\nfunction makeSingletonHighlighterCore(createHighlighter) {\n  let _shiki;\n  async function getSingletonHighlighterCore2(options) {\n    if (!_shiki) {\n      _shiki = createHighlighter({\n        ...options,\n        themes: options.themes || [],\n        langs: options.langs || []\n      });\n      return _shiki;\n    } else {\n      const s = await _shiki;\n      await Promise.all([\n        s.loadTheme(...options.themes || []),\n        s.loadLanguage(...options.langs || [])\n      ]);\n      return s;\n    }\n  }\n  return getSingletonHighlighterCore2;\n}\nconst getSingletonHighlighterCore = /* @__PURE__ */ makeSingletonHighlighterCore(createHighlighterCore);\n\nfunction createBundledHighlighter(options) {\n  const bundledLanguages = options.langs;\n  const bundledThemes = options.themes;\n  const engine = options.engine;\n  async function createHighlighter(options2) {\n    function resolveLang(lang) {\n      if (typeof lang === \"string\") {\n        lang = options2.langAlias?.[lang] || lang;\n        if (isSpecialLang(lang))\n          return [];\n        const bundle = bundledLanguages[lang];\n        if (!bundle)\n          throw new ShikiError$1(`Language \\`${lang}\\` is not included in this bundle. You may want to load it from external source.`);\n        return bundle;\n      }\n      return lang;\n    }\n    function resolveTheme(theme) {\n      if (isSpecialTheme(theme))\n        return \"none\";\n      if (typeof theme === \"string\") {\n        const bundle = bundledThemes[theme];\n        if (!bundle)\n          throw new ShikiError$1(`Theme \\`${theme}\\` is not included in this bundle. You may want to load it from external source.`);\n        return bundle;\n      }\n      return theme;\n    }\n    const _themes = (options2.themes ?? []).map((i) => resolveTheme(i));\n    const langs = (options2.langs ?? []).map((i) => resolveLang(i));\n    const core = await createHighlighterCore({\n      engine: options2.engine ?? engine(),\n      ...options2,\n      themes: _themes,\n      langs\n    });\n    return {\n      ...core,\n      loadLanguage(...langs2) {\n        return core.loadLanguage(...langs2.map(resolveLang));\n      },\n      loadTheme(...themes) {\n        return core.loadTheme(...themes.map(resolveTheme));\n      },\n      getBundledLanguages() {\n        return bundledLanguages;\n      },\n      getBundledThemes() {\n        return bundledThemes;\n      }\n    };\n  }\n  return createHighlighter;\n}\nfunction makeSingletonHighlighter(createHighlighter) {\n  let _shiki;\n  async function getSingletonHighlighter(options = {}) {\n    if (!_shiki) {\n      _shiki = createHighlighter({\n        ...options,\n        themes: [],\n        langs: []\n      });\n      const s = await _shiki;\n      await Promise.all([\n        s.loadTheme(...options.themes || []),\n        s.loadLanguage(...options.langs || [])\n      ]);\n      return s;\n    } else {\n      const s = await _shiki;\n      await Promise.all([\n        s.loadTheme(...options.themes || []),\n        s.loadLanguage(...options.langs || [])\n      ]);\n      return s;\n    }\n  }\n  return getSingletonHighlighter;\n}\nfunction createSingletonShorthands(createHighlighter, config) {\n  const getSingletonHighlighter = makeSingletonHighlighter(createHighlighter);\n  async function get(code, options) {\n    const shiki = await getSingletonHighlighter({\n      langs: [options.lang],\n      themes: \"theme\" in options ? [options.theme] : Object.values(options.themes)\n    });\n    const langs = await config?.guessEmbeddedLanguages?.(code, options.lang, shiki);\n    if (langs) {\n      await shiki.loadLanguage(...langs);\n    }\n    return shiki;\n  }\n  return {\n    getSingletonHighlighter(options) {\n      return getSingletonHighlighter(options);\n    },\n    async codeToHtml(code, options) {\n      const shiki = await get(code, options);\n      return shiki.codeToHtml(code, options);\n    },\n    async codeToHast(code, options) {\n      const shiki = await get(code, options);\n      return shiki.codeToHast(code, options);\n    },\n    async codeToTokens(code, options) {\n      const shiki = await get(code, options);\n      return shiki.codeToTokens(code, options);\n    },\n    async codeToTokensBase(code, options) {\n      const shiki = await get(code, options);\n      return shiki.codeToTokensBase(code, options);\n    },\n    async codeToTokensWithThemes(code, options) {\n      const shiki = await get(code, options);\n      return shiki.codeToTokensWithThemes(code, options);\n    },\n    async getLastGrammarState(code, options) {\n      const shiki = await getSingletonHighlighter({\n        langs: [options.lang],\n        themes: [options.theme]\n      });\n      return shiki.getLastGrammarState(code, options);\n    }\n  };\n}\nconst createdBundledHighlighter = createBundledHighlighter;\n\nfunction createCssVariablesTheme(options = {}) {\n  const {\n    name = \"css-variables\",\n    variablePrefix = \"--shiki-\",\n    fontStyle = true\n  } = options;\n  const variable = (name2) => {\n    if (options.variableDefaults?.[name2])\n      return `var(${variablePrefix}${name2}, ${options.variableDefaults[name2]})`;\n    return `var(${variablePrefix}${name2})`;\n  };\n  const theme = {\n    name,\n    type: \"dark\",\n    colors: {\n      \"editor.foreground\": variable(\"foreground\"),\n      \"editor.background\": variable(\"background\"),\n      \"terminal.ansiBlack\": variable(\"ansi-black\"),\n      \"terminal.ansiRed\": variable(\"ansi-red\"),\n      \"terminal.ansiGreen\": variable(\"ansi-green\"),\n      \"terminal.ansiYellow\": variable(\"ansi-yellow\"),\n      \"terminal.ansiBlue\": variable(\"ansi-blue\"),\n      \"terminal.ansiMagenta\": variable(\"ansi-magenta\"),\n      \"terminal.ansiCyan\": variable(\"ansi-cyan\"),\n      \"terminal.ansiWhite\": variable(\"ansi-white\"),\n      \"terminal.ansiBrightBlack\": variable(\"ansi-bright-black\"),\n      \"terminal.ansiBrightRed\": variable(\"ansi-bright-red\"),\n      \"terminal.ansiBrightGreen\": variable(\"ansi-bright-green\"),\n      \"terminal.ansiBrightYellow\": variable(\"ansi-bright-yellow\"),\n      \"terminal.ansiBrightBlue\": variable(\"ansi-bright-blue\"),\n      \"terminal.ansiBrightMagenta\": variable(\"ansi-bright-magenta\"),\n      \"terminal.ansiBrightCyan\": variable(\"ansi-bright-cyan\"),\n      \"terminal.ansiBrightWhite\": variable(\"ansi-bright-white\")\n    },\n    tokenColors: [\n      {\n        scope: [\n          \"keyword.operator.accessor\",\n          \"meta.group.braces.round.function.arguments\",\n          \"meta.template.expression\",\n          \"markup.fenced_code meta.embedded.block\"\n        ],\n        settings: {\n          foreground: variable(\"foreground\")\n        }\n      },\n      {\n        scope: \"emphasis\",\n        settings: {\n          fontStyle: \"italic\"\n        }\n      },\n      {\n        scope: [\"strong\", \"markup.heading.markdown\", \"markup.bold.markdown\"],\n        settings: {\n          fontStyle: \"bold\"\n        }\n      },\n      {\n        scope: [\"markup.italic.markdown\"],\n        settings: {\n          fontStyle: \"italic\"\n        }\n      },\n      {\n        scope: \"meta.link.inline.markdown\",\n        settings: {\n          fontStyle: \"underline\",\n          foreground: variable(\"token-link\")\n        }\n      },\n      {\n        scope: [\"string\", \"markup.fenced_code\", \"markup.inline\"],\n        settings: {\n          foreground: variable(\"token-string\")\n        }\n      },\n      {\n        scope: [\"comment\", \"string.quoted.docstring.multi\"],\n        settings: {\n          foreground: variable(\"token-comment\")\n        }\n      },\n      {\n        scope: [\n          \"constant.numeric\",\n          \"constant.language\",\n          \"constant.other.placeholder\",\n          \"constant.character.format.placeholder\",\n          \"variable.language.this\",\n          \"variable.other.object\",\n          \"variable.other.class\",\n          \"variable.other.constant\",\n          \"meta.property-name\",\n          \"meta.property-value\",\n          \"support\"\n        ],\n        settings: {\n          foreground: variable(\"token-constant\")\n        }\n      },\n      {\n        scope: [\n          \"keyword\",\n          \"storage.modifier\",\n          \"storage.type\",\n          \"storage.control.clojure\",\n          \"entity.name.function.clojure\",\n          \"entity.name.tag.yaml\",\n          \"support.function.node\",\n          \"support.type.property-name.json\",\n          \"punctuation.separator.key-value\",\n          \"punctuation.definition.template-expression\"\n        ],\n        settings: {\n          foreground: variable(\"token-keyword\")\n        }\n      },\n      {\n        scope: \"variable.parameter.function\",\n        settings: {\n          foreground: variable(\"token-parameter\")\n        }\n      },\n      {\n        scope: [\n          \"support.function\",\n          \"entity.name.type\",\n          \"entity.other.inherited-class\",\n          \"meta.function-call\",\n          \"meta.instance.constructor\",\n          \"entity.other.attribute-name\",\n          \"entity.name.function\",\n          \"constant.keyword.clojure\"\n        ],\n        settings: {\n          foreground: variable(\"token-function\")\n        }\n      },\n      {\n        scope: [\n          \"entity.name.tag\",\n          \"string.quoted\",\n          \"string.regexp\",\n          \"string.interpolated\",\n          \"string.template\",\n          \"string.unquoted.plain.out.yaml\",\n          \"keyword.other.template\"\n        ],\n        settings: {\n          foreground: variable(\"token-string-expression\")\n        }\n      },\n      {\n        scope: [\n          \"punctuation.definition.arguments\",\n          \"punctuation.definition.dict\",\n          \"punctuation.separator\",\n          \"meta.function-call.arguments\"\n        ],\n        settings: {\n          foreground: variable(\"token-punctuation\")\n        }\n      },\n      {\n        // [Custom] Markdown links\n        scope: [\n          \"markup.underline.link\",\n          \"punctuation.definition.metadata.markdown\"\n        ],\n        settings: {\n          foreground: variable(\"token-link\")\n        }\n      },\n      {\n        // [Custom] Markdown list\n        scope: [\"beginning.punctuation.definition.list.markdown\"],\n        settings: {\n          foreground: variable(\"token-string\")\n        }\n      },\n      {\n        // [Custom] Markdown punctuation definition brackets\n        scope: [\n          \"punctuation.definition.string.begin.markdown\",\n          \"punctuation.definition.string.end.markdown\",\n          \"string.other.link.title.markdown\",\n          \"string.other.link.description.markdown\"\n        ],\n        settings: {\n          foreground: variable(\"token-keyword\")\n        }\n      },\n      {\n        // [Custom] Diff\n        scope: [\n          \"markup.inserted\",\n          \"meta.diff.header.to-file\",\n          \"punctuation.definition.inserted\"\n        ],\n        settings: {\n          foreground: variable(\"token-inserted\")\n        }\n      },\n      {\n        scope: [\n          \"markup.deleted\",\n          \"meta.diff.header.from-file\",\n          \"punctuation.definition.deleted\"\n        ],\n        settings: {\n          foreground: variable(\"token-deleted\")\n        }\n      },\n      {\n        scope: [\n          \"markup.changed\",\n          \"punctuation.definition.changed\"\n        ],\n        settings: {\n          foreground: variable(\"token-changed\")\n        }\n      }\n    ]\n  };\n  if (!fontStyle) {\n    theme.tokenColors = theme.tokenColors?.map((tokenColor) => {\n      if (tokenColor.settings?.fontStyle)\n        delete tokenColor.settings.fontStyle;\n      return tokenColor;\n    });\n  }\n  return theme;\n}\n\nexport { addClassToHast, applyColorReplacements, codeToHast, codeToHtml, codeToTokens, codeToTokensBase, codeToTokensWithThemes, createBundledHighlighter, createCssVariablesTheme, createHighlighterCore, createHighlighterCoreSync, createPositionConverter, createShikiInternal, createShikiInternalSync, createSingletonShorthands, createdBundledHighlighter, enableDeprecationWarnings, flatTokenVariants, getSingletonHighlighterCore, getTokenStyleObject, guessEmbeddedLanguages, hastToHtml, isNoneTheme, isPlainLang, isSpecialLang, isSpecialTheme, makeSingletonHighlighter, makeSingletonHighlighterCore, normalizeGetter, normalizeTheme, resolveColorReplacements, splitLines, splitToken, splitTokens, stringifyTokenStyle, toArray, tokenizeAnsiWithTheme, tokenizeWithTheme, tokensToHast, transformerDecorations, warnDeprecated };\n","function cpOf(char: string): number {\n  // Count code point length\n  if ([...char].length !== 1) {\n    throw new Error(`Expected \"${char}\" to be a single code point`);\n  }\n  return char.codePointAt(0)!;\n}\n\nfunction getOrInsert<Key, Value>(map: Map<Key, Value>, key: Key, defaultValue: Value): Value {\n  if (!map.has(key)) {\n    map.set(key, defaultValue);\n  }\n  return map.get(key)!;\n}\n\nconst PosixClassNames = new Set([\n  'alnum',\n  'alpha',\n  'ascii',\n  'blank',\n  'cntrl',\n  'digit',\n  'graph',\n  'lower',\n  'print',\n  'punct',\n  'space',\n  'upper',\n  'word',\n  'xdigit',\n]);\n\nconst r = String.raw;\n\nfunction throwIfNullish<Value>(value: Value, msg?: string): NonNullable<Value> {\n  if (value == null) {\n    throw new Error(msg ?? 'Value expected');\n  }\n  return value;\n}\n\nexport {\n  cpOf,\n  getOrInsert,\n  PosixClassNames,\n  r,\n  throwIfNullish,\n};\n","import {cpOf, PosixClassNames, r, throwIfNullish} from '../utils.js';\n\ntype Token =\n  AlternatorToken |\n  AssertionToken |\n  BackreferenceToken |\n  CharacterToken |\n  CharacterClassCloseToken |\n  CharacterClassHyphenToken |\n  CharacterClassIntersectorToken |\n  CharacterClassOpenToken |\n  CharacterSetToken |\n  DirectiveToken |\n  GroupCloseToken |\n  GroupOpenToken |\n  NamedCalloutToken |\n  QuantifierToken |\n  SubroutineToken;\n\ntype IntermediateToken =\n  EscapedNumberToken;\n\ntype TokenCharacterSetKind =\n  'any' |\n  'digit' |\n  'dot' |\n  'hex' |\n  'newline' |\n  'posix' |\n  'property' |\n  'space' |\n  'text_segment' |\n  'word';\n\ntype TokenDirectiveKind =\n  'flags' |\n  'keep';\n\ntype TokenGroupOpenKind =\n  'absence_repeater' |\n  'atomic' |\n  'capturing' |\n  'group' |\n  'lookahead' |\n  'lookbehind';\n\ntype TokenQuantifierKind =\n  'greedy' |\n  'lazy' |\n  'possessive';\n\ntype TokenNamedCalloutKind =\n  'count' |\n  'cmp' |\n  'error' |\n  'fail' |\n  'max' |\n  'mismatch' |\n  'skip' |\n  'total_count' |\n  'custom';\n\nconst charClassOpenPattern = r`\\[\\^?`;\nconst sharedEscapesPattern = `${\n  // Control char\n  'c.? | C(?:-.?)?'\n}|${\n  // Unicode property; Onig considers `\\p` an identity escape, but e.g. `\\p{`, `\\p{ ^L}`, and\n  // `\\p{gc=L}` are invalid\n  r`[pP]\\{(?:\\^?[-\\x20_]*[A-Za-z][-\\x20\\w]*\\})?`\n}|${\n  // Hex encoded byte sequence; attempt match before other `\\xNN` hex char\n  r`x[89A-Fa-f]\\p{AHex}(?:\\\\x[89A-Fa-f]\\p{AHex})*`\n}|${\n  // Hex char\n  r`u(?:\\p{AHex}{4})? | x\\{[^\\}]*\\}? | x\\p{AHex}{0,2}`\n}|${\n  // Enclosed octal code point\n  r`o\\{[^\\}]*\\}?`\n}|${\n  // Escaped number\n  r`\\d{1,3}`\n}`;\n// Even with flag x, Onig doesn't allow whitespace to separate a quantifier from the `?` or `+`\n// that makes it lazy or possessive. Possessive suffixes don't apply to interval quantifiers\nconst quantifierRe = /[?*+][?+]?|\\{(?:\\d+(?:,\\d*)?|,\\d+)\\}\\??/;\nconst tokenRe = new RegExp(r`\n  \\\\ (?:\n    ${sharedEscapesPattern}\n    | [gk]<[^>]*>?\n    | [gk]'[^']*'?\n    | .\n  )\n  | \\( (?:\n    \\? (?:\n      [:=!>({]\n      | <[=!]\n      | <[^>]*>\n      | '[^']*'\n      | ~\\|?\n      | #(?:[^)\\\\]|\\\\.?)*\n      | [^:)]*[:)]\n    )?\n    | \\*[^\\)]*\\)?\n  )?\n  | (?:${quantifierRe.source})+\n  | ${charClassOpenPattern}\n  | .\n`.replace(/\\s+/g, ''), 'gsu');\nconst charClassTokenRe = new RegExp(r`\n  \\\\ (?:\n    ${sharedEscapesPattern}\n    | .\n  )\n  | \\[:(?:\\^?\\p{Alpha}+|\\^):\\]\n  | ${charClassOpenPattern}\n  | &&\n  | .\n`.replace(/\\s+/g, ''), 'gsu');\n\ntype Context = {\n  captureGroup: boolean;\n  getCurrentModX(): boolean;\n  numOpenGroups: number;\n  popModX(): void;\n  pushModX(isXOn: boolean): void;\n  replaceCurrentModX(isXOn: boolean): void;\n  singleline: boolean;\n};\n\ntype TokenizeOptions = {\n  flags?: string;\n  rules?: {\n    captureGroup?: boolean;\n    singleline?: boolean;\n  };\n};\n\nfunction tokenize(pattern: string, options: TokenizeOptions = {}): {\n  tokens: Array<Token>;\n  flags: FlagProperties;\n} {\n  const opts = {\n    flags: '',\n    ...options,\n    rules: {\n      captureGroup: false, // `ONIG_OPTION_CAPTURE_GROUP`\n      singleline: false, // `ONIG_OPTION_SINGLELINE`\n      ...options.rules,\n    },\n  };\n  if (typeof pattern !== 'string') {\n    throw new Error('String expected as pattern');\n  }\n  const flagProperties = getFlagProperties(opts.flags);\n  const xStack = [flagProperties.extended];\n  const context: Context = {\n    captureGroup: opts.rules.captureGroup,\n    // Always at least has the top-level flag x\n    getCurrentModX() {return xStack.at(-1)!},\n    numOpenGroups: 0,\n    popModX() {xStack.pop()},\n    pushModX(isXOn) {xStack.push(isXOn)},\n    replaceCurrentModX(isXOn) {xStack[xStack.length - 1] = isXOn},\n    singleline: opts.rules.singleline,\n  };\n  let tokens: Array<Token | IntermediateToken> = [];\n  let match: RegExpExecArray | null;\n  tokenRe.lastIndex = 0;\n  while ((match = tokenRe.exec(pattern))) {\n    const result = getTokenWithDetails(context, pattern, match[0], tokenRe.lastIndex);\n    if (result.tokens) {\n      tokens.push(...result.tokens);\n    } else if (result.token) {\n      tokens.push(result.token);\n    }\n    if (result.lastIndex !== undefined) {\n      tokenRe.lastIndex = result.lastIndex;\n    }\n  }\n\n  const potentialUnnamedCaptureTokens: Array<GroupOpenToken> = [];\n  let numNamedAndOptInUnnamedCaptures = 0;\n  tokens.filter(t => t.type === 'GroupOpen').forEach(t => {\n    if (t.kind === 'capturing') {\n      t.number = ++numNamedAndOptInUnnamedCaptures;\n    } else if (t.raw === '(') {\n      potentialUnnamedCaptureTokens.push(t);\n    }\n  });\n  // Enable unnamed capturing groups if no named captures (when `captureGroup` not enabled)\n  if (!numNamedAndOptInUnnamedCaptures) {\n    potentialUnnamedCaptureTokens.forEach((t, i) => {\n      t.kind = 'capturing';\n      t.number = i + 1;\n    });\n  }\n  const numCaptures = numNamedAndOptInUnnamedCaptures || potentialUnnamedCaptureTokens.length;\n  // Can now split escaped nums accurately, accounting for number of captures\n  const tokensWithoutIntermediate = tokens.map(\n    t => t.type === 'EscapedNumber' ? splitEscapedNumberToken(t, numCaptures) : t\n  ).flat();\n\n  return {\n    tokens: tokensWithoutIntermediate,\n    flags: flagProperties,\n  };\n}\n\nfunction getTokenWithDetails(context: Context, pattern: string, m: string, lastIndex: number): {\n  token: Token | IntermediateToken;\n  tokens?: never;\n  lastIndex?: number;\n} | {\n  token?: never;\n  tokens: Array<Token | IntermediateToken>;\n  lastIndex?: number;\n} | {\n  token?: never;\n  tokens?: never;\n  lastIndex: number;\n} {\n  const [m0, m1] = m;\n\n  if (m === '[' || m === '[^') {\n    const result = getAllTokensForCharClass(pattern, m, lastIndex);\n    return {\n      // Array of all of the char class's tokens\n      tokens: result.tokens,\n      // Jump forward to the end of the char class\n      lastIndex: result.lastIndex,\n    };\n  }\n\n  if (m0 === '\\\\') {\n    if ('AbBGyYzZ'.includes(m1)) {\n      return {\n        token: createAssertionToken(m, m),\n      };\n    }\n    if (/^\\\\g[<']/.test(m)) {\n      if (!/^\\\\g(?:<[^>]+>|'[^']+')$/.test(m)) {\n        throw new Error(`Invalid group name \"${m}\"`);\n      }\n      return {\n        token: createSubroutineToken(m),\n      };\n    }\n    if (/^\\\\k[<']/.test(m)) {\n      if (!/^\\\\k(?:<[^>]+>|'[^']+')$/.test(m)) {\n        throw new Error(`Invalid group name \"${m}\"`);\n      }\n      return {\n        token: createBackreferenceToken(m),\n      };\n    }\n    if (m1 === 'K') {\n      return {\n        token: createDirectiveToken('keep', m),\n      };\n    }\n    if (m1 === 'N' || m1 === 'R') {\n      return {\n        token: createCharacterSetToken('newline', m, {\n          // `\\N` and `\\R` are not actually opposites since the former only excludes `\\n`\n          negate: m1 === 'N',\n        }),\n      };\n    }\n    if (m1 === 'O') {\n      return {\n        token: createCharacterSetToken('any', m),\n      };\n    }\n    if (m1 === 'X') {\n      return {\n        token: createCharacterSetToken('text_segment', m),\n      };\n    }\n    // Run last since it assumes an identity escape as final condition\n    const result = tokenizeSharedEscape(m, {inCharClass: false});\n    return Array.isArray(result) ? {tokens: result} : {token: result};\n  }\n\n  if (m0 === '(') {\n    if (m1 === '*') {\n      return {\n        token: tokenizeNamedCallout(m),\n      };\n    }\n    if (m === '(?{') {\n      throw new Error(`Unsupported callout \"${m}\"`);\n    }\n    // Comment group\n    if (m.startsWith('(?#')) {\n      // Everything except the closing unescaped `)` is included in the match\n      if (pattern[lastIndex] !== ')') {\n        throw new Error('Unclosed comment group \"(?#\"');\n      }\n      return {\n        // Jump forward to after the closing paren\n        lastIndex: lastIndex + 1,\n      };\n    }\n    // Flag modifier (directive or group opener)\n    if (/^\\(\\?[-imx]+[:)]$/.test(m)) {\n      return {\n        token: tokenizeFlagModifier(m, context),\n      };\n    }\n    // --- Remaining group types all reuse current flag x status ---\n    context.pushModX(context.getCurrentModX());\n    context.numOpenGroups++;\n    if (\n      // Unnamed capture if no named captures present and `captureGroup` not enabled, else\n      // noncapturing group\n      (m === '(' && !context.captureGroup) ||\n      // Noncapturing group\n      m === '(?:'\n    ) {\n      return {\n        // For `(`, will later change to `capturing` and add `number` prop if no named captures\n        token: createGroupOpenToken('group', m),\n      };\n    }\n    // Atomic group\n    if (m === '(?>') {\n      return {\n        token: createGroupOpenToken('atomic', m),\n      };\n    }\n    // Lookaround\n    if (m === '(?=' || m === '(?!' || m === '(?<=' || m === '(?<!') {\n      return {\n        token: createGroupOpenToken(m[2] === '<' ? 'lookbehind' : 'lookahead', m, {\n          negate: m.endsWith('!'),\n        }),\n      };\n    }\n    // Unnamed capture when `captureGroup` enabled, or named capture (checked after lookbehind due\n    // to similar syntax)\n    if (\n      (m === '(' && context.captureGroup) ||\n      (m.startsWith('(?<') && m.endsWith('>')) ||\n      (m.startsWith(\"(?'\") && m.endsWith(\"'\"))\n    ) {\n      return {\n        token: createGroupOpenToken('capturing', m, {\n          // Will add `number` prop in a second pass\n          ...(m !== '(' && {name: m.slice(3, -1)}),\n        }),\n      };\n    }\n    if (m.startsWith('(?~')) {\n      if (m === '(?~|') {\n        throw new Error(`Unsupported absence function kind \"${m}\"`);\n      }\n      return {\n        token: createGroupOpenToken('absence_repeater', m),\n      };\n    }\n    if (m === '(?(') {\n      // TODO: Add support\n      throw new Error(`Unsupported conditional \"${m}\"`);\n    }\n    throw new Error(`Invalid or unsupported group option \"${m}\"`);\n  }\n  if (m === ')') {\n    context.popModX();\n    context.numOpenGroups--;\n    if (context.numOpenGroups < 0) {\n      throw new Error('Unmatched \")\"');\n    }\n    return {\n      token: createGroupCloseToken(m),\n    };\n  }\n\n  if (context.getCurrentModX()) {\n    if (m === '#') {\n      // Onig's only line break char is line feed\n      const end = pattern.indexOf('\\n', lastIndex);\n      return {\n        // Jump forward to the end of the comment\n        lastIndex: end === -1 ? pattern.length : end,\n      };\n    }\n    if (/^\\s$/.test(m)) {\n      const re = /\\s+/y;\n      re.lastIndex = lastIndex;\n      const rest = re.exec(pattern);\n      return {\n        // Jump forward to the end of the whitespace\n        lastIndex: rest ? re.lastIndex : lastIndex,\n      };\n    }\n  }\n\n  if (m === '.') {\n    return {\n      token: createCharacterSetToken('dot', m),\n    };\n  }\n\n  if (m === '^' || m === '$') {\n    const kind = context.singleline ? {\n      '^': r`\\A`,\n      '$': r`\\Z`,\n    }[m] : m;\n    return {\n      token: createAssertionToken(kind, m),\n    };\n  }\n\n  if (m === '|') {\n    return {\n      token: createAlternatorToken(m),\n    };\n  }\n\n  if (quantifierRe.test(m)) {\n    return {\n      tokens: splitQuantifierMatch(m),\n    };\n  }\n\n  // `cpOf` asserts that it's a single code point\n  return {\n    token: createCharacterToken(cpOf(m), m),\n  };\n}\n\nfunction getAllTokensForCharClass(pattern: string, opener: CharacterClassOpener, lastIndex: number): {\n  tokens: Array<Token | IntermediateToken>;\n  lastIndex: number;\n} {\n  const tokens: Array<Token | IntermediateToken> = [createCharacterClassOpenToken(opener[1] === '^', opener)];\n  let numCharClassesOpen = 1;\n  let match: RegExpExecArray | null;\n  charClassTokenRe.lastIndex = lastIndex;\n  while ((match = charClassTokenRe.exec(pattern))) {\n    const m = match[0];\n    // Start of nested char class\n    // POSIX classes are handled as a single token; not as a nested char class\n    if (m[0] === '[' && m[1] !== ':') {\n      numCharClassesOpen++;\n      tokens.push(createCharacterClassOpenToken(m[1] === '^', m as CharacterClassOpener));\n    } else if (m === ']') {\n      // Always at least includes the char class opener\n      if (tokens.at(-1)!.type === 'CharacterClassOpen') {\n        // Allow unescaped `]` as leading char\n        tokens.push(createCharacterToken(93, m));\n      } else {\n        numCharClassesOpen--;\n        tokens.push(createCharacterClassCloseToken(m));\n        if (!numCharClassesOpen) {\n          break;\n        }\n      }\n    } else {\n      const result = tokenizeAnyTokenWithinCharClass(m);\n      if (Array.isArray(result)) {\n        tokens.push(...result);\n      } else {\n        tokens.push(result);\n      }\n    }\n  }\n  return {\n    tokens,\n    lastIndex: charClassTokenRe.lastIndex || pattern.length,\n  };\n}\n\nfunction tokenizeAnyTokenWithinCharClass(raw: string): Token | IntermediateToken | Array<Token> {\n  if (raw[0] === '\\\\') {\n    // Assumes an identity escape as final condition\n    return tokenizeSharedEscape(raw, {inCharClass: true});\n  }\n  // POSIX class: `[:name:]` or `[:^name:]`\n  if (raw[0] === '[') {\n    const posix = /\\[:(?<negate>\\^?)(?<name>[a-z]+):\\]/.exec(raw);\n    if (!posix || !PosixClassNames.has(posix.groups!.name)) {\n      throw new Error(`Invalid POSIX class \"${raw}\"`);\n    }\n    return createCharacterSetToken('posix', raw, {\n      value: posix.groups!.name,\n      negate: !!posix.groups!.negate,\n    });\n  }\n  // Range (possibly invalid) or literal hyphen\n  if (raw === '-') {\n    return createCharacterClassHyphenToken(raw);\n  }\n  if (raw === '&&') {\n    return createCharacterClassIntersectorToken(raw);\n  }\n  // `cpOf` asserts that it's a single code point\n  return createCharacterToken(cpOf(raw), raw);\n}\n\n// Tokens shared by base syntax and char class syntax that start with `\\`\nfunction tokenizeSharedEscape(raw: string, {inCharClass}: {inCharClass: boolean}): Token | IntermediateToken | Array<Token> {\n  const char1 = raw[1];\n  if (char1 === 'c' || char1 === 'C') {\n    return tokenizeControlCharacter(raw);\n  }\n  if ('dDhHsSwW'.includes(char1)) {\n    return tokenizeShorthand(raw);\n  }\n  if (raw.startsWith(r`\\o{`)) {\n    throw new Error(`Incomplete, invalid, or unsupported octal code point \"${raw}\"`);\n  }\n  if (/^\\\\[pP]\\{/.test(raw)) {\n    if (raw.length === 3) {\n      throw new Error(`Incomplete or invalid Unicode property \"${raw}\"`);\n    }\n    return tokenizeUnicodeProperty(raw);\n  }\n  // Hex UTF-8 encoded byte sequence\n  if (/^\\\\x[89A-Fa-f]\\p{AHex}/u.test(raw)) {\n    try {\n      const bytes = raw.split(/\\\\x/).slice(1).map(hex => parseInt(hex, 16));\n      const decoded = new TextDecoder('utf-8', {\n        ignoreBOM: true,\n        fatal: true,\n      }).decode(new Uint8Array(bytes));\n      const encoder = new TextEncoder();\n      const tokens = [...decoded].map(char => {\n        // Since this regenerates `raw`, it might have different casing for hex A-F than the input\n        const raw = [...encoder.encode(char)].map(byte => `\\\\x${byte.toString(16)}`).join('');\n        return createCharacterToken(cpOf(char), raw);\n      });\n      return tokens;\n    } catch {\n      throw new Error(`Multibyte code \"${raw}\" incomplete or invalid in Oniguruma`);\n    }\n  }\n  if (char1 === 'u' || char1 === 'x') {\n    return createCharacterToken(getValidatedHexCharCode(raw), raw);\n  }\n  if (EscapeCharCodes.has(char1)) {\n    return createCharacterToken(EscapeCharCodes.get(char1)!, raw);\n  }\n  // Escaped number: backref (possibly invalid), null, octal, or identity escape, possibly followed\n  // by 1-2 literal digits\n  if (/\\d/.test(char1)) {\n    return createEscapedNumberToken(inCharClass, raw);\n  }\n  if (raw === '\\\\') {\n    throw new Error(r`Incomplete escape \"\\\"`);\n  }\n  // Meta `\\M-x` and `\\M-\\C-x` are unsupported; avoid treating as an identity escape\n  if (char1 === 'M') {\n    // TODO: Add support. See:\n    // - <github.com/kkos/oniguruma/blob/master/doc/SYNTAX.md#12-onig_syn_op2_esc_capital_m_bar_meta-enable-m-x>\n    // - <github.com/kkos/oniguruma/blob/43a8c3f3daf263091f3a74019d4b32ebb6417093/src/regparse.c#L4695>\n    // - <github.com/ammar/regexp_parser/blob/8851030feda68223d74f502335fb254a20d77016/lib/regexp_parser/expression/classes/escape_sequence.rb#L75>\n    throw new Error(`Unsupported meta \"${raw}\"`);\n  }\n  // Identity escape; count code point length\n  if ([...raw].length === 2) {\n    return createCharacterToken(raw.codePointAt(1)!, raw);\n  }\n  throw new Error(`Unexpected escape \"${raw}\"`);\n}\n\n// --------------------------------\n// --- Token creation and types ---\n// --------------------------------\n\ntype AlternatorToken = {\n  type: 'Alternator';\n  raw: '|';\n};\nfunction createAlternatorToken(raw: '|'): AlternatorToken {\n  return {\n    type: 'Alternator',\n    raw,\n  };\n}\n\ntype AssertionToken = {\n  type: 'Assertion';\n  kind: string;\n  raw: string;\n};\nfunction createAssertionToken(kind: string, raw: string): AssertionToken {\n  return {\n    type: 'Assertion',\n    kind,\n    raw,\n  };\n}\n\ntype BackreferenceToken = {\n  type: 'Backreference';\n  raw: string;\n};\nfunction createBackreferenceToken(raw: string): BackreferenceToken {\n  return {\n    type: 'Backreference',\n    raw,\n  };\n}\n\ntype CharacterToken = {\n  type: 'Character';\n  value: number;\n  raw: string;\n};\nfunction createCharacterToken(value: number, raw: string): CharacterToken {\n  return {\n    type: 'Character',\n    value,\n    raw,\n  };\n}\n\ntype CharacterClassCloseToken = {\n  type: 'CharacterClassClose';\n  raw: ']';\n};\nfunction createCharacterClassCloseToken(raw: ']'): CharacterClassCloseToken {\n  return {\n    type: 'CharacterClassClose',\n    raw,\n  };\n}\n\ntype CharacterClassHyphenToken = {\n  type: 'CharacterClassHyphen';\n  raw: '-';\n};\nfunction createCharacterClassHyphenToken(raw: '-'): CharacterClassHyphenToken {\n  return {\n    type: 'CharacterClassHyphen',\n    raw,\n  };\n}\n\ntype CharacterClassIntersectorToken = {\n  type: 'CharacterClassIntersector';\n  raw: '&&';\n};\nfunction createCharacterClassIntersectorToken(raw: '&&'): CharacterClassIntersectorToken {\n  return {\n    type: 'CharacterClassIntersector',\n    raw,\n  };\n}\n\ntype CharacterClassOpenToken = {\n  type: 'CharacterClassOpen';\n  negate: boolean;\n  raw: CharacterClassOpener;\n};\ntype CharacterClassOpener = '[' | '[^';\nfunction createCharacterClassOpenToken(negate: boolean, raw: CharacterClassOpener): CharacterClassOpenToken {\n  return {\n    type: 'CharacterClassOpen',\n    negate,\n    raw,\n  };\n}\n\ntype CharacterSetToken = {\n  type: 'CharacterSet';\n  kind: TokenCharacterSetKind;\n  value?: string;\n  negate?: boolean;\n  raw: string;\n};\nfunction createCharacterSetToken(\n  kind: TokenCharacterSetKind,\n  raw: string,\n  options: {\n    value?: string;\n    negate?: boolean;\n  } = {}\n): CharacterSetToken {\n  return {\n    type: 'CharacterSet',\n    kind,\n    ...options,\n    raw,\n  };\n}\n\ntype DirectiveToken = {\n  type: 'Directive';\n  raw: string;\n} & ({\n  kind: 'keep';\n  flags?: never;\n} | {\n  kind: 'flags';\n  flags: FlagGroupModifiers;\n});\nfunction createDirectiveToken(kind: TokenDirectiveKind, raw: string, options: {flags?: FlagGroupModifiers} = {}): DirectiveToken {\n  if (kind === 'keep') {\n    return {\n      type: 'Directive',\n      kind,\n      raw,\n    };\n  }\n  return {\n    type: 'Directive',\n    kind,\n    flags: throwIfNullish(options.flags),\n    raw,\n  };\n}\n\ntype EscapedNumberToken = {\n  type: 'EscapedNumber';\n  inCharClass: boolean;\n  raw: string;\n};\n/**\nIntermediate representation only; will become a `Backreference` or one or more `Character`s.\n*/\nfunction createEscapedNumberToken(inCharClass: boolean, raw: string): EscapedNumberToken {\n  return {\n    type: 'EscapedNumber',\n    inCharClass,\n    raw,\n  };\n}\n\ntype GroupCloseToken = {\n  type: 'GroupClose';\n  raw: ')';\n};\nfunction createGroupCloseToken(raw: ')'): GroupCloseToken {\n  return {\n    type: 'GroupClose',\n    raw,\n  };\n}\n\ntype GroupOpenToken = {\n  type: 'GroupOpen';\n  kind: TokenGroupOpenKind;\n  flags?: FlagGroupModifiers;\n  name?: string;\n  number?: number;\n  negate?: boolean;\n  raw: string;\n};\nfunction createGroupOpenToken(\n  kind: TokenGroupOpenKind,\n  raw: string,\n  options: {\n    flags?: FlagGroupModifiers;\n    name?: string;\n    number?: number;\n    negate?: boolean;\n  } = {}\n): GroupOpenToken {\n  return {\n    type: 'GroupOpen',\n    kind,\n    ...options,\n    raw,\n  };\n}\n\ntype NamedCalloutToken = {\n  type: 'NamedCallout';\n  kind: TokenNamedCalloutKind;\n  tag: string | null;\n  arguments: Array<string | number> | null;\n  raw: string;\n};\nfunction createNamedCalloutToken(\n  kind: TokenNamedCalloutKind,\n  tag: string | null,\n  args: Array<string | number> | null,\n  raw: string\n): NamedCalloutToken {\n  return {\n    type: 'NamedCallout',\n    kind,\n    tag,\n    arguments: args,\n    raw,\n  };\n};\n\ntype QuantifierToken = {\n  type: 'Quantifier';\n  kind: TokenQuantifierKind;\n  min: number;\n  max: number;\n  raw: string;\n};\nfunction createQuantifierToken(\n  kind: TokenQuantifierKind,\n  min: number,\n  max: number,\n  raw: string\n): QuantifierToken {\n  return {\n    type: 'Quantifier',\n    kind,\n    min,\n    max,\n    raw,\n  };\n}\n\ntype SubroutineToken = {\n  type: 'Subroutine';\n  raw: string;\n};\nfunction createSubroutineToken(raw: string): SubroutineToken {\n  return {\n    type: 'Subroutine',\n    raw,\n  };\n}\n\n// ---------------\n// --- Helpers ---\n// ---------------\n\ntype FlagProperties = {\n  ignoreCase: boolean;\n  dotAll: boolean;\n  extended: boolean;\n  digitIsAscii: boolean;\n  posixIsAscii: boolean;\n  spaceIsAscii: boolean;\n  wordIsAscii: boolean;\n  textSegmentMode: 'grapheme' | 'word' | null;\n};\n\ntype FlagGroupModifiers = {\n  enable?: FlagGroupSwitches;\n  disable?: FlagGroupSwitches;\n};\n\ntype FlagGroupSwitches = {\n  ignoreCase?: true;\n  dotAll?: true;\n  extended?: true;\n};\n\nconst CalloutNames = new Set<Uppercase<Exclude<TokenNamedCalloutKind, 'custom'>>>([\n  'COUNT',\n  'CMP',\n  'ERROR',\n  'FAIL',\n  'MAX',\n  'MISMATCH',\n  'SKIP',\n  'TOTAL_COUNT',\n]);\n\nconst EscapeCharCodes = new Map([\n  ['a',  7], // alert/bell (Not available in JS)\n  ['b',  8], // backspace (only in char classes)\n  ['e', 27], // escape (Not available in JS)\n  ['f', 12], // form feed\n  ['n', 10], // line feed\n  ['r', 13], // carriage return\n  ['t',  9], // horizontal tab\n  ['v', 11], // vertical tab\n]);\n\n// Expects `\\cx` or `\\C-x`\nfunction tokenizeControlCharacter(raw: string): CharacterToken {\n  const char = raw[1] === 'c' ? raw[2] : raw[3];\n  if (!char || !/[A-Za-z]/.test(char)) {\n    // Unlike JS, Onig allows any char to follow `\\c` or `\\C-`, but this is an extreme edge case\n    // TODO: Add support. See:\n    // - <github.com/kkos/oniguruma/blob/master/doc/SYNTAX.md#11-onig_syn_op2_esc_capital_c_bar_control-enable-c-x>\n    // - <github.com/kkos/oniguruma/blob/43a8c3f3daf263091f3a74019d4b32ebb6417093/src/regparse.c#L4695>\n    throw new Error(`Unsupported control character \"${raw}\"`);\n  }\n  return createCharacterToken(cpOf(char.toUpperCase()) - 64, raw);\n}\n\nfunction tokenizeFlagModifier(raw: string, context: Context): DirectiveToken | GroupOpenToken {\n  // Allows multiple `-` and solo `-` without `on` or `off` flags\n  let {on, off} = /^\\(\\?(?<on>[imx]*)(?:-(?<off>[-imx]*))?/.exec(raw)!.groups as {on: string, off: string | undefined};\n  off ??= '';\n  // Flag x is used directly by the tokenizer since it changes how to interpret the pattern\n  const isXOn = (context.getCurrentModX() || on.includes('x')) && !off.includes('x');\n  const enabledFlags = getFlagGroupSwitches(on);\n  const disabledFlags = getFlagGroupSwitches(off);\n  const flagChanges: FlagGroupModifiers = {};\n  enabledFlags && (flagChanges.enable = enabledFlags);\n  disabledFlags && (flagChanges.disable = disabledFlags);\n  // Flag directive; ex: `(?im-x)`\n  if (raw.endsWith(')')) {\n    // Replace flag x value until the end of the current group\n    context.replaceCurrentModX(isXOn);\n    // Can't remove flag directives without flags like `(?-)`; they affect following quantifiers\n    return createDirectiveToken('flags', raw, {\n      flags: flagChanges,\n    });\n  }\n  // Flag group opener; ex: `(?im-x:`\n  if (raw.endsWith(':')) {\n    context.pushModX(isXOn);\n    context.numOpenGroups++;\n    return createGroupOpenToken('group', raw, {\n      ...((enabledFlags || disabledFlags) && {flags: flagChanges}),\n    });\n  }\n  throw new Error(`Unexpected flag modifier \"${raw}\"`);\n}\n\nfunction tokenizeNamedCallout(raw: string): NamedCalloutToken {\n  const callout = /\\(\\*(?<name>[A-Za-z_]\\w*)?(?:\\[(?<tag>(?:[A-Za-z_]\\w*)?)\\])?(?:\\{(?<args>[^}]*)\\})?\\)/.exec(raw);\n  if (!callout) {\n    throw new Error(`Incomplete or invalid named callout \"${raw}\"`);\n  }\n  const {name, tag, args} = callout.groups as Partial<{\n    name: string;\n    tag: string;\n    args: string;\n  }>;\n  if (!name) {\n    throw new Error(`Invalid named callout \"${raw}\"`);\n  }\n  if (tag === '') {\n    throw new Error(`Named callout tag with empty value not allowed \"${raw}\"`);\n  }\n  const argsArray: Array<string | number> = args ?\n    args.split(',').\n      // Onig skips over/ignores redundant/unnecessary commas\n      filter(arg => arg !== '').\n      map(arg => /^[+-]?\\d+$/.test(arg) ? +arg : arg) :\n    [];\n  const [arg0, arg1, arg2] = argsArray;\n  const kind: TokenNamedCalloutKind = CalloutNames.has(name as Uppercase<Exclude<TokenNamedCalloutKind, 'custom'>>) ?\n    name.toLowerCase() as TokenNamedCalloutKind :\n    'custom';\n  switch (kind) {\n    case 'fail':\n    case 'mismatch':\n    case 'skip':\n      if (argsArray.length > 0) {\n        throw new Error(`Named callout arguments not allowed \"${argsArray}\"`);\n      }\n      break;\n    case 'error':\n      if (argsArray.length > 1) {\n        throw new Error(`Named callout allows only one argument \"${argsArray}\"`);\n      }\n      if (typeof arg0 === 'string') {\n        throw new Error(`Named callout argument must be a number \"${arg0}\"`);\n      }\n      break;\n    case 'max':\n      if (!argsArray.length || argsArray.length > 2) {\n        throw new Error(`Named callout must have one or two arguments \"${argsArray}\"`);\n      }\n      if (typeof arg0 === 'string' && !/^[A-Za-z_]\\w*$/.test(arg0)) {\n        throw new Error(`Named callout argument one must be a tag or number \"${arg0}\"`);\n      }\n      if (argsArray.length === 2 && (typeof arg1 === 'number' || !/^[<>X]$/.test(arg1))) {\n        throw new Error(`Named callout optional argument two must be '<', '>', or 'X' \"${arg1}\"`);\n      }\n      break;\n    case 'count':\n    case 'total_count':\n      if (argsArray.length > 1) {\n        throw new Error(`Named callout allows only one argument \"${argsArray}\"`);\n      }\n      if (argsArray.length === 1 && (typeof arg0 === 'number' || !/^[<>X]$/.test(arg0))) {\n        throw new Error(`Named callout optional argument must be '<', '>', or 'X' \"${arg0}\"`);\n      }\n      break;\n    case 'cmp':\n      if (argsArray.length !== 3) {\n        throw new Error(`Named callout must have three arguments \"${argsArray}\"`);\n      }\n      if (typeof arg0 === 'string' && !/^[A-Za-z_]\\w*$/.test(arg0)) {\n        throw new Error(`Named callout argument one must be a tag or number \"${arg0}\"`);\n      }\n      if (typeof arg1 === 'number' || !/^(?:[<>!=]=|[<>])$/.test(arg1)) {\n        throw new Error(`Named callout argument two must be '==', '!=', '>', '<', '>=', or '<=' \"${arg1}\"`);\n      }\n      if (typeof arg2 === 'string' && !/^[A-Za-z_]\\w*$/.test(arg2)) {\n        throw new Error(`Named callout argument three must be a tag or number \"${arg2}\"`);\n      }\n      break;\n    case 'custom':\n      // TODO: Can support custom callout names via a new option that allows providing a list of\n      // allowed, non-built-in names\n      throw new Error(`Undefined callout name \"${name}\"`);\n    default:\n      throw new Error(`Unexpected named callout kind \"${kind}\"`);\n  }\n  // TODO: If supporting custom callout names in the future (with an added `name` property for\n  // `NamedCalloutToken`), will need to set `name` to `null` if `kind` isn't `'custom'`\n  return createNamedCalloutToken(kind, tag ?? null, args?.split(',') ?? null, raw);\n}\n\nfunction tokenizeQuantifier(raw: string): QuantifierToken {\n  let kind: TokenQuantifierKind = null!;\n  let min: number;\n  let max: number;\n  if (raw[0] === '{') {\n    const {minStr, maxStr} =\n      /^\\{(?<minStr>\\d*)(?:,(?<maxStr>\\d*))?/.exec(raw)!.groups as {minStr: string, maxStr: string | undefined};\n    const limit = 100_000;\n    if (+minStr > limit || (maxStr && +maxStr > limit)) {\n      throw new Error('Quantifier value unsupported in Oniguruma');\n    }\n    min = +minStr;\n    max = maxStr === undefined ? +minStr : (maxStr === '' ? Infinity : +maxStr);\n    // By default, Onig doesn't support making interval quantifiers possessive with a `+` suffix;\n    // uses reversed range instead\n    if (min > max) {\n      kind = 'possessive';\n      [min, max] = [max, min];\n    }\n    if (raw.endsWith('?')) {\n      if (kind === 'possessive') {\n        // TODO: <github.com/slevithan/oniguruma-parser/issues/10>\n        throw new Error('Unsupported possessive interval quantifier chain with \"?\"');\n      }\n      kind = 'lazy';\n    } else if (!kind) {\n      kind = 'greedy';\n    }\n  } else {\n    min = raw[0] === '+' ? 1 : 0;\n    max = raw[0] === '?' ? 1 : Infinity;\n    kind = raw[1] === '+' ? 'possessive' : (raw[1] === '?' ? 'lazy' : 'greedy');\n  }\n  return createQuantifierToken(kind, min, max, raw);\n}\n\nfunction tokenizeShorthand(raw: string): CharacterSetToken {\n  const lower = raw[1].toLowerCase();\n  return createCharacterSetToken({\n    'd': 'digit',\n    'h': 'hex',\n    's': 'space',\n    'w': 'word',\n  }[lower] as TokenCharacterSetKind, raw, {\n    negate: raw[1] !== lower,\n  });\n}\n\nfunction tokenizeUnicodeProperty(raw: string): CharacterSetToken {\n  const {p, neg, value} = /^\\\\(?<p>[pP])\\{(?<neg>\\^?)(?<value>[^}]+)/.exec(raw)!.groups!;\n  const negate = (p === 'P' && !neg) || (p === 'p' && !!neg);\n  return createCharacterSetToken('property', raw, {\n    value,\n    negate,\n  });\n}\n\nfunction getFlagGroupSwitches(flags: string): FlagGroupSwitches | null {\n  // Don't include `false` for flags that aren't included\n  const obj: FlagGroupSwitches = {};\n  if (flags.includes('i')) {\n    obj.ignoreCase = true;\n  }\n  if (flags.includes('m')) {\n    // Onig flag m is equivalent to JS flag s\n    obj.dotAll = true;\n  }\n  if (flags.includes('x')) {\n    obj.extended = true;\n  }\n  return Object.keys(obj).length ? obj : null;\n}\n\nfunction getFlagProperties(flags: string): FlagProperties {\n  const flagProperties: FlagProperties = {\n    ignoreCase: false,\n    dotAll: false,\n    extended: false,\n    digitIsAscii: false,\n    posixIsAscii: false,\n    spaceIsAscii: false,\n    wordIsAscii: false,\n    textSegmentMode: null,\n  };\n  for (let i = 0; i < flags.length; i++) {\n    const char = flags[i];\n    if (!'imxDPSWy'.includes(char)) {\n      throw new Error(`Invalid flag \"${char}\"`);\n    }\n    // Flags y{g}, y{w} are currently only supported via the top-level `flags` option\n    if (char === 'y') {\n      if (!/^y{[gw]}/.test(flags.slice(i))) {\n        throw new Error('Invalid or unspecified flag \"y\" mode');\n      }\n      // If text segment mode flags appear multiple times, use the last one\n      flagProperties.textSegmentMode = flags[i + 2] === 'g' ? 'grapheme' : 'word';\n      i += 3;\n      continue;\n    }\n    flagProperties[{\n      i: 'ignoreCase',\n      // Flag m is called `multiline` in Onig, but that has a different meaning in JS. Onig flag m\n      // is equivalent to JS flag s\n      m: 'dotAll',\n      // Flag x is fully handled during tokenization\n      x: 'extended',\n      // Flags D, P, S, W are currently only supported via the top-level `flags` option\n      D: 'digitIsAscii',\n      P: 'posixIsAscii',\n      S: 'spaceIsAscii',\n      W: 'wordIsAscii',\n    }[char] as Exclude<keyof FlagProperties, 'textSegmentMode'>] = true;\n  }\n  return flagProperties;\n}\n\n// - Unenclosed `\\xNN` above 0x7F is handled elsewhere as a UTF-8 encoded byte sequence\n// - Enclosed `\\x{}` with value above 0x10FFFF is allowed here; handled in the parser\nfunction getValidatedHexCharCode(raw: string): number {\n  // Note: Onig 6.9.10 and earlier have a bug where pattern-terminating `\\u` and `\\x` are treated\n  // as identity escapes; see <github.com/kkos/oniguruma/issues/343>. Don't emulate these bugs.\n  // Additionally, Onig treats bare `\\x` as equivalent to `\\0`, and treats incomplete `\\x{` (with\n  // the brace but not immediately followed by a hex digit) as an identity escape, so e.g. `\\x{`\n  // matches `x{` and `^\\x{,2}$` matches `xx`, but `\\x{2,}` and `\\x{0,2}` are errors. Currently,\n  // this library treats all such cases as errors\n  if (/^(?:\\\\u(?!\\p{AHex}{4})|\\\\x(?!\\p{AHex}{1,2}|\\{\\p{AHex}{1,8}\\}))/u.test(raw)) {\n    throw new Error(`Incomplete or invalid escape \"${raw}\"`);\n  }\n  // Might include leading 0s\n  const hex = raw[2] === '{' ?\n    /^\\\\x\\{\\s*(?<hex>\\p{AHex}+)/u.exec(raw)!.groups!.hex :\n    raw.slice(2);\n  return parseInt(hex, 16);\n}\n\n// Value is 1-3 digits, which can be a backref (possibly invalid), null, octal, or identity escape,\n// possibly followed by 1-2 literal digits\nfunction splitEscapedNumberToken(token: EscapedNumberToken, numCaptures: number): Array<BackreferenceToken> | Array<CharacterToken> {\n  const {raw, inCharClass} = token;\n  // Keep any leading 0s since they indicate octal\n  const value = raw.slice(1);\n  // Backref (possibly invalid)\n  if (\n    !inCharClass &&\n    ( // Single digit 1-9 outside a char class is always treated as a backref\n      (value !== '0' && value.length === 1) ||\n      // Leading 0 makes it octal; backrefs can't include following literal digits\n      (value[0] !== '0' && +value <= numCaptures)\n    )\n  ) {\n    return [createBackreferenceToken(raw)];\n  }\n  const tokens: Array<CharacterToken> = [];\n  // Returns 1-3 matches; the first (only) might be octal\n  const matches = value.match(/^[0-7]+|\\d/g)!;\n  for (let i = 0; i < matches.length; i++) {\n    const m = matches[i];\n    let value: number;\n    // Octal digits are 0-7\n    if (i === 0 && m !== '8' && m !== '9') {\n      value = parseInt(m, 8);\n      if (value > 0o177) {\n        // Octal UTF-8 encoded byte sequence; not yet supported\n        throw new Error(r`Octal encoded byte above 177 unsupported \"${raw}\"`);\n      }\n    } else {\n      value = cpOf(m);\n    }\n    tokens.push(createCharacterToken(value, (i === 0 ? '\\\\' : '') + m));\n  }\n  return tokens;\n}\n\nfunction splitQuantifierMatch(str: string): Array<QuantifierToken> {\n  const tokens: Array<QuantifierToken> = [];\n  // `str` is one or more quantifiers in a chain. It can't be split by a regex because of one edge\n  // case where we have to compare numeric values: although `{1,2}?` is a single, lazy quantifier,\n  // a reversed (possessive) interval quantifier like `{2,1}` can't be both possessive and lazy, so\n  // any following `?`, `??`, or `?+` is a second, chained quantifier (i.e., `{2,1}?` is equivalent\n  // to `{2,1}{0,1}` or `{2,0}`)\n  const withG = new RegExp(quantifierRe, 'gy');\n  let match: RegExpExecArray | null;\n  while ((match = withG.exec(str))) {\n    const m = match[0];\n    if (m[0] === '{') {\n      // Doesn't need to handle fixed `{n}`, infinite max `{n,}`, or implicit zero min `{,n}`\n      // since, according to Onig syntax rules, those can't be possessive\n      const parts = /^\\{(?<min>\\d+),(?<max>\\d+)\\}\\??$/.exec(m);\n      if (parts) {\n        const {min, max} = parts.groups as {min: string, max: string};\n        if (+min > +max && m.endsWith('?')) {\n          // Leave the trailing `?` for the next match\n          withG.lastIndex--;\n          tokens.push(tokenizeQuantifier(m.slice(0, -1)));\n          continue;\n        }\n      }\n    }\n    tokens.push(tokenizeQuantifier(m));\n  }\n  return tokens;\n}\n\nexport {\n  type AlternatorToken,\n  type AssertionToken,\n  type BackreferenceToken,\n  type CharacterToken,\n  type CharacterClassCloseToken,\n  type CharacterClassHyphenToken,\n  type CharacterClassIntersectorToken,\n  type CharacterClassOpenToken,\n  type CharacterSetToken,\n  type DirectiveToken,\n  type FlagGroupModifiers,\n  type FlagProperties,\n  type GroupCloseToken,\n  type GroupOpenToken,\n  type NamedCalloutToken,\n  type QuantifierToken,\n  type SubroutineToken,\n  type Token,\n  type TokenCharacterSetKind,\n  type TokenDirectiveKind,\n  type TokenNamedCalloutKind,\n  type TokenQuantifierKind,\n  tokenize,\n};\n","import type {AlternativeContainerNode, Node, ParentNode, QuantifiableNode} from './parse.js';\n\ntype KeysOfUnion<T> = T extends T ? keyof T: never;\ntype Props = {[key in KeysOfUnion<Node>]?: any} & {type?: Node['type']};\n\nfunction hasOnlyChild(node: ParentNode & {body: Array<Node>}, props?: Props): boolean {\n  if (!Array.isArray(node.body)) {\n    throw new Error('Expected node with body array');\n  }\n  if (node.body.length !== 1) {\n    return false;\n  }\n  const kid = node.body[0] as Props;\n  return !props || Object.keys(props).every(key => props[key as keyof Props] === kid[key as keyof Props]);\n}\n\nfunction isAlternativeContainer(node: Node): node is AlternativeContainerNode {\n  if (\n    !alternativeContainerTypes.has(node.type) ||\n    (node.type === 'AbsenceFunction' && node.kind !== 'repeater')\n  ) {\n    return false;\n  }\n  return true;\n}\nconst alternativeContainerTypes = new Set<Node['type']>([\n  'AbsenceFunction',\n  'CapturingGroup',\n  'Group',\n  'LookaroundAssertion',\n  'Regex',\n]);\n\nfunction isQuantifiable(node: Node): node is QuantifiableNode {\n  return quantifiableTypes.has(node.type);\n}\nconst quantifiableTypes = new Set<Node['type']>([\n  'AbsenceFunction',\n  'Backreference',\n  'CapturingGroup',\n  'Character',\n  'CharacterClass',\n  'CharacterSet',\n  'Group',\n  'Quantifier',\n  'Subroutine',\n]);\n\nexport {\n  hasOnlyChild,\n  isAlternativeContainer,\n  isQuantifiable,\n};\n","import type {AssertionToken, BackreferenceToken, CharacterClassHyphenToken, CharacterClassOpenToken, CharacterSetToken, FlagGroupModifiers, FlagProperties, GroupOpenToken, QuantifierToken, SubroutineToken, Token, TokenCharacterSetKind, TokenDirectiveKind, TokenNamedCalloutKind, TokenQuantifierKind} from '../tokenizer/tokenize.js';\nimport {tokenize} from '../tokenizer/tokenize.js';\nimport {cpOf, getOrInsert, PosixClassNames, r, throwIfNullish} from '../utils.js';\nimport {hasOnlyChild, isAlternativeContainer, isQuantifiable} from './node-utils.js';\n\n// Watch out for the DOM `Node` interface!\ntype Node =\n  AbsenceFunctionNode |\n  AlternativeNode |\n  AssertionNode |\n  BackreferenceNode |\n  CapturingGroupNode |\n  CharacterNode |\n  CharacterClassNode |\n  CharacterClassRangeNode |\n  CharacterSetNode |\n  DirectiveNode |\n  FlagsNode |\n  GroupNode |\n  LookaroundAssertionNode |\n  NamedCalloutNode |\n  QuantifierNode |\n  RegexNode |\n  SubroutineNode;\n\ntype OnigurumaAst = RegexNode;\n\ntype ParentNode =\n  AlternativeContainerNode |\n  AlternativeNode |\n  CharacterClassNode |\n  CharacterClassRangeNode |\n  QuantifierNode;\n\n// See also `isAlternativeContainer`\ntype AlternativeContainerNode =\n  AbsenceFunctionNode | // Some sub-kinds aren't alternative containers\n  CapturingGroupNode |\n  GroupNode |\n  LookaroundAssertionNode |\n  RegexNode;\n\ntype AlternativeElementNode =\n  AbsenceFunctionNode |\n  AssertionNode |\n  BackreferenceNode |\n  CapturingGroupNode |\n  CharacterNode |\n  CharacterClassNode |\n  CharacterSetNode |\n  DirectiveNode |\n  GroupNode |\n  LookaroundAssertionNode |\n  NamedCalloutNode |\n  QuantifierNode |\n  SubroutineNode;\n\ntype CharacterClassElementNode =\n  CharacterNode |\n  CharacterClassNode |\n  CharacterClassRangeNode |\n  CharacterSetNode;\n\n// See also `isQuantifiable`\ntype QuantifiableNode =\n  AbsenceFunctionNode |\n  BackreferenceNode |\n  CapturingGroupNode |\n  CharacterNode |\n  CharacterClassNode |\n  CharacterSetNode |\n  GroupNode |\n  QuantifierNode |\n  SubroutineNode;\n\n// TODO: Support remaining kinds; see <github.com/slevithan/oniguruma-to-es/issues/13>\ntype NodeAbsenceFunctionKind =\n  'repeater';\n\ntype NodeAssertionKind =\n  'line_end' |\n  'line_start' |\n  'search_start' |\n  'string_end' |\n  'string_end_newline' |\n  'string_start' |\n  'text_segment_boundary' |\n  'word_boundary';\n\ntype NodeCharacterClassKind =\n  'union' |\n  'intersection';\n\ntype NodeCharacterSetKind = TokenCharacterSetKind;\n\ntype NodeDirectiveKind = TokenDirectiveKind;\n\ntype NodeLookaroundAssertionKind =\n  'lookahead' |\n  'lookbehind';\n\ntype NodeNamedCalloutKind = TokenNamedCalloutKind;\n\ntype NodeQuantifierKind = TokenQuantifierKind;\n\ntype UnicodePropertyMap = Map<string, string>;\n\ntype Context = {\n  capturingGroups: Array<CapturingGroupNode>;\n  hasNumberedRef: boolean;\n  namedGroupsByName: Map<string, Array<CapturingGroupNode>>;\n  nextIndex: number;\n  normalizeUnknownPropertyNames: boolean;\n  parent: ParentNode;\n  skipBackrefValidation: boolean;\n  skipLookbehindValidation: boolean;\n  skipPropertyNameValidation: boolean;\n  subroutines: Array<SubroutineNode>;\n  tokens: Array<Token>;\n  unicodePropertyMap: UnicodePropertyMap | null;\n  walk: (parent: ParentNode, state: State) => Node;\n};\n\n// Top-level `walk` calls are given empty state; nested calls can add data specific to their `walk`\ntype State = {\n  isCheckingRangeEnd?: boolean;\n  isInAbsenceFunction?: boolean;\n  isInLookbehind?: boolean;\n  isInNegLookbehind?: boolean;\n};\n\ntype ParseOptions = {\n  flags?: string;\n  normalizeUnknownPropertyNames?: boolean;\n  rules?: {\n    captureGroup?: boolean;\n    singleline?: boolean;\n  };\n  skipBackrefValidation?: boolean;\n  skipLookbehindValidation?: boolean;\n  skipPropertyNameValidation?: boolean;\n  unicodePropertyMap?: UnicodePropertyMap | null;\n};\n\nfunction parse(pattern: string, options: ParseOptions = {}): OnigurumaAst {\n  const opts: Required<ParseOptions> = {\n    flags: '',\n    normalizeUnknownPropertyNames: false,\n    skipBackrefValidation: false,\n    skipLookbehindValidation: false,\n    skipPropertyNameValidation: false,\n    // `toOnigurumaAst` provides `OnigUnicodePropertyMap`, but it can be custom or `null`\n    unicodePropertyMap: null,\n    ...options,\n    rules: {\n      captureGroup: false, // `ONIG_OPTION_CAPTURE_GROUP`\n      singleline: false, // `ONIG_OPTION_SINGLELINE`\n      ...options.rules,\n    },\n  };\n  const tokenized = tokenize(pattern, {\n    // Limit to the tokenizer's options\n    flags: opts.flags,\n    rules: {\n      captureGroup: opts.rules.captureGroup,\n      singleline: opts.rules.singleline,\n    },\n  });\n  const walk: Context['walk'] = (parent, state) => {\n    const token = tokenized.tokens[context.nextIndex];\n    context.parent = parent;\n    // Advance for the next iteration\n    context.nextIndex++;\n    switch (token.type) {\n      case 'Alternator':\n        // Top-level only; groups handle their own alternators\n        return createAlternative();\n      case 'Assertion':\n        return parseAssertion(token);\n      case 'Backreference':\n        return parseBackreference(token, context);\n      case 'Character':\n        return createCharacter(token.value, {useLastValid: !!state.isCheckingRangeEnd});\n      case 'CharacterClassHyphen':\n        return parseCharacterClassHyphen(token, context, state);\n      case 'CharacterClassOpen':\n        return parseCharacterClassOpen(token, context, state);\n      case 'CharacterSet':\n        return parseCharacterSet(token, context);\n      case 'Directive':\n        return createDirective(token.kind, {flags: token.flags});\n      case 'GroupOpen':\n        return parseGroupOpen(token, context, state);\n      case 'NamedCallout':\n        return createNamedCallout(token.kind, token.tag, token.arguments);\n      case 'Quantifier':\n        return parseQuantifier(token, context);\n      case 'Subroutine':\n        return parseSubroutine(token, context);\n      default:\n        throw new Error(`Unexpected token type \"${token.type}\"`);\n    }\n  }\n  const context: Context = {\n    capturingGroups: [],\n    hasNumberedRef: false,\n    namedGroupsByName: new Map(),\n    nextIndex: 0,\n    normalizeUnknownPropertyNames: opts.normalizeUnknownPropertyNames,\n    parent: null!, // Assigned by `walk`\n    skipBackrefValidation: opts.skipBackrefValidation,\n    skipLookbehindValidation: opts.skipLookbehindValidation,\n    skipPropertyNameValidation: opts.skipPropertyNameValidation,\n    subroutines: [],\n    tokens: tokenized.tokens,\n    unicodePropertyMap: opts.unicodePropertyMap,\n    walk,\n  };\n\n  // ## AST construction from tokens\n  const ast = createRegex(createFlags(tokenized.flags));\n  let top = ast.body[0]; // First alt\n  while (context.nextIndex < tokenized.tokens.length) {\n    const node = walk(top, {});\n    if (node.type === 'Alternative') {\n      ast.body.push(node);\n      top = node;\n    } else {\n      top.body.push(node as AlternativeElementNode);\n    }\n  }\n\n  // ## Validation that requires knowledge about the complete pattern\n  // `context` updated by the preceding `walk` loop\n  const {capturingGroups, hasNumberedRef, namedGroupsByName, subroutines} = context;\n  if (hasNumberedRef && namedGroupsByName.size && !opts.rules.captureGroup) {\n    throw new Error('Numbered backref/subroutine not allowed when using named capture');\n  }\n  for (const {ref} of subroutines) {\n    if (typeof ref === 'number') {\n      // Relative nums are already resolved\n      if (ref > capturingGroups.length) {\n        throw new Error(`Subroutine uses a group number that's not defined`);\n      }\n      if (ref) {\n        capturingGroups[ref - 1].isSubroutined = true;\n      }\n    } else if (!namedGroupsByName.has(ref)) {\n      throw new Error(r`Subroutine uses a group name that's not defined \"\\g<${ref}>\"`);\n    } else if (namedGroupsByName.get(ref)!.length > 1) {\n      throw new Error(r`Subroutine uses a duplicate group name \"\\g<${ref}>\"`);\n    } else {\n      namedGroupsByName.get(ref)![0].isSubroutined = true;\n    }\n  }\n\n  return ast;\n}\n\nfunction parseAssertion({kind}: AssertionToken): AssertionNode {\n  return createAssertion(\n    throwIfNullish({\n      '^': 'line_start',\n      '$': 'line_end',\n      '\\\\A': 'string_start',\n      '\\\\b': 'word_boundary',\n      '\\\\B': 'word_boundary',\n      '\\\\G': 'search_start',\n      '\\\\y': 'text_segment_boundary',\n      '\\\\Y': 'text_segment_boundary',\n      '\\\\z': 'string_end',\n      '\\\\Z': 'string_end_newline',\n    }[kind], `Unexpected assertion kind \"${kind}\"`) as NodeAssertionKind,\n    {negate: kind === r`\\B` || kind === r`\\Y`}\n  );\n}\n\n// Supported (if the backref appears to the right of the reffed capture's opening paren):\n// - `\\k<name>`, `\\k'name'`\n// - When named capture not used:\n//   - `\\n`, `\\nn`, `\\nnn`\n//   - `\\k<n>`, `\\k'n'\n//   - `\\k<-n>`, `\\k'-n'`\n// Unsupported:\n// - `\\k<+n>`, `\\k'+n'` - Note that, Unlike Oniguruma, Onigmo doesn't support this as special\n//   syntax and therefore considers it a valid group name.\n// - Backref with recursion level (with num or name): `\\k<n+level>`, `\\k<n-level>`, etc.\n//   (Onigmo also supports `\\k<-n+level>`, `\\k<-n-level>`, etc.)\n// Backrefs in Onig use multiplexing for duplicate group names (the rules can be complicated when\n// overlapping with subroutines), but a `Backreference`'s simple `ref` prop doesn't capture these\n// details so multiplexed ref pointers need to be derived when working with the AST\nfunction parseBackreference({raw}: BackreferenceToken, context: Context): BackreferenceNode {\n  const hasKWrapper = /^\\\\k[<']/.test(raw);\n  const ref = hasKWrapper ? raw.slice(3, -1) : raw.slice(1);\n  const fromNum = (num: number, isRelative = false) => {\n    const numCapturesToLeft = context.capturingGroups.length;\n    let orphan = false;\n    // Note: It's not an error for numbered backrefs to come before their referenced group in Onig,\n    // but it's currently an error in this library.\n    // - Most such placements are mistakes and can never match, due to Onig's behavior for backrefs\n    //   to nonparticipating groups.\n    //   - The edge cases where they're matchable rely on rules for backref resetting within\n    //     quantified groups that are different in JS (thus not emulatable in `oniguruma-to-es`).\n    // - Erroring matches the correct behavior of named backrefs.\n    // - For unenclosed backrefs, this only affects `\\1`-`\\9` since it's not a backref in the first\n    //   place if using `\\10` or higher and not as many capturing groups are defined to the left\n    //   (it's an octal or identity escape).\n    // TODO: Ideally this would be refactored to include the backref in the AST when it's not an\n    // error in Onig (due to the reffed group being defined to the right), and the error handling\n    // would move to the `oniguruma-to-es` transformer\n    if (num > numCapturesToLeft) {\n      // Skipping the error breaks assumptions and might create edge case issues, since backrefs\n      // are required to come after their captures; unfortunately this option is needed for\n      // TextMate grammars\n      if (context.skipBackrefValidation) {\n        orphan = true;\n      } else {\n        throw new Error(`Not enough capturing groups defined to the left \"${raw}\"`);\n      }\n    }\n    context.hasNumberedRef = true;\n    return createBackreference(isRelative ? numCapturesToLeft + 1 - num : num, {orphan});\n  };\n  if (hasKWrapper) {\n    const numberedRef = /^(?<sign>-?)0*(?<num>[1-9]\\d*)$/.exec(ref);\n    if (numberedRef) {\n      return fromNum(+numberedRef.groups!.num, !!numberedRef.groups!.sign);\n    }\n    // Invalid in a backref name even when valid in a group name\n    if (/[-+]/.test(ref)) {\n      throw new Error(`Invalid backref name \"${raw}\"`);\n    }\n    if (!context.namedGroupsByName.has(ref)) {\n      throw new Error(`Group name not defined to the left \"${raw}\"`);\n    }\n    return createBackreference(ref);\n  }\n  return fromNum(+ref);\n}\n\nfunction parseCharacterClassHyphen(_: CharacterClassHyphenToken, context: Context, state: State): CharacterNode | CharacterClassRangeNode {\n  const {tokens, walk} = context;\n  const parent = context.parent as CharacterClassNode;\n  const prevSiblingNode = parent.body.at(-1);\n  const nextToken = tokens[context.nextIndex];\n  if (\n    !state.isCheckingRangeEnd &&\n    prevSiblingNode &&\n    prevSiblingNode.type !== 'CharacterClass' &&\n    prevSiblingNode.type !== 'CharacterClassRange' &&\n    nextToken &&\n    nextToken.type !== 'CharacterClassOpen' &&\n    nextToken.type !== 'CharacterClassClose' &&\n    nextToken.type !== 'CharacterClassIntersector'\n  ) {\n    const nextNode = walk(parent, {\n      ...state,\n      isCheckingRangeEnd: true,\n    });\n    if (prevSiblingNode.type === 'Character' && nextNode.type === 'Character') {\n      parent.body.pop();\n      return createCharacterClassRange(prevSiblingNode, nextNode);\n    }\n    throw new Error('Invalid character class range');\n  }\n  return createCharacter(cpOf('-'));\n}\n\nfunction parseCharacterClassOpen({negate}: CharacterClassOpenToken, context: Context, state: State): CharacterClassNode {\n  const {tokens, walk} = context;\n  const intersections = [createCharacterClass()];\n  const ccFirstToken = tokens[context.nextIndex];\n  let nextToken = throwIfUnclosedCharacterClass(ccFirstToken);\n  while (nextToken.type !== 'CharacterClassClose') {\n    if (nextToken.type === 'CharacterClassIntersector') {\n      intersections.push(createCharacterClass());\n      // Skip the intersector\n      context.nextIndex++;\n    } else {\n      const cc = intersections.at(-1)!; // Always at least one\n      cc.body.push(walk(cc, state) as CharacterClassElementNode);\n    }\n    nextToken = throwIfUnclosedCharacterClass(tokens[context.nextIndex], ccFirstToken);\n  }\n  const node = createCharacterClass({negate});\n  if (intersections.length === 1) {\n    node.body = intersections[0].body;\n  } else {\n    node.kind = 'intersection';\n    node.body = intersections.map(cc => cc.body.length === 1 ? cc.body[0] : cc);\n  }\n  // Skip the closing square bracket\n  context.nextIndex++;\n  return node;\n}\n\nfunction parseCharacterSet({kind, negate, value}: CharacterSetToken, context: Context): CharacterSetNode {\n  const {normalizeUnknownPropertyNames, skipPropertyNameValidation, unicodePropertyMap} = context;\n  if (kind === 'property') {\n    const normalized = slug(value!);\n    // Don't treat as POSIX if it's in the provided list of Unicode property names\n    if (PosixClassNames.has(normalized) && !unicodePropertyMap?.has(normalized)) {\n      kind = 'posix';\n      value = normalized;\n    } else {\n      return createUnicodeProperty(value!, {\n        negate,\n        normalizeUnknownPropertyNames,\n        skipPropertyNameValidation,\n        unicodePropertyMap,\n      });\n    }\n  }\n  if (kind === 'posix') {\n    return createPosixClass(value!, {negate});\n  }\n  return createCharacterSet(kind, {negate});\n}\n\nfunction parseGroupOpen(token: GroupOpenToken, context: Context, state: State): AbsenceFunctionNode | CapturingGroupNode | GroupNode | LookaroundAssertionNode {\n  const {tokens, capturingGroups, namedGroupsByName, skipLookbehindValidation, walk} = context;\n  const node = createByGroupKind(token);\n  const isThisAbsenceFunction = node.type === 'AbsenceFunction';\n  const isThisLookbehind = isLookbehind(node);\n  const isThisNegLookbehind = isThisLookbehind && node.negate;\n  // Track capturing group details for backrefs and subroutines (before parsing the group's\n  // contents so nested groups with the same name are tracked in order)\n  if (node.type === 'CapturingGroup') {\n    capturingGroups.push(node);\n    if (node.name) {\n      getOrInsert(namedGroupsByName, node.name, []).push(node);\n    }\n  }\n  // Don't allow nested absence functions\n  if (isThisAbsenceFunction && state.isInAbsenceFunction) {\n    // Is officially unsupported in Onig but doesn't throw, gives strange results\n    throw new Error('Nested absence function not supported by Oniguruma');\n  }\n  let nextToken = throwIfUnclosedGroup(tokens[context.nextIndex]);\n  while (nextToken.type !== 'GroupClose') {\n    if (nextToken.type === 'Alternator') {\n      node.body.push(createAlternative());\n      // Skip the alternator\n      context.nextIndex++;\n    } else {\n      const alt = node.body.at(-1)!; // Always at least one\n      const child = walk(alt, {\n        ...state,\n        isInAbsenceFunction: state.isInAbsenceFunction || isThisAbsenceFunction,\n        isInLookbehind: state.isInLookbehind || isThisLookbehind,\n        isInNegLookbehind: state.isInNegLookbehind || isThisNegLookbehind,\n      }) as AlternativeElementNode;\n      alt.body.push(child);\n      // Centralized validation of lookbehind contents\n      if ((isThisLookbehind || state.isInLookbehind) && !skipLookbehindValidation) {\n        // JS supports all features within lookbehind, but Onig doesn't. Absence functions of form\n        // `(?~|)` and `(?~|…)` are also invalid in lookbehind (the `(?~…)` and `(?~|…|…)` forms\n        // are allowed), but all forms with `(?~|` throw since they aren't yet supported\n        const msg = 'Lookbehind includes a pattern not allowed by Oniguruma';\n        if (isThisNegLookbehind || state.isInNegLookbehind) {\n          // - Invalid: `(?=…)`, `(?!…)`, capturing groups\n          // - Valid: `(?<=…)`, `(?<!…)`\n          if (isLookahead(child) || child.type === 'CapturingGroup') {\n            throw new Error(msg);\n          }\n        } else {\n          // - Invalid: `(?=…)`, `(?!…)`, `(?<!…)`\n          // - Valid: `(?<=…)`, capturing groups\n          if (isLookahead(child) || (isLookbehind(child) && child.negate)) {\n            throw new Error(msg);\n          }\n        }\n      }\n    }\n    nextToken = throwIfUnclosedGroup(tokens[context.nextIndex]);\n  }\n  // Skip the closing parenthesis\n  context.nextIndex++;\n  return node;\n}\n\nfunction parseQuantifier({kind, min, max}: QuantifierToken, context: Context): QuantifierNode {\n  const parent = context.parent as AlternativeNode;\n  const quantifiedNode = parent.body.at(-1);\n  if (!quantifiedNode || !isQuantifiable(quantifiedNode)) {\n    throw new Error('Quantifier requires a repeatable token');\n  }\n  const node = createQuantifier(kind, min, max, quantifiedNode);\n  parent.body.pop();\n  return node;\n}\n\n// Onig subroutine behavior:\n// - Subroutines can appear before the groups they reference; ex: `\\g<1>(a)` is valid.\n// - Multiple subroutines can reference the same group.\n// - Subroutines can reference groups that themselves contain subroutines, followed to any depth.\n// - Subroutines can be used recursively, and `\\g<0>` recursively references the whole pattern.\n// - Subroutines can use relative references (backward or forward); ex: `\\g<+1>(.)\\g<-1>`.\n// - Subroutines don't get their own capturing group numbers; ex: `(.)\\g<1>\\2` is invalid.\n// - Subroutines use the flags that apply to their referenced group, so e.g.\n//   `(?-i)(?<a>a)(?i)\\g<a>` is fully case sensitive.\n// - Differences from PCRE/Perl/Regex+ subroutines:\n//   - Subroutines can't reference duplicate group names (though duplicate names are valid if no\n//     subroutines reference them).\n//   - Subroutines can't use absolute or relative numbers if named capture is used anywhere.\n//   - Named backrefs must be to the right of their group definition, so the backref in\n//     `\\g<a>\\k<a>(?<a>)` is invalid (not directly related to subroutines).\n//   - Subroutines don't restore capturing group match values (for backrefs) upon exit, so e.g.\n//     `(?<a>(?<b>[ab]))\\g<a>\\k<b>` matches `abb` but not `aba`; same for numbered.\n// The interaction of backref multiplexing (an Onig-specific feature) and subroutines is complex:\n// - Only the most recent value matched by a capturing group and its subroutines is considered for\n//   backref multiplexing, and this also applies to capturing groups nested within a group that's\n//   referenced by a subroutine.\n// - Although a subroutine can't reference a group with a duplicate name, it can reference a group\n//   with a nested capture whose name is duplicated (e.g. outside of the referenced group).\n//   - These duplicate names can then multiplex; but only the most recent value matched from within\n//     the outer group (or the subroutines that reference it) is available for multiplexing.\n//   - Ex: With `(?<a>(?<b>[123]))\\g<a>\\g<a>(?<b>0)\\k<b>`, the backref `\\k<b>` can only match `0`\n//     or whatever was matched by the most recently matched subroutine. If you took out `(?<b>0)`,\n//     no multiplexing would occur.\nfunction parseSubroutine({raw}: SubroutineToken, context: Context): SubroutineNode {\n  const {capturingGroups, subroutines} = context;\n  let ref: string | number = raw.slice(3, -1);\n  const numberedRef = /^(?<sign>[-+]?)0*(?<num>[1-9]\\d*)$/.exec(ref);\n  if (numberedRef) {\n    const num = +numberedRef.groups!.num;\n    const numCapturesToLeft = capturingGroups.length;\n    context.hasNumberedRef = true;\n    ref = {\n      '': num,\n      '+': numCapturesToLeft + num,\n      '-': numCapturesToLeft + 1 - num,\n    }[numberedRef.groups!.sign]!;\n    if (ref < 1) {\n      throw new Error('Invalid subroutine number');\n    }\n  // Special case for full-pattern recursion; can't be `+0`, `-0`, `00`, etc.\n  } else if (ref === '0') {\n    ref = 0;\n  }\n  const node = createSubroutine(ref);\n  subroutines.push(node);\n  return node;\n}\n\n// -------------------------------\n// --- Node creation and types ---\n// -------------------------------\n\ntype AbsenceFunctionNode = {\n  type: 'AbsenceFunction';\n  kind: NodeAbsenceFunctionKind;\n  body: Array<AlternativeNode>;\n};\nfunction createAbsenceFunction(kind: NodeAbsenceFunctionKind, options?: {\n  body?: Array<AlternativeNode>;\n}): AbsenceFunctionNode {\n  if (kind !== 'repeater') {\n    throw new Error(`Unexpected absence function kind \"${kind}\"`);\n  }\n  return {\n    type: 'AbsenceFunction',\n    kind,\n    body: getBodyForAlternativeContainer(options?.body),\n  };\n}\n\ntype AlternativeNode = {\n  type: 'Alternative';\n  body: Array<AlternativeElementNode>;\n};\nfunction createAlternative(options?: {\n  body?: Array<AlternativeElementNode>;\n}): AlternativeNode {\n  return {\n    type: 'Alternative',\n    body: getBodyForElementContainer(options?.body) as Array<AlternativeElementNode>,\n  };\n}\n\ntype AssertionNode = {\n  type: 'Assertion';\n  kind: NodeAssertionKind;\n  negate?: boolean;\n};\nfunction createAssertion(kind: NodeAssertionKind, options?: {\n  negate?: boolean;\n}): AssertionNode {\n  const node: AssertionNode = {\n    type: 'Assertion',\n    kind,\n  };\n  if (kind === 'word_boundary' || kind === 'text_segment_boundary') {\n    node.negate = !!options?.negate;\n  }\n  return node;\n}\n\ntype BackreferenceNode = {\n  type: 'Backreference';\n  ref: string | number;\n  orphan?: boolean;\n};\nfunction createBackreference(ref: string | number, options?: {\n  orphan?: boolean;\n}): BackreferenceNode {\n  const orphan = !!options?.orphan;\n  return {\n    type: 'Backreference',\n    ref,\n    ...(orphan && {orphan}),\n  };\n}\n\ntype CapturingGroupNode = {\n  type: 'CapturingGroup';\n  kind?: never;\n  number: number;\n  name?: string;\n  // One or more subroutines in the regex reference this group\n  isSubroutined?: boolean;\n  body: Array<AlternativeNode>;\n};\nfunction createCapturingGroup(number: number, options?: {\n  name?: string;\n  isSubroutined?: boolean;\n  body?: Array<AlternativeNode>;\n}): CapturingGroupNode {\n  const opts = {\n    name: undefined,\n    isSubroutined: false,\n    ...options,\n  };\n  if (opts.name !== undefined && !isValidGroupName(opts.name)) {\n    throw new Error(`Group name \"${opts.name}\" invalid in Oniguruma`);\n  }\n  return {\n    type: 'CapturingGroup',\n    number,\n    ...(opts.name && {name: opts.name}),\n    ...(opts.isSubroutined && {isSubroutined: opts.isSubroutined}),\n    body: getBodyForAlternativeContainer(options?.body),\n  };\n}\n\ntype CharacterNode = {\n  type: 'Character';\n  value: number;\n};\nfunction createCharacter(charCode: number, options?: {\n  useLastValid?: boolean;\n}): CharacterNode {\n  const opts = {\n    useLastValid: false,\n    ...options,\n  };\n  if (charCode > 0x10FFFF) {\n    const hex = charCode.toString(16);\n    if (opts.useLastValid) {\n      charCode = 0x10FFFF;\n    } else if (charCode > 0x13FFFF) {\n      throw new Error(`Invalid code point out of range \"\\\\x{${hex}}\"`);\n    } else {\n      throw new Error(`Invalid code point out of range in JS \"\\\\x{${hex}}\"`);\n    }\n  }\n  return {\n    type: 'Character',\n    value: charCode,\n  };\n}\n\ntype CharacterClassNode = {\n  type: 'CharacterClass';\n  kind: NodeCharacterClassKind;\n  negate: boolean;\n  body: Array<CharacterClassElementNode>;\n};\nfunction createCharacterClass(options?: {\n  kind?: NodeCharacterClassKind;\n  negate?: boolean;\n  body?: Array<CharacterClassElementNode>;\n}): CharacterClassNode {\n  const opts = {\n    kind: 'union' as NodeCharacterClassKind,\n    negate: false,\n    ...options,\n  };\n  return {\n    type: 'CharacterClass',\n    kind: opts.kind,\n    negate: opts.negate,\n    body: getBodyForElementContainer(options?.body) as Array<CharacterClassElementNode>,\n  };\n}\n\ntype CharacterClassRangeNode = {\n  type: 'CharacterClassRange';\n  min: CharacterNode;\n  max: CharacterNode;\n};\nfunction createCharacterClassRange(min: CharacterNode, max: CharacterNode): CharacterClassRangeNode {\n  if (max.value < min.value) {\n    throw new Error('Character class range out of order');\n  }\n  return {\n    type: 'CharacterClassRange',\n    min,\n    max,\n  };\n}\n\ntype NamedCharacterSetNode = {\n  type: 'CharacterSet';\n  kind: 'posix' | 'property';\n  value: string;\n  negate: boolean;\n  variableLength?: never;\n};\ntype UnnamedCharacterSetNode = {\n  type: 'CharacterSet';\n  kind: Exclude<NodeCharacterSetKind, NamedCharacterSetNode['kind']>;\n  value?: never;\n  negate?: boolean;\n  variableLength?: boolean;\n};\ntype CharacterSetNode = NamedCharacterSetNode | UnnamedCharacterSetNode;\n/**\nUse `createUnicodeProperty` and `createPosixClass` for `kind` values `'property'` and `'posix'`.\n*/\nfunction createCharacterSet(kind: UnnamedCharacterSetNode['kind'], options?: {\n  negate?: boolean;\n}): UnnamedCharacterSetNode {\n  const negate = !!options?.negate;\n  const node: UnnamedCharacterSetNode = {\n    type: 'CharacterSet',\n    kind,\n  };\n  if (\n    kind === 'digit' ||\n    kind === 'hex' ||\n    kind === 'newline' ||\n    kind === 'space' ||\n    kind === 'word'\n  ) {\n    node.negate = negate;\n  }\n  if (\n    kind === 'text_segment' ||\n    (kind === 'newline' && !negate)\n  ) {\n    node.variableLength = true;\n  }\n  return node;\n}\n\ntype DirectiveNode = {\n  type: 'Directive';\n} & ({\n  kind: 'keep';\n  flags?: never;\n} | {\n  kind: 'flags';\n  flags: FlagGroupModifiers;\n});\nfunction createDirective(kind: NodeDirectiveKind, options: {flags?: FlagGroupModifiers} = {}): DirectiveNode {\n  if (kind === 'keep') {\n    return {\n      type: 'Directive',\n      kind,\n    };\n  }\n  if (kind === 'flags') {\n    // Note: Flag effects might extend across alternation; ex: `a(?i)b|c` is equivalent to\n    // `a(?i:b)|(?i:c)`, not `a(?i:b|c)`\n    return {\n      type: 'Directive',\n      kind,\n      flags: throwIfNullish(options.flags),\n    };\n  }\n  throw new Error(`Unexpected directive kind \"${kind}\"`);\n}\n\ntype FlagsNode = {\n  type: 'Flags';\n} & FlagProperties;\nfunction createFlags(flags: FlagProperties): FlagsNode {\n  return {\n    type: 'Flags',\n    ...flags,\n  };\n}\n\ntype GroupNode = {\n  type: 'Group';\n  kind?: never;\n  atomic?: boolean;\n  flags?: FlagGroupModifiers;\n  body: Array<AlternativeNode>;\n};\nfunction createGroup(options?: {\n  atomic?: boolean;\n  flags?: FlagGroupModifiers;\n  body?: Array<AlternativeNode>;\n}): GroupNode {\n  const atomic = options?.atomic;\n  const flags = options?.flags;\n  if (atomic && flags) {\n    throw new Error('Atomic group cannot have flags');\n  }\n  return {\n    type: 'Group',\n    ...(atomic && {atomic}),\n    ...(flags && {flags}),\n    body: getBodyForAlternativeContainer(options?.body),\n  };\n}\n\ntype LookaroundAssertionNode = {\n  type: 'LookaroundAssertion';\n  kind: NodeLookaroundAssertionKind;\n  negate: boolean;\n  body: Array<AlternativeNode>;\n};\nfunction createLookaroundAssertion(options?: {\n  behind?: boolean;\n  negate?: boolean;\n  body?: Array<AlternativeNode>;\n}): LookaroundAssertionNode {\n  const opts = {\n    behind: false,\n    negate: false,\n    ...options,\n  };\n  return {\n    type: 'LookaroundAssertion',\n    kind: opts.behind ? 'lookbehind' : 'lookahead',\n    negate: opts.negate,\n    body: getBodyForAlternativeContainer(options?.body),\n  };\n}\n\ntype NamedCalloutNode = {\n  type: 'NamedCallout';\n  kind: NodeNamedCalloutKind;\n  tag: string | null;\n  arguments: Array<string | number> | null;\n};\nfunction createNamedCallout(\n  kind: NodeNamedCalloutKind,\n  tag: string | null,\n  args: Array<string | number> | null\n): NamedCalloutNode {\n  return {\n    type: 'NamedCallout',\n    kind,\n    tag,\n    arguments: args,\n  };\n}\n\nfunction createPosixClass(name: string, options?: {\n  negate?: boolean;\n}): NamedCharacterSetNode & {kind: 'posix'} {\n  const negate = !!options?.negate;\n  if (!PosixClassNames.has(name)) {\n    throw new Error(`Invalid POSIX class \"${name}\"`);\n  }\n  return {\n    type: 'CharacterSet',\n    kind: 'posix',\n    value: name,\n    negate,\n  };\n}\n\ntype QuantifierNode = {\n  type: 'Quantifier';\n  kind: NodeQuantifierKind;\n  min: number;\n  max: number;\n  body: QuantifiableNode;\n};\nfunction createQuantifier(kind: NodeQuantifierKind, min: number, max: number, body: QuantifiableNode): QuantifierNode {\n  if (min > max) {\n    throw new Error('Invalid reversed quantifier range');\n  }\n  return {\n    type: 'Quantifier',\n    kind,\n    min,\n    max,\n    body,\n  };\n}\n\ntype RegexNode = {\n  type: 'Regex';\n  body: Array<AlternativeNode>;\n  flags: FlagsNode;\n};\nfunction createRegex(flags: FlagsNode, options?: {\n  body?: Array<AlternativeNode>;\n}): RegexNode {\n  return {\n    type: 'Regex',\n    body: getBodyForAlternativeContainer(options?.body),\n    flags,\n  };\n}\n\ntype SubroutineNode = {\n  type: 'Subroutine';\n  ref: string | number;\n};\nfunction createSubroutine(ref: string | number): SubroutineNode {\n  return {\n    type: 'Subroutine',\n    ref,\n  };\n}\n\ntype CreateUnicodePropertyOptions = {\n  negate?: boolean;\n  normalizeUnknownPropertyNames?: boolean;\n  skipPropertyNameValidation?: boolean;\n  unicodePropertyMap?: UnicodePropertyMap | null;\n};\nfunction createUnicodeProperty(name: string, options?: CreateUnicodePropertyOptions): NamedCharacterSetNode & {kind: 'property'} {\n  const opts: Required<CreateUnicodePropertyOptions> = {\n    negate: false,\n    normalizeUnknownPropertyNames: false,\n    skipPropertyNameValidation: false,\n    unicodePropertyMap: null,\n    ...options,\n  };\n  let normalized = opts.unicodePropertyMap?.get(slug(name));\n  if (!normalized) {\n    if (opts.normalizeUnknownPropertyNames) {\n      normalized = normalizeUnicodePropertyName(name);\n    // Let the name through as-is if no map provided and normalization not requested\n    } else if (opts.unicodePropertyMap && !opts.skipPropertyNameValidation) {\n      throw new Error(r`Invalid Unicode property \"\\p{${name}}\"`);\n    }\n  }\n  return {\n    type: 'CharacterSet',\n    kind: 'property',\n    value: normalized ?? name,\n    negate: opts.negate,\n  };\n}\n\n// ---------------\n// --- Helpers ---\n// ---------------\n\nfunction createByGroupKind({flags, kind, name, negate, number}: GroupOpenToken): AbsenceFunctionNode | CapturingGroupNode | GroupNode | LookaroundAssertionNode {\n  switch (kind) {\n    case 'absence_repeater':\n      return createAbsenceFunction('repeater');\n    case 'atomic':\n      return createGroup({atomic: true});\n    case 'capturing':\n      return createCapturingGroup(number!, {name});\n    case 'group':\n      return createGroup({flags});\n    case 'lookahead':\n    case 'lookbehind':\n      return createLookaroundAssertion({\n        behind: kind === 'lookbehind',\n        negate,\n      });\n    default:\n      throw new Error(`Unexpected group kind \"${kind}\"`);\n  }\n}\n\nfunction getBodyForAlternativeContainer(body: unknown): Array<AlternativeNode> {\n  if (body === undefined) {\n    body = [createAlternative()];\n  } else if (!Array.isArray(body) || !body.length || !body.every(node => (node as Node).type === 'Alternative')) {\n    throw new Error('Invalid body; expected array of one or more Alternative nodes');\n  }\n  return body as Array<AlternativeNode>;\n}\n\nfunction getBodyForElementContainer(body: unknown): Array<Node> {\n  if (body === undefined) {\n    body = [];\n  } else if (!Array.isArray(body) || !body.every(node => !!(node as Node).type)) {\n    throw new Error('Invalid body; expected array of nodes');\n  }\n  return body as Array<Node>;\n}\n\nfunction isLookahead(node: Node): node is (LookaroundAssertionNode & {kind: 'lookahead'}) {\n  return node.type === 'LookaroundAssertion' && node.kind === 'lookahead';\n}\n\nfunction isLookbehind(node: Node): node is (LookaroundAssertionNode & {kind: 'lookbehind'}) {\n  return node.type === 'LookaroundAssertion' && node.kind === 'lookbehind';\n}\n\nfunction isValidGroupName(name: string): boolean {\n  // Note that backrefs and subroutines might contextually use `-` and `+` to indicate relative\n  // index or recursion level\n  return /^[\\p{Alpha}\\p{Pc}][^)]*$/u.test(name);\n}\n\nfunction normalizeUnicodePropertyName(name: string): string {\n  // In Onig, Unicode property names ignore case, spaces, hyphens, and underscores. Use best effort\n  // to reformat the name to follow official values (covers a lot, but isn't able to map for all\n  // possible formatting differences)\n  return name.\n    trim().\n    replace(/[- _]+/g, '_').\n    replace(/[A-Z][a-z]+(?=[A-Z])/g, '$&_'). // `PropertyName` to `Property_Name`\n    replace(/[A-Za-z]+/g, m => m[0].toUpperCase() + m.slice(1).toLowerCase());\n}\n\n/**\nGenerates a Unicode property lookup name: lowercase, without spaces, hyphens, or underscores.\n*/\nfunction slug(name: string): string {\n  return name.replace(/[- _]+/g, '').toLowerCase();\n}\n\nfunction throwIfUnclosedCharacterClass<T>(token: T, ccFirstToken?: Token): NonNullable<T> {\n  const first = ccFirstToken;\n  return throwIfNullish(token, `Unclosed character class${\n    // Help avoid confusion since e.g. `[]abc` is unclosed but looks like it has an empty class\n    first?.type === 'Character' && first.value === 93 && first.raw === ']' ? ' (started with \"]\")' : ''\n  }`);\n}\n\nfunction throwIfUnclosedGroup<T>(token: T): NonNullable<T> {\n  return throwIfNullish(token, 'Unclosed group');\n}\n\nexport {\n  type AbsenceFunctionNode,\n  type AlternativeNode,\n  type AlternativeContainerNode,\n  type AlternativeElementNode,\n  type AssertionNode,\n  type BackreferenceNode,\n  type CapturingGroupNode,\n  type CharacterClassElementNode,\n  type CharacterClassNode,\n  type CharacterClassRangeNode,\n  type CharacterNode,\n  type CharacterSetNode,\n  type DirectiveNode,\n  type FlagsNode,\n  type GroupNode,\n  type LookaroundAssertionNode,\n  type NamedCalloutNode,\n  type Node,\n  type NodeAbsenceFunctionKind,\n  type NodeAssertionKind,\n  type NodeCharacterClassKind,\n  type NodeCharacterSetKind,\n  type NodeDirectiveKind,\n  type NodeLookaroundAssertionKind,\n  type NodeQuantifierKind,\n  type OnigurumaAst,\n  type ParentNode,\n  type ParseOptions,\n  type QuantifiableNode,\n  type QuantifierNode,\n  type RegexNode,\n  type SubroutineNode,\n  type UnicodePropertyMap,\n  createAbsenceFunction,\n  createAlternative,\n  createAssertion,\n  createBackreference,\n  createCapturingGroup,\n  createCharacter,\n  createCharacterClass,\n  createCharacterClassRange,\n  createCharacterSet,\n  createDirective,\n  createFlags,\n  createGroup,\n  createLookaroundAssertion,\n  createNamedCallout,\n  createPosixClass,\n  createQuantifier,\n  createRegex,\n  createSubroutine,\n  createUnicodeProperty,\n  hasOnlyChild,\n  isAlternativeContainer,\n  isQuantifiable,\n  parse,\n  slug,\n};\n","import type {AlternativeElementNode, AlternativeNode, CharacterClassElementNode, Node, ParentNode, RegexNode} from '../parser/parse.js';\nimport {throwIfNullish} from '../utils.js';\n\ntype ContainerElementNode =\n  // Used within the `body` container of any `AlternativeContainerNode`\n  AlternativeNode |\n  // Any node type used within the `body` container of an `AlternativeNode`\n  AlternativeElementNode |\n  // Any node type used within the `body` container of a `CharacterClassNode`\n  CharacterClassElementNode;\n\ntype Path<N = Node, Root = RegexNode> = {\n  // The current node being traversed\n  node: N;\n  // Parent node of the current node\n  parent: N extends RegexNode ? null : ParentNode;\n  // String property where the current node in held by the parent node, or numeric index in the\n  // parent's `container` array\n  key: N extends RegexNode ? null : number | string;\n  // Container array holding the current node in the parent node; `null` if the parent isn't a type\n  // that contains a list of nodes\n  container: N extends RegexNode ? null : Array<ContainerElementNode> | null;\n  // Starting node of the AST being traversed; usually a `RegexNode` but can be any node type if\n  // traversing from a midpoint\n  root: Root;\n  // Removes the current node; its kids won't be traversed\n  remove: () => void;\n  // Removes all siblings to the right of the current node, without traversing them; returns the\n  // removed nodes\n  removeAllNextSiblings: () => Array<Node>;\n  // Removes all siblings to the left of the current node, which have already been traversed;\n  // returns the removed nodes\n  removeAllPrevSiblings: () => Array<Node>;\n  // Replaces the current node with a new node; kids of the replaced node won't be traversed;\n  // optionally traverses the new node\n  replaceWith: (newNode: Node, options?: {traverse?: boolean}) => void;\n  // Replaces the current node with multiple new nodes; kids of the replaced node won't be\n  // traversed; optionally traverses the new nodes\n  replaceWithMultiple: (newNodes: Array<Node>, options?: {traverse?: boolean}) => void;\n  // Skips traversing kids of the current node\n  skip: () => void;\n};\n\n// `VisitorNodeFn() {…}` is shorthand for `VisitorNodeFn: {enter() {…}}`.\ntype Visitor<State extends object | null = null, Root extends Node = RegexNode> = {\n  [N in Node as N['type']]?: VisitorNodeFn<Path<N, Root>, State> | {\n    enter?: VisitorNodeFn<Path<N, Root>, State>;\n    exit?: VisitorNodeFn<Path<N, Root>, State>;\n  };\n} & {\n  '*'?: VisitorNodeFn<Path<Node, Root>, State> | {\n    enter?: VisitorNodeFn<Path<Node, Root>, State>;\n    exit?: VisitorNodeFn<Path<Node, Root>, State>;\n  };\n};\n\ntype VisitorNodeFn<P, State> = (path: P, state: State) => void;\n\n/**\nTraverses an AST and calls the provided `visitor`'s node function for each node. Returns the same\nobject, possibly modified.\n\nVisitor node functions can modify the AST in place and use methods on the `path` (provided as their\nfirst argument) to help modify the AST. Provided `state` is passed through to all visitor node\nfunctions as their second argument.\n\nVisitor node functions are called in the following order:\n1. `enter` function of the `'*'` node type (if any)\n2. `enter` function of the given node's type (if any)\n3. [The node's kids (if any) are traversed recursively, unless `skip` is called]\n4. `exit` function of the given node's type (if any)\n5. `exit` function of the `'*'` node type (if any)\n*/\nfunction traverse<State extends object | null = null, Root extends Node = RegexNode>(\n  root: Root,\n  visitor: Visitor<State, Root>,\n  state: State | null = null\n): Root {\n  function traverseArray(array: NonNullable<Path['container']>, parent: Path['parent']) {\n    for (let i = 0; i < array.length; i++) {\n      const keyShift = traverseNode(array[i], parent, i, array);\n      i = Math.max(-1, i + keyShift);\n    }\n  }\n  function traverseNode(\n    node: Path['node'],\n    parent: Path['parent'] = null,\n    key: Path['key'] = null,\n    container: Path['container'] = null\n  ): number {\n    let keyShift = 0;\n    let skipTraversingKidsOfPath = false;\n    const path: Path = {\n      node,\n      parent,\n      key,\n      container,\n      root: root as RegexNode,\n      remove() {\n        arrayContainer(container).splice(Math.max(0, numericKey(key) + keyShift), 1);\n        keyShift--;\n        skipTraversingKidsOfPath = true;\n      },\n      removeAllNextSiblings() {\n        return arrayContainer(container).splice(numericKey(key) + 1);\n      },\n      removeAllPrevSiblings() {\n        const shifted = numericKey(key) + keyShift;\n        keyShift -= shifted;\n        return arrayContainer(container).splice(0, Math.max(0, shifted));\n      },\n      replaceWith(newNode, options = {}) {\n        const traverseNew = !!options.traverse;\n        if (container) {\n          container[Math.max(0, numericKey(key) + keyShift)] = newNode as ContainerElementNode;\n        } else {\n          // `key` will be one of:\n          // - For `CharacterClassRangeNode`: 'min', 'max'\n          // - For `QuantifierNode`: 'body'\n          // - For `RegexNode`: 'flags'\n          // @ts-expect-error\n          throwIfNullish(parent, `Can't replace root node`)[key as string] = newNode;\n        }\n        if (traverseNew) {\n          traverseNode(newNode, parent, key, container);\n        }\n        skipTraversingKidsOfPath = true;\n      },\n      replaceWithMultiple(newNodes, options = {}) {\n        const traverseNew = !!options.traverse;\n        arrayContainer(container).splice(Math.max(0, numericKey(key) + keyShift), 1, ...newNodes);\n        keyShift += newNodes.length - 1;\n        if (traverseNew) {\n          let keyShiftInLoop = 0;\n          for (let i = 0; i < newNodes.length; i++) {\n            keyShiftInLoop += traverseNode(newNodes[i], parent, numericKey(key) + i + keyShiftInLoop, container);\n          }\n        }\n        skipTraversingKidsOfPath = true;\n      },\n      skip() {\n        skipTraversingKidsOfPath = true;\n      },\n    };\n\n    const {type} = node;\n    const anyTypeVisitor = visitor['*'];\n    const thisTypeVisitor = visitor[type];\n    const enterAllFn = typeof anyTypeVisitor === 'function' ? anyTypeVisitor : anyTypeVisitor?.enter;\n    const enterThisFn = typeof thisTypeVisitor === 'function' ? thisTypeVisitor : thisTypeVisitor?.enter;\n    // Type args are too complex to avoid TS errors here, but `VisitorNodeFn`s get correct types\n    // @ts-expect-error\n    enterAllFn?.(path, state);\n    // @ts-expect-error\n    enterThisFn?.(path, state);\n\n    if (!skipTraversingKidsOfPath) {\n      switch (type) {\n        case 'AbsenceFunction':\n        case 'Alternative':\n        case 'CapturingGroup':\n        case 'CharacterClass':\n        case 'Group':\n        case 'LookaroundAssertion':\n          traverseArray(node.body, node);\n          break;\n        case 'Assertion':\n        case 'Backreference':\n        case 'Character':\n        case 'CharacterSet':\n        case 'Directive':\n        case 'Flags':\n        case 'NamedCallout':\n        case 'Subroutine':\n          break;\n        case 'CharacterClassRange':\n          traverseNode(node.min, node, 'min');\n          traverseNode(node.max, node, 'max');\n          break;\n        case 'Quantifier':\n          traverseNode(node.body, node, 'body');\n          break;\n        case 'Regex':\n          traverseArray(node.body, node);\n          traverseNode(node.flags, node, 'flags');\n          break;\n        default:\n          throw new Error(`Unexpected node type \"${type}\"`);\n      }\n    }\n\n    // @ts-expect-error\n    (thisTypeVisitor as Exclude<typeof thisTypeVisitor, Function>)?.exit?.(path, state);\n    // @ts-expect-error\n    (anyTypeVisitor as Exclude<typeof anyTypeVisitor, Function>)?.exit?.(path, state);\n    return keyShift;\n  }\n  traverseNode(root);\n  return root;\n}\n\nfunction arrayContainer(value: unknown): Array<Node> {\n  if (!Array.isArray(value)) {\n    throw new Error('Container expected');\n  }\n  return value;\n}\n\nfunction numericKey(value: unknown): number {\n  if (typeof value !== 'number') {\n    throw new Error('Numeric key expected');\n  }\n  return value;\n}\n\nexport {\n  type Path,\n  type Visitor,\n  traverse,\n};\n","// Separating some utils for improved tree shaking of the `./internals` export\n\nconst noncapturingDelim = String.raw`\\(\\?(?:[:=!>A-Za-z\\-]|<[=!]|\\(DEFINE\\))`;\n\n/**\nUpdates the array in place by incrementing each value greater than or equal to the threshold.\n@param {Array<number>} arr\n@param {number} threshold\n*/\nfunction incrementIfAtLeast(arr, threshold) {\n  for (let i = 0; i < arr.length; i++) {\n    if (arr[i] >= threshold) {\n      arr[i]++;\n    }\n  }\n}\n\n/**\n@param {string} str\n@param {number} pos\n@param {string} oldValue\n@param {string} newValue\n@returns {string}\n*/\nfunction spliceStr(str, pos, oldValue, newValue) {\n  return str.slice(0, pos) + newValue + str.slice(pos + oldValue.length);\n}\n\nexport {\n  incrementIfAtLeast,\n  noncapturingDelim,\n  spliceStr,\n};\n","// Constant properties for tracking regex syntax context\nexport const Context = Object.freeze({\n  DEFAULT: 'DEFAULT',\n  CHAR_CLASS: 'CHAR_CLASS',\n});\n\n/**\nReplaces all unescaped instances of a regex pattern in the given context, using a replacement\nstring or callback.\n\nDoesn't skip over complete multicharacter tokens (only `\\` plus its folowing char) so must be used\nwith knowledge of what's safe to do given regex syntax. Assumes UnicodeSets-mode syntax.\n@param {string} expression Search target\n@param {string} needle Search as a regex pattern, with flags `su` applied\n@param {string | (match: RegExpExecArray, details: {\n  context: 'DEFAULT' | 'CHAR_CLASS';\n  negated: boolean;\n}) => string} replacement\n@param {'DEFAULT' | 'CHAR_CLASS'} [context] All contexts if not specified\n@returns {string} Updated expression\n@example\nconst str = '.\\\\.\\\\\\\\.[[\\\\.].].';\nreplaceUnescaped(str, '\\\\.', '@');\n// → '@\\\\.\\\\\\\\@[[\\\\.]@]@'\nreplaceUnescaped(str, '\\\\.', '@', Context.DEFAULT);\n// → '@\\\\.\\\\\\\\@[[\\\\.].]@'\nreplaceUnescaped(str, '\\\\.', '@', Context.CHAR_CLASS);\n// → '.\\\\.\\\\\\\\.[[\\\\.]@].'\n*/\nexport function replaceUnescaped(expression, needle, replacement, context) {\n  const re = new RegExp(String.raw`${needle}|(?<$skip>\\[\\^?|\\\\?.)`, 'gsu');\n  const negated = [false];\n  let numCharClassesOpen = 0;\n  let result = '';\n  for (const match of expression.matchAll(re)) {\n    const {0: m, groups: {$skip}} = match;\n    if (!$skip && (!context || (context === Context.DEFAULT) === !numCharClassesOpen)) {\n      if (replacement instanceof Function) {\n        result += replacement(match, {\n          context: numCharClassesOpen ? Context.CHAR_CLASS : Context.DEFAULT,\n          negated: negated[negated.length - 1],\n        });\n      } else {\n        result += replacement;\n      }\n      continue;\n    }\n    if (m[0] === '[') {\n      numCharClassesOpen++;\n      negated.push(m[1] === '^');\n    } else if (m === ']' && numCharClassesOpen) {\n      numCharClassesOpen--;\n      negated.pop();\n    }\n    result += m;\n  }\n  return result;\n}\n\n/**\nRuns a callback for each unescaped instance of a regex pattern in the given context.\n\nDoesn't skip over complete multicharacter tokens (only `\\` plus its folowing char) so must be used\nwith knowledge of what's safe to do given regex syntax. Assumes UnicodeSets-mode syntax.\n@param {string} expression Search target\n@param {string} needle Search as a regex pattern, with flags `su` applied\n@param {(match: RegExpExecArray, details: {\n  context: 'DEFAULT' | 'CHAR_CLASS';\n  negated: boolean;\n}) => void} callback\n@param {'DEFAULT' | 'CHAR_CLASS'} [context] All contexts if not specified\n*/\nexport function forEachUnescaped(expression, needle, callback, context) {\n  // Do this the easy way\n  replaceUnescaped(expression, needle, callback, context);\n}\n\n/**\nReturns a match object for the first unescaped instance of a regex pattern in the given context, or\n`null`.\n\nDoesn't skip over complete multicharacter tokens (only `\\` plus its folowing char) so must be used\nwith knowledge of what's safe to do given regex syntax. Assumes UnicodeSets-mode syntax.\n@param {string} expression Search target\n@param {string} needle Search as a regex pattern, with flags `su` applied\n@param {number} [pos] Offset to start the search\n@param {'DEFAULT' | 'CHAR_CLASS'} [context] All contexts if not specified\n@returns {RegExpExecArray | null}\n*/\nexport function execUnescaped(expression, needle, pos = 0, context) {\n  // Quick partial test; avoid the loop if not needed\n  if (!(new RegExp(needle, 'su').test(expression))) {\n    return null;\n  }\n  const re = new RegExp(`${needle}|(?<$skip>\\\\\\\\?.)`, 'gsu');\n  re.lastIndex = pos;\n  let numCharClassesOpen = 0;\n  let match;\n  while (match = re.exec(expression)) {\n    const {0: m, groups: {$skip}} = match;\n    if (!$skip && (!context || (context === Context.DEFAULT) === !numCharClassesOpen)) {\n      return match;\n    }\n    if (m === '[') {\n      numCharClassesOpen++;\n    } else if (m === ']' && numCharClassesOpen) {\n      numCharClassesOpen--;\n    }\n    // Avoid an infinite loop on zero-length matches\n    if (re.lastIndex == match.index) {\n      re.lastIndex++;\n    }\n  }\n  return null;\n}\n\n/**\nChecks whether an unescaped instance of a regex pattern appears in the given context.\n\nDoesn't skip over complete multicharacter tokens (only `\\` plus its folowing char) so must be used\nwith knowledge of what's safe to do given regex syntax. Assumes UnicodeSets-mode syntax.\n@param {string} expression Search target\n@param {string} needle Search as a regex pattern, with flags `su` applied\n@param {'DEFAULT' | 'CHAR_CLASS'} [context] All contexts if not specified\n@returns {boolean} Whether the pattern was found\n*/\nexport function hasUnescaped(expression, needle, context) {\n  // Do this the easy way\n  return !!execUnescaped(expression, needle, 0, context);\n}\n\n/**\nExtracts the full contents of a group (subpattern) from the given expression, accounting for\nescaped characters, nested groups, and character classes. The group is identified by the position\nwhere its contents start (the string index just after the group's opening delimiter). Returns the\nrest of the string if the group is unclosed.\n\nAssumes UnicodeSets-mode syntax.\n@param {string} expression Search target\n@param {number} contentsStartPos\n@returns {string}\n*/\nexport function getGroupContents(expression, contentsStartPos) {\n  const token = /\\\\?./gsu;\n  token.lastIndex = contentsStartPos;\n  let contentsEndPos = expression.length;\n  let numCharClassesOpen = 0;\n  // Starting search within an open group, after the group's opening\n  let numGroupsOpen = 1;\n  let match;\n  while (match = token.exec(expression)) {\n    const [m] = match;\n    if (m === '[') {\n      numCharClassesOpen++;\n    } else if (!numCharClassesOpen) {\n      if (m === '(') {\n        numGroupsOpen++;\n      } else if (m === ')') {\n        numGroupsOpen--;\n        if (!numGroupsOpen) {\n          contentsEndPos = match.index;\n          break;\n        }\n      }\n    } else if (m === ']') {\n      numCharClassesOpen--;\n    }\n  }\n  return expression.slice(contentsStartPos, contentsEndPos);\n}\n","import {incrementIfAtLeast, noncapturingDelim, spliceStr} from './utils-internals.js';\nimport {Context, replaceUnescaped} from 'regex-utilities';\n/**\n@import {PluginData, PluginResult} from './regex.js';\n*/\n\nconst atomicPluginToken = new RegExp(String.raw`(?<noncapturingStart>${noncapturingDelim})|(?<capturingStart>\\((?:\\?<[^>]+>)?)|\\\\?.`, 'gsu');\n\n/**\nApply transformations for atomic groups: `(?>…)`.\n@param {string} expression\n@param {PluginData} [data]\n@returns {Required<PluginResult>}\n*/\nfunction atomic(expression, data) {\n  const hiddenCaptures = data?.hiddenCaptures ?? [];\n  // Capture transfer is used by <github.com/slevithan/oniguruma-to-es>\n  let captureTransfers = data?.captureTransfers ?? new Map();\n  if (!/\\(\\?>/.test(expression)) {\n    return {\n      pattern: expression,\n      captureTransfers,\n      hiddenCaptures,\n    };\n  }\n\n  const aGDelim = '(?>';\n  const emulatedAGDelim = '(?:(?=(';\n  const captureNumMap = [0];\n  const addedHiddenCaptures = [];\n  let numCapturesBeforeAG = 0;\n  let numAGs = 0;\n  let aGPos = NaN;\n  let hasProcessedAG;\n  do {\n    hasProcessedAG = false;\n    let numCharClassesOpen = 0;\n    let numGroupsOpenInAG = 0;\n    let inAG = false;\n    let match;\n    atomicPluginToken.lastIndex = Number.isNaN(aGPos) ? 0 : aGPos + emulatedAGDelim.length;\n    while (match = atomicPluginToken.exec(expression)) {\n      const {0: m, index, groups: {capturingStart, noncapturingStart}} = match;\n      if (m === '[') {\n        numCharClassesOpen++;\n      } else if (!numCharClassesOpen) {\n\n        if (m === aGDelim && !inAG) {\n          aGPos = index;\n          inAG = true;\n        } else if (inAG && noncapturingStart) {\n          numGroupsOpenInAG++;\n        } else if (capturingStart) {\n          if (inAG) {\n            numGroupsOpenInAG++;\n          } else {\n            numCapturesBeforeAG++;\n            captureNumMap.push(numCapturesBeforeAG + numAGs);\n          }\n        } else if (m === ')' && inAG) {\n          if (!numGroupsOpenInAG) {\n            numAGs++;\n            const addedCaptureNum = numCapturesBeforeAG + numAGs;\n            // Replace `expression` and use `<$$N>` as a temporary wrapper for the backref so it\n            // can avoid backref renumbering afterward. Wrap the whole substitution (including the\n            // lookahead and following backref) in a noncapturing group to handle following\n            // quantifiers and literal digits\n            expression = `${expression.slice(0, aGPos)}${emulatedAGDelim}${\n                expression.slice(aGPos + aGDelim.length, index)\n              }))<$$${addedCaptureNum}>)${expression.slice(index + 1)}`;\n            hasProcessedAG = true;\n            addedHiddenCaptures.push(addedCaptureNum);\n            incrementIfAtLeast(hiddenCaptures, addedCaptureNum);\n            if (captureTransfers.size) {\n              const newCaptureTransfers = new Map();\n              captureTransfers.forEach((from, to) => {\n                newCaptureTransfers.set(\n                  to >= addedCaptureNum ? to + 1 : to,\n                  from.map(f => f >= addedCaptureNum ? f + 1 : f)\n                );\n              });\n              captureTransfers = newCaptureTransfers;\n            }\n            break;\n          }\n          numGroupsOpenInAG--;\n        }\n\n      } else if (m === ']') {\n        numCharClassesOpen--;\n      }\n    }\n  // Start over from the beginning of the atomic group's contents, in case the processed group\n  // contains additional atomic groups\n  } while (hasProcessedAG);\n\n  hiddenCaptures.push(...addedHiddenCaptures);\n\n  // Second pass to adjust numbered backrefs\n  expression = replaceUnescaped(\n    expression,\n    String.raw`\\\\(?<backrefNum>[1-9]\\d*)|<\\$\\$(?<wrappedBackrefNum>\\d+)>`,\n    ({0: m, groups: {backrefNum, wrappedBackrefNum}}) => {\n      if (backrefNum) {\n        const bNum = +backrefNum;\n        if (bNum > captureNumMap.length - 1) {\n          throw new Error(`Backref \"${m}\" greater than number of captures`);\n        }\n        return `\\\\${captureNumMap[bNum]}`;\n      }\n      return `\\\\${wrappedBackrefNum}`;\n    },\n    Context.DEFAULT\n  );\n\n  return {\n    pattern: expression,\n    captureTransfers,\n    hiddenCaptures,\n  };\n}\n\nconst baseQuantifier = String.raw`(?:[?*+]|\\{\\d+(?:,\\d*)?\\})`;\n// Complete tokenizer for base syntax; doesn't (need to) know about character-class-only syntax\nconst possessivePluginToken = new RegExp(String.raw`\n\\\\(?: \\d+\n  | c[A-Za-z]\n  | [gk]<[^>]+>\n  | [pPu]\\{[^\\}]+\\}\n  | u[A-Fa-f\\d]{4}\n  | x[A-Fa-f\\d]{2}\n  )\n| \\((?: \\? (?: [:=!>]\n  | <(?:[=!]|[^>]+>)\n  | [A-Za-z\\-]+:\n  | \\(DEFINE\\)\n  ))?\n| (?<qBase>${baseQuantifier})(?<qMod>[?+]?)(?<invalidQ>[?*+\\{]?)\n| \\\\?.\n`.replace(/\\s+/g, ''), 'gsu');\n\n/**\nTransform posessive quantifiers into atomic groups. The posessessive quantifiers are:\n`?+`, `*+`, `++`, `{N}+`, `{N,}+`, `{N,N}+`.\nThis follows Java, PCRE, Perl, and Python.\nPossessive quantifiers in Oniguruma and Onigmo are only: `?+`, `*+`, `++`.\n@param {string} expression\n@returns {PluginResult}\n*/\nfunction possessive(expression) {\n  if (!(new RegExp(`${baseQuantifier}\\\\+`).test(expression))) {\n    return {\n      pattern: expression,\n    };\n  }\n\n  const openGroupIndices = [];\n  let lastGroupIndex = null;\n  let lastCharClassIndex = null;\n  let lastToken = '';\n  let numCharClassesOpen = 0;\n  let match;\n  possessivePluginToken.lastIndex = 0;\n  while (match = possessivePluginToken.exec(expression)) {\n    const {0: m, index, groups: {qBase, qMod, invalidQ}} = match;\n    if (m === '[') {\n      if (!numCharClassesOpen) {\n        lastCharClassIndex = index;\n      }\n      numCharClassesOpen++;\n    } else if (m === ']') {\n      if (numCharClassesOpen) {\n        numCharClassesOpen--;\n      // Unmatched `]`\n      } else {\n        lastCharClassIndex = null;\n      }\n    } else if (!numCharClassesOpen) {\n\n      if (qMod === '+' && lastToken && !lastToken.startsWith('(')) {\n        // Invalid following quantifier would become valid via the wrapping group\n        if (invalidQ) {\n          throw new Error(`Invalid quantifier \"${m}\"`);\n        }\n        let charsAdded = -1; // -1 for removed trailing `+`\n        // Possessivizing fixed repetition quantifiers like `{2}` does't change their behavior, so\n        // avoid doing so (convert them to greedy)\n        if (/^\\{\\d+\\}$/.test(qBase)) {\n          expression = spliceStr(expression, index + qBase.length, qMod, '');\n        } else {\n          if (lastToken === ')' || lastToken === ']') {\n            const nodeIndex = lastToken === ')' ? lastGroupIndex : lastCharClassIndex;\n            // Unmatched `)` would break out of the wrapping group and mess with handling.\n            // Unmatched `]` wouldn't be a problem, but it's unnecessary to have dedicated support\n            // for unescaped `]++` since this won't work with flag u or v anyway\n            if (nodeIndex === null) {\n              throw new Error(`Invalid unmatched \"${lastToken}\"`);\n            }\n            expression = `${expression.slice(0, nodeIndex)}(?>${expression.slice(nodeIndex, index)}${qBase})${expression.slice(index + m.length)}`;\n          } else {\n            expression = `${expression.slice(0, index - lastToken.length)}(?>${lastToken}${qBase})${expression.slice(index + m.length)}`;\n          }\n          charsAdded += 4; // `(?>)`\n        }\n        possessivePluginToken.lastIndex += charsAdded;\n      } else if (m[0] === '(') {\n        openGroupIndices.push(index);\n      } else if (m === ')') {\n        lastGroupIndex = openGroupIndices.length ? openGroupIndices.pop() : null;\n      }\n\n    }\n    lastToken = m;\n  }\n\n  return {\n    pattern: expression,\n  };\n}\n\nexport {\n  atomic,\n  possessive,\n};\n","import {Context, forEachUnescaped, getGroupContents, hasUnescaped, replaceUnescaped} from 'regex-utilities';\n\nconst r = String.raw;\nconst gRToken = r`\\\\g<(?<gRNameOrNum>[^>&]+)&R=(?<gRDepth>[^>]+)>`;\nconst recursiveToken = r`\\(\\?R=(?<rDepth>[^\\)]+)\\)|${gRToken}`;\nconst namedCaptureDelim = r`\\(\\?<(?![=!])(?<captureName>[^>]+)>`;\nconst captureDelim = r`${namedCaptureDelim}|(?<unnamed>\\()(?!\\?)`;\nconst token = new RegExp(r`${namedCaptureDelim}|${recursiveToken}|\\(\\?|\\\\?.`, 'gsu');\nconst overlappingRecursionMsg = 'Cannot use multiple overlapping recursions';\n\n/**\n@param {string} pattern\n@param {{\n  flags?: string;\n  captureTransfers?: Map<number, Array<number>>;\n  hiddenCaptures?: Array<number>;\n  mode?: 'plugin' | 'external';\n}} [data]\n@returns {{\n  pattern: string;\n  captureTransfers: Map<number, Array<number>>;\n  hiddenCaptures: Array<number>;\n}}\n*/\nfunction recursion(pattern, data) {\n  const {hiddenCaptures, mode} = {\n    hiddenCaptures: [],\n    mode: 'plugin',\n    ...data,\n  };\n  // Capture transfer is used by <github.com/slevithan/oniguruma-to-es>\n  let captureTransfers = data?.captureTransfers ?? new Map();\n  // Keep the initial fail-check (which avoids unneeded processing) as fast as possible by testing\n  // without the accuracy improvement of using `hasUnescaped` with `Context.DEFAULT`\n  if (!(new RegExp(recursiveToken, 'su').test(pattern))) {\n    return {\n      pattern,\n      captureTransfers,\n      hiddenCaptures,\n    };\n  }\n  if (mode === 'plugin' && hasUnescaped(pattern, r`\\(\\?\\(DEFINE\\)`, Context.DEFAULT)) {\n    throw new Error('DEFINE groups cannot be used with recursion');\n  }\n\n  const addedHiddenCaptures = [];\n  const hasNumberedBackref = hasUnescaped(pattern, r`\\\\[1-9]`, Context.DEFAULT);\n  const groupContentsStartPos = new Map();\n  const openGroups = [];\n  let hasRecursed = false;\n  let numCharClassesOpen = 0;\n  let numCapturesPassed = 0;\n  let match;\n  token.lastIndex = 0;\n  while ((match = token.exec(pattern))) {\n    const {0: m, groups: {captureName, rDepth, gRNameOrNum, gRDepth}} = match;\n    if (m === '[') {\n      numCharClassesOpen++;\n    } else if (!numCharClassesOpen) {\n\n      // `(?R=N)`\n      if (rDepth) {\n        assertMaxInBounds(rDepth);\n        if (hasRecursed) {\n          throw new Error(overlappingRecursionMsg);\n        }\n        if (hasNumberedBackref) {\n          // Could add support for numbered backrefs with extra effort, but it's probably not worth\n          // it. To trigger this error, the regex must include recursion and one of the following:\n          // - An interpolated regex that contains a numbered backref (since other numbered\n          //   backrefs are prevented by implicit flag n).\n          // - A numbered backref, when flag n is explicitly disabled.\n          // Note that Regex+'s extended syntax (atomic groups and sometimes subroutines) can also\n          // add numbered backrefs, but those work fine because external plugins like this one run\n          // *before* the transformation of built-in syntax extensions\n          throw new Error(\n            // When used in `external` mode by transpilers other than Regex+, backrefs might have\n            // gone through conversion from named to numbered, so avoid a misleading error\n            `${mode === 'external' ? 'Backrefs' : 'Numbered backrefs'} cannot be used with global recursion`\n          );\n        }\n        const left = pattern.slice(0, match.index);\n        const right = pattern.slice(token.lastIndex);\n        if (hasUnescaped(right, recursiveToken, Context.DEFAULT)) {\n          throw new Error(overlappingRecursionMsg);\n        }\n        const reps = +rDepth - 1;\n        pattern = makeRecursive(\n          left,\n          right,\n          reps,\n          false,\n          hiddenCaptures,\n          addedHiddenCaptures,\n          numCapturesPassed\n        );\n        captureTransfers = mapCaptureTransfers(\n          captureTransfers,\n          left,\n          reps,\n          addedHiddenCaptures.length,\n          0,\n          numCapturesPassed\n        );\n        // No need to parse further\n        break;\n      // `\\g<name&R=N>`, `\\g<number&R=N>`\n      } else if (gRNameOrNum) {\n        assertMaxInBounds(gRDepth);\n        let isWithinReffedGroup = false;\n        for (const g of openGroups) {\n          if (g.name === gRNameOrNum || g.num === +gRNameOrNum) {\n            isWithinReffedGroup = true;\n            if (g.hasRecursedWithin) {\n              throw new Error(overlappingRecursionMsg);\n            }\n            break;\n          }\n        }\n        if (!isWithinReffedGroup) {\n          throw new Error(r`Recursive \\g cannot be used outside the referenced group \"${\n            mode === 'external' ? gRNameOrNum : r`\\g<${gRNameOrNum}&R=${gRDepth}>`\n          }\"`);\n        }\n        const startPos = groupContentsStartPos.get(gRNameOrNum);\n        const groupContents = getGroupContents(pattern, startPos);\n        if (\n          hasNumberedBackref &&\n          hasUnescaped(groupContents, r`${namedCaptureDelim}|\\((?!\\?)`, Context.DEFAULT)\n        ) {\n          throw new Error(\n            // When used in `external` mode by transpilers other than Regex+, backrefs might have\n            // gone through conversion from named to numbered, so avoid a misleading error\n            `${mode === 'external' ? 'Backrefs' : 'Numbered backrefs'} cannot be used with recursion of capturing groups`\n          );\n        }\n        const groupContentsLeft = pattern.slice(startPos, match.index);\n        const groupContentsRight = groupContents.slice(groupContentsLeft.length + m.length);\n        const numAddedHiddenCapturesPreExpansion = addedHiddenCaptures.length;\n        const reps = +gRDepth - 1;\n        const expansion = makeRecursive(\n          groupContentsLeft,\n          groupContentsRight,\n          reps,\n          true,\n          hiddenCaptures,\n          addedHiddenCaptures,\n          numCapturesPassed\n        );\n        captureTransfers = mapCaptureTransfers(\n          captureTransfers,\n          groupContentsLeft,\n          reps,\n          addedHiddenCaptures.length - numAddedHiddenCapturesPreExpansion,\n          numAddedHiddenCapturesPreExpansion,\n          numCapturesPassed\n        );\n        const pre = pattern.slice(0, startPos);\n        const post = pattern.slice(startPos + groupContents.length);\n        // Modify the string we're looping over\n        pattern = `${pre}${expansion}${post}`;\n        // Step forward for the next loop iteration\n        token.lastIndex += expansion.length - m.length - groupContentsLeft.length - groupContentsRight.length;\n        openGroups.forEach(g => g.hasRecursedWithin = true);\n        hasRecursed = true;\n      } else if (captureName) {\n        numCapturesPassed++;\n        groupContentsStartPos.set(String(numCapturesPassed), token.lastIndex);\n        groupContentsStartPos.set(captureName, token.lastIndex);\n        openGroups.push({\n          num: numCapturesPassed,\n          name: captureName,\n        });\n      } else if (m[0] === '(') {\n        const isUnnamedCapture = m === '(';\n        if (isUnnamedCapture) {\n          numCapturesPassed++;\n          groupContentsStartPos.set(String(numCapturesPassed), token.lastIndex);\n        }\n        openGroups.push(isUnnamedCapture ? {num: numCapturesPassed} : {});\n      } else if (m === ')') {\n        openGroups.pop();\n      }\n\n    } else if (m === ']') {\n      numCharClassesOpen--;\n    }\n  }\n\n  hiddenCaptures.push(...addedHiddenCaptures);\n\n  return {\n    pattern,\n    captureTransfers,\n    hiddenCaptures,\n  };\n}\n\n/**\n@param {string} max\n*/\nfunction assertMaxInBounds(max) {\n  const errMsg = `Max depth must be integer between 2 and 100; used ${max}`;\n  if (!/^[1-9]\\d*$/.test(max)) {\n    throw new Error(errMsg);\n  }\n  max = +max;\n  if (max < 2 || max > 100) {\n    throw new Error(errMsg);\n  }\n}\n\n/**\n@param {string} left\n@param {string} right\n@param {number} reps\n@param {boolean} isSubpattern\n@param {Array<number>} hiddenCaptures\n@param {Array<number>} addedHiddenCaptures\n@param {number} numCapturesPassed\n@returns {string}\n*/\nfunction makeRecursive(\n  left,\n  right,\n  reps,\n  isSubpattern,\n  hiddenCaptures,\n  addedHiddenCaptures,\n  numCapturesPassed\n) {\n  const namesInRecursed = new Set();\n  // Can skip this work if not needed\n  if (isSubpattern) {\n    forEachUnescaped(left + right, namedCaptureDelim, ({groups: {captureName}}) => {\n      namesInRecursed.add(captureName);\n    }, Context.DEFAULT);\n  }\n  const rest = [\n    reps,\n    isSubpattern ? namesInRecursed : null,\n    hiddenCaptures,\n    addedHiddenCaptures,\n    numCapturesPassed,\n  ];\n  // Depth 2: 'left(?:left(?:)right)right'\n  // Depth 3: 'left(?:left(?:left(?:)right)right)right'\n  // Empty group in the middle separates tokens and absorbs a following quantifier if present\n  return `${left}${\n    repeatWithDepth(`(?:${left}`, 'forward', ...rest)\n  }(?:)${\n    repeatWithDepth(`${right})`, 'backward', ...rest)\n  }${right}`;\n}\n\n/**\n@param {string} pattern\n@param {'forward' | 'backward'} direction\n@param {number} reps\n@param {Set<string> | null} namesInRecursed\n@param {Array<number>} hiddenCaptures\n@param {Array<number>} addedHiddenCaptures\n@param {number} numCapturesPassed\n@returns {string}\n*/\nfunction repeatWithDepth(\n  pattern,\n  direction,\n  reps,\n  namesInRecursed,\n  hiddenCaptures,\n  addedHiddenCaptures,\n  numCapturesPassed\n) {\n  const startNum = 2;\n  const getDepthNum = i => direction === 'forward' ? (i + startNum) : (reps - i + startNum - 1);\n  let result = '';\n  for (let i = 0; i < reps; i++) {\n    const depthNum = getDepthNum(i);\n    result += replaceUnescaped(\n      pattern,\n      r`${captureDelim}|\\\\k<(?<backref>[^>]+)>`,\n      ({0: m, groups: {captureName, unnamed, backref}}) => {\n        if (backref && namesInRecursed && !namesInRecursed.has(backref)) {\n          // Don't alter backrefs to groups outside the recursed subpattern\n          return m;\n        }\n        const suffix = `_$${depthNum}`;\n        if (unnamed || captureName) {\n          const addedCaptureNum = numCapturesPassed + addedHiddenCaptures.length + 1;\n          addedHiddenCaptures.push(addedCaptureNum);\n          incrementIfAtLeast(hiddenCaptures, addedCaptureNum);\n          return unnamed ? m : `(?<${captureName}${suffix}>`;\n        }\n        return r`\\k<${backref}${suffix}>`;\n      },\n      Context.DEFAULT\n    );\n  }\n  return result;\n}\n\n/**\nUpdates the array in place by incrementing each value greater than or equal to the threshold.\n@param {Array<number>} arr\n@param {number} threshold\n*/\nfunction incrementIfAtLeast(arr, threshold) {\n  for (let i = 0; i < arr.length; i++) {\n    if (arr[i] >= threshold) {\n      arr[i]++;\n    }\n  }\n}\n\n/**\n@param {Map<number, Array<number>>} captureTransfers\n@param {string} left\n@param {number} reps\n@param {number} numCapturesAddedInExpansion\n@param {number} numAddedHiddenCapturesPreExpansion\n@param {number} numCapturesPassed\n@returns {Map<number, Array<number>>}\n*/\nfunction mapCaptureTransfers(captureTransfers, left, reps, numCapturesAddedInExpansion, numAddedHiddenCapturesPreExpansion, numCapturesPassed) {\n  if (captureTransfers.size && numCapturesAddedInExpansion) {\n    let numCapturesInLeft = 0;\n    forEachUnescaped(left, captureDelim, () => numCapturesInLeft++, Context.DEFAULT);\n    // Is 0 for global recursion\n    const recursionDelimCaptureNum = numCapturesPassed - numCapturesInLeft + numAddedHiddenCapturesPreExpansion;\n    const newCaptureTransfers = new Map();\n    captureTransfers.forEach((from, to) => {\n      const numCapturesInRight = (numCapturesAddedInExpansion - (numCapturesInLeft * reps)) / reps;\n      const numCapturesAddedInLeft = numCapturesInLeft * reps;\n      const newTo = to > (recursionDelimCaptureNum + numCapturesInLeft) ? to + numCapturesAddedInExpansion : to;\n      const newFrom = [];\n      for (const f of from) {\n        // Before the recursed subpattern\n        if (f <= recursionDelimCaptureNum) {\n          newFrom.push(f);\n        // After the recursed subpattern\n        } else if (f > (recursionDelimCaptureNum + numCapturesInLeft + numCapturesInRight)) {\n          newFrom.push(f + numCapturesAddedInExpansion);\n        // Within the recursed subpattern, on the left of the recursion token\n        } else if (f <= (recursionDelimCaptureNum + numCapturesInLeft)) {\n          for (let i = 0; i <= reps; i++) {\n            newFrom.push(f + (numCapturesInLeft * i));\n          }\n        // Within the recursed subpattern, on the right of the recursion token\n        } else {\n          for (let i = 0; i <= reps; i++) {\n            newFrom.push(f + numCapturesAddedInLeft + (numCapturesInRight * i));\n          }\n        }\n      }\n      newCaptureTransfers.set(newTo, newFrom);\n    });\n    return newCaptureTransfers;\n  }\n  return captureTransfers;\n}\n\nexport {\n  recursion,\n};\n","import {EsVersion, Target} from './options.js';\n\nconst cp = String.fromCodePoint;\nconst r = String.raw;\n\nconst envFlags = {};\n// Use `globalThis` to prevent env-testing fns from being replaced with constants during bundling\n// with Rolldown; see <github.com/slevithan/oniguruma-to-es/issues/42>\nconst globalRegExp = globalThis.RegExp;\nenvFlags.flagGroups = (() => {\n  try {\n    new globalRegExp('(?i:)');\n  } catch {\n    return false;\n  }\n  return true;\n})();\nenvFlags.unicodeSets = (() => {\n  try {\n    // Check for flag v support and also that nested classes can be parsed\n    // See <github.com/slevithan/oniguruma-to-es/pull/41>\n    new globalRegExp('[[]]', 'v');\n  } catch {\n    return false;\n  }\n  return true;\n})();\n// Detect WebKit bug: <github.com/slevithan/oniguruma-to-es/issues/30>\nenvFlags.bugFlagVLiteralHyphenIsRange = envFlags.unicodeSets ? (() => {\n  try {\n    new globalRegExp(r`[\\d\\-a]`, 'v');\n  } catch {\n    return true;\n  }\n  return false;\n})() : false;\n// Detect WebKit bug: <github.com/slevithan/oniguruma-to-es/issues/38>\nenvFlags.bugNestedClassIgnoresNegation = envFlags.unicodeSets && new globalRegExp('[[^a]]', 'v').test('a');\n\nfunction getNewCurrentFlags(current, {enable, disable}) {\n  return {\n    dotAll: !disable?.dotAll && !!(enable?.dotAll || current.dotAll),\n    ignoreCase: !disable?.ignoreCase && !!(enable?.ignoreCase || current.ignoreCase),\n  };\n}\n\nfunction getOrInsert(map, key, defaultValue) {\n  if (!map.has(key)) {\n    map.set(key, defaultValue);\n  }\n  return map.get(key);\n}\n\n/**\n@param {keyof Target} target\n@param {keyof Target} min\n@returns {boolean}\n*/\nfunction isMinTarget(target, min) {\n  return EsVersion[target] >= EsVersion[min];\n}\n\nfunction throwIfNullish(value, msg) {\n  if (value == null) {\n    throw new Error(msg ?? 'Value expected');\n  }\n  return value;\n}\n\nexport {\n  cp,\n  envFlags,\n  getNewCurrentFlags,\n  getOrInsert,\n  isMinTarget,\n  r,\n  throwIfNullish,\n};\n","import {envFlags} from './utils.js';\n/**\n@import {ToRegExpOptions} from './index.js';\n*/\n\nconst Accuracy = /** @type {const} */ ({\n  default: 'default',\n  strict: 'strict',\n});\n\nconst EsVersion = {\n  ES2025: 2025,\n  ES2024: 2024,\n  ES2018: 2018,\n};\n\nconst Target = /** @type {const} */ ({\n  auto: 'auto',\n  ES2025: 'ES2025',\n  ES2024: 'ES2024',\n  ES2018: 'ES2018',\n});\n\n/**\nReturns a complete set of options, with default values set for options that weren't provided.\n@param {ToRegExpOptions} [options]\n@returns {Required<ToRegExpOptions>}\n*/\nfunction getOptions(options = {}) {\n  if ({}.toString.call(options) !== '[object Object]') {\n    throw new Error('Unexpected options');\n  }\n  if (options.target !== undefined && !Target[options.target]) {\n    throw new Error(`Unexpected target \"${options.target}\"`)\n  }\n  // Set default values\n  const opts = {\n    // Sets the level of emulation rigor/strictness.\n    accuracy: 'default',\n    // Disables advanced emulation that relies on returning a `RegExp` subclass, resulting in\n    // certain patterns not being emulatable.\n    avoidSubclass: false,\n    // Oniguruma flags; a string with `i`, `m`, `x`, `D`, `S`, `W`, `y{g}` in any order (all\n    // optional). Oniguruma's `m` is equivalent to JavaScript's `s` (`dotAll`).\n    flags: '',\n    // Include JavaScript flag `g` (`global`) in the result.\n    global: false,\n    // Include JavaScript flag `d` (`hasIndices`) in the result.\n    hasIndices: false,\n    // Delay regex construction until first use if the transpiled pattern is at least this length.\n    lazyCompileLength: Infinity,\n    // JavaScript version used for generated regexes. Using `auto` detects the best value based on\n    // your environment. Later targets allow faster processing, simpler generated source, and\n    // support for additional features.\n    target: 'auto',\n    // Disables minifications that simplify the pattern without changing the meaning.\n    verbose: false,\n    ...options,\n    // Advanced options that override standard behavior, error checking, and flags when enabled.\n    rules: {\n      // Useful with TextMate grammars that merge backreferences across patterns.\n      allowOrphanBackrefs: false,\n      // Use ASCII `\\b` and `\\B`, which increases search performance of generated regexes.\n      asciiWordBoundaries: false,\n      // Allow unnamed captures and numbered calls (backreferences and subroutines) when using\n      // named capture. This is Oniguruma option `ONIG_OPTION_CAPTURE_GROUP`; on by default in\n      // `vscode-oniguruma`.\n      captureGroup: false,\n      // Change the recursion depth limit from Oniguruma's `20` to an integer `2`–`20`.\n      recursionLimit: 20,\n      // `^` as `\\A`; `$` as`\\Z`. Improves search performance of generated regexes without changing\n      // the meaning if searching line by line. This is Oniguruma option `ONIG_OPTION_SINGLELINE`.\n      singleline: false,\n      ...options.rules,\n    },\n  };\n  if (opts.target === 'auto') {\n    opts.target = envFlags.flagGroups ? 'ES2025' : (envFlags.unicodeSets ? 'ES2024' : 'ES2018');\n  }\n  return opts;\n}\n\nexport {\n  Accuracy,\n  EsVersion,\n  getOptions,\n  Target,\n};\n","import {cp, r} from './utils.js';\nimport {slug} from 'oniguruma-parser/parser';\n\n// `\\t\\n\\v\\f\\r\\x20`\nconst asciiSpaceChar = '[\\t-\\r ]';\n\nconst CharsWithoutIgnoreCaseExpansion = new Set([\n  cp(0x130), // İ\n  cp(0x131), // ı\n]);\n\n// Different than `PosixClassMap`'s `word`\nconst defaultWordChar = r`[\\p{L}\\p{M}\\p{N}\\p{Pc}]`;\n\nfunction getIgnoreCaseMatchChars(char) {\n  // Some chars should not match the chars they case swap to\n  if (CharsWithoutIgnoreCaseExpansion.has(char)) {\n    return [char];\n  }\n  const set = new Set();\n  const lower = char.toLowerCase();\n  // Everything else is based on `lower`\n  const upper = lower.toUpperCase();\n  const title = LowerToTitleCaseMap.get(lower);\n  const altLower = LowerToAlternativeLowerCaseMap.get(lower);\n  const altUpper = LowerToAlternativeUpperCaseMap.get(lower);\n  // Exclude ucase if multiple chars; count code point length. Excludes ucase versions of German\n  // es-zed 'ß', ligatures like 'ﬀ', and chars with no precomposed ucase like 'ŉ'. See\n  // <unicode.org/Public/UNIDATA/SpecialCasing.txt>\n  if ([...upper].length === 1) {\n    set.add(upper);\n  }\n  altUpper && set.add(altUpper);\n  title && set.add(title);\n  // Lcase of 'İ' is multiple chars, but it's excluded by `CharsWithoutIgnoreCaseExpansion`\n  set.add(lower);\n  altLower && set.add(altLower);\n  return [...set];\n}\n\n// The following set includes:\n// - All ES2024 general categories and their aliases (all are supported by Oniguruma). See\n//   <github.com/mathiasbynens/unicode-match-property-value-ecmascript/blob/main/data/mappings.js>\n// - All ES2024 binary properties and their aliases (all are supported by Oniguruma). See\n//   <tc39.es/ecma262/multipage/text-processing.html#table-binary-unicode-properties>\n// Unicode properties must be mapped to property names supported by JS, and must also apply JS's\n// stricter rules for casing, whitespace, hyphens, and underscores in Unicode property names. In\n// order to remain lightweight, this library assumes properties not in this list are Unicode script\n// names (which require a `Script=` or `sc=` prefix in JS). Unlike JS, Oniguruma doesn't support\n// script extensions, and it supports some properties that aren't supported in JS (including blocks\n// with an `In_` prefix). See also:\n// - Properties supported in Oniguruma: <github.com/kkos/oniguruma/blob/master/doc/UNICODE_PROPERTIES>\n// - Properties supported in JS by spec version: <github.com/eslint-community/regexpp/blob/main/src/unicode/properties.ts>\nconst JsUnicodePropertyMap = /* @__PURE__ */ new Map(\n`C Other\nCc Control cntrl\nCf Format\nCn Unassigned\nCo Private_Use\nCs Surrogate\nL Letter\nLC Cased_Letter\nLl Lowercase_Letter\nLm Modifier_Letter\nLo Other_Letter\nLt Titlecase_Letter\nLu Uppercase_Letter\nM Mark Combining_Mark\nMc Spacing_Mark\nMe Enclosing_Mark\nMn Nonspacing_Mark\nN Number\nNd Decimal_Number digit\nNl Letter_Number\nNo Other_Number\nP Punctuation punct\nPc Connector_Punctuation\nPd Dash_Punctuation\nPe Close_Punctuation\nPf Final_Punctuation\nPi Initial_Punctuation\nPo Other_Punctuation\nPs Open_Punctuation\nS Symbol\nSc Currency_Symbol\nSk Modifier_Symbol\nSm Math_Symbol\nSo Other_Symbol\nZ Separator\nZl Line_Separator\nZp Paragraph_Separator\nZs Space_Separator\nASCII\nASCII_Hex_Digit AHex\nAlphabetic Alpha\nAny\nAssigned\nBidi_Control Bidi_C\nBidi_Mirrored Bidi_M\nCase_Ignorable CI\nCased\nChanges_When_Casefolded CWCF\nChanges_When_Casemapped CWCM\nChanges_When_Lowercased CWL\nChanges_When_NFKC_Casefolded CWKCF\nChanges_When_Titlecased CWT\nChanges_When_Uppercased CWU\nDash\nDefault_Ignorable_Code_Point DI\nDeprecated Dep\nDiacritic Dia\nEmoji\nEmoji_Component EComp\nEmoji_Modifier EMod\nEmoji_Modifier_Base EBase\nEmoji_Presentation EPres\nExtended_Pictographic ExtPict\nExtender Ext\nGrapheme_Base Gr_Base\nGrapheme_Extend Gr_Ext\nHex_Digit Hex\nIDS_Binary_Operator IDSB\nIDS_Trinary_Operator IDST\nID_Continue IDC\nID_Start IDS\nIdeographic Ideo\nJoin_Control Join_C\nLogical_Order_Exception LOE\nLowercase Lower\nMath\nNoncharacter_Code_Point NChar\nPattern_Syntax Pat_Syn\nPattern_White_Space Pat_WS\nQuotation_Mark QMark\nRadical\nRegional_Indicator RI\nSentence_Terminal STerm\nSoft_Dotted SD\nTerminal_Punctuation Term\nUnified_Ideograph UIdeo\nUppercase Upper\nVariation_Selector VS\nWhite_Space space\nXID_Continue XIDC\nXID_Start XIDS`.\n  split(/\\s/).\n  map(p => [slug(p), p])\n);\n\nconst LowerToAlternativeLowerCaseMap = new Map([\n  ['s', cp(0x17F)], // s, ſ\n  [cp(0x17F), 's'], // ſ, s\n]);\n\nconst LowerToAlternativeUpperCaseMap = new Map([\n  [cp(0xDF), cp(0x1E9E)], // ß, ẞ\n  [cp(0x6B), cp(0x212A)], // k, K (Kelvin)\n  [cp(0xE5), cp(0x212B)], // å, Å (Angstrom)\n  [cp(0x3C9), cp(0x2126)], // ω, Ω (Ohm)\n]);\n\n// See <github.com/node-unicode/unicode-16.0.0/tree/main/General_Category/Titlecase_Letter>\nconst LowerToTitleCaseMap = new Map([\n  titleEntry(0x1C5),\n  titleEntry(0x1C8),\n  titleEntry(0x1CB),\n  titleEntry(0x1F2),\n  ...titleRange(0x1F88, 0x1F8F),\n  ...titleRange(0x1F98, 0x1F9F),\n  ...titleRange(0x1FA8, 0x1FAF),\n  titleEntry(0x1FBC),\n  titleEntry(0x1FCC),\n  titleEntry(0x1FFC),\n]);\n\n// Unlike Onig's Unicode properties via `\\p` and `\\P`, these names are case sensitive and don't\n// allow inserting whitespace and underscores. Definitions at\n// <github.com/kkos/oniguruma/blob/master/doc/RE> (see: POSIX bracket: Unicode Case)\n// Note: Handling in the transformer assumes all values here are a single, negateable node that's\n// not pre-negated at the top level. It also uses ASCII versions of `graph` and `print` for target\n// `ES2018` (which doesn't allow intersection) if `accuracy` isn't `strict`\nconst PosixClassMap = new Map([\n  ['alnum', r`[\\p{Alpha}\\p{Nd}]`],\n  ['alpha', r`\\p{Alpha}`],\n  ['ascii', r`\\p{ASCII}`],\n  ['blank', r`[\\p{Zs}\\t]`],\n  ['cntrl', r`\\p{Cc}`],\n  ['digit', r`\\p{Nd}`],\n  ['graph', r`[\\P{space}&&\\P{Cc}&&\\P{Cn}&&\\P{Cs}]`],\n  ['lower', r`\\p{Lower}`],\n  ['print', r`[[\\P{space}&&\\P{Cc}&&\\P{Cn}&&\\P{Cs}]\\p{Zs}]`],\n  ['punct', r`[\\p{P}\\p{S}]`], // Updated value from Onig 6.9.9; changed from Unicode `\\p{punct}`\n  ['space', r`\\p{space}`],\n  ['upper', r`\\p{Upper}`],\n  ['word', r`[\\p{Alpha}\\p{M}\\p{Nd}\\p{Pc}]`],\n  ['xdigit', r`\\p{AHex}`],\n]);\n\nfunction range(start, end) {\n  // const range = Array.from(Array(end + 1 - start), (_, i) => i + start);\n  // const range = Array(end + 1 - start).fill(start).map((x, i) => x + i);\n  const range = [];\n  for (let i = start; i <= end; i++) {\n    range.push(i);\n  }\n  return range;\n}\n\nfunction titleEntry(codePoint) {\n  const char = cp(codePoint);\n  return [char.toLowerCase(), char];\n}\n\nfunction titleRange(start, end) {\n  return range(start, end).map(codePoint => titleEntry(codePoint));\n}\n\nconst UnicodePropertiesWithSpecificCase = new Set([\n  'Lower', 'Lowercase',\n  'Upper', 'Uppercase',\n  'Ll', 'Lowercase_Letter',\n  'Lt', 'Titlecase_Letter',\n  'Lu', 'Uppercase_Letter',\n  // The `Changes_When_*` properties (and their aliases) could be included, but they're very rare.\n  // Some other properties include a handful of chars with specific cases only, but these chars are\n  // generally extreme edge cases and using such properties case insensitively generally produces\n  // undesired behavior anyway\n]);\n\nexport {\n  asciiSpaceChar,\n  defaultWordChar,\n  getIgnoreCaseMatchChars,\n  JsUnicodePropertyMap,\n  PosixClassMap,\n  UnicodePropertiesWithSpecificCase,\n};\n","import {Accuracy, Target} from './options.js';\nimport {asciiSpaceChar, defaultWordChar, JsUnicodePropertyMap, PosixClassMap} from './unicode.js';\nimport {cp, getNewCurrentFlags, getOrInsert, isMinTarget, r} from './utils.js';\nimport {createAlternative, createAssertion, createBackreference, createCapturingGroup, createCharacter, createCharacterClass, createCharacterSet, createGroup, createLookaroundAssertion, createQuantifier, createSubroutine, createUnicodeProperty, hasOnlyChild, parse, slug} from 'oniguruma-parser/parser';\nimport {traverse} from 'oniguruma-parser/traverser';\n/**\n@import {CapturingGroupNode, OnigurumaAst, Node} from 'oniguruma-parser/parser';\n@import {Visitor} from 'oniguruma-parser/traverser';\n*/\n\n/**\n@typedef {\n  OnigurumaAst & {\n    options: {\n      disable: {[key: string]: boolean};\n      force: {[key: string]: boolean};\n    };\n    _originMap: Map<CapturingGroupNode, CapturingGroupNode>;\n    _strategy: string | null;\n  }\n} RegexPlusAst\n*/\n/**\nTransforms an Oniguruma AST in-place to a [Regex+](https://github.com/slevithan/regex) AST.\nAssumes target ES2025, expecting the generator to down-convert to the desired JS target version.\n\nRegex+'s syntax and behavior is a strict superset of native JavaScript, so the AST is very close\nto representing native ES2025 `RegExp` but with some added features (atomic groups, possessive\nquantifiers, recursion). The AST doesn't use some of Regex+'s extended features like flag x or\nsubroutines because they follow PCRE behavior and work somewhat differently than in Oniguruma. The\nAST represents what's needed to precisely reproduce Oniguruma behavior using Regex+.\n@param {OnigurumaAst} ast\n@param {{\n  accuracy?: keyof Accuracy;\n  asciiWordBoundaries?: boolean;\n  avoidSubclass?: boolean;\n  bestEffortTarget?: keyof Target;\n}} [options]\n@returns {RegexPlusAst}\n*/\nfunction transform(ast, options) {\n  const opts = {\n    // A couple edge cases exist where options `accuracy` and `bestEffortTarget` are used:\n    // - `CharacterSet` kind `text_segment` (`\\X`): An exact representation would require heavy\n    //   Unicode data; a best-effort approximation requires knowing the target.\n    // - `CharacterSet` kind `posix` with values `graph` and `print`: Their complex Unicode\n    //   representations would be hard to change to ASCII versions after the fact in the generator\n    //   based on `target`/`accuracy`, so produce the appropriate structure here.\n    accuracy: 'default',\n    asciiWordBoundaries: false,\n    avoidSubclass: false,\n    bestEffortTarget: 'ES2025',\n    ...options,\n  };\n  // Add `parent` properties to all nodes to help during traversal; also expected by the generator\n  addParentProperties(ast);\n  const firstPassState = {\n    accuracy: opts.accuracy,\n    asciiWordBoundaries: opts.asciiWordBoundaries,\n    avoidSubclass: opts.avoidSubclass,\n    flagDirectivesByAlt: new Map(),\n    jsGroupNameMap: new Map(),\n    minTargetEs2024: isMinTarget(opts.bestEffortTarget, 'ES2024'),\n    passedLookbehind: false,\n    strategy: null,\n    // Subroutines can appear before the groups they ref, so collect reffed nodes for a second pass \n    subroutineRefMap: new Map(),\n    supportedGNodes: new Set(),\n    digitIsAscii: ast.flags.digitIsAscii,\n    spaceIsAscii: ast.flags.spaceIsAscii,\n    wordIsAscii: ast.flags.wordIsAscii,\n  };\n  traverse(ast, FirstPassVisitor, firstPassState);\n  // Global flags modified by the first pass\n  const globalFlags = {\n    dotAll: ast.flags.dotAll,\n    ignoreCase: ast.flags.ignoreCase,\n  };\n  // The interplay of subroutines (with Onig's unique rules/behavior for them; see comments in the\n  // parser for details) with backref multiplexing (a unique Onig feature), flag modifiers, and\n  // duplicate group names (which might be indirectly referenced by subroutines even though\n  // subroutines can't directly reference duplicate names) is extremely complicated to emulate in\n  // JS in a way that handles all edge cases, so we need multiple passes to do it\n  const secondPassState = {\n    currentFlags: globalFlags,\n    prevFlags: null,\n    globalFlags,\n    groupOriginByCopy: new Map(),\n    groupsByName: new Map(),\n    multiplexCapturesToLeftByRef: new Map(),\n    openRefs: new Map(),\n    reffedNodesByReferencer: new Map(),\n    subroutineRefMap: firstPassState.subroutineRefMap,\n  };\n  traverse(ast, SecondPassVisitor, secondPassState);\n  const thirdPassState = {\n    groupsByName: secondPassState.groupsByName,\n    highestOrphanBackref: 0,\n    numCapturesToLeft: 0,\n    reffedNodesByReferencer: secondPassState.reffedNodesByReferencer,\n  };\n  traverse(ast, ThirdPassVisitor, thirdPassState);\n  ast._originMap = secondPassState.groupOriginByCopy;\n  ast._strategy = firstPassState.strategy;\n  return ast;\n}\n\nconst /** @type {Visitor} */ FirstPassVisitor = {\n  AbsenceFunction({node, parent, replaceWith}) {\n    const {body, kind} = node;\n    if (kind === 'repeater') {\n      // Convert `(?~…)` to `(?:(?:(?!…)\\p{Any})*)`\n      const innerGroup = createGroup();\n      innerGroup.body[0].body.push(\n        // Insert own alts as `body`\n        createLookaroundAssertion({negate: true, body}),\n        createUnicodeProperty('Any')\n      );\n      const outerGroup = createGroup();\n      outerGroup.body[0].body.push(\n        createQuantifier('greedy', 0, Infinity, innerGroup)\n      );\n      replaceWith(setParentDeep(outerGroup, parent), {traverse: true});\n    } else {\n      throw new Error(`Unsupported absence function \"(?~|\"`);\n    }\n  },\n\n  Alternative: {\n    enter({node, parent, key}, {flagDirectivesByAlt}) {\n      // Look for own-level flag directives when entering an alternative because after traversing\n      // the directive itself, any subsequent flag directives will no longer be at the same level\n      const flagDirectives = node.body.filter(el => el.kind === 'flags');\n      for (let i = key + 1; i < parent.body.length; i++) {\n        const forwardSiblingAlt = parent.body[i];\n        getOrInsert(flagDirectivesByAlt, forwardSiblingAlt, []).push(...flagDirectives);\n      }\n    },\n    exit({node}, {flagDirectivesByAlt}) {\n      // Wait until exiting to wrap an alternative's nodes with flag groups that extend flag\n      // directives from prior sibling alternatives, because doing this at the end allows inner\n      // nodes to accurately check their level in the tree\n      if (flagDirectivesByAlt.get(node)?.length) {\n        const flags = getCombinedFlagModsFromFlagNodes(flagDirectivesByAlt.get(node));\n        if (flags) {\n          const flagGroup = createGroup({flags});\n          flagGroup.body[0].body = node.body;\n          node.body = [setParentDeep(flagGroup, node)];\n        }\n      }\n    },\n  },\n\n  Assertion({node, parent, key, container, root, remove, replaceWith}, state) {\n    const {kind, negate} = node;\n    const {asciiWordBoundaries, avoidSubclass, supportedGNodes, wordIsAscii} = state;\n    if (kind === 'text_segment_boundary') {\n      // Supported by the parser but not yet for transpilation\n      throw new Error(`Unsupported text segment boundary \"\\\\${negate ? 'Y' : 'y'}\"`);\n    } else if (kind === 'line_end') {\n      replaceWith(setParentDeep(createLookaroundAssertion({body: [\n        createAlternative({body: [createAssertion('string_end')]}),\n        createAlternative({body: [createCharacter(10)]}), // `\\n`\n      ]}), parent));\n    } else if (kind === 'line_start') {\n      // Onig's `^` doesn't match after a string-terminating line feed\n      replaceWith(setParentDeep(parseFragment(r`(?<=\\A|\\n(?!\\z))`, {skipLookbehindValidation: true}), parent));\n    } else if (kind === 'search_start') {\n      if (supportedGNodes.has(node)) {\n        root.flags.sticky = true;\n        remove();\n      } else {\n        const prev = container[key - 1]; // parent.body[key - 1]\n        // Not all ways of blocking the `\\G` from matching are covered here (ex: a node prior to\n        // the `prev` node could block), but blocked `\\G` is an edge case and it's okay if some\n        // blocked cases result in the standard error for being unsupported without a subclass\n        if (prev && isAlwaysNonZeroLength(prev)) {\n          replaceWith(setParentDeep(createLookaroundAssertion({negate: true}), parent));\n        } else if (avoidSubclass) {\n          throw new Error(r`Uses \"\\G\" in a way that requires a subclass`);\n        } else {\n          replaceWith(setParent(createAssertion('string_start'), parent));\n          state.strategy = 'clip_search';\n        }\n      }\n    } else if (kind === 'string_end' || kind === 'string_start') {\n      // Don't need transformation since JS flag m isn't used\n    } else if (kind === 'string_end_newline') {\n      replaceWith(setParentDeep(parseFragment(r`(?=\\n?\\z)`), parent));\n    } else if (kind === 'word_boundary') {\n      if (!wordIsAscii && !asciiWordBoundaries) {\n        const b = `(?:(?<=${defaultWordChar})(?!${defaultWordChar})|(?<!${defaultWordChar})(?=${defaultWordChar}))`;\n        const B = `(?:(?<=${defaultWordChar})(?=${defaultWordChar})|(?<!${defaultWordChar})(?!${defaultWordChar}))`;\n        replaceWith(setParentDeep(parseFragment(negate ? B : b), parent));\n      }\n    } else {\n      throw new Error(`Unexpected assertion kind \"${kind}\"`);\n    }\n  },\n\n  Backreference({node}, {jsGroupNameMap}) {\n    let {ref} = node;\n    if (typeof ref === 'string' && !isValidJsGroupName(ref)) {\n      ref = getAndStoreJsGroupName(ref, jsGroupNameMap);\n      node.ref = ref;\n    }\n  },\n\n  CapturingGroup({node}, {jsGroupNameMap, subroutineRefMap}) {\n    let {name} = node;\n    if (name && !isValidJsGroupName(name)) {\n      name = getAndStoreJsGroupName(name, jsGroupNameMap);\n      node.name = name;\n    }\n    subroutineRefMap.set(node.number, node);\n    if (name) {\n      subroutineRefMap.set(name, node);\n    }\n  },\n\n  CharacterClassRange({node, parent, replaceWith}) {\n    if (parent.kind === 'intersection') {\n      // JS doesn't allow intersection with ranges without a wrapper class\n      const cc = createCharacterClass({body: [node]});\n      replaceWith(setParentDeep(cc, parent), {traverse: true});\n    }\n  },\n\n  CharacterSet({node, parent, replaceWith}, {accuracy, minTargetEs2024, digitIsAscii, spaceIsAscii, wordIsAscii}) {\n    const {kind, negate, value} = node;\n    // Flag D with `\\d`, `\\p{Digit}`, `[[:digit:]]`\n    if (digitIsAscii && (kind === 'digit' || value === 'digit')) {\n      replaceWith(setParent(createCharacterSet('digit', {negate}), parent));\n      return;\n    }\n    // Flag S with `\\s`, `\\p{Space}`, `[[:space:]]`\n    if (spaceIsAscii && (kind === 'space' || value === 'space')) {\n      replaceWith(setParentDeep(setNegate(parseFragment(asciiSpaceChar), negate), parent));\n      return;\n    }\n    // Flag W with `\\w`, `\\p{Word}`, `[[:word:]]`\n    if (wordIsAscii && (kind === 'word' || value === 'word')) {\n      replaceWith(setParent(createCharacterSet('word', {negate}), parent));\n      return;\n    }\n    if (kind === 'any') {\n      replaceWith(setParent(createUnicodeProperty('Any'), parent));\n    } else if (kind === 'digit') {\n      replaceWith(setParent(createUnicodeProperty('Nd', {negate}), parent));\n    } else if (kind === 'dot') {\n      // No-op; doesn't need transformation\n    } else if (kind === 'text_segment') {\n      if (accuracy === 'strict') {\n        throw new Error(r`Use of \"\\X\" requires non-strict accuracy`);\n      }\n      // Emoji pattern based on <github.com/slevithan/emoji-regex-xs> but adapted for our use case\n      // Note: Not using raw strings to work around Bun ≤ 1.1.34 issue <github.com/oven-sh/bun/issues/7540>\n      const eBase = '\\\\p{Emoji}(?:\\\\p{EMod}|\\\\uFE0F\\\\u20E3?|[\\\\x{E0020}-\\\\x{E007E}]+\\\\x{E007F})?';\n      const emoji = r`\\p{RI}{2}|${eBase}(?:\\u200D${eBase})*`;\n      replaceWith(setParentDeep(parseFragment(\n        // Close approximation of an extended grapheme cluster; see <unicode.org/reports/tr29/>\n        r`(?>\\r\\n|${minTargetEs2024 ? r`\\p{RGI_Emoji}` : emoji}|\\P{M}\\p{M}*)`,\n        // Allow JS property `RGI_Emoji` through\n        {skipPropertyNameValidation: true}\n      ), parent));\n    } else if (kind === 'hex') {\n      replaceWith(setParent(createUnicodeProperty('AHex', {negate}), parent));\n    } else if (kind === 'newline') {\n      replaceWith(setParentDeep(parseFragment(negate ? '[^\\n]' : '(?>\\r\\n?|[\\n\\v\\f\\x85\\u2028\\u2029])'), parent));\n    } else if (kind === 'posix') {\n      if (!minTargetEs2024 && (value === 'graph' || value === 'print')) {\n        if (accuracy === 'strict') {\n          throw new Error(`POSIX class \"${value}\" requires min target ES2024 or non-strict accuracy`);\n        }\n        let ascii = {\n          graph: '!-~',\n          print: ' -~',\n        }[value];\n        if (negate) {\n          // POSIX classes are always nested in a char class; manually invert the range rather than\n          // using `[^…]` so it can be unwrapped since ES2018 doesn't support nested classes\n          ascii = `\\0-${cp(ascii.codePointAt(0) - 1)}${cp(ascii.codePointAt(2) + 1)}-\\u{10FFFF}`;\n        }\n        replaceWith(setParentDeep(parseFragment(`[${ascii}]`), parent));\n      } else {\n        replaceWith(setParentDeep(setNegate(parseFragment(PosixClassMap.get(value)), negate), parent));\n      }\n    } else if (kind === 'property') {\n      if (!JsUnicodePropertyMap.has(slug(value))) {\n        // Assume it's a script; no error checking is the price for avoiding heavyweight Unicode\n        // data for all script names\n        node.key = 'sc';\n      }\n    } else if (kind === 'space') {\n      // Can't use JS's Unicode `\\s` since unlike Onig it includes `\\uFEFF` and excludes `\\x85`\n      replaceWith(setParent(createUnicodeProperty('space', {negate}), parent));\n    } else if (kind === 'word') {\n      replaceWith(setParentDeep(setNegate(parseFragment(defaultWordChar), negate), parent));\n    } else {\n      throw new Error(`Unexpected character set kind \"${kind}\"`);\n    }\n  },\n\n  Directive({node, parent, root, remove, replaceWith, removeAllPrevSiblings, removeAllNextSiblings}) {\n    const {kind, flags} = node;\n    if (kind === 'flags') {\n      if (!flags.enable && !flags.disable) {\n        // Flag directive without flags; ex: `(?-)`, `(?--)`\n        remove();\n      } else {\n        const flagGroup = createGroup({flags});\n        flagGroup.body[0].body = removeAllNextSiblings();\n        replaceWith(setParentDeep(flagGroup, parent), {traverse: true});\n      }\n    } else if (kind === 'keep') {\n      const firstAlt = root.body[0];\n      // Supporting a full-pattern wrapper around `\\K` enables use with flag modifiers\n      const hasWrapperGroup =\n        root.body.length === 1 &&\n        // Not emulatable if within a `CapturingGroup`\n        hasOnlyChild(firstAlt, {type: 'Group'}) &&\n        firstAlt.body[0].body.length === 1;\n      const topLevel = hasWrapperGroup ? firstAlt.body[0] : root;\n      if (parent.parent !== topLevel || topLevel.body.length > 1) {\n        throw new Error(r`Uses \"\\K\" in a way that's unsupported`);\n      }\n      const lookbehind = createLookaroundAssertion({behind: true});\n      lookbehind.body[0].body = removeAllPrevSiblings();\n      replaceWith(setParentDeep(lookbehind, parent));\n    } else {\n      throw new Error(`Unexpected directive kind \"${kind}\"`);\n    }\n  },\n\n  Flags({node, parent}) {\n    // Throw for flags supported by the parser but not yet for transpilation\n    if (node.posixIsAscii) {\n      throw new Error('Unsupported flag \"P\"');\n    }\n    if (node.textSegmentMode === 'word') {\n      throw new Error('Unsupported flag \"y{w}\"');\n    }\n    // Remove Onig flags that aren't available in JS\n    [ 'digitIsAscii', // Flag D\n      'extended', // Flag x\n      'posixIsAscii', // Flag P\n      'spaceIsAscii', // Flag S\n      'wordIsAscii', // Flag W\n      'textSegmentMode', // Flag y{g} or y{w}\n    ].forEach(f => delete node[f]);\n    Object.assign(node, {\n      // JS flag g; no Onig equiv\n      global: false,\n      // JS flag d; no Onig equiv\n      hasIndices: false,\n      // JS flag m; no Onig equiv but its behavior is always on in Onig. Onig's only line break\n      // char is line feed, unlike JS, so this flag isn't used since it would produce inaccurate\n      // results (also allows `^` and `$` to be used in the generator for string start and end)\n      multiline: false,\n      // JS flag y; no Onig equiv, but used for `\\G` emulation\n      sticky: node.sticky ?? false,\n      // Note: Regex+ doesn't allow explicitly adding flags it handles implicitly, so leave out\n      // properties `unicode` (JS flag u) and `unicodeSets` (JS flag v). Keep the existing values\n      // for `ignoreCase` (flag i) and `dotAll` (JS flag s, but Onig flag m)\n    });\n    // Options accepted by Regex+; see <github.com/slevithan/regex#-options>\n    parent.options = {\n      disable: {\n        // Onig uses different rules for flag x than Regex+, so disable the implicit flag\n        x: true,\n        // Onig has no flag to control \"named capture only\" mode but contextually applies its\n        // behavior when named capturing is used, so disable Regex+'s implicit flag for it\n        n: true,\n      },\n      force: {\n        // Always add flag v because we're generating an AST that relies on it (it enables JS\n        // support for Onig features nested classes, intersection, Unicode properties, etc.).\n        // However, the generator might disable flag v based on its `target` option\n        v: true,\n      },\n    };\n  },\n\n  Group({node}) {\n    if (!node.flags) {\n      return;\n    }\n    const {enable, disable} = node.flags;\n    // Onig's flag x (`extended`) isn't available in JS\n    enable?.extended && delete enable.extended;\n    disable?.extended && delete disable.extended;\n    // JS doesn't support flag groups that enable and disable the same flag; ex: `(?i-i:)`\n    enable?.dotAll && disable?.dotAll && delete enable.dotAll;\n    enable?.ignoreCase && disable?.ignoreCase && delete enable.ignoreCase;\n    // Cleanup\n    enable && !Object.keys(enable).length && delete node.flags.enable;\n    disable && !Object.keys(disable).length && delete node.flags.disable;\n    !node.flags.enable && !node.flags.disable && delete node.flags;\n  },\n\n  LookaroundAssertion({node}, state) {\n    const {kind} = node;\n    if (kind === 'lookbehind') {\n      state.passedLookbehind = true;\n    }\n  },\n\n  NamedCallout({node, parent, replaceWith}) {\n    const {kind} = node;\n    if (kind === 'fail') {\n      replaceWith(setParentDeep(createLookaroundAssertion({negate: true}), parent));\n    } else {\n      throw new Error(`Unsupported named callout \"(*${kind.toUpperCase()}\"`);\n    }\n  },\n\n  Quantifier({node}) {\n    if (node.body.type === 'Quantifier') {\n      // Change e.g. `a**` to `(?:a*)*`\n      const group = createGroup();\n      group.body[0].body.push(node.body);\n      node.body = setParentDeep(group, node);\n    }\n  },\n\n  Regex: {\n    enter({node}, {supportedGNodes}) {\n      // For `\\G` to be accurately emulatable using JS flag y, it must be at (and only at) the start\n      // of every top-level alternative (with complex rules for what determines being at the start).\n      // Additional `\\G` error checking in `Assertion` visitor\n      const leadingGs = [];\n      let hasAltWithLeadG = false;\n      let hasAltWithoutLeadG = false;\n      for (const alt of node.body) {\n        if (alt.body.length === 1 && alt.body[0].kind === 'search_start') {\n          // Remove the `\\G` (leaving behind an empty alternative, and without adding JS flag y)\n          // since a top-level alternative that includes only `\\G` always matches at the start of the\n          // match attempt. Note that this is based on Oniguruma's rules, and is different than other\n          // regex flavors where `\\G` matches at the end of the previous match (a subtle distinction\n          // that's relevant after zero-length matches)\n          alt.body.pop();\n        } else {\n          const leadingG = getLeadingG(alt.body);\n          if (leadingG) {\n            hasAltWithLeadG = true;\n            Array.isArray(leadingG) ?\n              leadingGs.push(...leadingG) :\n              leadingGs.push(leadingG);\n          } else {\n            hasAltWithoutLeadG = true;\n          }\n        }\n      }\n      if (hasAltWithLeadG && !hasAltWithoutLeadG) {\n        // Supported `\\G` nodes will be removed (and add flag y) when traversed\n        leadingGs.forEach(g => supportedGNodes.add(g));\n      }\n    },\n    exit(_, {accuracy, passedLookbehind, strategy}) {\n      if (accuracy === 'strict' && passedLookbehind && strategy) {\n        throw new Error(r`Uses \"\\G\" in a way that requires non-strict accuracy`);\n      }\n    },\n  },\n\n  Subroutine({node}, {jsGroupNameMap}) {\n    let {ref} = node;\n    if (typeof ref === 'string' && !isValidJsGroupName(ref)) {\n      ref = getAndStoreJsGroupName(ref, jsGroupNameMap);\n      node.ref = ref;\n    }\n  },\n};\n\nconst /** @type {Visitor} */ SecondPassVisitor = {\n  Backreference({node}, {multiplexCapturesToLeftByRef, reffedNodesByReferencer}) {\n    const {orphan, ref} = node;\n    if (!orphan) {\n      // Copy the current state for later multiplexing expansion. That's done in a subsequent pass\n      // because backref numbers need to be recalculated after subroutine expansion\n      reffedNodesByReferencer.set(node, [...multiplexCapturesToLeftByRef.get(ref).map(({node}) => node)]);\n    }\n  },\n\n  CapturingGroup: {\n    enter(\n      { node,\n        parent,\n        replaceWith,\n        skip,\n      },\n      { groupOriginByCopy,\n        groupsByName,\n        multiplexCapturesToLeftByRef,\n        openRefs,\n        reffedNodesByReferencer,\n      }\n    ) {\n      // Has value if we're within a subroutine expansion\n      const origin = groupOriginByCopy.get(node);\n\n      // ## Handle recursion; runs after subroutine expansion\n      if (origin && openRefs.has(node.number)) {\n        // Recursive subroutines don't affect any following backrefs to their `ref` (unlike other\n        // subroutines), so don't wrap with a capture. The reffed group might have its name removed\n        // due to later subroutine expansion\n        const recursion = setParent(createRecursion(node.number), parent);\n        reffedNodesByReferencer.set(recursion, openRefs.get(node.number));\n        replaceWith(recursion);\n        return;\n      }\n      openRefs.set(node.number, node);\n\n      // ## Track data for backref multiplexing\n      multiplexCapturesToLeftByRef.set(node.number, []);\n      if (node.name) {\n        getOrInsert(multiplexCapturesToLeftByRef, node.name, []);\n      }\n      const multiplexNodes = multiplexCapturesToLeftByRef.get(node.name ?? node.number);\n      for (let i = 0; i < multiplexNodes.length; i++) {\n        // Captures added via subroutine expansion (maybe indirectly because they were descendant\n        // captures of the reffed group or in a nested subroutine expansion) form a set with their\n        // origin group and any other copies of it added via subroutines. Only the most recently\n        // matched within this set is added to backref multiplexing. So search the list of already-\n        // tracked multiplexed nodes for this group name or number to see if there's a node being\n        // replaced by this capture\n        const multiplex = multiplexNodes[i];\n        if (\n          // This group is from subroutine expansion, and there's a multiplex value from either the\n          // origin node or a prior subroutine expansion group with the same origin\n          (origin === multiplex.node || (origin && origin === multiplex.origin)) ||\n          // This group is not from subroutine expansion, and it comes after a subroutine expansion\n          // group that refers to this group\n          node === multiplex.origin\n        ) {\n          multiplexNodes.splice(i, 1);\n          break;\n        }\n      }\n      multiplexCapturesToLeftByRef.get(node.number).push({node, origin});\n      if (node.name) {\n        multiplexCapturesToLeftByRef.get(node.name).push({node, origin});\n      }\n\n      // ## Track data for duplicate names\n      // Pre-ES2025 doesn't allow duplicate names, but ES2025 allows duplicate names that are\n      // unique per mutually exclusive alternation path. However, Oniguruma's handling for named\n      // subpatterns on match results means we can't use this ES2025 feature even when in an ES2025\n      // env. So, if using a duplicate name, remove the name from all but the first instance that\n      // wasn't created by subroutine expansion\n      if (node.name) {\n        const groupsWithSameName = getOrInsert(groupsByName, node.name, new Map());\n        let hasDuplicateNameToRemove = false;\n        if (origin) {\n          // Subroutines and their child captures shouldn't hold duplicate names in the final state\n          hasDuplicateNameToRemove = true;\n        } else {\n          for (const groupInfo of groupsWithSameName.values()) {\n            if (!groupInfo.hasDuplicateNameToRemove) {\n              // Will change to an unnamed capture in a later pass\n              hasDuplicateNameToRemove = true;\n              break;\n            }\n          }\n        }\n        groupsByName.get(node.name).set(node, {node, hasDuplicateNameToRemove});\n      }\n    },\n    exit({node}, {openRefs}) {\n      // During `enter`, ownership of `openRefs` isn't claimed when recursive clones are replaced,\n      // so only the node that inserted the current entry should clear it on exit\n      if (openRefs.get(node.number) === node) {\n        openRefs.delete(node.number);\n      }\n    },\n  },\n\n  Group: {\n    enter({node}, state) {\n      // Flag directives have already been converted to flag groups by the previous pass\n      state.prevFlags = state.currentFlags;\n      if (node.flags) {\n        state.currentFlags = getNewCurrentFlags(state.currentFlags, node.flags);\n      }\n    },\n    exit(_, state) {\n      state.currentFlags = state.prevFlags;\n    },\n  },\n\n  Subroutine({node, parent, replaceWith}, state) {\n    const {isRecursive, ref} = node;\n\n    // Subroutine nodes with `isRecursive` are created during the current traversal; they're only\n    // traversed here if a recursive subroutine created during traversal is then copied by a\n    // subroutine expansion, e.g. with `(?<a>\\g<a>)\\g<a>`\n    if (isRecursive) {\n      // Immediate parent is an alternative or quantifier; can skip\n      let reffed = parent;\n      while ((reffed = reffed.parent)) {\n        if (reffed.type === 'CapturingGroup' && (reffed.name === ref || reffed.number === ref)) {\n          break;\n        }\n      }\n      // Track the referenced node because `ref`s are rewritten in a subsequent pass; capturing\n      // group names and numbers might change due to subroutine expansion and duplicate group names\n      state.reffedNodesByReferencer.set(node, reffed);\n      return;\n    }\n\n    const reffedGroupNode = state.subroutineRefMap.get(ref);\n    // Other forms of recursion are handled by the `CapturingGroup` visitor\n    const isGlobalRecursion = ref === 0;\n    const expandedSubroutine = isGlobalRecursion ?\n      createRecursion(0) :\n      // The reffed group might itself contain subroutines, which are expanded during sub-traversal\n      cloneCapturingGroup(reffedGroupNode, state.groupOriginByCopy, null);\n    let replacement = expandedSubroutine;\n    if (!isGlobalRecursion) {\n      // Subroutines take their flags from the reffed group, not the flags surrounding themselves\n      const reffedGroupFlagMods = getCombinedFlagModsFromFlagNodes(getAllParents(\n        reffedGroupNode,\n        p => p.type === 'Group' && !!p.flags\n      ));\n      const reffedGroupFlags = reffedGroupFlagMods ?\n        getNewCurrentFlags(state.globalFlags, reffedGroupFlagMods) :\n        state.globalFlags;\n      if (!areFlagsEqual(reffedGroupFlags, state.currentFlags)) {\n        replacement = createGroup({\n          flags: getFlagModsFromFlags(reffedGroupFlags),\n        });\n        replacement.body[0].body.push(expandedSubroutine);\n      }\n    }\n    replaceWith(setParentDeep(replacement, parent), {traverse: !isGlobalRecursion});\n  },\n};\n\nconst /** @type {Visitor} */ ThirdPassVisitor = {\n  Backreference({node, parent, replaceWith}, state) {\n    if (node.orphan) {\n      state.highestOrphanBackref = Math.max(state.highestOrphanBackref, node.ref);\n      // Don't renumber; used with `allowOrphanBackrefs`\n      return;\n    }\n    const reffedNodes = state.reffedNodesByReferencer.get(node);\n    const participants = reffedNodes.filter(reffed => canParticipateWithNode(reffed, node));\n    // For the backref's `ref`, use `number` rather than `name` because group names might have been\n    // removed if they're duplicates within their alternation path, or they might be removed later\n    // by the generator (depending on target) if they're duplicates within the overall pattern.\n    // Backrefs must come after groups they ref, so reffed node `number`s are already recalculated\n    if (!participants.length) {\n      // If no participating capture, convert backref to to `(?!)`; backrefs to nonparticipating\n      // groups can't match in Onig but match the empty string in JS\n      replaceWith(setParentDeep(createLookaroundAssertion({negate: true}), parent));\n    } else if (participants.length > 1) {\n      // Multiplex for backrefs to duplicate capture names; try them in reverse order\n      const group = createGroup({\n        atomic: true,\n        body: participants.reverse().map(reffed => createAlternative({\n          body: [createBackreference(reffed.number)],\n        })),\n      });\n      replaceWith(setParentDeep(group, parent));\n    } else {\n      node.ref = participants[0].number;\n    }\n  },\n\n  CapturingGroup({node}, state) {\n    // Recalculate the number since the current value might be wrong due to subroutine expansion\n    node.number = ++state.numCapturesToLeft;\n    if (node.name) {\n      // Removing duplicate names here rather than in an earlier pass avoids extra complexity when\n      // handling subroutine expansion and backref multiplexing\n      if (state.groupsByName.get(node.name).get(node).hasDuplicateNameToRemove) {\n        delete node.name;\n      }\n    }\n  },\n\n  Regex: {\n    exit({node}, state) {\n      // HACK: Add unnamed captures to the end of the regex if needed to allow orphaned backrefs\n      // to be valid in JS with flag u/v. This is needed to support TextMate grammars, which\n      // replace numbered backrefs in their `end` pattern with values matched by captures in their\n      // `begin` pattern! See <github.com/microsoft/vscode-textmate/blob/7e0ea282f4f25fef12a6c84fa4fa7266f67b58dc/src/rule.ts#L661-L663>\n      // An `end` pattern, prior to this substitution, might have backrefs to a group that doesn't\n      // exist within `end`. This presents a dilemma since both Oniguruma and JS (with flag u/v)\n      // error for backrefs to undefined captures. So adding captures to the end is a solution that\n      // doesn't change what the regex matches, and lets invalid numbered backrefs through. Note:\n      // Orphan backrefs are only allowed if `allowOrphanBackrefs` is enabled\n      const numCapsNeeded = Math.max(state.highestOrphanBackref - state.numCapturesToLeft, 0);\n      for (let i = 0; i < numCapsNeeded; i++) {\n        const emptyCapture = createCapturingGroup();\n        node.body.at(-1).body.push(emptyCapture);\n      }\n    },\n  },\n\n  Subroutine({node}, state) {\n    if (!node.isRecursive || node.ref === 0) {\n      return;\n    }\n    // For the recursion's `ref`, use `number` rather than `name` because group names might have\n    // been removed if they're duplicates within their alternation path, or they might be removed\n    // later by the generator (depending on target) if they're duplicates within the overall\n    // pattern. Since recursion appears within the group it refs, the reffed node's `number` has\n    // already been recalculated\n    node.ref = state.reffedNodesByReferencer.get(node).number;\n  },\n};\n\n// ---------------\n// --- Helpers ---\n// ---------------\n\nfunction addParentProperties(root) {\n  traverse(root, {\n    '*'({node, parent}) {\n      node.parent = parent;\n    },\n  });\n}\n\nfunction areFlagsEqual(a, b) {\n  return a.dotAll === b.dotAll && a.ignoreCase === b.ignoreCase;\n}\n\nfunction canParticipateWithNode(capture, node) {\n  // Walks to the left (prev siblings), down (sibling descendants), up (parent), then back down\n  // (parent's prev sibling descendants) the tree in a loop\n  let rightmostPoint = node;\n  do {\n    if (rightmostPoint.type === 'Regex') {\n      // End of the line; capture is not in node's alternation path\n      return false;\n    }\n    if (rightmostPoint.type === 'Alternative') {\n      // Skip past alts to their parent because we don't want to look at the kids of preceding alts\n      continue;\n    }\n    if (rightmostPoint === capture) {\n      // Capture is ancestor of node\n      return false;\n    }\n    const kidsOfParent = getKids(rightmostPoint.parent);\n    for (const kid of kidsOfParent) {\n      if (kid === rightmostPoint) {\n        // Reached rightmost node in sibling list that we want to consider; break to parent loop\n        break;\n      }\n      if (kid === capture || isAncestorOf(kid, capture)) {\n        return true;\n      }\n    }\n  } while ((rightmostPoint = rightmostPoint.parent));\n  throw new Error('Unexpected path');\n}\n\n// Creates a deep copy of the provided node, with special handling:\n// - Make `parent` props point to their parent in the copy\n// - Update the provided `originMap` for each cloned capturing group (outer and nested)\nfunction cloneCapturingGroup(obj, originMap, up, up2) {\n  const store = Array.isArray(obj) ? [] : {};\n  for (const [key, value] of Object.entries(obj)) {\n    if (key === 'parent') {\n      // If the last cloned item was a container array (for holding kids), use the object above it\n      store.parent = Array.isArray(up) ? up2 : up;\n    } else if (value && typeof value === 'object') {\n      store[key] = cloneCapturingGroup(value, originMap, store, up);\n    } else {\n      if (key === 'type' && value === 'CapturingGroup') {\n        // Key is the copied node, value is the origin node\n        originMap.set(store, originMap.get(obj) ?? obj);\n      }\n      store[key] = value;\n    }\n  }\n  return store;\n}\n\nfunction createRecursion(ref) {\n  const node = createSubroutine(ref);\n  // In the future, the parser will set a `recursive` property on subroutines:\n  // <github.com/slevithan/oniguruma-parser/issues/3>. When that's available, this function won't\n  // be needed and the related logic in this transformer should change (simplify) to use it\n  node.isRecursive = true;\n  return node;\n}\n\nfunction getAllParents(node, filterFn) {\n  const results = [];\n  while ((node = node.parent)) {\n    if (!filterFn || filterFn(node)) {\n      results.push(node);\n    }\n  }\n  return results;\n}\n\n// See also `isValidJsGroupName`\nfunction getAndStoreJsGroupName(name, map) {\n  if (map.has(name)) {\n    return map.get(name);\n  }\n  // Onig group names can't start with `$`, but JS names can\n  const jsName = `$${map.size}_${name.replace(/^[^$_\\p{IDS}]|[^$\\u200C\\u200D\\p{IDC}]/ug, '_')}`;\n  map.set(name, jsName);\n  return jsName;\n}\n\nfunction getCombinedFlagModsFromFlagNodes(flagNodes) {\n  const flagProps = ['dotAll', 'ignoreCase'];\n  const combinedFlags = {enable: {}, disable: {}};\n  flagNodes.forEach(({flags}) => {\n    flagProps.forEach(prop => {\n      if (flags.enable?.[prop]) {\n        // Need to remove `disable` since disabled flags take precedence\n        delete combinedFlags.disable[prop];\n        combinedFlags.enable[prop] = true;\n      }\n      if (flags.disable?.[prop]) {\n        combinedFlags.disable[prop] = true;\n      }\n    });\n  });\n  if (!Object.keys(combinedFlags.enable).length) {\n    delete combinedFlags.enable;\n  }\n  if (!Object.keys(combinedFlags.disable).length) {\n    delete combinedFlags.disable;\n  }\n  if (combinedFlags.enable || combinedFlags.disable) {\n    return combinedFlags;\n  }\n  return null;\n}\n\nfunction getFlagModsFromFlags({dotAll, ignoreCase}) {\n  const mods = {};\n  if (dotAll || ignoreCase) {\n    mods.enable = {};\n    dotAll && (mods.enable.dotAll = true);\n    ignoreCase && (mods.enable.ignoreCase = true);\n  }\n  if (!dotAll || !ignoreCase) {\n    mods.disable = {};\n    !dotAll && (mods.disable.dotAll = true);\n    !ignoreCase && (mods.disable.ignoreCase = true);\n  }\n  return mods;\n}\n\nfunction getKids(node) {\n  if (!node) {\n    throw new Error('Node expected');\n  }\n  // NOTE: Not handling `CharacterClassRange`'s `min`/`max` and `Regex`'s `flags`, only because\n  // they haven't been needed by current callers\n  const {body} = node;\n  return Array.isArray(body) ? body : (body ? [body] : null);\n}\n\nfunction getLeadingG(els) {\n  const firstToConsider = els.find(el => (\n    el.kind === 'search_start' ||\n    isLoneGLookaround(el, {negate: false}) ||\n    !isAlwaysZeroLength(el)\n  ));\n  if (!firstToConsider) {\n    return null;\n  }\n  if (firstToConsider.kind === 'search_start') {\n    return firstToConsider;\n  }\n  if (firstToConsider.type === 'LookaroundAssertion') {\n    return firstToConsider.body[0].body[0];\n  }\n  if (firstToConsider.type === 'CapturingGroup' || firstToConsider.type === 'Group') {\n    const gNodesForGroup = [];\n    // Recursively find `\\G` nodes for all alternatives in the group\n    for (const alt of firstToConsider.body) {\n      const leadingG = getLeadingG(alt.body);\n      if (!leadingG) {\n        // Don't return `gNodesForGroup` collected so far since this alt didn't qualify\n        return null;\n      }\n      Array.isArray(leadingG) ?\n        gNodesForGroup.push(...leadingG) :\n        gNodesForGroup.push(leadingG);\n    }\n    return gNodesForGroup;\n  }\n  return null;\n}\n\nfunction isAncestorOf(node, descendant) {\n  const kids = getKids(node) ?? [];\n  for (const kid of kids) {\n    if (kid === descendant || isAncestorOf(kid, descendant)) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n@param {Node} node\n@returns {boolean}\n*/\nfunction isAlwaysZeroLength({type}) {\n  return (\n    type === 'Assertion' ||\n    type === 'Directive' ||\n    type === 'LookaroundAssertion'\n  );\n}\n\n/**\n@param {Node} node\n@returns {boolean}\n*/\nfunction isAlwaysNonZeroLength(node) {\n  const types = [\n    'Character',\n    'CharacterClass',\n    'CharacterSet',\n  ];\n  return types.includes(node.type) || (\n    node.type === 'Quantifier' &&\n    node.min &&\n    types.includes(node.body.type)\n  );\n}\n\nfunction isLoneGLookaround(node, options) {\n  const opts = {\n    negate: null,\n    ...options,\n  };\n  return (\n    node.type === 'LookaroundAssertion' &&\n    (opts.negate === null || node.negate === opts.negate) &&\n    node.body.length === 1 &&\n    hasOnlyChild(node.body[0], {\n      type: 'Assertion',\n      kind: 'search_start',\n    })\n  );\n}\n\n// See also `getAndStoreJsGroupName`\nfunction isValidJsGroupName(name) {\n  // JS group names are more restrictive than Onig; see\n  // <developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers>\n  return /^[$_\\p{IDS}][$\\u200C\\u200D\\p{IDC}]*$/u.test(name);\n}\n\n// Returns a single node, either the given node or all nodes wrapped in a noncapturing group\nfunction parseFragment(pattern, options) {\n  const ast = parse(pattern, {\n    ...options,\n    // Providing a custom set of Unicode property names avoids converting some JS Unicode\n    // properties (ex: `\\p{Alpha}`) to Onig POSIX classes\n    unicodePropertyMap: JsUnicodePropertyMap,\n  });\n  const alts = ast.body;\n  if (alts.length > 1 || alts[0].body.length > 1) {\n    return createGroup({body: alts});\n  }\n  return alts[0].body[0];\n}\n\nfunction setNegate(node, negate) {\n  node.negate = negate;\n  return node;\n}\n\nfunction setParent(node, parent) {\n  node.parent = parent;\n  return node;\n}\n\nfunction setParentDeep(node, parent) {\n  addParentProperties(node);\n  node.parent = parent;\n  return node;\n}\n\nexport {\n  transform,\n};\n","import {getOptions} from './options.js';\nimport {getIgnoreCaseMatchChars, UnicodePropertiesWithSpecificCase} from './unicode.js';\nimport {cp, envFlags, getNewCurrentFlags, getOrInsert, isMinTarget, r, throwIfNullish} from './utils.js';\nimport {createAlternative, createCharacter, createGroup} from 'oniguruma-parser/parser';\nimport {traverse} from 'oniguruma-parser/traverser';\n/**\n@import {ToRegExpOptions} from './index.js';\n@import {RegexPlusAst} from './transform.js';\n@import {AlternativeNode, AssertionNode, BackreferenceNode, CapturingGroupNode, CharacterClassNode, CharacterClassRangeNode, CharacterNode, CharacterSetNode, FlagsNode, GroupNode, LookaroundAssertionNode, Node, QuantifierNode, SubroutineNode} from 'oniguruma-parser/parser';\n@import {Visitor} from 'oniguruma-parser/traverser';\n*/\n\n/**\nGenerates a Regex+ compatible `pattern`, `flags`, and `options` from a Regex+ AST.\n@param {RegexPlusAst} ast\n@param {ToRegExpOptions} [options]\n@returns {{\n  pattern: string;\n  flags: string;\n  options: Object;\n  _captureTransfers: Map<number, Array<number>>;\n  _hiddenCaptures: Array<number>;\n}}\n*/\nfunction generate(ast, options) {\n  const opts = getOptions(options);\n  const minTargetEs2024 = isMinTarget(opts.target, 'ES2024');\n  const minTargetEs2025 = isMinTarget(opts.target, 'ES2025');\n  const recursionLimit = opts.rules.recursionLimit;\n  if (!Number.isInteger(recursionLimit) || recursionLimit < 2 || recursionLimit > 20) {\n    throw new Error('Invalid recursionLimit; use 2-20');\n  }\n\n  // If the output can't use flag groups, we need a pre-pass to check for the use of chars with\n  // case in case sensitive/insensitive states. This minimizes the need for case expansions (though\n  // expansions are lossless, even given Unicode case complexities) and allows supporting case\n  // insensitive backrefs in more cases\n  // TODO: Consider gathering this data in the transformer's final traversal to avoid work here\n  let hasCaseInsensitiveNode = null;\n  let hasCaseSensitiveNode = null;\n  if (!minTargetEs2025) {\n    const iStack = [ast.flags.ignoreCase];\n    traverse(ast, FlagModifierVisitor, {\n      getCurrentModI: () => iStack.at(-1),\n      popModI() {iStack.pop()},\n      pushModI(isIOn) {iStack.push(isIOn)},\n      setHasCasedChar() {\n        if (iStack.at(-1)) {\n          hasCaseInsensitiveNode = true;\n        } else {\n          hasCaseSensitiveNode = true;\n        }\n      },\n    });\n  }\n\n  const appliedGlobalFlags = {\n    dotAll: ast.flags.dotAll,\n    // - Turn global flag i on if a case insensitive node was used and no case sensitive nodes were\n    //   used (to avoid unnecessary node expansion).\n    // - Turn global flag i off if a case sensitive node was used (since case sensitivity can't be\n    //   forced without the use of ES2025 flag groups)\n    ignoreCase: !!((ast.flags.ignoreCase || hasCaseInsensitiveNode) && !hasCaseSensitiveNode),\n  };\n  let /** @type {Node} */ lastNode = ast;\n  const state = {\n    accuracy: opts.accuracy,\n    appliedGlobalFlags,\n    captureMap: new Map(),\n    currentFlags: {\n      dotAll: ast.flags.dotAll,\n      ignoreCase: ast.flags.ignoreCase,\n    },\n    inCharClass: false,\n    lastNode,\n    originMap: ast._originMap,\n    recursionLimit,\n    useAppliedIgnoreCase: !!(!minTargetEs2025 && hasCaseInsensitiveNode && hasCaseSensitiveNode),\n    useFlagMods: minTargetEs2025,\n    useFlagV: minTargetEs2024,\n    verbose: opts.verbose,\n  };\n  function gen(/** @type {Node} */ node) {\n    state.lastNode = lastNode;\n    lastNode = node; // For the next iteration\n    const fn = throwIfNullish(generator[node.type], `Unexpected node type \"${node.type}\"`);\n    return fn(node, state, gen);\n  }\n\n  const result = {\n    pattern: ast.body.map(gen).join('|'),\n    // Could reset `lastNode` at this point via `lastNode = ast`, but it isn't needed by flags\n    flags: gen(ast.flags),\n    options: {...ast.options},\n  };\n  if (!minTargetEs2024) {\n    // Switch from flag v to u; Regex+ implicitly chooses by default\n    delete result.options.force.v;\n    result.options.disable.v = true;\n    result.options.unicodeSetsPlugin = null;\n  }\n  result._captureTransfers = new Map();\n  result._hiddenCaptures = [];\n  state.captureMap.forEach((value, key) => {\n    if (value.hidden) {\n      result._hiddenCaptures.push(key);\n    }\n    if (value.transferTo) {\n      getOrInsert(result._captureTransfers, value.transferTo, []).push(key);\n    }\n  });\n\n  return result;\n}\n\nconst /** @type {Visitor} */ FlagModifierVisitor = {\n  '*': {\n    enter({node}, state) {\n      if (isAnyGroup(node)) {\n        const currentModI = state.getCurrentModI();\n        state.pushModI(\n          node.flags ?\n            getNewCurrentFlags({ignoreCase: currentModI}, node.flags).ignoreCase :\n            currentModI\n        );\n      }\n    },\n    exit({node}, state) {\n      if (isAnyGroup(node)) {\n        state.popModI();\n      }\n    },\n  },\n  Backreference(_, state) {\n    // Can't know for sure, so assume the backref will include chars with case (best that could be\n    // done is not calling `setHasCasedChar` if the reffed group doesn't contain a char with case\n    // or most kinds of char sets)\n    state.setHasCasedChar();\n  },\n  Character({node}, state) {\n    if (charHasCase(cp(node.value))) {\n      state.setHasCasedChar();\n    }\n  },\n  CharacterClassRange({node, skip}, state) {\n    skip();\n    if (getCasesOutsideCharClassRange(node, {firstOnly: true}).length) {\n      state.setHasCasedChar();\n    }\n  },\n  CharacterSet({node}, state) {\n    if (\n      node.kind === 'property' &&\n      UnicodePropertiesWithSpecificCase.has(node.value)\n    ) {\n      state.setHasCasedChar();\n    }\n  },\n};\n\n// `AbsenceFunction`, `Directive`, and `NamedCallout` nodes aren't included in transformer output\nconst generator = {\n  /**\n  @param {AlternativeNode} node\n  */\n  Alternative({body}, _, gen) {\n    return body.map(gen).join('');\n  },\n\n  /**\n  @param {AssertionNode} node\n  */\n  Assertion({kind, negate}) {\n    // Can always use `^` and `$` for string boundaries since JS flag m is never used (Onig uses\n    // different line break chars)\n    if (kind === 'string_end') {\n      return '$';\n    }\n    if (kind === 'string_start') {\n      return '^';\n    }\n    // If a word boundary came through the transformer unaltered, that means `wordIsAscii` or\n    // `asciiWordBoundaries` is enabled\n    if (kind === 'word_boundary') {\n      return negate ? r`\\B` : r`\\b`;\n    }\n    // Kinds `line_end`, `line_start`, `search_start`, `string_end_newline`, and\n    // `text_segment_boundary` are never included in transformer output\n    throw new Error(`Unexpected assertion kind \"${kind}\"`);\n  },\n\n  /**\n  @param {BackreferenceNode} node\n  */\n  Backreference({ref}, state) {\n    if (typeof ref !== 'number') {\n      throw new Error('Unexpected named backref in transformed AST');\n    }\n    if (\n      !state.useFlagMods &&\n      state.accuracy === 'strict' &&\n      state.currentFlags.ignoreCase &&\n      !state.captureMap.get(ref).ignoreCase\n    ) {\n      throw new Error('Use of case-insensitive backref to case-sensitive group requires target ES2025 or non-strict accuracy');\n    }\n    return '\\\\' + ref;\n  },\n\n  /**\n  @param {CapturingGroupNode} node\n  */\n  CapturingGroup(node, state, gen) {\n    const {body, name, number} = node;\n    const data = {ignoreCase: state.currentFlags.ignoreCase};\n    // Has origin if the capture is from an expanded subroutine\n    const origin = state.originMap.get(node);\n    if (origin) {\n      // All captures from/within expanded subroutines are marked as hidden\n      data.hidden = true;\n      // If a subroutine (or descendant capture) occurs after its origin group, it's marked to have\n      // its captured value transferred to the origin's capture slot. `number` and `origin.number`\n      // are the capture numbers *after* subroutine expansion\n      if (number > origin.number) {\n        data.transferTo = origin.number;\n      }\n    }\n    state.captureMap.set(number, data);\n    return `(${name ? `?<${name}>` : ''}${body.map(gen).join('|')})`;\n  },\n\n  /**\n  @param {CharacterNode} node\n  */\n  Character({value}, state) {\n    const char = cp(value);\n    const escaped = getCharEscape(value, {\n      escDigit: state.lastNode.type === 'Backreference',\n      inCharClass: state.inCharClass,\n      useFlagV: state.useFlagV,\n    });\n    if (escaped !== char) {\n      return escaped;\n    }\n    if (state.useAppliedIgnoreCase && state.currentFlags.ignoreCase && charHasCase(char)) {\n      const cases = getIgnoreCaseMatchChars(char);\n      return state.inCharClass ?\n        cases.join('') :\n        (cases.length > 1 ? `[${cases.join('')}]` : cases[0]);\n    }\n    return char;\n  },\n\n  /**\n  @param {CharacterClassNode} node\n  */\n  CharacterClass(node, state, gen) {\n    const {kind, negate, parent} = node;\n    let {body} = node;\n    if (kind === 'intersection' && !state.useFlagV) {\n      throw new Error('Use of character class intersection requires min target ES2024');\n    }\n    // Work around a WebKit parser bug by moving literal hyphens to the beginning of the class; see\n    // <github.com/slevithan/oniguruma-to-es/issues/30>\n    if (envFlags.bugFlagVLiteralHyphenIsRange && state.useFlagV && body.some(isLiteralHyphen)) {\n      body = [createCharacter(45), ...body.filter(kid => !isLiteralHyphen(kid))];\n    }\n    const genClass = () => `[${negate ? '^' : ''}${\n      body.map(gen).join(kind === 'intersection' ? '&&' : '')\n    }]`;\n    if (!state.inCharClass) {\n      // HACK: Transform the AST to support top-level-nested, negated classes in non-negated\n      // classes (ex: `[…[^…]]`) with pre-ES2024 `target`, via `(?:[…]|[^…])` or `(?:[^…])`,\n      // possibly with multiple alts that contain negated classes. Would be better to do this in\n      // the transformer, but it doesn't have true `target` since that's supposed to be a concern\n      // of the generator\n      if (\n        // Already established `kind !== 'intersection'` if `!state.useFlagV`; don't check again\n        (!state.useFlagV || envFlags.bugNestedClassIgnoresNegation) &&\n        !negate\n      ) {\n        const negatedChildClasses = body.filter(\n          kid => kid.type === 'CharacterClass' && kid.kind === 'union' && kid.negate\n        );\n        if (negatedChildClasses.length) {\n          const group = createGroup();\n          const groupFirstAlt = group.body[0];\n          group.parent = parent;\n          groupFirstAlt.parent = group;\n          body = body.filter(kid => !negatedChildClasses.includes(kid));\n          node.body = body;\n          if (body.length) {\n            node.parent = groupFirstAlt;\n            groupFirstAlt.body.push(node);\n          } else {\n            // Remove the group's only alt thus far, but since the class's `body` is empty, that\n            // implies there's at least one negated class we removed from it, so we'll add at least\n            // one alt back to the group, next\n            group.body.pop();\n          }\n          negatedChildClasses.forEach(cc => {\n            const newAlt = createAlternative({body: [cc]});\n            cc.parent = newAlt;\n            newAlt.parent = group;\n            group.body.push(newAlt);\n          });\n          return gen(group);\n        }\n      }\n      // For the outermost char class, set state\n      state.inCharClass = true;\n      const result = genClass();\n      state.inCharClass = false;\n      return result;\n    }\n    // No first element for implicit class in empty intersection like `[&&]`\n    const firstEl = body[0];\n    if (\n      // Already established that the parent is a char class via `inCharClass`; don't check again\n      kind === 'union' &&\n      !negate &&\n      firstEl &&\n      (\n        ( // Allows many nested classes to work with `target` ES2018 which doesn't support nesting\n          (!state.useFlagV || !state.verbose) &&\n          parent.kind === 'union' &&\n          !(envFlags.bugFlagVLiteralHyphenIsRange && state.useFlagV)\n        ) ||\n        ( !state.verbose &&\n          parent.kind === 'intersection' &&\n          // JS doesn't allow intersection with union or ranges\n          body.length === 1 &&\n          firstEl.type !== 'CharacterClassRange'\n        )\n      )\n    ) {\n      // Remove unnecessary nesting; unwrap kids into the parent char class\n      return body.map(gen).join('');\n    }\n    if (!state.useFlagV && parent.type === 'CharacterClass') {\n      throw new Error('Uses nested character class in a way that requires min target ES2024');\n    }\n    return genClass();\n  },\n\n  /**\n  @param {CharacterClassRangeNode} node\n  */\n  CharacterClassRange(node, state) {\n    const min = node.min.value;\n    const max = node.max.value;\n    const escOpts = {\n      escDigit: false,\n      inCharClass: true,\n      useFlagV: state.useFlagV,\n    };\n    const minStr = getCharEscape(min, escOpts);\n    const maxStr = getCharEscape(max, escOpts);\n    const extraChars = new Set();\n    if (state.useAppliedIgnoreCase && state.currentFlags.ignoreCase) {\n      // TODO: Avoid duplication by considering other chars in the parent char class when expanding\n      const charsOutsideRange = getCasesOutsideCharClassRange(node);\n      const ranges = getCodePointRangesFromChars(charsOutsideRange);\n      ranges.forEach(value => {\n        extraChars.add(\n          Array.isArray(value) ?\n            `${getCharEscape(value[0], escOpts)}-${getCharEscape(value[1], escOpts)}` :\n            getCharEscape(value, escOpts)\n        );\n      });\n    }\n    // Create the range without calling `gen` on the `min`/`max` kids\n    return `${minStr}-${maxStr}${[...extraChars].join('')}`;\n  },\n\n  /**\n  @param {CharacterSetNode} node\n  */\n  CharacterSet({kind, negate, value, key}, state) {\n    if (kind === 'dot') {\n      return state.currentFlags.dotAll ?\n        ((state.appliedGlobalFlags.dotAll || state.useFlagMods) ? '.' : '[^]') :\n        // Onig's only line break char is line feed, unlike JS\n        r`[^\\n]`;\n    }\n    if (kind === 'digit') {\n      return negate ? r`\\D` : r`\\d`;\n    }\n    if (kind === 'property') {\n      if (\n        state.useAppliedIgnoreCase &&\n        state.currentFlags.ignoreCase &&\n        UnicodePropertiesWithSpecificCase.has(value)\n      ) {\n        // Support for this would require heavy Unicode data. Could change e.g. `\\p{Lu}` to\n        // `\\p{LC}` if not using strict `accuracy` (since it's close but not 100%), but this\n        // wouldn't work for e.g. `\\p{Lt}`, and in any case, it's probably user error if using\n        // these case-specific props case-insensitively\n        throw new Error(`Unicode property \"${value}\" can't be case-insensitive when other chars have specific case`);\n      }\n      return `${negate ? r`\\P` : r`\\p`}{${key ? `${key}=` : ''}${value}}`;\n    }\n    if (kind === 'word') {\n      return negate ? r`\\W` : r`\\w`;\n    }\n    // Kinds `any`, `hex`, `newline`, `posix`, `space`, and `text_segment` are never included in\n    // transformer output\n    throw new Error(`Unexpected character set kind \"${kind}\"`);\n  },\n\n  /**\n  @param {FlagsNode} node\n  */\n  Flags(node, state) {\n    return (\n      // The transformer should never turn on the properties for flags d, g, m since Onig doesn't\n      // have equivs. Flag m is never used since Onig uses different line break chars than JS\n      // (node.hasIndices ? 'd' : '') +\n      // (node.global ? 'g' : '') +\n      // (node.multiline ? 'm' : '') +\n      (state.appliedGlobalFlags.ignoreCase ? 'i' : '') +\n      (node.dotAll ? 's' : '') +\n      (node.sticky ? 'y' : '')\n      // Regex+ doesn't allow explicitly adding flags it handles implicitly, so there are no\n      // `unicode` (flag u) or `unicodeSets` (flag v) props; those flags are added separately\n    );\n  },\n\n  /**\n  @param {GroupNode} node\n  */\n  Group({atomic, body, flags, parent}, state, gen) {\n    const currentFlags = state.currentFlags;\n    if (flags) {\n      state.currentFlags = getNewCurrentFlags(currentFlags, flags);\n    }\n    const contents = body.map(gen).join('|');\n    const result = (\n      !state.verbose &&\n      body.length === 1 && // Single alt\n      parent.type !== 'Quantifier' &&\n      !atomic &&\n      (!state.useFlagMods || !flags)\n     ) ? contents : `(?${getGroupPrefix(atomic, flags, state.useFlagMods)}${contents})`;\n    state.currentFlags = currentFlags;\n    return result;\n  },\n\n  /**\n  @param {LookaroundAssertionNode} node\n  */\n  LookaroundAssertion({body, kind, negate}, _, gen) {\n    const prefix = `${kind === 'lookahead' ? '' : '<'}${negate ? '!' : '='}`;\n    return `(?${prefix}${body.map(gen).join('|')})`;\n  },\n\n  /**\n  @param {QuantifierNode} node\n  */\n  Quantifier(node, _, gen) {\n    return gen(node.body) + getQuantifierStr(node);\n  },\n\n  /**\n  @param {SubroutineNode & {isRecursive: true}} node\n  */\n  Subroutine({isRecursive, ref}, state) {\n    if (!isRecursive) {\n      throw new Error('Unexpected non-recursive subroutine in transformed AST');\n    }\n    const limit = state.recursionLimit;\n    // Using the syntax supported by `regex-recursion`\n    return ref === 0 ? `(?R=${limit})` : r`\\g<${ref}&R=${limit}>`;\n  },\n};\n\n// ---------------\n// --- Helpers ---\n// ---------------\n\nconst BaseEscapeChars = new Set([\n  '$', '(', ')', '*', '+', '.', '?', '[', '\\\\', ']', '^', '{', '|', '}',\n]);\n\nconst CharClassEscapeChars = new Set([\n  '-', '\\\\', ']', '^',\n  // Literal `[` doesn't require escaping with flag u, but this can help work around regex source\n  // linters and regex syntax processors that expect unescaped `[` to create a nested class\n  '[',\n]);\n\nconst CharClassEscapeCharsFlagV = new Set([\n  '(', ')', '-', '/', '[', '\\\\', ']', '^', '{', '|', '}',\n  // Double punctuators; also includes already-listed `-` and `^`\n  '!', '#', '$', '%', '&', '*', '+', ',', '.', ':', ';', '<', '=', '>', '?', '@', '`', '~',\n]);\n\nconst CharCodeEscapeMap = new Map([\n  [ 9, r`\\t`], // horizontal tab\n  [10, r`\\n`], // line feed\n  [11, r`\\v`], // vertical tab\n  [12, r`\\f`], // form feed\n  [13, r`\\r`], // carriage return\n  [0x2028, r`\\u2028`], // line separator\n  [0x2029, r`\\u2029`], // paragraph separator\n  [0xFEFF, r`\\uFEFF`], // ZWNBSP/BOM\n]);\n\nconst casedRe = /^\\p{Cased}$/u;\nfunction charHasCase(char) {\n  return casedRe.test(char);\n}\n\n/**\nGiven a `CharacterClassRange` node, returns an array of chars that are a case variant of a char in\nthe range, and aren't already in the range.\n*/\nfunction getCasesOutsideCharClassRange(node, options) {\n  const firstOnly = !!options?.firstOnly;\n  const min = node.min.value;\n  const max = node.max.value;\n  const found = [];\n  // Avoid unneeded work. Assumptions (per Unicode 16):\n  // - No case variants cross the Basic Multilingual Plane boundary\n  // - No cased chars appear beyond the Supplementary Multilingual Plane\n  if ((min < 65 && (max === 0xFFFF || max >= 0x1FFFF)) || (min === 0x10000 && max >= 0x1FFFF)) {\n    return found;\n  }\n  for (let i = min; i <= max; i++) {\n    const char = cp(i);\n    if (!charHasCase(char)) {\n      continue;\n    }\n    const charsOutsideRange = getIgnoreCaseMatchChars(char).filter(caseOfChar => {\n      const num = caseOfChar.codePointAt(0);\n      return num < min || num > max;\n    });\n    if (charsOutsideRange.length) {\n      found.push(...charsOutsideRange);\n      if (firstOnly) {\n        break;\n      }\n    }\n  }\n  return found;\n}\n\n// This shouldn't modifiy any char that has case\nfunction getCharEscape(codePoint, {escDigit, inCharClass, useFlagV}) {\n  if (CharCodeEscapeMap.has(codePoint)) {\n    return CharCodeEscapeMap.get(codePoint);\n  }\n  if (\n    // Control chars, etc.; condition modeled on the Chrome developer console's display for strings\n    codePoint < 32 || (codePoint > 126 && codePoint < 160) ||\n    // Unicode planes 4-16; unassigned, special purpose, and private use area\n    codePoint > 0x3FFFF ||\n    // Avoid corrupting a preceding backref by immediately following it with a literal digit\n    (escDigit && isDigitCharCode(codePoint))\n  ) {\n    // Don't convert codePoint `0` to `\\0` since that's corruptible by following literal digits\n    // Note: Not using raw strings to work around Bun ≤ 1.1.34 issue <github.com/oven-sh/bun/issues/7540>\n    return codePoint > 0xFF ?\n      `\\\\u{${codePoint.toString(16).toUpperCase()}}` :\n      `\\\\x${codePoint.toString(16).toUpperCase().padStart(2, '0')}`;\n  }\n  const escapeChars = inCharClass ?\n    (useFlagV ? CharClassEscapeCharsFlagV : CharClassEscapeChars) :\n    BaseEscapeChars;\n  const char = cp(codePoint);\n  return (escapeChars.has(char) ? '\\\\' : '') + char;\n}\n\nfunction getCodePointRangesFromChars(chars) {\n  const codePoints = chars.map(char => char.codePointAt(0)).sort((a, b) => a - b);\n  const values = [];\n  let start = null;\n  for (let i = 0; i < codePoints.length; i++) {\n    if (codePoints[i + 1] === codePoints[i] + 1) {\n      start ??= codePoints[i];\n    } else if (start === null) {\n      values.push(codePoints[i]);\n    } else {\n      values.push([start, codePoints[i]]);\n      start = null;\n    }\n  }\n  return values;\n}\n\nfunction getGroupPrefix(atomic, flagMods, useFlagMods) {\n  if (atomic) {\n    return '>';\n  }\n  let mods = '';\n  if (flagMods && useFlagMods) {\n    const {enable, disable} = flagMods;\n    mods =\n      (enable?.ignoreCase ? 'i' : '') +\n      (enable?.dotAll ? 's' : '') +\n      (disable ? '-' : '') +\n      (disable?.ignoreCase ? 'i' : '') +\n      (disable?.dotAll ? 's' : '');\n  }\n  return `${mods}:`;\n}\n\n/**\n@param {QuantifierNode} node\n@returns {string}\n*/\nfunction getQuantifierStr({kind, max, min}) {\n  let base;\n  if (!min && max === 1) {\n    base = '?';\n  } else if (!min && max === Infinity) {\n    base = '*';\n  } else if (min === 1 && max === Infinity) {\n    base = '+';\n  } else if (min === max) {\n    base = `{${min}}`;\n  } else {\n    base = `{${min},${max === Infinity ? '' : max}}`;\n  }\n  return base + {\n    greedy: '',\n    lazy: '?',\n    possessive: '+',\n  }[kind];\n}\n\n/**\n@param {Node} node\n@returns {boolean}\n*/\nfunction isAnyGroup({type}) {\n  return type === 'CapturingGroup' ||\n    type === 'Group' ||\n    type === 'LookaroundAssertion';\n}\n\nfunction isDigitCharCode(value) {\n  return value > 47 && value < 58;\n}\n\n/**\n@param {Node} node\n@returns {boolean}\n*/\nfunction isLiteralHyphen({type, value}) {\n  return type === 'Character' && value === 45;\n}\n\nexport {\n  generate,\n};\n","import {getOrInsert} from './utils.js';\n\n/**\n@typedef {{\n  hiddenCaptures?: Array<number>;\n  lazyCompile?: boolean;\n  strategy?: string | null;\n  transfers?: Array<[number, Array<number>]>;\n}} EmulatedRegExpOptions\n*/\n\n/**\nWorks the same as JavaScript's native `RegExp` constructor in all contexts, but can be given\nresults from `toRegExpDetails` to produce the same result as `toRegExp`.\n*/\nclass EmulatedRegExp extends RegExp {\n  /**\n  @type {Map<number, {\n    hidden?: true;\n    transferTo?: number;\n  }>}\n  */\n  #captureMap = new Map();\n\n  /**\n  @type {RegExp | EmulatedRegExp | null}\n  */\n  #compiled = null;\n\n  /**\n  @type {string}\n  */\n  #pattern;\n\n  /**\n  @type {Map<number, string>?}\n  */\n  #nameMap = null;\n\n  /**\n  @type {string?}\n  */\n  #strategy = null;\n\n  /**\n  Can be used to serialize the instance.\n  @type {EmulatedRegExpOptions}\n  */\n  rawOptions = {};\n\n  // Override the getter with one that works with lazy-compiled regexes\n  get source() {\n    return this.#pattern || '(?:)';\n  }\n\n  /**\n  @overload\n  @param {string} pattern\n  @param {string} [flags]\n  @param {EmulatedRegExpOptions} [options]\n  */\n  /**\n  @overload\n  @param {EmulatedRegExp} pattern\n  @param {string} [flags]\n  */\n  constructor(pattern, flags, options) {\n    const lazyCompile = !!options?.lazyCompile;\n    if (pattern instanceof RegExp) {\n      // Argument `options` isn't provided when regexes are copied, including as part of the\n      // internal handling of string methods `matchAll` and `split`\n      if (options) {\n        throw new Error('Cannot provide options when copying a regexp');\n      }\n      const re = pattern; // Alias for readability\n      super(re, flags);\n      this.#pattern = re.source;\n      if (re instanceof EmulatedRegExp) {\n        this.#captureMap = re.#captureMap;\n        this.#nameMap = re.#nameMap;\n        this.#strategy = re.#strategy;\n        this.rawOptions = re.rawOptions;\n      }\n    } else {\n      const opts = {\n        hiddenCaptures: [],\n        strategy: null,\n        transfers: [],\n        ...options,\n      };\n      super(lazyCompile ? '' : pattern, flags);\n      this.#pattern = pattern;\n      this.#captureMap = createCaptureMap(opts.hiddenCaptures, opts.transfers);\n      this.#strategy = opts.strategy;\n      // Don't add default values from `opts` since this gets serialized\n      this.rawOptions = options ?? {};\n    }\n    if (!lazyCompile) {\n      this.#compiled = this;\n    }\n  }\n\n  /**\n  Called internally by all String/RegExp methods that use regexes.\n  @override\n  @param {string} str\n  @returns {RegExpExecArray?}\n  */\n  exec(str) {\n    // Lazy compilation\n    if (!this.#compiled) {\n      const {lazyCompile, ...rest} = this.rawOptions;\n      this.#compiled = new EmulatedRegExp(this.#pattern, this.flags, rest);\n    }\n\n    const useLastIndex = this.global || this.sticky;\n    const pos = this.lastIndex;\n\n    if (this.#strategy === 'clip_search' && useLastIndex && pos) {\n      // Reset since this tests on a sliced string that we want to match at the start of\n      this.lastIndex = 0;\n      // Slicing the string can lead to mismatches when three edge cases are stacked on each other:\n      // 1. An uncommon use of `\\G` that relies on `clip_search`, combined with...\n      // 2. Lookbehind that searches behind the search start (not match start) position...\n      // 3. During a search when the regex's `lastIndex` isn't `0`.\n      // The `clip_search` strategy is therefore only allowed when lookbehind isn't present, if\n      // using strict `accuracy`\n      const match = this.#execCore(str.slice(pos));\n      if (match) {\n        adjustMatchDetailsForOffset(match, pos, str, this.hasIndices);\n        this.lastIndex += pos;\n      }\n      return match;\n    }\n\n    return this.#execCore(str);\n  }\n\n  /**\n  Adds support for hidden and transfer captures.\n  @param {string} str\n  @returns\n  */\n  #execCore(str) {\n    // Support lazy compilation\n    this.#compiled.lastIndex = this.lastIndex;\n    const match = super.exec.call(this.#compiled, str);\n    this.lastIndex = this.#compiled.lastIndex;\n\n    if (!match || !this.#captureMap.size) {\n      return match;\n    }\n\n    const matchCopy = [...match];\n    // Empty all but the first value of the array while preserving its other properties\n    match.length = 1;\n    let indicesCopy;\n    if (this.hasIndices) {\n      indicesCopy = [...match.indices];\n      match.indices.length = 1;\n    }\n    const mappedNums = [0];\n    for (let i = 1; i < matchCopy.length; i++) {\n      const {hidden, transferTo} = this.#captureMap.get(i) ?? {};\n      if (hidden) {\n        mappedNums.push(null);\n      } else {\n        mappedNums.push(match.length);\n        match.push(matchCopy[i]);\n        if (this.hasIndices) {\n          match.indices.push(indicesCopy[i]);\n        }\n      }\n\n      // Only transfer if the capture participated in the match\n      if (transferTo && matchCopy[i] !== undefined) {\n        const to = mappedNums[transferTo];\n        if (!to) {\n          throw new Error(`Invalid capture transfer to \"${to}\"`);\n        }\n        match[to] = matchCopy[i];\n        if (this.hasIndices) {\n          match.indices[to] = indicesCopy[i];\n        }\n        if (match.groups) {\n          if (!this.#nameMap) {\n            // Generate and cache the first time it's needed\n            this.#nameMap = createNameMap(this.source);\n          }\n          const name = this.#nameMap.get(transferTo);\n          if (name) {\n            match.groups[name] = matchCopy[i];\n            if (this.hasIndices) {\n              match.indices.groups[name] = indicesCopy[i];\n            }\n          }\n        }\n      }\n    }\n\n    return match;\n  }\n}\n\nfunction adjustMatchDetailsForOffset(match, offset, input, hasIndices) {\n  match.index += offset;\n  match.input = input;\n  if (hasIndices) {\n    const indices = match.indices;\n    for (let i = 0; i < indices.length; i++) {\n      const arr = indices[i];\n      if (arr) {\n        // Replace the array rather than updating values since the keys of `match.indices` and\n        // `match.indices.groups` share their value arrays by reference. Need to be precise in case\n        // they were previously altered separately\n        indices[i] = [arr[0] + offset, arr[1] + offset];\n      }\n    }\n    const groupIndices = indices.groups;\n    if (groupIndices) {\n      Object.keys(groupIndices).forEach(key => {\n        const arr = groupIndices[key];\n        if (arr) {\n          groupIndices[key] = [arr[0] + offset, arr[1] + offset];\n        }\n      });\n    }\n  }\n}\n\n/**\nBuild the capturing group map, with hidden/transfer groups marked to indicate their submatches\nshould get special handling in match results.\n@param {Array<number>} hiddenCaptures\n@param {Array<[number, Array<number>]>} transfers\n@returns {Map<number, {\n  hidden?: true;\n  transferTo?: number;\n}>}\n*/\nfunction createCaptureMap(hiddenCaptures, transfers) {\n  const captureMap = new Map();\n  for (const num of hiddenCaptures) {\n    captureMap.set(num, {\n      hidden: true,\n    });\n  }\n  for (const [to, from] of transfers) {\n    for (const num of from) {\n      getOrInsert(captureMap, num, {}).transferTo = to;\n    }\n  }\n  return captureMap;\n}\n\n/**\n@param {string} pattern\n@returns {Map<number, string>}\n*/\nfunction createNameMap(pattern) {\n  const re = /(?<capture>\\((?:\\?<(?![=!])(?<name>[^>]+)>|(?!\\?)))|\\\\?./gsu;\n  const map = new Map();\n  let numCharClassesOpen = 0;\n  let numCaptures = 0;\n  let match;\n  while ((match = re.exec(pattern))) {\n    const {0: m, groups: {capture, name}} = match;\n    // Relies on no unescaped literal `[` in char classes (valid in JS if not using flag v), but\n    // this library's generator never produces unescaped literal `[` even with `target` ES2018 (see\n    // `CharClassEscapeChars`)\n    if (m === '[') {\n      numCharClassesOpen++;\n    } else if (!numCharClassesOpen) {\n      if (capture) {\n        numCaptures++;\n        if (name) {\n          map.set(numCaptures, name);\n        }\n      }\n    } else if (m === ']') {\n      numCharClassesOpen--;\n    }\n  }\n  return map;\n}\n\nexport {\n  EmulatedRegExp,\n};\n","import {transform} from './transform.js';\nimport {generate} from './generate.js';\nimport {Accuracy, getOptions, Target} from './options.js';\nimport {EmulatedRegExp} from './subclass.js';\nimport {JsUnicodePropertyMap} from './unicode.js';\nimport {parse} from 'oniguruma-parser/parser';\nimport {atomic, possessive} from 'regex/internals';\nimport {recursion} from 'regex-recursion';\n/**\n@import {EmulatedRegExpOptions} from './subclass.js';\n*/\n\n// The validation and transformation for Oniguruma's unique syntax and behavior differences\n// compared to native JS RegExp is layered into all steps of the compilation process:\n// 1. Parser: Uses `oniguruma-parser` to build an Oniguruma AST, which accounts for many\n//    differences between Oniguruma and JS.\n// 2. Transformer: Converts the Oniguruma AST to a Regex+ AST that preserves all Oniguruma\n//    behavior. This is true even in cases of non-native-JS features that are supported by both\n//    Regex+ and Oniguruma but with subtly different behavior in each (subroutines, flag x).\n// 3. Generator: Converts the Regex+ AST to a Regex+ pattern, flags, and options.\n// 4. Postprocessing: Regex+ internals and plugins are used to transpile several remaining features\n//    (atomic groups, possessive quantifiers, recursion). Regex+ uses a strict superset of JS\n//    RegExp syntax, so using it allows this library to benefit from not reinventing the wheel for\n//    complex features that Regex+ already knows how to transpile to JS.\n\n/**\n@typedef {{\n  accuracy?: keyof Accuracy;\n  avoidSubclass?: boolean;\n  flags?: string;\n  global?: boolean;\n  hasIndices?: boolean;\n  lazyCompileLength?: number;\n  rules?: {\n    allowOrphanBackrefs?: boolean;\n    asciiWordBoundaries?: boolean;\n    captureGroup?: boolean;\n    recursionLimit?: number;\n    singleline?: boolean;\n  };\n  target?: keyof Target;\n  verbose?: boolean;\n}} ToRegExpOptions\n*/\n\n/**\nAccepts an Oniguruma pattern and returns an equivalent JavaScript `RegExp`.\n@param {string} pattern Oniguruma regex pattern.\n@param {ToRegExpOptions} [options]\n@returns {RegExp | EmulatedRegExp}\n*/\nfunction toRegExp(pattern, options) {\n  const d = toRegExpDetails(pattern, options);\n  if (d.options) {\n    return new EmulatedRegExp(d.pattern, d.flags, d.options);\n  }\n  return new RegExp(d.pattern, d.flags);\n}\n\n/**\nAccepts an Oniguruma pattern and returns the details for an equivalent JavaScript `RegExp`.\n@param {string} pattern Oniguruma regex pattern.\n@param {ToRegExpOptions} [options]\n@returns {{\n  pattern: string;\n  flags: string;\n  options?: EmulatedRegExpOptions;\n}}\n*/\nfunction toRegExpDetails(pattern, options) {\n  const opts = getOptions(options);\n  const onigurumaAst = parse(pattern, {\n    flags: opts.flags,\n    normalizeUnknownPropertyNames: true,\n    rules: {\n      captureGroup: opts.rules.captureGroup,\n      singleline: opts.rules.singleline,\n    },\n    skipBackrefValidation: opts.rules.allowOrphanBackrefs,\n    unicodePropertyMap: JsUnicodePropertyMap,\n  });\n  const regexPlusAst = transform(onigurumaAst, {\n    accuracy: opts.accuracy,\n    asciiWordBoundaries: opts.rules.asciiWordBoundaries,\n    avoidSubclass: opts.avoidSubclass,\n    bestEffortTarget: opts.target,\n  });\n  const generated = generate(regexPlusAst, opts);\n  const recursionResult = recursion(generated.pattern, {\n    captureTransfers: generated._captureTransfers,\n    hiddenCaptures: generated._hiddenCaptures,\n    mode: 'external',\n  });\n  const possessiveResult = possessive(recursionResult.pattern);\n  const atomicResult = atomic(possessiveResult.pattern, {\n    captureTransfers: recursionResult.captureTransfers,\n    hiddenCaptures: recursionResult.hiddenCaptures,\n  });\n  const details = {\n    pattern: atomicResult.pattern,\n    flags: `${opts.hasIndices ? 'd' : ''}${opts.global ? 'g' : ''}${generated.flags}${generated.options.disable.v ? 'u' : 'v'}`,\n  };\n  if (opts.avoidSubclass) {\n    if (opts.lazyCompileLength !== Infinity) {\n      throw new Error('Lazy compilation requires subclass');\n    }\n  } else {\n    // Sort isn't required; only for readability when serialized\n    const hiddenCaptures = atomicResult.hiddenCaptures.sort((a, b) => a - b);\n    // Change the map to the `EmulatedRegExp` format, serializable as JSON\n    const transfers = Array.from(atomicResult.captureTransfers);\n    const strategy = regexPlusAst._strategy;\n    const lazyCompile = details.pattern.length >= opts.lazyCompileLength;\n    if (hiddenCaptures.length || transfers.length || strategy || lazyCompile) {\n      details.options = {\n        ...(hiddenCaptures.length && {hiddenCaptures}),\n        ...(transfers.length && {transfers}),\n        ...(strategy && {strategy}),\n        ...(lazyCompile && {lazyCompile}),\n      };\n    }\n  }\n  return details;\n}\n\n// function toOnigurumaAst(pattern, options) {\n//   return parse(pattern, {\n//     flags: options?.flags ?? '',\n//     normalizeUnknownPropertyNames: true,\n//     rules: options?.rules ?? {},\n//     unicodePropertyMap: JsUnicodePropertyMap,\n//   });\n// }\n\n// function toRegexPlusAst(pattern, options) {\n//   return transform(toOnigurumaAst(pattern, options));\n// }\n\nexport {\n  EmulatedRegExp,\n  toRegExp,\n  toRegExpDetails,\n  // toOnigurumaAst,\n  // toRegexPlusAst,\n};\n","const MAX = 4294967295;\nclass JavaScriptScanner {\n  constructor(patterns, options = {}) {\n    this.patterns = patterns;\n    this.options = options;\n    const {\n      forgiving = false,\n      cache,\n      regexConstructor\n    } = options;\n    if (!regexConstructor) {\n      throw new Error(\"Option `regexConstructor` is not provided\");\n    }\n    this.regexps = patterns.map((p) => {\n      if (typeof p !== \"string\") {\n        return p;\n      }\n      const cached = cache?.get(p);\n      if (cached) {\n        if (cached instanceof RegExp) {\n          return cached;\n        }\n        if (forgiving)\n          return null;\n        throw cached;\n      }\n      try {\n        const regex = regexConstructor(p);\n        cache?.set(p, regex);\n        return regex;\n      } catch (e) {\n        cache?.set(p, e);\n        if (forgiving)\n          return null;\n        throw e;\n      }\n    });\n  }\n  regexps;\n  findNextMatchSync(string, startPosition, _options) {\n    const str = typeof string === \"string\" ? string : string.content;\n    const pending = [];\n    function toResult(index, match, offset = 0) {\n      return {\n        index,\n        captureIndices: match.indices.map((indice) => {\n          if (indice == null) {\n            return {\n              start: MAX,\n              end: MAX,\n              length: 0\n            };\n          }\n          return {\n            start: indice[0] + offset,\n            end: indice[1] + offset,\n            length: indice[1] - indice[0]\n          };\n        })\n      };\n    }\n    for (let i = 0; i < this.regexps.length; i++) {\n      const regexp = this.regexps[i];\n      if (!regexp)\n        continue;\n      try {\n        regexp.lastIndex = startPosition;\n        const match = regexp.exec(str);\n        if (!match)\n          continue;\n        if (match.index === startPosition) {\n          return toResult(i, match, 0);\n        }\n        pending.push([i, match, 0]);\n      } catch (e) {\n        if (this.options.forgiving)\n          continue;\n        throw e;\n      }\n    }\n    if (pending.length) {\n      const minIndex = Math.min(...pending.map((m) => m[1].index));\n      for (const [i, match, offset] of pending) {\n        if (match.index === minIndex) {\n          return toResult(i, match, offset);\n        }\n      }\n    }\n    return null;\n  }\n}\n\nexport { JavaScriptScanner as J };\n","import { toRegExp } from 'oniguruma-to-es';\nimport { J as JavaScriptScanner } from './shared/engine-javascript.hzpS1_41.mjs';\n\nfunction defaultJavaScriptRegexConstructor(pattern, options) {\n  return toRegExp(\n    pattern,\n    {\n      global: true,\n      hasIndices: true,\n      // This has no benefit for the standard JS engine, but it avoids a perf penalty for\n      // precompiled grammars when constructing extremely long patterns that aren't always used\n      lazyCompileLength: 3e3,\n      rules: {\n        // Needed since TextMate grammars merge backrefs across patterns\n        allowOrphanBackrefs: true,\n        // Improves search performance for generated regexes\n        asciiWordBoundaries: true,\n        // Follow `vscode-oniguruma` which enables this Oniguruma option by default\n        captureGroup: true,\n        // Oniguruma uses depth limit `20`; lowered here to keep regexes shorter and maybe\n        // sometimes faster, but can be increased if issues reported due to low limit\n        recursionLimit: 5,\n        // Oniguruma option for `^`->`\\A`, `$`->`\\Z`; improves search performance without any\n        // change in meaning since TM grammars search line by line\n        singleline: true\n      },\n      ...options\n    }\n  );\n}\nfunction createJavaScriptRegexEngine(options = {}) {\n  const _options = Object.assign(\n    {\n      target: \"auto\",\n      cache: /* @__PURE__ */ new Map()\n    },\n    options\n  );\n  _options.regexConstructor ||= (pattern) => defaultJavaScriptRegexConstructor(pattern, { target: _options.target });\n  return {\n    createScanner(patterns) {\n      return new JavaScriptScanner(patterns, _options);\n    },\n    createString(s) {\n      return {\n        content: s\n      };\n    }\n  };\n}\n\nexport { createJavaScriptRegexEngine, defaultJavaScriptRegexConstructor };\n","/* Theme: github-light */\nexport default Object.freeze(JSON.parse(\"{\\\"colors\\\":{\\\"activityBar.activeBorder\\\":\\\"#f9826c\\\",\\\"activityBar.background\\\":\\\"#fff\\\",\\\"activityBar.border\\\":\\\"#e1e4e8\\\",\\\"activityBar.foreground\\\":\\\"#2f363d\\\",\\\"activityBar.inactiveForeground\\\":\\\"#959da5\\\",\\\"activityBarBadge.background\\\":\\\"#2188ff\\\",\\\"activityBarBadge.foreground\\\":\\\"#fff\\\",\\\"badge.background\\\":\\\"#dbedff\\\",\\\"badge.foreground\\\":\\\"#005cc5\\\",\\\"breadcrumb.activeSelectionForeground\\\":\\\"#586069\\\",\\\"breadcrumb.focusForeground\\\":\\\"#2f363d\\\",\\\"breadcrumb.foreground\\\":\\\"#6a737d\\\",\\\"breadcrumbPicker.background\\\":\\\"#fafbfc\\\",\\\"button.background\\\":\\\"#159739\\\",\\\"button.foreground\\\":\\\"#fff\\\",\\\"button.hoverBackground\\\":\\\"#138934\\\",\\\"button.secondaryBackground\\\":\\\"#e1e4e8\\\",\\\"button.secondaryForeground\\\":\\\"#1b1f23\\\",\\\"button.secondaryHoverBackground\\\":\\\"#d1d5da\\\",\\\"checkbox.background\\\":\\\"#fafbfc\\\",\\\"checkbox.border\\\":\\\"#d1d5da\\\",\\\"debugToolBar.background\\\":\\\"#fff\\\",\\\"descriptionForeground\\\":\\\"#6a737d\\\",\\\"diffEditor.insertedTextBackground\\\":\\\"#34d05822\\\",\\\"diffEditor.removedTextBackground\\\":\\\"#d73a4922\\\",\\\"dropdown.background\\\":\\\"#fafbfc\\\",\\\"dropdown.border\\\":\\\"#e1e4e8\\\",\\\"dropdown.foreground\\\":\\\"#2f363d\\\",\\\"dropdown.listBackground\\\":\\\"#fff\\\",\\\"editor.background\\\":\\\"#fff\\\",\\\"editor.findMatchBackground\\\":\\\"#ffdf5d\\\",\\\"editor.findMatchHighlightBackground\\\":\\\"#ffdf5d66\\\",\\\"editor.focusedStackFrameHighlightBackground\\\":\\\"#28a74525\\\",\\\"editor.foldBackground\\\":\\\"#d1d5da11\\\",\\\"editor.foreground\\\":\\\"#24292e\\\",\\\"editor.inactiveSelectionBackground\\\":\\\"#0366d611\\\",\\\"editor.lineHighlightBackground\\\":\\\"#f6f8fa\\\",\\\"editor.linkedEditingBackground\\\":\\\"#0366d611\\\",\\\"editor.selectionBackground\\\":\\\"#0366d625\\\",\\\"editor.selectionHighlightBackground\\\":\\\"#34d05840\\\",\\\"editor.selectionHighlightBorder\\\":\\\"#34d05800\\\",\\\"editor.stackFrameHighlightBackground\\\":\\\"#ffd33d33\\\",\\\"editor.wordHighlightBackground\\\":\\\"#34d05800\\\",\\\"editor.wordHighlightBorder\\\":\\\"#24943e99\\\",\\\"editor.wordHighlightStrongBackground\\\":\\\"#34d05800\\\",\\\"editor.wordHighlightStrongBorder\\\":\\\"#24943e50\\\",\\\"editorBracketHighlight.foreground1\\\":\\\"#005cc5\\\",\\\"editorBracketHighlight.foreground2\\\":\\\"#e36209\\\",\\\"editorBracketHighlight.foreground3\\\":\\\"#5a32a3\\\",\\\"editorBracketHighlight.foreground4\\\":\\\"#005cc5\\\",\\\"editorBracketHighlight.foreground5\\\":\\\"#e36209\\\",\\\"editorBracketHighlight.foreground6\\\":\\\"#5a32a3\\\",\\\"editorBracketMatch.background\\\":\\\"#34d05840\\\",\\\"editorBracketMatch.border\\\":\\\"#34d05800\\\",\\\"editorCursor.foreground\\\":\\\"#044289\\\",\\\"editorError.foreground\\\":\\\"#cb2431\\\",\\\"editorGroup.border\\\":\\\"#e1e4e8\\\",\\\"editorGroupHeader.tabsBackground\\\":\\\"#f6f8fa\\\",\\\"editorGroupHeader.tabsBorder\\\":\\\"#e1e4e8\\\",\\\"editorGutter.addedBackground\\\":\\\"#28a745\\\",\\\"editorGutter.deletedBackground\\\":\\\"#d73a49\\\",\\\"editorGutter.modifiedBackground\\\":\\\"#2188ff\\\",\\\"editorIndentGuide.activeBackground\\\":\\\"#d7dbe0\\\",\\\"editorIndentGuide.background\\\":\\\"#eff2f6\\\",\\\"editorLineNumber.activeForeground\\\":\\\"#24292e\\\",\\\"editorLineNumber.foreground\\\":\\\"#1b1f234d\\\",\\\"editorOverviewRuler.border\\\":\\\"#fff\\\",\\\"editorWarning.foreground\\\":\\\"#f9c513\\\",\\\"editorWhitespace.foreground\\\":\\\"#d1d5da\\\",\\\"editorWidget.background\\\":\\\"#f6f8fa\\\",\\\"errorForeground\\\":\\\"#cb2431\\\",\\\"focusBorder\\\":\\\"#2188ff\\\",\\\"foreground\\\":\\\"#444d56\\\",\\\"gitDecoration.addedResourceForeground\\\":\\\"#28a745\\\",\\\"gitDecoration.conflictingResourceForeground\\\":\\\"#e36209\\\",\\\"gitDecoration.deletedResourceForeground\\\":\\\"#d73a49\\\",\\\"gitDecoration.ignoredResourceForeground\\\":\\\"#959da5\\\",\\\"gitDecoration.modifiedResourceForeground\\\":\\\"#005cc5\\\",\\\"gitDecoration.submoduleResourceForeground\\\":\\\"#959da5\\\",\\\"gitDecoration.untrackedResourceForeground\\\":\\\"#28a745\\\",\\\"input.background\\\":\\\"#fafbfc\\\",\\\"input.border\\\":\\\"#e1e4e8\\\",\\\"input.foreground\\\":\\\"#2f363d\\\",\\\"input.placeholderForeground\\\":\\\"#959da5\\\",\\\"list.activeSelectionBackground\\\":\\\"#e2e5e9\\\",\\\"list.activeSelectionForeground\\\":\\\"#2f363d\\\",\\\"list.focusBackground\\\":\\\"#cce5ff\\\",\\\"list.hoverBackground\\\":\\\"#ebf0f4\\\",\\\"list.hoverForeground\\\":\\\"#2f363d\\\",\\\"list.inactiveFocusBackground\\\":\\\"#dbedff\\\",\\\"list.inactiveSelectionBackground\\\":\\\"#e8eaed\\\",\\\"list.inactiveSelectionForeground\\\":\\\"#2f363d\\\",\\\"notificationCenterHeader.background\\\":\\\"#e1e4e8\\\",\\\"notificationCenterHeader.foreground\\\":\\\"#6a737d\\\",\\\"notifications.background\\\":\\\"#fafbfc\\\",\\\"notifications.border\\\":\\\"#e1e4e8\\\",\\\"notifications.foreground\\\":\\\"#2f363d\\\",\\\"notificationsErrorIcon.foreground\\\":\\\"#d73a49\\\",\\\"notificationsInfoIcon.foreground\\\":\\\"#005cc5\\\",\\\"notificationsWarningIcon.foreground\\\":\\\"#e36209\\\",\\\"panel.background\\\":\\\"#f6f8fa\\\",\\\"panel.border\\\":\\\"#e1e4e8\\\",\\\"panelInput.border\\\":\\\"#e1e4e8\\\",\\\"panelTitle.activeBorder\\\":\\\"#f9826c\\\",\\\"panelTitle.activeForeground\\\":\\\"#2f363d\\\",\\\"panelTitle.inactiveForeground\\\":\\\"#6a737d\\\",\\\"pickerGroup.border\\\":\\\"#e1e4e8\\\",\\\"pickerGroup.foreground\\\":\\\"#2f363d\\\",\\\"progressBar.background\\\":\\\"#2188ff\\\",\\\"quickInput.background\\\":\\\"#fafbfc\\\",\\\"quickInput.foreground\\\":\\\"#2f363d\\\",\\\"scrollbar.shadow\\\":\\\"#6a737d33\\\",\\\"scrollbarSlider.activeBackground\\\":\\\"#959da588\\\",\\\"scrollbarSlider.background\\\":\\\"#959da533\\\",\\\"scrollbarSlider.hoverBackground\\\":\\\"#959da544\\\",\\\"settings.headerForeground\\\":\\\"#2f363d\\\",\\\"settings.modifiedItemIndicator\\\":\\\"#2188ff\\\",\\\"sideBar.background\\\":\\\"#f6f8fa\\\",\\\"sideBar.border\\\":\\\"#e1e4e8\\\",\\\"sideBar.foreground\\\":\\\"#586069\\\",\\\"sideBarSectionHeader.background\\\":\\\"#f6f8fa\\\",\\\"sideBarSectionHeader.border\\\":\\\"#e1e4e8\\\",\\\"sideBarSectionHeader.foreground\\\":\\\"#2f363d\\\",\\\"sideBarTitle.foreground\\\":\\\"#2f363d\\\",\\\"statusBar.background\\\":\\\"#fff\\\",\\\"statusBar.border\\\":\\\"#e1e4e8\\\",\\\"statusBar.debuggingBackground\\\":\\\"#f9826c\\\",\\\"statusBar.debuggingForeground\\\":\\\"#fff\\\",\\\"statusBar.foreground\\\":\\\"#586069\\\",\\\"statusBar.noFolderBackground\\\":\\\"#fff\\\",\\\"statusBarItem.prominentBackground\\\":\\\"#e8eaed\\\",\\\"statusBarItem.remoteBackground\\\":\\\"#fff\\\",\\\"statusBarItem.remoteForeground\\\":\\\"#586069\\\",\\\"tab.activeBackground\\\":\\\"#fff\\\",\\\"tab.activeBorder\\\":\\\"#fff\\\",\\\"tab.activeBorderTop\\\":\\\"#f9826c\\\",\\\"tab.activeForeground\\\":\\\"#2f363d\\\",\\\"tab.border\\\":\\\"#e1e4e8\\\",\\\"tab.hoverBackground\\\":\\\"#fff\\\",\\\"tab.inactiveBackground\\\":\\\"#f6f8fa\\\",\\\"tab.inactiveForeground\\\":\\\"#6a737d\\\",\\\"tab.unfocusedActiveBorder\\\":\\\"#fff\\\",\\\"tab.unfocusedActiveBorderTop\\\":\\\"#e1e4e8\\\",\\\"tab.unfocusedHoverBackground\\\":\\\"#fff\\\",\\\"terminal.ansiBlack\\\":\\\"#24292e\\\",\\\"terminal.ansiBlue\\\":\\\"#0366d6\\\",\\\"terminal.ansiBrightBlack\\\":\\\"#959da5\\\",\\\"terminal.ansiBrightBlue\\\":\\\"#005cc5\\\",\\\"terminal.ansiBrightCyan\\\":\\\"#3192aa\\\",\\\"terminal.ansiBrightGreen\\\":\\\"#22863a\\\",\\\"terminal.ansiBrightMagenta\\\":\\\"#5a32a3\\\",\\\"terminal.ansiBrightRed\\\":\\\"#cb2431\\\",\\\"terminal.ansiBrightWhite\\\":\\\"#d1d5da\\\",\\\"terminal.ansiBrightYellow\\\":\\\"#b08800\\\",\\\"terminal.ansiCyan\\\":\\\"#1b7c83\\\",\\\"terminal.ansiGreen\\\":\\\"#28a745\\\",\\\"terminal.ansiMagenta\\\":\\\"#5a32a3\\\",\\\"terminal.ansiRed\\\":\\\"#d73a49\\\",\\\"terminal.ansiWhite\\\":\\\"#6a737d\\\",\\\"terminal.ansiYellow\\\":\\\"#dbab09\\\",\\\"terminal.foreground\\\":\\\"#586069\\\",\\\"terminal.tab.activeBorder\\\":\\\"#f9826c\\\",\\\"terminalCursor.background\\\":\\\"#d1d5da\\\",\\\"terminalCursor.foreground\\\":\\\"#005cc5\\\",\\\"textBlockQuote.background\\\":\\\"#fafbfc\\\",\\\"textBlockQuote.border\\\":\\\"#e1e4e8\\\",\\\"textCodeBlock.background\\\":\\\"#f6f8fa\\\",\\\"textLink.activeForeground\\\":\\\"#005cc5\\\",\\\"textLink.foreground\\\":\\\"#0366d6\\\",\\\"textPreformat.foreground\\\":\\\"#586069\\\",\\\"textSeparator.foreground\\\":\\\"#d1d5da\\\",\\\"titleBar.activeBackground\\\":\\\"#fff\\\",\\\"titleBar.activeForeground\\\":\\\"#2f363d\\\",\\\"titleBar.border\\\":\\\"#e1e4e8\\\",\\\"titleBar.inactiveBackground\\\":\\\"#f6f8fa\\\",\\\"titleBar.inactiveForeground\\\":\\\"#6a737d\\\",\\\"tree.indentGuidesStroke\\\":\\\"#e1e4e8\\\",\\\"welcomePage.buttonBackground\\\":\\\"#f6f8fa\\\",\\\"welcomePage.buttonHoverBackground\\\":\\\"#e1e4e8\\\"},\\\"displayName\\\":\\\"GitHub Light\\\",\\\"name\\\":\\\"github-light\\\",\\\"semanticHighlighting\\\":true,\\\"tokenColors\\\":[{\\\"scope\\\":[\\\"comment\\\",\\\"punctuation.definition.comment\\\",\\\"string.comment\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#6a737d\\\"}},{\\\"scope\\\":[\\\"constant\\\",\\\"entity.name.constant\\\",\\\"variable.other.constant\\\",\\\"variable.other.enummember\\\",\\\"variable.language\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#005cc5\\\"}},{\\\"scope\\\":[\\\"entity\\\",\\\"entity.name\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#6f42c1\\\"}},{\\\"scope\\\":\\\"variable.parameter.function\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#24292e\\\"}},{\\\"scope\\\":\\\"entity.name.tag\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#22863a\\\"}},{\\\"scope\\\":\\\"keyword\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#d73a49\\\"}},{\\\"scope\\\":[\\\"storage\\\",\\\"storage.type\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#d73a49\\\"}},{\\\"scope\\\":[\\\"storage.modifier.package\\\",\\\"storage.modifier.import\\\",\\\"storage.type.java\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#24292e\\\"}},{\\\"scope\\\":[\\\"string\\\",\\\"punctuation.definition.string\\\",\\\"string punctuation.section.embedded source\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#032f62\\\"}},{\\\"scope\\\":\\\"support\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#005cc5\\\"}},{\\\"scope\\\":\\\"meta.property-name\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#005cc5\\\"}},{\\\"scope\\\":\\\"variable\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#e36209\\\"}},{\\\"scope\\\":\\\"variable.other\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#24292e\\\"}},{\\\"scope\\\":\\\"invalid.broken\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#b31d28\\\"}},{\\\"scope\\\":\\\"invalid.deprecated\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#b31d28\\\"}},{\\\"scope\\\":\\\"invalid.illegal\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#b31d28\\\"}},{\\\"scope\\\":\\\"invalid.unimplemented\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#b31d28\\\"}},{\\\"scope\\\":\\\"carriage-return\\\",\\\"settings\\\":{\\\"background\\\":\\\"#d73a49\\\",\\\"content\\\":\\\"^M\\\",\\\"fontStyle\\\":\\\"italic underline\\\",\\\"foreground\\\":\\\"#fafbfc\\\"}},{\\\"scope\\\":\\\"message.error\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#b31d28\\\"}},{\\\"scope\\\":\\\"string variable\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#005cc5\\\"}},{\\\"scope\\\":[\\\"source.regexp\\\",\\\"string.regexp\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#032f62\\\"}},{\\\"scope\\\":[\\\"string.regexp.character-class\\\",\\\"string.regexp constant.character.escape\\\",\\\"string.regexp source.ruby.embedded\\\",\\\"string.regexp string.regexp.arbitrary-repitition\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#032f62\\\"}},{\\\"scope\\\":\\\"string.regexp constant.character.escape\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#22863a\\\"}},{\\\"scope\\\":\\\"support.constant\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#005cc5\\\"}},{\\\"scope\\\":\\\"support.variable\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#005cc5\\\"}},{\\\"scope\\\":\\\"meta.module-reference\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#005cc5\\\"}},{\\\"scope\\\":\\\"punctuation.definition.list.begin.markdown\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#e36209\\\"}},{\\\"scope\\\":[\\\"markup.heading\\\",\\\"markup.heading entity.name\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#005cc5\\\"}},{\\\"scope\\\":\\\"markup.quote\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#22863a\\\"}},{\\\"scope\\\":\\\"markup.italic\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#24292e\\\"}},{\\\"scope\\\":\\\"markup.bold\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#24292e\\\"}},{\\\"scope\\\":[\\\"markup.underline\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"underline\\\"}},{\\\"scope\\\":[\\\"markup.strikethrough\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"strikethrough\\\"}},{\\\"scope\\\":\\\"markup.inline.raw\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#005cc5\\\"}},{\\\"scope\\\":[\\\"markup.deleted\\\",\\\"meta.diff.header.from-file\\\",\\\"punctuation.definition.deleted\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#ffeef0\\\",\\\"foreground\\\":\\\"#b31d28\\\"}},{\\\"scope\\\":[\\\"markup.inserted\\\",\\\"meta.diff.header.to-file\\\",\\\"punctuation.definition.inserted\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#f0fff4\\\",\\\"foreground\\\":\\\"#22863a\\\"}},{\\\"scope\\\":[\\\"markup.changed\\\",\\\"punctuation.definition.changed\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#ffebda\\\",\\\"foreground\\\":\\\"#e36209\\\"}},{\\\"scope\\\":[\\\"markup.ignored\\\",\\\"markup.untracked\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#005cc5\\\",\\\"foreground\\\":\\\"#f6f8fa\\\"}},{\\\"scope\\\":\\\"meta.diff.range\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#6f42c1\\\"}},{\\\"scope\\\":\\\"meta.diff.header\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#005cc5\\\"}},{\\\"scope\\\":\\\"meta.separator\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#005cc5\\\"}},{\\\"scope\\\":\\\"meta.output\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#005cc5\\\"}},{\\\"scope\\\":[\\\"brackethighlighter.tag\\\",\\\"brackethighlighter.curly\\\",\\\"brackethighlighter.round\\\",\\\"brackethighlighter.square\\\",\\\"brackethighlighter.angle\\\",\\\"brackethighlighter.quote\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#586069\\\"}},{\\\"scope\\\":\\\"brackethighlighter.unmatched\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#b31d28\\\"}},{\\\"scope\\\":[\\\"constant.other.reference.link\\\",\\\"string.other.link\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"underline\\\",\\\"foreground\\\":\\\"#032f62\\\"}}],\\\"type\\\":\\\"light\\\"}\"))\n","/* Theme: github-dark */\nexport default Object.freeze(JSON.parse(\"{\\\"colors\\\":{\\\"activityBar.activeBorder\\\":\\\"#f9826c\\\",\\\"activityBar.background\\\":\\\"#24292e\\\",\\\"activityBar.border\\\":\\\"#1b1f23\\\",\\\"activityBar.foreground\\\":\\\"#e1e4e8\\\",\\\"activityBar.inactiveForeground\\\":\\\"#6a737d\\\",\\\"activityBarBadge.background\\\":\\\"#0366d6\\\",\\\"activityBarBadge.foreground\\\":\\\"#fff\\\",\\\"badge.background\\\":\\\"#044289\\\",\\\"badge.foreground\\\":\\\"#c8e1ff\\\",\\\"breadcrumb.activeSelectionForeground\\\":\\\"#d1d5da\\\",\\\"breadcrumb.focusForeground\\\":\\\"#e1e4e8\\\",\\\"breadcrumb.foreground\\\":\\\"#959da5\\\",\\\"breadcrumbPicker.background\\\":\\\"#2b3036\\\",\\\"button.background\\\":\\\"#176f2c\\\",\\\"button.foreground\\\":\\\"#dcffe4\\\",\\\"button.hoverBackground\\\":\\\"#22863a\\\",\\\"button.secondaryBackground\\\":\\\"#444d56\\\",\\\"button.secondaryForeground\\\":\\\"#fff\\\",\\\"button.secondaryHoverBackground\\\":\\\"#586069\\\",\\\"checkbox.background\\\":\\\"#444d56\\\",\\\"checkbox.border\\\":\\\"#1b1f23\\\",\\\"debugToolBar.background\\\":\\\"#2b3036\\\",\\\"descriptionForeground\\\":\\\"#959da5\\\",\\\"diffEditor.insertedTextBackground\\\":\\\"#28a74530\\\",\\\"diffEditor.removedTextBackground\\\":\\\"#d73a4930\\\",\\\"dropdown.background\\\":\\\"#2f363d\\\",\\\"dropdown.border\\\":\\\"#1b1f23\\\",\\\"dropdown.foreground\\\":\\\"#e1e4e8\\\",\\\"dropdown.listBackground\\\":\\\"#24292e\\\",\\\"editor.background\\\":\\\"#24292e\\\",\\\"editor.findMatchBackground\\\":\\\"#ffd33d44\\\",\\\"editor.findMatchHighlightBackground\\\":\\\"#ffd33d22\\\",\\\"editor.focusedStackFrameHighlightBackground\\\":\\\"#2b6a3033\\\",\\\"editor.foldBackground\\\":\\\"#58606915\\\",\\\"editor.foreground\\\":\\\"#e1e4e8\\\",\\\"editor.inactiveSelectionBackground\\\":\\\"#3392FF22\\\",\\\"editor.lineHighlightBackground\\\":\\\"#2b3036\\\",\\\"editor.linkedEditingBackground\\\":\\\"#3392FF22\\\",\\\"editor.selectionBackground\\\":\\\"#3392FF44\\\",\\\"editor.selectionHighlightBackground\\\":\\\"#17E5E633\\\",\\\"editor.selectionHighlightBorder\\\":\\\"#17E5E600\\\",\\\"editor.stackFrameHighlightBackground\\\":\\\"#C6902625\\\",\\\"editor.wordHighlightBackground\\\":\\\"#17E5E600\\\",\\\"editor.wordHighlightBorder\\\":\\\"#17E5E699\\\",\\\"editor.wordHighlightStrongBackground\\\":\\\"#17E5E600\\\",\\\"editor.wordHighlightStrongBorder\\\":\\\"#17E5E666\\\",\\\"editorBracketHighlight.foreground1\\\":\\\"#79b8ff\\\",\\\"editorBracketHighlight.foreground2\\\":\\\"#ffab70\\\",\\\"editorBracketHighlight.foreground3\\\":\\\"#b392f0\\\",\\\"editorBracketHighlight.foreground4\\\":\\\"#79b8ff\\\",\\\"editorBracketHighlight.foreground5\\\":\\\"#ffab70\\\",\\\"editorBracketHighlight.foreground6\\\":\\\"#b392f0\\\",\\\"editorBracketMatch.background\\\":\\\"#17E5E650\\\",\\\"editorBracketMatch.border\\\":\\\"#17E5E600\\\",\\\"editorCursor.foreground\\\":\\\"#c8e1ff\\\",\\\"editorError.foreground\\\":\\\"#f97583\\\",\\\"editorGroup.border\\\":\\\"#1b1f23\\\",\\\"editorGroupHeader.tabsBackground\\\":\\\"#1f2428\\\",\\\"editorGroupHeader.tabsBorder\\\":\\\"#1b1f23\\\",\\\"editorGutter.addedBackground\\\":\\\"#28a745\\\",\\\"editorGutter.deletedBackground\\\":\\\"#ea4a5a\\\",\\\"editorGutter.modifiedBackground\\\":\\\"#2188ff\\\",\\\"editorIndentGuide.activeBackground\\\":\\\"#444d56\\\",\\\"editorIndentGuide.background\\\":\\\"#2f363d\\\",\\\"editorLineNumber.activeForeground\\\":\\\"#e1e4e8\\\",\\\"editorLineNumber.foreground\\\":\\\"#444d56\\\",\\\"editorOverviewRuler.border\\\":\\\"#1b1f23\\\",\\\"editorWarning.foreground\\\":\\\"#ffea7f\\\",\\\"editorWhitespace.foreground\\\":\\\"#444d56\\\",\\\"editorWidget.background\\\":\\\"#1f2428\\\",\\\"errorForeground\\\":\\\"#f97583\\\",\\\"focusBorder\\\":\\\"#005cc5\\\",\\\"foreground\\\":\\\"#d1d5da\\\",\\\"gitDecoration.addedResourceForeground\\\":\\\"#34d058\\\",\\\"gitDecoration.conflictingResourceForeground\\\":\\\"#ffab70\\\",\\\"gitDecoration.deletedResourceForeground\\\":\\\"#ea4a5a\\\",\\\"gitDecoration.ignoredResourceForeground\\\":\\\"#6a737d\\\",\\\"gitDecoration.modifiedResourceForeground\\\":\\\"#79b8ff\\\",\\\"gitDecoration.submoduleResourceForeground\\\":\\\"#6a737d\\\",\\\"gitDecoration.untrackedResourceForeground\\\":\\\"#34d058\\\",\\\"input.background\\\":\\\"#2f363d\\\",\\\"input.border\\\":\\\"#1b1f23\\\",\\\"input.foreground\\\":\\\"#e1e4e8\\\",\\\"input.placeholderForeground\\\":\\\"#959da5\\\",\\\"list.activeSelectionBackground\\\":\\\"#39414a\\\",\\\"list.activeSelectionForeground\\\":\\\"#e1e4e8\\\",\\\"list.focusBackground\\\":\\\"#044289\\\",\\\"list.hoverBackground\\\":\\\"#282e34\\\",\\\"list.hoverForeground\\\":\\\"#e1e4e8\\\",\\\"list.inactiveFocusBackground\\\":\\\"#1d2d3e\\\",\\\"list.inactiveSelectionBackground\\\":\\\"#282e34\\\",\\\"list.inactiveSelectionForeground\\\":\\\"#e1e4e8\\\",\\\"notificationCenterHeader.background\\\":\\\"#24292e\\\",\\\"notificationCenterHeader.foreground\\\":\\\"#959da5\\\",\\\"notifications.background\\\":\\\"#2f363d\\\",\\\"notifications.border\\\":\\\"#1b1f23\\\",\\\"notifications.foreground\\\":\\\"#e1e4e8\\\",\\\"notificationsErrorIcon.foreground\\\":\\\"#ea4a5a\\\",\\\"notificationsInfoIcon.foreground\\\":\\\"#79b8ff\\\",\\\"notificationsWarningIcon.foreground\\\":\\\"#ffab70\\\",\\\"panel.background\\\":\\\"#1f2428\\\",\\\"panel.border\\\":\\\"#1b1f23\\\",\\\"panelInput.border\\\":\\\"#2f363d\\\",\\\"panelTitle.activeBorder\\\":\\\"#f9826c\\\",\\\"panelTitle.activeForeground\\\":\\\"#e1e4e8\\\",\\\"panelTitle.inactiveForeground\\\":\\\"#959da5\\\",\\\"peekViewEditor.background\\\":\\\"#1f242888\\\",\\\"peekViewEditor.matchHighlightBackground\\\":\\\"#ffd33d33\\\",\\\"peekViewResult.background\\\":\\\"#1f2428\\\",\\\"peekViewResult.matchHighlightBackground\\\":\\\"#ffd33d33\\\",\\\"pickerGroup.border\\\":\\\"#444d56\\\",\\\"pickerGroup.foreground\\\":\\\"#e1e4e8\\\",\\\"progressBar.background\\\":\\\"#0366d6\\\",\\\"quickInput.background\\\":\\\"#24292e\\\",\\\"quickInput.foreground\\\":\\\"#e1e4e8\\\",\\\"scrollbar.shadow\\\":\\\"#0008\\\",\\\"scrollbarSlider.activeBackground\\\":\\\"#6a737d88\\\",\\\"scrollbarSlider.background\\\":\\\"#6a737d33\\\",\\\"scrollbarSlider.hoverBackground\\\":\\\"#6a737d44\\\",\\\"settings.headerForeground\\\":\\\"#e1e4e8\\\",\\\"settings.modifiedItemIndicator\\\":\\\"#0366d6\\\",\\\"sideBar.background\\\":\\\"#1f2428\\\",\\\"sideBar.border\\\":\\\"#1b1f23\\\",\\\"sideBar.foreground\\\":\\\"#d1d5da\\\",\\\"sideBarSectionHeader.background\\\":\\\"#1f2428\\\",\\\"sideBarSectionHeader.border\\\":\\\"#1b1f23\\\",\\\"sideBarSectionHeader.foreground\\\":\\\"#e1e4e8\\\",\\\"sideBarTitle.foreground\\\":\\\"#e1e4e8\\\",\\\"statusBar.background\\\":\\\"#24292e\\\",\\\"statusBar.border\\\":\\\"#1b1f23\\\",\\\"statusBar.debuggingBackground\\\":\\\"#931c06\\\",\\\"statusBar.debuggingForeground\\\":\\\"#fff\\\",\\\"statusBar.foreground\\\":\\\"#d1d5da\\\",\\\"statusBar.noFolderBackground\\\":\\\"#24292e\\\",\\\"statusBarItem.prominentBackground\\\":\\\"#282e34\\\",\\\"statusBarItem.remoteBackground\\\":\\\"#24292e\\\",\\\"statusBarItem.remoteForeground\\\":\\\"#d1d5da\\\",\\\"tab.activeBackground\\\":\\\"#24292e\\\",\\\"tab.activeBorder\\\":\\\"#24292e\\\",\\\"tab.activeBorderTop\\\":\\\"#f9826c\\\",\\\"tab.activeForeground\\\":\\\"#e1e4e8\\\",\\\"tab.border\\\":\\\"#1b1f23\\\",\\\"tab.hoverBackground\\\":\\\"#24292e\\\",\\\"tab.inactiveBackground\\\":\\\"#1f2428\\\",\\\"tab.inactiveForeground\\\":\\\"#959da5\\\",\\\"tab.unfocusedActiveBorder\\\":\\\"#24292e\\\",\\\"tab.unfocusedActiveBorderTop\\\":\\\"#1b1f23\\\",\\\"tab.unfocusedHoverBackground\\\":\\\"#24292e\\\",\\\"terminal.ansiBlack\\\":\\\"#586069\\\",\\\"terminal.ansiBlue\\\":\\\"#2188ff\\\",\\\"terminal.ansiBrightBlack\\\":\\\"#959da5\\\",\\\"terminal.ansiBrightBlue\\\":\\\"#79b8ff\\\",\\\"terminal.ansiBrightCyan\\\":\\\"#56d4dd\\\",\\\"terminal.ansiBrightGreen\\\":\\\"#85e89d\\\",\\\"terminal.ansiBrightMagenta\\\":\\\"#b392f0\\\",\\\"terminal.ansiBrightRed\\\":\\\"#f97583\\\",\\\"terminal.ansiBrightWhite\\\":\\\"#fafbfc\\\",\\\"terminal.ansiBrightYellow\\\":\\\"#ffea7f\\\",\\\"terminal.ansiCyan\\\":\\\"#39c5cf\\\",\\\"terminal.ansiGreen\\\":\\\"#34d058\\\",\\\"terminal.ansiMagenta\\\":\\\"#b392f0\\\",\\\"terminal.ansiRed\\\":\\\"#ea4a5a\\\",\\\"terminal.ansiWhite\\\":\\\"#d1d5da\\\",\\\"terminal.ansiYellow\\\":\\\"#ffea7f\\\",\\\"terminal.foreground\\\":\\\"#d1d5da\\\",\\\"terminal.tab.activeBorder\\\":\\\"#f9826c\\\",\\\"terminalCursor.background\\\":\\\"#586069\\\",\\\"terminalCursor.foreground\\\":\\\"#79b8ff\\\",\\\"textBlockQuote.background\\\":\\\"#24292e\\\",\\\"textBlockQuote.border\\\":\\\"#444d56\\\",\\\"textCodeBlock.background\\\":\\\"#2f363d\\\",\\\"textLink.activeForeground\\\":\\\"#c8e1ff\\\",\\\"textLink.foreground\\\":\\\"#79b8ff\\\",\\\"textPreformat.foreground\\\":\\\"#d1d5da\\\",\\\"textSeparator.foreground\\\":\\\"#586069\\\",\\\"titleBar.activeBackground\\\":\\\"#24292e\\\",\\\"titleBar.activeForeground\\\":\\\"#e1e4e8\\\",\\\"titleBar.border\\\":\\\"#1b1f23\\\",\\\"titleBar.inactiveBackground\\\":\\\"#1f2428\\\",\\\"titleBar.inactiveForeground\\\":\\\"#959da5\\\",\\\"tree.indentGuidesStroke\\\":\\\"#2f363d\\\",\\\"welcomePage.buttonBackground\\\":\\\"#2f363d\\\",\\\"welcomePage.buttonHoverBackground\\\":\\\"#444d56\\\"},\\\"displayName\\\":\\\"GitHub Dark\\\",\\\"name\\\":\\\"github-dark\\\",\\\"semanticHighlighting\\\":true,\\\"tokenColors\\\":[{\\\"scope\\\":[\\\"comment\\\",\\\"punctuation.definition.comment\\\",\\\"string.comment\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#6a737d\\\"}},{\\\"scope\\\":[\\\"constant\\\",\\\"entity.name.constant\\\",\\\"variable.other.constant\\\",\\\"variable.other.enummember\\\",\\\"variable.language\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#79b8ff\\\"}},{\\\"scope\\\":[\\\"entity\\\",\\\"entity.name\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#b392f0\\\"}},{\\\"scope\\\":\\\"variable.parameter.function\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#e1e4e8\\\"}},{\\\"scope\\\":\\\"entity.name.tag\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#85e89d\\\"}},{\\\"scope\\\":\\\"keyword\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#f97583\\\"}},{\\\"scope\\\":[\\\"storage\\\",\\\"storage.type\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#f97583\\\"}},{\\\"scope\\\":[\\\"storage.modifier.package\\\",\\\"storage.modifier.import\\\",\\\"storage.type.java\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#e1e4e8\\\"}},{\\\"scope\\\":[\\\"string\\\",\\\"punctuation.definition.string\\\",\\\"string punctuation.section.embedded source\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#9ecbff\\\"}},{\\\"scope\\\":\\\"support\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79b8ff\\\"}},{\\\"scope\\\":\\\"meta.property-name\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79b8ff\\\"}},{\\\"scope\\\":\\\"variable\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#ffab70\\\"}},{\\\"scope\\\":\\\"variable.other\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#e1e4e8\\\"}},{\\\"scope\\\":\\\"invalid.broken\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#fdaeb7\\\"}},{\\\"scope\\\":\\\"invalid.deprecated\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#fdaeb7\\\"}},{\\\"scope\\\":\\\"invalid.illegal\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#fdaeb7\\\"}},{\\\"scope\\\":\\\"invalid.unimplemented\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#fdaeb7\\\"}},{\\\"scope\\\":\\\"carriage-return\\\",\\\"settings\\\":{\\\"background\\\":\\\"#f97583\\\",\\\"content\\\":\\\"^M\\\",\\\"fontStyle\\\":\\\"italic underline\\\",\\\"foreground\\\":\\\"#24292e\\\"}},{\\\"scope\\\":\\\"message.error\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#fdaeb7\\\"}},{\\\"scope\\\":\\\"string variable\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79b8ff\\\"}},{\\\"scope\\\":[\\\"source.regexp\\\",\\\"string.regexp\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#dbedff\\\"}},{\\\"scope\\\":[\\\"string.regexp.character-class\\\",\\\"string.regexp constant.character.escape\\\",\\\"string.regexp source.ruby.embedded\\\",\\\"string.regexp string.regexp.arbitrary-repitition\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#dbedff\\\"}},{\\\"scope\\\":\\\"string.regexp constant.character.escape\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#85e89d\\\"}},{\\\"scope\\\":\\\"support.constant\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79b8ff\\\"}},{\\\"scope\\\":\\\"support.variable\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79b8ff\\\"}},{\\\"scope\\\":\\\"meta.module-reference\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79b8ff\\\"}},{\\\"scope\\\":\\\"punctuation.definition.list.begin.markdown\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#ffab70\\\"}},{\\\"scope\\\":[\\\"markup.heading\\\",\\\"markup.heading entity.name\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#79b8ff\\\"}},{\\\"scope\\\":\\\"markup.quote\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#85e89d\\\"}},{\\\"scope\\\":\\\"markup.italic\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#e1e4e8\\\"}},{\\\"scope\\\":\\\"markup.bold\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#e1e4e8\\\"}},{\\\"scope\\\":[\\\"markup.underline\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"underline\\\"}},{\\\"scope\\\":[\\\"markup.strikethrough\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"strikethrough\\\"}},{\\\"scope\\\":\\\"markup.inline.raw\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79b8ff\\\"}},{\\\"scope\\\":[\\\"markup.deleted\\\",\\\"meta.diff.header.from-file\\\",\\\"punctuation.definition.deleted\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#86181d\\\",\\\"foreground\\\":\\\"#fdaeb7\\\"}},{\\\"scope\\\":[\\\"markup.inserted\\\",\\\"meta.diff.header.to-file\\\",\\\"punctuation.definition.inserted\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#144620\\\",\\\"foreground\\\":\\\"#85e89d\\\"}},{\\\"scope\\\":[\\\"markup.changed\\\",\\\"punctuation.definition.changed\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#c24e00\\\",\\\"foreground\\\":\\\"#ffab70\\\"}},{\\\"scope\\\":[\\\"markup.ignored\\\",\\\"markup.untracked\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#79b8ff\\\",\\\"foreground\\\":\\\"#2f363d\\\"}},{\\\"scope\\\":\\\"meta.diff.range\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#b392f0\\\"}},{\\\"scope\\\":\\\"meta.diff.header\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79b8ff\\\"}},{\\\"scope\\\":\\\"meta.separator\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#79b8ff\\\"}},{\\\"scope\\\":\\\"meta.output\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79b8ff\\\"}},{\\\"scope\\\":[\\\"brackethighlighter.tag\\\",\\\"brackethighlighter.curly\\\",\\\"brackethighlighter.round\\\",\\\"brackethighlighter.square\\\",\\\"brackethighlighter.angle\\\",\\\"brackethighlighter.quote\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#d1d5da\\\"}},{\\\"scope\\\":\\\"brackethighlighter.unmatched\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#fdaeb7\\\"}},{\\\"scope\\\":[\\\"constant.other.reference.link\\\",\\\"string.other.link\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"underline\\\",\\\"foreground\\\":\\\"#dbedff\\\"}}],\\\"type\\\":\\\"dark\\\"}\"))\n","import { h as a } from \"./StreamMarkdown-BUAEdLZw.js\";\nimport { b as r, C as g, a as o, D as t, G as n, M as u, S as k, g as h, f as l, l as L, p as S, c as d, r as p, d as B, e as C, u as c } from \"./StreamMarkdown-BUAEdLZw.js\";\na();\nexport {\n  r as CODE_BLOCK_META_KEY,\n  g as CodeBlock,\n  o as CopyButton,\n  t as DownloadButton,\n  n as GLOBAL_CODE_BLOCK_ACTIONS,\n  u as MermaidBlock,\n  k as StreamMarkdown,\n  h as clearRegisteredShikiLanguages,\n  l as excludeShikiLanguages,\n  L as loadRegisteredShikiLanguage,\n  S as parseBlocks,\n  d as parseIncompleteMarkdown,\n  a as registerDefaultShikiLanguages,\n  p as registerShikiLanguage,\n  B as registerShikiLanguages,\n  C as unregisterShikiLanguage,\n  c as useShikiHighlighter\n};\n","<script setup lang=\"ts\">\nimport { computed, shallowRef } from \"vue\";\nimport { FlaskConical, X, FileText, LogOut, SquarePen } from \"lucide-vue-next\";\nimport { AlertDialogRoot, AlertDialogTrigger, AlertDialogPortal, AlertDialogOverlay, AlertDialogContent, AlertDialogTitle, AlertDialogDescription, AlertDialogCancel } from \"reka-ui\";\nimport { logout } from \"../lib/runtime\";\nimport ThemeToggle from \"./ThemeToggle.vue\";\nimport FieldError from \"./FieldError.vue\";\n\nconst props = defineProps<{\n  active: boolean;\n  activeConversationTitle?: string;\n  chats: Array<{ id: string; title: string; updatedAt: number }>;\n  currentChatId: string;\n  busy: boolean;\n}>();\ndefineEmits<{\n  (e: \"select-chat\", id: string): void;\n  (e: \"new-chat\"): void;\n  (e: \"start-test-mode\"): void;\n  (e: \"stop-test-mode\"): void;\n  (e: \"show-prompt\"): void;\n}>();\n\nconst sortedChats = computed(() => [...props.chats].sort((a, b) => b.updatedAt - a.updatedAt));\nconst logoutOpen = shallowRef(false);\nconst loggingOut = shallowRef(false);\nconst logoutError = shallowRef(\"\");\n\nasync function handleLogout() {\n  if (loggingOut.value || !logoutOpen.value) return;\n  loggingOut.value = true;\n  logoutError.value = \"\";\n  try {\n    await logout();\n  } catch {\n    logoutError.value = \"Uitloggen is niet gelukt. Probeer het opnieuw.\";\n    loggingOut.value = false;\n  }\n}\n</script>\n\n<template>\n  <div class=\"sidebar-navigation\">\n    <div class=\"sidebar__section\">\n      <button type=\"button\" class=\"sidebar__btn sidebar__btn--secondary\" :disabled=\"busy\" @click=\"$emit('new-chat')\">\n        <SquarePen :size=\"17\" aria-hidden=\"true\" /> Nieuw gesprek\n      </button>\n    </div>\n    <nav class=\"sidebar__chats\" aria-label=\"Jouw chats\">\n      <h2 class=\"sidebar__chats-heading\">Jouw chats</h2>\n      <ul v-if=\"sortedChats.length\" class=\"sidebar__chat-list\">\n        <li v-for=\"chat in sortedChats\" :key=\"chat.id\">\n          <button\n            type=\"button\"\n            class=\"sidebar__chat\"\n            :class=\"{ 'sidebar__chat--active': !active && chat.id === currentChatId }\"\n            :aria-current=\"!active && chat.id === currentChatId ? 'page' : undefined\"\n            :title=\"chat.title\"\n            :disabled=\"busy\"\n            @click=\"$emit('select-chat', chat.id)\"\n          >\n            {{ chat.title }}\n          </button>\n        </li>\n      </ul>\n      <p v-else class=\"sidebar__empty\">Je gesprekken verschijnen hier zodra je een vraag stelt.</p>\n    </nav>\n    <div class=\"sidebar__section\">\n      <template v-if=\"active\">\n        <div class=\"sidebar__badge-box\">\n          <span class=\"sidebar__badge\"><FlaskConical :size=\"12\" /> Testmodus actief</span>\n          <p v-if=\"activeConversationTitle\" class=\"sidebar__convtitle\">{{ activeConversationTitle }}</p>\n        </div>\n        <button type=\"button\" class=\"sidebar__btn sidebar__btn--outline\" :disabled=\"busy\" @click=\"$emit('stop-test-mode')\">\n          <X :size=\"14\" /> Testmodus verlaten\n        </button>\n      </template>\n      <button v-else type=\"button\" class=\"sidebar__btn sidebar__btn--secondary\" :disabled=\"busy\" @click=\"$emit('start-test-mode')\">\n        <FlaskConical :size=\"14\" /> Testmodus starten\n      </button>\n    </div>\n\n    <div class=\"sidebar__section\">\n      <button type=\"button\" class=\"sidebar__btn sidebar__btn--ghost\" @click=\"$emit('show-prompt')\">\n        <FileText :size=\"14\" /> Bekijk prompt\n      </button>\n    </div>\n\n    <div class=\"sidebar__footer\">\n      <ThemeToggle />\n      <AlertDialogRoot v-model:open=\"logoutOpen\">\n        <AlertDialogTrigger class=\"sidebar__btn sidebar__btn--ghost sidebar__logout\" @click=\"logoutError = ''\">\n          <LogOut :size=\"16\" aria-hidden=\"true\" /> Uitloggen\n        </AlertDialogTrigger>\n        <AlertDialogPortal>\n          <AlertDialogOverlay class=\"logout-dialog__overlay\" />\n          <AlertDialogContent class=\"logout-dialog\" @escape-key-down=\"loggingOut && $event.preventDefault()\">\n            <AlertDialogTitle class=\"logout-dialog__title\">Uitloggen?</AlertDialogTitle>\n            <AlertDialogDescription class=\"logout-dialog__description\">\n              Weet je zeker dat je wilt uitloggen bij BTW Coach?\n            </AlertDialogDescription>\n            <FieldError v-if=\"logoutError\">{{ logoutError }}</FieldError>\n            <div class=\"logout-dialog__actions\">\n              <AlertDialogCancel class=\"logout-dialog__button\" :disabled=\"loggingOut\">Annuleren</AlertDialogCancel>\n              <button type=\"button\" class=\"logout-dialog__button logout-dialog__button--confirm\" :disabled=\"loggingOut\" :aria-busy=\"loggingOut\" @click=\"handleLogout\">\n                {{ loggingOut ? \"Uitloggen…\" : \"Uitloggen\" }}\n              </button>\n            </div>\n          </AlertDialogContent>\n        </AlertDialogPortal>\n      </AlertDialogRoot>\n    </div>\n  </div>\n</template>\n\n<style scoped>\n.sidebar__section {\n  padding: 14px 16px 0;\n  display: flex;\n  flex-direction: column;\n  gap: 10px;\n}\n.sidebar__footer {\n  display: flex;\n  flex-wrap: wrap;\n  align-items: center;\n  gap: 8px;\n  padding: 16px;\n  border-top: 1px solid var(--btw-line);\n}\n.sidebar__btn.sidebar__logout { width: auto; flex: 0 0 auto; margin-left: auto; padding: 0 10px; white-space: nowrap; }\n.sidebar__logout:focus-visible { outline: 2px solid var(--btw-accent); outline-offset: 2px; }\n.sidebar__logout:active { transform: translateY(1px); }\n.sidebar__logout:disabled { cursor: wait; opacity: 0.6; }\n.logout-dialog__overlay {\n  position: fixed;\n  inset: 0;\n  z-index: 100;\n  background: rgba(0, 0, 0, 0.45);\n  backdrop-filter: blur(2px);\n}\n.logout-dialog {\n  pointer-events: auto;\n  position: fixed;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  z-index: 101;\n  box-sizing: border-box;\n  width: min(400px, calc(100vw - 32px));\n  padding: 24px;\n  border: 1px solid var(--btw-line);\n  border-radius: 16px;\n  background: var(--btw-surface);\n  color: var(--btw-fg);\n  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.25);\n}\n.logout-dialog__title { margin: 0; font-size: 20px; font-weight: 700; }\n.logout-dialog__description { margin: 12px 0 24px; color: var(--btw-fg-muted); line-height: 1.5; }\n.logout-dialog__actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }\n.logout-dialog__button {\n  min-height: 40px;\n  padding: 0 16px;\n  border: 1px solid var(--btw-line);\n  border-radius: 10px;\n  background: var(--btw-surface-2);\n  color: var(--btw-fg);\n  font: inherit;\n  font-weight: 600;\n  cursor: pointer;\n}\n.logout-dialog__button:hover { background: var(--btw-surface-3); }\n.logout-dialog__button--confirm { background: var(--btw-accent); color: white; border-color: transparent; }\n.logout-dialog__button--confirm:hover { background: var(--btw-accent-hover, var(--btw-accent)); filter: brightness(0.95); }\n.logout-dialog__button:focus-visible { outline: 2px solid var(--btw-accent); outline-offset: 3px; }\n.logout-dialog__button:active { transform: translateY(1px); }\n.logout-dialog__button:disabled { cursor: wait; opacity: 0.6; }\n.sidebar__badge-box {\n  padding: 12px;\n  border-radius: 12px;\n  background: var(--btw-accent-soft);\n}\n.sidebar__badge {\n  display: inline-flex;\n  align-items: center;\n  gap: 5px;\n  font-size: 11.5px;\n  font-weight: 600;\n  color: var(--btw-accent);\n}\n.sidebar__convtitle {\n  margin: 6px 0 0;\n  font-size: 12px;\n  color: var(--btw-fg-muted);\n}\n.sidebar__btn {\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  gap: 6px;\n  width: 100%;\n  height: 36px;\n  border-radius: 10px;\n  border: 1px solid transparent;\n  font-size: 13px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: background 0.12s, color 0.12s, border-color 0.12s;\n}\n.sidebar__btn--secondary {\n  background: var(--btw-surface-2);\n  color: var(--btw-fg);\n}\n.sidebar__btn--secondary:hover { background: var(--btw-surface-3); }\n.sidebar__btn--outline {\n  background: transparent;\n  border-color: var(--btw-line-strong);\n  color: var(--btw-fg-muted);\n}\n.sidebar__btn--outline:hover { color: var(--btw-fg); border-color: var(--btw-fg-subtle); }\n.sidebar__btn--ghost {\n  justify-content: flex-start;\n  background: transparent;\n  color: var(--btw-fg-muted);\n}\n.sidebar__btn--ghost:hover { background: var(--btw-surface-2); color: var(--btw-fg); }\n.sidebar__btn--ghost.sidebar__logout { justify-content: flex-end; }\n\n\n.sidebar-navigation { display: flex; flex-direction: column; flex: 1; min-height: 0; overflow: hidden; }\n.sidebar__chats { flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: 22px 10px 12px; }\n.sidebar__chats-heading { margin: 0 8px 8px; color: var(--btw-fg-subtle); font-size: 12px; font-weight: 500; }\n.sidebar__chat-list { list-style: none; padding: 0; margin: 0; }\n.sidebar__chat { display: block; width: 100%; min-height: 40px; padding: 10px; border: 0; border-radius: 9px; background: transparent; color: var(--btw-fg-muted); font: inherit; font-size: 13px; text-align: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; }\n.sidebar__chat:hover { background: var(--btw-surface-2); color: var(--btw-fg); }\n.sidebar__chat--active { background: var(--btw-surface-3); color: var(--btw-fg); font-weight: 600; }\n.sidebar__empty { margin: 0 8px; color: var(--btw-fg-subtle); font-size: 12px; line-height: 1.6; }\n.sidebar__btn:focus-visible, .sidebar__chat:focus-visible { outline: 2px solid var(--btw-accent); outline-offset: -2px; }\n.sidebar__btn:active, .sidebar__chat:active { transform: translateY(1px); }\n.sidebar__btn:disabled, .sidebar__chat:disabled { opacity: 0.5; cursor: not-allowed; }\n.sidebar__footer { flex-shrink: 0; margin-top: 14px; padding-bottom: max(16px, env(safe-area-inset-bottom)); }\n@media (max-width: 720px) {\n  .sidebar__btn, .sidebar__chat, .logout-dialog__button { min-height: 44px; }\n  .sidebar__footer :deep(.theme-toggle) { width: 44px; height: 44px; }\n}\n</style>\n","// Theme state: dark | light. Dark is the default (the app's identity). Persisted\n// in localStorage; falls back to the system `prefers-color-scheme` on first\n// load. `data-theme` on <html> drives the CSS variable switching in\n// frontend.scss (`:root` = dark, `[data-theme=\"light\"]` = light).\nimport { onBeforeUnmount, onMounted, readonly, ref } from \"vue\";\n\nconst STORAGE_KEY = \"btw:theme\";\nconst ATTR = \"data-theme\";\n\nexport type Theme = \"dark\" | \"light\";\n\nfunction readStored(): Theme | null {\n  try {\n    const v = localStorage.getItem(STORAGE_KEY);\n    return v === \"dark\" || v === \"light\" ? v : null;\n  } catch {\n    return null;\n  }\n}\n\nfunction prefersLight(): boolean {\n  return typeof window !== \"undefined\" && window.matchMedia(\"(prefers-color-scheme: light)\").matches;\n}\n\nfunction resolveInitialTheme(): Theme {\n  // Default to dark unless stored, or the system explicitly prefers light.\n  return readStored() ?? (prefersLight() ? \"light\" : \"dark\");\n}\n\nfunction apply(theme: Theme) {\n  document.documentElement.setAttribute(ATTR, theme);\n}\n\n// Sync init — call once from frontend.ts before Vue mounts so the first paint\n// matches the resolved theme.\nexport function initTheme(): void {\n  apply(resolveInitialTheme());\n}\n\nexport function useTheme() {\n  const theme = ref<Theme>((document.documentElement.getAttribute(ATTR) as Theme | null) ?? resolveInitialTheme());\n\n  function setTheme(next: Theme) {\n    theme.value = next;\n    apply(next);\n    try { localStorage.setItem(STORAGE_KEY, next); } catch { /* quota/denied — silent */ }\n  }\n\n  function toggleTheme() {\n    setTheme(theme.value === \"dark\" ? \"light\" : \"dark\");\n  }\n\n  const mq = typeof window !== \"undefined\" ? window.matchMedia(\"(prefers-color-scheme: light)\") : null;\n  function onSystemChange() {\n    if (readStored() !== null) return;\n    setThemeInternal(mq?.matches ? \"light\" : \"dark\");\n  }\n  function setThemeInternal(next: Theme) {\n    theme.value = next;\n    apply(next);\n  }\n\n  onMounted(() => {\n    mq?.addEventListener(\"change\", onSystemChange);\n  });\n  onBeforeUnmount(() => {\n    mq?.removeEventListener(\"change\", onSystemChange);\n  });\n\n  return {\n    theme: readonly(theme),\n    setTheme,\n    toggleTheme,\n  };\n}\n","<template>\n  <button\n    type=\"button\"\n    class=\"theme-toggle\"\n    :class=\"`theme-toggle--${theme}`\"\n    :aria-label=\"theme === 'dark' ? 'Schakel naar licht thema' : 'Schakel naar donker thema'\"\n    :title=\"theme === 'dark' ? 'Licht thema' : 'Donker thema'\"\n    @click=\"toggleTheme\"\n  >\n    <Sun v-if=\"theme === 'dark'\" :size=\"16\" />\n    <Moon v-else :size=\"16\" />\n  </button>\n</template>\n\n<script setup lang=\"ts\">\nimport { Sun, Moon } from \"lucide-vue-next\";\nimport { useTheme } from \"../lib/useTheme\";\n\nconst { theme, toggleTheme } = useTheme();\n</script>\n\n<style scoped>\n.theme-toggle {\n  display: grid;\n  place-items: center;\n  width: 34px;\n  height: 34px;\n  flex-shrink: 0;\n  border-radius: 99px;\n  border: 1px solid var(--btw-line);\n  background: var(--btw-glass);\n  backdrop-filter: blur(12px) saturate(140%);\n  -webkit-backdrop-filter: blur(12px) saturate(140%);\n  color: var(--btw-fg-muted);\n  cursor: pointer;\n  transition: background 0.18s var(--ease-out), color 0.18s var(--ease-out),\n    border-color 0.18s var(--ease-out), transform 0.15s var(--ease-spring);\n}\n.theme-toggle:hover {\n  color: var(--btw-accent);\n  border-color: var(--btw-accent-soft);\n  background: var(--btw-accent-soft);\n  transform: translateY(-1px);\n}\n.theme-toggle:active {\n  transform: translateY(0);\n}\n.theme-toggle--dark { color: var(--btw-golden); }\n.theme-toggle--light { color: var(--btw-fg-muted); }\n</style>\n","import { openBlock as _openBlock, createBlock as _createBlock, createCommentVNode as _createCommentVNode, normalizeClass as _normalizeClass, createElementBlock as _createElementBlock } from \"vue\"\n\nconst _hoisted_1 = [\"aria-label\", \"title\"]\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createElementBlock(\"button\", {\n    type: \"button\",\n    class: _normalizeClass([\"theme-toggle\", `theme-toggle--${$setup.theme}`]),\n    \"aria-label\": $setup.theme === 'dark' ? 'Schakel naar licht thema' : 'Schakel naar donker thema',\n    title: $setup.theme === 'dark' ? 'Licht thema' : 'Donker thema',\n    onClick: _cache[0] || (_cache[0] = (...args) => ($setup.toggleTheme && $setup.toggleTheme(...args)))\n  }, [\n    ($setup.theme === 'dark')\n      ? (_openBlock(), _createBlock($setup[\"Sun\"], {\n          key: 0,\n          size: 16\n        }))\n      : (_openBlock(), _createBlock($setup[\"Moon\"], {\n          key: 1,\n          size: 16\n        }))\n  ], 10 /* CLASS, PROPS */, _hoisted_1))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ThemeToggle.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ThemeToggle.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ThemeToggle.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ThemeToggle.vue\";script.__scopeId = \"data-v-a2a270f9\";export default script;","import { createVNode as _createVNode, renderSlot as _renderSlot, createElementVNode as _createElementVNode, openBlock as _openBlock, createElementBlock as _createElementBlock } from \"vue\"\n\nconst _hoisted_1 = {\n  class: \"fielderror\",\n  role: \"alert\"\n}\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createElementBlock(\"span\", _hoisted_1, [\n    _createVNode($setup[\"CircleAlert\"], {\n      size: 15,\n      class: \"fielderror__icon\"\n    }),\n    _createElementVNode(\"span\", null, [\n      _renderSlot(_ctx.$slots, \"default\", {}, undefined, true)\n    ])\n  ]))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/FieldError.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/FieldError.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/FieldError.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/FieldError.vue\";script.__scopeId = \"data-v-f8d5cea2\";export default script;","import { createVNode as _createVNode, createTextVNode as _createTextVNode, createElementVNode as _createElementVNode, renderList as _renderList, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock, toDisplayString as _toDisplayString, normalizeClass as _normalizeClass, createCommentVNode as _createCommentVNode, withCtx as _withCtx, createBlock as _createBlock } from \"vue\"\n\nconst _hoisted_1 = { class: \"sidebar-navigation\" }\nconst _hoisted_2 = { class: \"sidebar__section\" }\nconst _hoisted_3 = [\"disabled\"]\nconst _hoisted_4 = {\n  class: \"sidebar__chats\",\n  \"aria-label\": \"Jouw chats\"\n}\nconst _hoisted_5 = {\n  key: 0,\n  class: \"sidebar__chat-list\"\n}\nconst _hoisted_6 = [\"aria-current\", \"title\", \"disabled\", \"onClick\"]\nconst _hoisted_7 = {\n  key: 1,\n  class: \"sidebar__empty\"\n}\nconst _hoisted_8 = { class: \"sidebar__section\" }\nconst _hoisted_9 = { class: \"sidebar__badge-box\" }\nconst _hoisted_10 = { class: \"sidebar__badge\" }\nconst _hoisted_11 = {\n  key: 0,\n  class: \"sidebar__convtitle\"\n}\nconst _hoisted_12 = [\"disabled\"]\nconst _hoisted_13 = [\"disabled\"]\nconst _hoisted_14 = { class: \"sidebar__section\" }\nconst _hoisted_15 = { class: \"sidebar__footer\" }\nconst _hoisted_16 = { class: \"logout-dialog__actions\" }\nconst _hoisted_17 = [\"disabled\", \"aria-busy\"]\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createElementBlock(\"div\", _hoisted_1, [\n    _createElementVNode(\"div\", _hoisted_2, [\n      _createElementVNode(\"button\", {\n        type: \"button\",\n        class: \"sidebar__btn sidebar__btn--secondary\",\n        disabled: $props.busy,\n        onClick: _cache[0] || (_cache[0] = $event => (_ctx.$emit('new-chat')))\n      }, [\n        _createVNode($setup[\"SquarePen\"], {\n          size: 17,\n          \"aria-hidden\": \"true\"\n        }),\n        _cache[7] || (_cache[7] = _createTextVNode(\" Nieuw gesprek \", -1 /* CACHED */))\n      ], 8 /* PROPS */, _hoisted_3)\n    ]),\n    _createElementVNode(\"nav\", _hoisted_4, [\n      _cache[8] || (_cache[8] = _createElementVNode(\"h2\", { class: \"sidebar__chats-heading\" }, \"Jouw chats\", -1 /* CACHED */)),\n      ($setup.sortedChats.length)\n        ? (_openBlock(), _createElementBlock(\"ul\", _hoisted_5, [\n            (_openBlock(true), _createElementBlock(_Fragment, null, _renderList($setup.sortedChats, (chat) => {\n              return (_openBlock(), _createElementBlock(\"li\", {\n                key: chat.id\n              }, [\n                _createElementVNode(\"button\", {\n                  type: \"button\",\n                  class: _normalizeClass([\"sidebar__chat\", { 'sidebar__chat--active': !$props.active && chat.id === $props.currentChatId }]),\n                  \"aria-current\": !$props.active && chat.id === $props.currentChatId ? 'page' : undefined,\n                  title: chat.title,\n                  disabled: $props.busy,\n                  onClick: $event => (_ctx.$emit('select-chat', chat.id))\n                }, _toDisplayString(chat.title), 11 /* TEXT, CLASS, PROPS */, _hoisted_6)\n              ]))\n            }), 128 /* KEYED_FRAGMENT */))\n          ]))\n        : (_openBlock(), _createElementBlock(\"p\", _hoisted_7, \"Je gesprekken verschijnen hier zodra je een vraag stelt.\"))\n    ]),\n    _createElementVNode(\"div\", _hoisted_8, [\n      ($props.active)\n        ? (_openBlock(), _createElementBlock(_Fragment, { key: 0 }, [\n            _createElementVNode(\"div\", _hoisted_9, [\n              _createElementVNode(\"span\", _hoisted_10, [\n                _createVNode($setup[\"FlaskConical\"], { size: 12 }),\n                _cache[9] || (_cache[9] = _createTextVNode(\" Testmodus actief\", -1 /* CACHED */))\n              ]),\n              ($props.activeConversationTitle)\n                ? (_openBlock(), _createElementBlock(\"p\", _hoisted_11, _toDisplayString($props.activeConversationTitle), 1 /* TEXT */))\n                : _createCommentVNode(\"v-if\", true)\n            ]),\n            _createElementVNode(\"button\", {\n              type: \"button\",\n              class: \"sidebar__btn sidebar__btn--outline\",\n              disabled: $props.busy,\n              onClick: _cache[1] || (_cache[1] = $event => (_ctx.$emit('stop-test-mode')))\n            }, [\n              _createVNode($setup[\"X\"], { size: 14 }),\n              _cache[10] || (_cache[10] = _createTextVNode(\" Testmodus verlaten \", -1 /* CACHED */))\n            ], 8 /* PROPS */, _hoisted_12)\n          ], 64 /* STABLE_FRAGMENT */))\n        : (_openBlock(), _createElementBlock(\"button\", {\n            key: 1,\n            type: \"button\",\n            class: \"sidebar__btn sidebar__btn--secondary\",\n            disabled: $props.busy,\n            onClick: _cache[2] || (_cache[2] = $event => (_ctx.$emit('start-test-mode')))\n          }, [\n            _createVNode($setup[\"FlaskConical\"], { size: 14 }),\n            _cache[11] || (_cache[11] = _createTextVNode(\" Testmodus starten \", -1 /* CACHED */))\n          ], 8 /* PROPS */, _hoisted_13))\n    ]),\n    _createElementVNode(\"div\", _hoisted_14, [\n      _createElementVNode(\"button\", {\n        type: \"button\",\n        class: \"sidebar__btn sidebar__btn--ghost\",\n        onClick: _cache[3] || (_cache[3] = $event => (_ctx.$emit('show-prompt')))\n      }, [\n        _createVNode($setup[\"FileText\"], { size: 14 }),\n        _cache[12] || (_cache[12] = _createTextVNode(\" Bekijk prompt \", -1 /* CACHED */))\n      ])\n    ]),\n    _createElementVNode(\"div\", _hoisted_15, [\n      _createVNode($setup[\"ThemeToggle\"]),\n      _createVNode($setup[\"AlertDialogRoot\"], {\n        open: $setup.logoutOpen,\n        \"onUpdate:open\": _cache[6] || (_cache[6] = $event => (($setup.logoutOpen) = $event))\n      }, {\n        default: _withCtx(() => [\n          _createVNode($setup[\"AlertDialogTrigger\"], {\n            class: \"sidebar__btn sidebar__btn--ghost sidebar__logout\",\n            onClick: _cache[4] || (_cache[4] = $event => ($setup.logoutError = ''))\n          }, {\n            default: _withCtx(() => [\n              _createVNode($setup[\"LogOut\"], {\n                size: 16,\n                \"aria-hidden\": \"true\"\n              }),\n              _cache[13] || (_cache[13] = _createTextVNode(\" Uitloggen \", -1 /* CACHED */))\n            ]),\n            _: 1 /* STABLE */,\n            __: [13]\n          }),\n          _createVNode($setup[\"AlertDialogPortal\"], null, {\n            default: _withCtx(() => [\n              _createVNode($setup[\"AlertDialogOverlay\"], { class: \"logout-dialog__overlay\" }),\n              _createVNode($setup[\"AlertDialogContent\"], {\n                class: \"logout-dialog\",\n                onEscapeKeyDown: _cache[5] || (_cache[5] = $event => ($setup.loggingOut && $event.preventDefault()))\n              }, {\n                default: _withCtx(() => [\n                  _createVNode($setup[\"AlertDialogTitle\"], { class: \"logout-dialog__title\" }, {\n                    default: _withCtx(() => _cache[14] || (_cache[14] = [\n                      _createTextVNode(\"Uitloggen?\", -1 /* CACHED */)\n                    ])),\n                    _: 1 /* STABLE */,\n                    __: [14]\n                  }),\n                  _createVNode($setup[\"AlertDialogDescription\"], { class: \"logout-dialog__description\" }, {\n                    default: _withCtx(() => _cache[15] || (_cache[15] = [\n                      _createTextVNode(\" Weet je zeker dat je wilt uitloggen bij BTW Coach? \", -1 /* CACHED */)\n                    ])),\n                    _: 1 /* STABLE */,\n                    __: [15]\n                  }),\n                  ($setup.logoutError)\n                    ? (_openBlock(), _createBlock($setup[\"FieldError\"], { key: 0 }, {\n                        default: _withCtx(() => [\n                          _createTextVNode(_toDisplayString($setup.logoutError), 1 /* TEXT */)\n                        ]),\n                        _: 1 /* STABLE */\n                      }))\n                    : _createCommentVNode(\"v-if\", true),\n                  _createElementVNode(\"div\", _hoisted_16, [\n                    _createVNode($setup[\"AlertDialogCancel\"], {\n                      class: \"logout-dialog__button\",\n                      disabled: $setup.loggingOut\n                    }, {\n                      default: _withCtx(() => _cache[16] || (_cache[16] = [\n                        _createTextVNode(\"Annuleren\", -1 /* CACHED */)\n                      ])),\n                      _: 1 /* STABLE */,\n                      __: [16]\n                    }, 8 /* PROPS */, [\"disabled\"]),\n                    _createElementVNode(\"button\", {\n                      type: \"button\",\n                      class: \"logout-dialog__button logout-dialog__button--confirm\",\n                      disabled: $setup.loggingOut,\n                      \"aria-busy\": $setup.loggingOut,\n                      onClick: $setup.handleLogout\n                    }, _toDisplayString($setup.loggingOut ? \"Uitloggen…\" : \"Uitloggen\"), 9 /* TEXT, PROPS */, _hoisted_17)\n                  ])\n                ]),\n                _: 1 /* STABLE */\n              })\n            ]),\n            _: 1 /* STABLE */\n          })\n        ]),\n        _: 1 /* STABLE */\n      }, 8 /* PROPS */, [\"open\"])\n    ])\n  ]))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/SidebarNavigation.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/SidebarNavigation.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/SidebarNavigation.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/SidebarNavigation.vue\";script.__scopeId = \"data-v-72f174a6\";export default script;","<template>\n  <Teleport to=\"body\">\n    <div v-if=\"open\" class=\"rdialog\" @keydown.esc=\"close\">\n      <div class=\"rdialog__overlay\" @click=\"close\" />\n      <div\n        ref=\"boxEl\"\n        class=\"rdialog__box\"\n        role=\"dialog\"\n        aria-modal=\"true\"\n        :style=\"{ width: size.width + 'px', height: size.height + 'px' }\"\n      >\n        <div class=\"rdialog__header\">\n          <h2 class=\"rdialog__title\">{{ title }}</h2>\n          <button type=\"button\" class=\"rdialog__close\" aria-label=\"Sluiten\" @click=\"close\">\n            <X :size=\"18\" />\n          </button>\n        </div>\n        <div class=\"rdialog__body\">\n          <slot />\n        </div>\n      </div>\n    </div>\n  </Teleport>\n</template>\n\n<script setup lang=\"ts\">\nimport { nextTick, onBeforeUnmount, ref, watch } from \"vue\";\nimport { X } from \"lucide-vue-next\";\nimport { usePersistedSize } from \"../lib/usePersistedSize\";\n\nconst props = defineProps<{\n  open: boolean;\n  title: string;\n  dialogId: string;\n  defaultWidth?: number;\n  defaultHeight?: number;\n}>();\nconst emit = defineEmits<{ (e: \"update:open\", value: boolean): void }>();\n\nconst { size } = usePersistedSize({\n  dialogId: props.dialogId,\n  defaultWidth: props.defaultWidth ?? 720,\n  defaultHeight: props.defaultHeight ?? 560,\n});\n\nconst boxEl = ref<HTMLElement | null>(null);\nlet observer: ResizeObserver | null = null;\n\nfunction close() {\n  emit(\"update:open\", false);\n}\n\n// When the user drags the CSS resize handle, capture the new size back so it\n// persists.\nwatch(\n  () => props.open,\n  async (isOpen) => {\n    if (isOpen) {\n      await nextTick();\n      if (boxEl.value) {\n        observer = new ResizeObserver((entries) => {\n          const bs = entries[0]?.borderBoxSize?.[0];\n          if (!bs) return;\n          const w = Math.round(bs.inlineSize);\n          const h = Math.round(bs.blockSize);\n          if (w !== size.value.width || h !== size.value.height) {\n            size.value = { width: w, height: h };\n          }\n        });\n        observer.observe(boxEl.value);\n      }\n    } else {\n      observer?.disconnect();\n      observer = null;\n    }\n  },\n);\n\nonBeforeUnmount(() => observer?.disconnect());\n</script>\n\n<style scoped>\n.rdialog {\n  position: fixed;\n  inset: 0;\n  z-index: 100;\n  display: grid;\n  place-items: center;\n  animation: btw-fade 0.15s var(--ease-out);\n}\n.rdialog__overlay {\n  position: absolute;\n  inset: 0;\n  background: rgba(0, 0, 0, 0.45);\n  backdrop-filter: blur(2px);\n}\n.rdialog__box {\n  position: relative;\n  display: flex;\n  flex-direction: column;\n  min-width: 320px;\n  min-height: 220px;\n  max-width: 92vw;\n  max-height: 90vh;\n  border-radius: 16px;\n  background: var(--btw-surface);\n  border: 1px solid var(--btw-line-strong);\n  box-shadow: var(--btw-shadow-card);\n  overflow: hidden;\n  resize: both;\n}\n.rdialog__header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: 12px;\n  padding: 16px 16px 12px;\n  flex-shrink: 0;\n}\n.rdialog__title {\n  margin: 0;\n  font-size: 15px;\n  font-weight: 600;\n  color: var(--btw-fg);\n}\n.rdialog__close {\n  display: grid;\n  place-items: center;\n  width: 30px;\n  height: 30px;\n  border: 0;\n  border-radius: 8px;\n  background: transparent;\n  color: var(--btw-fg-muted);\n  cursor: pointer;\n  transition: background 0.12s, color 0.12s;\n}\n.rdialog__close:hover { background: var(--btw-surface-2); color: var(--btw-fg); }\n.rdialog__body {\n  flex: 1;\n  overflow-y: auto;\n  padding: 4px 16px 16px;\n}\n</style>\n","import { ref, watch } from \"vue\";\n\n// Persist a dialog's drag-resized dimensions per dialogId in localStorage,\n// debounced. Mirrors the Next.js hooks/use-persisted-size.ts contract\n// (key `dialog-size-<id>`, 300ms debounce, numeric validation).\nexport function usePersistedSize(opts: { dialogId: string; defaultWidth: number; defaultHeight: number }) {\n  const key = `dialog-size-${opts.dialogId}`;\n\n  function load(): { width: number; height: number } {\n    try {\n      const raw = localStorage.getItem(key);\n      if (raw) {\n        const parsed = JSON.parse(raw) as { width?: unknown; height?: unknown };\n        if (typeof parsed.width === \"number\" && typeof parsed.height === \"number\") {\n          return { width: parsed.width, height: parsed.height };\n        }\n      }\n    } catch {\n      // ignore — fall back to defaults\n    }\n    return { width: opts.defaultWidth, height: opts.defaultHeight };\n  }\n\n  const size = ref(load());\n  let timer: number | null = null;\n  watch(\n    size,\n    () => {\n      if (timer !== null) window.clearTimeout(timer);\n      timer = window.setTimeout(() => {\n        try { localStorage.setItem(key, JSON.stringify(size.value)); } catch { /* ignore */ }\n      }, 300);\n    },\n    { deep: true },\n  );\n\n  return { size };\n}\n","import { createElementVNode as _createElementVNode, toDisplayString as _toDisplayString, createVNode as _createVNode, renderSlot as _renderSlot, normalizeStyle as _normalizeStyle, withKeys as _withKeys, openBlock as _openBlock, createElementBlock as _createElementBlock, createCommentVNode as _createCommentVNode, Teleport as _Teleport, createBlock as _createBlock } from \"vue\"\n\nconst _hoisted_1 = { class: \"rdialog__header\" }\nconst _hoisted_2 = { class: \"rdialog__title\" }\nconst _hoisted_3 = { class: \"rdialog__body\" }\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createBlock(_Teleport, { to: \"body\" }, [\n    ($props.open)\n      ? (_openBlock(), _createElementBlock(\"div\", {\n          key: 0,\n          class: \"rdialog\",\n          onKeydown: _withKeys($setup.close, [\"esc\"])\n        }, [\n          _createElementVNode(\"div\", {\n            class: \"rdialog__overlay\",\n            onClick: $setup.close\n          }),\n          _createElementVNode(\"div\", {\n            ref: \"boxEl\",\n            class: \"rdialog__box\",\n            role: \"dialog\",\n            \"aria-modal\": \"true\",\n            style: _normalizeStyle({ width: $setup.size.width + 'px', height: $setup.size.height + 'px' })\n          }, [\n            _createElementVNode(\"div\", _hoisted_1, [\n              _createElementVNode(\"h2\", _hoisted_2, _toDisplayString($props.title), 1 /* TEXT */),\n              _createElementVNode(\"button\", {\n                type: \"button\",\n                class: \"rdialog__close\",\n                \"aria-label\": \"Sluiten\",\n                onClick: $setup.close\n              }, [\n                _createVNode($setup[\"X\"], { size: 18 })\n              ])\n            ]),\n            _createElementVNode(\"div\", _hoisted_3, [\n              _renderSlot(_ctx.$slots, \"default\", {}, undefined, true)\n            ])\n          ], 4 /* STYLE */)\n        ], 32 /* NEED_HYDRATION */))\n      : _createCommentVNode(\"v-if\", true)\n  ]))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ResizableDialog.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ResizableDialog.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ResizableDialog.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ResizableDialog.vue\";script.__scopeId = \"data-v-140b37dd\";export default script;","import { createElementVNode as _createElementVNode, mergeProps as _mergeProps, createVNode as _createVNode, withCtx as _withCtx, toDisplayString as _toDisplayString, openBlock as _openBlock, createElementBlock as _createElementBlock, createCommentVNode as _createCommentVNode, createTextVNode as _createTextVNode, createBlock as _createBlock, Fragment as _Fragment } from \"vue\"\n\nconst _hoisted_1 = {\n  class: \"sidebar\",\n  \"aria-label\": \"Navigatie\"\n}\nconst _hoisted_2 = { class: \"mobile-header\" }\nconst _hoisted_3 = [\"title\"]\nconst _hoisted_4 = [\"disabled\"]\nconst _hoisted_5 = { class: \"sidebar-drawer__header\" }\nconst _hoisted_6 = {\n  key: 1,\n  class: \"sidebar__prompt-empty\"\n}\nconst _hoisted_7 = { key: 1 }\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createElementBlock(_Fragment, null, [\n    _createElementVNode(\"aside\", _hoisted_1, [\n      _cache[10] || (_cache[10] = _createElementVNode(\"div\", { class: \"sidebar__header\" }, [\n        _createElementVNode(\"h1\", { class: \"sidebar__title\" }, \"BTW Coach\"),\n        _createElementVNode(\"p\", { class: \"sidebar__subtitle\" }, \"Kennisassistent voor Brede Welvaart in Twente\")\n      ], -1 /* CACHED */)),\n      _createVNode($setup[\"SidebarNavigation\"], _mergeProps($setup.navigationProps, {\n        onSelectChat: $setup.selectChat,\n        onNewChat: _cache[0] || (_cache[0] = $event => ($setup.navigate('new-chat'))),\n        onStartTestMode: _cache[1] || (_cache[1] = $event => ($setup.navigate('start-test-mode'))),\n        onStopTestMode: _cache[2] || (_cache[2] = $event => ($setup.navigate('stop-test-mode'))),\n        onShowPrompt: $setup.showPrompt\n      }), null, 16 /* FULL_PROPS */)\n    ]),\n    _createVNode($setup[\"DialogRoot\"], {\n      open: $setup.menuOpen,\n      \"onUpdate:open\": _cache[8] || (_cache[8] = $event => (($setup.menuOpen) = $event))\n    }, {\n      default: _withCtx(() => [\n        _createElementVNode(\"header\", _hoisted_2, [\n          _createVNode($setup[\"DialogTrigger\"], {\n            class: \"sidebar__icon-button\",\n            \"aria-label\": \"Menu openen\"\n          }, {\n            default: _withCtx(() => [\n              _createVNode($setup[\"Menu\"], {\n                size: 21,\n                \"aria-hidden\": \"true\"\n              })\n            ]),\n            _: 1 /* STABLE */\n          }),\n          _createElementVNode(\"h1\", {\n            class: \"mobile-header__title\",\n            title: $setup.mobileTitle\n          }, _toDisplayString($setup.mobileTitle), 9 /* TEXT, PROPS */, _hoisted_3),\n          ($props.hasMessages)\n            ? (_openBlock(), _createElementBlock(\"button\", {\n                key: 0,\n                type: \"button\",\n                class: \"sidebar__icon-button\",\n                \"aria-label\": \"Download gesprek\",\n                onClick: _cache[3] || (_cache[3] = $event => ($setup.emit('download')))\n              }, [\n                _createVNode($setup[\"Download\"], {\n                  size: 20,\n                  \"aria-hidden\": \"true\"\n                })\n              ]))\n            : _createCommentVNode(\"v-if\", true),\n          _createElementVNode(\"button\", {\n            type: \"button\",\n            class: \"sidebar__icon-button\",\n            \"aria-label\": \"Nieuw gesprek\",\n            disabled: $props.busy,\n            onClick: _cache[4] || (_cache[4] = $event => ($setup.navigate('new-chat')))\n          }, [\n            _createVNode($setup[\"SquarePen\"], {\n              size: 20,\n              \"aria-hidden\": \"true\"\n            })\n          ], 8 /* PROPS */, _hoisted_4)\n        ]),\n        _createVNode($setup[\"DialogPortal\"], null, {\n          default: _withCtx(() => [\n            _createVNode($setup[\"DialogOverlay\"], { class: \"sidebar-drawer__overlay\" }),\n            _createVNode($setup[\"DialogContent\"], { class: \"sidebar-drawer\" }, {\n              default: _withCtx(() => [\n                _createElementVNode(\"div\", _hoisted_5, [\n                  _createVNode($setup[\"DialogTitle\"], { class: \"sidebar__title\" }, {\n                    default: _withCtx(() => _cache[11] || (_cache[11] = [\n                      _createTextVNode(\"BTW Coach\", -1 /* CACHED */)\n                    ])),\n                    _: 1 /* STABLE */,\n                    __: [11]\n                  }),\n                  _createVNode($setup[\"DialogClose\"], {\n                    class: \"sidebar__icon-button\",\n                    \"aria-label\": \"Menu sluiten\"\n                  }, {\n                    default: _withCtx(() => [\n                      _createVNode($setup[\"X\"], {\n                        size: 21,\n                        \"aria-hidden\": \"true\"\n                      })\n                    ]),\n                    _: 1 /* STABLE */\n                  })\n                ]),\n                _createVNode($setup[\"DialogDescription\"], { class: \"sidebar-drawer__description\" }, {\n                  default: _withCtx(() => _cache[12] || (_cache[12] = [\n                    _createTextVNode(\"Je gesprekken en instellingen\", -1 /* CACHED */)\n                  ])),\n                  _: 1 /* STABLE */,\n                  __: [12]\n                }),\n                _createVNode($setup[\"SidebarNavigation\"], _mergeProps($setup.navigationProps, {\n                  onSelectChat: $setup.selectChat,\n                  onNewChat: _cache[5] || (_cache[5] = $event => ($setup.navigate('new-chat'))),\n                  onStartTestMode: _cache[6] || (_cache[6] = $event => ($setup.navigate('start-test-mode'))),\n                  onStopTestMode: _cache[7] || (_cache[7] = $event => ($setup.navigate('stop-test-mode'))),\n                  onShowPrompt: $setup.showPrompt\n                }), null, 16 /* FULL_PROPS */)\n              ]),\n              _: 1 /* STABLE */\n            })\n          ]),\n          _: 1 /* STABLE */\n        })\n      ]),\n      _: 1 /* STABLE */\n    }, 8 /* PROPS */, [\"open\"]),\n    _createVNode($setup[\"ResizableDialog\"], {\n      open: $setup.promptOpen,\n      \"onUpdate:open\": _cache[9] || (_cache[9] = $event => (($setup.promptOpen) = $event)),\n      title: \"Systeemprompt\",\n      \"dialog-id\": \"prompt-viewer\",\n      \"default-width\": 800,\n      \"default-height\": 600\n    }, {\n      default: _withCtx(() => [\n        ($props.systemPrompt)\n          ? (_openBlock(), _createBlock($setup[\"StreamMarkdown\"], {\n              key: 0,\n              class: \"sidebar__prompt\",\n              content: $props.systemPrompt\n            }, null, 8 /* PROPS */, [\"content\"]))\n          : (_openBlock(), _createElementBlock(\"div\", _hoisted_6, [\n              ($props.apiOffline)\n                ? (_openBlock(), _createElementBlock(_Fragment, { key: 0 }, [\n                    _createVNode($setup[\"AlertTriangle\"], {\n                      size: 16,\n                      class: \"sidebar__prompt-empty-icon\"\n                    }),\n                    _cache[13] || (_cache[13] = _createElementVNode(\"p\", null, [\n                      _createTextVNode(\" De chat-API draait niet op \"),\n                      _createElementVNode(\"code\", null, \"localhost:4104\"),\n                      _createTextVNode(\". Start 'm met \"),\n                      _createElementVNode(\"code\", null, \"./start\"),\n                      _createTextVNode(\" — dan verschijnt de prompt hier. \")\n                    ], -1 /* CACHED */))\n                  ], 64 /* STABLE_FRAGMENT */))\n                : (_openBlock(), _createElementBlock(\"p\", _hoisted_7, \"(prompt nog niet geladen)\"))\n            ]))\n      ]),\n      _: 1 /* STABLE */\n    }, 8 /* PROPS */, [\"open\"])\n  ], 64 /* STABLE_FRAGMENT */))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/Sidebar.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/Sidebar.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/Sidebar.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/Sidebar.vue\";script.__scopeId = \"data-v-a905bd19\";export default script;","<template>\n  <form class=\"prompt\" @submit.prevent=\"onSubmit\">\n    <div class=\"prompt__box\">\n      <textarea\n        ref=\"textareaEl\"\n        class=\"prompt__textarea\"\n        aria-label=\"Je vraag\"\n        :value=\"modelValue\"\n        :placeholder=\"placeholder\"\n        rows=\"1\"\n        @input=\"onInput\"\n        @keydown=\"onKeydown\"\n        @compositionstart=\"composing = true\"\n        @compositionend=\"composing = false\"\n      />\n      <div class=\"prompt__footer\">\n        <select\n          class=\"prompt__select\"\n          :value=\"modelId\"\n          aria-label=\"Model kiezen\"\n          @change=\"onModelChange\"\n        >\n          <option v-for=\"m in models\" :key=\"m.id\" :value=\"m.id\" :disabled=\"m.disabled\">{{ m.name }}{{ m.disabled ? \" (niet beschikbaar)\" : \"\" }}</option>\n        </select>\n\n        <button\n          v-if=\"isStreaming\"\n          type=\"button\"\n          class=\"prompt__submit prompt__submit--stop\"\n          aria-label=\"Stop\"\n          @click=\"$emit('stop')\"\n        >\n          <Square :size=\"16\" />\n        </button>\n        <button\n          v-else\n          type=\"submit\"\n          class=\"prompt__submit\"\n          :disabled=\"!modelValue.trim() || isBusy\"\n          aria-label=\"Verstuur\"\n        >\n          <Loader2 v-if=\"isBusy\" :size=\"16\" class=\"prompt__spin\" />\n          <CornerDownLeft v-else :size=\"16\" />\n        </button>\n      </div>\n    </div>\n  </form>\n</template>\n\n<script setup lang=\"ts\">\nimport { computed, ref } from \"vue\";\nimport { CornerDownLeft, Square, Loader2 } from \"lucide-vue-next\";\nimport type { ModelMeta } from \"../lib/meta\";\n\nconst props = defineProps<{\n  modelValue: string;\n  modelId: string;\n  models: ModelMeta[];\n  status: string;\n  placeholder?: string;\n}>();\nconst emit = defineEmits<{\n  (e: \"update:modelValue\", value: string): void;\n  (e: \"update:modelId\", value: string): void;\n  (e: \"submit\"): void;\n  (e: \"stop\"): void;\n}>();\n\nconst placeholder = computed(() => props.placeholder ?? \"Stel je vraag over Brede Welvaart…\");\nconst isStreaming = computed(() => props.status === \"streaming\");\nconst isBusy = computed(() => props.status === \"submitted\" || props.status === \"streaming\");\n\nconst textareaEl = ref<HTMLTextAreaElement | null>(null);\nconst composing = ref(false);\n\nfunction onInput(e: Event) {\n  emit(\"update:modelValue\", (e.target as HTMLTextAreaElement).value);\n}\nfunction onModelChange(e: Event) {\n  emit(\"update:modelId\", (e.target as HTMLSelectElement).value);\n}\nfunction onKeydown(e: KeyboardEvent) {\n  if (e.key === \"Enter\" && !e.shiftKey && !composing.value && !(e as KeyboardEvent).isComposing) {\n    e.preventDefault();\n    onSubmit();\n  }\n}\nfunction onSubmit() {\n  if (!props.modelValue.trim() || isBusy.value) return;\n  emit(\"submit\");\n}\n</script>\n\n<style scoped>\n.prompt {\n  width: 100%;\n  max-width: 768px;\n  margin: 0 auto;\n}\n.prompt__box {\n  border: 1px solid var(--btw-line);\n  border-radius: var(--btw-radius);\n  background: var(--btw-surface);\n  box-shadow: var(--btw-shadow-card);\n  overflow: hidden;\n  transition: border-color 0.12s, box-shadow 0.12s;\n}\n.prompt__box:focus-within {\n  border-color: var(--btw-accent);\n}\n.prompt__textarea {\n  display: block;\n  width: 100%;\n  min-height: 56px;\n  max-height: 200px;\n  field-sizing: content;\n  padding: 16px 16px 8px;\n  border: 0;\n  background: transparent;\n  color: var(--btw-fg);\n  font-family: var(--font-sans);\n  font-size: 15px;\n  line-height: 1.5;\n  resize: none;\n  outline: none;\n}\n.prompt__textarea::placeholder { color: var(--btw-fg-placeholder); }\n.prompt__footer {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: 8px;\n  padding: 8px 10px 10px;\n}\n.prompt__select {\n  appearance: none;\n  -webkit-appearance: none;\n  padding: 6px 12px;\n  border: 0;\n  border-radius: 10px;\n  background: transparent;\n  color: var(--btw-fg-muted);\n  font-family: var(--font-sans);\n  font-size: 13px;\n  font-weight: 500;\n  cursor: pointer;\n  transition: background 0.12s, color 0.12s;\n}\n.prompt__select:hover {\n  background: var(--btw-surface-2);\n  color: var(--btw-fg);\n}\n.prompt__submit {\n  display: grid;\n  place-items: center;\n  width: 38px;\n  height: 38px;\n  border: 0;\n  border-radius: 12px;\n  background: var(--btw-accent);\n  color: var(--btw-accent-fg);\n  cursor: pointer;\n  transition: background 0.12s, opacity 0.12s, transform 0.1s var(--ease-spring);\n}\n.prompt__submit:hover:not(:disabled) { background: var(--btw-accent-strong); transform: translateY(-1px); }\n.prompt__submit:disabled { opacity: 0.4; cursor: not-allowed; }\n.prompt__submit--stop { background: var(--btw-surface-3); color: var(--btw-fg); }\n.prompt__spin { animation: btw-spin 0.7s linear infinite; }\n@media (max-width: 720px) {\n  .prompt__textarea { font-size: 16px; padding: 14px 14px 6px; }\n  .prompt__select { min-width: 0; max-width: calc(100% - 52px); min-height: 44px; font-size: 16px; text-overflow: ellipsis; }\n  .prompt__submit { width: 44px; height: 44px; flex-shrink: 0; }\n}\n</style>\n","import { createElementVNode as _createElementVNode, renderList as _renderList, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock, toDisplayString as _toDisplayString, createVNode as _createVNode, createCommentVNode as _createCommentVNode, createBlock as _createBlock, withModifiers as _withModifiers } from \"vue\"\n\nconst _hoisted_1 = { class: \"prompt__box\" }\nconst _hoisted_2 = [\"value\", \"placeholder\"]\nconst _hoisted_3 = { class: \"prompt__footer\" }\nconst _hoisted_4 = [\"value\"]\nconst _hoisted_5 = [\"value\", \"disabled\"]\nconst _hoisted_6 = [\"disabled\"]\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createElementBlock(\"form\", {\n    class: \"prompt\",\n    onSubmit: _withModifiers($setup.onSubmit, [\"prevent\"])\n  }, [\n    _createElementVNode(\"div\", _hoisted_1, [\n      _createElementVNode(\"textarea\", {\n        ref: \"textareaEl\",\n        class: \"prompt__textarea\",\n        \"aria-label\": \"Je vraag\",\n        value: $props.modelValue,\n        placeholder: $setup.placeholder,\n        rows: \"1\",\n        onInput: $setup.onInput,\n        onKeydown: $setup.onKeydown,\n        onCompositionstart: _cache[0] || (_cache[0] = $event => ($setup.composing = true)),\n        onCompositionend: _cache[1] || (_cache[1] = $event => ($setup.composing = false))\n      }, null, 40 /* PROPS, NEED_HYDRATION */, _hoisted_2),\n      _createElementVNode(\"div\", _hoisted_3, [\n        _createElementVNode(\"select\", {\n          class: \"prompt__select\",\n          value: $props.modelId,\n          \"aria-label\": \"Model kiezen\",\n          onChange: $setup.onModelChange\n        }, [\n          (_openBlock(true), _createElementBlock(_Fragment, null, _renderList($props.models, (m) => {\n            return (_openBlock(), _createElementBlock(\"option\", {\n              key: m.id,\n              value: m.id,\n              disabled: m.disabled\n            }, _toDisplayString(m.name) + _toDisplayString(m.disabled ? \" (niet beschikbaar)\" : \"\"), 9 /* TEXT, PROPS */, _hoisted_5))\n          }), 128 /* KEYED_FRAGMENT */))\n        ], 40 /* PROPS, NEED_HYDRATION */, _hoisted_4),\n        ($setup.isStreaming)\n          ? (_openBlock(), _createElementBlock(\"button\", {\n              key: 0,\n              type: \"button\",\n              class: \"prompt__submit prompt__submit--stop\",\n              \"aria-label\": \"Stop\",\n              onClick: _cache[2] || (_cache[2] = $event => (_ctx.$emit('stop')))\n            }, [\n              _createVNode($setup[\"Square\"], { size: 16 })\n            ]))\n          : (_openBlock(), _createElementBlock(\"button\", {\n              key: 1,\n              type: \"submit\",\n              class: \"prompt__submit\",\n              disabled: !$props.modelValue.trim() || $setup.isBusy,\n              \"aria-label\": \"Verstuur\"\n            }, [\n              ($setup.isBusy)\n                ? (_openBlock(), _createBlock($setup[\"Loader2\"], {\n                    key: 0,\n                    size: 16,\n                    class: \"prompt__spin\"\n                  }))\n                : (_openBlock(), _createBlock($setup[\"CornerDownLeft\"], {\n                    key: 1,\n                    size: 16\n                  }))\n            ], 8 /* PROPS */, _hoisted_6))\n      ])\n    ])\n  ], 32 /* NEED_HYDRATION */))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/PromptInput.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/PromptInput.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/PromptInput.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/PromptInput.vue\";script.__scopeId = \"data-v-090e064b\";export default script;","<template>\n  <div class=\"msg\" :class=\"message.role === 'user' ? 'msg--user' : 'msg--assistant'\">\n    <div class=\"msg__content\">\n      <!-- 1. Reasoning (if any) -->\n      <Reasoning\n        v-if=\"hasReasoning\"\n        :reasoning=\"reasoningText\"\n        :is-streaming=\"isReasoningStreaming\"\n      />\n\n      <!-- 2. Chain-of-thought / sources (if any tool calls) -->\n      <ChainOfThought v-if=\"toolParts.length\" :tool-parts=\"toolParts\" />\n\n      <!-- 3. Text parts, in order, with citation badges -->\n      <template v-for=\"(part, i) in message.parts\" :key=\"`${message.id}-${i}`\">\n        <StreamMarkdown\n          v-if=\"part.type === 'text'\"\n          class=\"msg__markdown\"\n          :content=\"message.role === 'assistant' ? preprocessCitations(part.text) : part.text\"\n          :components=\"markdownComponents\"\n          :allowed-link-prefixes=\"markdownLinkPrefixes\"\n        />\n      </template>\n    </div>\n\n    <!-- Actiebalk (kopiëren + feedback) onder een afgerond assistant-antwoord. -->\n    <MessageActions\n      v-if=\"showActions\"\n      :text=\"assistantText\"\n      :feedback=\"feedback\"\n      @feedback=\"(rating) => $emit('feedback', rating)\"\n    />\n  </div>\n</template>\n\n<script setup lang=\"ts\">\nimport { computed, provide, watch } from \"vue\";\nimport { StreamMarkdown } from \"streamdown-vue\";\nimport Reasoning from \"./Reasoning.vue\";\nimport ChainOfThought from \"./ChainOfThought.vue\";\nimport CitationLink from \"./CitationLink.vue\";\nimport MessageActions from \"./MessageActions.vue\";\nimport { preprocessCitations, citationSourcesKey, sourcesFromParts } from \"../lib/citations\";\nimport type { FeedbackState } from \"../lib/chatHistory\";\n\n// message.parts is loosely typed (AI SDK UIMessage) — .vue isn't type-checked.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst props = defineProps<{ message: any; isLast: boolean; isStreaming: boolean; feedback?: FeedbackState | null }>();\ndefineEmits<{ (e: \"feedback\", rating: \"positive\" | \"negative\"): void }>();\n\nconst markdownComponents = { a: CitationLink };\n// streamdown-vue removes fragment links before invoking the custom anchor\n// component unless this specific prefix is explicitly allowed.\nconst markdownLinkPrefixes = [\"https://\", \"http://\", \"#cite=\"];\n// The markdown renderer creates deeply nested citation components. Scope their\n// sources to this answer so another turn cannot supply an unrelated passage.\nprovide(citationSourcesKey, computed(() => sourcesFromParts(props.message.parts)));\n\n// Plain-text of the assistant answer, for the copy button.\nconst assistantText = computed(() =>\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  (props.message.parts ?? []).filter((p: any) => p.type === \"text\").map((p: any) => p.text).join(\"\"),\n);\n\n// Show the action bar only under a finished, non-empty assistant answer (never\n// on user messages or the still-streaming last one).\nconst showActions = computed(() =>\n  props.message.role === \"assistant\" &&\n  !(props.isLast && props.isStreaming) &&\n  assistantText.value.trim().length > 0,\n);\n\nconst reasoningParts = computed(() =>\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  (props.message.parts ?? []).filter((p: any) => p.type === \"reasoning\"),\n);\nconst reasoningText = computed(() =>\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  reasoningParts.value.map((p: any) => p.text).join(\"\\n\\n\"),\n);\nconst hasReasoning = computed(() => reasoningParts.value.length > 0);\n\nconst isReasoningStreaming = computed(() => {\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  const last = (props.message.parts ?? []).at(-1);\n  return props.isLast && props.isStreaming && last?.type === \"reasoning\";\n});\n\nconst toolParts = computed(() =>\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  (props.message.parts ?? []).filter(\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    (p: any) => typeof p.type === \"string\" && p.type.startsWith(\"tool-\") && p.type !== \"dynamic-tool\" && \"toolCallId\" in p,\n  ),\n);\n\n// Debug log each completed tool call's I/O once (deduped by toolCallId).\nconst logged = new Set<string>();\nwatch(\n  toolParts,\n  (parts) => {\n    for (const part of parts) {\n      if (part.state === \"output-available\" && !logged.has(part.toolCallId)) {\n        logged.add(part.toolCallId);\n        console.log(`[semanticSearch] \"${part.input?.query}\"`, part.output);\n      }\n    }\n  },\n  { deep: true, immediate: true },\n);\n</script>\n\n<style scoped>\n.msg {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n  width: 100%;\n  max-width: 95%;\n}\n.msg--user {\n  margin-left: auto;\n  align-items: flex-end;\n}\n.msg__content {\n  display: flex;\n  flex-direction: column;\n  min-width: 0;\n  max-width: 100%;\n  font-size: 14.5px;\n}\n.msg--user .msg__content {\n  width: fit-content;\n  margin-left: auto;\n  padding: 12px 16px;\n  border-radius: 16px 16px 4px 16px;\n  background: var(--btw-surface-2);\n  color: var(--btw-fg);\n  white-space: pre-wrap;\n}\n.msg--assistant .msg__content {\n  color: var(--btw-fg);\n}\n\n/* Markdown body styling (StreamMarkdown renders into here). */\n.msg__markdown {\n  line-height: 1.65;\n}\n.msg__markdown :deep(> *:first-child) { margin-top: 0; }\n.msg__markdown :deep(> *:last-child) { margin-bottom: 0; }\n.msg__markdown :deep(p) { margin: 0 0 12px; }\n.msg__markdown :deep(h1) { font-size: 1.5em; font-weight: 700; margin: 18px 0 8px; }\n.msg__markdown :deep(h2) { font-size: 1.25em; font-weight: 700; margin: 18px 0 8px; }\n.msg__markdown :deep(h3) { font-size: 1.1em; font-weight: 600; margin: 14px 0 6px; }\n.msg__markdown :deep(ul),\n.msg__markdown :deep(ol) { margin: 0 0 12px; padding-left: 22px; }\n.msg__markdown :deep(li) { margin: 2px 0; }\n.msg__markdown :deep(strong) { font-weight: 700; color: var(--btw-fg); }\n.msg__markdown :deep(a) { color: var(--btw-accent); }\n.msg__markdown :deep(code) {\n  font-family: var(--font-mono);\n  font-size: 0.88em;\n  padding: 1px 5px;\n  border-radius: 6px;\n  background: var(--btw-surface-2);\n}\n.msg__markdown :deep(pre) {\n  margin: 0 0 12px;\n  padding: 14px 16px;\n  border-radius: 12px;\n  background: var(--btw-surface-2);\n  border: 1px solid var(--btw-line);\n  overflow-x: auto;\n}\n.msg__markdown :deep(pre code) { padding: 0; background: transparent; }\n.msg__markdown :deep(blockquote) {\n  margin: 0 0 12px;\n  padding-left: 14px;\n  border-left: 3px solid var(--btw-line-strong);\n  color: var(--btw-fg-muted);\n}\n</style>\n","<template>\n  <div class=\"reasoning\">\n    <button type=\"button\" class=\"reasoning__trigger\" @click=\"isOpen = !isOpen\">\n      <Brain :size=\"16\" />\n      <span class=\"reasoning__label\" :class=\"{ 'reasoning__label--shimmer': isStreaming }\">{{ label }}</span>\n      <ChevronDown :size=\"16\" class=\"reasoning__chevron\" :class=\"{ 'reasoning__chevron--open': isOpen }\" />\n    </button>\n    <div v-show=\"isOpen\" class=\"reasoning__content\">\n      <StreamMarkdown :content=\"reasoning\" />\n    </div>\n  </div>\n</template>\n\n<script setup lang=\"ts\">\nimport { computed, ref, watch } from \"vue\";\nimport { Brain, ChevronDown } from \"lucide-vue-next\";\nimport { StreamMarkdown } from \"streamdown-vue\";\n\nconst props = defineProps<{ reasoning: string; isStreaming: boolean }>();\n\nconst AUTO_CLOSE_DELAY = 1000;\n\nconst isOpen = ref(props.isStreaming);\nconst duration = ref<number | undefined>(undefined);\nlet startTime: number | null = null;\nlet hasEverStreamed = props.isStreaming;\nlet hasAutoClosed = false;\nlet closeTimer: number | null = null;\n\nconst label = computed(() => {\n  if (props.isStreaming || duration.value === 0) return \"Aan het nadenken…\";\n  if (duration.value === undefined) return \"Even nagedacht\";\n  return `${duration.value} sec. nagedacht`;\n});\n\nwatch(\n  () => props.isStreaming,\n  (streaming, was) => {\n    if (streaming && !was) {\n      hasEverStreamed = true;\n      if (startTime === null) startTime = Date.now();\n      if (!isOpen.value) isOpen.value = true;\n    }\n    if (!streaming && was && startTime !== null) {\n      duration.value = Math.ceil((Date.now() - startTime) / 1000);\n      startTime = null;\n    }\n    // Auto-close 1s after streaming ends (fires once).\n    if (hasEverStreamed && !streaming && isOpen.value && !hasAutoClosed) {\n      if (closeTimer !== null) window.clearTimeout(closeTimer);\n      closeTimer = window.setTimeout(() => {\n        isOpen.value = false;\n        hasAutoClosed = true;\n        closeTimer = null;\n      }, AUTO_CLOSE_DELAY);\n    }\n  },\n);\n</script>\n\n<style scoped>\n.reasoning {\n  margin-bottom: 12px;\n}\n.reasoning__trigger {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  width: 100%;\n  padding: 0;\n  border: 0;\n  background: transparent;\n  color: var(--btw-fg-muted);\n  font-size: 13px;\n  cursor: pointer;\n  transition: color 0.12s;\n}\n.reasoning__trigger:hover { color: var(--btw-fg); }\n.reasoning__label { flex: 1; text-align: left; }\n.reasoning__label--shimmer {\n  background: linear-gradient(90deg, var(--btw-fg-subtle) 30%, var(--btw-fg) 50%, var(--btw-fg-subtle) 70%);\n  background-size: 200% 100%;\n  -webkit-background-clip: text;\n  background-clip: text;\n  -webkit-text-fill-color: transparent;\n  animation: btw-shimmer 1.4s linear infinite;\n}\n.reasoning__chevron { transition: transform 0.2s var(--ease-out); flex-shrink: 0; }\n.reasoning__chevron--open { transform: rotate(180deg); }\n.reasoning__content {\n  margin-top: 10px;\n  padding-left: 24px;\n  font-size: 13.5px;\n  color: var(--btw-fg-muted);\n  line-height: 1.6;\n}\n@keyframes btw-shimmer {\n  to { background-position: -200% 0; }\n}\n</style>\n","import { createVNode as _createVNode, toDisplayString as _toDisplayString, normalizeClass as _normalizeClass, createElementVNode as _createElementVNode, vShow as _vShow, withDirectives as _withDirectives, openBlock as _openBlock, createElementBlock as _createElementBlock } from \"vue\"\n\nconst _hoisted_1 = { class: \"reasoning\" }\nconst _hoisted_2 = { class: \"reasoning__content\" }\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createElementBlock(\"div\", _hoisted_1, [\n    _createElementVNode(\"button\", {\n      type: \"button\",\n      class: \"reasoning__trigger\",\n      onClick: _cache[0] || (_cache[0] = $event => ($setup.isOpen = !$setup.isOpen))\n    }, [\n      _createVNode($setup[\"Brain\"], { size: 16 }),\n      _createElementVNode(\"span\", {\n        class: _normalizeClass([\"reasoning__label\", { 'reasoning__label--shimmer': $props.isStreaming }])\n      }, _toDisplayString($setup.label), 3 /* TEXT, CLASS */),\n      _createVNode($setup[\"ChevronDown\"], {\n        size: 16,\n        class: _normalizeClass([\"reasoning__chevron\", { 'reasoning__chevron--open': $setup.isOpen }])\n      }, null, 8 /* PROPS */, [\"class\"])\n    ]),\n    _withDirectives(_createElementVNode(\"div\", _hoisted_2, [\n      _createVNode($setup[\"StreamMarkdown\"], { content: $props.reasoning }, null, 8 /* PROPS */, [\"content\"])\n    ], 512 /* NEED_PATCH */), [\n      [_vShow, $setup.isOpen]\n    ])\n  ]))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/Reasoning.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/Reasoning.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/Reasoning.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/Reasoning.vue\";script.__scopeId = \"data-v-2e6b0642\";export default script;","<template>\n  <div class=\"cot\">\n    <button type=\"button\" class=\"cot__header\" @click=\"isOpen = !isOpen\">\n      <Brain :size=\"16\" />\n      <span class=\"cot__title\">{{ headerText }}</span>\n      <ChevronDown :size=\"16\" class=\"cot__chevron\" :class=\"{ 'cot__chevron--open': isOpen }\" />\n    </button>\n\n    <div v-show=\"isOpen\" class=\"cot__content\">\n      <div v-for=\"(part, i) in toolParts\" :key=\"part.toolCallId ?? i\" class=\"cot__step\">\n        <div class=\"cot__icon\" :class=\"{ 'cot__icon--active': !isComplete(part) }\">\n          <Loader2 v-if=\"!isComplete(part)\" :size=\"15\" class=\"cot__spin\" />\n          <Search v-else :size=\"15\" />\n          <span v-if=\"i < toolParts.length - 1\" class=\"cot__line\" />\n        </div>\n        <div class=\"cot__body\">\n          <div class=\"cot__label\">{{ queryOf(part) || \"Zoeken…\" }}</div>\n          <div v-if=\"isComplete(part)\" class=\"cot__desc\">{{ resultsOf(part).length }} bronnen gevonden</div>\n          <div v-if=\"isComplete(part) && resultsOf(part).length\" class=\"cot__results\">\n            <SourceBadge v-for=\"r in resultsOf(part)\" :key=\"r.id\" :reference=\"r.id\" :sources=\"[r]\" :score=\"r.score\" />\n          </div>\n        </div>\n      </div>\n    </div>\n  </div>\n</template>\n\n<script setup lang=\"ts\">\nimport { computed, ref } from \"vue\";\nimport { Brain, ChevronDown, Search, Loader2 } from \"lucide-vue-next\";\nimport SourceBadge from \"./SourceBadge.vue\";\nimport { sourcesFromParts, type CitationSource } from \"../lib/citations\";\n\n// toolParts are AI SDK `tool-*` message parts (loosely typed — .vue isn't\n// type-checked, so we read fields defensively).\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst props = defineProps<{ toolParts: any[] }>();\n\nconst isOpen = ref(false);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction isComplete(part: any): boolean {\n  return part?.state === \"output-available\";\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction queryOf(part: any): string {\n  return part?.input?.query ?? \"\";\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction resultsOf(part: any): CitationSource[] {\n  return sourcesFromParts([part]);\n}\n\nconst allComplete = computed(() => props.toolParts.every(isComplete));\nconst totalSources = computed(() =>\n  props.toolParts.reduce((sum, p) => sum + (isComplete(p) ? resultsOf(p).length : 0), 0),\n);\nconst headerText = computed(() =>\n  allComplete.value ? `${totalSources.value} bronnen geraadpleegd` : \"Bronnen zoeken…\",\n);\n</script>\n\n<style scoped>\n.cot {\n  margin-bottom: 12px;\n}\n.cot__header {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  width: 100%;\n  padding: 0;\n  border: 0;\n  background: transparent;\n  color: var(--btw-fg-muted);\n  font-size: 13px;\n  cursor: pointer;\n  transition: color 0.12s;\n}\n.cot__header:hover { color: var(--btw-fg); }\n.cot__title { flex: 1; text-align: left; }\n.cot__chevron { transition: transform 0.2s var(--ease-out); flex-shrink: 0; }\n.cot__chevron--open { transform: rotate(180deg); }\n\n.cot__content {\n  margin-top: 10px;\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n}\n.cot__step {\n  display: flex;\n  gap: 10px;\n  font-size: 13px;\n  color: var(--btw-fg-muted);\n  animation: btw-fade 0.25s var(--ease-out);\n}\n.cot__icon {\n  position: relative;\n  margin-top: 2px;\n  color: var(--btw-fg-subtle);\n  flex-shrink: 0;\n}\n.cot__icon--active { color: var(--btw-accent); }\n.cot__spin { animation: btw-spin 0.7s linear infinite; }\n.cot__line {\n  position: absolute;\n  top: 22px;\n  bottom: -14px;\n  left: 50%;\n  width: 1px;\n  margin-left: -0.5px;\n  background: var(--btw-line);\n}\n.cot__body { flex: 1; min-width: 0; }\n.cot__label { color: var(--btw-fg); }\n.cot__desc { margin-top: 2px; font-size: 12px; color: var(--btw-fg-subtle); }\n.cot__results {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 6px;\n  margin-top: 8px;\n}\n</style>\n","<script setup lang=\"ts\">\nimport { computed } from \"vue\";\nimport { FileText, X } from \"lucide-vue-next\";\nimport { DialogRoot, DialogTrigger, DialogPortal, DialogOverlay, DialogContent, DialogTitle, DialogDescription, DialogClose } from \"reka-ui\";\nimport { citationLabel, resolveCitation, type CitationSource } from \"../lib/citations\";\n\nconst props = defineProps<{\n  reference: string;\n  sources: CitationSource[];\n  score?: number | null;\n}>();\n\nconst label = computed(() => citationLabel(props));\nconst passages = computed(() => resolveCitation(props));\nconst missingTitle = computed(() => /^file:\\d+:chunk:\\d+$/.test(props.reference) && !passages.value[0]?.title);\n\nfunction passageLabel(source: CitationSource): string {\n  const chunk = /:chunk:(\\d+)$/.exec(source.id);\n  return chunk ? `Fragment ${chunk[1]}` : \"Bronfragment\";\n}\n</script>\n\n<template>\n  <DialogRoot>\n    <DialogTrigger class=\"source-badge\" :title=\"label\" :aria-label=\"`Bekijk bron: ${label}`\">\n      <FileText :size=\"12\" aria-hidden=\"true\" class=\"source-badge__icon\" />\n      <span class=\"source-badge__label\">{{ label }}</span>\n      <span v-if=\"typeof score === 'number'\" class=\"source-badge__score\">{{ Math.round(score * 100) }}%</span>\n    </DialogTrigger>\n    <DialogPortal>\n      <DialogOverlay class=\"source-dialog__overlay\" />\n      <DialogContent class=\"source-dialog\">\n        <div class=\"source-dialog__header\">\n          <div class=\"source-dialog__heading\">\n            <p class=\"source-dialog__eyebrow\">Bronvermelding</p>\n            <DialogTitle class=\"source-dialog__title\">{{ label }}</DialogTitle>\n          </div>\n          <DialogClose class=\"source-dialog__close\" aria-label=\"Bron sluiten\">\n            <X :size=\"20\" aria-hidden=\"true\" />\n          </DialogClose>\n        </div>\n        <DialogDescription class=\"source-dialog__description\">\n          Bekijk de tekst die bij dit antwoord als bron is gebruikt.\n        </DialogDescription>\n        <div class=\"source-dialog__body\" tabindex=\"0\" aria-label=\"Brontekst\">\n          <p v-if=\"missingTitle\" class=\"source-dialog__notice\">De naam van dit document is nog niet beschikbaar.</p>\n          <p v-if=\"!passages.length\" class=\"source-dialog__notice\">\n            Het bijbehorende bronfragment is niet beschikbaar in dit gesprek.\n          </p>\n          <section v-for=\"passage in passages\" :key=\"passage.id\" class=\"source-dialog__passage\">\n            <h3 class=\"source-dialog__fragment\">{{ passageLabel(passage) }}</h3>\n            <p v-if=\"passage.textTruncated\" class=\"source-dialog__notice\">\n              Bij dit oudere gesprek is alleen een verkort bronfragment bewaard. De volledige oorspronkelijke tekst is hier niet beschikbaar.\n            </p>\n            <p v-if=\"passage.text\" class=\"source-dialog__text\">{{ passage.text }}</p>\n            <p v-else class=\"source-dialog__notice\">De tekst van dit bronfragment is niet beschikbaar.</p>\n          </section>\n        </div>\n      </DialogContent>\n    </DialogPortal>\n  </DialogRoot>\n</template>\n\n<style scoped>\n.source-badge {\n  display: inline-flex;\n  align-items: center;\n  gap: 5px;\n  max-width: 100%;\n  margin: 0 2px;\n  padding: 2px 8px;\n  border: 1px solid var(--btw-line-strong);\n  border-radius: 999px;\n  background: var(--btw-mint-soft);\n  color: var(--btw-mint);\n  font-family: inherit;\n  font-size: 11.5px;\n  font-weight: 500;\n  line-height: 1.6;\n  vertical-align: baseline;\n  text-align: left;\n  cursor: pointer;\n}\n.source-badge__icon, .source-badge__score { flex-shrink: 0; }\n.source-badge__label { min-width: 0; overflow-wrap: anywhere; }\n.source-badge__score { font-size: 10px; font-variant-numeric: tabular-nums; opacity: 0.8; }\n.source-badge:focus-visible, .source-dialog__close:focus-visible, .source-dialog__body:focus-visible {\n  outline: 2px solid var(--btw-accent);\n  outline-offset: 3px;\n}\n.source-dialog__overlay {\n  position: fixed;\n  inset: 0;\n  z-index: 100;\n  background: rgba(0, 0, 0, 0.5);\n  backdrop-filter: blur(2px);\n}\n.source-dialog {\n  position: fixed;\n  z-index: 101;\n  top: 50%;\n  left: 50%;\n  transform: translate(-50%, -50%);\n  display: flex;\n  flex-direction: column;\n  width: min(720px, calc(100vw - 32px));\n  max-height: calc(100dvh - 48px);\n  border: 1px solid var(--btw-line-strong);\n  border-radius: 16px;\n  background: var(--btw-surface);\n  color: var(--btw-fg);\n  box-shadow: var(--btw-shadow-card);\n  pointer-events: auto;\n  overflow: hidden;\n}\n.source-dialog__header { display: flex; align-items: flex-start; gap: 12px; padding: 20px 20px 8px; }\n.source-dialog__heading { flex: 1; min-width: 0; }\n.source-dialog__eyebrow { margin: 0 0 6px; color: var(--btw-fg-subtle); font-size: 12px; }\n.source-dialog__title { margin: 0; font-size: 18px; font-weight: 650; line-height: 1.4; overflow-wrap: anywhere; }\n.source-dialog__close {\n  display: grid;\n  place-items: center;\n  flex-shrink: 0;\n  width: 32px;\n  height: 32px;\n  border: 0;\n  border-radius: 8px;\n  background: transparent;\n  color: var(--btw-fg-muted);\n  cursor: pointer;\n}\n.source-dialog__description { margin: 0; padding: 0 20px 16px; color: var(--btw-fg-muted); font-size: 13px; }\n.source-dialog__body { min-height: 0; overflow-y: auto; padding: 0 20px 20px; overscroll-behavior: contain; }\n.source-dialog__passage + .source-dialog__passage { margin-top: 20px; }\n.source-dialog__fragment { margin: 0 0 8px; color: var(--btw-fg-muted); font-size: 12px; font-weight: 600; }\n.source-dialog__text { margin: 0; padding: 16px; border: 1px solid var(--btw-line); border-radius: 10px; background: var(--btw-surface-2); font-size: 14px; line-height: 1.75; white-space: pre-wrap; overflow-wrap: anywhere; }\n.source-dialog__notice { margin: 0 0 12px; color: var(--btw-fg-muted); font-size: 13px; line-height: 1.6; }\n@media (hover: hover) {\n  .source-badge:hover { border-color: var(--btw-mint); }\n  .source-dialog__close:hover { background: var(--btw-surface-2); color: var(--btw-fg); }\n}\n</style>\n","// Citation system: assistant text contains `[Bron: <titel>]` markers. We rewrite\n// each to a markdown link with an encoded reference, then StreamMarkdown's\n// `a`-override (CitationLink.vue) renders it as an interactive badge. The `#cite`\n// fragment sentinel is used (not a custom protocol) because markdown hardeners\n// block non-standard protocols. Bare chunk IDs from older answers are supported too.\n\nimport type { InjectionKey, Ref } from \"vue\";\n\nexport interface CitationSource {\n  id: string;\n  source?: string;\n  title?: string;\n  text: string;\n  score?: number | null;\n  textTruncated?: boolean;\n}\n\nexport const citationSourcesKey: InjectionKey<Readonly<Ref<CitationSource[]>>> = Symbol(\"citationSources\");\n\nexport const BRON_REGEX = /\\[Bron:\\s*([^\\]]+)\\]/g;\n\nfunction citationMarkdown(reference: string): string {\n  const label = reference.replace(/[\\\\[\\]<>]/g, \"\\\\$&\");\n  return `[${label}](#cite=${encodeURIComponent(reference)})`;\n}\n\nexport function preprocessCitations(text: string): string {\n  // Process each original token only once, so generated links cannot be nested.\n  // Preserve ordinary links and code blocks, but accept a chunk ID in backticks.\n  return text.replace(/```[\\s\\S]*?(?:```|$)|~~~[\\s\\S]*?(?:~~~|$)|\\[Bron:\\s*([^\\]]+)\\]|!?\\[[^\\]\\n]*\\]\\([^\\n]*?\\)|`[^`\\n]*`|\\bfile:\\d+:chunk:\\d+\\b/g, (match, reference?: string) => {\n    if (reference) {\n      const ids = reference.match(/\\bfile:\\d+:chunk:\\d+\\b/g);\n      return ids ? [...new Set(ids)].map(citationMarkdown).join(\" \") : citationMarkdown(reference.trim());\n    }\n    if (/^`?file:\\d+:chunk:\\d+`?$/.test(match)) return citationMarkdown(match.replaceAll(\"`\", \"\"));\n    return match;\n  });\n}\n\nexport function citationReference(href?: string): string | null {\n  if (!href?.startsWith(\"#cite=\")) return null;\n  try {\n    return decodeURIComponent(href.slice(6));\n  } catch {\n    return null;\n  }\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n  return value !== null && typeof value === \"object\" ? value as Record<string, unknown> : undefined;\n}\n\n/** Read only completed search results; never infer a source from the answer itself. */\nexport function sourcesFromParts(parts: unknown): CitationSource[] {\n  if (!Array.isArray(parts)) return [];\n  const sources = new Map<string, CitationSource>();\n  for (const value of parts) {\n    const part = record(value);\n    if (part?.type !== \"tool-semanticSearch\" || part.state !== \"output-available\") continue;\n    const results = record(part.output)?.results;\n    if (!Array.isArray(results)) continue;\n    for (const item of results) {\n      const hit = record(item);\n      const id = typeof hit?.source === \"string\" ? hit.source : hit?.id;\n      if (!hit || typeof id !== \"string\" || !id || typeof hit.text !== \"string\") continue;\n      const source: CitationSource = { id, text: hit.text };\n      if (typeof hit.source === \"string\") source.source = hit.source;\n      if (typeof hit.title === \"string\" && hit.title.trim()) source.title = hit.title.trim();\n      if (typeof hit.score === \"number\" || hit.score === null) source.score = hit.score;\n      if (typeof hit.textTruncated === \"boolean\") source.textTruncated = hit.textTruncated;\n      sources.set(id, source);\n    }\n  }\n  return [...sources.values()];\n}\n\n/**\n * Resolves references against the supplied message sources.\n * Legacy answers may cite a document title instead of a chunk ID;\n * return all exact title matches because the intended chunk is unknown.\n * An exact ID match takes precedence. Unmatched references return no sources.\n */\nexport function resolveCitation(options: { reference: string; sources: CitationSource[] }): CitationSource[] {\n  const exact = options.sources.find(source => source.id === options.reference || source.source === options.reference);\n  if (exact) return [exact];\n  return options.sources.filter(source => source.title === options.reference);\n}\n\nexport function citationLabel(options: { reference: string; sources: CitationSource[] }): string {\n  const source = resolveCitation(options)[0];\n  if (source?.title) return source.title;\n  // File IDs belong to the upstream knowledge bank, not the local WHFS.\n  // Without an upstream title, use a neutral label rather than a local lookup.\n  const file = /^file:(\\d+):chunk:\\d+$/.exec(options.reference);\n  return file ? `Document #${file[1]}` : options.reference;\n}\n","import { createVNode as _createVNode, toDisplayString as _toDisplayString, createElementVNode as _createElementVNode, openBlock as _openBlock, createElementBlock as _createElementBlock, createCommentVNode as _createCommentVNode, withCtx as _withCtx, createTextVNode as _createTextVNode, renderList as _renderList, Fragment as _Fragment, createBlock as _createBlock } from \"vue\"\n\nconst _hoisted_1 = { class: \"source-badge__label\" }\nconst _hoisted_2 = {\n  key: 0,\n  class: \"source-badge__score\"\n}\nconst _hoisted_3 = { class: \"source-dialog__header\" }\nconst _hoisted_4 = { class: \"source-dialog__heading\" }\nconst _hoisted_5 = {\n  class: \"source-dialog__body\",\n  tabindex: \"0\",\n  \"aria-label\": \"Brontekst\"\n}\nconst _hoisted_6 = {\n  key: 0,\n  class: \"source-dialog__notice\"\n}\nconst _hoisted_7 = {\n  key: 1,\n  class: \"source-dialog__notice\"\n}\nconst _hoisted_8 = { class: \"source-dialog__fragment\" }\nconst _hoisted_9 = {\n  key: 0,\n  class: \"source-dialog__notice\"\n}\nconst _hoisted_10 = {\n  key: 1,\n  class: \"source-dialog__text\"\n}\nconst _hoisted_11 = {\n  key: 2,\n  class: \"source-dialog__notice\"\n}\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createBlock($setup[\"DialogRoot\"], null, {\n    default: _withCtx(() => [\n      _createVNode($setup[\"DialogTrigger\"], {\n        class: \"source-badge\",\n        title: $setup.label,\n        \"aria-label\": `Bekijk bron: ${$setup.label}`\n      }, {\n        default: _withCtx(() => [\n          _createVNode($setup[\"FileText\"], {\n            size: 12,\n            \"aria-hidden\": \"true\",\n            class: \"source-badge__icon\"\n          }),\n          _createElementVNode(\"span\", _hoisted_1, _toDisplayString($setup.label), 1 /* TEXT */),\n          (typeof $props.score === 'number')\n            ? (_openBlock(), _createElementBlock(\"span\", _hoisted_2, _toDisplayString(Math.round($props.score * 100)) + \"%\", 1 /* TEXT */))\n            : _createCommentVNode(\"v-if\", true)\n        ]),\n        _: 1 /* STABLE */\n      }, 8 /* PROPS */, [\"title\", \"aria-label\"]),\n      _createVNode($setup[\"DialogPortal\"], null, {\n        default: _withCtx(() => [\n          _createVNode($setup[\"DialogOverlay\"], { class: \"source-dialog__overlay\" }),\n          _createVNode($setup[\"DialogContent\"], { class: \"source-dialog\" }, {\n            default: _withCtx(() => [\n              _createElementVNode(\"div\", _hoisted_3, [\n                _createElementVNode(\"div\", _hoisted_4, [\n                  _cache[0] || (_cache[0] = _createElementVNode(\"p\", { class: \"source-dialog__eyebrow\" }, \"Bronvermelding\", -1 /* CACHED */)),\n                  _createVNode($setup[\"DialogTitle\"], { class: \"source-dialog__title\" }, {\n                    default: _withCtx(() => [\n                      _createTextVNode(_toDisplayString($setup.label), 1 /* TEXT */)\n                    ]),\n                    _: 1 /* STABLE */\n                  })\n                ]),\n                _createVNode($setup[\"DialogClose\"], {\n                  class: \"source-dialog__close\",\n                  \"aria-label\": \"Bron sluiten\"\n                }, {\n                  default: _withCtx(() => [\n                    _createVNode($setup[\"X\"], {\n                      size: 20,\n                      \"aria-hidden\": \"true\"\n                    })\n                  ]),\n                  _: 1 /* STABLE */\n                })\n              ]),\n              _createVNode($setup[\"DialogDescription\"], { class: \"source-dialog__description\" }, {\n                default: _withCtx(() => _cache[1] || (_cache[1] = [\n                  _createTextVNode(\" Bekijk de tekst die bij dit antwoord als bron is gebruikt. \", -1 /* CACHED */)\n                ])),\n                _: 1 /* STABLE */,\n                __: [1]\n              }),\n              _createElementVNode(\"div\", _hoisted_5, [\n                ($setup.missingTitle)\n                  ? (_openBlock(), _createElementBlock(\"p\", _hoisted_6, \"De naam van dit document is nog niet beschikbaar.\"))\n                  : _createCommentVNode(\"v-if\", true),\n                (!$setup.passages.length)\n                  ? (_openBlock(), _createElementBlock(\"p\", _hoisted_7, \" Het bijbehorende bronfragment is niet beschikbaar in dit gesprek. \"))\n                  : _createCommentVNode(\"v-if\", true),\n                (_openBlock(true), _createElementBlock(_Fragment, null, _renderList($setup.passages, (passage) => {\n                  return (_openBlock(), _createElementBlock(\"section\", {\n                    key: passage.id,\n                    class: \"source-dialog__passage\"\n                  }, [\n                    _createElementVNode(\"h3\", _hoisted_8, _toDisplayString($setup.passageLabel(passage)), 1 /* TEXT */),\n                    (passage.textTruncated)\n                      ? (_openBlock(), _createElementBlock(\"p\", _hoisted_9, \" Bij dit oudere gesprek is alleen een verkort bronfragment bewaard. De volledige oorspronkelijke tekst is hier niet beschikbaar. \"))\n                      : _createCommentVNode(\"v-if\", true),\n                    (passage.text)\n                      ? (_openBlock(), _createElementBlock(\"p\", _hoisted_10, _toDisplayString(passage.text), 1 /* TEXT */))\n                      : (_openBlock(), _createElementBlock(\"p\", _hoisted_11, \"De tekst van dit bronfragment is niet beschikbaar.\"))\n                  ]))\n                }), 128 /* KEYED_FRAGMENT */))\n              ])\n            ]),\n            _: 1 /* STABLE */\n          })\n        ]),\n        _: 1 /* STABLE */\n      })\n    ]),\n    _: 1 /* STABLE */\n  }))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/SourceBadge.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/SourceBadge.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/SourceBadge.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/SourceBadge.vue\";script.__scopeId = \"data-v-17f9a683\";export default script;","import { createVNode as _createVNode, toDisplayString as _toDisplayString, createElementVNode as _createElementVNode, normalizeClass as _normalizeClass, renderList as _renderList, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock, createBlock as _createBlock, createCommentVNode as _createCommentVNode, vShow as _vShow, withDirectives as _withDirectives } from \"vue\"\n\nconst _hoisted_1 = { class: \"cot\" }\nconst _hoisted_2 = { class: \"cot__title\" }\nconst _hoisted_3 = { class: \"cot__content\" }\nconst _hoisted_4 = {\n  key: 2,\n  class: \"cot__line\"\n}\nconst _hoisted_5 = { class: \"cot__body\" }\nconst _hoisted_6 = { class: \"cot__label\" }\nconst _hoisted_7 = {\n  key: 0,\n  class: \"cot__desc\"\n}\nconst _hoisted_8 = {\n  key: 1,\n  class: \"cot__results\"\n}\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createElementBlock(\"div\", _hoisted_1, [\n    _createElementVNode(\"button\", {\n      type: \"button\",\n      class: \"cot__header\",\n      onClick: _cache[0] || (_cache[0] = $event => ($setup.isOpen = !$setup.isOpen))\n    }, [\n      _createVNode($setup[\"Brain\"], { size: 16 }),\n      _createElementVNode(\"span\", _hoisted_2, _toDisplayString($setup.headerText), 1 /* TEXT */),\n      _createVNode($setup[\"ChevronDown\"], {\n        size: 16,\n        class: _normalizeClass([\"cot__chevron\", { 'cot__chevron--open': $setup.isOpen }])\n      }, null, 8 /* PROPS */, [\"class\"])\n    ]),\n    _withDirectives(_createElementVNode(\"div\", _hoisted_3, [\n      (_openBlock(true), _createElementBlock(_Fragment, null, _renderList($props.toolParts, (part, i) => {\n        return (_openBlock(), _createElementBlock(\"div\", {\n          key: part.toolCallId ?? i,\n          class: \"cot__step\"\n        }, [\n          _createElementVNode(\"div\", {\n            class: _normalizeClass([\"cot__icon\", { 'cot__icon--active': !$setup.isComplete(part) }])\n          }, [\n            (!$setup.isComplete(part))\n              ? (_openBlock(), _createBlock($setup[\"Loader2\"], {\n                  key: 0,\n                  size: 15,\n                  class: \"cot__spin\"\n                }))\n              : (_openBlock(), _createBlock($setup[\"Search\"], {\n                  key: 1,\n                  size: 15\n                })),\n            (i < $props.toolParts.length - 1)\n              ? (_openBlock(), _createElementBlock(\"span\", _hoisted_4))\n              : _createCommentVNode(\"v-if\", true)\n          ], 2 /* CLASS */),\n          _createElementVNode(\"div\", _hoisted_5, [\n            _createElementVNode(\"div\", _hoisted_6, _toDisplayString($setup.queryOf(part) || \"Zoeken…\"), 1 /* TEXT */),\n            ($setup.isComplete(part))\n              ? (_openBlock(), _createElementBlock(\"div\", _hoisted_7, _toDisplayString($setup.resultsOf(part).length) + \" bronnen gevonden\", 1 /* TEXT */))\n              : _createCommentVNode(\"v-if\", true),\n            ($setup.isComplete(part) && $setup.resultsOf(part).length)\n              ? (_openBlock(), _createElementBlock(\"div\", _hoisted_8, [\n                  (_openBlock(true), _createElementBlock(_Fragment, null, _renderList($setup.resultsOf(part), (r) => {\n                    return (_openBlock(), _createBlock($setup[\"SourceBadge\"], {\n                      key: r.id,\n                      reference: r.id,\n                      sources: [r],\n                      score: r.score\n                    }, null, 8 /* PROPS */, [\"reference\", \"sources\", \"score\"]))\n                  }), 128 /* KEYED_FRAGMENT */))\n                ]))\n              : _createCommentVNode(\"v-if\", true)\n          ])\n        ]))\n      }), 128 /* KEYED_FRAGMENT */))\n    ], 512 /* NEED_PATCH */), [\n      [_vShow, $setup.isOpen]\n    ])\n  ]))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChainOfThought.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChainOfThought.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChainOfThought.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChainOfThought.vue\";script.__scopeId = \"data-v-c18f5606\";export default script;","<script setup lang=\"ts\">\n// StreamMarkdown `a`-override. `[Bron: ...]` markers are preprocessed to\n// encoded citation links; those render here as inline badge pills. Any real link\n// renders as a normal anchor.\nimport { computed, inject, shallowRef } from \"vue\";\nimport SourceBadge from \"./SourceBadge.vue\";\nimport { citationReference, citationSourcesKey, type CitationSource } from \"../lib/citations\";\n\nconst props = defineProps<{ href?: string }>();\nconst sources = inject(citationSourcesKey, shallowRef<CitationSource[]>([]));\nconst reference = computed(() => citationReference(props.href));\n</script>\n\n<template>\n  <SourceBadge v-if=\"reference !== null\" :reference=\"reference\" :sources=\"sources\" />\n  <a v-else :href=\"href\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"citation-link\"><slot /></a>\n</template>\n\n<style scoped>\n.citation-link {\n  color: var(--btw-accent);\n  text-decoration: underline;\n  text-underline-offset: 2px;\n}\n</style>\n","import { openBlock as _openBlock, createBlock as _createBlock, createCommentVNode as _createCommentVNode, renderSlot as _renderSlot, createElementBlock as _createElementBlock } from \"vue\"\n\nconst _hoisted_1 = [\"href\"]\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return ($setup.reference !== null)\n    ? (_openBlock(), _createBlock($setup[\"SourceBadge\"], {\n        key: 0,\n        reference: $setup.reference,\n        sources: $setup.sources\n      }, null, 8 /* PROPS */, [\"reference\", \"sources\"]))\n    : (_openBlock(), _createElementBlock(\"a\", {\n        key: 1,\n        href: $props.href,\n        target: \"_blank\",\n        rel: \"noopener noreferrer\",\n        class: \"citation-link\"\n      }, [\n        _renderSlot(_ctx.$slots, \"default\", {}, undefined, true)\n      ], 8 /* PROPS */, _hoisted_1))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/CitationLink.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/CitationLink.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/CitationLink.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/CitationLink.vue\";script.__scopeId = \"data-v-82ab7bd3\";export default script;","<template>\n  <div class=\"actions\">\n    <button\n      type=\"button\"\n      class=\"actions__btn\"\n      :aria-label=\"copied ? 'Gekopieerd' : 'Kopieer antwoord'\"\n      :title=\"copied ? 'Gekopieerd' : 'Kopieer'\"\n      @click=\"copy\"\n    >\n      <Check v-if=\"copied\" :size=\"15\" />\n      <Copy v-else :size=\"15\" />\n    </button>\n\n    <button\n      type=\"button\"\n      class=\"actions__btn\"\n      :class=\"{ 'actions__btn--active': feedback?.rating === 'positive' }\"\n      :aria-pressed=\"feedback?.rating === 'positive'\"\n      aria-label=\"Positieve feedback\"\n      title=\"Goed antwoord\"\n      @click=\"$emit('feedback', 'positive')\"\n    >\n      <ThumbsUp :size=\"15\" />\n    </button>\n\n    <button\n      type=\"button\"\n      class=\"actions__btn\"\n      :class=\"{ 'actions__btn--active': feedback?.rating === 'negative' }\"\n      :aria-pressed=\"feedback?.rating === 'negative'\"\n      aria-label=\"Negatieve feedback\"\n      title=\"Kan beter\"\n      @click=\"$emit('feedback', 'negative')\"\n    >\n      <ThumbsDown :size=\"15\" />\n    </button>\n  </div>\n</template>\n\n<script setup lang=\"ts\">\nimport { onBeforeUnmount, ref } from \"vue\";\nimport { Copy, Check, ThumbsUp, ThumbsDown } from \"lucide-vue-next\";\nimport type { FeedbackState } from \"../lib/chatHistory\";\n\nconst props = defineProps<{ text: string; feedback?: FeedbackState | null }>();\ndefineEmits<{ (e: \"feedback\", rating: \"positive\" | \"negative\"): void }>();\n\nconst copied = ref(false);\nlet timer: ReturnType<typeof setTimeout> | undefined;\n\nasync function copy() {\n  try {\n    await navigator.clipboard.writeText(props.text);\n    copied.value = true;\n    if (timer) clearTimeout(timer);\n    timer = setTimeout(() => { copied.value = false; }, 1500);\n  } catch {\n    // Clipboard blocked (insecure context / permissions): silently ignore.\n  }\n}\n\nonBeforeUnmount(() => { if (timer) clearTimeout(timer); });\n</script>\n\n<style scoped>\n.actions {\n  display: flex;\n  align-items: center;\n  gap: 2px;\n  margin-top: 2px;\n}\n.actions__btn {\n  display: grid;\n  place-items: center;\n  width: 30px;\n  height: 30px;\n  border: 0;\n  border-radius: 8px;\n  background: transparent;\n  color: var(--btw-fg-subtle);\n  cursor: pointer;\n  transition: background 0.12s, color 0.12s;\n}\n.actions__btn:hover {\n  background: var(--btw-surface-2);\n  color: var(--btw-fg);\n}\n.actions__btn--active {\n  color: var(--btw-accent);\n}\n.actions__btn--active:hover {\n  color: var(--btw-accent);\n}\n</style>\n","import { openBlock as _openBlock, createBlock as _createBlock, createCommentVNode as _createCommentVNode, createElementVNode as _createElementVNode, createVNode as _createVNode, normalizeClass as _normalizeClass, createElementBlock as _createElementBlock } from \"vue\"\n\nconst _hoisted_1 = { class: \"actions\" }\nconst _hoisted_2 = [\"aria-label\", \"title\"]\nconst _hoisted_3 = [\"aria-pressed\"]\nconst _hoisted_4 = [\"aria-pressed\"]\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createElementBlock(\"div\", _hoisted_1, [\n    _createElementVNode(\"button\", {\n      type: \"button\",\n      class: \"actions__btn\",\n      \"aria-label\": $setup.copied ? 'Gekopieerd' : 'Kopieer antwoord',\n      title: $setup.copied ? 'Gekopieerd' : 'Kopieer',\n      onClick: $setup.copy\n    }, [\n      ($setup.copied)\n        ? (_openBlock(), _createBlock($setup[\"Check\"], {\n            key: 0,\n            size: 15\n          }))\n        : (_openBlock(), _createBlock($setup[\"Copy\"], {\n            key: 1,\n            size: 15\n          }))\n    ], 8 /* PROPS */, _hoisted_2),\n    _createElementVNode(\"button\", {\n      type: \"button\",\n      class: _normalizeClass([\"actions__btn\", { 'actions__btn--active': $props.feedback?.rating === 'positive' }]),\n      \"aria-pressed\": $props.feedback?.rating === 'positive',\n      \"aria-label\": \"Positieve feedback\",\n      title: \"Goed antwoord\",\n      onClick: _cache[0] || (_cache[0] = $event => (_ctx.$emit('feedback', 'positive')))\n    }, [\n      _createVNode($setup[\"ThumbsUp\"], { size: 15 })\n    ], 10 /* CLASS, PROPS */, _hoisted_3),\n    _createElementVNode(\"button\", {\n      type: \"button\",\n      class: _normalizeClass([\"actions__btn\", { 'actions__btn--active': $props.feedback?.rating === 'negative' }]),\n      \"aria-pressed\": $props.feedback?.rating === 'negative',\n      \"aria-label\": \"Negatieve feedback\",\n      title: \"Kan beter\",\n      onClick: _cache[1] || (_cache[1] = $event => (_ctx.$emit('feedback', 'negative')))\n    }, [\n      _createVNode($setup[\"ThumbsDown\"], { size: 15 })\n    ], 10 /* CLASS, PROPS */, _hoisted_4)\n  ]))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/MessageActions.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/MessageActions.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/MessageActions.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/MessageActions.vue\";script.__scopeId = \"data-v-467940c3\";export default script;","import { createCommentVNode as _createCommentVNode, openBlock as _openBlock, createBlock as _createBlock, renderList as _renderList, Fragment as _Fragment, createElementBlock as _createElementBlock, createElementVNode as _createElementVNode, normalizeClass as _normalizeClass } from \"vue\"\n\nconst _hoisted_1 = { class: \"msg__content\" }\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createElementBlock(\"div\", {\n    class: _normalizeClass([\"msg\", $props.message.role === 'user' ? 'msg--user' : 'msg--assistant'])\n  }, [\n    _createElementVNode(\"div\", _hoisted_1, [\n      _createCommentVNode(\" 1. Reasoning (if any) \"),\n      ($setup.hasReasoning)\n        ? (_openBlock(), _createBlock($setup[\"Reasoning\"], {\n            key: 0,\n            reasoning: $setup.reasoningText,\n            \"is-streaming\": $setup.isReasoningStreaming\n          }, null, 8 /* PROPS */, [\"reasoning\", \"is-streaming\"]))\n        : _createCommentVNode(\"v-if\", true),\n      _createCommentVNode(\" 2. Chain-of-thought / sources (if any tool calls) \"),\n      ($setup.toolParts.length)\n        ? (_openBlock(), _createBlock($setup[\"ChainOfThought\"], {\n            key: 1,\n            \"tool-parts\": $setup.toolParts\n          }, null, 8 /* PROPS */, [\"tool-parts\"]))\n        : _createCommentVNode(\"v-if\", true),\n      _createCommentVNode(\" 3. Text parts, in order, with citation badges \"),\n      (_openBlock(true), _createElementBlock(_Fragment, null, _renderList($props.message.parts, (part, i) => {\n        return (_openBlock(), _createElementBlock(_Fragment, {\n          key: `${$props.message.id}-${i}`\n        }, [\n          (part.type === 'text')\n            ? (_openBlock(), _createBlock($setup[\"StreamMarkdown\"], {\n                key: 0,\n                class: \"msg__markdown\",\n                content: $props.message.role === 'assistant' ? $setup.preprocessCitations(part.text) : part.text,\n                components: $setup.markdownComponents,\n                \"allowed-link-prefixes\": $setup.markdownLinkPrefixes\n              }, null, 8 /* PROPS */, [\"content\"]))\n            : _createCommentVNode(\"v-if\", true)\n        ], 64 /* STABLE_FRAGMENT */))\n      }), 128 /* KEYED_FRAGMENT */))\n    ]),\n    _createCommentVNode(\" Actiebalk (kopiëren + feedback) onder een afgerond assistant-antwoord. \"),\n    ($setup.showActions)\n      ? (_openBlock(), _createBlock($setup[\"MessageActions\"], {\n          key: 0,\n          text: $setup.assistantText,\n          feedback: $props.feedback,\n          onFeedback: _cache[0] || (_cache[0] = (rating) => _ctx.$emit('feedback', rating))\n        }, null, 8 /* PROPS */, [\"text\", \"feedback\"]))\n      : _createCommentVNode(\"v-if\", true)\n  ], 2 /* CLASS */))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/MessageItem.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/MessageItem.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/MessageItem.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/MessageItem.vue\";script.__scopeId = \"data-v-a1be3da0\";export default script;","import { createElementVNode as _createElementVNode, renderList as _renderList, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock, createVNode as _createVNode, toDisplayString as _toDisplayString, withCtx as _withCtx, createBlock as _createBlock } from \"vue\"\n\nconst _hoisted_1 = [\"onClick\"]\nconst _hoisted_2 = { class: \"picker__text\" }\nconst _hoisted_3 = { class: \"picker__title\" }\nconst _hoisted_4 = { class: \"picker__desc\" }\nconst _hoisted_5 = { class: \"picker__count\" }\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createBlock($setup[\"ResizableDialog\"], {\n    open: $props.open,\n    title: \"Kies een testgesprek\",\n    \"dialog-id\": \"test-mode-picker\",\n    \"default-width\": 480,\n    \"default-height\": 440,\n    \"onUpdate:open\": _cache[0] || (_cache[0] = $event => (_ctx.$emit('update:open', $event)))\n  }, {\n    default: _withCtx(() => [\n      _cache[1] || (_cache[1] = _createElementVNode(\"p\", { class: \"picker__intro\" }, \"Selecteer een voorbeeldgesprek om de BTW Coach te demonstreren.\", -1 /* CACHED */)),\n      (_openBlock(true), _createElementBlock(_Fragment, null, _renderList($props.conversations, (conv) => {\n        return (_openBlock(), _createElementBlock(\"button\", {\n          key: conv.id,\n          type: \"button\",\n          class: \"picker__card\",\n          onClick: $event => (_ctx.$emit('select', conv.id))\n        }, [\n          _createVNode($setup[\"MessageSquare\"], {\n            size: 16,\n            class: \"picker__icon\"\n          }),\n          _createElementVNode(\"span\", _hoisted_2, [\n            _createElementVNode(\"span\", _hoisted_3, _toDisplayString(conv.title), 1 /* TEXT */),\n            _createElementVNode(\"span\", _hoisted_4, _toDisplayString(conv.description), 1 /* TEXT */),\n            _createElementVNode(\"span\", _hoisted_5, _toDisplayString(conv.questions.length) + \" vragen\", 1 /* TEXT */)\n          ])\n        ], 8 /* PROPS */, _hoisted_1))\n      }), 128 /* KEYED_FRAGMENT */))\n    ]),\n    _: 1 /* STABLE */,\n    __: [1]\n  }, 8 /* PROPS */, [\"open\"]))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/TestModePicker.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/TestModePicker.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/TestModePicker.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/TestModePicker.vue\";script.__scopeId = \"data-v-545e2657\";export default script;","<template>\n  <Teleport to=\"body\">\n    <div v-if=\"open\" class=\"fdialog\" @keydown.esc=\"close\">\n      <div class=\"fdialog__overlay\" @click=\"close\" />\n      <div class=\"fdialog__box\" role=\"dialog\" aria-modal=\"true\" :aria-label=\"title\">\n        <div class=\"fdialog__header\">\n          <h2 class=\"fdialog__title\">{{ title }}</h2>\n          <button type=\"button\" class=\"fdialog__close\" aria-label=\"Sluiten\" @click=\"close\">\n            <X :size=\"18\" />\n          </button>\n        </div>\n\n        <div class=\"fdialog__body\">\n          <label class=\"fdialog__label\" :for=\"fieldId\">\n            {{ rating === \"negative\" ? \"Wat kan er beter? (verplicht)\" : \"Toelichting (optioneel)\" }}\n          </label>\n          <textarea\n            :id=\"fieldId\"\n            ref=\"textareaEl\"\n            v-model=\"comment\"\n            class=\"fdialog__textarea\"\n            :placeholder=\"placeholder\"\n            rows=\"4\"\n          />\n          <p v-if=\"rating === 'negative' && !isValid\" class=\"fdialog__hint\">\n            Vul een toelichting in.\n          </p>\n        </div>\n\n        <div class=\"fdialog__footer\">\n          <button type=\"button\" class=\"fdialog__btn fdialog__btn--ghost\" @click=\"close\">\n            Annuleren\n          </button>\n          <button\n            type=\"button\"\n            class=\"fdialog__btn fdialog__btn--primary\"\n            :disabled=\"!isValid\"\n            @click=\"submit\"\n          >\n            Versturen\n          </button>\n        </div>\n      </div>\n    </div>\n  </Teleport>\n</template>\n\n<script setup lang=\"ts\">\nimport { computed, nextTick, ref, watch } from \"vue\";\nimport { X } from \"lucide-vue-next\";\n\nconst props = defineProps<{\n  open: boolean;\n  rating: \"positive\" | \"negative\";\n  existingComment?: string;\n}>();\nconst emit = defineEmits<{\n  (e: \"update:open\", value: boolean): void;\n  (e: \"submit\", comment: string): void;\n}>();\n\nconst comment = ref(\"\");\nconst textareaEl = ref<HTMLTextAreaElement | null>(null);\nconst fieldId = `fb-${Math.round(performance.now())}`;\n\nconst title = computed(() =>\n  props.rating === \"negative\" ? \"Negatieve feedback geven\" : \"Positieve feedback\",\n);\nconst placeholder = computed(() =>\n  props.rating === \"negative\"\n    ? \"Wat was er mis of onvolledig aan dit antwoord?\"\n    : \"Wat vond je goed aan dit antwoord?\",\n);\n// Negative feedback requires a comment; positive is always valid.\nconst isValid = computed(() => props.rating === \"positive\" || comment.value.trim().length > 0);\n\n// Prefill with any existing comment and focus the field when opened.\nwatch(\n  () => props.open,\n  async (isOpen) => {\n    if (isOpen) {\n      comment.value = props.existingComment ?? \"\";\n      await nextTick();\n      textareaEl.value?.focus();\n    }\n  },\n);\n\nfunction close() {\n  emit(\"update:open\", false);\n}\n\nfunction submit() {\n  if (!isValid.value) return;\n  emit(\"submit\", comment.value.trim());\n}\n</script>\n\n<style scoped>\n.fdialog {\n  position: fixed;\n  inset: 0;\n  z-index: 100;\n  display: grid;\n  place-items: center;\n  animation: btw-fade 0.15s var(--ease-out);\n}\n.fdialog__overlay {\n  position: absolute;\n  inset: 0;\n  background: rgba(0, 0, 0, 0.45);\n  backdrop-filter: blur(2px);\n}\n.fdialog__box {\n  position: relative;\n  display: flex;\n  flex-direction: column;\n  width: 92vw;\n  max-width: 480px;\n  border-radius: 16px;\n  background: var(--btw-surface);\n  border: 1px solid var(--btw-line-strong);\n  box-shadow: var(--btw-shadow-card);\n  overflow: hidden;\n}\n.fdialog__header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: 12px;\n  padding: 16px 16px 4px;\n}\n.fdialog__title {\n  margin: 0;\n  font-size: 16px;\n  font-weight: 700;\n  color: var(--btw-fg);\n}\n.fdialog__close {\n  display: grid;\n  place-items: center;\n  width: 30px;\n  height: 30px;\n  border: 0;\n  border-radius: 8px;\n  background: transparent;\n  color: var(--btw-fg-muted);\n  cursor: pointer;\n  transition: background 0.12s, color 0.12s;\n}\n.fdialog__close:hover { background: var(--btw-surface-2); color: var(--btw-fg); }\n.fdialog__body {\n  padding: 8px 16px 4px;\n}\n.fdialog__label {\n  display: block;\n  margin-bottom: 6px;\n  font-size: 13px;\n  color: var(--btw-fg-muted);\n}\n.fdialog__textarea {\n  width: 100%;\n  padding: 10px 12px;\n  border: 1px solid var(--btw-line);\n  border-radius: 10px;\n  background: var(--btw-surface-2);\n  color: var(--btw-fg);\n  font-family: inherit;\n  font-size: 14px;\n  line-height: 1.5;\n  resize: vertical;\n}\n.fdialog__textarea:focus {\n  outline: none;\n  border-color: var(--btw-accent);\n}\n.fdialog__hint {\n  margin: 6px 0 0;\n  font-size: 12px;\n  color: var(--btw-fg-subtle);\n}\n.fdialog__footer {\n  display: flex;\n  justify-content: flex-end;\n  gap: 8px;\n  padding: 12px 16px 16px;\n}\n.fdialog__btn {\n  padding: 8px 16px;\n  border-radius: 10px;\n  font-size: 14px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: background 0.12s, color 0.12s, opacity 0.12s;\n}\n.fdialog__btn--ghost {\n  border: 1px solid var(--btw-line);\n  background: transparent;\n  color: var(--btw-fg-muted);\n}\n.fdialog__btn--ghost:hover { background: var(--btw-surface-2); color: var(--btw-fg); }\n.fdialog__btn--primary {\n  border: 1px solid var(--btw-accent);\n  background: var(--btw-accent);\n  color: var(--btw-accent-fg, #fff);\n}\n.fdialog__btn--primary:hover:not(:disabled) { filter: brightness(1.05); }\n.fdialog__btn--primary:disabled {\n  opacity: 0.5;\n  cursor: not-allowed;\n}\n</style>\n","import { createElementVNode as _createElementVNode, toDisplayString as _toDisplayString, createVNode as _createVNode, vModelText as _vModelText, withDirectives as _withDirectives, openBlock as _openBlock, createElementBlock as _createElementBlock, createCommentVNode as _createCommentVNode, withKeys as _withKeys, Teleport as _Teleport, createBlock as _createBlock } from \"vue\"\n\nconst _hoisted_1 = [\"aria-label\"]\nconst _hoisted_2 = { class: \"fdialog__header\" }\nconst _hoisted_3 = { class: \"fdialog__title\" }\nconst _hoisted_4 = { class: \"fdialog__body\" }\nconst _hoisted_5 = [\"placeholder\"]\nconst _hoisted_6 = {\n  key: 0,\n  class: \"fdialog__hint\"\n}\nconst _hoisted_7 = { class: \"fdialog__footer\" }\nconst _hoisted_8 = [\"disabled\"]\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createBlock(_Teleport, { to: \"body\" }, [\n    ($props.open)\n      ? (_openBlock(), _createElementBlock(\"div\", {\n          key: 0,\n          class: \"fdialog\",\n          onKeydown: _withKeys($setup.close, [\"esc\"])\n        }, [\n          _createElementVNode(\"div\", {\n            class: \"fdialog__overlay\",\n            onClick: $setup.close\n          }),\n          _createElementVNode(\"div\", {\n            class: \"fdialog__box\",\n            role: \"dialog\",\n            \"aria-modal\": \"true\",\n            \"aria-label\": $setup.title\n          }, [\n            _createElementVNode(\"div\", _hoisted_2, [\n              _createElementVNode(\"h2\", _hoisted_3, _toDisplayString($setup.title), 1 /* TEXT */),\n              _createElementVNode(\"button\", {\n                type: \"button\",\n                class: \"fdialog__close\",\n                \"aria-label\": \"Sluiten\",\n                onClick: $setup.close\n              }, [\n                _createVNode($setup[\"X\"], { size: 18 })\n              ])\n            ]),\n            _createElementVNode(\"div\", _hoisted_4, [\n              _createElementVNode(\"label\", {\n                class: \"fdialog__label\",\n                for: $setup.fieldId\n              }, _toDisplayString($props.rating === \"negative\" ? \"Wat kan er beter? (verplicht)\" : \"Toelichting (optioneel)\"), 1 /* TEXT */),\n              _withDirectives(_createElementVNode(\"textarea\", {\n                id: $setup.fieldId,\n                ref: \"textareaEl\",\n                \"onUpdate:modelValue\": _cache[0] || (_cache[0] = $event => (($setup.comment) = $event)),\n                class: \"fdialog__textarea\",\n                placeholder: $setup.placeholder,\n                rows: \"4\"\n              }, null, 8 /* PROPS */, _hoisted_5), [\n                [_vModelText, $setup.comment]\n              ]),\n              ($props.rating === 'negative' && !$setup.isValid)\n                ? (_openBlock(), _createElementBlock(\"p\", _hoisted_6, \" Vul een toelichting in. \"))\n                : _createCommentVNode(\"v-if\", true)\n            ]),\n            _createElementVNode(\"div\", _hoisted_7, [\n              _createElementVNode(\"button\", {\n                type: \"button\",\n                class: \"fdialog__btn fdialog__btn--ghost\",\n                onClick: $setup.close\n              }, \" Annuleren \"),\n              _createElementVNode(\"button\", {\n                type: \"button\",\n                class: \"fdialog__btn fdialog__btn--primary\",\n                disabled: !$setup.isValid,\n                onClick: $setup.submit\n              }, \" Versturen \", 8 /* PROPS */, _hoisted_8)\n            ])\n          ], 8 /* PROPS */, _hoisted_1)\n        ], 32 /* NEED_HYDRATION */))\n      : _createCommentVNode(\"v-if\", true)\n  ]))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/FeedbackDialog.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/FeedbackDialog.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/FeedbackDialog.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/FeedbackDialog.vue\";script.__scopeId = \"data-v-44017205\";export default script;","import { reactive } from \"vue\";\nimport { useChat } from \"@ai-sdk/vue\";\nimport { DefaultChatTransport, type UIMessage } from \"ai\";\nimport { chatApiUrl, chatFetch } from \"./chatGateway\";\n\n// ── Chat factory ─────────────────────────────────────────────────────────────\n// Reads the current mock-mode + model selection per request via getters, so the\n// same chat follows the user's live selection without re-creation.\n\nexport interface CreateChatOptions {\n  getMockMode: () => boolean;\n  getModelId: () => string;\n  /** Fixed conversation id (URL/persistence key + server WRD conversation key). */\n  id?: string;\n  /** Messages restored from a persisted conversation on refresh. */\n  initialMessages?: UIMessage[];\n}\n\n/** Must be called from a component's setup. reactive() unwraps useChat's refs, so callers read chat.messages / chat.status. */\nexport function createChat(opts: CreateChatOptions) {\n  return reactive(useChat<UIMessage>({\n    id: opts.id,\n    // useChat pushes into this array in place; copy it so the caller's snapshot stays untouched.\n    messages: opts.initialMessages ? [...opts.initialMessages] : undefined,\n    onError: (error) => {\n      console.error(\"Chat request failed:\", error);\n    },\n    transport: new DefaultChatTransport<UIMessage>({\n      api: chatApiUrl(\"chat\"),\n      // Adds the bearer token, renews it near expiry and retries once on a 401.\n      fetch: chatFetch,\n      // Returning `body` REPLACES the default body (still so in ai@7), so id,\n      // messages, trigger and messageId are re-included next to our own fields.\n      prepareSendMessagesRequest: ({ id, messages, trigger, messageId, body }) => ({\n        body: {\n          ...body,\n          id,\n          messages,\n          trigger,\n          messageId,\n          mockMode: opts.getMockMode(),\n          modelId: opts.getModelId(),\n        },\n      }),\n    }),\n  }));\n}\n\nexport type BtwChat = ReturnType<typeof createChat>;\n","/**\n * Symbol used for identifying AI SDK Error instances.\n * Enables checking if an error is an instance of AISDKError across package versions.\n */\nconst marker = 'vercel.ai.error';\nconst symbol = Symbol.for(marker);\n\n/**\n * Custom error class for AI SDK related errors.\n * @extends Error\n */\nexport class AISDKError extends Error {\n  private readonly [symbol] = true; // used in isInstance\n\n  /**\n   * The underlying cause of the error, if any.\n   */\n  readonly cause?: unknown;\n\n  /**\n   * Creates an AI SDK Error.\n   *\n   * @param {Object} params - The parameters for creating the error.\n   * @param {string} params.name - The name of the error.\n   * @param {string} params.message - The error message.\n   * @param {unknown} [params.cause] - The underlying cause of the error.\n   */\n  constructor({\n    name,\n    message,\n    cause,\n  }: {\n    name: string;\n    message: string;\n    cause?: unknown;\n  }) {\n    super(message);\n\n    this.name = name;\n    this.cause = cause;\n  }\n\n  /**\n   * Checks if the given error is an AI SDK Error.\n   * @param {unknown} error - The error to check.\n   * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n   */\n  static isInstance(error: unknown): error is AISDKError {\n    return AISDKError.hasMarker(error, marker);\n  }\n\n  protected static hasMarker(error: unknown, marker: string): boolean {\n    const markerSymbol = Symbol.for(marker);\n    return (\n      error != null &&\n      typeof error === 'object' &&\n      markerSymbol in error &&\n      typeof error[markerSymbol] === 'boolean' &&\n      error[markerSymbol] === true\n    );\n  }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_APICallError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class APICallError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly url: string;\n  readonly requestBodyValues: unknown;\n  readonly statusCode?: number;\n\n  readonly responseHeaders?: Record<string, string>;\n  readonly responseBody?: string;\n\n  readonly isRetryable: boolean;\n  readonly data?: unknown;\n\n  constructor({\n    message,\n    url,\n    requestBodyValues,\n    statusCode,\n    responseHeaders,\n    responseBody,\n    cause,\n    isRetryable = statusCode != null &&\n      (statusCode === 408 || // request timeout\n        statusCode === 409 || // conflict\n        statusCode === 429 || // too many requests\n        statusCode >= 500), // server error\n    data,\n  }: {\n    message: string;\n    url: string;\n    requestBodyValues: unknown;\n    statusCode?: number;\n    responseHeaders?: Record<string, string>;\n    responseBody?: string;\n    cause?: unknown;\n    isRetryable?: boolean;\n    data?: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.url = url;\n    this.requestBodyValues = requestBodyValues;\n    this.statusCode = statusCode;\n    this.responseHeaders = responseHeaders;\n    this.responseBody = responseBody;\n    this.isRetryable = isRetryable;\n    this.data = data;\n  }\n\n  static isInstance(error: unknown): error is APICallError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_EmptyResponseBodyError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class EmptyResponseBodyError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({ message = 'Empty response body' }: { message?: string } = {}) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is EmptyResponseBodyError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_EvaluationUnsupportedQuestionTypeError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * An evaluation model does not support the type of a requested question.\n */\nexport class EvaluationUnsupportedQuestionTypeError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly questionId: string;\n  readonly questionType: string;\n  readonly provider: string;\n  readonly modelId: string;\n\n  constructor({\n    questionId,\n    questionType,\n    provider,\n    modelId,\n    message = `Question \"${questionId}\" has type \"${questionType}\", which is not supported by provider \"${provider}\" and model \"${modelId}\".`,\n  }: {\n    questionId: string;\n    questionType: string;\n    provider: string;\n    modelId: string;\n    message?: string;\n  }) {\n    super({ name, message });\n\n    this.questionId = questionId;\n    this.questionType = questionType;\n    this.provider = provider;\n    this.modelId = modelId;\n  }\n\n  static isInstance(\n    error: unknown,\n  ): error is EvaluationUnsupportedQuestionTypeError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","export function getErrorMessage(error: unknown | undefined) {\n  if (error == null) {\n    return 'unknown error';\n  }\n\n  if (typeof error === 'string') {\n    return error;\n  }\n\n  if (error instanceof Error) {\n    return error.toString();\n  }\n\n  return JSON.stringify(error);\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidArgumentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * A function argument is invalid.\n */\nexport class InvalidArgumentError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly argument: string;\n\n  constructor({\n    message,\n    cause,\n    argument,\n  }: {\n    argument: string;\n    message: string;\n    cause?: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.argument = argument;\n  }\n\n  static isInstance(error: unknown): error is InvalidArgumentError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidPromptError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * A prompt is invalid. This error should be thrown by providers when they cannot\n * process a prompt.\n */\nexport class InvalidPromptError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly prompt: unknown;\n\n  constructor({\n    prompt,\n    message,\n    cause,\n  }: {\n    prompt: unknown;\n    message: string;\n    cause?: unknown;\n  }) {\n    super({ name, message: `Invalid prompt: ${message}`, cause });\n\n    this.prompt = prompt;\n  }\n\n  static isInstance(error: unknown): error is InvalidPromptError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidResponseDataError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Server returned a response with invalid data content.\n * This should be thrown by providers when they cannot parse the response from the API.\n */\nexport class InvalidResponseDataError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly data: unknown;\n\n  constructor({\n    data,\n    message = `Invalid response data: ${JSON.stringify(data)}.`,\n  }: {\n    data: unknown;\n    message?: string;\n  }) {\n    super({ name, message });\n\n    this.data = data;\n  }\n\n  static isInstance(error: unknown): error is InvalidResponseDataError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from './ai-sdk-error';\nimport { getErrorMessage } from './get-error-message';\n\nconst name = 'AI_JSONParseError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class JSONParseError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly text: string;\n\n  constructor({ text, cause }: { text: string; cause: unknown }) {\n    super({\n      name,\n      message:\n        `JSON parsing failed: ` +\n        `Text: ${text}.\\n` +\n        `Error message: ${getErrorMessage(cause)}`,\n      cause,\n    });\n\n    this.text = text;\n  }\n\n  static isInstance(error: unknown): error is JSONParseError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_LoadAPIKeyError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class LoadAPIKeyError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({ message }: { message: string }) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is LoadAPIKeyError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_LoadSettingError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class LoadSettingError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({ message }: { message: string }) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is LoadSettingError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_NoContentGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Thrown when the AI provider fails to generate any content.\n */\nexport class NoContentGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({\n    message = 'No content generated.',\n  }: { message?: string } = {}) {\n    super({ name, message });\n  }\n\n  static isInstance(error: unknown): error is NoContentGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_NoSuchModelError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchModelError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly modelId: string;\n  readonly modelType:\n    | 'languageModel'\n    | 'embeddingModel'\n    | 'imageModel'\n    | 'transcriptionModel'\n    | 'speechModel'\n    | 'rerankingModel'\n    | 'videoModel'\n    | 'evaluationModel';\n\n  constructor({\n    errorName = name,\n    modelId,\n    modelType,\n    message = `No such ${modelType}: ${modelId}`,\n  }: {\n    errorName?: string;\n    modelId: string;\n    modelType:\n      | 'languageModel'\n      | 'embeddingModel'\n      | 'imageModel'\n      | 'transcriptionModel'\n      | 'speechModel'\n      | 'rerankingModel'\n      | 'videoModel'\n      | 'evaluationModel';\n    message?: string;\n  }) {\n    super({ name: errorName, message });\n\n    this.modelId = modelId;\n    this.modelType = modelType;\n  }\n\n  static isInstance(error: unknown): error is NoSuchModelError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import type { SharedV4ProviderReference } from '../shared/v4/shared-v4-provider-reference';\nimport { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_NoSuchProviderReferenceError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Thrown when a provider reference cannot be resolved because the specified\n * provider is not found in the provider reference mapping.\n */\nexport class NoSuchProviderReferenceError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly provider: string;\n  readonly reference: SharedV4ProviderReference;\n\n  constructor({\n    provider,\n    reference,\n    message = `No provider reference found for provider '${provider}'. Available providers: ${Object.keys(reference).join(', ')}`,\n  }: {\n    provider: string;\n    reference: SharedV4ProviderReference;\n    message?: string;\n  }) {\n    super({ name, message });\n    this.provider = provider;\n    this.reference = reference;\n  }\n\n  static isInstance(error: unknown): error is NoSuchProviderReferenceError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_TooManyEmbeddingValuesForCallError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class TooManyEmbeddingValuesForCallError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly provider: string;\n  readonly modelId: string;\n  readonly maxEmbeddingsPerCall: number;\n  readonly values: Array<unknown>;\n\n  constructor(options: {\n    provider: string;\n    modelId: string;\n    maxEmbeddingsPerCall: number;\n    values: Array<unknown>;\n  }) {\n    super({\n      name,\n      message:\n        `Too many values for a single embedding call. ` +\n        `The ${options.provider} model \"${options.modelId}\" can only embed up to ` +\n        `${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`,\n    });\n\n    this.provider = options.provider;\n    this.modelId = options.modelId;\n    this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n    this.values = options.values;\n  }\n\n  static isInstance(\n    error: unknown,\n  ): error is TooManyEmbeddingValuesForCallError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from './ai-sdk-error';\nimport { getErrorMessage } from './get-error-message';\n\nconst name = 'AI_TypeValidationError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport interface TypeValidationContext {\n  /**\n   * Field path in dot notation (e.g., \"message.metadata\", \"message.parts[3].data\")\n   */\n  field?: string;\n\n  /**\n   * Entity name (e.g., tool name, data type name)\n   */\n  entityName?: string;\n\n  /**\n   * Entity identifier (e.g., message ID, tool call ID)\n   */\n  entityId?: string;\n}\n\nexport class TypeValidationError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly value: unknown;\n  readonly context?: TypeValidationContext;\n\n  constructor({\n    value,\n    cause,\n    context,\n  }: {\n    value: unknown;\n    cause: unknown;\n    context?: TypeValidationContext;\n  }) {\n    let contextPrefix = 'Type validation failed';\n\n    if (context?.field) {\n      contextPrefix += ` for ${context.field}`;\n    }\n\n    if (context?.entityName || context?.entityId) {\n      contextPrefix += ' (';\n      const parts: string[] = [];\n      if (context.entityName) {\n        parts.push(context.entityName);\n      }\n      if (context.entityId) {\n        parts.push(`id: \"${context.entityId}\"`);\n      }\n      contextPrefix += parts.join(', ');\n      contextPrefix += ')';\n    }\n\n    super({\n      name,\n      message:\n        `${contextPrefix}: ` +\n        `Value: ${JSON.stringify(value)}.\\n` +\n        `Error message: ${getErrorMessage(cause)}`,\n      cause,\n    });\n\n    this.value = value;\n    this.context = context;\n  }\n\n  static isInstance(error: unknown): error is TypeValidationError {\n    return AISDKError.hasMarker(error, marker);\n  }\n\n  /**\n   * Wraps an error into a TypeValidationError.\n   * If the cause is already a TypeValidationError with the same value and context, it returns the cause.\n   * Otherwise, it creates a new TypeValidationError.\n   *\n   * @param {Object} params - The parameters for wrapping the error.\n   * @param {unknown} params.value - The value that failed validation.\n   * @param {unknown} params.cause - The original error or cause of the validation failure.\n   * @param {TypeValidationContext} params.context - Optional context about what is being validated.\n   * @returns {TypeValidationError} A TypeValidationError instance.\n   */\n  static wrap({\n    value,\n    cause,\n    context,\n  }: {\n    value: unknown;\n    cause: unknown;\n    context?: TypeValidationContext;\n  }): TypeValidationError {\n    if (\n      TypeValidationError.isInstance(cause) &&\n      cause.value === value &&\n      cause.context?.field === context?.field &&\n      cause.context?.entityName === context?.entityName &&\n      cause.context?.entityId === context?.entityId\n    ) {\n      return cause;\n    }\n\n    return new TypeValidationError({ value, cause, context });\n  }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_UnsupportedFunctionalityError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class UnsupportedFunctionalityError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly functionality: string;\n\n  constructor({\n    functionality,\n    message = `'${functionality}' functionality not supported.`,\n  }: {\n    functionality: string;\n    message?: string;\n  }) {\n    super({ name, message });\n    this.functionality = functionality;\n  }\n\n  static isInstance(error: unknown): error is UnsupportedFunctionalityError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import type { JSONArray, JSONObject, JSONValue } from './json-value';\n\nexport function isJSONValue(value: unknown): value is JSONValue {\n  if (\n    value === null ||\n    typeof value === 'string' ||\n    typeof value === 'number' ||\n    typeof value === 'boolean'\n  ) {\n    return true;\n  }\n\n  if (Array.isArray(value)) {\n    return value.every(isJSONValue);\n  }\n\n  if (typeof value === 'object') {\n    return Object.entries(value).every(\n      ([key, val]) =>\n        typeof key === 'string' && (val === undefined || isJSONValue(val)),\n    );\n  }\n\n  return false;\n}\n\nexport function isJSONArray(value: unknown): value is JSONArray {\n  return Array.isArray(value) && value.every(isJSONValue);\n}\n\nexport function isJSONObject(value: unknown): value is JSONObject {\n  return (\n    value != null &&\n    typeof value === 'object' &&\n    Object.entries(value).every(\n      ([key, val]) =>\n        typeof key === 'string' && (val === undefined || isJSONValue(val)),\n    )\n  );\n}\n","var _a;\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n    status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n    function init(inst, def) {\n        if (!inst._zod) {\n            Object.defineProperty(inst, \"_zod\", {\n                value: {\n                    def,\n                    constr: _,\n                    traits: new Set(),\n                },\n                enumerable: false,\n            });\n        }\n        if (inst._zod.traits.has(name)) {\n            return;\n        }\n        inst._zod.traits.add(name);\n        initializer(inst, def);\n        // support prototype modifications\n        const proto = _.prototype;\n        const keys = Object.keys(proto);\n        for (let i = 0; i < keys.length; i++) {\n            const k = keys[i];\n            if (!(k in inst)) {\n                inst[k] = proto[k].bind(inst);\n            }\n        }\n    }\n    // doesn't work if Parent has a constructor with arguments\n    const Parent = params?.Parent ?? Object;\n    class Definition extends Parent {\n    }\n    Object.defineProperty(Definition, \"name\", { value: name });\n    function _(def) {\n        var _a;\n        const inst = params?.Parent ? new Definition() : this;\n        init(inst, def);\n        (_a = inst._zod).deferred ?? (_a.deferred = []);\n        for (const fn of inst._zod.deferred) {\n            fn();\n        }\n        return inst;\n    }\n    Object.defineProperty(_, \"init\", { value: init });\n    Object.defineProperty(_, Symbol.hasInstance, {\n        value: (inst) => {\n            if (params?.Parent && inst instanceof params.Parent)\n                return true;\n            return inst?._zod?.traits?.has(name);\n        },\n    });\n    Object.defineProperty(_, \"name\", { value: name });\n    return _;\n}\n//////////////////////////////   UTILITIES   ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n    constructor() {\n        super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n    }\n}\nexport class $ZodEncodeError extends Error {\n    constructor(name) {\n        super(`Encountered unidirectional transform during encode: ${name}`);\n        this.name = \"ZodEncodeError\";\n    }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n    if (newConfig)\n        Object.assign(globalConfig, newConfig);\n    return globalConfig;\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n    return val;\n}\nexport function assertNotEqual(val) {\n    return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n    throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n    const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n    const values = Object.entries(entries)\n        .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n        .map(([_, v]) => v);\n    return values;\n}\nexport function joinValues(array, separator = \"|\") {\n    return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n    if (typeof value === \"bigint\")\n        return value.toString();\n    return value;\n}\nexport function cached(getter) {\n    const set = false;\n    return {\n        get value() {\n            if (!set) {\n                const value = getter();\n                Object.defineProperty(this, \"value\", { value });\n                return value;\n            }\n            throw new Error(\"cached value already set\");\n        },\n    };\n}\nexport function nullish(input) {\n    return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n    const start = source.startsWith(\"^\") ? 1 : 0;\n    const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n    return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n    const ratio = val / step;\n    const roundedRatio = Math.round(ratio);\n    // Use a relative epsilon scaled to the magnitude of the result\n    const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);\n    if (Math.abs(ratio - roundedRatio) < tolerance)\n        return 0;\n    return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n    let value = undefined;\n    Object.defineProperty(object, key, {\n        get() {\n            if (value === EVALUATING) {\n                // Circular reference detected, return undefined to break the cycle\n                return undefined;\n            }\n            if (value === undefined) {\n                value = EVALUATING;\n                value = getter();\n            }\n            return value;\n        },\n        set(v) {\n            Object.defineProperty(object, key, {\n                value: v,\n                // configurable: true,\n            });\n            // object[key] = v;\n        },\n        configurable: true,\n    });\n}\nexport function objectClone(obj) {\n    return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n    Object.defineProperty(target, prop, {\n        value,\n        writable: true,\n        enumerable: true,\n        configurable: true,\n    });\n}\nexport function mergeDefs(...defs) {\n    const mergedDescriptors = {};\n    for (const def of defs) {\n        const descriptors = Object.getOwnPropertyDescriptors(def);\n        Object.assign(mergedDescriptors, descriptors);\n    }\n    return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n    return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n    if (!path)\n        return obj;\n    return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n    const keys = Object.keys(promisesObj);\n    const promises = keys.map((key) => promisesObj[key]);\n    return Promise.all(promises).then((results) => {\n        const resolvedObj = {};\n        for (let i = 0; i < keys.length; i++) {\n            resolvedObj[keys[i]] = results[i];\n        }\n        return resolvedObj;\n    });\n}\nexport function randomString(length = 10) {\n    const chars = \"abcdefghijklmnopqrstuvwxyz\";\n    let str = \"\";\n    for (let i = 0; i < length; i++) {\n        str += chars[Math.floor(Math.random() * chars.length)];\n    }\n    return str;\n}\nexport function esc(str) {\n    return JSON.stringify(str);\n}\nexport function slugify(input) {\n    return input\n        .toLowerCase()\n        .trim()\n        .replace(/[^\\w\\s-]/g, \"\")\n        .replace(/[\\s_-]+/g, \"-\")\n        .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n    return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n    // Skip the probe under `jitless`: strict CSPs report the caught `new Function`\n    // as a `securitypolicyviolation` even though the throw is swallowed.\n    if (globalConfig.jitless) {\n        return false;\n    }\n    // @ts-ignore\n    if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n        return false;\n    }\n    try {\n        const F = Function;\n        new F(\"\");\n        return true;\n    }\n    catch (_) {\n        return false;\n    }\n});\nexport function isPlainObject(o) {\n    if (isObject(o) === false)\n        return false;\n    // modified constructor\n    const ctor = o.constructor;\n    if (ctor === undefined)\n        return true;\n    if (typeof ctor !== \"function\")\n        return true;\n    // modified prototype\n    const prot = ctor.prototype;\n    if (isObject(prot) === false)\n        return false;\n    // ctor doesn't have static `isPrototypeOf`\n    if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n        return false;\n    }\n    return true;\n}\nexport function shallowClone(o) {\n    if (isPlainObject(o))\n        return { ...o };\n    if (Array.isArray(o))\n        return [...o];\n    if (o instanceof Map)\n        return new Map(o);\n    if (o instanceof Set)\n        return new Set(o);\n    return o;\n}\nexport function numKeys(data) {\n    let keyCount = 0;\n    for (const key in data) {\n        if (Object.prototype.hasOwnProperty.call(data, key)) {\n            keyCount++;\n        }\n    }\n    return keyCount;\n}\nexport const getParsedType = (data) => {\n    const t = typeof data;\n    switch (t) {\n        case \"undefined\":\n            return \"undefined\";\n        case \"string\":\n            return \"string\";\n        case \"number\":\n            return Number.isNaN(data) ? \"nan\" : \"number\";\n        case \"boolean\":\n            return \"boolean\";\n        case \"function\":\n            return \"function\";\n        case \"bigint\":\n            return \"bigint\";\n        case \"symbol\":\n            return \"symbol\";\n        case \"object\":\n            if (Array.isArray(data)) {\n                return \"array\";\n            }\n            if (data === null) {\n                return \"null\";\n            }\n            if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n                return \"promise\";\n            }\n            if (typeof Map !== \"undefined\" && data instanceof Map) {\n                return \"map\";\n            }\n            if (typeof Set !== \"undefined\" && data instanceof Set) {\n                return \"set\";\n            }\n            if (typeof Date !== \"undefined\" && data instanceof Date) {\n                return \"date\";\n            }\n            // @ts-ignore\n            if (typeof File !== \"undefined\" && data instanceof File) {\n                return \"file\";\n            }\n            return \"object\";\n        default:\n            throw new Error(`Unknown data type: ${t}`);\n    }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n    \"string\",\n    \"number\",\n    \"bigint\",\n    \"boolean\",\n    \"symbol\",\n    \"undefined\",\n]);\nexport function escapeRegex(str) {\n    return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n    const cl = new inst._zod.constr(def ?? inst._zod.def);\n    if (!def || params?.parent)\n        cl._zod.parent = inst;\n    return cl;\n}\nexport function normalizeParams(_params) {\n    const params = _params;\n    if (!params)\n        return {};\n    if (typeof params === \"string\")\n        return { error: () => params };\n    if (params?.message !== undefined) {\n        if (params?.error !== undefined)\n            throw new Error(\"Cannot specify both `message` and `error` params\");\n        params.error = params.message;\n    }\n    delete params.message;\n    if (typeof params.error === \"string\")\n        return { ...params, error: () => params.error };\n    return params;\n}\nexport function createTransparentProxy(getter) {\n    let target;\n    return new Proxy({}, {\n        get(_, prop, receiver) {\n            target ?? (target = getter());\n            return Reflect.get(target, prop, receiver);\n        },\n        set(_, prop, value, receiver) {\n            target ?? (target = getter());\n            return Reflect.set(target, prop, value, receiver);\n        },\n        has(_, prop) {\n            target ?? (target = getter());\n            return Reflect.has(target, prop);\n        },\n        deleteProperty(_, prop) {\n            target ?? (target = getter());\n            return Reflect.deleteProperty(target, prop);\n        },\n        ownKeys(_) {\n            target ?? (target = getter());\n            return Reflect.ownKeys(target);\n        },\n        getOwnPropertyDescriptor(_, prop) {\n            target ?? (target = getter());\n            return Reflect.getOwnPropertyDescriptor(target, prop);\n        },\n        defineProperty(_, prop, descriptor) {\n            target ?? (target = getter());\n            return Reflect.defineProperty(target, prop, descriptor);\n        },\n    });\n}\nexport function stringifyPrimitive(value) {\n    if (typeof value === \"bigint\")\n        return value.toString() + \"n\";\n    if (typeof value === \"string\")\n        return `\"${value}\"`;\n    return `${value}`;\n}\nexport function optionalKeys(shape) {\n    return Object.keys(shape).filter((k) => {\n        return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n    });\n}\nexport const NUMBER_FORMAT_RANGES = {\n    safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n    int32: [-2147483648, 2147483647],\n    uint32: [0, 4294967295],\n    float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n    float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n    int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n    uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n    const currDef = schema._zod.def;\n    const checks = currDef.checks;\n    const hasChecks = checks && checks.length > 0;\n    if (hasChecks) {\n        throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n    }\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const newShape = {};\n            for (const key in mask) {\n                if (!(key in currDef.shape)) {\n                    throw new Error(`Unrecognized key: \"${key}\"`);\n                }\n                if (!mask[key])\n                    continue;\n                newShape[key] = currDef.shape[key];\n            }\n            assignProp(this, \"shape\", newShape); // self-caching\n            return newShape;\n        },\n        checks: [],\n    });\n    return clone(schema, def);\n}\nexport function omit(schema, mask) {\n    const currDef = schema._zod.def;\n    const checks = currDef.checks;\n    const hasChecks = checks && checks.length > 0;\n    if (hasChecks) {\n        throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n    }\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const newShape = { ...schema._zod.def.shape };\n            for (const key in mask) {\n                if (!(key in currDef.shape)) {\n                    throw new Error(`Unrecognized key: \"${key}\"`);\n                }\n                if (!mask[key])\n                    continue;\n                delete newShape[key];\n            }\n            assignProp(this, \"shape\", newShape); // self-caching\n            return newShape;\n        },\n        checks: [],\n    });\n    return clone(schema, def);\n}\nexport function extend(schema, shape) {\n    if (!isPlainObject(shape)) {\n        throw new Error(\"Invalid input to extend: expected a plain object\");\n    }\n    const checks = schema._zod.def.checks;\n    const hasChecks = checks && checks.length > 0;\n    if (hasChecks) {\n        // Only throw if new shape overlaps with existing shape\n        // Use getOwnPropertyDescriptor to check key existence without accessing values\n        const existingShape = schema._zod.def.shape;\n        for (const key in shape) {\n            if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n                throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n            }\n        }\n    }\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const _shape = { ...schema._zod.def.shape, ...shape };\n            assignProp(this, \"shape\", _shape); // self-caching\n            return _shape;\n        },\n    });\n    return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n    if (!isPlainObject(shape)) {\n        throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n    }\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const _shape = { ...schema._zod.def.shape, ...shape };\n            assignProp(this, \"shape\", _shape); // self-caching\n            return _shape;\n        },\n    });\n    return clone(schema, def);\n}\nexport function merge(a, b) {\n    if (a._zod.def.checks?.length) {\n        throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n    }\n    const def = mergeDefs(a._zod.def, {\n        get shape() {\n            const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n            assignProp(this, \"shape\", _shape); // self-caching\n            return _shape;\n        },\n        get catchall() {\n            return b._zod.def.catchall;\n        },\n        checks: b._zod.def.checks ?? [],\n    });\n    return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n    const currDef = schema._zod.def;\n    const checks = currDef.checks;\n    const hasChecks = checks && checks.length > 0;\n    if (hasChecks) {\n        throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n    }\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const oldShape = schema._zod.def.shape;\n            const shape = { ...oldShape };\n            if (mask) {\n                for (const key in mask) {\n                    if (!(key in oldShape)) {\n                        throw new Error(`Unrecognized key: \"${key}\"`);\n                    }\n                    if (!mask[key])\n                        continue;\n                    // if (oldShape[key]!._zod.optin === \"optional\") continue;\n                    shape[key] = Class\n                        ? new Class({\n                            type: \"optional\",\n                            innerType: oldShape[key],\n                        })\n                        : oldShape[key];\n                }\n            }\n            else {\n                for (const key in oldShape) {\n                    // if (oldShape[key]!._zod.optin === \"optional\") continue;\n                    shape[key] = Class\n                        ? new Class({\n                            type: \"optional\",\n                            innerType: oldShape[key],\n                        })\n                        : oldShape[key];\n                }\n            }\n            assignProp(this, \"shape\", shape); // self-caching\n            return shape;\n        },\n        checks: [],\n    });\n    return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const oldShape = schema._zod.def.shape;\n            const shape = { ...oldShape };\n            if (mask) {\n                for (const key in mask) {\n                    if (!(key in shape)) {\n                        throw new Error(`Unrecognized key: \"${key}\"`);\n                    }\n                    if (!mask[key])\n                        continue;\n                    // overwrite with non-optional\n                    shape[key] = new Class({\n                        type: \"nonoptional\",\n                        innerType: oldShape[key],\n                    });\n                }\n            }\n            else {\n                for (const key in oldShape) {\n                    // overwrite with non-optional\n                    shape[key] = new Class({\n                        type: \"nonoptional\",\n                        innerType: oldShape[key],\n                    });\n                }\n            }\n            assignProp(this, \"shape\", shape); // self-caching\n            return shape;\n        },\n    });\n    return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n    if (x.aborted === true)\n        return true;\n    for (let i = startIndex; i < x.issues.length; i++) {\n        if (x.issues[i]?.continue !== true) {\n            return true;\n        }\n    }\n    return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).\n// Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n    if (x.aborted === true)\n        return true;\n    for (let i = startIndex; i < x.issues.length; i++) {\n        if (x.issues[i]?.continue === false) {\n            return true;\n        }\n    }\n    return false;\n}\nexport function prefixIssues(path, issues) {\n    return issues.map((iss) => {\n        var _a;\n        (_a = iss).path ?? (_a.path = []);\n        iss.path.unshift(path);\n        return iss;\n    });\n}\nexport function unwrapMessage(message) {\n    return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n    const message = iss.message\n        ? iss.message\n        : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n            unwrapMessage(ctx?.error?.(iss)) ??\n            unwrapMessage(config.customError?.(iss)) ??\n            unwrapMessage(config.localeError?.(iss)) ??\n            \"Invalid input\");\n    const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;\n    rest.path ?? (rest.path = []);\n    rest.message = message;\n    if (ctx?.reportInput) {\n        rest.input = _input;\n    }\n    return rest;\n}\nexport function getSizableOrigin(input) {\n    if (input instanceof Set)\n        return \"set\";\n    if (input instanceof Map)\n        return \"map\";\n    // @ts-ignore\n    if (input instanceof File)\n        return \"file\";\n    return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n    if (Array.isArray(input))\n        return \"array\";\n    if (typeof input === \"string\")\n        return \"string\";\n    return \"unknown\";\n}\nexport function parsedType(data) {\n    const t = typeof data;\n    switch (t) {\n        case \"number\": {\n            return Number.isNaN(data) ? \"nan\" : \"number\";\n        }\n        case \"object\": {\n            if (data === null) {\n                return \"null\";\n            }\n            if (Array.isArray(data)) {\n                return \"array\";\n            }\n            const obj = data;\n            if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n                return obj.constructor.name;\n            }\n        }\n    }\n    return t;\n}\nexport function issue(...args) {\n    const [iss, input, inst] = args;\n    if (typeof iss === \"string\") {\n        return {\n            message: iss,\n            code: \"custom\",\n            input,\n            inst,\n        };\n    }\n    return { ...iss };\n}\nexport function cleanEnum(obj) {\n    return Object.entries(obj)\n        .filter(([k, _]) => {\n        // return true if NaN, meaning it's not a number, thus a string key\n        return Number.isNaN(Number.parseInt(k, 10));\n    })\n        .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n    const binaryString = atob(base64);\n    const bytes = new Uint8Array(binaryString.length);\n    for (let i = 0; i < binaryString.length; i++) {\n        bytes[i] = binaryString.charCodeAt(i);\n    }\n    return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n    let binaryString = \"\";\n    for (let i = 0; i < bytes.length; i++) {\n        binaryString += String.fromCharCode(bytes[i]);\n    }\n    return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n    const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n    const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n    return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n    return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n    const cleanHex = hex.replace(/^0x/, \"\");\n    if (cleanHex.length % 2 !== 0) {\n        throw new Error(\"Invalid hex string length\");\n    }\n    const bytes = new Uint8Array(cleanHex.length / 2);\n    for (let i = 0; i < cleanHex.length; i += 2) {\n        bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n    }\n    return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n    return Array.from(bytes)\n        .map((b) => b.toString(16).padStart(2, \"0\"))\n        .join(\"\");\n}\n// instanceof\nexport class Class {\n    constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n    inst.name = \"$ZodError\";\n    Object.defineProperty(inst, \"_zod\", {\n        value: inst._zod,\n        enumerable: false,\n    });\n    Object.defineProperty(inst, \"issues\", {\n        value: def,\n        enumerable: false,\n    });\n    inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n    Object.defineProperty(inst, \"toString\", {\n        value: () => inst.message,\n        enumerable: false,\n    });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n    const fieldErrors = {};\n    const formErrors = [];\n    for (const sub of error.issues) {\n        if (sub.path.length > 0) {\n            fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n            fieldErrors[sub.path[0]].push(mapper(sub));\n        }\n        else {\n            formErrors.push(mapper(sub));\n        }\n    }\n    return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n    const fieldErrors = { _errors: [] };\n    const processError = (error, path = []) => {\n        for (const issue of error.issues) {\n            if (issue.code === \"invalid_union\" && issue.errors.length) {\n                issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n            }\n            else if (issue.code === \"invalid_key\") {\n                processError({ issues: issue.issues }, [...path, ...issue.path]);\n            }\n            else if (issue.code === \"invalid_element\") {\n                processError({ issues: issue.issues }, [...path, ...issue.path]);\n            }\n            else {\n                const fullpath = [...path, ...issue.path];\n                if (fullpath.length === 0) {\n                    fieldErrors._errors.push(mapper(issue));\n                }\n                else {\n                    let curr = fieldErrors;\n                    let i = 0;\n                    while (i < fullpath.length) {\n                        const el = fullpath[i];\n                        const terminal = i === fullpath.length - 1;\n                        if (!terminal) {\n                            curr[el] = curr[el] || { _errors: [] };\n                        }\n                        else {\n                            curr[el] = curr[el] || { _errors: [] };\n                            curr[el]._errors.push(mapper(issue));\n                        }\n                        curr = curr[el];\n                        i++;\n                    }\n                }\n            }\n        }\n    };\n    processError(error);\n    return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n    const result = { errors: [] };\n    const processError = (error, path = []) => {\n        var _a, _b;\n        for (const issue of error.issues) {\n            if (issue.code === \"invalid_union\" && issue.errors.length) {\n                // regular union error\n                issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n            }\n            else if (issue.code === \"invalid_key\") {\n                processError({ issues: issue.issues }, [...path, ...issue.path]);\n            }\n            else if (issue.code === \"invalid_element\") {\n                processError({ issues: issue.issues }, [...path, ...issue.path]);\n            }\n            else {\n                const fullpath = [...path, ...issue.path];\n                if (fullpath.length === 0) {\n                    result.errors.push(mapper(issue));\n                    continue;\n                }\n                let curr = result;\n                let i = 0;\n                while (i < fullpath.length) {\n                    const el = fullpath[i];\n                    const terminal = i === fullpath.length - 1;\n                    if (typeof el === \"string\") {\n                        curr.properties ?? (curr.properties = {});\n                        (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n                        curr = curr.properties[el];\n                    }\n                    else {\n                        curr.items ?? (curr.items = []);\n                        (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n                        curr = curr.items[el];\n                    }\n                    if (terminal) {\n                        curr.errors.push(mapper(issue));\n                    }\n                    i++;\n                }\n            }\n        }\n    };\n    processError(error);\n    return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n *   issues: [\n *     {\n *       expected: 'string',\n *       code: 'invalid_type',\n *       path: [ 'username' ],\n *       message: 'Invalid input: expected string'\n *     },\n *     {\n *       expected: 'number',\n *       code: 'invalid_type',\n *       path: [ 'favoriteNumbers', 1 ],\n *       message: 'Invalid input: expected number'\n *     }\n *   ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n *   ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n *   ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n    const segs = [];\n    const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n    for (const seg of path) {\n        if (typeof seg === \"number\")\n            segs.push(`[${seg}]`);\n        else if (typeof seg === \"symbol\")\n            segs.push(`[${JSON.stringify(String(seg))}]`);\n        else if (/[^\\w$]/.test(seg))\n            segs.push(`[${JSON.stringify(seg)}]`);\n        else {\n            if (segs.length)\n                segs.push(\".\");\n            segs.push(seg);\n        }\n    }\n    return segs.join(\"\");\n}\nexport function prettifyError(error) {\n    const lines = [];\n    // sort by path length\n    const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n    // Process each issue\n    for (const issue of issues) {\n        lines.push(`✖ ${issue.message}`);\n        if (issue.path?.length)\n            lines.push(`  → at ${toDotPath(issue.path)}`);\n    }\n    // Convert Map to formatted string\n    return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n    const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n    const result = schema._zod.run({ value, issues: [] }, ctx);\n    if (result instanceof Promise) {\n        throw new core.$ZodAsyncError();\n    }\n    if (result.issues.length) {\n        const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n        util.captureStackTrace(e, _params?.callee);\n        throw e;\n    }\n    return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n    const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n    let result = schema._zod.run({ value, issues: [] }, ctx);\n    if (result instanceof Promise)\n        result = await result;\n    if (result.issues.length) {\n        const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n        util.captureStackTrace(e, params?.callee);\n        throw e;\n    }\n    return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n    const result = schema._zod.run({ value, issues: [] }, ctx);\n    if (result instanceof Promise) {\n        throw new core.$ZodAsyncError();\n    }\n    return result.issues.length\n        ? {\n            success: false,\n            error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n        }\n        : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n    let result = schema._zod.run({ value, issues: [] }, ctx);\n    if (result instanceof Promise)\n        result = await result;\n    return result.issues.length\n        ? {\n            success: false,\n            error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n        }\n        : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n    return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n    return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n    return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n    return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n    return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n    return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n    return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n    return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n    if (!version)\n        return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n    return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n    return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n    const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n    return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n    const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n    const regex = typeof args.precision === \"number\"\n        ? args.precision === -1\n            ? `${hhmm}`\n            : args.precision === 0\n                ? `${hhmm}:[0-5]\\\\d`\n                : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n        : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n    return regex;\n}\nexport function time(args) {\n    return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n    const time = timeSource({ precision: args.precision });\n    const opts = [\"Z\"];\n    if (args.local)\n        opts.push(\"\");\n    // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n    if (args.offset)\n        opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n    const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n    return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n    const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n    return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n    return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n    return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n    var _a;\n    inst._zod ?? (inst._zod = {});\n    inst._zod.def = def;\n    (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n    number: \"number\",\n    bigint: \"bigint\",\n    object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const origin = numericOriginMap[typeof def.value];\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n        if (def.value < curr) {\n            if (def.inclusive)\n                bag.maximum = def.value;\n            else\n                bag.exclusiveMaximum = def.value;\n        }\n    });\n    inst._zod.check = (payload) => {\n        if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n            return;\n        }\n        payload.issues.push({\n            origin,\n            code: \"too_big\",\n            maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n            input: payload.value,\n            inclusive: def.inclusive,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const origin = numericOriginMap[typeof def.value];\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n        if (def.value > curr) {\n            if (def.inclusive)\n                bag.minimum = def.value;\n            else\n                bag.exclusiveMinimum = def.value;\n        }\n    });\n    inst._zod.check = (payload) => {\n        if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n            return;\n        }\n        payload.issues.push({\n            origin,\n            code: \"too_small\",\n            minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n            input: payload.value,\n            inclusive: def.inclusive,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    inst._zod.onattach.push((inst) => {\n        var _a;\n        (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n    });\n    inst._zod.check = (payload) => {\n        if (typeof payload.value !== typeof def.value)\n            throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n        const isMultiple = typeof payload.value === \"bigint\"\n            ? payload.value % def.value === BigInt(0)\n            : util.floatSafeRemainder(payload.value, def.value) === 0;\n        if (isMultiple)\n            return;\n        payload.issues.push({\n            origin: typeof payload.value,\n            code: \"not_multiple_of\",\n            divisor: def.value,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n    $ZodCheck.init(inst, def); // no format checks\n    def.format = def.format || \"float64\";\n    const isInt = def.format?.includes(\"int\");\n    const origin = isInt ? \"int\" : \"number\";\n    const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.format = def.format;\n        bag.minimum = minimum;\n        bag.maximum = maximum;\n        if (isInt)\n            bag.pattern = regexes.integer;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        if (isInt) {\n            if (!Number.isInteger(input)) {\n                // invalid_format issue\n                // payload.issues.push({\n                //   expected: def.format,\n                //   format: def.format,\n                //   code: \"invalid_format\",\n                //   input,\n                //   inst,\n                // });\n                // invalid_type issue\n                payload.issues.push({\n                    expected: origin,\n                    format: def.format,\n                    code: \"invalid_type\",\n                    continue: false,\n                    input,\n                    inst,\n                });\n                return;\n                // not_multiple_of issue\n                // payload.issues.push({\n                //   code: \"not_multiple_of\",\n                //   origin: \"number\",\n                //   input,\n                //   inst,\n                //   divisor: 1,\n                // });\n            }\n            if (!Number.isSafeInteger(input)) {\n                if (input > 0) {\n                    // too_big\n                    payload.issues.push({\n                        input,\n                        code: \"too_big\",\n                        maximum: Number.MAX_SAFE_INTEGER,\n                        note: \"Integers must be within the safe integer range.\",\n                        inst,\n                        origin,\n                        inclusive: true,\n                        continue: !def.abort,\n                    });\n                }\n                else {\n                    // too_small\n                    payload.issues.push({\n                        input,\n                        code: \"too_small\",\n                        minimum: Number.MIN_SAFE_INTEGER,\n                        note: \"Integers must be within the safe integer range.\",\n                        inst,\n                        origin,\n                        inclusive: true,\n                        continue: !def.abort,\n                    });\n                }\n                return;\n            }\n        }\n        if (input < minimum) {\n            payload.issues.push({\n                origin: \"number\",\n                input,\n                code: \"too_small\",\n                minimum,\n                inclusive: true,\n                inst,\n                continue: !def.abort,\n            });\n        }\n        if (input > maximum) {\n            payload.issues.push({\n                origin: \"number\",\n                input,\n                code: \"too_big\",\n                maximum,\n                inclusive: true,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n    $ZodCheck.init(inst, def); // no format checks\n    const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.format = def.format;\n        bag.minimum = minimum;\n        bag.maximum = maximum;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        if (input < minimum) {\n            payload.issues.push({\n                origin: \"bigint\",\n                input,\n                code: \"too_small\",\n                minimum: minimum,\n                inclusive: true,\n                inst,\n                continue: !def.abort,\n            });\n        }\n        if (input > maximum) {\n            payload.issues.push({\n                origin: \"bigint\",\n                input,\n                code: \"too_big\",\n                maximum,\n                inclusive: true,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n        const val = payload.value;\n        return !util.nullish(val) && val.size !== undefined;\n    });\n    inst._zod.onattach.push((inst) => {\n        const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n        if (def.maximum < curr)\n            inst._zod.bag.maximum = def.maximum;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const size = input.size;\n        if (size <= def.maximum)\n            return;\n        payload.issues.push({\n            origin: util.getSizableOrigin(input),\n            code: \"too_big\",\n            maximum: def.maximum,\n            inclusive: true,\n            input,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n        const val = payload.value;\n        return !util.nullish(val) && val.size !== undefined;\n    });\n    inst._zod.onattach.push((inst) => {\n        const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n        if (def.minimum > curr)\n            inst._zod.bag.minimum = def.minimum;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const size = input.size;\n        if (size >= def.minimum)\n            return;\n        payload.issues.push({\n            origin: util.getSizableOrigin(input),\n            code: \"too_small\",\n            minimum: def.minimum,\n            inclusive: true,\n            input,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n        const val = payload.value;\n        return !util.nullish(val) && val.size !== undefined;\n    });\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.minimum = def.size;\n        bag.maximum = def.size;\n        bag.size = def.size;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const size = input.size;\n        if (size === def.size)\n            return;\n        const tooBig = size > def.size;\n        payload.issues.push({\n            origin: util.getSizableOrigin(input),\n            ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n            inclusive: true,\n            exact: true,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n        const val = payload.value;\n        return !util.nullish(val) && val.length !== undefined;\n    });\n    inst._zod.onattach.push((inst) => {\n        const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n        if (def.maximum < curr)\n            inst._zod.bag.maximum = def.maximum;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const length = input.length;\n        if (length <= def.maximum)\n            return;\n        const origin = util.getLengthableOrigin(input);\n        payload.issues.push({\n            origin,\n            code: \"too_big\",\n            maximum: def.maximum,\n            inclusive: true,\n            input,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n        const val = payload.value;\n        return !util.nullish(val) && val.length !== undefined;\n    });\n    inst._zod.onattach.push((inst) => {\n        const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n        if (def.minimum > curr)\n            inst._zod.bag.minimum = def.minimum;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const length = input.length;\n        if (length >= def.minimum)\n            return;\n        const origin = util.getLengthableOrigin(input);\n        payload.issues.push({\n            origin,\n            code: \"too_small\",\n            minimum: def.minimum,\n            inclusive: true,\n            input,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n        const val = payload.value;\n        return !util.nullish(val) && val.length !== undefined;\n    });\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.minimum = def.length;\n        bag.maximum = def.length;\n        bag.length = def.length;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const length = input.length;\n        if (length === def.length)\n            return;\n        const origin = util.getLengthableOrigin(input);\n        const tooBig = length > def.length;\n        payload.issues.push({\n            origin,\n            ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n            inclusive: true,\n            exact: true,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n    var _a, _b;\n    $ZodCheck.init(inst, def);\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.format = def.format;\n        if (def.pattern) {\n            bag.patterns ?? (bag.patterns = new Set());\n            bag.patterns.add(def.pattern);\n        }\n    });\n    if (def.pattern)\n        (_a = inst._zod).check ?? (_a.check = (payload) => {\n            def.pattern.lastIndex = 0;\n            if (def.pattern.test(payload.value))\n                return;\n            payload.issues.push({\n                origin: \"string\",\n                code: \"invalid_format\",\n                format: def.format,\n                input: payload.value,\n                ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n                inst,\n                continue: !def.abort,\n            });\n        });\n    else\n        (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n    $ZodCheckStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        def.pattern.lastIndex = 0;\n        if (def.pattern.test(payload.value))\n            return;\n        payload.issues.push({\n            origin: \"string\",\n            code: \"invalid_format\",\n            format: \"regex\",\n            input: payload.value,\n            pattern: def.pattern.toString(),\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.lowercase);\n    $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.uppercase);\n    $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const escapedRegex = util.escapeRegex(def.includes);\n    const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n    def.pattern = pattern;\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.patterns ?? (bag.patterns = new Set());\n        bag.patterns.add(pattern);\n    });\n    inst._zod.check = (payload) => {\n        if (payload.value.includes(def.includes, def.position))\n            return;\n        payload.issues.push({\n            origin: \"string\",\n            code: \"invalid_format\",\n            format: \"includes\",\n            includes: def.includes,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n    def.pattern ?? (def.pattern = pattern);\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.patterns ?? (bag.patterns = new Set());\n        bag.patterns.add(pattern);\n    });\n    inst._zod.check = (payload) => {\n        if (payload.value.startsWith(def.prefix))\n            return;\n        payload.issues.push({\n            origin: \"string\",\n            code: \"invalid_format\",\n            format: \"starts_with\",\n            prefix: def.prefix,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n    def.pattern ?? (def.pattern = pattern);\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.patterns ?? (bag.patterns = new Set());\n        bag.patterns.add(pattern);\n    });\n    inst._zod.check = (payload) => {\n        if (payload.value.endsWith(def.suffix))\n            return;\n        payload.issues.push({\n            origin: \"string\",\n            code: \"invalid_format\",\n            format: \"ends_with\",\n            suffix: def.suffix,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\n///////////////////////////////////\n/////    $ZodCheckProperty    /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n    if (result.issues.length) {\n        payload.issues.push(...util.prefixIssues(property, result.issues));\n    }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    inst._zod.check = (payload) => {\n        const result = def.schema._zod.run({\n            value: payload.value[def.property],\n            issues: [],\n        }, {});\n        if (result instanceof Promise) {\n            return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n        }\n        handleCheckPropertyResult(result, payload, def.property);\n        return;\n    };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const mimeSet = new Set(def.mime);\n    inst._zod.onattach.push((inst) => {\n        inst._zod.bag.mime = def.mime;\n    });\n    inst._zod.check = (payload) => {\n        if (mimeSet.has(payload.value.type))\n            return;\n        payload.issues.push({\n            code: \"invalid_value\",\n            values: def.mime,\n            input: payload.value.type,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    inst._zod.check = (payload) => {\n        payload.value = def.tx(payload.value);\n    };\n});\n","export class Doc {\n    constructor(args = []) {\n        this.content = [];\n        this.indent = 0;\n        if (this)\n            this.args = args;\n    }\n    indented(fn) {\n        this.indent += 1;\n        fn(this);\n        this.indent -= 1;\n    }\n    write(arg) {\n        if (typeof arg === \"function\") {\n            arg(this, { execution: \"sync\" });\n            arg(this, { execution: \"async\" });\n            return;\n        }\n        const content = arg;\n        const lines = content.split(\"\\n\").filter((x) => x);\n        const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n        const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n        for (const line of dedented) {\n            this.content.push(line);\n        }\n    }\n    compile() {\n        const F = Function;\n        const args = this?.args;\n        const content = this?.content ?? [``];\n        const lines = [...content.map((x) => `  ${x}`)];\n        // console.log(lines.join(\"\\n\"));\n        return new F(...args, lines.join(\"\\n\"));\n    }\n}\n","export const version = {\n    major: 4,\n    minor: 4,\n    patch: 3,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n    var _a;\n    inst ?? (inst = {});\n    inst._zod.def = def; // set _def property\n    inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n    inst._zod.version = version;\n    const checks = [...(inst._zod.def.checks ?? [])];\n    // if inst is itself a checks.$ZodCheck, run it as a check\n    if (inst._zod.traits.has(\"$ZodCheck\")) {\n        checks.unshift(inst);\n    }\n    for (const ch of checks) {\n        for (const fn of ch._zod.onattach) {\n            fn(inst);\n        }\n    }\n    if (checks.length === 0) {\n        // deferred initializer\n        // inst._zod.parse is not yet defined\n        (_a = inst._zod).deferred ?? (_a.deferred = []);\n        inst._zod.deferred?.push(() => {\n            inst._zod.run = inst._zod.parse;\n        });\n    }\n    else {\n        const runChecks = (payload, checks, ctx) => {\n            let isAborted = util.aborted(payload);\n            let asyncResult;\n            for (const ch of checks) {\n                if (ch._zod.def.when) {\n                    if (util.explicitlyAborted(payload))\n                        continue;\n                    const shouldRun = ch._zod.def.when(payload);\n                    if (!shouldRun)\n                        continue;\n                }\n                else if (isAborted) {\n                    continue;\n                }\n                const currLen = payload.issues.length;\n                const _ = ch._zod.check(payload);\n                if (_ instanceof Promise && ctx?.async === false) {\n                    throw new core.$ZodAsyncError();\n                }\n                if (asyncResult || _ instanceof Promise) {\n                    asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n                        await _;\n                        const nextLen = payload.issues.length;\n                        if (nextLen === currLen)\n                            return;\n                        if (!isAborted)\n                            isAborted = util.aborted(payload, currLen);\n                    });\n                }\n                else {\n                    const nextLen = payload.issues.length;\n                    if (nextLen === currLen)\n                        continue;\n                    if (!isAborted)\n                        isAborted = util.aborted(payload, currLen);\n                }\n            }\n            if (asyncResult) {\n                return asyncResult.then(() => {\n                    return payload;\n                });\n            }\n            return payload;\n        };\n        const handleCanaryResult = (canary, payload, ctx) => {\n            // abort if the canary is aborted\n            if (util.aborted(canary)) {\n                canary.aborted = true;\n                return canary;\n            }\n            // run checks first, then\n            const checkResult = runChecks(payload, checks, ctx);\n            if (checkResult instanceof Promise) {\n                if (ctx.async === false)\n                    throw new core.$ZodAsyncError();\n                return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n            }\n            return inst._zod.parse(checkResult, ctx);\n        };\n        inst._zod.run = (payload, ctx) => {\n            if (ctx.skipChecks) {\n                return inst._zod.parse(payload, ctx);\n            }\n            if (ctx.direction === \"backward\") {\n                // run canary\n                // initial pass (no checks)\n                const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n                if (canary instanceof Promise) {\n                    return canary.then((canary) => {\n                        return handleCanaryResult(canary, payload, ctx);\n                    });\n                }\n                return handleCanaryResult(canary, payload, ctx);\n            }\n            // forward\n            const result = inst._zod.parse(payload, ctx);\n            if (result instanceof Promise) {\n                if (ctx.async === false)\n                    throw new core.$ZodAsyncError();\n                return result.then((result) => runChecks(result, checks, ctx));\n            }\n            return runChecks(result, checks, ctx);\n        };\n    }\n    // Lazy initialize ~standard to avoid creating objects for every schema\n    util.defineLazy(inst, \"~standard\", () => ({\n        validate: (value) => {\n            try {\n                const r = safeParse(inst, value);\n                return r.success ? { value: r.data } : { issues: r.error?.issues };\n            }\n            catch (_) {\n                return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n            }\n        },\n        vendor: \"zod\",\n        version: 1,\n    }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n    inst._zod.parse = (payload, _) => {\n        if (def.coerce)\n            try {\n                payload.value = String(payload.value);\n            }\n            catch (_) { }\n        if (typeof payload.value === \"string\")\n            return payload;\n        payload.issues.push({\n            expected: \"string\",\n            code: \"invalid_type\",\n            input: payload.value,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n    // check initialization must come first\n    checks.$ZodCheckStringFormat.init(inst, def);\n    $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.guid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n    if (def.version) {\n        const versionMap = {\n            v1: 1,\n            v2: 2,\n            v3: 3,\n            v4: 4,\n            v5: 5,\n            v6: 6,\n            v7: 7,\n            v8: 8,\n        };\n        const v = versionMap[def.version];\n        if (v === undefined)\n            throw new Error(`Invalid UUID version: \"${def.version}\"`);\n        def.pattern ?? (def.pattern = regexes.uuid(v));\n    }\n    else\n        def.pattern ?? (def.pattern = regexes.uuid());\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.email);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        try {\n            // Trim whitespace from input\n            const trimmed = payload.value.trim();\n            // When normalize is off, require :// for http/https URLs\n            // This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n            if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source) {\n                if (!/^https?:\\/\\//i.test(trimmed)) {\n                    payload.issues.push({\n                        code: \"invalid_format\",\n                        format: \"url\",\n                        note: \"Invalid URL format\",\n                        input: payload.value,\n                        inst,\n                        continue: !def.abort,\n                    });\n                    return;\n                }\n            }\n            // @ts-ignore\n            const url = new URL(trimmed);\n            if (def.hostname) {\n                def.hostname.lastIndex = 0;\n                if (!def.hostname.test(url.hostname)) {\n                    payload.issues.push({\n                        code: \"invalid_format\",\n                        format: \"url\",\n                        note: \"Invalid hostname\",\n                        pattern: def.hostname.source,\n                        input: payload.value,\n                        inst,\n                        continue: !def.abort,\n                    });\n                }\n            }\n            if (def.protocol) {\n                def.protocol.lastIndex = 0;\n                if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n                    payload.issues.push({\n                        code: \"invalid_format\",\n                        format: \"url\",\n                        note: \"Invalid protocol\",\n                        pattern: def.protocol.source,\n                        input: payload.value,\n                        inst,\n                        continue: !def.abort,\n                    });\n                }\n            }\n            // Set the output value based on normalize flag\n            if (def.normalize) {\n                // Use normalized URL\n                payload.value = url.href;\n            }\n            else {\n                // Preserve the original input (trimmed)\n                payload.value = trimmed;\n            }\n            return;\n        }\n        catch (_) {\n            payload.issues.push({\n                code: \"invalid_format\",\n                format: \"url\",\n                input: payload.value,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.emoji());\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.nanoid);\n    $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.cuid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.cuid2);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.ulid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.xid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.ksuid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.datetime(def));\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.date);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.time(def));\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.duration);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.ipv4);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.ipv6);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.bag.format = `ipv6`;\n    inst._zod.check = (payload) => {\n        try {\n            // @ts-ignore\n            new URL(`http://[${payload.value}]`);\n            // return;\n        }\n        catch {\n            payload.issues.push({\n                code: \"invalid_format\",\n                format: \"ipv6\",\n                input: payload.value,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n    $ZodStringFormat.init(inst, def);\n    inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.cidrv4);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        const parts = payload.value.split(\"/\");\n        try {\n            if (parts.length !== 2)\n                throw new Error();\n            const [address, prefix] = parts;\n            if (!prefix)\n                throw new Error();\n            const prefixNum = Number(prefix);\n            if (`${prefixNum}` !== prefix)\n                throw new Error();\n            if (prefixNum < 0 || prefixNum > 128)\n                throw new Error();\n            // @ts-ignore\n            new URL(`http://[${address}]`);\n        }\n        catch {\n            payload.issues.push({\n                code: \"invalid_format\",\n                format: \"cidrv6\",\n                input: payload.value,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\n//////////////////////////////   ZodBase64   //////////////////////////////\nexport function isValidBase64(data) {\n    if (data === \"\")\n        return true;\n    // atob ignores whitespace, so reject it up front.\n    if (/\\s/.test(data))\n        return false;\n    if (data.length % 4 !== 0)\n        return false;\n    try {\n        // @ts-ignore\n        atob(data);\n        return true;\n    }\n    catch {\n        return false;\n    }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.base64);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.bag.contentEncoding = \"base64\";\n    inst._zod.check = (payload) => {\n        if (isValidBase64(payload.value))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: \"base64\",\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\n//////////////////////////////   ZodBase64   //////////////////////////////\nexport function isValidBase64URL(data) {\n    if (!regexes.base64url.test(data))\n        return false;\n    const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n    const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n    return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.base64url);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.bag.contentEncoding = \"base64url\";\n    inst._zod.check = (payload) => {\n        if (isValidBase64URL(payload.value))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: \"base64url\",\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.e164);\n    $ZodStringFormat.init(inst, def);\n});\n//////////////////////////////   ZodJWT   //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n    try {\n        const tokensParts = token.split(\".\");\n        if (tokensParts.length !== 3)\n            return false;\n        const [header] = tokensParts;\n        if (!header)\n            return false;\n        // @ts-ignore\n        const parsedHeader = JSON.parse(atob(header));\n        if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n            return false;\n        if (!parsedHeader.alg)\n            return false;\n        if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n            return false;\n        return true;\n    }\n    catch {\n        return false;\n    }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (isValidJWT(payload.value, def.alg))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: \"jwt\",\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (def.fn(payload.value))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: def.format,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n    inst._zod.parse = (payload, _ctx) => {\n        if (def.coerce)\n            try {\n                payload.value = Number(payload.value);\n            }\n            catch (_) { }\n        const input = payload.value;\n        if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n            return payload;\n        }\n        const received = typeof input === \"number\"\n            ? Number.isNaN(input)\n                ? \"NaN\"\n                : !Number.isFinite(input)\n                    ? \"Infinity\"\n                    : undefined\n            : undefined;\n        payload.issues.push({\n            expected: \"number\",\n            code: \"invalid_type\",\n            input,\n            inst,\n            ...(received ? { received } : {}),\n        });\n        return payload;\n    };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n    checks.$ZodCheckNumberFormat.init(inst, def);\n    $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = regexes.boolean;\n    inst._zod.parse = (payload, _ctx) => {\n        if (def.coerce)\n            try {\n                payload.value = Boolean(payload.value);\n            }\n            catch (_) { }\n        const input = payload.value;\n        if (typeof input === \"boolean\")\n            return payload;\n        payload.issues.push({\n            expected: \"boolean\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = regexes.bigint;\n    inst._zod.parse = (payload, _ctx) => {\n        if (def.coerce)\n            try {\n                payload.value = BigInt(payload.value);\n            }\n            catch (_) { }\n        if (typeof payload.value === \"bigint\")\n            return payload;\n        payload.issues.push({\n            expected: \"bigint\",\n            code: \"invalid_type\",\n            input: payload.value,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n    checks.$ZodCheckBigIntFormat.init(inst, def);\n    $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (typeof input === \"symbol\")\n            return payload;\n        payload.issues.push({\n            expected: \"symbol\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = regexes.undefined;\n    inst._zod.values = new Set([undefined]);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (typeof input === \"undefined\")\n            return payload;\n        payload.issues.push({\n            expected: \"undefined\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = regexes.null;\n    inst._zod.values = new Set([null]);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (input === null)\n            return payload;\n        payload.issues.push({\n            expected: \"null\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        payload.issues.push({\n            expected: \"never\",\n            code: \"invalid_type\",\n            input: payload.value,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (typeof input === \"undefined\")\n            return payload;\n        payload.issues.push({\n            expected: \"void\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        if (def.coerce) {\n            try {\n                payload.value = new Date(payload.value);\n            }\n            catch (_err) { }\n        }\n        const input = payload.value;\n        const isDate = input instanceof Date;\n        const isValidDate = isDate && !Number.isNaN(input.getTime());\n        if (isValidDate)\n            return payload;\n        payload.issues.push({\n            expected: \"date\",\n            code: \"invalid_type\",\n            input,\n            ...(isDate ? { received: \"Invalid Date\" } : {}),\n            inst,\n        });\n        return payload;\n    };\n});\nfunction handleArrayResult(result, final, index) {\n    if (result.issues.length) {\n        final.issues.push(...util.prefixIssues(index, result.issues));\n    }\n    final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!Array.isArray(input)) {\n            payload.issues.push({\n                expected: \"array\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        payload.value = Array(input.length);\n        const proms = [];\n        for (let i = 0; i < input.length; i++) {\n            const item = input[i];\n            const result = def.element._zod.run({\n                value: item,\n                issues: [],\n            }, ctx);\n            if (result instanceof Promise) {\n                proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n            }\n            else {\n                handleArrayResult(result, payload, i);\n            }\n        }\n        if (proms.length) {\n            return Promise.all(proms).then(() => payload);\n        }\n        return payload; //handleArrayResultsAsync(parseResults, final);\n    };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {\n    const isPresent = key in input;\n    if (result.issues.length) {\n        // For optional-in/out schemas, ignore errors on absent keys.\n        if (isOptionalIn && isOptionalOut && !isPresent) {\n            return;\n        }\n        final.issues.push(...util.prefixIssues(key, result.issues));\n    }\n    if (!isPresent && !isOptionalIn) {\n        if (!result.issues.length) {\n            final.issues.push({\n                code: \"invalid_type\",\n                expected: \"nonoptional\",\n                input: undefined,\n                path: [key],\n            });\n        }\n        return;\n    }\n    if (result.value === undefined) {\n        if (isPresent) {\n            final.value[key] = undefined;\n        }\n    }\n    else {\n        final.value[key] = result.value;\n    }\n}\nfunction normalizeDef(def) {\n    const keys = Object.keys(def.shape);\n    for (const k of keys) {\n        if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n            throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n        }\n    }\n    const okeys = util.optionalKeys(def.shape);\n    return {\n        ...def,\n        keys,\n        keySet: new Set(keys),\n        numKeys: keys.length,\n        optionalKeys: new Set(okeys),\n    };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n    const unrecognized = [];\n    const keySet = def.keySet;\n    const _catchall = def.catchall._zod;\n    const t = _catchall.def.type;\n    const isOptionalIn = _catchall.optin === \"optional\";\n    const isOptionalOut = _catchall.optout === \"optional\";\n    for (const key in input) {\n        // skip __proto__ so it can't replace the result prototype via the\n        // assignment setter on the plain {} we build into\n        if (key === \"__proto__\")\n            continue;\n        if (keySet.has(key))\n            continue;\n        if (t === \"never\") {\n            unrecognized.push(key);\n            continue;\n        }\n        const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n        if (r instanceof Promise) {\n            proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n        }\n        else {\n            handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n        }\n    }\n    if (unrecognized.length) {\n        payload.issues.push({\n            code: \"unrecognized_keys\",\n            keys: unrecognized,\n            input,\n            inst,\n        });\n    }\n    if (!proms.length)\n        return payload;\n    return Promise.all(proms).then(() => {\n        return payload;\n    });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n    // requires cast because technically $ZodObject doesn't extend\n    $ZodType.init(inst, def);\n    // const sh = def.shape;\n    const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n    if (!desc?.get) {\n        const sh = def.shape;\n        Object.defineProperty(def, \"shape\", {\n            get: () => {\n                const newSh = { ...sh };\n                Object.defineProperty(def, \"shape\", {\n                    value: newSh,\n                });\n                return newSh;\n            },\n        });\n    }\n    const _normalized = util.cached(() => normalizeDef(def));\n    util.defineLazy(inst._zod, \"propValues\", () => {\n        const shape = def.shape;\n        const propValues = {};\n        for (const key in shape) {\n            const field = shape[key]._zod;\n            if (field.values) {\n                propValues[key] ?? (propValues[key] = new Set());\n                for (const v of field.values)\n                    propValues[key].add(v);\n            }\n        }\n        return propValues;\n    });\n    const isObject = util.isObject;\n    const catchall = def.catchall;\n    let value;\n    inst._zod.parse = (payload, ctx) => {\n        value ?? (value = _normalized.value);\n        const input = payload.value;\n        if (!isObject(input)) {\n            payload.issues.push({\n                expected: \"object\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        payload.value = {};\n        const proms = [];\n        const shape = value.shape;\n        for (const key of value.keys) {\n            const el = shape[key];\n            const isOptionalIn = el._zod.optin === \"optional\";\n            const isOptionalOut = el._zod.optout === \"optional\";\n            const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n            if (r instanceof Promise) {\n                proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n            }\n            else {\n                handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n            }\n        }\n        if (!catchall) {\n            return proms.length ? Promise.all(proms).then(() => payload) : payload;\n        }\n        return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n    };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n    // requires cast because technically $ZodObject doesn't extend\n    $ZodObject.init(inst, def);\n    const superParse = inst._zod.parse;\n    const _normalized = util.cached(() => normalizeDef(def));\n    const generateFastpass = (shape) => {\n        const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n        const normalized = _normalized.value;\n        const parseStr = (key) => {\n            const k = util.esc(key);\n            return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n        };\n        doc.write(`const input = payload.value;`);\n        const ids = Object.create(null);\n        let counter = 0;\n        for (const key of normalized.keys) {\n            ids[key] = `key_${counter++}`;\n        }\n        // A: preserve key order {\n        doc.write(`const newResult = {};`);\n        for (const key of normalized.keys) {\n            const id = ids[key];\n            const k = util.esc(key);\n            const schema = shape[key];\n            const isOptionalIn = schema?._zod?.optin === \"optional\";\n            const isOptionalOut = schema?._zod?.optout === \"optional\";\n            doc.write(`const ${id} = ${parseStr(key)};`);\n            if (isOptionalIn && isOptionalOut) {\n                // For optional-in/out schemas, ignore errors on absent keys\n                doc.write(`\n        if (${id}.issues.length) {\n          if (${k} in input) {\n            payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n              ...iss,\n              path: iss.path ? [${k}, ...iss.path] : [${k}]\n            })));\n          }\n        }\n        \n        if (${id}.value === undefined) {\n          if (${k} in input) {\n            newResult[${k}] = undefined;\n          }\n        } else {\n          newResult[${k}] = ${id}.value;\n        }\n        \n      `);\n            }\n            else if (!isOptionalIn) {\n                doc.write(`\n        const ${id}_present = ${k} in input;\n        if (${id}.issues.length) {\n          payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n            ...iss,\n            path: iss.path ? [${k}, ...iss.path] : [${k}]\n          })));\n        }\n        if (!${id}_present && !${id}.issues.length) {\n          payload.issues.push({\n            code: \"invalid_type\",\n            expected: \"nonoptional\",\n            input: undefined,\n            path: [${k}]\n          });\n        }\n\n        if (${id}_present) {\n          if (${id}.value === undefined) {\n            newResult[${k}] = undefined;\n          } else {\n            newResult[${k}] = ${id}.value;\n          }\n        }\n\n      `);\n            }\n            else {\n                doc.write(`\n        if (${id}.issues.length) {\n          payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n            ...iss,\n            path: iss.path ? [${k}, ...iss.path] : [${k}]\n          })));\n        }\n        \n        if (${id}.value === undefined) {\n          if (${k} in input) {\n            newResult[${k}] = undefined;\n          }\n        } else {\n          newResult[${k}] = ${id}.value;\n        }\n        \n      `);\n            }\n        }\n        doc.write(`payload.value = newResult;`);\n        doc.write(`return payload;`);\n        const fn = doc.compile();\n        return (payload, ctx) => fn(shape, payload, ctx);\n    };\n    let fastpass;\n    const isObject = util.isObject;\n    const jit = !core.globalConfig.jitless;\n    const allowsEval = util.allowsEval;\n    const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n    const catchall = def.catchall;\n    let value;\n    inst._zod.parse = (payload, ctx) => {\n        value ?? (value = _normalized.value);\n        const input = payload.value;\n        if (!isObject(input)) {\n            payload.issues.push({\n                expected: \"object\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n            // always synchronous\n            if (!fastpass)\n                fastpass = generateFastpass(def.shape);\n            payload = fastpass(payload, ctx);\n            if (!catchall)\n                return payload;\n            return handleCatchall([], input, payload, ctx, value, inst);\n        }\n        return superParse(payload, ctx);\n    };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n    for (const result of results) {\n        if (result.issues.length === 0) {\n            final.value = result.value;\n            return final;\n        }\n    }\n    const nonaborted = results.filter((r) => !util.aborted(r));\n    if (nonaborted.length === 1) {\n        final.value = nonaborted[0].value;\n        return nonaborted[0];\n    }\n    final.issues.push({\n        code: \"invalid_union\",\n        input: final.value,\n        inst,\n        errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n    });\n    return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n    util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n    util.defineLazy(inst._zod, \"values\", () => {\n        if (def.options.every((o) => o._zod.values)) {\n            return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n        }\n        return undefined;\n    });\n    util.defineLazy(inst._zod, \"pattern\", () => {\n        if (def.options.every((o) => o._zod.pattern)) {\n            const patterns = def.options.map((o) => o._zod.pattern);\n            return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n        }\n        return undefined;\n    });\n    const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n    inst._zod.parse = (payload, ctx) => {\n        if (first) {\n            return first(payload, ctx);\n        }\n        let async = false;\n        const results = [];\n        for (const option of def.options) {\n            const result = option._zod.run({\n                value: payload.value,\n                issues: [],\n            }, ctx);\n            if (result instanceof Promise) {\n                results.push(result);\n                async = true;\n            }\n            else {\n                if (result.issues.length === 0)\n                    return result;\n                results.push(result);\n            }\n        }\n        if (!async)\n            return handleUnionResults(results, payload, inst, ctx);\n        return Promise.all(results).then((results) => {\n            return handleUnionResults(results, payload, inst, ctx);\n        });\n    };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n    const successes = results.filter((r) => r.issues.length === 0);\n    if (successes.length === 1) {\n        final.value = successes[0].value;\n        return final;\n    }\n    if (successes.length === 0) {\n        // No matches - same as regular union\n        final.issues.push({\n            code: \"invalid_union\",\n            input: final.value,\n            inst,\n            errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n        });\n    }\n    else {\n        // Multiple matches - exclusive union failure\n        final.issues.push({\n            code: \"invalid_union\",\n            input: final.value,\n            inst,\n            errors: [],\n            inclusive: false,\n        });\n    }\n    return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n    $ZodUnion.init(inst, def);\n    def.inclusive = false;\n    const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n    inst._zod.parse = (payload, ctx) => {\n        if (first) {\n            return first(payload, ctx);\n        }\n        let async = false;\n        const results = [];\n        for (const option of def.options) {\n            const result = option._zod.run({\n                value: payload.value,\n                issues: [],\n            }, ctx);\n            if (result instanceof Promise) {\n                results.push(result);\n                async = true;\n            }\n            else {\n                results.push(result);\n            }\n        }\n        if (!async)\n            return handleExclusiveUnionResults(results, payload, inst, ctx);\n        return Promise.all(results).then((results) => {\n            return handleExclusiveUnionResults(results, payload, inst, ctx);\n        });\n    };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n    def.inclusive = false;\n    $ZodUnion.init(inst, def);\n    const _super = inst._zod.parse;\n    util.defineLazy(inst._zod, \"propValues\", () => {\n        const propValues = {};\n        for (const option of def.options) {\n            const pv = option._zod.propValues;\n            if (!pv || Object.keys(pv).length === 0)\n                throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n            for (const [k, v] of Object.entries(pv)) {\n                if (!propValues[k])\n                    propValues[k] = new Set();\n                for (const val of v) {\n                    propValues[k].add(val);\n                }\n            }\n        }\n        return propValues;\n    });\n    const disc = util.cached(() => {\n        const opts = def.options;\n        const map = new Map();\n        for (const o of opts) {\n            const values = o._zod.propValues?.[def.discriminator];\n            if (!values || values.size === 0)\n                throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n            for (const v of values) {\n                if (map.has(v)) {\n                    throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n                }\n                map.set(v, o);\n            }\n        }\n        return map;\n    });\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!util.isObject(input)) {\n            payload.issues.push({\n                code: \"invalid_type\",\n                expected: \"object\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        const opt = disc.value.get(input?.[def.discriminator]);\n        if (opt) {\n            return opt._zod.run(payload, ctx);\n        }\n        // Fall back to union matching when the fast discriminator path fails:\n        // - explicitly enabled via unionFallback, or\n        // - during backward direction (encode), since codec-based discriminators\n        //   have different values in forward vs backward directions\n        if (def.unionFallback || ctx.direction === \"backward\") {\n            return _super(payload, ctx);\n        }\n        // no matching discriminator\n        payload.issues.push({\n            code: \"invalid_union\",\n            errors: [],\n            note: \"No matching discriminator\",\n            discriminator: def.discriminator,\n            options: Array.from(disc.value.keys()),\n            input,\n            path: [def.discriminator],\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n        const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n        const async = left instanceof Promise || right instanceof Promise;\n        if (async) {\n            return Promise.all([left, right]).then(([left, right]) => {\n                return handleIntersectionResults(payload, left, right);\n            });\n        }\n        return handleIntersectionResults(payload, left, right);\n    };\n});\nfunction mergeValues(a, b) {\n    // const aType = parse.t(a);\n    // const bType = parse.t(b);\n    if (a === b) {\n        return { valid: true, data: a };\n    }\n    if (a instanceof Date && b instanceof Date && +a === +b) {\n        return { valid: true, data: a };\n    }\n    if (util.isPlainObject(a) && util.isPlainObject(b)) {\n        const bKeys = Object.keys(b);\n        const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n        const newObj = { ...a, ...b };\n        for (const key of sharedKeys) {\n            const sharedValue = mergeValues(a[key], b[key]);\n            if (!sharedValue.valid) {\n                return {\n                    valid: false,\n                    mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n                };\n            }\n            newObj[key] = sharedValue.data;\n        }\n        return { valid: true, data: newObj };\n    }\n    if (Array.isArray(a) && Array.isArray(b)) {\n        if (a.length !== b.length) {\n            return { valid: false, mergeErrorPath: [] };\n        }\n        const newArray = [];\n        for (let index = 0; index < a.length; index++) {\n            const itemA = a[index];\n            const itemB = b[index];\n            const sharedValue = mergeValues(itemA, itemB);\n            if (!sharedValue.valid) {\n                return {\n                    valid: false,\n                    mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n                };\n            }\n            newArray.push(sharedValue.data);\n        }\n        return { valid: true, data: newArray };\n    }\n    return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n    // Track which side(s) report each key as unrecognized\n    const unrecKeys = new Map();\n    let unrecIssue;\n    for (const iss of left.issues) {\n        if (iss.code === \"unrecognized_keys\") {\n            unrecIssue ?? (unrecIssue = iss);\n            for (const k of iss.keys) {\n                if (!unrecKeys.has(k))\n                    unrecKeys.set(k, {});\n                unrecKeys.get(k).l = true;\n            }\n        }\n        else {\n            result.issues.push(iss);\n        }\n    }\n    for (const iss of right.issues) {\n        if (iss.code === \"unrecognized_keys\") {\n            for (const k of iss.keys) {\n                if (!unrecKeys.has(k))\n                    unrecKeys.set(k, {});\n                unrecKeys.get(k).r = true;\n            }\n        }\n        else {\n            result.issues.push(iss);\n        }\n    }\n    // Report only keys unrecognized by BOTH sides\n    const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n    if (bothKeys.length && unrecIssue) {\n        result.issues.push({ ...unrecIssue, keys: bothKeys });\n    }\n    if (util.aborted(result))\n        return result;\n    const merged = mergeValues(left.value, right.value);\n    if (!merged.valid) {\n        throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n    }\n    result.value = merged.data;\n    return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const items = def.items;\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!Array.isArray(input)) {\n            payload.issues.push({\n                input,\n                inst,\n                expected: \"tuple\",\n                code: \"invalid_type\",\n            });\n            return payload;\n        }\n        payload.value = [];\n        const proms = [];\n        const optinStart = getTupleOptStart(items, \"optin\");\n        const optoutStart = getTupleOptStart(items, \"optout\");\n        if (!def.rest) {\n            if (input.length < optinStart) {\n                payload.issues.push({\n                    code: \"too_small\",\n                    minimum: optinStart,\n                    inclusive: true,\n                    input,\n                    inst,\n                    origin: \"array\",\n                });\n                return payload;\n            }\n            if (input.length > items.length) {\n                payload.issues.push({\n                    code: \"too_big\",\n                    maximum: items.length,\n                    inclusive: true,\n                    input,\n                    inst,\n                    origin: \"array\",\n                });\n            }\n        }\n        // Run every item in parallel, collecting results into an indexed\n        // array. The post-processing in `handleTupleResults` walks them in\n        // order so it can decide whether an absent optional-output error can\n        // truncate the tail or must be reported to preserve required output.\n        const itemResults = new Array(items.length);\n        for (let i = 0; i < items.length; i++) {\n            const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n            if (r instanceof Promise) {\n                proms.push(r.then((rr) => {\n                    itemResults[i] = rr;\n                }));\n            }\n            else {\n                itemResults[i] = r;\n            }\n        }\n        if (def.rest) {\n            let i = items.length - 1;\n            const rest = input.slice(items.length);\n            for (const el of rest) {\n                i++;\n                const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n                if (result instanceof Promise) {\n                    proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n                }\n                else {\n                    handleTupleResult(result, payload, i);\n                }\n            }\n        }\n        if (proms.length) {\n            return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n        }\n        return handleTupleResults(itemResults, payload, items, input, optoutStart);\n    };\n});\nfunction getTupleOptStart(items, key) {\n    for (let i = items.length - 1; i >= 0; i--) {\n        if (items[i]._zod[key] !== \"optional\")\n            return i + 1;\n    }\n    return 0;\n}\nfunction handleTupleResult(result, final, index) {\n    if (result.issues.length) {\n        final.issues.push(...util.prefixIssues(index, result.issues));\n    }\n    final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n    // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional\n    // rule, but only after `optoutStart`: the first index where the output\n    // tuple tail can be absent.\n    for (let i = 0; i < items.length; i++) {\n        const r = itemResults[i];\n        const isPresent = i < input.length;\n        if (r.issues.length) {\n            if (!isPresent && i >= optoutStart) {\n                final.value.length = i;\n                break;\n            }\n            final.issues.push(...util.prefixIssues(i, r.issues));\n        }\n        final.value[i] = r.value;\n    }\n    // Drop trailing slots that produced `undefined` for absent input\n    // (the array analog of an absent optional key on an object). The\n    // `i >= input.length` floor is critical: an explicit `undefined`\n    // *inside* the input must be preserved even when the schema is\n    // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n    // explicit undefined value).\n    for (let i = final.value.length - 1; i >= input.length; i--) {\n        if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n            final.value.length = i;\n        }\n        else {\n            break;\n        }\n    }\n    return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!util.isPlainObject(input)) {\n            payload.issues.push({\n                expected: \"record\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        const proms = [];\n        const values = def.keyType._zod.values;\n        if (values) {\n            payload.value = {};\n            const recordKeys = new Set();\n            for (const key of values) {\n                if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n                    recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n                    const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n                    if (keyResult instanceof Promise) {\n                        throw new Error(\"Async schemas not supported in object keys currently\");\n                    }\n                    if (keyResult.issues.length) {\n                        payload.issues.push({\n                            code: \"invalid_key\",\n                            origin: \"record\",\n                            issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n                            input: key,\n                            path: [key],\n                            inst,\n                        });\n                        continue;\n                    }\n                    const outKey = keyResult.value;\n                    const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n                    if (result instanceof Promise) {\n                        proms.push(result.then((result) => {\n                            if (result.issues.length) {\n                                payload.issues.push(...util.prefixIssues(key, result.issues));\n                            }\n                            payload.value[outKey] = result.value;\n                        }));\n                    }\n                    else {\n                        if (result.issues.length) {\n                            payload.issues.push(...util.prefixIssues(key, result.issues));\n                        }\n                        payload.value[outKey] = result.value;\n                    }\n                }\n            }\n            let unrecognized;\n            for (const key in input) {\n                if (!recordKeys.has(key)) {\n                    unrecognized = unrecognized ?? [];\n                    unrecognized.push(key);\n                }\n            }\n            if (unrecognized && unrecognized.length > 0) {\n                payload.issues.push({\n                    code: \"unrecognized_keys\",\n                    input,\n                    inst,\n                    keys: unrecognized,\n                });\n            }\n        }\n        else {\n            payload.value = {};\n            // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n            for (const key of Reflect.ownKeys(input)) {\n                if (key === \"__proto__\")\n                    continue;\n                if (!Object.prototype.propertyIsEnumerable.call(input, key))\n                    continue;\n                let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n                if (keyResult instanceof Promise) {\n                    throw new Error(\"Async schemas not supported in object keys currently\");\n                }\n                // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n                // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n                const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n                if (checkNumericKey) {\n                    const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n                    if (retryResult instanceof Promise) {\n                        throw new Error(\"Async schemas not supported in object keys currently\");\n                    }\n                    if (retryResult.issues.length === 0) {\n                        keyResult = retryResult;\n                    }\n                }\n                if (keyResult.issues.length) {\n                    if (def.mode === \"loose\") {\n                        // Pass through unchanged\n                        payload.value[key] = input[key];\n                    }\n                    else {\n                        // Default \"strict\" behavior: error on invalid key\n                        payload.issues.push({\n                            code: \"invalid_key\",\n                            origin: \"record\",\n                            issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n                            input: key,\n                            path: [key],\n                            inst,\n                        });\n                    }\n                    continue;\n                }\n                const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n                if (result instanceof Promise) {\n                    proms.push(result.then((result) => {\n                        if (result.issues.length) {\n                            payload.issues.push(...util.prefixIssues(key, result.issues));\n                        }\n                        payload.value[keyResult.value] = result.value;\n                    }));\n                }\n                else {\n                    if (result.issues.length) {\n                        payload.issues.push(...util.prefixIssues(key, result.issues));\n                    }\n                    payload.value[keyResult.value] = result.value;\n                }\n            }\n        }\n        if (proms.length) {\n            return Promise.all(proms).then(() => payload);\n        }\n        return payload;\n    };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!(input instanceof Map)) {\n            payload.issues.push({\n                expected: \"map\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        const proms = [];\n        payload.value = new Map();\n        for (const [key, value] of input) {\n            const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n            const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n            if (keyResult instanceof Promise || valueResult instanceof Promise) {\n                proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n                    handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n                }));\n            }\n            else {\n                handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n            }\n        }\n        if (proms.length)\n            return Promise.all(proms).then(() => payload);\n        return payload;\n    };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n    if (keyResult.issues.length) {\n        if (util.propertyKeyTypes.has(typeof key)) {\n            final.issues.push(...util.prefixIssues(key, keyResult.issues));\n        }\n        else {\n            final.issues.push({\n                code: \"invalid_key\",\n                origin: \"map\",\n                input,\n                inst,\n                issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n            });\n        }\n    }\n    if (valueResult.issues.length) {\n        if (util.propertyKeyTypes.has(typeof key)) {\n            final.issues.push(...util.prefixIssues(key, valueResult.issues));\n        }\n        else {\n            final.issues.push({\n                origin: \"map\",\n                code: \"invalid_element\",\n                input,\n                inst,\n                key: key,\n                issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n            });\n        }\n    }\n    final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!(input instanceof Set)) {\n            payload.issues.push({\n                input,\n                inst,\n                expected: \"set\",\n                code: \"invalid_type\",\n            });\n            return payload;\n        }\n        const proms = [];\n        payload.value = new Set();\n        for (const item of input) {\n            const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n            if (result instanceof Promise) {\n                proms.push(result.then((result) => handleSetResult(result, payload)));\n            }\n            else\n                handleSetResult(result, payload);\n        }\n        if (proms.length)\n            return Promise.all(proms).then(() => payload);\n        return payload;\n    };\n});\nfunction handleSetResult(result, final) {\n    if (result.issues.length) {\n        final.issues.push(...result.issues);\n    }\n    final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const values = util.getEnumValues(def.entries);\n    const valuesSet = new Set(values);\n    inst._zod.values = valuesSet;\n    inst._zod.pattern = new RegExp(`^(${values\n        .filter((k) => util.propertyKeyTypes.has(typeof k))\n        .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n        .join(\"|\")})$`);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (valuesSet.has(input)) {\n            return payload;\n        }\n        payload.issues.push({\n            code: \"invalid_value\",\n            values,\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n    $ZodType.init(inst, def);\n    if (def.values.length === 0) {\n        throw new Error(\"Cannot create literal schema with no valid values\");\n    }\n    const values = new Set(def.values);\n    inst._zod.values = values;\n    inst._zod.pattern = new RegExp(`^(${def.values\n        .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n        .join(\"|\")})$`);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (values.has(input)) {\n            return payload;\n        }\n        payload.issues.push({\n            code: \"invalid_value\",\n            values: def.values,\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        // @ts-ignore\n        if (input instanceof File)\n            return payload;\n        payload.issues.push({\n            expected: \"file\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.optin = \"optional\";\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            throw new core.$ZodEncodeError(inst.constructor.name);\n        }\n        const _out = def.transform(payload.value, payload);\n        if (ctx.async) {\n            const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n            return output.then((output) => {\n                payload.value = output;\n                payload.fallback = true;\n                return payload;\n            });\n        }\n        if (_out instanceof Promise) {\n            throw new core.$ZodAsyncError();\n        }\n        payload.value = _out;\n        payload.fallback = true;\n        return payload;\n    };\n});\nfunction handleOptionalResult(result, input) {\n    if (input === undefined && (result.issues.length || result.fallback)) {\n        return { issues: [], value: undefined };\n    }\n    return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.optin = \"optional\";\n    inst._zod.optout = \"optional\";\n    util.defineLazy(inst._zod, \"values\", () => {\n        return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n    });\n    util.defineLazy(inst._zod, \"pattern\", () => {\n        const pattern = def.innerType._zod.pattern;\n        return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n    });\n    inst._zod.parse = (payload, ctx) => {\n        if (def.innerType._zod.optin === \"optional\") {\n            const input = payload.value;\n            const result = def.innerType._zod.run(payload, ctx);\n            if (result instanceof Promise)\n                return result.then((r) => handleOptionalResult(r, input));\n            return handleOptionalResult(result, input);\n        }\n        if (payload.value === undefined) {\n            return payload;\n        }\n        return def.innerType._zod.run(payload, ctx);\n    };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n    // Call parent init - inherits optin/optout = \"optional\"\n    $ZodOptional.init(inst, def);\n    // Override values/pattern to NOT add undefined\n    util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n    util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n    // Override parse to just delegate (no undefined handling)\n    inst._zod.parse = (payload, ctx) => {\n        return def.innerType._zod.run(payload, ctx);\n    };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n    util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n    util.defineLazy(inst._zod, \"pattern\", () => {\n        const pattern = def.innerType._zod.pattern;\n        return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n    });\n    util.defineLazy(inst._zod, \"values\", () => {\n        return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n    });\n    inst._zod.parse = (payload, ctx) => {\n        // Forward direction (decode): allow null to pass through\n        if (payload.value === null)\n            return payload;\n        return def.innerType._zod.run(payload, ctx);\n    };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n    $ZodType.init(inst, def);\n    // inst._zod.qin = \"true\";\n    inst._zod.optin = \"optional\";\n    util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            return def.innerType._zod.run(payload, ctx);\n        }\n        // Forward direction (decode): apply defaults for undefined input\n        if (payload.value === undefined) {\n            payload.value = def.defaultValue;\n            /**\n             * $ZodDefault returns the default value immediately in forward direction.\n             * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe.   */\n            return payload;\n        }\n        // Forward direction: continue with default handling\n        const result = def.innerType._zod.run(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then((result) => handleDefaultResult(result, def));\n        }\n        return handleDefaultResult(result, def);\n    };\n});\nfunction handleDefaultResult(payload, def) {\n    if (payload.value === undefined) {\n        payload.value = def.defaultValue;\n    }\n    return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.optin = \"optional\";\n    util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            return def.innerType._zod.run(payload, ctx);\n        }\n        // Forward direction (decode): apply prefault for undefined input\n        if (payload.value === undefined) {\n            payload.value = def.defaultValue;\n        }\n        return def.innerType._zod.run(payload, ctx);\n    };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazy(inst._zod, \"values\", () => {\n        const v = def.innerType._zod.values;\n        return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n    });\n    inst._zod.parse = (payload, ctx) => {\n        const result = def.innerType._zod.run(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then((result) => handleNonOptionalResult(result, inst));\n        }\n        return handleNonOptionalResult(result, inst);\n    };\n});\nfunction handleNonOptionalResult(payload, inst) {\n    if (!payload.issues.length && payload.value === undefined) {\n        payload.issues.push({\n            code: \"invalid_type\",\n            expected: \"nonoptional\",\n            input: payload.value,\n            inst,\n        });\n    }\n    return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            throw new core.$ZodEncodeError(\"ZodSuccess\");\n        }\n        const result = def.innerType._zod.run(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then((result) => {\n                payload.value = result.issues.length === 0;\n                return payload;\n            });\n        }\n        payload.value = result.issues.length === 0;\n        return payload;\n    };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.optin = \"optional\";\n    util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n    util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            return def.innerType._zod.run(payload, ctx);\n        }\n        // Forward direction (decode): apply catch logic\n        const result = def.innerType._zod.run(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then((result) => {\n                payload.value = result.value;\n                if (result.issues.length) {\n                    payload.value = def.catchValue({\n                        ...payload,\n                        error: {\n                            issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n                        },\n                        input: payload.value,\n                    });\n                    payload.issues = [];\n                    payload.fallback = true;\n                }\n                return payload;\n            });\n        }\n        payload.value = result.value;\n        if (result.issues.length) {\n            payload.value = def.catchValue({\n                ...payload,\n                error: {\n                    issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n                },\n                input: payload.value,\n            });\n            payload.issues = [];\n            payload.fallback = true;\n        }\n        return payload;\n    };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n            payload.issues.push({\n                input: payload.value,\n                inst,\n                expected: \"nan\",\n                code: \"invalid_type\",\n            });\n            return payload;\n        }\n        return payload;\n    };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n    util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n    util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n    util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            const right = def.out._zod.run(payload, ctx);\n            if (right instanceof Promise) {\n                return right.then((right) => handlePipeResult(right, def.in, ctx));\n            }\n            return handlePipeResult(right, def.in, ctx);\n        }\n        const left = def.in._zod.run(payload, ctx);\n        if (left instanceof Promise) {\n            return left.then((left) => handlePipeResult(left, def.out, ctx));\n        }\n        return handlePipeResult(left, def.out, ctx);\n    };\n});\nfunction handlePipeResult(left, next, ctx) {\n    if (left.issues.length) {\n        // prevent further checks\n        left.aborted = true;\n        return left;\n    }\n    return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n    util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n    util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n    util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n    inst._zod.parse = (payload, ctx) => {\n        const direction = ctx.direction || \"forward\";\n        if (direction === \"forward\") {\n            const left = def.in._zod.run(payload, ctx);\n            if (left instanceof Promise) {\n                return left.then((left) => handleCodecAResult(left, def, ctx));\n            }\n            return handleCodecAResult(left, def, ctx);\n        }\n        else {\n            const right = def.out._zod.run(payload, ctx);\n            if (right instanceof Promise) {\n                return right.then((right) => handleCodecAResult(right, def, ctx));\n            }\n            return handleCodecAResult(right, def, ctx);\n        }\n    };\n});\nfunction handleCodecAResult(result, def, ctx) {\n    if (result.issues.length) {\n        // prevent further checks\n        result.aborted = true;\n        return result;\n    }\n    const direction = ctx.direction || \"forward\";\n    if (direction === \"forward\") {\n        const transformed = def.transform(result.value, result);\n        if (transformed instanceof Promise) {\n            return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n        }\n        return handleCodecTxResult(result, transformed, def.out, ctx);\n    }\n    else {\n        const transformed = def.reverseTransform(result.value, result);\n        if (transformed instanceof Promise) {\n            return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n        }\n        return handleCodecTxResult(result, transformed, def.in, ctx);\n    }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n    // Check if transform added any issues\n    if (left.issues.length) {\n        left.aborted = true;\n        return left;\n    }\n    return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n    $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n    util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n    util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n    util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            return def.innerType._zod.run(payload, ctx);\n        }\n        const result = def.innerType._zod.run(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then(handleReadonlyResult);\n        }\n        return handleReadonlyResult(result);\n    };\n});\nfunction handleReadonlyResult(payload) {\n    payload.value = Object.freeze(payload.value);\n    return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const regexParts = [];\n    for (const part of def.parts) {\n        if (typeof part === \"object\" && part !== null) {\n            // is Zod schema\n            if (!part._zod.pattern) {\n                // if (!source)\n                throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n            }\n            const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n            if (!source)\n                throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n            const start = source.startsWith(\"^\") ? 1 : 0;\n            const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n            regexParts.push(source.slice(start, end));\n        }\n        else if (part === null || util.primitiveTypes.has(typeof part)) {\n            regexParts.push(util.escapeRegex(`${part}`));\n        }\n        else {\n            throw new Error(`Invalid template literal part: ${part}`);\n        }\n    }\n    inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n    inst._zod.parse = (payload, _ctx) => {\n        if (typeof payload.value !== \"string\") {\n            payload.issues.push({\n                input: payload.value,\n                inst,\n                expected: \"string\",\n                code: \"invalid_type\",\n            });\n            return payload;\n        }\n        inst._zod.pattern.lastIndex = 0;\n        if (!inst._zod.pattern.test(payload.value)) {\n            payload.issues.push({\n                input: payload.value,\n                inst,\n                code: \"invalid_format\",\n                format: def.format ?? \"template_literal\",\n                pattern: inst._zod.pattern.source,\n            });\n            return payload;\n        }\n        return payload;\n    };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._def = def;\n    inst._zod.def = def;\n    inst.implement = (func) => {\n        if (typeof func !== \"function\") {\n            throw new Error(\"implement() must be called with a function\");\n        }\n        return function (...args) {\n            const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n            const result = Reflect.apply(func, this, parsedArgs);\n            if (inst._def.output) {\n                return parse(inst._def.output, result);\n            }\n            return result;\n        };\n    };\n    inst.implementAsync = (func) => {\n        if (typeof func !== \"function\") {\n            throw new Error(\"implementAsync() must be called with a function\");\n        }\n        return async function (...args) {\n            const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n            const result = await Reflect.apply(func, this, parsedArgs);\n            if (inst._def.output) {\n                return await parseAsync(inst._def.output, result);\n            }\n            return result;\n        };\n    };\n    inst._zod.parse = (payload, _ctx) => {\n        if (typeof payload.value !== \"function\") {\n            payload.issues.push({\n                code: \"invalid_type\",\n                expected: \"function\",\n                input: payload.value,\n                inst,\n            });\n            return payload;\n        }\n        // Check if output is a promise type to determine if we should use async implementation\n        const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n        if (hasPromiseOutput) {\n            payload.value = inst.implementAsync(payload.value);\n        }\n        else {\n            payload.value = inst.implement(payload.value);\n        }\n        return payload;\n    };\n    inst.input = (...args) => {\n        const F = inst.constructor;\n        if (Array.isArray(args[0])) {\n            return new F({\n                type: \"function\",\n                input: new $ZodTuple({\n                    type: \"tuple\",\n                    items: args[0],\n                    rest: args[1],\n                }),\n                output: inst._def.output,\n            });\n        }\n        return new F({\n            type: \"function\",\n            input: args[0],\n            output: inst._def.output,\n        });\n    };\n    inst.output = (output) => {\n        const F = inst.constructor;\n        return new F({\n            type: \"function\",\n            input: inst._def.input,\n            output,\n        });\n    };\n    return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, ctx) => {\n        return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n    };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n    $ZodType.init(inst, def);\n    // Cache the resolved inner type on the shared `def` so all clones of this\n    // lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance,\n    // preserving identity for cycle detection on recursive schemas.\n    util.defineLazy(inst._zod, \"innerType\", () => {\n        const d = def;\n        if (!d._cachedInner)\n            d._cachedInner = def.getter();\n        return d._cachedInner;\n    });\n    util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n    util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n    util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n    util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n    inst._zod.parse = (payload, ctx) => {\n        const inner = inst._zod.innerType;\n        return inner._zod.run(payload, ctx);\n    };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n    checks.$ZodCheck.init(inst, def);\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _) => {\n        return payload;\n    };\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const r = def.fn(input);\n        if (r instanceof Promise) {\n            return r.then((r) => handleRefineResult(r, payload, input, inst));\n        }\n        handleRefineResult(r, payload, input, inst);\n        return;\n    };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n    if (!result) {\n        const _iss = {\n            code: \"custom\",\n            input,\n            inst, // incorporates params.error into issue reporting\n            path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n            continue: !inst._zod.def.abort,\n            // params: inst._zod.def.params,\n        };\n        if (inst._zod.def.params)\n            _iss.params = inst._zod.def.params;\n        payload.issues.push(util.issue(_iss));\n    }\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n    constructor() {\n        this._map = new WeakMap();\n        this._idmap = new Map();\n    }\n    add(schema, ..._meta) {\n        const meta = _meta[0];\n        this._map.set(schema, meta);\n        if (meta && typeof meta === \"object\" && \"id\" in meta) {\n            this._idmap.set(meta.id, schema);\n        }\n        return this;\n    }\n    clear() {\n        this._map = new WeakMap();\n        this._idmap = new Map();\n        return this;\n    }\n    remove(schema) {\n        const meta = this._map.get(schema);\n        if (meta && typeof meta === \"object\" && \"id\" in meta) {\n            this._idmap.delete(meta.id);\n        }\n        this._map.delete(schema);\n        return this;\n    }\n    get(schema) {\n        // return this._map.get(schema) as any;\n        // inherit metadata\n        const p = schema._zod.parent;\n        if (p) {\n            const pm = { ...(this.get(p) ?? {}) };\n            delete pm.id; // do not inherit id\n            const f = { ...pm, ...this._map.get(schema) };\n            return Object.keys(f).length ? f : undefined;\n        }\n        return this._map.get(schema);\n    }\n    has(schema) {\n        return this._map.has(schema);\n    }\n}\n// registries\nexport function registry() {\n    return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n    return new Class({\n        type: \"string\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n    return new Class({\n        type: \"string\",\n        coerce: true,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"email\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"guid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"uuid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"uuid\",\n        check: \"string_format\",\n        abort: false,\n        version: \"v4\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"uuid\",\n        check: \"string_format\",\n        abort: false,\n        version: \"v6\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"uuid\",\n        check: \"string_format\",\n        abort: false,\n        version: \"v7\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"url\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"emoji\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"nanoid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"cuid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"cuid2\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"ulid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"xid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"ksuid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"ipv4\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"ipv6\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"mac\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"cidrv4\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"cidrv6\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"base64\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"base64url\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"e164\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"jwt\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\nexport const TimePrecision = {\n    Any: null,\n    Minute: -1,\n    Second: 0,\n    Millisecond: 3,\n    Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"datetime\",\n        check: \"string_format\",\n        offset: false,\n        local: false,\n        precision: null,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"date\",\n        check: \"string_format\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"time\",\n        check: \"string_format\",\n        precision: null,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"duration\",\n        check: \"string_format\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n    return new Class({\n        type: \"number\",\n        checks: [],\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n    return new Class({\n        type: \"number\",\n        coerce: true,\n        checks: [],\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"safeint\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"float32\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"float64\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"int32\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"uint32\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n    return new Class({\n        type: \"boolean\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n    return new Class({\n        type: \"boolean\",\n        coerce: true,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n    return new Class({\n        type: \"bigint\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n    return new Class({\n        type: \"bigint\",\n        coerce: true,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n    return new Class({\n        type: \"bigint\",\n        check: \"bigint_format\",\n        abort: false,\n        format: \"int64\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n    return new Class({\n        type: \"bigint\",\n        check: \"bigint_format\",\n        abort: false,\n        format: \"uint64\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n    return new Class({\n        type: \"symbol\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n    return new Class({\n        type: \"undefined\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n    return new Class({\n        type: \"null\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n    return new Class({\n        type: \"any\",\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n    return new Class({\n        type: \"unknown\",\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n    return new Class({\n        type: \"never\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n    return new Class({\n        type: \"void\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n    return new Class({\n        type: \"date\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n    return new Class({\n        type: \"date\",\n        coerce: true,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n    return new Class({\n        type: \"nan\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n    return new checks.$ZodCheckLessThan({\n        check: \"less_than\",\n        ...util.normalizeParams(params),\n        value,\n        inclusive: false,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n    return new checks.$ZodCheckLessThan({\n        check: \"less_than\",\n        ...util.normalizeParams(params),\n        value,\n        inclusive: true,\n    });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n    return new checks.$ZodCheckGreaterThan({\n        check: \"greater_than\",\n        ...util.normalizeParams(params),\n        value,\n        inclusive: false,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n    return new checks.$ZodCheckGreaterThan({\n        check: \"greater_than\",\n        ...util.normalizeParams(params),\n        value,\n        inclusive: true,\n    });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n    return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n    return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n    return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n    return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n    return new checks.$ZodCheckMultipleOf({\n        check: \"multiple_of\",\n        ...util.normalizeParams(params),\n        value,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n    return new checks.$ZodCheckMaxSize({\n        check: \"max_size\",\n        ...util.normalizeParams(params),\n        maximum,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n    return new checks.$ZodCheckMinSize({\n        check: \"min_size\",\n        ...util.normalizeParams(params),\n        minimum,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n    return new checks.$ZodCheckSizeEquals({\n        check: \"size_equals\",\n        ...util.normalizeParams(params),\n        size,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n    const ch = new checks.$ZodCheckMaxLength({\n        check: \"max_length\",\n        ...util.normalizeParams(params),\n        maximum,\n    });\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n    return new checks.$ZodCheckMinLength({\n        check: \"min_length\",\n        ...util.normalizeParams(params),\n        minimum,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n    return new checks.$ZodCheckLengthEquals({\n        check: \"length_equals\",\n        ...util.normalizeParams(params),\n        length,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n    return new checks.$ZodCheckRegex({\n        check: \"string_format\",\n        format: \"regex\",\n        ...util.normalizeParams(params),\n        pattern,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n    return new checks.$ZodCheckLowerCase({\n        check: \"string_format\",\n        format: \"lowercase\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n    return new checks.$ZodCheckUpperCase({\n        check: \"string_format\",\n        format: \"uppercase\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n    return new checks.$ZodCheckIncludes({\n        check: \"string_format\",\n        format: \"includes\",\n        ...util.normalizeParams(params),\n        includes,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n    return new checks.$ZodCheckStartsWith({\n        check: \"string_format\",\n        format: \"starts_with\",\n        ...util.normalizeParams(params),\n        prefix,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n    return new checks.$ZodCheckEndsWith({\n        check: \"string_format\",\n        format: \"ends_with\",\n        ...util.normalizeParams(params),\n        suffix,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n    return new checks.$ZodCheckProperty({\n        check: \"property\",\n        property,\n        schema,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n    return new checks.$ZodCheckMimeType({\n        check: \"mime_type\",\n        mime: types,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n    return new checks.$ZodCheckOverwrite({\n        check: \"overwrite\",\n        tx,\n    });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n    return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n    return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n    return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n    return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n    return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n    return new Class({\n        type: \"array\",\n        element,\n        // get element() {\n        //   return element;\n        // },\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n    return new Class({\n        type: \"union\",\n        options,\n        ...util.normalizeParams(params),\n    });\n}\nexport function _xor(Class, options, params) {\n    return new Class({\n        type: \"union\",\n        options,\n        inclusive: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n    return new Class({\n        type: \"union\",\n        options,\n        discriminator,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n    return new Class({\n        type: \"intersection\",\n        left,\n        right,\n    });\n}\n// export function _tuple(\n//   Class: util.SchemaClass<schemas.$ZodTuple>,\n//   items: [],\n//   params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n    const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n    const params = hasRest ? _params : _paramsOrRest;\n    const rest = hasRest ? _paramsOrRest : null;\n    return new Class({\n        type: \"tuple\",\n        items,\n        rest,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n    return new Class({\n        type: \"record\",\n        keyType,\n        valueType,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n    return new Class({\n        type: \"map\",\n        keyType,\n        valueType,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n    return new Class({\n        type: \"set\",\n        valueType,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n    const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n    // if (Array.isArray(values)) {\n    //   for (const value of values) {\n    //     entries[value] = value;\n    //   }\n    // } else {\n    //   Object.assign(entries, values);\n    // }\n    // const entries: util.EnumLike = {};\n    // for (const val of values) {\n    //   entries[val] = val;\n    // }\n    return new Class({\n        type: \"enum\",\n        entries,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n    return new Class({\n        type: \"enum\",\n        entries,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n    return new Class({\n        type: \"literal\",\n        values: Array.isArray(value) ? value : [value],\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n    return new Class({\n        type: \"file\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n    return new Class({\n        type: \"transform\",\n        transform: fn,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n    return new Class({\n        type: \"optional\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n    return new Class({\n        type: \"nullable\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n    return new Class({\n        type: \"default\",\n        innerType,\n        get defaultValue() {\n            return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n        },\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n    return new Class({\n        type: \"nonoptional\",\n        innerType,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n    return new Class({\n        type: \"success\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n    return new Class({\n        type: \"catch\",\n        innerType,\n        catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n    return new Class({\n        type: \"pipe\",\n        in: in_,\n        out,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n    return new Class({\n        type: \"readonly\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n    return new Class({\n        type: \"template_literal\",\n        parts,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n    return new Class({\n        type: \"lazy\",\n        getter,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n    return new Class({\n        type: \"promise\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n    const norm = util.normalizeParams(_params);\n    norm.abort ?? (norm.abort = true); // default to abort:false\n    const schema = new Class({\n        type: \"custom\",\n        check: \"custom\",\n        fn: fn,\n        ...norm,\n    });\n    return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n    const schema = new Class({\n        type: \"custom\",\n        check: \"custom\",\n        fn: fn,\n        ...util.normalizeParams(_params),\n    });\n    return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n    const ch = _check((payload) => {\n        payload.addIssue = (issue) => {\n            if (typeof issue === \"string\") {\n                payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n            }\n            else {\n                // for Zod 3 backwards compatibility\n                const _issue = issue;\n                if (_issue.fatal)\n                    _issue.continue = false;\n                _issue.code ?? (_issue.code = \"custom\");\n                _issue.input ?? (_issue.input = payload.value);\n                _issue.inst ?? (_issue.inst = ch);\n                _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n                payload.issues.push(util.issue(_issue));\n            }\n        };\n        return fn(payload.value, payload);\n    }, params);\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n    const ch = new checks.$ZodCheck({\n        check: \"custom\",\n        ...util.normalizeParams(params),\n    });\n    ch._zod.check = fn;\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n    const ch = new checks.$ZodCheck({ check: \"describe\" });\n    ch._zod.onattach = [\n        (inst) => {\n            const existing = registries.globalRegistry.get(inst) ?? {};\n            registries.globalRegistry.add(inst, { ...existing, description });\n        },\n    ];\n    ch._zod.check = () => { }; // no-op check\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n    const ch = new checks.$ZodCheck({ check: \"meta\" });\n    ch._zod.onattach = [\n        (inst) => {\n            const existing = registries.globalRegistry.get(inst) ?? {};\n            registries.globalRegistry.add(inst, { ...existing, ...metadata });\n        },\n    ];\n    ch._zod.check = () => { }; // no-op check\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n    const params = util.normalizeParams(_params);\n    let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n    let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n    if (params.case !== \"sensitive\") {\n        truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n        falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n    }\n    const truthySet = new Set(truthyArray);\n    const falsySet = new Set(falsyArray);\n    const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n    const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n    const _String = Classes.String ?? schemas.$ZodString;\n    const stringSchema = new _String({ type: \"string\", error: params.error });\n    const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n    const codec = new _Codec({\n        type: \"pipe\",\n        in: stringSchema,\n        out: booleanSchema,\n        transform: ((input, payload) => {\n            let data = input;\n            if (params.case !== \"sensitive\")\n                data = data.toLowerCase();\n            if (truthySet.has(data)) {\n                return true;\n            }\n            else if (falsySet.has(data)) {\n                return false;\n            }\n            else {\n                payload.issues.push({\n                    code: \"invalid_value\",\n                    expected: \"stringbool\",\n                    values: [...truthySet, ...falsySet],\n                    input: payload.value,\n                    inst: codec,\n                    continue: false,\n                });\n                return {};\n            }\n        }),\n        reverseTransform: ((input, _payload) => {\n            if (input === true) {\n                return truthyArray[0] || \"true\";\n            }\n            else {\n                return falsyArray[0] || \"false\";\n            }\n        }),\n        error: params.error,\n    });\n    return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n    const params = util.normalizeParams(_params);\n    const def = {\n        ...util.normalizeParams(_params),\n        check: \"string_format\",\n        type: \"string\",\n        format,\n        fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n        ...params,\n    };\n    if (fnOrRegex instanceof RegExp) {\n        def.pattern = fnOrRegex;\n    }\n    const inst = new Class(def);\n    return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n//   return {\n//     processor: inputs.processor,\n//     metadataRegistry: inputs.metadata ?? globalRegistry,\n//     target: inputs.target ?? \"draft-2020-12\",\n//     unrepresentable: inputs.unrepresentable ?? \"throw\",\n//   };\n// }\nexport function initializeContext(params) {\n    // Normalize target: convert old non-hyphenated versions to hyphenated versions\n    let target = params?.target ?? \"draft-2020-12\";\n    if (target === \"draft-4\")\n        target = \"draft-04\";\n    if (target === \"draft-7\")\n        target = \"draft-07\";\n    return {\n        processors: params.processors ?? {},\n        metadataRegistry: params?.metadata ?? globalRegistry,\n        target,\n        unrepresentable: params?.unrepresentable ?? \"throw\",\n        override: params?.override ?? (() => { }),\n        io: params?.io ?? \"output\",\n        counter: 0,\n        seen: new Map(),\n        cycles: params?.cycles ?? \"ref\",\n        reused: params?.reused ?? \"inline\",\n        external: params?.external ?? undefined,\n    };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n    var _a;\n    const def = schema._zod.def;\n    // check for schema in seens\n    const seen = ctx.seen.get(schema);\n    if (seen) {\n        seen.count++;\n        // check if cycle\n        const isCycle = _params.schemaPath.includes(schema);\n        if (isCycle) {\n            seen.cycle = _params.path;\n        }\n        return seen.schema;\n    }\n    // initialize\n    const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n    ctx.seen.set(schema, result);\n    // custom method overrides default behavior\n    const overrideSchema = schema._zod.toJSONSchema?.();\n    if (overrideSchema) {\n        result.schema = overrideSchema;\n    }\n    else {\n        const params = {\n            ..._params,\n            schemaPath: [..._params.schemaPath, schema],\n            path: _params.path,\n        };\n        if (schema._zod.processJSONSchema) {\n            schema._zod.processJSONSchema(ctx, result.schema, params);\n        }\n        else {\n            const _json = result.schema;\n            const processor = ctx.processors[def.type];\n            if (!processor) {\n                throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n            }\n            processor(schema, ctx, _json, params);\n        }\n        const parent = schema._zod.parent;\n        if (parent) {\n            // Also set ref if processor didn't (for inheritance)\n            if (!result.ref)\n                result.ref = parent;\n            process(parent, ctx, params);\n            ctx.seen.get(parent).isParent = true;\n        }\n    }\n    // metadata\n    const meta = ctx.metadataRegistry.get(schema);\n    if (meta)\n        Object.assign(result.schema, meta);\n    if (ctx.io === \"input\" && isTransforming(schema)) {\n        // examples/defaults only apply to output type of pipe\n        delete result.schema.examples;\n        delete result.schema.default;\n    }\n    // set prefault as default\n    if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n        (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n    delete result.schema._prefault;\n    // pulling fresh from ctx.seen in case it was overwritten\n    const _result = ctx.seen.get(schema);\n    return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n    // iterate over seen map;\n    const root = ctx.seen.get(schema);\n    if (!root)\n        throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n    // Track ids to detect duplicates across different schemas\n    const idToSchema = new Map();\n    for (const entry of ctx.seen.entries()) {\n        const id = ctx.metadataRegistry.get(entry[0])?.id;\n        if (id) {\n            const existing = idToSchema.get(id);\n            if (existing && existing !== entry[0]) {\n                throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n            }\n            idToSchema.set(id, entry[0]);\n        }\n    }\n    // returns a ref to the schema\n    // defId will be empty if the ref points to an external schema (or #)\n    const makeURI = (entry) => {\n        // comparing the seen objects because sometimes\n        // multiple schemas map to the same seen object.\n        // e.g. lazy\n        // external is configured\n        const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n        if (ctx.external) {\n            const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n            // check if schema is in the external registry\n            const uriGenerator = ctx.external.uri ?? ((id) => id);\n            if (externalId) {\n                return { ref: uriGenerator(externalId) };\n            }\n            // otherwise, add to __shared\n            const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n            entry[1].defId = id; // set defId so it will be reused if needed\n            return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n        }\n        if (entry[1] === root) {\n            return { ref: \"#\" };\n        }\n        // self-contained schema\n        const uriPrefix = `#`;\n        const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n        const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n        return { defId, ref: defUriPrefix + defId };\n    };\n    // stored cached version in `def` property\n    // remove all properties, set $ref\n    const extractToDef = (entry) => {\n        // if the schema is already a reference, do not extract it\n        if (entry[1].schema.$ref) {\n            return;\n        }\n        const seen = entry[1];\n        const { ref, defId } = makeURI(entry);\n        seen.def = { ...seen.schema };\n        // defId won't be set if the schema is a reference to an external schema\n        // or if the schema is the root schema\n        if (defId)\n            seen.defId = defId;\n        // wipe away all properties except $ref\n        const schema = seen.schema;\n        for (const key in schema) {\n            delete schema[key];\n        }\n        schema.$ref = ref;\n    };\n    // throw on cycles\n    // break cycles\n    if (ctx.cycles === \"throw\") {\n        for (const entry of ctx.seen.entries()) {\n            const seen = entry[1];\n            if (seen.cycle) {\n                throw new Error(\"Cycle detected: \" +\n                    `#/${seen.cycle?.join(\"/\")}/<root>` +\n                    '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n            }\n        }\n    }\n    // extract schemas into $defs\n    for (const entry of ctx.seen.entries()) {\n        const seen = entry[1];\n        // convert root schema to # $ref\n        if (schema === entry[0]) {\n            extractToDef(entry); // this has special handling for the root schema\n            continue;\n        }\n        // extract schemas that are in the external registry\n        if (ctx.external) {\n            const ext = ctx.external.registry.get(entry[0])?.id;\n            if (schema !== entry[0] && ext) {\n                extractToDef(entry);\n                continue;\n            }\n        }\n        // extract schemas with `id` meta\n        const id = ctx.metadataRegistry.get(entry[0])?.id;\n        if (id) {\n            extractToDef(entry);\n            continue;\n        }\n        // break cycles\n        if (seen.cycle) {\n            // any\n            extractToDef(entry);\n            continue;\n        }\n        // extract reused schemas\n        if (seen.count > 1) {\n            if (ctx.reused === \"ref\") {\n                extractToDef(entry);\n                // biome-ignore lint:\n                continue;\n            }\n        }\n    }\n}\nexport function finalize(ctx, schema) {\n    const root = ctx.seen.get(schema);\n    if (!root)\n        throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n    // flatten refs - inherit properties from parent schemas\n    const flattenRef = (zodSchema) => {\n        const seen = ctx.seen.get(zodSchema);\n        // already processed\n        if (seen.ref === null)\n            return;\n        const schema = seen.def ?? seen.schema;\n        const _cached = { ...schema };\n        const ref = seen.ref;\n        seen.ref = null; // prevent infinite recursion\n        if (ref) {\n            flattenRef(ref);\n            const refSeen = ctx.seen.get(ref);\n            const refSchema = refSeen.schema;\n            // merge referenced schema into current\n            if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n                // older drafts can't combine $ref with other properties\n                schema.allOf = schema.allOf ?? [];\n                schema.allOf.push(refSchema);\n            }\n            else {\n                Object.assign(schema, refSchema);\n            }\n            // restore child's own properties (child wins)\n            Object.assign(schema, _cached);\n            const isParentRef = zodSchema._zod.parent === ref;\n            // For parent chain, child is a refinement - remove parent-only properties\n            if (isParentRef) {\n                for (const key in schema) {\n                    if (key === \"$ref\" || key === \"allOf\")\n                        continue;\n                    if (!(key in _cached)) {\n                        delete schema[key];\n                    }\n                }\n            }\n            // When ref was extracted to $defs, remove properties that match the definition\n            if (refSchema.$ref && refSeen.def) {\n                for (const key in schema) {\n                    if (key === \"$ref\" || key === \"allOf\")\n                        continue;\n                    if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n                        delete schema[key];\n                    }\n                }\n            }\n        }\n        // If parent was extracted (has $ref), propagate $ref to this schema\n        // This handles cases like: readonly().meta({id}).describe()\n        // where processor sets ref to innerType but parent should be referenced\n        const parent = zodSchema._zod.parent;\n        if (parent && parent !== ref) {\n            // Ensure parent is processed first so its def has inherited properties\n            flattenRef(parent);\n            const parentSeen = ctx.seen.get(parent);\n            if (parentSeen?.schema.$ref) {\n                schema.$ref = parentSeen.schema.$ref;\n                // De-duplicate with parent's definition\n                if (parentSeen.def) {\n                    for (const key in schema) {\n                        if (key === \"$ref\" || key === \"allOf\")\n                            continue;\n                        if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n                            delete schema[key];\n                        }\n                    }\n                }\n            }\n        }\n        // execute overrides\n        ctx.override({\n            zodSchema: zodSchema,\n            jsonSchema: schema,\n            path: seen.path ?? [],\n        });\n    };\n    for (const entry of [...ctx.seen.entries()].reverse()) {\n        flattenRef(entry[0]);\n    }\n    const result = {};\n    if (ctx.target === \"draft-2020-12\") {\n        result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n    }\n    else if (ctx.target === \"draft-07\") {\n        result.$schema = \"http://json-schema.org/draft-07/schema#\";\n    }\n    else if (ctx.target === \"draft-04\") {\n        result.$schema = \"http://json-schema.org/draft-04/schema#\";\n    }\n    else if (ctx.target === \"openapi-3.0\") {\n        // OpenAPI 3.0 schema objects should not include a $schema property\n    }\n    else {\n        // Arbitrary string values are allowed but won't have a $schema property set\n    }\n    if (ctx.external?.uri) {\n        const id = ctx.external.registry.get(schema)?.id;\n        if (!id)\n            throw new Error(\"Schema is missing an `id` property\");\n        result.$id = ctx.external.uri(id);\n    }\n    Object.assign(result, root.def ?? root.schema);\n    // The `id` in `.meta()` is a Zod-specific registration tag used to extract\n    // schemas into $defs — it is not user-facing JSON Schema metadata. Strip it\n    // from the output body where it would otherwise leak. The id is preserved\n    // implicitly via the $defs key (and via $ref paths).\n    const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n    if (rootMetaId !== undefined && result.id === rootMetaId)\n        delete result.id;\n    // build defs object\n    const defs = ctx.external?.defs ?? {};\n    for (const entry of ctx.seen.entries()) {\n        const seen = entry[1];\n        if (seen.def && seen.defId) {\n            if (seen.def.id === seen.defId)\n                delete seen.def.id;\n            defs[seen.defId] = seen.def;\n        }\n    }\n    // set definitions in result\n    if (ctx.external) {\n    }\n    else {\n        if (Object.keys(defs).length > 0) {\n            if (ctx.target === \"draft-2020-12\") {\n                result.$defs = defs;\n            }\n            else {\n                result.definitions = defs;\n            }\n        }\n    }\n    try {\n        // this \"finalizes\" this schema and ensures all cycles are removed\n        // each call to finalize() is functionally independent\n        // though the seen map is shared\n        const finalized = JSON.parse(JSON.stringify(result));\n        Object.defineProperty(finalized, \"~standard\", {\n            value: {\n                ...schema[\"~standard\"],\n                jsonSchema: {\n                    input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n                    output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n                },\n            },\n            enumerable: false,\n            writable: false,\n        });\n        return finalized;\n    }\n    catch (_err) {\n        throw new Error(\"Error converting schema to JSON.\");\n    }\n}\nfunction isTransforming(_schema, _ctx) {\n    const ctx = _ctx ?? { seen: new Set() };\n    if (ctx.seen.has(_schema))\n        return false;\n    ctx.seen.add(_schema);\n    const def = _schema._zod.def;\n    if (def.type === \"transform\")\n        return true;\n    if (def.type === \"array\")\n        return isTransforming(def.element, ctx);\n    if (def.type === \"set\")\n        return isTransforming(def.valueType, ctx);\n    if (def.type === \"lazy\")\n        return isTransforming(def.getter(), ctx);\n    if (def.type === \"promise\" ||\n        def.type === \"optional\" ||\n        def.type === \"nonoptional\" ||\n        def.type === \"nullable\" ||\n        def.type === \"readonly\" ||\n        def.type === \"default\" ||\n        def.type === \"prefault\") {\n        return isTransforming(def.innerType, ctx);\n    }\n    if (def.type === \"intersection\") {\n        return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n    }\n    if (def.type === \"record\" || def.type === \"map\") {\n        return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n    }\n    if (def.type === \"pipe\") {\n        if (_schema._zod.traits.has(\"$ZodCodec\"))\n            return true;\n        return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n    }\n    if (def.type === \"object\") {\n        for (const key in def.shape) {\n            if (isTransforming(def.shape[key], ctx))\n                return true;\n        }\n        return false;\n    }\n    if (def.type === \"union\") {\n        for (const option of def.options) {\n            if (isTransforming(option, ctx))\n                return true;\n        }\n        return false;\n    }\n    if (def.type === \"tuple\") {\n        for (const item of def.items) {\n            if (isTransforming(item, ctx))\n                return true;\n        }\n        if (def.rest && isTransforming(def.rest, ctx))\n            return true;\n        return false;\n    }\n    return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n    const ctx = initializeContext({ ...params, processors });\n    process(schema, ctx);\n    extractDefs(ctx, schema);\n    return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n    const { libraryOptions, target } = params ?? {};\n    const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n    process(schema, ctx);\n    extractDefs(ctx, schema);\n    return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n    guid: \"uuid\",\n    url: \"uri\",\n    datetime: \"date-time\",\n    json_string: \"json-string\",\n    regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n    const json = _json;\n    json.type = \"string\";\n    const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n        .bag;\n    if (typeof minimum === \"number\")\n        json.minLength = minimum;\n    if (typeof maximum === \"number\")\n        json.maxLength = maximum;\n    // custom pattern overrides format\n    if (format) {\n        json.format = formatMap[format] ?? format;\n        if (json.format === \"\")\n            delete json.format; // empty format is not valid\n        // JSON Schema format: \"time\" requires a full time with offset or Z\n        // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n        if (format === \"time\") {\n            delete json.format;\n        }\n    }\n    if (contentEncoding)\n        json.contentEncoding = contentEncoding;\n    if (patterns && patterns.size > 0) {\n        const regexes = [...patterns];\n        if (regexes.length === 1)\n            json.pattern = regexes[0].source;\n        else if (regexes.length > 1) {\n            json.allOf = [\n                ...regexes.map((regex) => ({\n                    ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n                        ? { type: \"string\" }\n                        : {}),\n                    pattern: regex.source,\n                })),\n            ];\n        }\n    }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n    const json = _json;\n    const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n    if (typeof format === \"string\" && format.includes(\"int\"))\n        json.type = \"integer\";\n    else\n        json.type = \"number\";\n    // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n    const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n    const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n    const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n    if (exMin) {\n        if (legacy) {\n            json.minimum = exclusiveMinimum;\n            json.exclusiveMinimum = true;\n        }\n        else {\n            json.exclusiveMinimum = exclusiveMinimum;\n        }\n    }\n    else if (typeof minimum === \"number\") {\n        json.minimum = minimum;\n    }\n    if (exMax) {\n        if (legacy) {\n            json.maximum = exclusiveMaximum;\n            json.exclusiveMaximum = true;\n        }\n        else {\n            json.exclusiveMaximum = exclusiveMaximum;\n        }\n    }\n    else if (typeof maximum === \"number\") {\n        json.maximum = maximum;\n    }\n    if (typeof multipleOf === \"number\")\n        json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n    json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"BigInt cannot be represented in JSON Schema\");\n    }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Symbols cannot be represented in JSON Schema\");\n    }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n    if (ctx.target === \"openapi-3.0\") {\n        json.type = \"string\";\n        json.nullable = true;\n        json.enum = [null];\n    }\n    else {\n        json.type = \"null\";\n    }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Undefined cannot be represented in JSON Schema\");\n    }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Void cannot be represented in JSON Schema\");\n    }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n    json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n    // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n    // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Date cannot be represented in JSON Schema\");\n    }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n    const def = schema._zod.def;\n    const values = getEnumValues(def.entries);\n    // Number enums can have both string and number values\n    if (values.every((v) => typeof v === \"number\"))\n        json.type = \"number\";\n    if (values.every((v) => typeof v === \"string\"))\n        json.type = \"string\";\n    json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n    const def = schema._zod.def;\n    const vals = [];\n    for (const val of def.values) {\n        if (val === undefined) {\n            if (ctx.unrepresentable === \"throw\") {\n                throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n            }\n            else {\n                // do not add to vals\n            }\n        }\n        else if (typeof val === \"bigint\") {\n            if (ctx.unrepresentable === \"throw\") {\n                throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n            }\n            else {\n                vals.push(Number(val));\n            }\n        }\n        else {\n            vals.push(val);\n        }\n    }\n    if (vals.length === 0) {\n        // do nothing (an undefined literal was stripped)\n    }\n    else if (vals.length === 1) {\n        const val = vals[0];\n        json.type = val === null ? \"null\" : typeof val;\n        if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n            json.enum = [val];\n        }\n        else {\n            json.const = val;\n        }\n    }\n    else {\n        if (vals.every((v) => typeof v === \"number\"))\n            json.type = \"number\";\n        if (vals.every((v) => typeof v === \"string\"))\n            json.type = \"string\";\n        if (vals.every((v) => typeof v === \"boolean\"))\n            json.type = \"boolean\";\n        if (vals.every((v) => v === null))\n            json.type = \"null\";\n        json.enum = vals;\n    }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"NaN cannot be represented in JSON Schema\");\n    }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n    const _json = json;\n    const pattern = schema._zod.pattern;\n    if (!pattern)\n        throw new Error(\"Pattern not found in template literal\");\n    _json.type = \"string\";\n    _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n    const _json = json;\n    const file = {\n        type: \"string\",\n        format: \"binary\",\n        contentEncoding: \"binary\",\n    };\n    const { minimum, maximum, mime } = schema._zod.bag;\n    if (minimum !== undefined)\n        file.minLength = minimum;\n    if (maximum !== undefined)\n        file.maxLength = maximum;\n    if (mime) {\n        if (mime.length === 1) {\n            file.contentMediaType = mime[0];\n            Object.assign(_json, file);\n        }\n        else {\n            Object.assign(_json, file); // shared props at root\n            _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n        }\n    }\n    else {\n        Object.assign(_json, file);\n    }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n    json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Custom types cannot be represented in JSON Schema\");\n    }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Function types cannot be represented in JSON Schema\");\n    }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Transforms cannot be represented in JSON Schema\");\n    }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Map cannot be represented in JSON Schema\");\n    }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n    if (ctx.unrepresentable === \"throw\") {\n        throw new Error(\"Set cannot be represented in JSON Schema\");\n    }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const def = schema._zod.def;\n    const { minimum, maximum } = schema._zod.bag;\n    if (typeof minimum === \"number\")\n        json.minItems = minimum;\n    if (typeof maximum === \"number\")\n        json.maxItems = maximum;\n    json.type = \"array\";\n    json.items = process(def.element, ctx, {\n        ...params,\n        path: [...params.path, \"items\"],\n    });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const def = schema._zod.def;\n    json.type = \"object\";\n    json.properties = {};\n    const shape = def.shape;\n    for (const key in shape) {\n        json.properties[key] = process(shape[key], ctx, {\n            ...params,\n            path: [...params.path, \"properties\", key],\n        });\n    }\n    // required keys\n    const allKeys = new Set(Object.keys(shape));\n    const requiredKeys = new Set([...allKeys].filter((key) => {\n        const v = def.shape[key]._zod;\n        if (ctx.io === \"input\") {\n            return v.optin === undefined;\n        }\n        else {\n            return v.optout === undefined;\n        }\n    }));\n    if (requiredKeys.size > 0) {\n        json.required = Array.from(requiredKeys);\n    }\n    // catchall\n    if (def.catchall?._zod.def.type === \"never\") {\n        // strict\n        json.additionalProperties = false;\n    }\n    else if (!def.catchall) {\n        // regular\n        if (ctx.io === \"output\")\n            json.additionalProperties = false;\n    }\n    else if (def.catchall) {\n        json.additionalProperties = process(def.catchall, ctx, {\n            ...params,\n            path: [...params.path, \"additionalProperties\"],\n        });\n    }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n    // This includes both z.xor() and discriminated unions\n    const isExclusive = def.inclusive === false;\n    const options = def.options.map((x, i) => process(x, ctx, {\n        ...params,\n        path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n    }));\n    if (isExclusive) {\n        json.oneOf = options;\n    }\n    else {\n        json.anyOf = options;\n    }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    const a = process(def.left, ctx, {\n        ...params,\n        path: [...params.path, \"allOf\", 0],\n    });\n    const b = process(def.right, ctx, {\n        ...params,\n        path: [...params.path, \"allOf\", 1],\n    });\n    const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n    const allOf = [\n        ...(isSimpleIntersection(a) ? a.allOf : [a]),\n        ...(isSimpleIntersection(b) ? b.allOf : [b]),\n    ];\n    json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const def = schema._zod.def;\n    json.type = \"array\";\n    const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n    const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n    const prefixItems = def.items.map((x, i) => process(x, ctx, {\n        ...params,\n        path: [...params.path, prefixPath, i],\n    }));\n    const rest = def.rest\n        ? process(def.rest, ctx, {\n            ...params,\n            path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n        })\n        : null;\n    if (ctx.target === \"draft-2020-12\") {\n        json.prefixItems = prefixItems;\n        if (rest) {\n            json.items = rest;\n        }\n    }\n    else if (ctx.target === \"openapi-3.0\") {\n        json.items = {\n            anyOf: prefixItems,\n        };\n        if (rest) {\n            json.items.anyOf.push(rest);\n        }\n        json.minItems = prefixItems.length;\n        if (!rest) {\n            json.maxItems = prefixItems.length;\n        }\n    }\n    else {\n        json.items = prefixItems;\n        if (rest) {\n            json.additionalItems = rest;\n        }\n    }\n    // length\n    const { minimum, maximum } = schema._zod.bag;\n    if (typeof minimum === \"number\")\n        json.minItems = minimum;\n    if (typeof maximum === \"number\")\n        json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const def = schema._zod.def;\n    json.type = \"object\";\n    // For looseRecord with regex patterns, use patternProperties\n    // This correctly represents \"only validate keys matching the pattern\" semantics\n    // and composes well with allOf (intersections)\n    const keyType = def.keyType;\n    const keyBag = keyType._zod.bag;\n    const patterns = keyBag?.patterns;\n    if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n        // Use patternProperties for looseRecord with regex patterns\n        const valueSchema = process(def.valueType, ctx, {\n            ...params,\n            path: [...params.path, \"patternProperties\", \"*\"],\n        });\n        json.patternProperties = {};\n        for (const pattern of patterns) {\n            json.patternProperties[pattern.source] = valueSchema;\n        }\n    }\n    else {\n        // Default behavior: use propertyNames + additionalProperties\n        if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n            json.propertyNames = process(def.keyType, ctx, {\n                ...params,\n                path: [...params.path, \"propertyNames\"],\n            });\n        }\n        json.additionalProperties = process(def.valueType, ctx, {\n            ...params,\n            path: [...params.path, \"additionalProperties\"],\n        });\n    }\n    // Add required for keys with discrete values (enum, literal, etc.)\n    const keyValues = keyType._zod.values;\n    if (keyValues) {\n        const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n        if (validKeyValues.length > 0) {\n            json.required = validKeyValues;\n        }\n    }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    const inner = process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    if (ctx.target === \"openapi-3.0\") {\n        seen.ref = def.innerType;\n        json.nullable = true;\n    }\n    else {\n        json.anyOf = [inner, { type: \"null\" }];\n    }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    if (ctx.io === \"input\")\n        json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    let catchValue;\n    try {\n        catchValue = def.catchValue(undefined);\n    }\n    catch {\n        throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n    }\n    json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n    const def = schema._zod.def;\n    const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n    const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n    process(innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n    const innerType = schema._zod.innerType;\n    process(innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n    string: stringProcessor,\n    number: numberProcessor,\n    boolean: booleanProcessor,\n    bigint: bigintProcessor,\n    symbol: symbolProcessor,\n    null: nullProcessor,\n    undefined: undefinedProcessor,\n    void: voidProcessor,\n    never: neverProcessor,\n    any: anyProcessor,\n    unknown: unknownProcessor,\n    date: dateProcessor,\n    enum: enumProcessor,\n    literal: literalProcessor,\n    nan: nanProcessor,\n    template_literal: templateLiteralProcessor,\n    file: fileProcessor,\n    success: successProcessor,\n    custom: customProcessor,\n    function: functionProcessor,\n    transform: transformProcessor,\n    map: mapProcessor,\n    set: setProcessor,\n    array: arrayProcessor,\n    object: objectProcessor,\n    union: unionProcessor,\n    intersection: intersectionProcessor,\n    tuple: tupleProcessor,\n    record: recordProcessor,\n    nullable: nullableProcessor,\n    nonoptional: nonoptionalProcessor,\n    default: defaultProcessor,\n    prefault: prefaultProcessor,\n    catch: catchProcessor,\n    pipe: pipeProcessor,\n    readonly: readonlyProcessor,\n    promise: promiseProcessor,\n    optional: optionalProcessor,\n    lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n    if (\"_idmap\" in input) {\n        // Registry case\n        const registry = input;\n        const ctx = initializeContext({ ...params, processors: allProcessors });\n        const defs = {};\n        // First pass: process all schemas to build the seen map\n        for (const entry of registry._idmap.entries()) {\n            const [_, schema] = entry;\n            process(schema, ctx);\n        }\n        const schemas = {};\n        const external = {\n            registry,\n            uri: params?.uri,\n            defs,\n        };\n        // Update the context with external configuration\n        ctx.external = external;\n        // Second pass: emit each schema\n        for (const entry of registry._idmap.entries()) {\n            const [key, schema] = entry;\n            extractDefs(ctx, schema);\n            schemas[key] = finalize(ctx, schema);\n        }\n        if (Object.keys(defs).length > 0) {\n            const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n            schemas.__shared = {\n                [defsSegment]: defs,\n            };\n        }\n        return { schemas };\n    }\n    // Single schema case\n    const ctx = initializeContext({ ...params, processors: allProcessors });\n    process(input, ctx);\n    extractDefs(ctx, input);\n    return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n    core.$ZodISODateTime.init(inst, def);\n    schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n    return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n    core.$ZodISODate.init(inst, def);\n    schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n    return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n    core.$ZodISOTime.init(inst, def);\n    schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n    return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n    core.$ZodISODuration.init(inst, def);\n    schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n    return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n    $ZodError.init(inst, issues);\n    inst.name = \"ZodError\";\n    Object.defineProperties(inst, {\n        format: {\n            value: (mapper) => core.formatError(inst, mapper),\n            // enumerable: false,\n        },\n        flatten: {\n            value: (mapper) => core.flattenError(inst, mapper),\n            // enumerable: false,\n        },\n        addIssue: {\n            value: (issue) => {\n                inst.issues.push(issue);\n                inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n            },\n            // enumerable: false,\n        },\n        addIssues: {\n            value: (issues) => {\n                inst.issues.push(...issues);\n                inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n            },\n            // enumerable: false,\n        },\n        isEmpty: {\n            get() {\n                return inst.issues.length === 0;\n            },\n            // enumerable: false,\n        },\n    });\n    // Object.defineProperty(inst, \"isEmpty\", {\n    //   get() {\n    //     return inst.issues.length === 0;\n    //   },\n    // });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, {\n    Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\n// Lazy-bind builder methods.\n//\n// Builder methods (`.optional`, `.array`, `.refine`, ...) live as\n// non-enumerable getters on each concrete schema constructor's\n// prototype. On first access from an instance the getter allocates\n// `fn.bind(this)` and caches it as an own property on that instance,\n// so detached usage (`const m = schema.optional; m()`) still works\n// and the per-instance allocation only happens for methods actually\n// touched.\n//\n// One install per (prototype, group), memoized by `_installedGroups`.\nconst _installedGroups = /* @__PURE__ */ new WeakMap();\nfunction _installLazyMethods(inst, group, methods) {\n    const proto = Object.getPrototypeOf(inst);\n    let installed = _installedGroups.get(proto);\n    if (!installed) {\n        installed = new Set();\n        _installedGroups.set(proto, installed);\n    }\n    if (installed.has(group))\n        return;\n    installed.add(group);\n    for (const key in methods) {\n        const fn = methods[key];\n        Object.defineProperty(proto, key, {\n            configurable: true,\n            enumerable: false,\n            get() {\n                const bound = fn.bind(this);\n                Object.defineProperty(this, key, {\n                    configurable: true,\n                    writable: true,\n                    enumerable: true,\n                    value: bound,\n                });\n                return bound;\n            },\n            set(v) {\n                Object.defineProperty(this, key, {\n                    configurable: true,\n                    writable: true,\n                    enumerable: true,\n                    value: v,\n                });\n            },\n        });\n    }\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n    core.$ZodType.init(inst, def);\n    Object.assign(inst[\"~standard\"], {\n        jsonSchema: {\n            input: createStandardJSONSchemaMethod(inst, \"input\"),\n            output: createStandardJSONSchemaMethod(inst, \"output\"),\n        },\n    });\n    inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n    inst.def = def;\n    inst.type = def.type;\n    Object.defineProperty(inst, \"_def\", { value: def });\n    // Parse-family is intentionally kept as per-instance closures: these are\n    // the hot path AND the most-detached methods (`arr.map(schema.parse)`,\n    // `const { parse } = schema`, etc.). Eager closures here mean callers pay\n    // ~12 closure allocations per schema but get monomorphic call sites and\n    // detached usage that \"just works\".\n    inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n    inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n    inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n    inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n    inst.spa = inst.safeParseAsync;\n    inst.encode = (data, params) => parse.encode(inst, data, params);\n    inst.decode = (data, params) => parse.decode(inst, data, params);\n    inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n    inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n    inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n    inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n    inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n    inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n    // All builder methods are placed on the internal prototype as lazy-bind\n    // getters. On first access per-instance, a bound thunk is allocated and\n    // cached as an own property; subsequent accesses skip the getter. This\n    // means: no per-instance allocation for unused methods, full\n    // detachability preserved (`const m = schema.optional; m()` works), and\n    // shared underlying function references across all instances.\n    _installLazyMethods(inst, \"ZodType\", {\n        check(...chks) {\n            const def = this.def;\n            return this.clone(util.mergeDefs(def, {\n                checks: [\n                    ...(def.checks ?? []),\n                    ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n                ],\n            }), { parent: true });\n        },\n        with(...chks) {\n            return this.check(...chks);\n        },\n        clone(def, params) {\n            return core.clone(this, def, params);\n        },\n        brand() {\n            return this;\n        },\n        register(reg, meta) {\n            reg.add(this, meta);\n            return this;\n        },\n        refine(check, params) {\n            return this.check(refine(check, params));\n        },\n        superRefine(refinement, params) {\n            return this.check(superRefine(refinement, params));\n        },\n        overwrite(fn) {\n            return this.check(checks.overwrite(fn));\n        },\n        optional() {\n            return optional(this);\n        },\n        exactOptional() {\n            return exactOptional(this);\n        },\n        nullable() {\n            return nullable(this);\n        },\n        nullish() {\n            return optional(nullable(this));\n        },\n        nonoptional(params) {\n            return nonoptional(this, params);\n        },\n        array() {\n            return array(this);\n        },\n        or(arg) {\n            return union([this, arg]);\n        },\n        and(arg) {\n            return intersection(this, arg);\n        },\n        transform(tx) {\n            return pipe(this, transform(tx));\n        },\n        default(d) {\n            return _default(this, d);\n        },\n        prefault(d) {\n            return prefault(this, d);\n        },\n        catch(params) {\n            return _catch(this, params);\n        },\n        pipe(target) {\n            return pipe(this, target);\n        },\n        readonly() {\n            return readonly(this);\n        },\n        describe(description) {\n            const cl = this.clone();\n            core.globalRegistry.add(cl, { description });\n            return cl;\n        },\n        meta(...args) {\n            // overloaded: meta() returns the registered metadata, meta(data)\n            // returns a clone with `data` registered. The mapped type picks\n            // up the second overload, so we accept variadic any-args and\n            // return `any` to satisfy both at runtime.\n            if (args.length === 0)\n                return core.globalRegistry.get(this);\n            const cl = this.clone();\n            core.globalRegistry.add(cl, args[0]);\n            return cl;\n        },\n        isOptional() {\n            return this.safeParse(undefined).success;\n        },\n        isNullable() {\n            return this.safeParse(null).success;\n        },\n        apply(fn) {\n            return fn(this);\n        },\n    });\n    Object.defineProperty(inst, \"description\", {\n        get() {\n            return core.globalRegistry.get(inst)?.description;\n        },\n        configurable: true,\n    });\n    return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n    core.$ZodString.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n    const bag = inst._zod.bag;\n    inst.format = bag.format ?? null;\n    inst.minLength = bag.minimum ?? null;\n    inst.maxLength = bag.maximum ?? null;\n    _installLazyMethods(inst, \"_ZodString\", {\n        regex(...args) {\n            return this.check(checks.regex(...args));\n        },\n        includes(...args) {\n            return this.check(checks.includes(...args));\n        },\n        startsWith(...args) {\n            return this.check(checks.startsWith(...args));\n        },\n        endsWith(...args) {\n            return this.check(checks.endsWith(...args));\n        },\n        min(...args) {\n            return this.check(checks.minLength(...args));\n        },\n        max(...args) {\n            return this.check(checks.maxLength(...args));\n        },\n        length(...args) {\n            return this.check(checks.length(...args));\n        },\n        nonempty(...args) {\n            return this.check(checks.minLength(1, ...args));\n        },\n        lowercase(params) {\n            return this.check(checks.lowercase(params));\n        },\n        uppercase(params) {\n            return this.check(checks.uppercase(params));\n        },\n        trim() {\n            return this.check(checks.trim());\n        },\n        normalize(...args) {\n            return this.check(checks.normalize(...args));\n        },\n        toLowerCase() {\n            return this.check(checks.toLowerCase());\n        },\n        toUpperCase() {\n            return this.check(checks.toUpperCase());\n        },\n        slugify() {\n            return this.check(checks.slugify());\n        },\n    });\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n    core.$ZodString.init(inst, def);\n    _ZodString.init(inst, def);\n    inst.email = (params) => inst.check(core._email(ZodEmail, params));\n    inst.url = (params) => inst.check(core._url(ZodURL, params));\n    inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n    inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n    inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n    inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n    inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n    inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n    inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n    inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n    inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n    inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n    inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n    inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n    inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n    inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n    inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n    inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n    inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n    inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n    inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n    inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n    inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n    // iso\n    inst.datetime = (params) => inst.check(iso.datetime(params));\n    inst.date = (params) => inst.check(iso.date(params));\n    inst.time = (params) => inst.check(iso.time(params));\n    inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n    return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n    core.$ZodStringFormat.init(inst, def);\n    _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodEmail.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n    return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodGUID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n    return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodUUID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n    return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n    return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n    return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n    return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodURL.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n    return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n    return core._url(ZodURL, {\n        protocol: core.regexes.httpProtocol,\n        hostname: core.regexes.domain,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodEmoji.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n    return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodNanoID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n    return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodCUID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n    return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodCUID2.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n    return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodULID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n    return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodXID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n    return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodKSUID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n    return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodIPv4.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n    return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodMAC.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n    return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodIPv6.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n    return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n    core.$ZodCIDRv4.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n    return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n    core.$ZodCIDRv6.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n    return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodBase64.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n    return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodBase64URL.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n    return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodE164.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n    return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodJWT.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n    return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodCustomStringFormat.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n    return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n    return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n    return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n    const enc = params?.enc ?? \"hex\";\n    const format = `${alg}_${enc}`;\n    const regex = core.regexes[format];\n    if (!regex)\n        throw new Error(`Unrecognized hash format: ${format}`);\n    return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n    core.$ZodNumber.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n    _installLazyMethods(inst, \"ZodNumber\", {\n        gt(value, params) {\n            return this.check(checks.gt(value, params));\n        },\n        gte(value, params) {\n            return this.check(checks.gte(value, params));\n        },\n        min(value, params) {\n            return this.check(checks.gte(value, params));\n        },\n        lt(value, params) {\n            return this.check(checks.lt(value, params));\n        },\n        lte(value, params) {\n            return this.check(checks.lte(value, params));\n        },\n        max(value, params) {\n            return this.check(checks.lte(value, params));\n        },\n        int(params) {\n            return this.check(int(params));\n        },\n        safe(params) {\n            return this.check(int(params));\n        },\n        positive(params) {\n            return this.check(checks.gt(0, params));\n        },\n        nonnegative(params) {\n            return this.check(checks.gte(0, params));\n        },\n        negative(params) {\n            return this.check(checks.lt(0, params));\n        },\n        nonpositive(params) {\n            return this.check(checks.lte(0, params));\n        },\n        multipleOf(value, params) {\n            return this.check(checks.multipleOf(value, params));\n        },\n        step(value, params) {\n            return this.check(checks.multipleOf(value, params));\n        },\n        finite() {\n            return this;\n        },\n    });\n    const bag = inst._zod.bag;\n    inst.minValue =\n        Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n    inst.maxValue =\n        Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n    inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n    inst.isFinite = true;\n    inst.format = bag.format ?? null;\n});\nexport function number(params) {\n    return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n    core.$ZodNumberFormat.init(inst, def);\n    ZodNumber.init(inst, def);\n});\nexport function int(params) {\n    return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n    return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n    return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n    return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n    return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n    core.$ZodBoolean.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n    return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n    core.$ZodBigInt.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n    inst.gte = (value, params) => inst.check(checks.gte(value, params));\n    inst.min = (value, params) => inst.check(checks.gte(value, params));\n    inst.gt = (value, params) => inst.check(checks.gt(value, params));\n    inst.gte = (value, params) => inst.check(checks.gte(value, params));\n    inst.min = (value, params) => inst.check(checks.gte(value, params));\n    inst.lt = (value, params) => inst.check(checks.lt(value, params));\n    inst.lte = (value, params) => inst.check(checks.lte(value, params));\n    inst.max = (value, params) => inst.check(checks.lte(value, params));\n    inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n    inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n    inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n    inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n    inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n    const bag = inst._zod.bag;\n    inst.minValue = bag.minimum ?? null;\n    inst.maxValue = bag.maximum ?? null;\n    inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n    return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n    core.$ZodBigIntFormat.init(inst, def);\n    ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n    return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n    return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n    core.$ZodSymbol.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n    return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n    core.$ZodUndefined.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n    return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n    core.$ZodNull.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n    return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n    core.$ZodAny.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n    return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n    core.$ZodUnknown.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n    return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n    core.$ZodNever.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n    return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n    core.$ZodVoid.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n    return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n    core.$ZodDate.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n    inst.min = (value, params) => inst.check(checks.gte(value, params));\n    inst.max = (value, params) => inst.check(checks.lte(value, params));\n    const c = inst._zod.bag;\n    inst.minDate = c.minimum ? new Date(c.minimum) : null;\n    inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n    return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n    core.$ZodArray.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n    inst.element = def.element;\n    _installLazyMethods(inst, \"ZodArray\", {\n        min(n, params) {\n            return this.check(checks.minLength(n, params));\n        },\n        nonempty(params) {\n            return this.check(checks.minLength(1, params));\n        },\n        max(n, params) {\n            return this.check(checks.maxLength(n, params));\n        },\n        length(n, params) {\n            return this.check(checks.length(n, params));\n        },\n        unwrap() {\n            return this.element;\n        },\n    });\n});\nexport function array(element, params) {\n    return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n    const shape = schema._zod.def.shape;\n    return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n    core.$ZodObjectJIT.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n    util.defineLazy(inst, \"shape\", () => {\n        return def.shape;\n    });\n    _installLazyMethods(inst, \"ZodObject\", {\n        keyof() {\n            return _enum(Object.keys(this._zod.def.shape));\n        },\n        catchall(catchall) {\n            return this.clone({ ...this._zod.def, catchall: catchall });\n        },\n        passthrough() {\n            return this.clone({ ...this._zod.def, catchall: unknown() });\n        },\n        loose() {\n            return this.clone({ ...this._zod.def, catchall: unknown() });\n        },\n        strict() {\n            return this.clone({ ...this._zod.def, catchall: never() });\n        },\n        strip() {\n            return this.clone({ ...this._zod.def, catchall: undefined });\n        },\n        extend(incoming) {\n            return util.extend(this, incoming);\n        },\n        safeExtend(incoming) {\n            return util.safeExtend(this, incoming);\n        },\n        merge(other) {\n            return util.merge(this, other);\n        },\n        pick(mask) {\n            return util.pick(this, mask);\n        },\n        omit(mask) {\n            return util.omit(this, mask);\n        },\n        partial(...args) {\n            return util.partial(ZodOptional, this, args[0]);\n        },\n        required(...args) {\n            return util.required(ZodNonOptional, this, args[0]);\n        },\n    });\n});\nexport function object(shape, params) {\n    const def = {\n        type: \"object\",\n        shape: shape ?? {},\n        ...util.normalizeParams(params),\n    };\n    return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n    return new ZodObject({\n        type: \"object\",\n        shape,\n        catchall: never(),\n        ...util.normalizeParams(params),\n    });\n}\n// looseObject\nexport function looseObject(shape, params) {\n    return new ZodObject({\n        type: \"object\",\n        shape,\n        catchall: unknown(),\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n    core.$ZodUnion.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n    inst.options = def.options;\n});\nexport function union(options, params) {\n    return new ZodUnion({\n        type: \"union\",\n        options: options,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n    ZodUnion.init(inst, def);\n    core.$ZodXor.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n    inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n    return new ZodXor({\n        type: \"union\",\n        options: options,\n        inclusive: false,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n    ZodUnion.init(inst, def);\n    core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n    // const [options, params] = args;\n    return new ZodDiscriminatedUnion({\n        type: \"union\",\n        options,\n        discriminator,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n    core.$ZodIntersection.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n    return new ZodIntersection({\n        type: \"intersection\",\n        left: left,\n        right: right,\n    });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n    core.$ZodTuple.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n    inst.rest = (rest) => inst.clone({\n        ...inst._zod.def,\n        rest: rest,\n    });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n    const hasRest = _paramsOrRest instanceof core.$ZodType;\n    const params = hasRest ? _params : _paramsOrRest;\n    const rest = hasRest ? _paramsOrRest : null;\n    return new ZodTuple({\n        type: \"tuple\",\n        items: items,\n        rest,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n    core.$ZodRecord.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n    inst.keyType = def.keyType;\n    inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n    // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n    if (!valueType || !valueType._zod) {\n        return new ZodRecord({\n            type: \"record\",\n            keyType: string(),\n            valueType: keyType,\n            ...util.normalizeParams(valueType),\n        });\n    }\n    return new ZodRecord({\n        type: \"record\",\n        keyType,\n        valueType: valueType,\n        ...util.normalizeParams(params),\n    });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n    const k = core.clone(keyType);\n    k._zod.values = undefined;\n    return new ZodRecord({\n        type: \"record\",\n        keyType: k,\n        valueType: valueType,\n        ...util.normalizeParams(params),\n    });\n}\nexport function looseRecord(keyType, valueType, params) {\n    return new ZodRecord({\n        type: \"record\",\n        keyType,\n        valueType: valueType,\n        mode: \"loose\",\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n    core.$ZodMap.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n    inst.keyType = def.keyType;\n    inst.valueType = def.valueType;\n    inst.min = (...args) => inst.check(core._minSize(...args));\n    inst.nonempty = (params) => inst.check(core._minSize(1, params));\n    inst.max = (...args) => inst.check(core._maxSize(...args));\n    inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n    return new ZodMap({\n        type: \"map\",\n        keyType: keyType,\n        valueType: valueType,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n    core.$ZodSet.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n    inst.min = (...args) => inst.check(core._minSize(...args));\n    inst.nonempty = (params) => inst.check(core._minSize(1, params));\n    inst.max = (...args) => inst.check(core._maxSize(...args));\n    inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n    return new ZodSet({\n        type: \"set\",\n        valueType: valueType,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n    core.$ZodEnum.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n    inst.enum = def.entries;\n    inst.options = Object.values(def.entries);\n    const keys = new Set(Object.keys(def.entries));\n    inst.extract = (values, params) => {\n        const newEntries = {};\n        for (const value of values) {\n            if (keys.has(value)) {\n                newEntries[value] = def.entries[value];\n            }\n            else\n                throw new Error(`Key ${value} not found in enum`);\n        }\n        return new ZodEnum({\n            ...def,\n            checks: [],\n            ...util.normalizeParams(params),\n            entries: newEntries,\n        });\n    };\n    inst.exclude = (values, params) => {\n        const newEntries = { ...def.entries };\n        for (const value of values) {\n            if (keys.has(value)) {\n                delete newEntries[value];\n            }\n            else\n                throw new Error(`Key ${value} not found in enum`);\n        }\n        return new ZodEnum({\n            ...def,\n            checks: [],\n            ...util.normalizeParams(params),\n            entries: newEntries,\n        });\n    };\n});\nfunction _enum(values, params) {\n    const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n    return new ZodEnum({\n        type: \"enum\",\n        entries,\n        ...util.normalizeParams(params),\n    });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n    return new ZodEnum({\n        type: \"enum\",\n        entries,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n    core.$ZodLiteral.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n    inst.values = new Set(def.values);\n    Object.defineProperty(inst, \"value\", {\n        get() {\n            if (def.values.length > 1) {\n                throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n            }\n            return def.values[0];\n        },\n    });\n});\nexport function literal(value, params) {\n    return new ZodLiteral({\n        type: \"literal\",\n        values: Array.isArray(value) ? value : [value],\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n    core.$ZodFile.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n    inst.min = (size, params) => inst.check(core._minSize(size, params));\n    inst.max = (size, params) => inst.check(core._maxSize(size, params));\n    inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n    return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n    core.$ZodTransform.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n    inst._zod.parse = (payload, _ctx) => {\n        if (_ctx.direction === \"backward\") {\n            throw new core.$ZodEncodeError(inst.constructor.name);\n        }\n        payload.addIssue = (issue) => {\n            if (typeof issue === \"string\") {\n                payload.issues.push(util.issue(issue, payload.value, def));\n            }\n            else {\n                // for Zod 3 backwards compatibility\n                const _issue = issue;\n                if (_issue.fatal)\n                    _issue.continue = false;\n                _issue.code ?? (_issue.code = \"custom\");\n                _issue.input ?? (_issue.input = payload.value);\n                _issue.inst ?? (_issue.inst = inst);\n                // _issue.continue ??= true;\n                payload.issues.push(util.issue(_issue));\n            }\n        };\n        const output = def.transform(payload.value, payload);\n        if (output instanceof Promise) {\n            return output.then((output) => {\n                payload.value = output;\n                payload.fallback = true;\n                return payload;\n            });\n        }\n        payload.value = output;\n        payload.fallback = true;\n        return payload;\n    };\n});\nexport function transform(fn) {\n    return new ZodTransform({\n        type: \"transform\",\n        transform: fn,\n    });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n    core.$ZodOptional.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n    return new ZodOptional({\n        type: \"optional\",\n        innerType: innerType,\n    });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n    core.$ZodExactOptional.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n    return new ZodExactOptional({\n        type: \"optional\",\n        innerType: innerType,\n    });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n    core.$ZodNullable.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n    return new ZodNullable({\n        type: \"nullable\",\n        innerType: innerType,\n    });\n}\n// nullish\nexport function nullish(innerType) {\n    return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n    core.$ZodDefault.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n    inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n    return new ZodDefault({\n        type: \"default\",\n        innerType: innerType,\n        get defaultValue() {\n            return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n        },\n    });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n    core.$ZodPrefault.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n    return new ZodPrefault({\n        type: \"prefault\",\n        innerType: innerType,\n        get defaultValue() {\n            return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n        },\n    });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n    core.$ZodNonOptional.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n    return new ZodNonOptional({\n        type: \"nonoptional\",\n        innerType: innerType,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n    core.$ZodSuccess.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n    return new ZodSuccess({\n        type: \"success\",\n        innerType: innerType,\n    });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n    core.$ZodCatch.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n    inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n    return new ZodCatch({\n        type: \"catch\",\n        innerType: innerType,\n        catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n    });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n    core.$ZodNaN.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n    return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n    core.$ZodPipe.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n    inst.in = def.in;\n    inst.out = def.out;\n});\nexport function pipe(in_, out) {\n    return new ZodPipe({\n        type: \"pipe\",\n        in: in_,\n        out: out,\n        // ...util.normalizeParams(params),\n    });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n    ZodPipe.init(inst, def);\n    core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n    return new ZodCodec({\n        type: \"pipe\",\n        in: in_,\n        out: out,\n        transform: params.decode,\n        reverseTransform: params.encode,\n    });\n}\nexport function invertCodec(codec) {\n    const def = codec._zod.def;\n    return new ZodCodec({\n        type: \"pipe\",\n        in: def.out,\n        out: def.in,\n        transform: def.reverseTransform,\n        reverseTransform: def.transform,\n    });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n    ZodPipe.init(inst, def);\n    core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n    core.$ZodReadonly.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n    return new ZodReadonly({\n        type: \"readonly\",\n        innerType: innerType,\n    });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n    core.$ZodTemplateLiteral.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n    return new ZodTemplateLiteral({\n        type: \"template_literal\",\n        parts,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n    core.$ZodLazy.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n    return new ZodLazy({\n        type: \"lazy\",\n        getter: getter,\n    });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n    core.$ZodPromise.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n    return new ZodPromise({\n        type: \"promise\",\n        innerType: innerType,\n    });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n    core.$ZodFunction.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n    return new ZodFunction({\n        type: \"function\",\n        input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n        output: params?.output ?? unknown(),\n    });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n    core.$ZodCustom.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n    const ch = new core.$ZodCheck({\n        check: \"custom\",\n        // ...util.normalizeParams(params),\n    });\n    ch._zod.check = fn;\n    return ch;\n}\nexport function custom(fn, _params) {\n    return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n    return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n    return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n    const inst = new ZodCustom({\n        type: \"custom\",\n        check: \"custom\",\n        fn: (data) => data instanceof cls,\n        abort: true,\n        ...util.normalizeParams(params),\n    });\n    inst._zod.bag.Class = cls;\n    // Override check to emit invalid_type instead of custom\n    inst._zod.check = (payload) => {\n        if (!(payload.value instanceof cls)) {\n            payload.issues.push({\n                code: \"invalid_type\",\n                expected: cls.name,\n                input: payload.value,\n                inst,\n                path: [...(inst._zod.def.path ?? [])],\n            });\n        }\n    };\n    return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n    Codec: ZodCodec,\n    Boolean: ZodBoolean,\n    String: ZodString,\n}, ...args);\nexport function json(params) {\n    const jsonSchema = lazy(() => {\n        return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n    });\n    return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n    return new ZodPreprocess({\n        type: \"pipe\",\n        in: transform(fn),\n        out: schema,\n    });\n}\n","/**\n * The type of error that occurred.\n * @public\n */\nexport type ErrorType = 'invalid-retry' | 'unknown-field' | 'max-buffer-size-exceeded'\n\n/**\n * Error thrown when encountering an issue during parsing.\n *\n * @public\n */\nexport class ParseError extends Error {\n  /**\n   * The type of error that occurred.\n   */\n  type: ErrorType\n\n  /**\n   * In the case of an unknown field encountered in the stream, this will be the field name.\n   */\n  field?: string | undefined\n\n  /**\n   * In the case of an unknown field encountered in the stream, this will be the value of the field.\n   */\n  value?: string | undefined\n\n  /**\n   * The line that caused the error, if available.\n   */\n  line?: string | undefined\n\n  constructor(\n    message: string,\n    options: {type: ErrorType; field?: string; value?: string; line?: string},\n  ) {\n    super(message)\n    this.name = 'ParseError'\n    this.type = options.type\n    this.field = options.field\n    this.value = options.value\n    this.line = options.line\n  }\n}\n","/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nimport {ParseError} from './errors.ts'\nimport type {EventSourceParser, ParserConfig} from './types.ts'\n\n// ASCII codes used in the hot parsing paths.\nconst LF = 10\nconst CR = 13\nconst SPACE = 32\n\n// oxlint-disable-next-line no-unused-vars\nfunction noop(_arg: unknown) {\n  // intentional noop\n}\n\n/**\n * Creates a new EventSource parser.\n *\n * @param config - Parser configuration. Accepts callbacks (see {@link ParserCallbacks})\n *   and options like `maxBufferSize` (see {@link ParserConfig}).\n *\n * @returns A new EventSource parser, with `feed` and `reset` methods.\n * @public\n */\nexport function createParser(config: ParserConfig): EventSourceParser {\n  if (typeof config === 'function') {\n    throw new TypeError(\n      '`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?',\n    )\n  }\n\n  const {onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize} = config\n\n  // Trailing bytes from prior `feed()` calls that did not yet form a complete line.\n  // Stored as an array of fragments and only joined when a line terminator arrives.\n  // Concatenating per-feed (`prefix + chunk`) is O(N²) when a single SSE line spans\n  // many chunks (e.g. a large `data:` payload streamed in tiny slices, or an MCP-style\n  // server that emits one giant content block). Buffering as fragments + joining once\n  // makes the same workload linear.\n  const pendingFragments: string[] = []\n\n  // Running total of `pendingFragments` lengths, kept in sync with the array so the\n  // `maxBufferSize` check doesn't have to walk the fragment list on every feed.\n  let pendingFragmentsLength = 0\n\n  let isFirstChunk = true\n  let id: string | undefined\n  let data = ''\n  let dataLines = 0\n  let eventType: string | undefined\n\n  // Set after a `maxBufferSize` overflow. Once tripped, `feed()` throws until\n  // `reset()` is called — see the comment on `maxBufferSize` in `ParserConfig`.\n  let terminated = false\n\n  /**\n   * Feeds a chunk of the SSE stream to the parser. Any trailing bytes that do\n   * not yet form a complete line are held back and prepended to the next chunk,\n   * so callers can pass arbitrary slices of the stream without worrying about\n   * line boundaries.\n   *\n   * Per the SSE spec, a UTF-8 BOM (0xEF 0xBB 0xBF) at the start of the very\n   * first chunk is stripped before parsing.\n   *\n   * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream\n   */\n  function feed(chunk: string) {\n    if (terminated) {\n      throw new Error(\n        'Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.',\n      )\n    }\n\n    if (isFirstChunk) {\n      isFirstChunk = false\n      // Match and strip UTF-8 BOM from the start of the stream, if present.\n      // (Per the spec, this is only valid at the very start of the stream)\n      if (\n        chunk.charCodeAt(0) === 0xef &&\n        chunk.charCodeAt(1) === 0xbb &&\n        chunk.charCodeAt(2) === 0xbf\n      ) {\n        chunk = chunk.slice(3)\n      }\n    }\n\n    // Hot path: no buffered prefix from a prior partial line. Hand the chunk\n    // straight to `processLines`, exactly like the original implementation.\n    // Zero new work in the common case (every chunk ends with `\\n\\n`).\n    if (pendingFragments.length === 0) {\n      const trailing = processLines(chunk)\n      if (trailing !== '') {\n        pendingFragments.push(trailing)\n        pendingFragmentsLength = trailing.length\n      }\n      checkBufferSize()\n      return\n    }\n\n    // We have a buffered prefix. If this chunk also has no terminator, append\n    // to the buffer without concatenating — that's the O(N²) trap we're\n    // avoiding (large single `data:` payload split across many tiny chunks).\n    if (chunk.indexOf('\\n') === -1 && chunk.indexOf('\\r') === -1) {\n      pendingFragments.push(chunk)\n      pendingFragmentsLength += chunk.length\n      checkBufferSize()\n      return\n    }\n\n    // Terminator arrived. Join the accumulated fragments + this chunk once,\n    // process, and buffer any new trailing partial line.\n    pendingFragments.push(chunk)\n    const input = pendingFragments.join('')\n    pendingFragments.length = 0\n    pendingFragmentsLength = 0\n    const trailing = processLines(input)\n    if (trailing !== '') {\n      pendingFragments.push(trailing)\n      pendingFragmentsLength = trailing.length\n    }\n    checkBufferSize()\n  }\n\n  function checkBufferSize() {\n    if (maxBufferSize === undefined) return\n    if (pendingFragmentsLength + data.length <= maxBufferSize) return\n\n    terminated = true\n    pendingFragments.length = 0\n    pendingFragmentsLength = 0\n    id = undefined\n    data = ''\n    dataLines = 0\n    eventType = undefined\n    onError(\n      new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {\n        type: 'max-buffer-size-exceeded',\n      }),\n    )\n  }\n\n  /**\n   * Splits `chunk` into SSE lines and dispatches each to the appropriate handler.\n   * Returns any trailing bytes that did not terminate with a line break, so the\n   * caller can prepend them to the next chunk.\n   *\n   * The SSE spec permits three line terminators: `\\n`, `\\r`, and `\\r\\n`. Real-world\n   * streams almost always use plain `\\n`, so we take a fast path when no `\\r` is\n   * present in the chunk. The slow path is spec-correct but does more work per line.\n   */\n  function processLines(chunk: string): string {\n    let searchIndex = 0\n\n    // Fast path: LF-only chunk (the common case for typical SSE servers).\n    // We can scan forward with a single `indexOf('\\n')` per line and inline\n    // the hot-path branches for `data:` and `event:` without the CR bookkeeping\n    // the slow path needs.\n    if (chunk.indexOf('\\r') === -1) {\n      let lfIndex = chunk.indexOf('\\n', searchIndex)\n      while (lfIndex !== -1) {\n        // Blank line: end-of-event marker. Dispatch the accumulated event (if any)\n        // and reset the buffered fields. This is hoisted out of `parseLine` because\n        // it's the single most common line shape after `data:` lines.\n        if (searchIndex === lfIndex) {\n          if (dataLines > 0) {\n            onEvent({id, event: eventType, data})\n          }\n          id = undefined\n          data = ''\n          dataLines = 0\n          eventType = undefined\n          searchIndex = lfIndex + 1\n          lfIndex = chunk.indexOf('\\n', searchIndex)\n          continue\n        }\n        const firstCharCode = chunk.charCodeAt(searchIndex)\n        if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n          // `data:` line — append the value to the event's data buffer.\n          // 'data:'.length === 5, 'data: '.length === 6\n          const valueStart =\n            chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5\n          const value = chunk.slice(valueStart, lfIndex)\n          // Fast path within a fast path: if this is the first data line AND the\n          // next char is another LF (i.e. `data:foo\\n\\n`), dispatch immediately\n          // without ever writing to the `data` buffer. This is the shape of a\n          // typical single-line SSE event (ChatGPT-style streams, etc.) and is\n          // hot enough to be worth the duplication.\n          if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n            onEvent({id, event: eventType, data: value})\n            id = undefined\n            data = ''\n            eventType = undefined\n            searchIndex = lfIndex + 2\n            lfIndex = chunk.indexOf('\\n', searchIndex)\n            continue\n          }\n          // Multi-line data: concatenate with newline separator per spec.\n          data = dataLines === 0 ? value : `${data}\\n${value}`\n          dataLines++\n        } else if (isEventPrefix(chunk, searchIndex, firstCharCode)) {\n          // `event:` line — set the event type for the next dispatch. Per spec,\n          // an empty value resets `event type` to its default (undefined here).\n          // 'event:'.length === 6, 'event: '.length === 7\n          eventType =\n            chunk.slice(\n              chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,\n              lfIndex,\n            ) || undefined\n        } else {\n          // Everything else: `id:`, `retry:`, comment lines (`:` prefix), unknown\n          // fields, or malformed lines. These are rarer and go through the full\n          // per-line parser, which handles the SSE field grammar in detail.\n          parseLine(chunk, searchIndex, lfIndex)\n        }\n        searchIndex = lfIndex + 1\n        lfIndex = chunk.indexOf('\\n', searchIndex)\n      }\n      return chunk.slice(searchIndex)\n    }\n\n    // Slow path: the chunk contains at least one `\\r`, so lines may be terminated\n    // by `\\r`, `\\n`, or `\\r\\n`. We locate the next terminator by looking at both\n    // the nearest `\\r` and `\\n` and picking whichever comes first.\n    while (searchIndex < chunk.length) {\n      const crIndex = chunk.indexOf('\\r', searchIndex)\n      const lfIndex = chunk.indexOf('\\n', searchIndex)\n\n      let lineEnd = -1\n      if (crIndex !== -1 && lfIndex !== -1) {\n        lineEnd = crIndex < lfIndex ? crIndex : lfIndex\n      } else if (crIndex !== -1) {\n        // A trailing `\\r` at the very end of the chunk is ambiguous: it could be\n        // a bare-CR terminator, or the first half of a `\\r\\n` whose `\\n` arrives\n        // in the next chunk. Defer until we see more input.\n        if (crIndex === chunk.length - 1) {\n          lineEnd = -1\n        } else {\n          lineEnd = crIndex\n        }\n      } else if (lfIndex !== -1) {\n        lineEnd = lfIndex\n      }\n\n      if (lineEnd === -1) {\n        break\n      }\n\n      parseLine(chunk, searchIndex, lineEnd)\n      searchIndex = lineEnd + 1\n      // If we just consumed a `\\r` and the next char is `\\n`, skip it so the\n      // pair is treated as a single terminator rather than an empty line.\n      if (chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF) {\n        searchIndex++\n      }\n    }\n\n    return chunk.slice(searchIndex)\n  }\n\n  function parseLine(chunk: string, start: number, end: number) {\n    if (start === end) {\n      dispatchEvent()\n      return\n    }\n\n    const firstCharCode = chunk.charCodeAt(start)\n\n    if (isDataPrefix(chunk, start, firstCharCode)) {\n      // 'data:'.length === 5, 'data: '.length === 6\n      const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5\n      const value = chunk.slice(valueStart, end)\n      data = dataLines === 0 ? value : `${data}\\n${value}`\n      dataLines++\n      return\n    }\n\n    if (isEventPrefix(chunk, start, firstCharCode)) {\n      // 'event:'.length === 6, 'event: '.length === 7\n      eventType =\n        chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined\n      return\n    }\n\n    // Fast path for \"id:\" — 'i' = 105, 'd' = 100, ':' = 58\n    if (\n      firstCharCode === 105 &&\n      chunk.charCodeAt(start + 1) === 100 &&\n      chunk.charCodeAt(start + 2) === 58\n    ) {\n      // 'id:'.length === 3, 'id: '.length === 4\n      const value = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end)\n      // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n      // the field value. Otherwise, ignore the field.\n      if (!value.includes('\\0')) id = value\n      return\n    }\n\n    // Comment line — ':' = 58\n    if (firstCharCode === 58) {\n      if (onComment) {\n        const line = chunk.slice(start, end)\n        // skip ':' (+1), or ': ' (+2) when a space follows\n        onComment(line.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1))\n      }\n      return\n    }\n\n    const line = chunk.slice(start, end)\n    const fieldSeparatorIndex = line.indexOf(':')\n    if (fieldSeparatorIndex === -1) {\n      processField(line, '', line)\n      return\n    }\n\n    const field = line.slice(0, fieldSeparatorIndex)\n    // skip ':' (+1), or ': ' (+2) when a space follows\n    const offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1\n    const value = line.slice(fieldSeparatorIndex + offset)\n    processField(field, value, line)\n  }\n\n  function processField(field: string, value: string, line: string) {\n    // Field names must be compared literally, with no case folding performed.\n    switch (field) {\n      case 'event':\n        // Set the `event type` buffer to field value\n        eventType = value || undefined\n        break\n      case 'data':\n        data = dataLines === 0 ? value : `${data}\\n${value}`\n        dataLines++\n        break\n      case 'id':\n        // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n        // the field value. Otherwise, ignore the field.\n        if (!value.includes('\\0')) id = value\n        break\n      case 'retry':\n        // If the field value consists of only ASCII digits, then interpret the field value as an\n        // integer in base ten, and set the event stream's reconnection time to that integer.\n        // Otherwise, ignore the field.\n        if (/^\\d+$/.test(value)) {\n          onRetry(parseInt(value, 10))\n        } else {\n          onError(\n            new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n              type: 'invalid-retry',\n              value,\n              line,\n            }),\n          )\n        }\n        break\n      default:\n        // Otherwise, the field is ignored.\n        onError(\n          new ParseError(\n            `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}…` : field}\"`,\n            {type: 'unknown-field', field, value, line},\n          ),\n        )\n        break\n    }\n  }\n\n  function dispatchEvent() {\n    if (dataLines > 0) {\n      onEvent({\n        id,\n        event: eventType,\n        data,\n      })\n    }\n\n    id = undefined\n    data = ''\n    dataLines = 0\n    eventType = undefined\n  }\n\n  function reset(options: {consume?: boolean} = {}) {\n    if (options.consume && pendingFragments.length > 0) {\n      const incompleteLine = pendingFragments.join('')\n      parseLine(incompleteLine, 0, incompleteLine.length)\n    }\n\n    isFirstChunk = true\n    id = undefined\n    data = ''\n    dataLines = 0\n    eventType = undefined\n    pendingFragments.length = 0\n    pendingFragmentsLength = 0\n    terminated = false\n  }\n\n  return {feed, reset}\n}\n\n/**\n * Checks if `chunk` starts with the literal `data:` at index `i`.\n *\n * Equivalent to `chunk.startsWith('data:', i)`, but benchmarks show this\n * hand-unrolled char-code comparison is ~20% faster on common event types.\n * The caller passes `firstCharCode` (the code at `i`) so it can be reused\n * across prefix checks.\n *\n * ASCII: 'd' = 100, 'a' = 97, 't' = 116, 'a' = 97, ':' = 58\n */\nfunction isDataPrefix(chunk: string, i: number, firstCharCode: number): boolean {\n  return (\n    firstCharCode === 100 &&\n    chunk.charCodeAt(i + 1) === 97 &&\n    chunk.charCodeAt(i + 2) === 116 &&\n    chunk.charCodeAt(i + 3) === 97 &&\n    chunk.charCodeAt(i + 4) === 58\n  )\n}\n\n/**\n * Checks if `chunk` starts with the literal `event:` at index `i`.\n *\n * See {@link isDataPrefix} for why this is hand-unrolled rather than using\n * `String.prototype.startsWith`.\n *\n * ASCII: 'e' = 101, 'v' = 118, 'e' = 101, 'n' = 110, 't' = 116, ':' = 58\n */\nfunction isEventPrefix(chunk: string, i: number, firstCharCode: number): boolean {\n  return (\n    firstCharCode === 101 &&\n    chunk.charCodeAt(i + 1) === 118 &&\n    chunk.charCodeAt(i + 2) === 101 &&\n    chunk.charCodeAt(i + 3) === 110 &&\n    chunk.charCodeAt(i + 4) === 116 &&\n    chunk.charCodeAt(i + 5) === 58\n  )\n}\n","import {createParser} from './parse.ts'\nimport type {EventSourceMessage, EventSourceParser} from './types.ts'\n\n/**\n * Options for the EventSourceParserStream.\n *\n * @public\n */\nexport interface StreamOptions {\n  /**\n   * Behavior when a parsing error occurs.\n   *\n   * - A custom function can be provided to handle the error.\n   * - `'terminate'` will error the stream and stop parsing.\n   * - Any other value will ignore the error and continue parsing.\n   *\n   * @defaultValue `undefined`\n   */\n  onError?: ('terminate' | ((error: Error) => void)) | undefined\n\n  /**\n   * Callback for when a reconnection interval is sent from the server.\n   *\n   * @param retry - The number of milliseconds to wait before reconnecting.\n   */\n  onRetry?: ((retry: number) => void) | undefined\n\n  /**\n   * Callback for when a comment is encountered in the stream.\n   *\n   * @param comment - The comment encountered in the stream.\n   */\n  onComment?: ((comment: string) => void) | undefined\n\n  /**\n   * Maximum number of characters the parser is allowed to buffer across calls to `feed()`.\n   * See {@link ParserConfig.maxBufferSize} for details.\n   *\n   * When the limit is exceeded, the stream is always errored (regardless of the `onError`\n   * setting) since the underlying parser is unrecoverable without a `reset()`.\n   *\n   * @defaultValue `undefined` (unbounded)\n   */\n  maxBufferSize?: number | undefined\n}\n\n/**\n * A TransformStream that ingests a stream of strings and produces a stream of `EventSourceMessage`.\n *\n * @example Basic usage\n * ```\n * const eventStream =\n *   response.body\n *     .pipeThrough(new TextDecoderStream())\n *     .pipeThrough(new EventSourceParserStream())\n * ```\n *\n * @example Terminate stream on parsing errors\n * ```\n * const eventStream =\n *  response.body\n *   .pipeThrough(new TextDecoderStream())\n *   .pipeThrough(new EventSourceParserStream({onError: 'terminate'}))\n * ```\n *\n * @public\n */\nexport class EventSourceParserStream extends TransformStream<string, EventSourceMessage> {\n  constructor({onError, onRetry, onComment, maxBufferSize}: StreamOptions = {}) {\n    let parser!: EventSourceParser\n\n    super({\n      start(controller) {\n        parser = createParser({\n          onEvent: (event) => {\n            controller.enqueue(event)\n          },\n          onError(error) {\n            if (typeof onError === 'function') {\n              onError(error)\n            }\n\n            // `max-buffer-size-exceeded` is fatal — the parser is unusable until\n            // `reset()`, which the stream wrapper has no way to call. Always\n            // terminate the stream in that case so consumers see the meaningful\n            // `ParseError` instead of an opaque \"cannot feed terminated parser\"\n            // throw from the next chunk.\n            if (onError === 'terminate' || error.type === 'max-buffer-size-exceeded') {\n              controller.error(error)\n            }\n\n            // Ignore by default\n          },\n          onRetry,\n          onComment,\n          maxBufferSize,\n        })\n      },\n      transform(chunk) {\n        parser.feed(chunk)\n      },\n    })\n  }\n}\n\nexport {type ErrorType, ParseError} from './errors.ts'\nexport type {EventSourceMessage} from './types.ts'\n","/**\n * A value that can be provided either as a single item, an array of items,\n * or be left undefined.\n */\nexport type Arrayable<T> = T | T[] | undefined;\n\n/**\n * Normalizes a possibly undefined or non-array value into an array.\n */\nexport function asArray<T>(value: Arrayable<T>): T[] {\n  return value === undefined ? [] : Array.isArray(value) ? value : [value];\n}\n","export function combineHeaders(\n  ...headers: Array<Record<string, string | undefined> | undefined>\n): Record<string, string | undefined> {\n  return headers.reduce(\n    (combinedHeaders, currentHeaders) => ({\n      ...combinedHeaders,\n      ...(currentHeaders ?? {}),\n    }),\n    {},\n  ) as Record<string, string | undefined>;\n}\n","/**\n * Removes entries from a record where the value is null or undefined.\n * @param record - The input object whose entries may be null or undefined.\n * @returns A new object containing only entries with non-null and non-undefined values.\n */\nexport function removeUndefinedEntries<T>(\n  record: Record<string, T | undefined>,\n): Record<string, T> {\n  return Object.fromEntries(\n    Object.entries(record).filter(([_key, value]) => value != null),\n  ) as Record<string, T>;\n}\n","/**\n * Creates a Promise that resolves after a specified delay\n * @param delayInMs - The delay duration in milliseconds. If null or undefined, resolves immediately.\n * @param signal - Optional AbortSignal to cancel the delay\n * @returns A Promise that resolves after the specified delay\n * @throws {DOMException} When the signal is aborted\n */\nexport async function delay(\n  delayInMs?: number | null,\n  options?: {\n    abortSignal?: AbortSignal;\n  },\n): Promise<void> {\n  if (delayInMs == null) {\n    return Promise.resolve();\n  }\n\n  const signal = options?.abortSignal;\n\n  return new Promise<void>((resolve, reject) => {\n    if (signal?.aborted) {\n      reject(createAbortError());\n      return;\n    }\n\n    const timeoutId = setTimeout(() => {\n      cleanup();\n      resolve();\n    }, delayInMs);\n\n    const cleanup = () => {\n      clearTimeout(timeoutId);\n      signal?.removeEventListener('abort', onAbort);\n    };\n\n    const onAbort = () => {\n      cleanup();\n      reject(createAbortError());\n    };\n\n    signal?.addEventListener('abort', onAbort);\n  });\n}\n\nfunction createAbortError(): DOMException {\n  return new DOMException('Delay was aborted', 'AbortError');\n}\n","import { delay } from './delay';\n\nexport type WebSocketLike = {\n  readyState: number;\n  /** Bytes queued by `send` but not yet transmitted (native + `ws`). */\n  readonly bufferedAmount?: number;\n  send(data: string | Uint8Array | ArrayBuffer): void;\n  close(code?: number, reason?: string): void;\n  onopen: ((event: unknown) => void) | null;\n  onmessage: ((event: { data: unknown }) => void) | null;\n  onerror: ((event: unknown) => void) | null;\n  onclose: ((event: unknown) => void) | null;\n};\n\nexport type WebSocketConstructor = new (\n  url: string | URL,\n  protocols?: string | string[],\n  options?: {\n    headers?: Record<string, string | undefined>;\n  },\n) => WebSocketLike;\n\nexport function getWebSocketConstructor(\n  webSocket: WebSocketConstructor | undefined,\n): WebSocketConstructor {\n  const WebSocketConstructor =\n    webSocket ?? (globalThis.WebSocket as unknown as WebSocketConstructor);\n\n  if (WebSocketConstructor == null) {\n    throw new Error('No WebSocket implementation available.');\n  }\n\n  return WebSocketConstructor;\n}\n\n/**\n * Converts an http(s) URL to the corresponding ws(s) URL.\n */\nexport function toWebSocketUrl(url: string | URL): URL {\n  const wsUrl = new URL(url);\n  if (wsUrl.protocol === 'http:') {\n    wsUrl.protocol = 'ws:';\n  } else if (wsUrl.protocol === 'https:') {\n    wsUrl.protocol = 'wss:';\n  }\n  return wsUrl;\n}\n\nconst textDecoder = new TextDecoder();\n\n/**\n * Reads WebSocket message data as text, handling string, binary,\n * and Blob payloads.\n */\nexport async function readWebSocketMessageText(data: unknown): Promise<string> {\n  if (typeof data === 'string') return data;\n  if (data instanceof ArrayBuffer) return textDecoder.decode(data);\n  if (ArrayBuffer.isView(data)) {\n    return textDecoder.decode(data);\n  }\n  if (typeof Blob !== 'undefined' && data instanceof Blob) {\n    return data.text();\n  }\n  return String(data);\n}\n\nconst WEBSOCKET_OPEN_STATE = 1;\n\n/**\n * Waits until the socket's send buffer drains below `highWaterMark` bytes.\n * No-op for implementations that do not expose `bufferedAmount`. There is no\n * portable drain event, so this polls. Returns as soon as the socket is no\n * longer open or the signal aborts — `bufferedAmount` never drains on a\n * closed socket, so waiting on would poll forever.\n */\nexport async function waitForWebSocketBufferDrain(\n  socket: WebSocketLike,\n  {\n    highWaterMark = 1024 * 1024,\n    pollIntervalMs = 20,\n    abortSignal,\n  }: {\n    highWaterMark?: number;\n    pollIntervalMs?: number;\n    abortSignal?: AbortSignal;\n  } = {},\n): Promise<void> {\n  while (\n    socket.readyState === WEBSOCKET_OPEN_STATE &&\n    (socket.bufferedAmount ?? 0) > highWaterMark\n  ) {\n    if (abortSignal?.aborted === true) {\n      return;\n    }\n    await delay(pollIntervalMs);\n  }\n}\n","import { removeUndefinedEntries } from './remove-undefined-entries';\nimport {\n  getWebSocketConstructor,\n  readWebSocketMessageText,\n  type WebSocketConstructor,\n  type WebSocketLike,\n} from './websocket';\n\nexport interface WebSocketConnection {\n  /** Undefined when the constructor threw or the signal was already aborted. */\n  socket: WebSocketLike | undefined;\n  /**\n   * Unregisters the abort listener and closes the socket. Never throws.\n   * Handlers stay attached; callers guard their own terminal state.\n   */\n  close: (code?: number) => void;\n}\n\n/**\n * Opens a WebSocket for a provider model, owning the transport-generic layer\n * (analogous to `postToApi` for HTTP): constructor resolution, header hygiene,\n * abort wiring, and message decoding. Callers own the URL, the auth channel\n * (subprotocols vs headers), and the wire protocol.\n */\nexport function connectToWebSocket({\n  url,\n  protocols,\n  headers,\n  webSocket,\n  abortSignal,\n  onOpen,\n  onMessageText,\n  onProcessingError,\n  onSocketError,\n  onClose,\n  onAbort,\n}: {\n  url: string | URL;\n  protocols?: string | string[];\n  headers?: Record<string, string | undefined>;\n  webSocket?: WebSocketConstructor;\n  abortSignal?: AbortSignal;\n  onOpen?: (socket: WebSocketLike) => void;\n  /** One decoded message. Throws and rejections go to `onProcessingError`. */\n  onMessageText: (text: string) => void | PromiseLike<void>;\n  /** Constructor throws and message decoding/processing failures. */\n  onProcessingError: (error: unknown) => void;\n  onSocketError?: () => void;\n  /**\n   * Receives the close code and reason when the transport provides them\n   * (native `CloseEvent` / `ws` close event).\n   */\n  onClose?: (info: { code?: number; reason?: string }) => void;\n  /** Also called (without opening a socket) when the signal is already aborted. */\n  onAbort?: (reason: unknown) => void;\n}): WebSocketConnection {\n  let socket: WebSocketLike | undefined;\n  let abortListener: (() => void) | undefined;\n\n  const close = (code?: number) => {\n    if (abortListener != null) {\n      abortSignal?.removeEventListener('abort', abortListener);\n      abortListener = undefined;\n    }\n    try {\n      socket?.close(code);\n    } catch {\n      // socket may already be closed\n    }\n  };\n\n  if (abortSignal?.aborted) {\n    onAbort?.(abortSignal.reason ?? new Error('Aborted'));\n    return { socket: undefined, close };\n  }\n\n  try {\n    const WebSocketConstructor = getWebSocketConstructor(webSocket);\n    // native `WebSocket` ignores the headers option; header-capable\n    // implementations like `ws` forward it and throw on undefined values:\n    socket = new WebSocketConstructor(url, protocols, {\n      headers: removeUndefinedEntries(headers ?? {}),\n    });\n  } catch (error) {\n    onProcessingError(error);\n    return { socket: undefined, close };\n  }\n\n  if (abortSignal != null && onAbort != null) {\n    abortListener = () => onAbort(abortSignal.reason ?? new Error('Aborted'));\n    abortSignal.addEventListener('abort', abortListener, { once: true });\n  }\n\n  const openedSocket = socket;\n  socket.onopen = () => {\n    try {\n      onOpen?.(openedSocket);\n    } catch (error) {\n      onProcessingError(error);\n    }\n  };\n  // Messages are processed through a promise tail so async decoding (e.g.\n  // Blob frames) cannot reorder them, and error/close handling cannot\n  // overtake a still-decoding terminal frame.\n  let tail: Promise<void> = Promise.resolve();\n  socket.onmessage = event => {\n    tail = tail\n      .then(() => readWebSocketMessageText(event.data))\n      .then(text => onMessageText(text))\n      .catch(onProcessingError);\n  };\n  socket.onerror = () => {\n    tail = tail.then(() => onSocketError?.()).catch(onProcessingError);\n  };\n  socket.onclose = event => {\n    // Extract close diagnostics when the transport provides them (native\n    // `CloseEvent` and `ws` both carry `code` and `reason`).\n    const closeEvent = event as\n      | { code?: unknown; reason?: unknown }\n      | null\n      | undefined;\n    const code =\n      typeof closeEvent?.code === 'number' ? closeEvent.code : undefined;\n    const reason =\n      typeof closeEvent?.reason === 'string' ? closeEvent.reason : undefined;\n    tail = tail\n      .then(() => onClose?.({ code, reason }))\n      .catch(onProcessingError);\n  };\n\n  return { socket, close };\n}\n","/**\n * Converts an AsyncIterator to a ReadableStream.\n *\n * @template T - The type of elements produced by the AsyncIterator.\n * @param { <T>} iterator - The AsyncIterator to convert.\n * @returns {ReadableStream<T>} - A ReadableStream that provides the same data as the AsyncIterator.\n */\nexport function convertAsyncIteratorToReadableStream<T>(\n  iterator: AsyncIterator<T>,\n): ReadableStream<T> {\n  let cancelled = false;\n\n  return new ReadableStream<T>({\n    /**\n     * Called when the consumer wants to pull more data from the stream.\n     *\n     * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.\n     * @returns {Promise<void>}\n     */\n    async pull(controller) {\n      if (cancelled) return;\n      try {\n        const { value, done } = await iterator.next();\n        if (done) {\n          controller.close();\n        } else {\n          controller.enqueue(value);\n        }\n      } catch (error) {\n        controller.error(error);\n      }\n    },\n    /**\n     * Called when the consumer cancels the stream.\n     */\n    async cancel(reason?: unknown) {\n      cancelled = true;\n      if (iterator.return) {\n        try {\n          await iterator.return(reason);\n        } catch {\n          // intentionally ignore errors during cancellation\n        }\n      }\n    },\n  });\n}\n","import { UnsupportedFunctionalityError } from '@ai-sdk/provider';\nimport type { FilePart } from './types/content-part';\nimport { convertBase64ToUint8Array } from './uint8-utils';\n\ntype InlineFileData = Extract<\n  FilePart['data'],\n  { type: 'data' } | { type: 'text' }\n>;\n\n/**\n * Converts inline file data (a tagged `data` or `text` shape) into raw bytes.\n *\n * - `{ type: 'text', text }` → UTF-8 encoded bytes\n * - `{ type: 'data', data: Uint8Array | Buffer }` → returned as-is\n * - `{ type: 'data', data: ArrayBuffer }` → wrapped in a `Uint8Array`\n * - `{ type: 'data', data: string }` → decoded as base64\n *\n * `{ type: 'stream' }` data is rejected: providers without streaming upload\n * support funnel here and surface a clear `UnsupportedFunctionalityError`.\n */\nexport function convertInlineFileDataToUint8Array(\n  data: InlineFileData | { type: 'stream'; stream: ReadableStream<Uint8Array> },\n): Uint8Array {\n  if (data.type === 'stream') {\n    const error = new UnsupportedFunctionalityError({\n      functionality: 'streaming file upload',\n    });\n    // the caller's stream is never consumed on this path — release it\n    void data.stream.cancel(error).catch(() => {});\n    throw error;\n  }\n  if (data.type === 'text') {\n    return new TextEncoder().encode(data.text);\n  }\n  if (data.data instanceof Uint8Array) {\n    return data.data;\n  }\n  if (data.data instanceof ArrayBuffer) {\n    return new Uint8Array(data.data);\n  }\n  return convertBase64ToUint8Array(data.data);\n}\n","// btoa and atob need to be invoked as a function call, not as a method call.\n// Otherwise CloudFlare will throw a\n// \"TypeError: Illegal invocation: function called with incorrect this reference\"\nconst { btoa, atob } = globalThis;\n\nexport function convertBase64ToUint8Array(base64String: string) {\n  const base64Url = base64String.replace(/-/g, '+').replace(/_/g, '/');\n  const latin1string = atob(base64Url);\n  return Uint8Array.from(latin1string, byte => byte.codePointAt(0)!);\n}\n\nexport function convertUint8ArrayToBase64(array: Uint8Array): string {\n  const chunks: string[] = [];\n  const chunkSize = 4096;\n\n  // Note: regular for loop to support older JavaScript versions that\n  // do not support for..of on Uint8Array\n  for (let i = 0; i < array.length; i += chunkSize) {\n    chunks.push(String.fromCodePoint(...array.subarray(i, i + chunkSize)));\n  }\n\n  return btoa(chunks.join(''));\n}\n\nexport function convertToBase64(value: string | Uint8Array): string {\n  return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;\n}\n","import type { ImageModelV4File } from '@ai-sdk/provider';\nimport { convertUint8ArrayToBase64 } from './uint8-utils';\n\n/**\n * Convert an ImageModelV4File to a URL or data URI string.\n *\n * If the file is a URL, it returns the URL as-is.\n * If the file is base64 data, it returns a data URI with the base64 data.\n * If the file is a Uint8Array, it converts it to base64 and returns a data URI.\n */\nexport function convertImageModelFileToDataUri(file: ImageModelV4File): string {\n  if (file.type === 'url') return file.url;\n\n  return `data:${file.mediaType};base64,${\n    typeof file.data === 'string'\n      ? file.data\n      : convertUint8ArrayToBase64(file.data)\n  }`;\n}\n","/**\n * Converts an input object to FormData for multipart/form-data requests.\n *\n * Handles the following cases:\n * - `null` or `undefined` values are skipped\n * - Arrays with a single element are appended as a single value\n * - Arrays with multiple elements are appended with `[]` suffix (e.g., `image[]`)\n *   unless `useArrayBrackets` is set to `false`\n * - All other values are appended directly\n *\n * @param input - The input object to convert. Use a generic type for type validation.\n * @param options - Optional configuration object.\n * @param options.useArrayBrackets - Whether to add `[]` suffix for multi-element arrays.\n *   Defaults to `true`. Set to `false` for APIs that expect repeated keys without brackets.\n * @returns A FormData object containing the input values.\n *\n * @example\n * ```ts\n * type MyInput = {\n *   model: string;\n *   prompt: string;\n *   images: Blob[];\n * };\n *\n * const formData = convertToFormData<MyInput>({\n *   model: 'gpt-image-1',\n *   prompt: 'A cat',\n *   images: [blob1, blob2],\n * });\n * ```\n */\nexport function convertToFormData<T extends Record<string, unknown>>(\n  input: T,\n  options: { useArrayBrackets?: boolean } = {},\n): FormData {\n  const { useArrayBrackets = true } = options;\n  const formData = new FormData();\n\n  for (const [key, value] of Object.entries(input)) {\n    if (value == null) {\n      continue;\n    }\n\n    if (Array.isArray(value)) {\n      if (value.length === 1) {\n        formData.append(key, value[0] as string | Blob);\n        continue;\n      }\n\n      const arrayKey = useArrayBrackets ? `${key}[]` : key;\n      for (const item of value) {\n        formData.append(arrayKey, item as string | Blob);\n      }\n      continue;\n    }\n\n    formData.append(key, value as string | Blob);\n  }\n\n  return formData;\n}\n","import type { LanguageModelV4ResponseMetadata } from '@ai-sdk/provider';\n\n/**\n * Converts common provider response fields into language model response\n * metadata.\n */\nexport function createLanguageModelResponseMetadata({\n  id,\n  model,\n  created,\n}: {\n  id?: string | null;\n  model?: string | null;\n  created?: number | null;\n}): LanguageModelV4ResponseMetadata {\n  return {\n    id: id ?? undefined,\n    modelId: model ?? undefined,\n    timestamp: created != null ? new Date(created * 1000) : undefined,\n  };\n}\n","import type { LanguageModelV4Usage } from '@ai-sdk/provider';\n\n/**\n * Creates an empty language model usage result for unavailable usage data.\n */\nexport function createNullLanguageModelUsage(): LanguageModelV4Usage {\n  return {\n    inputTokens: {\n      total: undefined,\n      noCache: undefined,\n      cacheRead: undefined,\n      cacheWrite: undefined,\n    },\n    outputTokens: {\n      total: undefined,\n      text: undefined,\n      reasoning: undefined,\n    },\n    raw: undefined,\n  };\n}\n","import type {\n  LanguageModelV4FunctionTool,\n  LanguageModelV4ProviderTool,\n} from '@ai-sdk/provider';\n\n/**\n * Interface for mapping between custom tool names and provider tool names.\n */\nexport interface ToolNameMapping {\n  /**\n   * Maps a custom tool name (used by the client) to the provider's tool name.\n   * If the custom tool name does not have a mapping, returns the input name.\n   *\n   * @param customToolName - The custom name of the tool defined by the client.\n   * @returns The corresponding provider tool name, or the input name if not mapped.\n   */\n  toProviderToolName: (customToolName: string) => string;\n\n  /**\n   * Maps a provider tool name to the custom tool name used by the client.\n   * If the provider tool name does not have a mapping, returns the input name.\n   *\n   * @param providerToolName - The name of the tool as understood by the provider.\n   * @returns The corresponding custom tool name, or the input name if not mapped.\n   */\n  toCustomToolName: (providerToolName: string) => string;\n}\n\n/**\n * @param tools - Tools that were passed to the language model.\n * @param providerToolNames - Maps the provider tool ids to the provider tool names.\n */\nexport function createToolNameMapping({\n  tools = [],\n  providerToolNames,\n}: {\n  /**\n   * Tools that were passed to the language model.\n   */\n  tools:\n    | Array<LanguageModelV4FunctionTool | LanguageModelV4ProviderTool>\n    | undefined;\n\n  /**\n   * Maps the provider tool ids to the provider tool names.\n   */\n  providerToolNames: Record<`${string}.${string}`, string>;\n}): ToolNameMapping {\n  const customToolNameToProviderToolName: Record<string, string> = {};\n  const providerToolNameToCustomToolName: Record<string, string> = {};\n\n  for (const tool of tools) {\n    if (tool.type === 'provider' && tool.id in providerToolNames) {\n      const providerToolName = providerToolNames[tool.id];\n      customToolNameToProviderToolName[tool.name] = providerToolName;\n      providerToolNameToCustomToolName[providerToolName] = tool.name;\n    }\n  }\n\n  return {\n    toProviderToolName: (customToolName: string) =>\n      customToolNameToProviderToolName[customToolName] ?? customToolName,\n    toCustomToolName: (providerToolName: string) =>\n      providerToolNameToCustomToolName[providerToolName] ?? providerToolName,\n  };\n}\n","const marker = Symbol.for('vercel.ai.providerStreamError');\n\nexport type ProviderStreamError = {\n  readonly message: string;\n  readonly type?: string;\n  readonly code?: string | number;\n  readonly statusCode?: number;\n  readonly isRetryable?: boolean;\n  readonly data: unknown;\n};\n\n/**\n * Adds provider-owned status and retry metadata to a stream error payload\n * without requiring provider packages to depend on AI SDK Core.\n */\nexport function createProviderStreamError({\n  message,\n  type,\n  code,\n  statusCode,\n  isRetryable,\n  data,\n}: {\n  message: string;\n  type?: string;\n  code?: string | number;\n  statusCode?: number;\n  isRetryable?: boolean;\n  data: unknown;\n}): ProviderStreamError {\n  const error = {\n    message,\n    type,\n    code,\n    statusCode,\n    isRetryable,\n    data,\n  };\n\n  Object.defineProperty(error, marker, { value: true });\n\n  return error;\n}\n\nexport function isProviderStreamError(\n  error: unknown,\n): error is ProviderStreamError {\n  return (\n    typeof error === 'object' &&\n    error != null &&\n    (error as Record<symbol, unknown>)[marker] === true\n  );\n}\n","/**\n * Delayed promise. It is only constructed once the value is accessed.\n * This is useful to avoid unhandled promise rejections when the promise is created\n * but not accessed.\n */\nexport class DelayedPromise<T> {\n  private status:\n    | { type: 'pending' }\n    | { type: 'resolved'; value: T }\n    | { type: 'rejected'; error: unknown } = { type: 'pending' };\n  private _promise: Promise<T> | undefined;\n  private _resolve: undefined | ((value: T) => void) = undefined;\n  private _reject: undefined | ((error: unknown) => void) = undefined;\n\n  get promise(): Promise<T> {\n    if (this._promise) {\n      return this._promise;\n    }\n\n    this._promise = new Promise<T>((resolve, reject) => {\n      if (this.status.type === 'resolved') {\n        resolve(this.status.value);\n      } else if (this.status.type === 'rejected') {\n        reject(this.status.error);\n      }\n\n      this._resolve = resolve;\n      this._reject = reject;\n    });\n\n    return this._promise;\n  }\n\n  resolve(value: T): void {\n    this.status = { type: 'resolved', value };\n\n    if (this._promise) {\n      this._resolve?.(value);\n    }\n  }\n\n  reject(error: unknown): void {\n    this.status = { type: 'rejected', error };\n\n    if (this._promise) {\n      this._reject?.(error);\n    }\n  }\n\n  isResolved(): boolean {\n    return this.status.type === 'resolved';\n  }\n\n  isRejected(): boolean {\n    return this.status.type === 'rejected';\n  }\n\n  isPending(): boolean {\n    return this.status.type === 'pending';\n  }\n}\n","import { APICallError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport type { FetchFunction } from './fetch-function';\nimport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nimport { handleFetchError } from './handle-fetch-error';\nimport { isAbortError } from './is-abort-error';\nimport type { ResponseHandler } from './response-handler';\nimport { VERSION } from './version';\nimport { withUserAgentSuffix } from './with-user-agent-suffix';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => globalThis.fetch;\n\n/**\n * Sends a DELETE request. For URLs built from developer-configured endpoints\n * only — there is no untrusted-URL validation path (use `getFromApi` with\n * `validateUrl` for response-supplied URLs).\n */\nexport const deleteFromApi = async <T>({\n  url,\n  headers = {},\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch = getOriginalFetch(),\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  failedResponseHandler: ResponseHandler<Error>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) => {\n  try {\n    const response = await fetch(url, {\n      method: 'DELETE',\n      headers: withUserAgentSuffix(\n        headers,\n        `ai-sdk/provider-utils/${VERSION}`,\n        getRuntimeEnvironmentUserAgent(),\n      ),\n      signal: abortSignal,\n    });\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.ok) {\n      let errorInformation: {\n        value: Error;\n        responseHeaders?: Record<string, string> | undefined;\n      };\n\n      try {\n        errorInformation = await failedResponseHandler({\n          response,\n          url,\n          requestBodyValues: {},\n        });\n      } catch (error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n\n        throw new APICallError({\n          message: 'Failed to process error response',\n          cause: error,\n          statusCode: response.status,\n          url,\n          responseHeaders,\n          requestBodyValues: {},\n        });\n      }\n\n      throw errorInformation.value;\n    }\n\n    try {\n      return await successfulResponseHandler({\n        response,\n        url,\n        requestBodyValues: {},\n      });\n    } catch (error) {\n      if (error instanceof Error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n      }\n\n      throw new APICallError({\n        message: 'Failed to process successful response',\n        cause: error,\n        statusCode: response.status,\n        url,\n        responseHeaders,\n        requestBodyValues: {},\n      });\n    }\n  } catch (error) {\n    throw handleFetchError({ error, url, requestBodyValues: {} });\n  }\n};\n","/**\n * Extracts the headers from a response object and returns them as a key-value object.\n *\n * @param response - The response object to extract headers from.\n * @returns The headers as a key-value object.\n */\nexport function extractResponseHeaders(response: Response) {\n  return Object.fromEntries<string>([...response.headers]);\n}\n","export function getRuntimeEnvironmentUserAgent(\n  globalThisAny: any = globalThis as any,\n): string {\n  // Browsers\n  if (globalThisAny.window) {\n    return `runtime/browser`;\n  }\n\n  // Cloudflare Workers / Deno / Bun / Node.js >= 21.1\n  if (globalThisAny.navigator?.userAgent) {\n    return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;\n  }\n\n  // Nodes.js < 21.1\n  if (globalThisAny.process?.versions?.node) {\n    return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;\n  }\n\n  if (globalThisAny.EdgeRuntime) {\n    return `runtime/vercel-edge`;\n  }\n\n  return 'runtime/unknown';\n}\n","import { APICallError } from '@ai-sdk/provider';\nimport { isAbortError } from './is-abort-error';\n\nconst FETCH_FAILED_ERROR_MESSAGES = ['fetch failed', 'failed to fetch'];\n\nconst RETRYABLE_NETWORK_ERROR_CODES = new Set([\n  'ConnectionRefused',\n  'ConnectionClosed',\n  'FailedToOpenSocket',\n  'ECONNRESET',\n  'ECONNREFUSED',\n  'ETIMEDOUT',\n  'EPIPE',\n  'UND_ERR_SOCKET',\n  'UND_ERR_HEADERS_TIMEOUT',\n  'UND_ERR_BODY_TIMEOUT',\n  'UND_ERR_CONNECT_TIMEOUT',\n]);\n\nfunction findNetworkError(\n  error: unknown,\n): (Error & { code?: unknown }) | undefined {\n  const visited = new Set<Error>();\n  let current = error;\n\n  while (current instanceof Error && !visited.has(current)) {\n    visited.add(current);\n\n    const errorWithCode = current as Error & { code?: unknown };\n    if (\n      typeof errorWithCode.code === 'string' &&\n      RETRYABLE_NETWORK_ERROR_CODES.has(errorWithCode.code)\n    ) {\n      return errorWithCode;\n    }\n\n    current = (current as Error & { cause?: unknown }).cause;\n  }\n\n  return undefined;\n}\n\nexport function handleFetchError({\n  error,\n  url,\n  requestBodyValues,\n}: {\n  error: unknown;\n  url: string;\n  requestBodyValues: unknown;\n}) {\n  if (isAbortError(error)) {\n    return error;\n  }\n\n  // unwrap original error when fetch failed (for easier debugging):\n  if (\n    error instanceof TypeError &&\n    FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())\n  ) {\n    const cause = (error as any).cause;\n\n    if (cause != null) {\n      // Failed to connect to server:\n      return new APICallError({\n        message: `Cannot connect to API: ${cause.message}`,\n        cause,\n        url,\n        requestBodyValues,\n        isRetryable: true, // retry when network error\n      });\n    }\n  }\n\n  const networkError = findNetworkError(error);\n\n  if (networkError != null) {\n    if (APICallError.isInstance(error)) {\n      return new APICallError({\n        message: error.message,\n        cause: error.cause,\n        url: error.url,\n        requestBodyValues: error.requestBodyValues,\n        statusCode: error.statusCode,\n        responseHeaders: error.responseHeaders,\n        responseBody: error.responseBody,\n        data: error.data,\n        isRetryable: true,\n      });\n    }\n\n    return new APICallError({\n      message: `Cannot connect to API: ${\n        error instanceof Error ? error.message : networkError.message\n      }`,\n      cause: error,\n      url,\n      requestBodyValues,\n      isRetryable: true,\n    });\n  }\n\n  return error;\n}\n","export function isAbortError(error: unknown): error is Error {\n  return (\n    (error instanceof Error ||\n      (typeof DOMException === 'function' && error instanceof DOMException)) &&\n    (error.name === 'AbortError' ||\n      error.name === 'ResponseAborted' || // Next.js\n      error.name === 'TimeoutError')\n  );\n}\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n  typeof __PACKAGE_VERSION__ !== 'undefined'\n    ? __PACKAGE_VERSION__\n    : '0.0.0-test';\n","/**\n * Normalizes different header inputs into a plain record with lower-case keys.\n * Entries with `undefined` or `null` values are removed.\n *\n * @param headers - Input headers (`Headers`, tuples array, plain record) to normalize.\n * @returns A record containing the normalized header entries.\n */\nexport function normalizeHeaders(\n  headers:\n    | HeadersInit\n    | Record<string, string | undefined>\n    | Array<[string, string | undefined]>\n    | undefined,\n): Record<string, string> {\n  if (headers == null) {\n    return {};\n  }\n\n  const normalized: Record<string, string> = {};\n\n  if (headers instanceof Headers) {\n    headers.forEach((value, key) => {\n      normalized[key.toLowerCase()] = value;\n    });\n  } else {\n    if (!Array.isArray(headers)) {\n      headers = Object.entries(headers);\n    }\n\n    for (const [key, value] of headers) {\n      if (value != null) {\n        normalized[key.toLowerCase()] = value;\n      }\n    }\n  }\n\n  return normalized;\n}\n","import { normalizeHeaders } from './normalize-headers';\n\n/**\n * Appends suffix parts to the `user-agent` header.\n * If a `user-agent` header already exists, the suffix parts are appended to it.\n * If no `user-agent` header exists, a new one is created with the suffix parts.\n * Automatically removes undefined entries from the headers.\n *\n * @param headers - The original headers.\n * @param userAgentSuffixParts - The parts to append to the `user-agent` header.\n * @returns The new headers with the `user-agent` header set or updated.\n */\nexport function withUserAgentSuffix(\n  headers: HeadersInit | Record<string, string | undefined> | undefined,\n  ...userAgentSuffixParts: string[]\n): Record<string, string> {\n  const normalizedHeaders = new Headers(normalizeHeaders(headers));\n\n  const currentUserAgentHeader = normalizedHeaders.get('user-agent') || '';\n\n  normalizedHeaders.set(\n    'user-agent',\n    [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(' '),\n  );\n\n  return Object.fromEntries(normalizedHeaders.entries());\n}\n","import { convertBase64ToUint8Array } from './uint8-utils';\n\nconst imageMediaTypeSignatures = [\n  {\n    mediaType: 'image/gif' as const,\n    bytesPrefix: [0x47, 0x49, 0x46, 0x38, 0x37, 0x61], // GIF87a\n  },\n  {\n    mediaType: 'image/gif' as const,\n    bytesPrefix: [0x47, 0x49, 0x46, 0x38, 0x39, 0x61], // GIF89a\n  },\n  {\n    mediaType: 'image/png' as const,\n    bytesPrefix: [0x89, 0x50, 0x4e, 0x47], // PNG\n  },\n  {\n    mediaType: 'image/jpeg' as const,\n    bytesPrefix: [0xff, 0xd8], // JPEG\n  },\n  {\n    mediaType: 'image/webp' as const,\n    bytesPrefix: [\n      0x52,\n      0x49,\n      0x46,\n      0x46, // \"RIFF\"\n      null,\n      null,\n      null,\n      null, // file size (variable)\n      0x57,\n      0x45,\n      0x42,\n      0x50, // \"WEBP\"\n    ],\n  },\n  {\n    mediaType: 'image/bmp' as const,\n    bytesPrefix: [0x42, 0x4d, null, null, null, null, 0x00, 0x00, 0x00, 0x00],\n  },\n  {\n    mediaType: 'image/tiff' as const,\n    bytesPrefix: [0x49, 0x49, 0x2a, 0x00],\n  },\n  {\n    mediaType: 'image/tiff' as const,\n    bytesPrefix: [0x4d, 0x4d, 0x00, 0x2a],\n  },\n  {\n    mediaType: 'image/avif' as const,\n    bytesPrefix: [\n      0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66,\n    ],\n  },\n  {\n    mediaType: 'image/heic' as const,\n    bytesPrefix: [\n      0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63,\n    ],\n  },\n] as const;\n\nconst documentMediaTypeSignatures = [\n  {\n    mediaType: 'application/pdf' as const,\n    bytesPrefix: [0x25, 0x50, 0x44, 0x46], // %PDF\n  },\n] as const;\n\nconst audioMediaTypeSignaturesWithoutMp4 = [\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xfb],\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xfa],\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xf3],\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xf2],\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xe3],\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xe2],\n  },\n  {\n    mediaType: 'audio/wav' as const,\n    bytesPrefix: [\n      0x52, // R\n      0x49, // I\n      0x46, // F\n      0x46, // F\n      null,\n      null,\n      null,\n      null,\n      0x57, // W\n      0x41, // A\n      0x56, // V\n      0x45, // E\n    ],\n  },\n  {\n    mediaType: 'audio/ogg' as const,\n    bytesPrefix: [0x4f, 0x67, 0x67, 0x53],\n  },\n  {\n    mediaType: 'audio/flac' as const,\n    bytesPrefix: [0x66, 0x4c, 0x61, 0x43],\n  },\n  {\n    mediaType: 'audio/aac' as const,\n    bytesPrefix: [0x40, 0x15, 0x00, 0x00],\n  },\n  {\n    mediaType: 'audio/webm',\n    bytesPrefix: [0x1a, 0x45, 0xdf, 0xa3],\n  },\n] as const;\n\nconst audioMediaTypeSignatures = [\n  ...audioMediaTypeSignaturesWithoutMp4,\n  {\n    mediaType: 'audio/mp4' as const,\n    bytesPrefix: [\n      0x00,\n      0x00,\n      0x00,\n      null,\n      0x66,\n      0x74,\n      0x79,\n      0x70, // ftyp\n    ],\n  },\n] as const;\n\nconst videoMediaTypeSignatures = [\n  {\n    mediaType: 'video/mp4' as const,\n    bytesPrefix: [\n      0x00,\n      0x00,\n      0x00,\n      null,\n      0x66,\n      0x74,\n      0x79,\n      0x70, // ftyp\n    ],\n  },\n  {\n    mediaType: 'video/webm' as const,\n    bytesPrefix: [0x1a, 0x45, 0xdf, 0xa3], // EBML\n  },\n  {\n    mediaType: 'video/quicktime' as const,\n    bytesPrefix: [\n      0x00,\n      0x00,\n      0x00,\n      0x14,\n      0x66,\n      0x74,\n      0x79,\n      0x70,\n      0x71,\n      0x74, // ftypqt\n    ],\n  },\n  {\n    mediaType: 'video/x-msvideo' as const,\n    bytesPrefix: [0x52, 0x49, 0x46, 0x46], // RIFF (AVI)\n  },\n] as const;\n\nconst DEFAULT_SNIFF_BYTES = 18;\n\n// Longest signature prefix in the tables above (e.g. image/avif = 12 bytes).\nconst MAX_SIGNATURE_BYTES = 12;\n\n// Largest ID3v2 tag (10-byte header + body) skipped to reach the audio frame.\n// Covers typical tags including embedded cover art while keeping the decode\n// bounded and O(1) in the attachment size. Exported for boundary tests.\nexport const MAX_ID3_TAG_BYTES = 128 * 1024;\n\n// Total prefix decoded when an ID3 tag is present: the tag plus room for the\n// trailing signature, so a tag right at the size limit stays detectable.\nconst ID3_SCAN_BYTES = MAX_ID3_TAG_BYTES + MAX_SIGNATURE_BYTES;\n\n// Decode/view exactly the first `maxBytes` bytes from the front of the input.\n// The base64 and raw-byte paths yield the same length, so detection does not\n// depend on the input's representation.\nfunction decodePrefix(data: Uint8Array | string, maxBytes: number): Uint8Array {\n  if (typeof data !== 'string') {\n    return data.length > maxBytes ? data.subarray(0, maxBytes) : data;\n  }\n  // base64: 4 chars -> 3 bytes. Decode whole 4-char groups, then trim the 0-2\n  // extra bytes so the result matches the raw-byte path exactly.\n  const maxChars = Math.ceil(maxBytes / 3) * 4;\n  const bytes = convertBase64ToUint8Array(\n    data.substring(0, Math.min(data.length, maxChars)),\n  );\n  return bytes.length > maxBytes ? bytes.subarray(0, maxBytes) : bytes;\n}\n\nfunction hasID3(bytes: Uint8Array): boolean {\n  return (\n    bytes.length > 10 &&\n    bytes[0] === 0x49 && // 'I'\n    bytes[1] === 0x44 && // 'D'\n    bytes[2] === 0x33 // '3'\n  );\n}\n\nconst stripID3 = (bytes: Uint8Array): Uint8Array => {\n  const id3Size =\n    ((bytes[6] & 0x7f) << 21) |\n    ((bytes[7] & 0x7f) << 14) |\n    ((bytes[8] & 0x7f) << 7) |\n    (bytes[9] & 0x7f);\n  return bytes.subarray(id3Size + 10);\n};\n\ntype MediaTypeSignatures = ReadonlyArray<{\n  readonly mediaType: string;\n  readonly bytesPrefix: ReadonlyArray<number | null>;\n}>;\n\nfunction detectMediaTypeBySignatures<T extends MediaTypeSignatures>({\n  data,\n  signatures,\n}: {\n  data: Uint8Array | string;\n  signatures: T;\n}): T[number]['mediaType'] | undefined {\n  let bytes = decodePrefix(data, DEFAULT_SNIFF_BYTES);\n\n  // ID3v2-tagged MP3s carry the audio frame after the tag; scan a bounded\n  // prefix past it rather than decoding the whole input.\n  if (hasID3(bytes)) {\n    bytes = stripID3(decodePrefix(data, ID3_SCAN_BYTES));\n  }\n\n  for (const signature of signatures) {\n    if (\n      bytes.length >= signature.bytesPrefix.length &&\n      signature.bytesPrefix.every(\n        (byte, index) => byte === null || bytes[index] === byte,\n      )\n    ) {\n      return signature.mediaType;\n    }\n  }\n\n  return undefined;\n}\n\nconst topLevelSignatureTables = {\n  image: imageMediaTypeSignatures,\n  audio: audioMediaTypeSignatures,\n  video: videoMediaTypeSignatures,\n  application: documentMediaTypeSignatures,\n} as const;\n\ntype TopLevelMediaType = keyof typeof topLevelSignatureTables;\n\n/**\n * Detect the IANA media type of a file from its raw bytes or base64 string.\n *\n * - When `topLevelType` is omitted, every known signature is considered\n *   (image, audio, video, and application). Returns `undefined` when the\n *   bytes do not match any known signature.\n * - When `topLevelType` is provided, only signatures for that top-level\n *   segment are considered. Returns `undefined` for unsupported segments\n *   (e.g. `\"text\"`) or when no signature matches.\n */\nexport function detectMediaType({\n  data,\n  topLevelType,\n}: {\n  data: Uint8Array | string;\n  topLevelType?: string;\n}): string | undefined {\n  if (topLevelType === undefined) {\n    return detectMediaTypeBySignatures({\n      data,\n      signatures: [\n        ...imageMediaTypeSignatures,\n        ...documentMediaTypeSignatures,\n        // MP4 containers cannot be distinguished as audio or video by ftyp alone.\n        // Preserve the generic detection result as video/mp4.\n        ...audioMediaTypeSignaturesWithoutMp4,\n        ...videoMediaTypeSignatures,\n      ],\n    });\n  }\n\n  const signatures = topLevelSignatureTables[topLevelType as TopLevelMediaType];\n\n  if (signatures === undefined) {\n    return undefined;\n  }\n\n  return detectMediaTypeBySignatures({ data, signatures });\n}\n\n/**\n * Returns the top-level segment of a media type (the portion before `/`).\n *\n * Examples:\n *   - `\"image/png\"` -> `\"image\"`\n *   - `\"image/*\"` -> `\"image\"`\n *   - `\"image\"` -> `\"image\"`\n *   - `\"image/\"` -> `\"image\"`\n *   - `\"\"` -> `\"\"`\n *   - `\"/\"` -> `\"\"`\n */\nexport function getTopLevelMediaType(mediaType: string): string {\n  const slashIndex = mediaType.indexOf('/');\n  return slashIndex === -1 ? mediaType : mediaType.substring(0, slashIndex);\n}\n\n/**\n * Returns `true` only when the given media type has a non-empty, non-wildcard\n * subtype (i.e. matches the form `type/subtype`, and `subtype` is not `*`).\n *\n * Examples:\n *   - `\"image/png\"` -> `true`\n *   - `\"image/*\"` -> `false`\n *   - `\"image\"` -> `false`\n *   - `\"image/\"` -> `false`\n *   - `\"\"` -> `false`\n *   - `\"/\"` -> `false`\n */\nexport function isFullMediaType(mediaType: string): boolean {\n  const slashIndex = mediaType.indexOf('/');\n  if (slashIndex === -1) {\n    return false;\n  }\n  const subtype = mediaType.substring(slashIndex + 1);\n  return subtype.length > 0 && subtype !== '*';\n}\n","/**\n * Cancels a response body to release the underlying connection.\n *\n * When a fetch Response is rejected without consuming its body (e.g. a failed\n * status code, an open-redirect rejection, or a Content-Length that exceeds the\n * size limit), the underlying TCP socket is not returned to the connection pool\n * and may stay open until the process runs out of file descriptors. Cancelling\n * the body avoids this leak.\n *\n * Errors thrown while cancelling are ignored: the body may already be locked,\n * disturbed, or absent, none of which should mask the original rejection.\n */\nexport async function cancelResponseBody(response: Response): Promise<void> {\n  try {\n    await response.body?.cancel();\n  } catch {\n    // Ignore cancel errors so the original rejection is preserved.\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_DownloadError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class DownloadError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly url: string;\n  readonly statusCode?: number;\n  readonly statusText?: string;\n\n  constructor({\n    url,\n    statusCode,\n    statusText,\n    cause,\n    message = cause == null\n      ? `Failed to download ${url}: ${statusCode} ${statusText}`\n      : `Failed to download ${url}: ${cause}`,\n  }: {\n    url: string;\n    statusCode?: number;\n    statusText?: string;\n    message?: string;\n    cause?: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.url = url;\n    this.statusCode = statusCode;\n    this.statusText = statusText;\n  }\n\n  static isInstance(error: unknown): error is DownloadError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","/**\n * Returns `true` when running in a browser.\n *\n * Detection keys on the presence of a global `window`, matching the browser\n * check used elsewhere in this package (see `getRuntimeEnvironmentUserAgent`)\n * so the SDK has a single, consistent definition of \"browser\". Server runtimes\n * (Node.js, Deno, Bun, edge/workers) do not define `window`.\n */\nexport function isBrowserRuntime(\n  globalThisAny: any = globalThis as any,\n): boolean {\n  return globalThisAny.window != null;\n}\n","/**\n * Returns true when `url` has the same origin (scheme + host + port) as\n * `baseUrl`.\n *\n * Used to decide whether provider credentials may be attached to a request to a\n * URL taken from a provider response (e.g. a polling or media-download URL).\n * Credentials must only be sent to the provider's own origin; a response that\n * names a foreign host (a CDN, or an attacker-controlled host if the response\n * is tampered with) must not receive the API key.\n *\n * Returns false if either value is not a valid absolute URL (fail-closed).\n */\nexport function isSameOrigin(url: string, baseUrl: string): boolean {\n  try {\n    return new URL(url).origin === new URL(baseUrl).origin;\n  } catch {\n    return false;\n  }\n}\n","import { DownloadError } from './download-error';\n\n/**\n * Validates that a URL is safe to download from, blocking private/internal addresses\n * to prevent SSRF attacks.\n *\n * Note: this function performs string/literal-IP checks only. The Node.js\n * download fetch additionally validates and pins DNS results at connect time.\n *\n * @param url - The URL string to validate.\n * @throws DownloadError if the URL is unsafe.\n */\nexport function validateDownloadUrl(url: string): void {\n  let parsed: URL;\n  try {\n    parsed = new URL(url);\n  } catch {\n    throw new DownloadError({\n      url,\n      message: `Invalid URL: ${url}`,\n    });\n  }\n\n  // data: URLs are inline content, so they do not trigger a network fetch or SSRF risk.\n  if (parsed.protocol === 'data:') {\n    return;\n  }\n\n  // Only allow http and https network protocols\n  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n    throw new DownloadError({\n      url,\n      message: `URL scheme must be http, https, or data, got ${parsed.protocol}`,\n    });\n  }\n\n  // Strip a trailing dot so a fully-qualified name like `localhost.` (which resolves\n  // identically to `localhost`) cannot bypass the hostname blocklist below.\n  const hostname = parsed.hostname.toLowerCase().replace(/\\.+$/, '');\n\n  // Block empty hostname\n  if (!hostname) {\n    throw new DownloadError({\n      url,\n      message: `URL must have a hostname`,\n    });\n  }\n\n  // Block localhost and .local domains\n  if (\n    hostname === 'localhost' ||\n    hostname.endsWith('.local') ||\n    hostname.endsWith('.localhost')\n  ) {\n    throw new DownloadError({\n      url,\n      message: `URL with hostname ${hostname} is not allowed`,\n    });\n  }\n\n  // Check for IPv6 addresses (enclosed in brackets in URLs)\n  if (hostname.startsWith('[') && hostname.endsWith(']')) {\n    const ipv6 = hostname.slice(1, -1);\n    if (isPrivateIPv6(ipv6)) {\n      throw new DownloadError({\n        url,\n        message: `URL with IPv6 address ${hostname} is not allowed`,\n      });\n    }\n    return;\n  }\n\n  // Check for IPv4 addresses\n  if (isIPv4(hostname)) {\n    if (isPrivateIPv4(hostname)) {\n      throw new DownloadError({\n        url,\n        message: `URL with IP address ${hostname} is not allowed`,\n      });\n    }\n    return;\n  }\n}\n\n/**\n * Validates an address returned by DNS before it is used to open a socket.\n * This is intentionally not exported from the package entry point.\n */\nexport function validateDownloadAddress({\n  address,\n  family,\n  hostname,\n}: {\n  address: string;\n  family: number;\n  hostname: string;\n}): void {\n  const isUnsafe =\n    family === 4\n      ? !isIPv4(address) || isPrivateIPv4(address)\n      : family === 6\n        ? isPrivateIPv6(address)\n        : true;\n\n  if (isUnsafe) {\n    throw new DownloadError({\n      url: hostname,\n      message: `Hostname ${hostname} resolved to disallowed IP address ${address}`,\n    });\n  }\n}\n\nfunction isIPv4(hostname: string): boolean {\n  const parts = hostname.split('.');\n  if (parts.length !== 4) return false;\n  return parts.every(part => {\n    const num = Number(part);\n    return (\n      Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part\n    );\n  });\n}\n\nfunction isPrivateIPv4(ip: string): boolean {\n  const parts = ip.split('.').map(Number);\n  const [a, b, c] = parts;\n\n  // 0.0.0.0/8\n  if (a === 0) return true;\n  // 10.0.0.0/8\n  if (a === 10) return true;\n  // 100.64.0.0/10 (CGNAT, used by some cloud providers for internal traffic)\n  if (a === 100 && b >= 64 && b <= 127) return true;\n  // 127.0.0.0/8\n  if (a === 127) return true;\n  // 169.254.0.0/16\n  if (a === 169 && b === 254) return true;\n  // 172.16.0.0/12\n  if (a === 172 && b >= 16 && b <= 31) return true;\n  // 192.0.0.0/24 (IETF protocol assignments)\n  if (a === 192 && b === 0 && c === 0) return true;\n  // 192.0.2.0/24 (TEST-NET-1, documentation)\n  if (a === 192 && b === 0 && c === 2) return true;\n  // 192.168.0.0/16\n  if (a === 192 && b === 168) return true;\n  // 198.18.0.0/15 (benchmarking)\n  if (a === 198 && (b === 18 || b === 19)) return true;\n  // 198.51.100.0/24 (TEST-NET-2, documentation)\n  if (a === 198 && b === 51 && c === 100) return true;\n  // 203.0.113.0/24 (TEST-NET-3, documentation)\n  if (a === 203 && b === 0 && c === 113) return true;\n  // 224.0.0.0/4 (multicast) and 240.0.0.0/4 (reserved, incl. 255.255.255.255 broadcast)\n  if (a >= 224) return true;\n\n  return false;\n}\n\n/**\n * Expands an IPv6 address string into its 8 16-bit groups, handling `::`\n * compression and an optional dotted-decimal IPv4 tail (e.g. `::ffff:127.0.0.1`).\n *\n * @returns the 8 groups, or null if the input is not a parseable IPv6 address.\n */\nfunction parseIPv6(ip: string): number[] | null {\n  // Strip an optional zone id (e.g. `fe80::1%eth0`).\n  let address = ip.toLowerCase();\n  const zoneIndex = address.indexOf('%');\n  if (zoneIndex !== -1) {\n    address = address.slice(0, zoneIndex);\n  }\n\n  // At most one `::` compression marker is allowed.\n  const halves = address.split('::');\n  if (halves.length > 2) return null;\n\n  const toGroups = (segment: string): number[] | null => {\n    if (segment === '') return [];\n    const groups: number[] = [];\n    const parts = segment.split(':');\n    for (let i = 0; i < parts.length; i++) {\n      const part = parts[i];\n      // A dotted-decimal IPv4 tail is only valid as the final part.\n      if (part.includes('.')) {\n        if (i !== parts.length - 1 || !isIPv4(part)) return null;\n        const [a, b, c, d] = part.split('.').map(Number);\n        groups.push((a << 8) | b, (c << 8) | d);\n        continue;\n      }\n      if (!/^[0-9a-f]{1,4}$/.test(part)) return null;\n      groups.push(parseInt(part, 16));\n    }\n    return groups;\n  };\n\n  const head = toGroups(halves[0]);\n  if (head === null) return null;\n\n  if (halves.length === 2) {\n    const tail = toGroups(halves[1]);\n    if (tail === null) return null;\n    const fill = 8 - head.length - tail.length;\n    if (fill < 0) return null;\n    return [...head, ...new Array<number>(fill).fill(0), ...tail];\n  }\n\n  // No `::` compression: the address must contain exactly 8 groups.\n  return head.length === 8 ? head : null;\n}\n\nfunction isPrivateIPv6(ip: string): boolean {\n  const groups = parseIPv6(ip);\n\n  // Fail closed: if the address cannot be parsed, treat it as unsafe.\n  if (groups === null) return true;\n\n  const topZero = (count: number) =>\n    groups.slice(0, count).every(group => group === 0);\n\n  // ::1 (loopback) and :: (unspecified)\n  if (topZero(7) && (groups[7] === 0 || groups[7] === 1)) return true;\n\n  // fc00::/7 (unique local addresses)\n  if ((groups[0] & 0xfe00) === 0xfc00) return true;\n\n  // fe80::/10 (link-local)\n  if ((groups[0] & 0xffc0) === 0xfe80) return true;\n\n  // fec0::/10 (site-local, deprecated but still routable internally)\n  if ((groups[0] & 0xffc0) === 0xfec0) return true;\n\n  // ff00::/8 (multicast)\n  if ((groups[0] & 0xff00) === 0xff00) return true;\n\n  // 2001:db8::/32 (documentation range, not globally routable)\n  if (groups[0] === 0x2001 && groups[1] === 0x0db8) return true;\n\n  // 3fff::/20 (documentation range, RFC 9637)\n  if (groups[0] === 0x3fff && (groups[1] & 0xf000) === 0x0000) return true;\n\n  // Addresses that embed an IPv4 address in their last 32 bits. For these we\n  // extract the embedded IPv4 and reuse the IPv4 private-range checks, so that\n  // e.g. ::ffff:127.0.0.1 or 64:ff9b::169.254.169.254 are blocked.\n  const embedsIPv4 =\n    // ::/96 — IPv4-compatible (deprecated)\n    topZero(6) ||\n    // ::ffff:0:0/96 — IPv4-mapped (ffff in group 5)\n    (topZero(5) && groups[5] === 0xffff) ||\n    // ::ffff:0:0/96 — IPv4-translated form (ffff in group 4, group 5 zero)\n    (topZero(4) && groups[4] === 0xffff && groups[5] === 0) ||\n    // 64:ff9b::/96 — NAT64 well-known prefix\n    (groups[0] === 0x0064 &&\n      groups[1] === 0xff9b &&\n      groups[2] === 0 &&\n      groups[3] === 0 &&\n      groups[4] === 0 &&\n      groups[5] === 0) ||\n    // 64:ff9b:1::/48 — NAT64 local-use prefix\n    (groups[0] === 0x0064 && groups[1] === 0xff9b && groups[2] === 0x0001);\n\n  if (embedsIPv4) {\n    const a = (groups[6] >> 8) & 0xff;\n    const b = groups[6] & 0xff;\n    const c = (groups[7] >> 8) & 0xff;\n    const d = groups[7] & 0xff;\n    return isPrivateIPv4(`${a}.${b}.${c}.${d}`);\n  }\n\n  return false;\n}\n","import type * as nodeDnsModule from 'node:dns';\nimport type * as nodeModule from 'node:module';\nimport type * as undiciModule from 'undici';\nimport type { FetchFunction } from './fetch-function';\nimport { validateDownloadAddress } from './validate-download-url';\n\ntype NodeDns = typeof nodeDnsModule;\ntype NodeModule = typeof nodeModule;\ntype Undici = typeof undiciModule;\n\ntype LookupAddress = {\n  address: string;\n  family: number;\n};\n\ntype LookupOptions = {\n  all?: boolean;\n  family?: number;\n  hints?: number;\n  order?: 'ipv4first' | 'ipv6first' | 'verbatim';\n  verbatim?: boolean;\n};\n\ntype Lookup = (\n  hostname: string,\n  options: LookupOptions & { all: true },\n  callback: (\n    error: NodeJS.ErrnoException | null,\n    addresses: LookupAddress[],\n  ) => void,\n) => void;\n\ntype LookupAllCallback = (\n  error: NodeJS.ErrnoException | null,\n  addresses: LookupAddress[],\n) => void;\n\ntype LookupOneCallback = (\n  error: NodeJS.ErrnoException | null,\n  address: string,\n  family: number,\n) => void;\n\ntype SafeLookup = {\n  (\n    hostname: string,\n    options: LookupOptions & { all: true },\n    callback: LookupAllCallback,\n  ): void;\n  (\n    hostname: string,\n    options: LookupOptions & { all?: false },\n    callback: LookupOneCallback,\n  ): void;\n};\n\n/**\n * Creates a DNS lookup hook that validates every returned address before\n * returning the callback shape requested by the HTTP connector. Because\n * resolution and validation happen inside the connector, the socket is pinned\n * to the validated result and DNS rebinding cannot introduce a second lookup.\n */\nexport function createSafeLookup(lookup: Lookup): SafeLookup {\n  return ((\n    hostname: string,\n    options: LookupOptions,\n    callback: LookupAllCallback | LookupOneCallback,\n  ): void => {\n    lookup(hostname, { ...options, all: true }, (error, addresses) => {\n      if (error) {\n        (callback as (error: Error) => void)(error);\n        return;\n      }\n\n      try {\n        const [firstAddress] = addresses;\n\n        if (firstAddress == null) {\n          throw new Error(`Hostname ${hostname} did not resolve to an address`);\n        }\n\n        for (const { address, family } of addresses) {\n          validateDownloadAddress({ address, family, hostname });\n        }\n\n        if (options.all === true) {\n          (callback as LookupAllCallback)(null, addresses);\n        } else {\n          (callback as LookupOneCallback)(\n            null,\n            firstAddress.address,\n            firstAddress.family,\n          );\n        }\n      } catch (error) {\n        (callback as (error: Error) => void)(\n          error instanceof Error ? error : new Error(String(error)),\n        );\n      }\n    });\n  }) as SafeLookup;\n}\n\nlet safeNodeFetchPromise: Promise<FetchFunction> | undefined;\n\nexport function isNodeRuntime(): boolean {\n  const runtimeProcess = globalThis.process as\n    | {\n        release?: { name?: string };\n        title?: string;\n        versions?: { bun?: string; deno?: string };\n      }\n    | undefined;\n\n  // Node-compatible process objects do not imply support for Node DNS/socket\n  // hooks. Workers identifies itself as workerd, including without navigator.\n  return (\n    runtimeProcess?.release?.name === 'node' &&\n    runtimeProcess.versions?.bun == null &&\n    runtimeProcess.versions?.deno == null &&\n    runtimeProcess.title !== 'workerd' &&\n    (globalThis as { EdgeRuntime?: unknown }).EdgeRuntime == null\n  );\n}\n\nexport async function getDefaultDownloadFetch(): Promise<FetchFunction> {\n  if (!isNodeRuntime()) {\n    return globalThis.fetch;\n  }\n\n  // Global fetch wrappers cannot be relied on to preserve the dispatcher\n  // that pins connections to validated DNS results.\n  return (safeNodeFetchPromise ??= Promise.resolve().then(createSafeNodeFetch));\n}\n\nfunction createSafeNodeFetch(): FetchFunction {\n  // Load Node-only modules indirectly so browser bundlers do not pull undici\n  // and Node built-ins into the browser-facing provider-utils entry point.\n  const { createRequire } = loadBuiltinModule<NodeModule>('node:module');\n  const { lookup } = loadBuiltinModule<NodeDns>('node:dns');\n  const { Agent, fetch } = createRequire(getCurrentModulePath())(\n    'undici',\n  ) as Undici;\n\n  const dispatcher = new Agent({\n    connect: {\n      lookup: createSafeLookup(lookup as Lookup) as never,\n    },\n  });\n\n  return ((input, init) =>\n    fetch(\n      input as Parameters<typeof fetch>[0],\n      {\n        ...init,\n        dispatcher,\n      } as Parameters<typeof fetch>[1],\n    ) as unknown as Promise<Response>) satisfies FetchFunction;\n}\n\nfunction loadBuiltinModule<T>(id: string): T {\n  const processWithBuiltins = globalThis.process as\n    | {\n        getBuiltinModule?: (id: string) => unknown;\n      }\n    | undefined;\n  const builtinModule = processWithBuiltins?.getBuiltinModule?.(id);\n\n  if (builtinModule == null) {\n    throw new Error(`Node.js built-in module ${id} is unavailable`);\n  }\n\n  return builtinModule as T;\n}\n\nfunction getCurrentModulePath(): string {\n  // `import.meta.url` breaks when provider-utils is rebundled as CommonJS.\n  // The caller frame points at this package when loaded directly and at the\n  // consuming bundle when inlined, giving createRequire the correct base path.\n  const originalPrepareStackTrace = Error.prepareStackTrace;\n\n  try {\n    Error.prepareStackTrace = (_error, callSites) => callSites as never;\n\n    const error = new Error('Capture current module path');\n    Error.captureStackTrace(error, getCurrentModulePath);\n    const [caller] = error.stack as unknown as NodeJS.CallSite[];\n    const fileName = caller?.getFileName();\n\n    if (fileName == null) {\n      throw new Error('Unable to determine the current module path');\n    }\n\n    return fileName;\n  } finally {\n    Error.prepareStackTrace = originalPrepareStackTrace;\n  }\n}\n","/**\n * Request headers stripped before fetching an untrusted URL: host/virtual-host\n * routing, proxy/origin spoofing, cloud-metadata, cookies, and hop-by-hop\n * transport headers (RFC 7230 §6.1).\n *\n * `Authorization` and other credential-bearing caller headers (e.g. `x-key`)\n * are intentionally not listed — they're needed on the first hop of some\n * provider polling calls. Instead, all caller headers except the user-agent are\n * dropped on a cross-origin redirect (see `fetch-with-validated-redirects`).\n */\nconst BLOCKED_REQUEST_HEADERS: readonly string[] = [\n  // Hop-by-hop / transport (RFC 7230 §6.1)\n  'connection',\n  'keep-alive',\n  'te',\n  'trailer',\n  'transfer-encoding',\n  'upgrade',\n\n  // Host / virtual-host routing\n  'host',\n\n  // Proxy / origin spoofing\n  'forwarded',\n  'proxy-authorization',\n  'via',\n  'x-forwarded-for',\n  'x-forwarded-host',\n  'x-forwarded-proto',\n  'x-real-ip',\n\n  // Cloud metadata (GCP, AWS IMDSv1/v2, Azure, Alibaba, DigitalOcean)\n  'metadata',\n  'metadata-flavor',\n  'x-aws-ec2-metadata-token',\n  'x-metadata-token',\n\n  // Session / cookie\n  'cookie',\n  'set-cookie',\n];\n\n/**\n * Returns a fresh `Headers` built from `input` with {@link BLOCKED_REQUEST_HEADERS}\n * removed. The input is never mutated.\n */\nexport function sanitizeRequestHeaders(input: HeadersInit): Headers {\n  const headers = new Headers(input);\n  for (const name of BLOCKED_REQUEST_HEADERS) {\n    headers.delete(name);\n  }\n  return headers;\n}\n","import { cancelResponseBody } from './cancel-response-body';\nimport { DownloadError } from './download-error';\nimport type { FetchFunction } from './fetch-function';\nimport { isBrowserRuntime } from './is-browser-runtime';\nimport { isSameOrigin } from './is-same-origin';\nimport { getDefaultDownloadFetch } from './safe-node-fetch';\nimport { sanitizeRequestHeaders } from './sanitize-request-headers';\nimport { validateDownloadUrl } from './validate-download-url';\n\nconst MAX_DOWNLOAD_REDIRECTS = 10;\n\n// Redirect status codes per the fetch spec (https://fetch.spec.whatwg.org/#redirect-status).\n// Notably 300 (Multiple Choices) and 304 (Not Modified) are NOT redirects,\n// even when a server attaches a Location header.\nconst REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308]);\n\nasync function getValidatedFetch(\n  customFetch: FetchFunction | undefined,\n): Promise<FetchFunction> {\n  // Callers commonly pass globalThis.fetch through several abstraction\n  // layers. Preserve the DNS-pinned Node.js default in that case rather than\n  // accidentally treating it as an intentionally custom fetch.\n  return customFetch == null || customFetch === globalThis.fetch\n    ? await getDefaultDownloadFetch()\n    : customFetch;\n}\n\n/**\n * Fetches one validated URL without following redirects.\n *\n * On Node.js, the default fetch validates and pins DNS results at connect time.\n * An injected fetch is responsible for equivalent connect-time validation.\n * Redirects are rejected by default. Callers using `redirect: 'manual'` must\n * validate the Location target before issuing another request.\n */\nexport async function fetchWithValidatedEndpoint({\n  url,\n  init,\n  fetch: customFetch,\n  trustedOrigin,\n  redirect = 'error',\n}: {\n  url: string | URL;\n  init?: RequestInit;\n  fetch?: FetchFunction;\n  /**\n   * A developer-configured origin that may legitimately resolve to a private\n   * address. This must never be derived from untrusted response data.\n   */\n  trustedOrigin?: string;\n  redirect?: 'error' | 'manual';\n}): Promise<Response> {\n  const urlText = url.toString();\n  const isTrusted =\n    trustedOrigin !== undefined && isSameOrigin(urlText, trustedOrigin);\n\n  if (!isTrusted) {\n    validateDownloadUrl(urlText);\n  }\n\n  const fetch =\n    isTrusted && customFetch != null\n      ? customFetch\n      : isTrusted\n        ? globalThis.fetch\n        : await getValidatedFetch(customFetch);\n\n  return await fetch(url, {\n    ...init,\n    redirect,\n  });\n}\n\n/**\n * Fetches a URL while enforcing the download guard on every hop.\n *\n * Redirects are followed manually (`redirect: 'manual'`) so each hop is\n * validated with {@link validateDownloadUrl} *before* it is requested. Relying\n * on the default `redirect: 'follow'` would issue the request to a redirect\n * target (e.g. an internal address) before we ever see its URL, defeating the\n * guard.\n *\n * Request headers are also protected: {@link sanitizeRequestHeaders} strips\n * proxy/metadata/cookie/hop-by-hop headers before the first request, and all\n * caller headers except `User-Agent` are dropped on a cross-origin redirect.\n * The fetch spec only strips `Authorization` on cross-origin redirects because\n * in a browser, CORS preflighting protects custom headers; there is no CORS on\n * the server, so provider API keys carried in custom headers (e.g. `x-key`)\n * must be dropped here as well.\n *\n * A `redirect: 'manual'` request yields an unreadable opaque response in the\n * browser (and in other spec-compliant fetch implementations), so the redirect\n * target cannot be validated here. In a real browser this is safe to follow\n * natively because reaching an internal network is not possible (fetch is\n * constrained by CORS and cannot reach a server's internal network or\n * cloud-metadata). On any other runtime we cannot validate the hop, so we fail\n * closed rather than follow it blindly and bypass the guard.\n *\n * A hop that is same-origin with `trustedOrigin` (the developer-configured\n * provider endpoint) skips target validation: that origin is exactly what an\n * unvalidated, config-derived request would fetch anyway, and validating it\n * would break legitimate self-hosted / localhost deployments whose response\n * URLs point back at the configured host. Hops on any other origin are always\n * validated.\n *\n * The returned response is the final (non-redirect) response. The caller is\n * responsible for checking `response.ok` and reading the body.\n *\n * On Node.js, the default fetch resolves every hostname through a validating\n * lookup hook and passes those exact addresses to the connector, preventing\n * hostname-to-private-IP and DNS-rebinding bypasses. An injected fetch is\n * responsible for equivalent connect-time validation. Other runtimes should\n * constrain egress at the network layer when handling untrusted URLs.\n *\n * @throws DownloadError if a hop is unsafe, the redirect limit is exceeded, or\n * a redirect cannot be validated on a non-browser runtime.\n */\nexport async function fetchWithValidatedRedirects({\n  url,\n  headers,\n  abortSignal,\n  maxRedirects = MAX_DOWNLOAD_REDIRECTS,\n  fetch: customFetch,\n  trustedOrigin,\n}: {\n  url: string;\n  headers?: HeadersInit;\n  abortSignal?: AbortSignal;\n  maxRedirects?: number;\n  fetch?: FetchFunction;\n  /**\n   * A developer-configured origin (e.g. the provider's `baseURL`) whose hops\n   * skip target validation. Must never be derived from response data.\n   */\n  trustedOrigin?: string;\n}): Promise<Response> {\n  // Left undefined when no headers are provided (bare request); otherwise\n  // sanitized once and replaced on a cross-origin hop (credential drop below).\n  let currentHeaders =\n    headers === undefined ? undefined : sanitizeRequestHeaders(headers);\n\n  const perHopInit = (redirect: RequestRedirect): RequestInit => {\n    const init: RequestInit = { signal: abortSignal, redirect };\n    if (currentHeaders !== undefined) {\n      // Snapshot per hop: the platform fetch reads headers synchronously, but\n      // an injected fetch may defer, and hops between credential drops would\n      // otherwise share one instance.\n      init.headers = new Headers(currentHeaders);\n    }\n    return init;\n  };\n\n  let currentUrl = url;\n  // The bound also acts as a backstop against an unterminated redirect chain.\n  for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {\n    // The developer-configured origin is trusted by definition; validating it\n    // would reject legitimate self-hosted / localhost deployments.\n    const isTrustedHop =\n      trustedOrigin !== undefined && isSameOrigin(currentUrl, trustedOrigin);\n\n    if (!isTrustedHop) {\n      validateDownloadUrl(currentUrl);\n    }\n\n    const fetch =\n      isTrustedHop && customFetch != null\n        ? customFetch\n        : isTrustedHop\n          ? globalThis.fetch\n          : await getValidatedFetch(customFetch);\n\n    const response = await fetch(currentUrl, perHopInit('manual'));\n\n    if (response.type === 'opaqueredirect') {\n      if (!isBrowserRuntime()) {\n        throw new DownloadError({\n          url,\n          message: `Redirect from ${currentUrl} could not be validated and was blocked`,\n        });\n      }\n      return await fetch(currentUrl, perHopInit('follow'));\n    }\n\n    const location = response.headers?.get('location');\n    if (REDIRECT_STATUS_CODES.has(response.status) && location) {\n      // Release the redirect response's connection before moving to the next\n      // hop. Whether that hop is followed or rejected by the guard, an\n      // unconsumed 3xx body would leak the underlying socket.\n      await cancelResponseBody(response);\n      const nextUrl = new URL(location, currentUrl).toString();\n\n      // Drop all caller headers except the user-agent before following a\n      // redirect that crosses origin. Only stripping Authorization (as the\n      // fetch spec does) is not enough on the server: providers authenticate\n      // with custom headers too (e.g. `x-key`), and without CORS there is\n      // nothing else stopping them from riding to a foreign host.\n      if (currentHeaders !== undefined && !isSameOrigin(nextUrl, currentUrl)) {\n        const userAgent = currentHeaders.get('user-agent');\n        currentHeaders = new Headers(\n          userAgent == null ? undefined : { 'user-agent': userAgent },\n        );\n      }\n\n      currentUrl = nextUrl;\n      continue;\n    }\n\n    return response;\n  }\n\n  throw new DownloadError({\n    url,\n    message: `Too many redirects (max ${maxRedirects})`,\n  });\n}\n","import { cancelResponseBody } from './cancel-response-body';\nimport { DownloadError } from './download-error';\n\n/**\n * Default maximum download size: 2 GiB.\n *\n * `fetch().arrayBuffer()` has ~2x peak memory overhead (undici buffers the\n * body internally, then creates the JS ArrayBuffer), so very large downloads\n * risk exceeding the default V8 heap limit on 64-bit systems and terminating\n * the process with an out-of-memory error.\n *\n * Setting this limit converts an unrecoverable OOM crash into a catchable\n * `DownloadError`.\n */\nexport const DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;\n\n/**\n * Reads a fetch Response body with a size limit to prevent memory exhaustion.\n *\n * Checks the Content-Length header for early rejection, then reads the body\n * incrementally via ReadableStream and aborts with a DownloadError when the\n * limit is exceeded.\n *\n * @param response - The fetch Response to read.\n * @param url - The URL being downloaded (used in error messages).\n * @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.\n * @returns A Uint8Array containing the response body.\n * @throws DownloadError if the response exceeds maxBytes.\n */\nexport async function readResponseWithSizeLimit({\n  response,\n  url,\n  maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE,\n}: {\n  response: Response;\n  url: string;\n  maxBytes?: number;\n}): Promise<Uint8Array> {\n  // Early rejection based on Content-Length header\n  const contentLength = response.headers.get('content-length');\n  if (contentLength != null) {\n    const length = parseInt(contentLength, 10);\n    if (!isNaN(length) && length > maxBytes) {\n      // Cancel the body so the underlying connection is released back to the\n      // pool instead of being left open until the socket is exhausted.\n      await cancelResponseBody(response);\n      throw new DownloadError({\n        url,\n        message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`,\n      });\n    }\n  }\n\n  const body = response.body;\n\n  // Handle missing body (empty responses)\n  if (body == null) {\n    return new Uint8Array(0);\n  }\n\n  const reader = body.getReader();\n  const chunks: Uint8Array[] = [];\n  let totalBytes = 0;\n\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n\n      if (done) {\n        break;\n      }\n\n      totalBytes += value.length;\n\n      if (totalBytes > maxBytes) {\n        throw new DownloadError({\n          url,\n          message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`,\n        });\n      }\n\n      chunks.push(value);\n    }\n  } finally {\n    try {\n      await reader.cancel();\n    } catch {\n      // Ignore cancel errors so the original rejection is preserved.\n    } finally {\n      reader.releaseLock();\n    }\n  }\n\n  // Concatenate chunks into a single Uint8Array\n  const result = new Uint8Array(totalBytes);\n  let offset = 0;\n  for (const chunk of chunks) {\n    result.set(chunk, offset);\n    offset += chunk.length;\n  }\n\n  return result;\n}\n","import { cancelResponseBody } from './cancel-response-body';\nimport { DownloadError } from './download-error';\nimport { fetchWithValidatedRedirects } from './fetch-with-validated-redirects';\nimport {\n  readResponseWithSizeLimit,\n  DEFAULT_MAX_DOWNLOAD_SIZE,\n} from './read-response-with-size-limit';\n\n/**\n * Download a file from a URL and return it as a Blob.\n *\n * @param url - The URL to download from.\n * @param options - Optional settings for the download.\n * @param options.maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.\n * @param options.abortSignal - An optional abort signal to cancel the download.\n * @returns A Promise that resolves to the downloaded Blob.\n *\n * @throws DownloadError if the download fails or exceeds maxBytes.\n */\nexport async function downloadBlob(\n  url: string,\n  options?: { maxBytes?: number; abortSignal?: AbortSignal },\n): Promise<Blob> {\n  try {\n    const response = await fetchWithValidatedRedirects({\n      url,\n      abortSignal: options?.abortSignal,\n    });\n\n    if (!response.ok) {\n      // Release the connection before rejecting so an error status from an\n      // attacker-controlled origin cannot leak open sockets.\n      await cancelResponseBody(response);\n      throw new DownloadError({\n        url,\n        statusCode: response.status,\n        statusText: response.statusText,\n      });\n    }\n\n    const data = await readResponseWithSizeLimit({\n      response,\n      url,\n      maxBytes: options?.maxBytes ?? DEFAULT_MAX_DOWNLOAD_SIZE,\n    });\n\n    const contentType = response.headers.get('content-type') ?? undefined;\n    return new Blob([data], contentType ? { type: contentType } : undefined);\n  } catch (error) {\n    if (DownloadError.isInstance(error)) {\n      throw error;\n    }\n\n    throw new DownloadError({ url, cause: error });\n  }\n}\n","/**\n * Symbol for exposing the UTF-8 input byte budget of an embedding model.\n *\n * This capability is experimental and intentionally lives outside the versioned\n * embedding model specification.\n */\nexport const EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL = Symbol.for(\n  'vercel.ai.embeddingModel.maxInputBytesPerCall',\n);\n","/**\n * Extracts a 1-based inclusive line range from `text`, auto-detecting the\n * file's line ending (`\\r\\n`, `\\n`, or `\\r`, in that priority).\n *\n * Mixed line endings are not supported: detection picks one and uses it for\n * both the split and the rejoin, so files that mix conventions will not slice\n * cleanly. When neither `startLine` nor `endLine` is provided, the input is\n * returned unchanged. `endLine` past EOF clamps to the last line.\n */\nexport function extractLines({\n  text,\n  startLine,\n  endLine,\n}: {\n  text: string;\n  startLine?: number;\n  endLine?: number;\n}): string {\n  if (startLine == null && endLine == null) return text;\n  const lineEnding = text.includes('\\r\\n')\n    ? '\\r\\n'\n    : text.includes('\\n')\n      ? '\\n'\n      : text.includes('\\r')\n        ? '\\r'\n        : '\\n';\n  const lines = text.split(lineEnding);\n  const start = Math.max(1, startLine ?? 1) - 1;\n  const end = Math.min(lines.length, endLine ?? lines.length);\n  return lines.slice(start, end).join(lineEnding);\n}\n","/**\n * Filters `null` and `undefined` values out of a list of values.\n *\n * @param values - The values to filter.\n * @returns A new array containing only non-nullish values.\n */\nexport function filterNullable<T>(\n  ...values: Array<T | undefined | null>\n): Array<T> {\n  return values.filter((value): value is NonNullable<T> => value != null);\n}\n","import { InvalidArgumentError } from '@ai-sdk/provider';\n\n/**\n * Creates an ID generator.\n * The total length of the ID is the sum of the prefix, separator, and random part length.\n * Not cryptographically secure.\n *\n * @param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.\n * @param prefix - The prefix of the ID to generate. Optional.\n * @param separator - The separator between the prefix and the random part of the ID. Default: '-'.\n * @param size - The size of the random part of the ID to generate. Default: 16.\n */\nexport const createIdGenerator = ({\n  prefix,\n  size = 16,\n  alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',\n  separator = '-',\n}: {\n  prefix?: string;\n  separator?: string;\n  size?: number;\n  alphabet?: string;\n} = {}): IdGenerator => {\n  const generator = () => {\n    const alphabetLength = alphabet.length;\n    const chars = new Array(size);\n    for (let i = 0; i < size; i++) {\n      chars[i] = alphabet[(Math.random() * alphabetLength) | 0];\n    }\n    return chars.join('');\n  };\n\n  if (prefix == null) {\n    return generator;\n  }\n\n  // check that the prefix is not part of the alphabet (otherwise prefix checking can fail randomly)\n  if (alphabet.includes(separator)) {\n    throw new InvalidArgumentError({\n      argument: 'separator',\n      message: `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`,\n    });\n  }\n\n  return () => `${prefix}${separator}${generator()}`;\n};\n\n/**\n * A function that generates an ID.\n */\nexport type IdGenerator = () => string;\n\n/**\n * Generates a 16-character random string to use for IDs.\n * Not cryptographically secure.\n */\nexport const generateId = createIdGenerator();\n","export { getErrorMessage } from '@ai-sdk/provider';\n","import { APICallError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport { fetchWithValidatedRedirects } from './fetch-with-validated-redirects';\nimport type { FetchFunction } from './fetch-function';\nimport { handleFetchError } from './handle-fetch-error';\nimport { isAbortError } from './is-abort-error';\nimport { isSameOrigin } from './is-same-origin';\nimport type { ResponseHandler } from './response-handler';\nimport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nimport { withUserAgentSuffix } from './with-user-agent-suffix';\nimport { VERSION } from './version';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => globalThis.fetch;\n\nexport const getFromApi = async <T>({\n  url,\n  headers = {},\n  successfulResponseHandler,\n  failedResponseHandler,\n  abortSignal,\n  fetch,\n  validateUrl,\n  credentialedOrigin,\n  trustedOrigin,\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  failedResponseHandler: ResponseHandler<Error>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n  /**\n   * Set `true` when `url` is untrusted (e.g. taken from a provider response\n   * body): it is routed through {@link fetchWithValidatedRedirects}, which\n   * rejects private/loopback/link-local targets and re-validates redirect\n   * hops; blocked URLs throw `DownloadError`. Set `false` only for URLs built\n   * from a developer-configured endpoint.\n   *\n   * Optional for backwards compatibility with existing callers; omitting it\n   * behaves like `false` (no validation). Provider code in this repository\n   * must always pass it explicitly so every call site makes a visible trust\n   * decision — see `contributing/secure-url-handling.md`.\n   */\n  validateUrl?: boolean;\n  /**\n   * When set, `headers` are sent only if `url` is same-origin with this origin\n   * (the user-agent suffix is always kept). Pass the provider's configured\n   * base URL alongside `validateUrl: true` so credentials never ride a request\n   * to a response-supplied host on a different origin (e.g. a CDN). Redirects\n   * that later cross origin drop all caller headers regardless (see\n   * {@link fetchWithValidatedRedirects}).\n   */\n  credentialedOrigin?: string;\n  /**\n   * A developer-configured origin (e.g. the provider's `baseURL`) that is\n   * exempt from URL validation when `validateUrl` is `true`. A response URL\n   * (or redirect hop) that is same-origin with it is fetched without target\n   * validation — it points at exactly the host a config-derived\n   * `validateUrl: false` request would fetch anyway, so blocking it would\n   * only break legitimate self-hosted / localhost deployments whose response\n   * URLs point back at the configured host. Hops on any other origin are\n   * still validated. Must never be derived from response data.\n   */\n  trustedOrigin?: string;\n}) => {\n  try {\n    const requestFetch = fetch ?? getOriginalFetch();\n\n    // Withhold caller headers when the URL is not same-origin with the origin\n    // allowed to receive credentials; the user-agent suffix is still applied.\n    const outgoingHeaders =\n      credentialedOrigin !== undefined && !isSameOrigin(url, credentialedOrigin)\n        ? {}\n        : headers;\n\n    const requestHeaders = withUserAgentSuffix(\n      outgoingHeaders,\n      `ai-sdk/provider-utils/${VERSION}`,\n      getRuntimeEnvironmentUserAgent(),\n    );\n\n    const response = validateUrl\n      ? await fetchWithValidatedRedirects({\n          url,\n          headers: requestHeaders,\n          abortSignal,\n          fetch,\n          trustedOrigin,\n        })\n      : await requestFetch(url, {\n          method: 'GET',\n          headers: requestHeaders,\n          signal: abortSignal,\n        });\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.ok) {\n      let errorInformation: {\n        value: Error;\n        responseHeaders?: Record<string, string> | undefined;\n      };\n\n      try {\n        errorInformation = await failedResponseHandler({\n          response,\n          url,\n          requestBodyValues: {},\n        });\n      } catch (error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n\n        throw new APICallError({\n          message: 'Failed to process error response',\n          cause: error,\n          statusCode: response.status,\n          url,\n          responseHeaders,\n          requestBodyValues: {},\n        });\n      }\n\n      throw errorInformation.value;\n    }\n\n    try {\n      return await successfulResponseHandler({\n        response,\n        url,\n        requestBodyValues: {},\n      });\n    } catch (error) {\n      if (error instanceof Error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n      }\n\n      throw new APICallError({\n        message: 'Failed to process successful response',\n        cause: error,\n        statusCode: response.status,\n        url,\n        responseHeaders,\n        requestBodyValues: {},\n      });\n    }\n  } catch (error) {\n    throw handleFetchError({ error, url, requestBodyValues: {} });\n  }\n};\n","import type {\n  JSONSchema7,\n  LanguageModelV4Message,\n  LanguageModelV4Prompt,\n} from '@ai-sdk/provider';\n\nconst DEFAULT_SCHEMA_PREFIX = 'JSON schema:';\nconst DEFAULT_SCHEMA_SUFFIX =\n  'You MUST answer with a JSON object that matches the JSON schema above.';\nconst DEFAULT_GENERIC_SUFFIX = 'You MUST answer with JSON.';\n\nexport function injectJsonInstruction({\n  prompt,\n  schema,\n  schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : undefined,\n  schemaSuffix = schema != null\n    ? DEFAULT_SCHEMA_SUFFIX\n    : DEFAULT_GENERIC_SUFFIX,\n}: {\n  prompt?: string;\n  schema?: JSONSchema7;\n  schemaPrefix?: string;\n  schemaSuffix?: string;\n}): string {\n  return [\n    prompt != null && prompt.length > 0 ? prompt : undefined,\n    prompt != null && prompt.length > 0 ? '' : undefined, // add a newline if prompt is not null\n    schemaPrefix,\n    schema != null ? JSON.stringify(schema) : undefined,\n    schemaSuffix,\n  ]\n    .filter(line => line != null)\n    .join('\\n');\n}\n\nexport function injectJsonInstructionIntoMessages({\n  messages,\n  schema,\n  schemaPrefix,\n  schemaSuffix,\n}: {\n  messages: LanguageModelV4Prompt;\n  schema?: JSONSchema7;\n  schemaPrefix?: string;\n  schemaSuffix?: string;\n}): LanguageModelV4Prompt {\n  const systemMessage: LanguageModelV4Message =\n    messages[0]?.role === 'system'\n      ? { ...messages[0] }\n      : { role: 'system', content: '' };\n\n  systemMessage.content = injectJsonInstruction({\n    prompt: systemMessage.content,\n    schema,\n    schemaPrefix,\n    schemaSuffix,\n  });\n\n  return [\n    systemMessage,\n    ...(messages[0]?.role === 'system' ? messages.slice(1) : messages),\n  ];\n}\n","/**\n * Type-guard for Node.js `Buffer` instances.\n *\n * Uses optional chaining on `globalThis.Buffer` so it returns `false` in\n * runtimes where `Buffer` is not available (e.g. CloudFlare Workers).\n */\nexport function isBuffer(value: unknown): value is Buffer {\n  return globalThis.Buffer?.isBuffer(value) ?? false;\n}\n","/**\n * Type guard that checks whether a value is not `null` or `undefined`.\n *\n * @template T - The type of the value to check.\n * @param value - The value to check.\n * @returns `true` if the value is neither `null` nor `undefined`, otherwise `false`.\n */\nexport function isNonNullable<T>(\n  value: T | undefined | null,\n): value is NonNullable<T> {\n  return value != null;\n}\n","import type { SharedV4ProviderReference } from '@ai-sdk/provider';\nimport { isBuffer } from './is-buffer';\n\n/**\n * Checks whether a value is a provider reference (a mapping of provider names\n * to provider-specific identifiers) as opposed to raw bytes, a URL, or a\n * tagged `{ type: ... }` object.\n */\nexport function isProviderReference(\n  data: unknown,\n): data is SharedV4ProviderReference {\n  return (\n    typeof data === 'object' &&\n    data !== null &&\n    !(data instanceof Uint8Array) &&\n    !(data instanceof URL) &&\n    !(data instanceof ArrayBuffer) &&\n    !isBuffer(data) &&\n    !('type' in data)\n  );\n}\n","/**\n * Checks whether a value is a non-null, non-array object.\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n  return value != null && typeof value === 'object' && !Array.isArray(value);\n}\n","/**\n * Checks if the given URL is supported natively by the model.\n *\n * @param mediaType - The media type of the URL. Case-sensitive. May be a full\n *                    `type/subtype`, a wildcard `type/*`, or just the\n *                    top-level segment (e.g. `image`).\n * @param url - The URL to check.\n * @param supportedUrls - A record where keys are case-sensitive media types (or '*')\n *                        and values are arrays of RegExp patterns for URLs.\n *\n * @returns `true` if the URL matches a pattern under the specific media type\n *          or the wildcard '*', `false` otherwise.\n */\nexport function isUrlSupported({\n  mediaType,\n  url,\n  supportedUrls,\n}: {\n  mediaType: string;\n  url: string;\n  supportedUrls: Record<string, RegExp[]>;\n}): boolean {\n  // standardize media type and url to lower case\n  url = url.toLowerCase();\n  mediaType = mediaType.toLowerCase();\n\n  const isTopLevelOnly = !mediaType.includes('/');\n\n  return (\n    Object.entries(supportedUrls)\n      // standardize supported url map into lowercase prefixes:\n      .map(([key, value]) => {\n        const mediaType = key.toLowerCase();\n        return mediaType === '*' || mediaType === '*/*'\n          ? { mediaTypePrefix: '', regexes: value }\n          : { mediaTypePrefix: mediaType.replace(/\\*/, ''), regexes: value };\n      })\n      // gather all regexp pattern from matched media type prefixes:\n      .filter(({ mediaTypePrefix }) => {\n        if (mediaTypePrefix === '') {\n          return true;\n        }\n        // For a top-level-only media type (e.g. `image`), we cannot determine\n        // whether a specific subtype (e.g. `image/png`) would apply, so we\n        // only match the corresponding `type/*` prefix exactly.\n        if (isTopLevelOnly) {\n          return `${mediaType}/` === mediaTypePrefix;\n        }\n        return mediaType.startsWith(mediaTypePrefix);\n      })\n      .flatMap(({ regexes }) => regexes)\n      // check if any pattern matches the url:\n      .some(pattern => testRegExpFromStart(pattern, url))\n  );\n}\n\nfunction testRegExpFromStart(pattern: RegExp, value: string): boolean {\n  if (!pattern.global && !pattern.sticky) {\n    return pattern.test(value);\n  }\n\n  // Global and sticky regexes retain match state in lastIndex.\n  // Evaluate from the start without changing caller-owned state.\n  const lastIndex = pattern.lastIndex;\n  pattern.lastIndex = 0;\n\n  try {\n    return pattern.test(value);\n  } finally {\n    pattern.lastIndex = lastIndex;\n  }\n}\n","import { LoadAPIKeyError } from '@ai-sdk/provider';\n\nexport function loadApiKey({\n  apiKey,\n  environmentVariableName,\n  apiKeyParameterName = 'apiKey',\n  description,\n}: {\n  apiKey: string | undefined;\n  environmentVariableName: string;\n  apiKeyParameterName?: string;\n  description: string;\n}): string {\n  if (typeof apiKey === 'string') {\n    return apiKey;\n  }\n\n  if (apiKey != null) {\n    throw new LoadAPIKeyError({\n      message: `${description} API key must be a string.`,\n    });\n  }\n\n  if (typeof process === 'undefined') {\n    throw new LoadAPIKeyError({\n      message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.`,\n    });\n  }\n\n  apiKey = process.env[environmentVariableName];\n\n  if (apiKey == null) {\n    throw new LoadAPIKeyError({\n      message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`,\n    });\n  }\n\n  if (typeof apiKey !== 'string') {\n    throw new LoadAPIKeyError({\n      message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`,\n    });\n  }\n\n  return apiKey;\n}\n","/**\n * Loads an optional `string` setting from the environment or a parameter.\n *\n * @param settingValue - The setting value.\n * @param environmentVariableName - The environment variable name.\n * @returns The setting value.\n */\nexport function loadOptionalSetting({\n  settingValue,\n  environmentVariableName,\n}: {\n  settingValue: string | undefined;\n  environmentVariableName: string;\n}): string | undefined {\n  if (typeof settingValue === 'string') {\n    return settingValue;\n  }\n\n  if (settingValue != null || typeof process === 'undefined') {\n    return undefined;\n  }\n\n  settingValue = process.env[environmentVariableName];\n\n  if (settingValue == null || typeof settingValue !== 'string') {\n    return undefined;\n  }\n\n  return settingValue;\n}\n","import { LoadSettingError } from '@ai-sdk/provider';\n\n/**\n * Loads a `string` setting from the environment or a parameter.\n *\n * @param settingValue - The setting value.\n * @param environmentVariableName - The environment variable name.\n * @param settingName - The setting name.\n * @param description - The description of the setting.\n * @returns The setting value.\n */\nexport function loadSetting({\n  settingValue,\n  environmentVariableName,\n  settingName,\n  description,\n}: {\n  settingValue: string | undefined;\n  environmentVariableName: string;\n  settingName: string;\n  description: string;\n}): string {\n  if (typeof settingValue === 'string') {\n    return settingValue;\n  }\n\n  if (settingValue != null) {\n    throw new LoadSettingError({\n      message: `${description} setting must be a string.`,\n    });\n  }\n\n  if (typeof process === 'undefined') {\n    throw new LoadSettingError({\n      message:\n        `${description} setting is missing. ` +\n        `Pass it using the '${settingName}' parameter. ` +\n        `Environment variables are not supported in this environment.`,\n    });\n  }\n\n  settingValue = process.env[environmentVariableName];\n\n  if (settingValue == null) {\n    throw new LoadSettingError({\n      message:\n        `${description} setting is missing. ` +\n        `Pass it using the '${settingName}' parameter ` +\n        `or the ${environmentVariableName} environment variable.`,\n    });\n  }\n\n  if (typeof settingValue !== 'string') {\n    throw new LoadSettingError({\n      message:\n        `${description} setting must be a string. ` +\n        `The value of the ${environmentVariableName} environment variable is not a string.`,\n    });\n  }\n\n  return settingValue;\n}\n","import type {\n  LanguageModelV4CallOptions,\n  SharedV4Warning,\n} from '@ai-sdk/provider';\n\nexport type ReasoningLevel = Exclude<\n  LanguageModelV4CallOptions['reasoning'],\n  'none' | 'provider-default' | undefined\n>;\n\nexport function isCustomReasoning(\n  reasoning: LanguageModelV4CallOptions['reasoning'],\n): reasoning is Exclude<\n  LanguageModelV4CallOptions['reasoning'],\n  'provider-default' | undefined\n> {\n  return reasoning !== undefined && reasoning !== 'provider-default';\n}\n\n/**\n * Maps a top-level reasoning level to a provider-specific effort string using\n * the given effort map. Pushes a compatibility warning if the reasoning level\n * maps to a different string, or an unsupported warning if the level is not\n * present in the map.\n *\n * @returns The mapped effort string, or `undefined` if the level is not\n *   supported.\n */\nexport function mapReasoningToProviderEffort<T extends string>({\n  reasoning,\n  effortMap,\n  warnings,\n}: {\n  reasoning: ReasoningLevel;\n  effortMap: Partial<Record<ReasoningLevel, T>>;\n  warnings: SharedV4Warning[];\n}): T | undefined {\n  const mapped = effortMap[reasoning];\n\n  if (mapped == null) {\n    warnings.push({\n      type: 'unsupported',\n      feature: 'reasoning',\n      details: `reasoning \"${reasoning}\" is not supported by this model.`,\n    });\n    return undefined;\n  }\n\n  if (mapped !== reasoning) {\n    warnings.push({\n      type: 'compatibility',\n      feature: 'reasoning',\n      details: `reasoning \"${reasoning}\" is not directly supported by this model. mapped to effort \"${mapped}\".`,\n    });\n  }\n\n  return mapped;\n}\n\nconst DEFAULT_REASONING_BUDGET_PERCENTAGES: Record<ReasoningLevel, number> = {\n  minimal: 0.02,\n  low: 0.1,\n  medium: 0.3,\n  high: 0.6,\n  xhigh: 0.9,\n};\n\n/**\n * Maps a top-level reasoning level to an absolute token budget by multiplying\n * the model's max output tokens by a percentage from the budget percentages\n * map. The result is clamped between `minReasoningBudget` (default 1024) and\n * `maxReasoningBudget`. Pushes an unsupported warning if the level is not\n * present in the budget percentages map.\n *\n * @returns The computed token budget, or `undefined` if the level is not\n *   supported.\n */\nexport function mapReasoningToProviderBudget({\n  reasoning,\n  maxOutputTokens,\n  maxReasoningBudget,\n  minReasoningBudget = 1024,\n  budgetPercentages = DEFAULT_REASONING_BUDGET_PERCENTAGES,\n  warnings,\n}: {\n  reasoning: ReasoningLevel;\n  maxOutputTokens: number;\n  maxReasoningBudget: number;\n  minReasoningBudget?: number;\n  budgetPercentages?: Partial<Record<ReasoningLevel, number>>;\n  warnings: SharedV4Warning[];\n}): number | undefined {\n  const pct = budgetPercentages[reasoning];\n\n  if (pct == null) {\n    warnings.push({\n      type: 'unsupported',\n      feature: 'reasoning',\n      details: `reasoning \"${reasoning}\" is not supported by this model.`,\n    });\n    return undefined;\n  }\n\n  return Math.min(\n    maxReasoningBudget,\n    Math.max(minReasoningBudget, Math.round(maxOutputTokens * pct)),\n  );\n}\n","/**\n * Maps a media type to its corresponding file extension.\n * It was originally introduced to set a filename for audio file uploads\n * in https://github.com/vercel/ai/pull/8159.\n *\n * @param mediaType The media type to map.\n * @returns The corresponding file extension\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types\n */\nexport function mediaTypeToExtension(mediaType: string) {\n  const [_type, subtype = ''] = mediaType.toLowerCase().split('/');\n\n  return (\n    {\n      mpeg: 'mp3',\n      'x-wav': 'wav',\n      opus: 'ogg',\n      mp4: 'm4a',\n      'x-m4a': 'm4a',\n    }[subtype] ?? subtype\n  );\n}\n","import type { Experimental_BatchV4Status as BatchV4Status } from '@ai-sdk/provider';\n\n/**\n * Normalizes complete batch request counts.\n *\n * Returns `undefined` when any count is missing, is not a non-negative safe\n * integer, or when the item counts do not add up to the total.\n */\nexport function normalizeBatchRequestCounts({\n  total,\n  pending,\n  completed,\n  failed,\n}: {\n  total: number | null | undefined;\n  pending: number | null | undefined;\n  completed: number | null | undefined;\n  failed: number | null | undefined;\n}): BatchV4Status['requestCounts'] | undefined {\n  if (\n    isNonNegativeSafeInteger(total) &&\n    isNonNegativeSafeInteger(pending) &&\n    isNonNegativeSafeInteger(completed) &&\n    isNonNegativeSafeInteger(failed) &&\n    pending + completed + failed === total\n  ) {\n    return {\n      total,\n      pending,\n      completed,\n      failed,\n    };\n  }\n\n  return undefined;\n}\n\nfunction isNonNegativeSafeInteger(\n  value: number | null | undefined,\n): value is number {\n  return value != null && Number.isSafeInteger(value) && value >= 0;\n}\n","import {\n  JSONParseError,\n  TypeValidationError,\n  type JSONValue,\n} from '@ai-sdk/provider';\nimport { secureJsonParse } from './secure-json-parse';\nimport { safeValidateTypes, validateTypes } from './validate-types';\nimport type { FlexibleSchema } from './schema';\n\n/**\n * Parses a JSON string into an unknown object.\n *\n * @param text - The JSON string to parse.\n * @returns {JSONValue} - The parsed JSON object.\n */\nexport async function parseJSON(options: {\n  text: string;\n  schema?: undefined;\n}): Promise<JSONValue>;\n/**\n * Parses a JSON string into a strongly-typed object using the provided schema.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Validator<T>} schema - The schema to use for parsing the JSON.\n * @returns {Promise<T>} - The parsed object.\n */\nexport async function parseJSON<T>(options: {\n  text: string;\n  schema: FlexibleSchema<T>;\n}): Promise<T>;\nexport async function parseJSON<T>({\n  text,\n  schema,\n}: {\n  text: string;\n  schema?: FlexibleSchema<T>;\n}): Promise<T> {\n  try {\n    const value = secureJsonParse(text);\n\n    if (schema == null) {\n      return value;\n    }\n\n    return await validateTypes<T>({ value, schema });\n  } catch (error) {\n    if (\n      JSONParseError.isInstance(error) ||\n      TypeValidationError.isInstance(error)\n    ) {\n      throw error;\n    }\n\n    throw new JSONParseError({ text, cause: error });\n  }\n}\n\nexport type ParseResult<T> =\n  | { success: true; value: T; rawValue: unknown }\n  | {\n      success: false;\n      error: JSONParseError | TypeValidationError;\n      rawValue: unknown;\n    };\n\n/**\n * Safely parses a JSON string and returns the result as an object of type `unknown`.\n *\n * @param text - The JSON string to parse.\n * @returns {Promise<object>} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.\n */\nexport async function safeParseJSON(options: {\n  text: string;\n  schema?: undefined;\n}): Promise<ParseResult<JSONValue>>;\n/**\n * Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Validator<T>} schema - The schema to use for parsing the JSON.\n * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n */\nexport async function safeParseJSON<T>(options: {\n  text: string;\n  schema: FlexibleSchema<T>;\n}): Promise<ParseResult<T>>;\nexport async function safeParseJSON<T>({\n  text,\n  schema,\n}: {\n  text: string;\n  schema?: FlexibleSchema<T>;\n}): Promise<ParseResult<T>> {\n  try {\n    const value = secureJsonParse(text);\n\n    if (schema == null) {\n      return { success: true, value: value as T, rawValue: value };\n    }\n\n    return await safeValidateTypes<T>({ value, schema });\n  } catch (error) {\n    return {\n      success: false,\n      error: JSONParseError.isInstance(error)\n        ? error\n        : new JSONParseError({ text, cause: error }),\n      rawValue: undefined,\n    };\n  }\n}\n\nexport function isParsableJson(input: string): boolean {\n  try {\n    secureJsonParse(input);\n    return true;\n  } catch {\n    return false;\n  }\n}\n","// Licensed under BSD-3-Clause (this file only)\n// Code adapted from https://github.com/fastify/secure-json-parse/blob/783fcb1b5434709466759847cec974381939673a/index.js\n//\n// Copyright (c) Vercel, Inc. (https://vercel.com)\n// Copyright (c) 2019 The Fastify Team\n// Copyright (c) 2019, Sideway Inc, and project contributors\n// All rights reserved.\n//\n// The complete list of contributors can be found at:\n// - https://github.com/hapijs/bourne/graphs/contributors\n// - https://github.com/fastify/secure-json-parse/graphs/contributors\n// - https://github.com/vercel/ai/commits/main/packages/provider-utils/src/secure-parse-json.ts\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nconst suspectProtoRx =\n  /\"(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])\"\\s*:/;\nconst suspectConstructorRx =\n  /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/;\n\nfunction _parse(text: string) {\n  // Parse normally\n  const obj = JSON.parse(text);\n\n  // Ignore null and non-objects\n  if (obj === null || typeof obj !== 'object') {\n    return obj;\n  }\n\n  if (\n    suspectProtoRx.test(text) === false &&\n    suspectConstructorRx.test(text) === false\n  ) {\n    return obj;\n  }\n\n  // Scan result for proto keys\n  return filter(obj);\n}\n\nfunction filter(obj: any) {\n  let next = [obj];\n\n  while (next.length) {\n    const nodes = next;\n    next = [];\n\n    for (const node of nodes) {\n      if (Object.prototype.hasOwnProperty.call(node, '__proto__')) {\n        throw new SyntaxError('Object contains forbidden prototype property');\n      }\n\n      if (\n        Object.prototype.hasOwnProperty.call(node, 'constructor') &&\n        node.constructor !== null &&\n        typeof node.constructor === 'object' &&\n        Object.prototype.hasOwnProperty.call(node.constructor, 'prototype')\n      ) {\n        throw new SyntaxError('Object contains forbidden prototype property');\n      }\n\n      for (const key in node) {\n        const value = node[key];\n        if (value && typeof value === 'object') {\n          next.push(value);\n        }\n      }\n    }\n  }\n  return obj;\n}\n\nexport function secureJsonParse(text: string) {\n  const { stackTraceLimit } = Error;\n  try {\n    // Performance optimization, see https://github.com/fastify/secure-json-parse/pull/90\n    Error.stackTraceLimit = 0;\n  } catch {\n    // Fallback in case Error is immutable (v8 readonly)\n    return _parse(text);\n  }\n\n  try {\n    return _parse(text);\n  } finally {\n    Error.stackTraceLimit = stackTraceLimit;\n  }\n}\n","import {\n  TypeValidationError,\n  type TypeValidationContext,\n} from '@ai-sdk/provider';\nimport { asSchema, type FlexibleSchema } from './schema';\n/**\n * Validates the types of an unknown object using a schema and\n * return a strongly-typed object.\n *\n * @template T - The type of the object to validate.\n * @param {string} options.value - The object to validate.\n * @param {Validator<T>} options.schema - The schema to use for validating the JSON.\n * @param {TypeValidationContext} options.context - Optional context about what is being validated.\n * @returns {Promise<T>} - The typed object.\n */\nexport async function validateTypes<OBJECT>({\n  value,\n  schema,\n  context,\n}: {\n  value: unknown;\n  schema: FlexibleSchema<OBJECT>;\n  context?: TypeValidationContext;\n}): Promise<OBJECT> {\n  const result = await safeValidateTypes({ value, schema, context });\n\n  if (!result.success) {\n    throw TypeValidationError.wrap({ value, cause: result.error, context });\n  }\n\n  return result.value;\n}\n\n/**\n * Safely validates the types of an unknown object using a schema and\n * return a strongly-typed object.\n *\n * @template T - The type of the object to validate.\n * @param {string} options.value - The JSON object to validate.\n * @param {Validator<T>} options.schema - The schema to use for validating the JSON.\n * @param {TypeValidationContext} options.context - Optional context about what is being validated.\n * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n */\nexport async function safeValidateTypes<OBJECT>({\n  value,\n  schema,\n  context,\n}: {\n  value: unknown;\n  schema: FlexibleSchema<OBJECT>;\n  context?: TypeValidationContext;\n}): Promise<\n  | {\n      success: true;\n      value: OBJECT;\n      rawValue: unknown;\n    }\n  | {\n      success: false;\n      error: TypeValidationError;\n      rawValue: unknown;\n    }\n> {\n  const actualSchema = asSchema(schema);\n\n  try {\n    if (actualSchema.validate == null) {\n      return { success: true, value: value as OBJECT, rawValue: value };\n    }\n\n    const result = await actualSchema.validate(value);\n\n    if (result.success) {\n      return { success: true, value: result.value, rawValue: value };\n    }\n\n    return {\n      success: false,\n      error: TypeValidationError.wrap({ value, cause: result.error, context }),\n      rawValue: value,\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: TypeValidationError.wrap({ value, cause: error, context }),\n      rawValue: value,\n    };\n  }\n}\n","import { TypeValidationError, type JSONSchema7 } from '@ai-sdk/provider';\nimport type {\n  StandardSchemaV1,\n  StandardJSONSchemaV1,\n} from '@standard-schema/spec';\nimport type * as z3 from 'zod/v3';\nimport { safeParseAsync } from 'zod/v4';\nimport { toJSONSchema, type $ZodType } from 'zod/v4/core';\nimport { addAdditionalPropertiesToJsonSchema } from './add-additional-properties-to-json-schema';\nimport { zod3ToJsonSchema } from './to-json-schema/zod3-to-json-schema';\n\n/**\n * Used to mark schemas so we can support both Zod and custom schemas.\n */\nconst schemaSymbol = Symbol.for('vercel.ai.schema');\n\nexport type ValidationResult<OBJECT> =\n  | { success: true; value: OBJECT }\n  | { success: false; error: Error };\n\nexport type Schema<OBJECT = unknown> = {\n  /**\n   * Used to mark schemas so we can support both Zod and custom schemas.\n   */\n  [schemaSymbol]: true;\n\n  /**\n   * Schema type for inference.\n   */\n  _type: OBJECT;\n\n  /**\n   * Optional. Validates that the structure of a value matches this schema,\n   * and returns a typed version of the value if it does.\n   */\n  readonly validate?: (\n    value: unknown,\n  ) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;\n\n  /**\n   * The JSON Schema for the schema. It is passed to the providers.\n   */\n  readonly jsonSchema: JSONSchema7 | PromiseLike<JSONSchema7>;\n};\n\n/**\n * Creates a schema with deferred creation.\n * This is important to reduce the startup time of the library\n * and to avoid initializing unused validators.\n *\n * @param createValidator A function that creates a schema.\n * @returns A function that returns a schema.\n */\nexport function lazySchema<SCHEMA>(\n  createSchema: () => Schema<SCHEMA>,\n): LazySchema<SCHEMA> {\n  // cache the validator to avoid initializing it multiple times\n  let schema: Schema<SCHEMA> | undefined;\n  return () => {\n    if (schema == null) {\n      schema = createSchema();\n    }\n    return schema;\n  };\n}\n\nexport type LazySchema<SCHEMA> = () => Schema<SCHEMA>;\n\nexport type ZodSchema<SCHEMA = any> =\n  | z3.Schema<SCHEMA, z3.ZodTypeDef, any>\n  | $ZodType<SCHEMA, any>;\n\nexport type StandardSchema<SCHEMA = any> = StandardSchemaV1<unknown, SCHEMA> & {\n  readonly '~standard': StandardSchemaV1.Props<unknown, SCHEMA> & {\n    readonly jsonSchema?: StandardJSONSchemaV1.Converter;\n  };\n};\n\ntype StandardSchemaWithJsonSchema<SCHEMA = any> = StandardSchema<SCHEMA> &\n  StandardJSONSchemaV1<unknown, SCHEMA>;\n\nexport type FlexibleSchema<SCHEMA = any> =\n  | Schema<SCHEMA>\n  | LazySchema<SCHEMA>\n  | ZodSchema<SCHEMA>\n  | StandardSchema<SCHEMA>;\n\nexport type InferSchema<SCHEMA> =\n  SCHEMA extends ZodSchema<infer T>\n    ? T\n    : SCHEMA extends StandardSchema<infer T>\n      ? T\n      : SCHEMA extends LazySchema<infer T>\n        ? T\n        : SCHEMA extends Schema<infer T>\n          ? T\n          : never;\n\n/**\n * Create a schema using a JSON Schema.\n *\n * @param jsonSchema The JSON Schema for the schema.\n * @param options.validate Optional. A validation function for the schema.\n */\nexport function jsonSchema<OBJECT = unknown>(\n  jsonSchema:\n    | JSONSchema7\n    | PromiseLike<JSONSchema7>\n    | (() => JSONSchema7 | PromiseLike<JSONSchema7>),\n  {\n    validate,\n  }: {\n    validate?: (\n      value: unknown,\n    ) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;\n  } = {},\n): Schema<OBJECT> {\n  return {\n    [schemaSymbol]: true,\n    _type: undefined as OBJECT, // should never be used directly\n    get jsonSchema() {\n      if (typeof jsonSchema === 'function') {\n        jsonSchema = jsonSchema(); // cache the function results\n      }\n      return jsonSchema;\n    },\n    validate,\n  };\n}\n\nfunction isSchema(value: unknown): value is Schema {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    schemaSymbol in value &&\n    value[schemaSymbol] === true &&\n    'jsonSchema' in value &&\n    'validate' in value\n  );\n}\n\nexport function asSchema<OBJECT>(\n  schema: FlexibleSchema<OBJECT> | undefined,\n): Schema<OBJECT> {\n  return schema == null\n    ? jsonSchema({\n        type: 'object',\n        properties: {},\n        additionalProperties: false,\n      })\n    : isSchema(schema)\n      ? schema\n      : '~standard' in schema\n        ? schema['~standard'].vendor === 'zod'\n          ? zodSchema(schema as ZodSchema<OBJECT>)\n          : standardSchema(schema as StandardSchema<OBJECT>)\n        : schema();\n}\n\nfunction standardSchema<OBJECT>(\n  standardSchema: StandardSchema<OBJECT>,\n): Schema<OBJECT> {\n  return jsonSchema(\n    () => {\n      if (!hasStandardJsonSchema(standardSchema)) {\n        throw new Error(\n          `Standard schema vendor '${standardSchema['~standard'].vendor}' does not support JSON Schema conversion.`,\n        );\n      }\n\n      return addAdditionalPropertiesToJsonSchema(\n        standardSchema['~standard'].jsonSchema.input({\n          target: 'draft-07',\n        }) as JSONSchema7,\n      );\n    },\n    {\n      validate: async value => {\n        const result = await standardSchema['~standard'].validate(value);\n        return 'value' in result\n          ? { success: true, value: result.value }\n          : {\n              success: false,\n              error: new TypeValidationError({\n                value,\n                cause: result.issues,\n              }),\n            };\n      },\n    },\n  );\n}\n\nfunction hasStandardJsonSchema<OBJECT>(\n  schema: StandardSchema<OBJECT>,\n): schema is StandardSchemaWithJsonSchema<OBJECT> {\n  return schema['~standard'].jsonSchema != null;\n}\n\nexport function zod3Schema<OBJECT>(\n  zodSchema: z3.Schema<OBJECT, z3.ZodTypeDef, any>,\n  options?: {\n    /**\n     * Enables support for references in the schema.\n     * This is required for recursive schemas, e.g. with `z.lazy`.\n     * However, not all language models and providers support such references.\n     * Defaults to `false`.\n     */\n    useReferences?: boolean;\n  },\n): Schema<OBJECT> {\n  // default to no references (to support openapi conversion for google)\n  const useReferences = options?.useReferences ?? false;\n\n  return jsonSchema(\n    // defer json schema creation to avoid unnecessary computation when only validation is needed\n    () =>\n      zod3ToJsonSchema(zodSchema, {\n        $refStrategy: useReferences ? 'root' : 'none',\n      }) as JSONSchema7,\n    {\n      validate: async value => {\n        const result = await zodSchema.safeParseAsync(value);\n        return result.success\n          ? { success: true, value: result.data }\n          : { success: false, error: result.error };\n      },\n    },\n  );\n}\n\nexport function zod4Schema<OBJECT>(\n  zodSchema: $ZodType<OBJECT, any>,\n  options?: {\n    /**\n     * Enables support for references in the schema.\n     * This is required for recursive schemas, e.g. with `z.lazy`.\n     * However, not all language models and providers support such references.\n     * Defaults to `false`.\n     */\n    useReferences?: boolean;\n  },\n): Schema<OBJECT> {\n  // default to no references (to support openapi conversion for google)\n  const useReferences = options?.useReferences ?? false;\n\n  return jsonSchema(\n    // defer json schema creation to avoid unnecessary computation when only validation is needed\n    () =>\n      addAdditionalPropertiesToJsonSchema(\n        toJSONSchema(zodSchema, {\n          target: 'draft-7',\n          io: 'input',\n          reused: useReferences ? 'ref' : 'inline',\n        }) as JSONSchema7,\n      ),\n    {\n      validate: async value => {\n        const result = await safeParseAsync(zodSchema, value);\n        return result.success\n          ? { success: true, value: result.data }\n          : { success: false, error: result.error };\n      },\n    },\n  );\n}\n\nexport function isZod4Schema(\n  zodSchema: $ZodType<any, any> | z3.Schema<any, z3.ZodTypeDef, any>,\n): zodSchema is $ZodType<any, any> {\n  // https://zod.dev/library-authors?id=how-to-support-zod-3-and-zod-4-simultaneously\n  return '_zod' in zodSchema;\n}\n\nexport function zodSchema<OBJECT>(\n  zodSchema: $ZodType<OBJECT, any> | z3.Schema<OBJECT, z3.ZodTypeDef, any>,\n  options?: {\n    /**\n     * Enables support for references in the schema.\n     * This is required for recursive schemas, e.g. with `z.lazy`.\n     * However, not all language models and providers support such references.\n     * Defaults to `false`.\n     */\n    useReferences?: boolean;\n  },\n): Schema<OBJECT> {\n  if (isZod4Schema(zodSchema)) {\n    return zod4Schema(zodSchema, options);\n  } else {\n    return zod3Schema(zodSchema, options);\n  }\n}\n","import type { JSONSchema7, JSONSchema7Definition } from '@ai-sdk/provider';\n\n/**\n * Recursively adds additionalProperties: false to object schemas that do not\n * define a schema for their additional properties. This is necessary because\n * some providers (e.g. OpenAI) do not support additionalProperties: true.\n */\nexport function addAdditionalPropertiesToJsonSchema(\n  jsonSchema: JSONSchema7,\n): JSONSchema7 {\n  if (\n    jsonSchema.type === 'object' ||\n    (Array.isArray(jsonSchema.type) && jsonSchema.type.includes('object'))\n  ) {\n    const { additionalProperties } = jsonSchema;\n    jsonSchema.additionalProperties =\n      additionalProperties != null && typeof additionalProperties !== 'boolean'\n        ? visit(additionalProperties)\n        : false;\n\n    const { properties } = jsonSchema;\n    if (properties != null) {\n      for (const key of Object.keys(properties)) {\n        properties[key] = visit(properties[key]);\n      }\n    }\n  }\n\n  if (jsonSchema.items != null) {\n    jsonSchema.items = Array.isArray(jsonSchema.items)\n      ? jsonSchema.items.map(visit)\n      : visit(jsonSchema.items);\n  }\n\n  if (jsonSchema.anyOf != null) {\n    jsonSchema.anyOf = jsonSchema.anyOf.map(visit);\n  }\n\n  if (jsonSchema.allOf != null) {\n    jsonSchema.allOf = jsonSchema.allOf.map(visit);\n  }\n\n  if (jsonSchema.oneOf != null) {\n    jsonSchema.oneOf = jsonSchema.oneOf.map(visit);\n  }\n\n  const { definitions } = jsonSchema;\n  if (definitions != null) {\n    for (const key of Object.keys(definitions)) {\n      definitions[key] = visit(definitions[key]);\n    }\n  }\n\n  return jsonSchema;\n}\n\nfunction visit(def: JSONSchema7Definition): JSONSchema7Definition {\n  if (typeof def === 'boolean') return def;\n  return addAdditionalPropertiesToJsonSchema(def);\n}\n","import type { ZodSchema, ZodTypeDef } from 'zod/v3';\nimport type { Refs, Seen } from './refs';\nimport type { JsonSchema7Type } from './parse-types';\n\nexport type DateStrategy =\n  | 'format:date-time'\n  | 'format:date'\n  | 'string'\n  | 'integer';\n\nexport const ignoreOverride = Symbol(\n  'Let zodToJsonSchema decide on which parser to use',\n);\n\nexport type OverrideCallback = (\n  def: ZodTypeDef,\n  refs: Refs,\n  seen: Seen | undefined,\n  forceResolution?: boolean,\n) => JsonSchema7Type | undefined | typeof ignoreOverride;\n\nexport type PostProcessCallback = (\n  jsonSchema: JsonSchema7Type | undefined,\n  def: ZodTypeDef,\n  refs: Refs,\n) => JsonSchema7Type | undefined;\n\nexport const jsonDescription: PostProcessCallback = (jsonSchema, def) => {\n  if (def.description) {\n    try {\n      return {\n        ...jsonSchema,\n        ...JSON.parse(def.description),\n      };\n    } catch {}\n  }\n\n  return jsonSchema;\n};\n\nexport type Options = {\n  name: string | undefined;\n  $refStrategy: 'root' | 'relative' | 'none' | 'seen';\n  basePath: string[];\n  effectStrategy: 'input' | 'any';\n  pipeStrategy: 'input' | 'output' | 'all';\n  dateStrategy: DateStrategy | DateStrategy[];\n  mapStrategy: 'entries' | 'record';\n  removeAdditionalStrategy: 'passthrough' | 'strict';\n  allowedAdditionalProperties: true | undefined;\n  rejectedAdditionalProperties: false | undefined;\n  strictUnions: boolean;\n  definitionPath: string;\n  definitions: Record<string, ZodSchema>;\n  errorMessages: boolean;\n  patternStrategy: 'escape' | 'preserve';\n  applyRegexFlags: boolean;\n  emailStrategy: 'format:email' | 'format:idn-email' | 'pattern:zod';\n  base64Strategy: 'format:binary' | 'contentEncoding:base64' | 'pattern:zod';\n  nameStrategy: 'ref' | 'title';\n  override?: OverrideCallback;\n  postProcess?: PostProcessCallback;\n};\n\nexport const defaultOptions: Options = {\n  name: undefined,\n  $refStrategy: 'root',\n  basePath: ['#'],\n  effectStrategy: 'input',\n  pipeStrategy: 'all',\n  dateStrategy: 'format:date-time',\n  mapStrategy: 'entries',\n  removeAdditionalStrategy: 'passthrough',\n  allowedAdditionalProperties: true,\n  rejectedAdditionalProperties: false,\n  definitionPath: 'definitions',\n  strictUnions: false,\n  definitions: {},\n  errorMessages: false,\n  patternStrategy: 'escape',\n  applyRegexFlags: false,\n  emailStrategy: 'format:email',\n  base64Strategy: 'contentEncoding:base64',\n  nameStrategy: 'ref',\n};\n\nexport const getDefaultOptions = (\n  options: Partial<Options> | string | undefined,\n) =>\n  (typeof options === 'string'\n    ? {\n        ...defaultOptions,\n        name: options,\n      }\n    : {\n        ...defaultOptions,\n        ...options,\n      }) as Options;\n","export type JsonSchema7AnyType = { $ref?: string };\n\nexport function parseAnyDef(): JsonSchema7AnyType {\n  return {};\n}\n","import type { ZodArrayDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport type JsonSchema7ArrayType = {\n  type: 'array';\n  items?: JsonSchema7Type;\n  minItems?: number;\n  maxItems?: number;\n};\n\nexport function parseArrayDef(def: ZodArrayDef, refs: Refs) {\n  const res: JsonSchema7ArrayType = {\n    type: 'array',\n  };\n  if (def.type?._def && def.type?._def?.typeName !== 'ZodAny') {\n    res.items = parseDef(def.type._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'items'],\n    });\n  }\n\n  if (def.minLength) {\n    res.minItems = def.minLength.value;\n  }\n  if (def.maxLength) {\n    res.maxItems = def.maxLength.value;\n  }\n  if (def.exactLength) {\n    res.minItems = def.exactLength.value;\n    res.maxItems = def.exactLength.value;\n  }\n  return res;\n}\n","import type { ZodBigIntDef } from 'zod/v3';\n\nexport type JsonSchema7BigintType = {\n  type: 'integer';\n  format: 'int64';\n  minimum?: BigInt;\n  exclusiveMinimum?: BigInt;\n  maximum?: BigInt;\n  exclusiveMaximum?: BigInt;\n  multipleOf?: BigInt;\n};\n\nexport function parseBigintDef(def: ZodBigIntDef): JsonSchema7BigintType {\n  const res: JsonSchema7BigintType = {\n    type: 'integer',\n    format: 'int64',\n  };\n\n  if (!def.checks) return res;\n\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case 'min':\n        if (check.inclusive) {\n          res.minimum = check.value;\n        } else {\n          res.exclusiveMinimum = check.value;\n        }\n        break;\n      case 'max':\n        if (check.inclusive) {\n          res.maximum = check.value;\n        } else {\n          res.exclusiveMaximum = check.value;\n        }\n\n        break;\n      case 'multipleOf':\n        res.multipleOf = check.value;\n        break;\n    }\n  }\n  return res;\n}\n","export type JsonSchema7BooleanType = {\n  type: 'boolean';\n};\n\nexport function parseBooleanDef(): JsonSchema7BooleanType {\n  return { type: 'boolean' };\n}\n","import type { ZodBrandedDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { Refs } from '../refs';\n\nexport function parseBrandedDef(_def: ZodBrandedDef<any>, refs: Refs) {\n  return parseDef(_def.type._def, refs);\n}\n","import type { ZodCatchDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { Refs } from '../refs';\n\nexport const parseCatchDef = (def: ZodCatchDef<any>, refs: Refs) => {\n  return parseDef(def.innerType._def, refs);\n};\n","import type { ZodDateDef } from 'zod/v3';\nimport type { Refs } from '../refs';\nimport type { DateStrategy } from '../options';\n\nexport type JsonSchema7DateType =\n  | {\n      type: 'integer' | 'string';\n      format: 'unix-time' | 'date-time' | 'date';\n      minimum?: number;\n      maximum?: number;\n    }\n  | {\n      anyOf: JsonSchema7DateType[];\n    };\n\nexport function parseDateDef(\n  def: ZodDateDef,\n  refs: Refs,\n  overrideDateStrategy?: DateStrategy,\n): JsonSchema7DateType {\n  const strategy = overrideDateStrategy ?? refs.dateStrategy;\n\n  if (Array.isArray(strategy)) {\n    return {\n      anyOf: strategy.map(item => parseDateDef(def, refs, item)),\n    };\n  }\n\n  switch (strategy) {\n    case 'string':\n    case 'format:date-time':\n      return {\n        type: 'string',\n        format: 'date-time',\n      };\n    case 'format:date':\n      return {\n        type: 'string',\n        format: 'date',\n      };\n    case 'integer':\n      return integerDateParser(def);\n  }\n}\n\nconst integerDateParser = (def: ZodDateDef) => {\n  const res: JsonSchema7DateType = {\n    type: 'integer',\n    format: 'unix-time',\n  };\n\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case 'min':\n        res.minimum = check.value;\n        break;\n      case 'max':\n        res.maximum = check.value;\n        break;\n    }\n  }\n\n  return res;\n};\n","import type { ZodDefaultDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport function parseDefaultDef(\n  _def: ZodDefaultDef,\n  refs: Refs,\n): JsonSchema7Type & { default: any } {\n  return {\n    ...parseDef(_def.innerType._def, refs),\n    default: _def.defaultValue(),\n  };\n}\n","import type { ZodEffectsDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport { parseAnyDef } from './any';\n\nexport function parseEffectsDef(\n  _def: ZodEffectsDef,\n  refs: Refs,\n): JsonSchema7Type | undefined {\n  return refs.effectStrategy === 'input'\n    ? parseDef(_def.schema._def, refs)\n    : parseAnyDef();\n}\n","import type { ZodEnumDef } from 'zod/v3';\n\nexport type JsonSchema7EnumType = {\n  type: 'string';\n  enum: string[];\n};\n\nexport function parseEnumDef(def: ZodEnumDef): JsonSchema7EnumType {\n  return {\n    type: 'string',\n    enum: Array.from(def.values),\n  };\n}\n","import type { ZodIntersectionDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport type { JsonSchema7StringType } from './string';\n\nexport type JsonSchema7AllOfType = {\n  allOf: JsonSchema7Type[];\n  unevaluatedProperties?: boolean;\n};\n\nconst isJsonSchema7AllOfType = (\n  type: JsonSchema7Type | JsonSchema7StringType,\n): type is JsonSchema7AllOfType => {\n  if ('type' in type && type.type === 'string') return false;\n  return 'allOf' in type;\n};\n\nexport function parseIntersectionDef(\n  def: ZodIntersectionDef,\n  refs: Refs,\n): JsonSchema7AllOfType | JsonSchema7Type | undefined {\n  const allOf = [\n    parseDef(def.left._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'allOf', '0'],\n    }),\n    parseDef(def.right._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'allOf', '1'],\n    }),\n  ].filter((x): x is JsonSchema7Type => !!x);\n\n  const mergedAllOf: JsonSchema7Type[] = [];\n  // If either of the schemas is an allOf, merge them into a single allOf\n  allOf.forEach(schema => {\n    if (isJsonSchema7AllOfType(schema)) {\n      mergedAllOf.push(...schema.allOf);\n    } else {\n      let nestedSchema: JsonSchema7Type = schema;\n      if (\n        'additionalProperties' in schema &&\n        schema.additionalProperties === false\n      ) {\n        const { additionalProperties: _additionalProperties, ...rest } = schema;\n        nestedSchema = rest;\n      }\n      mergedAllOf.push(nestedSchema);\n    }\n  });\n  return mergedAllOf.length ? { allOf: mergedAllOf } : undefined;\n}\n","import type { ZodLiteralDef } from 'zod/v3';\n\nexport type JsonSchema7LiteralType =\n  | {\n      type: 'string' | 'number' | 'integer' | 'boolean';\n      const: string | number | boolean;\n    }\n  | {\n      type: 'object' | 'array';\n    };\n\nexport function parseLiteralDef(def: ZodLiteralDef): JsonSchema7LiteralType {\n  const parsedType = typeof def.value;\n  if (\n    parsedType !== 'bigint' &&\n    parsedType !== 'number' &&\n    parsedType !== 'boolean' &&\n    parsedType !== 'string'\n  ) {\n    return {\n      type: Array.isArray(def.value) ? 'array' : 'object',\n    };\n  }\n\n  return {\n    type: parsedType === 'bigint' ? 'integer' : parsedType,\n    const: def.value,\n  };\n}\n","import type { ZodStringDef } from 'zod/v3';\nimport type { Refs } from '../refs';\n\nlet emojiRegex: RegExp | undefined = undefined;\n\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n  /**\n   * `c` was changed to `[cC]` to replicate /i flag\n   */\n  cuid: /^[cC][^\\s-]{8,}$/,\n  cuid2: /^[0-9a-z]+$/,\n  ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n  /**\n   * `a-z` was added to replicate /i flag\n   */\n  email:\n    /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n  /**\n   * Constructed a valid Unicode RegExp\n   *\n   * Lazily instantiate since this type of regex isn't supported\n   * in all envs (e.g. React Native).\n   *\n   * See:\n   * https://github.com/colinhacks/zod/issues/2433\n   * Fix in Zod:\n   * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n   */\n  emoji: () => {\n    if (emojiRegex === undefined) {\n      emojiRegex = RegExp(\n        '^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$',\n        'u',\n      );\n    }\n    return emojiRegex;\n  },\n  /**\n   * Unused\n   */\n  uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n  /**\n   * Unused\n   */\n  ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n  ipv4Cidr:\n    /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n  /**\n   * Unused\n   */\n  ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n  ipv6Cidr:\n    /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n  base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n  base64url:\n    /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n  nanoid: /^[a-zA-Z0-9_-]{21}$/,\n  jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n} as const;\n\nexport type JsonSchema7StringType = {\n  type: 'string';\n  minLength?: number;\n  maxLength?: number;\n  format?:\n    | 'email'\n    | 'idn-email'\n    | 'uri'\n    | 'uuid'\n    | 'date-time'\n    | 'ipv4'\n    | 'ipv6'\n    | 'date'\n    | 'time'\n    | 'duration';\n  pattern?: string;\n  allOf?: {\n    pattern: string;\n  }[];\n  anyOf?: {\n    format: string;\n  }[];\n  contentEncoding?: string;\n};\n\nexport function parseStringDef(\n  def: ZodStringDef,\n  refs: Refs,\n): JsonSchema7StringType {\n  const res: JsonSchema7StringType = {\n    type: 'string',\n  };\n\n  if (def.checks) {\n    for (const check of def.checks) {\n      switch (check.kind) {\n        case 'min':\n          res.minLength =\n            typeof res.minLength === 'number'\n              ? Math.max(res.minLength, check.value)\n              : check.value;\n          break;\n        case 'max':\n          res.maxLength =\n            typeof res.maxLength === 'number'\n              ? Math.min(res.maxLength, check.value)\n              : check.value;\n\n          break;\n        case 'email':\n          switch (refs.emailStrategy) {\n            case 'format:email':\n              addFormat(res, 'email', check.message, refs);\n              break;\n            case 'format:idn-email':\n              addFormat(res, 'idn-email', check.message, refs);\n              break;\n            case 'pattern:zod':\n              addPattern(res, zodPatterns.email, check.message, refs);\n              break;\n          }\n\n          break;\n        case 'url':\n          addFormat(res, 'uri', check.message, refs);\n          break;\n        case 'uuid':\n          addFormat(res, 'uuid', check.message, refs);\n          break;\n        case 'regex':\n          addPattern(res, check.regex, check.message, refs);\n          break;\n        case 'cuid':\n          addPattern(res, zodPatterns.cuid, check.message, refs);\n          break;\n        case 'cuid2':\n          addPattern(res, zodPatterns.cuid2, check.message, refs);\n          break;\n        case 'startsWith':\n          addPattern(\n            res,\n            RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),\n            check.message,\n            refs,\n          );\n          break;\n        case 'endsWith':\n          addPattern(\n            res,\n            RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),\n            check.message,\n            refs,\n          );\n          break;\n        case 'datetime':\n          addFormat(res, 'date-time', check.message, refs);\n          break;\n        case 'date':\n          addFormat(res, 'date', check.message, refs);\n          break;\n        case 'time':\n          addFormat(res, 'time', check.message, refs);\n          break;\n        case 'duration':\n          addFormat(res, 'duration', check.message, refs);\n          break;\n        case 'length':\n          res.minLength =\n            typeof res.minLength === 'number'\n              ? Math.max(res.minLength, check.value)\n              : check.value;\n          res.maxLength =\n            typeof res.maxLength === 'number'\n              ? Math.min(res.maxLength, check.value)\n              : check.value;\n          break;\n        case 'includes': {\n          addPattern(\n            res,\n            RegExp(escapeLiteralCheckValue(check.value, refs)),\n            check.message,\n            refs,\n          );\n          break;\n        }\n        case 'ip': {\n          if (check.version !== 'v6') {\n            addFormat(res, 'ipv4', check.message, refs);\n          }\n          if (check.version !== 'v4') {\n            addFormat(res, 'ipv6', check.message, refs);\n          }\n          break;\n        }\n        case 'base64url':\n          addPattern(res, zodPatterns.base64url, check.message, refs);\n          break;\n        case 'jwt':\n          addPattern(res, zodPatterns.jwt, check.message, refs);\n          break;\n        case 'cidr': {\n          if (check.version !== 'v6') {\n            addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n          }\n          if (check.version !== 'v4') {\n            addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n          }\n          break;\n        }\n        case 'emoji':\n          addPattern(res, zodPatterns.emoji(), check.message, refs);\n          break;\n        case 'ulid': {\n          addPattern(res, zodPatterns.ulid, check.message, refs);\n          break;\n        }\n        case 'base64': {\n          switch (refs.base64Strategy) {\n            case 'format:binary': {\n              addFormat(res, 'binary' as any, check.message, refs);\n              break;\n            }\n\n            case 'contentEncoding:base64': {\n              res.contentEncoding = 'base64';\n              break;\n            }\n\n            case 'pattern:zod': {\n              addPattern(res, zodPatterns.base64, check.message, refs);\n              break;\n            }\n          }\n          break;\n        }\n        case 'nanoid': {\n          addPattern(res, zodPatterns.nanoid, check.message, refs);\n        }\n        case 'toLowerCase':\n        case 'toUpperCase':\n        case 'trim':\n          break;\n        default:\n          /* c8 ignore next */\n          ((_: never) => {})(check);\n      }\n    }\n  }\n\n  return res;\n}\n\nfunction escapeLiteralCheckValue(literal: string, refs: Refs): string {\n  return refs.patternStrategy === 'escape'\n    ? escapeNonAlphaNumeric(literal)\n    : literal;\n}\n\nconst ALPHA_NUMERIC = new Set(\n  'ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789',\n);\n\nfunction escapeNonAlphaNumeric(source: string) {\n  let result = '';\n\n  for (let i = 0; i < source.length; i++) {\n    if (!ALPHA_NUMERIC.has(source[i])) {\n      result += '\\\\';\n    }\n\n    result += source[i];\n  }\n\n  return result;\n}\n\n// Adds a \"format\" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones.\nfunction addFormat(\n  schema: JsonSchema7StringType,\n  value: Required<JsonSchema7StringType>['format'],\n  message: string | undefined,\n  refs: Refs,\n) {\n  if (schema.format || schema.anyOf?.some(x => x.format)) {\n    if (!schema.anyOf) {\n      schema.anyOf = [];\n    }\n\n    if (schema.format) {\n      schema.anyOf!.push({\n        format: schema.format,\n      });\n      delete schema.format;\n    }\n\n    schema.anyOf!.push({\n      format: value,\n      ...(message &&\n        refs.errorMessages && { errorMessage: { format: message } }),\n    });\n  } else {\n    schema.format = value;\n  }\n}\n\n// Adds a \"pattern\" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones.\nfunction addPattern(\n  schema: JsonSchema7StringType,\n  regex: RegExp,\n  message: string | undefined,\n  refs: Refs,\n) {\n  if (schema.pattern || schema.allOf?.some(x => x.pattern)) {\n    if (!schema.allOf) {\n      schema.allOf = [];\n    }\n\n    if (schema.pattern) {\n      schema.allOf!.push({\n        pattern: schema.pattern,\n      });\n      delete schema.pattern;\n    }\n\n    schema.allOf!.push({\n      pattern: stringifyRegExpWithFlags(regex, refs),\n      ...(message &&\n        refs.errorMessages && { errorMessage: { pattern: message } }),\n    });\n  } else {\n    schema.pattern = stringifyRegExpWithFlags(regex, refs);\n  }\n}\n\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nfunction stringifyRegExpWithFlags(regex: RegExp, refs: Refs): string {\n  if (!refs.applyRegexFlags || !regex.flags) {\n    return regex.source;\n  }\n\n  // Currently handled flags\n  const flags = {\n    i: regex.flags.includes('i'), // Case-insensitive\n    m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters\n    s: regex.flags.includes('s'), // `.` matches newlines\n  };\n\n  // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n  const source = flags.i ? regex.source.toLowerCase() : regex.source;\n  let pattern = '';\n  let isEscaped = false;\n  let inCharGroup = false;\n  let inCharRange = false;\n\n  for (let i = 0; i < source.length; i++) {\n    if (isEscaped) {\n      pattern += source[i];\n      isEscaped = false;\n      continue;\n    }\n\n    if (flags.i) {\n      if (inCharGroup) {\n        if (source[i].match(/[a-z]/)) {\n          if (inCharRange) {\n            pattern += source[i];\n            pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n            inCharRange = false;\n          } else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) {\n            pattern += source[i];\n            inCharRange = true;\n          } else {\n            pattern += `${source[i]}${source[i].toUpperCase()}`;\n          }\n          continue;\n        }\n      } else if (source[i].match(/[a-z]/)) {\n        pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n        continue;\n      }\n    }\n\n    if (flags.m) {\n      if (source[i] === '^') {\n        pattern += `(^|(?<=[\\r\\n]))`;\n        continue;\n      } else if (source[i] === '$') {\n        pattern += `($|(?=[\\r\\n]))`;\n        continue;\n      }\n    }\n\n    if (flags.s && source[i] === '.') {\n      pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n      continue;\n    }\n\n    pattern += source[i];\n    if (source[i] === '\\\\') {\n      isEscaped = true;\n    } else if (inCharGroup && source[i] === ']') {\n      inCharGroup = false;\n    } else if (!inCharGroup && source[i] === '[') {\n      inCharGroup = true;\n    }\n  }\n\n  try {\n    new RegExp(pattern);\n  } catch {\n    console.warn(\n      `Could not convert regex pattern at ${refs.currentPath.join(\n        '/',\n      )} to a flag-independent form! Falling back to the flag-ignorant source`,\n    );\n    return regex.source;\n  }\n\n  return pattern;\n}\n","import type { ZodMapDef, ZodRecordDef, ZodTypeAny } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport { parseBrandedDef } from './branded';\nimport type { JsonSchema7EnumType } from './enum';\nimport { parseStringDef, type JsonSchema7StringType } from './string';\ntype JsonSchema7RecordPropertyNamesType =\n  | Omit<JsonSchema7StringType, 'type'>\n  | Omit<JsonSchema7EnumType, 'type'>;\n\nexport type JsonSchema7RecordType = {\n  type: 'object';\n  additionalProperties?: JsonSchema7Type | true;\n  propertyNames?: JsonSchema7RecordPropertyNamesType;\n};\n\nexport function parseRecordDef(\n  def: ZodRecordDef<ZodTypeAny, ZodTypeAny> | ZodMapDef,\n  refs: Refs,\n): JsonSchema7RecordType {\n  const schema: JsonSchema7RecordType = {\n    type: 'object',\n    additionalProperties:\n      parseDef(def.valueType._def, {\n        ...refs,\n        currentPath: [...refs.currentPath, 'additionalProperties'],\n      }) ?? refs.allowedAdditionalProperties,\n  };\n\n  if (\n    def.keyType?._def.typeName === 'ZodString' &&\n    def.keyType._def.checks?.length\n  ) {\n    const { type: _type, ...keyType } = parseStringDef(def.keyType._def, refs);\n\n    return {\n      ...schema,\n      propertyNames: keyType,\n    };\n  } else if (def.keyType?._def.typeName === 'ZodEnum') {\n    return {\n      ...schema,\n      propertyNames: {\n        enum: def.keyType._def.values,\n      },\n    };\n  } else if (\n    def.keyType?._def.typeName === 'ZodBranded' &&\n    def.keyType._def.type._def.typeName === 'ZodString' &&\n    def.keyType._def.type._def.checks?.length\n  ) {\n    const { type: _type, ...keyType } = parseBrandedDef(\n      def.keyType._def,\n      refs,\n    ) as JsonSchema7StringType;\n\n    return {\n      ...schema,\n      propertyNames: keyType,\n    };\n  }\n\n  return schema;\n}\n","import type { ZodMapDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport { parseAnyDef } from './any';\nimport { parseRecordDef, type JsonSchema7RecordType } from './record';\nexport type JsonSchema7MapType = {\n  type: 'array';\n  maxItems: 125;\n  items: {\n    type: 'array';\n    items: [JsonSchema7Type, JsonSchema7Type];\n    minItems: 2;\n    maxItems: 2;\n  };\n};\n\nexport function parseMapDef(\n  def: ZodMapDef,\n  refs: Refs,\n): JsonSchema7MapType | JsonSchema7RecordType {\n  if (refs.mapStrategy === 'record') {\n    return parseRecordDef(def, refs);\n  }\n\n  const keys =\n    parseDef(def.keyType._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'items', 'items', '0'],\n    }) || parseAnyDef();\n  const values =\n    parseDef(def.valueType._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'items', 'items', '1'],\n    }) || parseAnyDef();\n  return {\n    type: 'array',\n    maxItems: 125,\n    items: {\n      type: 'array',\n      items: [keys, values],\n      minItems: 2,\n      maxItems: 2,\n    },\n  };\n}\n","import type { ZodNativeEnumDef } from 'zod/v3';\n\nexport type JsonSchema7NativeEnumType = {\n  type: 'string' | 'number' | ['string', 'number'];\n  enum: (string | number)[];\n};\n\nexport function parseNativeEnumDef(\n  def: ZodNativeEnumDef,\n): JsonSchema7NativeEnumType {\n  const object = def.values;\n  const actualKeys = Object.keys(def.values).filter((key: string) => {\n    return typeof object[object[key]] !== 'number';\n  });\n\n  const actualValues = actualKeys.map((key: string) => object[key]);\n\n  const parsedTypes = Array.from(\n    new Set(actualValues.map((values: string | number) => typeof values)),\n  );\n\n  return {\n    type:\n      parsedTypes.length === 1\n        ? parsedTypes[0] === 'string'\n          ? 'string'\n          : 'number'\n        : ['string', 'number'],\n    enum: actualValues,\n  };\n}\n","import { parseAnyDef, type JsonSchema7AnyType } from './any';\nexport type JsonSchema7NeverType = {\n  not: JsonSchema7AnyType;\n};\n\nexport function parseNeverDef(): JsonSchema7NeverType | undefined {\n  return { not: parseAnyDef() };\n}\n","export type JsonSchema7NullType = {\n  type: 'null';\n};\n\nexport function parseNullDef(): JsonSchema7NullType {\n  return {\n    type: 'null',\n  };\n}\n","import type {\n  ZodDiscriminatedUnionDef,\n  ZodLiteralDef,\n  ZodTypeAny,\n  ZodUnionDef,\n} from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport const primitiveMappings = {\n  ZodString: 'string',\n  ZodNumber: 'number',\n  ZodBigInt: 'integer',\n  ZodBoolean: 'boolean',\n  ZodNull: 'null',\n} as const;\ntype ZodPrimitive = keyof typeof primitiveMappings;\ntype JsonSchema7Primitive =\n  (typeof primitiveMappings)[keyof typeof primitiveMappings];\n\nexport type JsonSchema7UnionType =\n  | JsonSchema7PrimitiveUnionType\n  | JsonSchema7AnyOfType;\n\ntype JsonSchema7PrimitiveUnionType =\n  | {\n      type: JsonSchema7Primitive | JsonSchema7Primitive[];\n    }\n  | {\n      type: JsonSchema7Primitive | JsonSchema7Primitive[];\n      enum: (string | number | bigint | boolean | null)[];\n    };\n\ntype JsonSchema7AnyOfType = {\n  anyOf: JsonSchema7Type[];\n};\n\nexport function parseUnionDef(\n  def: ZodUnionDef | ZodDiscriminatedUnionDef<any, any>,\n  refs: Refs,\n): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined {\n  const options: readonly ZodTypeAny[] =\n    def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n\n  // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.\n  if (\n    options.every(\n      x =>\n        x._def.typeName in primitiveMappings &&\n        (!x._def.checks || !x._def.checks.length),\n    )\n  ) {\n    // all types in union are primitive and lack checks, so might as well squash into {type: [...]}\n\n    const types = options.reduce((types: JsonSchema7Primitive[], x) => {\n      const type = primitiveMappings[x._def.typeName as ZodPrimitive]; //Can be safely casted due to row 43\n      return type && !types.includes(type) ? [...types, type] : types;\n    }, []);\n\n    return {\n      type: types.length > 1 ? types : types[0],\n    };\n  } else if (\n    options.every(x => x._def.typeName === 'ZodLiteral' && !x.description)\n  ) {\n    // all options literals\n\n    const types = options.reduce(\n      (acc: JsonSchema7Primitive[], x: { _def: ZodLiteralDef }) => {\n        const type = typeof x._def.value;\n        switch (type) {\n          case 'string':\n          case 'number':\n          case 'boolean':\n            return [...acc, type];\n          case 'bigint':\n            return [...acc, 'integer' as const];\n          case 'object':\n            if (x._def.value === null) return [...acc, 'null' as const];\n          case 'symbol':\n          case 'undefined':\n          case 'function':\n          default:\n            return acc;\n        }\n      },\n      [],\n    );\n\n    if (types.length === options.length) {\n      // all the literals are primitive, as far as null can be considered primitive\n\n      const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n      return {\n        type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n        enum: options.reduce(\n          (acc, x) => {\n            return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n          },\n          [] as (string | number | bigint | boolean | null)[],\n        ),\n      };\n    }\n  } else if (options.every(x => x._def.typeName === 'ZodEnum')) {\n    return {\n      type: 'string',\n      enum: options.reduce(\n        (acc: string[], x) => [\n          ...acc,\n          ...x._def.values.filter((x: string) => !acc.includes(x)),\n        ],\n        [],\n      ),\n    };\n  }\n\n  return asAnyOf(def, refs);\n}\n\nconst asAnyOf = (\n  def: ZodUnionDef | ZodDiscriminatedUnionDef<any, any>,\n  refs: Refs,\n): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined => {\n  const anyOf = (\n    (def.options instanceof Map\n      ? Array.from(def.options.values())\n      : def.options) as any[]\n  )\n    .map((x, i) =>\n      parseDef(x._def, {\n        ...refs,\n        currentPath: [...refs.currentPath, 'anyOf', `${i}`],\n      }),\n    )\n    .filter(\n      (x): x is JsonSchema7Type =>\n        !!x &&\n        (!refs.strictUnions ||\n          (typeof x === 'object' && Object.keys(x).length > 0)),\n    );\n\n  return anyOf.length ? { anyOf } : undefined;\n};\n","import type { ZodNullableDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport type { JsonSchema7NullType } from './null';\nimport { primitiveMappings } from './union';\n\nexport type JsonSchema7NullableType =\n  | {\n      anyOf: [JsonSchema7Type, JsonSchema7NullType];\n    }\n  | {\n      type: [string, 'null'];\n    };\n\nexport function parseNullableDef(\n  def: ZodNullableDef,\n  refs: Refs,\n): JsonSchema7NullableType | undefined {\n  if (\n    ['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(\n      def.innerType._def.typeName,\n    ) &&\n    (!def.innerType._def.checks || !def.innerType._def.checks.length)\n  ) {\n    return {\n      type: [\n        primitiveMappings[\n          def.innerType._def.typeName as keyof typeof primitiveMappings\n        ],\n        'null',\n      ],\n    };\n  }\n\n  const base = parseDef(def.innerType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'anyOf', '0'],\n  });\n\n  return base && { anyOf: [base, { type: 'null' }] };\n}\n","import type { ZodNumberDef } from 'zod/v3';\n\nexport type JsonSchema7NumberType = {\n  type: 'number' | 'integer';\n  minimum?: number;\n  exclusiveMinimum?: number;\n  maximum?: number;\n  exclusiveMaximum?: number;\n  multipleOf?: number;\n};\n\nexport function parseNumberDef(def: ZodNumberDef): JsonSchema7NumberType {\n  const res: JsonSchema7NumberType = {\n    type: 'number',\n  };\n\n  if (!def.checks) return res;\n\n  for (const check of def.checks) {\n    switch (check.kind) {\n      case 'int':\n        res.type = 'integer';\n        break;\n      case 'min':\n        if (check.inclusive) {\n          res.minimum = check.value;\n        } else {\n          res.exclusiveMinimum = check.value;\n        }\n        break;\n      case 'max':\n        if (check.inclusive) {\n          res.maximum = check.value;\n        } else {\n          res.exclusiveMaximum = check.value;\n        }\n        break;\n      case 'multipleOf':\n        res.multipleOf = check.value;\n        break;\n    }\n  }\n  return res;\n}\n","import type { ZodObjectDef, ZodTypeAny } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport type JsonSchema7ObjectType = {\n  type: 'object';\n  properties: Record<string, JsonSchema7Type>;\n  additionalProperties?: boolean | JsonSchema7Type;\n  required?: string[];\n};\n\nexport function parseObjectDef(def: ZodObjectDef, refs: Refs) {\n  const result: JsonSchema7ObjectType = {\n    type: 'object',\n    properties: {},\n  };\n\n  const required: string[] = [];\n\n  const shape = def.shape();\n\n  for (const propName in shape) {\n    let propDef = shape[propName];\n\n    if (propDef === undefined || propDef._def === undefined) {\n      continue;\n    }\n\n    const propOptional = safeIsOptional(propDef);\n\n    const parsedDef = parseDef(propDef._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'properties', propName],\n      propertyPath: [...refs.currentPath, 'properties', propName],\n    });\n\n    if (parsedDef === undefined) {\n      continue;\n    }\n\n    result.properties[propName] = parsedDef;\n\n    if (!propOptional) {\n      required.push(propName);\n    }\n  }\n\n  if (required.length) {\n    result.required = required;\n  }\n\n  const additionalProperties = decideAdditionalProperties(def, refs);\n\n  if (additionalProperties !== undefined) {\n    result.additionalProperties = additionalProperties;\n  }\n\n  return result;\n}\n\nfunction decideAdditionalProperties(def: ZodObjectDef, refs: Refs) {\n  if (def.catchall._def.typeName !== 'ZodNever') {\n    return parseDef(def.catchall._def, {\n      ...refs,\n      currentPath: [...refs.currentPath, 'additionalProperties'],\n    });\n  }\n\n  switch (def.unknownKeys) {\n    case 'passthrough':\n      return refs.allowedAdditionalProperties;\n    case 'strict':\n      return refs.rejectedAdditionalProperties;\n    case 'strip':\n      return refs.removeAdditionalStrategy === 'strict'\n        ? refs.allowedAdditionalProperties\n        : refs.rejectedAdditionalProperties;\n  }\n}\n\nfunction safeIsOptional(schema: ZodTypeAny): boolean {\n  try {\n    return schema.isOptional();\n  } catch {\n    return true;\n  }\n}\n","import type { ZodOptionalDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport { parseAnyDef } from './any';\n\nexport const parseOptionalDef = (\n  def: ZodOptionalDef,\n  refs: Refs,\n): JsonSchema7Type | undefined => {\n  if (refs.currentPath.toString() === refs.propertyPath?.toString()) {\n    return parseDef(def.innerType._def, refs);\n  }\n\n  const innerSchema = parseDef(def.innerType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'anyOf', '1'],\n  });\n\n  return innerSchema\n    ? { anyOf: [{ not: parseAnyDef() }, innerSchema] }\n    : parseAnyDef();\n};\n","import type { ZodPipelineDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\nimport type { JsonSchema7AllOfType } from './intersection';\n\nexport const parsePipelineDef = (\n  def: ZodPipelineDef<any, any>,\n  refs: Refs,\n): JsonSchema7AllOfType | JsonSchema7Type | undefined => {\n  if (refs.pipeStrategy === 'input') {\n    return parseDef(def.in._def, refs);\n  } else if (refs.pipeStrategy === 'output') {\n    return parseDef(def.out._def, refs);\n  }\n\n  const inputSchema = parseDef(def.in._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'allOf', '0'],\n  });\n  const outputSchema = parseDef(def.out._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'allOf', inputSchema ? '1' : '0'],\n  });\n\n  return {\n    allOf: [inputSchema, outputSchema].filter(\n      (schema): schema is JsonSchema7Type => schema !== undefined,\n    ),\n  };\n};\n","import type { ZodPromiseDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport function parsePromiseDef(\n  def: ZodPromiseDef,\n  refs: Refs,\n): JsonSchema7Type | undefined {\n  return parseDef(def.type._def, refs);\n}\n","import type { ZodSetDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport type JsonSchema7SetType = {\n  type: 'array';\n  uniqueItems: true;\n  items?: JsonSchema7Type;\n  minItems?: number;\n  maxItems?: number;\n};\n\nexport function parseSetDef(def: ZodSetDef, refs: Refs): JsonSchema7SetType {\n  const items = parseDef(def.valueType._def, {\n    ...refs,\n    currentPath: [...refs.currentPath, 'items'],\n  });\n\n  const schema: JsonSchema7SetType = {\n    type: 'array',\n    uniqueItems: true,\n    items,\n  };\n\n  if (def.minSize) {\n    schema.minItems = def.minSize.value;\n  }\n\n  if (def.maxSize) {\n    schema.maxItems = def.maxSize.value;\n  }\n\n  return schema;\n}\n","import type { ZodTupleDef, ZodTupleItems, ZodTypeAny } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { JsonSchema7Type } from '../parse-types';\nimport type { Refs } from '../refs';\n\nexport type JsonSchema7TupleType = {\n  type: 'array';\n  minItems: number;\n  items: JsonSchema7Type[];\n} & (\n  | {\n      maxItems: number;\n    }\n  | {\n      additionalItems?: JsonSchema7Type;\n    }\n);\n\nexport function parseTupleDef(\n  def: ZodTupleDef<ZodTupleItems | [], ZodTypeAny | null>,\n  refs: Refs,\n): JsonSchema7TupleType {\n  if (def.rest) {\n    return {\n      type: 'array',\n      minItems: def.items.length,\n      items: def.items\n        .map((x, i) =>\n          parseDef(x._def, {\n            ...refs,\n            currentPath: [...refs.currentPath, 'items', `${i}`],\n          }),\n        )\n        .reduce(\n          (acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]),\n          [],\n        ),\n      additionalItems: parseDef(def.rest._def, {\n        ...refs,\n        currentPath: [...refs.currentPath, 'additionalItems'],\n      }),\n    };\n  } else {\n    return {\n      type: 'array',\n      minItems: def.items.length,\n      maxItems: def.items.length,\n      items: def.items\n        .map((x, i) =>\n          parseDef(x._def, {\n            ...refs,\n            currentPath: [...refs.currentPath, 'items', `${i}`],\n          }),\n        )\n        .reduce(\n          (acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]),\n          [],\n        ),\n    };\n  }\n}\n","import { parseAnyDef, type JsonSchema7AnyType } from './any';\nexport type JsonSchema7UndefinedType = {\n  not: JsonSchema7AnyType;\n};\n\nexport function parseUndefinedDef(): JsonSchema7UndefinedType {\n  return {\n    not: parseAnyDef(),\n  };\n}\n","import { parseAnyDef, type JsonSchema7AnyType } from './any';\nexport type JsonSchema7UnknownType = JsonSchema7AnyType;\n\nexport function parseUnknownDef(): JsonSchema7UnknownType {\n  return parseAnyDef();\n}\n","import type { ZodReadonlyDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport type { Refs } from '../refs';\n\nexport const parseReadonlyDef = (def: ZodReadonlyDef<any>, refs: Refs) => {\n  return parseDef(def.innerType._def, refs);\n};\n","import type { ZodFirstPartyTypeKind } from 'zod/v3';\nimport { parseAnyDef } from './parsers/any';\nimport { parseArrayDef } from './parsers/array';\nimport { parseBigintDef } from './parsers/bigint';\nimport { parseBooleanDef } from './parsers/boolean';\nimport { parseBrandedDef } from './parsers/branded';\nimport { parseCatchDef } from './parsers/catch';\nimport { parseDateDef } from './parsers/date';\nimport { parseDefaultDef } from './parsers/default';\nimport { parseEffectsDef } from './parsers/effects';\nimport { parseEnumDef } from './parsers/enum';\nimport { parseIntersectionDef } from './parsers/intersection';\nimport { parseLiteralDef } from './parsers/literal';\nimport { parseMapDef } from './parsers/map';\nimport { parseNativeEnumDef } from './parsers/native-enum';\nimport { parseNeverDef } from './parsers/never';\nimport { parseNullDef } from './parsers/null';\nimport { parseNullableDef } from './parsers/nullable';\nimport { parseNumberDef } from './parsers/number';\nimport { parseObjectDef } from './parsers/object';\nimport { parseOptionalDef } from './parsers/optional';\nimport { parsePipelineDef } from './parsers/pipeline';\nimport { parsePromiseDef } from './parsers/promise';\nimport { parseRecordDef } from './parsers/record';\nimport { parseSetDef } from './parsers/set';\nimport { parseStringDef } from './parsers/string';\nimport { parseTupleDef } from './parsers/tuple';\nimport { parseUndefinedDef } from './parsers/undefined';\nimport { parseUnionDef } from './parsers/union';\nimport { parseUnknownDef } from './parsers/unknown';\nimport type { Refs } from './refs';\nimport { parseReadonlyDef } from './parsers/readonly';\nimport type { JsonSchema7Type } from './parse-types';\n\nexport type InnerDefGetter = () => any;\n\ntype Zod3TypeName = `${ZodFirstPartyTypeKind}`;\n\nexport const selectParser = (\n  def: any,\n  typeName: Zod3TypeName,\n  refs: Refs,\n): JsonSchema7Type | undefined | InnerDefGetter => {\n  switch (typeName) {\n    case 'ZodString':\n      return parseStringDef(def, refs);\n    case 'ZodNumber':\n      return parseNumberDef(def);\n    case 'ZodObject':\n      return parseObjectDef(def, refs);\n    case 'ZodBigInt':\n      return parseBigintDef(def);\n    case 'ZodBoolean':\n      return parseBooleanDef();\n    case 'ZodDate':\n      return parseDateDef(def, refs);\n    case 'ZodUndefined':\n      return parseUndefinedDef();\n    case 'ZodNull':\n      return parseNullDef();\n    case 'ZodArray':\n      return parseArrayDef(def, refs);\n    case 'ZodUnion':\n    case 'ZodDiscriminatedUnion':\n      return parseUnionDef(def, refs);\n    case 'ZodIntersection':\n      return parseIntersectionDef(def, refs);\n    case 'ZodTuple':\n      return parseTupleDef(def, refs);\n    case 'ZodRecord':\n      return parseRecordDef(def, refs);\n    case 'ZodLiteral':\n      return parseLiteralDef(def);\n    case 'ZodEnum':\n      return parseEnumDef(def);\n    case 'ZodNativeEnum':\n      return parseNativeEnumDef(def);\n    case 'ZodNullable':\n      return parseNullableDef(def, refs);\n    case 'ZodOptional':\n      return parseOptionalDef(def, refs);\n    case 'ZodMap':\n      return parseMapDef(def, refs);\n    case 'ZodSet':\n      return parseSetDef(def, refs);\n    case 'ZodLazy':\n      return () => (def as any).getter()._def;\n    case 'ZodPromise':\n      return parsePromiseDef(def, refs);\n    case 'ZodNaN':\n    case 'ZodNever':\n      return parseNeverDef();\n    case 'ZodEffects':\n      return parseEffectsDef(def, refs);\n    case 'ZodAny':\n      return parseAnyDef();\n    case 'ZodUnknown':\n      return parseUnknownDef();\n    case 'ZodDefault':\n      return parseDefaultDef(def, refs);\n    case 'ZodBranded':\n      return parseBrandedDef(def, refs);\n    case 'ZodReadonly':\n      return parseReadonlyDef(def, refs);\n    case 'ZodCatch':\n      return parseCatchDef(def, refs);\n    case 'ZodPipeline':\n      return parsePipelineDef(def, refs);\n    case 'ZodFunction':\n    case 'ZodVoid':\n    case 'ZodSymbol':\n      return undefined;\n    default:\n      /* c8 ignore next */\n      return ((_: never) => undefined)(typeName);\n  }\n};\n","export const getRelativePath = (pathA: string[], pathB: string[]) => {\n  let i = 0;\n  for (; i < pathA.length && i < pathB.length; i++) {\n    if (pathA[i] !== pathB[i]) break;\n  }\n  return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/');\n};\n","import type { ZodTypeDef } from 'zod/v3';\nimport type { Refs, Seen } from './refs';\nimport { ignoreOverride } from './options';\nimport type { JsonSchema7Type } from './parse-types';\nimport { selectParser } from './select-parser';\nimport { getRelativePath } from './get-relative-path';\nimport { parseAnyDef } from './parsers/any';\n\nexport function parseDef(\n  def: ZodTypeDef,\n  refs: Refs,\n  forceResolution = false, // Forces a new schema to be instantiated even though its def has been seen. Used for improving refs in definitions. See https://github.com/StefanTerdell/zod-to-json-schema/pull/61.\n): JsonSchema7Type | undefined {\n  const seenItem = refs.seen.get(def);\n\n  if (refs.override) {\n    const overrideResult = refs.override?.(\n      def,\n      refs,\n      seenItem,\n      forceResolution,\n    );\n\n    if (overrideResult !== ignoreOverride) {\n      return overrideResult;\n    }\n  }\n\n  if (seenItem && !forceResolution) {\n    const seenSchema = get$ref(seenItem, refs);\n\n    if (seenSchema !== undefined) {\n      return seenSchema;\n    }\n  }\n\n  const newItem: Seen = { def, path: refs.currentPath, jsonSchema: undefined };\n\n  refs.seen.set(def, newItem);\n\n  const jsonSchemaOrGetter = selectParser(def, (def as any).typeName, refs);\n\n  // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive)\n  const jsonSchema =\n    typeof jsonSchemaOrGetter === 'function'\n      ? parseDef(jsonSchemaOrGetter(), refs)\n      : jsonSchemaOrGetter;\n\n  if (jsonSchema) {\n    addMeta(def, refs, jsonSchema);\n  }\n\n  if (refs.postProcess) {\n    const postProcessResult = refs.postProcess(jsonSchema, def, refs);\n\n    newItem.jsonSchema = jsonSchema;\n\n    return postProcessResult;\n  }\n\n  newItem.jsonSchema = jsonSchema;\n\n  return jsonSchema;\n}\n\nconst get$ref = (\n  item: Seen,\n  refs: Refs,\n):\n  | {\n      $ref: string;\n    }\n  | {}\n  | undefined => {\n  switch (refs.$refStrategy) {\n    case 'root':\n      return { $ref: item.path.join('/') };\n    case 'relative':\n      return { $ref: getRelativePath(refs.currentPath, item.path) };\n    case 'none':\n    case 'seen': {\n      if (\n        item.path.length < refs.currentPath.length &&\n        item.path.every((value, index) => refs.currentPath[index] === value)\n      ) {\n        console.warn(\n          `Recursive reference detected at ${refs.currentPath.join(\n            '/',\n          )}! Defaulting to any`,\n        );\n\n        return parseAnyDef();\n      }\n\n      return refs.$refStrategy === 'seen' ? parseAnyDef() : undefined;\n    }\n  }\n};\n\nconst addMeta = (\n  def: ZodTypeDef,\n  refs: Refs,\n  jsonSchema: JsonSchema7Type,\n): JsonSchema7Type => {\n  if (def.description) {\n    jsonSchema.description = def.description;\n  }\n  return jsonSchema;\n};\n","import type { ZodTypeDef } from 'zod/v3';\nimport { getDefaultOptions, type Options } from './options';\nimport type { JsonSchema7Type } from './parse-types';\n\nexport type Refs = {\n  seen: Map<ZodTypeDef, Seen>;\n  currentPath: string[];\n  propertyPath: string[] | undefined;\n} & Options;\n\nexport type Seen = {\n  def: ZodTypeDef;\n  path: string[];\n  jsonSchema: JsonSchema7Type | undefined;\n};\n\nexport const getRefs = (options?: string | Partial<Options>): Refs => {\n  const _options = getDefaultOptions(options);\n  const currentPath =\n    _options.name !== undefined\n      ? [..._options.basePath, _options.definitionPath, _options.name]\n      : _options.basePath;\n  return {\n    ..._options,\n    currentPath: currentPath,\n    propertyPath: undefined,\n    seen: new Map(\n      Object.entries(_options.definitions).map(([name, def]) => [\n        def._def,\n        {\n          def: def._def,\n          path: [..._options.basePath, _options.definitionPath, name],\n          // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n          jsonSchema: undefined,\n        },\n      ]),\n    ),\n  };\n};\n","import type { ZodSchema } from 'zod/v3';\nimport type { Options } from './options';\nimport { parseDef } from './parse-def';\nimport type { JsonSchema7Type } from './parse-types';\nimport { getRefs } from './refs';\nimport { parseAnyDef } from './parsers/any';\n\nconst zod3ToJsonSchema = (\n  schema: ZodSchema<any>,\n  options?: Partial<Options> | string,\n): JsonSchema7Type & {\n  $schema?: string;\n  definitions?: {\n    [key: string]: JsonSchema7Type;\n  };\n} => {\n  const refs = getRefs(options);\n\n  let definitions =\n    typeof options === 'object' && options.definitions\n      ? Object.entries(options.definitions).reduce(\n          (acc: { [key: string]: JsonSchema7Type }, [name, schema]) => ({\n            ...acc,\n            [name]:\n              parseDef(\n                schema._def,\n                {\n                  ...refs,\n                  currentPath: [...refs.basePath, refs.definitionPath, name],\n                },\n                true,\n              ) ?? parseAnyDef(),\n          }),\n          {},\n        )\n      : undefined;\n\n  const name =\n    typeof options === 'string'\n      ? options\n      : options?.nameStrategy === 'title'\n        ? undefined\n        : options?.name;\n\n  const main =\n    parseDef(\n      schema._def,\n      name === undefined\n        ? refs\n        : {\n            ...refs,\n            currentPath: [...refs.basePath, refs.definitionPath, name],\n          },\n      false,\n    ) ?? (parseAnyDef() as JsonSchema7Type);\n\n  const title =\n    typeof options === 'object' &&\n    options.name !== undefined &&\n    options.nameStrategy === 'title'\n      ? options.name\n      : undefined;\n\n  if (title !== undefined) {\n    main.title = title;\n  }\n\n  const combined: ReturnType<typeof zod3ToJsonSchema> =\n    name === undefined\n      ? definitions\n        ? {\n            ...main,\n            [refs.definitionPath]: definitions,\n          }\n        : main\n      : {\n          $ref: [\n            ...(refs.$refStrategy === 'relative' ? [] : refs.basePath),\n            refs.definitionPath,\n            name,\n          ].join('/'),\n          [refs.definitionPath]: {\n            ...definitions,\n            [name]: main,\n          },\n        };\n\n  combined.$schema = 'http://json-schema.org/draft-07/schema#';\n\n  return combined;\n};\n\nexport { zod3ToJsonSchema };\n","import {\n  EventSourceParserStream,\n  type EventSourceMessage,\n} from 'eventsource-parser/stream';\nimport { safeParseJSON, type ParseResult } from './parse-json';\nimport type { FlexibleSchema } from './schema';\n\n/**\n * Parses a JSON event stream into a stream of parsed JSON objects.\n */\nexport function parseJsonEventStream<T>({\n  stream,\n  schema,\n}: {\n  stream: ReadableStream<Uint8Array>;\n  schema: FlexibleSchema<T>;\n}): ReadableStream<ParseResult<T>> {\n  return stream\n    .pipeThrough(new TextDecoderStream())\n    .pipeThrough(new EventSourceParserStream())\n    .pipeThrough(\n      new TransformStream<EventSourceMessage, ParseResult<T>>({\n        async transform({ data }, controller) {\n          // ignore the 'DONE' event that e.g. OpenAI sends:\n          if (data === '[DONE]') {\n            return;\n          }\n\n          controller.enqueue(await safeParseJSON({ text: data, schema }));\n        },\n      }),\n    );\n}\n","import { InvalidArgumentError } from '@ai-sdk/provider';\nimport { safeValidateTypes } from './validate-types';\nimport type { FlexibleSchema } from './schema';\n\nexport async function parseProviderOptions<OPTIONS>({\n  provider,\n  providerOptions,\n  schema,\n}: {\n  provider: string;\n  providerOptions: Record<string, unknown> | undefined;\n  schema: FlexibleSchema<OPTIONS>;\n}): Promise<OPTIONS | undefined> {\n  if (providerOptions?.[provider] == null) {\n    return undefined;\n  }\n\n  const parsedProviderOptions = await safeValidateTypes<OPTIONS | undefined>({\n    value: providerOptions[provider],\n    schema,\n  });\n\n  if (!parsedProviderOptions.success) {\n    throw new InvalidArgumentError({\n      argument: 'providerOptions',\n      message: `invalid ${provider} provider options`,\n      cause: parsedProviderOptions.error,\n    });\n  }\n\n  return parsedProviderOptions.value;\n}\n","import { APICallError } from '@ai-sdk/provider';\nimport { convertAsyncIteratorToReadableStream } from './convert-async-iterator-to-readable-stream';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport type { FetchFunction } from './fetch-function';\nimport { generateId } from './generate-id';\nimport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nimport { handleFetchError } from './handle-fetch-error';\nimport { isAbortError } from './is-abort-error';\nimport type { ResponseHandler } from './response-handler';\nimport { VERSION } from './version';\nimport { withUserAgentSuffix } from './with-user-agent-suffix';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => globalThis.fetch;\n\n/**\n * A part of a streaming multipart/form-data request body.\n *\n * Parts are emitted in array order, which providers may depend on\n * (e.g. xAI requires expiry fields to precede the file part).\n */\nexport type MultipartStreamPart =\n  | { type: 'field'; name: string; value: string }\n  | {\n      type: 'file';\n      name: string;\n      filename?: string;\n      mediaType?: string;\n      content: ReadableStream<Uint8Array> | Uint8Array;\n    };\n\n// header parameter values must not smuggle CR/LF or break the quoted-string\nfunction escapeMultipartHeaderValue(value: string): string {\n  return value\n    .replace(/[\\r\\n]/g, '')\n    .replace(/\\\\/g, '\\\\\\\\')\n    .replace(/\"/g, '\\\\\"');\n}\n\ninterface MultipartBody {\n  stream: ReadableStream<Uint8Array>;\n  /**\n   * Deterministically releases every stream part after a failed or abandoned\n   * request — fetch implementations do not reliably cancel streaming request\n   * bodies on rejection/abort. Safe to call multiple times.\n   */\n  dispose: (reason?: unknown) => Promise<void>;\n}\n\nfunction createMultipartBody(\n  parts: Array<MultipartStreamPart>,\n  boundary: string,\n): MultipartBody {\n  const encoder = new TextEncoder();\n\n  let disposed = false;\n  let activeReader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n  const enteredStreams = new Set<ReadableStream<Uint8Array>>();\n\n  async function* emitParts(): AsyncGenerator<Uint8Array> {\n    for (const part of parts) {\n      if (disposed) return;\n\n      const disposition = `--${boundary}\\r\\nContent-Disposition: form-data; name=\"${escapeMultipartHeaderValue(part.name)}\"`;\n\n      if (part.type === 'field') {\n        yield encoder.encode(`${disposition}\\r\\n\\r\\n${part.value}\\r\\n`);\n        continue;\n      }\n\n      // a filename parameter is always emitted: without it, multipart\n      // parsers treat the part as a scalar field (FormData defaults to\n      // \"blob\" as well)\n      const filenameParameter = `; filename=\"${escapeMultipartHeaderValue(\n        part.filename ?? 'blob',\n      )}\"`;\n      const mediaType = (part.mediaType ?? 'application/octet-stream').replace(\n        /[\\r\\n]/g,\n        '',\n      );\n\n      yield encoder.encode(\n        `${disposition}${filenameParameter}\\r\\nContent-Type: ${mediaType}\\r\\n\\r\\n`,\n      );\n\n      if (part.content instanceof Uint8Array) {\n        yield part.content;\n      } else {\n        // synchronous handoff (no awaits) so dispose() sees either the\n        // active reader or an un-entered stream, never neither\n        const reader = part.content.getReader();\n        activeReader = reader;\n        enteredStreams.add(part.content);\n\n        let finished = false;\n        try {\n          while (true) {\n            const { done, value } = await reader.read();\n            if (done || disposed) {\n              finished = done;\n              break;\n            }\n            yield value;\n          }\n        } finally {\n          activeReader = undefined;\n          // early teardown (dispose/cancel): release the source stream\n          if (!finished) {\n            await reader.cancel().catch(() => {});\n          }\n          reader.releaseLock();\n        }\n\n        if (disposed) return;\n      }\n\n      yield encoder.encode('\\r\\n');\n    }\n\n    yield encoder.encode(`--${boundary}--\\r\\n`);\n  }\n\n  return {\n    stream: convertAsyncIteratorToReadableStream(emitParts()),\n    async dispose(reason?: unknown) {\n      if (disposed) return;\n      disposed = true;\n\n      // an active reader holds the lock; cancelling it resolves a pending\n      // read() and propagates cancellation to the underlying source\n      const reader = activeReader;\n      if (reader != null) {\n        await reader.cancel(reason).catch(() => {});\n      }\n\n      // streams the generator never entered are still unlocked\n      for (const part of parts) {\n        if (\n          part.type === 'file' &&\n          !(part.content instanceof Uint8Array) &&\n          !enteredStreams.has(part.content)\n        ) {\n          await part.content.cancel(reason).catch(() => {});\n        }\n      }\n    },\n  };\n}\n\n/**\n * POSTs a multipart/form-data body as a request stream, so file parts backed\n * by a `ReadableStream` are sent without buffering the full file in memory.\n *\n * Requires a fetch implementation that supports streaming request bodies\n * (`duplex: 'half'`). Callers with fully buffered payloads can keep using\n * `postFormDataToApi`.\n */\nexport const postMultipartStreamToApi = async <T>({\n  url,\n  headers = {},\n  parts,\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch = getOriginalFetch(),\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  parts: Array<MultipartStreamPart>;\n  failedResponseHandler: ResponseHandler<Error>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) => {\n  const boundary = `ai-sdk-multipart-${generateId()}`;\n\n  // stream contents cannot be replayed for error reporting; expose part\n  // names, field values, and file placeholders only\n  const requestBodyValues = Object.fromEntries(\n    parts.map(part => [\n      part.name,\n      part.type === 'field'\n        ? part.value\n        : `<file:${part.filename ?? part.name}>`,\n    ]),\n  );\n\n  const body = createMultipartBody(parts, boundary);\n\n  try {\n    const requestInit: RequestInit & { duplex: 'half' } = {\n      method: 'POST',\n      headers: withUserAgentSuffix(\n        {\n          ...headers,\n          'Content-Type': `multipart/form-data; boundary=${boundary}`,\n        },\n        `ai-sdk/provider-utils/${VERSION}`,\n        getRuntimeEnvironmentUserAgent(),\n      ),\n      body: body.stream,\n      duplex: 'half',\n      signal: abortSignal,\n    };\n\n    const response = await fetch(url, requestInit);\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.ok) {\n      let errorInformation: {\n        value: Error;\n        responseHeaders?: Record<string, string> | undefined;\n      };\n\n      try {\n        errorInformation = await failedResponseHandler({\n          response,\n          url,\n          requestBodyValues,\n        });\n      } catch (error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n\n        throw new APICallError({\n          message: 'Failed to process error response',\n          cause: error,\n          statusCode: response.status,\n          url,\n          responseHeaders,\n          requestBodyValues,\n        });\n      }\n\n      throw errorInformation.value;\n    }\n\n    try {\n      return await successfulResponseHandler({\n        response,\n        url,\n        requestBodyValues,\n      });\n    } catch (error) {\n      if (error instanceof Error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n      }\n\n      throw new APICallError({\n        message: 'Failed to process successful response',\n        cause: error,\n        statusCode: response.status,\n        url,\n        responseHeaders,\n        requestBodyValues,\n      });\n    }\n  } catch (error) {\n    // fetch implementations do not reliably cancel streaming request bodies\n    // on rejection/abort — release every source part deterministically\n    await body.dispose(error);\n    throw handleFetchError({ error, url, requestBodyValues });\n  }\n};\n","import { APICallError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport type { FetchFunction } from './fetch-function';\nimport { handleFetchError } from './handle-fetch-error';\nimport { isAbortError } from './is-abort-error';\nimport type { ResponseHandler } from './response-handler';\nimport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nimport { withUserAgentSuffix } from './with-user-agent-suffix';\nimport { VERSION } from './version';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => globalThis.fetch;\n\nexport const postJsonToApi = async <T>({\n  url,\n  headers,\n  body,\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch,\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  body: unknown;\n  failedResponseHandler: ResponseHandler<APICallError>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) =>\n  await postToApi({\n    url,\n    headers: {\n      'Content-Type': 'application/json',\n      ...headers,\n    },\n    body: {\n      content: JSON.stringify(body),\n      values: body,\n    },\n    failedResponseHandler,\n    successfulResponseHandler,\n    abortSignal,\n    fetch,\n  });\n\nexport const postFormDataToApi = async <T>({\n  url,\n  headers,\n  formData,\n  failedResponseHandler,\n  successfulResponseHandler,\n  abortSignal,\n  fetch,\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  formData: FormData;\n  failedResponseHandler: ResponseHandler<APICallError>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) =>\n  await postToApi({\n    url,\n    headers,\n    body: {\n      content: formData,\n      values: Object.fromEntries((formData as any).entries()),\n    },\n    failedResponseHandler,\n    successfulResponseHandler,\n    abortSignal,\n    fetch,\n  });\n\nexport const postToApi = async <T>({\n  url,\n  headers = {},\n  body,\n  successfulResponseHandler,\n  failedResponseHandler,\n  abortSignal,\n  fetch = getOriginalFetch(),\n}: {\n  url: string;\n  headers?: Record<string, string | undefined>;\n  body: {\n    content: string | FormData | Uint8Array | Blob;\n    values: unknown;\n  };\n  failedResponseHandler: ResponseHandler<Error>;\n  successfulResponseHandler: ResponseHandler<T>;\n  abortSignal?: AbortSignal;\n  fetch?: FetchFunction;\n}) => {\n  try {\n    const response = await fetch(url, {\n      method: 'POST',\n      headers: withUserAgentSuffix(\n        headers,\n        `ai-sdk/provider-utils/${VERSION}`,\n        getRuntimeEnvironmentUserAgent(),\n      ),\n      body: body.content,\n      signal: abortSignal,\n    });\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.ok) {\n      let errorInformation: {\n        value: Error;\n        responseHeaders?: Record<string, string> | undefined;\n      };\n\n      try {\n        errorInformation = await failedResponseHandler({\n          response,\n          url,\n          requestBodyValues: body.values,\n        });\n      } catch (error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n\n        throw new APICallError({\n          message: 'Failed to process error response',\n          cause: error,\n          statusCode: response.status,\n          url,\n          responseHeaders,\n          requestBodyValues: body.values,\n        });\n      }\n\n      throw errorInformation.value;\n    }\n\n    try {\n      return await successfulResponseHandler({\n        response,\n        url,\n        requestBodyValues: body.values,\n      });\n    } catch (error) {\n      if (error instanceof Error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n      }\n\n      throw new APICallError({\n        message: 'Failed to process successful response',\n        cause: error,\n        statusCode: response.status,\n        url,\n        responseHeaders,\n        requestBodyValues: body.values,\n      });\n    }\n  } catch (error) {\n    throw handleFetchError({ error, url, requestBodyValues: body.values });\n  }\n};\n","import type { JSONValue, JSONObject } from '@ai-sdk/provider';\nimport type { FlexibleSchema } from '../schema';\nimport type { ToolResultOutput } from './content-part';\nimport type { Context } from './context';\nimport type { ExecutableTool } from './executable-tool';\nimport type { NeverOptional } from './never-optional';\nimport type { ProviderOptions } from './provider-options';\nimport type {\n  ToolExecuteFunction,\n  ToolExecutionOptions,\n} from './tool-execute-function';\nimport type { ToolNeedsApprovalFunction } from './tool-needs-approval-function';\nimport type { SandboxSession } from './sandbox';\n\n/**\n * Helper type to determine the outputSchema and execute function properties of a tool.\n */\ntype ToolOutputProperties<\n  INPUT,\n  OUTPUT,\n  CONTEXT extends Context | unknown | never,\n> = NeverOptional<\n  OUTPUT,\n  | {\n      /**\n       * The optional schema of the output that the tool produces.\n       *\n       * If not provided, the output shape will be inferred from the execute function.\n       */\n      outputSchema?: FlexibleSchema<OUTPUT>;\n\n      /**\n       * An async function that is called with the arguments from the tool call and produces a result.\n       * If not provided, the tool will not be executed automatically.\n       *\n       * @args is the input of the tool call.\n       * @options.abortSignal is a signal that can be used to abort the tool call.\n       */\n      execute: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;\n    }\n  | {\n      /**\n       * The schema of the output that the tool produces.\n       *\n       * Required when no execute function is provided.\n       */\n      outputSchema: FlexibleSchema<OUTPUT>;\n\n      execute?: never;\n    }\n>;\n\n/**\n * Common properties shared by all tool kinds.\n */\ntype BaseTool<\n  INPUT extends JSONValue | unknown | never = any,\n  OUTPUT extends JSONValue | unknown | never = any,\n  CONTEXT extends Context | unknown | never = any,\n> = {\n  /**\n   * Defer exposing this tool until it is discovered by `toolSearch`.\n   * Supports direct calls and local callers that announce tools in conversation\n   * messages (code mode with `toolDiscovery: 'conversation'`). Discovered tools\n   * become available on the next model step.\n   */\n  deferLoading?: boolean;\n\n  /**\n   * An optional title of the tool.\n   *\n   * @deprecated Use `providerMetadata` for source-specific tool display metadata.\n   */\n  title?: string;\n\n  /**\n   * Additional provider-specific metadata. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Optional metadata about the tool itself (e.g. its source).\n   *\n   * Unlike `providerOptions`, this metadata is not sent to the language\n   * model. Instead, it is propagated onto the resulting tool call's\n   * `toolMetadata` so consumers can read it from tool call / result parts\n   * and UI message parts. This is useful for sources of dynamic tools (e.g.\n   * an MCP server) to identify themselves.\n   */\n  metadata?: JSONObject;\n\n  /**\n   * The schema of the input that the tool expects.\n   * The language model will use this to generate the input.\n   * It is also used to validate the output of the language model.\n   *\n   * You can use descriptions on the schema properties to make the input understandable for the language model.\n   */\n  inputSchema: FlexibleSchema<INPUT>;\n\n  /**\n   * An optional schema describing the context that the tool expects.\n   *\n   * The context is passed to execute function as part of the execution options.\n   */\n  contextSchema?: FlexibleSchema<CONTEXT>;\n\n  /**\n   * Whether the tool needs approval before it can be executed.\n   *\n   * @deprecated Tool approval is handled on a `generateText` / `streamText` level now.\n   */\n  needsApproval?:\n    | boolean\n    | ToolNeedsApprovalFunction<\n        [INPUT] extends [never] ? unknown : INPUT,\n        NoInfer<CONTEXT>\n      >;\n\n  /**\n   * Optional function that is called when the model starts generating the tool input.\n   * In non-streaming contexts, it is called immediately before `onInputAvailable`.\n   */\n  onInputStart?: (\n    options: ToolExecutionOptions<NoInfer<CONTEXT>>,\n  ) => void | PromiseLike<void>;\n\n  /**\n   * Optional function that is called when an argument streaming delta is available.\n   * Only called when the tool is used in a streaming context.\n   */\n  onInputDelta?: (\n    options: { inputTextDelta: string } & ToolExecutionOptions<\n      NoInfer<CONTEXT>\n    >,\n  ) => void | PromiseLike<void>;\n\n  /**\n   * Optional function that is called when a tool call can be started,\n   * even if the execute function is not provided.\n   */\n  onInputAvailable?: (\n    options: {\n      input: [INPUT] extends [never] ? unknown : INPUT;\n    } & ToolExecutionOptions<NoInfer<CONTEXT>>,\n  ) => void | PromiseLike<void>;\n\n  /**\n   * Optional conversion function that maps the tool result to an output that can be used by the language model.\n   *\n   * If not provided, the tool result will be sent as a JSON object.\n   *\n   * This function is invoked on the server by `convertToModelMessages`, so ensure that you pass the same \"tools\" (ToolSet) to both \"convertToModelMessages\" and \"streamText\" (or other generation APIs).\n   */\n  toModelOutput?: (options: {\n    /**\n     * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.\n     */\n    toolCallId: string;\n\n    /**\n     * The input of the tool call.\n     */\n    input: [INPUT] extends [never] ? unknown : INPUT;\n\n    /**\n     * The output of the tool call.\n     */\n    output: 0 extends 1 & OUTPUT\n      ? any\n      : [OUTPUT] extends [never]\n        ? any\n        : NoInfer<OUTPUT>;\n  }) => ToolResultOutput | PromiseLike<ToolResultOutput>;\n} & ToolOutputProperties<INPUT, OUTPUT, NoInfer<CONTEXT>>;\n\n/**\n * Common properties shared by function-style tools.\n */\ntype BaseFunctionTool<\n  INPUT extends JSONValue | unknown | never = any,\n  OUTPUT extends JSONValue | unknown | never = any,\n  CONTEXT extends Context | unknown | never = any,\n> = BaseTool<INPUT, OUTPUT, CONTEXT> & {\n  /**\n   * Optional description of what the tool does.\n   *\n   * Included in the tool definition sent to the language model so it can\n   * decide when and how to call the tool.\n   *\n   * Provide a string for a fixed description, or a function that returns a\n   * string from the current `context` (and optional `experimental_sandbox`) when the\n   * description should vary per call.\n   */\n  description?:\n    | string\n    | ((options: {\n        context: NoInfer<CONTEXT>;\n        experimental_sandbox?: SandboxSession;\n      }) => string);\n\n  /**\n   * Strict mode setting for the tool.\n   *\n   * Providers that support strict mode will use this setting to determine\n   * how the input should be generated. Strict mode will always produce\n   * valid inputs, but it might limit what input schemas are supported.\n   */\n  strict?: boolean;\n\n  /**\n   * An optional list of input examples that show the language\n   * model what the input should look like.\n   */\n  inputExamples?: Array<{ input: NoInfer<INPUT> }>;\n\n  // make all properties available to improve usage dx\n  id?: never;\n  isProviderExecuted?: never;\n  args?: never;\n  supportsDeferredResults?: never;\n};\n\n/**\n * Tool with user-defined input and output schemas that is executed by the AI SDK.\n */\nexport type FunctionTool<\n  INPUT extends JSONValue | unknown | never = any,\n  OUTPUT extends JSONValue | unknown | never = any,\n  CONTEXT extends Context | unknown | never = any,\n> = BaseFunctionTool<INPUT, OUTPUT, CONTEXT> & {\n  type?: undefined | 'function';\n};\n\n/**\n * Tool that is defined at runtime.\n * The types of input and output are not known at development time.\n *\n * For example, MCP tools that are not known at development time.\n */\nexport type DynamicTool<\n  INPUT extends JSONValue | unknown | never = any,\n  OUTPUT extends JSONValue | unknown | never = any,\n  CONTEXT extends Context | unknown | never = any,\n> = BaseFunctionTool<INPUT, OUTPUT, CONTEXT> & {\n  type: 'dynamic';\n};\n\n/**\n * Common properties shared by provider tools.\n */\ntype BaseProviderTool<\n  INPUT extends JSONValue | unknown | never = any,\n  OUTPUT extends JSONValue | unknown | never = any,\n  CONTEXT extends Context | unknown | never = any,\n> = BaseTool<INPUT, OUTPUT, CONTEXT> & {\n  type: 'provider';\n\n  /**\n   * The ID of the tool. Must follow the format `<provider-name>.<unique-tool-name>`.\n   */\n  id: `${string}.${string}`;\n\n  /**\n   * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool.\n   */\n  args: Record<string, unknown>;\n\n  // make all properties available to improve usage dx\n  description?: never;\n  strict?: never;\n  inputExamples?: never;\n};\n\n/**\n * Tool with provider-defined input and output schemas that is executed by the\n * user.\n *\n * For example, shell tools that are executed in a local shell, but have provider-defined input and output schemas.\n */\nexport type ProviderDefinedTool<\n  INPUT extends JSONValue | unknown | never = any,\n  OUTPUT extends JSONValue | unknown | never = any,\n  CONTEXT extends Context | unknown | never = any,\n> = BaseProviderTool<INPUT, OUTPUT, CONTEXT> & {\n  /**\n   * Flag that indicates whether the tool is executed by the provider.\n   */\n  isProviderExecuted: false;\n\n  // make all properties available to improve usage dx\n  supportsDeferredResults?: never;\n};\n\n/**\n * Tool with provider-defined input and output schemas that is executed by the\n * provider.\n *\n * For example, web search tools and code execution tools that are executed by the provider itself.\n */\nexport type ProviderExecutedTool<\n  INPUT extends JSONValue | unknown | never = any,\n  OUTPUT extends JSONValue | unknown | never = any,\n  CONTEXT extends Context | unknown | never = any,\n> = BaseProviderTool<INPUT, OUTPUT, CONTEXT> & {\n  /**\n   * Flag that indicates whether the tool is executed by the provider.\n   */\n  isProviderExecuted: true;\n\n  /**\n   * Whether this provider-executed tool supports deferred results.\n   *\n   * When true, the tool result may not be returned in the same turn as the\n   * tool call (e.g., when using programmatic tool calling where a server tool\n   * triggers a client-executed tool, and the server tool's result is deferred\n   * until the client tool is resolved).\n   *\n   * This flag allows the AI SDK to handle tool results that arrive without\n   * a matching tool call in the current response.\n   *\n   * @default false\n   */\n  supportsDeferredResults?: boolean;\n};\n\n/**\n * A tool can either be user-defined or provider-defined.\n *\n * It contains the schemas and metadata needed for the language model to call\n * the tool and can include an execute function for tools that are executed by\n * the AI SDK.\n */\nexport type Tool<\n  INPUT extends JSONValue | unknown | never = any,\n  OUTPUT extends JSONValue | unknown | never = any,\n  CONTEXT extends Context | unknown | never = any,\n> =\n  | FunctionTool<INPUT, OUTPUT, CONTEXT>\n  | DynamicTool<INPUT, OUTPUT, CONTEXT>\n  | ProviderDefinedTool<INPUT, OUTPUT, CONTEXT>\n  | ProviderExecutedTool<INPUT, OUTPUT, CONTEXT>;\n\n/**\n * Infer the tool type from a tool object.\n *\n * This is useful for type inference when working with tool objects.\n *\n * When the input has an `execute` function, the return type narrows to\n * `ExecutableTool<Tool<...>>` so that `.execute` is non-nullable without\n * needing `isExecutableTool` or a `!` assertion at the call site.\n */\n// Note: overload order is important for auto-completion.\n// The \"with execute\" overload comes first so calls that include an\n// `execute` function get the narrowed return type. Calls without\n// `execute` fall through to the overloads below.\nexport function tool<INPUT, OUTPUT, CONTEXT extends Context>(\n  tool: Tool<INPUT, OUTPUT, CONTEXT> & {\n    execute: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;\n  },\n): ExecutableTool<Tool<INPUT, OUTPUT, CONTEXT>>;\nexport function tool<INPUT, OUTPUT, CONTEXT extends Context>(\n  tool: Tool<INPUT, OUTPUT, CONTEXT>,\n): Tool<INPUT, OUTPUT, CONTEXT>;\nexport function tool<INPUT, CONTEXT extends Context>(\n  tool: Tool<INPUT, never, CONTEXT>,\n): Tool<INPUT, never, CONTEXT>;\nexport function tool<OUTPUT, CONTEXT extends Context>(\n  tool: Tool<never, OUTPUT, CONTEXT>,\n): Tool<never, OUTPUT, CONTEXT>;\nexport function tool<CONTEXT extends Context>(\n  tool: Tool<never, never, CONTEXT>,\n): Tool<never, never, CONTEXT>;\nexport function tool(tool: any): any {\n  return tool;\n}\n\n/**\n * Define a dynamic tool.\n */\nexport function dynamicTool(\n  tool: Omit<DynamicTool<unknown, unknown, Context>, 'type'>,\n): DynamicTool<unknown, unknown, Context> {\n  return { ...tool, type: 'dynamic' } as DynamicTool<unknown, unknown, Context>;\n}\n","import { tool, type ProviderDefinedTool, type Tool } from './types/tool';\nimport type { FlexibleSchema } from './schema';\nimport type { Context } from './types/context';\nimport type { ToolExecuteFunction } from './types/tool-execute-function';\n/**\n * A provider-defined tool is a tool for which the provider defines the input\n * and output schemas, but does not execute the tool.\n */\nexport type ProviderDefinedToolFactory<\n  INPUT,\n  ARGS extends object,\n  CONTEXT extends Context = {},\n> = <OUTPUT>(\n  options: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;\n    needsApproval?: Tool<INPUT, OUTPUT, CONTEXT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT, CONTEXT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];\n  },\n) => ProviderDefinedTool<INPUT, OUTPUT, CONTEXT>;\n\nexport function createProviderDefinedToolFactory<\n  INPUT,\n  ARGS extends object,\n  CONTEXT extends Context = {},\n>({\n  id,\n  inputSchema,\n}: {\n  id: `${string}.${string}`;\n  inputSchema: FlexibleSchema<INPUT>;\n}): ProviderDefinedToolFactory<INPUT, ARGS, CONTEXT> {\n  return <OUTPUT>({\n    execute,\n    outputSchema,\n    needsApproval,\n    toModelOutput,\n    onInputStart,\n    onInputDelta,\n    onInputAvailable,\n    ...args\n  }: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;\n    outputSchema?: FlexibleSchema<OUTPUT>;\n    needsApproval?: Tool<INPUT, OUTPUT, CONTEXT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT, CONTEXT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];\n  }): ProviderDefinedTool<INPUT, OUTPUT, CONTEXT> =>\n    tool({\n      type: 'provider',\n      isProviderExecuted: false,\n      id,\n      args,\n      inputSchema,\n      outputSchema,\n      execute,\n      needsApproval,\n      toModelOutput,\n      onInputStart,\n      onInputDelta,\n      onInputAvailable,\n    }) as ProviderDefinedTool<INPUT, OUTPUT, CONTEXT>;\n}\n\nexport type ProviderDefinedToolFactoryWithOutputSchema<\n  INPUT,\n  OUTPUT,\n  ARGS extends object,\n  CONTEXT extends Context = {},\n> = (\n  options: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;\n    needsApproval?: Tool<INPUT, OUTPUT, CONTEXT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT, CONTEXT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];\n  },\n) => ProviderDefinedTool<INPUT, OUTPUT, CONTEXT>;\n\nexport function createProviderDefinedToolFactoryWithOutputSchema<\n  INPUT,\n  OUTPUT,\n  ARGS extends object,\n  CONTEXT extends Context = {},\n>({\n  id,\n  inputSchema,\n  outputSchema,\n}: {\n  id: `${string}.${string}`;\n  inputSchema: FlexibleSchema<INPUT>;\n  outputSchema: FlexibleSchema<OUTPUT>;\n}): ProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS, CONTEXT> {\n  return ({\n    execute,\n    needsApproval,\n    toModelOutput,\n    onInputStart,\n    onInputDelta,\n    onInputAvailable,\n    ...args\n  }: ARGS & {\n    execute?: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;\n    needsApproval?: Tool<INPUT, OUTPUT, CONTEXT>['needsApproval'];\n    toModelOutput?: Tool<INPUT, OUTPUT, CONTEXT>['toModelOutput'];\n    onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];\n  }): ProviderDefinedTool<INPUT, OUTPUT, CONTEXT> =>\n    tool({\n      type: 'provider',\n      isProviderExecuted: false,\n      id,\n      args,\n      inputSchema,\n      outputSchema,\n      execute,\n      needsApproval,\n      toModelOutput,\n      onInputStart,\n      onInputDelta,\n      onInputAvailable,\n    }) as ProviderDefinedTool<INPUT, OUTPUT, CONTEXT>;\n}\n","import type { FlexibleSchema } from './schema';\nimport type { Context } from './types/context';\nimport { tool, type ProviderExecutedTool, type Tool } from './types/tool';\n/**\n * A provider-executed tool is a tool for which the provider executes the tool.\n */\nexport type ProviderExecutedToolFactory<\n  INPUT,\n  OUTPUT,\n  ARGS extends object,\n  CONTEXT extends Context = {},\n> = (\n  options: ARGS & {\n    onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];\n  },\n) => ProviderExecutedTool<INPUT, OUTPUT, CONTEXT>;\n\nexport function createProviderExecutedToolFactory<\n  INPUT,\n  OUTPUT,\n  ARGS extends object,\n  CONTEXT extends Context = {},\n>({\n  id,\n  inputSchema,\n  outputSchema,\n  supportsDeferredResults,\n}: {\n  id: `${string}.${string}`;\n  inputSchema: FlexibleSchema<INPUT>;\n  outputSchema: FlexibleSchema<OUTPUT>;\n\n  /**\n   * Whether this provider-executed tool supports deferred results.\n   *\n   * When true, the tool result may not be returned in the same turn as the\n   * tool call (e.g., when using programmatic tool calling where a server tool\n   * triggers a client-executed tool, and the server tool's result is deferred\n   * until the client tool is resolved).\n   *\n   * @default false\n   */\n  supportsDeferredResults?: boolean;\n}): ProviderExecutedToolFactory<INPUT, OUTPUT, ARGS, CONTEXT> {\n  return ({\n    onInputStart,\n    onInputDelta,\n    onInputAvailable,\n    ...args\n  }: ARGS & {\n    onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];\n    onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];\n    onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];\n  }): ProviderExecutedTool<INPUT, OUTPUT, CONTEXT> =>\n    tool({\n      type: 'provider',\n      isProviderExecuted: true,\n      id,\n      args,\n      inputSchema,\n      outputSchema,\n      onInputStart,\n      onInputDelta,\n      onInputAvailable,\n      supportsDeferredResults,\n    }) as ProviderExecutedTool<INPUT, OUTPUT, CONTEXT>;\n}\n","import type { MaybePromiseLike } from './maybe-promise-like';\n\n/**\n * A value or a lazy provider of a value, each of which may be synchronous or asynchronous.\n *\n * @template T The resolved type after {@link resolve} runs.\n *\n * One of:\n * - A plain value of type {@link T}\n * - A {@link PromiseLike} of {@link T} (e.g. a `Promise<T>`)\n * - A zero-argument function that returns a plain {@link T}\n * - A zero-argument function that returns a {@link PromiseLike} of {@link T}\n *\n * The function form is only invoked when passed to {@link resolve}; it is not distinguished from\n * a {@link T} that happens to be a function—callers should wrap function values if disambiguation\n * is required.\n */\nexport type Resolvable<T> = MaybePromiseLike<T> | (() => MaybePromiseLike<T>);\n\n/**\n * Resolves a value that could be a raw value, a Promise, a function returning a value,\n * or a function returning a Promise.\n */\nexport async function resolve<T>(value: Resolvable<T>): Promise<T> {\n  // If it's a function, call it to get the value/promise\n  if (typeof value === 'function') {\n    value = (value as Function)();\n  }\n\n  // Otherwise just resolve whatever we got (value or promise)\n  return Promise.resolve(value as T);\n}\n","import {\n  UnsupportedFunctionalityError,\n  type LanguageModelV4FilePart,\n} from '@ai-sdk/provider';\nimport {\n  detectMediaType,\n  getTopLevelMediaType,\n  isFullMediaType,\n} from './detect-media-type';\n\n/**\n * Resolves a file part's media type to a full `type/subtype` form required by\n * providers whose API demands the full IANA media type.\n *\n * - If `part.mediaType` is already a full media type (e.g. `image/png`), it is\n *   returned as-is.\n * - Otherwise, when inline bytes are available (`part.data.type === 'data'`),\n *   the subtype is sniffed from the bytes using the signature table that\n *   corresponds to the top-level segment.\n * - When neither applies (e.g. top-level-only with a URL source, or bytes that\n *   cannot be detected), an `UnsupportedFunctionalityError` is thrown.\n */\nexport function resolveFullMediaType({\n  part,\n}: {\n  part: LanguageModelV4FilePart;\n}): string {\n  if (isFullMediaType(part.mediaType)) {\n    return part.mediaType;\n  }\n\n  if (part.data.type === 'data') {\n    const detected = detectMediaType({\n      data: part.data.data,\n      topLevelType: getTopLevelMediaType(part.mediaType),\n    });\n    if (detected) {\n      return detected;\n    }\n\n    throw new UnsupportedFunctionalityError({\n      functionality: `file of media type \"${part.mediaType}\" must specify subtype since it could not be auto-detected`,\n    });\n  }\n\n  throw new UnsupportedFunctionalityError({\n    functionality: `file of media type \"${part.mediaType}\" must specify subtype since it is not passed as inline bytes`,\n  });\n}\n","import {\n  NoSuchProviderReferenceError,\n  type SharedV4ProviderReference,\n} from '@ai-sdk/provider';\n/**\n * Resolves a provider reference to the provider-specific identifier for the\n * given provider. Throws `NoSuchProviderReferenceError` if the provider is not\n * found in the reference mapping.\n */\nexport function resolveProviderReference({\n  reference,\n  provider,\n}: {\n  reference: SharedV4ProviderReference;\n  provider: string;\n}): string {\n  const id = reference[provider];\n  if (id != null) {\n    return id;\n  }\n\n  throw new NoSuchProviderReferenceError({\n    provider,\n    reference,\n  });\n}\n","import { delay } from './delay';\nimport { getErrorMessage } from './get-error-message';\nimport { isAbortError } from './is-abort-error';\n\nexport type RetryFunction = <OUTPUT>(\n  fn: () => PromiseLike<OUTPUT>,\n) => PromiseLike<OUTPUT>;\n\nexport type RetryErrorReason = 'maxRetriesExceeded' | 'errorNotRetryable';\n\nexport type RetryErrorFactory = ({\n  message,\n  reason,\n  errors,\n}: {\n  message: string;\n  reason: RetryErrorReason;\n  errors: Array<unknown>;\n}) => unknown;\n\nexport type RetryDelayProvider = ({\n  error,\n  exponentialBackoffDelay,\n}: {\n  error: unknown;\n  exponentialBackoffDelay: number;\n}) => number;\n\nexport type ShouldRetryFunction = (\n  error: unknown,\n) => boolean | Promise<boolean>;\n\n/**\n * Retries a failed operation with exponential backoff.\n */\nexport const retryWithExponentialBackoff =\n  ({\n    maxRetries = 2,\n    initialDelayInMs = 2000,\n    backoffFactor = 2,\n    abortSignal,\n    shouldRetry,\n    getDelayInMs = ({ exponentialBackoffDelay }) => exponentialBackoffDelay,\n    createRetryError = ({ message }) => new Error(message),\n  }: {\n    maxRetries?: number;\n    initialDelayInMs?: number;\n    backoffFactor?: number;\n    abortSignal?: AbortSignal;\n    shouldRetry: ShouldRetryFunction;\n    getDelayInMs?: RetryDelayProvider;\n    createRetryError?: RetryErrorFactory;\n  }): RetryFunction =>\n  async <OUTPUT>(f: () => PromiseLike<OUTPUT>) =>\n    retryWithExponentialBackoffInternal(f, {\n      maxRetries,\n      delayInMs: initialDelayInMs,\n      backoffFactor,\n      abortSignal,\n      shouldRetry,\n      getDelayInMs,\n      createRetryError,\n    });\n\nasync function retryWithExponentialBackoffInternal<OUTPUT>(\n  f: () => PromiseLike<OUTPUT>,\n  {\n    maxRetries,\n    delayInMs,\n    backoffFactor,\n    abortSignal,\n    shouldRetry,\n    getDelayInMs,\n    createRetryError,\n  }: {\n    maxRetries: number;\n    delayInMs: number;\n    backoffFactor: number;\n    abortSignal: AbortSignal | undefined;\n    shouldRetry: ShouldRetryFunction;\n    getDelayInMs: RetryDelayProvider;\n    createRetryError: RetryErrorFactory;\n  },\n  errors: unknown[] = [],\n): Promise<OUTPUT> {\n  try {\n    return await f();\n  } catch (error) {\n    if (isAbortError(error)) {\n      throw error; // don't retry when the request was aborted\n    }\n\n    if (maxRetries === 0) {\n      throw error; // don't wrap the error when retries are disabled\n    }\n\n    const errorMessage = getErrorMessage(error);\n    const newErrors = [...errors, error];\n    const tryNumber = newErrors.length;\n\n    if (tryNumber > maxRetries) {\n      throw createRetryError({\n        message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,\n        reason: 'maxRetriesExceeded',\n        errors: newErrors,\n      });\n    }\n\n    if ((await shouldRetry(error)) && tryNumber <= maxRetries) {\n      await delay(\n        getDelayInMs({\n          error,\n          exponentialBackoffDelay: delayInMs,\n        }),\n        { abortSignal },\n      );\n\n      return retryWithExponentialBackoffInternal(\n        f,\n        {\n          maxRetries,\n          delayInMs: backoffFactor * delayInMs,\n          backoffFactor,\n          abortSignal,\n          shouldRetry,\n          getDelayInMs,\n          createRetryError,\n        },\n        newErrors,\n      );\n    }\n\n    if (tryNumber === 1) {\n      throw error; // don't wrap the error when a non-retryable error occurs on the first try\n    }\n\n    throw createRetryError({\n      message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,\n      reason: 'errorNotRetryable',\n      errors: newErrors,\n    });\n  }\n}\n","import { APICallError, EmptyResponseBodyError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport { handleFetchError } from './handle-fetch-error';\nimport { isAbortError } from './is-abort-error';\nimport { parseJSON, safeParseJSON, type ParseResult } from './parse-json';\nimport { parseJsonEventStream } from './parse-json-event-stream';\nimport { readResponseWithSizeLimit } from './read-response-with-size-limit';\nimport type { FlexibleSchema } from './schema';\n\nexport type ResponseHandler<RETURN_TYPE> = (options: {\n  url: string;\n  requestBodyValues: unknown;\n  response: Response;\n}) => PromiseLike<{\n  value: RETURN_TYPE;\n  rawValue?: unknown;\n  responseHeaders?: Record<string, string>;\n}>;\n\nconst textDecoder = new TextDecoder();\n\nfunction wrapResponseBodyStream({\n  stream,\n  url,\n  requestBodyValues,\n  statusCode,\n  responseHeaders,\n}: {\n  stream: ReadableStream<Uint8Array>;\n  url: string;\n  requestBodyValues: unknown;\n  statusCode: number;\n  responseHeaders: Record<string, string>;\n}): ReadableStream<Uint8Array> {\n  const reader = stream.getReader();\n  let readerReleased = false;\n\n  const releaseReader = () => {\n    if (!readerReleased) {\n      reader.releaseLock();\n      readerReleased = true;\n    }\n  };\n\n  return new ReadableStream<Uint8Array>({\n    async pull(controller) {\n      try {\n        const { done, value } = await reader.read();\n\n        if (done) {\n          releaseReader();\n          controller.close();\n        } else {\n          controller.enqueue(value);\n        }\n      } catch (error) {\n        releaseReader();\n\n        if (isAbortError(error)) {\n          controller.error(error);\n          return;\n        }\n\n        controller.error(\n          handleFetchError({\n            error: new APICallError({\n              message: 'Failed to process successful response',\n              cause: error,\n              statusCode,\n              url,\n              responseHeaders,\n              requestBodyValues,\n            }),\n            url,\n            requestBodyValues,\n          }),\n        );\n      }\n    },\n    async cancel(reason) {\n      try {\n        await reader.cancel(reason);\n      } finally {\n        releaseReader();\n      }\n    },\n  });\n}\n\nasync function readResponseBodyAsText({\n  response,\n  url,\n}: {\n  response: Response;\n  url: string;\n}) {\n  return textDecoder.decode(\n    await readResponseWithSizeLimit({\n      response,\n      url,\n    }),\n  );\n}\n\nexport const createJsonErrorResponseHandler =\n  <T>({\n    errorSchema,\n    errorToMessage,\n    isRetryable,\n  }: {\n    errorSchema: FlexibleSchema<T>;\n    errorToMessage: (error: T) => string;\n    isRetryable?: (response: Response, error?: T) => boolean;\n  }): ResponseHandler<APICallError> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseBody = await readResponseBodyAsText({ response, url });\n    const responseHeaders = extractResponseHeaders(response);\n\n    // Some providers return an empty response body for some errors:\n    if (responseBody.trim() === '') {\n      return {\n        responseHeaders,\n        value: new APICallError({\n          message: response.statusText,\n          url,\n          requestBodyValues,\n          statusCode: response.status,\n          responseHeaders,\n          responseBody,\n          isRetryable: isRetryable?.(response),\n        }),\n      };\n    }\n\n    // resilient parsing in case the response is not JSON or does not match the schema:\n    try {\n      const parsedError = await parseJSON({\n        text: responseBody,\n        schema: errorSchema,\n      });\n\n      return {\n        responseHeaders,\n        value: new APICallError({\n          message: errorToMessage(parsedError),\n          url,\n          requestBodyValues,\n          statusCode: response.status,\n          responseHeaders,\n          responseBody,\n          data: parsedError,\n          isRetryable: isRetryable?.(response, parsedError),\n        }),\n      };\n    } catch {\n      return {\n        responseHeaders,\n        value: new APICallError({\n          message: response.statusText,\n          url,\n          requestBodyValues,\n          statusCode: response.status,\n          responseHeaders,\n          responseBody,\n          isRetryable: isRetryable?.(response),\n        }),\n      };\n    }\n  };\n\nexport const createEventSourceResponseHandler =\n  <T>(\n    chunkSchema: FlexibleSchema<T>,\n  ): ResponseHandler<ReadableStream<ParseResult<T>>> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (response.body == null) {\n      throw new EmptyResponseBodyError({});\n    }\n\n    return {\n      responseHeaders,\n      value: parseJsonEventStream({\n        stream: wrapResponseBodyStream({\n          stream: response.body,\n          url,\n          requestBodyValues,\n          statusCode: response.status,\n          responseHeaders,\n        }),\n        schema: chunkSchema,\n      }),\n    };\n  };\n\nexport const createJsonResponseHandler =\n  <T>(responseSchema: FlexibleSchema<T>): ResponseHandler<T> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseBody = await readResponseBodyAsText({ response, url });\n\n    const parsedResult = await safeParseJSON({\n      text: responseBody,\n      schema: responseSchema,\n    });\n\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!parsedResult.success) {\n      throw new APICallError({\n        message: 'Invalid JSON response',\n        cause: parsedResult.error,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody,\n        url,\n        requestBodyValues,\n      });\n    }\n\n    return {\n      responseHeaders,\n      value: parsedResult.value,\n      rawValue: parsedResult.rawValue,\n    };\n  };\n\nexport const createJsonLinesResponseHandler =\n  <T>(responseSchema: FlexibleSchema<T>): ResponseHandler<AsyncGenerator<T>> =>\n  async ({ response }) => {\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (response.body == null) {\n      throw new EmptyResponseBodyError({});\n    }\n\n    return {\n      responseHeaders,\n      value: parseJsonLines({\n        stream: response.body,\n        schema: responseSchema,\n      }),\n    };\n  };\n\nasync function* parseJsonLines<T>({\n  stream,\n  schema,\n}: {\n  stream: ReadableStream<Uint8Array>;\n  schema: FlexibleSchema<T>;\n}): AsyncGenerator<T> {\n  const reader = stream.getReader();\n  const decoder = new TextDecoder();\n  let buffer = '';\n  let finished = false;\n\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n\n      if (done) {\n        finished = true;\n        buffer += decoder.decode();\n        break;\n      }\n\n      buffer += decoder.decode(value, { stream: true });\n\n      let lineEnd = buffer.indexOf('\\n');\n      while (lineEnd !== -1) {\n        const line = buffer.slice(0, lineEnd).replace(/\\r$/, '');\n        buffer = buffer.slice(lineEnd + 1);\n\n        if (line.trim().length > 0) {\n          yield await parseJSON({ text: line, schema });\n        }\n\n        lineEnd = buffer.indexOf('\\n');\n      }\n    }\n\n    const finalLine = buffer.replace(/\\r$/, '');\n    if (finalLine.trim().length > 0) {\n      yield await parseJSON({ text: finalLine, schema });\n    }\n  } finally {\n    if (!finished) {\n      await reader.cancel().catch(() => {});\n    }\n    reader.releaseLock();\n  }\n}\n\nexport const createBinaryResponseHandler =\n  (): ResponseHandler<Uint8Array> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (!response.body) {\n      throw new APICallError({\n        message: 'Response body is empty',\n        url,\n        requestBodyValues,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody: undefined,\n      });\n    }\n\n    try {\n      const buffer = await response.arrayBuffer();\n      return {\n        responseHeaders,\n        value: new Uint8Array(buffer),\n      };\n    } catch (error) {\n      throw new APICallError({\n        message: 'Failed to read response as array buffer',\n        url,\n        requestBodyValues,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody: undefined,\n        cause: error,\n      });\n    }\n  };\n\n/**\n * Passes the response body through as a `ReadableStream<Uint8Array>` without\n * buffering it (unlike `createBinaryResponseHandler`). The consumer is\n * responsible for draining or cancelling the stream.\n */\nexport const createBinaryStreamResponseHandler =\n  (): ResponseHandler<ReadableStream<Uint8Array>> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseHeaders = extractResponseHeaders(response);\n\n    if (response.body == null) {\n      throw new EmptyResponseBodyError({});\n    }\n\n    return {\n      responseHeaders,\n      value: wrapResponseBodyStream({\n        stream: response.body,\n        url,\n        requestBodyValues,\n        statusCode: response.status,\n        responseHeaders,\n      }),\n    };\n  };\n\nexport const createStatusCodeErrorResponseHandler =\n  (): ResponseHandler<APICallError> =>\n  async ({ response, url, requestBodyValues }) => {\n    const responseHeaders = extractResponseHeaders(response);\n    const responseBody = await readResponseBodyAsText({ response, url });\n\n    return {\n      responseHeaders,\n      value: new APICallError({\n        message: response.statusText,\n        url,\n        requestBodyValues: requestBodyValues as Record<string, unknown>,\n        statusCode: response.status,\n        responseHeaders,\n        responseBody,\n      }),\n    };\n  };\n","import type { JSONValue } from '@ai-sdk/provider';\n\n/**\n * Checks whether a value can cross a workflow serialization boundary.\n *\n * The check accepts JSON-like primitives, arrays, and plain objects whose\n * nested values are also serializable. It rejects functions, symbols,\n * bigints, and non-plain objects such as class instances, dates, and regexes.\n */\nexport function isJSONSerializable(value: unknown): value is JSONValue {\n  if (value === null || value === undefined) return true;\n\n  const type = typeof value;\n  if (type === 'string' || type === 'number' || type === 'boolean') return true;\n  if (type === 'function' || type === 'symbol' || type === 'bigint')\n    return false;\n\n  if (Array.isArray(value)) {\n    return value.every(isJSONSerializable);\n  }\n\n  if (Object.getPrototypeOf(value) === Object.prototype) {\n    return Object.values(value as Record<string, unknown>).every(\n      isJSONSerializable,\n    );\n  }\n\n  return false;\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_SerializationError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class SerializationError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({\n    message = 'Failed to serialize value.',\n    cause,\n  }: {\n    message?: string;\n    cause?: unknown;\n  } = {}) {\n    super({ name, message, cause });\n  }\n\n  static isInstance(error: unknown): error is SerializationError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import type { JSONObject } from '@ai-sdk/provider';\nimport { isJSONSerializable } from './is-json-serializable';\nimport type { Resolvable } from './resolve';\nimport { SerializationError } from './serialization-error';\n\n/**\n * Serializes a model instance for workflow step boundaries.\n * Returns the `modelId` plus the JSON-serializable config properties.\n *\n * Non-serializable values are omitted. As a special case, a\n * function-valued `headers` property is resolved during serialization\n * and included if the returned value is JSON-serializable.\n *\n * Used as the body of `static [WORKFLOW_SERIALIZE]` in provider models.\n *\n * @example\n * ```ts\n * static [WORKFLOW_SERIALIZE](model: MyLanguageModel) {\n *   return serializeModelOptions({\n *     modelId: model.modelId,\n *     config: model.config,\n *   });\n * }\n * ```\n */\nexport function serializeModelOptions<\n  CONFIG extends {\n    headers?: Resolvable<Record<string, string | undefined>>;\n  },\n>(options: {\n  modelId: string;\n  config: CONFIG;\n}): {\n  modelId: string;\n  config: JSONObject;\n} {\n  const serializableConfig: JSONObject = {};\n  for (const [key, value] of Object.entries(options.config)) {\n    if (key === 'headers') {\n      const resolvedHeaders = resolveSync(value);\n      if (isJSONSerializable(resolvedHeaders)) {\n        serializableConfig[key] = resolvedHeaders;\n      }\n    } else if (isJSONSerializable(value)) {\n      serializableConfig[key] = value;\n    }\n  }\n  return { modelId: options.modelId, config: serializableConfig };\n}\n\nfunction resolveSync<T>(value: Resolvable<T>): T {\n  let next: unknown = value;\n  if (typeof value === 'function') {\n    next = (value as () => unknown)();\n  }\n\n  if (next instanceof Promise) {\n    throw new SerializationError({\n      message: 'Cannot serialize asynchronous model options.',\n    });\n  }\n\n  return next as T;\n}\n","import {\n  InvalidResponseDataError,\n  type LanguageModelV4StreamPart,\n  type SharedV4ProviderMetadata,\n} from '@ai-sdk/provider';\nimport { generateId as defaultGenerateId } from './generate-id';\n\n/**\n * Minimal interface for a streaming tool call delta from an OpenAI-compatible API.\n */\nexport interface StreamingToolCallDelta {\n  index?: number | null;\n  id?: string | null;\n  type?: string | null;\n  function?: {\n    name?: string | null;\n    arguments?: string | null;\n  } | null;\n}\n\nexport interface StreamingToolCallTrackerOptions<\n  DELTA extends StreamingToolCallDelta = StreamingToolCallDelta,\n> {\n  /**\n   * ID generator function for tool call IDs.\n   * Defaults to the standard generateId.\n   */\n  generateId?: () => string;\n\n  /**\n   * How to validate the `type` field on new tool call deltas.\n   * - `'none'`: no validation (default)\n   * - `'if-present'`: throw if type is present and not `'function'`\n   * - `'required'`: throw if type is not exactly `'function'`\n   */\n  typeValidation?: 'none' | 'if-present' | 'required';\n\n  /**\n   * Extract provider-specific metadata from a tool call delta.\n   * Called once when a new tool call is detected.\n   * The returned metadata is stored on the tool call and passed to\n   * `buildToolCallProviderMetadata` when the tool call is finalized.\n   */\n  extractMetadata?: (delta: DELTA) => SharedV4ProviderMetadata | undefined;\n\n  /**\n   * Build the `providerMetadata` object for a `tool-call` event.\n   * Receives the metadata previously extracted via `extractMetadata`.\n   * If `undefined` is returned, no `providerMetadata` is included in the event.\n   */\n  buildToolCallProviderMetadata?: (\n    metadata: SharedV4ProviderMetadata | undefined,\n  ) => SharedV4ProviderMetadata | undefined;\n}\n\ninterface TrackedToolCall {\n  id: string;\n  type: 'function';\n  function: { name: string; arguments: string };\n  hasFinished: boolean;\n  metadata?: SharedV4ProviderMetadata;\n}\n\ntype StreamingToolCallTrackerController = Pick<\n  TransformStreamDefaultController<LanguageModelV4StreamPart>,\n  'enqueue'\n>;\n\n/**\n * Tracks streaming tool call state across multiple deltas from an\n * OpenAI-compatible chat completion stream. Handles argument accumulation,\n * emits tool-input-start/delta/end and tool-call events, and finalizes\n * unfinished tool calls on flush.\n *\n * Used by openai, openai-compatible, groq, deepseek, and alibaba providers.\n */\nexport class StreamingToolCallTracker<\n  DELTA extends StreamingToolCallDelta = StreamingToolCallDelta,\n> {\n  private toolCalls = new Set<TrackedToolCall>();\n  private toolCallsById = new Map<string, TrackedToolCall>();\n  private toolCallsByIndex = new Map<number, TrackedToolCall>();\n  private latestToolCall: TrackedToolCall | undefined;\n  private readonly controller: StreamingToolCallTrackerController;\n  private readonly _generateId: () => string;\n  private readonly typeValidation: 'none' | 'if-present' | 'required';\n  private readonly extractMetadata?: (\n    delta: DELTA,\n  ) => SharedV4ProviderMetadata | undefined;\n  private readonly buildToolCallProviderMetadata?: (\n    metadata: SharedV4ProviderMetadata | undefined,\n  ) => SharedV4ProviderMetadata | undefined;\n\n  constructor(\n    controller: StreamingToolCallTrackerController,\n    options: StreamingToolCallTrackerOptions<DELTA> = {},\n  ) {\n    this.controller = controller;\n    this._generateId = options.generateId ?? defaultGenerateId;\n    this.typeValidation = options.typeValidation ?? 'none';\n    this.extractMetadata = options.extractMetadata;\n    this.buildToolCallProviderMetadata = options.buildToolCallProviderMetadata;\n  }\n\n  /**\n   * Process a tool call delta from a streaming response chunk.\n   * Emits tool-input-start, tool-input-delta, tool-input-end, and tool-call\n   * events as appropriate.\n   */\n  processDelta(toolCallDelta: DELTA): void {\n    const { id, index } = toolCallDelta;\n    let toolCall =\n      id != null && id.length > 0\n        ? this.toolCallsById.get(id)\n        : index != null\n          ? this.toolCallsByIndex.get(index)\n          : this.latestToolCall;\n\n    if (toolCall == null) {\n      toolCall = this.processNewToolCall(toolCallDelta);\n    } else {\n      this.processExistingToolCall(toolCall, toolCallDelta);\n    }\n\n    if (index != null) {\n      this.toolCallsByIndex.set(index, toolCall);\n    }\n    this.latestToolCall = toolCall;\n  }\n\n  /**\n   * Finalize any unfinished tool calls. Should be called during the stream's\n   * flush handler to ensure all tool calls are properly completed.\n   */\n  flush(): void {\n    for (const toolCall of this.toolCalls) {\n      if (!toolCall.hasFinished) {\n        this.finishToolCall(toolCall);\n      }\n    }\n  }\n\n  private processNewToolCall(toolCallDelta: DELTA): TrackedToolCall {\n    if (this.typeValidation === 'required') {\n      if (toolCallDelta.type !== 'function') {\n        throw new InvalidResponseDataError({\n          data: toolCallDelta,\n          message: `Expected 'function' type.`,\n        });\n      }\n    } else if (this.typeValidation === 'if-present') {\n      if (toolCallDelta.type != null && toolCallDelta.type !== 'function') {\n        throw new InvalidResponseDataError({\n          data: toolCallDelta,\n          message: `Expected 'function' type.`,\n        });\n      }\n    }\n\n    if (toolCallDelta.id == null) {\n      throw new InvalidResponseDataError({\n        data: toolCallDelta,\n        message: `Expected 'id' to be a string.`,\n      });\n    }\n\n    if (toolCallDelta.function?.name == null) {\n      throw new InvalidResponseDataError({\n        data: toolCallDelta,\n        message: `Expected 'function.name' to be a string.`,\n      });\n    }\n\n    this.controller.enqueue({\n      type: 'tool-input-start',\n      id: toolCallDelta.id,\n      toolName: toolCallDelta.function.name,\n    });\n\n    const metadata = this.extractMetadata?.(toolCallDelta);\n\n    const toolCall: TrackedToolCall = {\n      id: toolCallDelta.id,\n      type: 'function',\n      function: {\n        name: toolCallDelta.function.name,\n        arguments: toolCallDelta.function.arguments ?? '',\n      },\n      hasFinished: false,\n      metadata,\n    };\n    this.toolCalls.add(toolCall);\n    if (toolCall.id.length > 0) {\n      this.toolCallsById.set(toolCall.id, toolCall);\n    }\n\n    // Emit initial delta if arguments already present\n    if (toolCall.function.arguments.length > 0) {\n      this.controller.enqueue({\n        type: 'tool-input-delta',\n        id: toolCall.id,\n        delta: toolCall.function.arguments,\n      });\n    }\n\n    // Tool calls must not finalize before the stream ends: a parsable\n    // argument buffer can still be the prefix of a longer argument string,\n    // so acting on it early would use truncated inputs (see #13137).\n    // Finalization happens in flush().\n    return toolCall;\n  }\n\n  private processExistingToolCall(\n    toolCall: TrackedToolCall,\n    toolCallDelta: DELTA,\n  ): void {\n    if (toolCall.hasFinished) {\n      return;\n    }\n\n    if (toolCallDelta.function?.arguments != null) {\n      toolCall.function.arguments += toolCallDelta.function.arguments;\n\n      this.controller.enqueue({\n        type: 'tool-input-delta',\n        id: toolCall.id,\n        delta: toolCallDelta.function.arguments,\n      });\n    }\n  }\n\n  private finishToolCall(toolCall: TrackedToolCall): void {\n    this.controller.enqueue({\n      type: 'tool-input-end',\n      id: toolCall.id,\n    });\n\n    const providerMetadata = this.buildToolCallProviderMetadata?.(\n      toolCall.metadata,\n    );\n\n    this.controller.enqueue({\n      type: 'tool-call',\n      toolCallId: toolCall.id ?? this._generateId(),\n      toolName: toolCall.function.name,\n      input: toolCall.function.arguments,\n      ...(providerMetadata ? { providerMetadata } : {}),\n    });\n\n    toolCall.hasFinished = true;\n  }\n}\n","/**\n * Strips file extension segments from a filename.\n *\n * Examples:\n * - \"report.pdf\" -> \"report\"\n * - \"archive.tar.gz\" -> \"archive\"\n * - \"filename\" -> \"filename\"\n */\nexport function stripFileExtension(filename: string): string {\n  const firstDotIndex = filename.indexOf('.');\n\n  return firstDotIndex === -1 ? filename : filename.slice(0, firstDotIndex);\n}\n","import type {\n  Experimental_TranscriptionModelV4StreamPart as TranscriptionModelV4StreamPart,\n  JSONObject,\n} from '@ai-sdk/provider';\nimport { isRecord } from './is-record';\nimport { secureJsonParse } from './secure-json-parse';\n\n/**\n * Experimental transcription-stream WebSocket envelope (v1): the standard\n * serialization of `TranscriptionModelV4.doStream` over a WebSocket. Clients\n * (e.g. the `@ai-sdk/gateway` provider) encode with this module and servers\n * (e.g. AI Gateway) decode with it, so the two sides cannot drift.\n *\n * Envelope rules:\n *\n * 1. The client sends exactly one `transcription-stream.start` TEXT frame\n *    first.\n * 2. Audio rides BINARY frames containing raw bytes in the declared\n *    `inputAudioFormat` (base64 string chunks are decoded before sending).\n * 3. The client signals end of audio with the\n *    `transcription-stream.audio-done` TEXT frame; a plain close without it\n *    is an abort.\n * 4. Every server→client TEXT frame is one JSON-serialized\n *    `TranscriptionModelV4StreamPart` (flattened, no wrapper). Payloads must\n *    be JSON-serializable. `Date` values (`response-metadata.timestamp`)\n *    serialize to ISO 8601 strings and are revived by\n *    `parseTranscriptionStreamPart`. `Error` payloads in `error` parts\n *    serialize as `{ name, message }`.\n * 5. The server closes with code 1000 after the `finish` part; on failure it\n *    sends an `error` part and closes non-1000. A close without a prior\n *    `finish` is an error.\n * 6. Unknown frame/part types are ignored in both directions (forward\n *    compatibility).\n * 7. Servers may enforce a maximum frame size (the AI Gateway rejects frames\n *    over 256 KiB); clients should split audio into frames of at most\n *    64 KiB.\n * 8. Connection establishment (URL, auth) is transport-specific and out of\n *    scope.\n *\n * The envelope validates frame shape only; server policy (accepted audio\n * formats, required `rate`, size limits) layers on top. Both parsers use\n * `secureJsonParse`, so frames carrying `__proto__` / `constructor.prototype`\n * keys are rejected (prototype-pollution protection) rather than parsed.\n */\n\n/** Type of the first client TEXT frame. */\nexport const TRANSCRIPTION_STREAM_START_FRAME_TYPE =\n  'transcription-stream.start';\n\n/** Type of the client TEXT frame that signals the end of the audio input. */\nexport const TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE =\n  'transcription-stream.audio-done';\n\n/**\n * The client's session start frame. Optional keys are omitted when undefined.\n */\nexport type TranscriptionStreamStartFrame = {\n  type: typeof TRANSCRIPTION_STREAM_START_FRAME_TYPE;\n\n  /** Audio format of the binary audio frames, e.g. `{ type: 'audio/pcm', rate: 16000 }`. */\n  inputAudioFormat: {\n    type: string;\n    rate?: number;\n  };\n\n  /** Provider-specific options, passed through verbatim. */\n  providerOptions?: Record<string, JSONObject>;\n\n  /** When true, the server should include `raw` parts in the stream. */\n  includeRawChunks?: boolean;\n};\n\n/** Server-side classification of a client TEXT frame. */\nexport type TranscriptionStreamClientFrame =\n  | {\n      type: 'start';\n      frame: TranscriptionStreamStartFrame;\n    }\n  | {\n      type: 'audio-done';\n    }\n  | {\n      /** Malformed JSON or a recognized frame with an invalid shape. */\n      type: 'invalid';\n      message: string;\n    }\n  | {\n      /** Unrecognized frame type; ignore for forward compatibility. */\n      type: 'unknown';\n    };\n\n/**\n * Server-side: parse a client TEXT frame. Validates envelope shape only and\n * rejects prototype-pollution payloads (parsed with `secureJsonParse`). Never\n * throws.\n */\nexport function parseTranscriptionStreamClientFrame(\n  text: string,\n): TranscriptionStreamClientFrame {\n  let value: unknown;\n  try {\n    value = secureJsonParse(text);\n  } catch {\n    return { type: 'invalid', message: 'malformed JSON' };\n  }\n\n  if (value == null || typeof value !== 'object' || Array.isArray(value)) {\n    return { type: 'invalid', message: 'frame must be a JSON object' };\n  }\n\n  const frame = value as Record<string, unknown>;\n\n  if (typeof frame.type !== 'string') {\n    return { type: 'invalid', message: 'frame type must be a string' };\n  }\n\n  switch (frame.type) {\n    case TRANSCRIPTION_STREAM_START_FRAME_TYPE: {\n      const inputAudioFormat = frame.inputAudioFormat as\n        | Record<string, unknown>\n        | null\n        | undefined;\n      if (\n        inputAudioFormat == null ||\n        typeof inputAudioFormat !== 'object' ||\n        Array.isArray(inputAudioFormat) ||\n        typeof inputAudioFormat.type !== 'string'\n      ) {\n        return {\n          type: 'invalid',\n          message:\n            'start frame must have an inputAudioFormat object with a string type',\n        };\n      }\n      if (\n        inputAudioFormat.rate !== undefined &&\n        typeof inputAudioFormat.rate !== 'number'\n      ) {\n        return {\n          type: 'invalid',\n          message: 'inputAudioFormat.rate must be a number when present',\n        };\n      }\n      if (\n        frame.providerOptions !== undefined &&\n        (frame.providerOptions == null ||\n          typeof frame.providerOptions !== 'object' ||\n          Array.isArray(frame.providerOptions))\n      ) {\n        return {\n          type: 'invalid',\n          message: 'providerOptions must be an object when present',\n        };\n      }\n      if (\n        frame.includeRawChunks !== undefined &&\n        typeof frame.includeRawChunks !== 'boolean'\n      ) {\n        return {\n          type: 'invalid',\n          message: 'includeRawChunks must be a boolean when present',\n        };\n      }\n      return {\n        type: 'start',\n        frame: frame as TranscriptionStreamStartFrame,\n      };\n    }\n\n    case TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE:\n      return { type: 'audio-done' };\n\n    default:\n      return { type: 'unknown' };\n  }\n}\n\n/**\n * Server-side: serialize a transcription stream part as one TEXT frame.\n * `Error` payloads in `error` parts serialize as `{ name, message }` —\n * `Error` properties are non-enumerable, so a plain `JSON.stringify` would\n * serialize them to `{}` and lose the message end-to-end. Returns\n * `undefined` for payloads that are not JSON-serializable (envelope rule 4,\n * e.g. bigint or cyclic values); callers drop the frame.\n */\nexport function serializeTranscriptionStreamPart(\n  part: TranscriptionModelV4StreamPart,\n): string | undefined {\n  try {\n    if (part.type === 'error' && isError(part.error)) {\n      return JSON.stringify({\n        ...part,\n        error: { name: part.error.name, message: part.error.message },\n      });\n    }\n    return JSON.stringify(part);\n  } catch {\n    return undefined;\n  }\n}\n\n// `instanceof` misses cross-realm Errors; the brand check does not.\nfunction isError(value: unknown): value is Error {\n  return (\n    value instanceof Error ||\n    Object.prototype.toString.call(value) === '[object Error]'\n  );\n}\n\n/**\n * Client-side: parse a server TEXT frame into a transcription stream part.\n * Returns `undefined` for malformed or unsafe (prototype-polluting) JSON\n * (parsed with `secureJsonParse`), unknown part types, and known part types\n * whose required or optional fields are missing or mistyped (including\n * warning and segment elements) — downstream SDK code dereferences those\n * fields, so a drifted server must not crash or pollute the stream.\n * Revives `response-metadata.timestamp` to a `Date`.\n */\nexport function parseTranscriptionStreamPart(\n  text: string,\n): TranscriptionModelV4StreamPart | undefined {\n  let value: unknown;\n  try {\n    value = secureJsonParse(text);\n  } catch {\n    return undefined;\n  }\n\n  if (value == null || typeof value !== 'object' || Array.isArray(value)) {\n    return undefined;\n  }\n\n  const part = value as TranscriptionModelV4StreamPart;\n\n  switch (part.type) {\n    case 'stream-start':\n      return Array.isArray(part.warnings) && part.warnings.every(isWarning)\n        ? part\n        : undefined;\n\n    case 'transcript-delta':\n      return isString(part.delta) &&\n        isOptional(part.id, isString) &&\n        isOptional(part.providerMetadata, isRecord)\n        ? part\n        : undefined;\n\n    case 'transcript-partial':\n      return isString(part.text) &&\n        isOptional(part.id, isString) &&\n        isOptional(part.startSecond, isNumber) &&\n        isOptional(part.durationInSeconds, isNumber) &&\n        isOptional(part.channelIndex, isNumber) &&\n        isOptional(part.providerMetadata, isRecord)\n        ? part\n        : undefined;\n\n    case 'transcript-final':\n      return isString(part.text) &&\n        isOptional(part.id, isString) &&\n        isOptional(part.startSecond, isNumber) &&\n        isOptional(part.endSecond, isNumber) &&\n        isOptional(part.channelIndex, isNumber) &&\n        isOptional(part.providerMetadata, isRecord)\n        ? part\n        : undefined;\n\n    case 'finish':\n      return isString(part.text) &&\n        Array.isArray(part.segments) &&\n        part.segments.every(isSegment) &&\n        isOptional(part.language, isString) &&\n        isOptional(part.durationInSeconds, isNumber) &&\n        isOptional(part.providerMetadata, isRecord)\n        ? part\n        : undefined;\n\n    case 'response-metadata': {\n      if (\n        !(\n          isOptional(part.modelId, isString) &&\n          isOptional(part.headers, isRecord)\n        )\n      ) {\n        return undefined;\n      }\n      // Envelope rule 4: timestamps ride as ISO 8601 strings.\n      const timestamp: unknown = part.timestamp;\n      if (timestamp == null) {\n        return { ...part, timestamp: undefined };\n      }\n      if (typeof timestamp !== 'string') {\n        return undefined;\n      }\n      const revived = new Date(timestamp);\n      return Number.isNaN(revived.getTime())\n        ? undefined\n        : { ...part, timestamp: revived };\n    }\n\n    case 'raw':\n      return 'rawValue' in part ? part : undefined;\n\n    case 'error':\n      return 'error' in part ? part : undefined;\n\n    default:\n      return undefined;\n  }\n}\n\nfunction isString(value: unknown): value is string {\n  return typeof value === 'string';\n}\n\nfunction isNumber(value: unknown): value is number {\n  return typeof value === 'number';\n}\n\nfunction isOptional(\n  value: unknown,\n  check: (value: unknown) => boolean,\n): boolean {\n  return value === undefined || check(value);\n}\n\nfunction isWarning(value: unknown): boolean {\n  return isRecord(value) && isString(value.type);\n}\n\nfunction isSegment(value: unknown): boolean {\n  return (\n    isRecord(value) &&\n    isString(value.text) &&\n    isNumber(value.startSecond) &&\n    isNumber(value.endSecond)\n  );\n}\n","import { InvalidArgumentError } from '@ai-sdk/provider';\n\nexport function validateBaseURL(baseURL: string | undefined) {\n  if (baseURL?.trim() === '') {\n    throw new InvalidArgumentError({\n      argument: 'baseURL',\n      message: 'baseURL must be a non-empty string.',\n    });\n  }\n\n  return baseURL;\n}\n","export function withoutTrailingSlash(url: string | undefined) {\n  return url?.replace(/\\/$/, '');\n}\n","import type { Tool } from './tool';\n\n/**\n * A tool that is guaranteed to expose an execute function.\n */\nexport type ExecutableTool<TOOL extends Tool = Tool> = TOOL & {\n  execute: NonNullable<TOOL['execute']>;\n};\n\n/**\n * Checks whether a tool exposes an execute function.\n */\nexport function isExecutableTool<TOOL extends Tool>(\n  tool: TOOL | undefined,\n): tool is ExecutableTool<TOOL> {\n  return tool != null && typeof tool.execute === 'function';\n}\n","export function isAsyncIterable<T = any>(obj: any): obj is AsyncIterable<T> {\n  return obj != null && typeof obj[Symbol.asyncIterator] === 'function';\n}\n","import { isAsyncIterable } from '../is-async-iterable';\nimport type { ExecutableTool } from './executable-tool';\nimport type { InferToolContext } from './infer-tool-context';\nimport type { InferToolInput } from './infer-tool-input';\nimport type { InferToolOutput } from './infer-tool-output';\nimport type { Tool } from './tool';\nimport type { ToolExecutionOptions } from './tool-execute-function';\n\n/**\n * Executes a tool function and normalizes its results into a stream of outputs.\n *\n * - If the tool's `execute` function returns an `AsyncIterable`, each yielded value is emitted as\n *   `{ type: \"preliminary\", output }`. After iteration completes, the last yielded value is emitted\n *   again as `{ type: \"final\", output }`.\n * - If the tool returns a direct value or Promise, a single `{ type: \"final\", output }` is yielded.\n *\n * @param params.tool The tool whose `execute` function should be invoked.\n * @param params.input The input value to pass to the tool.\n * @param params.options Additional options for tool execution.\n * @yields A preliminary output for each streamed value, followed by a final output, or a single final\n * output for non-streaming tools.\n */\nexport async function* executeTool<TOOL extends Tool>({\n  tool,\n  input,\n  options,\n}: {\n  tool: ExecutableTool<TOOL>;\n  input: InferToolInput<TOOL>;\n  options: ToolExecutionOptions<InferToolContext<TOOL>>;\n}): AsyncGenerator<\n  | { type: 'preliminary'; output: InferToolOutput<TOOL> }\n  | { type: 'final'; output: InferToolOutput<TOOL> }\n> {\n  const result = tool.execute(input, options);\n\n  if (isAsyncIterable(result)) {\n    let lastOutput: InferToolOutput<TOOL> | undefined;\n    for await (const output of result) {\n      lastOutput = output;\n      yield { type: 'preliminary', output };\n    }\n    yield { type: 'final', output: lastOutput! };\n  } else {\n    yield { type: 'final', output: await result };\n  }\n}\n","import type { ProviderOptions } from './provider-options';\nimport type { Tool } from './tool';\nimport type { ToolSet } from './tool-set';\n\nexport type ToolCallerDefinition =\n  | {\n      type: 'local';\n      bind: (tools: ToolSet) => Tool;\n      /**\n       * Creates a provider-agnostic user message that describes the tools\n       * available through this caller. When present, the unbound caller tool\n       * remains model-visible so its definition stays stable, while the\n       * returned message is added to the conversation when its content has\n       * not already been announced.\n       */\n      prepareModelMessage?: (tools: ToolSet) => string | undefined;\n    }\n  | {\n      type: 'provider';\n      prepareProviderOptions: (\n        providerOptions: ProviderOptions | undefined,\n      ) => ProviderOptions;\n    };\n\nexport type ToolCallerTool<TOOL extends Tool = Tool> = TOOL & {\n  readonly experimental_toolCaller: ToolCallerDefinition;\n};\n\nexport function toolCaller<TOOL extends Tool>(\n  tool: TOOL,\n  definition: ToolCallerDefinition,\n): ToolCallerTool<TOOL> {\n  return Object.defineProperty({ ...tool }, 'experimental_toolCaller', {\n    value: definition,\n  }) as ToolCallerTool<TOOL>;\n}\n\nexport function getToolCaller(\n  tool: Tool | undefined,\n): ToolCallerDefinition | undefined {\n  return (tool as ToolCallerTool | undefined)?.experimental_toolCaller;\n}\n","export { asArray } from './as-array';\nexport type { Arrayable } from './as-array';\nexport * from './combine-headers';\nexport {\n  connectToWebSocket,\n  type WebSocketConnection,\n} from './connect-to-websocket';\nexport { convertAsyncIteratorToReadableStream } from './convert-async-iterator-to-readable-stream';\nexport { convertInlineFileDataToUint8Array } from './convert-inline-file-data-to-uint8-array';\nexport { convertImageModelFileToDataUri } from './convert-image-model-file-to-data-uri';\nexport { convertToFormData } from './convert-to-form-data';\nexport { createLanguageModelResponseMetadata } from './create-language-model-response-metadata';\nexport { createNullLanguageModelUsage } from './create-null-language-model-usage';\nexport {\n  createToolNameMapping,\n  type ToolNameMapping,\n} from './create-tool-name-mapping';\nexport {\n  createProviderStreamError,\n  isProviderStreamError,\n  type ProviderStreamError,\n} from './create-provider-stream-error';\nexport * from './delay';\nexport { DelayedPromise } from './delayed-promise';\nexport * from './delete-from-api';\nexport {\n  detectMediaType,\n  getTopLevelMediaType,\n  isFullMediaType,\n} from './detect-media-type';\nexport { downloadBlob } from './download-blob';\nexport { DownloadError } from './download-error';\nexport { EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL } from './embedding-model-capabilities';\nexport {\n  fetchWithValidatedEndpoint,\n  fetchWithValidatedRedirects,\n} from './fetch-with-validated-redirects';\nexport { extractLines } from './extract-lines';\nexport * from './extract-response-headers';\nexport * from './fetch-function';\nexport { filterNullable } from './filter-nullable';\nexport { createIdGenerator, generateId, type IdGenerator } from './generate-id';\nexport * from './get-error-message';\nexport * from './get-from-api';\nexport { getRuntimeEnvironmentUserAgent } from './get-runtime-environment-user-agent';\nexport type { HasRequiredKey } from './has-required-key';\nexport { injectJsonInstructionIntoMessages } from './inject-json-instruction';\nexport * from './is-abort-error';\nexport { isBrowserRuntime } from './is-browser-runtime';\nexport { isBuffer } from './is-buffer';\nexport { isSameOrigin } from './is-same-origin';\nexport { isNonNullable } from './is-non-nullable';\nexport { isProviderReference } from './is-provider-reference';\nexport { isRecord } from './is-record';\nexport { isUrlSupported } from './is-url-supported';\nexport * from './load-api-key';\nexport { loadOptionalSetting } from './load-optional-setting';\nexport { loadSetting } from './load-setting';\nexport {\n  isCustomReasoning,\n  mapReasoningToProviderBudget,\n  mapReasoningToProviderEffort,\n} from './map-reasoning-to-provider';\nexport { type MaybePromiseLike } from './maybe-promise-like';\nexport { mediaTypeToExtension } from './media-type-to-extension';\nexport { normalizeHeaders } from './normalize-headers';\nexport { normalizeBatchRequestCounts } from './normalize-batch-request-counts';\nexport * from './parse-json';\nexport { parseJsonEventStream } from './parse-json-event-stream';\nexport { parseProviderOptions } from './parse-provider-options';\nexport * from './post-multipart-stream-to-api';\nexport * from './post-to-api';\nexport {\n  createProviderDefinedToolFactory,\n  createProviderDefinedToolFactoryWithOutputSchema,\n  type ProviderDefinedToolFactory,\n  type ProviderDefinedToolFactoryWithOutputSchema,\n} from './provider-defined-tool-factory';\nexport {\n  createProviderExecutedToolFactory,\n  type ProviderExecutedToolFactory,\n} from './provider-executed-tool-factory';\nexport { cancelResponseBody } from './cancel-response-body';\nexport {\n  DEFAULT_MAX_DOWNLOAD_SIZE,\n  readResponseWithSizeLimit,\n} from './read-response-with-size-limit';\nexport * from './remove-undefined-entries';\nexport * from './resolve';\nexport { resolveFullMediaType } from './resolve-full-media-type';\nexport { resolveProviderReference } from './resolve-provider-reference';\nexport * from './retry-with-exponential-backoff';\nexport * from './response-handler';\nexport {\n  asSchema,\n  jsonSchema,\n  lazySchema,\n  zodSchema,\n  type FlexibleSchema,\n  type InferSchema,\n  type LazySchema,\n  type Schema,\n  type ValidationResult,\n} from './schema';\nexport { serializeModelOptions } from './serialize-model-options';\nexport { SerializationError } from './serialization-error';\nexport { secureJsonParse } from './secure-json-parse';\nexport {\n  StreamingToolCallTracker,\n  type StreamingToolCallDelta,\n  type StreamingToolCallTrackerOptions,\n} from './streaming-tool-call-tracker';\nexport { stripFileExtension } from './strip-file-extension';\nexport {\n  TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE as EXPERIMENTAL_TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE,\n  TRANSCRIPTION_STREAM_START_FRAME_TYPE as EXPERIMENTAL_TRANSCRIPTION_STREAM_START_FRAME_TYPE,\n  parseTranscriptionStreamClientFrame as experimental_parseTranscriptionStreamClientFrame,\n  parseTranscriptionStreamPart as experimental_parseTranscriptionStreamPart,\n  serializeTranscriptionStreamPart as experimental_serializeTranscriptionStreamPart,\n  type TranscriptionStreamClientFrame as Experimental_TranscriptionStreamClientFrame,\n  type TranscriptionStreamStartFrame as Experimental_TranscriptionStreamStartFrame,\n} from './transcription-stream-envelope';\nexport * from './uint8-utils';\nexport { validateBaseURL } from './validate-base-url';\nexport { validateDownloadUrl } from './validate-download-url';\nexport * from './validate-types';\nexport { VERSION } from './version';\nexport {\n  getWebSocketConstructor,\n  readWebSocketMessageText,\n  toWebSocketUrl,\n  waitForWebSocketBufferDrain,\n  type WebSocketConstructor,\n  type WebSocketLike,\n} from './websocket';\nexport { withUserAgentSuffix } from './with-user-agent-suffix';\nexport * from './without-trailing-slash';\n\n// folder re-exports\nexport * from './types';\n\n// external re-exports\nexport type * from '@standard-schema/spec';\nexport { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from '@workflow/serde';\nexport {\n  EventSourceParserStream,\n  type EventSourceMessage,\n} from 'eventsource-parser/stream';\n","// import globals\nimport './global';\n\n// re-exports:\nexport {\n  createGateway,\n  gateway,\n  type GatewayAsyncJobMetadata,\n  type GatewayModelId,\n  type GatewayProviderMetadata,\n} from '@ai-sdk/gateway';\nexport {\n  asSchema,\n  createIdGenerator,\n  dynamicTool,\n  experimental_toolCaller,\n  generateId,\n  jsonSchema,\n  parseJsonEventStream,\n  tool,\n  zodSchema,\n  type FlexibleSchema,\n  type IdGenerator,\n  type InferSchema,\n  type InferToolInput,\n  type InferToolOutput,\n  type Experimental_SandboxSession,\n  type Experimental_SandboxProcess,\n  type Experimental_ToolCallerTool,\n  type Schema,\n  type Tool,\n  type ToolApprovalRequest,\n  type ToolApprovalResponse,\n  type ToolExecuteFunction,\n  type ToolExecutionOptions,\n  type ToolSet,\n} from '@ai-sdk/provider-utils';\n\n// directory exports\nexport * from './agent';\nexport * from './batch';\nexport * from './embed';\nexport * from './error';\nexport * from './evaluate';\nexport * from './generate-image';\nexport * from './generate-object';\nexport * from './generate-speech';\nexport * from './generate-text';\nexport * from './generate-video';\nexport * from './logger';\nexport * from './middleware';\nexport * from './prompt';\nexport * from './realtime';\nexport * from './registry';\nexport * from './rerank';\nexport * from './telemetry';\nexport * from './text-stream';\nexport { toolSearch } from './tool-search/tool-search';\nexport * from './transcribe';\nexport * from './translate';\nexport * from './types';\nexport * from './ui';\nexport * from './ui-message-stream';\nexport * from './upload-file';\nexport * from './upload-skill';\nexport * from './util';\n","import {\n  validateTypes,\n  withUserAgentSuffix,\n  type Context,\n  type Experimental_SandboxSession as SandboxSession,\n  type ModelMessage,\n  type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { generateText } from '../generate-text/generate-text';\nimport type {\n  GenerateTextOnStartCallback,\n  GenerateTextOnStepStartCallback,\n} from '../generate-text/generate-text-events';\nimport type { GenerateTextResult } from '../generate-text/generate-text-result';\nimport type { Output } from '../generate-text/output';\nimport { isStepCount } from '../generate-text/stop-condition';\nimport { streamText } from '../generate-text/stream-text';\nimport type { StreamTextResult } from '../generate-text/stream-text-result';\nimport type { Prompt } from '../prompt';\nimport { mergeCallbacks } from '../util/merge-callbacks';\nimport type {\n  Agent,\n  AgentCallParameters,\n  AgentStreamParameters,\n} from './agent';\nimport type { ToolLoopAgentSettings } from './tool-loop-agent-settings';\n\n/**\n * A tool loop agent is an agent that runs tools in a loop. In each step,\n * it calls the LLM, and if there are tool calls, it executes the tools\n * and calls the LLM again in a new step with the tool results.\n *\n * The loop continues until:\n * - A finish reasoning other than tool-calls is returned, or\n * - A tool that is invoked does not have an execute function, or\n * - A tool call needs approval via `toolApproval` or tool-level `needsApproval`, or\n * - A stop condition is met (default stop condition is isStepCount(20))\n */\nexport class ToolLoopAgent<\n  CALL_OPTIONS = never,\n  TOOLS extends ToolSet = {},\n  RUNTIME_CONTEXT extends Context = Context,\n  OUTPUT extends Output = never,\n> implements Agent<CALL_OPTIONS, TOOLS, RUNTIME_CONTEXT, OUTPUT> {\n  readonly version = 'agent-v1';\n\n  private readonly settings: ToolLoopAgentSettings<\n    CALL_OPTIONS,\n    TOOLS,\n    RUNTIME_CONTEXT,\n    OUTPUT\n  >;\n\n  constructor(\n    settings: ToolLoopAgentSettings<\n      CALL_OPTIONS,\n      TOOLS,\n      RUNTIME_CONTEXT,\n      OUTPUT\n    >,\n  ) {\n    const { onFinish, onEnd = onFinish } = settings;\n    this.settings = { ...settings, onEnd };\n  }\n\n  /**\n   * The id of the agent.\n   */\n  get id(): string | undefined {\n    return this.settings.id;\n  }\n\n  /**\n   * The tools that the agent can use.\n   */\n  get tools(): TOOLS {\n    return this.settings.tools as TOOLS;\n  }\n\n  private async prepareCall(options: {\n    prompt?: string | Array<ModelMessage>;\n    messages?: Array<ModelMessage>;\n    options?: CALL_OPTIONS;\n    experimental_sandbox?: SandboxSession;\n  }): Promise<\n    Omit<\n      ToolLoopAgentSettings<CALL_OPTIONS, TOOLS, RUNTIME_CONTEXT, OUTPUT>,\n      | 'prepareCall'\n      | 'instructions'\n      | 'allowSystemInMessages'\n      | 'onStart'\n      | 'experimental_onStart'\n      | 'onStepStart'\n      | 'experimental_onStepStart'\n      | 'onToolExecutionStart'\n      | 'onToolExecutionEnd'\n      | 'onStepEnd'\n      | 'onStepFinish'\n      | 'onEnd'\n      | 'onFinish'\n    > &\n      Prompt\n  > {\n    if (\n      this.settings.callOptionsSchema != null &&\n      options.options !== undefined\n    ) {\n      const validatedOptions = await validateTypes({\n        value: options.options,\n        schema: this.settings.callOptionsSchema,\n        context: { field: 'options' },\n      });\n      options = { ...options, options: validatedOptions };\n    }\n\n    const {\n      onStart: _settingsStableOnStart,\n      experimental_onStart: _settingsExperimentalOnStart,\n      onStepStart: _settingsStableOnStepStart,\n      experimental_onStepStart: _settingsExperimentalOnStepStart,\n      onToolExecutionStart: _settingsOnToolExecutionStart,\n      onToolExecutionEnd: _settingsOnToolExecutionEnd,\n      onStepEnd: _settingsOnStepEnd,\n      onStepFinish: _settingsOnStepFinish,\n      onFinish: _settingsOnFinish,\n      onEnd: _settingsOnEnd,\n      ...settingsWithoutCallbacks\n    } = this.settings;\n\n    const baseCallArgs = {\n      ...settingsWithoutCallbacks,\n      stopWhen: this.settings.stopWhen ?? isStepCount(20),\n      ...options,\n    };\n\n    const preparedCallArgs =\n      (await this.settings.prepareCall?.(\n        baseCallArgs as Parameters<\n          NonNullable<\n            ToolLoopAgentSettings<\n              CALL_OPTIONS,\n              TOOLS,\n              RUNTIME_CONTEXT,\n              OUTPUT\n            >['prepareCall']\n          >\n        >[0],\n      )) ?? baseCallArgs;\n\n    const {\n      instructions,\n      allowSystemInMessages,\n      messages,\n      prompt,\n      runtimeContext,\n      ...callArgs\n    } = preparedCallArgs;\n\n    const promptArgs = {\n      instructions,\n      allowSystemInMessages,\n      messages,\n      prompt,\n    } as Prompt;\n\n    if (runtimeContext === undefined) {\n      return {\n        ...callArgs,\n        ...promptArgs,\n      };\n    }\n\n    return {\n      ...callArgs,\n      runtimeContext,\n      ...promptArgs,\n    };\n  }\n\n  /**\n   * Tags outgoing requests so usage can be attributed to ToolLoopAgent. Chains\n   * with the `ai/<version>` and `ai-sdk/<provider>/<version>` suffixes added\n   * downstream by generateText/streamText and the provider.\n   */\n  private agentHeaders(preparedCall: {\n    headers?: unknown;\n  }): Record<string, string> {\n    return withUserAgentSuffix(\n      (preparedCall.headers as Record<string, string | undefined>) ?? {},\n      'ai-sdk-agent/tool-loop',\n    );\n  }\n\n  /**\n   * Generates an output from the agent (non-streaming).\n   */\n  async generate({\n    abortSignal,\n    timeout,\n    experimental_sandbox: sandbox,\n    onStart,\n    experimental_onStart,\n    onStepStart,\n    experimental_onStepStart,\n    onToolExecutionStart,\n    onToolExecutionEnd,\n    onStepEnd,\n    onStepFinish,\n    onFinish,\n    onEnd = onFinish,\n    ...options\n  }: AgentCallParameters<CALL_OPTIONS, TOOLS, RUNTIME_CONTEXT>): Promise<\n    GenerateTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>\n  > {\n    const generate = generateText<TOOLS, RUNTIME_CONTEXT, OUTPUT>;\n    const preparedCall = await this.prepareCall({\n      ...options,\n      experimental_sandbox: sandbox,\n    });\n    const callbackArgs = {\n      abortSignal,\n      timeout: timeout ?? preparedCall.timeout,\n      experimental_sandbox: sandbox,\n      onStart: mergeCallbacks(\n        this.settings.onStart ?? this.settings.experimental_onStart,\n        (onStart ?? experimental_onStart) as\n          | GenerateTextOnStartCallback<TOOLS, RUNTIME_CONTEXT, OUTPUT>\n          | undefined,\n      ),\n      onStepStart: mergeCallbacks(\n        this.settings.onStepStart ?? this.settings.experimental_onStepStart,\n        (onStepStart ?? experimental_onStepStart) as\n          | GenerateTextOnStepStartCallback<TOOLS, RUNTIME_CONTEXT, OUTPUT>\n          | undefined,\n      ),\n      onToolExecutionStart: mergeCallbacks(\n        this.settings.onToolExecutionStart,\n        onToolExecutionStart,\n      ),\n      onToolExecutionEnd: mergeCallbacks(\n        this.settings.onToolExecutionEnd,\n        onToolExecutionEnd,\n      ),\n      onStepEnd: mergeCallbacks(\n        this.settings.onStepEnd ?? this.settings.onStepFinish,\n        onStepEnd ?? onStepFinish,\n      ),\n      onEnd: mergeCallbacks(this.settings.onEnd, onEnd),\n    };\n\n    return await generate({\n      ...preparedCall,\n      ...callbackArgs,\n      headers: this.agentHeaders(preparedCall),\n    } as unknown as Parameters<typeof generate>[0]);\n  }\n\n  /**\n   * Streams an output from the agent (streaming).\n   */\n  async stream({\n    abortSignal,\n    timeout,\n    experimental_sandbox: sandbox,\n    experimental_transform,\n    onStart,\n    experimental_onStart,\n    onStepStart,\n    experimental_onStepStart,\n    onToolExecutionStart,\n    onToolExecutionEnd,\n    onStepEnd,\n    onStepFinish,\n    onFinish,\n    onEnd = onFinish,\n    ...options\n  }: AgentStreamParameters<CALL_OPTIONS, TOOLS, RUNTIME_CONTEXT>): Promise<\n    StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>\n  > {\n    const stream = streamText<TOOLS, RUNTIME_CONTEXT, OUTPUT>;\n    const preparedCall = await this.prepareCall({\n      ...options,\n      experimental_sandbox: sandbox,\n    });\n    const callbackArgs = {\n      abortSignal,\n      timeout: timeout ?? preparedCall.timeout,\n      experimental_sandbox: sandbox,\n      experimental_transform,\n      onStart: mergeCallbacks(\n        this.settings.onStart ?? this.settings.experimental_onStart,\n        (onStart ?? experimental_onStart) as\n          | GenerateTextOnStartCallback<TOOLS, RUNTIME_CONTEXT, OUTPUT>\n          | undefined,\n      ),\n      onStepStart: mergeCallbacks(\n        this.settings.onStepStart ?? this.settings.experimental_onStepStart,\n        (onStepStart ?? experimental_onStepStart) as\n          | GenerateTextOnStepStartCallback<TOOLS, RUNTIME_CONTEXT, OUTPUT>\n          | undefined,\n      ),\n      onToolExecutionStart: mergeCallbacks(\n        this.settings.onToolExecutionStart,\n        onToolExecutionStart,\n      ),\n      onToolExecutionEnd: mergeCallbacks(\n        this.settings.onToolExecutionEnd,\n        onToolExecutionEnd,\n      ),\n      onStepEnd: mergeCallbacks(\n        this.settings.onStepEnd ?? this.settings.onStepFinish,\n        onStepEnd ?? onStepFinish,\n      ),\n      onEnd: mergeCallbacks(this.settings.onEnd, onEnd),\n    };\n\n    return await stream({\n      ...preparedCall,\n      ...callbackArgs,\n      headers: this.agentHeaders(preparedCall),\n    } as unknown as Parameters<typeof stream>[0]);\n  }\n}\n","import type {\n  LanguageModelV4GenerateResult,\n  LanguageModelV4ToolCall,\n} from '@ai-sdk/provider';\nimport {\n  asArray,\n  createIdGenerator,\n  getErrorMessage,\n  withUserAgentSuffix,\n  type Arrayable,\n  type Context,\n  type Experimental_SandboxSession as SandboxSession,\n  type IdGenerator,\n  type InferToolSetContext,\n  type ProviderOptions,\n  type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { NoOutputGeneratedError, ToolChoiceViolationError } from '../error';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveLanguageModel } from '../model/resolve-model';\nimport type { ModelMessage } from '../prompt';\nimport { cloneModelMessages } from '../prompt/clone-model-message';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { createToolModelOutput } from '../prompt/create-tool-model-output';\nimport type { LanguageModelCallOptions } from '../prompt/language-model-call-options';\nimport { prepareLanguageModelCallOptions } from '../prompt/prepare-language-model-call-options';\nimport { prepareToolChoice } from '../prompt/prepare-tool-choice';\nimport { prepareTools } from '../prompt/prepare-tools';\nimport type { Prompt } from '../prompt/prompt';\nimport {\n  getChunkTimeoutMs,\n  getFirstChunkTimeoutMs,\n  getStepTimeoutMs,\n  getTotalTimeoutMs,\n  type RequestOptions,\n  type TimeoutConfiguration,\n} from '../prompt/request-options';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport { wrapGatewayError } from '../prompt/wrap-gateway-error';\nimport type { Telemetry, TelemetryDispatcher } from '../telemetry/telemetry';\nimport type { TelemetryOptions } from '../telemetry/telemetry-options';\nimport type {\n  LanguageModel,\n  LanguageModelRequestMetadata,\n  ToolChoice,\n  Warning,\n} from '../types';\nimport {\n  addLanguageModelUsage,\n  asLanguageModelUsage,\n  type LanguageModelUsage,\n} from '../types/usage';\nimport type { DownloadFunction } from '../util/download/download-function';\nimport { getOwn } from '../util/get-own';\nimport { mergeAbortSignals } from '../util/merge-abort-signals';\nimport { mergeObjects } from '../util/merge-objects';\nimport { now as originalNow } from '../util/now';\nimport { notify } from '../util/notify';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { setAbortTimeout } from '../util/set-abort-timeout';\nimport { VERSION } from '../version';\nimport type { ActiveTools } from './active-tools';\nimport { calculateTokensPerSecond } from './calculate-tokens-per-second';\nimport { collectToolApprovals } from './collect-tool-approvals';\nimport { convertLanguageModelContent } from './convert-language-model-content';\nimport { createToolSearchState } from '../tool-search/prepare-tool-search';\nimport { executeToolCall } from './execute-tool-call';\nimport {\n  filterActiveTools,\n  type ActiveToolSubset,\n} from './filter-active-tools';\nimport type {\n  GenerateTextOnEndCallback,\n  GenerateTextOnStartCallback,\n  GenerateTextOnStepEndCallback,\n  GenerateTextOnStepFinishCallback,\n  GenerateTextOnStepStartCallback,\n} from './generate-text-events';\nimport type { GenerateTextResult } from './generate-text-result';\nimport { isToolExecutionAllowedFinishReason } from './is-tool-execution-allowed-finish-reason';\nimport type {\n  OnLanguageModelCallEndCallback,\n  OnLanguageModelCallStartCallback,\n} from './language-model-events';\nimport { text, type Output } from './output';\nimport type { InferCompleteOutput } from './output-utils';\nimport { parseToolCall } from './parse-tool-call';\nimport type { PrepareStepFunction } from './prepare-step';\nimport { prepareStepCallSettings } from './prepare-step-call-settings';\nimport { convertToReasoningOutputs } from './reasoning-output';\nimport { resolveToolApproval } from './resolve-tool-approval';\nimport type { ResponseMessage } from './response-message';\nimport { createRestrictedTelemetryDispatcher } from './restricted-telemetry-dispatcher';\nimport {\n  DefaultStepResult,\n  type StepResult,\n  type StepResultPerformance,\n} from './step-result';\nimport {\n  isStepCount,\n  isStopConditionMet,\n  type StopCondition,\n} from './stop-condition';\nimport { sumTokenCounts } from './sum-token-counts';\nimport { toResponseMessages } from './to-response-messages';\nimport type { ToolApprovalConfiguration } from './tool-approval-configuration';\nimport type { ToolApprovalRequestOutput } from './tool-approval-request-output';\nimport type { ToolApprovalResponseOutput } from './tool-approval-response-output';\nimport {\n  appendToolCallerMessages,\n  prepareToolsForToolCallers,\n  resolveToolCallerConfiguration,\n  type Experimental_ToolCallers,\n} from './tool-caller-configuration';\nimport type { TypedToolCall } from './tool-call';\nimport type { ToolCallRepairFunction } from './tool-call-repair-function';\nimport type {\n  OnToolExecutionEndCallback,\n  OnToolExecutionStartCallback,\n} from './tool-execution-events';\nimport type { ToolInputRefinement } from './tool-input-refinement';\nimport type { ToolOrder } from './tool-order';\nimport type { ToolOutput } from './tool-output';\nimport type { ToolsContextParameter } from './tools-context-parameter';\nimport { maybeSignApproval } from './tool-approval-signature';\nimport { validateApprovedToolApprovals } from './validate-tool-approvals';\n\nconst originalGenerateId = createIdGenerator({\n  prefix: 'aitxt',\n  size: 24,\n});\n\nconst originalGenerateCallId = createIdGenerator({\n  prefix: 'call',\n  size: 24,\n});\n\nexport type GenerateTextInclude = {\n  /**\n   * Whether to retain the request body in step results.\n   * The request body can be large when sending images or files.\n   *\n   * @default false\n   */\n  requestBody?: boolean;\n\n  /**\n   * Whether to retain the request messages in step results.\n   * The request messages can be large when sending images or files.\n   *\n   * @default false\n   */\n  requestMessages?: boolean;\n\n  /**\n   * Whether to retain the response body in step results.\n   *\n   * @default false\n   */\n  responseBody?: boolean;\n};\n\n/**\n * Generate a text and call tools for a given prompt using a language model.\n *\n * This function does not stream the output. If you want to stream the output, use `streamText` instead.\n *\n * @param model - The language model to use.\n *\n * @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.\n * @param toolChoice - The tool choice strategy. Default: 'auto'.\n * @param toolOrder - Controls the order in which tools are sent to the provider. Tools not listed are appended alphabetically.\n *\n * @param system - A system message that will be part of the prompt.\n * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n * @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false.\n *\n * @param maxOutputTokens - Maximum number of tokens to generate.\n * @param temperature - Temperature setting.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topP - Nucleus sampling.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topK - Only sample from the top K options for each subsequent token.\n * Used to remove \"long tail\" low probability responses.\n * Recommended for advanced use cases only. You usually only need to use temperature.\n * @param presencePenalty - Presence penalty setting.\n * It affects the likelihood of the model to repeat information that is already in the prompt.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param frequencyPenalty - Frequency penalty setting.\n * It affects the likelihood of the model to repeatedly use the same words or phrases.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param stopSequences - Stop sequences.\n * If set, the model will stop generating text when one of the stop sequences is generated.\n * @param seed - The seed (integer) to use for random sampling.\n * If set and supported by the model, calls will generate deterministic results.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param timeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @param experimental_sandbox - The sandbox environment that is passed through to tool execution.\n * @param runtimeContext - User-defined runtime context that flows through the entire generation lifecycle.\n * @param experimental_refineToolInput - Optional mapping of tool names to functions that refine parsed tool inputs before tools are executed and before outputs, callbacks, and telemetry are recorded.\n * @param onStart - Callback invoked when generation begins, before any LLM calls.\n * @param experimental_onStart - Deprecated alias for `onStart`.\n * @param onStepStart - Callback invoked when each step begins, before the provider is called.\n * @param experimental_onStepStart - Deprecated alias for `onStepStart`.\n * Receives step number, messages (in ModelMessage format), tools, and runtimeContext.\n * @param onLanguageModelCallStart - Callback invoked immediately before each provider model call begins.\n * @param experimental_onLanguageModelCallStart - Deprecated alias for `onLanguageModelCallStart`.\n * @param onLanguageModelCallEnd - Callback invoked after each provider model call response is normalized and parsed.\n * @param experimental_onLanguageModelCallEnd - Deprecated alias for `onLanguageModelCallEnd`.\n * @param onToolExecutionStart - Callback invoked before each tool execution begins.\n * Receives tool name, call ID, input, and context.\n * @param experimental_onToolCallStart - Deprecated alias for `onToolExecutionStart`.\n * @param onToolExecutionEnd - Callback invoked after each tool execution completes.\n * Uses a discriminated union: check `success` to determine if `output` or `error` is present.\n * @param experimental_onToolCallFinish - Deprecated alias for `onToolExecutionEnd`.\n * @param onStepFinish - Callback that is called when each step (LLM call) is finished, including intermediate steps.\n * @param onEnd - Callback that is called when all steps are finished and the response is complete.\n * @param onFinish - Deprecated alias for `onEnd`.\n *\n * @returns\n * A result object that contains the generated text, the results of the tool calls, and additional information.\n */\nexport async function generateText<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context = Context,\n  OUTPUT extends Output = Output<string, string>,\n>({\n  model: modelArg,\n  tools,\n  toolChoice,\n  instructions,\n  system,\n  prompt,\n  messages,\n  allowSystemInMessages,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  timeout,\n  headers,\n  stopWhen = isStepCount(1),\n  experimental_sandbox: sandbox,\n  output,\n  toolApproval,\n  experimental_toolCallers,\n  experimental_toolApprovalSecret,\n  experimental_telemetry,\n  telemetry = experimental_telemetry,\n  providerOptions,\n  activeTools,\n  toolOrder,\n  prepareStep,\n  experimental_repairToolCall,\n  repairToolCall = experimental_repairToolCall,\n  experimental_refineToolInput: refineToolInput,\n  experimental_download: download,\n  runtimeContext = {} as RUNTIME_CONTEXT,\n  toolsContext = {} as InferToolSetContext<TOOLS>,\n  experimental_include,\n  include = experimental_include,\n  _internal: {\n    generateId = originalGenerateId,\n    generateCallId = originalGenerateCallId,\n    now = originalNow,\n  } = {},\n  onStart,\n  experimental_onStart,\n  onStepStart,\n  experimental_onStepStart,\n  onLanguageModelCallStart,\n  experimental_onLanguageModelCallStart,\n  onLanguageModelCallEnd,\n  experimental_onLanguageModelCallEnd,\n  onToolExecutionStart,\n  onToolExecutionEnd,\n  experimental_onToolCallStart,\n  experimental_onToolCallFinish,\n  onStepEnd,\n  onStepFinish,\n  onFinish,\n  onEnd = onFinish,\n  ...settings\n}: LanguageModelCallOptions &\n  RequestOptions<TOOLS> &\n  Prompt &\n  ToolsContextParameter<TOOLS> & {\n    /**\n     * The language model to use.\n     */\n    model: LanguageModel;\n\n    /**\n     * The tool choice strategy. Default: 'auto'.\n     */\n    toolChoice?: ToolChoice<NoInfer<TOOLS>>;\n\n    /**\n     * Condition for stopping the generation when there are tool results in the last step.\n     * When the condition is an array, any of the conditions can be met to stop the generation.\n     *\n     * @default isStepCount(1)\n     */\n    stopWhen?: Arrayable<StopCondition<NoInfer<TOOLS>, RUNTIME_CONTEXT>>;\n\n    /**\n     * Optional telemetry configuration.\n     */\n    telemetry?: TelemetryOptions<RUNTIME_CONTEXT, NoInfer<TOOLS>>;\n\n    /**\n     * Optional telemetry configuration.\n     *\n     * @deprecated Use `telemetry` instead. This alias will be removed in a future major release.\n     */\n    experimental_telemetry?: TelemetryOptions<RUNTIME_CONTEXT, NoInfer<TOOLS>>;\n\n    /**\n     * Additional provider-specific options. They are passed through\n     * to the provider from the AI SDK and enable provider-specific\n     * functionality that can be fully encapsulated in the provider.\n     */\n    providerOptions?: ProviderOptions;\n\n    /**\n     * The sandbox environment that is passed through to tool execution.\n     */\n    experimental_sandbox?: SandboxSession;\n\n    /**\n     * Runtime context. Treat runtime context as immutable.\n     * If you need to mutate runtime context, update it in `prepareStep`.\n     */\n    runtimeContext?: RUNTIME_CONTEXT;\n\n    /**\n     * Limits the tools that are available for the model to call without\n     * changing the tool call and result types in the result.\n     */\n    activeTools?: ActiveTools<NoInfer<TOOLS>>;\n\n    /**\n     * Controls the order in which tools are sent to the provider.\n     *\n     * The list can be partial. Tools not listed in `toolOrder` are sent after\n     * the listed tools, sorted alphabetically. This can improve provider-side\n     * caching by keeping tool definitions in a stable order.\n     */\n    toolOrder?: ToolOrder<NoInfer<TOOLS>>;\n\n    /**\n     * Optional specification for parsing structured outputs from the LLM response.\n     */\n    output?: OUTPUT;\n\n    /**\n     * Optional tool approval configuration.\n     *\n     * This configuration takes precedence over tool-defined approval settings.\n     */\n    toolApproval?: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT>;\n\n    /**\n     * Configures which caller tools may invoke each tool.\n     */\n    experimental_toolCallers?: Experimental_ToolCallers<NoInfer<TOOLS>>;\n\n    /**\n     * Secret for HMAC-signing tool approval requests. When set, the server\n     * signs each approval request at issuance and verifies the signature when\n     * the approval is replayed, preventing client-forged approvals.\n     */\n    experimental_toolApprovalSecret?: string | Uint8Array;\n\n    /**\n     * Custom download function to use for URLs.\n     *\n     * By default, files are downloaded if the model does not support the URL for the given media type.\n     */\n    experimental_download?: DownloadFunction | undefined;\n\n    /**\n     * Optional function that you can use to provide different settings for a step.\n     */\n    prepareStep?: PrepareStepFunction<NoInfer<TOOLS>, RUNTIME_CONTEXT>;\n\n    /**\n     * A function that attempts to repair a tool call that failed to parse.\n     */\n    repairToolCall?: ToolCallRepairFunction<NoInfer<TOOLS>>;\n\n    /**\n     * A function that attempts to repair a tool call that failed to parse.\n     *\n     * @deprecated Use `repairToolCall` instead.\n     */\n    experimental_repairToolCall?: ToolCallRepairFunction<NoInfer<TOOLS>>;\n\n    /**\n     * Optional mapping of tool names to functions that refine parsed tool inputs.\n     *\n     * The refined input must have the same type shape as the tool input. Refined\n     * inputs are used for tool execution, outputs, callbacks, and telemetry.\n     */\n    experimental_refineToolInput?: ToolInputRefinement<NoInfer<TOOLS>>;\n\n    /**\n     * Callback that is called when the generateText operation begins,\n     * before any LLM calls are made.\n     */\n    onStart?: GenerateTextOnStartCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>,\n      NoInfer<OUTPUT>\n    >;\n\n    /**\n     * Callback that is called when the generateText operation begins,\n     * before any LLM calls are made.\n     *\n     * @deprecated Use `onStart` instead.\n     */\n    experimental_onStart?: GenerateTextOnStartCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>,\n      NoInfer<OUTPUT>\n    >;\n\n    /**\n     * Callback that is called when a step (LLM call) begins,\n     * before the provider is called.\n     */\n    onStepStart?: GenerateTextOnStepStartCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>,\n      NoInfer<OUTPUT>\n    >;\n\n    /**\n     * Callback that is called when a step (LLM call) begins,\n     * before the provider is called.\n     *\n     * @deprecated Use `onStepStart` instead.\n     */\n    experimental_onStepStart?: GenerateTextOnStepStartCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>,\n      NoInfer<OUTPUT>\n    >;\n\n    /**\n     * Callback that is called immediately before the provider model call begins.\n     */\n    onLanguageModelCallStart?: OnLanguageModelCallStartCallback;\n\n    /**\n     * Callback that is called immediately before the provider model call begins.\n     *\n     * @deprecated Use `onLanguageModelCallStart` instead.\n     */\n    experimental_onLanguageModelCallStart?: OnLanguageModelCallStartCallback;\n\n    /**\n     * Callback that is called after the model response has been normalized and parsed,\n     * but before any client-side tool execution begins.\n     */\n    onLanguageModelCallEnd?: OnLanguageModelCallEndCallback<NoInfer<TOOLS>>;\n\n    /**\n     * Callback that is called after the model response has been normalized and parsed,\n     * but before any client-side tool execution begins.\n     *\n     * @deprecated Use `onLanguageModelCallEnd` instead.\n     */\n    experimental_onLanguageModelCallEnd?: OnLanguageModelCallEndCallback<\n      NoInfer<TOOLS>\n    >;\n\n    /**\n     * Callback that is called right before a tool's execute function runs.\n     */\n    onToolExecutionStart?: OnToolExecutionStartCallback<NoInfer<TOOLS>>;\n\n    /**\n     * Callback that is called right before a tool's execute function runs.\n     *\n     * @deprecated Use `onToolExecutionStart` instead.\n     */\n    experimental_onToolCallStart?: OnToolExecutionStartCallback<NoInfer<TOOLS>>;\n\n    /**\n     * Callback that is called right after a tool's execute function completes (or errors).\n     */\n    onToolExecutionEnd?: OnToolExecutionEndCallback<NoInfer<TOOLS>>;\n\n    /**\n     * Callback that is called right after a tool's execute function completes (or errors).\n     *\n     * @deprecated Use `onToolExecutionEnd` instead.\n     */\n    experimental_onToolCallFinish?: OnToolExecutionEndCallback<NoInfer<TOOLS>>;\n\n    /**\n     * Callback that is called when each step (LLM call) ends, including intermediate steps.\n     */\n    onStepEnd?: GenerateTextOnStepEndCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>\n    >;\n\n    /**\n     * Callback that is called when each step (LLM call) ends, including intermediate steps.\n     *\n     * @deprecated Use `onStepEnd` instead.\n     */\n    onStepFinish?: GenerateTextOnStepFinishCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>\n    >;\n\n    /**\n     * Callback that is called when all steps are finished and the response is complete.\n     */\n    onEnd?: GenerateTextOnEndCallback<NoInfer<TOOLS>, NoInfer<RUNTIME_CONTEXT>>;\n\n    /**\n     * Callback that is called when all steps are finished and the response is complete.\n     *\n     * @deprecated Use `onEnd` instead.\n     */\n    onFinish?: GenerateTextOnEndCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>\n    >;\n\n    /**\n     * Settings for controlling what data is included in step results.\n     * Disabling inclusion can help reduce memory usage when processing\n     * large payloads like images.\n     *\n     * By default, request bodies, request messages, and response bodies are\n     * excluded.\n     */\n    include?: GenerateTextInclude;\n\n    /**\n     * Settings for controlling what data is included in step results.\n     *\n     * @deprecated Use `include` instead.\n     */\n    experimental_include?: GenerateTextInclude;\n\n    /**\n     * Internal. For test use only. May change without notice.\n     */\n    _internal?: {\n      generateId?: IdGenerator;\n      generateCallId?: IdGenerator;\n      now?: () => number;\n    };\n  }): Promise<GenerateTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>> {\n  // assign default values to include:\n  include = {\n    requestBody: include?.requestBody ?? false,\n    requestMessages: include?.requestMessages ?? false,\n    responseBody: include?.responseBody ?? false,\n  };\n\n  const model = resolveLanguageModel(modelArg);\n  const resolvedToolCallers = resolveToolCallerConfiguration({\n    tools,\n    toolCallers: experimental_toolCallers,\n  });\n  const prepareToolSearch = createToolSearchState({\n    tools,\n    toolCallers: resolvedToolCallers,\n  });\n  const stopConditions = asArray(stopWhen);\n  const resolvedOnStart = onStart ?? experimental_onStart;\n  const resolvedOnStepStart = onStepStart ?? experimental_onStepStart;\n  const resolvedOnLanguageModelCallStart =\n    onLanguageModelCallStart ?? experimental_onLanguageModelCallStart;\n  const resolvedOnLanguageModelCallEnd =\n    onLanguageModelCallEnd ?? experimental_onLanguageModelCallEnd;\n  const resolvedOnToolExecutionStart =\n    onToolExecutionStart ?? experimental_onToolCallStart;\n  const resolvedOnToolExecutionEnd =\n    onToolExecutionEnd ?? experimental_onToolCallFinish;\n  const resolvedOnStepEnd = onStepEnd ?? onStepFinish;\n\n  const unsupportedTimeoutWarnings: Warning[] = [];\n\n  if (getFirstChunkTimeoutMs(timeout) != null) {\n    unsupportedTimeoutWarnings.push({\n      type: 'unsupported',\n      feature: 'timeout.firstChunkMs',\n      details:\n        'The firstChunkMs timeout is only supported by streaming functions.',\n    });\n  }\n\n  if (getChunkTimeoutMs(timeout) != null) {\n    unsupportedTimeoutWarnings.push({\n      type: 'unsupported',\n      feature: 'timeout.chunkMs',\n      details: 'The chunkMs timeout is only supported by streaming functions.',\n    });\n  }\n\n  if (unsupportedTimeoutWarnings.length > 0) {\n    logWarnings({\n      warnings: unsupportedTimeoutWarnings,\n      provider: model.provider,\n      model: model.modelId,\n    });\n  }\n\n  const totalTimeoutMs = getTotalTimeoutMs(timeout);\n  const stepTimeoutMs = getStepTimeoutMs(timeout);\n  const stepAbortController =\n    stepTimeoutMs != null ? new AbortController() : undefined;\n  const mergedAbortSignal = mergeAbortSignals(\n    abortSignal,\n    totalTimeoutMs,\n    stepAbortController?.signal,\n  );\n\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal: mergedAbortSignal,\n  });\n\n  const callSettings = prepareLanguageModelCallOptions(settings);\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const initialPrompt = await standardizePrompt({\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n  } as Prompt);\n\n  const callId = generateCallId();\n\n  const telemetryDispatcher = createRestrictedTelemetryDispatcher<\n    TOOLS,\n    RUNTIME_CONTEXT,\n    OUTPUT\n  >({\n    telemetry,\n    includeRuntimeContext: telemetry?.includeRuntimeContext,\n    includeToolsContext: telemetry?.includeToolsContext,\n  });\n\n  const runInTracingChannelSpan =\n    telemetryDispatcher.runInTracingChannelSpan ??\n    (async <T>({ execute }: { execute: () => PromiseLike<T> }) =>\n      await execute());\n\n  const generateTextStartEvent = {\n    callId,\n    operationId: 'ai.generateText',\n    provider: model.provider,\n    modelId: model.modelId,\n    instructions: initialPrompt.instructions,\n    messages: initialPrompt.messages,\n    tools,\n    toolChoice,\n    activeTools,\n    toolOrder,\n    maxOutputTokens: callSettings.maxOutputTokens,\n    temperature: callSettings.temperature,\n    topP: callSettings.topP,\n    topK: callSettings.topK,\n    presencePenalty: callSettings.presencePenalty,\n    frequencyPenalty: callSettings.frequencyPenalty,\n    stopSequences: callSettings.stopSequences,\n    seed: callSettings.seed,\n    reasoning: callSettings.reasoning,\n    maxRetries,\n    timeout,\n    headers: headersWithUserAgent,\n    providerOptions,\n    output,\n    runtimeContext,\n    toolsContext,\n  };\n\n  const executeGenerateText = async () => {\n    await notify({\n      event: generateTextStartEvent,\n      callbacks: [resolvedOnStart, telemetryDispatcher.onStart],\n    });\n\n    try {\n      const initialMessages = initialPrompt.messages;\n      const initialResponseMessages: Array<ResponseMessage> = [];\n\n      const {\n        approvedToolApprovals,\n        deniedToolApprovals: collectedDeniedToolApprovals,\n      } = collectToolApprovals<TOOLS>({ messages: initialMessages });\n\n      const {\n        approvedToolApprovals: localApprovedToolApprovals,\n        deniedToolApprovals: revalidationDeniedToolApprovals,\n        invalidToolApprovals,\n      } = await validateApprovedToolApprovals<TOOLS, RUNTIME_CONTEXT>({\n        approvedToolApprovals: approvedToolApprovals.filter(\n          toolApproval => !toolApproval.toolCall.providerExecuted,\n        ),\n        tools,\n        toolApproval,\n        messages: initialMessages,\n        toolsContext,\n        runtimeContext,\n        toolApprovalSecret: experimental_toolApprovalSecret,\n      });\n\n      const deniedToolApprovals = [\n        ...collectedDeniedToolApprovals,\n        ...revalidationDeniedToolApprovals,\n      ];\n      const deniedToolApprovalsWithoutResults = deniedToolApprovals.filter(\n        toolApproval => toolApproval.existingToolResult == null,\n      );\n\n      if (\n        deniedToolApprovalsWithoutResults.length > 0 ||\n        localApprovedToolApprovals.length > 0 ||\n        invalidToolApprovals.length > 0\n      ) {\n        const toolResults = await executeTools({\n          toolCalls: localApprovedToolApprovals.map(\n            toolApproval => toolApproval.toolCall,\n          ),\n          tools: tools as TOOLS,\n          callId,\n          messages: initialMessages,\n          abortSignal: mergedAbortSignal,\n          timeout,\n          experimental_sandbox: sandbox,\n          toolsContext,\n          onToolExecutionStart: event =>\n            notify({\n              event,\n              callbacks: [\n                resolvedOnToolExecutionStart,\n                telemetryDispatcher.onToolExecutionStart,\n              ],\n            }),\n          onToolExecutionEnd: event =>\n            notify({\n              event,\n              callbacks: [\n                resolvedOnToolExecutionEnd,\n                telemetryDispatcher.onToolExecutionEnd,\n              ],\n            }),\n          executeToolInTelemetryContext: telemetryDispatcher.executeTool,\n          runInTracingChannelSpan,\n        });\n\n        const toolContent: Array<any> = [];\n\n        // add regular tool results for approved tool calls:\n        for (const result of toolResults) {\n          const output = result.output;\n          const modelOutput = await createToolModelOutput({\n            toolCallId: output.toolCallId,\n            input: output.input,\n            tool: getOwn(tools, output.toolName),\n            output:\n              output.type === 'tool-result' ? output.output : output.error,\n            errorMode: output.type === 'tool-error' ? 'text' : 'none',\n          });\n\n          toolContent.push({\n            type: 'tool-result' as const,\n            toolCallId: output.toolCallId,\n            toolName: output.toolName,\n            output: modelOutput,\n          });\n        }\n\n        // Report invalid approved tool calls to the model without executing\n        // them. Repairing the input after approval would change the operation\n        // that the user authorized.\n        for (const toolApproval of invalidToolApprovals) {\n          toolContent.push({\n            type: 'tool-result' as const,\n            toolCallId: toolApproval.toolCall.toolCallId,\n            toolName: toolApproval.toolCall.toolName,\n            output: await createToolModelOutput({\n              toolCallId: toolApproval.toolCall.toolCallId,\n              input: toolApproval.toolCall.input,\n              tool: getOwn(tools, toolApproval.toolCall.toolName),\n              output: toolApproval.error,\n              errorMode: 'text',\n            }),\n          });\n        }\n\n        // add execution denied tool results for all denied tool approvals:\n        for (const toolApproval of deniedToolApprovalsWithoutResults) {\n          toolContent.push({\n            type: 'tool-result' as const,\n            toolCallId: toolApproval.toolCall.toolCallId,\n            toolName: toolApproval.toolCall.toolName,\n            output: {\n              type: 'execution-denied' as const,\n              reason: toolApproval.approvalResponse.reason,\n              // For provider-executed tools, include approvalId so provider can correlate\n              ...(toolApproval.toolCall.providerExecuted && {\n                providerOptions: {\n                  openai: {\n                    approvalId: toolApproval.approvalResponse.approvalId,\n                  },\n                },\n              }),\n            },\n          });\n        }\n\n        initialResponseMessages.push({\n          role: 'tool',\n          content: toolContent,\n        });\n      }\n\n      const callSettings = prepareLanguageModelCallOptions(settings);\n\n      let currentModelResponse: LanguageModelV4GenerateResult & {\n        response: { id: string; timestamp: Date; modelId: string };\n      };\n      let clientToolCalls: Array<TypedToolCall<TOOLS>> = [];\n      let clientToolOutputs: Array<ToolOutput<TOOLS>> = [];\n      let toolApprovalResponses: Array<ToolApprovalResponseOutput<TOOLS>> = [];\n      let deniedToolApprovalResponses: Array<\n        ToolApprovalResponseOutput<TOOLS>\n      > = [];\n      const steps: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['steps'] =\n        [];\n      let instructionsForNextStep = initialPrompt.instructions;\n      let messagesForNextStep = [\n        ...initialMessages,\n        ...initialResponseMessages,\n      ];\n\n      // Track provider-executed tool calls that support deferred results\n      // (e.g., code_execution in programmatic tool calling scenarios).\n      // These tools may not return their results in the same turn as their call.\n      const pendingDeferredToolCalls = new Map<string, { toolName: string }>();\n\n      do {\n        if (steps.length > 0) {\n          mergedAbortSignal?.throwIfAborted();\n        }\n\n        // Set up step timeout if configured\n        const stepTimeoutId = setAbortTimeout({\n          abortController: stepAbortController,\n          label: 'Step',\n          timeoutMs: stepTimeoutMs,\n        });\n        const stepNumber = steps.length;\n\n        try {\n          await runInTracingChannelSpan({\n            type: 'step',\n            event: { callId, stepNumber },\n            execute: async () => {\n              const accumulatedResponseMessages = [\n                ...initialResponseMessages,\n                ...steps.flatMap(step => step.response.messages),\n              ];\n              const stepInputMessages = messagesForNextStep;\n\n              const prepareStepResult = await prepareStep?.({\n                model,\n                steps,\n                stepNumber: steps.length,\n                instructions: instructionsForNextStep,\n                initialInstructions: initialPrompt.instructions,\n                messages: stepInputMessages,\n                initialMessages,\n                responseMessages: accumulatedResponseMessages,\n                runtimeContext,\n                toolsContext,\n                experimental_sandbox: sandbox,\n              });\n\n              const stepSandbox =\n                prepareStepResult?.experimental_sandbox ?? sandbox;\n\n              const stepModel = resolveLanguageModel(\n                prepareStepResult?.model ?? model,\n              );\n\n              const stepInstructions =\n                prepareStepResult?.instructions ??\n                prepareStepResult?.system ??\n                instructionsForNextStep;\n\n              runtimeContext =\n                prepareStepResult?.runtimeContext ?? runtimeContext;\n              toolsContext = prepareStepResult?.toolsContext ?? toolsContext;\n\n              const stepActiveTools = filterActiveTools({\n                tools,\n                activeTools: prepareStepResult?.activeTools ?? activeTools,\n              });\n              const {\n                executionTools: stepExecutionTools,\n                modelTools: stepModelTools,\n                toolCallerMessages,\n              } = prepareToolsForToolCallers({\n                tools: prepareToolSearch(stepActiveTools, {\n                  toolsContext,\n                  experimental_sandbox: stepSandbox,\n                }),\n                toolCallers: resolvedToolCallers,\n              });\n              const stepToolOrder = prepareStepResult?.toolOrder ?? toolOrder;\n\n              const stepTools = await prepareTools({\n                tools: stepModelTools as ActiveToolSubset<\n                  TOOLS,\n                  ActiveTools<NoInfer<TOOLS>>\n                >,\n                toolOrder: stepToolOrder as ToolOrder<\n                  ActiveToolSubset<TOOLS, ActiveTools<NoInfer<TOOLS>>>\n                >,\n                // active tools context is a subset of the tools context, so we can cast to the unknown type\n                toolsContext: toolsContext as unknown as InferToolSetContext<\n                  ActiveToolSubset<TOOLS, ActiveTools<NoInfer<TOOLS>>>\n                >,\n                experimental_sandbox: stepSandbox,\n              });\n\n              const stepToolChoice = prepareToolChoice({\n                toolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n              });\n\n              const stepMessages = appendToolCallerMessages({\n                messages: prepareStepResult?.messages ?? stepInputMessages,\n                toolCallerMessages,\n              });\n\n              const promptMessages = await convertToLanguageModelPrompt({\n                prompt: {\n                  instructions: stepInstructions,\n                  messages: stepMessages,\n                },\n                supportedUrls: await stepModel.supportedUrls,\n                download,\n                provider: stepModel.provider.split('.')[0],\n              });\n\n              const stepProviderOptions = mergeObjects(\n                providerOptions,\n                prepareStepResult?.providerOptions,\n              );\n\n              const stepCallSettings = prepareStepCallSettings({\n                callSettings,\n                stepSettings: prepareStepResult,\n              });\n\n              await notify({\n                event: {\n                  callId,\n                  provider: stepModel.provider,\n                  modelId: stepModel.modelId,\n                  stepNumber,\n                  instructions: stepInstructions,\n                  messages: stepMessages,\n                  tools,\n                  toolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n                  activeTools: prepareStepResult?.activeTools ?? activeTools,\n                  toolOrder: stepToolOrder,\n                  steps: [...steps],\n                  providerOptions: stepProviderOptions,\n                  output,\n                  runtimeContext,\n                  promptMessages,\n                  stepTools,\n                  stepToolChoice,\n                  toolsContext,\n                },\n                callbacks: [\n                  resolvedOnStepStart,\n                  telemetryDispatcher.onStepStart,\n                ],\n              });\n\n              const languageModelCallContext = {\n                provider: stepModel.provider,\n                modelId: stepModel.modelId,\n                instructions: stepInstructions,\n                messages: stepMessages,\n                tools: stepTools,\n                ...stepCallSettings,\n              };\n              const languageModelCallStartEvent = {\n                callId,\n                ...languageModelCallContext,\n              };\n\n              const stepStartTimestampMs = now();\n\n              await notify({\n                event: languageModelCallStartEvent,\n                callbacks: [\n                  resolvedOnLanguageModelCallStart,\n                  telemetryDispatcher.onLanguageModelCallStart as\n                    | undefined\n                    | OnLanguageModelCallStartCallback,\n                ],\n              });\n\n              const executeLanguageModelCallInTelemetryContext =\n                telemetryDispatcher.executeLanguageModelCall ??\n                (async <T>({ execute }: { execute: () => PromiseLike<T> }) =>\n                  await execute());\n\n              currentModelResponse = await retry(async () => {\n                const result = await executeLanguageModelCallInTelemetryContext(\n                  {\n                    ...languageModelCallStartEvent,\n                    execute: async () =>\n                      await stepModel.doGenerate({\n                        ...stepCallSettings,\n                        tools: stepTools,\n                        toolChoice: stepToolChoice,\n                        responseFormat: await output?.responseFormat,\n                        prompt: promptMessages,\n                        providerOptions: stepProviderOptions,\n                        abortSignal: mergedAbortSignal,\n                        headers: headersWithUserAgent,\n                      }),\n                  },\n                );\n\n                const responseData = {\n                  id: result.response?.id ?? generateId(),\n                  timestamp: result.response?.timestamp ?? new Date(),\n                  modelId: result.response?.modelId ?? stepModel.modelId,\n                  headers: result.response?.headers,\n                  body: result.response?.body,\n                };\n\n                return { ...result, response: responseData };\n              });\n              const responseTimeMs = now() - stepStartTimestampMs;\n              const stepUsage = asLanguageModelUsage(\n                currentModelResponse.usage,\n              );\n\n              // parse tool calls:\n              const stepToolCalls: TypedToolCall<TOOLS>[] = await Promise.all(\n                currentModelResponse.content\n                  .filter(\n                    (part): part is LanguageModelV4ToolCall =>\n                      part.type === 'tool-call',\n                  )\n                  .map(toolCall =>\n                    parseToolCall({\n                      toolCall,\n                      tools: stepExecutionTools as TOOLS,\n                      repairToolCall,\n                      refineToolInput,\n                      instructions: stepInstructions,\n                      messages: stepMessages,\n                    }),\n                  ),\n              );\n\n              const toolApprovalRequests: Record<\n                string,\n                ToolApprovalRequestOutput<TOOLS>\n              > = {};\n              const stepToolApprovalResponses: Record<\n                string,\n                ToolApprovalResponseOutput<TOOLS>\n              > = {};\n              const blockedToolCallIds = new Set<string>();\n\n              const modelCallContent = convertLanguageModelContent({\n                content: currentModelResponse.content,\n                toolCalls: stepToolCalls,\n                toolOutputs: [],\n                toolApprovalRequests: [],\n                toolApprovalResponses: [],\n                tools,\n              });\n\n              await notify({\n                event: {\n                  callId,\n                  provider: stepModel.provider,\n                  modelId: currentModelResponse.response.modelId,\n                  finishReason: currentModelResponse.finishReason.unified,\n                  usage: stepUsage,\n                  content: modelCallContent,\n                  responseId: currentModelResponse.response.id,\n                  ...(currentModelResponse.providerMetadata != null\n                    ? {\n                        providerMetadata: currentModelResponse.providerMetadata,\n                      }\n                    : {}),\n                  performance: {\n                    responseTimeMs,\n                    effectiveOutputTokensPerSecond: calculateTokensPerSecond({\n                      tokens: stepUsage.outputTokens,\n                      durationMs: responseTimeMs,\n                    }),\n                    outputTokensPerSecond: undefined,\n                    inputTokensPerSecond: undefined,\n                    effectiveTotalTokensPerSecond: calculateTokensPerSecond({\n                      tokens: sumTokenCounts(\n                        stepUsage.inputTokens,\n                        stepUsage.outputTokens,\n                      ),\n                      durationMs: responseTimeMs,\n                    }),\n                    timeToFirstOutputMs: undefined,\n                  },\n                },\n                callbacks: [\n                  resolvedOnLanguageModelCallEnd,\n                  telemetryDispatcher.onLanguageModelCallEnd as\n                    | undefined\n                    | OnLanguageModelCallEndCallback<TOOLS>,\n                ],\n              });\n\n              const enforcedToolChoice =\n                stepToolChoice.type === 'required' ||\n                stepToolChoice.type === 'tool'\n                  ? stepToolChoice\n                  : undefined;\n\n              if (\n                enforcedToolChoice != null &&\n                !stepToolCalls.some(\n                  toolCall =>\n                    enforcedToolChoice.type === 'required' ||\n                    toolCall.toolName === enforcedToolChoice.toolName,\n                )\n              ) {\n                throw new ToolChoiceViolationError({\n                  toolChoice: enforcedToolChoice,\n                  finishReason: currentModelResponse.finishReason.unified,\n                  provider: stepModel.provider,\n                  modelId: stepModel.modelId,\n                  content: currentModelResponse.content,\n                });\n              }\n\n              // notify the tools that the tool calls are available:\n              for (const toolCall of stepToolCalls) {\n                if (toolCall.invalid) {\n                  continue; // ignore invalid tool calls\n                }\n\n                const tool = getOwn(stepExecutionTools, toolCall.toolName);\n\n                if (tool == null) {\n                  // ignore tool calls for tools that are not available,\n                  // e.g. provider-executed dynamic tools\n                  continue;\n                }\n\n                if (tool.onInputStart != null) {\n                  await tool.onInputStart({\n                    toolCallId: toolCall.toolCallId,\n                    messages: stepMessages,\n                    abortSignal: mergedAbortSignal,\n                    context: runtimeContext,\n                  });\n                }\n\n                if (tool?.onInputAvailable != null) {\n                  await tool.onInputAvailable({\n                    input: toolCall.input,\n                    toolCallId: toolCall.toolCallId,\n                    messages: stepMessages,\n                    abortSignal: mergedAbortSignal,\n                    context: runtimeContext,\n                  });\n                }\n\n                const toolApprovalStatus = await resolveToolApproval({\n                  tools: stepExecutionTools as TOOLS,\n                  toolApproval,\n                  toolCall,\n                  messages: stepMessages,\n                  toolsContext,\n                  runtimeContext,\n                });\n\n                // Tools that don't require approval ('not-applicable') must not\n                // consume an approval id, so that id generation stays stable for\n                // callers that rely on deterministic id sequences.\n                if (toolApprovalStatus.type === 'not-applicable') {\n                  continue;\n                }\n\n                const approvalId = generateId();\n                const signature = await maybeSignApproval({\n                  secret: experimental_toolApprovalSecret,\n                  approvalId,\n                  toolCallId: toolCall.toolCallId,\n                  toolName: toolCall.toolName,\n                  input: toolCall.input,\n                });\n\n                switch (toolApprovalStatus.type) {\n                  case 'user-approval': {\n                    toolApprovalRequests[toolCall.toolCallId] = {\n                      type: 'tool-approval-request',\n                      approvalId,\n                      toolCall,\n                      ...(toolApprovalStatus.reason != null\n                        ? { reason: toolApprovalStatus.reason }\n                        : {}),\n                      ...(signature != null ? { signature } : {}),\n                    };\n                    blockedToolCallIds.add(toolCall.toolCallId);\n                    break;\n                  }\n\n                  case 'approved': {\n                    toolApprovalRequests[toolCall.toolCallId] = {\n                      type: 'tool-approval-request',\n                      approvalId,\n                      toolCall,\n                      isAutomatic: true,\n                      ...(signature != null ? { signature } : {}),\n                    };\n                    stepToolApprovalResponses[toolCall.toolCallId] = {\n                      type: 'tool-approval-response',\n                      approvalId,\n                      toolCall,\n                      approved: true,\n                      reason: toolApprovalStatus.reason,\n                      providerExecuted: toolCall.providerExecuted,\n                    };\n                    break;\n                  }\n\n                  case 'denied': {\n                    toolApprovalRequests[toolCall.toolCallId] = {\n                      type: 'tool-approval-request',\n                      approvalId,\n                      toolCall,\n                      isAutomatic: true,\n                      ...(signature != null ? { signature } : {}),\n                    };\n                    stepToolApprovalResponses[toolCall.toolCallId] = {\n                      type: 'tool-approval-response',\n                      approvalId,\n                      toolCall,\n                      approved: false,\n                      reason: toolApprovalStatus.reason,\n                      providerExecuted: toolCall.providerExecuted,\n                    };\n                    blockedToolCallIds.add(toolCall.toolCallId);\n                    break;\n                  }\n                }\n              }\n\n              // insert error tool outputs for invalid tool calls:\n              // TODO AI SDK 6: invalid inputs should not require output parts\n              const invalidToolCalls = stepToolCalls.filter(\n                toolCall =>\n                  toolCall.invalid &&\n                  toolCall.dynamic &&\n                  !toolCall.providerExecuted,\n              );\n\n              clientToolOutputs = [];\n\n              for (const toolCall of invalidToolCalls) {\n                clientToolOutputs.push({\n                  type: 'tool-error',\n                  toolCallId: toolCall.toolCallId,\n                  toolName: toolCall.toolName,\n                  input: toolCall.input,\n                  error: getErrorMessage(toolCall.error!),\n                  dynamic: true,\n                });\n              }\n\n              // execute client tool calls:\n              clientToolCalls = stepToolCalls.filter(\n                toolCall => !toolCall.providerExecuted,\n              );\n              toolApprovalResponses = Object.values(stepToolApprovalResponses);\n              deniedToolApprovalResponses = toolApprovalResponses.filter(\n                toolApprovalResponse => toolApprovalResponse.approved === false,\n              );\n              const toolExecutionMs: Record<string, number> = {};\n\n              if (\n                stepExecutionTools != null &&\n                isToolExecutionAllowedFinishReason(\n                  currentModelResponse.finishReason.unified,\n                )\n              ) {\n                const toolExecutionResults = await executeTools({\n                  toolCalls: clientToolCalls.filter(\n                    toolCall =>\n                      !toolCall.invalid &&\n                      !blockedToolCallIds.has(toolCall.toolCallId),\n                  ),\n                  tools: stepExecutionTools as TOOLS,\n                  callId,\n                  messages: stepMessages,\n                  abortSignal: mergedAbortSignal,\n                  timeout,\n                  experimental_sandbox: stepSandbox,\n                  toolsContext,\n                  onToolExecutionStart: event =>\n                    notify({\n                      event,\n                      callbacks: [\n                        resolvedOnToolExecutionStart,\n                        telemetryDispatcher.onToolExecutionStart,\n                      ],\n                    }),\n                  onToolExecutionEnd: event =>\n                    notify({\n                      event,\n                      callbacks: [\n                        resolvedOnToolExecutionEnd,\n                        telemetryDispatcher.onToolExecutionEnd,\n                      ],\n                    }),\n                  executeToolInTelemetryContext:\n                    telemetryDispatcher.executeTool,\n                  runInTracingChannelSpan,\n                });\n\n                for (const result of toolExecutionResults) {\n                  toolExecutionMs[result.output.toolCallId] =\n                    result.toolExecutionMs;\n                  clientToolOutputs.push(result.output);\n                }\n              }\n\n              const stepTimeMs = now() - stepStartTimestampMs;\n              const stepPerformance: StepResultPerformance = {\n                effectiveOutputTokensPerSecond: calculateTokensPerSecond({\n                  tokens: stepUsage.outputTokens,\n                  durationMs: responseTimeMs,\n                }),\n                outputTokensPerSecond: undefined,\n                inputTokensPerSecond: undefined,\n                effectiveTotalTokensPerSecond: calculateTokensPerSecond({\n                  tokens: sumTokenCounts(\n                    stepUsage.inputTokens,\n                    stepUsage.outputTokens,\n                  ),\n                  durationMs: responseTimeMs,\n                }),\n                stepTimeMs,\n                responseTimeMs,\n                toolExecutionMs,\n                timeToFirstOutputMs: undefined,\n              };\n\n              // Track provider-executed tool calls that support deferred results.\n              // In programmatic tool calling, a server tool (e.g., code_execution) may\n              // trigger a client tool, and the server tool's result is deferred until\n              // the client tool's result is sent back.\n              for (const toolCall of stepToolCalls) {\n                if (!toolCall.providerExecuted) continue;\n                const tool = getOwn(stepExecutionTools, toolCall.toolName);\n                if (tool?.type === 'provider' && tool.supportsDeferredResults) {\n                  // Check if this tool call already has a result in the current response\n                  const hasResultInResponse = currentModelResponse.content.some(\n                    part =>\n                      part.type === 'tool-result' &&\n                      part.toolCallId === toolCall.toolCallId,\n                  );\n                  if (!hasResultInResponse) {\n                    pendingDeferredToolCalls.set(toolCall.toolCallId, {\n                      toolName: toolCall.toolName,\n                    });\n                  }\n                }\n              }\n\n              // Mark deferred tool calls as resolved when we receive their results\n              for (const part of currentModelResponse.content) {\n                if (part.type === 'tool-result') {\n                  pendingDeferredToolCalls.delete(part.toolCallId);\n                }\n              }\n\n              // content:\n              const stepContent = convertLanguageModelContent({\n                content: currentModelResponse.content,\n                toolCalls: stepToolCalls,\n                toolOutputs: clientToolOutputs,\n                toolApprovalRequests: Object.values(toolApprovalRequests),\n                toolApprovalResponses,\n                tools,\n              });\n\n              const stepResponseMessages = await toResponseMessages({\n                content: stepContent,\n                tools,\n              });\n\n              // Add step information (after response messages are updated):\n              // Conditionally include request.body and response.body based on include settings.\n              // Large payloads (e.g., base64-encoded images) can cause memory issues.\n              const stepRequest: LanguageModelRequestMetadata = {\n                ...currentModelResponse.request,\n                body: include.requestBody\n                  ? currentModelResponse.request?.body\n                  : undefined,\n                messages: include.requestMessages\n                  ? cloneModelMessages(stepMessages)\n                  : undefined,\n              };\n\n              const stepResponse = {\n                ...currentModelResponse.response,\n                // deep clone msgs to avoid mutating step results in multi-step:\n                messages: cloneModelMessages(stepResponseMessages),\n                // Conditionally include response body:\n                body: include.responseBody\n                  ? currentModelResponse.response?.body\n                  : undefined,\n              };\n\n              const currentStepResult: StepResult<TOOLS, RUNTIME_CONTEXT> =\n                new DefaultStepResult({\n                  callId,\n                  stepNumber,\n                  provider: stepModel.provider,\n                  modelId: stepModel.modelId,\n                  runtimeContext,\n                  content: stepContent,\n                  finishReason: currentModelResponse.finishReason.unified,\n                  rawFinishReason: currentModelResponse.finishReason.raw,\n                  usage: stepUsage,\n                  performance: stepPerformance,\n                  warnings: currentModelResponse.warnings,\n                  providerMetadata: currentModelResponse.providerMetadata,\n                  request: stepRequest,\n                  response: stepResponse,\n                  toolsContext,\n                });\n\n              logWarnings({\n                warnings: currentModelResponse.warnings ?? [],\n                provider: stepModel.provider,\n                model: stepModel.modelId,\n              });\n\n              steps.push(currentStepResult);\n              instructionsForNextStep = stepInstructions;\n              messagesForNextStep = [...stepMessages, ...stepResponseMessages];\n\n              await notify({\n                event: currentStepResult,\n                callbacks: [resolvedOnStepEnd, telemetryDispatcher.onStepEnd],\n              });\n\n              return currentStepResult;\n            },\n          });\n        } finally {\n          if (stepTimeoutId != null) {\n            clearTimeout(stepTimeoutId);\n          }\n        }\n      } while (\n        // Continue only after all client tool calls have been executed or denied,\n        // and if there are client results or pending deferred provider results.\n        clientToolOutputs.length + deniedToolApprovalResponses.length ===\n          clientToolCalls.length &&\n        (clientToolCalls.length > 0 || pendingDeferredToolCalls.size > 0) &&\n        // continue until a stop condition is met:\n        !(await isStopConditionMet({ stopConditions, steps }))\n      );\n\n      const lastStep = steps[steps.length - 1];\n\n      const totalUsage = steps.reduce(\n        (totalUsage, step) => {\n          return addLanguageModelUsage(totalUsage, step.usage);\n        },\n        {\n          inputTokens: undefined,\n          inputTokenDetails: {\n            noCacheTokens: undefined,\n            cacheReadTokens: undefined,\n            cacheWriteTokens: undefined,\n          },\n          outputTokens: undefined,\n          outputTokenDetails: {\n            textTokens: undefined,\n            reasoningTokens: undefined,\n          },\n          totalTokens: undefined,\n        } as LanguageModelUsage,\n      );\n\n      const files = steps.flatMap(step => step.files);\n      const sources = steps.flatMap(step => step.sources);\n      const toolCalls = steps.flatMap(step => step.toolCalls);\n      const staticToolCalls = steps.flatMap(step => step.staticToolCalls);\n      const dynamicToolCalls = steps.flatMap(step => step.dynamicToolCalls);\n      const toolResults = steps.flatMap(step => step.toolResults);\n      const staticToolResults = steps.flatMap(step => step.staticToolResults);\n      const dynamicToolResults = steps.flatMap(step => step.dynamicToolResults);\n      const warnings = steps.flatMap(step => step.warnings ?? []);\n\n      const onEndEvent = {\n        callId,\n        stepNumber: lastStep.stepNumber,\n        model: lastStep.model,\n        runtimeContext: lastStep.runtimeContext,\n        finishReason: lastStep.finishReason,\n        rawFinishReason: lastStep.rawFinishReason,\n        usage: totalUsage,\n        totalUsage,\n        content: steps.flatMap(step => step.content),\n        text: lastStep.text,\n        reasoning: lastStep.reasoning,\n        reasoningText: lastStep.reasoningText,\n        files,\n        sources,\n        toolCalls,\n        staticToolCalls,\n        dynamicToolCalls,\n        toolResults,\n        staticToolResults,\n        dynamicToolResults,\n        responseMessages: [\n          ...initialResponseMessages,\n          ...steps.flatMap(step => step.response.messages),\n        ],\n        warnings,\n        request: lastStep.request,\n        response: lastStep.response,\n        providerMetadata: lastStep.providerMetadata,\n        steps,\n        finalStep: lastStep,\n        toolsContext,\n      };\n\n      await notify({\n        event: onEndEvent,\n        callbacks: [onEnd, telemetryDispatcher.onEnd],\n      });\n\n      // parse output for stop responses and non-empty responses that are not\n      // tool calls:\n      let resolvedOutput;\n      if (\n        lastStep.finishReason === 'stop' ||\n        (lastStep.finishReason !== 'tool-calls' && lastStep.text.length > 0)\n      ) {\n        const outputSpecification = output ?? text();\n        resolvedOutput = await outputSpecification.parseCompleteOutput(\n          { text: lastStep.text },\n          {\n            response: lastStep.response,\n            usage: lastStep.usage,\n            finishReason: lastStep.finishReason,\n          },\n        );\n      }\n\n      return new DefaultGenerateTextResult({\n        initialResponseMessages,\n        steps,\n        totalUsage,\n        output: resolvedOutput,\n      });\n    } catch (error) {\n      await telemetryDispatcher.onError?.({ callId, error });\n      throw wrapGatewayError(error);\n    }\n  };\n\n  return await runInTracingChannelSpan({\n    type: 'generateText',\n    event: generateTextStartEvent,\n    execute: executeGenerateText,\n  });\n}\n\nasync function executeTools<TOOLS extends ToolSet>({\n  toolCalls,\n  tools,\n  callId,\n  messages,\n  abortSignal,\n  timeout,\n  experimental_sandbox: sandbox,\n  toolsContext,\n  onToolExecutionStart,\n  onToolExecutionEnd,\n  executeToolInTelemetryContext,\n  runInTracingChannelSpan,\n}: {\n  toolCalls: Array<TypedToolCall<TOOLS>>;\n  tools: TOOLS;\n  callId: string;\n  messages: ModelMessage[];\n  abortSignal: AbortSignal | undefined;\n  timeout?: TimeoutConfiguration<TOOLS>;\n  experimental_sandbox?: SandboxSession;\n  toolsContext: InferToolSetContext<TOOLS>;\n  onToolExecutionStart?: OnToolExecutionStartCallback<TOOLS>;\n  onToolExecutionEnd?: OnToolExecutionEndCallback<TOOLS>;\n  executeToolInTelemetryContext?: Telemetry['executeTool'];\n  runInTracingChannelSpan?: NonNullable<\n    TelemetryDispatcher['runInTracingChannelSpan']\n  >;\n}): Promise<\n  Array<{\n    output: ToolOutput<TOOLS>;\n    toolExecutionMs: number;\n  }>\n> {\n  const toolResults = await Promise.all(\n    toolCalls.map(\n      async toolCall =>\n        await executeToolCall({\n          toolCall,\n          tools,\n          callId,\n          messages,\n          abortSignal,\n          timeout,\n          experimental_sandbox: sandbox,\n          toolsContext,\n          onToolExecutionStart,\n          onToolExecutionEnd,\n          executeToolInTelemetryContext,\n          runInTracingChannelSpan,\n        }),\n    ),\n  );\n\n  return toolResults.filter(\n    (result): result is NonNullable<typeof result> => result != null,\n  );\n}\n\nclass DefaultGenerateTextResult<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context,\n  OUTPUT extends Output,\n> implements GenerateTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT> {\n  readonly steps: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['steps'];\n  readonly totalUsage: LanguageModelUsage;\n  private readonly _output: InferCompleteOutput<OUTPUT> | undefined;\n\n  constructor(options: {\n    initialResponseMessages: Array<ResponseMessage>;\n    steps: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['steps'];\n    output: InferCompleteOutput<OUTPUT> | undefined;\n    totalUsage: LanguageModelUsage;\n  }) {\n    this.initialResponseMessages = options.initialResponseMessages;\n    this.steps = options.steps;\n    this._output = options.output;\n    this.totalUsage = options.totalUsage;\n  }\n\n  private readonly initialResponseMessages: Array<ResponseMessage>;\n\n  get finalStep() {\n    return this.steps.at(-1)!;\n  }\n\n  get content() {\n    return this.steps.flatMap(step => step.content);\n  }\n\n  get text() {\n    return this.finalStep.text;\n  }\n\n  get files() {\n    return this.steps.flatMap(step => step.files);\n  }\n\n  get reasoningText() {\n    return this.finalStep.reasoningText;\n  }\n\n  get reasoning() {\n    return convertToReasoningOutputs(this.finalStep.reasoning);\n  }\n\n  get toolCalls() {\n    return this.steps.flatMap(step => step.toolCalls);\n  }\n\n  get staticToolCalls() {\n    return this.steps.flatMap(step => step.staticToolCalls);\n  }\n\n  get dynamicToolCalls() {\n    return this.steps.flatMap(step => step.dynamicToolCalls);\n  }\n\n  get toolResults() {\n    return this.steps.flatMap(step => step.toolResults);\n  }\n\n  get staticToolResults() {\n    return this.steps.flatMap(step => step.staticToolResults);\n  }\n\n  get dynamicToolResults() {\n    return this.steps.flatMap(step => step.dynamicToolResults);\n  }\n\n  get sources() {\n    return this.steps.flatMap(step => step.sources);\n  }\n\n  get finishReason() {\n    return this.finalStep.finishReason;\n  }\n\n  get rawFinishReason() {\n    return this.finalStep.rawFinishReason;\n  }\n\n  get warnings() {\n    return this.steps.flatMap(step => step.warnings ?? []);\n  }\n\n  get providerMetadata() {\n    return this.finalStep.providerMetadata;\n  }\n\n  get response() {\n    return this.finalStep.response;\n  }\n\n  get responseMessages() {\n    return [\n      ...this.initialResponseMessages,\n      ...this.steps.flatMap(step => step.response.messages),\n    ];\n  }\n\n  get request() {\n    return this.finalStep.request;\n  }\n\n  get usage() {\n    return this.totalUsage;\n  }\n\n  get output() {\n    if (this._output == null) {\n      throw new NoOutputGeneratedError();\n    }\n\n    return this._output;\n  }\n}\n","export {\n  AISDKError,\n  APICallError,\n  EmptyResponseBodyError,\n  Experimental_EvaluationUnsupportedQuestionTypeError,\n  InvalidPromptError,\n  InvalidResponseDataError,\n  JSONParseError,\n  LoadAPIKeyError,\n  LoadSettingError,\n  NoContentGeneratedError,\n  NoSuchModelError,\n  NoSuchProviderReferenceError,\n  TooManyEmbeddingValuesForCallError,\n  TypeValidationError,\n  UnsupportedFunctionalityError,\n} from '@ai-sdk/provider';\n\nexport { InvalidArgumentError } from './invalid-argument-error';\nexport { InvalidStreamPartError } from './invalid-stream-part-error';\nexport { InvalidToolApprovalError } from './invalid-tool-approval-error';\nexport { InvalidToolApprovalSignatureError } from './invalid-tool-approval-signature-error';\nexport { InvalidToolInputError } from './invalid-tool-input-error';\nexport { ToolCallNotFoundForApprovalError } from './tool-call-not-found-for-approval-error';\nexport { MissingToolResultsError } from './missing-tool-result-error';\nexport { NoImageGeneratedError } from './no-image-generated-error';\nexport { NoObjectGeneratedError } from './no-object-generated-error';\nexport { NoOutputGeneratedError } from './no-output-generated-error';\nexport { NoSpeechGeneratedError } from './no-speech-generated-error';\nexport { NoTranscriptGeneratedError } from './no-transcript-generated-error';\nexport { NoTranslationGeneratedError } from './no-translation-generated-error';\nexport { NoVideoGeneratedError } from './no-video-generated-error';\nexport { NoSuchToolError } from './no-such-tool-error';\nexport { StreamProviderError } from './stream-provider-error';\nexport { ToolCallRepairError } from './tool-call-repair-error';\nexport { ToolChoiceViolationError } from './tool-choice-violation-error';\nexport { UnsupportedModelVersionError } from './unsupported-model-version-error';\nexport { UIMessageStreamError } from './ui-message-stream-error';\nexport { InvalidDataContentError } from '../prompt/invalid-data-content-error';\nexport { InvalidMessageRoleError } from '../prompt/invalid-message-role-error';\nexport { MessageConversionError } from '../prompt/message-conversion-error';\nexport { DownloadError } from '@ai-sdk/provider-utils';\nexport { RetryError } from '../util/retry-error';\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidArgumentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidArgumentError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly parameter: string;\n  readonly value: unknown;\n\n  constructor({\n    parameter,\n    value,\n    message,\n  }: {\n    parameter: string;\n    value: unknown;\n    message: string;\n  }) {\n    super({\n      name,\n      message: `Invalid argument for parameter ${parameter}: ${message}`,\n    });\n\n    this.parameter = parameter;\n    this.value = value;\n  }\n\n  static isInstance(error: unknown): error is InvalidArgumentError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport type { LanguageModelStreamPart } from '../generate-text/stream-language-model-call';\n\nconst name = 'AI_InvalidStreamPartError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidStreamPartError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly chunk: LanguageModelStreamPart<any>;\n\n  constructor({\n    chunk,\n    message,\n  }: {\n    chunk: LanguageModelStreamPart<any>;\n    message: string;\n  }) {\n    super({ name, message });\n\n    this.chunk = chunk;\n  }\n\n  static isInstance(error: unknown): error is InvalidStreamPartError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolApprovalError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolApprovalError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly approvalId: string;\n\n  constructor({ approvalId }: { approvalId: string }) {\n    super({\n      name,\n      message:\n        `Tool approval response references unknown approvalId: \"${approvalId}\". ` +\n        `No matching tool-approval-request found in message history.`,\n    });\n\n    this.approvalId = approvalId;\n  }\n\n  static isInstance(error: unknown): error is InvalidToolApprovalError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolApprovalSignatureError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolApprovalSignatureError extends AISDKError {\n  private readonly [symbol] = true;\n\n  readonly approvalId: string;\n  readonly toolCallId: string;\n\n  constructor({\n    approvalId,\n    toolCallId,\n    reason,\n  }: {\n    approvalId: string;\n    toolCallId: string;\n    reason: string;\n  }) {\n    super({\n      name,\n      message: `Tool approval signature verification failed for approval \"${approvalId}\" (tool call \"${toolCallId}\"): ${reason}`,\n    });\n    this.approvalId = approvalId;\n    this.toolCallId = toolCallId;\n  }\n\n  static isInstance(\n    error: unknown,\n  ): error is InvalidToolApprovalSignatureError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError, getErrorMessage } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolInputError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolInputError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly toolName: string;\n  readonly toolInput: string;\n\n  constructor({\n    toolInput,\n    toolName,\n    cause,\n    message = `Invalid input for tool ${toolName}: ${getErrorMessage(cause)}`,\n  }: {\n    message?: string;\n    toolInput: string;\n    toolName: string;\n    cause: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.toolInput = toolInput;\n    this.toolName = toolName;\n  }\n\n  static isInstance(error: unknown): error is InvalidToolInputError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_ToolCallNotFoundForApprovalError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class ToolCallNotFoundForApprovalError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly toolCallId: string;\n  readonly approvalId: string;\n\n  constructor({\n    toolCallId,\n    approvalId,\n  }: {\n    toolCallId: string;\n    approvalId: string;\n  }) {\n    super({\n      name,\n      message: `Tool call \"${toolCallId}\" not found for approval request \"${approvalId}\".`,\n    });\n\n    this.toolCallId = toolCallId;\n    this.approvalId = approvalId;\n  }\n\n  static isInstance(error: unknown): error is ToolCallNotFoundForApprovalError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_MissingToolResultsError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class MissingToolResultsError extends AISDKError {\n  private readonly [symbol] = true;\n\n  readonly toolCallIds: string[];\n\n  constructor({ toolCallIds }: { toolCallIds: string[] }) {\n    super({\n      name,\n      message: `Tool result${\n        toolCallIds.length > 1 ? 's are' : ' is'\n      } missing for tool call${toolCallIds.length > 1 ? 's' : ''} ${toolCallIds.join(\n        ', ',\n      )}.`,\n    });\n\n    this.toolCallIds = toolCallIds;\n  }\n\n  static isInstance(error: unknown): error is MissingToolResultsError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport type { GenerateImageCall } from '../generate-image/generate-image-result';\nimport type { ImageModelResponseMetadata } from '../types/image-model-response-metadata';\n\nconst name = 'AI_NoImageGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Thrown when no image could be generated. This can have multiple causes:\n *\n * - The model failed to generate a response.\n * - The model generated a response that could not be parsed.\n */\nexport class NoImageGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  /**\n   * The results of the underlying image model calls.\n   */\n  readonly calls: Array<GenerateImageCall> | undefined;\n\n  /**\n   * The response metadata for each call.\n   */\n  readonly responses: Array<ImageModelResponseMetadata> | undefined;\n\n  constructor({\n    message = 'No image generated.',\n    cause,\n    calls,\n    responses,\n  }: {\n    message?: string;\n    cause?: Error;\n    calls?: Array<GenerateImageCall>;\n    responses?: Array<ImageModelResponseMetadata>;\n  }) {\n    super({ name, message, cause });\n\n    this.calls = calls;\n    this.responses = responses;\n  }\n\n  static isInstance(error: unknown): error is NoImageGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport type { FinishReason } from '../types/language-model';\nimport type { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';\nimport type { LanguageModelUsage } from '../types/usage';\n\nconst name = 'AI_NoObjectGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Thrown when no object could be generated. This can have several causes:\n *\n * - The model failed to generate a response.\n * - The model generated a response that could not be parsed.\n * - The model generated a response that could not be validated against the schema.\n *\n * The error contains the following properties:\n *\n * - `text`: The text that was generated by the model. This can be the raw text or the tool call text, depending on the model.\n */\nexport class NoObjectGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  /**\n   * The text that was generated by the model. This can be the raw text or the tool call text, depending on the model.\n   */\n  readonly text: string | undefined;\n\n  /**\n   * The response metadata.\n   */\n  readonly response:\n    | Omit<LanguageModelResponseMetadata, 'messages'>\n    | undefined;\n\n  /**\n   * The usage of the model.\n   */\n  readonly usage: LanguageModelUsage | undefined;\n\n  /**\n   * Reason why the model finished generating a response.\n   */\n  readonly finishReason: FinishReason | undefined;\n\n  constructor({\n    message = 'No object generated.',\n    cause,\n    text,\n    response,\n    usage,\n    finishReason,\n  }: {\n    message?: string;\n    cause?: Error;\n    text?: string;\n    response: Omit<LanguageModelResponseMetadata, 'messages'>;\n    usage: LanguageModelUsage;\n    finishReason: FinishReason;\n  }) {\n    super({ name, message, cause });\n\n    this.text = text;\n    this.response = response;\n    this.usage = usage;\n    this.finishReason = finishReason;\n  }\n\n  static isInstance(error: unknown): error is NoObjectGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoOutputGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Thrown when no LLM output was generated, e.g. because of errors.\n */\nexport class NoOutputGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  constructor({\n    message = 'No output generated.',\n    cause,\n  }: {\n    message?: string;\n    cause?: Error;\n  } = {}) {\n    super({ name, message, cause });\n  }\n\n  static isInstance(error: unknown): error is NoOutputGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport type { SpeechModelResponseMetadata } from '../types/speech-model-response-metadata';\n\nconst name = 'AI_NoSpeechGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Error that is thrown when no speech audio was generated.\n */\nexport class NoSpeechGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly responses: Array<SpeechModelResponseMetadata>;\n\n  constructor(options: { responses: Array<SpeechModelResponseMetadata> }) {\n    super({\n      name,\n      message: 'No speech audio generated.',\n    });\n\n    this.responses = options.responses;\n  }\n\n  static isInstance(error: unknown): error is NoSpeechGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport type { TranscriptionModelResponseMetadata } from '../types/transcription-model-response-metadata';\n\nconst name = 'AI_NoTranscriptGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Error that is thrown when no transcript was generated.\n */\nexport class NoTranscriptGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly responses: Array<TranscriptionModelResponseMetadata>;\n\n  constructor(options: {\n    responses: Array<TranscriptionModelResponseMetadata>;\n  }) {\n    super({\n      name,\n      message: 'No transcript generated.',\n    });\n\n    this.responses = options.responses;\n  }\n\n  static isInstance(error: unknown): error is NoTranscriptGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport type { SpeechTranslationModelResponseMetadata } from '../types/speech-translation-model-response-metadata';\n\nconst name = 'AI_NoTranslationGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Error that is thrown when no translation was generated.\n */\nexport class NoTranslationGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly response: SpeechTranslationModelResponseMetadata;\n\n  constructor(options: { response: SpeechTranslationModelResponseMetadata }) {\n    super({\n      name,\n      message: 'No translation generated.',\n    });\n\n    this.response = options.response;\n  }\n\n  static isInstance(error: unknown): error is NoTranslationGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport type { VideoModelResponseMetadata } from '../types/video-model-response-metadata';\n\nconst name = 'AI_NoVideoGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoVideoGeneratedError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly responses: Array<VideoModelResponseMetadata>;\n\n  constructor({\n    message = 'No video generated.',\n    cause,\n    responses,\n  }: {\n    message?: string;\n    cause?: unknown;\n    responses: Array<VideoModelResponseMetadata>;\n  }) {\n    super({ name, message, cause });\n\n    this.responses = responses;\n  }\n\n  static isInstance(error: unknown): error is NoVideoGeneratedError {\n    return AISDKError.hasMarker(error, marker);\n  }\n\n  /**\n   * @deprecated use `isInstance` instead\n   */\n  static isNoVideoGeneratedError(\n    error: unknown,\n  ): error is NoVideoGeneratedError {\n    return error instanceof Error &&\n      error.name === name &&\n      typeof (error as NoVideoGeneratedError).responses !== 'undefined'\n      ? true\n      : false;\n  }\n\n  /**\n   * @deprecated Do not use this method. It will be removed in the next major version.\n   */\n  toJSON() {\n    return {\n      name: this.name,\n      message: this.message,\n      stack: this.stack,\n\n      cause: this.cause,\n      responses: this.responses,\n    };\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoSuchToolError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchToolError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly toolName: string;\n  readonly availableTools: string[] | undefined;\n\n  constructor({\n    toolName,\n    availableTools = undefined,\n    message = `Model tried to call unavailable tool '${toolName}'. ${\n      availableTools === undefined\n        ? 'No tools are available.'\n        : `Available tools: ${availableTools.join(', ')}.`\n    }`,\n  }: {\n    toolName: string;\n    availableTools?: string[] | undefined;\n    message?: string;\n  }) {\n    super({ name, message });\n\n    this.toolName = toolName;\n    this.availableTools = availableTools;\n  }\n\n  static isInstance(error: unknown): error is NoSuchToolError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_StreamProviderError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Error reported by a provider after a model response stream has started.\n */\nexport class StreamProviderError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  /**\n   * Provider-defined error type, when supplied by the provider.\n   */\n  readonly type?: string;\n\n  /**\n   * Provider-defined error code, when supplied by the provider.\n   */\n  readonly code?: string | number;\n\n  /**\n   * HTTP-equivalent status code, when supplied by or inferable from the\n   * provider error metadata.\n   */\n  readonly statusCode?: number;\n\n  /**\n   * Whether retrying the model call may succeed.\n   */\n  readonly isRetryable: boolean;\n\n  /**\n   * Original provider error payload.\n   */\n  readonly data?: unknown;\n\n  constructor({\n    message,\n    type,\n    code,\n    statusCode,\n    isRetryable = isRetryableStatusCode(statusCode),\n    data,\n    cause,\n  }: {\n    message: string;\n    type?: string;\n    code?: string | number;\n    statusCode?: number;\n    isRetryable?: boolean;\n    data?: unknown;\n    cause?: unknown;\n  }) {\n    super({ name, message, cause });\n\n    this.type = type;\n    this.code = code;\n    this.statusCode = statusCode;\n    this.isRetryable = isRetryable;\n    this.data = data;\n  }\n\n  static isInstance(error: unknown): error is StreamProviderError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n\nfunction isRetryableStatusCode(statusCode: number | undefined): boolean {\n  return (\n    statusCode != null &&\n    (statusCode === 408 ||\n      statusCode === 409 ||\n      statusCode === 429 ||\n      statusCode >= 500)\n  );\n}\n","import { AISDKError, getErrorMessage } from '@ai-sdk/provider';\nimport type { InvalidToolInputError } from './invalid-tool-input-error';\nimport type { NoSuchToolError } from './no-such-tool-error';\n\nconst name = 'AI_ToolCallRepairError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class ToolCallRepairError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly originalError: NoSuchToolError | InvalidToolInputError;\n\n  constructor({\n    cause,\n    originalError,\n    message = `Error repairing tool call: ${getErrorMessage(cause)}`,\n  }: {\n    message?: string;\n    cause: unknown;\n    originalError: NoSuchToolError | InvalidToolInputError;\n  }) {\n    super({ name, message, cause });\n    this.originalError = originalError;\n  }\n\n  static isInstance(error: unknown): error is ToolCallRepairError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import {\n  AISDKError,\n  type LanguageModelV4Content,\n  type LanguageModelV4ToolChoice,\n} from '@ai-sdk/provider';\nimport type { FinishReason } from '../types/language-model';\n\nconst name = 'AI_ToolChoiceViolationError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\ntype EnforcedToolChoice = Extract<\n  LanguageModelV4ToolChoice,\n  { type: 'required' } | { type: 'tool' }\n>;\n\n/**\n * Thrown when a model response does not satisfy an enforced tool choice.\n */\nexport class ToolChoiceViolationError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  /**\n   * The tool choice that the model response did not satisfy.\n   */\n  readonly toolChoice: EnforcedToolChoice;\n\n  /**\n   * Reason why the model finished generating the response.\n   */\n  readonly finishReason: FinishReason;\n\n  /**\n   * The provider that returned the response.\n   */\n  readonly provider: string;\n\n  /**\n   * The model that returned the response.\n   */\n  readonly modelId: string;\n\n  /**\n   * The normalized content returned by the model.\n   *\n   * This can be inspected to recover a tool call that the provider returned as\n   * text or reasoning instead of a structured tool call.\n   */\n  readonly content: Array<LanguageModelV4Content>;\n\n  constructor({\n    toolChoice,\n    finishReason,\n    provider,\n    modelId,\n    content,\n    message = toolChoice.type === 'required'\n      ? 'Model response did not contain a tool call even though tool choice was required.'\n      : `Model response did not contain a call to the required tool '${toolChoice.toolName}'.`,\n  }: {\n    toolChoice: EnforcedToolChoice;\n    finishReason: FinishReason;\n    provider: string;\n    modelId: string;\n    content: Array<LanguageModelV4Content>;\n    message?: string;\n  }) {\n    super({ name, message });\n\n    this.toolChoice = toolChoice;\n    this.finishReason = finishReason;\n    this.provider = provider;\n    this.modelId = modelId;\n    this.content = content;\n  }\n\n  static isInstance(error: unknown): error is ToolChoiceViolationError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\n/**\n * Error that is thrown when a model with an unsupported version is used.\n */\nexport class UnsupportedModelVersionError extends AISDKError {\n  readonly version: string;\n  readonly provider: string;\n  readonly modelId: string;\n\n  constructor(options: { version: string; provider: string; modelId: string }) {\n    super({\n      name: 'AI_UnsupportedModelVersionError',\n      message:\n        `Unsupported model version ${options.version} for provider \"${options.provider}\" and model \"${options.modelId}\". ` +\n        `AI SDK 5 only supports models that implement specification version \"v2\".`,\n    });\n\n    this.version = options.version;\n    this.provider = options.provider;\n    this.modelId = options.modelId;\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_UIMessageStreamError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Error thrown when a UI message stream reports an error or contains invalid\n * or out-of-sequence chunks.\n *\n * This typically occurs when:\n * - An error chunk is received\n * - A delta chunk is received without a corresponding start chunk\n * - An end chunk is received without a corresponding start chunk\n * - A tool invocation is not found for the given toolCallId\n *\n * @see https://ai-sdk.dev/docs/reference/ai-sdk-errors/ai-ui-message-stream-error\n */\nexport class UIMessageStreamError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  /**\n   * The type of chunk that caused the error (e.g., 'text-delta', 'reasoning-end').\n   */\n  readonly chunkType: string;\n\n  /**\n   * The ID associated with the failing chunk (part ID or toolCallId), or an\n   * empty string when the chunk does not have an ID.\n   */\n  readonly chunkId: string;\n\n  constructor({\n    chunkType,\n    chunkId,\n    message,\n  }: {\n    chunkType: string;\n    chunkId: string;\n    message: string;\n  }) {\n    super({ name, message });\n\n    this.chunkType = chunkType;\n    this.chunkId = chunkId;\n  }\n\n  static isInstance(error: unknown): error is UIMessageStreamError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidDataContentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidDataContentError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly content: unknown;\n\n  constructor({\n    content,\n    cause,\n    message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`,\n  }: {\n    content: unknown;\n    cause?: unknown;\n    message?: string;\n  }) {\n    super({ name, message, cause });\n\n    this.content = content;\n  }\n\n  static isInstance(error: unknown): error is InvalidDataContentError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidMessageRoleError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidMessageRoleError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly role: string;\n\n  constructor({\n    role,\n    message = `Invalid message role: '${role}'. Must be one of: \"system\", \"user\", \"assistant\", \"tool\".`,\n  }: {\n    role: string;\n    message?: string;\n  }) {\n    super({ name, message });\n\n    this.role = role;\n  }\n\n  static isInstance(error: unknown): error is InvalidMessageRoleError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport type { UIMessage } from '../ui/ui-messages';\n\nconst name = 'AI_MessageConversionError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class MessageConversionError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly originalMessage: Omit<UIMessage, 'id'>;\n\n  constructor({\n    originalMessage,\n    message,\n  }: {\n    originalMessage: Omit<UIMessage, 'id'>;\n    message: string;\n  }) {\n    super({ name, message });\n\n    this.originalMessage = originalMessage;\n  }\n\n  static isInstance(error: unknown): error is MessageConversionError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_RetryError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport type RetryErrorReason =\n  | 'maxRetriesExceeded'\n  | 'errorNotRetryable'\n  | 'abort';\n\nexport class RetryError extends AISDKError {\n  private readonly [symbol] = true; // used in isInstance\n\n  // note: property order determines debugging output\n  readonly reason: RetryErrorReason;\n  readonly lastError: unknown;\n  readonly errors: Array<unknown>;\n\n  constructor({\n    message,\n    reason,\n    errors,\n  }: {\n    message: string;\n    reason: RetryErrorReason;\n    errors: Array<unknown>;\n  }) {\n    super({ name, message });\n\n    this.reason = reason;\n    this.errors = errors;\n\n    // separate our last error to make debugging via log easier:\n    this.lastError = errors[errors.length - 1];\n  }\n\n  static isInstance(error: unknown): error is RetryError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import type { Warning } from '../types';\n\n/**\n * A function for logging warnings.\n *\n * You can assign it to the `AI_SDK_LOG_WARNINGS` global variable to use it as the default warning logger.\n *\n * @example\n * ```ts\n * globalThis.AI_SDK_LOG_WARNINGS = (options) => {\n *   console.log('WARNINGS:', options.warnings, options.provider, options.model);\n * };\n * ```\n */\nexport type LogWarningsFunction = (options: {\n  /**\n   * The warnings returned by the model provider.\n   */\n  warnings: Warning[];\n\n  /**\n   * The provider id used for the call, if scoped to a specific provider.\n   */\n  provider?: string;\n\n  /**\n   * The model id used for the call, if scoped to a specific provider.\n   */\n  model?: string;\n}) => void;\n\n/**\n * Formats a warning object into a human-readable string with clear AI SDK branding.\n *\n * @param options - The options for formatting the warning.\n * @param options.warning - The warning to format.\n * @param options.provider - The provider id used for the call, if scoped to a specific provider.\n * @param options.model - The model id used for the call, if scoped to a specific provider.\n * @returns A formatted warning message string.\n */\nfunction formatWarning({\n  warning,\n  provider,\n  model,\n}: {\n  warning: Warning;\n  provider?: string;\n  model?: string;\n}): string {\n  const scope =\n    provider != null && model != null ? ` (${provider} / ${model})` : '';\n  const prefix = `AI SDK Warning${scope}:`;\n\n  switch (warning.type) {\n    case 'unsupported': {\n      let message = `${prefix} The feature \"${warning.feature}\" is not supported.`;\n      if (warning.details) {\n        message += ` ${warning.details}`;\n      }\n      return message;\n    }\n\n    case 'compatibility': {\n      let message = `${prefix} The feature \"${warning.feature}\" is used in a compatibility mode.`;\n      if (warning.details) {\n        message += ` ${warning.details}`;\n      }\n      return message;\n    }\n\n    case 'deprecated': {\n      return `${prefix} Deprecated: \"${warning.setting}\". ${warning.message}`;\n    }\n\n    case 'other': {\n      return `${prefix} ${warning.message}`;\n    }\n\n    default: {\n      // Fallback for any unknown warning types\n      return `${prefix} ${JSON.stringify(warning, null, 2)}`;\n    }\n  }\n}\n\nexport const FIRST_WARNING_INFO_MESSAGE =\n  'AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.';\n\nlet hasLoggedBefore = false;\n\nfunction emitWarning({\n  message,\n  type,\n}: {\n  message: string;\n  type: 'DeprecationWarning' | 'Warning';\n}) {\n  if (\n    typeof process !== 'undefined' &&\n    typeof process.emitWarning === 'function'\n  ) {\n    process.emitWarning(message, { type });\n  } else {\n    console.warn(message);\n  }\n}\n\n/**\n * Logs warnings to the console or uses a custom logger if configured.\n *\n * The behavior can be customized via the `AI_SDK_LOG_WARNINGS` global variable:\n * - If set to `false`, warnings are suppressed.\n * - If set to a function, that function is called with the warnings.\n * - Otherwise, warnings are logged to the console using `console.warn`.\n *\n * @param options - The options containing warnings and context.\n * @param options.warnings - The warnings to log.\n * @param options.provider - The provider id used for the call, if scoped to a specific provider.\n * @param options.model - The model id used for the call, if scoped to a specific provider.\n */\nexport const logWarnings: LogWarningsFunction = options => {\n  // if the warnings array is empty, do nothing\n  if (options.warnings.length === 0) {\n    return;\n  }\n\n  const logger = globalThis.AI_SDK_LOG_WARNINGS;\n\n  // if the logger is set to false, do nothing\n  if (logger === false) {\n    return;\n  }\n\n  // use the provided logger if it is a function\n  if (typeof logger === 'function') {\n    logger(options);\n    return;\n  }\n\n  // display information note on first call\n  if (!hasLoggedBefore) {\n    hasLoggedBefore = true;\n    emitWarning({\n      message: FIRST_WARNING_INFO_MESSAGE,\n      type: 'Warning',\n    });\n  }\n\n  // default behavior: log warnings via process.emitWarning if available, otherwise console.warn\n  for (const warning of options.warnings) {\n    const message = formatWarning({\n      warning,\n      provider: options.provider,\n      model: options.model,\n    });\n    emitWarning({\n      message,\n      type: warning.type === 'deprecated' ? 'DeprecationWarning' : 'Warning',\n    });\n  }\n};\n\n/**\n * Resets the internal logging state. Used for testing purposes.\n */\nexport const resetLogWarningsState = () => {\n  hasLoggedBefore = false;\n};\n","import { gateway } from '@ai-sdk/gateway';\nimport {\n  NoSuchModelError,\n  type Experimental_EvaluationModelV4 as EvaluationModelV4,\n  type EmbeddingModelV4,\n  type Experimental_SpeechTranslationModelV4,\n  type Experimental_VideoModelV4,\n  type ImageModelV4,\n  type LanguageModelV4,\n  type ProviderV4,\n  type RerankingModelV4,\n  type SpeechModelV4,\n  type TranscriptionModelV4,\n} from '@ai-sdk/provider';\nimport type { EvaluationModel } from '../evaluate/evaluation-result';\nimport type { EvaluationProvider } from '../evaluate/evaluation-provider';\nimport { UnsupportedModelVersionError } from '../error';\nimport type { EmbeddingModel } from '../types/embedding-model';\nimport type { LanguageModel } from '../types/language-model';\nimport type { SpeechModel } from '../types/speech-model';\nimport type { SpeechTranslationModel } from '../types/speech-translation-model';\nimport type { TranscriptionModel } from '../types/transcription-model';\nimport { asEmbeddingModelV4 } from './as-embedding-model-v4';\nimport { asImageModelV4 } from './as-image-model-v4';\nimport { asLanguageModelV4 } from './as-language-model-v4';\nimport { asRerankingModelV4 } from './as-reranking-model-v4';\nimport { asSpeechModelV4 } from './as-speech-model-v4';\nimport { asTranscriptionModelV4 } from './as-transcription-model-v4';\nimport { asVideoModelV4 } from './as-video-model-v4';\nimport { asProviderV4 } from './as-provider-v4';\nimport type { ImageModel } from '../types/image-model';\nimport type { RerankingModel } from '../types/reranking-model';\nimport type { VideoModel } from '../types/video-model';\n\nexport function resolveLanguageModel(model: LanguageModel): LanguageModelV4 {\n  if (typeof model === 'string') {\n    return getGlobalProvider().languageModel(model);\n  }\n\n  if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n    const unsupportedModel: any = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId,\n    });\n  }\n\n  return asLanguageModelV4(model);\n}\n\nexport function resolveEmbeddingModel(model: EmbeddingModel): EmbeddingModelV4 {\n  if (typeof model === 'string') {\n    return getGlobalProvider().embeddingModel(model);\n  }\n\n  if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n    const unsupportedModel: any = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId,\n    });\n  }\n\n  return asEmbeddingModelV4(model);\n}\n\nexport function resolveTranscriptionModel(\n  model: TranscriptionModel,\n): TranscriptionModelV4 | undefined {\n  if (typeof model === 'string') {\n    return getGlobalProvider().transcriptionModel?.(model);\n  }\n\n  if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n    const unsupportedModel: any = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId,\n    });\n  }\n\n  return asTranscriptionModelV4(model);\n}\n\nexport function resolveSpeechTranslationModel(\n  model: SpeechTranslationModel,\n): Experimental_SpeechTranslationModelV4 {\n  if (typeof model === 'string') {\n    // Use raw global provider because speechTranslationModel is experimental\n    // and not part of the ProviderV4 interface\n    const provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway;\n    // TODO AI SDK v7\n    // @ts-expect-error - speechTranslationModel support is experimental\n    const speechTranslationModel = provider.speechTranslationModel;\n\n    if (!speechTranslationModel) {\n      throw new Error(\n        'The default provider does not support speech translation models. ' +\n          'Please pass a provider model instance that implements the experimental speech translation model specification.',\n      );\n    }\n\n    return speechTranslationModel(model);\n  }\n\n  if (model.specificationVersion !== 'v4') {\n    const unsupportedModel: any = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId,\n    });\n  }\n\n  return model;\n}\n\nexport function resolveSpeechModel(\n  model: SpeechModel,\n): SpeechModelV4 | undefined {\n  if (typeof model === 'string') {\n    return getGlobalProvider().speechModel?.(model);\n  }\n\n  if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n    const unsupportedModel: any = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId,\n    });\n  }\n\n  return asSpeechModelV4(model);\n}\n\nexport function resolveImageModel(model: ImageModel): ImageModelV4 {\n  if (typeof model === 'string') {\n    return getGlobalProvider().imageModel(model);\n  }\n\n  if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n    const unsupportedModel: any = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId,\n    });\n  }\n\n  return asImageModelV4(model);\n}\n\nexport function resolveVideoModel(\n  model: VideoModel,\n): Experimental_VideoModelV4 {\n  if (typeof model === 'string') {\n    // Use raw global provider because videoModel is experimental\n    // and not part of the ProviderV4 interface\n    const provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway;\n    // TODO AI SDK v7\n    // @ts-expect-error - videoModel support is experimental\n    const videoModel = provider.videoModel;\n\n    if (!videoModel) {\n      throw new Error(\n        'The default provider does not support video models. ' +\n          'Please use a Experimental_VideoModelV4 object from a provider (e.g., vertex.video(\"model-id\")).',\n      );\n    }\n\n    return videoModel(model);\n  }\n\n  if (!['v4', 'v3'].includes(model.specificationVersion)) {\n    const unsupportedModel: any = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId,\n    });\n  }\n\n  return asVideoModelV4(model);\n}\n\nexport function resolveRerankingModel(model: RerankingModel): RerankingModelV4 {\n  if (typeof model === 'string') {\n    const provider = getGlobalProvider();\n    const rerankingModel = provider.rerankingModel;\n\n    if (!rerankingModel) {\n      throw new Error(\n        'The default provider does not support reranking models. ' +\n          'Please use a RerankingModel object from a provider (e.g., gateway.rerankingModel(\"model-id\")).',\n      );\n    }\n\n    return rerankingModel(model);\n  }\n\n  if (\n    model.specificationVersion !== 'v4' &&\n    model.specificationVersion !== 'v3'\n  ) {\n    const unsupportedModel: any = model;\n    throw new UnsupportedModelVersionError({\n      version: unsupportedModel.specificationVersion,\n      provider: unsupportedModel.provider,\n      modelId: unsupportedModel.modelId,\n    });\n  }\n\n  return asRerankingModelV4(model);\n}\n\nexport function resolveEvaluationModel(\n  model: EvaluationModel,\n): EvaluationModelV4 {\n  if (typeof model === 'string') {\n    // Use the original provider so experimental methods and their receiver survive.\n    const provider = (globalThis.AI_SDK_DEFAULT_PROVIDER ??\n      gateway) as EvaluationProvider;\n\n    if (typeof provider?.evaluationModel !== 'function') {\n      throw new NoSuchModelError({\n        modelId: model,\n        modelType: 'evaluationModel',\n        message:\n          'The default provider does not support evaluation models. ' +\n          'Pass an evaluation model instance or configure AI_SDK_DEFAULT_PROVIDER with an evaluationModel method.',\n      });\n    }\n\n    const resolvedModel = provider.evaluationModel(model);\n    if (resolvedModel == null) {\n      throw new NoSuchModelError({\n        modelId: model,\n        modelType: 'evaluationModel',\n      });\n    }\n    model = resolvedModel;\n  }\n\n  if (model.specificationVersion !== 'v4') {\n    throw new UnsupportedModelVersionError({\n      version: model.specificationVersion,\n      provider: model.provider,\n      modelId: model.modelId,\n    });\n  }\n\n  return model;\n}\n\nfunction getGlobalProvider(): ProviderV4 {\n  const provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway;\n  return asProviderV4(provider);\n}\n","import { logWarnings } from '../logger/log-warnings';\n\nexport function logV2CompatibilityWarning({\n  provider,\n  modelId,\n}: {\n  provider: string;\n  modelId: string;\n}): void {\n  logWarnings({\n    warnings: [\n      {\n        type: 'compatibility',\n        feature: 'specificationVersion',\n        details: `Using v2 specification compatibility mode. Some features may not be available.`,\n      },\n    ],\n    provider,\n    model: modelId,\n  });\n}\n","import type { EmbeddingModelV2, EmbeddingModelV3 } from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asEmbeddingModelV3(\n  model: EmbeddingModelV2<string> | EmbeddingModelV3,\n): EmbeddingModelV3 {\n  if (model.specificationVersion === 'v3') {\n    return model;\n  }\n\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId,\n  });\n\n  // TODO this could break, we need to properly map v2 to v3\n  // and support all relevant v3 properties:\n  return new Proxy(model, {\n    get(target, prop: keyof EmbeddingModelV2<string>) {\n      if (prop === 'specificationVersion') return 'v3';\n      return target[prop];\n    },\n  }) as unknown as EmbeddingModelV3;\n}\n","import type {\n  EmbeddingModelV2,\n  EmbeddingModelV3,\n  EmbeddingModelV4,\n} from '@ai-sdk/provider';\nimport { asEmbeddingModelV3 } from './as-embedding-model-v3';\n\nexport function asEmbeddingModelV4(\n  model: EmbeddingModelV2<string> | EmbeddingModelV3 | EmbeddingModelV4,\n): EmbeddingModelV4 {\n  if (model.specificationVersion === 'v4') {\n    return model;\n  }\n\n  // first convert v2 to v3, then proxy v3 as v4:\n  const v3Model =\n    model.specificationVersion === 'v2' ? asEmbeddingModelV3(model) : model;\n\n  return new Proxy(v3Model, {\n    get(target, prop: keyof EmbeddingModelV3) {\n      if (prop === 'specificationVersion') return 'v4';\n      return target[prop];\n    },\n  }) as unknown as EmbeddingModelV4;\n}\n","import type { ImageModelV2, ImageModelV3 } from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asImageModelV3(\n  model: ImageModelV2 | ImageModelV3,\n): ImageModelV3 {\n  if (model.specificationVersion === 'v3') {\n    return model;\n  }\n\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId,\n  });\n\n  // TODO this could break, we need to properly map v2 to v3\n  // and support all relevant v3 properties:\n  return new Proxy(model, {\n    get(target, prop: keyof ImageModelV2) {\n      if (prop === 'specificationVersion') return 'v3';\n      return target[prop];\n    },\n  }) as unknown as ImageModelV3;\n}\n","import type {\n  ImageModelV2,\n  ImageModelV3,\n  ImageModelV4,\n} from '@ai-sdk/provider';\nimport { asImageModelV3 } from './as-image-model-v3';\n\nexport function asImageModelV4(\n  model: ImageModelV2 | ImageModelV3 | ImageModelV4,\n): ImageModelV4 {\n  if (model.specificationVersion === 'v4') {\n    return model;\n  }\n\n  // first convert v2 to v3, then proxy v3 as v4:\n  const v3Model =\n    model.specificationVersion === 'v2' ? asImageModelV3(model) : model;\n\n  return new Proxy(v3Model, {\n    get(target, prop: keyof ImageModelV3) {\n      if (prop === 'specificationVersion') return 'v4';\n      return target[prop];\n    },\n  }) as unknown as ImageModelV4;\n}\n","import type {\n  LanguageModelV2,\n  LanguageModelV2FinishReason,\n  LanguageModelV2StreamPart,\n  LanguageModelV2Usage,\n  LanguageModelV3,\n  LanguageModelV3FinishReason,\n  LanguageModelV3StreamPart,\n  LanguageModelV3Usage,\n} from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asLanguageModelV3(\n  model: LanguageModelV2 | LanguageModelV3,\n): LanguageModelV3 {\n  if (model.specificationVersion === 'v3') {\n    return model;\n  }\n\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId,\n  });\n\n  // TODO this could break, we need to properly map v2 to v3\n  // and support all relevant v3 properties:\n  return new Proxy(model, {\n    get(target, prop: keyof LanguageModelV2) {\n      switch (prop) {\n        case 'specificationVersion':\n          return 'v3';\n        case 'doGenerate':\n          return async (...args: Parameters<LanguageModelV2['doGenerate']>) => {\n            const result = await target.doGenerate(...args);\n            return {\n              ...result,\n              finishReason: convertV2FinishReasonToV3(result.finishReason),\n              usage: convertV2UsageToV3(result.usage),\n            };\n          };\n        case 'doStream':\n          return async (...args: Parameters<LanguageModelV2['doStream']>) => {\n            const result = await target.doStream(...args);\n            return {\n              ...result,\n              stream: convertV2StreamToV3(result.stream),\n            };\n          };\n        default:\n          return target[prop];\n      }\n    },\n  }) as unknown as LanguageModelV3;\n}\n\nfunction convertV2StreamToV3(\n  stream: ReadableStream<LanguageModelV2StreamPart>,\n): ReadableStream<LanguageModelV3StreamPart> {\n  return stream.pipeThrough(\n    new TransformStream<LanguageModelV2StreamPart, LanguageModelV3StreamPart>({\n      transform(chunk, controller) {\n        switch (chunk.type) {\n          case 'finish':\n            controller.enqueue({\n              ...chunk,\n              finishReason: convertV2FinishReasonToV3(chunk.finishReason),\n              usage: convertV2UsageToV3(chunk.usage),\n            });\n            break;\n          default:\n            // TODO: AI SDK 6 - no casting (stream parts need to be mapped)\n            controller.enqueue(chunk as LanguageModelV3StreamPart);\n            break;\n        }\n      },\n    }),\n  );\n}\n\nfunction convertV2FinishReasonToV3(\n  finishReason: LanguageModelV2FinishReason,\n): LanguageModelV3FinishReason {\n  return {\n    unified: finishReason === 'unknown' ? 'other' : finishReason,\n    raw: undefined,\n  };\n}\n\nfunction convertV2UsageToV3(usage: LanguageModelV2Usage): LanguageModelV3Usage {\n  return {\n    inputTokens: {\n      total: usage.inputTokens,\n      noCache: undefined,\n      cacheRead: usage.cachedInputTokens,\n      cacheWrite: undefined,\n    },\n    outputTokens: {\n      total: usage.outputTokens,\n      text: undefined,\n      reasoning: usage.reasoningTokens,\n    },\n  };\n}\n","import type {\n  LanguageModelV2,\n  LanguageModelV3,\n  LanguageModelV4,\n} from '@ai-sdk/provider';\nimport { asLanguageModelV3 } from './as-language-model-v3';\n\nexport function asLanguageModelV4(\n  model: LanguageModelV2 | LanguageModelV3 | LanguageModelV4,\n): LanguageModelV4 {\n  if (model.specificationVersion === 'v4') {\n    return model;\n  }\n\n  // first convert v2 to v3, then proxy v3 as v4:\n  const v3Model =\n    model.specificationVersion === 'v2' ? asLanguageModelV3(model) : model;\n\n  return new Proxy(v3Model, {\n    get(target, prop: keyof LanguageModelV3) {\n      if (prop === 'specificationVersion') return 'v4';\n      return target[prop];\n    },\n  }) as unknown as LanguageModelV4;\n}\n","import type { RerankingModelV3, RerankingModelV4 } from '@ai-sdk/provider';\n\nexport function asRerankingModelV4(\n  model: RerankingModelV3 | RerankingModelV4,\n): RerankingModelV4 {\n  if (model.specificationVersion === 'v4') {\n    return model;\n  }\n\n  return new Proxy(model, {\n    get(target, prop: keyof RerankingModelV3) {\n      if (prop === 'specificationVersion') return 'v4';\n      return target[prop];\n    },\n  }) as unknown as RerankingModelV4;\n}\n","import type { SpeechModelV2, SpeechModelV3 } from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asSpeechModelV3(\n  model: SpeechModelV3 | SpeechModelV2,\n): SpeechModelV3 {\n  if (model.specificationVersion === 'v3') {\n    return model;\n  }\n\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId,\n  });\n\n  // TODO this could break, we need to properly map v2 to v3\n  // and support all relevant v3 properties:\n  return new Proxy(model, {\n    get(target, prop: keyof SpeechModelV2) {\n      if (prop === 'specificationVersion') return 'v3';\n      return target[prop];\n    },\n  }) as unknown as SpeechModelV3;\n}\n","import type {\n  SpeechModelV2,\n  SpeechModelV3,\n  SpeechModelV4,\n} from '@ai-sdk/provider';\nimport { asSpeechModelV3 } from './as-speech-model-v3';\n\nexport function asSpeechModelV4(\n  model: SpeechModelV2 | SpeechModelV3 | SpeechModelV4,\n): SpeechModelV4 {\n  if (model.specificationVersion === 'v4') {\n    return model;\n  }\n\n  // first convert v2 to v3, then proxy v3 as v4:\n  const v3Model =\n    model.specificationVersion === 'v2' ? asSpeechModelV3(model) : model;\n\n  return new Proxy(v3Model, {\n    get(target, prop: keyof SpeechModelV3) {\n      if (prop === 'specificationVersion') return 'v4';\n      return target[prop];\n    },\n  }) as unknown as SpeechModelV4;\n}\n","import type {\n  TranscriptionModelV2,\n  TranscriptionModelV3,\n} from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asTranscriptionModelV3(\n  model: TranscriptionModelV3 | TranscriptionModelV2,\n): TranscriptionModelV3 {\n  if (model.specificationVersion === 'v3') {\n    return model;\n  }\n\n  logV2CompatibilityWarning({\n    provider: model.provider,\n    modelId: model.modelId,\n  });\n\n  // TODO this could break, we need to properly map v2 to v3\n  // and support all relevant v3 properties:\n  return new Proxy(model, {\n    get(target, prop: keyof TranscriptionModelV2) {\n      if (prop === 'specificationVersion') return 'v3';\n      return target[prop];\n    },\n  }) as unknown as TranscriptionModelV3;\n}\n","import type {\n  TranscriptionModelV2,\n  TranscriptionModelV3,\n  TranscriptionModelV4,\n} from '@ai-sdk/provider';\nimport { asTranscriptionModelV3 } from './as-transcription-model-v3';\n\nexport function asTranscriptionModelV4(\n  model: TranscriptionModelV2 | TranscriptionModelV3 | TranscriptionModelV4,\n): TranscriptionModelV4 {\n  if (model.specificationVersion === 'v4') {\n    return model;\n  }\n\n  // first convert v2 to v3, then proxy v3 as v4:\n  const v3Model =\n    model.specificationVersion === 'v2' ? asTranscriptionModelV3(model) : model;\n\n  return new Proxy(v3Model, {\n    get(target, prop: keyof TranscriptionModelV3) {\n      if (prop === 'specificationVersion') return 'v4';\n      return target[prop];\n    },\n  }) as unknown as TranscriptionModelV4;\n}\n","import type {\n  Experimental_VideoModelV3,\n  Experimental_VideoModelV4,\n} from '@ai-sdk/provider';\n\nexport function asVideoModelV4(\n  model: Experimental_VideoModelV3 | Experimental_VideoModelV4,\n): Experimental_VideoModelV4 {\n  if (model.specificationVersion === 'v4') {\n    return model;\n  }\n\n  return new Proxy(model, {\n    get(target, prop: keyof Experimental_VideoModelV3) {\n      if (prop === 'specificationVersion') return 'v4';\n      return target[prop];\n    },\n  }) as unknown as Experimental_VideoModelV4;\n}\n","import type { ProviderV2, ProviderV3 } from '@ai-sdk/provider';\nimport { asEmbeddingModelV3 } from './as-embedding-model-v3';\nimport { asImageModelV3 } from './as-image-model-v3';\nimport { asLanguageModelV3 } from './as-language-model-v3';\nimport { asTranscriptionModelV3 } from './as-transcription-model-v3';\nimport { asSpeechModelV3 } from './as-speech-model-v3';\n\nexport function asProviderV3(provider: ProviderV2 | ProviderV3): ProviderV3 {\n  if (\n    'specificationVersion' in provider &&\n    provider.specificationVersion === 'v3'\n  ) {\n    return provider;\n  }\n\n  // v3 providers have already been returned\n  const v2Provider: ProviderV2 = provider as ProviderV2;\n\n  return {\n    specificationVersion: 'v3',\n    languageModel: (modelId: string) =>\n      asLanguageModelV3(v2Provider.languageModel(modelId)),\n    embeddingModel: (modelId: string) =>\n      asEmbeddingModelV3(v2Provider.textEmbeddingModel(modelId)),\n    imageModel: (modelId: string) =>\n      asImageModelV3(v2Provider.imageModel(modelId)),\n    transcriptionModel: v2Provider.transcriptionModel\n      ? (modelId: string) =>\n          asTranscriptionModelV3(v2Provider.transcriptionModel!(modelId))\n      : undefined,\n    speechModel: v2Provider.speechModel\n      ? (modelId: string) => asSpeechModelV3(v2Provider.speechModel!(modelId))\n      : undefined,\n    rerankingModel: undefined, // v2 providers don't have reranking models\n  };\n}\n","import type { ProviderV2, ProviderV3, ProviderV4 } from '@ai-sdk/provider';\nimport { asProviderV3 } from './as-provider-v3';\nimport { asEmbeddingModelV4 } from './as-embedding-model-v4';\nimport { asImageModelV4 } from './as-image-model-v4';\nimport { asLanguageModelV4 } from './as-language-model-v4';\nimport { asRerankingModelV4 } from './as-reranking-model-v4';\nimport { asTranscriptionModelV4 } from './as-transcription-model-v4';\nimport { asSpeechModelV4 } from './as-speech-model-v4';\n\nexport function asProviderV4(\n  provider: ProviderV2 | ProviderV3 | ProviderV4,\n): ProviderV4 {\n  if (\n    'specificationVersion' in provider &&\n    provider.specificationVersion === 'v4'\n  ) {\n    return provider;\n  }\n\n  // first ensure we have at least a v3 provider:\n  const v3Provider: ProviderV3 =\n    !('specificationVersion' in provider) ||\n    provider.specificationVersion !== 'v3'\n      ? asProviderV3(provider as ProviderV2)\n      : provider;\n\n  return {\n    specificationVersion: 'v4',\n    languageModel: (modelId: string) =>\n      asLanguageModelV4(v3Provider.languageModel(modelId)),\n    embeddingModel: (modelId: string) =>\n      asEmbeddingModelV4(v3Provider.embeddingModel(modelId)),\n    imageModel: (modelId: string) =>\n      asImageModelV4(v3Provider.imageModel(modelId)),\n    transcriptionModel: v3Provider.transcriptionModel\n      ? (modelId: string) =>\n          asTranscriptionModelV4(v3Provider.transcriptionModel!(modelId))\n      : undefined,\n    speechModel: v3Provider.speechModel\n      ? (modelId: string) => asSpeechModelV4(v3Provider.speechModel!(modelId))\n      : undefined,\n    rerankingModel: v3Provider.rerankingModel\n      ? (modelId: string) =>\n          asRerankingModelV4(v3Provider.rerankingModel!(modelId))\n      : undefined,\n  };\n}\n","import type { ModelMessage } from '@ai-sdk/provider-utils';\n\n/**\n * Clone model messages while preserving URL instances. Node's structuredClone\n * currently rejects URL objects, which are valid file/image prompt payloads.\n */\nexport function cloneModelMessages<T extends ModelMessage>(\n  messages: Array<T>,\n): Array<T> {\n  return messages.map(message => cloneValue(message)) as Array<T>;\n}\n\nfunction cloneValue<T>(value: T): T {\n  if (value instanceof URL) {\n    return new URL(value.href) as T;\n  }\n\n  if (Array.isArray(value)) {\n    return value.map(item => cloneValue(item)) as T;\n  }\n\n  if (value instanceof Uint8Array) {\n    return new Uint8Array(value) as T;\n  }\n\n  if (value instanceof ArrayBuffer) {\n    return value.slice(0) as T;\n  }\n\n  if (value instanceof Date) {\n    return new Date(value) as T;\n  }\n\n  if (value != null && typeof value === 'object') {\n    return Object.fromEntries(\n      Object.entries(value).map(([key, value]) => [key, cloneValue(value)]),\n    ) as T;\n  }\n\n  return value;\n}\n","import type {\n  LanguageModelV4FilePart,\n  LanguageModelV4Message,\n  LanguageModelV4Prompt,\n  LanguageModelV4TextPart,\n  LanguageModelV4ToolResultOutput,\n} from '@ai-sdk/provider';\nimport {\n  asArray,\n  detectMediaType,\n  isFullMediaType,\n  isUrlSupported,\n  type CustomPart,\n  type FilePart,\n  type ImagePart,\n  type ModelMessage,\n  type ReasoningFilePart,\n  type ReasoningPart,\n  type TextPart,\n  type ToolCallPart,\n  type ToolResultOutput,\n  type ToolResultPart,\n} from '@ai-sdk/provider-utils';\nimport {\n  createDefaultDownloadFunction,\n  type DownloadFunction,\n} from '../util/download/download-function';\nimport { mergeObjects } from '../util/merge-objects';\nimport { convertToLanguageModelV4FilePart } from './file-part-data';\nimport { logWarnings } from '../logger/log-warnings';\nimport type { Warning } from '../types/warning';\nimport { InvalidMessageRoleError } from './invalid-message-role-error';\nimport type { StandardizedPrompt } from './standardize-prompt';\nimport { MissingToolResultsError } from '../error/missing-tool-result-error';\n\nexport async function convertToLanguageModelPrompt({\n  prompt,\n  supportedUrls,\n  download = createDefaultDownloadFunction(),\n  // `provider` is only needed here to convert legacy tool output types via `mapToolResultOutput`.\n  // TODO: remove in v8 when \"file-id\" and \"image-file-id\" types are removed\n  provider,\n}: {\n  prompt: StandardizedPrompt;\n  supportedUrls: Record<string, RegExp[]>;\n  download: DownloadFunction | undefined;\n  provider?: string;\n}): Promise<LanguageModelV4Prompt> {\n  const downloadedAssets = await downloadAssets(\n    prompt.messages,\n    download,\n    supportedUrls,\n  );\n\n  const approvalIdToToolCallId = new Map<string, string>();\n  for (const message of prompt.messages) {\n    if (message.role === 'assistant' && Array.isArray(message.content)) {\n      for (const part of message.content) {\n        if (\n          part.type === 'tool-approval-request' &&\n          'approvalId' in part &&\n          'toolCallId' in part\n        ) {\n          approvalIdToToolCallId.set(\n            part.approvalId as string,\n            part.toolCallId as string,\n          );\n        }\n      }\n    }\n  }\n\n  const approvedToolCallIds = new Set<string>();\n  for (const message of prompt.messages) {\n    if (message.role === 'tool') {\n      for (const part of message.content) {\n        if (part.type === 'tool-approval-response') {\n          const toolCallId = approvalIdToToolCallId.get(part.approvalId);\n          if (toolCallId) {\n            approvedToolCallIds.add(toolCallId);\n          }\n        }\n      }\n    }\n  }\n\n  const messages = [\n    ...(prompt.instructions != null\n      ? typeof prompt.instructions === 'string'\n        ? [{ role: 'system' as const, content: prompt.instructions }]\n        : asArray(prompt.instructions).map(message => ({\n            role: 'system' as const,\n            content: message.content,\n            providerOptions: message.providerOptions,\n          }))\n      : []),\n    ...prompt.messages.map(message =>\n      convertToLanguageModelMessage({ message, downloadedAssets, provider }),\n    ),\n  ];\n\n  // combine consecutive tool messages into a single tool message\n  const combinedMessages = [];\n  for (const message of messages) {\n    if (message.role !== 'tool') {\n      combinedMessages.push(message);\n      continue;\n    }\n\n    const lastCombinedMessage = combinedMessages.at(-1);\n    if (lastCombinedMessage?.role === 'tool') {\n      const lastContentPart = lastCombinedMessage.content.at(-1);\n      if (\n        lastContentPart != null &&\n        lastCombinedMessage.providerOptions != null\n      ) {\n        lastContentPart.providerOptions = mergeObjects(\n          lastCombinedMessage.providerOptions,\n          lastContentPart.providerOptions,\n        );\n      }\n\n      lastCombinedMessage.content.push(...message.content);\n      lastCombinedMessage.providerOptions = message.providerOptions;\n    } else {\n      combinedMessages.push(message);\n    }\n  }\n\n  const toolCallIds = new Set<string>();\n\n  for (const message of combinedMessages) {\n    switch (message.role) {\n      case 'assistant': {\n        for (const content of message.content) {\n          if (content.type === 'tool-call' && !content.providerExecuted) {\n            toolCallIds.add(content.toolCallId);\n          }\n        }\n        break;\n      }\n      case 'tool': {\n        for (const content of message.content) {\n          if (content.type === 'tool-result') {\n            toolCallIds.delete(content.toolCallId);\n          }\n        }\n        break;\n      }\n      case 'user':\n      case 'system':\n        // remove approved tool calls from the set before checking:\n        for (const id of approvedToolCallIds) {\n          toolCallIds.delete(id);\n        }\n\n        if (toolCallIds.size > 0) {\n          throw new MissingToolResultsError({\n            toolCallIds: Array.from(toolCallIds),\n          });\n        }\n        break;\n    }\n  }\n\n  // remove approved tool calls from the set before checking:\n  for (const id of approvedToolCallIds) {\n    toolCallIds.delete(id);\n  }\n\n  if (toolCallIds.size > 0) {\n    throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });\n  }\n\n  return combinedMessages.filter(\n    // Filter out empty tool messages (e.g. if they only contained\n    // tool-approval-response parts that were removed).\n    // This prevents sending invalid empty messages to the provider.\n    // Note: provider-executed tool-approval-response parts are preserved.\n    message => message.role !== 'tool' || message.content.length > 0,\n  );\n}\n\n/**\n * Convert a ModelMessage to a LanguageModelV4Message.\n *\n * @param message - The ModelMessage to convert.\n * @param downloadedAssets - A map of URLs to their downloaded data. Only\n * available if the model does not support URLs, null otherwise.\n */\nexport function convertToLanguageModelMessage({\n  message,\n  downloadedAssets,\n  // `provider` is only needed here to convert legacy tool output types via `mapToolResultOutput`.\n  // TODO: remove in v8 when \"file-id\" and \"image-file-id\" types are removed\n  provider,\n}: {\n  message: ModelMessage;\n  downloadedAssets: Record<\n    string,\n    { mediaType: string | undefined; data: Uint8Array }\n  >;\n  provider?: string;\n}): LanguageModelV4Message {\n  const warnings: Warning[] = [];\n\n  const role = message.role;\n  switch (role) {\n    case 'system': {\n      return {\n        role: 'system',\n        content: message.content,\n        providerOptions: message.providerOptions,\n      };\n    }\n\n    case 'user': {\n      if (typeof message.content === 'string') {\n        return {\n          role: 'user',\n          content: [{ type: 'text', text: message.content }],\n          providerOptions: message.providerOptions,\n        };\n      }\n\n      const converted = {\n        role: 'user' as const,\n        content: message.content\n          .map(part => {\n            if (part.type === 'image') {\n              warnings.push({\n                type: 'deprecated',\n                setting: '\"image\" content part',\n                message: `The \"image\" content part type is deprecated. Use a \"file\" part with mediaType: 'image' (or a more specific image/* subtype) instead.`,\n              });\n            }\n            return convertImagePartToFilePart(part);\n          })\n          .map(part => convertPartToLanguageModelPart(part, downloadedAssets))\n          // remove empty text parts:\n          .filter(part => part.type !== 'text' || part.text !== ''),\n        providerOptions: message.providerOptions,\n      };\n      if (warnings.length > 0) {\n        logWarnings({ warnings });\n      }\n      return converted;\n    }\n\n    case 'assistant': {\n      if (typeof message.content === 'string') {\n        return {\n          role: 'assistant',\n          content: [{ type: 'text', text: message.content }],\n          providerOptions: message.providerOptions,\n        };\n      }\n\n      const converted = {\n        role: 'assistant' as const,\n        content: message.content\n          .filter(\n            // remove empty text parts (no text, and no provider options):\n            part =>\n              part.type !== 'text' ||\n              part.text !== '' ||\n              part.providerOptions != null,\n          )\n          .filter(\n            (\n              part,\n            ): part is\n              | CustomPart\n              | TextPart\n              | FilePart\n              | ReasoningPart\n              | ReasoningFilePart\n              | ToolCallPart\n              | ToolResultPart => part.type !== 'tool-approval-request',\n          )\n          .map(part => {\n            const providerOptions = part.providerOptions;\n\n            switch (part.type) {\n              case 'custom': {\n                return {\n                  type: 'custom' as const,\n                  kind: part.kind,\n                  providerOptions,\n                };\n              }\n              case 'file': {\n                const { data, mediaType } = convertToLanguageModelV4FilePart(\n                  part.data,\n                );\n                return {\n                  type: 'file' as const,\n                  data,\n                  filename: part.filename,\n                  mediaType: mediaType ?? part.mediaType,\n                  providerOptions,\n                };\n              }\n              case 'reasoning': {\n                return {\n                  type: 'reasoning' as const,\n                  text: part.text,\n                  providerOptions,\n                };\n              }\n              case 'reasoning-file': {\n                const { data, mediaType } = convertToLanguageModelV4FilePart(\n                  part.data,\n                );\n                if (data.type !== 'data' && data.type !== 'url') {\n                  throw new Error(\n                    `Unsupported reasoning-file data type: ${data.type}`,\n                  );\n                }\n                return {\n                  type: 'reasoning-file' as const,\n                  data,\n                  mediaType: mediaType ?? part.mediaType,\n                  providerOptions,\n                };\n              }\n              case 'text': {\n                return {\n                  type: 'text' as const,\n                  text: part.text,\n                  providerOptions,\n                };\n              }\n              case 'tool-call': {\n                return {\n                  type: 'tool-call' as const,\n                  toolCallId: part.toolCallId,\n                  toolName: part.toolName,\n                  input: part.input,\n                  providerExecuted: part.providerExecuted,\n                  providerOptions,\n                };\n              }\n              case 'tool-result': {\n                return {\n                  type: 'tool-result' as const,\n                  toolCallId: part.toolCallId,\n                  toolName: part.toolName,\n                  output: mapToolResultOutput({\n                    output: part.output,\n                    provider,\n                    warnings,\n                    downloadedAssets,\n                  }),\n                  providerOptions,\n                };\n              }\n            }\n          }),\n        providerOptions: message.providerOptions,\n      };\n      if (warnings.length > 0) {\n        logWarnings({ warnings });\n      }\n      return converted;\n    }\n\n    case 'tool': {\n      const converted = {\n        role: 'tool' as const,\n        content: message.content\n          .filter(\n            // Only include tool-approval-response for provider-executed tools\n            part =>\n              part.type !== 'tool-approval-response' || part.providerExecuted,\n          )\n          .map(part => {\n            switch (part.type) {\n              case 'tool-result': {\n                return {\n                  type: 'tool-result' as const,\n                  toolCallId: part.toolCallId,\n                  toolName: part.toolName,\n                  output: mapToolResultOutput({\n                    output: part.output,\n                    provider,\n                    warnings,\n                    downloadedAssets,\n                  }),\n                  providerOptions: part.providerOptions,\n                };\n              }\n              case 'tool-approval-response': {\n                return {\n                  type: 'tool-approval-response' as const,\n                  approvalId: part.approvalId,\n                  approved: part.approved,\n                  reason: part.reason,\n                };\n              }\n            }\n          }),\n        providerOptions: message.providerOptions,\n      };\n      if (warnings.length > 0) {\n        logWarnings({ warnings });\n      }\n      return converted;\n    }\n\n    default: {\n      const _exhaustiveCheck: never = role;\n      throw new InvalidMessageRoleError({ role: _exhaustiveCheck });\n    }\n  }\n}\n\n/*\n * Rewrites a legacy `ImagePart` into an equivalent `FilePart`. The default\n * `mediaType` for a bare `ImagePart` (no `mediaType`) is `\"image\"` (top-level\n * segment); an explicit `mediaType` is carried through verbatim. After this\n * pre-pass, only `TextPart` and `FilePart` ever reach the provider-facing\n * conversion logic.\n */\nfunction convertImagePartToFilePart(\n  part: TextPart | ImagePart | FilePart,\n): TextPart | FilePart {\n  if (part.type !== 'image') {\n    return part;\n  }\n  return {\n    type: 'file',\n    data: part.image,\n    mediaType: part.mediaType ?? 'image',\n    providerOptions: part.providerOptions,\n  };\n}\n\n/**\n * Downloads files from URLs in the user messages.\n */\nexport async function downloadAssets(\n  messages: ModelMessage[],\n  download: DownloadFunction,\n  supportedUrls: Record<string, RegExp[]>,\n): Promise<\n  Record<string, { mediaType: string | undefined; data: Uint8Array }>\n> {\n  type ConvertedFile = {\n    mediaType: string | undefined;\n    data: LanguageModelV4FilePart['data'];\n  };\n  type UrlTaggedFile = {\n    mediaType: string | undefined;\n    data: { type: 'url'; url: URL };\n  };\n\n  const downloadableFiles: FilePart[] = [];\n\n  for (const message of messages) {\n    if (message.role === 'user' && Array.isArray(message.content)) {\n      for (const part of message.content) {\n        const filePart = convertImagePartToFilePart(part);\n\n        if (filePart.type === 'file') {\n          downloadableFiles.push(filePart);\n        }\n      }\n    }\n\n    if (message.role === 'tool') {\n      for (const part of message.content) {\n        if (part.type !== 'tool-result') {\n          continue;\n        }\n\n        if (part.output.type !== 'content') {\n          continue;\n        }\n\n        for (const contentPart of part.output.value) {\n          if (contentPart.type === 'file') {\n            downloadableFiles.push(contentPart);\n          }\n        }\n      }\n    }\n\n    if (message.role === 'assistant' && Array.isArray(message.content)) {\n      for (const part of message.content) {\n        if (part.type !== 'tool-result') {\n          continue;\n        }\n        if (part.output.type !== 'content') {\n          continue;\n        }\n        for (const contentPart of part.output.value) {\n          if (contentPart.type === 'file') {\n            downloadableFiles.push(contentPart);\n          }\n        }\n      }\n    }\n  }\n\n  const plannedDownloads = downloadableFiles\n    .map((part): ConvertedFile => {\n      const mediaType = part.mediaType;\n      const { data } = convertToLanguageModelV4FilePart(part.data);\n      return { mediaType, data };\n    })\n    .filter((part): part is UrlTaggedFile => part.data.type === 'url')\n    .map(part => ({\n      url: part.data.url,\n      isUrlSupportedByModel:\n        part.mediaType != null &&\n        isUrlSupported({\n          url: part.data.url.toString(),\n          mediaType: part.mediaType,\n          supportedUrls,\n        }),\n    }));\n  // download in parallel:\n  const downloadedFiles = await download(plannedDownloads);\n\n  return Object.fromEntries(\n    downloadedFiles\n      .map((file, index) =>\n        file == null\n          ? null\n          : [\n              plannedDownloads[index].url.toString(),\n              { data: file.data, mediaType: file.mediaType },\n            ],\n      )\n      .filter(file => file != null),\n  );\n}\n\n/**\n * Convert part of a user message to a LanguageModelV4Part.\n *\n * @param part - The part to convert.\n * @param downloadedAssets - A map of URLs to their downloaded data. Only\n * available if the model does not support URLs, null otherwise.\n * @returns The converted part.\n */\nfunction convertPartToLanguageModelPart(\n  part: TextPart | FilePart,\n  downloadedAssets: Record<\n    string,\n    { mediaType: string | undefined; data: Uint8Array }\n  >,\n): LanguageModelV4TextPart | LanguageModelV4FilePart {\n  if (part.type === 'text') {\n    return {\n      type: 'text',\n      text: part.text,\n      providerOptions: part.providerOptions,\n    };\n  }\n\n  const { data: normalizedData, mediaType: dataUrlMediaType } =\n    convertToLanguageModelV4FilePart(part.data);\n\n  let mediaType: string | undefined = dataUrlMediaType ?? part.mediaType;\n  let data: LanguageModelV4FilePart['data'] = normalizedData;\n\n  if (data.type === 'url') {\n    const downloadedFile = downloadedAssets[data.url.toString()];\n    if (downloadedFile) {\n      data = { type: 'data', data: downloadedFile.data };\n      if (\n        downloadedFile.mediaType != null &&\n        (mediaType == null || !isFullMediaType(mediaType))\n      ) {\n        mediaType = downloadedFile.mediaType;\n      }\n    }\n  }\n\n  if (\n    data.type === 'data' &&\n    (data.data instanceof Uint8Array || typeof data.data === 'string')\n  ) {\n    const imageMediaType = detectMediaType({\n      data: data.data,\n      topLevelType: 'image',\n    });\n    if (imageMediaType != null) {\n      mediaType = imageMediaType;\n    }\n  }\n\n  if (mediaType == null) {\n    throw new Error(`Media type is missing for file part`);\n  }\n\n  return {\n    type: 'file',\n    mediaType,\n    filename: part.filename,\n    data,\n    providerOptions: part.providerOptions,\n  };\n}\n\nexport function mapToolResultOutput({\n  output,\n  // `provider` is only needed here to convert legacy \"file-id\" and \"image-file-id\" types to provider references, in case they are using string ID values.\n  // TODO: remove in v8 when \"file-id\" and \"image-file-id\" types are removed\n  provider,\n  warnings = [],\n  downloadedAssets,\n}: {\n  output: ToolResultOutput;\n  provider?: string;\n  warnings?: Warning[];\n  downloadedAssets: Record<\n    string,\n    { mediaType: string | undefined; data: Uint8Array }\n  >;\n}): LanguageModelV4ToolResultOutput {\n  if (output.type !== 'content') {\n    return output;\n  }\n\n  return {\n    type: 'content',\n    value: output.value.map(item => {\n      switch (item.type) {\n        case 'file': {\n          const convertedPart = convertPartToLanguageModelPart(\n            item,\n            downloadedAssets,\n          );\n\n          if (convertedPart.type !== 'file') {\n            throw new Error(\n              'Expected tool result file content to convert to file.',\n            );\n          }\n\n          return convertedPart;\n        }\n        case 'file-data': {\n          warnings.push({\n            type: 'deprecated',\n            setting: '\"tool-result\" content of type \"file-data\"',\n            message: `The \"file-data\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'data', data } instead.`,\n          });\n          return {\n            type: 'file' as const,\n            data: { type: 'data' as const, data: item.data },\n            filename: item.filename,\n            mediaType: item.mediaType,\n            providerOptions: item.providerOptions,\n          };\n        }\n        case 'file-url': {\n          const mediaType = item.mediaType ?? getMediaTypeFromUrl(item.url);\n          let message = `The \"file-url\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'url', url } instead.`;\n          if (!item.mediaType) {\n            const inferenceSuffix =\n              mediaType === 'application/octet-stream'\n                ? `Unable to infer media type from URL. Defaulting to 'application/octet-stream'.`\n                : `Inferred media type '${mediaType}' from URL.`;\n            message = `The \"file-url\" tool result content part with URL \"${item.url}\" is missing a \"mediaType\". ${inferenceSuffix} ${message}`;\n          }\n          warnings.push({\n            type: 'deprecated',\n            setting: '\"tool-result\" content of type \"file-url\"',\n            message,\n          });\n          return {\n            type: 'file' as const,\n            data: { type: 'url' as const, url: new URL(item.url) },\n            mediaType,\n            providerOptions: item.providerOptions,\n          };\n        }\n        case 'file-id': {\n          warnings.push({\n            type: 'deprecated',\n            setting: '\"tool-result\" content of type \"file-id\"',\n            message: `The \"file-id\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`,\n          });\n          return {\n            type: 'file' as const,\n            data: {\n              type: 'reference' as const,\n              reference: convertFileIdToProviderReference({\n                fileId: item.fileId,\n                provider,\n              }),\n            },\n            mediaType: 'application',\n            providerOptions: item.providerOptions,\n          };\n        }\n        case 'file-reference': {\n          warnings.push({\n            type: 'deprecated',\n            setting: '\"tool-result\" content of type \"file-reference\"',\n            message: `The \"file-reference\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`,\n          });\n          return {\n            type: 'file' as const,\n            data: {\n              type: 'reference' as const,\n              reference: item.providerReference,\n            },\n            mediaType: 'application',\n            providerOptions: item.providerOptions,\n          };\n        }\n        // The \"image-*\" types are legacy and deprecated.\n        // TODO: remove migration in v8 in combination with the removal of these types from the provider utils.\n        case 'image-data': {\n          warnings.push({\n            type: 'deprecated',\n            setting: '\"tool-result\" content of type \"image-data\"',\n            message: `The \"image-data\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'data', data } instead.`,\n          });\n          return {\n            type: 'file' as const,\n            data: { type: 'data' as const, data: item.data },\n            mediaType: item.mediaType,\n            providerOptions: item.providerOptions,\n          };\n        }\n        case 'image-url': {\n          warnings.push({\n            type: 'deprecated',\n            setting: '\"tool-result\" content of type \"image-url\"',\n            message: `The \"image-url\" type for tool result content is deprecated. Use the \"file\" type with mediaType 'image' (or a specific image/* subtype) and { type: 'url', url } instead.`,\n          });\n          return {\n            type: 'file' as const,\n            data: { type: 'url' as const, url: new URL(item.url) },\n            mediaType: 'image',\n            providerOptions: item.providerOptions,\n          };\n        }\n        case 'image-file-id': {\n          warnings.push({\n            type: 'deprecated',\n            setting: '\"tool-result\" content of type \"image-file-id\"',\n            message: `The \"image-file-id\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`,\n          });\n          return {\n            type: 'file' as const,\n            data: {\n              type: 'reference' as const,\n              reference: convertFileIdToProviderReference({\n                fileId: item.fileId,\n                provider,\n              }),\n            },\n            mediaType: 'image',\n            providerOptions: item.providerOptions,\n          };\n        }\n        case 'image-file-reference': {\n          warnings.push({\n            type: 'deprecated',\n            setting: '\"tool-result\" content of type \"image-file-reference\"',\n            message: `The \"image-file-reference\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`,\n          });\n          return {\n            type: 'file' as const,\n            data: {\n              type: 'reference' as const,\n              reference: item.providerReference,\n            },\n            mediaType: 'image',\n            providerOptions: item.providerOptions,\n          };\n        }\n        default:\n          return item;\n      }\n    }),\n  };\n}\n\nfunction convertFileIdToProviderReference({\n  fileId,\n  provider,\n}: {\n  fileId: string | Record<string, string>;\n  provider?: string;\n}): Record<string, string> {\n  if (typeof fileId === 'object') {\n    return fileId;\n  }\n\n  if (provider == null) {\n    throw new Error(\n      'Cannot convert string fileId to provider reference without a provider ID. ' +\n        'Use a Record<string, string> fileId or switch to the file-reference type.',\n    );\n  }\n\n  return { [provider]: fileId };\n}\n\n// Temporary private helper (see below).\nconst URL_EXTENSION_TO_MEDIA_TYPE: Record<string, string> = {\n  jpg: 'image/jpeg',\n  jpeg: 'image/jpeg',\n  png: 'image/png',\n  gif: 'image/gif',\n  webp: 'image/webp',\n  svg: 'image/svg+xml',\n  avif: 'image/avif',\n  heic: 'image/heic',\n  bmp: 'image/bmp',\n  tiff: 'image/tiff',\n  tif: 'image/tiff',\n  pdf: 'application/pdf',\n  mp4: 'video/mp4',\n  webm: 'video/webm',\n  mp3: 'audio/mpeg',\n  wav: 'audio/wav',\n  ogg: 'audio/ogg',\n};\n\n/*\n * Attempts to infer an IANA media type from the file extension in a URL's\n * pathname. Returns `fallbackMediaType` when the extension is absent,\n * unrecognized, or the URL cannot be parsed.\n *\n * Temporary private helper as a best-effort solution for missing media types on \"file-url\" content parts.\n */\nfunction getMediaTypeFromUrl(\n  url: string,\n  fallbackMediaType = 'application/octet-stream',\n): string {\n  try {\n    const pathname = new URL(url).pathname;\n    const fileExtension = pathname.split('.').pop()?.toLowerCase();\n    if (\n      fileExtension &&\n      Object.hasOwn(URL_EXTENSION_TO_MEDIA_TYPE, fileExtension)\n    ) {\n      return URL_EXTENSION_TO_MEDIA_TYPE[fileExtension];\n    }\n  } catch {\n    // ignore URL parse errors\n  }\n  return fallbackMediaType;\n}\n","import {\n  cancelResponseBody,\n  DownloadError,\n  readResponseWithSizeLimit,\n  DEFAULT_MAX_DOWNLOAD_SIZE,\n  fetchWithValidatedRedirects,\n  withUserAgentSuffix,\n  getRuntimeEnvironmentUserAgent,\n} from '@ai-sdk/provider-utils';\nimport { VERSION } from '../../version';\n\n/**\n * Download a file from a URL.\n *\n * @param url - The URL to download from.\n * @param maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.\n * @param abortSignal - An optional abort signal to cancel the download.\n * @returns The downloaded data and media type.\n *\n * @throws DownloadError if the download fails or exceeds maxBytes.\n */\nexport const download = async ({\n  url,\n  maxBytes,\n  abortSignal,\n}: {\n  url: URL;\n  maxBytes?: number;\n  abortSignal?: AbortSignal;\n}) => {\n  const urlText = url.toString();\n  try {\n    const headers = withUserAgentSuffix(\n      {},\n      `ai-sdk/${VERSION}`,\n      getRuntimeEnvironmentUserAgent(),\n    );\n\n    const response = await fetchWithValidatedRedirects({\n      url: urlText,\n      headers,\n      abortSignal,\n    });\n\n    if (!response.ok) {\n      // Release the connection before rejecting so an error status from an\n      // attacker-controlled origin cannot leak open sockets.\n      await cancelResponseBody(response);\n      throw new DownloadError({\n        url: urlText,\n        statusCode: response.status,\n        statusText: response.statusText,\n      });\n    }\n\n    const data = await readResponseWithSizeLimit({\n      response,\n      url: urlText,\n      maxBytes: maxBytes ?? DEFAULT_MAX_DOWNLOAD_SIZE,\n    });\n\n    return {\n      data,\n      mediaType: response.headers.get('content-type') ?? undefined,\n    };\n  } catch (error) {\n    if (DownloadError.isInstance(error)) {\n      throw error;\n    }\n\n    throw new DownloadError({ url: urlText, cause: error });\n  }\n};\n","declare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n  typeof __PACKAGE_VERSION__ !== 'undefined'\n    ? __PACKAGE_VERSION__\n    : '0.0.0-test';\n","import { download as originalDownload } from './download';\n\n/**\n * Experimental. Can change in patch versions without warning.\n *\n * Download function. Called with the array of URLs and a boolean indicating\n * whether the URL is supported by the model.\n *\n * The download function can decide for each URL:\n * - to return null (which means that the URL should be passed to the model)\n * - to download the asset and return the data (incl. retries, authentication, etc.)\n *\n * Should throw DownloadError if the download fails.\n *\n * Should return an array of objects sorted by the order of the requested downloads.\n * For each object, the data should be a Uint8Array if the URL was downloaded.\n * For each object, the mediaType should be the media type of the downloaded asset.\n * For each object, the data should be null if the URL should be passed through as is.\n */\nexport type DownloadFunction = (\n  options: Array<{\n    url: URL;\n    isUrlSupportedByModel: boolean;\n  }>,\n) => PromiseLike<\n  Array<{\n    data: Uint8Array;\n    mediaType: string | undefined;\n  } | null>\n>;\n\n/**\n * Default download function.\n * Downloads the file if it is not supported by the model.\n */\nexport const createDefaultDownloadFunction =\n  (download: typeof originalDownload = originalDownload): DownloadFunction =>\n  requestedDownloads =>\n    Promise.all(\n      requestedDownloads.map(async requestedDownload =>\n        requestedDownload.isUrlSupportedByModel\n          ? null\n          : await download(requestedDownload),\n      ),\n    );\n","/**\n * Deeply merges two objects together.\n * - Properties from the `overrides` object override those in the `base` object with the same key.\n * - For nested objects, the merge is performed recursively (deep merge).\n * - Arrays are replaced, not merged.\n * - Primitive values are replaced.\n * - If both `base` and `overrides` are undefined, returns undefined.\n * - If one of `base` or `overrides` is undefined, returns the other.\n *\n * @param base The target object to merge into\n * @param overrides The source object to merge from\n * @returns A new object with the merged properties, or undefined if both inputs are undefined\n */\nexport function mergeObjects<T extends object, U extends object>(\n  base: T | undefined,\n  overrides: U | undefined,\n): (T & U) | T | U | undefined {\n  // If both inputs are undefined, return undefined\n  if (base === undefined && overrides === undefined) {\n    return undefined;\n  }\n\n  // If target is undefined, return source\n  if (base === undefined) {\n    return overrides;\n  }\n\n  // If source is undefined, return target\n  if (overrides === undefined) {\n    return base;\n  }\n\n  // Create a new object to avoid mutating the inputs\n  const result = { ...base } as T & U;\n\n  // Iterate through all keys in the source object\n  for (const key in overrides) {\n    // Skip prototype-polluting keys when merging untrusted input\n    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n      continue;\n    }\n\n    if (Object.prototype.hasOwnProperty.call(overrides, key)) {\n      const overridesValue = overrides[key];\n\n      // Skip if the overrides value is undefined\n      if (overridesValue === undefined) continue;\n\n      // Get the base value if it exists\n      const baseValue =\n        key in base ? base[key as unknown as keyof T] : undefined;\n\n      // Check if both values are objects that can be deeply merged\n      const isSourceObject =\n        overridesValue !== null &&\n        typeof overridesValue === 'object' &&\n        !Array.isArray(overridesValue) &&\n        !(overridesValue instanceof Date) &&\n        !(overridesValue instanceof RegExp);\n\n      const isTargetObject =\n        baseValue !== null &&\n        baseValue !== undefined &&\n        typeof baseValue === 'object' &&\n        !Array.isArray(baseValue) &&\n        !(baseValue instanceof Date) &&\n        !(baseValue instanceof RegExp);\n\n      // If both values are mergeable objects, merge them recursively\n      if (isSourceObject && isTargetObject) {\n        result[key as keyof (T & U)] = mergeObjects(\n          baseValue as object,\n          overridesValue as object,\n        ) as any;\n      } else {\n        // For primitives, arrays, or when one value is not a mergeable object,\n        // simply override with the source value\n        result[key as keyof (T & U)] = overridesValue as any;\n      }\n    }\n  }\n\n  return result;\n}\n","import type { LanguageModelV4FilePart } from '@ai-sdk/provider';\nimport {\n  isBuffer,\n  isProviderReference,\n  type DataContent,\n  type FilePart,\n  type ProviderReference,\n} from '@ai-sdk/provider-utils';\nimport { InvalidDataContentError } from './invalid-data-content-error';\nimport { splitDataUrl } from './split-data-url';\n\ntype TaggedFileData = Extract<FilePart['data'], { type: string }>;\n\nfunction isTaggedFileData(value: unknown): value is TaggedFileData {\n  if (typeof value !== 'object' || value === null) return false;\n  const type = (value as { type?: unknown }).type;\n  return (\n    type === 'data' || type === 'url' || type === 'reference' || type === 'text'\n  );\n}\n\ntype ConvertResult = {\n  data: LanguageModelV4FilePart['data'];\n  mediaType: string | undefined;\n};\n\nfunction convertUrlToFilePartData(url: URL): ConvertResult {\n  if (url.protocol === 'data:') {\n    const { mediaType, base64Content } = splitDataUrl(url.toString());\n\n    if (mediaType == null || base64Content == null) {\n      throw new InvalidDataContentError({\n        content: url,\n        message: `Invalid data URL format in content ${url.toString()}`,\n      });\n    }\n\n    return { data: { type: 'data', data: base64Content }, mediaType };\n  }\n\n  return { data: { type: 'url', url }, mediaType: undefined };\n}\n\nfunction convertInlineDataToFilePartData(content: DataContent): ConvertResult {\n  if (content instanceof Uint8Array) {\n    return { data: { type: 'data', data: content }, mediaType: undefined };\n  }\n  if (content instanceof ArrayBuffer) {\n    return {\n      data: { type: 'data', data: new Uint8Array(content) },\n      mediaType: undefined,\n    };\n  }\n  if (isBuffer(content)) {\n    return {\n      data: { type: 'data', data: new Uint8Array(content) },\n      mediaType: undefined,\n    };\n  }\n  return {\n    data: { type: 'data', data: content as string },\n    mediaType: undefined,\n  };\n}\n\n/**\n * Converts any legacy-or-tagged top-level `FilePart.data` /\n * `ReasoningFilePart.data` value into the tagged v4 provider prompt shape.\n *\n * Returns the tagged `data` together with the resolved mediaType (extracted\n * from a `data:` URL when applicable).\n */\nexport function convertToLanguageModelV4FilePart(\n  content: FilePart['data'],\n): ConvertResult {\n  if (isTaggedFileData(content)) {\n    switch (content.type) {\n      case 'data':\n        if (\n          typeof content.data === 'string' &&\n          content.data.startsWith('data:')\n        ) {\n          throw new InvalidDataContentError({\n            content: content.data,\n            message:\n              'Data URLs are not valid inline data. Pass them as { type: \"url\", url } instead.',\n          });\n        }\n        return convertInlineDataToFilePartData(content.data);\n      case 'url':\n        return convertUrlToFilePartData(content.url);\n      case 'reference':\n        return {\n          data: { type: 'reference', reference: content.reference },\n          mediaType: undefined,\n        };\n      case 'text':\n        return {\n          data: { type: 'text', text: content.text },\n          mediaType: undefined,\n        };\n    }\n  }\n\n  if (content instanceof URL) {\n    return convertUrlToFilePartData(content);\n  }\n\n  if (typeof content === 'string') {\n    try {\n      return convertUrlToFilePartData(new URL(content));\n    } catch {\n      return convertInlineDataToFilePartData(content);\n    }\n  }\n\n  if (isProviderReference(content)) {\n    return {\n      data: { type: 'reference', reference: content as ProviderReference },\n      mediaType: undefined,\n    };\n  }\n\n  return convertInlineDataToFilePartData(content as DataContent);\n}\n","export function splitDataUrl(dataUrl: string): {\n  mediaType: string | undefined;\n  base64Content: string | undefined;\n} {\n  try {\n    const [header, base64Content] = dataUrl.split(',');\n    return {\n      mediaType: header.split(';')[0].split(':')[1],\n      base64Content,\n    };\n  } catch {\n    return {\n      mediaType: undefined,\n      base64Content: undefined,\n    };\n  }\n}\n","import { getErrorMessage, type JSONValue } from '@ai-sdk/provider';\nimport {\n  parseJSON,\n  type Tool,\n  type ToolResultOutput,\n} from '@ai-sdk/provider-utils';\n\nexport async function createToolModelOutput({\n  toolCallId,\n  input,\n  output,\n  tool,\n  errorMode,\n}: {\n  toolCallId: string;\n  input: unknown;\n  output: unknown;\n  tool: Tool | undefined;\n  errorMode: 'none' | 'text' | 'json';\n}): Promise<ToolResultOutput> {\n  if (errorMode === 'text') {\n    return { type: 'error-text', value: getErrorMessage(output) };\n  } else if (errorMode === 'json') {\n    return { type: 'error-json', value: await toJSONValue(output) };\n  }\n\n  if (tool?.toModelOutput) {\n    return await tool.toModelOutput({ toolCallId, input, output });\n  }\n\n  return typeof output === 'string'\n    ? { type: 'text', value: output }\n    : { type: 'json', value: await toJSONValue(output) };\n}\n\nasync function toJSONValue(value: unknown): Promise<JSONValue> {\n  if (value === undefined) {\n    return null;\n  }\n\n  const serialized = JSON.stringify(value);\n  return serialized === undefined\n    ? null\n    : await parseJSON({ text: serialized });\n}\n","import { InvalidArgumentError } from '../error/invalid-argument-error';\nimport type { LanguageModelCallOptions } from './language-model-call-options';\n\n/**\n * Validates model call options and returns a new object with normalized values.\n */\nexport function prepareLanguageModelCallOptions({\n  maxOutputTokens,\n  temperature,\n  topP,\n  topK,\n  presencePenalty,\n  frequencyPenalty,\n  seed,\n  stopSequences,\n  reasoning,\n}: LanguageModelCallOptions): LanguageModelCallOptions {\n  if (maxOutputTokens != null) {\n    if (!Number.isInteger(maxOutputTokens)) {\n      throw new InvalidArgumentError({\n        parameter: 'maxOutputTokens',\n        value: maxOutputTokens,\n        message: 'maxOutputTokens must be an integer',\n      });\n    }\n\n    if (maxOutputTokens < 1) {\n      throw new InvalidArgumentError({\n        parameter: 'maxOutputTokens',\n        value: maxOutputTokens,\n        message: 'maxOutputTokens must be >= 1',\n      });\n    }\n  }\n\n  if (temperature != null) {\n    if (typeof temperature !== 'number') {\n      throw new InvalidArgumentError({\n        parameter: 'temperature',\n        value: temperature,\n        message: 'temperature must be a number',\n      });\n    }\n  }\n\n  if (topP != null) {\n    if (typeof topP !== 'number') {\n      throw new InvalidArgumentError({\n        parameter: 'topP',\n        value: topP,\n        message: 'topP must be a number',\n      });\n    }\n  }\n\n  if (topK != null) {\n    if (typeof topK !== 'number') {\n      throw new InvalidArgumentError({\n        parameter: 'topK',\n        value: topK,\n        message: 'topK must be a number',\n      });\n    }\n  }\n\n  if (presencePenalty != null) {\n    if (typeof presencePenalty !== 'number') {\n      throw new InvalidArgumentError({\n        parameter: 'presencePenalty',\n        value: presencePenalty,\n        message: 'presencePenalty must be a number',\n      });\n    }\n  }\n\n  if (frequencyPenalty != null) {\n    if (typeof frequencyPenalty !== 'number') {\n      throw new InvalidArgumentError({\n        parameter: 'frequencyPenalty',\n        value: frequencyPenalty,\n        message: 'frequencyPenalty must be a number',\n      });\n    }\n  }\n\n  if (seed != null) {\n    if (!Number.isInteger(seed)) {\n      throw new InvalidArgumentError({\n        parameter: 'seed',\n        value: seed,\n        message: 'seed must be an integer',\n      });\n    }\n  }\n\n  return {\n    maxOutputTokens,\n    temperature,\n    topP,\n    topK,\n    presencePenalty,\n    frequencyPenalty,\n    stopSequences,\n    seed,\n    reasoning,\n  };\n}\n","import type { LanguageModelV4ToolChoice } from '@ai-sdk/provider';\nimport type { ToolChoice } from '../types/language-model';\n\nexport function prepareToolChoice({\n  toolChoice,\n}: {\n  // use of any because it doesn't matter for tool choice preparation\n  toolChoice: ToolChoice<any> | undefined;\n}): LanguageModelV4ToolChoice {\n  return toolChoice == null\n    ? { type: 'auto' }\n    : typeof toolChoice === 'string'\n      ? { type: toolChoice }\n      : { type: 'tool' as const, toolName: toolChoice.toolName as string };\n}\n","import type {\n  LanguageModelV4FunctionTool,\n  LanguageModelV4ProviderTool,\n} from '@ai-sdk/provider';\nimport {\n  asSchema,\n  type Experimental_SandboxSession as SandboxSession,\n  type InferToolSetContext,\n  type Tool,\n  type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type { ToolOrder } from '../generate-text/tool-order';\nimport { isNonEmptyObject } from '../util/is-non-empty-object';\n\nexport async function prepareTools<TOOLS extends ToolSet>({\n  tools,\n  toolOrder,\n  toolsContext = {} as InferToolSetContext<TOOLS>,\n  experimental_sandbox: sandbox,\n}: {\n  tools: TOOLS | undefined;\n  toolOrder?: ToolOrder<TOOLS>;\n  toolsContext?: InferToolSetContext<TOOLS>;\n  experimental_sandbox?: SandboxSession;\n}): Promise<\n  Array<LanguageModelV4FunctionTool | LanguageModelV4ProviderTool> | undefined\n> {\n  if (!isNonEmptyObject(tools)) {\n    return undefined;\n  }\n\n  const languageModelTools: Array<\n    LanguageModelV4FunctionTool | LanguageModelV4ProviderTool\n  > = [];\n  for (const [name, tool] of orderToolEntries({ tools, toolOrder })) {\n    const toolType = tool.type;\n\n    switch (toolType) {\n      case undefined:\n      case 'dynamic':\n      case 'function': {\n        const description = resolveToolDescription({\n          tool,\n          toolName: name,\n          toolsContext,\n          experimental_sandbox: sandbox,\n        });\n        const providerOptions = tool.providerOptions;\n        const inputExamples = tool.inputExamples;\n        const strict = tool.strict;\n\n        languageModelTools.push({\n          type: 'function' as const,\n          name,\n          inputSchema: await asSchema(tool.inputSchema).jsonSchema,\n          ...(description != null ? { description } : {}),\n          ...(inputExamples != null ? { inputExamples } : {}),\n          ...(providerOptions != null ? { providerOptions } : {}),\n          ...(strict != null ? { strict } : {}),\n        });\n        break;\n      }\n      case 'provider': {\n        languageModelTools.push({\n          type: 'provider' as const,\n          name,\n          id: tool.id,\n          args: tool.args,\n        });\n        break;\n      }\n      default: {\n        const exhaustiveCheck: never = toolType as never;\n        throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);\n      }\n    }\n  }\n\n  return languageModelTools;\n}\n\nfunction orderToolEntries<TOOLS extends ToolSet>({\n  tools,\n  toolOrder,\n}: {\n  tools: TOOLS;\n  toolOrder?: ToolOrder<TOOLS>;\n}): Array<[string, Tool]> {\n  if (toolOrder == null) {\n    return Object.entries(tools);\n  }\n\n  const toolEntries = Object.entries(tools);\n\n  const orderedTools = toolEntries\n    .filter(([name]) => toolOrder.includes(name))\n    .sort(\n      ([nameA], [nameB]) => toolOrder.indexOf(nameA) - toolOrder.indexOf(nameB),\n    );\n\n  const unorderedTools = toolEntries\n    .filter(([name]) => !toolOrder.includes(name))\n    .sort(([nameA], [nameB]) => (nameA < nameB ? -1 : nameA > nameB ? 1 : 0));\n\n  return [...orderedTools, ...unorderedTools];\n}\n\nexport function resolveToolDescription<TOOLS extends ToolSet>({\n  tool,\n  toolName,\n  toolsContext,\n  experimental_sandbox: sandbox,\n}: {\n  tool: Tool;\n  toolName: string;\n  toolsContext: InferToolSetContext<TOOLS>;\n  experimental_sandbox?: SandboxSession;\n}): string | undefined {\n  return tool.description === undefined\n    ? undefined\n    : typeof tool.description === 'string'\n      ? tool.description\n      : tool.description({\n          context: toolsContext[toolName as keyof InferToolSetContext<TOOLS>],\n          experimental_sandbox: sandbox,\n        });\n}\n","export function isNonEmptyObject(\n  object: Record<string, unknown> | undefined | null,\n): object is Record<string, unknown> {\n  return object != null && Object.keys(object).length > 0;\n}\n","import type { ToolSet } from '@ai-sdk/provider-utils';\n\n/**\n * Timeout configuration for API calls. Can be specified as:\n * - A number representing milliseconds\n * - An object with `totalMs` property for the total timeout in milliseconds\n * - An object with `stepMs` property for the timeout of each step in milliseconds\n * - An object with `firstChunkMs` property for the timeout until the first content chunk of each step (streaming only)\n * - An object with `chunkMs` property for the timeout between content chunks (streaming only)\n * - An object with `toolMs` property for the default timeout for all tool executions\n * - An object with `tools` property for per-tool timeout overrides using `{toolName}Ms` keys\n */\nexport type TimeoutConfiguration<TOOLS extends ToolSet> =\n  | number\n  | {\n      totalMs?: number;\n      stepMs?: number;\n      firstChunkMs?: number;\n      chunkMs?: number;\n      toolMs?: number;\n      tools?: Partial<Record<`${keyof TOOLS & string}Ms`, number>>;\n    };\n\n/**\n * Extracts the total timeout value in milliseconds from a TimeoutConfiguration.\n *\n * @param timeout - The timeout configuration.\n * @returns The total timeout in milliseconds, or undefined if no timeout is configured.\n */\nexport function getTotalTimeoutMs(\n  timeout: TimeoutConfiguration<any> | undefined,\n): number | undefined {\n  if (timeout == null) {\n    return undefined;\n  }\n  if (typeof timeout === 'number') {\n    return timeout;\n  }\n  return timeout.totalMs;\n}\n\n/**\n * Extracts the step timeout value in milliseconds from a TimeoutConfiguration.\n *\n * @param timeout - The timeout configuration.\n * @returns The step timeout in milliseconds, or undefined if no step timeout is configured.\n */\nexport function getStepTimeoutMs(\n  timeout: TimeoutConfiguration<any> | undefined,\n): number | undefined {\n  if (timeout == null || typeof timeout === 'number') {\n    return undefined;\n  }\n  return timeout.stepMs;\n}\n\n/**\n * Extracts the first chunk timeout value in milliseconds from a TimeoutConfiguration.\n * This timeout is for streaming only - it aborts if no content chunk is received within the specified duration.\n *\n * @param timeout - The timeout configuration.\n * @returns The first chunk timeout in milliseconds, or undefined if no first chunk timeout is configured.\n */\nexport function getFirstChunkTimeoutMs(\n  timeout: TimeoutConfiguration<any> | undefined,\n): number | undefined {\n  if (timeout == null || typeof timeout === 'number') {\n    return undefined;\n  }\n  return timeout.firstChunkMs;\n}\n\n/**\n * Extracts the chunk timeout value in milliseconds from a TimeoutConfiguration.\n * This timeout is for streaming only - it aborts if no new content chunk is received within the specified duration.\n *\n * @param timeout - The timeout configuration.\n * @returns The chunk timeout in milliseconds, or undefined if no chunk timeout is configured.\n */\nexport function getChunkTimeoutMs(\n  timeout: TimeoutConfiguration<any> | undefined,\n): number | undefined {\n  if (timeout == null || typeof timeout === 'number') {\n    return undefined;\n  }\n  return timeout.chunkMs;\n}\n\nexport function getToolTimeoutMs<TOOLS extends ToolSet>(\n  timeout: TimeoutConfiguration<TOOLS> | undefined,\n  toolName: keyof TOOLS & string,\n): number | undefined {\n  if (timeout == null || typeof timeout === 'number') {\n    return undefined;\n  }\n\n  return timeout.tools?.[`${toolName}Ms`] ?? timeout.toolMs;\n}\n\n/**\n * Request-facing controls. These settings affect transport, retries,\n * cancellation, headers, and timeout – not model generation behavior.\n */\nexport type RequestOptions<TOOLS extends ToolSet = ToolSet> = {\n  /**\n   * Maximum number of retries. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional HTTP headers to be sent with the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string | undefined>;\n\n  /**\n   * Timeout configuration for the request.\n   */\n  timeout?: TimeoutConfiguration<TOOLS>;\n};\n","import { InvalidPromptError } from '@ai-sdk/provider';\nimport {\n  asArray,\n  safeValidateTypes,\n  type ModelMessage,\n} from '@ai-sdk/provider-utils';\nimport { z } from '../util/zod';\nimport { modelMessageSchema } from './message';\nimport type { Instructions, Prompt } from './prompt';\n\nexport type StandardizedPrompt = {\n  /**\n   * Instructions.\n   */\n  instructions: Instructions | undefined;\n\n  /**\n   * Messages.\n   */\n  messages: ModelMessage[];\n};\n\n/**\n * Converts a prompt input into a standardized prompt with validated model\n * messages.\n *\n * @param prompt - The prompt definition to standardize.\n * Set `allowSystemInMessages` to true to allow system messages in the\n * `prompt` or `messages` fields. System messages in the `instructions`\n * option are always allowed.\n * @returns The standardized prompt.\n * @throws {InvalidPromptError} When the prompt is invalid.\n */\nexport async function standardizePrompt({\n  allowSystemInMessages = false,\n  system,\n  instructions = system,\n  prompt,\n  messages,\n}: Prompt): Promise<StandardizedPrompt> {\n  if (prompt == null && messages == null) {\n    throw new InvalidPromptError({\n      prompt,\n      message: 'prompt or messages must be defined',\n    });\n  }\n\n  if (prompt != null && messages != null) {\n    throw new InvalidPromptError({\n      prompt,\n      message: 'prompt and messages cannot be defined at the same time',\n    });\n  }\n\n  // validate that instructions is a string or a SystemModelMessage\n  if (\n    typeof instructions !== 'string' &&\n    !asArray(instructions).every(message => message.role === 'system')\n  ) {\n    throw new InvalidPromptError({\n      prompt,\n      message:\n        'instructions must be a string, SystemModelMessage, or array of SystemModelMessage',\n    });\n  }\n\n  if (prompt != null && typeof prompt === 'string') {\n    messages = [{ role: 'user', content: prompt }];\n  } else if (prompt != null && Array.isArray(prompt)) {\n    messages = prompt;\n  } else if (messages == null) {\n    throw new InvalidPromptError({\n      prompt,\n      message: 'prompt or messages must be defined',\n    });\n  }\n\n  if (messages.length === 0) {\n    throw new InvalidPromptError({\n      prompt,\n      message: 'messages must not be empty',\n    });\n  }\n\n  if (\n    !allowSystemInMessages &&\n    messages.some(message => message.role === 'system')\n  ) {\n    throw new InvalidPromptError({\n      prompt,\n      message:\n        'System messages are not allowed in the prompt or messages fields. Use the instructions option instead.',\n    });\n  }\n\n  const validationResult = await safeValidateTypes({\n    value: messages,\n    schema: z.array(modelMessageSchema),\n  });\n\n  if (!validationResult.success) {\n    throw new InvalidPromptError({\n      prompt,\n      message: 'The messages do not match the ModelMessage[] schema.',\n      cause: validationResult.error,\n    });\n  }\n\n  return { messages, instructions };\n}\n","import {\n  array,\n  boolean,\n  custom,\n  discriminatedUnion,\n  enum as enumType,\n  instanceof as instanceOf,\n  lazy,\n  literal,\n  looseObject,\n  never,\n  null as nullType,\n  number,\n  object,\n  record,\n  string,\n  union,\n  unknown,\n} from 'zod/v4';\n\n// Import individual Zod factories so bundlers can tree-shake the full `z`\n// namespace, which also re-exports every locale.\nexport const z = {\n  array,\n  boolean,\n  custom,\n  discriminatedUnion,\n  enum: enumType,\n  instanceof: instanceOf,\n  lazy,\n  literal,\n  looseObject,\n  never,\n  null: nullType,\n  number,\n  object,\n  record,\n  string,\n  union,\n  unknown,\n};\n\nexport type { ZodType } from 'zod/v4';\n","import type { JSONValue as OriginalJSONValue } from '@ai-sdk/provider';\nimport { z, type ZodType } from '../util/zod';\n\nexport const jsonValueSchema: ZodType<JSONValue> = z.lazy(() =>\n  z.union([\n    z.null(),\n    z.string(),\n    z.number(),\n    z.boolean(),\n    z.record(z.string(), jsonValueSchema.optional()),\n    z.array(jsonValueSchema),\n  ]),\n);\n\nexport type JSONValue = OriginalJSONValue;\n","import type { SharedV4ProviderMetadata } from '@ai-sdk/provider';\nimport { z, type ZodType } from '../util/zod';\nimport { jsonValueSchema } from './json-value';\n\n/**\n * Additional provider-specific metadata that is returned from the provider.\n *\n * This is needed to enable provider-specific functionality that can be\n * fully encapsulated in the provider.\n */\nexport type ProviderMetadata = SharedV4ProviderMetadata;\n\nexport const providerMetadataSchema: ZodType<ProviderMetadata> = z.record(\n  z.string(),\n  z.record(z.string(), jsonValueSchema.optional()),\n);\n","import {\n  isBuffer,\n  type CustomPart,\n  type DataContent,\n  type FilePart,\n  type ImagePart,\n  type ProviderOptions,\n  type ReasoningFilePart,\n  type ReasoningPart,\n  type TextPart,\n  type ToolApprovalRequest,\n  type ToolApprovalResponse,\n  type ToolResultOutput,\n  type ToolResultPart,\n} from '@ai-sdk/provider-utils';\nimport { jsonValueSchema } from '../types/json-value';\nimport { providerMetadataSchema } from '../types/provider-metadata';\nimport { z, type ZodType } from '../util/zod';\n\nconst fileInlineDataSchema: ZodType<DataContent> = z.union([\n  z.string(),\n  z.instanceof(Uint8Array),\n  z.instanceof(ArrayBuffer),\n  z.custom<Buffer>(isBuffer, { message: 'Must be a Buffer' }),\n]);\n\nconst providerReferenceSchema = z.record(z.string(), z.string());\n\n/**\n * @internal\n */\nexport const textPartSchema: ZodType<TextPart> = z.object({\n  type: z.literal('text'),\n  text: z.string(),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n * @deprecated Use `filePartSchema` with `mediaType: 'image'` instead:\n * `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`.\n */\nexport const imagePartSchema: ZodType<ImagePart> = z.object({\n  type: z.literal('image'),\n  image: z.union([\n    fileInlineDataSchema,\n    z.instanceof(URL),\n    providerReferenceSchema,\n  ]),\n  mediaType: z.string().optional(),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\nconst taggedFileDataSchema = z.discriminatedUnion('type', [\n  z.object({ type: z.literal('data'), data: fileInlineDataSchema }),\n  z.object({ type: z.literal('url'), url: z.instanceof(URL) }),\n  z.object({\n    type: z.literal('reference'),\n    reference: providerReferenceSchema,\n  }),\n  z.object({ type: z.literal('text'), text: z.string() }),\n]);\n\nconst taggedReasoningFileDataSchema = z.discriminatedUnion('type', [\n  z.object({ type: z.literal('data'), data: fileInlineDataSchema }),\n  z.object({ type: z.literal('url'), url: z.instanceof(URL) }),\n]);\n\n/**\n * @internal\n */\nexport const filePartSchema: ZodType<FilePart> = z.object({\n  type: z.literal('file'),\n  data: z.union([\n    taggedFileDataSchema,\n    fileInlineDataSchema,\n    z.instanceof(URL),\n    providerReferenceSchema,\n  ]),\n  filename: z.string().optional(),\n  mediaType: z.string(),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n */\nexport const reasoningPartSchema: ZodType<ReasoningPart> = z.object({\n  type: z.literal('reasoning'),\n  text: z.string(),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n */\nexport const customPartSchema: ZodType<CustomPart> = z.object({\n  type: z.literal('custom'),\n  kind: z.string().transform(value => value as `${string}.${string}`),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n */\nexport const reasoningFilePartSchema: ZodType<ReasoningFilePart> = z.object({\n  type: z.literal('reasoning-file'),\n  data: z.union([\n    taggedReasoningFileDataSchema,\n    fileInlineDataSchema,\n    z.instanceof(URL),\n  ]),\n  mediaType: z.string(),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model).\n */\nexport interface ToolCallPart {\n  type: 'tool-call';\n\n  /**\n   * ID of the tool call. This ID is used to match the tool call with the tool result.\n   */\n  toolCallId: string;\n\n  /**\n   * Name of the tool that is being called.\n   */\n  toolName: string;\n\n  /**\n   * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.\n   */\n  input: unknown;\n\n  /**\n   * Additional provider-specific metadata. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerOptions?: ProviderOptions;\n}\n\n/**\n * @internal\n */\nexport const toolCallPartSchema: ZodType<ToolCallPart> = z.object({\n  type: z.literal('tool-call'),\n  toolCallId: z.string(),\n  toolName: z.string(),\n  input: z.unknown(),\n  providerOptions: providerMetadataSchema.optional(),\n  providerExecuted: z.boolean().optional(),\n}) as ZodType<ToolCallPart>; // necessary bc input is optional on Zod type\n\n/**\n * @internal\n */\nexport const outputSchema: ZodType<ToolResultOutput> = z.discriminatedUnion(\n  'type',\n  [\n    z.object({\n      type: z.literal('text'),\n      value: z.string(),\n      providerOptions: providerMetadataSchema.optional(),\n    }),\n    z.object({\n      type: z.literal('json'),\n      value: jsonValueSchema,\n      providerOptions: providerMetadataSchema.optional(),\n    }),\n    z.object({\n      type: z.literal('execution-denied'),\n      reason: z.string().optional(),\n      providerOptions: providerMetadataSchema.optional(),\n    }),\n    z.object({\n      type: z.literal('error-text'),\n      value: z.string(),\n      providerOptions: providerMetadataSchema.optional(),\n    }),\n    z.object({\n      type: z.literal('error-json'),\n      value: jsonValueSchema,\n      providerOptions: providerMetadataSchema.optional(),\n    }),\n    z.object({\n      type: z.literal('content'),\n      value: z.array(\n        z.union([\n          z.object({\n            type: z.literal('text'),\n            text: z.string(),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            type: z.literal('file'),\n            data: taggedFileDataSchema,\n            mediaType: z.string(),\n            filename: z.string().optional(),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            // Deprecated.\n            type: z.literal('file-data'),\n            data: z.string(),\n            mediaType: z.string(),\n            filename: z.string().optional(),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            // Deprecated.\n            type: z.literal('file-url'),\n            url: z.string(),\n            mediaType: z.string().optional(),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            // Deprecated.\n            type: z.literal('file-id'),\n            fileId: z.union([z.string(), z.record(z.string(), z.string())]),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            // Deprecated.\n            type: z.literal('file-reference'),\n            providerReference: z.record(z.string(), z.string()),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            // Deprecated.\n            type: z.literal('image-data'),\n            data: z.string(),\n            mediaType: z.string(),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            // Deprecated.\n            type: z.literal('image-url'),\n            url: z.string(),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            // Deprecated.\n            type: z.literal('image-file-id'),\n            fileId: z.union([z.string(), z.record(z.string(), z.string())]),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            // Deprecated.\n            type: z.literal('image-file-reference'),\n            providerReference: z.record(z.string(), z.string()),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n          z.object({\n            type: z.literal('custom'),\n            providerOptions: providerMetadataSchema.optional(),\n          }),\n        ]),\n      ),\n    }),\n  ],\n);\n\n/**\n * @internal\n */\nexport const toolResultPartSchema: ZodType<ToolResultPart> = z.object({\n  type: z.literal('tool-result'),\n  toolCallId: z.string(),\n  toolName: z.string(),\n  output: outputSchema,\n  providerOptions: providerMetadataSchema.optional(),\n}) as ZodType<ToolResultPart>; // necessary bc result is optional on Zod type\n\n/**\n * @internal\n */\nexport const toolApprovalRequestSchema: ZodType<ToolApprovalRequest> = z.object(\n  {\n    type: z.literal('tool-approval-request'),\n    approvalId: z.string(),\n    toolCallId: z.string(),\n    reason: z.string().optional(),\n  },\n);\n\n/**\n * @internal\n */\nexport const toolApprovalResponseSchema: ZodType<ToolApprovalResponse> =\n  z.object({\n    type: z.literal('tool-approval-response'),\n    approvalId: z.string(),\n    approved: z.boolean(),\n    reason: z.string().optional(),\n  });\n","import type {\n  AssistantModelMessage,\n  ModelMessage,\n  SystemModelMessage,\n  ToolModelMessage,\n  UserModelMessage,\n} from '@ai-sdk/provider-utils';\nimport { providerMetadataSchema } from '../types/provider-metadata';\nimport { z, type ZodType } from '../util/zod';\nimport {\n  customPartSchema,\n  filePartSchema,\n  imagePartSchema,\n  reasoningFilePartSchema,\n  reasoningPartSchema,\n  textPartSchema,\n  toolApprovalRequestSchema,\n  toolCallPartSchema,\n  toolApprovalResponseSchema,\n  toolResultPartSchema,\n} from './content-part';\n\nexport const systemModelMessageSchema: ZodType<SystemModelMessage> = z.object({\n  role: z.literal('system'),\n  content: z.string(),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\nexport const userModelMessageSchema: ZodType<UserModelMessage> = z.object({\n  role: z.literal('user'),\n  content: z.union([\n    z.string(),\n    z.array(z.union([textPartSchema, imagePartSchema, filePartSchema])),\n  ]),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\nexport const assistantModelMessageSchema: ZodType<AssistantModelMessage> =\n  z.object({\n    role: z.literal('assistant'),\n    content: z.union([\n      z.string(),\n      z.array(\n        z.union([\n          textPartSchema,\n          customPartSchema,\n          filePartSchema,\n          reasoningPartSchema,\n          reasoningFilePartSchema,\n          toolCallPartSchema,\n          toolResultPartSchema,\n          toolApprovalRequestSchema,\n        ]),\n      ),\n    ]),\n    providerOptions: providerMetadataSchema.optional(),\n  });\n\nexport const toolModelMessageSchema: ZodType<ToolModelMessage> = z.object({\n  role: z.literal('tool'),\n  content: z.array(z.union([toolResultPartSchema, toolApprovalResponseSchema])),\n  providerOptions: providerMetadataSchema.optional(),\n});\n\nexport const modelMessageSchema: ZodType<ModelMessage> = z.union([\n  systemModelMessageSchema,\n  userModelMessageSchema,\n  assistantModelMessageSchema,\n  toolModelMessageSchema,\n]);\n","import { GatewayAuthenticationError } from '@ai-sdk/gateway';\nimport { AISDKError } from '@ai-sdk/provider';\n\nexport function wrapGatewayError(error: unknown): unknown {\n  if (!GatewayAuthenticationError.isInstance(error)) return error;\n\n  const isProductionEnv = process?.env.NODE_ENV === 'production';\n  const moreInfoURL = 'https://ai-sdk.dev/unauthenticated-ai-gateway';\n\n  if (isProductionEnv) {\n    return new AISDKError({\n      name: 'GatewayError',\n      message: `Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${moreInfoURL}`,\n    });\n  }\n\n  return Object.assign(\n    new Error(`\\u001b[1m\\u001b[31mUnauthenticated request to AI Gateway.\\u001b[0m\n\nTo authenticate, set the \\u001b[33mAI_GATEWAY_API_KEY\\u001b[0m environment variable with your API key.\n\nAlternatively, you can use a provider module instead of the AI Gateway.\n\nLearn more: \\u001b[34m${moreInfoURL}\\u001b[0m\n\n`),\n    { name: 'GatewayAuthenticationError' },\n  );\n}\n","import type {\n  ImageModelV4Usage,\n  JSONObject,\n  LanguageModelV4Usage,\n} from '@ai-sdk/provider';\n\n/**\n * Represents the number of tokens used in a prompt and completion.\n */\nexport type LanguageModelUsage = {\n  /**\n   * The total number of input (prompt) tokens used.\n   */\n  inputTokens: number | undefined;\n\n  /**\n   * Detailed information about the input tokens.\n   */\n  inputTokenDetails: {\n    /**\n     * The number of non-cached input (prompt) tokens used.\n     */\n    noCacheTokens: number | undefined;\n\n    /**\n     * The number of cached input (prompt) tokens read.\n     */\n    cacheReadTokens: number | undefined;\n\n    /**\n     * The number of cached input (prompt) tokens written.\n     */\n    cacheWriteTokens: number | undefined;\n  };\n\n  /**\n   * The number of total output (completion) tokens used.\n   */\n  outputTokens: number | undefined;\n\n  /**\n   * Detailed information about the output tokens.\n   */\n  outputTokenDetails: {\n    /**\n     * The number of text tokens used.\n     */\n    textTokens: number | undefined;\n\n    /**\n     * The number of reasoning tokens used.\n     */\n    reasoningTokens: number | undefined;\n  };\n\n  /**\n   * The total number of tokens used.\n   */\n  totalTokens: number | undefined;\n\n  /**\n   * Raw usage information from the provider.\n   *\n   * This is the usage information in the shape that the provider returns.\n   * It can include additional information that is not part of the standard usage information.\n   */\n  raw?: JSONObject;\n};\n\n/**\n * Represents the number of tokens used in an embedding.\n */\n// TODO replace with EmbeddingModelV4Usage once available in @ai-sdk/provider\nexport type EmbeddingModelUsage = {\n  /**\n   * The number of tokens used in the embedding.\n   */\n  tokens: number;\n};\n\nexport function asLanguageModelUsage(\n  usage: LanguageModelV4Usage,\n): LanguageModelUsage {\n  return {\n    inputTokens: usage.inputTokens.total,\n    inputTokenDetails: {\n      noCacheTokens: usage.inputTokens.noCache,\n      cacheReadTokens: usage.inputTokens.cacheRead,\n      cacheWriteTokens: usage.inputTokens.cacheWrite,\n    },\n    outputTokens: usage.outputTokens.total,\n    outputTokenDetails: {\n      textTokens: usage.outputTokens.text,\n      reasoningTokens: usage.outputTokens.reasoning,\n    },\n    totalTokens: addTokenCounts(\n      usage.inputTokens.total,\n      usage.outputTokens.total,\n    ),\n    raw: usage.raw,\n  };\n}\n\nexport function createNullLanguageModelUsage(): LanguageModelUsage {\n  return {\n    inputTokens: undefined,\n    inputTokenDetails: {\n      noCacheTokens: undefined,\n      cacheReadTokens: undefined,\n      cacheWriteTokens: undefined,\n    },\n    outputTokens: undefined,\n    outputTokenDetails: {\n      textTokens: undefined,\n      reasoningTokens: undefined,\n    },\n    totalTokens: undefined,\n    raw: undefined,\n  };\n}\n\nexport function addLanguageModelUsage(\n  usage1: LanguageModelUsage,\n  usage2: LanguageModelUsage,\n): LanguageModelUsage {\n  return {\n    inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n    inputTokenDetails: {\n      noCacheTokens: addTokenCounts(\n        usage1.inputTokenDetails?.noCacheTokens,\n        usage2.inputTokenDetails?.noCacheTokens,\n      ),\n      cacheReadTokens: addTokenCounts(\n        usage1.inputTokenDetails?.cacheReadTokens,\n        usage2.inputTokenDetails?.cacheReadTokens,\n      ),\n      cacheWriteTokens: addTokenCounts(\n        usage1.inputTokenDetails?.cacheWriteTokens,\n        usage2.inputTokenDetails?.cacheWriteTokens,\n      ),\n    },\n    outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n    outputTokenDetails: {\n      textTokens: addTokenCounts(\n        usage1.outputTokenDetails?.textTokens,\n        usage2.outputTokenDetails?.textTokens,\n      ),\n      reasoningTokens: addTokenCounts(\n        usage1.outputTokenDetails?.reasoningTokens,\n        usage2.outputTokenDetails?.reasoningTokens,\n      ),\n    },\n    totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),\n  };\n}\n\nfunction addTokenCounts(\n  tokenCount1: number | undefined,\n  tokenCount2: number | undefined,\n): number | undefined {\n  return tokenCount1 == null && tokenCount2 == null\n    ? undefined\n    : (tokenCount1 ?? 0) + (tokenCount2 ?? 0);\n}\n\n/**\n * Usage information for an image model call.\n */\nexport type ImageModelUsage = ImageModelV4Usage;\n\nexport function addImageModelUsage(\n  usage1: ImageModelUsage,\n  usage2: ImageModelUsage,\n): ImageModelUsage {\n  return {\n    inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n    outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n    totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),\n  };\n}\n","/**\n * Reads a property by an untrusted key, ignoring inherited prototype members.\n *\n * Tool sets, tool contexts, and similar lookup objects are indexed by names\n * that can come from model output or client-supplied message history. Plain\n * bracket access (`obj[name]`) resolves names such as `constructor`,\n * `toString`, or `__proto__` to values on `Object.prototype`, which would slip\n * past the `== null` / `!value` guards that treat an unknown name as \"not\n * present\". This helper returns `undefined` unless `key` is an own property.\n */\nexport function getOwn<T extends object>(\n  obj: T | undefined | null,\n  key: string,\n): T[keyof T] | undefined {\n  return obj != null && Object.hasOwn(obj, key)\n    ? obj[key as keyof T]\n    : undefined;\n}\n","import { filterNullable } from '@ai-sdk/provider-utils';\n\n/**\n * Merges multiple abort sources into a single `AbortSignal`.\n * The returned signal will abort when any input signal aborts or when any\n * numeric timeout elapses, using the reason from the first source to abort.\n *\n * @param signals - Abort signals or timeout durations in milliseconds.\n * `null` and `undefined` values are ignored.\n * @returns An `AbortSignal` that aborts when any valid source aborts,\n * or `undefined` if no valid sources are provided.\n */\nexport function mergeAbortSignals(\n  ...signals: (AbortSignal | null | undefined | number)[]\n): AbortSignal | undefined {\n  const validSignals = filterNullable(...signals).map(signal =>\n    typeof signal === 'number' ? AbortSignal.timeout(signal) : signal,\n  );\n\n  return validSignals.length === 0\n    ? undefined\n    : validSignals.length === 1\n      ? validSignals[0]\n      : AbortSignal.any(validSignals);\n}\n","// Shim for performance.now() to support environments that don't have it:\nexport function now(): number {\n  return globalThis?.performance?.now() ?? Date.now();\n}\n","import { asArray, type Arrayable } from '@ai-sdk/provider-utils';\nimport type { Callback } from './callback';\n\n/**\n * Notifies all provided callbacks with the given event in parallel.\n * Errors in callbacks do not break the generation flow.\n */\nexport async function notify<EVENT>(options: {\n  event: EVENT;\n  callbacks?: Arrayable<Callback<EVENT> | undefined | null>;\n}): Promise<void> {\n  await Promise.all(\n    asArray(options.callbacks).map(async callback => {\n      try {\n        await callback?.(options.event);\n      } catch {}\n    }),\n  );\n}\n","import { APICallError } from '@ai-sdk/provider';\nimport { GatewayError } from '@ai-sdk/gateway';\nimport {\n  retryWithExponentialBackoff,\n  type RetryFunction,\n  type ShouldRetryFunction,\n} from '@ai-sdk/provider-utils';\nimport { RetryError } from './retry-error';\n\nfunction getRetryDelayInMs({\n  error,\n  exponentialBackoffDelay,\n}: {\n  error: APICallError | GatewayError;\n  exponentialBackoffDelay: number;\n}): number {\n  const headers = APICallError.isInstance(error)\n    ? error.responseHeaders\n    : APICallError.isInstance(error.cause)\n      ? (error.cause as APICallError).responseHeaders\n      : undefined;\n\n  if (!headers) return exponentialBackoffDelay;\n\n  let ms: number | undefined;\n\n  // retry-ms is more precise than retry-after and used by e.g. OpenAI\n  const retryAfterMs = headers['retry-after-ms'];\n  if (retryAfterMs) {\n    const timeoutMs = parseFloat(retryAfterMs);\n    if (!Number.isNaN(timeoutMs)) {\n      ms = timeoutMs;\n    }\n  }\n\n  // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n  const retryAfter = headers['retry-after'];\n  if (retryAfter && ms === undefined) {\n    const timeoutSeconds = parseFloat(retryAfter);\n    if (!Number.isNaN(timeoutSeconds)) {\n      ms = timeoutSeconds * 1000;\n    } else {\n      ms = Date.parse(retryAfter) - Date.now();\n    }\n  }\n\n  // check that the delay is reasonable:\n  if (\n    ms != null &&\n    !Number.isNaN(ms) &&\n    0 <= ms &&\n    (ms < 60 * 1000 || ms < exponentialBackoffDelay)\n  ) {\n    return ms;\n  }\n\n  return exponentialBackoffDelay;\n}\n\n/**\n * The `retryWithExponentialBackoffRespectingRetryHeaders` strategy retries a failed API call with an exponential backoff,\n * while respecting rate limit headers (retry-after-ms and retry-after) if they are provided and reasonable (0-60 seconds).\n * You can configure the maximum number of retries, the initial delay, and the backoff factor.\n */\nexport const retryWithExponentialBackoffRespectingRetryHeaders = ({\n  maxRetries = 2,\n  initialDelayInMs = 2000,\n  backoffFactor = 2,\n  abortSignal,\n  additionalRetryableError,\n}: {\n  maxRetries?: number;\n  initialDelayInMs?: number;\n  backoffFactor?: number;\n  abortSignal?: AbortSignal;\n  additionalRetryableError?: ShouldRetryFunction;\n} = {}): RetryFunction =>\n  retryWithExponentialBackoff({\n    maxRetries,\n    initialDelayInMs,\n    backoffFactor,\n    abortSignal,\n    shouldRetry: async error =>\n      (error instanceof Error &&\n        ((APICallError.isInstance(error) && error.isRetryable === true) ||\n          (GatewayError.isInstance(error) && error.isRetryable === true))) ||\n      (additionalRetryableError != null &&\n        (await additionalRetryableError(error))),\n    getDelayInMs: ({ error, exponentialBackoffDelay }) =>\n      getRetryDelayInMs({\n        error: error as APICallError | GatewayError,\n        exponentialBackoffDelay,\n      }),\n    createRetryError: ({ message, reason, errors }) =>\n      new RetryError({ message, reason, errors }),\n  });\n","import { InvalidArgumentError } from '../error/invalid-argument-error';\nimport type {\n  RetryFunction,\n  ShouldRetryFunction,\n} from '@ai-sdk/provider-utils';\nimport { retryWithExponentialBackoffRespectingRetryHeaders } from '../util/retry-with-exponential-backoff';\n/**\n * Validate and prepare retries.\n */\nexport function prepareRetries({\n  maxRetries,\n  abortSignal,\n  additionalRetryableError,\n  parameter = 'maxRetries',\n  defaultMaxRetries = 2,\n}: {\n  maxRetries: number | undefined;\n  abortSignal: AbortSignal | undefined;\n  additionalRetryableError?: ShouldRetryFunction;\n  parameter?: string;\n  defaultMaxRetries?: number;\n}): {\n  maxRetries: number;\n  retry: RetryFunction;\n} {\n  if (maxRetries != null) {\n    if (!Number.isInteger(maxRetries)) {\n      throw new InvalidArgumentError({\n        parameter,\n        value: maxRetries,\n        message: `${parameter} must be an integer`,\n      });\n    }\n\n    if (maxRetries < 0) {\n      throw new InvalidArgumentError({\n        parameter,\n        value: maxRetries,\n        message: `${parameter} must be >= 0`,\n      });\n    }\n  }\n\n  const maxRetriesResult = maxRetries ?? defaultMaxRetries;\n\n  return {\n    maxRetries: maxRetriesResult,\n    retry: retryWithExponentialBackoffRespectingRetryHeaders({\n      maxRetries: maxRetriesResult,\n      abortSignal,\n      additionalRetryableError,\n    }),\n  };\n}\n","/**\n * Schedules a timeout that aborts the given controller with a `TimeoutError`\n * `DOMException`, matching the reason produced by `AbortSignal.timeout(ms)`.\n *\n * @param abortController - The controller to abort when the timeout elapses.\n * If undefined, no timeout is scheduled.\n * @param label - Human-readable label included in the error message\n * (e.g. \"Step\", \"Chunk\").\n * @param timeoutMs - Duration in milliseconds before the controller is aborted.\n * If undefined, no timeout is scheduled.\n * @returns The timeout id (suitable for passing to `clearTimeout`), or\n * `undefined` if no timeout was scheduled.\n */\nexport function setAbortTimeout({\n  abortController,\n  label,\n  timeoutMs,\n}: {\n  abortController: AbortController | undefined;\n  label: string;\n  timeoutMs: number | undefined;\n}): ReturnType<typeof setTimeout> | undefined {\n  if (abortController == null || timeoutMs == null) {\n    return undefined;\n  }\n\n  return setTimeout(\n    () =>\n      abortController.abort(\n        new DOMException(\n          `${label} timeout of ${timeoutMs}ms exceeded`,\n          'TimeoutError',\n        ),\n      ),\n    timeoutMs,\n  );\n}\n","/**\n * Calculates a token rate in tokens per second.\n *\n * Returns 0 when the token count is unknown, the duration is unknown or 0, or\n * the computed rate cannot be represented as a finite JSON-safe number.\n */\nexport function calculateTokensPerSecond({\n  tokens,\n  durationMs,\n}: {\n  tokens: number | undefined;\n  durationMs: number | undefined;\n}): number {\n  const tokenRate = (1000 * (tokens ?? 0)) / (durationMs ?? 0);\n\n  return Number.isFinite(tokenRate) ? tokenRate : 0;\n}\n","import type {\n  ModelMessage,\n  ToolApprovalRequest,\n  ToolApprovalResponse,\n  ToolResultPart,\n  ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { InvalidToolApprovalError } from '../error/invalid-tool-approval-error';\nimport { ToolCallNotFoundForApprovalError } from '../error/tool-call-not-found-for-approval-error';\nimport type { TypedToolCall } from './tool-call';\n\nexport type CollectedToolApprovals<TOOLS extends ToolSet> = {\n  approvalRequest: ToolApprovalRequest;\n  approvalResponse: ToolApprovalResponse;\n  toolCall: TypedToolCall<TOOLS>;\n  existingToolResult?: ToolResultPart;\n};\n\n/**\n * If the last message is a tool message, this function collects all tool approvals\n * from that message.\n */\nexport function collectToolApprovals<TOOLS extends ToolSet>({\n  messages,\n}: {\n  messages: ModelMessage[];\n}): {\n  approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n  deniedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n} {\n  const lastMessage = messages.at(-1);\n\n  if (lastMessage?.role != 'tool') {\n    return {\n      approvedToolApprovals: [],\n      deniedToolApprovals: [],\n    };\n  }\n\n  // gather tool calls and prepare lookup.\n  //\n  // These maps are keyed by client-supplied ids (`toolCallId`, `approvalId`)\n  // from the message history. Using `Object.create(null)` gives them no\n  // prototype, so an id that matches an inherited object property (e.g.\n  // `toString`, `constructor`, `__proto__`) is treated as absent instead of\n  // resolving to a prototype value and slipping past the `== null` guards\n  // below (which would otherwise skip the InvalidToolApproval /\n  // ToolCallNotFound checks).\n  const toolCallsByToolCallId: Record<\n    string,\n    TypedToolCall<TOOLS>\n  > = Object.create(null);\n  for (const message of messages) {\n    if (message.role === 'assistant' && typeof message.content !== 'string') {\n      const content = message.content;\n      for (const part of content) {\n        if (part.type === 'tool-call') {\n          toolCallsByToolCallId[part.toolCallId] = part as TypedToolCall<TOOLS>;\n        }\n      }\n    }\n  }\n\n  // gather approval responses and prepare lookup\n  const toolApprovalRequestsByApprovalId: Record<string, ToolApprovalRequest> =\n    Object.create(null);\n  for (const message of messages) {\n    if (message.role === 'assistant' && typeof message.content !== 'string') {\n      const content = message.content;\n      for (const part of content) {\n        if (part.type === 'tool-approval-request') {\n          toolApprovalRequestsByApprovalId[part.approvalId] = part;\n        }\n      }\n    }\n  }\n\n  // gather tool results from the last tool message\n  const toolResults: Record<string, ToolResultPart> = Object.create(null);\n  for (const part of lastMessage.content) {\n    if (part.type === 'tool-result') {\n      toolResults[part.toolCallId] = part;\n    }\n  }\n\n  const approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>> = [];\n  const deniedToolApprovals: Array<CollectedToolApprovals<TOOLS>> = [];\n\n  const approvalResponses = lastMessage.content.filter(\n    part => part.type === 'tool-approval-response',\n  );\n  for (const approvalResponse of approvalResponses) {\n    const approvalRequest =\n      toolApprovalRequestsByApprovalId[approvalResponse.approvalId];\n\n    if (approvalRequest == null) {\n      throw new InvalidToolApprovalError({\n        approvalId: approvalResponse.approvalId,\n      });\n    }\n\n    const existingToolResult = toolResults[approvalRequest.toolCallId];\n    if (\n      existingToolResult != null &&\n      (approvalResponse.approved ||\n        existingToolResult.output.type !== 'execution-denied')\n    ) {\n      continue;\n    }\n\n    const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];\n    if (toolCall == null) {\n      throw new ToolCallNotFoundForApprovalError({\n        toolCallId: approvalRequest.toolCallId,\n        approvalId: approvalRequest.approvalId,\n      });\n    }\n\n    const approval: CollectedToolApprovals<TOOLS> = {\n      approvalRequest,\n      approvalResponse,\n      toolCall,\n      ...(existingToolResult != null ? { existingToolResult } : {}),\n    };\n\n    if (approvalResponse.approved) {\n      approvedToolApprovals.push(approval);\n    } else {\n      deniedToolApprovals.push(approval);\n    }\n  }\n\n  return { approvedToolApprovals, deniedToolApprovals };\n}\n","import {\n  convertBase64ToUint8Array,\n  convertUint8ArrayToBase64,\n} from '@ai-sdk/provider-utils';\nimport type { JSONObject } from '@ai-sdk/provider';\n\n/**\n * A generated file.\n */\nexport interface GeneratedFile {\n  /**\n   * File as a base64 encoded string.\n   */\n  readonly base64: string;\n\n  /**\n   * File as a Uint8Array.\n   */\n  readonly uint8Array: Uint8Array;\n\n  /**\n   * The IANA media type of the file.\n   *\n   * @see https://www.iana.org/assignments/media-types/media-types.xhtml\n   */\n  readonly mediaType: string;\n\n  /**\n   * Provider-specific metadata for this file.\n   */\n  readonly providerMetadata?: Record<string, JSONObject>;\n}\n\n/**\n * @deprecated Use `GeneratedFile` instead. This alias will be removed in v8.\n */\nexport type Experimental_GeneratedImage = GeneratedFile;\n\nexport class DefaultGeneratedFile implements GeneratedFile {\n  private base64Data: string | undefined;\n  private uint8ArrayData: Uint8Array | undefined;\n\n  readonly mediaType: string;\n  readonly providerMetadata?: Record<string, JSONObject>;\n\n  constructor({\n    data,\n    mediaType,\n    providerMetadata,\n  }: {\n    data: string | Uint8Array;\n    mediaType: string;\n    providerMetadata?: Record<string, JSONObject>;\n  }) {\n    const isUint8Array = data instanceof Uint8Array;\n    this.base64Data = isUint8Array ? undefined : data;\n    this.uint8ArrayData = isUint8Array ? data : undefined;\n    this.mediaType = mediaType;\n    this.providerMetadata = providerMetadata;\n  }\n\n  // lazy conversion with caching to avoid unnecessary conversion overhead:\n  get base64() {\n    if (this.base64Data == null) {\n      this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData!);\n    }\n    return this.base64Data;\n  }\n\n  // lazy conversion with caching to avoid unnecessary conversion overhead:\n  get uint8Array() {\n    if (this.uint8ArrayData == null) {\n      this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data!);\n    }\n    return this.uint8ArrayData;\n  }\n}\n\nexport class DefaultGeneratedFileWithType extends DefaultGeneratedFile {\n  readonly type = 'file';\n\n  constructor(options: {\n    data: string | Uint8Array;\n    mediaType: string;\n    providerMetadata?: Record<string, JSONObject>;\n  }) {\n    super(options);\n  }\n}\n","import type { LanguageModelV4Content } from '@ai-sdk/provider';\nimport type { ToolSet } from '@ai-sdk/provider-utils';\nimport { ToolCallNotFoundForApprovalError } from '../error/tool-call-not-found-for-approval-error';\nimport { getOwn } from '../util/get-own';\nimport type { ContentPart } from './content-part';\nimport { DefaultGeneratedFile } from './generated-file';\nimport type { ToolApprovalRequestOutput } from './tool-approval-request-output';\nimport type { ToolApprovalResponseOutput } from './tool-approval-response-output';\nimport type { TypedToolCall } from './tool-call';\nimport type { TypedToolError } from './tool-error';\nimport type { ToolOutput } from './tool-output';\nimport type { TypedToolResult } from './tool-result';\n\nexport function convertLanguageModelContent<TOOLS extends ToolSet>({\n  content,\n  toolCalls,\n  toolOutputs,\n  toolApprovalRequests,\n  toolApprovalResponses,\n  tools,\n}: {\n  content: Array<LanguageModelV4Content>;\n  toolCalls: Array<TypedToolCall<TOOLS>>;\n  toolOutputs: Array<ToolOutput<TOOLS>>;\n  toolApprovalRequests: Array<ToolApprovalRequestOutput<TOOLS>>;\n  toolApprovalResponses: Array<ToolApprovalResponseOutput<TOOLS>>;\n  tools: TOOLS | undefined;\n}): Array<ContentPart<TOOLS>> {\n  const contentParts: Array<ContentPart<TOOLS>> = [];\n  const toolOutputsWithApprovalResponses: Array<ToolOutput<TOOLS>> = [];\n  const toolOutputsWithoutApprovalResponses: Array<ToolOutput<TOOLS>> = [];\n  const toolCallIdsWithApprovalResponses = new Set(\n    toolApprovalResponses.map(\n      toolApprovalResponse => toolApprovalResponse.toolCall.toolCallId,\n    ),\n  );\n\n  for (const part of content) {\n    switch (part.type) {\n      case 'text':\n      case 'reasoning':\n      case 'custom':\n      case 'source':\n        contentParts.push(part);\n        break;\n\n      case 'file':\n      case 'reasoning-file': {\n        contentParts.push({\n          type: part.type as 'file' | 'reasoning-file',\n          file: new DefaultGeneratedFile({\n            data:\n              part.data.type === 'data'\n                ? part.data.data\n                : part.data.url.toString(),\n            mediaType: part.mediaType,\n          }),\n          ...(part.providerMetadata != null\n            ? { providerMetadata: part.providerMetadata }\n            : {}),\n        });\n        break;\n      }\n\n      case 'tool-call': {\n        const toolCall = toolCalls.find(\n          toolCall => toolCall.toolCallId === part.toolCallId,\n        );\n\n        if (toolCall == null) {\n          throw new Error(`Tool call ${part.toolCallId} not found.`);\n        }\n\n        contentParts.push(toolCall);\n        break;\n      }\n\n      case 'tool-result': {\n        const toolCall = toolCalls.find(\n          toolCall => toolCall.toolCallId === part.toolCallId,\n        );\n\n        // Handle deferred results for provider-executed tools (e.g., programmatic tool calling).\n        // When a server tool (like code_execution) triggers a client tool, the server tool's\n        // result may be deferred to a later turn. In this case, there's no matching tool-call\n        // in the current response.\n        if (toolCall == null) {\n          const tool = getOwn(tools, part.toolName);\n          const supportsDeferredResults =\n            tool?.type === 'provider' && tool.supportsDeferredResults;\n\n          if (!supportsDeferredResults) {\n            throw new Error(`Tool call ${part.toolCallId} not found.`);\n          }\n\n          // Create tool result without tool call input (deferred result)\n          if (part.isError) {\n            contentParts.push({\n              type: 'tool-error' as const,\n              toolCallId: part.toolCallId,\n              toolName: part.toolName as keyof TOOLS & string,\n              input: undefined,\n              error: part.result,\n              providerExecuted: true,\n              dynamic: part.dynamic,\n              ...(part.providerMetadata != null\n                ? { providerMetadata: part.providerMetadata }\n                : {}),\n              ...(tool?.metadata != null\n                ? { toolMetadata: tool.metadata }\n                : {}),\n            } as TypedToolError<TOOLS>);\n          } else {\n            contentParts.push({\n              type: 'tool-result' as const,\n              toolCallId: part.toolCallId,\n              toolName: part.toolName as keyof TOOLS & string,\n              input: undefined,\n              output: part.result,\n              providerExecuted: true,\n              dynamic: part.dynamic,\n              ...(part.providerMetadata != null\n                ? { providerMetadata: part.providerMetadata }\n                : {}),\n              ...(tool?.metadata != null\n                ? { toolMetadata: tool.metadata }\n                : {}),\n            } as TypedToolResult<TOOLS>);\n          }\n          break;\n        }\n\n        if (part.isError) {\n          contentParts.push({\n            type: 'tool-error' as const,\n            toolCallId: part.toolCallId,\n            toolName: part.toolName as keyof TOOLS & string,\n            input: toolCall.input,\n            error: part.result,\n            providerExecuted: true,\n            dynamic: toolCall.dynamic,\n            ...(part.providerMetadata != null\n              ? { providerMetadata: part.providerMetadata }\n              : {}),\n            ...(toolCall.toolMetadata != null\n              ? { toolMetadata: toolCall.toolMetadata }\n              : {}),\n          } as TypedToolError<TOOLS>);\n        } else {\n          contentParts.push({\n            type: 'tool-result' as const,\n            toolCallId: part.toolCallId,\n            toolName: part.toolName as keyof TOOLS & string,\n            input: toolCall.input,\n            output: part.result,\n            providerExecuted: true,\n            dynamic: toolCall.dynamic,\n            ...(part.providerMetadata != null\n              ? { providerMetadata: part.providerMetadata }\n              : {}),\n            ...(toolCall.toolMetadata != null\n              ? { toolMetadata: toolCall.toolMetadata }\n              : {}),\n          } as TypedToolResult<TOOLS>);\n        }\n        break;\n      }\n\n      case 'tool-approval-request': {\n        const toolCall = toolCalls.find(\n          toolCall => toolCall.toolCallId === part.toolCallId,\n        );\n\n        if (toolCall == null) {\n          throw new ToolCallNotFoundForApprovalError({\n            toolCallId: part.toolCallId,\n            approvalId: part.approvalId,\n          });\n        }\n\n        contentParts.push({\n          type: 'tool-approval-request' as const,\n          approvalId: part.approvalId,\n          toolCall,\n        });\n        break;\n      }\n    }\n  }\n\n  for (const toolOutput of toolOutputs) {\n    if (toolCallIdsWithApprovalResponses.has(toolOutput.toolCallId)) {\n      toolOutputsWithApprovalResponses.push(toolOutput);\n    } else {\n      toolOutputsWithoutApprovalResponses.push(toolOutput);\n    }\n  }\n\n  return [\n    ...contentParts,\n    ...toolOutputsWithoutApprovalResponses,\n    ...toolApprovalRequests,\n    ...toolApprovalResponses,\n    ...toolOutputsWithApprovalResponses,\n  ];\n}\n","import {\n  experimental_getToolCaller,\n  type ToolSet,\n  type InferToolSetContext,\n  type Experimental_SandboxSession as SandboxSession,\n} from '@ai-sdk/provider-utils';\nimport { InvalidArgumentError } from '../error/invalid-argument-error';\nimport {\n  DIRECT_TOOL_CALL,\n  type ResolvedToolCallers,\n} from '../generate-text/tool-caller-configuration';\nimport { resolveToolDescription } from '../prompt/prepare-tools';\nimport { getOwn } from '../util/get-own';\nimport { isToolSearch } from './tool-search';\n\n/** Create discovery state for one generation, never for a shared tool instance. */\nexport function createToolSearchState({\n  tools,\n  toolCallers,\n}: {\n  tools: ToolSet | undefined;\n  toolCallers: ResolvedToolCallers | undefined;\n}): (\n  activeTools: ToolSet | undefined,\n  options?: {\n    toolsContext?: InferToolSetContext<ToolSet>;\n    experimental_sandbox?: SandboxSession;\n  },\n) => ToolSet | undefined {\n  const searchTools = Object.entries(tools ?? {}).filter(\n    ([, tool]) => tool.deferLoading || isToolSearch(tool),\n  );\n  if (searchTools.length === 0) {\n    return activeTools => activeTools;\n  }\n\n  const discovered = new Set<string>();\n  // An omitted entry permits direct calls; an explicit empty list permits none.\n  const getCallers = (name: string) =>\n    getOwn(toolCallers, name) ?? [DIRECT_TOOL_CALL];\n\n  for (const [name, tool] of searchTools) {\n    const callers = getCallers(name);\n    if (\n      callers.some(name => {\n        if (name === DIRECT_TOOL_CALL) {\n          return false;\n        }\n        const caller = experimental_getToolCaller(tools?.[name]);\n        return caller?.type !== 'local' || caller.prepareModelMessage == null;\n      }) ||\n      (isToolSearch(tool) && tool.deferLoading)\n    ) {\n      throw new InvalidArgumentError({\n        parameter: 'tools',\n        value: name,\n        message: `tool \"${name}\" must be callable directly or through code mode with toolDiscovery: 'conversation'. The search tool itself must not defer loading.`,\n      });\n    }\n  }\n\n  return (activeTools, { toolsContext = {}, experimental_sandbox } = {}) => {\n    if (activeTools == null) {\n      return undefined;\n    }\n\n    // Snapshot eligibility before binding callers. Newly discovered tools are\n    // intentionally absent from this step's execution bindings and catalog.\n    const entries = Object.entries(activeTools);\n    return Object.fromEntries(\n      entries\n        .filter(([name, tool]) => !tool.deferLoading || discovered.has(name))\n        .map(([searchName, tool]) => {\n          if (!isToolSearch(tool)) {\n            return [searchName, tool];\n          }\n\n          const callers = getCallers(searchName).filter(\n            name =>\n              name === DIRECT_TOOL_CALL || Object.hasOwn(activeTools, name),\n          );\n          const candidates = entries.filter(\n            ([name, candidate]) =>\n              candidate.deferLoading &&\n              !isToolSearch(candidate) &&\n              callers.some(caller => getCallers(name).includes(caller)),\n          );\n\n          return [\n            searchName,\n            {\n              ...tool,\n              execute: ({ query }: { query: string }) => {\n                const terms = [...new Set(tokenize(query))];\n                const matches = candidates\n                  .map(([name, candidate]) => {\n                    const description = resolveToolDescription({\n                      tool: candidate,\n                      toolName: name,\n                      toolsContext,\n                      experimental_sandbox,\n                    });\n                    const nameTerms = tokenize(name);\n                    const descriptionTerms = tokenize(description ?? '');\n                    const score = terms.reduce(\n                      (score, term) =>\n                        score +\n                        (nameTerms.includes(term) ? 2 : 0) +\n                        (descriptionTerms.includes(term) ? 1 : 0),\n                      0,\n                    );\n                    return { name, description, score };\n                  })\n                  .filter(match => match.score > 0)\n                  .sort((a, b) => b.score - a.score)\n                  .slice(0, 5);\n\n                for (const { name } of matches) {\n                  discovered.add(name);\n                }\n\n                return {\n                  tools: matches.map(({ name, description }) => ({\n                    name,\n                    ...(description == null ? {} : { description }),\n                  })),\n                };\n              },\n            },\n          ];\n        }),\n    );\n  };\n}\n\nfunction tokenize(text: string): string[] {\n  return (\n    text\n      .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n      .toLowerCase()\n      .match(/[\\p{L}\\p{N}]+/gu) ?? []\n  );\n}\n","import {\n  experimental_getToolCaller,\n  type Experimental_ToolCallerTool,\n  type ModelMessage,\n  type Tool,\n  type ToolSet,\n  type UserModelMessage,\n} from '@ai-sdk/provider-utils';\nimport { InvalidArgumentError } from '../error/invalid-argument-error';\n\nexport const DIRECT_TOOL_CALL = 'AI_SDK_DIRECT_TOOL_CALL';\n\ntype ToolCallerName<TOOLS extends ToolSet> = {\n  [NAME in keyof TOOLS]: TOOLS[NAME] extends Experimental_ToolCallerTool\n    ? NAME\n    : never;\n}[keyof TOOLS] &\n  string;\n\nexport type Experimental_ToolCallers<TOOLS extends ToolSet> = {\n  [NAME in keyof TOOLS]?: ReadonlyArray<\n    'AI_SDK_DIRECT_TOOL_CALL' | ToolCallerName<TOOLS>\n  >;\n};\n\nexport type ResolvedToolCallers = Record<string, ReadonlyArray<string>>;\n\nexport function resolveToolCallerConfiguration<TOOLS extends ToolSet>({\n  tools,\n  toolCallers,\n}: {\n  tools: TOOLS | undefined;\n  toolCallers: Experimental_ToolCallers<TOOLS> | undefined;\n}): ResolvedToolCallers | undefined {\n  if (tools == null || toolCallers == null) {\n    return undefined;\n  }\n\n  const resolved: ResolvedToolCallers = {};\n\n  for (const [toolName, callers] of Object.entries(toolCallers)) {\n    if (!Object.prototype.hasOwnProperty.call(tools, toolName)) {\n      throw new InvalidArgumentError({\n        parameter: 'experimental_toolCallers',\n        value: toolCallers,\n        message: `unknown tool \"${toolName}\".`,\n      });\n    }\n\n    if (!Array.isArray(callers)) {\n      throw new InvalidArgumentError({\n        parameter: 'experimental_toolCallers',\n        value: toolCallers,\n        message: `callers for tool \"${toolName}\" must be an array.`,\n      });\n    }\n\n    resolved[toolName] = callers.map(caller => {\n      if (caller === DIRECT_TOOL_CALL) {\n        return caller;\n      }\n\n      if (\n        typeof caller !== 'string' ||\n        !Object.prototype.hasOwnProperty.call(tools, caller) ||\n        experimental_getToolCaller(tools[caller]) == null\n      ) {\n        throw new InvalidArgumentError({\n          parameter: 'experimental_toolCallers',\n          value: toolCallers,\n          message: `tool \"${toolName}\" contains an invalid caller.`,\n        });\n      }\n\n      return caller;\n    });\n  }\n\n  return resolved;\n}\n\nexport function prepareToolsForToolCallers({\n  tools,\n  toolCallers,\n}: {\n  tools: ToolSet | undefined;\n  toolCallers: ResolvedToolCallers | undefined;\n}): {\n  executionTools: ToolSet | undefined;\n  modelTools: ToolSet | undefined;\n  toolCallerMessages: UserModelMessage[];\n} {\n  if (tools == null || toolCallers == null) {\n    return {\n      executionTools: tools,\n      modelTools: tools,\n      toolCallerMessages: [],\n    };\n  }\n\n  // Tools available to the runtime for execution.\n  const executionTools: ToolSet = { ...tools };\n\n  // Tools exposed directly to the model.\n  const modelTools: ToolSet = { ...tools };\n\n  // Tools routed through each local caller.\n  const localToolsByCaller = new Map<string, ToolSet>();\n\n  // User messages describing caller-accessible tools.\n  const toolCallerMessages: UserModelMessage[] = [];\n\n  for (const [toolName, callerNames] of Object.entries(toolCallers)) {\n    const tool = executionTools[toolName];\n    if (tool == null) {\n      continue;\n    }\n\n    let availableDirectly = false;\n    let availableToProvider = false;\n    let preparedTool: Tool = tool;\n\n    for (const callerName of callerNames) {\n      if (callerName === DIRECT_TOOL_CALL) {\n        availableDirectly = true;\n        continue;\n      }\n\n      const caller = experimental_getToolCaller(executionTools[callerName]);\n      if (caller == null) {\n        continue;\n      }\n\n      if (caller.type === 'provider') {\n        availableToProvider = true;\n        preparedTool = {\n          ...preparedTool,\n          providerOptions: caller.prepareProviderOptions(\n            preparedTool.providerOptions,\n          ),\n        } as Tool;\n      } else {\n        const localTools = localToolsByCaller.get(callerName) ?? {};\n        localTools[toolName] = preparedTool;\n        localToolsByCaller.set(callerName, localTools);\n      }\n    }\n\n    executionTools[toolName] = preparedTool;\n\n    if (availableDirectly || availableToProvider) {\n      modelTools[toolName] = preparedTool;\n    } else {\n      delete modelTools[toolName];\n    }\n  }\n\n  for (const [callerName, callerTool] of Object.entries(executionTools)) {\n    const caller = experimental_getToolCaller(callerTool);\n    if (caller?.type !== 'local') {\n      continue;\n    }\n\n    const callerTools = localToolsByCaller.get(callerName) ?? {};\n    const boundCaller = caller.bind(callerTools);\n    executionTools[callerName] = boundCaller;\n\n    if (Object.prototype.hasOwnProperty.call(modelTools, callerName)) {\n      if (caller.prepareModelMessage == null) {\n        modelTools[callerName] = boundCaller;\n      } else {\n        const content = caller.prepareModelMessage(callerTools);\n        if (content != null) {\n          toolCallerMessages.push({ role: 'user', content });\n        }\n      }\n    }\n  }\n\n  return { executionTools, modelTools, toolCallerMessages };\n}\n\nexport function appendToolCallerMessages({\n  messages,\n  toolCallerMessages,\n}: {\n  messages: ModelMessage[];\n  toolCallerMessages: UserModelMessage[];\n}): ModelMessage[] {\n  if (toolCallerMessages.length === 0) {\n    return messages;\n  }\n\n  const latestUserText = messages.findLast(\n    message => message.role === 'user' && typeof message.content === 'string',\n  )?.content;\n  const existingUserText = new Set(\n    latestUserText == null ? [] : [latestUserText],\n  );\n  const additions = toolCallerMessages.filter(message => {\n    if (\n      typeof message.content !== 'string' ||\n      existingUserText.has(message.content)\n    ) {\n      return false;\n    }\n    existingUserText.add(message.content);\n    return true;\n  });\n\n  return additions.length === 0 ? messages : [...messages, ...additions];\n}\n","import { jsonSchema, tool, type Tool } from '@ai-sdk/provider-utils';\n\nconst toolSearchSymbol = Symbol.for('vercel.ai.toolSearch');\n\ntype ToolSearchInput = { query: string };\ntype ToolSearchOutput = {\n  tools: Array<{ name: string; description?: string }>;\n};\n\n/**\n * Search deferred tools by name and description. The surrounding generation\n * binds the search registry and makes matches available on the next step.\n * Use directly or through code mode with `toolDiscovery: 'conversation'`.\n */\nexport function toolSearch(): Tool<ToolSearchInput, ToolSearchOutput> & {\n  type: 'function';\n} {\n  return Object.assign(\n    tool({\n      description:\n        'Search for tools by keywords in their names and descriptions. Returns up to five matching tools. Matches become available on the next model step, after this execution finishes. Wait for their tool definitions before calling the discovered tools. If no tools match, try different keywords.',\n      inputSchema: jsonSchema<ToolSearchInput>({\n        type: 'object',\n        properties: { query: { type: 'string', minLength: 1 } },\n        required: ['query'],\n        additionalProperties: false,\n      }),\n      outputSchema: jsonSchema<ToolSearchOutput>({\n        type: 'object',\n        properties: {\n          tools: {\n            type: 'array',\n            items: {\n              type: 'object',\n              properties: {\n                name: { type: 'string' },\n                description: { type: 'string' },\n              },\n              required: ['name'],\n              additionalProperties: false,\n            },\n          },\n        },\n        required: ['tools'],\n        additionalProperties: false,\n      }),\n      execute: () => {\n        throw new Error('toolSearch must be bound by an AI SDK generation.');\n      },\n    }),\n    { type: 'function' as const, [toolSearchSymbol]: true },\n  );\n}\n\nexport function isToolSearch(tool: Tool): boolean {\n  return (\n    (tool as Tool & { [toolSearchSymbol]?: boolean })[toolSearchSymbol] === true\n  );\n}\n","import {\n  executeTool,\n  isExecutableTool,\n  type Arrayable,\n  type Experimental_SandboxSession as SandboxSession,\n  type InferToolInput,\n  type InferToolSetContext,\n  type ModelMessage,\n  type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport {\n  getToolTimeoutMs,\n  type TimeoutConfiguration,\n} from '../prompt/request-options';\nimport type { TelemetryDispatcher } from '../telemetry/telemetry';\nimport { getOwn } from '../util/get-own';\nimport { mergeAbortSignals } from '../util/merge-abort-signals';\nimport { notify } from '../util/notify';\nimport { now } from '../util/now';\nimport type { TypedToolCall } from './tool-call';\nimport type { TypedToolError } from './tool-error';\nimport type {\n  OnToolExecutionEndCallback,\n  OnToolExecutionStartCallback,\n  ToolExecutionEndEvent,\n  ToolExecutionStartEvent,\n} from './tool-execution-events';\nimport type { ToolOutput } from './tool-output';\nimport type { TypedToolResult } from './tool-result';\nimport { validateToolContext } from './validate-tool-context';\n\n/**\n * Executes a single tool call and manages its lifecycle callbacks.\n *\n * This function handles the complete tool execution flow:\n * 1. Invokes `onToolExecutionStart` callback before execution\n * 2. Executes the tool's `execute` function with proper context\n * 3. Handles streaming outputs via `onPreliminaryToolResult`\n * 4. Invokes `onToolExecutionEnd` callback with success or error result\n *\n * @returns The tool output with performance metrics, or undefined if the tool has no execute function.\n */\nexport async function executeToolCall<TOOLS extends ToolSet>({\n  toolCall,\n  tools,\n  toolsContext,\n  callId,\n  messages,\n  abortSignal,\n  timeout,\n  experimental_sandbox: sandbox,\n  onPreliminaryToolResult,\n  onToolExecutionStart,\n  onToolExecutionEnd,\n  executeToolInTelemetryContext = async ({ execute }) => await execute(),\n  runInTracingChannelSpan = async ({ execute }) => await execute(),\n}: {\n  toolCall: TypedToolCall<TOOLS>;\n  tools: TOOLS | undefined;\n  callId: string;\n  messages: ModelMessage[];\n  abortSignal: AbortSignal | undefined;\n  toolsContext: InferToolSetContext<TOOLS>;\n  timeout?: TimeoutConfiguration<TOOLS>;\n  experimental_sandbox?: SandboxSession;\n  onPreliminaryToolResult?: (result: TypedToolResult<TOOLS>) => void;\n  onToolExecutionStart?: Arrayable<OnToolExecutionStartCallback<TOOLS>>;\n  onToolExecutionEnd?: Arrayable<OnToolExecutionEndCallback<TOOLS>>;\n  executeToolInTelemetryContext?: <T>(\n    params: Partial<ToolExecutionStartEvent<TOOLS>> & {\n      callId: string;\n      toolCallId: string;\n      execute: () => PromiseLike<T>;\n    },\n  ) => PromiseLike<T>;\n  runInTracingChannelSpan?: NonNullable<\n    TelemetryDispatcher['runInTracingChannelSpan']\n  >;\n}): Promise<\n  | {\n      output: ToolOutput<TOOLS>;\n      toolExecutionMs: number;\n    }\n  | undefined\n> {\n  const { toolName, toolCallId, input } = toolCall;\n  const tool = getOwn(tools, toolName);\n\n  if (!isExecutableTool(tool)) {\n    return undefined;\n  }\n\n  const context = await validateToolContext({\n    toolName,\n    context: getOwn(toolsContext, toolName),\n    contextSchema: tool.contextSchema,\n  });\n\n  const toolExecutionContext = {\n    toolCall,\n    messages,\n    toolContext: context,\n  };\n  const baseCallbackEvent = {\n    callId,\n    ...toolExecutionContext,\n  };\n\n  return await runInTracingChannelSpan({\n    type: 'executeTool',\n    event: baseCallbackEvent,\n    execute: async () => {\n      let output: unknown;\n\n      await notify({\n        event: baseCallbackEvent as ToolExecutionStartEvent<TOOLS>,\n        callbacks: onToolExecutionStart,\n      });\n\n      const toolTimeoutMs = getToolTimeoutMs<TOOLS>(timeout, toolName);\n      const toolAbortSignal = mergeAbortSignals(abortSignal, toolTimeoutMs);\n\n      let toolExecutionMs = 0;\n      try {\n        // Integration wrappers keep nested AI SDK calls associated with this tool execution.\n        await executeToolInTelemetryContext({\n          callId,\n          toolCallId,\n          ...(toolExecutionContext as Partial<ToolExecutionStartEvent<TOOLS>>),\n          execute: async () => {\n            const startTime = now();\n            try {\n              const stream = executeTool({\n                tool,\n                input: input as InferToolInput<typeof tool>,\n                options: {\n                  toolCallId,\n                  messages,\n                  abortSignal: toolAbortSignal,\n                  context,\n                  experimental_sandbox: sandbox,\n                },\n              });\n\n              for await (const part of stream) {\n                if (part.type === 'preliminary') {\n                  onPreliminaryToolResult?.({\n                    ...toolCall,\n                    type: 'tool-result',\n                    output: part.output,\n                    preliminary: true,\n                  });\n                } else {\n                  output = part.output;\n                }\n              }\n            } finally {\n              toolExecutionMs = now() - startTime;\n            }\n          },\n        });\n      } catch (error) {\n        const toolError = {\n          type: 'tool-error',\n          toolCallId,\n          toolName,\n          input,\n          error,\n          dynamic: tool.type === 'dynamic',\n          ...(toolCall.providerMetadata != null\n            ? { providerMetadata: toolCall.providerMetadata }\n            : {}),\n          ...(toolCall.toolMetadata != null\n            ? { toolMetadata: toolCall.toolMetadata }\n            : {}),\n        } as TypedToolError<TOOLS>;\n\n        await notify({\n          event: {\n            ...baseCallbackEvent,\n            toolOutput: toolError,\n            toolExecutionMs,\n          } as ToolExecutionEndEvent<TOOLS>,\n          callbacks: onToolExecutionEnd,\n        });\n\n        return {\n          output: toolError,\n          toolExecutionMs,\n        };\n      }\n\n      const toolResult = {\n        type: 'tool-result',\n        toolCallId,\n        toolName,\n        input,\n        output,\n        dynamic: tool.type === 'dynamic',\n        ...(toolCall.providerMetadata != null\n          ? { providerMetadata: toolCall.providerMetadata }\n          : {}),\n        ...(toolCall.toolMetadata != null\n          ? { toolMetadata: toolCall.toolMetadata }\n          : {}),\n      } as TypedToolResult<TOOLS>;\n\n      await notify({\n        event: {\n          ...baseCallbackEvent,\n          toolOutput: toolResult,\n          toolExecutionMs,\n        } as ToolExecutionEndEvent<TOOLS>,\n        callbacks: onToolExecutionEnd,\n      });\n\n      return {\n        output: toolResult,\n        toolExecutionMs,\n      };\n    },\n  });\n}\n","import { validateTypes, type FlexibleSchema } from '@ai-sdk/provider-utils';\n/**\n * Validates a tool context value against the tool's optional context schema.\n *\n * When no context schema is defined, the original context value is returned as-is.\n * Otherwise, the context is validated and normalized through the schema before\n * being passed into tool execution and approval hooks.\n *\n * @throws {TypeValidationError} When the provided tool context does not match\n * the tool's declared `contextSchema`.\n */\nexport async function validateToolContext<CONTEXT>({\n  toolName,\n  context,\n  contextSchema,\n}: {\n  toolName: string;\n  context: unknown;\n  contextSchema: FlexibleSchema<CONTEXT> | undefined;\n}): Promise<CONTEXT> {\n  if (contextSchema == null) {\n    return context as CONTEXT;\n  }\n\n  return await validateTypes({\n    value: context,\n    schema: contextSchema,\n    context: {\n      field: 'tool context',\n      entityName: toolName,\n    },\n  });\n}\n","import type { ToolSet } from '@ai-sdk/provider-utils';\nimport type { ActiveTools } from './active-tools';\n\nexport type ActiveToolSubset<\n  TOOLS extends ToolSet | undefined,\n  ACTIVE_TOOL_NAMES extends ActiveTools<NonNullable<TOOLS>>,\n> = TOOLS extends undefined\n  ? undefined\n  : [ACTIVE_TOOL_NAMES] extends [NonNullable<ActiveTools<NonNullable<TOOLS>>>]\n    ? Pick<NonNullable<TOOLS>, ACTIVE_TOOL_NAMES[number]>\n    : TOOLS;\n\n/**\n * Filters the tools to only include the active tools.\n * When activeTools is provided, we only include the tools that are in the list.\n *\n * @param tools - The tools to filter.\n * @param activeTools - The active tools to include.\n * @returns The filtered tools.\n */\nexport function filterActiveTools<\n  TOOLS extends ToolSet | undefined,\n  ACTIVE_TOOL_NAMES extends ActiveTools<NonNullable<TOOLS>>,\n>({\n  tools,\n  activeTools,\n}: {\n  tools: TOOLS;\n  activeTools: ACTIVE_TOOL_NAMES;\n}): ActiveToolSubset<TOOLS, ACTIVE_TOOL_NAMES> {\n  if (tools == null || activeTools == null) {\n    return tools as ActiveToolSubset<TOOLS, ACTIVE_TOOL_NAMES>;\n  }\n\n  return Object.fromEntries(\n    Object.entries(tools).filter(([name]) => activeTools.includes(name)),\n  ) as ActiveToolSubset<TOOLS, ACTIVE_TOOL_NAMES>;\n}\n","import type { FinishReason } from '../types/language-model';\n\nexport function isToolExecutionAllowedFinishReason(\n  finishReason: FinishReason,\n): boolean {\n  return finishReason === 'stop' || finishReason === 'tool-calls';\n}\n","import {\n  TypeValidationError,\n  type JSONSchema7,\n  type JSONValue,\n  type LanguageModelV4CallOptions,\n} from '@ai-sdk/provider';\nimport {\n  asSchema,\n  resolve,\n  safeParseJSON,\n  safeValidateTypes,\n  type FlexibleSchema,\n} from '@ai-sdk/provider-utils';\nimport { InvalidArgumentError } from '../error/invalid-argument-error';\nimport { NoObjectGeneratedError } from '../error/no-object-generated-error';\nimport type { FinishReason } from '../types/language-model';\nimport type { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';\nimport type { LanguageModelUsage } from '../types/usage';\nimport type { DeepPartial } from '../util/deep-partial';\nimport { parsePartialJson } from '../util/parse-partial-json';\nimport type { EnrichedStreamPart } from './stream-text';\n\nexport interface Output<OUTPUT = any, PARTIAL = any, ELEMENT = any> {\n  /**\n   * The name of the output mode.\n   */\n  name: string;\n\n  /**\n   * The response format to use for the model.\n   */\n  responseFormat: PromiseLike<LanguageModelV4CallOptions['responseFormat']>;\n\n  /**\n   * Parses the complete output of the model.\n   */\n  parseCompleteOutput(\n    options: { text: string },\n    context: {\n      response: Omit<LanguageModelResponseMetadata, 'messages' | 'body'>;\n      usage: LanguageModelUsage;\n      finishReason: FinishReason;\n    },\n  ): Promise<OUTPUT>;\n\n  /**\n   * Parses the partial output of the model.\n   */\n  parsePartialOutput(options: {\n    text: string;\n  }): Promise<{ partial: PARTIAL } | undefined>;\n\n  /**\n   * Creates a stream transform that emits individual elements as they complete.\n   */\n  createElementStreamTransform():\n    | TransformStream<EnrichedStreamPart<any, PARTIAL>, ELEMENT>\n    | undefined;\n}\n\n/**\n * Output specification for text generation.\n * This is the default output mode that generates plain text.\n *\n * @returns An output specification for generating text.\n */\nexport const text = (): Output<string, string, never> => ({\n  name: 'text',\n  responseFormat: Promise.resolve({ type: 'text' }),\n\n  async parseCompleteOutput({ text }: { text: string }) {\n    return text;\n  },\n\n  async parsePartialOutput({ text }: { text: string }) {\n    return { partial: text };\n  },\n\n  createElementStreamTransform() {\n    return undefined;\n  },\n});\n\n/**\n * Output specification for typed object generation using schemas.\n * When the model generates a text response, it will return an object that matches the schema.\n *\n * @param schema - The schema of the object to generate.\n * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n *\n * @returns An output specification for generating objects with the specified schema.\n */\nexport const object = <OBJECT>({\n  schema: inputSchema,\n  name,\n  description,\n}: {\n  schema: FlexibleSchema<OBJECT>;\n  /**\n   * Optional name of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n   */\n  name?: string;\n  /**\n   * Optional description of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n   */\n  description?: string;\n}): Output<OBJECT, DeepPartial<OBJECT>, never> => {\n  const schema = asSchema(inputSchema);\n\n  return {\n    name: 'object',\n\n    responseFormat: resolve(schema.jsonSchema).then(jsonSchema => ({\n      type: 'json' as const,\n      schema: jsonSchema,\n      ...(name != null && { name }),\n      ...(description != null && { description }),\n    })),\n\n    async parseCompleteOutput(\n      { text }: { text: string },\n      context: {\n        response: LanguageModelResponseMetadata;\n        usage: LanguageModelUsage;\n        finishReason: FinishReason;\n      },\n    ) {\n      const parseResult = await safeParseJSON({ text });\n\n      if (!parseResult.success) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: could not parse the response.',\n          cause: parseResult.error,\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      const validationResult = await safeValidateTypes({\n        value: parseResult.value,\n        schema,\n      });\n\n      if (!validationResult.success) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: response did not match schema.',\n          cause: validationResult.error,\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      return validationResult.value;\n    },\n\n    async parsePartialOutput({ text }: { text: string }) {\n      const result = await parsePartialJson(text);\n\n      switch (result.state) {\n        case 'failed-parse':\n        case 'undefined-input': {\n          return undefined;\n        }\n\n        case 'repaired-parse':\n        case 'successful-parse': {\n          return {\n            // Note: currently no validation of partial results:\n            partial: result.value as DeepPartial<OBJECT>,\n          };\n        }\n      }\n    },\n\n    createElementStreamTransform() {\n      return undefined;\n    },\n  };\n};\n\n/**\n * Output specification for array generation.\n * When the model generates a text response, it will return an array of elements.\n *\n * @param element - The schema of the array elements to generate.\n * @param minItems - Optional minimum number of elements to generate.\n * @param maxItems - Optional maximum number of elements to generate.\n * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n *\n * @returns An output specification for generating an array of elements.\n */\nexport const array = <ELEMENT>({\n  element: inputElementSchema,\n  minItems,\n  maxItems,\n  name,\n  description,\n}: {\n  element: FlexibleSchema<ELEMENT>;\n  /**\n   * Optional minimum number of elements to generate.\n   */\n  minItems?: number;\n  /**\n   * Optional maximum number of elements to generate.\n   */\n  maxItems?: number;\n  /**\n   * Optional name of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n   */\n  name?: string;\n  /**\n   * Optional description of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n   */\n  description?: string;\n}): Output<Array<ELEMENT>, Array<ELEMENT>, ELEMENT> => {\n  validateArrayBound({ name: 'minItems', value: minItems });\n  validateArrayBound({ name: 'maxItems', value: maxItems });\n\n  if (minItems != null && maxItems != null && minItems > maxItems) {\n    throw new InvalidArgumentError({\n      parameter: 'minItems',\n      value: minItems,\n      message: 'minItems must be less than or equal to maxItems',\n    });\n  }\n\n  const elementSchema = asSchema(inputElementSchema);\n\n  return {\n    name: 'array',\n\n    // JSON schema that describes an array of elements:\n    responseFormat: resolve(elementSchema.jsonSchema).then(jsonSchema => {\n      // keep root-level definitions available to root-relative references:\n      const {\n        $schema: _$schema,\n        definitions,\n        $defs,\n        ...itemSchema\n      } = jsonSchema as JSONSchema7 & {\n        $defs?: JSONSchema7['definitions'];\n      };\n\n      return {\n        type: 'json' as const,\n        schema: {\n          $schema: 'http://json-schema.org/draft-07/schema#',\n          ...(definitions != null && { definitions }),\n          ...($defs != null && { $defs }),\n          type: 'object',\n          properties: {\n            elements: {\n              type: 'array',\n              items: itemSchema,\n              ...(minItems != null && { minItems }),\n              ...(maxItems != null && { maxItems }),\n            },\n          },\n          required: ['elements'],\n          additionalProperties: false,\n        },\n        ...(name != null && { name }),\n        ...(description != null && { description }),\n      };\n    }),\n\n    async parseCompleteOutput(\n      { text }: { text: string },\n      context: {\n        response: LanguageModelResponseMetadata;\n        usage: LanguageModelUsage;\n        finishReason: FinishReason;\n      },\n    ) {\n      const parseResult = await safeParseJSON({ text });\n\n      if (!parseResult.success) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: could not parse the response.',\n          cause: parseResult.error,\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      const outerValue = parseResult.value;\n\n      if (\n        outerValue == null ||\n        typeof outerValue !== 'object' ||\n        !('elements' in outerValue) ||\n        !Array.isArray(outerValue.elements)\n      ) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: response did not match schema.',\n          cause: new TypeValidationError({\n            value: outerValue,\n            cause: 'response must be an object with an elements array',\n          }),\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      const lengthValidationError = getArrayLengthValidationError({\n        value: outerValue.elements,\n        minItems,\n        maxItems,\n      });\n\n      if (lengthValidationError != null) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: response did not match schema.',\n          cause: lengthValidationError,\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      const validatedElements: Array<ELEMENT> = [];\n      for (const element of outerValue.elements) {\n        const validationResult = await safeValidateTypes({\n          value: element,\n          schema: elementSchema,\n        });\n\n        if (!validationResult.success) {\n          throw new NoObjectGeneratedError({\n            message: 'No object generated: response did not match schema.',\n            cause: validationResult.error,\n            text,\n            response: context.response,\n            usage: context.usage,\n            finishReason: context.finishReason,\n          });\n        }\n\n        validatedElements.push(validationResult.value);\n      }\n\n      return validatedElements;\n    },\n\n    async parsePartialOutput({ text }: { text: string }) {\n      const result = await parsePartialJson(text);\n\n      switch (result.state) {\n        case 'failed-parse':\n        case 'undefined-input': {\n          return undefined;\n        }\n\n        case 'repaired-parse':\n        case 'successful-parse': {\n          const outerValue = result.value;\n\n          // no parsable elements array\n          if (\n            outerValue == null ||\n            typeof outerValue !== 'object' ||\n            !('elements' in outerValue) ||\n            !Array.isArray(outerValue.elements)\n          ) {\n            return undefined;\n          }\n\n          const rawElements =\n            result.state === 'repaired-parse' && outerValue.elements.length > 0\n              ? outerValue.elements.slice(0, -1)\n              : outerValue.elements;\n\n          const parsedElements: Array<ELEMENT> = [];\n          for (const rawElement of rawElements) {\n            const validationResult = await safeValidateTypes({\n              value: rawElement,\n              schema: elementSchema,\n            });\n\n            if (validationResult.success) {\n              parsedElements.push(validationResult.value);\n            }\n          }\n\n          return { partial: parsedElements };\n        }\n      }\n    },\n\n    createElementStreamTransform() {\n      let publishedElements = 0;\n\n      return new TransformStream<\n        EnrichedStreamPart<any, Array<ELEMENT>>,\n        ELEMENT\n      >({\n        transform({ partialOutput }, controller) {\n          if (partialOutput != null) {\n            // Only enqueue new elements that haven't been published yet\n            for (\n              ;\n              publishedElements < partialOutput.length;\n              publishedElements++\n            ) {\n              if (maxItems != null && publishedElements >= maxItems) {\n                controller.error(\n                  getArrayLengthValidationError({\n                    value: partialOutput,\n                    maxItems,\n                  }),\n                );\n                return;\n              }\n\n              controller.enqueue(partialOutput[publishedElements]);\n            }\n          }\n        },\n      });\n    },\n  };\n};\n\nfunction validateArrayBound({\n  name,\n  value,\n}: {\n  name: 'minItems' | 'maxItems';\n  value: number | undefined;\n}) {\n  if (value == null) {\n    return;\n  }\n\n  if (!Number.isInteger(value)) {\n    throw new InvalidArgumentError({\n      parameter: name,\n      value,\n      message: `${name} must be an integer`,\n    });\n  }\n\n  if (value < 0) {\n    throw new InvalidArgumentError({\n      parameter: name,\n      value,\n      message: `${name} must be greater than or equal to 0`,\n    });\n  }\n}\n\nfunction getArrayLengthValidationError({\n  value,\n  minItems,\n  maxItems,\n}: {\n  value: Array<unknown>;\n  minItems?: number;\n  maxItems?: number;\n}): TypeValidationError | undefined {\n  if (minItems != null && value.length < minItems) {\n    return new TypeValidationError({\n      value,\n      cause: `elements array must contain at least ${minItems} items`,\n    });\n  }\n\n  if (maxItems != null && value.length > maxItems) {\n    return new TypeValidationError({\n      value,\n      cause: `elements array must contain at most ${maxItems} items`,\n    });\n  }\n\n  return undefined;\n}\n\n/**\n * Output specification for choice generation.\n * When the model generates a text response, it will return a one of the choice options.\n *\n * @param options - The available choices.\n * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n *\n * @returns An output specification for generating a choice.\n */\nexport const choice = <CHOICE extends string>({\n  options: choiceOptions,\n  name,\n  description,\n}: {\n  options: Array<CHOICE>;\n  /**\n   * Optional name of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n   */\n  name?: string;\n  /**\n   * Optional description of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n   */\n  description?: string;\n}): Output<CHOICE, CHOICE, never> => {\n  return {\n    name: 'choice',\n\n    // JSON schema that describes an enumeration:\n    responseFormat: Promise.resolve({\n      type: 'json',\n      schema: {\n        $schema: 'http://json-schema.org/draft-07/schema#',\n        type: 'object',\n        properties: {\n          result: { type: 'string', enum: choiceOptions },\n        },\n        required: ['result'],\n        additionalProperties: false,\n      },\n      ...(name != null && { name }),\n      ...(description != null && { description }),\n    } as const),\n\n    async parseCompleteOutput(\n      { text }: { text: string },\n      context: {\n        response: LanguageModelResponseMetadata;\n        usage: LanguageModelUsage;\n        finishReason: FinishReason;\n      },\n    ) {\n      const parseResult = await safeParseJSON({ text });\n\n      if (!parseResult.success) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: could not parse the response.',\n          cause: parseResult.error,\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      const outerValue = parseResult.value;\n\n      if (\n        outerValue == null ||\n        typeof outerValue !== 'object' ||\n        !('result' in outerValue) ||\n        typeof outerValue.result !== 'string' ||\n        !choiceOptions.includes(outerValue.result as any)\n      ) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: response did not match schema.',\n          cause: new TypeValidationError({\n            value: outerValue,\n            cause: 'response must be an object that contains a choice value.',\n          }),\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      return outerValue.result as CHOICE;\n    },\n\n    async parsePartialOutput({ text }: { text: string }) {\n      const result = await parsePartialJson(text);\n\n      switch (result.state) {\n        case 'failed-parse':\n        case 'undefined-input': {\n          return undefined;\n        }\n\n        case 'repaired-parse':\n        case 'successful-parse': {\n          const outerValue = result.value;\n\n          if (\n            outerValue == null ||\n            typeof outerValue !== 'object' ||\n            !('result' in outerValue) ||\n            typeof outerValue.result !== 'string'\n          ) {\n            return undefined;\n          }\n\n          // list of potential matches.\n          const potentialMatches = choiceOptions.filter(choiceOption =>\n            choiceOption.startsWith(outerValue.result as string),\n          );\n\n          if (result.state === 'successful-parse') {\n            // successful parse: exact choice value\n            return potentialMatches.includes(outerValue.result as any)\n              ? { partial: outerValue.result as CHOICE }\n              : undefined;\n          } else {\n            // repaired parse: only return if not ambiguous\n            return potentialMatches.length === 1\n              ? { partial: potentialMatches[0] as CHOICE }\n              : undefined;\n          }\n        }\n      }\n    },\n\n    createElementStreamTransform() {\n      return undefined;\n    },\n  };\n};\n\n/**\n * Output specification for unstructured JSON generation.\n * When the model generates a text response, it will return a JSON object.\n *\n * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n *\n * @returns An output specification for generating JSON.\n */\nexport const json = ({\n  name,\n  description,\n}: {\n  /**\n   * Optional name of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema name.\n   */\n  name?: string;\n  /**\n   * Optional description of the output that should be generated.\n   * Used by some providers for additional LLM guidance, e.g. via tool or schema description.\n   */\n  description?: string;\n} = {}): Output<JSONValue, JSONValue, never> => {\n  return {\n    name: 'json',\n\n    responseFormat: Promise.resolve({\n      type: 'json' as const,\n      ...(name != null && { name }),\n      ...(description != null && { description }),\n    }),\n\n    async parseCompleteOutput(\n      { text }: { text: string },\n      context: {\n        response: LanguageModelResponseMetadata;\n        usage: LanguageModelUsage;\n        finishReason: FinishReason;\n      },\n    ) {\n      const parseResult = await safeParseJSON({ text });\n\n      if (!parseResult.success) {\n        throw new NoObjectGeneratedError({\n          message: 'No object generated: could not parse the response.',\n          cause: parseResult.error,\n          text,\n          response: context.response,\n          usage: context.usage,\n          finishReason: context.finishReason,\n        });\n      }\n\n      return parseResult.value;\n    },\n\n    async parsePartialOutput({ text }: { text: string }) {\n      const result = await parsePartialJson(text);\n\n      switch (result.state) {\n        case 'failed-parse':\n        case 'undefined-input': {\n          return undefined;\n        }\n\n        case 'repaired-parse':\n        case 'successful-parse': {\n          return result.value === undefined\n            ? undefined\n            : { partial: result.value };\n        }\n      }\n    },\n\n    createElementStreamTransform() {\n      return undefined;\n    },\n  };\n};\n","import type { JSONValue } from '@ai-sdk/provider';\nimport { safeParseJSON } from '@ai-sdk/provider-utils';\nimport { fixJson } from './fix-json';\n\nexport async function parsePartialJson(jsonText: string | undefined): Promise<{\n  value: JSONValue | undefined;\n  state:\n    | 'undefined-input'\n    | 'successful-parse'\n    | 'repaired-parse'\n    | 'failed-parse';\n}> {\n  if (jsonText === undefined) {\n    return { value: undefined, state: 'undefined-input' };\n  }\n\n  let result = await safeParseJSON({ text: jsonText });\n\n  if (result.success) {\n    return { value: result.value, state: 'successful-parse' };\n  }\n\n  result = await safeParseJSON({ text: fixJson(jsonText) });\n\n  if (result.success) {\n    return { value: result.value, state: 'repaired-parse' };\n  }\n\n  return { value: undefined, state: 'failed-parse' };\n}\n","type State =\n  | 'ROOT'\n  | 'FINISH'\n  | 'INSIDE_STRING'\n  | 'INSIDE_STRING_ESCAPE'\n  | 'INSIDE_STRING_UNICODE_ESCAPE'\n  | 'INSIDE_LITERAL'\n  | 'INSIDE_NUMBER'\n  | 'INSIDE_OBJECT_START'\n  | 'INSIDE_OBJECT_KEY'\n  | 'INSIDE_OBJECT_AFTER_KEY'\n  | 'INSIDE_OBJECT_BEFORE_VALUE'\n  | 'INSIDE_OBJECT_AFTER_VALUE'\n  | 'INSIDE_OBJECT_AFTER_COMMA'\n  | 'INSIDE_ARRAY_START'\n  | 'INSIDE_ARRAY_AFTER_VALUE'\n  | 'INSIDE_ARRAY_AFTER_COMMA';\n\n// Implemented as a scanner with additional fixing\n// that performs a single linear time scan pass over the partial JSON.\n//\n// The states should ideally match relevant states from the JSON spec:\n// https://www.json.org/json-en.html\n//\n// Please note that invalid JSON is not considered/covered, because it\n// is assumed that the resulting JSON will be processed by a standard\n// JSON parser that will detect any invalid JSON.\nexport function fixJson(input: string): string {\n  const stack: State[] = ['ROOT'];\n  let lastValidIndex = -1;\n  let literalStart: number | null = null;\n  let unicodeEscapeDigits = 0;\n\n  function isHexDigit(char: string) {\n    return (\n      (char >= '0' && char <= '9') ||\n      (char >= 'A' && char <= 'F') ||\n      (char >= 'a' && char <= 'f')\n    );\n  }\n\n  function processValueStart(char: string, i: number, swapState: State) {\n    {\n      switch (char) {\n        case '\"': {\n          lastValidIndex = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push('INSIDE_STRING');\n          break;\n        }\n\n        case 'f':\n        case 't':\n        case 'n': {\n          lastValidIndex = i;\n          literalStart = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push('INSIDE_LITERAL');\n          break;\n        }\n\n        case '-': {\n          stack.pop();\n          stack.push(swapState);\n          stack.push('INSIDE_NUMBER');\n          break;\n        }\n        case '0':\n        case '1':\n        case '2':\n        case '3':\n        case '4':\n        case '5':\n        case '6':\n        case '7':\n        case '8':\n        case '9': {\n          lastValidIndex = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push('INSIDE_NUMBER');\n          break;\n        }\n\n        case '{': {\n          lastValidIndex = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push('INSIDE_OBJECT_START');\n          break;\n        }\n\n        case '[': {\n          lastValidIndex = i;\n          stack.pop();\n          stack.push(swapState);\n          stack.push('INSIDE_ARRAY_START');\n          break;\n        }\n      }\n    }\n  }\n\n  function processAfterObjectValue(char: string, i: number) {\n    switch (char) {\n      case ',': {\n        stack.pop();\n        stack.push('INSIDE_OBJECT_AFTER_COMMA');\n        break;\n      }\n      case '}': {\n        lastValidIndex = i;\n        stack.pop();\n        break;\n      }\n    }\n  }\n\n  function processAfterArrayValue(char: string, i: number) {\n    switch (char) {\n      case ',': {\n        stack.pop();\n        stack.push('INSIDE_ARRAY_AFTER_COMMA');\n        break;\n      }\n      case ']': {\n        lastValidIndex = i;\n        stack.pop();\n        break;\n      }\n    }\n  }\n\n  for (let i = 0; i < input.length; i++) {\n    const char = input[i];\n    const currentState = stack[stack.length - 1];\n\n    switch (currentState) {\n      case 'ROOT':\n        processValueStart(char, i, 'FINISH');\n        break;\n\n      case 'INSIDE_OBJECT_START': {\n        switch (char) {\n          case '\"': {\n            stack.pop();\n            stack.push('INSIDE_OBJECT_KEY');\n            break;\n          }\n          case '}': {\n            lastValidIndex = i;\n            stack.pop();\n            break;\n          }\n        }\n        break;\n      }\n\n      case 'INSIDE_OBJECT_AFTER_COMMA': {\n        switch (char) {\n          case '\"': {\n            stack.pop();\n            stack.push('INSIDE_OBJECT_KEY');\n            break;\n          }\n        }\n        break;\n      }\n\n      case 'INSIDE_OBJECT_KEY': {\n        switch (char) {\n          case '\"': {\n            stack.pop();\n            stack.push('INSIDE_OBJECT_AFTER_KEY');\n            break;\n          }\n        }\n        break;\n      }\n\n      case 'INSIDE_OBJECT_AFTER_KEY': {\n        switch (char) {\n          case ':': {\n            stack.pop();\n            stack.push('INSIDE_OBJECT_BEFORE_VALUE');\n\n            break;\n          }\n        }\n        break;\n      }\n\n      case 'INSIDE_OBJECT_BEFORE_VALUE': {\n        processValueStart(char, i, 'INSIDE_OBJECT_AFTER_VALUE');\n        break;\n      }\n\n      case 'INSIDE_OBJECT_AFTER_VALUE': {\n        processAfterObjectValue(char, i);\n        break;\n      }\n\n      case 'INSIDE_STRING': {\n        switch (char) {\n          case '\"': {\n            stack.pop();\n            lastValidIndex = i;\n            break;\n          }\n\n          case '\\\\': {\n            stack.push('INSIDE_STRING_ESCAPE');\n            break;\n          }\n\n          default: {\n            lastValidIndex = i;\n          }\n        }\n\n        break;\n      }\n\n      case 'INSIDE_ARRAY_START': {\n        switch (char) {\n          case ']': {\n            lastValidIndex = i;\n            stack.pop();\n            break;\n          }\n\n          default: {\n            lastValidIndex = i;\n            processValueStart(char, i, 'INSIDE_ARRAY_AFTER_VALUE');\n            break;\n          }\n        }\n        break;\n      }\n\n      case 'INSIDE_ARRAY_AFTER_VALUE': {\n        switch (char) {\n          case ',': {\n            stack.pop();\n            stack.push('INSIDE_ARRAY_AFTER_COMMA');\n            break;\n          }\n\n          case ']': {\n            lastValidIndex = i;\n            stack.pop();\n            break;\n          }\n\n          default: {\n            lastValidIndex = i;\n            break;\n          }\n        }\n\n        break;\n      }\n\n      case 'INSIDE_ARRAY_AFTER_COMMA': {\n        processValueStart(char, i, 'INSIDE_ARRAY_AFTER_VALUE');\n        break;\n      }\n\n      case 'INSIDE_STRING_ESCAPE': {\n        stack.pop();\n\n        if (char === 'u') {\n          unicodeEscapeDigits = 0;\n          stack.push('INSIDE_STRING_UNICODE_ESCAPE');\n        } else {\n          lastValidIndex = i;\n        }\n\n        break;\n      }\n\n      case 'INSIDE_STRING_UNICODE_ESCAPE': {\n        if (isHexDigit(char)) {\n          unicodeEscapeDigits++;\n\n          if (unicodeEscapeDigits === 4) {\n            stack.pop();\n            lastValidIndex = i;\n          }\n        }\n\n        break;\n      }\n\n      case 'INSIDE_NUMBER': {\n        switch (char) {\n          case '0':\n          case '1':\n          case '2':\n          case '3':\n          case '4':\n          case '5':\n          case '6':\n          case '7':\n          case '8':\n          case '9': {\n            lastValidIndex = i;\n            break;\n          }\n\n          case 'e':\n          case 'E':\n          case '-':\n          case '.': {\n            break;\n          }\n\n          case ',': {\n            stack.pop();\n\n            if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {\n              processAfterArrayValue(char, i);\n            }\n\n            if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {\n              processAfterObjectValue(char, i);\n            }\n\n            break;\n          }\n\n          case '}': {\n            stack.pop();\n\n            if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {\n              processAfterObjectValue(char, i);\n            }\n\n            break;\n          }\n\n          case ']': {\n            stack.pop();\n\n            if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {\n              processAfterArrayValue(char, i);\n            }\n\n            break;\n          }\n\n          default: {\n            stack.pop();\n            break;\n          }\n        }\n\n        break;\n      }\n\n      case 'INSIDE_LITERAL': {\n        const partialLiteral = input.substring(literalStart!, i + 1);\n\n        if (\n          !'false'.startsWith(partialLiteral) &&\n          !'true'.startsWith(partialLiteral) &&\n          !'null'.startsWith(partialLiteral)\n        ) {\n          stack.pop();\n\n          if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {\n            processAfterObjectValue(char, i);\n          } else if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {\n            processAfterArrayValue(char, i);\n          }\n        } else {\n          lastValidIndex = i;\n        }\n\n        break;\n      }\n    }\n  }\n\n  let result = input.slice(0, lastValidIndex + 1);\n\n  for (let i = stack.length - 1; i >= 0; i--) {\n    const state = stack[i];\n\n    switch (state) {\n      case 'INSIDE_STRING': {\n        result += '\"';\n        break;\n      }\n\n      case 'INSIDE_OBJECT_KEY':\n      case 'INSIDE_OBJECT_AFTER_KEY':\n      case 'INSIDE_OBJECT_AFTER_COMMA':\n      case 'INSIDE_OBJECT_START':\n      case 'INSIDE_OBJECT_BEFORE_VALUE':\n      case 'INSIDE_OBJECT_AFTER_VALUE': {\n        result += '}';\n        break;\n      }\n\n      case 'INSIDE_ARRAY_START':\n      case 'INSIDE_ARRAY_AFTER_COMMA':\n      case 'INSIDE_ARRAY_AFTER_VALUE': {\n        result += ']';\n        break;\n      }\n\n      case 'INSIDE_LITERAL': {\n        const partialLiteral = input.substring(literalStart!, input.length);\n\n        if ('true'.startsWith(partialLiteral)) {\n          result += 'true'.slice(partialLiteral.length);\n        } else if ('false'.startsWith(partialLiteral)) {\n          result += 'false'.slice(partialLiteral.length);\n        } else if ('null'.startsWith(partialLiteral)) {\n          result += 'null'.slice(partialLiteral.length);\n        }\n      }\n    }\n  }\n\n  return result;\n}\n","import type { LanguageModelV4ToolCall } from '@ai-sdk/provider';\nimport {\n  asSchema,\n  safeParseJSON,\n  safeValidateTypes,\n  type InferToolInput,\n  type ModelMessage,\n  type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { InvalidToolInputError } from '../error/invalid-tool-input-error';\nimport { NoSuchToolError } from '../error/no-such-tool-error';\nimport { ToolCallRepairError } from '../error/tool-call-repair-error';\nimport type { Instructions } from '../prompt';\nimport { getOwn } from '../util/get-own';\nimport type { DynamicToolCall, TypedToolCall } from './tool-call';\nimport type { ToolCallRepairFunction } from './tool-call-repair-function';\nimport type { ToolInputRefinement } from './tool-input-refinement';\n\nexport async function parseToolCall<TOOLS extends ToolSet>({\n  toolCall,\n  tools,\n  repairToolCall,\n  refineToolInput,\n  messages,\n  instructions,\n}: {\n  toolCall: LanguageModelV4ToolCall;\n  tools: TOOLS | undefined;\n  repairToolCall: ToolCallRepairFunction<TOOLS> | undefined;\n  refineToolInput?: ToolInputRefinement<TOOLS> | undefined;\n  instructions: Instructions | undefined;\n  messages: ModelMessage[];\n}): Promise<TypedToolCall<TOOLS>> {\n  try {\n    if (tools == null) {\n      // provider-executed dynamic tools are not part of our list of tools:\n      if (toolCall.providerExecuted && toolCall.dynamic) {\n        return await refineParsedToolCallInput({\n          toolCall: await parseProviderExecutedDynamicToolCall(toolCall),\n          refineToolInput,\n        });\n      }\n\n      throw new NoSuchToolError({ toolName: toolCall.toolName });\n    }\n\n    try {\n      return await refineParsedToolCallInput({\n        toolCall: await doParseToolCall({ toolCall, tools }),\n        refineToolInput,\n      });\n    } catch (error) {\n      if (\n        repairToolCall == null ||\n        !(\n          NoSuchToolError.isInstance(error) ||\n          InvalidToolInputError.isInstance(error)\n        )\n      ) {\n        throw error;\n      }\n\n      let repairedToolCall: LanguageModelV4ToolCall | null = null;\n\n      try {\n        repairedToolCall = await repairToolCall({\n          toolCall,\n          tools,\n          inputSchema: async ({ toolName }) => {\n            const inputSchema = getOwn(tools, toolName)?.inputSchema;\n            return await asSchema(inputSchema).jsonSchema;\n          },\n          instructions,\n          system: instructions,\n          messages,\n          error,\n        });\n      } catch (repairError) {\n        throw new ToolCallRepairError({\n          cause: repairError,\n          originalError: error,\n        });\n      }\n\n      // no repaired tool call returned\n      if (repairedToolCall == null) {\n        throw error;\n      }\n\n      return await refineParsedToolCallInput({\n        toolCall: await doParseToolCall({ toolCall: repairedToolCall, tools }),\n        refineToolInput,\n      });\n    }\n  } catch (error) {\n    // use parsed input when possible\n    const parsedInput = await safeParseJSON({ text: toolCall.input });\n    const input = parsedInput.success ? parsedInput.value : toolCall.input;\n    const tool = getOwn(tools, toolCall.toolName);\n\n    // TODO AI SDK 6: special invalid tool call parts\n    return {\n      type: 'tool-call',\n      toolCallId: toolCall.toolCallId,\n      toolName: toolCall.toolName,\n      input,\n      dynamic: true,\n      invalid: true,\n      error,\n      title: tool?.title,\n      providerExecuted: toolCall.providerExecuted,\n      providerMetadata: toolCall.providerMetadata,\n      ...(tool?.metadata != null ? { toolMetadata: tool.metadata } : {}),\n    };\n  }\n}\n\nasync function refineParsedToolCallInput<TOOLS extends ToolSet>({\n  toolCall,\n  refineToolInput,\n}: {\n  toolCall: TypedToolCall<TOOLS>;\n  refineToolInput: ToolInputRefinement<TOOLS> | undefined;\n}): Promise<TypedToolCall<TOOLS>> {\n  const refine = getOwn(refineToolInput, toolCall.toolName);\n\n  if (refine == null) {\n    return toolCall;\n  }\n\n  return {\n    ...toolCall,\n    input: await refine(toolCall.input as InferToolInput<TOOLS[keyof TOOLS]>),\n  } as TypedToolCall<TOOLS>;\n}\n\nasync function parseProviderExecutedDynamicToolCall(\n  toolCall: LanguageModelV4ToolCall,\n): Promise<DynamicToolCall> {\n  const parseResult =\n    toolCall.input.trim() === ''\n      ? { success: true as const, value: {} }\n      : await safeParseJSON({ text: toolCall.input });\n\n  if (parseResult.success === false) {\n    throw new InvalidToolInputError({\n      toolName: toolCall.toolName,\n      toolInput: toolCall.input,\n      cause: parseResult.error,\n    });\n  }\n\n  return {\n    type: 'tool-call',\n    toolCallId: toolCall.toolCallId,\n    toolName: toolCall.toolName,\n    input: parseResult.value,\n    providerExecuted: true,\n    dynamic: true,\n    providerMetadata: toolCall.providerMetadata,\n  };\n}\n\nasync function doParseToolCall<TOOLS extends ToolSet>({\n  toolCall,\n  tools,\n}: {\n  toolCall: LanguageModelV4ToolCall;\n  tools: TOOLS;\n}): Promise<TypedToolCall<TOOLS>> {\n  const toolName = toolCall.toolName as keyof TOOLS & string;\n\n  const tool = getOwn(tools, toolName);\n\n  if (tool == null) {\n    // provider-executed dynamic tools are not part of our list of tools:\n    if (toolCall.providerExecuted && toolCall.dynamic) {\n      return await parseProviderExecutedDynamicToolCall(toolCall);\n    }\n\n    throw new NoSuchToolError({\n      toolName: toolCall.toolName,\n      availableTools: Object.keys(tools),\n    });\n  }\n\n  const schema = asSchema(tool.inputSchema);\n\n  // when the tool call has no arguments, we try passing an empty object to the schema\n  // (many LLMs generate empty strings for tool calls with no arguments)\n  const parseResult =\n    toolCall.input.trim() === ''\n      ? await safeValidateTypes({ value: {}, schema })\n      : await safeParseJSON({ text: toolCall.input, schema });\n\n  if (parseResult.success === false) {\n    throw new InvalidToolInputError({\n      toolName,\n      toolInput: toolCall.input,\n      cause: parseResult.error,\n    });\n  }\n\n  return tool.type === 'dynamic'\n    ? {\n        type: 'tool-call',\n        toolCallId: toolCall.toolCallId,\n        toolName: toolCall.toolName,\n        input: parseResult.value,\n        providerExecuted: toolCall.providerExecuted,\n        providerMetadata: toolCall.providerMetadata,\n        ...(tool.metadata != null ? { toolMetadata: tool.metadata } : {}),\n        dynamic: true,\n        title: tool.title,\n      }\n    : {\n        type: 'tool-call',\n        toolCallId: toolCall.toolCallId,\n        toolName,\n        input: parseResult.value,\n        providerExecuted: toolCall.providerExecuted,\n        providerMetadata: toolCall.providerMetadata,\n        ...(tool.metadata != null ? { toolMetadata: tool.metadata } : {}),\n        title: tool.title,\n      };\n}\n","import type { LanguageModelCallOptions } from '../prompt/language-model-call-options';\nimport { prepareLanguageModelCallOptions } from '../prompt/prepare-language-model-call-options';\n\n/**\n * Resolves model call settings for a single step.\n *\n * Undefined step settings intentionally fall back to the outer call settings,\n * while defined falsy values such as `temperature: 0` and `seed: 0` are kept.\n */\nexport function prepareStepCallSettings({\n  callSettings,\n  stepSettings,\n}: {\n  callSettings: LanguageModelCallOptions;\n  stepSettings: LanguageModelCallOptions | undefined;\n}): LanguageModelCallOptions {\n  return prepareLanguageModelCallOptions({\n    maxOutputTokens:\n      stepSettings?.maxOutputTokens ?? callSettings.maxOutputTokens,\n    temperature: stepSettings?.temperature ?? callSettings.temperature,\n    topP: stepSettings?.topP ?? callSettings.topP,\n    topK: stepSettings?.topK ?? callSettings.topK,\n    presencePenalty:\n      stepSettings?.presencePenalty ?? callSettings.presencePenalty,\n    frequencyPenalty:\n      stepSettings?.frequencyPenalty ?? callSettings.frequencyPenalty,\n    stopSequences: stepSettings?.stopSequences ?? callSettings.stopSequences,\n    seed: stepSettings?.seed ?? callSettings.seed,\n    reasoning: stepSettings?.reasoning ?? callSettings.reasoning,\n  });\n}\n","import type {\n  DataContent,\n  ReasoningFilePart,\n  ReasoningPart,\n} from '@ai-sdk/provider-utils';\nimport type { ProviderMetadata } from '../types/provider-metadata';\nimport { DefaultGeneratedFile, type GeneratedFile } from './generated-file';\n\nfunction unwrapReasoningFileData(\n  data: ReasoningFilePart['data'],\n): DataContent | URL {\n  if (typeof data === 'object' && data !== null && 'type' in data) {\n    return data.type === 'data' ? data.data : data.url;\n  }\n  return data;\n}\n\n/**\n * Reasoning output of a text generation. It contains a reasoning.\n */\nexport interface ReasoningOutput {\n  type: 'reasoning';\n\n  /**\n   * The reasoning text.\n   */\n  text: string;\n\n  /**\n   * Additional provider-specific metadata. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerMetadata?: ProviderMetadata;\n}\n\n/**\n * Reasoning file output of a text generation.\n * It contains a file generated as part of reasoning.\n */\nexport interface ReasoningFileOutput {\n  type: 'reasoning-file';\n\n  /**\n   * The generated file.\n   */\n  file: GeneratedFile;\n\n  /**\n   * Additional provider-specific metadata. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerMetadata?: ProviderMetadata;\n}\n\nexport function convertFromReasoningOutputs(\n  parts: Array<ReasoningOutput | ReasoningFileOutput>,\n): Array<ReasoningPart | ReasoningFilePart> {\n  return parts.map(part => {\n    if (part.type === 'reasoning') {\n      return {\n        type: 'reasoning' as const,\n        text: part.text,\n        ...(part.providerMetadata != null\n          ? { providerOptions: part.providerMetadata }\n          : {}),\n      };\n    }\n\n    return {\n      type: 'reasoning-file' as const,\n      data: part.file.base64,\n      mediaType: part.file.mediaType,\n      ...(part.providerMetadata != null\n        ? { providerOptions: part.providerMetadata }\n        : {}),\n    };\n  });\n}\n\nexport function convertToReasoningOutputs(\n  parts: Array<ReasoningPart | ReasoningFilePart>,\n): Array<ReasoningOutput | ReasoningFileOutput> {\n  return parts.map(part => {\n    if (part.type === 'reasoning') {\n      return {\n        type: 'reasoning' as const,\n        text: part.text,\n        ...(part.providerOptions != null\n          ? { providerMetadata: part.providerOptions as ProviderMetadata }\n          : {}),\n      };\n    }\n\n    const rawData = unwrapReasoningFileData(part.data);\n\n    const fileData: string | Uint8Array =\n      rawData instanceof ArrayBuffer\n        ? new Uint8Array(rawData)\n        : rawData instanceof URL\n          ? rawData.toString()\n          : (rawData as string | Uint8Array);\n\n    return {\n      type: 'reasoning-file' as const,\n      file: new DefaultGeneratedFile({\n        data: fileData,\n        mediaType: part.mediaType,\n      }),\n      ...(part.providerOptions != null\n        ? { providerMetadata: part.providerOptions as ProviderMetadata }\n        : {}),\n    };\n  });\n}\n","import type {\n  Context,\n  InferToolInput,\n  InferToolSetContext,\n  ModelMessage,\n  ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type {\n  ToolApprovalConfiguration,\n  ToolApprovalStatus,\n} from './tool-approval-configuration';\nimport { getOwn } from '../util/get-own';\nimport type { TypedToolCall } from './tool-call';\nimport { validateToolContext } from './validate-tool-context';\n\n/**\n * Resolves the approval state for a tool call by checking user-supplied and tool-defined\n * approval settings, and normalizes the result to the object status shape.\n * User-defined approval settings take precedence over tool-defined settings.\n * If no approval settings are provided, the tool call does not require approval.\n */\nexport async function resolveToolApproval<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context | unknown | never,\n>({\n  tools,\n  toolCall,\n  toolApproval,\n  messages,\n  toolsContext,\n  runtimeContext,\n}: {\n  /**\n   * Tools that are available for the model to call.\n   */\n  tools: TOOLS | undefined;\n\n  /**\n   * Valid tool call.\n   */\n  toolCall: TypedToolCall<TOOLS>;\n\n  /**\n   * User-defined approval configuration for tools.\n   *\n   * This configuration takes precedence over tool-defined approval settings.\n   */\n  toolApproval: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT> | undefined;\n\n  /**\n   * Messages that were sent to the language model to initiate the response that contained the tool call.\n   */\n  messages: ModelMessage[];\n\n  /**\n   * Tool context as defined by the tool's context schema.\n   */\n  toolsContext: InferToolSetContext<TOOLS>;\n\n  /**\n   * User-defined runtime context (same as `runtimeContext` on `generateText` / `streamText`).\n   */\n  runtimeContext: RUNTIME_CONTEXT;\n}): Promise<Exclude<ToolApprovalStatus, string | undefined>> {\n  // user-defined generic tool approval\n  if (toolApproval != null && typeof toolApproval === 'function') {\n    return normalizeToolApprovalStatus(\n      await toolApproval({\n        toolCall,\n        tools,\n        toolsContext,\n        messages,\n        runtimeContext,\n      }),\n    );\n  }\n\n  const toolName = toolCall.toolName;\n  // `toolName` can be client-controlled, so look tools/approvals up by own\n  // property only: a name that matches an inherited object property (e.g.\n  // `constructor`, `toString`) resolves to \"no such tool\"/\"unconfigured\"\n  // instead of a value on `Object.prototype`.\n  const tool = getOwn(tools, toolName);\n\n  // assume that the input has been validated and matches the tool's input schema\n  const input = toolCall.input as InferToolInput<TOOLS[keyof TOOLS]>;\n\n  // user-defined per-tool approval\n  const userDefinedToolApprovalStatus = getOwn(toolApproval, toolName);\n  if (userDefinedToolApprovalStatus != null) {\n    const approvalStatus: ToolApprovalStatus | undefined =\n      typeof userDefinedToolApprovalStatus === 'function'\n        ? await userDefinedToolApprovalStatus(input, {\n            toolCallId: toolCall.toolCallId,\n            messages,\n            toolContext: await validateToolContext({\n              toolName,\n              context: getOwn(toolsContext, toolName),\n              contextSchema: tool?.contextSchema,\n            }),\n            runtimeContext,\n          })\n        : userDefinedToolApprovalStatus;\n\n    return normalizeToolApprovalStatus(approvalStatus);\n  }\n\n  // tool-defined approval\n  if (tool?.needsApproval == null) {\n    return { type: 'not-applicable' };\n  }\n\n  const needsApproval =\n    typeof tool.needsApproval === 'function'\n      ? await tool.needsApproval(input, {\n          toolCallId: toolCall.toolCallId,\n          messages,\n          context: await validateToolContext({\n            toolName,\n            context: getOwn(toolsContext, toolName),\n            contextSchema: tool?.contextSchema,\n          }),\n        })\n      : tool.needsApproval;\n\n  return needsApproval ? { type: 'user-approval' } : { type: 'not-applicable' };\n}\n\nfunction normalizeToolApprovalStatus(\n  status: ToolApprovalStatus | undefined,\n): Exclude<ToolApprovalStatus, string | undefined> {\n  return status === undefined\n    ? { type: 'not-applicable' }\n    : typeof status === 'string'\n      ? { type: status }\n      : status;\n}\n","import type { Context } from '@ai-sdk/provider-utils';\nimport type { IncludedContext } from './telemetry-options';\n\n/**\n * Returns a shallow copy of the runtime context with only top-level\n * properties marked for telemetry inclusion.\n */\nexport function filterIncludedContext<CONTEXT extends Context>({\n  context,\n  includeContext,\n}: {\n  context: CONTEXT;\n  includeContext: IncludedContext<CONTEXT>;\n}): Context {\n  if (context == null) {\n    return {};\n  }\n\n  return Object.fromEntries(\n    Object.entries(context).filter(\n      ([key]) => includeContext?.[key as keyof CONTEXT] === true,\n    ),\n  );\n}\n","import { asArray } from '@ai-sdk/provider-utils';\nimport type { Callback } from '../util/callback';\nimport { mergeCallbacks } from '../util/merge-callbacks';\nimport type {\n  InferTelemetryEvent,\n  Telemetry,\n  TelemetryDispatcher,\n} from './telemetry';\nimport {\n  openTelemetryChannelSpanContext,\n  runWithTracingChannelSpan,\n} from './tracing-channel-publisher';\nimport { getGlobalTelemetryIntegrations } from './telemetry-registry';\nimport type { TelemetryOptions } from './telemetry-options';\n\n/**\n * The subset of `TelemetryDispatcher` keys whose values are Callback callbacks.\n * This excludes dispatcher-only helpers and non-Callback properties such as\n * `executeLanguageModelCall` and `executeTool`.\n */\ntype TelemetryCallbackKey = Exclude<\n  keyof {\n    [K in keyof TelemetryDispatcher as TelemetryDispatcher[K] extends\n      | Callback<any>\n      | undefined\n      ? K\n      : never]: true;\n  },\n  'runInTracingChannelSpan' | 'startTracingChannelContext'\n>;\n\n/**\n * Resolves the public  event type accepted by a telemetry callback key.\n */\ntype TelemetryEvent<K extends TelemetryCallbackKey> =\n  TelemetryDispatcher[K] extends Callback<infer EVENT> | undefined\n    ? EVENT\n    : never;\n\nfunction augmentEvent<EVENT>(\n  event: EVENT,\n  telemetry: Pick<\n    TelemetryOptions,\n    'recordInputs' | 'recordOutputs' | 'functionId'\n  >,\n): InferTelemetryEvent<EVENT> {\n  return Object.assign(\n    Object.create(Object.getPrototypeOf(event)),\n    event,\n    telemetry,\n  );\n}\n\n/**\n * Creates a telemetry dispatcher that sends telemetry events\n * to the resolved set of integrations.\n *\n * When per-call integrations are provided, they take precedence over the globally\n * registered integrations for that call. When no per-call integrations are\n * provided, the globally registered integrations are used.\n *\n * @param args.telemetry - Optional per-call telemetry settings and integrations.\n *\n * @returns A telemetry dispatcher that fans out lifecycle events to the\n * resolved set of integrations.\n */\nexport function createTelemetryDispatcher({\n  telemetry,\n}: {\n  telemetry?: TelemetryOptions;\n  // operationId: string;\n}): TelemetryDispatcher {\n  // When telemetry is explicitly disabled, return a dispatcher\n  // that performs no work and lets tool execution pass through unwrapped.\n  if (telemetry?.isEnabled === false) {\n    return {};\n  }\n\n  const localIntegrations = telemetry?.integrations;\n  const integrations: Array<Telemetry> =\n    localIntegrations != null\n      ? asArray(localIntegrations)\n      : getGlobalTelemetryIntegrations();\n\n  const telemetryMetadata = {\n    recordInputs: telemetry?.recordInputs,\n    recordOutputs: telemetry?.recordOutputs,\n    functionId: telemetry?.functionId,\n  };\n\n  const mergeTelemetryCallback = <KEY extends TelemetryCallbackKey>(\n    key: KEY,\n  ): Callback<TelemetryEvent<KEY>> => {\n    const integrationCallbacks = (\n      integrations\n        .map(integration => integration[key]?.bind(integration))\n        .filter(Boolean) as Array<\n        Callback<InferTelemetryEvent<TelemetryEvent<KEY>>>\n      >\n    ).map(\n      callback =>\n        ((event: TelemetryEvent<KEY>) =>\n          callback(augmentEvent(event, telemetryMetadata))) as Callback<\n          TelemetryEvent<KEY>\n        >,\n    );\n\n    const mergedIntegrationCallback = mergeCallbacks(...integrationCallbacks);\n\n    return async (event: TelemetryEvent<KEY>) => {\n      await mergedIntegrationCallback(event);\n    };\n  };\n\n  const executeLanguageModelCallWrappers = integrations\n    .map(integration => integration.executeLanguageModelCall?.bind(integration))\n    .filter(Boolean) as Array<\n    NonNullable<Telemetry['executeLanguageModelCall']>\n  >;\n\n  const executeToolWrappers = integrations\n    .map(integration => integration.executeTool?.bind(integration))\n    .filter(Boolean) as Array<NonNullable<Telemetry['executeTool']>>;\n\n  return {\n    runInTracingChannelSpan: async ({ type, event, execute }) =>\n      await runWithTracingChannelSpan(\n        {\n          type,\n          event: augmentEvent(event, telemetryMetadata),\n        },\n        execute,\n      ),\n\n    startTracingChannelContext: ({ type, event, completion }) =>\n      openTelemetryChannelSpanContext({\n        message: {\n          type,\n          event: augmentEvent(event, telemetryMetadata),\n        },\n        completion,\n      }),\n\n    onStart: mergeTelemetryCallback('onStart'),\n    onStepStart: mergeTelemetryCallback('onStepStart'),\n    onLanguageModelCallStart: mergeTelemetryCallback(\n      'onLanguageModelCallStart',\n    ),\n    onLanguageModelCallEnd: mergeTelemetryCallback('onLanguageModelCallEnd'),\n    onToolExecutionStart: mergeTelemetryCallback('onToolExecutionStart'),\n    onToolExecutionEnd: mergeTelemetryCallback('onToolExecutionEnd'),\n    // Fan out step-end events to both the new `onStepEnd` callback and the\n    // deprecated `onStepFinish` callback so integrations that still implement\n    // only `onStepFinish` keep receiving step-end events during the deprecation\n    // window.\n    onStepEnd: mergeCallbacks(\n      mergeTelemetryCallback('onStepEnd'),\n      mergeTelemetryCallback('onStepFinish'),\n    ),\n    onObjectStepStart: mergeTelemetryCallback('onObjectStepStart'),\n    onObjectStepEnd: mergeTelemetryCallback('onObjectStepEnd'),\n    onEmbedStart: mergeTelemetryCallback('onEmbedStart'),\n    onEmbedEnd: mergeTelemetryCallback('onEmbedEnd'),\n    onRerankStart: mergeTelemetryCallback('onRerankStart'),\n    onRerankEnd: mergeTelemetryCallback('onRerankEnd'),\n    onEnd: mergeTelemetryCallback('onEnd'),\n    onAbort: mergeTelemetryCallback('onAbort'),\n    onError: mergeTelemetryCallback('onError'),\n\n    /**\n     * Runs provider calls inside integration-specific context so\n     * auto-instrumented provider requests can be associated with model work.\n     */\n    executeLanguageModelCall: async ({ execute, ...event }) => {\n      const augmentedEvent = augmentEvent(event, telemetryMetadata);\n\n      let wrappedExecute = execute;\n      for (const executeWrapper of executeLanguageModelCallWrappers) {\n        const innerExecute = wrappedExecute;\n        wrappedExecute = () =>\n          executeWrapper({ ...augmentedEvent, execute: innerExecute });\n      }\n\n      return await runWithTracingChannelSpan(\n        { type: 'languageModelCall', event: augmentedEvent },\n        wrappedExecute,\n      );\n    },\n\n    /**\n     * Composes all `executeTool` wrappers around the original tool execution.\n     * Each wrapper receives an `execute` function that calls the next wrapper in\n     * the chain, so integrations can establish nested telemetry context before\n     * delegating to the underlying tool.\n     */\n    executeTool: async ({ execute, ...event }) => {\n      const augmentedEvent = augmentEvent(event, telemetryMetadata);\n\n      let wrappedExecute = execute;\n      for (const executeWrapper of executeToolWrappers) {\n        const innerExecute = wrappedExecute;\n        wrappedExecute = () =>\n          executeWrapper({ ...augmentedEvent, execute: innerExecute });\n      }\n\n      return await wrappedExecute();\n    },\n  };\n}\n","import type { Callback } from '../util/callback';\n\n/**\n * Creates an async callback that invokes the provided callbacks in parallel.\n * Undefined callbacks are skipped, and thrown or rejected callback errors are\n * ignored.\n *\n * @param callbacks The callbacks to invoke for each event.\n * @returns A callback that forwards each event to all callbacks and waits for\n * them to settle.\n */\nexport function mergeCallbacks<EVENT>(\n  ...callbacks: Array<Callback<EVENT> | undefined>\n): Callback<EVENT> {\n  return async (event: EVENT) => {\n    await Promise.allSettled(\n      callbacks.map(async callback => {\n        await callback?.(event);\n      }),\n    );\n  };\n}\n","export const AI_SDK_TELEMETRY_TRACING_CHANNEL = 'ai:telemetry';\n\nexport type TelemetryTracingEventType =\n  | 'generateText'\n  | 'streamText'\n  | 'step'\n  | 'languageModelCall'\n  | 'executeTool'\n  | 'embed'\n  | 'embedMany'\n  | 'rerank';\n\nexport type TelemetryTracingChannelMessage<EVENT = unknown> = {\n  readonly type: TelemetryTracingEventType;\n  readonly event: EVENT;\n};\n","export function isNodeRuntime(): boolean {\n  return typeof process !== 'undefined' && process.release?.name === 'node';\n}\n","import type * as diagnosticsChannelModule from 'node:diagnostics_channel';\nimport type * as asyncHooksModule from 'node:async_hooks';\nimport {\n  AI_SDK_TELEMETRY_TRACING_CHANNEL,\n  type TelemetryTracingChannelMessage,\n} from './tracing-channel';\nimport { isNodeRuntime } from '../util/is-node-runtime';\n\ntype DiagnosticsChannel = typeof diagnosticsChannelModule;\ntype AsyncHooks = typeof asyncHooksModule;\ntype AsyncResource = asyncHooksModule.AsyncResource;\n\nexport type TracingChannelContext = {\n  run<T>(execute: () => T): T;\n};\n\nlet diagnosticsChannelPromise:\n  | Promise<DiagnosticsChannel | undefined>\n  | undefined;\n\n/**\n * Loads Node's diagnostics channel module only when the current runtime supports\n * it. Unsupported runtimes and failed imports intentionally resolve to\n * undefined so telemetry tracing never crashes user code.\n */\nasync function loadDiagnosticsChannel(): Promise<\n  DiagnosticsChannel | undefined\n> {\n  if (!isNodeRuntime()) {\n    return undefined;\n  }\n\n  if (diagnosticsChannelPromise == null) {\n    diagnosticsChannelPromise = Promise.resolve(\n      loadBuiltinModule<DiagnosticsChannel>('node:diagnostics_channel'),\n    );\n  }\n\n  return diagnosticsChannelPromise;\n}\n\nfunction loadBuiltinModule<T>(id: string): T | undefined {\n  const processWithBuiltins = globalThis.process as\n    | {\n        getBuiltinModule?: (id: string) => unknown;\n      }\n    | undefined;\n\n  try {\n    return processWithBuiltins?.getBuiltinModule?.(id) as T | undefined;\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * Runs an async operation inside the AI SDK telemetry tracing channel when\n * tracing subscribers may exist. Without Node diagnostics-channel support,\n * without tracingChannel support, or when the runtime reports no subscribers,\n * this is a direct pass-through.\n *\n * The execution bookkeeping preserves the original model/tool result or error\n * if tracing itself throws, and prevents falling back by calling `execute` a\n * second time.\n */\nexport async function runWithTracingChannelSpan<T>(\n  message: TelemetryTracingChannelMessage,\n  execute: () => PromiseLike<T>,\n): Promise<T> {\n  const diagnosticsChannel = await loadDiagnosticsChannel();\n  const tracingChannel = diagnosticsChannel?.tracingChannel?.(\n    AI_SDK_TELEMETRY_TRACING_CHANNEL,\n  );\n\n  if (tracingChannel == null || tracingChannel.hasSubscribers === false) {\n    return await execute();\n  }\n\n  let executePromise: Promise<T> | undefined;\n  let executionResult: T | undefined;\n  let executionError: unknown;\n  let hasExecutionResult = false;\n  let hasExecutionError = false;\n\n  const tracedExecute = () => {\n    try {\n      executePromise = Promise.resolve(execute());\n    } catch (error) {\n      executePromise = Promise.reject(error);\n    }\n\n    executePromise = executePromise.then(\n      result => {\n        executionResult = result;\n        hasExecutionResult = true;\n        return result;\n      },\n      error => {\n        executionError = error;\n        hasExecutionError = true;\n        throw error;\n      },\n    );\n\n    return executePromise;\n  };\n\n  try {\n    return await tracingChannel.tracePromise(tracedExecute, message);\n  } catch {\n    if (hasExecutionError) {\n      throw executionError;\n    }\n\n    if (hasExecutionResult) {\n      return executionResult as T;\n    }\n\n    if (executePromise != null) {\n      return await executePromise;\n    }\n\n    return await execute();\n  }\n}\n\n/**\n * Opens a long-lived tracing-channel span context and returns a runner that can\n * re-enter that context later without changing stream setup timing.\n */\nexport function openTelemetryChannelSpanContext({\n  message,\n  completion,\n}: {\n  message: TelemetryTracingChannelMessage;\n  completion: PromiseLike<unknown>;\n}): TracingChannelContext | undefined {\n  if (!isNodeRuntime()) {\n    return undefined;\n  }\n\n  const diagnosticsChannel = loadBuiltinModule<DiagnosticsChannel>(\n    'node:diagnostics_channel',\n  );\n  const asyncHooks = loadBuiltinModule<AsyncHooks>('node:async_hooks');\n  const tracingChannel = diagnosticsChannel?.tracingChannel?.(\n    AI_SDK_TELEMETRY_TRACING_CHANNEL,\n  );\n\n  if (\n    tracingChannel == null ||\n    tracingChannel.hasSubscribers === false ||\n    asyncHooks == null\n  ) {\n    Promise.resolve(completion).catch(() => {});\n    return undefined;\n  }\n\n  const context = message as TelemetryTracingChannelMessage & {\n    result?: unknown;\n    error?: unknown;\n  };\n  let asyncResource: AsyncResource | undefined;\n  let asyncEndPublished = false;\n\n  const safePublish = (publish: () => void) => {\n    try {\n      publish();\n    } catch {\n      // Diagnostics subscribers should never affect SDK stream behavior.\n    }\n  };\n\n  const publishAsyncEnd = ({\n    result,\n    error,\n  }: {\n    result?: unknown;\n    error?: unknown;\n  }) => {\n    if (asyncEndPublished) {\n      return;\n    }\n\n    asyncEndPublished = true;\n\n    if (error !== undefined) {\n      context.error = error;\n      safePublish(() => tracingChannel.error.publish(context));\n    }\n\n    if (result !== undefined) {\n      context.result = result;\n    }\n\n    safePublish(() => tracingChannel.asyncEnd.publish(context));\n  };\n\n  safePublish(() => {\n    tracingChannel.start.runStores(context, () => {\n      asyncResource = new asyncHooks.AsyncResource('ai.telemetry');\n    });\n  });\n  safePublish(() => tracingChannel.end.publish(context));\n\n  void Promise.resolve(completion).then(\n    result => publishAsyncEnd({ result }),\n    error => publishAsyncEnd({ error }),\n  );\n\n  return {\n    run: execute =>\n      asyncResource == null\n        ? execute()\n        : asyncResource.runInAsyncScope(execute),\n  };\n}\n","import type { Telemetry } from './telemetry';\n\n/**\n * Registers one or more telemetry integrations globally.\n */\nexport function registerTelemetry(...integrations: Telemetry[]): void {\n  if (!globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) {\n    globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [];\n  }\n  globalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(...integrations);\n}\n\nexport function getGlobalTelemetryIntegrations(): Telemetry[] {\n  return globalThis.AI_SDK_TELEMETRY_INTEGRATIONS ?? [];\n}\n","import type { ReasoningPart, ReasoningFilePart } from '@ai-sdk/provider-utils';\n\nexport function asReasoningText(\n  reasoningParts: Array<ReasoningPart | ReasoningFilePart>,\n): string | undefined {\n  const reasoningText = reasoningParts\n    .map(part => ('text' in part ? part.text : ''))\n    .join('');\n  return reasoningText.length > 0 ? reasoningText : undefined;\n}\n","import type {\n  Context,\n  InferToolSetContext,\n  ReasoningFilePart,\n  ReasoningPart,\n  ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type {\n  CallWarning,\n  FinishReason,\n  LanguageModelRequestMetadata,\n  LanguageModelResponseMetadata,\n  ProviderMetadata,\n} from '../types';\nimport type { Source } from '../types/language-model';\nimport type { LanguageModelUsage } from '../types/usage';\nimport type { ContentPart } from './content-part';\nimport type { GeneratedFile } from './generated-file';\nimport { asReasoningText } from './reasoning';\nimport {\n  convertFromReasoningOutputs,\n  type ReasoningFileOutput,\n  type ReasoningOutput,\n} from './reasoning-output';\nimport type {\n  DynamicToolCall,\n  StaticToolCall,\n  TypedToolCall,\n} from './tool-call';\nimport type {\n  DynamicToolResult,\n  StaticToolResult,\n  TypedToolResult,\n} from './tool-result';\n\n/**\n * Timing statistics for the gaps between generated output chunks.\n */\nexport type OutputChunkTimingStats = {\n  /** Shortest observed time between output chunks in milliseconds. */\n  readonly min: number;\n\n  /** 10th percentile time between output chunks in milliseconds. */\n  readonly p10: number;\n\n  /** Median time between output chunks in milliseconds. */\n  readonly median: number;\n\n  /** Average time between output chunks in milliseconds. */\n  readonly avg: number;\n\n  /** 90th percentile time between output chunks in milliseconds. */\n  readonly p90: number;\n\n  /** Longest observed time between output chunks in milliseconds. */\n  readonly max: number;\n};\n\n/**\n * Performance metrics for a single step in the generation process.\n */\nexport type StepResultPerformance = {\n  /**\n   * Effective number of output tokens per second over the full language model\n   * response.\n   *\n   * Calculated as `outputTokens / requestSeconds`.\n   */\n  readonly effectiveOutputTokensPerSecond: number;\n\n  /**\n   * Number of output tokens per second after the first generated output chunk\n   * was received.\n   *\n   * Only available for streaming steps.\n   *\n   * Calculated as `outputTokens / outputStreamSeconds`.\n   */\n  readonly outputTokensPerSecond: number | undefined;\n\n  /**\n   * Number of input tokens processed per second before the first generated\n   * output chunk was received.\n   *\n   * Only available for streaming steps.\n   *\n   * Calculated as `inputTokens / ttftSeconds`.\n   */\n  readonly inputTokensPerSecond: number | undefined;\n\n  /**\n   * Effective number of input and output tokens per second over the full\n   * language model response.\n   *\n   * Calculated as `(inputTokens + outputTokens) / requestSeconds`.\n   */\n  readonly effectiveTotalTokensPerSecond: number;\n\n  /**\n   * Total time spent on the step in milliseconds.\n   */\n  readonly stepTimeMs: number;\n\n  /**\n   * Time spent waiting for the language model response in milliseconds.\n   */\n  readonly responseTimeMs: number;\n\n  /**\n   * Time spent executing each client-side tool call in milliseconds, keyed by\n   * tool call ID.\n   */\n  readonly toolExecutionMs: Readonly<Record<string, number>>;\n\n  /**\n   * Time until the first generated output chunk was received in milliseconds.\n   *\n   * This includes text deltas, reasoning deltas, generated files, reasoning\n   * files, tool input deltas, and tool calls.\n   *\n   * Only available for streaming steps.\n   */\n  readonly timeToFirstOutputMs: number | undefined;\n\n  /**\n   * Timing statistics for the gaps between generated output chunks in\n   * milliseconds.\n   *\n   * Only available for streaming steps with at least two generated output\n   * chunks.\n   */\n  readonly timeBetweenOutputChunksMs?: OutputChunkTimingStats;\n};\n\n/**\n * The result of a single step in the generation process.\n */\nexport type StepResult<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context = Context,\n> = {\n  /**\n   * Unique identifier for the generation call this step belongs to.\n   */\n  readonly callId: string;\n\n  /**\n   * Zero-based index of this step.\n   */\n  readonly stepNumber: number;\n\n  /**\n   * Information about the model that produced this step.\n   */\n  readonly model: {\n    /** The provider of the model. */\n    readonly provider: string;\n\n    /** The ID of the model. */\n    readonly modelId: string;\n  };\n\n  /**\n   * Tool context.\n   */\n  readonly toolsContext: InferToolSetContext<TOOLS>;\n\n  /**\n   * The runtime context that was used as input for the step.\n   */\n  readonly runtimeContext: RUNTIME_CONTEXT;\n\n  /**\n   * The content that was generated in the last step.\n   */\n  readonly content: Array<ContentPart<TOOLS>>;\n\n  /**\n   * The concatenation of all text parts generated in this step.\n   * It is an empty string if the step contains no text parts.\n   */\n  readonly text: string;\n\n  /**\n   * The reasoning that was generated during the generation.\n   */\n  readonly reasoning: Array<ReasoningPart | ReasoningFilePart>;\n\n  /**\n   * The reasoning text that was generated during the generation.\n   *\n   * It is a concatenation of all reasoning parts (but excluding reasoning file parts).\n   * Can be undefined if the model has only generated text.\n   */\n  readonly reasoningText: string | undefined;\n\n  /**\n   * The files that were generated during the generation.\n   */\n  readonly files: Array<GeneratedFile>;\n\n  /**\n   * The sources that were used to generate the text.\n   */\n  readonly sources: Array<Source>;\n\n  /**\n   * The tool calls that were made during the generation.\n   */\n  readonly toolCalls: Array<TypedToolCall<TOOLS>>;\n\n  /**\n   * The static tool calls that were made in the last step.\n   */\n  readonly staticToolCalls: Array<StaticToolCall<TOOLS>>;\n\n  /**\n   * The dynamic tool calls that were made in the last step.\n   */\n  readonly dynamicToolCalls: Array<DynamicToolCall>;\n\n  /**\n   * The results of the tool calls.\n   */\n  readonly toolResults: Array<TypedToolResult<TOOLS>>;\n\n  /**\n   * The static tool results that were made in the last step.\n   */\n  readonly staticToolResults: Array<StaticToolResult<TOOLS>>;\n\n  /**\n   * The dynamic tool results that were made in the last step.\n   */\n  readonly dynamicToolResults: Array<DynamicToolResult>;\n\n  /**\n   * The unified reason why the generation finished.\n   */\n  readonly finishReason: FinishReason;\n\n  /**\n   * The raw reason why the generation finished (from the provider).\n   */\n  readonly rawFinishReason: string | undefined;\n\n  /**\n   * The token usage of the generated text.\n   */\n  readonly usage: LanguageModelUsage;\n\n  /**\n   * Performance metrics for the step.\n   */\n  readonly performance: StepResultPerformance;\n\n  /**\n   * Warnings from the model provider (e.g. unsupported settings).\n   */\n  readonly warnings: CallWarning[] | undefined;\n\n  /**\n   * Additional request information.\n   */\n  readonly request: LanguageModelRequestMetadata;\n\n  /**\n   * Additional response information.\n   */\n  readonly response: LanguageModelResponseMetadata;\n\n  /**\n   * Additional provider-specific metadata. They are passed through\n   * from the provider to the AI SDK and enable provider-specific\n   * results that can be fully encapsulated in the provider.\n   */\n  readonly providerMetadata: ProviderMetadata | undefined;\n};\n\nexport class DefaultStepResult<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context = Context,\n> implements StepResult<TOOLS, RUNTIME_CONTEXT> {\n  readonly callId: StepResult<TOOLS, RUNTIME_CONTEXT>['callId'];\n  readonly stepNumber: StepResult<TOOLS, RUNTIME_CONTEXT>['stepNumber'];\n  readonly model: StepResult<TOOLS, RUNTIME_CONTEXT>['model'];\n  readonly toolsContext: StepResult<TOOLS, RUNTIME_CONTEXT>['toolsContext'];\n  readonly runtimeContext: StepResult<TOOLS, RUNTIME_CONTEXT>['runtimeContext'];\n  readonly content: StepResult<TOOLS, RUNTIME_CONTEXT>['content'];\n  readonly finishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['finishReason'];\n  readonly rawFinishReason: StepResult<\n    TOOLS,\n    RUNTIME_CONTEXT\n  >['rawFinishReason'];\n  readonly usage: StepResult<TOOLS, RUNTIME_CONTEXT>['usage'];\n  readonly performance: StepResult<TOOLS, RUNTIME_CONTEXT>['performance'];\n  readonly warnings: StepResult<TOOLS, RUNTIME_CONTEXT>['warnings'];\n  readonly request: StepResult<TOOLS, RUNTIME_CONTEXT>['request'];\n  readonly response: StepResult<TOOLS, RUNTIME_CONTEXT>['response'];\n  readonly providerMetadata: StepResult<\n    TOOLS,\n    RUNTIME_CONTEXT\n  >['providerMetadata'];\n\n  constructor({\n    callId,\n    stepNumber,\n    provider,\n    modelId,\n    runtimeContext,\n    toolsContext,\n    content,\n    finishReason,\n    rawFinishReason,\n    usage,\n    performance,\n    warnings,\n    request,\n    response,\n    providerMetadata,\n  }: {\n    callId: StepResult<TOOLS, RUNTIME_CONTEXT>['callId'];\n    stepNumber: StepResult<TOOLS, RUNTIME_CONTEXT>['stepNumber'];\n    provider: StepResult<TOOLS, RUNTIME_CONTEXT>['model']['provider'];\n    modelId: StepResult<TOOLS, RUNTIME_CONTEXT>['model']['modelId'];\n    runtimeContext: StepResult<TOOLS, RUNTIME_CONTEXT>['runtimeContext'];\n    toolsContext: StepResult<TOOLS, RUNTIME_CONTEXT>['toolsContext'];\n    content: StepResult<TOOLS, RUNTIME_CONTEXT>['content'];\n    finishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['finishReason'];\n    rawFinishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['rawFinishReason'];\n    usage: StepResult<TOOLS, RUNTIME_CONTEXT>['usage'];\n    performance: StepResult<TOOLS, RUNTIME_CONTEXT>['performance'];\n    warnings: StepResult<TOOLS, RUNTIME_CONTEXT>['warnings'];\n    request: StepResult<TOOLS, RUNTIME_CONTEXT>['request'];\n    response: StepResult<TOOLS, RUNTIME_CONTEXT>['response'];\n    providerMetadata: StepResult<TOOLS, RUNTIME_CONTEXT>['providerMetadata'];\n  }) {\n    this.callId = callId;\n    this.stepNumber = stepNumber;\n    this.model = { provider, modelId };\n    this.runtimeContext = runtimeContext;\n    this.toolsContext = toolsContext;\n    this.content = content;\n    this.finishReason = finishReason;\n    this.rawFinishReason = rawFinishReason;\n    this.usage = usage;\n    this.performance = performance;\n    this.warnings = warnings;\n    this.request = request;\n    this.response = response;\n    this.providerMetadata = providerMetadata;\n  }\n\n  get text() {\n    return this.content\n      .filter(part => part.type === 'text')\n      .map(part => part.text)\n      .join('');\n  }\n\n  get reasoning(): Array<ReasoningPart | ReasoningFilePart> {\n    return convertFromReasoningOutputs(\n      this.content.filter(\n        (part): part is ReasoningOutput | ReasoningFileOutput =>\n          part.type === 'reasoning' || part.type === 'reasoning-file',\n      ),\n    );\n  }\n\n  get reasoningText() {\n    return asReasoningText(this.reasoning);\n  }\n\n  get files() {\n    return this.content\n      .filter(part => part.type === 'file')\n      .map(part => part.file);\n  }\n\n  get sources() {\n    return this.content.filter(part => part.type === 'source');\n  }\n\n  get toolCalls() {\n    return this.content.filter(part => part.type === 'tool-call');\n  }\n\n  get staticToolCalls() {\n    return this.toolCalls.filter(\n      (toolCall): toolCall is StaticToolCall<TOOLS> =>\n        toolCall.dynamic !== true,\n    );\n  }\n\n  get dynamicToolCalls() {\n    return this.toolCalls.filter(\n      (toolCall): toolCall is DynamicToolCall => toolCall.dynamic === true,\n    );\n  }\n\n  get toolResults() {\n    return this.content.filter(part => part.type === 'tool-result');\n  }\n\n  get staticToolResults() {\n    return this.toolResults.filter(\n      (toolResult): toolResult is StaticToolResult<TOOLS> =>\n        toolResult.dynamic !== true,\n    );\n  }\n\n  get dynamicToolResults() {\n    return this.toolResults.filter(\n      (toolResult): toolResult is DynamicToolResult =>\n        toolResult.dynamic === true,\n    );\n  }\n}\n","import type {\n  Context,\n  InferToolContext,\n  InferToolSetContext,\n  ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { filterIncludedContext } from '../telemetry/filter-included-context';\nimport { createTelemetryDispatcher } from '../telemetry/create-telemetry-dispatcher';\nimport type { TelemetryDispatcher } from '../telemetry/telemetry';\nimport type {\n  IncludedContext,\n  IncludedToolsContext,\n  TelemetryOptions,\n} from '../telemetry/telemetry-options';\nimport type {\n  GenerateTextOnAbortCallback,\n  GenerateTextOnEndCallback,\n  GenerateTextOnStartCallback,\n  GenerateTextOnStepEndCallback,\n  GenerateTextOnStepFinishCallback,\n  GenerateTextOnStepStartCallback,\n} from './generate-text-events';\nimport type { Output } from './output';\nimport { DefaultStepResult, type StepResult } from './step-result';\nimport type {\n  OnToolExecutionEndCallback,\n  OnToolExecutionStartCallback,\n} from './tool-execution-events';\n\n/**\n * Telemetry dispatcher for text generation with callbacks typed to the\n * operation-specific tool set, runtime context, and output shape.\n */\nexport type RestrictedTelemetryDispatcher<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context,\n  OUTPUT extends Output,\n> = Omit<\n  TelemetryDispatcher,\n  | 'onStart'\n  | 'onStepStart'\n  | 'onStepEnd'\n  | 'onStepFinish'\n  | 'onEnd'\n  | 'onAbort'\n  | 'onToolExecutionStart'\n  | 'onToolExecutionEnd'\n> & {\n  onStart: GenerateTextOnStartCallback<TOOLS, RUNTIME_CONTEXT, OUTPUT>;\n  onStepStart: GenerateTextOnStepStartCallback<TOOLS, RUNTIME_CONTEXT, OUTPUT>;\n  onStepEnd: GenerateTextOnStepEndCallback<TOOLS, RUNTIME_CONTEXT>;\n  /** @deprecated Use `onStepEnd` instead. */\n  onStepFinish: GenerateTextOnStepFinishCallback<TOOLS, RUNTIME_CONTEXT>;\n  onEnd: GenerateTextOnEndCallback<TOOLS, RUNTIME_CONTEXT>;\n  onAbort?: GenerateTextOnAbortCallback<TOOLS, RUNTIME_CONTEXT>;\n  onToolExecutionStart?: OnToolExecutionStartCallback<TOOLS>;\n  onToolExecutionEnd?: OnToolExecutionEndCallback<TOOLS>;\n};\n\n/**\n * Creates a copy of a step result whose runtime context only contains\n * top-level properties marked for telemetry inclusion.\n */\nfunction restrictStepResult<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context,\n>({\n  step,\n  includeRuntimeContext,\n  includeToolsContext,\n}: {\n  step: StepResult<TOOLS, RUNTIME_CONTEXT>;\n  includeRuntimeContext: IncludedContext<RUNTIME_CONTEXT>;\n  includeToolsContext: IncludedToolsContext<TOOLS>;\n}) {\n  return new DefaultStepResult({\n    callId: step.callId,\n    stepNumber: step.stepNumber,\n    provider: step.model.provider,\n    modelId: step.model.modelId,\n    runtimeContext: filterIncludedContext({\n      context: step.runtimeContext,\n      includeContext: includeRuntimeContext,\n    }),\n    toolsContext: filterToolsContext({\n      toolsContext: step.toolsContext,\n      includeToolsContext,\n    }),\n    content: step.content,\n    finishReason: step.finishReason,\n    rawFinishReason: step.rawFinishReason,\n    usage: step.usage,\n    performance: step.performance,\n    warnings: step.warnings,\n    request: step.request,\n    response: step.response,\n    providerMetadata: step.providerMetadata,\n  });\n}\n\n/**\n * Returns a shallow copy of the tools context with only top-level properties\n * marked for telemetry inclusion for each tool.\n */\nfunction filterToolsContext<TOOLS extends ToolSet>({\n  toolsContext,\n  includeToolsContext,\n}: {\n  toolsContext: InferToolSetContext<TOOLS>;\n  includeToolsContext: IncludedToolsContext<TOOLS>;\n}): InferToolSetContext<TOOLS> {\n  if (includeToolsContext == null) {\n    return {} as InferToolSetContext<TOOLS>;\n  }\n\n  return Object.fromEntries(\n    Object.entries(toolsContext).map(([toolName, toolContext]) => [\n      toolName,\n      filterToolContext({\n        toolName,\n        toolContext,\n        includeToolsContext,\n      }),\n    ]),\n  ) as InferToolSetContext<TOOLS>;\n}\n\nfunction filterToolContext<TOOLS extends ToolSet>({\n  toolName,\n  toolContext,\n  includeToolsContext,\n}: {\n  toolName: string;\n  toolContext: unknown;\n  includeToolsContext: IncludedToolsContext<TOOLS>;\n}) {\n  const includeToolContext = (\n    includeToolsContext as\n      | Record<\n          string,\n          IncludedContext<InferToolContext<TOOLS[typeof toolName]>>\n        >\n      | undefined\n  )?.[toolName];\n\n  return filterIncludedContext({\n    context: toolContext as InferToolContext<TOOLS[typeof toolName]>,\n    includeContext: includeToolContext,\n  });\n}\n\n/**\n * Creates a telemetry dispatcher that only includes configured runtime context\n * properties in text-generation lifecycle events before dispatching them.\n */\nexport function createRestrictedTelemetryDispatcher<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context,\n  OUTPUT extends Output,\n>({\n  telemetry,\n  includeRuntimeContext,\n  includeToolsContext,\n}: {\n  telemetry?: TelemetryOptions<RUNTIME_CONTEXT, TOOLS>;\n  includeRuntimeContext: IncludedContext<RUNTIME_CONTEXT>;\n  includeToolsContext?: IncludedToolsContext<TOOLS>;\n}): RestrictedTelemetryDispatcher<TOOLS, RUNTIME_CONTEXT, OUTPUT> {\n  const telemetryDispatcher = createTelemetryDispatcher({ telemetry });\n\n  return {\n    ...telemetryDispatcher,\n    onStart: event =>\n      telemetryDispatcher.onStart?.({\n        ...event,\n        runtimeContext: filterIncludedContext({\n          context: event.runtimeContext,\n          includeContext: includeRuntimeContext,\n        }),\n        toolsContext: filterToolsContext({\n          toolsContext: event.toolsContext,\n          includeToolsContext,\n        }),\n      }),\n    onStepStart: event =>\n      telemetryDispatcher.onStepStart?.({\n        ...event,\n        runtimeContext: filterIncludedContext({\n          context: event.runtimeContext,\n          includeContext: includeRuntimeContext,\n        }),\n        steps: event.steps.map(step =>\n          restrictStepResult({\n            step,\n            includeRuntimeContext,\n            includeToolsContext,\n          }),\n        ),\n        toolsContext: filterToolsContext({\n          toolsContext: event.toolsContext,\n          includeToolsContext,\n        }),\n      }),\n    onStepEnd: event =>\n      telemetryDispatcher.onStepEnd?.(\n        restrictStepResult({\n          step: event,\n          includeRuntimeContext,\n          includeToolsContext,\n        }),\n      ),\n    onStepFinish: event =>\n      telemetryDispatcher.onStepEnd?.(\n        restrictStepResult({\n          step: event,\n          includeRuntimeContext,\n          includeToolsContext,\n        }),\n      ),\n    onEnd: event =>\n      telemetryDispatcher.onEnd?.(\n        ((restrictedSteps: StepResult<TOOLS, Context>[]) => {\n          return {\n            ...event,\n            runtimeContext: filterIncludedContext({\n              context: event.runtimeContext,\n              includeContext: includeRuntimeContext,\n            }),\n            steps: restrictedSteps,\n            finalStep: restrictedSteps.at(-1)!,\n            toolsContext: filterToolsContext({\n              toolsContext: event.toolsContext,\n              includeToolsContext,\n            }),\n          };\n        })(\n          event.steps.map(step =>\n            restrictStepResult({\n              step,\n              includeRuntimeContext,\n              includeToolsContext,\n            }),\n          ),\n        ),\n      ),\n    onAbort: event =>\n      telemetryDispatcher.onAbort?.({\n        ...event,\n        steps: event.steps.map(step =>\n          restrictStepResult({\n            step,\n            includeRuntimeContext,\n            includeToolsContext,\n          }),\n        ),\n      }),\n    onToolExecutionStart: event =>\n      telemetryDispatcher.onToolExecutionStart?.({\n        ...event,\n        toolContext: filterToolContext({\n          toolName: event.toolCall.toolName,\n          toolContext: event.toolContext,\n          includeToolsContext,\n        }),\n      }),\n    onToolExecutionEnd: event =>\n      telemetryDispatcher.onToolExecutionEnd?.({\n        ...event,\n        toolContext: filterToolContext({\n          toolName: event.toolCall.toolName,\n          toolContext: event.toolContext,\n          includeToolsContext,\n        }),\n      }),\n  };\n}\n","import type { Context, ToolSet } from '@ai-sdk/provider-utils';\nimport type { StepResult } from './step-result';\n\n/**\n * A predicate that decides whether a tool-calling loop should stop after the\n * current step.\n *\n * A tool calling loop continues until one of the following conditions is met:\n * - The model returns a finish reason other than `tool-calls`\n * - A tool without an execute function is called\n * - A tool call needs approval\n * - One of the provided stop conditions returns `true`\n */\nexport type StopCondition<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context = Context,\n> = (options: {\n  steps: Array<StepResult<TOOLS, RUNTIME_CONTEXT>>;\n}) => PromiseLike<boolean> | boolean;\n\n/**\n * Creates a stop condition that returns `true` when the number of completed\n * steps equals `stepCount`.\n *\n * @param stepCount - The number of steps to allow before stopping.\n */\nexport function isStepCount(stepCount: number): StopCondition<any, any> {\n  return ({ steps }) => steps.length === stepCount;\n}\n\n/**\n * Creates a stop condition that never returns `true`.\n *\n * This lets the tool-calling loop continue until it reaches one of its\n * natural termination conditions.\n */\nexport function isLoopFinished(): StopCondition<any, any> {\n  return () => false;\n}\n\n/**\n * Creates a stop condition that returns `true` when the most recent step\n * contains a tool call with any of the specified names.\n *\n * @param toolName - The names of the tools that should stop the loop.\n */\nexport function hasToolCall<TOOLS extends ToolSet>(\n  ...toolName: Array<keyof TOOLS | (string & {})> // autocomplete support for tool names\n): StopCondition<TOOLS, any> {\n  return ({ steps }) =>\n    steps[steps.length - 1]?.toolCalls?.some(toolCall =>\n      toolName.includes(toolCall.toolName),\n    ) ?? false;\n}\n\n/**\n * Evaluates the provided stop conditions for the current list of steps.\n *\n * Returns `true` as soon as any stop condition is met.\n *\n * @param stopConditions - The stop conditions to evaluate.\n * @param steps - The completed steps accumulated so far.\n */\nexport async function isStopConditionMet<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context = Context,\n>({\n  stopConditions,\n  steps,\n}: {\n  stopConditions: Array<StopCondition<TOOLS, RUNTIME_CONTEXT>>;\n  steps: Array<StepResult<TOOLS, RUNTIME_CONTEXT>>;\n}): Promise<boolean> {\n  return (\n    await Promise.all(stopConditions.map(condition => condition({ steps })))\n  ).some(result => result);\n}\n","/**\n * Adds token counts while preserving an unknown total when both counts are\n * unknown.\n */\nexport function sumTokenCounts(\n  tokenCount1: number | undefined,\n  tokenCount2: number | undefined,\n): number | undefined {\n  return tokenCount1 == null && tokenCount2 == null\n    ? undefined\n    : (tokenCount1 ?? 0) + (tokenCount2 ?? 0);\n}\n","import type {\n  AssistantContent,\n  AssistantModelMessage,\n  ToolContent,\n  ToolModelMessage,\n} from '../prompt';\nimport { createToolModelOutput } from '../prompt/create-tool-model-output';\nimport { getOwn } from '../util/get-own';\nimport type { ContentPart } from './content-part';\nimport type { ToolSet } from '@ai-sdk/provider-utils';\n\n/**\n * Converts the result of a `generateText` or `streamText` call to a list of response messages.\n */\nexport async function toResponseMessages<TOOLS extends ToolSet>({\n  content: inputContent,\n  tools,\n}: {\n  content: Array<ContentPart<TOOLS>>;\n  tools: TOOLS | undefined;\n}): Promise<Array<AssistantModelMessage | ToolModelMessage>> {\n  const responseMessages: Array<AssistantModelMessage | ToolModelMessage> = [];\n  const toolCallOrder = new Map<string, number>();\n\n  const content: AssistantContent = [];\n  for (const part of inputContent) {\n    // Skip sources - they are response-only content that no provider expects back\n    if (part.type === 'source') {\n      continue;\n    }\n\n    // Skip non-provider-executed tool results/errors (they go in the tool message)\n    if (\n      (part.type === 'tool-result' || part.type === 'tool-error') &&\n      !part.providerExecuted\n    ) {\n      continue;\n    }\n\n    // Skip empty text\n    if (part.type === 'text' && part.text.length === 0) {\n      continue;\n    }\n\n    switch (part.type) {\n      case 'text':\n        content.push({\n          type: 'text',\n          text: part.text,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      case 'custom':\n        content.push({\n          type: 'custom',\n          kind: part.kind,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      case 'reasoning':\n        content.push({\n          type: 'reasoning',\n          text: part.text,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      case 'file':\n        content.push({\n          type: 'file',\n          data: part.file.base64,\n          mediaType: part.file.mediaType,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      case 'reasoning-file':\n        content.push({\n          type: 'reasoning-file',\n          data: part.file.base64,\n          mediaType: part.file.mediaType,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      case 'tool-call':\n        if (!toolCallOrder.has(part.toolCallId)) {\n          toolCallOrder.set(part.toolCallId, toolCallOrder.size);\n        }\n        content.push({\n          type: 'tool-call',\n          toolCallId: part.toolCallId,\n          toolName: part.toolName,\n          input:\n            part.invalid && typeof part.input !== 'object' ? {} : part.input,\n          providerExecuted: part.providerExecuted,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      case 'tool-result': {\n        const output = await createToolModelOutput({\n          toolCallId: part.toolCallId,\n          input: part.input,\n          tool: getOwn(tools, part.toolName),\n          output: part.output,\n          errorMode: 'none',\n        });\n        content.push({\n          type: 'tool-result',\n          toolCallId: part.toolCallId,\n          toolName: part.toolName,\n          output,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      }\n      case 'tool-error': {\n        const output = await createToolModelOutput({\n          toolCallId: part.toolCallId,\n          input: part.input,\n          tool: getOwn(tools, part.toolName),\n          output: part.error,\n          errorMode: 'json',\n        });\n        content.push({\n          type: 'tool-result',\n          toolCallId: part.toolCallId,\n          toolName: part.toolName,\n          output,\n          providerOptions: part.providerMetadata,\n        });\n        break;\n      }\n      case 'tool-approval-request':\n        content.push({\n          type: 'tool-approval-request',\n          approvalId: part.approvalId,\n          toolCallId: part.toolCall.toolCallId,\n          ...(part.reason != null ? { reason: part.reason } : {}),\n          isAutomatic: part.isAutomatic,\n          ...(part.signature != null ? { signature: part.signature } : {}),\n        });\n        break;\n    }\n  }\n\n  if (content.length > 0) {\n    responseMessages.push({\n      role: 'assistant',\n      content,\n    });\n  }\n\n  const toolResultContent: ToolContent = [];\n  for (const part of inputContent) {\n    if (\n      part.type !== 'tool-approval-response' &&\n      part.type !== 'tool-result' &&\n      part.type !== 'tool-error'\n    ) {\n      continue;\n    }\n\n    if (part.type === 'tool-approval-response') {\n      toolResultContent.push({\n        type: 'tool-approval-response',\n        approvalId: part.approvalId,\n        approved: part.approved,\n        reason: part.reason,\n        providerExecuted: part.providerExecuted,\n      });\n\n      // when the tool approval is denied,\n      // we need to add an execution-denied tool result\n      // since there is no corresponding tool result for the tool call\n      if (part.approved === false) {\n        toolResultContent.push({\n          type: 'tool-result',\n          toolCallId: part.toolCall.toolCallId,\n          toolName: part.toolCall.toolName,\n          output: {\n            type: 'execution-denied' as const,\n            reason: part.reason,\n          },\n        });\n      }\n      continue;\n    }\n\n    if (part.providerExecuted) {\n      continue;\n    }\n\n    const output = await createToolModelOutput({\n      toolCallId: part.toolCallId,\n      input: part.input,\n      tool: getOwn(tools, part.toolName),\n      output: part.type === 'tool-result' ? part.output : part.error,\n      errorMode: part.type === 'tool-error' ? 'text' : 'none',\n    });\n\n    toolResultContent.push({\n      type: 'tool-result',\n      toolCallId: part.toolCallId,\n      toolName: part.toolName,\n      output,\n      ...(part.providerMetadata != null\n        ? { providerOptions: part.providerMetadata }\n        : {}),\n    });\n  }\n\n  if (toolResultContent.length > 0) {\n    responseMessages.push({\n      role: 'tool',\n      content: sortToolResultContentByToolCallOrder({\n        toolResultContent,\n        toolCallOrder,\n      }),\n    });\n  }\n\n  return responseMessages;\n}\n\nfunction sortToolResultContentByToolCallOrder({\n  toolResultContent,\n  toolCallOrder,\n}: {\n  toolResultContent: ToolContent;\n  toolCallOrder: Map<string, number>;\n}): ToolContent {\n  const sortedToolResults = toolResultContent\n    .filter(part => part.type === 'tool-result')\n    .map((part, index) => ({ part, index }))\n    .sort((a, b) => {\n      const aOrder = toolCallOrder.get(a.part.toolCallId);\n      const bOrder = toolCallOrder.get(b.part.toolCallId);\n\n      if (aOrder == null && bOrder == null) {\n        return a.index - b.index;\n      }\n\n      if (aOrder == null) {\n        return 1;\n      }\n\n      if (bOrder == null) {\n        return -1;\n      }\n\n      return aOrder - bOrder || a.index - b.index;\n    })\n    .map(({ part }) => part);\n\n  let toolResultIndex = 0;\n\n  return toolResultContent.map(part =>\n    part.type === 'tool-result' ? sortedToolResults[toolResultIndex++] : part,\n  );\n}\n","import { convertBase64ToUint8Array } from '@ai-sdk/provider-utils';\nimport { hashCanonical, toBase64url } from '../util/canonical-hash';\n\nconst encoder = new TextEncoder();\n\nfunction fromBase64url(str: string): Uint8Array {\n  return convertBase64ToUint8Array(str);\n}\n\nasync function importKey(secret: string | Uint8Array): Promise<CryptoKey> {\n  const keyData = typeof secret === 'string' ? encoder.encode(secret) : secret;\n  return crypto.subtle.importKey(\n    'raw',\n    keyData,\n    { name: 'HMAC', hash: 'SHA-256' },\n    false,\n    ['sign', 'verify'],\n  );\n}\n\n// Serialize with JSON so the encoding is injective: fields may contain any\n// character (including newlines), and escaping + array structure keeps field\n// boundaries unambiguous. The version prefix provides domain separation.\nfunction buildPayload(\n  approvalId: string,\n  toolCallId: string,\n  toolName: string,\n  inputDigest: string,\n): Uint8Array {\n  return encoder.encode(\n    JSON.stringify([\n      'ai-sdk-tool-approval-v1',\n      approvalId,\n      toolCallId,\n      toolName,\n      inputDigest,\n    ]),\n  );\n}\n\n// Legacy newline-joined payload. Ambiguous when any field contains the `\\n`\n// delimiter, which is why it was replaced; only used as a verify-time fallback\n// guarded on delimiter-free fields.\n// TODO(#17494): remove in v8 when backwards compatibility with pre-JSON\n// signatures (approvals signed before the injective format) is no longer\n// needed.\nfunction buildLegacyPayload(\n  approvalId: string,\n  toolCallId: string,\n  toolName: string,\n  inputDigest: string,\n): Uint8Array {\n  return encoder.encode(\n    `${approvalId}\\n${toolCallId}\\n${toolName}\\n${inputDigest}`,\n  );\n}\n\nexport async function signToolApproval({\n  secret,\n  approvalId,\n  toolCallId,\n  toolName,\n  input,\n}: {\n  secret: string | Uint8Array;\n  approvalId: string;\n  toolCallId: string;\n  toolName: string;\n  input: unknown;\n}): Promise<string> {\n  const key = await importKey(secret);\n  const inputDigest = await hashCanonical(input);\n  const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest);\n  const sig = await crypto.subtle.sign('HMAC', key, payload);\n  return toBase64url(new Uint8Array(sig));\n}\n\nexport async function verifyToolApprovalSignature({\n  secret,\n  signature,\n  approvalId,\n  toolCallId,\n  toolName,\n  input,\n}: {\n  secret: string | Uint8Array;\n  signature: string;\n  approvalId: string;\n  toolCallId: string;\n  toolName: string;\n  input: unknown;\n}): Promise<boolean> {\n  const key = await importKey(secret);\n  const inputDigest = await hashCanonical(input);\n  const sigBytes = fromBase64url(signature);\n\n  const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest);\n  if (await crypto.subtle.verify('HMAC', key, sigBytes, payload)) {\n    return true;\n  }\n\n  // Backwards compatibility: accept a signature produced by the legacy\n  // newline-joined format, but only when no field contains the `\\n` delimiter\n  // — the exact condition that made that format ambiguous. This keeps the\n  // retupling collision closed (the attack requires a newline in a field)\n  // while still verifying benign approvals signed by an older version, e.g. a\n  // pending approval that straddles an upgrade.\n  // TODO(#17494): remove in v8 (drop buildLegacyPayload and this fallback).\n  if (\n    !approvalId.includes('\\n') &&\n    !toolCallId.includes('\\n') &&\n    !toolName.includes('\\n')\n  ) {\n    const legacyPayload = buildLegacyPayload(\n      approvalId,\n      toolCallId,\n      toolName,\n      inputDigest,\n    );\n    return crypto.subtle.verify('HMAC', key, sigBytes, legacyPayload);\n  }\n\n  return false;\n}\n\nexport async function maybeSignApproval({\n  secret,\n  approvalId,\n  toolCallId,\n  toolName,\n  input,\n}: {\n  secret: string | Uint8Array | undefined;\n  approvalId: string;\n  toolCallId: string;\n  toolName: string;\n  input: unknown;\n}): Promise<string | undefined> {\n  if (secret == null) return undefined;\n  return signToolApproval({ secret, approvalId, toolCallId, toolName, input });\n}\n","import { convertUint8ArrayToBase64 } from '@ai-sdk/provider-utils';\n\nconst encoder = new TextEncoder();\n\n/**\n * Deterministic JSON serialization: object keys are sorted so that two\n * structurally-equal values always produce the same string regardless of key\n * insertion order. Used as the input to content hashing.\n */\nexport function canonicalJSON(value: unknown): string {\n  if (value === null || value === undefined) {\n    return JSON.stringify(value);\n  }\n  if (typeof value !== 'object') {\n    return JSON.stringify(value);\n  }\n  if (Array.isArray(value)) {\n    return `[${value\n      .map(element => (element === undefined ? 'null' : canonicalJSON(element)))\n      .join(',')}]`;\n  }\n  const keys = Object.keys(value as Record<string, unknown>).sort();\n  const entries = keys.map(\n    k =>\n      `${JSON.stringify(k)}:${canonicalJSON((value as Record<string, unknown>)[k])}`,\n  );\n  return `{${entries.join(',')}}`;\n}\n\nexport function toBase64url(bytes: Uint8Array): string {\n  return convertUint8ArrayToBase64(bytes)\n    .replace(/\\+/g, '-')\n    .replace(/\\//g, '_')\n    .replace(/=+$/g, '');\n}\n\n/**\n * Canonical SHA-256 digest (base64url) of an arbitrary JSON-serializable value.\n */\nexport async function hashCanonical(value: unknown): Promise<string> {\n  const digest = await crypto.subtle.digest(\n    'SHA-256',\n    encoder.encode(canonicalJSON(value)),\n  );\n  return toBase64url(new Uint8Array(digest));\n}\n","import {\n  asSchema,\n  isExecutableTool,\n  safeValidateTypes,\n  type Context,\n  type InferToolSetContext,\n  type ModelMessage,\n  type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { InvalidToolApprovalSignatureError } from '../error/invalid-tool-approval-signature-error';\nimport { InvalidToolInputError } from '../error/invalid-tool-input-error';\nimport { getOwn } from '../util/get-own';\nimport type { CollectedToolApprovals } from './collect-tool-approvals';\nimport { resolveToolApproval } from './resolve-tool-approval';\nimport { verifyToolApprovalSignature } from './tool-approval-signature';\nimport type { ToolApprovalConfiguration } from './tool-approval-configuration';\n\n/**\n * Re-validates approved tool approvals reconstructed from client-supplied\n * message history before they are executed. Checks HMAC signature (when\n * configured), input schema, and approval policy.\n */\nexport async function validateApprovedToolApprovals<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context | unknown | never,\n>({\n  approvedToolApprovals,\n  tools,\n  toolApproval,\n  messages,\n  toolsContext,\n  runtimeContext,\n  toolApprovalSecret,\n}: {\n  approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n  tools: TOOLS | undefined;\n  toolApproval: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT> | undefined;\n  messages: ModelMessage[];\n  toolsContext: InferToolSetContext<TOOLS>;\n  runtimeContext: RUNTIME_CONTEXT;\n  toolApprovalSecret?: string | Uint8Array;\n}): Promise<{\n  approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n  deniedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n  invalidToolApprovals: Array<\n    CollectedToolApprovals<TOOLS> & { error: InvalidToolInputError }\n  >;\n}> {\n  const approved: Array<CollectedToolApprovals<TOOLS>> = [];\n  const denied: Array<CollectedToolApprovals<TOOLS>> = [];\n  const invalid: Array<\n    CollectedToolApprovals<TOOLS> & { error: InvalidToolInputError }\n  > = [];\n\n  for (const approval of approvedToolApprovals) {\n    const { toolCall, approvalRequest } = approval;\n    // Look up the tool by own property only: `toolName` comes from\n    // client-supplied history, so a name matching an inherited object property\n    // (e.g. `constructor`, `toString`) must resolve to \"no such tool\" rather\n    // than a prototype value that would silently skip input validation below.\n    const tool = getOwn(tools, toolCall.toolName);\n\n    if (toolApprovalSecret != null) {\n      if (approvalRequest.signature == null) {\n        throw new InvalidToolApprovalSignatureError({\n          approvalId: approvalRequest.approvalId,\n          toolCallId: toolCall.toolCallId,\n          reason: 'missing signature',\n        });\n      }\n\n      const valid = await verifyToolApprovalSignature({\n        secret: toolApprovalSecret,\n        signature: approvalRequest.signature,\n        approvalId: approvalRequest.approvalId,\n        toolCallId: toolCall.toolCallId,\n        toolName: toolCall.toolName,\n        input: toolCall.input,\n      });\n\n      if (!valid) {\n        throw new InvalidToolApprovalSignatureError({\n          approvalId: approvalRequest.approvalId,\n          toolCallId: toolCall.toolCallId,\n          reason: 'invalid signature',\n        });\n      }\n    }\n\n    if (isExecutableTool(tool) && tool.inputSchema != null) {\n      const validation = await safeValidateTypes({\n        value: toolCall.input,\n        schema: asSchema(tool.inputSchema),\n      });\n\n      if (!validation.success) {\n        invalid.push({\n          ...approval,\n          error: new InvalidToolInputError({\n            toolName: toolCall.toolName,\n            toolInput: JSON.stringify(toolCall.input),\n            cause: validation.error,\n          }),\n        });\n        continue;\n      }\n    }\n\n    const approvalStatus = await resolveToolApproval({\n      tools,\n      toolApproval,\n      toolCall,\n      messages,\n      toolsContext,\n      runtimeContext,\n    });\n\n    if (approvalStatus.type === 'denied') {\n      denied.push({\n        ...approval,\n        approvalResponse: {\n          ...approval.approvalResponse,\n          approved: false,\n          reason: approvalStatus.reason ?? approval.approvalResponse.reason,\n        },\n      });\n    } else {\n      approved.push(approval);\n    }\n  }\n\n  return {\n    approvedToolApprovals: approved,\n    deniedToolApprovals: denied,\n    invalidToolApprovals: invalid,\n  };\n}\n","import {\n  getErrorMessage,\n  UnsupportedFunctionalityError,\n  type LanguageModelV4,\n  type SharedV4Warning,\n} from '@ai-sdk/provider';\nimport {\n  asArray,\n  createIdGenerator,\n  DelayedPromise,\n  filterNullable,\n  isAbortError,\n  type Arrayable,\n  type Context,\n  type Experimental_SandboxSession as SandboxSession,\n  type IdGenerator,\n  type InferToolSetContext,\n  type ModelMessage,\n  type ProviderOptions,\n  type ToolApprovalResponse,\n  type ToolContent,\n  type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type { ServerResponse } from 'node:http';\nimport { NoOutputGeneratedError, ToolChoiceViolationError } from '../error';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveLanguageModel } from '../model/resolve-model';\nimport { cloneModelMessages } from '../prompt/clone-model-message';\nimport { createToolModelOutput } from '../prompt/create-tool-model-output';\nimport type { LanguageModelCallOptions } from '../prompt/language-model-call-options';\nimport { prepareLanguageModelCallOptions } from '../prompt/prepare-language-model-call-options';\nimport { prepareToolChoice } from '../prompt/prepare-tool-choice';\nimport { prepareTools } from '../prompt/prepare-tools';\nimport type { Prompt } from '../prompt/prompt';\nimport {\n  getChunkTimeoutMs,\n  getFirstChunkTimeoutMs,\n  getStepTimeoutMs,\n  getTotalTimeoutMs,\n  type RequestOptions,\n  type TimeoutConfiguration,\n} from '../prompt/request-options';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport { wrapGatewayError } from '../prompt/wrap-gateway-error';\nimport type { TelemetryDispatcher } from '../telemetry/telemetry';\nimport type { TelemetryOptions } from '../telemetry/telemetry-options';\nimport { createTextStreamResponse } from '../text-stream/create-text-stream-response';\nimport { pipeTextStreamToResponse } from '../text-stream/pipe-text-stream-to-response';\nimport { toTextStream } from '../text-stream/to-text-stream';\nimport type { LanguageModelRequestMetadata } from '../types';\nimport type {\n  CallWarning,\n  FinishReason,\n  LanguageModel,\n  ToolChoice,\n} from '../types/language-model';\nimport type { ProviderMetadata } from '../types/provider-metadata';\nimport {\n  addLanguageModelUsage,\n  createNullLanguageModelUsage,\n  type LanguageModelUsage,\n} from '../types/usage';\nimport type { UIMessage } from '../ui';\nimport { createUIMessageStreamResponse } from '../ui-message-stream/create-ui-message-stream-response';\nimport { pipeUIMessageStreamToResponse } from '../ui-message-stream/pipe-ui-message-stream-to-response';\nimport { toUIMessageStream as toUIMessageStreamHelper } from '../ui-message-stream/to-ui-message-stream';\nimport type { InferUIMessageChunk } from '../ui-message-stream/ui-message-chunks';\nimport type { UIMessageStreamResponseInit } from '../ui-message-stream/ui-message-stream-response-init';\nimport {\n  createAsyncIterableStream,\n  type AsyncIterableStream,\n} from '../util/async-iterable-stream';\nimport type { Callback } from '../util/callback';\nimport { consumeStream } from '../util/consume-stream';\nimport { createIdMap } from '../util/create-id-map';\nimport { createStitchableStream } from '../util/create-stitchable-stream';\nimport type { DownloadFunction } from '../util/download/download-function';\nimport { getOwn } from '../util/get-own';\nimport { mergeAbortSignals } from '../util/merge-abort-signals';\nimport { mergeObjects } from '../util/merge-objects';\nimport { notify } from '../util/notify';\nimport { now as originalNow } from '../util/now';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { setAbortTimeout } from '../util/set-abort-timeout';\nimport type { ActiveTools } from './active-tools';\nimport { collectToolApprovals } from './collect-tool-approvals';\nimport type { ContentPart } from './content-part';\nimport {\n  executeToolsFromStream,\n  type ExecuteToolsStreamPart,\n} from './execute-tools-from-stream';\nimport { createToolSearchState } from '../tool-search/prepare-tool-search';\nimport { executeToolCall } from './execute-tool-call';\nimport {\n  filterActiveTools,\n  type ActiveToolSubset,\n} from './filter-active-tools';\nimport type {\n  GenerateTextAbortEvent,\n  GenerateTextEndEvent,\n  GenerateTextOnStartCallback,\n  GenerateTextOnStepEndCallback,\n  GenerateTextOnStepFinishCallback,\n  GenerateTextOnStepStartCallback,\n} from './generate-text-events';\nimport { invokeToolCallbacksFromStream } from './invoke-tool-callbacks-from-stream';\nimport type {\n  OnLanguageModelCallEndCallback,\n  OnLanguageModelCallStartCallback,\n} from './language-model-events';\nimport { text, type Output } from './output';\nimport type {\n  InferCompleteOutput,\n  InferElementOutput,\n  InferPartialOutput,\n} from './output-utils';\nimport type { PrepareStepFunction } from './prepare-step';\nimport { prepareStepCallSettings } from './prepare-step-call-settings';\nimport { convertToReasoningOutputs } from './reasoning-output';\nimport type { ResponseMessage } from './response-message';\nimport { createRestrictedTelemetryDispatcher } from './restricted-telemetry-dispatcher';\nimport {\n  DefaultStepResult,\n  type StepResult,\n  type StepResultPerformance,\n} from './step-result';\nimport {\n  isStepCount,\n  isStopConditionMet,\n  type StopCondition,\n} from './stop-condition';\nimport {\n  streamLanguageModelCall,\n  type LanguageModelStreamPart,\n} from './stream-language-model-call';\nimport {\n  createStreamRetryAttemptBoundaryPart,\n  isStreamRetryAttemptBoundaryPart,\n  type StreamRetryAttemptBoundaryPart,\n} from './stream-retry-attempt-boundary';\nimport type {\n  ConsumeStreamOptions,\n  StreamTextResult,\n  TextStreamPart,\n  UIMessageStreamOptions,\n} from './stream-text-result';\nimport { toResponseMessages } from './to-response-messages';\nimport type { ToolApprovalConfiguration } from './tool-approval-configuration';\nimport {\n  appendToolCallerMessages,\n  prepareToolsForToolCallers,\n  resolveToolCallerConfiguration,\n  type Experimental_ToolCallers,\n} from './tool-caller-configuration';\nimport type { TypedToolCall } from './tool-call';\nimport type { ToolCallRepairFunction } from './tool-call-repair-function';\nimport type {\n  OnToolExecutionEndCallback,\n  OnToolExecutionStartCallback,\n} from './tool-execution-events';\nimport type { ToolInputRefinement } from './tool-input-refinement';\nimport type { ToolOrder } from './tool-order';\nimport type { ToolOutput } from './tool-output';\nimport type { StaticToolOutputDenied } from './tool-output-denied';\nimport type { ToolsContextParameter } from './tools-context-parameter';\nimport { validateApprovedToolApprovals } from './validate-tool-approvals';\n\nconst originalGenerateId = createIdGenerator({\n  prefix: 'aitxt',\n  size: 24,\n});\n\nconst originalGenerateCallId = createIdGenerator({\n  prefix: 'call',\n  size: 24,\n});\n\n// Chunk types that contain semantic model output. This classification is used\n// for first-content and inter-content timeouts as well as to distinguish empty\n// incomplete streams from incomplete streams with partial results. It is\n// exhaustive so that new chunk types must be classified explicitly.\nconst isOutputChunkType = {\n  file: true,\n  custom: false,\n  source: false,\n  'text-start': false,\n  'text-end': false,\n  'text-delta': true,\n  'reasoning-start': false,\n  'reasoning-end': false,\n  'reasoning-delta': true,\n  'reasoning-file': true,\n  'tool-input-start': false,\n  'tool-input-end': false,\n  'tool-input-delta': true,\n  'tool-approval-request': false,\n  'tool-approval-response': false,\n  'tool-call': true,\n  'tool-result': false,\n  'tool-error': false,\n  'tool-output-denied': false,\n  'tool-execution-end': false,\n  'model-call-start': false,\n  'model-call-response-metadata': false,\n  'model-call-end': false,\n  error: false,\n  raw: false,\n} as const satisfies Record<\n  Exclude<ExecuteToolsStreamPart, StreamRetryAttemptBoundaryPart>['type'],\n  boolean\n>;\n\nfunction isOutputChunk(\n  chunk: Exclude<ExecuteToolsStreamPart, StreamRetryAttemptBoundaryPart>,\n): boolean {\n  if (!isOutputChunkType[chunk.type]) {\n    return false;\n  }\n\n  switch (chunk.type) {\n    case 'text-delta':\n    case 'reasoning-delta':\n      return chunk.text.length > 0;\n    case 'tool-input-delta':\n      return chunk.delta.length > 0;\n    case 'file':\n    case 'reasoning-file':\n    case 'tool-call':\n      return true;\n    default:\n      return false;\n  }\n}\n\nexport type StreamTextInclude = {\n  /**\n   * Whether to retain the request body in step results.\n   * The request body can be large when sending images or files.\n   *\n   * @default false\n   */\n  requestBody?: boolean;\n\n  /**\n   * Whether to retain the request messages in step results.\n   * The request messages can be large when sending images or files.\n   *\n   * @default false\n   */\n  requestMessages?: boolean;\n\n  /**\n   * Whether to include raw chunks from the provider in the stream.\n   *\n   * When enabled, you will receive raw chunks with type 'raw' that contain\n   * the unprocessed data from the provider.\n   *\n   * This allows access to cutting-edge provider features not yet wrapped by\n   * the AI SDK.\n   *\n   * @default false\n   */\n  rawChunks?: boolean;\n};\n\n/**\n * A transformation that is applied to the stream.\n *\n * @param stopStream - A function that stops the source stream.\n * @param tools - The tools that are accessible to and can be called by the model. The model needs to support calling tools.\n */\nexport type StreamTextTransform<TOOLS extends ToolSet> = (options: {\n  tools: TOOLS; // for type inference\n  stopStream: () => void;\n}) => TransformStream<TextStreamPart<TOOLS>, TextStreamPart<TOOLS>>;\n\n/** A result that requests recovery from a streamed provider error. */\nexport type StreamTextOnErrorResult = { retry: true };\n\n/**\n * Existing observer callback that is set using the `onError` option.\n *\n * @param event - The event that is passed to the callback.\n */\nexport type StreamTextOnErrorCallback = Callback<{ error: unknown }>;\n\n/**\n * Retry-capable callback that is set using the `onError` option.\n *\n * @param event - The event that is passed to the callback.\n */\nexport type StreamTextOnErrorRetryCallback = (event: {\n  error: unknown;\n}) =>\n  | PromiseLike<void | StreamTextOnErrorResult>\n  | void\n  | StreamTextOnErrorResult;\n\ntype StreamTextOnErrorHandler = (event: { error: unknown }) => void;\n\n/**\n * Callback that is set using the `onChunk` option.\n *\n * @param event - The event that is passed to the callback.\n */\nexport type StreamTextOnChunkCallback<TOOLS extends ToolSet> = (event: {\n  chunk: TextStreamPart<TOOLS>;\n}) => PromiseLike<void> | void;\n\nexport type StreamTextEndEvent<\n  TOOLS extends ToolSet = ToolSet,\n  RUNTIME_CONTEXT extends Context = Context,\n  OUTPUT extends Output = Output,\n> = GenerateTextEndEvent<TOOLS, RUNTIME_CONTEXT> & {\n  /**\n   * The parsed output when an output setting was provided and parsing\n   * succeeded.\n   */\n  readonly output?: InferCompleteOutput<OUTPUT>;\n};\n\nexport type StreamTextOnEndCallback<\n  TOOLS extends ToolSet = ToolSet,\n  RUNTIME_CONTEXT extends Context = Context,\n  OUTPUT extends Output = Output,\n> = Callback<StreamTextEndEvent<TOOLS, RUNTIME_CONTEXT, OUTPUT>>;\n\n/**\n * Callback that is set using the `onAbort` option.\n *\n * @param event - The event that is passed to the callback.\n */\nexport type StreamTextOnAbortCallback<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context,\n> = Callback<GenerateTextAbortEvent<TOOLS, RUNTIME_CONTEXT>>;\n\n/**\n * Generate a text and call tools for a given prompt using a language model.\n *\n * This function streams the output. If you do not want to stream the output, use `generateText` instead.\n *\n * @param model - The language model to use.\n * @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.\n * @param toolOrder - Controls the order in which tools are sent to the provider. Tools not listed are appended alphabetically.\n *\n * @param system - A system message that will be part of the prompt.\n * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n * @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false.\n *\n * @param maxOutputTokens - Maximum number of tokens to generate.\n * @param temperature - Temperature setting.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topP - Nucleus sampling.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topK - Only sample from the top K options for each subsequent token.\n * Used to remove \"long tail\" low probability responses.\n * Recommended for advanced use cases only. You usually only need to use temperature.\n * @param presencePenalty - Presence penalty setting.\n * It affects the likelihood of the model to repeat information that is already in the prompt.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param frequencyPenalty - Frequency penalty setting.\n * It affects the likelihood of the model to repeatedly use the same words or phrases.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param stopSequences - Stop sequences.\n * If set, the model will stop generating text when one of the stop sequences is generated.\n * @param seed - The seed (integer) to use for random sampling.\n * If set and supported by the model, calls will generate deterministic results.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param streamRetries - Maximum number of retries for provider errors received after streaming starts. Set to 0 to disable automatic stream retries while allowing `onError` to request retries. Omit to disable all stream retry behavior. Default: 0.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param timeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @param experimental_sandbox - The sandbox environment that is passed through to tool execution.\n * @param runtimeContext - User-defined runtime context that flows through the entire generation lifecycle.\n * @param experimental_refineToolInput - Optional mapping of tool names to functions that refine parsed tool inputs before tools are executed and before outputs, callbacks, and telemetry are recorded.\n *\n * @param onChunk - Callback that is called for each chunk of the stream. The stream processing will pause until the callback promise is resolved.\n * @param onError - Callback that is called when an error occurs during streaming. You can use it to log errors.\n * @param onStart - Callback invoked when generation begins, before any LLM calls.\n * @param experimental_onStart - Deprecated alias for `onStart`.\n * @param onStepStart - Callback invoked when each step begins, before the provider is called.\n * @param experimental_onStepStart - Deprecated alias for `onStepStart`.\n * @param onLanguageModelCallStart - Callback invoked immediately before each provider model call begins.\n * @param experimental_onLanguageModelCallStart - Deprecated alias for `onLanguageModelCallStart`.\n * @param onLanguageModelCallEnd - Callback invoked after each provider model call response is normalized and parsed.\n * @param experimental_onLanguageModelCallEnd - Deprecated alias for `onLanguageModelCallEnd`.\n * @param onToolExecutionStart - Callback invoked before each tool execution begins.\n * @param experimental_onToolCallStart - Deprecated alias for `onToolExecutionStart`.\n * @param onToolExecutionEnd - Callback invoked after each tool execution completes.\n * @param experimental_onToolCallFinish - Deprecated alias for `onToolExecutionEnd`.\n * @param onStepEnd - Callback that is called when each step (LLM call) ends, including intermediate steps.\n * @param onStepFinish - Deprecated alias for `onStepEnd`.\n * @param onEnd - Callback that is called when all steps are finished and the response is complete.\n * @param onFinish - Deprecated alias for `onEnd`.\n *\n * @returns\n * A result object for accessing different stream types and additional information.\n */\nexport function streamText<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context = Context,\n  OUTPUT extends Output = Output<string, string, never>,\n>({\n  model,\n  tools,\n  toolChoice,\n  instructions,\n  system,\n  prompt,\n  messages,\n  allowSystemInMessages,\n  maxRetries,\n  streamRetries,\n  abortSignal,\n  timeout,\n  headers,\n  stopWhen = isStepCount(1),\n  experimental_sandbox: sandbox,\n  output,\n  toolApproval,\n  experimental_toolCallers,\n  experimental_toolApprovalSecret,\n  experimental_telemetry,\n  telemetry = experimental_telemetry,\n  prepareStep,\n  providerOptions,\n  activeTools,\n  toolOrder,\n  experimental_repairToolCall,\n  repairToolCall = experimental_repairToolCall,\n  experimental_refineToolInput: refineToolInput,\n  experimental_transform: transform,\n  experimental_download: download,\n  includeRawChunks,\n  onChunk,\n  onError: onErrorArg,\n  onFinish,\n  onEnd = onFinish,\n  onAbort,\n  onStepEnd,\n  onStepFinish,\n  onStart,\n  experimental_onStart,\n  onStepStart,\n  experimental_onStepStart,\n  onLanguageModelCallStart,\n  experimental_onLanguageModelCallStart,\n  onLanguageModelCallEnd,\n  experimental_onLanguageModelCallEnd,\n  onToolExecutionStart,\n  onToolExecutionEnd,\n  experimental_onToolCallStart,\n  experimental_onToolCallFinish,\n  runtimeContext = {} as RUNTIME_CONTEXT,\n  toolsContext = {} as InferToolSetContext<TOOLS>,\n  experimental_include,\n  include = experimental_include,\n  _internal: {\n    now = originalNow,\n    generateId = originalGenerateId,\n    generateCallId = originalGenerateCallId,\n  } = {},\n  ...settings\n}: LanguageModelCallOptions &\n  RequestOptions<TOOLS> &\n  Prompt &\n  ToolsContextParameter<TOOLS> & {\n    /**\n     * The language model to use.\n     */\n    model: LanguageModel;\n\n    /**\n     * The tool choice strategy. Default: 'auto'.\n     */\n    toolChoice?: ToolChoice<TOOLS>;\n\n    /**\n     * Condition for stopping the generation when there are tool results in the last step.\n     * When the condition is an array, any of the conditions can be met to stop the generation.\n     *\n     * @default isStepCount(1)\n     */\n    stopWhen?: Arrayable<StopCondition<NoInfer<TOOLS>, RUNTIME_CONTEXT>>;\n\n    /**\n     * Optional telemetry configuration.\n     */\n    telemetry?: TelemetryOptions<RUNTIME_CONTEXT, NoInfer<TOOLS>>;\n\n    /**\n     * Optional telemetry configuration.\n     *\n     * @deprecated Use `telemetry` instead. This alias will be removed in a future major release.\n     */\n    experimental_telemetry?: TelemetryOptions<RUNTIME_CONTEXT, NoInfer<TOOLS>>;\n\n    /**\n     * Additional provider-specific options. They are passed through\n     * to the provider from the AI SDK and enable provider-specific\n     * functionality that can be fully encapsulated in the provider.\n     */\n    providerOptions?: ProviderOptions;\n\n    /**\n     * The sandbox environment that is passed through to tool execution.\n     */\n    experimental_sandbox?: SandboxSession;\n\n    /**\n     * Runtime context. Treat runtime context as immutable.\n     * If you need to mutate runtime context, update it in `prepareStep`.\n     */\n    runtimeContext?: RUNTIME_CONTEXT;\n\n    /**\n     * Limits the tools that are available for the model to call without\n     * changing the tool call and result types in the result.\n     */\n    activeTools?: ActiveTools<NoInfer<TOOLS>>;\n\n    /**\n     * Controls the order in which tools are sent to the provider.\n     *\n     * The list can be partial. Tools not listed in `toolOrder` are sent after\n     * the listed tools, sorted alphabetically. This can improve provider-side\n     * caching by keeping tool definitions in a stable order.\n     */\n    toolOrder?: ToolOrder<NoInfer<TOOLS>>;\n\n    /**\n     * Optional specification for parsing structured outputs from the LLM response.\n     */\n    output?: OUTPUT;\n\n    /**\n     * Optional tool approval configuration.\n     *\n     * This configuration takes precedence over tool-defined approval settings.\n     */\n    toolApproval?: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT>;\n\n    /**\n     * Configures which caller tools may invoke each tool.\n     */\n    experimental_toolCallers?: Experimental_ToolCallers<NoInfer<TOOLS>>;\n\n    /**\n     * Secret for HMAC-signing tool approval requests. When set, the server\n     * signs each approval request at issuance and verifies the signature when\n     * the approval is replayed, preventing client-forged approvals.\n     */\n    experimental_toolApprovalSecret?: string | Uint8Array;\n\n    /**\n     * Optional function that you can use to provide different settings for a step.\n     *\n     * @param options - The options for the step.\n     * @param options.steps - The steps that have been executed so far.\n     * @param options.stepNumber - The number of the step that is being executed.\n     * @param options.model - The model that is being used.\n     *\n     * @returns An object that contains the settings for the step.\n     * If you return undefined (or for undefined settings), the settings from the outer level will be used.\n     */\n    prepareStep?: PrepareStepFunction<NoInfer<TOOLS>, RUNTIME_CONTEXT>;\n\n    /**\n     * A function that attempts to repair a tool call that failed to parse.\n     */\n    repairToolCall?: ToolCallRepairFunction<TOOLS>;\n\n    /**\n     * A function that attempts to repair a tool call that failed to parse.\n     *\n     * @deprecated Use `repairToolCall` instead.\n     */\n    experimental_repairToolCall?: ToolCallRepairFunction<TOOLS>;\n\n    /**\n     * Optional mapping of tool names to functions that refine parsed tool inputs.\n     *\n     * The refined input must have the same type shape as the tool input. Refined\n     * inputs are used for tool execution, stream parts, callbacks, and telemetry.\n     */\n    experimental_refineToolInput?: ToolInputRefinement<NoInfer<TOOLS>>;\n\n    /**\n     * Optional stream transformations.\n     * They are applied in the order they are provided.\n     * The stream transformations must maintain the stream structure for streamText to work correctly.\n     */\n    experimental_transform?: Arrayable<StreamTextTransform<TOOLS>>;\n\n    /**\n     * Custom download function to use for URLs.\n     *\n     * By default, files are downloaded if the model does not support the URL for the given media type.\n     */\n    experimental_download?: DownloadFunction | undefined;\n\n    /**\n     * Whether to include raw chunks from the provider in the stream.\n     * When enabled, you will receive raw chunks with type 'raw' that contain the unprocessed data from the provider.\n     * This allows access to cutting-edge provider features not yet wrapped by the AI SDK.\n     * Defaults to false.\n     *\n     * @deprecated Use `include.rawChunks` instead.\n     */\n    includeRawChunks?: boolean;\n\n    /**\n     * Callback that is called for each chunk of the stream.\n     * The stream processing will pause until the callback promise is resolved.\n     */\n    onChunk?: StreamTextOnChunkCallback<TOOLS>;\n\n    /**\n     * Callback that is invoked when an error occurs during streaming.\n     * You can use it to log errors.\n     * Return `{ retry: true }` to retry the current model step after a provider\n     * error is received from the response stream when `streamRetries` is\n     * explicitly configured.\n     * The stream processing will pause until the callback promise is resolved.\n     */\n    onError?:\n      | StreamTextOnErrorCallback\n      | StreamTextOnErrorRetryCallback\n      | StreamTextOnErrorHandler;\n\n    /**\n     * Maximum number of automatic retries for provider errors received after\n     * response streaming has started. Each retry reruns only the current model\n     * step. Completed earlier steps and their tool results are preserved.\n     *\n     * Partial output from a failed attempt that was already emitted cannot be\n     * retracted and remains in consumer-facing streams. It is excluded from\n     * the recovered step result, structured output parsing, response messages,\n     * and subsequent model steps.\n     *\n     * Set to `0` to disable automatic retries while allowing `onError` to\n     * request one retry. When automatic retries are configured, `onError` can\n     * request at most one additional retry after they are exhausted. Omit this\n     * option to disable all stream retry behavior and preserve incremental tool\n     * streaming for existing `onError` observers.\n     *\n     * @default 0 (stream retry behavior disabled when omitted)\n     */\n    streamRetries?: number;\n\n    /**\n     * Callback that is called when the LLM response and all request tool executions\n     * (for tools that have an `execute` function) are finished.\n     *\n     * The usage is the combined usage of all steps.\n     */\n    onEnd?: StreamTextOnEndCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>,\n      NoInfer<OUTPUT>\n    >;\n\n    /**\n     * Callback that is called when the LLM response and all request tool executions\n     * (for tools that have an `execute` function) are finished.\n     *\n     * The usage is the combined usage of all steps.\n     *\n     * @deprecated Use `onEnd` instead.\n     */\n    onFinish?: StreamTextOnEndCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>,\n      NoInfer<OUTPUT>\n    >;\n\n    onAbort?: StreamTextOnAbortCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>\n    >;\n\n    /**\n     * Callback that is called when each step (LLM call) ends, including intermediate steps.\n     */\n    onStepEnd?: GenerateTextOnStepEndCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>\n    >;\n\n    /**\n     * Callback that is called when each step (LLM call) ends, including intermediate steps.\n     *\n     * @deprecated Use `onStepEnd` instead.\n     */\n    onStepFinish?: GenerateTextOnStepFinishCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>\n    >;\n\n    /**\n     * Callback that is called when the streamText operation begins,\n     * before any LLM calls are made.\n     */\n    onStart?: GenerateTextOnStartCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>,\n      NoInfer<OUTPUT>\n    >;\n\n    /**\n     * Callback that is called when the streamText operation begins,\n     * before any LLM calls are made.\n     *\n     * @deprecated Use `onStart` instead.\n     */\n    experimental_onStart?: GenerateTextOnStartCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>,\n      NoInfer<OUTPUT>\n    >;\n\n    /**\n     * Callback that is called when a step (LLM call) begins,\n     * before the provider is called.\n     */\n    onStepStart?: GenerateTextOnStepStartCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>,\n      NoInfer<OUTPUT>\n    >;\n\n    /**\n     * Callback that is called when a step (LLM call) begins,\n     * before the provider is called.\n     *\n     * @deprecated Use `onStepStart` instead.\n     */\n    experimental_onStepStart?: GenerateTextOnStepStartCallback<\n      NoInfer<TOOLS>,\n      NoInfer<RUNTIME_CONTEXT>,\n      NoInfer<OUTPUT>\n    >;\n\n    /**\n     * Callback that is called immediately before the provider model call begins.\n     */\n    onLanguageModelCallStart?: OnLanguageModelCallStartCallback;\n\n    /**\n     * Callback that is called immediately before the provider model call begins.\n     *\n     * @deprecated Use `onLanguageModelCallStart` instead.\n     */\n    experimental_onLanguageModelCallStart?: OnLanguageModelCallStartCallback;\n\n    /**\n     * Callback that is called after the model response has been normalized and parsed,\n     * but before any client-side tool execution begins.\n     */\n    onLanguageModelCallEnd?: OnLanguageModelCallEndCallback<NoInfer<TOOLS>>;\n\n    /**\n     * Callback that is called after the model response has been normalized and parsed,\n     * but before any client-side tool execution begins.\n     *\n     * @deprecated Use `onLanguageModelCallEnd` instead.\n     */\n    experimental_onLanguageModelCallEnd?: OnLanguageModelCallEndCallback<\n      NoInfer<TOOLS>\n    >;\n\n    /**\n     * Callback that is called right before a tool's execute function runs.\n     */\n    onToolExecutionStart?: OnToolExecutionStartCallback<NoInfer<TOOLS>>;\n\n    /**\n     * Callback that is called right before a tool's execute function runs.\n     *\n     * @deprecated Use `onToolExecutionStart` instead.\n     */\n    experimental_onToolCallStart?: OnToolExecutionStartCallback<NoInfer<TOOLS>>;\n\n    /**\n     * Callback that is called right after a tool's execute function completes (or errors).\n     */\n    onToolExecutionEnd?: OnToolExecutionEndCallback<NoInfer<TOOLS>>;\n\n    /**\n     * Callback that is called right after a tool's execute function completes (or errors).\n     *\n     * @deprecated Use `onToolExecutionEnd` instead.\n     */\n    experimental_onToolCallFinish?: OnToolExecutionEndCallback<NoInfer<TOOLS>>;\n\n    /**\n     * Settings for controlling what data is included in step results.\n     * Disabling inclusion can help reduce memory usage when processing\n     * large payloads like images.\n     *\n     * By default, request bodies and request messages are excluded.\n     */\n    include?: StreamTextInclude;\n\n    /**\n     * Settings for controlling what data is included in step results.\n     *\n     * @deprecated Use `include` instead.\n     */\n    experimental_include?: StreamTextInclude;\n\n    /**\n     * Internal. For test use only. May change without notice.\n     */\n    _internal?: {\n      now?: () => number;\n      generateId?: IdGenerator;\n      generateCallId?: IdGenerator;\n    };\n  }): StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT> {\n  const totalTimeoutMs = getTotalTimeoutMs(timeout);\n  const stepTimeoutMs = getStepTimeoutMs(timeout);\n  const firstChunkTimeoutMs = getFirstChunkTimeoutMs(timeout);\n  const chunkTimeoutMs = getChunkTimeoutMs(timeout);\n  const stepAbortController =\n    stepTimeoutMs != null ? new AbortController() : undefined;\n  const firstChunkAbortController =\n    firstChunkTimeoutMs != null ? new AbortController() : undefined;\n  const chunkAbortController =\n    chunkTimeoutMs != null ? new AbortController() : undefined;\n  const onError: StreamTextOnErrorHandler =\n    onErrorArg ??\n    (({ error }) => {\n      console.error(error);\n    });\n  const resolvedOnStart = onStart ?? experimental_onStart;\n  const resolvedOnStepStart = onStepStart ?? experimental_onStepStart;\n  const resolvedOnLanguageModelCallStart =\n    onLanguageModelCallStart ?? experimental_onLanguageModelCallStart;\n  const resolvedOnLanguageModelCallEnd =\n    onLanguageModelCallEnd ?? experimental_onLanguageModelCallEnd;\n  const resolvedOnToolExecutionStart =\n    onToolExecutionStart ?? experimental_onToolCallStart;\n  const resolvedOnToolExecutionEnd =\n    onToolExecutionEnd ?? experimental_onToolCallFinish;\n  const resolvedOnStepEnd = onStepEnd ?? onStepFinish;\n  return new DefaultStreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>({\n    model: resolveLanguageModel(model),\n    telemetry,\n    headers,\n    settings,\n    maxRetries,\n    streamRetries,\n    abortSignal: mergeAbortSignals(\n      abortSignal,\n      totalTimeoutMs,\n      stepAbortController?.signal,\n      firstChunkAbortController?.signal,\n      chunkAbortController?.signal,\n    ),\n    stepTimeoutMs,\n    stepAbortController,\n    firstChunkTimeoutMs,\n    firstChunkAbortController,\n    chunkTimeoutMs,\n    chunkAbortController,\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    experimental_sandbox: sandbox,\n    tools,\n    toolsContext,\n    runtimeContext,\n    toolChoice,\n    transforms: asArray(transform),\n    activeTools,\n    toolOrder,\n    repairToolCall,\n    refineToolInput,\n    stopConditions: asArray(stopWhen),\n    output,\n    toolApproval,\n    experimental_toolCallers,\n    experimental_toolApprovalSecret,\n    providerOptions,\n    prepareStep,\n    timeout,\n    onChunk,\n    onError,\n    canRetryStreamViaOnError: streamRetries !== undefined && onErrorArg != null,\n    onEnd,\n    onAbort,\n    onStepFinish: resolvedOnStepEnd,\n    onStart: resolvedOnStart,\n    onStepStart: resolvedOnStepStart,\n    onLanguageModelCallStart: resolvedOnLanguageModelCallStart,\n    onLanguageModelCallEnd: resolvedOnLanguageModelCallEnd,\n    onToolExecutionStart: resolvedOnToolExecutionStart,\n    onToolExecutionEnd: resolvedOnToolExecutionEnd,\n    now,\n    generateId,\n    generateCallId,\n    download,\n\n    // assign default values to include:\n    include: {\n      requestBody: include?.requestBody ?? false,\n      requestMessages: include?.requestMessages ?? false,\n      rawChunks: include?.rawChunks ?? includeRawChunks ?? false,\n    },\n  });\n}\n\nexport type EnrichedStreamPart<TOOLS extends ToolSet, PARTIAL_OUTPUT> = {\n  part: TextStreamPart<TOOLS>;\n  partialOutput: PARTIAL_OUTPUT | undefined;\n};\n\ntype StreamRetryBoundaryMetadata = {\n  request: LanguageModelRequestMetadata;\n  warnings: Array<CallWarning>;\n};\n\nconst streamRetryBoundarySymbol = Symbol('streamRetryBoundary');\n\ntype StreamRetryBoundaryPart = {\n  [streamRetryBoundarySymbol]: StreamRetryBoundaryMetadata;\n};\n\ntype InternalTextStreamPart<TOOLS extends ToolSet> =\n  | TextStreamPart<TOOLS>\n  | StreamRetryBoundaryPart;\n\ntype InternalEnrichedStreamPart<TOOLS extends ToolSet, PARTIAL_OUTPUT> =\n  | EnrichedStreamPart<TOOLS, PARTIAL_OUTPUT>\n  | StreamRetryBoundaryPart;\n\nfunction isStreamRetryBoundaryPart(\n  part: object,\n): part is StreamRetryBoundaryPart {\n  return streamRetryBoundarySymbol in part;\n}\n\nasync function markPromiseAsHandled<T>(promise: Promise<T>): Promise<void> {\n  try {\n    await promise;\n  } catch {}\n}\n\nfunction createOutputTransformStream<\n  TOOLS extends ToolSet,\n  OUTPUT extends Output,\n>(\n  output: OUTPUT,\n): TransformStream<\n  InternalTextStreamPart<TOOLS>,\n  InternalEnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>\n> {\n  let firstTextChunkId: string | undefined = undefined;\n  let text = '';\n  let textChunk = '';\n  let textProviderMetadata: ProviderMetadata | undefined = undefined;\n  let lastPublishedValue = '';\n\n  function resetAttemptState() {\n    firstTextChunkId = undefined;\n    text = '';\n    textChunk = '';\n    textProviderMetadata = undefined;\n    lastPublishedValue = '';\n  }\n\n  function enqueueChunk({\n    controller,\n    chunk,\n  }: {\n    controller: TransformStreamDefaultController<\n      InternalEnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>\n    >;\n    chunk: EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>;\n  }) {\n    controller.enqueue(chunk);\n  }\n\n  function publishTextChunk({\n    controller,\n    partialOutput = undefined,\n  }: {\n    controller: TransformStreamDefaultController<\n      InternalEnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>\n    >;\n    partialOutput?: InferPartialOutput<OUTPUT>;\n  }) {\n    enqueueChunk({\n      controller,\n      chunk: {\n        part: {\n          type: 'text-delta',\n          id: firstTextChunkId!,\n          text: textChunk,\n          providerMetadata: textProviderMetadata,\n        },\n        partialOutput,\n      },\n    });\n    textChunk = '';\n  }\n\n  return new TransformStream<\n    InternalTextStreamPart<TOOLS>,\n    InternalEnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>\n  >({\n    async transform(chunk, controller) {\n      if (isStreamRetryBoundaryPart(chunk)) {\n        resetAttemptState();\n        controller.enqueue(chunk);\n        return;\n      }\n\n      // ensure that we publish the last text chunk before the step finish:\n      if (chunk.type === 'finish-step' && textChunk.length > 0) {\n        publishTextChunk({ controller });\n      }\n\n      if (\n        chunk.type !== 'text-delta' &&\n        chunk.type !== 'text-start' &&\n        chunk.type !== 'text-end'\n      ) {\n        enqueueChunk({\n          controller,\n          chunk: { part: chunk, partialOutput: undefined },\n        });\n        return;\n      }\n\n      // we have to pick a text chunk which contains the json text\n      // since we are streaming, we have to pick the first text chunk\n      if (firstTextChunkId == null) {\n        firstTextChunkId = chunk.id;\n      } else if (chunk.id !== firstTextChunkId) {\n        enqueueChunk({\n          controller,\n          chunk: { part: chunk, partialOutput: undefined },\n        });\n        return;\n      }\n\n      if (chunk.type === 'text-start') {\n        enqueueChunk({\n          controller,\n          chunk: { part: chunk, partialOutput: undefined },\n        });\n        return;\n      }\n\n      if (chunk.type === 'text-end') {\n        if (textChunk.length > 0) {\n          publishTextChunk({ controller });\n        }\n        enqueueChunk({\n          controller,\n          chunk: { part: chunk, partialOutput: undefined },\n        });\n        return;\n      }\n\n      text += chunk.text;\n      textChunk += chunk.text;\n      textProviderMetadata = chunk.providerMetadata ?? textProviderMetadata;\n\n      if (chunk.text.length === 0 && chunk.providerMetadata != null) {\n        enqueueChunk({\n          controller,\n          chunk: { part: chunk, partialOutput: undefined },\n        });\n        return;\n      }\n\n      // only publish if partial json can be parsed:\n      const result = await output.parsePartialOutput({ text });\n\n      // null should be allowed (valid JSON value) but undefined should not:\n      if (result !== undefined) {\n        // only send new value if it has changed:\n        // For string partials (text output), compare directly to avoid unnecessary JSON.stringify overhead\n        const currentValue =\n          typeof result.partial === 'string'\n            ? result.partial\n            : JSON.stringify(result.partial);\n        if (currentValue !== lastPublishedValue) {\n          publishTextChunk({ controller, partialOutput: result.partial });\n          lastPublishedValue = currentValue;\n        }\n      }\n    },\n  });\n}\n\nfunction applyStreamTextTransforms<TOOLS extends ToolSet>({\n  stream,\n  transforms,\n  tools,\n  stopStream,\n}: {\n  stream: ReadableStream<InternalTextStreamPart<TOOLS>>;\n  transforms: Array<StreamTextTransform<TOOLS>>;\n  tools: TOOLS;\n  stopStream: () => void;\n}): ReadableStream<InternalTextStreamPart<TOOLS>> {\n  const sourceReader = stream.getReader();\n  let sourceDone = false;\n  let pendingBoundary: StreamRetryBoundaryPart | undefined;\n  let transformedSegmentReader:\n    | ReadableStreamDefaultReader<TextStreamPart<TOOLS>>\n    | undefined;\n\n  const createTransformedSegmentReader = () => {\n    let segment = new ReadableStream<TextStreamPart<TOOLS>>(\n      {\n        async pull(controller) {\n          const { done, value } = await sourceReader.read();\n\n          if (done) {\n            sourceDone = true;\n            controller.close();\n            return;\n          }\n\n          if (isStreamRetryBoundaryPart(value)) {\n            pendingBoundary = value;\n            controller.close();\n            return;\n          }\n\n          controller.enqueue(value);\n        },\n        cancel(reason) {\n          return sourceReader.cancel(reason);\n        },\n      },\n      // Do not prefetch the next source chunk. `stopStream` is invoked from a\n      // user transform and must close the gate before another chunk enters it.\n      { highWaterMark: 0 },\n    );\n\n    for (const transform of transforms) {\n      segment = segment.pipeThrough(\n        transform({\n          tools,\n          stopStream,\n        }),\n      );\n    }\n\n    return segment.getReader();\n  };\n\n  return new ReadableStream<InternalTextStreamPart<TOOLS>>({\n    async pull(controller) {\n      transformedSegmentReader ??= createTransformedSegmentReader();\n\n      const { done, value } = await transformedSegmentReader.read();\n\n      if (!done) {\n        controller.enqueue(value);\n        return;\n      }\n\n      transformedSegmentReader = undefined;\n\n      if (pendingBoundary != null) {\n        controller.enqueue(pendingBoundary);\n        pendingBoundary = undefined;\n        return;\n      }\n\n      if (sourceDone) {\n        controller.close();\n      }\n    },\n    async cancel(reason) {\n      await transformedSegmentReader?.cancel(reason);\n      await sourceReader.cancel(reason);\n    },\n  });\n}\n\nclass DefaultStreamTextResult<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context,\n  OUTPUT extends Output,\n> implements StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT> {\n  private readonly _totalUsage = new DelayedPromise<\n    Awaited<StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['usage']>\n  >();\n  private readonly _finishReason = new DelayedPromise<\n    Awaited<StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['finishReason']>\n  >();\n  private readonly _rawFinishReason = new DelayedPromise<\n    Awaited<StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['rawFinishReason']>\n  >();\n  private readonly _steps = new DelayedPromise<\n    Awaited<StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['steps']>\n  >();\n  private readonly _initialResponseMessages = new DelayedPromise<\n    Array<ResponseMessage>\n  >();\n\n  private outputPromise: Promise<InferCompleteOutput<OUTPUT>> | undefined;\n\n  private readonly addStream: (\n    stream: ReadableStream<InternalTextStreamPart<TOOLS>>,\n    callbacks?: {\n      onError?: (error: unknown) => void;\n      onCancel?: () => void;\n    },\n  ) => void;\n\n  private readonly closeStream: () => void;\n\n  private baseStream: ReadableStream<\n    EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>\n  >;\n\n  private outputSpecification: OUTPUT | undefined;\n\n  private tools: TOOLS | undefined;\n\n  constructor({\n    model,\n    telemetry,\n    headers,\n    settings,\n    maxRetries: maxRetriesArg,\n    streamRetries: streamRetriesArg,\n    abortSignal,\n    stepTimeoutMs,\n    stepAbortController,\n    firstChunkTimeoutMs,\n    firstChunkAbortController,\n    chunkTimeoutMs,\n    chunkAbortController,\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    experimental_sandbox: sandbox,\n    tools,\n    toolChoice,\n    transforms,\n    activeTools,\n    toolOrder,\n    repairToolCall,\n    refineToolInput,\n    stopConditions,\n    output,\n    toolApproval,\n    experimental_toolCallers,\n    experimental_toolApprovalSecret,\n    providerOptions,\n    prepareStep,\n    now,\n    generateId,\n    generateCallId,\n    timeout,\n    onChunk,\n    onError,\n    canRetryStreamViaOnError,\n    onEnd,\n    onAbort,\n    onStepFinish,\n    onStart,\n    onStepStart,\n    onLanguageModelCallStart,\n    onLanguageModelCallEnd,\n    onToolExecutionStart,\n    onToolExecutionEnd,\n    runtimeContext,\n    toolsContext,\n    download,\n    include,\n  }: {\n    model: LanguageModelV4;\n    telemetry: TelemetryOptions<RUNTIME_CONTEXT, TOOLS> | undefined;\n    headers: Record<string, string | undefined> | undefined;\n    settings: LanguageModelCallOptions;\n    maxRetries: number | undefined;\n    streamRetries: number | undefined;\n    abortSignal: AbortSignal | undefined;\n    stepTimeoutMs: number | undefined;\n    stepAbortController: AbortController | undefined;\n    firstChunkTimeoutMs: number | undefined;\n    firstChunkAbortController: AbortController | undefined;\n    chunkTimeoutMs: number | undefined;\n    chunkAbortController: AbortController | undefined;\n    toolsContext: InferToolSetContext<TOOLS>;\n    runtimeContext: RUNTIME_CONTEXT;\n    instructions: Prompt['instructions'];\n    system: Prompt['system'];\n    prompt: Prompt['prompt'];\n    messages: Prompt['messages'];\n    allowSystemInMessages: Prompt['allowSystemInMessages'];\n    experimental_sandbox: SandboxSession | undefined;\n    tools: TOOLS | undefined;\n    toolChoice: ToolChoice<TOOLS> | undefined;\n    transforms: Array<StreamTextTransform<TOOLS>>;\n    activeTools: ActiveTools<TOOLS>;\n    toolOrder: ToolOrder<TOOLS>;\n    repairToolCall: ToolCallRepairFunction<TOOLS> | undefined;\n    refineToolInput: ToolInputRefinement<TOOLS> | undefined;\n    stopConditions: Array<\n      StopCondition<NoInfer<TOOLS>, NoInfer<RUNTIME_CONTEXT>>\n    >;\n    output: OUTPUT | undefined;\n    toolApproval: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT> | undefined;\n    experimental_toolCallers: Experimental_ToolCallers<TOOLS> | undefined;\n    experimental_toolApprovalSecret: string | Uint8Array | undefined;\n    providerOptions: ProviderOptions | undefined;\n    prepareStep:\n      | PrepareStepFunction<NoInfer<TOOLS>, NoInfer<RUNTIME_CONTEXT>>\n      | undefined;\n    now: () => number;\n    generateId: () => string;\n    generateCallId: () => string;\n    timeout: TimeoutConfiguration<TOOLS> | undefined;\n    download: DownloadFunction | undefined;\n    include: Required<StreamTextInclude>;\n\n    // callbacks:\n    onChunk: undefined | StreamTextOnChunkCallback<TOOLS>;\n    onError: StreamTextOnErrorHandler;\n    canRetryStreamViaOnError: boolean;\n    onEnd:\n      | undefined\n      | StreamTextOnEndCallback<\n          NoInfer<TOOLS>,\n          NoInfer<RUNTIME_CONTEXT>,\n          NoInfer<OUTPUT>\n        >;\n    onAbort:\n      | undefined\n      | StreamTextOnAbortCallback<NoInfer<TOOLS>, NoInfer<RUNTIME_CONTEXT>>;\n    onStepFinish:\n      | undefined\n      | GenerateTextOnStepFinishCallback<\n          NoInfer<TOOLS>,\n          NoInfer<RUNTIME_CONTEXT>\n        >;\n    onStart:\n      | undefined\n      | GenerateTextOnStartCallback<\n          NoInfer<TOOLS>,\n          NoInfer<RUNTIME_CONTEXT>,\n          NoInfer<OUTPUT>\n        >;\n    onStepStart:\n      | undefined\n      | GenerateTextOnStepStartCallback<\n          NoInfer<TOOLS>,\n          NoInfer<RUNTIME_CONTEXT>,\n          NoInfer<OUTPUT>\n        >;\n    onLanguageModelCallStart: undefined | OnLanguageModelCallStartCallback;\n    onLanguageModelCallEnd:\n      | undefined\n      | OnLanguageModelCallEndCallback<NoInfer<TOOLS>>;\n    onToolExecutionStart: undefined | OnToolExecutionStartCallback<TOOLS>;\n    onToolExecutionEnd: undefined | OnToolExecutionEndCallback<TOOLS>;\n  }) {\n    this.outputSpecification = output;\n    this.tools = tools;\n    const resolvedToolCallers = resolveToolCallerConfiguration({\n      tools,\n      toolCallers: experimental_toolCallers,\n    });\n    const prepareToolSearch = createToolSearchState({\n      tools,\n      toolCallers: resolvedToolCallers,\n    });\n\n    const telemetryDispatcher = createRestrictedTelemetryDispatcher<\n      TOOLS,\n      RUNTIME_CONTEXT,\n      OUTPUT\n    >({\n      telemetry,\n      includeRuntimeContext: telemetry?.includeRuntimeContext,\n      includeToolsContext: telemetry?.includeToolsContext,\n    });\n\n    // promise to ensure that the step has been fully processed by the event processor\n    // before a new step is started. This is required because the continuation condition\n    // needs the updated steps to determine if another step is needed.\n    let stepFinish!: DelayedPromise<void>;\n\n    let recordedContent: Array<ContentPart<TOOLS>> = [];\n    let recordedFinishReason: FinishReason | undefined = undefined;\n    let recordedRawFinishReason: string | undefined = undefined;\n    let recordedTotalUsage: LanguageModelUsage | undefined = undefined;\n    let recordedRequest: Omit<LanguageModelRequestMetadata, 'messages'> = {};\n    let recordedRequestMessages: Array<ModelMessage> = [];\n    let recordedWarnings: Array<CallWarning> = [];\n    const recordedSteps: StepResult<TOOLS, RUNTIME_CONTEXT>[] = [];\n    const initialResponseMessages: Array<ResponseMessage> = [];\n    let stepMessagesForNextStep: Array<ModelMessage> | undefined;\n    let currentStepMessages: Array<ModelMessage> = [];\n\n    // provider-assigned text/reasoning part IDs are only unique within a\n    // single model call (e.g. Anthropic uses the content block index, which\n    // restarts at 0 for every call), so colliding IDs are remapped to keep\n    // them unique across the whole multi-step stream:\n    const createPartIdReserver = () => {\n      const usedIds = new Set<string>();\n\n      return (id: string) => {\n        if (!usedIds.has(id)) {\n          usedIds.add(id);\n          return id;\n        }\n\n        const generatedId = generateId();\n        let uniqueId = generatedId;\n        let suffix = 0;\n\n        while (usedIds.has(uniqueId)) {\n          uniqueId = `${generatedId}-${++suffix}`;\n        }\n\n        usedIds.add(uniqueId);\n        return uniqueId;\n      };\n    };\n\n    const reserveTextPartId = createPartIdReserver();\n    const reserveReasoningPartId = createPartIdReserver();\n\n    // Track provider-executed tool calls that support deferred results\n    // (e.g., code_execution in programmatic tool calling scenarios).\n    // These tools may not return their results in the same turn as their call.\n    const pendingDeferredToolCalls = new Map<string, { toolName: string }>();\n\n    let activeTextContent: Record<\n      string,\n      {\n        type: 'text';\n        text: string;\n        providerMetadata: ProviderMetadata | undefined;\n      }\n    > = createIdMap();\n\n    let activeReasoningContent: Record<\n      string,\n      {\n        type: 'reasoning';\n        text: string;\n        providerMetadata: ProviderMetadata | undefined;\n      }\n    > = createIdMap();\n    let recordedNoOutputError: NoOutputGeneratedError | undefined;\n    const errorsHandledForStreamRetry = new Set<unknown>();\n\n    const eventProcessor = new TransformStream<\n      InternalEnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>,\n      EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>\n    >({\n      async transform(chunk, controller) {\n        if (isStreamRetryBoundaryPart(chunk)) {\n          const retryBoundary = chunk[streamRetryBoundarySymbol];\n          recordedContent = [];\n          activeReasoningContent = createIdMap();\n          activeTextContent = createIdMap();\n          recordedRequest = retryBoundary.request;\n          recordedRequestMessages = retryBoundary.request.messages ?? [];\n          recordedWarnings = retryBoundary.warnings;\n          return;\n        }\n\n        const { part } = chunk;\n        controller.enqueue(chunk); // forward the chunk to the next stream\n\n        const callbacksHandledForStreamRetry =\n          part.type === 'error' && errorsHandledForStreamRetry.has(part.error);\n\n        if (!callbacksHandledForStreamRetry) {\n          await notify({\n            event: { chunk: part },\n            callbacks: onChunk,\n          });\n        }\n\n        if (part.type === 'error') {\n          const error = wrapGatewayError(part.error);\n\n          if (NoOutputGeneratedError.isInstance(error)) {\n            recordedNoOutputError = error;\n          }\n\n          if (callbacksHandledForStreamRetry) {\n            errorsHandledForStreamRetry.delete(part.error);\n          } else {\n            await notify({\n              event: { error },\n              callbacks: async event => {\n                await onError(event);\n              },\n            });\n          }\n        }\n\n        if (\n          part.type === 'custom' ||\n          part.type === 'source' ||\n          part.type === 'tool-call' ||\n          part.type === 'tool-approval-request' ||\n          part.type === 'tool-approval-response' ||\n          part.type === 'tool-error'\n        ) {\n          recordedContent.push(part);\n        }\n\n        if (part.type === 'text-start') {\n          activeTextContent[part.id] = {\n            type: 'text',\n            text: '',\n            providerMetadata: part.providerMetadata,\n          };\n\n          recordedContent.push(activeTextContent[part.id]);\n        }\n\n        if (part.type === 'text-delta') {\n          const activeText = activeTextContent[part.id];\n\n          if (activeText == null) {\n            controller.enqueue({\n              part: {\n                type: 'error',\n                error: `text part ${part.id} not found`,\n              },\n              partialOutput: undefined,\n            });\n            return;\n          }\n\n          activeText.text += part.text;\n          activeText.providerMetadata =\n            part.providerMetadata ?? activeText.providerMetadata;\n        }\n\n        if (part.type === 'text-end') {\n          const activeText = activeTextContent[part.id];\n\n          if (activeText == null) {\n            controller.enqueue({\n              part: {\n                type: 'error',\n                error: `text part ${part.id} not found`,\n              },\n              partialOutput: undefined,\n            });\n            return;\n          }\n\n          activeText.providerMetadata =\n            part.providerMetadata ?? activeText.providerMetadata;\n\n          delete activeTextContent[part.id];\n        }\n\n        if (part.type === 'reasoning-start') {\n          activeReasoningContent[part.id] = {\n            type: 'reasoning',\n            text: '',\n            providerMetadata: part.providerMetadata,\n          };\n\n          recordedContent.push(activeReasoningContent[part.id]);\n        }\n\n        if (part.type === 'reasoning-delta') {\n          const activeReasoning = activeReasoningContent[part.id];\n\n          if (activeReasoning == null) {\n            controller.enqueue({\n              part: {\n                type: 'error',\n                error: `reasoning part ${part.id} not found`,\n              },\n              partialOutput: undefined,\n            });\n            return;\n          }\n\n          activeReasoning.text += part.text;\n          activeReasoning.providerMetadata =\n            part.providerMetadata ?? activeReasoning.providerMetadata;\n        }\n\n        if (part.type === 'reasoning-end') {\n          const activeReasoning = activeReasoningContent[part.id];\n\n          if (activeReasoning == null) {\n            controller.enqueue({\n              part: {\n                type: 'error',\n                error: `reasoning part ${part.id} not found`,\n              },\n              partialOutput: undefined,\n            });\n            return;\n          }\n\n          activeReasoning.providerMetadata =\n            part.providerMetadata ?? activeReasoning.providerMetadata;\n\n          delete activeReasoningContent[part.id];\n        }\n\n        if (part.type === 'file' || part.type === 'reasoning-file') {\n          recordedContent.push({\n            type: part.type,\n            file: part.file,\n            ...(part.providerMetadata != null\n              ? { providerMetadata: part.providerMetadata }\n              : {}),\n          });\n        }\n\n        if (part.type === 'tool-result' && !part.preliminary) {\n          recordedContent.push(part);\n        }\n\n        if (part.type === 'start-step') {\n          // reset the recorded data when a new step starts:\n          recordedContent = [];\n          activeReasoningContent = createIdMap();\n          activeTextContent = createIdMap();\n\n          recordedRequest = part.request;\n          recordedWarnings = part.warnings;\n        }\n\n        if (part.type === 'finish-step') {\n          const stepResponseMessages = await toResponseMessages({\n            content: recordedContent,\n            tools,\n          });\n\n          // Add step information (after response messages are updated):\n          const currentStepResult: StepResult<TOOLS, RUNTIME_CONTEXT> =\n            new DefaultStepResult({\n              callId,\n              stepNumber: recordedSteps.length,\n              provider: model.provider,\n              modelId: model.modelId,\n              runtimeContext,\n              toolsContext,\n              content: recordedContent,\n              finishReason: part.finishReason,\n              rawFinishReason: part.rawFinishReason,\n              usage: part.usage,\n              performance: part.performance,\n              warnings: recordedWarnings,\n              request: {\n                ...recordedRequest,\n                messages: include.requestMessages\n                  ? cloneModelMessages(recordedRequestMessages)\n                  : undefined,\n              },\n              response: {\n                ...part.response,\n                messages: cloneModelMessages(stepResponseMessages),\n              },\n              providerMetadata: part.providerMetadata,\n            });\n\n          await notify({\n            event: currentStepResult,\n            callbacks: [onStepFinish, telemetryDispatcher.onStepEnd],\n          });\n\n          logWarnings({\n            warnings: recordedWarnings,\n            provider: model.provider,\n            model: model.modelId,\n          });\n\n          recordedSteps.push(currentStepResult);\n          stepMessagesForNextStep = [\n            ...currentStepMessages,\n            ...stepResponseMessages,\n          ];\n\n          // resolve the promise to signal that the step has been fully processed\n          // by the event processor:\n          stepFinish.resolve();\n        }\n\n        if (part.type === 'finish') {\n          recordedTotalUsage = part.totalUsage;\n          recordedFinishReason = part.finishReason;\n          recordedRawFinishReason = part.rawFinishReason;\n        }\n      },\n\n      async flush(controller) {\n        try {\n          // reject when no output was generated or an incomplete model stream\n          // ended a continuation step:\n          if (recordedSteps.length === 0 || recordedNoOutputError != null) {\n            const error = abortSignal?.aborted\n              ? abortSignal.reason\n              : (recordedNoOutputError ??\n                new NoOutputGeneratedError({\n                  message: 'No output generated. Check the stream for errors.',\n                }));\n\n            self.rejectResultPromises(error);\n\n            return; // no steps recorded (e.g. in error scenario)\n          }\n\n          // derived:\n          const finishReason = recordedFinishReason ?? 'other';\n          const totalUsage =\n            recordedTotalUsage ?? createNullLanguageModelUsage();\n\n          // from finish:\n          self._finishReason.resolve(finishReason);\n          self._rawFinishReason.resolve(recordedRawFinishReason);\n          self._totalUsage.resolve(totalUsage);\n\n          // aggregate results:\n          self._steps.resolve(recordedSteps);\n\n          // call onEnd callback:\n          const finalStep = recordedSteps[recordedSteps.length - 1];\n          const content = recordedSteps.flatMap(step => step.content);\n          const files = recordedSteps.flatMap(step => step.files);\n          const sources = recordedSteps.flatMap(step => step.sources);\n          const toolCalls = recordedSteps.flatMap(step => step.toolCalls);\n          const staticToolCalls = recordedSteps.flatMap(\n            step => step.staticToolCalls,\n          );\n          const dynamicToolCalls = recordedSteps.flatMap(\n            step => step.dynamicToolCalls,\n          );\n          const toolResults = recordedSteps.flatMap(step => step.toolResults);\n          const staticToolResults = recordedSteps.flatMap(\n            step => step.staticToolResults,\n          );\n          const dynamicToolResults = recordedSteps.flatMap(\n            step => step.dynamicToolResults,\n          );\n          const warnings = recordedSteps.flatMap(step => step.warnings ?? []);\n          const onEndWithOutput =\n            onEnd == null\n              ? undefined\n              : async (event: GenerateTextEndEvent<TOOLS, RUNTIME_CONTEXT>) => {\n                  const parsedOutput =\n                    output == null\n                      ? undefined\n                      : await self.getOutputPromise().catch(() => undefined);\n\n                  await onEnd({\n                    ...event,\n                    ...(output != null ? { output: parsedOutput } : {}),\n                  });\n                };\n\n          const onEndEvent = {\n            callId,\n            toolsContext: finalStep.toolsContext,\n            stepNumber: finalStep.stepNumber,\n            model: finalStep.model,\n            runtimeContext: finalStep.runtimeContext,\n            finishReason: finalStep.finishReason,\n            rawFinishReason: finalStep.rawFinishReason,\n            usage: totalUsage,\n            totalUsage,\n            content,\n            text: finalStep.text,\n            reasoning: finalStep.reasoning,\n            reasoningText: finalStep.reasoningText,\n            files,\n            sources,\n            toolCalls,\n            staticToolCalls,\n            dynamicToolCalls,\n            toolResults,\n            staticToolResults,\n            dynamicToolResults,\n            responseMessages: [\n              ...initialResponseMessages,\n              ...recordedSteps.flatMap(step => step.response.messages),\n            ],\n            warnings,\n            request: finalStep.request,\n            response: finalStep.response,\n            providerMetadata: finalStep.providerMetadata,\n            steps: recordedSteps,\n            finalStep,\n          };\n\n          await Promise.all([\n            notify({\n              event: onEndEvent,\n              callbacks: onEndWithOutput,\n            }),\n            notify({\n              event: onEndEvent,\n              callbacks: telemetryDispatcher.onEnd,\n            }),\n          ]);\n        } catch (error) {\n          controller.error(error);\n        }\n      },\n    });\n\n    // initialize the stitchable stream and the transformed stream:\n    const stitchableStream =\n      createStitchableStream<InternalTextStreamPart<TOOLS>>();\n    this.addStream = stitchableStream.addStream;\n    this.closeStream = stitchableStream.close;\n\n    // resilient stream that handles abort signals and errors:\n    const reader = stitchableStream.stream.getReader();\n    let stream = new ReadableStream<InternalTextStreamPart<TOOLS>>({\n      async start(controller) {\n        // send start event:\n        controller.enqueue({ type: 'start' });\n      },\n\n      async pull(controller) {\n        // abort handling:\n        async function abort() {\n          await notify({\n            event: {\n              callId,\n              steps: recordedSteps,\n              ...(abortSignal?.reason !== undefined\n                ? { reason: abortSignal.reason }\n                : {}),\n            },\n            callbacks: [onAbort, telemetryDispatcher.onAbort],\n          });\n          controller.enqueue({\n            type: 'abort',\n            // The `reason` is usually of type DOMException, but it can also be of any type,\n            // so we use getErrorMessage for serialization because it is already designed to accept values of the unknown type.\n            // See: https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/reason\n            ...(abortSignal?.reason !== undefined\n              ? { reason: getErrorMessage(abortSignal.reason) }\n              : {}),\n          });\n          controller.close();\n        }\n\n        try {\n          const { done, value } = await reader.read();\n\n          if (done) {\n            controller.close();\n            return;\n          }\n\n          if (abortSignal?.aborted) {\n            await abort();\n            return;\n          }\n\n          controller.enqueue(value);\n        } catch (error) {\n          if (isAbortError(error) && abortSignal?.aborted) {\n            await abort();\n          } else {\n            controller.error(error);\n          }\n        }\n      },\n\n      cancel(reason) {\n        return stitchableStream.stream.cancel(reason);\n      },\n    });\n\n    // introduce a gate that prevent further tokens from\n    // being emitted after a transform calls stopStream\n    let isRunning = true;\n    stream = stream.pipeThrough(\n      new TransformStream({\n        async transform(chunk, controller) {\n          if (isRunning) {\n            controller.enqueue(chunk);\n          }\n        },\n      }),\n    );\n\n    // Transform each retry attempt independently. The retry boundary is\n    // intercepted outside user transforms, so transforms may filter or\n    // reconstruct any public stream part without losing logical isolation.\n    stream = applyStreamTextTransforms({\n      stream,\n      transforms,\n      tools: tools as TOOLS,\n      stopStream() {\n        stitchableStream.terminate();\n        isRunning = false;\n      },\n    });\n\n    this.baseStream = stream\n      .pipeThrough(createOutputTransformStream(output ?? text()))\n      .pipeThrough(eventProcessor);\n\n    const { maxRetries } = prepareRetries({\n      maxRetries: maxRetriesArg,\n      abortSignal,\n    });\n    const { maxRetries: streamRetries } = prepareRetries({\n      maxRetries: streamRetriesArg,\n      abortSignal,\n      parameter: 'streamRetries',\n      defaultMaxRetries: 0,\n    });\n\n    const callSettings = prepareLanguageModelCallOptions(settings);\n\n    const self = this;\n\n    const callId = generateCallId();\n\n    (async () => {\n      const initialPrompt = await standardizePrompt({\n        instructions,\n        system,\n        prompt,\n        messages,\n        allowSystemInMessages,\n      } as Prompt);\n\n      const startEvent = {\n        callId,\n        operationId: 'ai.streamText',\n        provider: model.provider,\n        modelId: model.modelId,\n        instructions: initialPrompt.instructions,\n        messages: initialPrompt.messages,\n        tools,\n        toolChoice,\n        activeTools,\n        toolOrder,\n        maxOutputTokens: callSettings.maxOutputTokens,\n        temperature: callSettings.temperature,\n        topP: callSettings.topP,\n        topK: callSettings.topK,\n        presencePenalty: callSettings.presencePenalty,\n        frequencyPenalty: callSettings.frequencyPenalty,\n        stopSequences: callSettings.stopSequences,\n        seed: callSettings.seed,\n        reasoning: callSettings.reasoning,\n        maxRetries,\n        timeout,\n        headers,\n        providerOptions,\n        output,\n        runtimeContext,\n        toolsContext,\n      };\n\n      const streamTextTracingChannelContext =\n        telemetryDispatcher.startTracingChannelContext?.({\n          type: 'streamText',\n          event: startEvent,\n          completion: self._totalUsage.promise.then(() => undefined),\n        });\n      // Re-enter the streamText tracing context after stream setup returns.\n      const runInStreamTextTracingChannelContext = <T>(execute: () => T): T =>\n        streamTextTracingChannelContext?.run(execute) ?? execute();\n      const runInTracingChannelSpanInStreamText =\n        telemetryDispatcher.runInTracingChannelSpan == null\n          ? undefined\n          : <T>(\n              options: Parameters<\n                NonNullable<TelemetryDispatcher['runInTracingChannelSpan']>\n              >[0] & {\n                execute: () => PromiseLike<T>;\n              },\n            ) =>\n              runInStreamTextTracingChannelContext(() =>\n                telemetryDispatcher.runInTracingChannelSpan!(options),\n              );\n\n      await notify({\n        event: startEvent,\n        callbacks: [onStart, telemetryDispatcher.onStart],\n      });\n\n      const initialMessages = initialPrompt.messages;\n      let instructionsForNextStep = initialPrompt.instructions;\n\n      const { approvedToolApprovals, deniedToolApprovals } =\n        collectToolApprovals<TOOLS>({ messages: initialMessages });\n\n      // initial tool execution step stream\n      if (deniedToolApprovals.length > 0 || approvedToolApprovals.length > 0) {\n        const {\n          approvedToolApprovals: localApprovedToolApprovals,\n          deniedToolApprovals: revalidationDeniedToolApprovals,\n          invalidToolApprovals,\n        } = await validateApprovedToolApprovals<TOOLS, RUNTIME_CONTEXT>({\n          approvedToolApprovals: approvedToolApprovals.filter(\n            toolApproval => !toolApproval.toolCall.providerExecuted,\n          ),\n          tools,\n          toolApproval,\n          messages: initialMessages,\n          toolsContext,\n          runtimeContext,\n          toolApprovalSecret: experimental_toolApprovalSecret,\n        });\n\n        const localDeniedToolApprovals = [\n          ...deniedToolApprovals.filter(\n            toolApproval => !toolApproval.toolCall.providerExecuted,\n          ),\n          ...revalidationDeniedToolApprovals,\n        ];\n        const localDeniedToolApprovalsWithoutResults =\n          localDeniedToolApprovals.filter(\n            toolApproval => toolApproval.existingToolResult == null,\n          );\n\n        const deniedProviderExecutedToolApprovals = deniedToolApprovals.filter(\n          toolApproval => toolApproval.toolCall.providerExecuted,\n        );\n\n        let toolExecutionStepStreamController:\n          | ReadableStreamDefaultController<TextStreamPart<TOOLS>>\n          | undefined;\n        const toolExecutionStepStream = new ReadableStream<\n          TextStreamPart<TOOLS>\n        >({\n          start(controller) {\n            toolExecutionStepStreamController = controller;\n          },\n        });\n\n        self.addStream(toolExecutionStepStream);\n\n        try {\n          for (const toolApproval of [\n            ...localDeniedToolApprovals,\n            ...deniedProviderExecutedToolApprovals,\n          ]) {\n            toolExecutionStepStreamController?.enqueue({\n              type: 'tool-output-denied',\n              toolCallId: toolApproval.toolCall.toolCallId,\n              toolName: toolApproval.toolCall.toolName,\n            } as StaticToolOutputDenied<TOOLS>);\n          }\n\n          for (const toolApproval of invalidToolApprovals) {\n            toolExecutionStepStreamController?.enqueue({\n              type: 'tool-error',\n              toolCallId: toolApproval.toolCall.toolCallId,\n              toolName: toolApproval.toolCall.toolName,\n              input: toolApproval.toolCall.input,\n              error: getErrorMessage(toolApproval.error),\n              title: toolApproval.toolCall.title,\n              ...(toolApproval.toolCall.dynamic === true\n                ? { dynamic: true as const }\n                : {}),\n              ...(toolApproval.toolCall.toolMetadata != null\n                ? { toolMetadata: toolApproval.toolCall.toolMetadata }\n                : {}),\n            } as TextStreamPart<TOOLS>);\n          }\n\n          const toolOutputs: Array<ToolOutput<TOOLS>> = [];\n\n          await Promise.all(\n            localApprovedToolApprovals.map(async toolApproval => {\n              const result = await executeToolCall({\n                toolCall: toolApproval.toolCall,\n                tools,\n                callId,\n                messages: initialMessages,\n                abortSignal,\n                timeout,\n                experimental_sandbox: sandbox,\n                toolsContext,\n                onToolExecutionStart: filterNullable(\n                  onToolExecutionStart,\n                  telemetryDispatcher.onToolExecutionStart,\n                ),\n                onToolExecutionEnd: filterNullable(\n                  onToolExecutionEnd,\n                  telemetryDispatcher.onToolExecutionEnd,\n                ),\n                executeToolInTelemetryContext: telemetryDispatcher.executeTool,\n                runInTracingChannelSpan: runInTracingChannelSpanInStreamText,\n                onPreliminaryToolResult: result => {\n                  toolExecutionStepStreamController?.enqueue(result);\n                },\n              });\n\n              if (result != null) {\n                toolExecutionStepStreamController?.enqueue(result.output);\n                toolOutputs.push(result.output);\n              }\n            }),\n          );\n\n          // Local tool results (approved + denied) are sent as tool results:\n          if (\n            toolOutputs.length > 0 ||\n            localDeniedToolApprovalsWithoutResults.length > 0 ||\n            invalidToolApprovals.length > 0\n          ) {\n            const localToolContent: ToolContent = [];\n\n            // add regular tool results for approved tool calls:\n            for (const output of toolOutputs) {\n              localToolContent.push({\n                type: 'tool-result' as const,\n                toolCallId: output.toolCallId,\n                toolName: output.toolName,\n                output: await createToolModelOutput({\n                  toolCallId: output.toolCallId,\n                  input: output.input,\n                  tool: getOwn(tools, output.toolName),\n                  output:\n                    output.type === 'tool-result'\n                      ? output.output\n                      : output.error,\n                  errorMode: output.type === 'tool-error' ? 'text' : 'none',\n                }),\n              });\n            }\n\n            // Report invalid approved tool calls to the model without\n            // executing them. Repairing the input after approval would change\n            // the operation that the user authorized.\n            for (const toolApproval of invalidToolApprovals) {\n              localToolContent.push({\n                type: 'tool-result' as const,\n                toolCallId: toolApproval.toolCall.toolCallId,\n                toolName: toolApproval.toolCall.toolName,\n                output: await createToolModelOutput({\n                  toolCallId: toolApproval.toolCall.toolCallId,\n                  input: toolApproval.toolCall.input,\n                  tool: getOwn(tools, toolApproval.toolCall.toolName),\n                  output: toolApproval.error,\n                  errorMode: 'text',\n                }),\n              });\n            }\n\n            // add execution denied tool results for denied local tool approvals:\n            for (const toolApproval of localDeniedToolApprovalsWithoutResults) {\n              localToolContent.push({\n                type: 'tool-result' as const,\n                toolCallId: toolApproval.toolCall.toolCallId,\n                toolName: toolApproval.toolCall.toolName,\n                output: {\n                  type: 'execution-denied' as const,\n                  reason: toolApproval.approvalResponse.reason,\n                },\n              });\n            }\n\n            initialResponseMessages.push({\n              role: 'tool',\n              content: localToolContent,\n            });\n          }\n        } finally {\n          toolExecutionStepStreamController?.close();\n        }\n      }\n\n      self._initialResponseMessages.resolve(initialResponseMessages);\n\n      async function streamStep({\n        currentStep,\n        usage,\n      }: {\n        currentStep: number;\n        usage: LanguageModelUsage;\n      }) {\n        // Set up step timeout if configured\n        const stepTimeoutId = setAbortTimeout({\n          abortController: stepAbortController,\n          label: 'Step',\n          timeoutMs: stepTimeoutMs,\n        });\n\n        // The first-content timeout is armed when the provider response stream\n        // starts and is cleared by the first semantic output chunk.\n        let firstChunkTimeoutId: ReturnType<typeof setTimeout> | undefined =\n          undefined;\n\n        function startFirstChunkTimeout() {\n          if (abortSignal?.aborted) {\n            return;\n          }\n\n          firstChunkTimeoutId = setAbortTimeout({\n            abortController: firstChunkAbortController,\n            label: 'First chunk',\n            timeoutMs: firstChunkTimeoutMs,\n          });\n        }\n\n        function clearFirstChunkTimeout() {\n          if (firstChunkTimeoutId != null) {\n            clearTimeout(firstChunkTimeoutId);\n            firstChunkTimeoutId = undefined;\n          }\n        }\n\n        // Chunk timeout tracking starts after semantic output begins and is\n        // reset only by subsequent semantic output chunks.\n        let chunkTimeoutId: ReturnType<typeof setTimeout> | undefined =\n          undefined;\n\n        function resetChunkTimeout() {\n          if (chunkTimeoutId != null) {\n            clearTimeout(chunkTimeoutId);\n          }\n          chunkTimeoutId = setAbortTimeout({\n            abortController: chunkAbortController,\n            label: 'Chunk',\n            timeoutMs: chunkTimeoutMs,\n          });\n        }\n\n        function clearChunkTimeout() {\n          if (chunkTimeoutId != null) {\n            clearTimeout(chunkTimeoutId);\n            chunkTimeoutId = undefined;\n          }\n        }\n\n        function clearStepTimeout() {\n          if (stepTimeoutId != null) {\n            clearTimeout(stepTimeoutId);\n          }\n        }\n\n        function clearStepTimeouts() {\n          clearStepTimeout();\n          clearFirstChunkTimeout();\n          clearChunkTimeout();\n        }\n\n        function cleanupStepTimeouts() {\n          abortSignal?.removeEventListener('abort', cleanupStepTimeouts);\n          clearStepTimeouts();\n        }\n\n        // The step's stream is registered lazily and consumed long after this\n        // function returns, so its timers must stay armed past setup. When the\n        // merged abort signal fires, drop all step-scoped timers so none\n        // outlives the step.\n        abortSignal?.addEventListener('abort', cleanupStepTimeouts, {\n          once: true,\n        });\n\n        try {\n          stepFinish = new DelayedPromise<void>();\n\n          const stepTracingChannelContext =\n            telemetryDispatcher.startTracingChannelContext?.({\n              type: 'step',\n              event: { callId, stepNumber: currentStep },\n              completion: stepFinish.promise,\n            });\n          // Re-enter the current step before creating child spans.\n          const runInStepTracingChannelContext = <T>(execute: () => T): T =>\n            stepTracingChannelContext?.run(execute) ?? execute();\n\n          const responseMessagesFromPreviousSteps = recordedSteps.flatMap(\n            step => step.response.messages,\n          );\n          const accumulatedResponseMessages = [\n            ...initialResponseMessages,\n            ...responseMessagesFromPreviousSteps,\n          ];\n          const stepInputMessages = stepMessagesForNextStep ?? [\n            ...initialMessages,\n            ...initialResponseMessages,\n          ];\n\n          const prepareStepResult = await prepareStep?.({\n            model,\n            steps: recordedSteps,\n            stepNumber: recordedSteps.length,\n            instructions: instructionsForNextStep,\n            initialInstructions: initialPrompt.instructions,\n            messages: stepInputMessages,\n            initialMessages,\n            responseMessages: accumulatedResponseMessages,\n            toolsContext,\n            runtimeContext,\n            experimental_sandbox: sandbox,\n          });\n\n          const stepSandbox =\n            prepareStepResult?.experimental_sandbox ?? sandbox;\n\n          runtimeContext = prepareStepResult?.runtimeContext ?? runtimeContext;\n          toolsContext = prepareStepResult?.toolsContext ?? toolsContext;\n\n          const stepModel = resolveLanguageModel(\n            prepareStepResult?.model ?? model,\n          );\n\n          const stepActiveTools = filterActiveTools({\n            tools,\n            activeTools: prepareStepResult?.activeTools ?? activeTools,\n          });\n          const {\n            executionTools: stepExecutionTools,\n            modelTools: stepModelTools,\n            toolCallerMessages,\n          } = prepareToolsForToolCallers({\n            tools: prepareToolSearch(stepActiveTools, {\n              toolsContext,\n              experimental_sandbox: stepSandbox,\n            }),\n            toolCallers: resolvedToolCallers,\n          });\n          const stepToolOrder = prepareStepResult?.toolOrder ?? toolOrder;\n\n          const stepTools = await prepareTools({\n            tools: stepModelTools as ActiveToolSubset<\n              TOOLS,\n              ActiveTools<NoInfer<TOOLS>>\n            >,\n            toolOrder: stepToolOrder as ToolOrder<\n              ActiveToolSubset<TOOLS, ActiveTools<NoInfer<TOOLS>>>\n            >,\n            // active tools context is a subset of the tools context, so we can cast to the unknown type\n            toolsContext: toolsContext as unknown as InferToolSetContext<\n              ActiveToolSubset<TOOLS, ActiveTools<NoInfer<TOOLS>>>\n            >,\n            experimental_sandbox: stepSandbox,\n          });\n\n          const stepToolChoice = prepareToolChoice({\n            toolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n          });\n\n          const stepMessages = appendToolCallerMessages({\n            messages: prepareStepResult?.messages ?? stepInputMessages,\n            toolCallerMessages,\n          });\n          currentStepMessages = stepMessages;\n          const stepInstructions =\n            prepareStepResult?.instructions ??\n            prepareStepResult?.system ??\n            instructionsForNextStep;\n          instructionsForNextStep = stepInstructions;\n\n          const stepProviderOptions = mergeObjects(\n            providerOptions,\n            prepareStepResult?.providerOptions,\n          );\n\n          const stepCallSettings = prepareStepCallSettings({\n            callSettings,\n            stepSettings: prepareStepResult,\n          });\n\n          const stepStartTimestampMs = now();\n\n          const { retry } = prepareRetries({ maxRetries, abortSignal });\n          let hasNotifiedStepStart = false;\n\n          const callLanguageModel = () =>\n            runInStepTracingChannelContext(() =>\n              retry(async () =>\n                streamLanguageModelCall({\n                  model: prepareStepResult?.model ?? model,\n                  tools: stepModelTools as TOOLS,\n                  toolOrder: stepToolOrder,\n                  toolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n                  instructions: stepInstructions,\n                  messages: stepMessages,\n                  allowSystemInMessages,\n                  repairToolCall,\n                  refineToolInput,\n                  abortSignal,\n                  headers,\n                  includeRawChunks: include.rawChunks,\n                  providerOptions: stepProviderOptions,\n                  download,\n                  output,\n                  callId,\n                  executeLanguageModelCallInTelemetryContext:\n                    telemetryDispatcher.executeLanguageModelCall,\n                  toolsContext,\n                  experimental_sandbox: stepSandbox,\n                  onLanguageModelCallStart: filterNullable(\n                    onLanguageModelCallStart,\n                    telemetryDispatcher.onLanguageModelCallStart as\n                      | undefined\n                      | OnLanguageModelCallStartCallback,\n                  ),\n                  onLanguageModelCallEnd: filterNullable(\n                    onLanguageModelCallEnd,\n                    telemetryDispatcher.onLanguageModelCallEnd as\n                      | undefined\n                      | OnLanguageModelCallEndCallback<TOOLS>,\n                  ),\n                  onStart: async ({ promptMessages }) => {\n                    if (hasNotifiedStepStart) {\n                      return;\n                    }\n                    hasNotifiedStepStart = true;\n\n                    await notify({\n                      event: {\n                        callId,\n                        provider: stepModel.provider,\n                        modelId: stepModel.modelId,\n                        stepNumber: recordedSteps.length,\n                        instructions: stepInstructions,\n                        messages: stepMessages,\n                        tools,\n                        toolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n                        activeTools:\n                          prepareStepResult?.activeTools ?? activeTools,\n                        toolOrder: stepToolOrder,\n                        steps: [...recordedSteps],\n                        providerOptions: stepProviderOptions,\n                        runtimeContext,\n                        toolsContext,\n                        output,\n                        promptMessages,\n                        stepTools,\n                        stepToolChoice,\n                      },\n                      callbacks: [onStepStart, telemetryDispatcher.onStepStart],\n                    });\n                  },\n                  _internal: {\n                    now,\n                  },\n                  ...stepCallSettings,\n                }),\n              ),\n            );\n\n          const initialLanguageModelCall = await callLanguageModel();\n          let request = initialLanguageModelCall.request;\n          let response = initialLanguageModelCall.response;\n          let languageModelStreamReader =\n            initialLanguageModelCall.stream.getReader();\n          let automaticStreamRetryCount = 0;\n          let callbackStreamRetryCount = 0;\n          let bufferedAttemptParts: LanguageModelStreamPart<TOOLS>[] = [];\n          const outputChunksHandledBeforeBuffering = new WeakSet<object>();\n          const openTextParts = new Set<string>();\n          const openReasoningParts = new Set<string>();\n          let enqueueStreamRetryAttemptBoundary = false;\n          const shouldBufferToolParts =\n            streamRetries > 0 || canRetryStreamViaOnError;\n\n          const languageModelStream = new ReadableStream<\n            LanguageModelStreamPart<TOOLS> | StreamRetryAttemptBoundaryPart\n          >({\n            async pull(controller) {\n              const enqueueAttemptPart = (\n                part: LanguageModelStreamPart<TOOLS>,\n              ) => {\n                switch (part.type) {\n                  case 'text-start':\n                    openTextParts.add(part.id);\n                    break;\n                  case 'text-end':\n                    openTextParts.delete(part.id);\n                    break;\n                  case 'reasoning-start':\n                    openReasoningParts.add(part.id);\n                    break;\n                  case 'reasoning-end':\n                    openReasoningParts.delete(part.id);\n                    break;\n                }\n\n                controller.enqueue(part);\n              };\n\n              const flushBufferedAttemptParts = () => {\n                for (const part of bufferedAttemptParts) {\n                  enqueueAttemptPart(part);\n                }\n                bufferedAttemptParts = [];\n              };\n\n              const closeOpenAttemptParts = () => {\n                for (const id of openTextParts) {\n                  controller.enqueue({ type: 'text-end', id });\n                }\n                openTextParts.clear();\n\n                for (const id of openReasoningParts) {\n                  controller.enqueue({ type: 'reasoning-end', id });\n                }\n                openReasoningParts.clear();\n              };\n\n              while (true) {\n                const { done, value } = await languageModelStreamReader.read();\n\n                if (enqueueStreamRetryAttemptBoundary) {\n                  controller.enqueue(\n                    createStreamRetryAttemptBoundaryPart({\n                      warnings:\n                        !done && value.type === 'model-call-start'\n                          ? value.warnings\n                          : [],\n                    }),\n                  );\n                  enqueueStreamRetryAttemptBoundary = false;\n                }\n\n                if (done) {\n                  flushBufferedAttemptParts();\n                  controller.close();\n                  return;\n                }\n\n                const isToolPart =\n                  value.type === 'tool-input-start' ||\n                  value.type === 'tool-input-delta' ||\n                  value.type === 'tool-input-end' ||\n                  value.type === 'tool-call' ||\n                  value.type === 'tool-approval-request' ||\n                  value.type === 'tool-approval-response' ||\n                  value.type === 'tool-result' ||\n                  value.type === 'tool-error';\n\n                if (value.type === 'model-call-end') {\n                  flushBufferedAttemptParts();\n                  enqueueAttemptPart(value);\n                  return;\n                }\n\n                if (\n                  shouldBufferToolParts &&\n                  value.type !== 'error' &&\n                  (isToolPart || bufferedAttemptParts.length > 0)\n                ) {\n                  if (isOutputChunk(value)) {\n                    clearFirstChunkTimeout();\n                    resetChunkTimeout();\n                    outputChunksHandledBeforeBuffering.add(value);\n                  }\n\n                  bufferedAttemptParts.push(value);\n                  continue;\n                }\n\n                if (value.type !== 'error') {\n                  enqueueAttemptPart(value);\n                  return;\n                }\n\n                await notify({\n                  event: { chunk: value },\n                  callbacks: onChunk,\n                });\n                const error = wrapGatewayError(value.error);\n                const isToolChoiceViolation =\n                  ToolChoiceViolationError.isInstance(error);\n                let onErrorResult: unknown;\n                try {\n                  onErrorResult = await onError({ error });\n                } catch {}\n                const callbackRequestedRetry =\n                  canRetryStreamViaOnError &&\n                  typeof onErrorResult === 'object' &&\n                  onErrorResult != null &&\n                  'retry' in onErrorResult &&\n                  onErrorResult.retry === true;\n                const automaticRetry =\n                  !isToolChoiceViolation &&\n                  automaticStreamRetryCount < streamRetries;\n                const callbackRetry =\n                  !isToolChoiceViolation &&\n                  !automaticRetry &&\n                  callbackRequestedRetry &&\n                  callbackStreamRetryCount < 1;\n\n                if (!automaticRetry && !callbackRetry) {\n                  flushBufferedAttemptParts();\n                  errorsHandledForStreamRetry.add(value.error);\n                  controller.enqueue(value);\n                  return;\n                }\n\n                if (automaticRetry) {\n                  automaticStreamRetryCount++;\n                } else {\n                  callbackStreamRetryCount++;\n                }\n\n                await languageModelStreamReader.cancel(error);\n                bufferedAttemptParts = [];\n                closeOpenAttemptParts();\n\n                let retryLanguageModelCall: Awaited<\n                  ReturnType<typeof callLanguageModel>\n                >;\n                try {\n                  retryLanguageModelCall = await callLanguageModel();\n                } catch (retryError) {\n                  controller.enqueue({\n                    type: 'error',\n                    error: retryError,\n                  });\n                  controller.close();\n                  return;\n                }\n                request = retryLanguageModelCall.request;\n                response = retryLanguageModelCall.response;\n                languageModelStreamReader =\n                  retryLanguageModelCall.stream.getReader();\n                enqueueStreamRetryAttemptBoundary = true;\n              }\n            },\n            cancel(reason) {\n              return languageModelStreamReader.cancel(reason);\n            },\n          });\n\n          startFirstChunkTimeout();\n\n          const streamAfterToolCallbackInvocation =\n            invokeToolCallbacksFromStream({\n              stream: languageModelStream,\n              tools: stepExecutionTools as TOOLS,\n              stepInputMessages: stepMessages,\n              abortSignal,\n              runtimeContext,\n            });\n\n          // Create child spans under the current step context.\n          const runInTracingChannelSpanInStep =\n            telemetryDispatcher.runInTracingChannelSpan == null\n              ? undefined\n              : <T>(\n                  options: Parameters<\n                    NonNullable<TelemetryDispatcher['runInTracingChannelSpan']>\n                  >[0] & {\n                    execute: () => PromiseLike<T>;\n                  },\n                ) =>\n                  runInStepTracingChannelContext(() =>\n                    telemetryDispatcher.runInTracingChannelSpan!(options),\n                  );\n\n          const streamWithToolResults = executeToolsFromStream({\n            stream: streamAfterToolCallbackInvocation,\n            tools: stepExecutionTools as TOOLS,\n            callId,\n            messages: stepMessages,\n            abortSignal,\n            timeout,\n            experimental_sandbox: stepSandbox,\n            toolsContext,\n            toolApproval,\n            runtimeContext,\n            toolApprovalSecret: experimental_toolApprovalSecret,\n            generateId,\n\n            // the callbacks need to be passed down and handled by executeToolCall\n            // to guarantee that the onToolExecutionStart callback is invoked before the tool execute function\n            onToolExecutionStart: filterNullable(\n              onToolExecutionStart,\n              telemetryDispatcher.onToolExecutionStart,\n            ),\n            onToolExecutionEnd: filterNullable(\n              onToolExecutionEnd,\n              telemetryDispatcher.onToolExecutionEnd,\n            ),\n\n            executeToolInTelemetryContext: telemetryDispatcher.executeTool,\n            runInTracingChannelSpan: runInTracingChannelSpanInStep,\n          });\n\n          // Conditionally include request.body based on include settings.\n          // Large payloads (e.g., base64-encoded images) can cause memory issues.\n          const getStepRequest = (): LanguageModelRequestMetadata => ({\n            ...request,\n            body: include.requestBody ? request?.body : undefined,\n            messages: include.requestMessages\n              ? cloneModelMessages(stepMessages)\n              : undefined,\n          });\n          recordedRequestMessages = getStepRequest().messages ?? [];\n\n          const stepToolCalls: TypedToolCall<TOOLS>[] = [];\n          const stepToolOutputs: ToolOutput<TOOLS>[] = [];\n          const stepToolApprovalResponses: ToolApprovalResponse[] = [];\n          let warnings: SharedV4Warning[] | undefined;\n\n          let stepFinishReason: FinishReason = 'other';\n          let stepRawFinishReason: string | undefined = undefined;\n\n          // terminal chunk = 'model-call-end' or 'error'; absence on stream\n          // end means the model stream is incomplete:\n          let hasReceivedTerminalChunk = false;\n\n          // output chunk = any content chunk (text, tool calls, etc.);\n          // used to distinguish empty incomplete streams from partial results:\n          let hasReceivedOutputChunk = false;\n\n          let stepUsage: LanguageModelUsage = createNullLanguageModelUsage();\n          let stepProviderMetadata: ProviderMetadata | undefined;\n          let stepFirstChunk = true;\n          const createModelCallPerformance = (): Omit<\n            StepResultPerformance,\n            'stepTimeMs' | 'toolExecutionMs'\n          > => ({\n            responseTimeMs: 0,\n            effectiveOutputTokensPerSecond: 0,\n            outputTokensPerSecond: undefined,\n            inputTokensPerSecond: undefined,\n            effectiveTotalTokensPerSecond: 0,\n            timeToFirstOutputMs: undefined,\n            timeBetweenOutputChunksMs: undefined,\n          });\n          let modelCallPerformance = createModelCallPerformance();\n          const toolExecutionMs: Record<string, number> = {};\n          const createStepResponse = () => ({\n            id: generateId(),\n            timestamp: new Date(),\n            modelId: model.modelId,\n          });\n          let stepResponse: {\n            id: string;\n            timestamp: Date;\n            modelId: string;\n          } = createStepResponse();\n\n          // maps provider-assigned IDs to stream-unique IDs for the text and\n          // reasoning parts that are active in this step\n          const textPartIds = new Map<string, string>();\n          const reasoningPartIds = new Map<string, string>();\n\n          const enqueueStepPart = (\n            controller: TransformStreamDefaultController<\n              InternalTextStreamPart<TOOLS>\n            >,\n            part: TextStreamPart<TOOLS>,\n          ) => {\n            controller.enqueue(part);\n          };\n\n          self.addStream(\n            streamWithToolResults.pipeThrough(\n              new TransformStream<\n                ExecuteToolsStreamPart<TOOLS>,\n                InternalTextStreamPart<TOOLS>\n              >({\n                async transform(chunk, controller): Promise<void> {\n                  if (isStreamRetryAttemptBoundaryPart(chunk)) {\n                    warnings = chunk.warnings;\n                    stepFinishReason = 'other';\n                    stepRawFinishReason = undefined;\n                    hasReceivedTerminalChunk = false;\n                    hasReceivedOutputChunk = false;\n                    stepUsage = createNullLanguageModelUsage();\n                    stepProviderMetadata = undefined;\n                    modelCallPerformance = createModelCallPerformance();\n                    stepResponse = createStepResponse();\n                    textPartIds.clear();\n                    reasoningPartIds.clear();\n\n                    controller.enqueue({\n                      [streamRetryBoundarySymbol]: {\n                        request: getStepRequest(),\n                        warnings,\n                      } satisfies StreamRetryBoundaryMetadata,\n                    });\n                    return;\n                  }\n\n                  if (chunk.type === 'model-call-start') {\n                    warnings = chunk.warnings;\n                    return; // stream start chunks are sent immediately and do not count as first chunk\n                  }\n\n                  if (stepFirstChunk) {\n                    stepFirstChunk = false;\n\n                    // Step start:\n                    enqueueStepPart(controller, {\n                      type: 'start-step',\n                      request: getStepRequest(),\n                      warnings: warnings ?? [],\n                    });\n                  }\n\n                  const chunkType = chunk.type;\n\n                  if (isOutputChunk(chunk)) {\n                    const timeoutHandledBeforeBuffering =\n                      outputChunksHandledBeforeBuffering.has(chunk);\n\n                    if (\n                      !hasReceivedOutputChunk &&\n                      !timeoutHandledBeforeBuffering\n                    ) {\n                      // Clear before forwarding the first output so a timeout\n                      // cannot race with already-visible generated content.\n                      clearFirstChunkTimeout();\n                    }\n                    hasReceivedOutputChunk = true;\n                    if (!timeoutHandledBeforeBuffering) {\n                      resetChunkTimeout();\n                    }\n                  }\n\n                  switch (chunkType) {\n                    case 'file':\n                    case 'custom':\n                    case 'source':\n                    case 'reasoning-file':\n                    case 'tool-input-start':\n                    case 'tool-input-end':\n                    case 'tool-input-delta':\n                    case 'tool-approval-request':\n                    case 'tool-output-denied': {\n                      enqueueStepPart(controller, chunk);\n                      break;\n                    }\n\n                    case 'text-start': {\n                      const id = reserveTextPartId(chunk.id);\n                      textPartIds.set(chunk.id, id);\n                      enqueueStepPart(controller, { ...chunk, id });\n                      break;\n                    }\n\n                    case 'text-delta': {\n                      if (\n                        chunk.text.length > 0 ||\n                        chunk.providerMetadata != null\n                      ) {\n                        enqueueStepPart(controller, {\n                          ...chunk,\n                          id: textPartIds.get(chunk.id) ?? chunk.id,\n                        });\n                      }\n                      break;\n                    }\n\n                    case 'text-end': {\n                      enqueueStepPart(controller, {\n                        ...chunk,\n                        id: textPartIds.get(chunk.id) ?? chunk.id,\n                      });\n                      textPartIds.delete(chunk.id);\n                      break;\n                    }\n\n                    case 'reasoning-start': {\n                      const id = reserveReasoningPartId(chunk.id);\n                      reasoningPartIds.set(chunk.id, id);\n                      enqueueStepPart(controller, { ...chunk, id });\n                      break;\n                    }\n\n                    case 'reasoning-delta': {\n                      enqueueStepPart(controller, {\n                        ...chunk,\n                        id: reasoningPartIds.get(chunk.id) ?? chunk.id,\n                      });\n                      break;\n                    }\n\n                    case 'reasoning-end': {\n                      enqueueStepPart(controller, {\n                        ...chunk,\n                        id: reasoningPartIds.get(chunk.id) ?? chunk.id,\n                      });\n                      reasoningPartIds.delete(chunk.id);\n                      break;\n                    }\n\n                    case 'tool-call': {\n                      enqueueStepPart(controller, chunk);\n                      // store tool calls for onEnd callback and toolCalls promise:\n                      stepToolCalls.push(chunk);\n                      break;\n                    }\n\n                    case 'tool-approval-response': {\n                      enqueueStepPart(controller, chunk);\n                      stepToolApprovalResponses.push(chunk);\n                      break;\n                    }\n\n                    case 'tool-result': {\n                      enqueueStepPart(controller, chunk);\n\n                      if (!chunk.preliminary) {\n                        stepToolOutputs.push(chunk);\n                      }\n\n                      break;\n                    }\n\n                    case 'tool-error': {\n                      enqueueStepPart(controller, chunk);\n                      stepToolOutputs.push(chunk);\n                      break;\n                    }\n\n                    case 'tool-execution-end': {\n                      toolExecutionMs[chunk.toolCallId] = chunk.toolExecutionMs;\n                      break;\n                    }\n\n                    case 'model-call-response-metadata': {\n                      stepResponse = {\n                        id: chunk.id ?? stepResponse.id,\n                        timestamp: chunk.timestamp ?? stepResponse.timestamp,\n                        modelId: chunk.modelId ?? stepResponse.modelId,\n                      };\n                      break;\n                    }\n\n                    case 'model-call-end': {\n                      hasReceivedTerminalChunk = true;\n\n                      // Note: tool executions might not be finished yet when the finish event is emitted.\n                      // store usage and finish reason for promises and onEnd callback:\n                      stepUsage = chunk.usage;\n                      stepFinishReason = chunk.finishReason;\n                      stepRawFinishReason = chunk.rawFinishReason;\n                      stepProviderMetadata = chunk.providerMetadata;\n                      modelCallPerformance = chunk.performance;\n\n                      break;\n                    }\n\n                    case 'error': {\n                      hasReceivedTerminalChunk = true;\n                      enqueueStepPart(controller, chunk);\n                      stepFinishReason = 'error';\n                      break;\n                    }\n\n                    case 'raw': {\n                      if (include.rawChunks) {\n                        enqueueStepPart(controller, chunk);\n                      }\n                      break;\n                    }\n\n                    default: {\n                      const exhaustiveCheck: never = chunkType;\n                      throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);\n                    }\n                  }\n                },\n\n                // invoke onEnd callback and resolve toolResults promise when the stream is about to close:\n                async flush(controller) {\n                  // emit an error when an incomplete model stream produced no\n                  // output instead of recording an empty step. incomplete\n                  // streams with partial output retain the partial result:\n                  if (!hasReceivedTerminalChunk && !hasReceivedOutputChunk) {\n                    enqueueStepPart(controller, {\n                      type: 'error',\n                      error: new NoOutputGeneratedError({\n                        message:\n                          'No output generated. The model stream ended without a finish chunk.',\n                      }),\n                    });\n\n                    cleanupStepTimeouts();\n                    self.closeStream();\n                    return;\n                  }\n\n                  const stepTimeMs = now() - stepStartTimestampMs;\n\n                  const finishStepPart: TextStreamPart<TOOLS> = {\n                    type: 'finish-step',\n                    finishReason: stepFinishReason,\n                    rawFinishReason: stepRawFinishReason,\n                    usage: stepUsage,\n                    performance: {\n                      stepTimeMs,\n                      toolExecutionMs,\n                      ...modelCallPerformance,\n                    },\n                    providerMetadata: stepProviderMetadata,\n                    response: {\n                      ...stepResponse,\n                      headers: response?.headers,\n                    },\n                  };\n\n                  enqueueStepPart(controller, finishStepPart);\n\n                  const combinedUsage = addLanguageModelUsage(usage, stepUsage);\n\n                  // wait for the step to be fully processed by the event processor\n                  // to ensure that the recorded steps are complete:\n                  await stepFinish.promise;\n\n                  const clientToolCalls = stepToolCalls.filter(\n                    toolCall => toolCall.providerExecuted !== true,\n                  );\n                  const clientToolOutputs = stepToolOutputs.filter(\n                    toolOutput => toolOutput.providerExecuted !== true,\n                  );\n                  const deniedToolApprovalResponses =\n                    stepToolApprovalResponses.filter(\n                      toolApprovalResponse =>\n                        toolApprovalResponse.approved === false,\n                    );\n\n                  // Track provider-executed tool calls that support deferred results.\n                  // In programmatic tool calling, a server tool (e.g., code_execution) may\n                  // trigger a client tool, and the server tool's result is deferred until\n                  // the client tool's result is sent back.\n                  for (const toolCall of stepToolCalls) {\n                    if (toolCall.providerExecuted !== true) continue;\n                    const tool = getOwn(stepExecutionTools, toolCall.toolName);\n                    if (\n                      tool?.type === 'provider' &&\n                      tool.supportsDeferredResults\n                    ) {\n                      // Check if this tool call already has a result in the current step\n                      const hasResultInStep = stepToolOutputs.some(\n                        output =>\n                          (output.type === 'tool-result' ||\n                            output.type === 'tool-error') &&\n                          output.toolCallId === toolCall.toolCallId,\n                      );\n                      if (!hasResultInStep) {\n                        pendingDeferredToolCalls.set(toolCall.toolCallId, {\n                          toolName: toolCall.toolName,\n                        });\n                      }\n                    }\n                  }\n\n                  // Mark deferred tool calls as resolved when we receive their results\n                  for (const output of stepToolOutputs) {\n                    if (\n                      output.type === 'tool-result' ||\n                      output.type === 'tool-error'\n                    ) {\n                      pendingDeferredToolCalls.delete(output.toolCallId);\n                    }\n                  }\n\n                  // Clear this step's timeouts before the next step is started.\n                  cleanupStepTimeouts();\n\n                  if (\n                    // Continue only after all client tool calls have been executed or denied,\n                    // and if there are client results or pending deferred provider results.\n                    clientToolCalls.length ===\n                      clientToolOutputs.length +\n                        deniedToolApprovalResponses.length &&\n                    (clientToolCalls.length > 0 ||\n                      pendingDeferredToolCalls.size > 0) &&\n                    // continue until a stop condition is met:\n                    !(await isStopConditionMet({\n                      stopConditions,\n                      steps: recordedSteps,\n                    }))\n                  ) {\n                    try {\n                      await runInStreamTextTracingChannelContext(() =>\n                        streamStep({\n                          currentStep: currentStep + 1,\n                          usage: combinedUsage,\n                        }),\n                      );\n                    } catch (error) {\n                      enqueueStepPart(controller, {\n                        type: 'error',\n                        error,\n                      });\n\n                      self.closeStream();\n                    }\n                  } else {\n                    enqueueStepPart(controller, {\n                      type: 'finish',\n                      finishReason: stepFinishReason,\n                      rawFinishReason: stepRawFinishReason,\n                      totalUsage: combinedUsage,\n                    });\n\n                    self.closeStream(); // close the stitchable stream\n                  }\n                },\n              }),\n            ),\n            {\n              onError: cleanupStepTimeouts,\n              onCancel: cleanupStepTimeouts,\n            },\n          );\n        } catch (error) {\n          // Setup failed before the stream was registered, so neither the\n          // stream's flush nor an abort will clear the timers — clear them here.\n          cleanupStepTimeouts();\n          throw error;\n        }\n      }\n\n      await runInStreamTextTracingChannelContext(() =>\n        // add the initial stream to the stitchable stream\n        streamStep({\n          currentStep: 0,\n          usage: createNullLanguageModelUsage(),\n        }),\n      );\n    })().catch(async error => {\n      await telemetryDispatcher.onError?.({ callId, error });\n      self._initialResponseMessages.reject(error);\n      markPromiseAsHandled(self._initialResponseMessages.promise);\n\n      // add an error stream part and close the streams:\n      self.addStream(\n        new ReadableStream({\n          start(controller) {\n            controller.enqueue({ type: 'error', error });\n            controller.close();\n          },\n        }),\n      );\n      self.closeStream();\n    });\n  }\n\n  get steps() {\n    // when any of the promises are accessed, the stream is consumed\n    // so it resolves without needing to consume the stream separately\n    this.consumeStream();\n\n    return this._steps.promise;\n  }\n\n  get finalStep() {\n    return this.steps.then(steps => steps.at(-1)!);\n  }\n\n  get content() {\n    return this.steps.then(steps => steps.flatMap(step => step.content));\n  }\n\n  get warnings() {\n    return this.steps.then(steps => steps.flatMap(step => step.warnings ?? []));\n  }\n\n  get providerMetadata() {\n    return this.finalStep.then(step => step.providerMetadata);\n  }\n\n  get text() {\n    return this.finalStep.then(step => step.text);\n  }\n\n  get reasoningText() {\n    return this.finalStep.then(step => step.reasoningText);\n  }\n\n  get reasoning() {\n    return this.finalStep.then(step =>\n      convertToReasoningOutputs(step.reasoning),\n    );\n  }\n\n  get sources() {\n    return this.steps.then(steps => steps.flatMap(step => step.sources));\n  }\n\n  get files() {\n    return this.steps.then(steps => steps.flatMap(step => step.files));\n  }\n\n  get toolCalls() {\n    return this.steps.then(steps => steps.flatMap(step => step.toolCalls));\n  }\n\n  get staticToolCalls() {\n    return this.steps.then(steps =>\n      steps.flatMap(step => step.staticToolCalls),\n    );\n  }\n\n  get dynamicToolCalls() {\n    return this.steps.then(steps =>\n      steps.flatMap(step => step.dynamicToolCalls),\n    );\n  }\n\n  get toolResults() {\n    return this.steps.then(steps => steps.flatMap(step => step.toolResults));\n  }\n\n  get staticToolResults() {\n    return this.steps.then(steps =>\n      steps.flatMap(step => step.staticToolResults),\n    );\n  }\n\n  get dynamicToolResults() {\n    return this.steps.then(steps =>\n      steps.flatMap(step => step.dynamicToolResults),\n    );\n  }\n\n  get usage() {\n    return this.totalUsage;\n  }\n\n  get request() {\n    return this.finalStep.then(step => step.request);\n  }\n\n  get response() {\n    return this.finalStep.then(step => step.response);\n  }\n\n  get responseMessages() {\n    return Promise.all([\n      this._initialResponseMessages.promise,\n      this.steps,\n    ]).then(([initialResponseMessages, steps]) => [\n      ...initialResponseMessages,\n      ...steps.flatMap(step => step.response.messages),\n    ]);\n  }\n\n  get totalUsage() {\n    // when any of the promises are accessed, the stream is consumed\n    // so it resolves without needing to consume the stream separately\n    this.consumeStream();\n\n    return this._totalUsage.promise;\n  }\n\n  get finishReason() {\n    // when any of the promises are accessed, the stream is consumed\n    // so it resolves without needing to consume the stream separately\n    this.consumeStream();\n\n    return this._finishReason.promise;\n  }\n\n  get rawFinishReason() {\n    // when any of the promises are accessed, the stream is consumed\n    // so it resolves without needing to consume the stream separately\n    this.consumeStream();\n\n    return this._rawFinishReason.promise;\n  }\n\n  /**\n   * Split out a new stream from the original stream.\n   * The original stream is replaced to allow for further splitting,\n   * since we do not know how many times the stream will be split.\n   *\n   * Note: this leads to buffering the stream content on the server.\n   * However, the LLM results are expected to be small enough to not cause issues.\n   */\n  private teeStream() {\n    const [stream1, stream2] = this.baseStream.tee();\n    this.baseStream = stream2;\n    return stream1;\n  }\n\n  get textStream(): AsyncIterableStream<string> {\n    return createAsyncIterableStream(toTextStream({ stream: this.stream }));\n  }\n\n  get stream(): AsyncIterableStream<TextStreamPart<TOOLS>> {\n    return createAsyncIterableStream(\n      this.teeStream().pipeThrough(\n        new TransformStream<\n          EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>,\n          TextStreamPart<TOOLS>\n        >({\n          transform({ part }, controller) {\n            controller.enqueue(part);\n          },\n        }),\n      ),\n    );\n  }\n\n  get fullStream(): AsyncIterableStream<TextStreamPart<TOOLS>> {\n    return this.stream;\n  }\n\n  private rejectResultPromises(error: unknown) {\n    this.rejectResultPromise({ delayedPromise: this._finishReason, error });\n    this.rejectResultPromise({ delayedPromise: this._rawFinishReason, error });\n    this.rejectResultPromise({ delayedPromise: this._totalUsage, error });\n    this.rejectResultPromise({ delayedPromise: this._steps, error });\n    this.rejectResultPromise({\n      delayedPromise: this._initialResponseMessages,\n      error,\n    });\n  }\n\n  private rejectResultPromise<T>({\n    delayedPromise,\n    error,\n  }: {\n    delayedPromise: DelayedPromise<T>;\n    error: unknown;\n  }) {\n    if (delayedPromise.isPending()) {\n      delayedPromise.reject(error);\n      markPromiseAsHandled(delayedPromise.promise);\n    }\n  }\n\n  async consumeStream(options?: ConsumeStreamOptions): Promise<void> {\n    try {\n      await consumeStream({\n        stream: this.stream,\n        onError: error => {\n          this.rejectResultPromises(error);\n          options?.onError?.(error);\n        },\n      });\n    } catch (error) {\n      this.rejectResultPromises(error);\n      options?.onError?.(error);\n    }\n  }\n\n  get experimental_partialOutputStream(): AsyncIterableStream<\n    InferPartialOutput<OUTPUT>\n  > {\n    return this.partialOutputStream;\n  }\n\n  get partialOutputStream(): AsyncIterableStream<InferPartialOutput<OUTPUT>> {\n    return createAsyncIterableStream(\n      this.teeStream().pipeThrough(\n        new TransformStream<\n          EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>,\n          InferPartialOutput<OUTPUT>\n        >({\n          transform({ partialOutput }, controller) {\n            if (partialOutput != null) {\n              controller.enqueue(partialOutput);\n            }\n          },\n        }),\n      ),\n    );\n  }\n\n  get elementStream(): AsyncIterableStream<InferElementOutput<OUTPUT>> {\n    const transform = this.outputSpecification?.createElementStreamTransform();\n\n    if (transform == null) {\n      throw new UnsupportedFunctionalityError({\n        functionality: `element streams in ${\n          this.outputSpecification?.name ?? 'text'\n        } mode`,\n      });\n    }\n\n    return createAsyncIterableStream(this.teeStream().pipeThrough(transform));\n  }\n\n  private getOutputPromise(): Promise<InferCompleteOutput<OUTPUT>> {\n    if (this.outputPromise == null) {\n      this.outputPromise = this.finalStep.then(step => {\n        const output = this.outputSpecification ?? text();\n        return output.parseCompleteOutput(\n          { text: step.text },\n          {\n            response: step.response,\n            usage: step.usage,\n            finishReason: step.finishReason,\n          },\n        );\n      });\n    }\n\n    return this.outputPromise;\n  }\n\n  get output(): Promise<InferCompleteOutput<OUTPUT>> {\n    return this.getOutputPromise();\n  }\n\n  toUIMessageStream<UI_MESSAGE extends UIMessage>({\n    originalMessages,\n    generateMessageId,\n    onEnd,\n    onFinish,\n    messageMetadata,\n    sendReasoning,\n    sendSources,\n    sendStart,\n    sendFinish,\n    onError,\n  }: UIMessageStreamOptions<UI_MESSAGE> = {}): AsyncIterableStream<\n    InferUIMessageChunk<UI_MESSAGE>\n  > {\n    return createAsyncIterableStream(\n      toUIMessageStreamHelper({\n        stream: this.stream,\n        tools: this.tools,\n        originalMessages,\n        generateMessageId,\n        onEnd: onEnd ?? onFinish,\n        messageMetadata,\n        sendReasoning,\n        sendSources,\n        sendStart,\n        sendFinish,\n        onError,\n      }),\n    );\n  }\n\n  pipeUIMessageStreamToResponse<UI_MESSAGE extends UIMessage>(\n    response: ServerResponse,\n    {\n      originalMessages,\n      generateMessageId,\n      onEnd,\n      onFinish,\n      messageMetadata,\n      sendReasoning,\n      sendSources,\n      sendFinish,\n      sendStart,\n      onError,\n      ...init\n    }: UIMessageStreamResponseInit & UIMessageStreamOptions<UI_MESSAGE> = {},\n  ) {\n    return pipeUIMessageStreamToResponse({\n      response,\n      stream: this.toUIMessageStream({\n        originalMessages,\n        generateMessageId,\n        onEnd: onEnd ?? onFinish,\n        messageMetadata,\n        sendReasoning,\n        sendSources,\n        sendFinish,\n        sendStart,\n        onError,\n      }),\n      ...init,\n    });\n  }\n\n  pipeTextStreamToResponse(response: ServerResponse, init?: ResponseInit) {\n    return pipeTextStreamToResponse({\n      response,\n      stream: this.textStream,\n      ...init,\n    });\n  }\n\n  toUIMessageStreamResponse<UI_MESSAGE extends UIMessage>({\n    originalMessages,\n    generateMessageId,\n    onEnd,\n    onFinish,\n    messageMetadata,\n    sendReasoning,\n    sendSources,\n    sendFinish,\n    sendStart,\n    onError,\n    ...init\n  }: UIMessageStreamResponseInit &\n    UIMessageStreamOptions<UI_MESSAGE> = {}): Response {\n    return createUIMessageStreamResponse({\n      stream: this.toUIMessageStream({\n        originalMessages,\n        generateMessageId,\n        onEnd: onEnd ?? onFinish,\n        messageMetadata,\n        sendReasoning,\n        sendSources,\n        sendFinish,\n        sendStart,\n        onError,\n      }),\n      ...init,\n    });\n  }\n\n  toTextStreamResponse(init?: ResponseInit): Response {\n    return createTextStreamResponse({\n      stream: this.textStream,\n      ...init,\n    });\n  }\n}\n","export function prepareHeaders(\n  headers: HeadersInit | undefined,\n  defaultHeaders: Record<string, string>,\n): Headers {\n  const responseHeaders = new Headers(headers ?? {});\n\n  for (const [key, value] of Object.entries(defaultHeaders)) {\n    if (!responseHeaders.has(key)) {\n      responseHeaders.set(key, value);\n    }\n  }\n\n  return responseHeaders;\n}\n","import { prepareHeaders } from '../util/prepare-headers';\n\n/**\n * Creates a Response object from a text stream.\n * Each text chunk is encoded as UTF-8 and sent as a separate chunk.\n * Sets a `Content-Type` header to `text/plain; charset=utf-8`.\n *\n * @param options - The options for creating the response.\n * @param options.status - Optional HTTP status code (default: 200).\n * @param options.statusText - Optional HTTP status text.\n * @param options.headers - Optional response headers.\n * @param options.stream - The text stream to send.\n * @returns A Response object with the text stream body.\n */\nexport function createTextStreamResponse({\n  status,\n  statusText,\n  headers,\n  stream,\n}: ResponseInit & {\n  stream: ReadableStream<string>;\n}): Response {\n  return new Response(stream.pipeThrough(new TextEncoderStream()), {\n    status: status ?? 200,\n    statusText,\n    headers: prepareHeaders(headers, {\n      'content-type': 'text/plain; charset=utf-8',\n    }),\n  });\n}\n","import type { ServerResponse } from 'node:http';\n\ntype FlushableServerResponse = ServerResponse & {\n  flush?: () => void;\n};\n\n/**\n * Writes the content of a stream to a server response.\n */\nexport function writeToServerResponse({\n  response,\n  status,\n  statusText,\n  headers,\n  stream,\n}: {\n  response: ServerResponse;\n  status?: number;\n  statusText?: string;\n  headers?: Record<string, string | number | string[]>;\n  stream: ReadableStream<Uint8Array>;\n}): Promise<void> {\n  const statusCode = status ?? 200;\n  if (statusText !== undefined) {\n    response.writeHead(statusCode, statusText, headers);\n  } else {\n    response.writeHead(statusCode, headers);\n  }\n\n  const reader = stream.getReader();\n  const read = async () => {\n    try {\n      while (true) {\n        const { done, value } = await reader.read();\n        if (done) break;\n\n        // Respect backpressure: if write() returns false, wait for 'drain' event\n        const canContinue = response.write(value);\n        const flush = (response as FlushableServerResponse).flush;\n        if (typeof flush === 'function') {\n          flush.call(response);\n        }\n\n        if (!canContinue) {\n          await new Promise<void>(resolve => {\n            response.once('drain', resolve);\n          });\n        }\n      }\n    } catch (error) {\n      throw error;\n    } finally {\n      response.end();\n    }\n  };\n\n  return read();\n}\n","import type { ServerResponse } from 'node:http';\nimport { prepareHeaders } from '../util/prepare-headers';\nimport { writeToServerResponse } from '../util/write-to-server-response';\n\n/**\n * Writes a text stream to a Node.js ServerResponse object.\n * Each text chunk is encoded as UTF-8 and written as a separate chunk.\n * Sets a `Content-Type` header to `text/plain; charset=utf-8`.\n *\n * @param options - The options for piping the stream.\n * @param options.response - The Node.js ServerResponse to write to.\n * @param options.status - Optional HTTP status code.\n * @param options.statusText - Optional HTTP status text.\n * @param options.headers - Optional response headers.\n * @param options.stream - The text stream to pipe.\n * @returns A promise that resolves when the stream has been written.\n */\nexport function pipeTextStreamToResponse({\n  response,\n  status,\n  statusText,\n  headers,\n  stream,\n}: {\n  response: ServerResponse;\n  stream: ReadableStream<string>;\n} & ResponseInit): Promise<void> {\n  return writeToServerResponse({\n    response,\n    status,\n    statusText,\n    headers: Object.fromEntries(\n      prepareHeaders(headers, {\n        'content-type': 'text/plain; charset=utf-8',\n      }).entries(),\n    ),\n    stream: stream.pipeThrough(new TextEncoderStream()),\n  });\n}\n","import type { ToolSet } from '@ai-sdk/provider-utils';\nimport type { TextStreamPart } from '../generate-text/stream-text-result';\n\n/**\n * Converts a stream of `TextStreamPart` chunks into a stream of text deltas.\n */\nexport function toTextStream<TOOLS extends ToolSet = ToolSet>({\n  stream,\n}: {\n  stream: ReadableStream<TextStreamPart<TOOLS>>;\n}): ReadableStream<string> {\n  return stream.pipeThrough(\n    new TransformStream<TextStreamPart<TOOLS>, string>({\n      transform(part, controller) {\n        if (part.type === 'text-delta') {\n          controller.enqueue(part.text);\n        }\n      },\n    }),\n  );\n}\n","/**\n * A TransformStream that converts JSON objects to Server-Sent Events (SSE) format.\n * Each object is serialized to JSON and wrapped in `data: ...\\n\\n` format.\n * When the stream ends, a `data: [DONE]\\n\\n` message is sent.\n */\nexport class JsonToSseTransformStream extends TransformStream<unknown, string> {\n  constructor() {\n    super({\n      transform(part, controller) {\n        controller.enqueue(`data: ${JSON.stringify(part)}\\n\\n`);\n      },\n      flush(controller) {\n        controller.enqueue('data: [DONE]\\n\\n');\n      },\n    });\n  }\n}\n","export const UI_MESSAGE_STREAM_HEADERS = {\n  'content-type': 'text/event-stream',\n  'cache-control': 'no-cache',\n  connection: 'keep-alive',\n  'x-vercel-ai-ui-message-stream': 'v1',\n  'x-accel-buffering': 'no', // disable nginx buffering\n};\n","import { prepareHeaders } from '../util/prepare-headers';\nimport { JsonToSseTransformStream } from './json-to-sse-transform-stream';\nimport { UI_MESSAGE_STREAM_HEADERS } from './ui-message-stream-headers';\nimport type { UIMessageChunk } from './ui-message-chunks';\nimport type { UIMessageStreamResponseInit } from './ui-message-stream-response-init';\n\n/**\n * Creates a Response object from a UI message stream.\n * The stream is transformed to Server-Sent Events (SSE) format.\n *\n * @param options.status - The HTTP status code for the response.\n * @param options.statusText - The HTTP status text for the response.\n * @param options.headers - Additional HTTP headers to include in the response.\n * @param options.stream - The UI message chunk stream to send.\n * @param options.consumeSseStream - Optional callback to consume a copy of the SSE stream independently.\n *\n * @returns A `Response` object with the UI message stream as the body.\n */\nexport function createUIMessageStreamResponse({\n  status,\n  statusText,\n  headers,\n  stream,\n  consumeSseStream,\n}: UIMessageStreamResponseInit & {\n  stream: ReadableStream<UIMessageChunk>;\n}): Response {\n  let sseStream = stream.pipeThrough(new JsonToSseTransformStream());\n\n  // when the consumeSseStream is provided, we need to tee the stream\n  // and send the second part to the consumeSseStream function\n  // so that it can be consumed by the client independently\n  if (consumeSseStream) {\n    const [stream1, stream2] = sseStream.tee();\n    sseStream = stream1;\n    consumeSseStream({ stream: stream2 }); // no await (do not block the response)\n  }\n\n  return new Response(sseStream.pipeThrough(new TextEncoderStream()), {\n    status,\n    statusText,\n    headers: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS),\n  });\n}\n","import type { ServerResponse } from 'node:http';\nimport { prepareHeaders } from '../util/prepare-headers';\nimport { writeToServerResponse } from '../util/write-to-server-response';\nimport { JsonToSseTransformStream } from './json-to-sse-transform-stream';\nimport { UI_MESSAGE_STREAM_HEADERS } from './ui-message-stream-headers';\nimport type { UIMessageChunk } from './ui-message-chunks';\nimport type { UIMessageStreamResponseInit } from './ui-message-stream-response-init';\n\n/**\n * Pipes a UI message stream to a Node.js ServerResponse object.\n * The stream is transformed to Server-Sent Events (SSE) format.\n *\n * @param options.response - The Node.js ServerResponse object to write to.\n * @param options.status - The HTTP status code for the response.\n * @param options.statusText - The HTTP status text for the response.\n * @param options.headers - Additional HTTP headers to include in the response.\n * @param options.stream - The UI message chunk stream to send.\n * @param options.consumeSseStream - Optional callback to consume a copy of the SSE stream independently.\n * @returns A promise that resolves when the stream has been written.\n */\nexport function pipeUIMessageStreamToResponse({\n  response,\n  status,\n  statusText,\n  headers,\n  stream,\n  consumeSseStream,\n}: {\n  response: ServerResponse;\n  stream: ReadableStream<UIMessageChunk>;\n} & UIMessageStreamResponseInit): Promise<void> {\n  let sseStream = stream.pipeThrough(new JsonToSseTransformStream());\n\n  // when the consumeSseStream is provided, we need to tee the stream\n  // and send the second part to the consumeSseStream function\n  // so that it can be consumed by the client independently\n  if (consumeSseStream) {\n    const [stream1, stream2] = sseStream.tee();\n    sseStream = stream1;\n    consumeSseStream({ stream: stream2 }); // no await (do not block the response)\n  }\n\n  return writeToServerResponse({\n    response,\n    status,\n    statusText,\n    headers: Object.fromEntries(\n      prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS).entries(),\n    ),\n    stream: sseStream.pipeThrough(new TextEncoderStream()),\n  });\n}\n","import type { IdGenerator } from '@ai-sdk/provider-utils';\nimport type { UIMessage } from '../ui/ui-messages';\n\n/**\n * Determines the message ID to use for a response message.\n * If the last message is an assistant message, its ID is reused (continuation).\n * Otherwise, a new ID is generated or the provided ID is used.\n *\n * @param options.originalMessages - The original messages. If not provided, returns `undefined`\n *   since client-side ID generation is used in non-persistence mode.\n * @param options.responseMessageId - The response message ID or an ID generator function.\n *\n * @returns The message ID to use, or `undefined` if no persistence mode.\n */\nexport function getResponseUIMessageId({\n  originalMessages,\n  responseMessageId,\n}: {\n  originalMessages: UIMessage[] | undefined;\n  responseMessageId: string | IdGenerator;\n}) {\n  // when there are no original messages (i.e. no persistence),\n  // the assistant message id generation is handled on the client side.\n  if (originalMessages == null) {\n    return undefined;\n  }\n\n  const lastMessage = originalMessages[originalMessages.length - 1];\n\n  return lastMessage?.role === 'assistant'\n    ? lastMessage.id\n    : typeof responseMessageId === 'function'\n      ? responseMessageId()\n      : responseMessageId;\n}\n","import type { JSONObject } from '@ai-sdk/provider';\nimport { validateTypes, type FlexibleSchema } from '@ai-sdk/provider-utils';\nimport { UIMessageStreamError } from '../error/ui-message-stream-error';\nimport type { ProviderMetadata } from '../types';\nimport type { FinishReason } from '../types/language-model';\nimport {\n  isDataUIMessageChunk,\n  type DataUIMessageChunk,\n  type InferUIMessageChunk,\n  type UIMessageChunk,\n} from '../ui-message-stream/ui-message-chunks';\nimport { createIdMap } from '../util/create-id-map';\nimport type { ErrorHandler } from '../util/error-handler';\nimport { mergeObjects } from '../util/merge-objects';\nimport { parsePartialJson } from '../util/parse-partial-json';\nimport type { UIDataTypesToSchemas } from './chat';\nimport {\n  getStaticToolName,\n  isStaticToolUIPart,\n  isToolUIPart,\n  type CustomContentUIPart,\n  type DataUIPart,\n  type DynamicToolUIPart,\n  type InferUIMessageData,\n  type InferUIMessageMetadata,\n  type InferUIMessageToolCall,\n  type InferUIMessageTools,\n  type ReasoningUIPart,\n  type TextUIPart,\n  type ToolUIPart,\n  type UIMessage,\n  type UIMessagePart,\n} from './ui-messages';\nimport { warnIfUIMessageHasDeprecatedRawInput } from './warn-if-ui-message-has-deprecated-raw-input';\n\nexport type StreamingUIMessageState<UI_MESSAGE extends UIMessage> = {\n  message: UI_MESSAGE;\n  activeTextParts: Record<string, TextUIPart>;\n  activeReasoningParts: Record<string, ReasoningUIPart>;\n  partialToolCalls: Record<\n    string,\n    {\n      text: string;\n      index: number;\n      toolName: string;\n      dynamic?: boolean;\n      title?: string;\n      toolMetadata?: JSONObject;\n    }\n  >;\n  finishReason?: FinishReason;\n};\n\nexport type UIMessageStreamWriteOptions = {\n  updateStatus?: boolean;\n};\n\nexport function createStreamingUIMessageState<UI_MESSAGE extends UIMessage>({\n  lastMessage,\n  messageId,\n}: {\n  lastMessage: UI_MESSAGE | undefined;\n  messageId: string;\n}): StreamingUIMessageState<UI_MESSAGE> {\n  return {\n    message:\n      lastMessage?.role === 'assistant'\n        ? lastMessage\n        : ({\n            id: messageId,\n            metadata: undefined,\n            role: 'assistant',\n            parts: [] as UIMessagePart<\n              InferUIMessageData<UI_MESSAGE>,\n              InferUIMessageTools<UI_MESSAGE>\n            >[],\n          } as UI_MESSAGE),\n    activeTextParts: createIdMap(),\n    activeReasoningParts: createIdMap(),\n    partialToolCalls: createIdMap(),\n  };\n}\n\nexport function processUIMessageStream<UI_MESSAGE extends UIMessage>({\n  stream,\n  messageMetadataSchema,\n  dataPartSchemas,\n  runUpdateMessageJob,\n  onError,\n  onToolCall,\n  onData,\n}: {\n  // input stream is not fully typed yet:\n  stream: ReadableStream<UIMessageChunk>;\n  messageMetadataSchema?: FlexibleSchema<UI_MESSAGE['metadata']>;\n  dataPartSchemas?: UIDataTypesToSchemas<InferUIMessageData<UI_MESSAGE>>;\n  onToolCall?: (options: {\n    toolCall: InferUIMessageToolCall<UI_MESSAGE>;\n  }) => void | PromiseLike<void>;\n  onData?: (dataPart: DataUIPart<InferUIMessageData<UI_MESSAGE>>) => void;\n  runUpdateMessageJob: (\n    job: (options: {\n      state: StreamingUIMessageState<UI_MESSAGE>;\n      write: (options?: UIMessageStreamWriteOptions) => void;\n    }) => Promise<void>,\n  ) => Promise<void>;\n  onError: ErrorHandler;\n}): ReadableStream<InferUIMessageChunk<UI_MESSAGE>> {\n  return stream.pipeThrough(\n    new TransformStream<UIMessageChunk, InferUIMessageChunk<UI_MESSAGE>>({\n      async transform(chunk, controller) {\n        await runUpdateMessageJob(async ({ state, write }) => {\n          function getCurrentStepParts() {\n            const parts = state.message.parts;\n            let currentStepStartIndex = parts.length - 1;\n\n            while (\n              currentStepStartIndex >= 0 &&\n              parts[currentStepStartIndex].type !== 'step-start'\n            ) {\n              currentStepStartIndex--;\n            }\n\n            return parts.slice(currentStepStartIndex + 1);\n          }\n\n          function getCurrentStepToolInvocations() {\n            return getCurrentStepParts().filter(isToolUIPart);\n          }\n\n          function getToolInvocation(toolCallId: string) {\n            const toolInvocations = getCurrentStepToolInvocations();\n\n            let toolInvocation = toolInvocations.find(\n              invocation => invocation.toolCallId === toolCallId,\n            );\n\n            if (toolInvocation == null) {\n              const parts = state.message.parts;\n\n              for (let i = parts.length - 1; i >= 0; i--) {\n                const part = parts[i];\n                if (isToolUIPart(part) && part.toolCallId === toolCallId) {\n                  toolInvocation = part;\n                  break;\n                }\n              }\n            }\n\n            if (toolInvocation == null) {\n              throw new UIMessageStreamError({\n                chunkType: 'tool-invocation',\n                chunkId: toolCallId,\n                message: `No tool invocation found for tool call ID \"${toolCallId}\".`,\n              });\n            }\n\n            return toolInvocation;\n          }\n\n          function getToolInvocationByApprovalId(approvalId: string) {\n            const toolInvocations = state.message.parts.filter(isToolUIPart);\n\n            const toolInvocation = toolInvocations.find(\n              invocation => invocation.approval?.id === approvalId,\n            );\n\n            if (toolInvocation == null) {\n              throw new UIMessageStreamError({\n                chunkType: 'tool-approval-response',\n                chunkId: approvalId,\n                message: `No tool invocation found for approval ID \"${approvalId}\".`,\n              });\n            }\n\n            return toolInvocation;\n          }\n\n          function updateToolPart(\n            options: {\n              toolName: keyof InferUIMessageTools<UI_MESSAGE> & string;\n              toolCallId: string;\n              providerExecuted?: boolean;\n              title?: string;\n              toolMetadata?: JSONObject;\n            } & (\n              | {\n                  state: 'input-streaming';\n                  input: unknown;\n                  providerExecuted?: boolean;\n                  providerMetadata?: ProviderMetadata;\n                }\n              | {\n                  state: 'input-available';\n                  input: unknown;\n                  providerExecuted?: boolean;\n                  providerMetadata?: ProviderMetadata;\n                }\n              | {\n                  state: 'output-available';\n                  input: unknown;\n                  output: unknown;\n                  providerExecuted?: boolean;\n                  preliminary?: boolean;\n                  providerMetadata?: ProviderMetadata;\n                }\n              | {\n                  state: 'output-error';\n                  input: unknown;\n                  rawInput?: unknown;\n                  errorText: string;\n                  providerExecuted?: boolean;\n                  providerMetadata?: ProviderMetadata;\n                }\n            ),\n            existingPart?: ToolUIPart<InferUIMessageTools<UI_MESSAGE>>,\n          ) {\n            const part =\n              existingPart ??\n              (getCurrentStepParts().find(\n                part =>\n                  isStaticToolUIPart(part) &&\n                  part.toolCallId === options.toolCallId,\n              ) as ToolUIPart<InferUIMessageTools<UI_MESSAGE>> | undefined);\n\n            const anyOptions = options as any;\n            const anyPart = part as any;\n\n            if (part != null) {\n              part.state = options.state;\n              anyPart.input = anyOptions.input;\n              anyPart.output = anyOptions.output;\n              anyPart.errorText = anyOptions.errorText;\n              anyPart.rawInput = anyOptions.rawInput;\n              anyPart.preliminary = anyOptions.preliminary;\n              if (options.title !== undefined) {\n                anyPart.title = options.title;\n              }\n              if (options.toolMetadata !== undefined) {\n                anyPart.toolMetadata = options.toolMetadata;\n              }\n              // once providerExecuted is set, it stays for streaming\n              anyPart.providerExecuted =\n                anyOptions.providerExecuted ?? part.providerExecuted;\n\n              const providerMetadata = anyOptions.providerMetadata;\n\n              if (providerMetadata != null) {\n                if (\n                  options.state === 'output-available' ||\n                  options.state === 'output-error'\n                ) {\n                  const resultPart = part as Extract<\n                    ToolUIPart<InferUIMessageTools<UI_MESSAGE>>,\n                    { state: 'output-available' | 'output-error' }\n                  >;\n\n                  resultPart.resultProviderMetadata = providerMetadata;\n                } else {\n                  part.callProviderMetadata = providerMetadata;\n                }\n              }\n            } else {\n              state.message.parts.push({\n                type: `tool-${options.toolName}`,\n                toolCallId: options.toolCallId,\n                state: options.state,\n                title: options.title,\n                ...(options.toolMetadata !== undefined\n                  ? { toolMetadata: options.toolMetadata }\n                  : {}),\n                input: anyOptions.input,\n                output: anyOptions.output,\n                rawInput: anyOptions.rawInput,\n                errorText: anyOptions.errorText,\n                providerExecuted: anyOptions.providerExecuted,\n                preliminary: anyOptions.preliminary,\n                ...(anyOptions.providerMetadata != null &&\n                (options.state === 'output-available' ||\n                  options.state === 'output-error')\n                  ? { resultProviderMetadata: anyOptions.providerMetadata }\n                  : {}),\n                ...(anyOptions.providerMetadata != null &&\n                !(\n                  options.state === 'output-available' ||\n                  options.state === 'output-error'\n                )\n                  ? { callProviderMetadata: anyOptions.providerMetadata }\n                  : {}),\n              } as ToolUIPart<InferUIMessageTools<UI_MESSAGE>>);\n            }\n          }\n\n          function updateDynamicToolPart(\n            options: {\n              toolName: keyof InferUIMessageTools<UI_MESSAGE> & string;\n              toolCallId: string;\n              providerExecuted?: boolean;\n              title?: string;\n              toolMetadata?: JSONObject;\n            } & (\n              | {\n                  state: 'input-streaming';\n                  input: unknown;\n                  providerMetadata?: ProviderMetadata;\n                }\n              | {\n                  state: 'input-available';\n                  input: unknown;\n                  providerMetadata?: ProviderMetadata;\n                }\n              | {\n                  state: 'output-available';\n                  input: unknown;\n                  output: unknown;\n                  preliminary: boolean | undefined;\n                  providerMetadata?: ProviderMetadata;\n                }\n              | {\n                  state: 'output-error';\n                  input: unknown;\n                  errorText: string;\n                  providerMetadata?: ProviderMetadata;\n                }\n            ),\n            existingPart?: DynamicToolUIPart,\n          ) {\n            const part =\n              existingPart ??\n              (getCurrentStepParts().find(\n                part =>\n                  part.type === 'dynamic-tool' &&\n                  part.toolCallId === options.toolCallId,\n              ) as DynamicToolUIPart | undefined);\n\n            const anyOptions = options as any;\n            const anyPart = part as any;\n\n            if (part != null) {\n              part.state = options.state;\n              anyPart.toolName = options.toolName;\n              anyPart.input = anyOptions.input;\n              anyPart.output = anyOptions.output;\n              anyPart.errorText = anyOptions.errorText;\n              anyPart.rawInput = anyOptions.rawInput ?? anyPart.rawInput;\n              anyPart.preliminary = anyOptions.preliminary;\n              if (options.title !== undefined) {\n                anyPart.title = options.title;\n              }\n              if (options.toolMetadata !== undefined) {\n                anyPart.toolMetadata = options.toolMetadata;\n              }\n              // once providerExecuted is set, it stays for streaming\n              anyPart.providerExecuted =\n                anyOptions.providerExecuted ?? part.providerExecuted;\n\n              const providerMetadata = anyOptions.providerMetadata;\n\n              if (providerMetadata != null) {\n                if (\n                  options.state === 'output-available' ||\n                  options.state === 'output-error'\n                ) {\n                  const resultPart = part as Extract<\n                    DynamicToolUIPart,\n                    { state: 'output-available' | 'output-error' }\n                  >;\n\n                  resultPart.resultProviderMetadata = providerMetadata;\n                } else {\n                  part.callProviderMetadata = providerMetadata;\n                }\n              }\n            } else {\n              state.message.parts.push({\n                type: 'dynamic-tool',\n                toolName: options.toolName,\n                toolCallId: options.toolCallId,\n                state: options.state,\n                input: anyOptions.input,\n                output: anyOptions.output,\n                errorText: anyOptions.errorText,\n                preliminary: anyOptions.preliminary,\n                providerExecuted: anyOptions.providerExecuted,\n                title: options.title,\n                ...(options.toolMetadata !== undefined\n                  ? { toolMetadata: options.toolMetadata }\n                  : {}),\n                ...(anyOptions.providerMetadata != null &&\n                (options.state === 'output-available' ||\n                  options.state === 'output-error')\n                  ? { resultProviderMetadata: anyOptions.providerMetadata }\n                  : {}),\n                ...(anyOptions.providerMetadata != null &&\n                !(\n                  options.state === 'output-available' ||\n                  options.state === 'output-error'\n                )\n                  ? { callProviderMetadata: anyOptions.providerMetadata }\n                  : {}),\n              } as DynamicToolUIPart);\n            }\n          }\n\n          async function updateMessageMetadata(metadata: unknown) {\n            if (metadata != null) {\n              const mergedMetadata =\n                state.message.metadata != null\n                  ? mergeObjects(state.message.metadata, metadata)\n                  : metadata;\n\n              if (messageMetadataSchema != null) {\n                await validateTypes({\n                  value: mergedMetadata,\n                  schema: messageMetadataSchema,\n                  context: {\n                    field: 'message.metadata',\n                    entityId: state.message.id,\n                  },\n                });\n              }\n\n              state.message.metadata =\n                mergedMetadata as InferUIMessageMetadata<UI_MESSAGE>;\n            }\n          }\n\n          switch (chunk.type) {\n            case 'text-start': {\n              const textPart: TextUIPart = {\n                type: 'text',\n                text: '',\n                providerMetadata: chunk.providerMetadata,\n                state: 'streaming',\n              };\n              state.activeTextParts[chunk.id] = textPart;\n              state.message.parts.push(textPart);\n              write();\n              break;\n            }\n\n            case 'text-delta': {\n              const textPart = state.activeTextParts[chunk.id];\n              if (textPart == null) {\n                throw new UIMessageStreamError({\n                  chunkType: 'text-delta',\n                  chunkId: chunk.id,\n                  message:\n                    `Received text-delta for missing text part with ID \"${chunk.id}\". ` +\n                    `Ensure a \"text-start\" chunk is sent before any \"text-delta\" chunks.`,\n                });\n              }\n              textPart.text += chunk.delta;\n              textPart.providerMetadata =\n                chunk.providerMetadata ?? textPart.providerMetadata;\n              write();\n              break;\n            }\n\n            case 'text-end': {\n              const textPart = state.activeTextParts[chunk.id];\n              if (textPart == null) {\n                throw new UIMessageStreamError({\n                  chunkType: 'text-end',\n                  chunkId: chunk.id,\n                  message:\n                    `Received text-end for missing text part with ID \"${chunk.id}\". ` +\n                    `Ensure a \"text-start\" chunk is sent before any \"text-end\" chunks.`,\n                });\n              }\n              textPart.state = 'done';\n              textPart.providerMetadata =\n                chunk.providerMetadata ?? textPart.providerMetadata;\n              delete state.activeTextParts[chunk.id];\n              write();\n              break;\n            }\n\n            case 'custom': {\n              const customPart: CustomContentUIPart = {\n                type: 'custom',\n                kind: chunk.kind,\n                providerMetadata: chunk.providerMetadata,\n              };\n              state.message.parts.push(customPart);\n              write();\n              break;\n            }\n\n            case 'reasoning-start': {\n              const reasoningPart: ReasoningUIPart = {\n                type: 'reasoning',\n                id: chunk.id,\n                text: '',\n                providerMetadata: chunk.providerMetadata,\n                state: 'streaming',\n              };\n              state.activeReasoningParts[chunk.id] = reasoningPart;\n              state.message.parts.push(reasoningPart);\n              write();\n              break;\n            }\n\n            case 'reasoning-delta': {\n              const reasoningPart = state.activeReasoningParts[chunk.id];\n              if (reasoningPart == null) {\n                throw new UIMessageStreamError({\n                  chunkType: 'reasoning-delta',\n                  chunkId: chunk.id,\n                  message:\n                    `Received reasoning-delta for missing reasoning part with ID \"${chunk.id}\". ` +\n                    `Ensure a \"reasoning-start\" chunk is sent before any \"reasoning-delta\" chunks.`,\n                });\n              }\n              reasoningPart.text += chunk.delta;\n              reasoningPart.providerMetadata =\n                chunk.providerMetadata ?? reasoningPart.providerMetadata;\n              write();\n              break;\n            }\n\n            case 'reasoning-end': {\n              const reasoningPart = state.activeReasoningParts[chunk.id];\n              if (reasoningPart == null) {\n                throw new UIMessageStreamError({\n                  chunkType: 'reasoning-end',\n                  chunkId: chunk.id,\n                  message:\n                    `Received reasoning-end for missing reasoning part with ID \"${chunk.id}\". ` +\n                    `Ensure a \"reasoning-start\" chunk is sent before any \"reasoning-end\" chunks.`,\n                });\n              }\n              reasoningPart.providerMetadata =\n                chunk.providerMetadata ?? reasoningPart.providerMetadata;\n              reasoningPart.state = 'done';\n              delete state.activeReasoningParts[chunk.id];\n\n              write();\n              break;\n            }\n\n            case 'file':\n            case 'reasoning-file': {\n              state.message.parts.push({\n                type: chunk.type,\n                mediaType: chunk.mediaType,\n                url: chunk.url,\n                ...(chunk.providerMetadata != null\n                  ? { providerMetadata: chunk.providerMetadata }\n                  : {}),\n              });\n\n              write();\n              break;\n            }\n\n            case 'source-url': {\n              state.message.parts.push({\n                type: 'source-url',\n                sourceId: chunk.sourceId,\n                url: chunk.url,\n                title: chunk.title,\n                providerMetadata: chunk.providerMetadata,\n              });\n\n              write();\n              break;\n            }\n\n            case 'source-document': {\n              state.message.parts.push({\n                type: 'source-document',\n                sourceId: chunk.sourceId,\n                mediaType: chunk.mediaType,\n                title: chunk.title,\n                filename: chunk.filename,\n                providerMetadata: chunk.providerMetadata,\n              });\n\n              write();\n              break;\n            }\n\n            case 'tool-input-start': {\n              const toolInvocations =\n                getCurrentStepParts().filter(isStaticToolUIPart);\n\n              // add the partial tool call to the map\n              state.partialToolCalls[chunk.toolCallId] = {\n                text: '',\n                toolName: chunk.toolName,\n                index: toolInvocations.length,\n                dynamic: chunk.dynamic,\n                title: chunk.title,\n                toolMetadata: chunk.toolMetadata,\n              };\n\n              if (chunk.dynamic) {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: 'input-streaming',\n                  input: undefined,\n                  providerExecuted: chunk.providerExecuted,\n                  title: chunk.title,\n                  toolMetadata: chunk.toolMetadata,\n                  providerMetadata: chunk.providerMetadata,\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: 'input-streaming',\n                  input: undefined,\n                  providerExecuted: chunk.providerExecuted,\n                  title: chunk.title,\n                  toolMetadata: chunk.toolMetadata,\n                  providerMetadata: chunk.providerMetadata,\n                });\n              }\n\n              write();\n              break;\n            }\n\n            case 'tool-input-delta': {\n              const partialToolCall = state.partialToolCalls[chunk.toolCallId];\n              if (partialToolCall == null) {\n                throw new UIMessageStreamError({\n                  chunkType: 'tool-input-delta',\n                  chunkId: chunk.toolCallId,\n                  message:\n                    `Received tool-input-delta for missing tool call with ID \"${chunk.toolCallId}\". ` +\n                    `Ensure a \"tool-input-start\" chunk is sent before any \"tool-input-delta\" chunks.`,\n                });\n              }\n\n              partialToolCall.text += chunk.inputTextDelta;\n\n              const { value: partialArgs } = await parsePartialJson(\n                partialToolCall.text,\n              );\n\n              if (partialToolCall.dynamic) {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: partialToolCall.toolName,\n                  state: 'input-streaming',\n                  input: partialArgs,\n                  title: partialToolCall.title,\n                  toolMetadata: partialToolCall.toolMetadata,\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: partialToolCall.toolName,\n                  state: 'input-streaming',\n                  input: partialArgs,\n                  title: partialToolCall.title,\n                  toolMetadata: partialToolCall.toolMetadata,\n                });\n              }\n\n              write();\n              break;\n            }\n\n            case 'tool-input-available': {\n              if (chunk.dynamic) {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: 'input-available',\n                  input: chunk.input,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  title: chunk.title,\n                  toolMetadata: chunk.toolMetadata,\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: 'input-available',\n                  input: chunk.input,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  title: chunk.title,\n                  toolMetadata: chunk.toolMetadata,\n                });\n              }\n\n              write();\n\n              // invoke the onToolCall callback if it exists. This is blocking.\n              // In the future we should make this non-blocking, which\n              // requires additional state management for error handling etc.\n              // Skip calling onToolCall for provider-executed tools since they are already executed\n              if (onToolCall && !chunk.providerExecuted) {\n                await onToolCall({\n                  toolCall: chunk as InferUIMessageToolCall<UI_MESSAGE>,\n                });\n              }\n              break;\n            }\n\n            case 'tool-input-error': {\n              // When a part already exists for this toolCallId (e.g. from\n              // tool-input-start), honour its type so we update in place\n              // instead of creating a duplicate with a mismatched type.\n              const existingPart = getCurrentStepParts()\n                .filter(isToolUIPart)\n                .find(p => p.toolCallId === chunk.toolCallId);\n              const isDynamic =\n                existingPart != null\n                  ? existingPart.type === 'dynamic-tool'\n                  : !!chunk.dynamic;\n\n              if (isDynamic) {\n                updateDynamicToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: 'output-error',\n                  input: chunk.input,\n                  errorText: chunk.errorText,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  toolMetadata: chunk.toolMetadata,\n                });\n              } else {\n                updateToolPart({\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                  state: 'output-error',\n                  input: undefined,\n                  rawInput: chunk.input,\n                  errorText: chunk.errorText,\n                  providerExecuted: chunk.providerExecuted,\n                  providerMetadata: chunk.providerMetadata,\n                  toolMetadata: chunk.toolMetadata,\n                });\n\n                warnIfUIMessageHasDeprecatedRawInput([state.message]);\n              }\n\n              write();\n              break;\n            }\n\n            case 'tool-approval-request': {\n              const toolInvocation = getToolInvocation(chunk.toolCallId);\n              toolInvocation.state = 'approval-requested';\n              toolInvocation.approval = {\n                id: chunk.approvalId,\n                ...(chunk.approvalDescriptor != null\n                  ? { descriptor: chunk.approvalDescriptor }\n                  : {}),\n                ...(chunk.reason != null\n                  ? { requestReason: chunk.reason }\n                  : {}),\n                ...(chunk.isAutomatic === true ? { isAutomatic: true } : {}),\n                ...(chunk.signature != null\n                  ? { signature: chunk.signature }\n                  : {}),\n              };\n              write();\n              break;\n            }\n\n            case 'tool-approval-response': {\n              const toolInvocation = getToolInvocationByApprovalId(\n                chunk.approvalId,\n              );\n              const approval =\n                toolInvocation.approval == null\n                  ? { id: chunk.approvalId }\n                  : toolInvocation.approval;\n\n              toolInvocation.state = 'approval-responded';\n              toolInvocation.approval = {\n                ...approval,\n                id: chunk.approvalId,\n                approved: chunk.approved,\n                ...(chunk.reason != null ? { reason: chunk.reason } : {}),\n              };\n              if (chunk.providerExecuted != null) {\n                toolInvocation.providerExecuted = chunk.providerExecuted;\n              }\n              if (chunk.providerMetadata != null) {\n                toolInvocation.callProviderMetadata = chunk.providerMetadata;\n              }\n              write();\n              break;\n            }\n\n            case 'tool-output-denied': {\n              const toolInvocation = getToolInvocation(chunk.toolCallId);\n              toolInvocation.state = 'output-denied';\n              write();\n              break;\n            }\n\n            case 'tool-output-available': {\n              const toolInvocation = getToolInvocation(chunk.toolCallId);\n\n              if (toolInvocation.type === 'dynamic-tool') {\n                updateDynamicToolPart(\n                  {\n                    toolCallId: chunk.toolCallId,\n                    toolName: toolInvocation.toolName,\n                    state: 'output-available',\n                    input: (toolInvocation as any).input,\n                    output: chunk.output,\n                    preliminary: chunk.preliminary,\n                    providerExecuted: chunk.providerExecuted,\n                    providerMetadata: chunk.providerMetadata,\n                    title: toolInvocation.title,\n                    toolMetadata: toolInvocation.toolMetadata,\n                  },\n                  toolInvocation,\n                );\n              } else {\n                updateToolPart(\n                  {\n                    toolCallId: chunk.toolCallId,\n                    toolName: getStaticToolName(toolInvocation),\n                    state: 'output-available',\n                    input: (toolInvocation as any).input,\n                    output: chunk.output,\n                    providerExecuted: chunk.providerExecuted,\n                    preliminary: chunk.preliminary,\n                    providerMetadata: chunk.providerMetadata,\n                    title: toolInvocation.title,\n                    toolMetadata: toolInvocation.toolMetadata,\n                  },\n                  toolInvocation as ToolUIPart<InferUIMessageTools<UI_MESSAGE>>,\n                );\n              }\n\n              write();\n              break;\n            }\n\n            case 'tool-output-error': {\n              const toolInvocation = getToolInvocation(chunk.toolCallId);\n\n              if (toolInvocation.type === 'dynamic-tool') {\n                updateDynamicToolPart(\n                  {\n                    toolCallId: chunk.toolCallId,\n                    toolName: toolInvocation.toolName,\n                    state: 'output-error',\n                    input: (toolInvocation as any).input,\n                    errorText: chunk.errorText,\n                    providerExecuted: chunk.providerExecuted,\n                    providerMetadata: chunk.providerMetadata,\n                    title: toolInvocation.title,\n                    toolMetadata: toolInvocation.toolMetadata,\n                  },\n                  toolInvocation,\n                );\n              } else {\n                updateToolPart(\n                  {\n                    toolCallId: chunk.toolCallId,\n                    toolName: getStaticToolName(toolInvocation),\n                    state: 'output-error',\n                    input: (toolInvocation as any).input,\n                    rawInput: (toolInvocation as any).rawInput,\n                    errorText: chunk.errorText,\n                    providerExecuted: chunk.providerExecuted,\n                    providerMetadata: chunk.providerMetadata,\n                    title: toolInvocation.title,\n                    toolMetadata: toolInvocation.toolMetadata,\n                  },\n                  toolInvocation as ToolUIPart<InferUIMessageTools<UI_MESSAGE>>,\n                );\n              }\n\n              write();\n              break;\n            }\n\n            case 'start-step': {\n              // add a step boundary part to the message\n              state.message.parts.push({ type: 'step-start' });\n              break;\n            }\n\n            case 'finish-step': {\n              // Active parts are closed by their explicit end chunks. A merged\n              // stream's step can finish while another stream's part is active.\n              break;\n            }\n\n            case 'reset-step': {\n              const currentStepParts = getCurrentStepParts();\n\n              state.activeTextParts = createIdMap();\n              state.activeReasoningParts = createIdMap();\n              state.partialToolCalls = createIdMap();\n\n              if (currentStepParts.length > 0) {\n                state.message.parts.splice(\n                  state.message.parts.length - currentStepParts.length,\n                  currentStepParts.length,\n                );\n                write();\n              }\n              break;\n            }\n\n            case 'start': {\n              if (chunk.messageId != null) {\n                state.message.id = chunk.messageId;\n              }\n\n              await updateMessageMetadata(chunk.messageMetadata);\n\n              if (chunk.messageId != null || chunk.messageMetadata != null) {\n                write({ updateStatus: false });\n              }\n              break;\n            }\n\n            case 'finish': {\n              if (chunk.finishReason != null) {\n                state.finishReason = chunk.finishReason;\n              }\n              await updateMessageMetadata(chunk.messageMetadata);\n              if (chunk.messageMetadata != null) {\n                write();\n              }\n              break;\n            }\n\n            case 'message-metadata': {\n              await updateMessageMetadata(chunk.messageMetadata);\n              if (chunk.messageMetadata != null) {\n                write();\n              }\n              break;\n            }\n\n            case 'error': {\n              onError?.(new Error(chunk.errorText));\n              break;\n            }\n\n            default: {\n              if (isDataUIMessageChunk(chunk)) {\n                // validate data chunk if dataPartSchemas is provided\n                if (dataPartSchemas?.[chunk.type] != null) {\n                  const partIdx = state.message.parts.findIndex(\n                    p =>\n                      'id' in p &&\n                      'data' in p &&\n                      p.id === chunk.id &&\n                      p.type === chunk.type,\n                  );\n                  const actualPartIdx =\n                    partIdx >= 0 ? partIdx : state.message.parts.length;\n\n                  await validateTypes({\n                    value: chunk.data,\n                    schema: dataPartSchemas[chunk.type],\n                    context: {\n                      field: `message.parts[${actualPartIdx}].data`,\n                      entityName: chunk.type,\n                      entityId: chunk.id,\n                    },\n                  });\n                }\n\n                // cast, validation is done above\n                const dataChunk = chunk as DataUIMessageChunk<\n                  InferUIMessageData<UI_MESSAGE>\n                >;\n\n                // transient parts are not added to the message state\n                if (dataChunk.transient) {\n                  onData?.(dataChunk);\n                  break;\n                }\n\n                const existingUIPart =\n                  dataChunk.id != null\n                    ? (state.message.parts.find(\n                        chunkArg =>\n                          dataChunk.type === chunkArg.type &&\n                          dataChunk.id === chunkArg.id,\n                      ) as\n                        | DataUIPart<InferUIMessageData<UI_MESSAGE>>\n                        | undefined)\n                    : undefined;\n\n                if (existingUIPart != null) {\n                  existingUIPart.data = dataChunk.data;\n                } else {\n                  state.message.parts.push(dataChunk);\n                }\n\n                onData?.(dataChunk);\n\n                write();\n              }\n            }\n          }\n\n          controller.enqueue(chunk as InferUIMessageChunk<UI_MESSAGE>);\n        });\n      },\n    }),\n  );\n}\n","import type { JSONObject } from '@ai-sdk/provider';\nimport {\n  providerMetadataSchema,\n  type ProviderMetadata,\n} from '../types/provider-metadata';\nimport { jsonValueSchema } from '../types/json-value';\nimport type { FinishReason } from '../types/language-model';\nimport type {\n  InferUIMessageData,\n  InferUIMessageMetadata,\n  UIDataTypes,\n  UIMessage,\n} from '../ui/ui-messages';\nimport type { ValueOf } from '../util/value-of';\nimport { z, type ZodType } from '../util/zod';\nimport { lazySchema, zodSchema } from '@ai-sdk/provider-utils';\n\nconst toolMetadataSchema: ZodType<JSONObject> = z.record(\n  z.string(),\n  jsonValueSchema.optional(),\n);\n\nexport const uiMessageChunkSchema = lazySchema(() =>\n  zodSchema<UIMessageChunk>(\n    z.union([\n      z.looseObject({\n        type: z.literal('text-start'),\n        id: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.looseObject({\n        type: z.literal('text-delta'),\n        id: z.string(),\n        delta: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.looseObject({\n        type: z.literal('text-end'),\n        id: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.looseObject({\n        type: z.literal('error'),\n        errorText: z.string(),\n      }),\n      z.looseObject({\n        type: z.literal('tool-input-start'),\n        toolCallId: z.string(),\n        toolName: z.string(),\n        providerExecuted: z.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z.boolean().optional(),\n        title: z.string().optional(),\n      }),\n      z.looseObject({\n        type: z.literal('tool-input-delta'),\n        toolCallId: z.string(),\n        inputTextDelta: z.string(),\n      }),\n      z.looseObject({\n        type: z.literal('tool-input-available'),\n        toolCallId: z.string(),\n        toolName: z.string(),\n        input: z.unknown(),\n        providerExecuted: z.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z.boolean().optional(),\n        title: z.string().optional(),\n      }),\n      z.looseObject({\n        type: z.literal('tool-input-error'),\n        toolCallId: z.string(),\n        toolName: z.string(),\n        input: z.unknown(),\n        providerExecuted: z.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z.boolean().optional(),\n        errorText: z.string(),\n        title: z.string().optional(),\n      }),\n      z.looseObject({\n        type: z.literal('tool-approval-request'),\n        approvalId: z.string(),\n        toolCallId: z.string(),\n        approvalDescriptor: z.unknown().optional(),\n        reason: z.string().optional(),\n        isAutomatic: z.boolean().optional(),\n        signature: z.string().optional(),\n      }),\n      z.looseObject({\n        type: z.literal('tool-approval-response'),\n        approvalId: z.string(),\n        approved: z.boolean(),\n        reason: z.string().optional(),\n        providerExecuted: z.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.looseObject({\n        type: z.literal('tool-output-available'),\n        toolCallId: z.string(),\n        output: z.unknown(),\n        providerExecuted: z.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z.boolean().optional(),\n        preliminary: z.boolean().optional(),\n      }),\n      z.looseObject({\n        type: z.literal('tool-output-error'),\n        toolCallId: z.string(),\n        errorText: z.string(),\n        providerExecuted: z.boolean().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n        toolMetadata: toolMetadataSchema.optional(),\n        dynamic: z.boolean().optional(),\n      }),\n      z.looseObject({\n        type: z.literal('tool-output-denied'),\n        toolCallId: z.string(),\n      }),\n      z.looseObject({\n        type: z.literal('reasoning-start'),\n        id: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.looseObject({\n        type: z.literal('reasoning-delta'),\n        id: z.string(),\n        delta: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.looseObject({\n        type: z.literal('reasoning-end'),\n        id: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.looseObject({\n        type: z.literal('custom'),\n        kind: z.string().transform(value => value as `${string}.${string}`),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.looseObject({\n        type: z.literal('source-url'),\n        sourceId: z.string(),\n        url: z.string(),\n        title: z.string().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.looseObject({\n        type: z.literal('source-document'),\n        sourceId: z.string(),\n        mediaType: z.string(),\n        title: z.string(),\n        filename: z.string().optional(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.looseObject({\n        type: z.literal('file'),\n        url: z.string(),\n        mediaType: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.looseObject({\n        type: z.literal('reasoning-file'),\n        url: z.string(),\n        mediaType: z.string(),\n        providerMetadata: providerMetadataSchema.optional(),\n      }),\n      z.looseObject({\n        type: z.custom<`data-${string}`>(\n          (value): value is `data-${string}` =>\n            typeof value === 'string' && value.startsWith('data-'),\n          { message: 'Type must start with \"data-\"' },\n        ),\n        id: z.string().optional(),\n        data: z.unknown(),\n        transient: z.boolean().optional(),\n      }),\n      z.looseObject({\n        type: z.literal('start-step'),\n      }),\n      z.looseObject({\n        type: z.literal('finish-step'),\n      }),\n      z.looseObject({\n        type: z.literal('reset-step'),\n      }),\n      z.looseObject({\n        type: z.literal('start'),\n        messageId: z.string().optional(),\n        messageMetadata: z.unknown().optional(),\n      }),\n      z.looseObject({\n        type: z.literal('finish'),\n        finishReason: z\n          .enum([\n            'stop',\n            'length',\n            'content-filter',\n            'tool-calls',\n            'error',\n            'other',\n          ] as const satisfies readonly FinishReason[])\n          .optional(),\n        messageMetadata: z.unknown().optional(),\n      }),\n      z.looseObject({\n        type: z.literal('abort'),\n        reason: z.string().optional(),\n      }),\n      z.looseObject({\n        type: z.literal('message-metadata'),\n        messageMetadata: z.unknown(),\n      }),\n    ]),\n  ),\n);\n\nexport type DataUIMessageChunk<DATA_TYPES extends UIDataTypes> = ValueOf<{\n  [NAME in keyof DATA_TYPES & string]: {\n    type: `data-${NAME}`;\n    id?: string;\n    data: DATA_TYPES[NAME];\n    transient?: boolean;\n  };\n}>;\n\nexport type UIMessageChunk<\n  METADATA = unknown,\n  DATA_TYPES extends UIDataTypes = UIDataTypes,\n> =\n  | {\n      type: 'text-start';\n      id: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'text-delta';\n      delta: string;\n      id: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'text-end';\n      id: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'reasoning-start';\n      id: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'reasoning-delta';\n      id: string;\n      delta: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'reasoning-end';\n      id: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'custom';\n      kind: `${string}.${string}`;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'error';\n      errorText: string;\n    }\n  | {\n      type: 'tool-input-available';\n      toolCallId: string;\n      toolName: string;\n      input: unknown;\n      providerExecuted?: boolean;\n      providerMetadata?: ProviderMetadata;\n      toolMetadata?: JSONObject;\n      dynamic?: boolean;\n      title?: string;\n    }\n  | {\n      type: 'tool-input-error';\n      toolCallId: string;\n      toolName: string;\n      input: unknown;\n      providerExecuted?: boolean;\n      providerMetadata?: ProviderMetadata;\n      toolMetadata?: JSONObject;\n      dynamic?: boolean;\n      errorText: string;\n      title?: string;\n    }\n  | {\n      type: 'tool-approval-request';\n      approvalId: string;\n      toolCallId: string;\n      approvalDescriptor?: unknown;\n      reason?: string;\n      isAutomatic?: boolean;\n      signature?: string;\n    }\n  | {\n      type: 'tool-approval-response';\n      approvalId: string;\n      approved: boolean;\n      reason?: string;\n      providerExecuted?: boolean;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'tool-output-available';\n      toolCallId: string;\n      output: unknown;\n      providerExecuted?: boolean;\n      providerMetadata?: ProviderMetadata;\n      toolMetadata?: JSONObject;\n      dynamic?: boolean;\n      preliminary?: boolean;\n    }\n  | {\n      type: 'tool-output-error';\n      toolCallId: string;\n      errorText: string;\n      providerExecuted?: boolean;\n      providerMetadata?: ProviderMetadata;\n      toolMetadata?: JSONObject;\n      dynamic?: boolean;\n    }\n  | {\n      type: 'tool-output-denied';\n      toolCallId: string;\n    }\n  | {\n      type: 'tool-input-start';\n      toolCallId: string;\n      toolName: string;\n      providerExecuted?: boolean;\n      providerMetadata?: ProviderMetadata;\n      toolMetadata?: JSONObject;\n      dynamic?: boolean;\n      title?: string;\n    }\n  | {\n      type: 'tool-input-delta';\n      toolCallId: string;\n      inputTextDelta: string;\n    }\n  | {\n      type: 'source-url';\n      sourceId: string;\n      url: string;\n      title?: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'source-document';\n      sourceId: string;\n      mediaType: string;\n      title: string;\n      filename?: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'file';\n      url: string;\n      mediaType: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | {\n      type: 'reasoning-file';\n      url: string;\n      mediaType: string;\n      providerMetadata?: ProviderMetadata;\n    }\n  | DataUIMessageChunk<DATA_TYPES>\n  | {\n      type: 'start-step';\n    }\n  | {\n      type: 'finish-step';\n    }\n  | {\n      /**\n       * Removes all message parts added during the current step.\n       */\n      type: 'reset-step';\n    }\n  | {\n      type: 'start';\n      messageId?: string;\n      messageMetadata?: METADATA;\n    }\n  | {\n      type: 'finish';\n      finishReason?: FinishReason;\n      messageMetadata?: METADATA;\n    }\n  | {\n      type: 'abort';\n      reason?: string;\n    }\n  | {\n      type: 'message-metadata';\n      messageMetadata: METADATA;\n    };\n\nexport function isDataUIMessageChunk(\n  chunk: UIMessageChunk,\n): chunk is DataUIMessageChunk<UIDataTypes> {\n  return chunk.type.startsWith('data-');\n}\n\nexport type InferUIMessageChunk<T extends UIMessage> = UIMessageChunk<\n  InferUIMessageMetadata<T>,\n  InferUIMessageData<T>\n>;\n","/**\n * Creates a string-keyed map without an object prototype.\n *\n * Use this for lookup tables keyed by IDs or names that may come from outside\n * the SDK, such as streamed chunk IDs or tool call IDs. Unlike `{}`, these maps\n * do not inherit `__proto__`, `constructor`, or other Object prototype members,\n * so a missing untrusted key cannot resolve to a shared prototype object.\n */\nexport function createIdMap<T>(): Record<string, T> {\n  return Object.create(null);\n}\n","import type { JSONObject } from '@ai-sdk/provider';\nimport type {\n  InferToolInput,\n  InferToolOutput,\n  Tool,\n  ToolCall,\n  ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type { ProviderMetadata } from '../types/provider-metadata';\nimport type { ProviderReference } from '../types/provider-reference';\nimport type { DeepPartial } from '../util/deep-partial';\nimport type { ValueOf } from '../util/value-of';\n\n/**\n * The data types that can be used in the UI message for the UI message data parts.\n */\nexport type UIDataTypes = Record<string, unknown>;\n\nexport type UITool = {\n  input: unknown;\n  output: unknown | undefined;\n};\n\n/**\n * Infer the input and output types of a tool so it can be used as a UI tool.\n */\nexport type InferUITool<TOOL extends Tool> = {\n  input: InferToolInput<TOOL>;\n  output: InferToolOutput<TOOL>;\n};\n\n/**\n * Infer the input and output types of a tool set so it can be used as a UI tool set.\n */\nexport type InferUITools<TOOLS extends ToolSet> = {\n  [NAME in keyof TOOLS & string]: InferUITool<TOOLS[NAME]>;\n};\n\nexport type UITools = Record<string, UITool>;\n\n/**\n * AI SDK UI Messages. They are used in the client and to communicate between the frontend and the API routes.\n */\nexport interface UIMessage<\n  METADATA = unknown,\n  DATA_PARTS extends UIDataTypes = UIDataTypes,\n  TOOLS extends UITools = UITools,\n> {\n  /**\n   * A unique identifier for the message.\n   */\n  id: string;\n\n  /**\n   * The role of the message.\n   */\n  role: 'system' | 'user' | 'assistant';\n\n  /**\n   * The metadata of the message.\n   */\n  metadata?: METADATA;\n\n  /**\n   * The parts of the message. Use this for rendering the message in the UI.\n   *\n   * System messages should be avoided (set the system prompt on the server instead).\n   * They can have text parts.\n   *\n   * User messages can have text parts and file parts.\n   *\n   * Assistant messages can have text, reasoning, tool invocation, and file parts.\n   */\n  parts: Array<UIMessagePart<DATA_PARTS, TOOLS>>;\n}\n\nexport type UIMessagePart<\n  DATA_TYPES extends UIDataTypes,\n  TOOLS extends UITools,\n> =\n  | TextUIPart\n  | CustomContentUIPart\n  | ReasoningUIPart\n  | ToolUIPart<TOOLS>\n  | DynamicToolUIPart\n  | SourceUrlUIPart\n  | SourceDocumentUIPart\n  | FileUIPart\n  | ReasoningFileUIPart\n  | DataUIPart<DATA_TYPES>\n  | StepStartUIPart;\n\n/**\n * A text part of a message.\n */\nexport type TextUIPart = {\n  type: 'text';\n\n  /**\n   * The text content.\n   */\n  text: string;\n\n  /**\n   * The state of the text part.\n   */\n  state?: 'streaming' | 'done';\n\n  /**\n   * The provider metadata.\n   */\n  providerMetadata?: ProviderMetadata;\n};\n\n/**\n * A provider-specific part of a message.\n */\nexport type CustomContentUIPart = {\n  type: 'custom';\n\n  /**\n   * The kind of custom content, in the format `{provider}.{provider-type}`.\n   */\n  kind: `${string}.${string}`;\n\n  /**\n   * The provider metadata.\n   */\n  providerMetadata?: ProviderMetadata;\n};\n\n/**\n * A reasoning part of a message.\n */\nexport type ReasoningUIPart = {\n  type: 'reasoning';\n\n  /**\n   * The reasoning part ID.\n   */\n  id?: string;\n\n  /**\n   * The reasoning text.\n   */\n  text: string;\n\n  /**\n   * The state of the reasoning part.\n   */\n  state?: 'streaming' | 'done';\n\n  /**\n   * The provider metadata.\n   */\n  providerMetadata?: ProviderMetadata;\n};\n\n/**\n * A source part of a message.\n */\nexport type SourceUrlUIPart = {\n  type: 'source-url';\n  sourceId: string;\n  url: string;\n  title?: string;\n  providerMetadata?: ProviderMetadata;\n};\n\n/**\n * A document source part of a message.\n */\nexport type SourceDocumentUIPart = {\n  type: 'source-document';\n  sourceId: string;\n  mediaType: string;\n  title: string;\n  filename?: string;\n  providerMetadata?: ProviderMetadata;\n};\n\n/**\n * A file part of a message.\n */\nexport type FileUIPart = {\n  type: 'file';\n\n  /**\n   * Either a full IANA media type (`type/subtype`, e.g. `image/png`) or just\n   * the top-level IANA segment (e.g. `image`, `audio`, `video`, `text`).\n   *\n   * `*`-subtype wildcards (e.g. `image/*`) are normalized as equivalent to the\n   * top-level segment alone (e.g. `image`). Providers can use the helpers in\n   * `@ai-sdk/provider-utils` (`isFullMediaType`, `getTopLevelMediaType`,\n   * `detectMediaType`) to resolve the field according to their API\n   * requirements.\n   *\n   * @see https://www.iana.org/assignments/media-types/media-types.xhtml\n   */\n  mediaType: string;\n\n  /**\n   * Optional filename of the file.\n   */\n  filename?: string;\n\n  /**\n   * The URL of the file.\n   * It can either be a URL to a hosted file or a [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs).\n   */\n  url: string;\n\n  /**\n   * Provider reference for files uploaded via `uploadFile`.\n   * Maps provider names to provider-specific file identifiers.\n   * When present, takes precedence over `url` in model messages.\n   */\n  providerReference?: ProviderReference;\n\n  /**\n   * The provider metadata.\n   */\n  providerMetadata?: ProviderMetadata;\n};\n\n/**\n * A reasoning file part of a message.\n */\nexport type ReasoningFileUIPart = {\n  type: 'reasoning-file';\n\n  /**\n   * IANA media type of the file.\n   *\n   * @see https://www.iana.org/assignments/media-types/media-types.xhtml\n   */\n  mediaType: string;\n\n  /**\n   * The URL of the file.\n   * It can either be a URL to a hosted file or a [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs).\n   */\n  url: string;\n\n  /**\n   * The provider metadata.\n   */\n  providerMetadata?: ProviderMetadata;\n};\n\n/**\n * A step boundary part of a message.\n */\nexport type StepStartUIPart = {\n  type: 'step-start';\n};\n\nexport type DataUIPart<DATA_TYPES extends UIDataTypes> = ValueOf<{\n  [NAME in keyof DATA_TYPES & string]: {\n    type: `data-${NAME}`;\n    id?: string;\n    data: DATA_TYPES[NAME];\n  };\n}>;\n\ntype asUITool<TOOL extends UITool | Tool> = TOOL extends Tool\n  ? InferUITool<TOOL>\n  : TOOL;\n\n/**\n * Check if a message part is a data part.\n */\nexport function isDataUIPart<DATA_TYPES extends UIDataTypes>(\n  part: UIMessagePart<DATA_TYPES, UITools>,\n): part is DataUIPart<DATA_TYPES> {\n  return part.type.startsWith('data-');\n}\n\n/**\n * A UI tool invocation contains all the information needed to render a tool invocation in the UI.\n * It can be derived from a tool without knowing the tool name, and can be used to define\n * UI components for the tool.\n */\nexport type UIToolInvocation<TOOL extends UITool | Tool> = {\n  /**\n   * ID of the tool call.\n   */\n  toolCallId: string;\n  title?: string;\n  toolMetadata?: JSONObject;\n\n  /**\n   * Whether the tool call was executed by the provider.\n   */\n  providerExecuted?: boolean;\n} & (\n  | {\n      state: 'input-streaming';\n      input?: DeepPartial<asUITool<TOOL>['input']> | undefined;\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval?: never;\n    }\n  | {\n      state: 'input-available';\n      input: asUITool<TOOL>['input'];\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval?: never;\n    }\n  | {\n      state: 'approval-requested';\n      input: asUITool<TOOL>['input'];\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval: {\n        id: string;\n        approved?: never;\n        descriptor?: unknown;\n        requestReason?: string;\n        reason?: never;\n        isAutomatic?: boolean;\n        signature?: string;\n      };\n    }\n  | {\n      state: 'approval-responded';\n      input: asUITool<TOOL>['input'];\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval: {\n        id: string;\n        approved: boolean;\n        descriptor?: unknown;\n        requestReason?: string;\n        reason?: string;\n        isAutomatic?: boolean;\n        signature?: string;\n      };\n    }\n  | {\n      state: 'output-available';\n      input: asUITool<TOOL>['input'];\n      output: asUITool<TOOL>['output'];\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      resultProviderMetadata?: ProviderMetadata;\n      preliminary?: boolean;\n      approval?: {\n        id: string;\n        approved: true;\n        descriptor?: unknown;\n        requestReason?: string;\n        reason?: string;\n        isAutomatic?: boolean;\n        signature?: string;\n      };\n    }\n  | {\n      state: 'output-error';\n      input: asUITool<TOOL>['input'] | undefined;\n      /**\n       * @deprecated Use `input` instead. This field will be removed in the next\n       * major version.\n       */\n      rawInput?: unknown;\n      output?: never;\n      errorText: string;\n      callProviderMetadata?: ProviderMetadata;\n      resultProviderMetadata?: ProviderMetadata;\n      approval?: {\n        id: string;\n        approved: true;\n        descriptor?: unknown;\n        requestReason?: string;\n        reason?: string;\n        isAutomatic?: boolean;\n        signature?: string;\n      };\n    }\n  | {\n      state: 'output-denied';\n      input: asUITool<TOOL>['input'];\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval: {\n        id: string;\n        approved: false;\n        descriptor?: unknown;\n        requestReason?: string;\n        reason?: string;\n        isAutomatic?: boolean;\n        signature?: string;\n      };\n    }\n);\n\nexport type ToolUIPart<TOOLS extends UITools = UITools> = ValueOf<{\n  [NAME in keyof TOOLS & string]: {\n    type: `tool-${NAME}`;\n  } & UIToolInvocation<TOOLS[NAME]>;\n}>;\n\nexport type DynamicToolUIPart = {\n  type: 'dynamic-tool';\n\n  /**\n   * Name of the tool that is being called.\n   */\n  toolName: string;\n\n  /**\n   * ID of the tool call.\n   */\n  toolCallId: string;\n  title?: string;\n  toolMetadata?: JSONObject;\n\n  /**\n   * Whether the tool call was executed by the provider.\n   */\n  providerExecuted?: boolean;\n} & (\n  | {\n      state: 'input-streaming';\n      input?: unknown;\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval?: never;\n    }\n  | {\n      state: 'input-available';\n      input: unknown;\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval?: never;\n    }\n  | {\n      state: 'approval-requested';\n      input: unknown;\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval: {\n        id: string;\n        approved?: never;\n        descriptor?: unknown;\n        requestReason?: string;\n        reason?: never;\n        isAutomatic?: boolean;\n        signature?: string;\n      };\n    }\n  | {\n      state: 'approval-responded';\n      input: unknown;\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval: {\n        id: string;\n        approved: boolean;\n        descriptor?: unknown;\n        requestReason?: string;\n        reason?: string;\n        isAutomatic?: boolean;\n        signature?: string;\n      };\n    }\n  | {\n      state: 'output-available';\n      input: unknown;\n      output: unknown;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      resultProviderMetadata?: ProviderMetadata;\n      preliminary?: boolean;\n      approval?: {\n        id: string;\n        approved: true;\n        descriptor?: unknown;\n        requestReason?: string;\n        reason?: string;\n        isAutomatic?: boolean;\n        signature?: string;\n      };\n    }\n  | {\n      state: 'output-error';\n      input: unknown;\n      output?: never;\n      errorText: string;\n      callProviderMetadata?: ProviderMetadata;\n      resultProviderMetadata?: ProviderMetadata;\n      approval?: {\n        id: string;\n        approved: true;\n        descriptor?: unknown;\n        requestReason?: string;\n        reason?: string;\n        isAutomatic?: boolean;\n        signature?: string;\n      };\n    }\n  | {\n      state: 'output-denied';\n      input: unknown;\n      output?: never;\n      errorText?: never;\n      callProviderMetadata?: ProviderMetadata;\n      approval: {\n        id: string;\n        approved: false;\n        descriptor?: unknown;\n        requestReason?: string;\n        reason?: string;\n        isAutomatic?: boolean;\n        signature?: string;\n      };\n    }\n);\n\n/**\n * A static or dynamic tool UI part whose execution failed.\n *\n * Use `isToolOutputErrorUIPart` to identify tool output errors without\n * depending on the underlying tool state discriminator.\n */\nexport type ToolOutputErrorUIPart<TOOLS extends UITools = UITools> = Extract<\n  ToolUIPart<TOOLS> | DynamicToolUIPart,\n  { state: 'output-error' }\n>;\n\n/**\n * Type guard to check if a message part is a text part.\n */\nexport function isTextUIPart(\n  part: UIMessagePart<UIDataTypes, UITools>,\n): part is TextUIPart {\n  return part.type === 'text';\n}\n\n/**\n * Type guard to check if a message part is a custom part.\n */\nexport function isCustomContentUIPart(\n  part: UIMessagePart<UIDataTypes, UITools>,\n): part is CustomContentUIPart {\n  return part.type === 'custom';\n}\n\n/**\n * Type guard to check if a message part is a file part.\n */\nexport function isFileUIPart(\n  part: UIMessagePart<UIDataTypes, UITools>,\n): part is FileUIPart {\n  return part.type === 'file';\n}\n\n/**\n * Type guard to check if a message part is a reasoning file part.\n */\nexport function isReasoningFileUIPart(\n  part: UIMessagePart<UIDataTypes, UITools>,\n): part is ReasoningFileUIPart {\n  return part.type === 'reasoning-file';\n}\n\n/**\n * Type guard to check if a message part is a reasoning part.\n */\nexport function isReasoningUIPart(\n  part: UIMessagePart<UIDataTypes, UITools>,\n): part is ReasoningUIPart {\n  return part.type === 'reasoning';\n}\n\n/**\n * Check if a message part is a static tool part.\n *\n * Static tools are tools for which the types are known at development time.\n */\nexport function isStaticToolUIPart<TOOLS extends UITools>(\n  part: UIMessagePart<UIDataTypes, TOOLS>,\n): part is ToolUIPart<TOOLS> {\n  return part.type.startsWith('tool-');\n}\n\n/**\n * Check if a message part is a dynamic tool part.\n *\n * Dynamic tools are tools for which the input and output types are unknown.\n */\nexport function isDynamicToolUIPart(\n  part: UIMessagePart<UIDataTypes, UITools>,\n): part is DynamicToolUIPart {\n  return part.type === 'dynamic-tool';\n}\n\n/**\n * Check if a message part is a tool part.\n *\n * Tool parts are either static or dynamic tools.\n *\n * Use `isStaticToolUIPart` or `isDynamicToolUIPart` to check the type of the tool.\n */\nexport function isToolUIPart<TOOLS extends UITools>(\n  part: UIMessagePart<UIDataTypes, TOOLS>,\n): part is ToolUIPart<TOOLS> | DynamicToolUIPart {\n  return isStaticToolUIPart(part) || isDynamicToolUIPart(part);\n}\n\n/**\n * Check if a message part is a tool output error part.\n *\n * This works for both static and dynamic tools.\n */\nexport function isToolOutputErrorUIPart<TOOLS extends UITools>(\n  part: UIMessagePart<UIDataTypes, TOOLS>,\n): part is ToolOutputErrorUIPart<TOOLS> {\n  return isToolUIPart(part) && part.state === 'output-error';\n}\n\n/**\n * Returns the name of the static tool.\n *\n * The possible values are the keys of the tool set.\n */\nexport function getStaticToolName<TOOLS extends UITools>(\n  part: ToolUIPart<TOOLS>,\n): keyof TOOLS {\n  return part.type.split('-').slice(1).join('-') as keyof TOOLS;\n}\n\n/**\n * Returns the name of the tool (static or dynamic).\n *\n * This function will not restrict the name to the keys of the tool set.\n * If you need to restrict the name to the keys of the tool set, use `getStaticToolName` instead.\n */\nexport function getToolName(\n  part: ToolUIPart<UITools> | DynamicToolUIPart,\n): string {\n  return isDynamicToolUIPart(part) ? part.toolName : getStaticToolName(part);\n}\n\n/**\n * @deprecated Use getToolName instead.\n */\nexport const getToolOrDynamicToolName = getToolName;\n\nexport type InferUIMessageMetadata<T extends UIMessage> =\n  T extends UIMessage<infer METADATA> ? METADATA : unknown;\n\nexport type InferUIMessageData<T extends UIMessage> =\n  T extends UIMessage<unknown, infer DATA_TYPES> ? DATA_TYPES : UIDataTypes;\n\nexport type InferUIMessageTools<T extends UIMessage> =\n  T extends UIMessage<unknown, UIDataTypes, infer TOOLS> ? TOOLS : UITools;\n\nexport type InferUIMessageToolOutputs<UI_MESSAGE extends UIMessage> =\n  InferUIMessageTools<UI_MESSAGE>[keyof InferUIMessageTools<UI_MESSAGE>]['output'];\n\nexport type InferUIMessageToolCall<UI_MESSAGE extends UIMessage> =\n  | ValueOf<{\n      [NAME in keyof InferUIMessageTools<UI_MESSAGE>]: ToolCall<\n        NAME & string,\n        InferUIMessageTools<UI_MESSAGE>[NAME] extends { input: infer INPUT }\n          ? INPUT\n          : never\n      > & { dynamic?: false };\n    }>\n  | (ToolCall<string, unknown> & { dynamic: true });\n\nexport type InferUIMessagePart<UI_MESSAGE extends UIMessage> = UIMessagePart<\n  InferUIMessageData<UI_MESSAGE>,\n  InferUIMessageTools<UI_MESSAGE>\n>;\n","import { logWarnings } from '../logger/log-warnings';\n\nconst rawInputDeprecationWarning = {\n  type: 'deprecated',\n  setting: 'rawInput in output-error UI message parts',\n  message:\n    'Use the \"input\" field instead. The \"rawInput\" field will be removed in the next major version.',\n} as const;\n\nexport function warnIfUIMessageHasDeprecatedRawInput(\n  messages: ReadonlyArray<{\n    parts: ReadonlyArray<unknown>;\n  }>,\n): void {\n  const hasDeprecatedRawInput = messages.some(message =>\n    message.parts.some(\n      part =>\n        part != null &&\n        typeof part === 'object' &&\n        'type' in part &&\n        typeof part.type === 'string' &&\n        (part.type === 'dynamic-tool' || part.type.startsWith('tool-')) &&\n        'state' in part &&\n        part.state === 'output-error' &&\n        Object.prototype.hasOwnProperty.call(part, 'rawInput') &&\n        'rawInput' in part &&\n        part.rawInput !== undefined,\n    ),\n  );\n\n  if (hasDeprecatedRawInput) {\n    logWarnings({\n      warnings: [rawInputDeprecationWarning],\n    });\n  }\n}\n","import {\n  createStreamingUIMessageState,\n  processUIMessageStream,\n  type StreamingUIMessageState,\n  type UIMessageStreamWriteOptions,\n} from '../ui/process-ui-message-stream';\nimport type { UIMessage } from '../ui/ui-messages';\nimport type { ErrorHandler } from '../util/error-handler';\nimport type { InferUIMessageChunk, UIMessageChunk } from './ui-message-chunks';\nimport type { UIMessageStreamOnEndCallback } from './ui-message-stream-on-end-callback';\nimport type { UIMessageStreamOutcome } from './ui-message-stream-outcome';\nimport type { UIMessageStreamOnStepEndCallback } from './ui-message-stream-on-step-end-callback';\nimport type { UIMessageStreamOnStepFinishCallback } from './ui-message-stream-on-step-finish-callback';\n\nexport function handleUIMessageStreamFinish<UI_MESSAGE extends UIMessage>({\n  messageId,\n  originalMessages = [],\n  onStepEnd,\n  onStepFinish,\n  onEnd,\n  onFinish,\n  onError,\n  stream,\n  getOutcome,\n}: {\n  stream: ReadableStream<InferUIMessageChunk<UI_MESSAGE>>;\n\n  /**\n   * The message ID to use for the response message.\n   * If not provided, no id will be set for the response message.\n   */\n  messageId?: string;\n\n  /**\n   * The original messages.\n   */\n  originalMessages?: UI_MESSAGE[];\n\n  onError: ErrorHandler;\n\n  /**\n   * Callback that is called when each step ends during multi-step agent runs.\n   */\n  onStepEnd?: UIMessageStreamOnStepEndCallback<UI_MESSAGE>;\n\n  /**\n   * Callback that is called when each step ends during multi-step agent runs.\n   *\n   * @deprecated Use `onStepEnd` instead.\n   */\n  onStepFinish?: UIMessageStreamOnStepFinishCallback<UI_MESSAGE>;\n\n  onEnd?: UIMessageStreamOnEndCallback<UI_MESSAGE>;\n\n  /**\n   * @deprecated Use `onEnd` instead.\n   */\n  onFinish?: UIMessageStreamOnEndCallback<UI_MESSAGE>;\n\n  /**\n   * Returns the operation-level outcome declared by the stream owner.\n   */\n  getOutcome?: () => UIMessageStreamOutcome;\n}): ReadableStream<InferUIMessageChunk<UI_MESSAGE>> {\n  // last message is only relevant for assistant messages\n  let lastMessage: UI_MESSAGE | undefined =\n    originalMessages?.[originalMessages.length - 1];\n  if (lastMessage?.role !== 'assistant') {\n    lastMessage = undefined;\n  } else {\n    // appending to the last message, so we need to use the same id\n    messageId = lastMessage.id;\n  }\n\n  let isAborted = false;\n  let hasProcessingFailure = false;\n  let processingError: unknown;\n\n  const recordProcessingFailure = (error: unknown) => {\n    hasProcessingFailure = true;\n    processingError = error;\n  };\n\n  const idInjectedStream = stream.pipeThrough(\n    new TransformStream<\n      InferUIMessageChunk<UI_MESSAGE>,\n      InferUIMessageChunk<UI_MESSAGE>\n    >({\n      transform(chunk, controller) {\n        try {\n          let outputChunk = chunk;\n\n          // when there is no messageId in the start chunk,\n          // but the user checked for persistence,\n          // inject the messageId into the chunk\n          if (chunk.type === 'start') {\n            const startChunk = chunk as UIMessageChunk & { type: 'start' };\n            if (startChunk.messageId == null && messageId != null) {\n              outputChunk = {\n                ...startChunk,\n                messageId,\n              } as InferUIMessageChunk<UI_MESSAGE>;\n            }\n          }\n\n          if (chunk.type === 'abort') {\n            isAborted = true;\n          }\n\n          controller.enqueue(outputChunk);\n        } catch (error) {\n          recordProcessingFailure(error);\n          throw error;\n        }\n      },\n    }),\n  );\n\n  // Only process the stream if we need to track state for callbacks\n  const resolvedOnStepEnd = onStepEnd ?? onStepFinish;\n  const resolvedOnEnd = onEnd ?? onFinish;\n\n  if (resolvedOnEnd == null && resolvedOnStepEnd == null) {\n    return idInjectedStream;\n  }\n\n  const state = createStreamingUIMessageState<UI_MESSAGE>({\n    lastMessage: lastMessage\n      ? (structuredClone(lastMessage) as UI_MESSAGE)\n      : undefined,\n    messageId: messageId ?? '', // will be overridden by the stream\n  });\n\n  const runUpdateMessageJob = async (\n    job: (options: {\n      state: StreamingUIMessageState<UI_MESSAGE>;\n      write: (options?: UIMessageStreamWriteOptions) => void;\n    }) => Promise<void>,\n  ) => {\n    try {\n      await job({ state, write: () => {} });\n    } catch (error) {\n      recordProcessingFailure(error);\n      throw error;\n    }\n  };\n\n  let finishCalled = false;\n\n  const callOnEnd = async () => {\n    if (finishCalled || !resolvedOnEnd) {\n      return;\n    }\n    finishCalled = true;\n\n    const isContinuation = state.message.id === lastMessage?.id;\n    const declaredOutcome = getOutcome?.() ?? { status: 'unknown' };\n    const outcome: UIMessageStreamOutcome = hasProcessingFailure\n      ? { status: 'failed', error: processingError }\n      : declaredOutcome.status === 'unknown' && isAborted\n        ? { status: 'aborted' }\n        : declaredOutcome;\n\n    await resolvedOnEnd({\n      isAborted: isAborted || outcome.status === 'aborted',\n      isContinuation,\n      outcome,\n      responseMessage: state.message as UI_MESSAGE,\n      messages: [\n        ...(isContinuation ? originalMessages.slice(0, -1) : originalMessages),\n        state.message,\n      ] as UI_MESSAGE[],\n      finishReason: state.finishReason,\n    });\n  };\n\n  const callOnStepFinish = async () => {\n    if (!resolvedOnStepEnd) {\n      return;\n    }\n\n    const isContinuation = state.message.id === lastMessage?.id;\n\n    try {\n      await resolvedOnStepEnd({\n        isContinuation,\n        responseMessage: structuredClone(state.message) as UI_MESSAGE,\n        messages: [\n          ...(isContinuation\n            ? originalMessages.slice(0, -1)\n            : originalMessages),\n          structuredClone(state.message),\n        ] as UI_MESSAGE[],\n      });\n    } catch (error) {\n      onError(error);\n    }\n  };\n\n  return processUIMessageStream<UI_MESSAGE>({\n    stream: idInjectedStream,\n    runUpdateMessageJob,\n    onError,\n  }).pipeThrough(\n    new TransformStream<\n      InferUIMessageChunk<UI_MESSAGE>,\n      InferUIMessageChunk<UI_MESSAGE>\n    >({\n      async transform(chunk, controller) {\n        if (chunk.type === 'finish-step') {\n          await callOnStepFinish();\n        }\n\n        controller.enqueue(chunk);\n      },\n      // @ts-expect-error cancel is still new and missing from types https://developer.mozilla.org/en-US/docs/Web/API/TransformStream#browser_compatibility\n      async cancel() {\n        await callOnEnd();\n      },\n\n      async flush() {\n        await callOnEnd();\n      },\n    }),\n  );\n}\n","import type { ToolSet } from '@ai-sdk/provider-utils';\nimport type { TextStreamPart } from '../generate-text/stream-text-result';\nimport type {\n  InferUIMessageData,\n  InferUIMessageMetadata,\n  UIMessage,\n} from '../ui/ui-messages';\nimport type { InferUIMessageChunk, UIMessageChunk } from './ui-message-chunks';\n\nexport type ToUIMessageChunkOptions<\n  TOOLS extends ToolSet = ToolSet,\n  UI_MESSAGE extends UIMessage = UIMessage,\n> = {\n  tools?: TOOLS;\n  sendReasoning?: boolean;\n  sendSources?: boolean;\n  sendStart?: boolean;\n  sendFinish?: boolean;\n  onError?: (error: unknown) => string;\n  messageMetadata?: InferUIMessageMetadata<UI_MESSAGE>;\n  responseMessageId?: string;\n};\n\n/**\n * Converts a single `TextStreamPart` (as emitted by `streamText`'s\n * `stream`) into a `UIMessageChunk`.\n *\n * Returns `undefined` for stream parts that do not produce UI message chunks.\n */\nexport function toUIMessageChunk<\n  TOOLS extends ToolSet = ToolSet,\n  UI_MESSAGE extends UIMessage = UIMessage,\n>(\n  part: TextStreamPart<TOOLS>,\n  {\n    tools,\n    sendReasoning = true,\n    sendSources = false,\n    sendStart = true,\n    sendFinish = true,\n    onError = () => 'An error occurred.', // prevent leaking server error details to the client by default\n    messageMetadata,\n    responseMessageId,\n  }: ToUIMessageChunkOptions<TOOLS, UI_MESSAGE> = {},\n): InferUIMessageChunk<UI_MESSAGE> | undefined {\n  // TODO simplify once dynamic is no longer needed for invalid tool inputs\n  const isDynamic = (toolPart: { toolName: string; dynamic?: boolean }) => {\n    const tool = tools?.[toolPart.toolName];\n\n    // provider-executed, dynamic tools are not listed in the tools object\n    if (tool == null) {\n      return toolPart.dynamic;\n    }\n\n    return tool?.type === 'dynamic' ? true : undefined;\n  };\n\n  const partType = part.type;\n  switch (partType) {\n    case 'text-start': {\n      return {\n        type: 'text-start',\n        id: part.id,\n        ...(part.providerMetadata != null\n          ? { providerMetadata: part.providerMetadata }\n          : {}),\n      };\n    }\n\n    case 'text-delta': {\n      return {\n        type: 'text-delta',\n        id: part.id,\n        delta: part.text,\n        ...(part.providerMetadata != null\n          ? { providerMetadata: part.providerMetadata }\n          : {}),\n      };\n    }\n\n    case 'text-end': {\n      return {\n        type: 'text-end',\n        id: part.id,\n        ...(part.providerMetadata != null\n          ? { providerMetadata: part.providerMetadata }\n          : {}),\n      };\n    }\n\n    case 'reasoning-start':\n    case 'reasoning-end': {\n      if (!sendReasoning) {\n        return undefined;\n      }\n\n      return {\n        type: partType,\n        id: part.id,\n        ...(part.providerMetadata != null\n          ? { providerMetadata: part.providerMetadata }\n          : {}),\n      };\n    }\n\n    case 'reasoning-delta': {\n      if (!sendReasoning) {\n        return undefined;\n      }\n\n      return {\n        type: 'reasoning-delta',\n        id: part.id,\n        delta: part.text,\n        ...(part.providerMetadata != null\n          ? { providerMetadata: part.providerMetadata }\n          : {}),\n      };\n    }\n\n    case 'file':\n    case 'reasoning-file': {\n      if (partType === 'reasoning-file' && !sendReasoning) {\n        return undefined;\n      }\n\n      return {\n        type: part.type,\n        mediaType: part.file.mediaType,\n        url: `data:${part.file.mediaType};base64,${part.file.base64}`,\n        ...(part.providerMetadata != null\n          ? { providerMetadata: part.providerMetadata }\n          : {}),\n      };\n    }\n\n    case 'source': {\n      if (!sendSources) {\n        return undefined;\n      }\n\n      if (part.sourceType === 'url') {\n        return {\n          type: 'source-url',\n          sourceId: part.id,\n          url: part.url,\n          title: part.title,\n          ...(part.providerMetadata != null\n            ? { providerMetadata: part.providerMetadata }\n            : {}),\n        };\n      }\n\n      if (part.sourceType === 'document') {\n        return {\n          type: 'source-document',\n          sourceId: part.id,\n          mediaType: part.mediaType,\n          title: part.title,\n          filename: part.filename,\n          ...(part.providerMetadata != null\n            ? { providerMetadata: part.providerMetadata }\n            : {}),\n        };\n      }\n\n      return undefined;\n    }\n\n    case 'custom': {\n      return {\n        type: 'custom',\n        kind: part.kind,\n        ...(part.providerMetadata != null\n          ? { providerMetadata: part.providerMetadata }\n          : {}),\n      };\n    }\n\n    case 'tool-input-start': {\n      const dynamic = isDynamic(part);\n\n      return {\n        type: 'tool-input-start',\n        toolCallId: part.id,\n        toolName: part.toolName,\n        ...(part.providerExecuted != null\n          ? { providerExecuted: part.providerExecuted }\n          : {}),\n        ...(part.providerMetadata != null\n          ? { providerMetadata: part.providerMetadata }\n          : {}),\n        ...(part.toolMetadata != null\n          ? { toolMetadata: part.toolMetadata }\n          : {}),\n        ...(dynamic != null ? { dynamic } : {}),\n        ...(part.title != null ? { title: part.title } : {}),\n      };\n    }\n\n    case 'tool-input-delta': {\n      return {\n        type: 'tool-input-delta',\n        toolCallId: part.id,\n        inputTextDelta: part.delta,\n      };\n    }\n\n    case 'tool-call': {\n      const dynamic = isDynamic(part);\n\n      if (part.invalid) {\n        return {\n          type: 'tool-input-error',\n          toolCallId: part.toolCallId,\n          toolName: part.toolName,\n          input: part.input,\n          ...(part.providerExecuted != null\n            ? { providerExecuted: part.providerExecuted }\n            : {}),\n          ...(part.providerMetadata != null\n            ? { providerMetadata: part.providerMetadata }\n            : {}),\n          ...(part.toolMetadata != null\n            ? { toolMetadata: part.toolMetadata }\n            : {}),\n          ...(dynamic != null ? { dynamic } : {}),\n          errorText: onError(part.error),\n          ...(part.title != null ? { title: part.title } : {}),\n        };\n      }\n\n      return {\n        type: 'tool-input-available',\n        toolCallId: part.toolCallId,\n        toolName: part.toolName,\n        input: part.input,\n        ...(part.providerExecuted != null\n          ? { providerExecuted: part.providerExecuted }\n          : {}),\n        ...(part.providerMetadata != null\n          ? { providerMetadata: part.providerMetadata }\n          : {}),\n        ...(part.toolMetadata != null\n          ? { toolMetadata: part.toolMetadata }\n          : {}),\n        ...(dynamic != null ? { dynamic } : {}),\n        ...(part.title != null ? { title: part.title } : {}),\n      };\n    }\n\n    case 'tool-approval-request': {\n      return {\n        type: 'tool-approval-request',\n        approvalId: part.approvalId,\n        toolCallId: part.toolCall.toolCallId,\n        ...(part.reason != null ? { reason: part.reason } : {}),\n        ...(part.isAutomatic != null ? { isAutomatic: part.isAutomatic } : {}),\n        ...(part.signature != null ? { signature: part.signature } : {}),\n      };\n    }\n\n    case 'tool-approval-response': {\n      return {\n        type: 'tool-approval-response',\n        approvalId: part.approvalId,\n        approved: part.approved,\n        ...(part.reason != null ? { reason: part.reason } : {}),\n        ...(part.providerExecuted != null\n          ? { providerExecuted: part.providerExecuted }\n          : {}),\n      };\n    }\n\n    case 'tool-result': {\n      const dynamic = isDynamic(part);\n\n      return {\n        type: 'tool-output-available',\n        toolCallId: part.toolCallId,\n        // UI stream chunks are serialized as JSON, which drops undefined\n        // properties. Use null so tool outputs always keep the output field.\n        output: part.output === undefined ? null : part.output,\n        ...(part.providerExecuted != null\n          ? { providerExecuted: part.providerExecuted }\n          : {}),\n        ...(part.providerMetadata != null\n          ? { providerMetadata: part.providerMetadata }\n          : {}),\n        ...(part.toolMetadata != null\n          ? { toolMetadata: part.toolMetadata }\n          : {}),\n        ...(part.preliminary != null ? { preliminary: part.preliminary } : {}),\n        ...(dynamic != null ? { dynamic } : {}),\n      };\n    }\n\n    case 'tool-error': {\n      const dynamic = isDynamic(part);\n\n      return {\n        type: 'tool-output-error',\n        toolCallId: part.toolCallId,\n        errorText: part.providerExecuted\n          ? typeof part.error === 'string'\n            ? part.error\n            : JSON.stringify(part.error)\n          : onError(part.error),\n        ...(part.providerExecuted != null\n          ? { providerExecuted: part.providerExecuted }\n          : {}),\n        ...(part.providerMetadata != null\n          ? { providerMetadata: part.providerMetadata }\n          : {}),\n        ...(part.toolMetadata != null\n          ? { toolMetadata: part.toolMetadata }\n          : {}),\n        ...(dynamic != null ? { dynamic } : {}),\n      };\n    }\n\n    case 'tool-output-denied': {\n      return {\n        type: 'tool-output-denied',\n        toolCallId: part.toolCallId,\n      };\n    }\n\n    case 'error': {\n      return {\n        type: 'error',\n        errorText: onError(part.error),\n      };\n    }\n\n    case 'start-step': {\n      return { type: 'start-step' };\n    }\n\n    case 'finish-step': {\n      return { type: 'finish-step' };\n    }\n\n    case 'start': {\n      if (!sendStart) {\n        return undefined;\n      }\n\n      return {\n        type: 'start',\n        ...(messageMetadata != null ? { messageMetadata } : {}),\n        ...(responseMessageId != null ? { messageId: responseMessageId } : {}),\n      } as UIMessageChunk<\n        InferUIMessageMetadata<UI_MESSAGE>,\n        InferUIMessageData<UI_MESSAGE>\n      >;\n    }\n\n    case 'finish': {\n      if (!sendFinish) {\n        return undefined;\n      }\n\n      return {\n        type: 'finish',\n        finishReason: part.finishReason,\n        ...(messageMetadata != null ? { messageMetadata } : {}),\n      } as UIMessageChunk<\n        InferUIMessageMetadata<UI_MESSAGE>,\n        InferUIMessageData<UI_MESSAGE>\n      >;\n    }\n\n    case 'abort': {\n      return part;\n    }\n\n    case 'tool-input-end':\n    case 'raw': {\n      return undefined;\n    }\n\n    default: {\n      const exhaustiveCheck: never = partType;\n      throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);\n    }\n  }\n}\n","import type { ToolSet } from '@ai-sdk/provider-utils';\nimport type {\n  TextStreamPart,\n  UIMessageStreamOptions,\n} from '../generate-text/stream-text-result';\nimport type { UIMessage } from '../ui/ui-messages';\nimport { getResponseUIMessageId } from './get-response-ui-message-id';\nimport { handleUIMessageStreamFinish } from './handle-ui-message-stream-finish';\nimport type { InferUIMessageChunk } from './ui-message-chunks';\nimport type { UIMessageStreamOutcome } from './ui-message-stream-outcome';\nimport { toUIMessageChunk } from './to-ui-message-chunk';\n\n/**\n * Converts a stream of `TextStreamPart<TOOLS>` chunks (as emitted by\n * `streamText`'s `stream`) into a stream of `UIMessageChunk`s suitable for\n * UI message streaming, including response message ID injection and\n * `onEnd` handling.\n */\nexport function toUIMessageStream<\n  TOOLS extends ToolSet = ToolSet,\n  UI_MESSAGE extends UIMessage = UIMessage,\n>({\n  stream,\n  tools,\n  sendReasoning = true,\n  sendSources = false,\n  sendStart = true,\n  sendFinish = true,\n  onError = () => 'An error occurred.', // prevent leaking server error details to the client by default\n  messageMetadata,\n  originalMessages,\n  generateMessageId,\n  onEnd,\n  onFinish,\n}: {\n  stream: ReadableStream<TextStreamPart<TOOLS>>;\n  tools?: TOOLS;\n} & UIMessageStreamOptions<UI_MESSAGE>): ReadableStream<\n  InferUIMessageChunk<UI_MESSAGE>\n> {\n  let outcome: UIMessageStreamOutcome = { status: 'unknown' };\n  let hasFatalFailure = false;\n\n  const setSourceOutcome = (newOutcome: UIMessageStreamOutcome) => {\n    if (\n      !hasFatalFailure &&\n      outcome.status !== 'completed' &&\n      outcome.status !== 'aborted' &&\n      newOutcome.status !== 'unknown' &&\n      (outcome.status === 'unknown' || newOutcome.status !== 'failed')\n    ) {\n      outcome = newOutcome;\n    }\n  };\n\n  const failOutcome = (error: unknown) => {\n    hasFatalFailure = true;\n    outcome = { status: 'failed', error };\n  };\n\n  const responseMessageId =\n    generateMessageId != null\n      ? getResponseUIMessageId({\n          originalMessages,\n          responseMessageId: generateMessageId,\n        })\n      : undefined;\n\n  const sourceReader = stream.getReader();\n  let sourceReaderReleased = false;\n  let sourceStreamCancelled = false;\n\n  const releaseSourceReader = () => {\n    if (!sourceReaderReleased) {\n      sourceReader.releaseLock();\n      sourceReaderReleased = true;\n    }\n  };\n\n  const sourceStream = new ReadableStream<TextStreamPart<TOOLS>>({\n    async pull(controller) {\n      try {\n        const { done, value } = await sourceReader.read();\n\n        if (done) {\n          releaseSourceReader();\n          if (!sourceStreamCancelled) {\n            controller.close();\n          }\n        } else {\n          controller.enqueue(value);\n        }\n      } catch (error) {\n        releaseSourceReader();\n        if (!sourceStreamCancelled) {\n          failOutcome(error);\n          controller.error(error);\n        }\n      }\n    },\n\n    async cancel(reason) {\n      sourceStreamCancelled = true;\n      if (sourceReaderReleased) {\n        return;\n      }\n\n      try {\n        await sourceReader.cancel(reason);\n      } finally {\n        releaseSourceReader();\n      }\n    },\n  });\n\n  const uiMessageChunkStream = sourceStream.pipeThrough(\n    new TransformStream({\n      transform: async (part, controller) => {\n        try {\n          const messageMetadataValue = messageMetadata?.({ part });\n\n          const uiMessageChunk = toUIMessageChunk(part, {\n            tools,\n            sendReasoning,\n            sendSources,\n            sendStart,\n            sendFinish,\n            onError,\n            messageMetadata: messageMetadataValue,\n            responseMessageId,\n          });\n\n          if (uiMessageChunk != null) {\n            controller.enqueue(uiMessageChunk);\n          }\n\n          // start and finish events already include metadata in the converted\n          // chunk; for other part types emit a separate message-metadata chunk\n          if (\n            messageMetadataValue != null &&\n            part.type !== 'start' &&\n            part.type !== 'finish'\n          ) {\n            controller.enqueue({\n              type: 'message-metadata',\n              messageMetadata: messageMetadataValue,\n            });\n          }\n\n          if (part.type === 'finish') {\n            setSourceOutcome({ status: 'completed' });\n          } else if (part.type === 'abort') {\n            setSourceOutcome({ status: 'aborted' });\n          } else if (part.type === 'error') {\n            setSourceOutcome({ status: 'failed', error: part.error });\n          }\n        } catch (error) {\n          failOutcome(error);\n          throw error;\n        }\n      },\n    }),\n  );\n\n  return handleUIMessageStreamFinish({\n    stream: uiMessageChunkStream,\n    messageId: responseMessageId ?? generateMessageId?.(),\n    originalMessages,\n    onEnd: onEnd ?? onFinish,\n    onError,\n    getOutcome: () => outcome,\n  });\n}\n","/**\n * A type that combines AsyncIterable and ReadableStream.\n * This allows a ReadableStream to be consumed using for-await-of syntax.\n */\nexport type AsyncIterableStream<T> = AsyncIterable<T> & ReadableStream<T>;\n\n/**\n * Wraps a ReadableStream and returns an object that is both a ReadableStream and an AsyncIterable.\n * This enables consumption of the stream using for-await-of, with proper resource cleanup on early exit or error.\n *\n * @template T The type of the stream's chunks.\n * @param source The source ReadableStream to wrap.\n * @returns An AsyncIterableStream that can be used as both a ReadableStream and an AsyncIterable.\n */\nexport function createAsyncIterableStream<T>(\n  source: ReadableStream<T>,\n): AsyncIterableStream<T> {\n  // Pipe through a TransformStream to ensure a fresh, unlocked stream.\n  return asAsyncIterableStream(source.pipeThrough(new TransformStream<T, T>()));\n}\n\n/**\n * Attaches the async iterator protocol to an existing ReadableStream in place,\n * turning it into an AsyncIterableStream without piping through an additional\n * TransformStream.\n *\n * Use this when the stream is already known to be fresh and exclusively owned\n * (e.g. the readable side of a TransformStream created for this consumer).\n * Adding an extra `pipeThrough` in that situation creates a chain of two\n * transforms fed by an active upstream pipe, which can surface a spurious\n * unhandled `undefined` rejection when the consumer cancels early (observed on\n * Node.js 26). {@link createAsyncIterableStream} wraps this after adding a\n * fresh transform for callers that may pass shared or locked streams.\n *\n * @template T The type of the stream's chunks.\n * @param stream The ReadableStream to augment. It must be fresh and unlocked.\n * @returns The same stream, augmented with the async iterator protocol.\n */\nexport function asAsyncIterableStream<T>(\n  stream: ReadableStream<T>,\n): AsyncIterableStream<T> {\n  /**\n   * Implements the async iterator protocol for the stream.\n   * Ensures proper cleanup (cancelling and releasing the reader) on completion, early exit, or error.\n   */\n  (stream as unknown as AsyncIterable<T>)[Symbol.asyncIterator] = function (\n    this: ReadableStream<T>,\n  ): AsyncIterator<T> {\n    const reader = this.getReader();\n\n    let finished = false;\n\n    /**\n     * Cleans up the reader by cancelling and releasing the lock.\n     */\n    async function cleanup(cancelStream: boolean) {\n      if (finished) return;\n\n      finished = true;\n      try {\n        if (cancelStream) {\n          await reader.cancel?.();\n        }\n      } finally {\n        try {\n          reader.releaseLock();\n        } catch {}\n      }\n    }\n\n    return {\n      /**\n       * Reads the next chunk from the stream.\n       * @returns A promise resolving to the next IteratorResult.\n       */\n      async next(): Promise<IteratorResult<T>> {\n        if (finished) {\n          return { done: true, value: undefined };\n        }\n\n        let result: ReadableStreamReadResult<T>;\n        try {\n          result = await reader.read();\n        } catch (error) {\n          await cleanup(false);\n          throw error;\n        }\n\n        const { done, value } = result;\n\n        if (done) {\n          await cleanup(true);\n          return { done: true, value: undefined };\n        }\n\n        return { done: false, value };\n      },\n\n      /**\n       * May be called on early exit (e.g., break from for-await) or after completion.\n       * Ensures the stream is cancelled and resources are released.\n       * @returns A promise resolving to a completed IteratorResult.\n       */\n      async return(): Promise<IteratorResult<T>> {\n        await cleanup(true);\n        return { done: true, value: undefined };\n      },\n\n      /**\n       * Called on early exit with error.\n       * Ensures the stream is cancelled and resources are released, then rethrows the error.\n       * @param err The error to throw.\n       * @returns A promise that rejects with the provided error.\n       */\n      async throw(err: unknown): Promise<IteratorResult<T>> {\n        await cleanup(true);\n        throw err;\n      },\n    };\n  };\n\n  return stream as AsyncIterableStream<T>;\n}\n","/**\n * Consumes a ReadableStream until it's fully read.\n *\n * This function reads the stream chunk by chunk until the stream is exhausted.\n * It doesn't process or return the data from the stream; it simply ensures\n * that the entire stream is read.\n *\n * @param options - The options for consuming the stream.\n * @param options.stream - The ReadableStream to be consumed.\n * @param options.onError - Optional callback to handle errors that occur during consumption.\n * @returns A promise that resolves when the stream is fully consumed.\n */\nexport async function consumeStream({\n  stream,\n  onError,\n  abortSignal,\n}: {\n  stream: ReadableStream;\n  onError?: (error: unknown) => void;\n  abortSignal?: AbortSignal;\n}): Promise<void> {\n  const reader = stream.getReader();\n  const cancelOnAbort = () => {\n    reader.cancel().catch(() => {});\n  };\n\n  if (abortSignal?.aborted) {\n    cancelOnAbort();\n  } else {\n    abortSignal?.addEventListener('abort', cancelOnAbort, { once: true });\n  }\n\n  try {\n    while (true) {\n      const { done } = await reader.read();\n      if (done) break;\n    }\n  } catch (error) {\n    onError?.(error);\n  } finally {\n    abortSignal?.removeEventListener('abort', cancelOnAbort);\n    reader.releaseLock();\n  }\n}\n","import type { ErrorHandler } from './error-handler';\n\n/**\n * Creates a Promise with externally accessible resolve and reject functions.\n *\n * @template T - The type of the value that the Promise will resolve to.\n * @returns An object containing:\n *   - promise: A Promise that can be resolved or rejected externally.\n *   - resolve: A function to resolve the Promise with a value of type T.\n *   - reject: A function to reject the Promise with an error.\n */\nexport function createResolvablePromise<T = any>(): {\n  promise: Promise<T>;\n  resolve: (value: T) => void;\n  reject: ErrorHandler;\n} {\n  let resolve: (value: T) => void;\n  let reject: ErrorHandler;\n\n  const promise = new Promise<T>((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n\n  return {\n    promise,\n    resolve: resolve!,\n    reject: reject!,\n  };\n}\n","import { createResolvablePromise } from './create-resolvable-promise';\n\n/**\n * Creates a stitchable stream that can pipe one stream at a time.\n *\n * @template T - The type of values emitted by the streams.\n * @returns {Object} An object containing the stitchable stream and control methods.\n */\nexport function createStitchableStream<T>(): {\n  stream: ReadableStream<T>;\n  addStream: (\n    innerStream: ReadableStream<T>,\n    callbacks?: {\n      onError?: (error: unknown) => void;\n      onCancel?: () => void;\n    },\n  ) => void;\n  close: () => void;\n  terminate: () => void;\n} {\n  let innerStreams: Array<{\n    reader: ReadableStreamDefaultReader<T>;\n    onError?: (error: unknown) => void;\n    onCancel?: () => void;\n  }> = [];\n  let controller: ReadableStreamDefaultController<T> | null = null;\n  let isClosed = false;\n  let isCancelled = false;\n  let waitForNewStream = createResolvablePromise<void>();\n\n  const terminate = () => {\n    if (isCancelled) {\n      return;\n    }\n\n    isClosed = true;\n    waitForNewStream.resolve();\n\n    innerStreams.forEach(({ reader, onCancel }) => {\n      onCancel?.();\n      reader.cancel();\n    });\n    innerStreams = [];\n    controller?.close();\n  };\n\n  const processPull = async () => {\n    if (isCancelled) {\n      return;\n    }\n\n    // Case 1: Outer stream is closed and no more inner streams\n    if (isClosed && innerStreams.length === 0) {\n      controller?.close();\n      return;\n    }\n\n    // Case 2: No inner streams available, but outer stream is open\n    // wait for a new inner stream to be added or the outer stream to close\n    if (innerStreams.length === 0) {\n      waitForNewStream = createResolvablePromise<void>();\n      await waitForNewStream.promise;\n      return await processPull();\n    }\n\n    const currentStream = innerStreams[0];\n\n    try {\n      const { value, done } = await currentStream.reader.read();\n\n      if (isCancelled) {\n        return;\n      }\n\n      if (done) {\n        // Case 3: Current inner stream is done\n        innerStreams.shift(); // Remove the finished stream\n\n        if (innerStreams.length === 0 && isClosed) {\n          // when closed and no more inner streams, stop pulling\n          controller?.close();\n        } else {\n          // continue pulling from the next stream\n          await processPull();\n        }\n      } else {\n        // Case 4: Current inner stream returns an item\n        controller?.enqueue(value);\n      }\n    } catch (error) {\n      if (isCancelled) {\n        return;\n      }\n\n      // Case 5: Current inner stream throws an error\n      currentStream.onError?.(error);\n      controller?.error(error);\n      innerStreams.shift(); // Remove the errored stream\n      terminate(); // we have errored, terminate all streams\n    }\n  };\n\n  return {\n    stream: new ReadableStream<T>({\n      start(controllerParam) {\n        controller = controllerParam;\n      },\n      pull: processPull,\n      async cancel() {\n        isCancelled = true;\n        isClosed = true;\n        waitForNewStream.resolve();\n\n        for (const { reader, onCancel } of innerStreams) {\n          onCancel?.();\n          await reader.cancel();\n        }\n        innerStreams = [];\n      },\n    }),\n    addStream: (\n      innerStream: ReadableStream<T>,\n      callbacks?: {\n        onError?: (error: unknown) => void;\n        onCancel?: () => void;\n      },\n    ) => {\n      if (isCancelled) {\n        callbacks?.onCancel?.();\n        void innerStream.cancel().catch(() => {});\n        return;\n      }\n\n      if (isClosed) {\n        throw new Error('Cannot add inner stream: outer stream is closed');\n      }\n\n      innerStreams.push({\n        reader: innerStream.getReader(),\n        ...callbacks,\n      });\n      waitForNewStream.resolve();\n    },\n\n    /**\n     * Gracefully close the outer stream. This will let the inner streams\n     * finish processing and then close the outer stream.\n     */\n    close: () => {\n      if (isCancelled) {\n        return;\n      }\n\n      isClosed = true;\n      waitForNewStream.resolve();\n\n      if (innerStreams.length === 0) {\n        controller?.close();\n      }\n    },\n\n    /**\n     * Immediately close the outer stream. This will cancel all inner streams\n     * and close the outer stream.\n     */\n    terminate,\n  };\n}\n","import type { SharedV4Warning } from '@ai-sdk/provider';\n\nconst streamRetryAttemptBoundarySymbol = Symbol('streamRetryAttemptBoundary');\n\nexport type StreamRetryAttemptBoundaryPart = {\n  [streamRetryAttemptBoundarySymbol]: true;\n  warnings: Array<SharedV4Warning>;\n};\n\nexport function createStreamRetryAttemptBoundaryPart({\n  warnings,\n}: {\n  warnings: Array<SharedV4Warning>;\n}): StreamRetryAttemptBoundaryPart {\n  return {\n    [streamRetryAttemptBoundarySymbol]: true,\n    warnings,\n  };\n}\n\nexport function isStreamRetryAttemptBoundaryPart(\n  part: unknown,\n): part is StreamRetryAttemptBoundaryPart {\n  return (\n    typeof part === 'object' &&\n    part != null &&\n    streamRetryAttemptBoundarySymbol in part\n  );\n}\n","import type {\n  Arrayable,\n  Context,\n  IdGenerator,\n  InferToolSetContext,\n  ModelMessage,\n  Experimental_SandboxSession as SandboxSession,\n  ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type { TimeoutConfiguration } from '../prompt/request-options';\nimport type { Telemetry, TelemetryDispatcher } from '../telemetry/telemetry';\nimport { getOwn } from '../util/get-own';\nimport { executeToolCall } from './execute-tool-call';\nimport { isToolExecutionAllowedFinishReason } from './is-tool-execution-allowed-finish-reason';\nimport { resolveToolApproval } from './resolve-tool-approval';\nimport type { LanguageModelStreamPart } from './stream-language-model-call';\nimport {\n  isStreamRetryAttemptBoundaryPart,\n  type StreamRetryAttemptBoundaryPart,\n} from './stream-retry-attempt-boundary';\nimport { maybeSignApproval } from './tool-approval-signature';\nimport type { ToolApprovalConfiguration } from './tool-approval-configuration';\nimport type { TypedToolCall } from './tool-call';\nimport type {\n  OnToolExecutionEndCallback,\n  OnToolExecutionStartCallback,\n} from './tool-execution-events';\nimport type { StaticToolOutputDenied } from './tool-output-denied';\n\nexport type ToolExecutionEndStreamPart = {\n  type: 'tool-execution-end';\n  toolCallId: string;\n  toolExecutionMs: number;\n};\n\nexport type ExecuteToolsStreamPart<TOOLS extends ToolSet = ToolSet> =\n  | LanguageModelStreamPart<TOOLS>\n  | StaticToolOutputDenied<TOOLS>\n  | ToolExecutionEndStreamPart\n  | StreamRetryAttemptBoundaryPart;\n\ntype ExecuteToolsInputStreamPart<TOOLS extends ToolSet> =\n  | LanguageModelStreamPart<TOOLS>\n  | StreamRetryAttemptBoundaryPart;\n\nexport function executeToolsFromStream<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context | unknown | never,\n>({\n  stream,\n  tools,\n  callId,\n  messages,\n  abortSignal,\n  timeout,\n  experimental_sandbox: sandbox,\n  toolsContext,\n  toolApproval,\n  runtimeContext,\n  toolApprovalSecret,\n  generateId,\n  onToolExecutionStart,\n  onToolExecutionEnd,\n  executeToolInTelemetryContext,\n  runInTracingChannelSpan,\n}: {\n  stream: ReadableStream<ExecuteToolsInputStreamPart<TOOLS>>;\n  tools: TOOLS | undefined;\n  callId: string;\n  messages: ModelMessage[];\n  abortSignal: AbortSignal | undefined;\n  timeout?: TimeoutConfiguration<TOOLS>;\n  experimental_sandbox?: SandboxSession;\n  toolsContext: InferToolSetContext<TOOLS>;\n  toolApproval?: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT>;\n  runtimeContext: RUNTIME_CONTEXT;\n  toolApprovalSecret?: string | Uint8Array;\n  generateId: IdGenerator;\n  onToolExecutionStart?: Arrayable<OnToolExecutionStartCallback<TOOLS>>;\n  onToolExecutionEnd?: Arrayable<OnToolExecutionEndCallback<TOOLS>>;\n  executeToolInTelemetryContext?: Telemetry['executeTool'];\n  runInTracingChannelSpan?: NonNullable<\n    TelemetryDispatcher['runInTracingChannelSpan']\n  >;\n}): ReadableStream<ExecuteToolsStreamPart<TOOLS>> {\n  const toolCallsToExecute: Array<TypedToolCall<TOOLS>> = [];\n\n  // forward stream\n  return stream.pipeThrough(\n    new TransformStream<\n      ExecuteToolsInputStreamPart<TOOLS>,\n      ExecuteToolsStreamPart<TOOLS>\n    >({\n      async transform(\n        chunk: ExecuteToolsInputStreamPart<TOOLS>,\n        controller: TransformStreamDefaultController<\n          ExecuteToolsStreamPart<TOOLS>\n        >,\n      ) {\n        // immediately forward all chunks\n        controller.enqueue(chunk);\n\n        if (isStreamRetryAttemptBoundaryPart(chunk)) {\n          toolCallsToExecute.length = 0;\n          return;\n        }\n\n        const chunkType = chunk.type;\n\n        switch (chunkType) {\n          case 'tool-call': {\n            if (chunk.invalid) {\n              return;\n            }\n\n            const tool = getOwn(tools, chunk.toolName);\n\n            if (tool == null) {\n              // ignore tool calls for tools that are not available,\n              // e.g. provider-executed dynamic tools\n              return;\n            }\n\n            const toolApprovalStatus = await resolveToolApproval({\n              tools,\n              toolCall: chunk,\n              toolApproval,\n              messages,\n              toolsContext,\n              runtimeContext,\n            });\n\n            // Tools that don't require approval ('not-applicable') must not\n            // consume an approval id, so that id generation stays stable for\n            // callers that rely on deterministic id sequences. They execute\n            // directly (when not provider-executed).\n            if (toolApprovalStatus.type === 'not-applicable') {\n              if (tool.execute != null && chunk.providerExecuted !== true) {\n                toolCallsToExecute.push(chunk);\n              }\n\n              return;\n            }\n\n            const approvalId = generateId();\n            const signature = await maybeSignApproval({\n              secret: toolApprovalSecret,\n              approvalId,\n              toolCallId: chunk.toolCallId,\n              toolName: chunk.toolName,\n              input: chunk.input,\n            });\n\n            switch (toolApprovalStatus.type) {\n              case 'user-approval': {\n                controller.enqueue({\n                  type: 'tool-approval-request',\n                  approvalId,\n                  toolCall: chunk,\n                  ...(toolApprovalStatus.reason != null\n                    ? { reason: toolApprovalStatus.reason }\n                    : {}),\n                  ...(signature != null ? { signature } : {}),\n                });\n\n                return; // don't execute tool\n              }\n\n              case 'denied': {\n                controller.enqueue({\n                  type: 'tool-approval-request',\n                  approvalId,\n                  toolCall: chunk,\n                  isAutomatic: true,\n                  ...(signature != null ? { signature } : {}),\n                });\n                controller.enqueue({\n                  type: 'tool-approval-response',\n                  approvalId,\n                  approved: false,\n                  toolCall: chunk,\n                  reason: toolApprovalStatus.reason,\n                  providerExecuted: chunk.providerExecuted,\n                });\n                controller.enqueue({\n                  type: 'tool-output-denied',\n                  toolCallId: chunk.toolCallId,\n                  toolName: chunk.toolName,\n                } as StaticToolOutputDenied<TOOLS>);\n\n                return; // don't execute tool\n              }\n\n              case 'approved': {\n                controller.enqueue({\n                  type: 'tool-approval-request',\n                  approvalId,\n                  toolCall: chunk,\n                  isAutomatic: true,\n                  ...(signature != null ? { signature } : {}),\n                });\n                controller.enqueue({\n                  type: 'tool-approval-response',\n                  approvalId,\n                  approved: true,\n                  toolCall: chunk,\n                  reason: toolApprovalStatus.reason,\n                  providerExecuted: chunk.providerExecuted,\n                });\n\n                break; // continue with tool execution\n              }\n            }\n\n            // approved tool calls continue to execution (when not\n            // provider-executed):\n            if (tool.execute != null && chunk.providerExecuted !== true) {\n              toolCallsToExecute.push(chunk);\n            }\n\n            return;\n          }\n\n          case 'model-call-end': {\n            if (!isToolExecutionAllowedFinishReason(chunk.finishReason)) {\n              return;\n            }\n\n            await Promise.all(\n              toolCallsToExecute.map(async toolCall => {\n                try {\n                  // Note: we don't await the tool execution here (by leaving out 'await' on recordSpan),\n                  // because we want to process the next chunk as soon as possible.\n                  // This is important for the case where the tool execution takes a long time.\n                  const result = await executeToolCall({\n                    toolCall,\n                    tools,\n                    callId,\n                    messages,\n                    abortSignal,\n                    timeout,\n                    experimental_sandbox: sandbox,\n                    toolsContext,\n                    onToolExecutionStart,\n                    onToolExecutionEnd,\n                    executeToolInTelemetryContext,\n                    runInTracingChannelSpan,\n                    onPreliminaryToolResult: result => {\n                      controller.enqueue(result);\n                    },\n                  });\n                  if (result != null) {\n                    controller.enqueue({\n                      type: 'tool-execution-end',\n                      toolCallId: result.output.toolCallId,\n                      toolExecutionMs: result.toolExecutionMs,\n                    });\n                    controller.enqueue(result.output);\n                  }\n                } catch (error) {\n                  controller.enqueue({\n                    type: 'error',\n                    error,\n                  });\n                }\n              }),\n            );\n\n            return;\n          }\n        }\n      },\n    }),\n  );\n}\n","import type { Context, ModelMessage, ToolSet } from '@ai-sdk/provider-utils';\nimport { createIdMap } from '../util/create-id-map';\nimport { getOwn } from '../util/get-own';\nimport type { LanguageModelStreamPart } from './stream-language-model-call';\nimport {\n  isStreamRetryAttemptBoundaryPart,\n  type StreamRetryAttemptBoundaryPart,\n} from './stream-retry-attempt-boundary';\n\ntype ToolCallbackStreamPart<TOOLS extends ToolSet> =\n  | LanguageModelStreamPart<TOOLS>\n  | StreamRetryAttemptBoundaryPart;\n\nexport function invokeToolCallbacksFromStream<\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context,\n>({\n  stream,\n  tools,\n  stepInputMessages,\n  abortSignal,\n  runtimeContext,\n}: {\n  stream: ReadableStream<ToolCallbackStreamPart<TOOLS>>;\n  tools: TOOLS | undefined;\n  stepInputMessages: Array<ModelMessage>;\n  abortSignal: AbortSignal | undefined;\n  runtimeContext: RUNTIME_CONTEXT;\n}): ReadableStream<ToolCallbackStreamPart<TOOLS>> {\n  if (tools == null) return stream;\n\n  const ongoingToolCallToolNames: Record<string, string> = createIdMap();\n\n  return stream.pipeThrough(\n    new TransformStream({\n      async transform(chunk, controller) {\n        controller.enqueue(chunk);\n\n        if (isStreamRetryAttemptBoundaryPart(chunk)) {\n          return;\n        }\n\n        switch (chunk.type) {\n          case 'tool-input-start': {\n            ongoingToolCallToolNames[chunk.id] = chunk.toolName;\n\n            const tool = getOwn(tools, chunk.toolName);\n            if (tool?.onInputStart != null) {\n              await tool.onInputStart({\n                toolCallId: chunk.id,\n                messages: stepInputMessages,\n                abortSignal,\n                context: runtimeContext,\n              });\n            }\n\n            break;\n          }\n\n          case 'tool-input-delta': {\n            const toolName = ongoingToolCallToolNames[chunk.id];\n            const tool = getOwn(tools, toolName);\n\n            if (tool?.onInputDelta != null) {\n              await tool.onInputDelta({\n                inputTextDelta: chunk.delta,\n                toolCallId: chunk.id,\n                messages: stepInputMessages,\n                abortSignal,\n                context: runtimeContext,\n              });\n            }\n\n            break;\n          }\n\n          case 'tool-call': {\n            const toolName = ongoingToolCallToolNames[chunk.toolCallId];\n            const tool = getOwn(tools, toolName);\n\n            delete ongoingToolCallToolNames[chunk.toolCallId];\n\n            if (tool?.onInputAvailable != null) {\n              await tool.onInputAvailable({\n                input: chunk.input,\n                toolCallId: chunk.toolCallId,\n                messages: stepInputMessages,\n                abortSignal,\n                context: runtimeContext,\n              });\n            }\n          }\n        }\n      },\n    }),\n  );\n}\n","import {\n  getErrorMessage,\n  type LanguageModelV4Content,\n  type LanguageModelV4Prompt,\n  type LanguageModelV4StreamPart,\n  type LanguageModelV4ToolChoice,\n  type SharedV4Headers,\n} from '@ai-sdk/provider';\nimport {\n  createIdGenerator,\n  type Arrayable,\n  type Experimental_SandboxSession as SandboxSession,\n  type IdGenerator,\n  type InferToolSetContext,\n  type ModelMessage,\n  type ProviderOptions,\n  type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { ToolCallNotFoundForApprovalError } from '../error/tool-call-not-found-for-approval-error';\nimport { resolveLanguageModel } from '../model/resolve-model';\nimport { getOwn } from '../util/get-own';\nimport type { Instructions, Prompt } from '../prompt';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport type { LanguageModelCallOptions } from '../prompt/language-model-call-options';\nimport { normalizeStreamProviderError } from '../prompt/normalize-stream-provider-error';\nimport { prepareToolChoice } from '../prompt/prepare-tool-choice';\nimport { prepareTools } from '../prompt/prepare-tools';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport type { Telemetry } from '../telemetry/telemetry';\nimport type {\n  CallWarning,\n  FinishReason,\n  LanguageModel,\n  ToolChoice,\n} from '../types/language-model';\nimport type { ProviderMetadata } from '../types/provider-metadata';\nimport { asLanguageModelUsage, type LanguageModelUsage } from '../types/usage';\nimport {\n  createAsyncIterableStream,\n  type AsyncIterableStream,\n} from '../util/async-iterable-stream';\nimport type { DownloadFunction } from '../util/download/download-function';\nimport { notify } from '../util/notify';\nimport { now as originalNow } from '../util/now';\nimport { ToolChoiceViolationError } from '../error';\nimport { calculateTokensPerSecond } from './calculate-tokens-per-second';\nimport type { ContentPart } from './content-part';\nimport { DefaultGeneratedFileWithType } from './generated-file';\nimport type { OutputChunkTimingStats } from './step-result';\nimport type {\n  OnLanguageModelCallEndCallback,\n  OnLanguageModelCallStartCallback,\n} from './language-model-events';\nimport type { Output } from './output';\nimport { parseToolCall } from './parse-tool-call';\nimport type {\n  TextStreamFilePart,\n  TextStreamPart,\n  TextStreamReasoningDeltaPart,\n  TextStreamReasoningFilePart,\n  TextStreamTextDeltaPart,\n  TextStreamToolApprovalRequestPart,\n  TextStreamToolApprovalResponsePart,\n  TextStreamToolCallPart,\n  TextStreamToolErrorPart,\n  TextStreamToolResultPart,\n} from './stream-text-result';\nimport { sumTokenCounts } from './sum-token-counts';\nimport type { TypedToolCall } from './tool-call';\nimport type { ToolCallRepairFunction } from './tool-call-repair-function';\nimport type { TypedToolError } from './tool-error';\nimport type { ToolInputRefinement } from './tool-input-refinement';\nimport type { ToolOrder } from './tool-order';\nimport type { TypedToolResult } from './tool-result';\n\nconst originalGenerateId = createIdGenerator({\n  prefix: 'aitxt',\n  size: 24,\n});\n\nconst originalGenerateCallId = createIdGenerator({\n  prefix: 'call',\n  size: 24,\n});\n\nexport type LanguageModelStreamPart<TOOLS extends ToolSet = ToolSet> =\n  | Exclude<\n      TextStreamPart<TOOLS>,\n      {\n        type:\n          | 'finish'\n          | 'stream-start'\n          | 'tool-output-denied'\n          | 'start-step'\n          | 'finish-step'\n          | 'start'\n          | 'abort';\n      }\n    >\n  | TextStreamTextDeltaPart\n  | TextStreamReasoningDeltaPart\n  | TextStreamFilePart\n  | TextStreamReasoningFilePart\n  | TextStreamToolApprovalRequestPart<TOOLS>\n  | TextStreamToolApprovalResponsePart<TOOLS>\n  | TextStreamToolCallPart<TOOLS>\n  | TextStreamToolResultPart<TOOLS>\n  | TextStreamToolErrorPart<TOOLS>\n  | {\n      type: 'model-call-end';\n      finishReason: FinishReason;\n      rawFinishReason: string | undefined;\n      usage: LanguageModelUsage;\n      providerMetadata?: ProviderMetadata;\n      performance: {\n        responseTimeMs: number;\n        effectiveOutputTokensPerSecond: number;\n        outputTokensPerSecond: number | undefined;\n        inputTokensPerSecond: number | undefined;\n        effectiveTotalTokensPerSecond: number;\n        timeToFirstOutputMs: number | undefined;\n        timeBetweenOutputChunksMs?: OutputChunkTimingStats;\n      };\n    }\n  | {\n      type: 'model-call-start';\n      warnings: Array<CallWarning>;\n    }\n  | {\n      type: 'model-call-response-metadata';\n\n      /**\n       * ID for the generated response, if the provider sends one.\n       */\n      id?: string;\n\n      /**\n       * Timestamp for the start of the generated response, if the provider sends one.\n       */\n      timestamp?: Date;\n\n      /**\n       * The ID of the response model that was used to generate the response, if the provider sends one.\n       */\n      modelId?: string;\n    };\n\n/**\n * Streams a single language model call after standardizing the prompt and tools.\n *\n * The returned stream emits model call parts together with request and response\n * metadata when available.\n *\n * @param model - The language model to use.\n * @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.\n * @param output - Output configuration that controls the response format requested from the model.\n * @param toolChoice - The tool choice strategy for the model call.\n *\n * @param system - A system message that will be part of the prompt.\n * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n * @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false.\n *\n * @param maxOutputTokens - Maximum number of tokens to generate.\n * @param temperature - Temperature setting.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topP - Nucleus sampling.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topK - Only sample from the top K options for each subsequent token.\n * Used to remove \"long tail\" low probability responses.\n * Recommended for advanced use cases only. You usually only need to use temperature.\n * @param presencePenalty - Presence penalty setting.\n * It affects the likelihood of the model to repeat information that is already in the prompt.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param frequencyPenalty - Frequency penalty setting.\n * It affects the likelihood of the model to repeatedly use the same words or phrases.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param stopSequences - Stop sequences.\n * If set, the model will stop generating text when one of the stop sequences is generated.\n * @param seed - The seed (integer) to use for random sampling.\n * If set and supported by the model, calls will generate deterministic results.\n * @param reasoning - Reasoning configuration for the model call.\n *\n * @param download - A function that downloads URLs as part of prompt conversion.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request.\n * @param includeRawChunks - Whether to include raw provider stream chunks in the model stream.\n * @param providerOptions - Additional provider-specific options.\n * @param repairToolCall - A function that can repair invalid tool calls before they are emitted.\n * @param refineToolInput - Optional mapping of tool names to functions that refine parsed tool inputs before they are emitted, used for telemetry, or executed.\n * @param onStart - A callback that receives the fully converted prompt before the model call starts.\n *\n * @returns A stream of model call parts together with request and response metadata when available.\n */\nexport async function streamLanguageModelCall<\n  TOOLS extends ToolSet,\n  OUTPUT extends Output = Output,\n>({\n  model,\n  tools,\n  toolOrder,\n  output,\n  toolChoice,\n  prompt,\n  system,\n  instructions,\n  messages,\n  allowSystemInMessages,\n  download,\n  abortSignal,\n  headers,\n  includeRawChunks,\n  providerOptions,\n  repairToolCall,\n  refineToolInput,\n  executeLanguageModelCallInTelemetryContext = async ({ execute }) =>\n    await execute(),\n  callId,\n  toolsContext,\n  experimental_sandbox: sandbox,\n  _internal: {\n    generateId = originalGenerateId,\n    generateCallId = originalGenerateCallId,\n    now = originalNow,\n  } = {},\n  onStart,\n  onLanguageModelCallStart,\n  onLanguageModelCallEnd,\n  ...callSettings\n}: {\n  model: LanguageModel;\n  tools?: TOOLS;\n  toolOrder?: ToolOrder<TOOLS>;\n  output?: OUTPUT;\n  toolChoice?: ToolChoice<TOOLS>;\n  download?: DownloadFunction;\n  abortSignal?: AbortSignal;\n  headers?: Record<string, string | undefined>;\n  includeRawChunks?: boolean;\n  providerOptions?: ProviderOptions;\n  repairToolCall?: ToolCallRepairFunction<TOOLS> | undefined;\n  refineToolInput?: ToolInputRefinement<TOOLS> | undefined;\n  executeLanguageModelCallInTelemetryContext?: Telemetry['executeLanguageModelCall'];\n  callId?: string;\n  /**\n   * Tool context used to resolve per-call tool metadata such as function\n   * descriptions before sending tools to the model.\n   */\n  toolsContext?: InferToolSetContext<TOOLS>;\n  /**\n   * Sandbox session passed through for resolving tool descriptions that depend on it.\n   */\n  experimental_sandbox?: SandboxSession;\n  _internal?: {\n    generateId?: IdGenerator;\n    generateCallId?: IdGenerator;\n    now?: () => number;\n  };\n  onLanguageModelCallStart?: Arrayable<OnLanguageModelCallStartCallback>;\n  onLanguageModelCallEnd?: Arrayable<OnLanguageModelCallEndCallback<TOOLS>>;\n\n  // onStart is currently required because the telemetry callbacks need\n  // LanguageModelV4Prompt and we only want download URLs at most once.\n  // Therefore convertToLanguageModelPrompt can only be called once\n  // per step and the resulting LanguageModelV4Prompt needs to be\n  // passed to the onStart callback.\n  //\n  // TODO explore decoupling by changing the telemetry callbacks to accept\n  // a Prompt or a standardized Prompt.\n  onStart?: (args: {\n    promptMessages: LanguageModelV4Prompt;\n  }) => Promise<void> | void;\n} & Prompt &\n  LanguageModelCallOptions): Promise<{\n  stream: AsyncIterableStream<LanguageModelStreamPart<TOOLS>>;\n  request?: {\n    /**\n     * Request HTTP body that was sent to the provider API.\n     */\n    body?: unknown;\n  };\n  response?: {\n    /**\n     * Response headers.\n     */\n    headers?: SharedV4Headers;\n  };\n}> {\n  const resolvedModel = resolveLanguageModel(model);\n  const effectiveCallId = callId ?? generateCallId();\n\n  const standardizedPrompt = await standardizePrompt({\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n  } as Prompt);\n\n  const promptMessages = await convertToLanguageModelPrompt({\n    prompt: {\n      instructions: standardizedPrompt.instructions,\n      messages: standardizedPrompt.messages,\n    },\n    supportedUrls: await resolvedModel.supportedUrls,\n    download,\n    provider: resolvedModel.provider.split('.')[0],\n  });\n\n  const stepTools = await prepareTools({\n    tools,\n    toolOrder,\n    toolsContext,\n    experimental_sandbox: sandbox,\n  });\n\n  const stepToolChoice = prepareToolChoice({\n    toolChoice,\n  });\n\n  await notify({\n    event: { promptMessages },\n    callbacks: onStart,\n  });\n\n  const languageModelCallContext = {\n    provider: resolvedModel.provider,\n    modelId: resolvedModel.modelId,\n    instructions: standardizedPrompt.instructions,\n    messages: standardizedPrompt.messages,\n    tools: stepTools,\n    ...callSettings,\n  };\n  const languageModelCallStartEvent = {\n    callId: effectiveCallId,\n    ...languageModelCallContext,\n  };\n\n  await notify({\n    event: languageModelCallStartEvent,\n    callbacks: onLanguageModelCallStart,\n  });\n\n  const callStartTimestampMs = now();\n\n  const {\n    stream: languageModelStream,\n    response,\n    request,\n  } = await executeLanguageModelCallInTelemetryContext({\n    ...languageModelCallStartEvent,\n    execute: async () =>\n      await resolvedModel.doStream({\n        ...callSettings,\n        tools: stepTools,\n        toolChoice: stepToolChoice,\n        responseFormat: await output?.responseFormat,\n        prompt: promptMessages,\n        providerOptions,\n        abortSignal,\n        headers,\n        includeRawChunks,\n      }),\n  });\n\n  const standardizedStream = languageModelStream.pipeThrough(\n    createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({\n      tools,\n      instructions: standardizedPrompt.instructions,\n      messages: standardizedPrompt.messages,\n      repairToolCall,\n      refineToolInput,\n      callId: effectiveCallId,\n      provider: resolvedModel.provider,\n      modelId: resolvedModel.modelId,\n      toolChoice: stepToolChoice,\n      generateId,\n      now,\n      callStartTimestampMs,\n      onLanguageModelCallEnd,\n    }),\n  );\n\n  return {\n    stream: createAsyncIterableStream(standardizedStream),\n    response,\n    request,\n  };\n}\n\n// Java Loves You.\nfunction createLanguageModelV4StreamPartToLanguageModelStreamPartTransform<\n  TOOLS extends ToolSet,\n>({\n  tools,\n  instructions,\n  messages,\n  repairToolCall,\n  refineToolInput,\n  callId,\n  provider,\n  modelId,\n  toolChoice,\n  generateId,\n  now,\n  callStartTimestampMs,\n  onLanguageModelCallEnd,\n}: {\n  tools: TOOLS | undefined;\n  instructions: Instructions | undefined;\n  messages: ModelMessage[];\n  repairToolCall: ToolCallRepairFunction<TOOLS> | undefined;\n  refineToolInput: ToolInputRefinement<TOOLS> | undefined;\n  callId: string;\n  provider: string;\n  modelId: string;\n  toolChoice: LanguageModelV4ToolChoice;\n  generateId: IdGenerator;\n  now: () => number;\n  callStartTimestampMs: number;\n  onLanguageModelCallEnd?: Arrayable<OnLanguageModelCallEndCallback<TOOLS>>;\n}) {\n  // keep track of parsed tool calls so provider-emitted approval requests can reference them\n  // keep track of tool inputs for provider-side tool results\n  const toolCallsByToolCallId = new Map<string, TypedToolCall<TOOLS>>();\n  const modelCallContent: Array<ContentPart<TOOLS>> = [];\n  const rawModelCallContent: Array<LanguageModelV4Content> = [];\n  const textPartIndexes = new Map<string, number>();\n  const reasoningPartIndexes = new Map<string, number>();\n  const rawTextPartIndexes = new Map<string, number>();\n  const rawReasoningPartIndexes = new Map<string, number>();\n  let responseId = generateId();\n  let responseModelId = modelId;\n  let timeToFirstOutputMs: number | undefined;\n  let previousOutputChunkTimestampMs: number | undefined;\n  const timeBetweenOutputChunksMs: number[] = [];\n\n  return new TransformStream<\n    LanguageModelV4StreamPart,\n    LanguageModelStreamPart<TOOLS>\n  >({\n    async transform(chunk, controller) {\n      if (isOutputChunk(chunk)) {\n        const outputChunkTimestampMs = now();\n\n        if (timeToFirstOutputMs == null) {\n          timeToFirstOutputMs = outputChunkTimestampMs - callStartTimestampMs;\n        } else if (previousOutputChunkTimestampMs != null) {\n          timeBetweenOutputChunksMs.push(\n            outputChunkTimestampMs - previousOutputChunkTimestampMs,\n          );\n        }\n\n        previousOutputChunkTimestampMs = outputChunkTimestampMs;\n      }\n\n      switch (chunk.type) {\n        case 'error':\n          controller.enqueue({\n            type: 'error',\n            error: normalizeStreamProviderError(chunk.error),\n          });\n          break;\n\n        case 'text-start':\n          upsertTextContentPart({\n            content: modelCallContent,\n            rawContent: rawModelCallContent,\n            partIndexes: textPartIndexes,\n            rawPartIndexes: rawTextPartIndexes,\n            id: chunk.id,\n            type: 'text',\n            providerMetadata: chunk.providerMetadata,\n          });\n          controller.enqueue(chunk);\n          break;\n\n        case 'text-delta':\n          upsertTextContentPart({\n            content: modelCallContent,\n            rawContent: rawModelCallContent,\n            partIndexes: textPartIndexes,\n            rawPartIndexes: rawTextPartIndexes,\n            id: chunk.id,\n            type: 'text',\n            textDelta: chunk.delta,\n            providerMetadata: chunk.providerMetadata,\n          });\n          controller.enqueue({\n            type: 'text-delta',\n            id: chunk.id,\n            text: chunk.delta,\n            providerMetadata: chunk.providerMetadata,\n          });\n          break;\n\n        case 'text-end':\n          upsertTextContentPart({\n            content: modelCallContent,\n            rawContent: rawModelCallContent,\n            partIndexes: textPartIndexes,\n            rawPartIndexes: rawTextPartIndexes,\n            id: chunk.id,\n            type: 'text',\n            providerMetadata: chunk.providerMetadata,\n          });\n          textPartIndexes.delete(chunk.id);\n          rawTextPartIndexes.delete(chunk.id);\n          controller.enqueue(chunk);\n          break;\n\n        case 'reasoning-start':\n          upsertTextContentPart({\n            content: modelCallContent,\n            rawContent: rawModelCallContent,\n            partIndexes: reasoningPartIndexes,\n            rawPartIndexes: rawReasoningPartIndexes,\n            id: chunk.id,\n            type: 'reasoning',\n            providerMetadata: chunk.providerMetadata,\n          });\n          controller.enqueue(chunk);\n          break;\n\n        case 'reasoning-delta':\n          upsertTextContentPart({\n            content: modelCallContent,\n            rawContent: rawModelCallContent,\n            partIndexes: reasoningPartIndexes,\n            rawPartIndexes: rawReasoningPartIndexes,\n            id: chunk.id,\n            type: 'reasoning',\n            textDelta: chunk.delta,\n            providerMetadata: chunk.providerMetadata,\n          });\n          controller.enqueue({\n            type: 'reasoning-delta',\n            id: chunk.id,\n            text: chunk.delta,\n            providerMetadata: chunk.providerMetadata,\n          });\n          break;\n\n        case 'reasoning-end':\n          upsertTextContentPart({\n            content: modelCallContent,\n            rawContent: rawModelCallContent,\n            partIndexes: reasoningPartIndexes,\n            rawPartIndexes: rawReasoningPartIndexes,\n            id: chunk.id,\n            type: 'reasoning',\n            providerMetadata: chunk.providerMetadata,\n          });\n          reasoningPartIndexes.delete(chunk.id);\n          rawReasoningPartIndexes.delete(chunk.id);\n          controller.enqueue(chunk);\n          break;\n\n        case 'file':\n        case 'reasoning-file': {\n          const file = new DefaultGeneratedFileWithType({\n            data:\n              chunk.data.type === 'data'\n                ? chunk.data.data\n                : chunk.data.url.toString(),\n            mediaType: chunk.mediaType,\n          });\n\n          modelCallContent.push({\n            type: chunk.type,\n            file,\n            ...(chunk.providerMetadata != null\n              ? { providerMetadata: chunk.providerMetadata }\n              : {}),\n          });\n          rawModelCallContent.push(chunk);\n\n          controller.enqueue({\n            type: chunk.type,\n            file,\n            providerMetadata: chunk.providerMetadata,\n          });\n          break;\n        }\n\n        case 'finish': {\n          const usage = asLanguageModelUsage(chunk.usage);\n          const responseTimeMs = now() - callStartTimestampMs;\n          const performance = {\n            responseTimeMs,\n            effectiveOutputTokensPerSecond: calculateTokensPerSecond({\n              tokens: usage.outputTokens,\n              durationMs: responseTimeMs,\n            }),\n            outputTokensPerSecond:\n              timeToFirstOutputMs == null\n                ? undefined\n                : calculateTokensPerSecond({\n                    tokens: usage.outputTokens,\n                    durationMs: responseTimeMs - timeToFirstOutputMs,\n                  }),\n            inputTokensPerSecond:\n              timeToFirstOutputMs == null\n                ? undefined\n                : calculateTokensPerSecond({\n                    tokens: usage.inputTokens,\n                    durationMs: timeToFirstOutputMs,\n                  }),\n            effectiveTotalTokensPerSecond: calculateTokensPerSecond({\n              tokens: sumTokenCounts(usage.inputTokens, usage.outputTokens),\n              durationMs: responseTimeMs,\n            }),\n            timeToFirstOutputMs,\n            timeBetweenOutputChunksMs:\n              timeBetweenOutputChunksMs.length > 0\n                ? calculateOutputChunkTimingStats(timeBetweenOutputChunksMs)\n                : undefined,\n          };\n\n          await notify({\n            event: {\n              callId,\n              provider,\n              modelId: responseModelId,\n              finishReason: chunk.finishReason.unified,\n              usage,\n              content: modelCallContent,\n              responseId,\n              ...(chunk.providerMetadata != null\n                ? { providerMetadata: chunk.providerMetadata }\n                : {}),\n              performance,\n            },\n            callbacks: onLanguageModelCallEnd,\n          });\n\n          // Preserve the completed model call's usage, metadata, and\n          // performance even when response validation below surfaces a\n          // semantic error.\n          controller.enqueue({\n            type: 'model-call-end',\n            finishReason: chunk.finishReason.unified,\n            rawFinishReason: chunk.finishReason.raw,\n            usage,\n            providerMetadata: chunk.providerMetadata,\n            performance,\n          });\n\n          const enforcedToolChoice =\n            toolChoice.type === 'required' || toolChoice.type === 'tool'\n              ? toolChoice\n              : undefined;\n\n          if (\n            enforcedToolChoice != null &&\n            ![...toolCallsByToolCallId.values()].some(\n              toolCall =>\n                enforcedToolChoice.type === 'required' ||\n                toolCall.toolName === enforcedToolChoice.toolName,\n            )\n          ) {\n            controller.enqueue({\n              type: 'error',\n              error: new ToolChoiceViolationError({\n                toolChoice: enforcedToolChoice,\n                finishReason: chunk.finishReason.unified,\n                provider,\n                modelId,\n                content: rawModelCallContent,\n              }),\n            });\n            break;\n          }\n          break;\n        }\n\n        case 'tool-call': {\n          rawModelCallContent.push(chunk);\n\n          try {\n            const toolCall = await parseToolCall({\n              toolCall: chunk,\n              tools,\n              repairToolCall,\n              refineToolInput,\n              instructions,\n              messages,\n            });\n\n            toolCallsByToolCallId.set(toolCall.toolCallId, toolCall);\n            controller.enqueue(toolCall);\n            modelCallContent.push(toolCall);\n\n            if (toolCall.invalid) {\n              if (!toolCall.providerExecuted) {\n                controller.enqueue({\n                  type: 'tool-error',\n                  toolCallId: toolCall.toolCallId,\n                  toolName: toolCall.toolName,\n                  input: toolCall.input,\n                  error: getErrorMessage(toolCall.error!),\n                  dynamic: true,\n                  title: toolCall.title,\n                  ...(toolCall.toolMetadata != null\n                    ? { toolMetadata: toolCall.toolMetadata }\n                    : {}),\n                });\n              }\n              break;\n            }\n          } catch (error) {\n            controller.enqueue({ type: 'error', error });\n          }\n\n          break;\n        }\n\n        case 'tool-approval-request': {\n          rawModelCallContent.push(chunk);\n\n          const toolCall = toolCallsByToolCallId.get(chunk.toolCallId);\n\n          if (toolCall == null) {\n            controller.enqueue({\n              type: 'error',\n              error: new ToolCallNotFoundForApprovalError({\n                toolCallId: chunk.toolCallId,\n                approvalId: chunk.approvalId,\n              }),\n            });\n            break;\n          }\n\n          const toolApprovalRequest = {\n            type: 'tool-approval-request',\n            approvalId: chunk.approvalId,\n            toolCall,\n          } as const;\n\n          controller.enqueue(toolApprovalRequest);\n          modelCallContent.push(toolApprovalRequest);\n          break;\n        }\n\n        case 'tool-result': {\n          rawModelCallContent.push(chunk);\n\n          const toolName = chunk.toolName as keyof TOOLS & string;\n          const toolCall = toolCallsByToolCallId.get(chunk.toolCallId);\n\n          const toolResultPart = chunk.isError\n            ? ({\n                type: 'tool-error',\n                toolCallId: chunk.toolCallId,\n                toolName,\n                input: toolCall?.input,\n                providerExecuted: true,\n                error: chunk.result,\n                dynamic: chunk.dynamic,\n                ...(chunk.providerMetadata != null\n                  ? { providerMetadata: chunk.providerMetadata }\n                  : {}),\n                ...(toolCall?.toolMetadata != null\n                  ? { toolMetadata: toolCall.toolMetadata }\n                  : {}),\n              } as TypedToolError<TOOLS>)\n            : ({\n                type: 'tool-result',\n                toolCallId: chunk.toolCallId,\n                toolName,\n                input: toolCall?.input,\n                output: chunk.result,\n                providerExecuted: true,\n                dynamic: chunk.dynamic,\n                ...(chunk.providerMetadata != null\n                  ? { providerMetadata: chunk.providerMetadata }\n                  : {}),\n                ...(toolCall?.toolMetadata != null\n                  ? { toolMetadata: toolCall.toolMetadata }\n                  : {}),\n              } as TypedToolResult<TOOLS>);\n\n          controller.enqueue(toolResultPart);\n          modelCallContent.push(toolResultPart);\n\n          break;\n        }\n\n        case 'tool-input-start': {\n          const tool = getOwn(tools, chunk.toolName);\n\n          controller.enqueue({\n            ...chunk,\n            dynamic: chunk.dynamic ?? tool?.type === 'dynamic',\n            title: tool?.title,\n            ...(tool?.metadata != null ? { toolMetadata: tool.metadata } : {}),\n          });\n          break;\n        }\n\n        case 'stream-start': {\n          controller.enqueue({\n            type: 'model-call-start',\n            warnings: chunk.warnings,\n          });\n          break;\n        }\n\n        case 'response-metadata': {\n          responseId = chunk.id ?? responseId;\n          responseModelId = chunk.modelId ?? responseModelId;\n\n          controller.enqueue({\n            type: 'model-call-response-metadata',\n            id: chunk.id,\n            timestamp: chunk.timestamp,\n            modelId: chunk.modelId,\n          });\n          break;\n        }\n\n        default:\n          if (chunk.type === 'custom' || chunk.type === 'source') {\n            modelCallContent.push(chunk);\n            rawModelCallContent.push(chunk);\n          }\n\n          controller.enqueue(chunk);\n          break;\n      }\n    },\n  });\n}\n\n/**\n * Returns true for chunks that contain generated model output.\n * Used to measure time-to-first-output for text, reasoning, generated files,\n * and tool calls.\n */\nfunction isOutputChunk(chunk: LanguageModelV4StreamPart): boolean {\n  return (\n    (chunk.type === 'text-delta' && chunk.delta.length > 0) ||\n    (chunk.type === 'reasoning-delta' && chunk.delta.length > 0) ||\n    (chunk.type === 'tool-input-delta' && chunk.delta.length > 0) ||\n    chunk.type === 'file' ||\n    chunk.type === 'reasoning-file' ||\n    chunk.type === 'tool-call'\n  );\n}\n\nfunction calculateOutputChunkTimingStats(\n  timingsMs: number[],\n): OutputChunkTimingStats {\n  const sortedTimingsMs = [...timingsMs].sort((a, b) => a - b);\n  const sum = timingsMs.reduce((sum, timingMs) => sum + timingMs, 0);\n\n  return {\n    min: sortedTimingsMs[0],\n    p10: calculateNearestRankPercentile(sortedTimingsMs, 0.1),\n    median: calculateNearestRankPercentile(sortedTimingsMs, 0.5),\n    avg: sum / timingsMs.length,\n    p90: calculateNearestRankPercentile(sortedTimingsMs, 0.9),\n    max: sortedTimingsMs[sortedTimingsMs.length - 1],\n  };\n}\n\nfunction calculateNearestRankPercentile(\n  sortedValues: number[],\n  percentile: number,\n): number {\n  return sortedValues[Math.ceil(percentile * sortedValues.length) - 1];\n}\n\n/**\n * Appends a text or reasoning content part into the content array and updates the part indexes.\n */\nfunction upsertTextContentPart<TOOLS extends ToolSet>({\n  content,\n  rawContent,\n  partIndexes,\n  rawPartIndexes,\n  id,\n  type,\n  textDelta,\n  providerMetadata,\n}: {\n  content: Array<ContentPart<TOOLS>>;\n  rawContent: Array<LanguageModelV4Content>;\n  partIndexes: Map<string, number>;\n  rawPartIndexes: Map<string, number>;\n  id: string;\n  type: 'text' | 'reasoning';\n  textDelta?: string;\n  providerMetadata?: ProviderMetadata;\n}) {\n  let partIndex = partIndexes.get(id);\n\n  if (partIndex == null) {\n    partIndex =\n      content.push({\n        type,\n        text: '',\n        ...(providerMetadata != null ? { providerMetadata } : {}),\n      }) - 1;\n    partIndexes.set(id, partIndex);\n  }\n\n  let rawPartIndex = rawPartIndexes.get(id);\n\n  if (rawPartIndex == null) {\n    rawPartIndex =\n      rawContent.push({\n        type,\n        text: '',\n        ...(providerMetadata != null ? { providerMetadata } : {}),\n      }) - 1;\n    rawPartIndexes.set(id, rawPartIndex);\n  }\n\n  const part = content[partIndex] as {\n    text: string;\n    providerMetadata?: ProviderMetadata;\n  };\n  const rawPart = rawContent[rawPartIndex] as {\n    text: string;\n    providerMetadata?: ProviderMetadata;\n  };\n\n  if (textDelta != null) {\n    part.text += textDelta;\n    rawPart.text += textDelta;\n  }\n\n  if (providerMetadata != null) {\n    part.providerMetadata = providerMetadata;\n    rawPart.providerMetadata = providerMetadata;\n  }\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport { isProviderStreamError } from '@ai-sdk/provider-utils';\nimport { StreamProviderError } from '../error/stream-provider-error';\n\n/**\n * Normalizes well-formed provider error payloads without changing existing\n * Error instances or malformed/unknown values.\n */\nexport function normalizeStreamProviderError(error: unknown): unknown {\n  if (\n    isError(error) ||\n    AISDKError.isInstance(error) ||\n    StreamProviderError.isInstance(error)\n  ) {\n    return error;\n  }\n\n  const outer = asRecord(error);\n  if (outer == null) {\n    return error;\n  }\n\n  const providerStreamError = isProviderStreamError(error);\n  const details = providerStreamError\n    ? outer\n    : (asRecord(asRecord(outer.response)?.error) ??\n      asRecord(outer.error) ??\n      outer);\n\n  if (typeof details.message !== 'string') {\n    return error;\n  }\n\n  const type = getString(details.type) ?? getString(outer.type);\n  const code = getStringOrNumber(details.code) ?? getStringOrNumber(outer.code);\n  const explicitStatusCode =\n    getHttpStatusCode(details.statusCode) ??\n    getHttpStatusCode(outer.statusCode) ??\n    getHttpStatusCode(details.status_code) ??\n    getHttpStatusCode(outer.status_code) ??\n    getHttpStatusCode(details.status) ??\n    getHttpStatusCode(outer.status) ??\n    getHttpStatusCode(details.code) ??\n    getHttpStatusCode(outer.code);\n  const messageMetadata = inferExactMessageMetadata(details.message);\n  const statusCode = explicitStatusCode ?? messageMetadata?.statusCode;\n  const explicitRetryability =\n    getBoolean(details.isRetryable) ??\n    getBoolean(outer.isRetryable) ??\n    getBoolean(details.is_retryable) ??\n    getBoolean(outer.is_retryable);\n\n  return new StreamProviderError({\n    message: details.message,\n    type,\n    code,\n    statusCode,\n    isRetryable:\n      explicitRetryability ??\n      messageMetadata?.isRetryable ??\n      isRetryableStatusCode(statusCode),\n    data: providerStreamError ? error.data : error,\n  });\n}\n\nfunction inferExactMessageMetadata(\n  message: string,\n): { statusCode: number; isRetryable: true } | undefined {\n  switch (message.trim().toLowerCase()) {\n    case 'overloaded':\n    case 'overloaded error':\n    case 'model overloaded':\n      return { statusCode: 503, isRetryable: true };\n    case 'internal server error':\n      return { statusCode: 500, isRetryable: true };\n    case 'service unavailable':\n      return { statusCode: 503, isRetryable: true };\n    default:\n      return undefined;\n  }\n}\n\nfunction isRetryableStatusCode(statusCode: number | undefined): boolean {\n  return (\n    statusCode != null &&\n    (statusCode === 408 ||\n      statusCode === 409 ||\n      statusCode === 429 ||\n      statusCode >= 500)\n  );\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n  return typeof value === 'object' && value != null\n    ? (value as Record<string, unknown>)\n    : undefined;\n}\n\n// `instanceof` misses Error instances created in another JavaScript realm.\nfunction isError(value: unknown): value is Error {\n  return (\n    value instanceof Error ||\n    Object.prototype.toString.call(value) === '[object Error]'\n  );\n}\n\nfunction getString(value: unknown): string | undefined {\n  return typeof value === 'string' ? value : undefined;\n}\n\nfunction getStringOrNumber(value: unknown): string | number | undefined {\n  return typeof value === 'string' || typeof value === 'number'\n    ? value\n    : undefined;\n}\n\nfunction getBoolean(value: unknown): boolean | undefined {\n  return typeof value === 'boolean' ? value : undefined;\n}\n\nfunction getHttpStatusCode(value: unknown): number | undefined {\n  const statusCode =\n    typeof value === 'string' && /^\\d{3}$/.test(value) ? Number(value) : value;\n\n  return typeof statusCode === 'number' &&\n    Number.isInteger(statusCode) &&\n    statusCode >= 400 &&\n    statusCode <= 599\n    ? statusCode\n    : undefined;\n}\n","import {\n  generateId as generateIdFunc,\n  type IdGenerator,\n} from '@ai-sdk/provider-utils';\nimport type { UIMessage } from '../ui/ui-messages';\nimport { handleUIMessageStreamFinish } from './handle-ui-message-stream-finish';\nimport type { InferUIMessageChunk } from './ui-message-chunks';\nimport type { UIMessageStreamOnEndCallback } from './ui-message-stream-on-end-callback';\nimport type { UIMessageStreamOutcome } from './ui-message-stream-outcome';\nimport type { UIMessageStreamOnStepEndCallback } from './ui-message-stream-on-step-end-callback';\nimport type { UIMessageStreamOnStepFinishCallback } from './ui-message-stream-on-step-finish-callback';\nimport type { UIMessageStreamWriterWithOutcome } from './ui-message-stream-writer';\n\n/**\n * Creates a UI message stream that can be used to send messages to the client.\n *\n * @param options.execute - A function that is called with a writer to write UI message chunks to the stream.\n * @param options.onError - A function that extracts an error message from an error. Defaults to `() => 'An error occurred.'` so server-side error details are not leaked to the client; supply your own to surface richer messages.\n * @param options.originalMessages - The original messages. If provided, persistence mode is assumed\n *   and a message ID is provided for the response message.\n * @param options.onStepEnd - A callback that is called when each step ends. Useful for persisting intermediate messages.\n * @param options.onStepFinish - Deprecated alias for `onStepEnd`.\n * @param options.onEnd - A callback that is called when the stream ends.\n * @param options.onFinish - Deprecated alias for `onEnd`.\n * @param options.generateId - A function that generates a unique ID. Defaults to the built-in ID generator.\n *\n * @returns A `ReadableStream` of UI message chunks.\n */\nexport function createUIMessageStream<UI_MESSAGE extends UIMessage>({\n  execute,\n  onError = () => 'An error occurred.', // prevent leaking server error details to the client by default\n  originalMessages,\n  onStepEnd,\n  onStepFinish,\n  onEnd,\n  onFinish,\n  generateId = generateIdFunc,\n}: {\n  execute: (options: {\n    writer: UIMessageStreamWriterWithOutcome<UI_MESSAGE>;\n  }) => Promise<void> | void;\n  onError?: (error: unknown) => string;\n\n  /**\n   * The original messages. If they are provided, persistence mode is assumed,\n   * and a message ID is provided for the response message.\n   */\n  originalMessages?: UI_MESSAGE[];\n\n  /**\n   * Callback that is called when each step ends during multi-step agent runs.\n   */\n  onStepEnd?: UIMessageStreamOnStepEndCallback<UI_MESSAGE>;\n\n  /**\n   * Callback that is called when each step ends during multi-step agent runs.\n   *\n   * @deprecated Use `onStepEnd` instead.\n   */\n  onStepFinish?: UIMessageStreamOnStepFinishCallback<UI_MESSAGE>;\n\n  onEnd?: UIMessageStreamOnEndCallback<UI_MESSAGE>;\n\n  /**\n   * @deprecated Use `onEnd` instead.\n   */\n  onFinish?: UIMessageStreamOnEndCallback<UI_MESSAGE>;\n\n  generateId?: IdGenerator;\n}): ReadableStream<InferUIMessageChunk<UI_MESSAGE>> {\n  let controller!: ReadableStreamDefaultController<\n    InferUIMessageChunk<UI_MESSAGE>\n  >;\n\n  const ongoingStreamPromises: Promise<void>[] = [];\n  let outcome: UIMessageStreamOutcome = { status: 'unknown' };\n\n  const stream = new ReadableStream({\n    start(controllerArg) {\n      controller = controllerArg;\n    },\n  });\n\n  function safeEnqueue(data: InferUIMessageChunk<UI_MESSAGE>) {\n    try {\n      controller.enqueue(data);\n    } catch {\n      // suppress errors when the stream has been closed\n    }\n  }\n\n  function setOutcome(newOutcome: UIMessageStreamOutcome) {\n    if (outcome.status === 'unknown' && newOutcome.status !== 'unknown') {\n      outcome = newOutcome;\n    }\n  }\n\n  function failOutcome(error: unknown) {\n    outcome = { status: 'failed', error };\n  }\n\n  function safeError(error: unknown) {\n    try {\n      controller.error(error);\n    } catch {\n      // suppress errors when the stream has been closed\n    }\n  }\n\n  function handleError(error: unknown) {\n    failOutcome(error);\n\n    let errorText: string;\n    try {\n      errorText = onError(error);\n    } catch (onErrorError) {\n      failOutcome(onErrorError);\n      safeError(onErrorError);\n      return;\n    }\n\n    safeEnqueue({\n      type: 'error',\n      errorText,\n    } as InferUIMessageChunk<UI_MESSAGE>);\n  }\n\n  try {\n    const result = execute({\n      writer: {\n        write(part: InferUIMessageChunk<UI_MESSAGE>) {\n          safeEnqueue(part);\n        },\n        merge(streamArg) {\n          ongoingStreamPromises.push(\n            (async () => {\n              const reader = streamArg.getReader();\n              while (true) {\n                const { done, value } = await reader.read();\n                if (done) break;\n                safeEnqueue(value);\n              }\n            })().catch(error => {\n              handleError(error);\n            }),\n          );\n        },\n        setOutcome,\n        onError,\n      },\n    });\n\n    if (result) {\n      ongoingStreamPromises.push(\n        result.catch(error => {\n          handleError(error);\n        }),\n      );\n    }\n  } catch (error) {\n    handleError(error);\n  }\n\n  // Wait until all ongoing streams are done. This approach enables merging\n  // streams even after execute has returned, as long as there is still an\n  // open merged stream. This is important to e.g. forward new streams and\n  // from callbacks.\n  const waitForStreams: Promise<void> = (async () => {\n    while (ongoingStreamPromises.length > 0) {\n      await ongoingStreamPromises.shift();\n    }\n  })();\n\n  waitForStreams.finally(() => {\n    try {\n      controller.close();\n    } catch {\n      // suppress errors when the stream has been closed\n    }\n  });\n\n  return handleUIMessageStreamFinish<UI_MESSAGE>({\n    stream,\n    messageId: generateId(),\n    originalMessages,\n    onStepEnd: onStepEnd ?? onStepFinish,\n    onEnd: onEnd ?? onFinish,\n    onError,\n    getOutcome: () => outcome,\n  });\n}\n","import type { UIMessage } from '../ui/ui-messages';\nimport type { UIMessageChunk } from './ui-message-chunks';\nimport {\n  createStreamingUIMessageState,\n  processUIMessageStream,\n  type StreamingUIMessageState,\n  type UIMessageStreamWriteOptions,\n} from '../ui/process-ui-message-stream';\nimport {\n  createAsyncIterableStream,\n  type AsyncIterableStream,\n} from '../util/async-iterable-stream';\nimport { consumeStream } from '../util/consume-stream';\n\nfunction createUIMessageSnapshot<UI_MESSAGE extends UIMessage>(\n  message: UI_MESSAGE,\n): UI_MESSAGE {\n  const textByPartIndex = new Map<number, string>();\n  const messageWithoutText = {\n    ...message,\n    parts: message.parts.map((part, index) => {\n      if (part.type === 'text' || part.type === 'reasoning') {\n        textByPartIndex.set(index, part.text);\n        return { ...part, text: '' };\n      }\n\n      return part;\n    }),\n  };\n\n  const snapshot = structuredClone(messageWithoutText) as UI_MESSAGE;\n\n  for (const [index, text] of textByPartIndex) {\n    const part = snapshot.parts[index];\n\n    if (part.type === 'text' || part.type === 'reasoning') {\n      part.text = text;\n    }\n  }\n\n  return snapshot;\n}\n\n/**\n * Transforms a stream of `UIMessageChunk`s into an `AsyncIterableStream` of `UIMessage`s.\n *\n * @param options.message - The last assistant message to use as a starting point when the conversation is resumed. Otherwise undefined.\n * @param options.stream - The stream of `UIMessageChunk`s to read.\n * @param options.terminateOnError - Whether to terminate the stream if an error occurs.\n * @param options.onError - A function that is called when an error occurs.\n *\n * @returns An `AsyncIterableStream` of `UIMessage`s. Each stream part is a different state of the same message\n * as it is being completed.\n */\nexport function readUIMessageStream<UI_MESSAGE extends UIMessage>({\n  message,\n  stream,\n  onError,\n  terminateOnError = false,\n}: {\n  message?: UI_MESSAGE;\n  stream: ReadableStream<UIMessageChunk>;\n  onError?: (error: unknown) => void;\n  terminateOnError?: boolean;\n}): AsyncIterableStream<UI_MESSAGE> {\n  let controller: ReadableStreamDefaultController<UI_MESSAGE> | undefined;\n  let hasErrored = false;\n\n  const outputStream = new ReadableStream<UI_MESSAGE>({\n    start(controllerParam) {\n      controller = controllerParam;\n    },\n  });\n\n  const state = createStreamingUIMessageState<UI_MESSAGE>({\n    messageId: message?.id ?? '',\n    lastMessage: message,\n  });\n\n  const handleError = (error: unknown) => {\n    onError?.(error);\n\n    if (!hasErrored && terminateOnError) {\n      hasErrored = true;\n      controller?.error(error);\n    }\n  };\n\n  consumeStream({\n    stream: processUIMessageStream({\n      stream,\n      runUpdateMessageJob(\n        job: (options: {\n          state: StreamingUIMessageState<UI_MESSAGE>;\n          write: (options?: UIMessageStreamWriteOptions) => void;\n        }) => Promise<void>,\n      ) {\n        return job({\n          state,\n          write: () => {\n            controller?.enqueue(createUIMessageSnapshot(state.message));\n          },\n        });\n      },\n      onError: handleError,\n    }),\n    onError: handleError,\n  }).finally(() => {\n    // Only close if no error occurred. Calling close() on an errored controller\n    // throws \"Invalid state: Controller is already closed\" TypeError.\n    if (!hasErrored) {\n      controller?.close();\n    }\n  });\n\n  return createAsyncIterableStream(outputStream);\n}\n","import {\n  isNonNullable,\n  type ToolSet,\n  type AssistantContent,\n  type CustomPart,\n  type FilePart,\n  type ModelMessage,\n  type TextPart,\n  type ToolApprovalResponse,\n  type ToolResultPart,\n} from '@ai-sdk/provider-utils';\nimport { createToolModelOutput } from '../prompt/create-tool-model-output';\nimport { MessageConversionError } from '../prompt/message-conversion-error';\nimport { getOwn } from '../util/get-own';\nimport {\n  getToolName,\n  isCustomContentUIPart,\n  isDataUIPart,\n  isFileUIPart,\n  isReasoningFileUIPart,\n  isReasoningUIPart,\n  isTextUIPart,\n  isToolUIPart,\n  type CustomContentUIPart,\n  type DataUIPart,\n  type DynamicToolUIPart,\n  type FileUIPart,\n  type InferUIMessageData,\n  type InferUIMessageTools,\n  type ReasoningFileUIPart,\n  type ReasoningUIPart,\n  type TextUIPart,\n  type ToolUIPart,\n  type UIMessage,\n} from './ui-messages';\nimport { warnIfUIMessageHasDeprecatedRawInput } from './warn-if-ui-message-has-deprecated-raw-input';\n/**\n * Converts an array of UI messages from useChat into an array of ModelMessages that can be used\n * with the AI functions (e.g. `streamText`, `generateText`).\n *\n * @param messages - The UI messages to convert.\n * @param options.tools - The tools to use.\n * @param options.ignoreIncompleteToolCalls - Whether to ignore incomplete tool calls. Default is `false`.\n * @param options.convertDataPart - Optional function to convert data parts to text or file model message parts. Returns `undefined` if the part should be ignored.\n *\n * @returns An array of ModelMessages.\n */\nexport async function convertToModelMessages<UI_MESSAGE extends UIMessage>(\n  messages: Array<Omit<UI_MESSAGE, 'id'>>,\n  options?: {\n    tools?: ToolSet;\n    ignoreIncompleteToolCalls?: boolean;\n    convertDataPart?: (\n      part: DataUIPart<InferUIMessageData<UI_MESSAGE>>,\n    ) => TextPart | FilePart | undefined;\n  },\n): Promise<ModelMessage[]> {\n  const modelMessages: ModelMessage[] = [];\n\n  warnIfUIMessageHasDeprecatedRawInput(messages);\n\n  if (options?.ignoreIncompleteToolCalls) {\n    messages = messages.map(message => ({\n      ...message,\n      parts: message.parts.filter(\n        part =>\n          !isToolUIPart(part) ||\n          part.state === 'approval-responded' ||\n          (part.state === 'output-available' && part.preliminary !== true) ||\n          part.state === 'output-error' ||\n          part.state === 'output-denied',\n      ),\n    }));\n  }\n\n  for (const message of messages) {\n    switch (message.role) {\n      case 'system': {\n        const textParts = message.parts.filter(\n          (part): part is TextUIPart => part.type === 'text',\n        );\n\n        const providerMetadata = textParts.reduce((acc, part) => {\n          if (part.providerMetadata != null) {\n            return { ...acc, ...part.providerMetadata };\n          }\n          return acc;\n        }, {});\n\n        modelMessages.push({\n          role: 'system',\n          content: textParts.map(part => part.text).join(''),\n          ...(Object.keys(providerMetadata).length > 0\n            ? { providerOptions: providerMetadata }\n            : {}),\n        });\n        break;\n      }\n\n      case 'user': {\n        modelMessages.push({\n          role: 'user',\n          content: message.parts\n            .map((part): TextPart | FilePart | undefined => {\n              // Process text parts\n              if (isTextUIPart(part)) {\n                return {\n                  type: 'text' as const,\n                  text: part.text,\n                  ...(part.providerMetadata != null\n                    ? { providerOptions: part.providerMetadata }\n                    : {}),\n                };\n              }\n\n              // Process file parts\n              if (isFileUIPart(part)) {\n                return {\n                  type: 'file' as const,\n                  mediaType: part.mediaType,\n                  filename: part.filename,\n                  data:\n                    part.providerReference != null\n                      ? {\n                          type: 'reference' as const,\n                          reference: part.providerReference,\n                        }\n                      : { type: 'url' as const, url: new URL(part.url) },\n                  ...(part.providerMetadata != null\n                    ? { providerOptions: part.providerMetadata }\n                    : {}),\n                };\n              }\n\n              // Process data parts with converter if provided\n              if (isDataUIPart(part)) {\n                return options?.convertDataPart?.(\n                  part as DataUIPart<InferUIMessageData<UI_MESSAGE>>,\n                );\n              }\n            })\n            .filter(isNonNullable),\n        });\n\n        break;\n      }\n\n      case 'assistant': {\n        if (message.parts != null) {\n          let block: Array<\n            | CustomContentUIPart\n            | TextUIPart\n            | ToolUIPart<InferUIMessageTools<UI_MESSAGE>>\n            | ReasoningUIPart\n            | FileUIPart\n            | ReasoningFileUIPart\n            | DynamicToolUIPart\n            | DataUIPart<InferUIMessageData<UI_MESSAGE>>\n          > = [];\n\n          async function processBlock() {\n            if (block.length === 0) {\n              return;\n            }\n\n            const content: AssistantContent = [];\n\n            for (const part of block) {\n              if (isTextUIPart(part)) {\n                content.push({\n                  type: 'text' as const,\n                  text: part.text,\n                  ...(part.providerMetadata != null\n                    ? { providerOptions: part.providerMetadata }\n                    : {}),\n                });\n              } else if (isCustomContentUIPart(part)) {\n                content.push({\n                  type: 'custom' as const,\n                  kind: part.kind,\n                  ...(part.providerMetadata != null\n                    ? { providerOptions: part.providerMetadata }\n                    : {}),\n                } satisfies CustomPart);\n              } else if (isFileUIPart(part)) {\n                content.push({\n                  type: 'file' as const,\n                  mediaType: part.mediaType,\n                  filename: part.filename,\n                  data:\n                    part.providerReference != null\n                      ? {\n                          type: 'reference' as const,\n                          reference: part.providerReference,\n                        }\n                      : { type: 'url' as const, url: new URL(part.url) },\n                  ...(part.providerMetadata != null\n                    ? { providerOptions: part.providerMetadata }\n                    : {}),\n                });\n              } else if (isReasoningFileUIPart(part)) {\n                content.push({\n                  type: 'reasoning-file' as const,\n                  data: { type: 'url' as const, url: new URL(part.url) },\n                  mediaType: part.mediaType,\n                  providerOptions: part.providerMetadata,\n                });\n              } else if (isReasoningUIPart(part)) {\n                content.push({\n                  type: 'reasoning' as const,\n                  text: part.text,\n                  providerOptions: part.providerMetadata,\n                });\n              } else if (isToolUIPart(part)) {\n                const toolName = getToolName(part);\n\n                if (part.state !== 'input-streaming') {\n                  const callProviderMetadata =\n                    part.callProviderMetadata ??\n                    (part.state === 'output-error'\n                      ? part.resultProviderMetadata\n                      : undefined);\n\n                  content.push({\n                    type: 'tool-call' as const,\n                    toolCallId: part.toolCallId,\n                    toolName,\n                    input:\n                      part.state === 'output-error'\n                        ? (part.input ??\n                          ('rawInput' in part ? part.rawInput : undefined))\n                        : part.input,\n                    providerExecuted: part.providerExecuted,\n                    ...(callProviderMetadata != null\n                      ? { providerOptions: callProviderMetadata }\n                      : {}),\n                  });\n\n                  if (part.approval != null) {\n                    content.push({\n                      type: 'tool-approval-request' as const,\n                      approvalId: part.approval.id,\n                      toolCallId: part.toolCallId,\n                      isAutomatic: part.approval.isAutomatic,\n                      ...(part.approval.requestReason != null\n                        ? { reason: part.approval.requestReason }\n                        : {}),\n                      ...(part.approval.signature != null\n                        ? { signature: part.approval.signature }\n                        : {}),\n                    });\n                  }\n\n                  if (\n                    part.providerExecuted === true &&\n                    part.state !== 'approval-responded' &&\n                    (part.state === 'output-available' ||\n                      part.state === 'output-error')\n                  ) {\n                    const resultProviderMetadata =\n                      part.resultProviderMetadata ?? part.callProviderMetadata;\n\n                    content.push({\n                      type: 'tool-result',\n                      toolCallId: part.toolCallId,\n                      toolName,\n                      output: await createToolModelOutput({\n                        toolCallId: part.toolCallId,\n                        input: part.input,\n                        output:\n                          part.state === 'output-error'\n                            ? part.errorText\n                            : part.output,\n                        tool: getOwn(options?.tools, toolName),\n                        errorMode:\n                          part.state === 'output-error' ? 'json' : 'none',\n                      }),\n                      ...(resultProviderMetadata != null\n                        ? { providerOptions: resultProviderMetadata }\n                        : {}),\n                    });\n                  }\n                }\n              } else if (isDataUIPart(part)) {\n                const dataPart = options?.convertDataPart?.(\n                  part as DataUIPart<InferUIMessageData<UI_MESSAGE>>,\n                );\n\n                if (dataPart != null) {\n                  content.push(dataPart);\n                }\n              } else {\n                const _exhaustiveCheck: never = part;\n                throw new Error(`Unsupported part: ${_exhaustiveCheck}`);\n              }\n            }\n\n            if (content.length > 0) {\n              modelMessages.push({\n                role: 'assistant',\n                content,\n              });\n            }\n\n            // check if there are tool invocations with results in the block\n            // Include non-provider-executed tools, OR provider-executed tools with approval responses\n            const toolParts = block.filter(\n              part =>\n                isToolUIPart(part) &&\n                (part.providerExecuted !== true ||\n                  part.approval?.approved != null),\n            ) as (\n              | ToolUIPart<InferUIMessageTools<UI_MESSAGE>>\n              | DynamicToolUIPart\n            )[];\n\n            // tool message with tool results\n            if (toolParts.length > 0) {\n              {\n                const content: Array<ToolResultPart | ToolApprovalResponse> =\n                  [];\n                for (const toolPart of toolParts) {\n                  // add approval response for approved tool calls:\n                  if (toolPart.approval?.approved != null) {\n                    content.push({\n                      type: 'tool-approval-response' as const,\n                      approvalId: toolPart.approval.id,\n                      approved: toolPart.approval.approved,\n                      reason: toolPart.approval.reason,\n                      providerExecuted: toolPart.providerExecuted,\n                    });\n                  }\n\n                  // add synthetic execution-denied result for denied tool approvals\n                  if (\n                    toolPart.state === 'approval-responded' &&\n                    toolPart.approval?.approved === false\n                  ) {\n                    content.push({\n                      type: 'tool-result',\n                      toolCallId: toolPart.toolCallId,\n                      toolName: getToolName(toolPart),\n                      output: {\n                        type: 'execution-denied' as const,\n                        reason: toolPart.approval.reason,\n                      },\n                      ...(toolPart.callProviderMetadata != null\n                        ? { providerOptions: toolPart.callProviderMetadata }\n                        : {}),\n                    });\n                  }\n\n                  // For provider-executed tools, the tool result is already in the\n                  // assistant content. Skip adding to tool message to avoid duplicates\n                  // (which would create orphaned function_call_output entries).\n                  if (toolPart.providerExecuted === true) {\n                    continue;\n                  }\n\n                  switch (toolPart.state) {\n                    case 'output-denied': {\n                      content.push({\n                        type: 'tool-result',\n                        toolCallId: toolPart.toolCallId,\n                        toolName: getToolName(toolPart),\n                        output: {\n                          type: 'error-text' as const,\n                          value:\n                            toolPart.approval?.reason ??\n                            'Tool call execution denied.',\n                        },\n                        ...(toolPart.callProviderMetadata != null\n                          ? { providerOptions: toolPart.callProviderMetadata }\n                          : {}),\n                      });\n                      break;\n                    }\n\n                    case 'output-error':\n                    case 'output-available': {\n                      const toolName = getToolName(toolPart);\n                      content.push({\n                        type: 'tool-result',\n                        toolCallId: toolPart.toolCallId,\n                        toolName,\n                        output: await createToolModelOutput({\n                          toolCallId: toolPart.toolCallId,\n                          input: toolPart.input,\n                          output:\n                            toolPart.state === 'output-error'\n                              ? toolPart.errorText\n                              : toolPart.output,\n                          tool: getOwn(options?.tools, toolName),\n                          errorMode:\n                            toolPart.state === 'output-error' ? 'text' : 'none',\n                        }),\n                        ...(toolPart.callProviderMetadata != null\n                          ? { providerOptions: toolPart.callProviderMetadata }\n                          : {}),\n                      });\n                      break;\n                    }\n                  }\n                }\n\n                if (content.length > 0) {\n                  modelMessages.push({\n                    role: 'tool',\n                    content,\n                  });\n                }\n              }\n            }\n\n            // updates for next block\n            block = [];\n          }\n\n          for (const part of message.parts) {\n            if (\n              isCustomContentUIPart(part) ||\n              isTextUIPart(part) ||\n              isReasoningUIPart(part) ||\n              isReasoningFileUIPart(part) ||\n              isFileUIPart(part) ||\n              isToolUIPart(part) ||\n              isDataUIPart(part)\n            ) {\n              block.push(part as (typeof block)[number]);\n            } else if (part.type === 'step-start') {\n              await processBlock();\n            }\n          }\n\n          await processBlock();\n\n          break;\n        }\n\n        break;\n      }\n\n      default: {\n        const _exhaustiveCheck: never = message.role;\n        throw new MessageConversionError({\n          originalMessage: message,\n          message: `Unsupported role: ${_exhaustiveCheck}`,\n        });\n      }\n    }\n  }\n\n  return modelMessages;\n}\n","import { TypeValidationError, type JSONObject } from '@ai-sdk/provider';\nimport {\n  lazySchema,\n  safeValidateTypes,\n  validateTypes,\n  zodSchema,\n  type FlexibleSchema,\n  type Tool,\n} from '@ai-sdk/provider-utils';\nimport { InvalidArgumentError } from '../error';\nimport { jsonValueSchema } from '../types/json-value';\nimport { getOwn } from '../util/get-own';\nimport { providerMetadataSchema } from '../types/provider-metadata';\nimport { z, type ZodType } from '../util/zod';\nimport type {\n  DataUIPart,\n  DynamicToolUIPart,\n  InferUIMessageData,\n  InferUIMessageTools,\n  ToolUIPart,\n  UIMessage,\n} from './ui-messages';\nimport { warnIfUIMessageHasDeprecatedRawInput } from './warn-if-ui-message-has-deprecated-raw-input';\n\nconst toolMetadataSchema: ZodType<JSONObject> = z.record(\n  z.string(),\n  jsonValueSchema.optional(),\n);\n\nconst providerReferenceSchema = z.record(z.string(), z.string());\n\nfunction isEmptyObject(value: unknown): value is Record<string, never> {\n  return (\n    value != null &&\n    typeof value === 'object' &&\n    !Array.isArray(value) &&\n    Object.keys(value).length === 0\n  );\n}\n\nfunction asDynamicToolPart(toolPart: ToolUIPart): DynamicToolUIPart {\n  const { type, ...part } = toolPart;\n\n  return {\n    ...part,\n    type: 'dynamic-tool',\n    toolName: type.slice(5),\n  } as DynamicToolUIPart;\n}\n\nconst uiMessagesSchema = lazySchema(() =>\n  zodSchema(\n    z\n      .array(\n        z\n          .object({\n            id: z.string(),\n            role: z.enum(['system', 'user', 'assistant']),\n            metadata: z.unknown().optional(),\n            parts: z.array(\n              z.union([\n                z.object({\n                  type: z.literal('text'),\n                  text: z.string(),\n                  state: z.enum(['streaming', 'done']).optional(),\n                  providerMetadata: providerMetadataSchema.optional(),\n                }),\n                z.object({\n                  type: z.literal('reasoning'),\n                  id: z.string().optional(),\n                  text: z.string(),\n                  state: z.enum(['streaming', 'done']).optional(),\n                  providerMetadata: providerMetadataSchema.optional(),\n                }),\n                z.object({\n                  type: z.literal('custom'),\n                  kind: z.string(),\n                  providerMetadata: providerMetadataSchema.optional(),\n                }),\n                z.object({\n                  type: z.literal('source-url'),\n                  sourceId: z.string(),\n                  url: z.string(),\n                  title: z.string().optional(),\n                  providerMetadata: providerMetadataSchema.optional(),\n                }),\n                z.object({\n                  type: z.literal('source-document'),\n                  sourceId: z.string(),\n                  mediaType: z.string(),\n                  title: z.string(),\n                  filename: z.string().optional(),\n                  providerMetadata: providerMetadataSchema.optional(),\n                }),\n                z.object({\n                  type: z.literal('file'),\n                  mediaType: z.string(),\n                  filename: z.string().optional(),\n                  url: z.string(),\n                  providerReference: providerReferenceSchema.optional(),\n                  providerMetadata: providerMetadataSchema.optional(),\n                }),\n                z.object({\n                  type: z.literal('reasoning-file'),\n                  mediaType: z.string(),\n                  url: z.string(),\n                  providerMetadata: providerMetadataSchema.optional(),\n                }),\n                z.object({\n                  type: z.literal('step-start'),\n                }),\n                z.object({\n                  type: z.string().startsWith('data-'),\n                  id: z.string().optional(),\n                  data: z.unknown(),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('input-streaming'),\n                  input: z.unknown().optional(),\n                  providerExecuted: z.boolean().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  approval: z.never().optional(),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('input-available'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.never().optional(),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('approval-requested'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.object({\n                    id: z.string(),\n                    approved: z.never().optional(),\n                    descriptor: z.unknown().optional(),\n                    requestReason: z.string().optional(),\n                    reason: z.never().optional(),\n                    isAutomatic: z.boolean().optional(),\n                    signature: z.string().optional(),\n                  }),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('approval-responded'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.object({\n                    id: z.string(),\n                    approved: z.boolean(),\n                    descriptor: z.unknown().optional(),\n                    requestReason: z.string().optional(),\n                    reason: z.string().optional(),\n                    isAutomatic: z.boolean().optional(),\n                    signature: z.string().optional(),\n                  }),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('output-available'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.unknown(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  resultProviderMetadata: providerMetadataSchema.optional(),\n                  preliminary: z.boolean().optional(),\n                  approval: z\n                    .object({\n                      id: z.string(),\n                      approved: z.literal(true),\n                      descriptor: z.unknown().optional(),\n                      requestReason: z.string().optional(),\n                      reason: z.string().optional(),\n                      isAutomatic: z.boolean().optional(),\n                      signature: z.string().optional(),\n                    })\n                    .optional(),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('output-error'),\n                  input: z.unknown().optional(),\n                  rawInput: z.unknown().optional(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.string(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  resultProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z\n                    .object({\n                      id: z.string(),\n                      approved: z.literal(true),\n                      descriptor: z.unknown().optional(),\n                      requestReason: z.string().optional(),\n                      reason: z.string().optional(),\n                      isAutomatic: z.boolean().optional(),\n                      signature: z.string().optional(),\n                    })\n                    .optional(),\n                }),\n                z.object({\n                  type: z.literal('dynamic-tool'),\n                  toolName: z.string(),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('output-denied'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.object({\n                    id: z.string(),\n                    approved: z.literal(false),\n                    descriptor: z.unknown().optional(),\n                    requestReason: z.string().optional(),\n                    reason: z.string().optional(),\n                    isAutomatic: z.boolean().optional(),\n                    signature: z.string().optional(),\n                  }),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('input-streaming'),\n                  providerExecuted: z.boolean().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  input: z.unknown().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  approval: z.never().optional(),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('input-available'),\n                  providerExecuted: z.boolean().optional(),\n                  input: z.unknown(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.never().optional(),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('approval-requested'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.object({\n                    id: z.string(),\n                    approved: z.never().optional(),\n                    descriptor: z.unknown().optional(),\n                    requestReason: z.string().optional(),\n                    reason: z.never().optional(),\n                    isAutomatic: z.boolean().optional(),\n                    signature: z.string().optional(),\n                  }),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('approval-responded'),\n                  input: z.unknown(),\n                  providerExecuted: z.boolean().optional(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.object({\n                    id: z.string(),\n                    approved: z.boolean(),\n                    descriptor: z.unknown().optional(),\n                    requestReason: z.string().optional(),\n                    reason: z.string().optional(),\n                    isAutomatic: z.boolean().optional(),\n                    signature: z.string().optional(),\n                  }),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('output-available'),\n                  providerExecuted: z.boolean().optional(),\n                  input: z.unknown(),\n                  output: z.unknown(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  resultProviderMetadata: providerMetadataSchema.optional(),\n                  preliminary: z.boolean().optional(),\n                  approval: z\n                    .object({\n                      id: z.string(),\n                      approved: z.literal(true),\n                      descriptor: z.unknown().optional(),\n                      requestReason: z.string().optional(),\n                      reason: z.string().optional(),\n                      isAutomatic: z.boolean().optional(),\n                      signature: z.string().optional(),\n                    })\n                    .optional(),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('output-error'),\n                  providerExecuted: z.boolean().optional(),\n                  input: z.unknown().optional(),\n                  rawInput: z.unknown().optional(),\n                  output: z.never().optional(),\n                  errorText: z.string(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  resultProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z\n                    .object({\n                      id: z.string(),\n                      approved: z.literal(true),\n                      descriptor: z.unknown().optional(),\n                      requestReason: z.string().optional(),\n                      reason: z.string().optional(),\n                      isAutomatic: z.boolean().optional(),\n                      signature: z.string().optional(),\n                    })\n                    .optional(),\n                }),\n                z.object({\n                  type: z.string().startsWith('tool-'),\n                  toolCallId: z.string(),\n                  title: z.string().optional(),\n                  toolMetadata: toolMetadataSchema.optional(),\n                  state: z.literal('output-denied'),\n                  providerExecuted: z.boolean().optional(),\n                  input: z.unknown(),\n                  output: z.never().optional(),\n                  errorText: z.never().optional(),\n                  callProviderMetadata: providerMetadataSchema.optional(),\n                  approval: z.object({\n                    id: z.string(),\n                    approved: z.literal(false),\n                    descriptor: z.unknown().optional(),\n                    requestReason: z.string().optional(),\n                    reason: z.string().optional(),\n                    isAutomatic: z.boolean().optional(),\n                    signature: z.string().optional(),\n                  }),\n                }),\n              ]),\n            ),\n          })\n          .superRefine((message, context) => {\n            if (message.role !== 'assistant' && message.parts.length === 0) {\n              context.addIssue({\n                origin: 'array',\n                code: 'too_small',\n                minimum: 1,\n                inclusive: true,\n                input: message.parts,\n                path: ['parts'],\n                message: 'Message must contain at least one part',\n              });\n            }\n          }),\n      )\n      .nonempty('Messages array must not be empty'),\n  ),\n);\n\nexport type SafeValidateUIMessagesResult<UI_MESSAGE extends UIMessage> =\n  | {\n      success: true;\n      data: Array<UI_MESSAGE>;\n    }\n  | {\n      success: false;\n      error: Error;\n    };\n\ntype ValidateUIMessagesOptions<UI_MESSAGE extends UIMessage> = {\n  messages: unknown;\n  metadataSchema?: FlexibleSchema<UIMessage['metadata']>;\n  dataSchemas?: {\n    [NAME in keyof InferUIMessageData<UI_MESSAGE> & string]?: FlexibleSchema<\n      InferUIMessageData<UI_MESSAGE>[NAME]\n    >;\n  };\n  tools?: {\n    [NAME in keyof InferUIMessageTools<UI_MESSAGE> & string]?:\n      | Tool<\n          InferUIMessageTools<UI_MESSAGE>[NAME]['input'],\n          InferUIMessageTools<UI_MESSAGE>[NAME]['output']\n        >\n      | {\n          inputSchema: FlexibleSchema<\n            InferUIMessageTools<UI_MESSAGE>[NAME]['input']\n          >;\n          outputSchema?: FlexibleSchema<\n            InferUIMessageTools<UI_MESSAGE>[NAME]['output']\n          >;\n        };\n  };\n};\n\nasync function safeValidateUIMessagesInternal<UI_MESSAGE extends UIMessage>(\n  {\n    messages,\n    metadataSchema,\n    dataSchemas,\n    tools,\n  }: ValidateUIMessagesOptions<UI_MESSAGE>,\n  {\n    convertMissingTerminalToolsToDynamic,\n  }: {\n    convertMissingTerminalToolsToDynamic: boolean;\n  },\n): Promise<SafeValidateUIMessagesResult<UI_MESSAGE>> {\n  try {\n    if (messages == null) {\n      return {\n        success: false,\n        error: new InvalidArgumentError({\n          parameter: 'messages',\n          value: messages,\n          message: 'messages parameter must be provided',\n        }),\n      };\n    }\n\n    const validatedMessages = await validateTypes({\n      value: messages,\n      schema: uiMessagesSchema,\n    });\n\n    warnIfUIMessageHasDeprecatedRawInput(validatedMessages);\n\n    if (metadataSchema) {\n      for (const [msgIdx, message] of validatedMessages.entries()) {\n        await validateTypes({\n          value: message.metadata,\n          schema: metadataSchema,\n          context: {\n            field: `messages[${msgIdx}].metadata`,\n            entityId: message.id,\n          },\n        });\n      }\n    }\n\n    const shouldValidateToolParts =\n      tools != null || convertMissingTerminalToolsToDynamic;\n\n    if (dataSchemas || shouldValidateToolParts) {\n      for (const [msgIdx, message] of validatedMessages.entries()) {\n        for (const [partIdx, part] of message.parts.entries()) {\n          // Data part validation\n          if (dataSchemas && part.type.startsWith('data-')) {\n            const dataPart = part as DataUIPart<InferUIMessageData<UI_MESSAGE>>;\n            const dataName = dataPart.type.slice(5);\n            const dataSchema = dataSchemas[dataName];\n\n            if (!dataSchema) {\n              return {\n                success: false,\n                error: new TypeValidationError({\n                  value: dataPart.data,\n                  cause: `No data schema found for data part ${dataName}`,\n                  context: {\n                    field: `messages[${msgIdx}].parts[${partIdx}].data`,\n                    entityName: dataName,\n                    entityId: dataPart.id,\n                  },\n                }),\n              };\n            }\n\n            await validateTypes({\n              value: dataPart.data,\n              schema: dataSchema,\n              context: {\n                field: `messages[${msgIdx}].parts[${partIdx}].data`,\n                entityName: dataName,\n                entityId: dataPart.id,\n              },\n            });\n          }\n\n          // Tool part validation\n          if (shouldValidateToolParts && part.type.startsWith('tool-')) {\n            const toolPart = part as ToolUIPart<\n              InferUIMessageTools<UI_MESSAGE>\n            >;\n            const toolName = toolPart.type.slice(5);\n            const tool = tools == null ? undefined : getOwn(tools, toolName);\n            const isTerminal =\n              toolPart.state === 'output-available' ||\n              toolPart.state === 'output-error' ||\n              toolPart.state === 'output-denied';\n\n            if (!tool && isTerminal) {\n              if (tools != null || convertMissingTerminalToolsToDynamic) {\n                // Persisted terminal history can reference tools that are no\n                // longer registered. Normalize those parts so callers do not\n                // receive unvalidated values under current static tool types.\n                message.parts[partIdx] = asDynamicToolPart(\n                  toolPart,\n                ) as (typeof message.parts)[number];\n              }\n              continue;\n            }\n\n            // TODO support dynamic tools\n            if (!tool) {\n              return {\n                success: false,\n                error: new TypeValidationError({\n                  value: toolPart.input,\n                  cause: `No tool schema found for tool part ${toolName}`,\n                  context: {\n                    field: `messages[${msgIdx}].parts[${partIdx}].input`,\n                    entityName: toolName,\n                    entityId: toolPart.toolCallId,\n                  },\n                }),\n              };\n            }\n\n            const inputValidationContext = {\n              field: `messages[${msgIdx}].parts[${partIdx}].input`,\n              entityName: toolName,\n              entityId: toolPart.toolCallId,\n            };\n            let convertToDynamic = false;\n\n            // Tool input validation\n            if (toolPart.state === 'output-error') {\n              // Failed calls can retain invalid input. Keep them loadable, but\n              // expose incompatible input as unknown instead of the current\n              // static tool input type.\n              if (toolPart.input !== undefined) {\n                const result = await safeValidateTypes({\n                  value: toolPart.input,\n                  schema: tool.inputSchema,\n                  context: inputValidationContext,\n                });\n                convertToDynamic = !result.success;\n              }\n            } else if (toolPart.state === 'output-available') {\n              const result = await safeValidateTypes({\n                value: toolPart.input,\n                schema: tool.inputSchema,\n                context: inputValidationContext,\n              });\n\n              if (!result.success) {\n                // Empty terminal input can represent aborted or incomplete\n                // history whose input was never streamed. Preserve it without\n                // claiming that it matches the current static input type.\n                if (isEmptyObject(toolPart.input)) {\n                  convertToDynamic = true;\n                } else {\n                  throw result.error;\n                }\n              }\n            } else if (\n              toolPart.state === 'input-available' ||\n              toolPart.state === 'approval-requested' ||\n              toolPart.state === 'approval-responded' ||\n              toolPart.state === 'output-denied'\n            ) {\n              await validateTypes({\n                value: toolPart.input,\n                schema: tool.inputSchema,\n                context: inputValidationContext,\n              });\n            }\n\n            // Tool output validation\n            if (toolPart.state === 'output-available' && tool.outputSchema) {\n              await validateTypes({\n                value: toolPart.output,\n                schema: tool.outputSchema,\n                context: {\n                  field: `messages[${msgIdx}].parts[${partIdx}].output`,\n                  entityName: toolName,\n                  entityId: toolPart.toolCallId,\n                },\n              });\n            }\n\n            if (convertToDynamic) {\n              message.parts[partIdx] = asDynamicToolPart(\n                toolPart,\n              ) as (typeof message.parts)[number];\n            }\n          }\n        }\n      }\n    }\n\n    return {\n      success: true,\n      data: validatedMessages as Array<UI_MESSAGE>,\n    };\n  } catch (error) {\n    const err = error as Error;\n\n    return {\n      success: false,\n      error: err,\n    };\n  }\n}\n\n/**\n * Validates a list of UI messages like `validateUIMessages`,\n * but instead of throwing it returns `{ success: true, data }`\n * or `{ success: false, error }`.\n */\nexport async function safeValidateUIMessages<UI_MESSAGE extends UIMessage>(\n  options: ValidateUIMessagesOptions<UI_MESSAGE>,\n): Promise<SafeValidateUIMessagesResult<UI_MESSAGE>> {\n  return safeValidateUIMessagesInternal(options, {\n    convertMissingTerminalToolsToDynamic: false,\n  });\n}\n\n/**\n * Validates a list of UI messages.\n *\n * Metadata, data parts, and generic tool call structures are only validated if\n * the corresponding schemas are provided. Otherwise, they are assumed to be\n * valid.\n */\nexport async function validateUIMessages<UI_MESSAGE extends UIMessage>(\n  options: ValidateUIMessagesOptions<UI_MESSAGE>,\n): Promise<Array<UI_MESSAGE>> {\n  const response = await safeValidateUIMessages(options);\n\n  if (!response.success) throw response.error;\n\n  return response.data;\n}\n\nexport async function validateUIMessagesForAgent<UI_MESSAGE extends UIMessage>(\n  options: ValidateUIMessagesOptions<UI_MESSAGE>,\n): Promise<Array<UI_MESSAGE>> {\n  const response = await safeValidateUIMessagesInternal(options, {\n    // Agent tool sets can include ephemeral tools (for example, tools from a\n    // disconnected MCP server), so terminal history is converted to dynamic\n    // tool parts when those tools are no longer registered.\n    convertMissingTerminalToolsToDynamic: true,\n  });\n\n  if (!response.success) throw response.error;\n\n  return response.data;\n}\n","import type {\n  Arrayable,\n  Context,\n  Experimental_SandboxSession as SandboxSession,\n  Tool,\n  ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type {\n  GenerateTextOnStepEndCallback,\n  GenerateTextOnStepFinishCallback,\n} from '../generate-text/generate-text-events';\nimport type { Output } from '../generate-text/output';\nimport type { StreamTextTransform } from '../generate-text/stream-text';\nimport type { UIMessageStreamOptions } from '../generate-text/stream-text-result';\nimport type { TimeoutConfiguration } from '../prompt/request-options';\nimport type { InferUIMessageChunk } from '../ui-message-stream';\nimport { toUIMessageStream } from '../ui-message-stream/to-ui-message-stream';\nimport { convertToModelMessages } from '../ui/convert-to-model-messages';\nimport type {\n  InferUIMessageTools,\n  InferUITools,\n  UIMessage,\n} from '../ui/ui-messages';\nimport { validateUIMessagesForAgent } from '../ui/validate-ui-messages';\nimport {\n  createAsyncIterableStream,\n  type AsyncIterableStream,\n} from '../util/async-iterable-stream';\nimport type { Agent } from './agent';\n\n/**\n * Runs the agent and stream the output as a UI message stream.\n *\n * @param agent - The agent to run.\n * @param uiMessages - The input UI messages.\n * @param abortSignal - The abort signal. Optional.\n * @param timeout - Timeout in milliseconds. Optional.\n * @param experimental_sandbox - The sandbox environment that is passed through to tool execution. Optional.\n * @param options - The options for the agent.\n * @param experimental_transform - The stream transformations. Optional.\n * @param onStepEnd - Callback that is called when each step ends. Optional.\n * @param onStepFinish - Deprecated alias for `onStepEnd`. Optional.\n *\n * @returns The UI message stream.\n */\nexport async function createAgentUIStream<\n  CALL_OPTIONS = never,\n  TOOLS extends ToolSet = {},\n  RUNTIME_CONTEXT extends Context = Context,\n  OUTPUT extends Output = never,\n  MESSAGE_METADATA = unknown,\n  UI_MESSAGE extends UIMessage<MESSAGE_METADATA, never, InferUITools<TOOLS>> =\n    UIMessage<MESSAGE_METADATA, never, InferUITools<TOOLS>>,\n>({\n  agent,\n  uiMessages,\n  options,\n  abortSignal,\n  timeout,\n  experimental_sandbox: sandbox,\n  experimental_transform,\n  onStepEnd,\n  onStepFinish,\n  ...uiMessageStreamOptions\n}: {\n  agent: Agent<CALL_OPTIONS, TOOLS, RUNTIME_CONTEXT, OUTPUT>;\n  uiMessages: unknown[];\n  abortSignal?: AbortSignal;\n  timeout?: TimeoutConfiguration<TOOLS>;\n  experimental_sandbox?: SandboxSession;\n  options?: CALL_OPTIONS;\n  experimental_transform?: Arrayable<StreamTextTransform<TOOLS>>;\n  onStepEnd?: GenerateTextOnStepEndCallback<TOOLS>;\n  /** @deprecated Use `onStepEnd` instead. */\n  onStepFinish?: GenerateTextOnStepFinishCallback<TOOLS>;\n  // TODO `originalMessages` is part of this for bc, omit in v7\n} & UIMessageStreamOptions<UI_MESSAGE>): Promise<\n  AsyncIterableStream<InferUIMessageChunk<UI_MESSAGE>>\n> {\n  const validatedMessages = await validateUIMessagesForAgent<UI_MESSAGE>({\n    messages: uiMessages,\n    // tools are compatible; the casting is required because the context param is\n    // not available in ui messages\n    tools: agent.tools as unknown as {\n      [NAME in keyof InferUIMessageTools<UI_MESSAGE> & string]?: Tool<\n        InferUIMessageTools<UI_MESSAGE>[NAME]['input'],\n        InferUIMessageTools<UI_MESSAGE>[NAME]['output']\n      >;\n    },\n  });\n\n  const modelMessages = await convertToModelMessages(validatedMessages, {\n    tools: agent.tools,\n  });\n\n  const result = await agent.stream({\n    prompt: modelMessages,\n    options: options as CALL_OPTIONS,\n    abortSignal,\n    timeout,\n    experimental_sandbox: sandbox,\n    experimental_transform,\n    onStepEnd: onStepEnd ?? onStepFinish,\n  });\n\n  // TODO reading `originalMessages` is here for bc, always use `validatedMessages` in v7\n  const originalMessages =\n    uiMessageStreamOptions.originalMessages ?? validatedMessages;\n\n  return createAsyncIterableStream(\n    toUIMessageStream({\n      ...uiMessageStreamOptions,\n      originalMessages,\n      stream: result.stream,\n      tools: agent.tools,\n    }),\n  );\n}\n","import type {\n  Arrayable,\n  Context,\n  Experimental_SandboxSession as SandboxSession,\n  ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type {\n  GenerateTextOnStepEndCallback,\n  GenerateTextOnStepFinishCallback,\n} from '../generate-text/generate-text-events';\nimport type { Output } from '../generate-text/output';\nimport type { StreamTextTransform } from '../generate-text/stream-text';\nimport type { UIMessageStreamOptions } from '../generate-text/stream-text-result';\nimport type { TimeoutConfiguration } from '../prompt/request-options';\nimport { createUIMessageStreamResponse } from '../ui-message-stream';\nimport type { UIMessageStreamResponseInit } from '../ui-message-stream/ui-message-stream-response-init';\nimport type { InferUITools, UIMessage } from '../ui/ui-messages';\nimport type { Agent } from './agent';\nimport { createAgentUIStream } from './create-agent-ui-stream';\n\n/**\n * Runs the agent and returns a response object with a UI message stream.\n *\n * @param agent - The agent to run.\n * @param uiMessages - The input UI messages.\n * @param abortSignal - Abort signal. Optional.\n * @param timeout - Timeout in milliseconds. Optional.\n * @param experimental_sandbox - The sandbox environment that is passed through to tool execution. Optional.\n * @param options - The options for the agent. Optional.\n * @param experimental_transform - Stream transformations. Optional.\n * @param onStepEnd - Callback that is called when each step ends. Optional.\n * @param onStepFinish - Deprecated alias for `onStepEnd`. Optional.\n * @param headers - Additional headers for the response. Optional.\n * @param status - The status code for the response. Optional.\n * @param statusText - The status text for the response. Optional.\n * @param consumeSseStream - Whether to consume the SSE stream. Optional.\n *\n * @returns The response object.\n */\nexport async function createAgentUIStreamResponse<\n  CALL_OPTIONS = never,\n  TOOLS extends ToolSet = {},\n  RUNTIME_CONTEXT extends Context = Context,\n  OUTPUT extends Output = never,\n  MESSAGE_METADATA = unknown,\n>({\n  headers,\n  status,\n  statusText,\n  consumeSseStream,\n  ...options\n}: {\n  agent: Agent<CALL_OPTIONS, TOOLS, RUNTIME_CONTEXT, OUTPUT>;\n  uiMessages: unknown[];\n  abortSignal?: AbortSignal;\n  timeout?: TimeoutConfiguration<TOOLS>;\n  experimental_sandbox?: SandboxSession;\n  options?: CALL_OPTIONS;\n  experimental_transform?: Arrayable<StreamTextTransform<TOOLS>>;\n  onStepEnd?: GenerateTextOnStepEndCallback<TOOLS>;\n  /** @deprecated Use `onStepEnd` instead. */\n  onStepFinish?: GenerateTextOnStepFinishCallback<TOOLS>;\n} & UIMessageStreamResponseInit &\n  UIMessageStreamOptions<\n    UIMessage<MESSAGE_METADATA, never, InferUITools<TOOLS>>\n  >): Promise<Response> {\n  return createUIMessageStreamResponse({\n    headers,\n    status,\n    statusText,\n    consumeSseStream,\n    stream: await createAgentUIStream(options),\n  });\n}\n","import type {\n  Arrayable,\n  Context,\n  Experimental_SandboxSession as SandboxSession,\n  ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type { ServerResponse } from 'node:http';\nimport type {\n  GenerateTextOnStepEndCallback,\n  GenerateTextOnStepFinishCallback,\n} from '../generate-text/generate-text-events';\nimport type { Output } from '../generate-text/output';\nimport type { StreamTextTransform } from '../generate-text/stream-text';\nimport type { UIMessageStreamOptions } from '../generate-text/stream-text-result';\nimport type { TimeoutConfiguration } from '../prompt/request-options';\nimport { pipeUIMessageStreamToResponse } from '../ui-message-stream';\nimport type { UIMessageStreamResponseInit } from '../ui-message-stream/ui-message-stream-response-init';\nimport type { InferUITools, UIMessage } from '../ui/ui-messages';\nimport type { Agent } from './agent';\nimport { createAgentUIStream } from './create-agent-ui-stream';\n\n/**\n * Pipes the agent UI message stream to a Node.js ServerResponse object.\n *\n * @param response - The Node.js ServerResponse object to pipe to.\n * @param agent - The agent to run.\n * @param uiMessages - The input UI messages.\n * @param abortSignal - Abort signal. Optional.\n * @param timeout - Timeout in milliseconds. Optional.\n * @param experimental_sandbox - The sandbox environment that is passed through to tool execution. Optional.\n * @param options - The options for the agent. Optional.\n * @param experimental_transform - Stream transformations. Optional.\n * @param onStepEnd - Callback that is called when each step ends. Optional.\n * @param onStepFinish - Deprecated alias for `onStepEnd`. Optional.\n * @param headers - Additional headers for the response. Optional.\n * @param status - The status code for the response. Optional.\n * @param statusText - The status text for the response. Optional.\n * @param consumeSseStream - Whether to consume the SSE stream. Optional.\n */\nexport async function pipeAgentUIStreamToResponse<\n  CALL_OPTIONS = never,\n  TOOLS extends ToolSet = {},\n  RUNTIME_CONTEXT extends Context = Context,\n  OUTPUT extends Output = never,\n  MESSAGE_METADATA = unknown,\n>({\n  response,\n  headers,\n  status,\n  statusText,\n  consumeSseStream,\n  ...options\n}: {\n  response: ServerResponse;\n  agent: Agent<CALL_OPTIONS, TOOLS, RUNTIME_CONTEXT, OUTPUT>;\n  uiMessages: unknown[];\n  abortSignal?: AbortSignal;\n  timeout?: TimeoutConfiguration<TOOLS>;\n  experimental_sandbox?: SandboxSession;\n  options?: CALL_OPTIONS;\n  experimental_transform?: Arrayable<StreamTextTransform<TOOLS>>;\n  onStepEnd?: GenerateTextOnStepEndCallback<TOOLS>;\n  /** @deprecated Use `onStepEnd` instead. */\n  onStepFinish?: GenerateTextOnStepFinishCallback<TOOLS>;\n} & UIMessageStreamResponseInit &\n  UIMessageStreamOptions<\n    UIMessage<MESSAGE_METADATA, never, InferUITools<TOOLS>>\n  >): Promise<void> {\n  return pipeUIMessageStreamToResponse({\n    response,\n    headers,\n    status,\n    statusText,\n    consumeSseStream,\n    stream: await createAgentUIStream(options),\n  });\n}\n","import {\n  UnsupportedFunctionalityError,\n  type Experimental_BatchV4 as BatchV4,\n  type Experimental_BatchV4ItemResult as BatchV4ItemResult,\n  type LanguageModelV4GenerateResult,\n  type LanguageModelV4ToolCall,\n  type ImageModelV4Result,\n  type ProviderV4,\n} from '@ai-sdk/provider';\nimport { gateway } from '@ai-sdk/gateway';\nimport {\n  detectMediaType,\n  type ToolSet,\n  withUserAgentSuffix,\n} from '@ai-sdk/provider-utils';\nimport { InvalidArgumentError } from '../error/invalid-argument-error';\nimport { convertLanguageModelContent } from '../generate-text/convert-language-model-content';\nimport {\n  getImageProviderMetadata,\n  normalizePrompt as normalizeImagePrompt,\n} from '../generate-image/generate-image';\nimport { DefaultGeneratedFile } from '../generate-text/generated-file';\nimport { parseToolCall } from '../generate-text/parse-tool-call';\nimport { prepareToolChoice } from '../prompt/prepare-tool-choice';\nimport { prepareTools } from '../prompt/prepare-tools';\nimport { logWarnings } from '../logger/log-warnings';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { prepareLanguageModelCallOptions } from '../prompt/prepare-language-model-call-options';\nimport { getTotalTimeoutMs } from '../prompt/request-options';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport { wrapGatewayError } from '../prompt/wrap-gateway-error';\nimport { asLanguageModelUsage } from '../types/usage';\nimport { asAsyncIterableStream } from '../util/async-iterable-stream';\nimport { mergeAbortSignals } from '../util/merge-abort-signals';\nimport { isDeepEqualData } from '../util/is-deep-equal-data';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\nimport { asProviderV4 } from '../model/as-provider-v4';\nimport type {\n  BatchItemResult,\n  BatchProvider,\n  BatchReference,\n  BatchStatus,\n  CancelBatchOptions,\n  CancelBatchResult,\n  GetBatchResultsOptions,\n  GetBatchStatusOptions,\n  ListBatchesOptions,\n  ListBatchesResult,\n  StartBatchOptions,\n  StartBatchResult,\n  TextBatchGenerationResult,\n  ImageBatchGenerationResult,\n} from './batch-types';\n\n/**\n * Requests cancellation of a batch.\n */\nexport async function cancelBatch({\n  provider,\n  batch,\n  providerOptions,\n  abortSignal,\n  headers,\n  timeout,\n}: CancelBatchOptions): Promise<CancelBatchResult> {\n  const batchApi = resolveBatchApi(provider);\n  validateBatchReference({ batchApi, batch });\n\n  if (batchApi.doCancelBatch == null) {\n    throw new UnsupportedFunctionalityError({\n      functionality: 'batch cancellation',\n      message: 'The provider does not support batch cancellation.',\n    });\n  }\n\n  const operationAbortSignal = mergeAbortSignals(\n    abortSignal,\n    getTotalTimeoutMs(timeout),\n  );\n\n  try {\n    return await batchApi.doCancelBatch({\n      batchId: batch.id,\n      providerOptions,\n      abortSignal: operationAbortSignal,\n      headers: withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`),\n    });\n  } catch (error) {\n    throw wrapGatewayError(error);\n  }\n}\n\n/**\n * Lists a page of batches.\n */\nexport async function listBatches({\n  provider,\n  providerOptions,\n  limit,\n  cursor,\n  maxRetries,\n  abortSignal,\n  headers,\n  timeout,\n}: ListBatchesOptions = {}): Promise<ListBatchesResult> {\n  const batchApi = resolveBatchApi(provider);\n\n  const doListBatches = batchApi.doListBatches?.bind(batchApi);\n  if (doListBatches == null) {\n    throw new UnsupportedFunctionalityError({\n      functionality: 'batch listing',\n      message: 'The provider does not support listing batches.',\n    });\n  }\n\n  const operationAbortSignal = mergeAbortSignals(\n    abortSignal,\n    getTotalTimeoutMs(timeout),\n  );\n  const { retry } = prepareRetries({\n    maxRetries,\n    abortSignal: operationAbortSignal,\n  });\n\n  try {\n    const { batches, nextCursor, providerMetadata } = await retry(() =>\n      doListBatches({\n        providerOptions,\n        abortSignal: operationAbortSignal,\n        headers: withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`),\n        ...(limit != null && { limit }),\n        ...(cursor != null && { cursor }),\n      }),\n    );\n\n    return {\n      batches: batches.map(({ batchId, ...status }) => ({\n        version: 2,\n        id: batchId,\n        provider: batchApi.provider,\n        ...status,\n      })),\n      ...(nextCursor != null && { nextCursor }),\n      ...(providerMetadata != null && { providerMetadata }),\n    };\n  } catch (error) {\n    throw wrapGatewayError(error);\n  }\n}\n\n/**\n * Starts a batch.\n */\nexport async function startBatch<\n  TOOLS extends ToolSet,\n  PROVIDER extends BatchProvider,\n>({\n  provider,\n  requests,\n  providerOptions,\n  webhookUrl,\n  abortSignal,\n  headers,\n  timeout,\n}: StartBatchOptions<TOOLS, PROVIDER>): Promise<StartBatchResult> {\n  validateRequests(requests);\n\n  const batchApi = resolveBatchApi(provider);\n  const operationAbortSignal = mergeAbortSignals(\n    abortSignal,\n    getTotalTimeoutMs(timeout),\n  );\n  const supportedUrls = await batchApi.supportedUrls;\n  operationAbortSignal?.throwIfAborted();\n  const normalizedRequests = [];\n  const toolsByName = new Map<string, unknown>();\n\n  for (const request of requests) {\n    const requestType = request.type;\n    switch (requestType) {\n      case 'text': {\n        const standardizedPrompt = await standardizePrompt(request);\n        const preparedTools = await prepareTools({\n          tools: request.tools,\n          toolOrder: request.toolOrder,\n          toolsContext: request.toolsContext,\n        });\n        validateCompatibleTools({\n          requestId: request.id,\n          tools: preparedTools,\n          toolsByName,\n        });\n\n        normalizedRequests.push({\n          id: request.id,\n          type: request.type,\n          modelId: request.model,\n          options: {\n            ...prepareLanguageModelCallOptions(request),\n            prompt: await convertToLanguageModelPrompt({\n              prompt: standardizedPrompt,\n              supportedUrls,\n              download: undefined,\n              provider: batchApi.provider.split('.')[0],\n            }),\n            tools: preparedTools,\n            toolChoice: prepareToolChoice({ toolChoice: request.toolChoice }),\n            providerOptions: request.providerOptions,\n          },\n        });\n        break;\n      }\n      case 'image': {\n        const { prompt, files, mask } = normalizeImagePrompt(request.prompt);\n        normalizedRequests.push({\n          id: request.id,\n          type: request.type,\n          modelId: request.model,\n          options: {\n            prompt,\n            n: request.n ?? 1,\n            size: request.size,\n            aspectRatio: request.aspectRatio,\n            seed: request.seed,\n            files,\n            mask,\n            providerOptions: request.providerOptions ?? {},\n          },\n        });\n        break;\n      }\n      default: {\n        const _exhaustiveCheck: never = requestType;\n        throw new InvalidArgumentError({\n          parameter: 'requests',\n          value: _exhaustiveCheck,\n          message: `Unsupported batch request type \"${_exhaustiveCheck}\".`,\n        });\n      }\n    }\n    operationAbortSignal?.throwIfAborted();\n  }\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n  try {\n    const result = await batchApi.doStartBatch({\n      requests: normalizedRequests,\n      providerOptions,\n      abortSignal: operationAbortSignal,\n      headers: headersWithUserAgent,\n      ...(webhookUrl != null && { webhookUrl }),\n    });\n    const { batchId, warnings, ...status } = result;\n\n    const modelByRequestId = new Map(\n      normalizedRequests.map(request => [request.id, request.modelId]),\n    );\n    for (const { requestId, warning } of warnings) {\n      logWarnings({\n        warnings: [warning],\n        provider: batchApi.provider,\n        model: requestId == null ? undefined : modelByRequestId.get(requestId),\n      });\n    }\n\n    return {\n      version: 2,\n      id: batchId,\n      provider: batchApi.provider,\n      ...status,\n      warnings,\n    };\n  } catch (error) {\n    throw wrapGatewayError(error);\n  }\n}\n\nfunction validateCompatibleTools({\n  requestId,\n  tools,\n  toolsByName,\n}: {\n  requestId: string;\n  tools: ReadonlyArray<{ name: string }> | undefined;\n  toolsByName: Map<string, unknown>;\n}) {\n  for (const tool of tools ?? []) {\n    const previousTool = toolsByName.get(tool.name);\n\n    if (previousTool != null && !isDeepEqualData(previousTool, tool)) {\n      throw new InvalidArgumentError({\n        parameter: 'requests',\n        value: requestId,\n        message: `tool \"${tool.name}\" must have the same definition in every batch request`,\n      });\n    }\n\n    toolsByName.set(tool.name, tool);\n  }\n}\n\n/**\n * Retrieves the latest normalized status for a batch.\n */\nexport async function getBatchStatus({\n  provider,\n  batch,\n  providerOptions,\n  maxRetries,\n  abortSignal,\n  headers,\n  timeout,\n}: GetBatchStatusOptions): Promise<BatchStatus> {\n  const batchApi = resolveBatchApi(provider);\n  validateBatchReference({ batchApi, batch });\n\n  const operationAbortSignal = mergeAbortSignals(\n    abortSignal,\n    getTotalTimeoutMs(timeout),\n  );\n  const { retry } = prepareRetries({\n    maxRetries,\n    abortSignal: operationAbortSignal,\n  });\n\n  try {\n    const status = await retry(() =>\n      batchApi.doGetBatchStatus({\n        batchId: batch.id,\n        providerOptions,\n        abortSignal: operationAbortSignal,\n        headers: withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`),\n      }),\n    );\n\n    return status;\n  } catch (error) {\n    throw wrapGatewayError(error);\n  }\n}\n\n/**\n * Streams complete terminal results for the requests in a batch.\n */\nexport function getBatchResults<TOOLS extends ToolSet>({\n  provider,\n  batch,\n  tools,\n  providerOptions,\n  maxRetries,\n  abortSignal,\n  headers,\n  timeout,\n}: GetBatchResultsOptions<TOOLS>) {\n  const batchApi = resolveBatchApi(provider);\n  validateBatchReference({ batchApi, batch });\n\n  const streamAbortController = new AbortController();\n  const operationAbortSignal = mergeAbortSignals(\n    abortSignal,\n    getTotalTimeoutMs(timeout),\n    streamAbortController.signal,\n  );\n  const { retry } = prepareRetries({\n    maxRetries,\n    abortSignal: operationAbortSignal,\n  });\n  const transformer: Transformer<BatchV4ItemResult, BatchItemResult<TOOLS>> & {\n    cancel?: (reason?: unknown) => void;\n  } = {\n    async transform(item, controller) {\n      controller.enqueue(await convertBatchItemResult({ item, tools }));\n    },\n\n    cancel(reason) {\n      streamAbortController.abort(\n        reason ?? new Error('Batch results stream was cancelled.'),\n      );\n    },\n  };\n  const transform = new TransformStream<\n    BatchV4ItemResult,\n    BatchItemResult<TOOLS>\n  >(transformer);\n\n  void (async () => {\n    try {\n      const stream = await retry(() =>\n        batchApi.doGetBatchResults({\n          batchId: batch.id,\n          providerOptions,\n          abortSignal: operationAbortSignal,\n          headers: withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`),\n        }),\n      );\n\n      await stream.pipeTo(transform.writable, {\n        signal: operationAbortSignal,\n      });\n    } catch (error) {\n      await transform.writable.abort(wrapGatewayError(error)).catch(() => {});\n    }\n  })();\n\n  return asAsyncIterableStream(transform.readable);\n}\n\nfunction resolveBatchApi(provider?: BatchProvider): BatchV4 {\n  provider ??= asProviderV4(globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway);\n\n  if (isBatchApi(provider)) {\n    return provider;\n  }\n\n  if (!hasBatchFactory(provider)) {\n    throw new UnsupportedFunctionalityError({\n      functionality: 'batch processing',\n      message:\n        'The provider does not support batch processing. Make sure it exposes an experimental_batch() method.',\n    });\n  }\n\n  return provider.experimental_batch();\n}\n\nfunction hasBatchFactory(\n  provider: ProviderV4,\n): provider is ProviderV4 & { experimental_batch(): BatchV4 } {\n  return (\n    typeof (provider as { experimental_batch?: unknown }).experimental_batch ===\n    'function'\n  );\n}\n\nfunction isBatchApi(provider: BatchProvider): provider is BatchV4 {\n  const candidate = provider as Partial<BatchV4>;\n  return (\n    typeof candidate.doStartBatch === 'function' &&\n    typeof candidate.doGetBatchStatus === 'function' &&\n    typeof candidate.doGetBatchResults === 'function'\n  );\n}\n\nfunction validateRequests(requests: ReadonlyArray<{ readonly id: string }>) {\n  if (requests.length === 0) {\n    throw new InvalidArgumentError({\n      parameter: 'requests',\n      value: requests,\n      message: 'requests must not be empty',\n    });\n  }\n\n  const ids = new Set<string>();\n\n  for (const request of requests) {\n    if (request.id.trim().length === 0) {\n      throw new InvalidArgumentError({\n        parameter: 'requests',\n        value: requests,\n        message: 'request IDs must not be empty',\n      });\n    }\n\n    if (ids.has(request.id)) {\n      throw new InvalidArgumentError({\n        parameter: 'requests',\n        value: requests,\n        message: `request IDs must be unique; duplicate ID \"${request.id}\"`,\n      });\n    }\n\n    ids.add(request.id);\n  }\n}\n\nfunction validateBatchReference({\n  batchApi,\n  batch,\n}: {\n  batchApi: BatchV4;\n  batch: BatchReference;\n}) {\n  if (batch.version !== 2) {\n    throw new InvalidArgumentError({\n      parameter: 'batch',\n      value: batch,\n      message: 'batch must be a supported batch reference',\n    });\n  }\n\n  if (batch.provider !== batchApi.provider) {\n    throw new InvalidArgumentError({\n      parameter: 'provider',\n      value: batchApi,\n      message:\n        `provider ${batchApi.provider} is not compatible with ` +\n        `batch provider ${batch.provider}`,\n    });\n  }\n}\n\nasync function convertBatchItemResult<TOOLS extends ToolSet>({\n  item,\n  tools,\n}: {\n  item: BatchV4ItemResult;\n  tools: TOOLS | undefined;\n}): Promise<BatchItemResult<TOOLS>> {\n  switch (item.type) {\n    case 'text':\n      switch (item.status) {\n        case 'succeeded':\n          return {\n            type: item.type,\n            id: item.id,\n            status: item.status,\n            ...(await convertGenerateResult({ result: item.result, tools })),\n          };\n        case 'failed':\n          return {\n            type: item.type,\n            id: item.id,\n            status: item.status,\n            error: item.error,\n            providerMetadata: item.providerMetadata,\n          };\n        case 'cancelled':\n        case 'expired':\n          return {\n            type: item.type,\n            id: item.id,\n            status: item.status,\n            error: item.error,\n            providerMetadata: item.providerMetadata,\n          };\n      }\n    case 'image':\n      switch (item.status) {\n        case 'succeeded':\n          return {\n            type: item.type,\n            id: item.id,\n            status: item.status,\n            ...convertImageResult(item.result),\n          };\n        case 'failed':\n          return {\n            type: item.type,\n            id: item.id,\n            status: item.status,\n            error: item.error,\n            providerMetadata: item.providerMetadata,\n          };\n        case 'cancelled':\n        case 'expired':\n          return {\n            type: item.type,\n            id: item.id,\n            status: item.status,\n            error: item.error,\n            providerMetadata: item.providerMetadata,\n          };\n      }\n  }\n}\n\nfunction convertImageResult(\n  result: ImageModelV4Result,\n): ImageBatchGenerationResult {\n  return {\n    images: result.images.map(\n      (image, index) =>\n        new DefaultGeneratedFile({\n          data: image,\n          mediaType:\n            detectMediaType({ data: image, topLevelType: 'image' }) ??\n            'image/png',\n          providerMetadata: getImageProviderMetadata(\n            result.providerMetadata,\n            index,\n          ),\n        }),\n    ),\n    warnings: result.warnings,\n    response: {\n      timestamp: result.response.timestamp,\n      modelId: result.response.modelId,\n      headers: result.response.headers,\n    },\n    providerMetadata: result.providerMetadata,\n    usage: result.usage,\n  };\n}\n\nasync function convertGenerateResult<TOOLS extends ToolSet>({\n  result,\n  tools,\n}: {\n  result: LanguageModelV4GenerateResult;\n  tools: TOOLS | undefined;\n}): Promise<TextBatchGenerationResult<TOOLS>> {\n  const toolCalls = await Promise.all(\n    result.content\n      .filter(\n        (part): part is LanguageModelV4ToolCall => part.type === 'tool-call',\n      )\n      .map(toolCall =>\n        parseToolCall<TOOLS>({\n          toolCall,\n          tools,\n          repairToolCall: undefined,\n          refineToolInput: undefined,\n          instructions: undefined,\n          messages: [],\n        }),\n      ),\n  );\n  const content = convertLanguageModelContent<TOOLS>({\n    content: result.content,\n    toolCalls,\n    toolOutputs: [],\n    toolApprovalRequests: [],\n    toolApprovalResponses: [],\n    tools,\n  });\n\n  return {\n    content,\n    text: result.content\n      .filter(\n        (part): part is Extract<typeof part, { type: 'text' }> =>\n          part.type === 'text',\n      )\n      .map(part => part.text)\n      .join(''),\n    finishReason: result.finishReason.unified,\n    rawFinishReason: result.finishReason.raw,\n    usage: asLanguageModelUsage(result.usage),\n    ...(result.response != null\n      ? {\n          response: {\n            id: result.response.id,\n            timestamp: result.response.timestamp?.toISOString(),\n            modelId: result.response.modelId,\n          },\n        }\n      : {}),\n    providerMetadata: result.providerMetadata,\n  };\n}\n","import {\n  isJSONObject,\n  type ImageModelV4,\n  type ImageModelV4CallOptions,\n  type ImageModelV4File,\n  type ImageModelV4ProviderMetadata,\n  type ImageModelV4Result,\n  type JSONObject,\n} from '@ai-sdk/provider';\nimport {\n  convertBase64ToUint8Array,\n  detectMediaType,\n  withUserAgentSuffix,\n  type DataContent,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { NoImageGeneratedError } from '../error/no-image-generated-error';\nimport {\n  DefaultGeneratedFile,\n  type GeneratedFile,\n} from '../generate-text/generated-file';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveImageModel } from '../model/resolve-model';\nimport type { ImageModel } from '../types/image-model';\nimport type { ImageModelResponseMetadata } from '../types/image-model-response-metadata';\nimport { addImageModelUsage, type ImageModelUsage } from '../types/usage';\nimport type { Warning } from '../types/warning';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { RetryError } from '../util/retry-error';\nimport { VERSION } from '../version';\nimport type {\n  GenerateImageCall,\n  GenerateImageResult,\n} from './generate-image-result';\nimport { convertDataContentToUint8Array } from '../prompt/data-content';\nimport { splitDataUrl } from '../prompt/split-data-url';\n\nconst gatewayCostMetadataKeys = [\n  'cost',\n  'gatewayCost',\n  'inferenceCost',\n  'inputInferenceCost',\n  'marketCost',\n  'outputInferenceCost',\n  'surchargeCost',\n] as const;\n\ntype GatewayCostMetadata = {\n  [key in (typeof gatewayCostMetadataKeys)[number]]?: unknown;\n};\n\nclass RetryableNoImageResultError extends Error {\n  constructor() {\n    super('No image generated.');\n    this.name = 'RetryableNoImageResultError';\n  }\n}\n\nexport type GenerateImagePrompt =\n  | string\n  | {\n      images: Array<DataContent>;\n      text?: string;\n      mask?: DataContent;\n    };\n\n/**\n * Generates images using an image model.\n *\n * @param model - The image model to use.\n * @param prompt - The prompt that should be used to generate the image.\n * @param n - Number of images to generate. Default: 1.\n * @param maxImagesPerCall - Maximum number of images to generate in a single API call.\n * @param size - Size of the images to generate. Must have the format `{width}x{height}`.\n * @param aspectRatio - Aspect ratio of the images to generate. Must have the format `{width}:{height}`.\n * @param seed - Seed for the image generation.\n * @param providerOptions - Additional provider-specific options that are passed through to the provider\n * as body parameters.\n * @param maxRetries - Maximum number of retries per image model call, including retries after unclassified empty responses. Empty responses marked as not retryable by the provider are not retried. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @returns A result object that contains the generated images.\n */\nexport async function generateImage({\n  model: modelArg,\n  prompt: promptArg,\n  n = 1,\n  maxImagesPerCall,\n  size,\n  aspectRatio,\n  seed,\n  providerOptions,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n}: {\n  /**\n   * The image model to use.\n   */\n  model: ImageModel;\n\n  /**\n   * The prompt that should be used to generate the image.\n   */\n  prompt: GenerateImagePrompt;\n\n  /**\n   * Number of images to generate.\n   */\n  n?: number;\n\n  /**\n   * Maximum number of images to generate in a single API call. If not provided, the model's default will be used.\n   */\n  maxImagesPerCall?: number;\n\n  /**\n   * Size of the images to generate. Must have the format `{width}x{height}`. If not provided, the default size will be used.\n   */\n  size?: `${number}x${number}`;\n\n  /**\n   * Aspect ratio of the images to generate. Must have the format `{width}:{height}`. If not provided, the default aspect ratio will be used.\n   */\n  aspectRatio?: `${number}:${number}`;\n\n  /**\n   * Seed for the image generation. If not provided, the default seed will be used.\n   */\n  seed?: number;\n\n  /**\n   * Additional provider-specific options that are passed through to the provider\n   * as body parameters.\n   *\n   * The outer record is keyed by the provider name, and the inner\n   * record is keyed by the provider-specific metadata key.\n   * ```ts\n   * {\n   * \"openai\": {\n   * \"style\": \"vivid\"\n   * }\n   * }\n   * ```\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Maximum number of retries per image model call, including retries after\n   * unclassified empty responses. Empty responses marked as not retryable by\n   * the provider are not retried. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n}): Promise<GenerateImageResult> {\n  const model = resolveImageModel(modelArg);\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n    additionalRetryableError: error =>\n      error instanceof RetryableNoImageResultError,\n  });\n\n  // default to 1 if the model has not specified limits on\n  // how many images can be generated in a single call\n  const maxImagesPerCallWithDefault =\n    maxImagesPerCall ?? (await invokeModelMaxImagesPerCall(model)) ?? 1;\n\n  // parallelize calls to the model:\n  const callCount = Math.ceil(n / maxImagesPerCallWithDefault);\n  const callImageCounts = Array.from({ length: callCount }, (_, i) => {\n    if (i < callCount - 1) {\n      return maxImagesPerCallWithDefault;\n    }\n\n    const remainder = n % maxImagesPerCallWithDefault;\n    return remainder === 0 ? maxImagesPerCallWithDefault : remainder;\n  });\n\n  const resultGroups = await Promise.all(\n    callImageCounts.map(async callImageCount => {\n      const callResults: Array<ImageModelV4Result> = [];\n\n      try {\n        await retry(async () => {\n          const { prompt, files, mask } = normalizePrompt(promptArg);\n\n          const result = await model.doGenerate({\n            prompt,\n            files,\n            mask,\n            n: callImageCount,\n            abortSignal,\n            headers: headersWithUserAgent,\n            size,\n            aspectRatio,\n            seed,\n            providerOptions: providerOptions ?? {},\n          });\n\n          callResults.push(result);\n\n          if (result.images.length === 0 && result.isRetryable !== false) {\n            throw new RetryableNoImageResultError();\n          }\n\n          return result;\n        });\n\n        return callResults;\n      } catch (error) {\n        const noImageResultError =\n          error instanceof RetryableNoImageResultError\n            ? error\n            : RetryError.isInstance(error) &&\n                error.lastError instanceof RetryableNoImageResultError\n              ? error.lastError\n              : undefined;\n\n        if (noImageResultError != null) {\n          return callResults;\n        }\n\n        throw error;\n      }\n    }),\n  );\n  const results = resultGroups.flat();\n\n  // collect result images, warnings, and response metadata\n  const images: Array<GeneratedFile> = [];\n  const calls: Array<GenerateImageCall> = [];\n  const warnings: Array<Warning> = [];\n  const responses: Array<ImageModelResponseMetadata> = [];\n  const providerMetadata: ImageModelV4ProviderMetadata = {};\n  let totalUsage: ImageModelUsage = {\n    inputTokens: undefined,\n    outputTokens: undefined,\n    totalTokens: undefined,\n  };\n  for (const result of results) {\n    const callImages = result.images.map(\n      (image, index) =>\n        new DefaultGeneratedFile({\n          data: image,\n          mediaType:\n            detectMediaType({\n              data: image,\n              topLevelType: 'image',\n            }) ?? 'image/png',\n          providerMetadata: getImageProviderMetadata(\n            result.providerMetadata,\n            index,\n          ),\n        }),\n    );\n    images.push(...callImages);\n    calls.push({\n      images: callImages,\n      providerMetadata: result.providerMetadata,\n      response: result.response,\n      warnings: result.warnings,\n      usage: result.usage,\n    });\n    warnings.push(...result.warnings);\n\n    if (result.usage != null) {\n      totalUsage = addImageModelUsage(totalUsage, result.usage);\n    }\n\n    if (result.providerMetadata) {\n      for (const [providerName, metadata] of Object.entries(\n        result.providerMetadata,\n      )) {\n        if (providerName === 'gateway') {\n          const currentEntry = providerMetadata[providerName];\n          if (currentEntry != null && typeof currentEntry === 'object') {\n            const currentGatewayMetadata = currentEntry as GatewayCostMetadata;\n            const newGatewayMetadata = metadata as GatewayCostMetadata;\n\n            providerMetadata[providerName] = {\n              ...(currentEntry as object),\n              ...(metadata as object),\n              ...Object.fromEntries(\n                gatewayCostMetadataKeys.flatMap(key => {\n                  const total = addDecimalStrings(\n                    currentGatewayMetadata[key],\n                    newGatewayMetadata[key],\n                  );\n\n                  return total == null ? [] : [[key, total]];\n                }),\n              ),\n            } as ImageModelV4ProviderMetadata[string];\n          } else {\n            providerMetadata[providerName] = {\n              ...(metadata as object),\n            } as ImageModelV4ProviderMetadata[string];\n          }\n          const imagesValue = (\n            providerMetadata[providerName] as { images?: unknown }\n          ).images;\n          if (Array.isArray(imagesValue) && imagesValue.length === 0) {\n            delete (providerMetadata[providerName] as { images?: unknown })\n              .images;\n          }\n        } else {\n          providerMetadata[providerName] ??= { images: [] };\n          providerMetadata[providerName].images.push(...metadata.images);\n        }\n      }\n    }\n\n    responses.push(result.response);\n  }\n\n  logWarnings({ warnings, provider: model.provider, model: model.modelId });\n\n  if (!images.length) {\n    throw new NoImageGeneratedError({ calls, responses });\n  }\n\n  return new DefaultGenerateImageResult({\n    images,\n    calls,\n    warnings,\n    responses,\n    providerMetadata,\n    usage: totalUsage,\n  });\n}\n\nclass DefaultGenerateImageResult implements GenerateImageResult {\n  readonly images: Array<GeneratedFile>;\n  readonly calls: Array<GenerateImageCall>;\n  readonly warnings: Array<Warning>;\n  readonly responses: Array<ImageModelResponseMetadata>;\n  readonly providerMetadata: ImageModelV4ProviderMetadata;\n  readonly usage: ImageModelUsage;\n\n  constructor(options: {\n    images: Array<GeneratedFile>;\n    calls: Array<GenerateImageCall>;\n    warnings: Array<Warning>;\n    responses: Array<ImageModelResponseMetadata>;\n    providerMetadata: ImageModelV4ProviderMetadata;\n    usage: ImageModelUsage;\n  }) {\n    this.images = options.images;\n    this.calls = options.calls;\n    this.warnings = options.warnings;\n    this.responses = options.responses;\n    this.providerMetadata = options.providerMetadata;\n    this.usage = options.usage;\n  }\n\n  get image() {\n    return this.images[0];\n  }\n}\n\n/**\n * Extracts per-image metadata from the legacy `providerMetadata.<provider>.images` result shape.\n */\nexport function getImageProviderMetadata(\n  providerMetadata: ImageModelV4ProviderMetadata | undefined,\n  imageIndex: number,\n): Record<string, JSONObject> | undefined {\n  if (providerMetadata == null) {\n    return undefined;\n  }\n\n  let imageMetadata: Record<string, JSONObject> | undefined;\n\n  for (const [providerName, metadata] of Object.entries(providerMetadata)) {\n    const value = metadata.images?.[imageIndex];\n\n    if (isJSONObject(value) && !Array.isArray(value)) {\n      (imageMetadata ??= {})[providerName] = value;\n    }\n  }\n\n  return imageMetadata;\n}\n\nasync function invokeModelMaxImagesPerCall(model: ImageModelV4) {\n  const isFunction = model.maxImagesPerCall instanceof Function;\n\n  if (!isFunction) {\n    return model.maxImagesPerCall;\n  }\n\n  return model.maxImagesPerCall({\n    modelId: model.modelId,\n  });\n}\n\nfunction addDecimalStrings(\n  value1: unknown,\n  value2: unknown,\n): string | undefined {\n  if (\n    typeof value1 !== 'string' ||\n    typeof value2 !== 'string' ||\n    !/^\\d+(?:\\.\\d+)?$/.test(value1) ||\n    !/^\\d+(?:\\.\\d+)?$/.test(value2)\n  ) {\n    return undefined;\n  }\n\n  const [integer1, fraction1 = ''] = value1.split('.');\n  const [integer2, fraction2 = ''] = value2.split('.');\n  const precision = Math.max(fraction1.length, fraction2.length);\n  const sum =\n    BigInt(integer1 + fraction1.padEnd(precision, '0')) +\n    BigInt(integer2 + fraction2.padEnd(precision, '0'));\n  const sumString = sum.toString().padStart(precision + 1, '0');\n\n  return precision === 0\n    ? sumString\n    : `${sumString.slice(0, -precision)}.${sumString.slice(\n        -precision,\n      )}`.replace(/\\.?0+$/, '');\n}\n\nexport function normalizePrompt(\n  prompt: GenerateImagePrompt,\n): Pick<ImageModelV4CallOptions, 'prompt' | 'files' | 'mask'> {\n  if (typeof prompt === 'string') {\n    return { prompt, files: undefined, mask: undefined };\n  }\n\n  return {\n    prompt: prompt.text,\n    files: prompt.images.map(toImageModelV4File),\n    mask: prompt.mask ? toImageModelV4File(prompt.mask) : undefined,\n  };\n}\n\nfunction toImageModelV4File(dataContent: DataContent): ImageModelV4File {\n  if (typeof dataContent === 'string' && dataContent.startsWith('http')) {\n    return {\n      type: 'url',\n      url: dataContent,\n    };\n  }\n\n  // Handle data URLs\n  if (typeof dataContent === 'string' && dataContent.startsWith('data:')) {\n    const { mediaType: dataUrlMediaType, base64Content } =\n      splitDataUrl(dataContent);\n\n    if (base64Content != null) {\n      const uint8Data = convertBase64ToUint8Array(base64Content);\n      return {\n        type: 'file',\n        data: uint8Data,\n        mediaType:\n          dataUrlMediaType ||\n          detectMediaType({\n            data: uint8Data,\n            topLevelType: 'image',\n          }) ||\n          'image/png',\n      };\n    }\n  }\n\n  const uint8Data = convertDataContentToUint8Array(dataContent);\n  return {\n    type: 'file',\n    data: uint8Data,\n    mediaType:\n      detectMediaType({\n        data: uint8Data,\n        topLevelType: 'image',\n      }) || 'image/png',\n  };\n}\n","import {\n  convertBase64ToUint8Array,\n  convertUint8ArrayToBase64,\n  type DataContent,\n} from '@ai-sdk/provider-utils';\nimport { InvalidDataContentError } from './invalid-data-content-error';\n\n/**\n * Converts data content to a base64-encoded string.\n *\n * @param content - Data content to convert.\n * @returns Base64-encoded string.\n */\nexport function convertDataContentToBase64String(content: DataContent): string {\n  if (typeof content === 'string') {\n    return content;\n  }\n\n  if (content instanceof ArrayBuffer) {\n    return convertUint8ArrayToBase64(new Uint8Array(content));\n  }\n\n  return convertUint8ArrayToBase64(content);\n}\n\n/**\n * Converts data content to a Uint8Array.\n *\n * @param content - Data content to convert.\n * @returns Uint8Array.\n */\nexport function convertDataContentToUint8Array(\n  content: DataContent,\n): Uint8Array {\n  if (content instanceof Uint8Array) {\n    return content;\n  }\n\n  if (typeof content === 'string') {\n    try {\n      return convertBase64ToUint8Array(content);\n    } catch (error) {\n      throw new InvalidDataContentError({\n        message:\n          'Invalid data content. Content string is not a base64-encoded media.',\n        content,\n        cause: error,\n      });\n    }\n  }\n\n  if (content instanceof ArrayBuffer) {\n    return new Uint8Array(content);\n  }\n\n  throw new InvalidDataContentError({ content });\n}\n","/**\n * Performs a deep-equal comparison of two parsed JSON objects.\n *\n * @param {any} obj1 - The first object to compare.\n * @param {any} obj2 - The second object to compare.\n * @returns {boolean} - Returns true if the two objects are deeply equal, false otherwise.\n */\nexport function isDeepEqualData(obj1: any, obj2: any): boolean {\n  // Check for strict equality first\n  if (obj1 === obj2) return true;\n\n  // Check if either is null or undefined\n  if (obj1 == null || obj2 == null) return false;\n\n  // Check if both are objects\n  if (typeof obj1 !== 'object' && typeof obj2 !== 'object')\n    return obj1 === obj2;\n\n  // If they are not strictly equal, they both need to be Objects\n  if (obj1.constructor !== obj2.constructor) return false;\n\n  // Special handling for Date objects\n  if (obj1 instanceof Date && obj2 instanceof Date) {\n    return obj1.getTime() === obj2.getTime();\n  }\n\n  // Handle arrays: compare length and then perform a recursive deep comparison on each item\n  if (Array.isArray(obj1)) {\n    if (obj1.length !== obj2.length) return false;\n    for (let i = 0; i < obj1.length; i++) {\n      if (!isDeepEqualData(obj1[i], obj2[i])) return false;\n    }\n    return true; // All array elements matched\n  }\n\n  // Compare the set of keys in each object\n  const keys1 = Object.keys(obj1);\n  const keys2 = Object.keys(obj2);\n  if (keys1.length !== keys2.length) return false;\n\n  // Check each key-value pair recursively\n  for (const key of keys1) {\n    if (!keys2.includes(key)) return false;\n    if (!isDeepEqualData(obj1[key], obj2[key])) return false;\n  }\n\n  return true; // All keys and values matched\n}\n","import {\n  createIdGenerator,\n  type Context,\n  withUserAgentSuffix,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { InvalidResponseDataError } from '../error';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveEmbeddingModel } from '../model/resolve-model';\nimport { createRestrictedTelemetryDispatcher } from './restricted-telemetry-dispatcher';\nimport type { TelemetryOptions } from '../telemetry/telemetry-options';\nimport type { EmbeddingModel } from '../types';\nimport type { Callback } from '../util/callback';\nimport { notify } from '../util/notify';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\nimport type { EmbedEndEvent, EmbedStartEvent } from './embed-events';\nimport type { EmbedResult } from './embed-result';\n\nconst originalGenerateCallId = createIdGenerator({\n  prefix: 'call',\n  size: 24,\n});\n\n/**\n * Embed a value using an embedding model. The type of the value is defined by the embedding model.\n *\n * @param model - The embedding model to use.\n * @param value - The value that should be embedded.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @param telemetry - Optional telemetry configuration.\n * @param runtimeContext - User-defined runtime context passed to callbacks and, when explicitly included, telemetry.\n *\n * @param providerOptions - Additional provider-specific options. They are passed through\n * to the provider from the AI SDK and enable provider-specific\n * functionality that can be fully encapsulated in the provider.\n *\n * @returns A result object that contains the embedding, the value, and additional information.\n */\nexport async function embed<RUNTIME_CONTEXT extends Context = Context>({\n  model: modelArg,\n  value,\n  providerOptions,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  experimental_telemetry,\n  telemetry = experimental_telemetry,\n  runtimeContext = {} as RUNTIME_CONTEXT,\n  onStart,\n  experimental_onStart,\n  onEnd,\n  experimental_onEnd,\n  _internal: { generateCallId = originalGenerateCallId } = {},\n}: {\n  /**\n   * The embedding model to use.\n   */\n  model: EmbeddingModel;\n\n  /**\n   * The value that should be embedded.\n   */\n  value: string;\n\n  /**\n   * Maximum number of retries per embedding model call. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * Additional provider-specific options. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Optional telemetry configuration.\n   */\n  telemetry?: TelemetryOptions<RUNTIME_CONTEXT>;\n\n  /**\n   * Optional telemetry configuration.\n   *\n   * @deprecated Use `telemetry` instead. This alias will be removed in a future major release.\n   */\n  experimental_telemetry?: TelemetryOptions<RUNTIME_CONTEXT>;\n\n  /**\n   * User-defined runtime context. Treat runtime context as immutable.\n   */\n  runtimeContext?: RUNTIME_CONTEXT;\n\n  /**\n   * Callback that is called when the embed operation begins,\n   * before the embedding model is called.\n   */\n  onStart?: Callback<EmbedStartEvent<RUNTIME_CONTEXT>>;\n\n  /**\n   * Callback that is called when the embed operation begins,\n   * before the embedding model is called.\n   *\n   * @deprecated Use `onStart` instead.\n   */\n  experimental_onStart?: Callback<EmbedStartEvent<RUNTIME_CONTEXT>>;\n\n  /**\n   * Callback that is called when the embed operation completes,\n   * after the embedding model returns.\n   */\n  onEnd?: Callback<EmbedEndEvent<RUNTIME_CONTEXT>>;\n\n  /**\n   * Callback that is called when the embed operation completes,\n   * after the embedding model returns.\n   *\n   * @deprecated Use `onEnd` instead.\n   */\n  experimental_onEnd?: Callback<EmbedEndEvent<RUNTIME_CONTEXT>>;\n\n  /**\n   * Internal. For test use only. May change without notice.\n   */\n  _internal?: {\n    generateCallId?: () => string;\n  };\n}): Promise<EmbedResult> {\n  const model = resolveEmbeddingModel(modelArg);\n\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n  const resolvedOnStart = onStart ?? experimental_onStart;\n  const resolvedOnEnd = onEnd ?? experimental_onEnd;\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const callId = generateCallId();\n\n  const telemetryDispatcher = createRestrictedTelemetryDispatcher({\n    telemetry,\n  });\n\n  const runInTracingChannelSpan =\n    telemetryDispatcher.runInTracingChannelSpan ??\n    (async <T>({ execute }: { execute: () => PromiseLike<T> }) =>\n      await execute());\n\n  const startEvent = {\n    callId,\n    operationId: 'ai.embed',\n    runtimeContext,\n    provider: model.provider,\n    modelId: model.modelId,\n    value,\n    maxRetries,\n    headers: headersWithUserAgent,\n    providerOptions,\n  };\n\n  return await runInTracingChannelSpan({\n    type: 'embed',\n    event: startEvent,\n    execute: async () => {\n      await notify({\n        event: startEvent,\n        callbacks: [resolvedOnStart, telemetryDispatcher.onStart],\n      });\n\n      try {\n        const { embedding, usage, warnings, response, providerMetadata } =\n          await retry(async () => {\n            const embedCallId = generateCallId();\n\n            await notify({\n              event: {\n                callId,\n                embedCallId,\n                operationId: 'ai.embed.doEmbed',\n                provider: model.provider,\n                modelId: model.modelId,\n                values: [value],\n              },\n              callbacks: [telemetryDispatcher.onEmbedStart],\n            });\n\n            const modelResponse = await model.doEmbed({\n              values: [value],\n              abortSignal,\n              headers: headersWithUserAgent,\n              providerOptions,\n            });\n\n            const embedding = modelResponse.embeddings[0];\n            const usage = modelResponse.usage ?? { tokens: NaN };\n\n            await notify({\n              event: {\n                callId,\n                embedCallId,\n                operationId: 'ai.embed.doEmbed',\n                provider: model.provider,\n                modelId: model.modelId,\n                values: [value],\n                embeddings: modelResponse.embeddings,\n                usage,\n              },\n              callbacks: [telemetryDispatcher.onEmbedEnd],\n            });\n\n            if (embedding == null) {\n              throw new InvalidResponseDataError({\n                data: modelResponse.embeddings,\n                message: 'No embedding generated.',\n              });\n            }\n\n            return {\n              embedding,\n              usage,\n              warnings: modelResponse.warnings ?? [],\n              providerMetadata: modelResponse.providerMetadata,\n              response: modelResponse.response,\n            };\n          });\n\n        logWarnings({\n          warnings,\n          provider: model.provider,\n          model: model.modelId,\n        });\n\n        await notify({\n          event: {\n            callId,\n            operationId: 'ai.embed',\n            runtimeContext,\n            provider: model.provider,\n            modelId: model.modelId,\n            value,\n            embedding,\n            usage,\n            warnings,\n            providerMetadata,\n            response,\n          },\n          callbacks: [resolvedOnEnd, telemetryDispatcher.onEnd],\n        });\n\n        return new DefaultEmbedResult({\n          value,\n          embedding,\n          usage,\n          warnings,\n          providerMetadata,\n          response,\n        });\n      } catch (error) {\n        await telemetryDispatcher.onError?.({ callId, error });\n        throw error;\n      }\n    },\n  });\n}\n\nclass DefaultEmbedResult implements EmbedResult {\n  readonly value: EmbedResult['value'];\n  readonly embedding: EmbedResult['embedding'];\n  readonly usage: EmbedResult['usage'];\n  readonly warnings: EmbedResult['warnings'];\n  readonly providerMetadata: EmbedResult['providerMetadata'];\n  readonly response: EmbedResult['response'];\n\n  constructor(options: {\n    value: EmbedResult['value'];\n    embedding: EmbedResult['embedding'];\n    usage: EmbedResult['usage'];\n    warnings: EmbedResult['warnings'];\n    providerMetadata?: EmbedResult['providerMetadata'];\n    response?: EmbedResult['response'];\n  }) {\n    this.value = options.value;\n    this.embedding = options.embedding;\n    this.usage = options.usage;\n    this.warnings = options.warnings;\n    this.providerMetadata = options.providerMetadata;\n    this.response = options.response;\n  }\n}\n","import type { Context } from '@ai-sdk/provider-utils';\nimport { createTelemetryDispatcher } from '../telemetry/create-telemetry-dispatcher';\nimport { filterIncludedContext } from '../telemetry/filter-included-context';\nimport type { TelemetryDispatcher } from '../telemetry/telemetry';\nimport type { TelemetryOptions } from '../telemetry/telemetry-options';\nimport type { Callback } from '../util/callback';\nimport type { EmbedStartEvent, EmbedEndEvent } from './embed-events';\n\n/**\n * Filters runtime context before sending operation events to telemetry integrations.\n * User callbacks continue to receive the original context.\n */\nexport function createRestrictedTelemetryDispatcher<\n  RUNTIME_CONTEXT extends Context,\n>({\n  telemetry,\n}: {\n  telemetry?: TelemetryOptions<RUNTIME_CONTEXT>;\n}): Omit<TelemetryDispatcher, 'onStart' | 'onEnd'> & {\n  onStart: Callback<EmbedStartEvent<RUNTIME_CONTEXT>>;\n  onEnd: Callback<EmbedEndEvent<RUNTIME_CONTEXT>>;\n} {\n  const dispatcher = createTelemetryDispatcher({ telemetry });\n\n  return {\n    ...dispatcher,\n    onStart: event =>\n      dispatcher.onStart?.({\n        ...event,\n        runtimeContext: filterIncludedContext({\n          context: event.runtimeContext,\n          includeContext: telemetry?.includeRuntimeContext,\n        }),\n      }),\n    onEnd: event =>\n      dispatcher.onEnd?.({\n        ...event,\n        runtimeContext: filterIncludedContext({\n          context: event.runtimeContext,\n          includeContext: telemetry?.includeRuntimeContext,\n        }),\n      }),\n  };\n}\n","import { InvalidResponseDataError } from '@ai-sdk/provider';\nimport {\n  createIdGenerator,\n  type Context,\n  withUserAgentSuffix,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { logWarnings } from '../logger/log-warnings';\nimport { getEmbeddingModelMaxInputBytesPerCall } from '../model/get-embedding-model-max-input-bytes-per-call';\nimport { resolveEmbeddingModel } from '../model/resolve-model';\nimport { createRestrictedTelemetryDispatcher } from './restricted-telemetry-dispatcher';\nimport type { TelemetryOptions } from '../telemetry/telemetry-options';\nimport type { Embedding, EmbeddingModel, ProviderMetadata } from '../types';\nimport type { Warning } from '../types/warning';\nimport type { Callback } from '../util/callback';\nimport { notify } from '../util/notify';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { splitArray } from '../util/split-array';\nimport type { EmbedEndEvent, EmbedStartEvent } from './embed-events';\nimport type { EmbedManyResult } from './embed-many-result';\nimport { VERSION } from '../version';\n\nconst originalGenerateCallId = createIdGenerator({\n  prefix: 'call',\n  size: 24,\n});\n\n/**\n * Embed several values using an embedding model. The type of the value is defined\n * by the embedding model.\n *\n * `embedMany` automatically splits large requests into smaller chunks when the\n * model has a limit on either the number of embeddings or the UTF-8 input bytes\n * that can be processed in a single call.\n *\n * @param model - The embedding model to use.\n * @param values - The values that should be embedded.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @param maxParallelCalls - Maximum number of concurrent requests when a request is split into\n * multiple model calls. Must be greater than 0 when the model supports parallel calls.\n * Default: Infinity.\n *\n * @param telemetry - Optional telemetry configuration.\n * @param runtimeContext - User-defined runtime context passed to callbacks and, when explicitly included, telemetry.\n *\n * @param providerOptions - Additional provider-specific options. They are passed through\n * to the provider from the AI SDK and enable provider-specific\n * functionality that can be fully encapsulated in the provider.\n *\n * @returns A result object that contains the embeddings, the value, and additional information.\n */\nexport async function embedMany<RUNTIME_CONTEXT extends Context = Context>({\n  model: modelArg,\n  values,\n  maxParallelCalls = Infinity,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  providerOptions,\n  experimental_telemetry,\n  telemetry = experimental_telemetry,\n  runtimeContext = {} as RUNTIME_CONTEXT,\n  onStart,\n  experimental_onStart,\n  onEnd,\n  experimental_onEnd,\n  _internal: { generateCallId = originalGenerateCallId } = {},\n}: {\n  /**\n   * The embedding model to use.\n   */\n  model: EmbeddingModel;\n\n  /**\n   * The values that should be embedded.\n   */\n  values: Array<string>;\n\n  /**\n   * Maximum number of retries per embedding model call. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * Optional telemetry configuration.\n   */\n  telemetry?: TelemetryOptions<RUNTIME_CONTEXT>;\n\n  /**\n   * Optional telemetry configuration.\n   *\n   * @deprecated Use `telemetry` instead. This alias will be removed in a future major release.\n   */\n  experimental_telemetry?: TelemetryOptions<RUNTIME_CONTEXT>;\n\n  /**\n   * User-defined runtime context. Treat runtime context as immutable.\n   */\n  runtimeContext?: RUNTIME_CONTEXT;\n\n  /**\n   * Additional provider-specific options. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Maximum number of concurrent requests when a request is split into multiple model calls.\n   * Must be greater than 0 when the model supports parallel calls.\n   *\n   * @default Infinity\n   */\n  maxParallelCalls?: number;\n\n  /**\n   * Callback that is called when the embedMany operation begins,\n   * before the embedding model is called.\n   */\n  onStart?: Callback<EmbedStartEvent<RUNTIME_CONTEXT>>;\n\n  /**\n   * Callback that is called when the embedMany operation begins,\n   * before the embedding model is called.\n   *\n   * @deprecated Use `onStart` instead.\n   */\n  experimental_onStart?: Callback<EmbedStartEvent<RUNTIME_CONTEXT>>;\n\n  /**\n   * Callback that is called when the embedMany operation completes,\n   * after all embedding model calls return.\n   */\n  onEnd?: Callback<EmbedEndEvent<RUNTIME_CONTEXT>>;\n\n  /**\n   * Callback that is called when the embedMany operation completes,\n   * after all embedding model calls return.\n   *\n   * @deprecated Use `onEnd` instead.\n   */\n  experimental_onEnd?: Callback<EmbedEndEvent<RUNTIME_CONTEXT>>;\n\n  /**\n   * Internal. For test use only. May change without notice.\n   */\n  _internal?: {\n    generateCallId?: () => string;\n  };\n}): Promise<EmbedManyResult> {\n  const model = resolveEmbeddingModel(modelArg);\n\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n  const resolvedOnStart = onStart ?? experimental_onStart;\n  const resolvedOnEnd = onEnd ?? experimental_onEnd;\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const callId = generateCallId();\n\n  const telemetryDispatcher = createRestrictedTelemetryDispatcher({\n    telemetry,\n  });\n\n  const runInTracingChannelSpan =\n    telemetryDispatcher.runInTracingChannelSpan ??\n    (async <T>({ execute }: { execute: () => PromiseLike<T> }) =>\n      await execute());\n\n  const startEvent = {\n    callId,\n    operationId: 'ai.embedMany',\n    runtimeContext,\n    provider: model.provider,\n    modelId: model.modelId,\n    value: values,\n    maxRetries,\n    headers: headersWithUserAgent,\n    providerOptions,\n  };\n\n  return await runInTracingChannelSpan({\n    type: 'embedMany',\n    event: startEvent,\n    execute: async () => {\n      await notify({\n        event: startEvent,\n        callbacks: [resolvedOnStart, telemetryDispatcher.onStart],\n      });\n\n      try {\n        const [\n          maxEmbeddingsPerCall,\n          maxInputBytesPerCall,\n          supportsParallelCalls,\n        ] = await Promise.all([\n          model.maxEmbeddingsPerCall,\n          getEmbeddingModelMaxInputBytesPerCall(model),\n          model.supportsParallelCalls,\n        ]);\n\n        const hasEmbeddingLimit =\n          maxEmbeddingsPerCall != null && maxEmbeddingsPerCall !== Infinity;\n        const hasInputByteLimit =\n          maxInputBytesPerCall != null && maxInputBytesPerCall !== Infinity;\n\n        if (!hasEmbeddingLimit && !hasInputByteLimit) {\n          const { embeddings, usage, warnings, response, providerMetadata } =\n            await retry(async () => {\n              const embedCallId = generateCallId();\n\n              await notify({\n                event: {\n                  callId,\n                  embedCallId,\n                  operationId: 'ai.embedMany.doEmbed',\n                  provider: model.provider,\n                  modelId: model.modelId,\n                  values,\n                },\n                callbacks: [telemetryDispatcher.onEmbedStart],\n              });\n\n              const modelResponse = await model.doEmbed({\n                values,\n                abortSignal,\n                headers: headersWithUserAgent,\n                providerOptions,\n              });\n\n              const embeddings = modelResponse.embeddings;\n              const usage = modelResponse.usage ?? { tokens: NaN };\n\n              await notify({\n                event: {\n                  callId,\n                  embedCallId,\n                  operationId: 'ai.embedMany.doEmbed',\n                  provider: model.provider,\n                  modelId: model.modelId,\n                  values,\n                  embeddings,\n                  usage,\n                },\n                callbacks: [telemetryDispatcher.onEmbedEnd],\n              });\n\n              return {\n                embeddings,\n                usage,\n                warnings: modelResponse.warnings ?? [],\n                providerMetadata: modelResponse.providerMetadata,\n                response: modelResponse.response,\n              };\n            });\n\n          validateEmbeddingCount({ embeddings, values });\n\n          logWarnings({\n            warnings,\n            provider: model.provider,\n            model: model.modelId,\n          });\n\n          await notify({\n            event: {\n              callId,\n              operationId: 'ai.embedMany',\n              runtimeContext,\n              provider: model.provider,\n              modelId: model.modelId,\n              value: values,\n              embedding: embeddings,\n              usage,\n              warnings,\n              providerMetadata,\n              response: [response],\n            },\n            callbacks: [resolvedOnEnd, telemetryDispatcher.onEnd],\n          });\n\n          return new DefaultEmbedManyResult({\n            values,\n            embeddings,\n            usage,\n            warnings,\n            providerMetadata,\n            responses: [response],\n          });\n        }\n\n        const valueChunks = splitByEmbeddingLimits({\n          values,\n          maxEmbeddingsPerCall: hasEmbeddingLimit\n            ? maxEmbeddingsPerCall\n            : Infinity,\n          maxInputBytesPerCall: hasInputByteLimit\n            ? maxInputBytesPerCall\n            : Infinity,\n        });\n\n        const embeddings: Array<Embedding> = [];\n        const warnings: Array<Warning> = [];\n        const responses: Array<\n          | {\n              headers?: Record<string, string>;\n              body?: unknown;\n            }\n          | undefined\n        > = [];\n        let tokens = 0;\n        let providerMetadata: ProviderMetadata | undefined;\n\n        const parallelChunks = splitArray(\n          valueChunks,\n          supportsParallelCalls ? maxParallelCalls : 1,\n        );\n\n        for (const parallelChunk of parallelChunks) {\n          const results = await Promise.all(\n            parallelChunk.map(async chunk => {\n              const result = await retry(async () => {\n                const embedCallId = generateCallId();\n\n                await notify({\n                  event: {\n                    callId,\n                    embedCallId,\n                    operationId: 'ai.embedMany.doEmbed',\n                    provider: model.provider,\n                    modelId: model.modelId,\n                    values: chunk,\n                  },\n                  callbacks: [telemetryDispatcher.onEmbedStart],\n                });\n\n                const modelResponse = await model.doEmbed({\n                  values: chunk,\n                  abortSignal,\n                  headers: headersWithUserAgent,\n                  providerOptions,\n                });\n\n                const chunkEmbeddings = modelResponse.embeddings;\n                const usage = modelResponse.usage ?? { tokens: NaN };\n\n                await notify({\n                  event: {\n                    callId,\n                    embedCallId,\n                    operationId: 'ai.embedMany.doEmbed',\n                    provider: model.provider,\n                    modelId: model.modelId,\n                    values: chunk,\n                    embeddings: chunkEmbeddings,\n                    usage,\n                  },\n                  callbacks: [telemetryDispatcher.onEmbedEnd],\n                });\n\n                return {\n                  embeddings: chunkEmbeddings,\n                  usage,\n                  warnings: modelResponse.warnings ?? [],\n                  providerMetadata: modelResponse.providerMetadata,\n                  response: modelResponse.response,\n                };\n              });\n\n              validateEmbeddingCount({\n                embeddings: result.embeddings,\n                values: chunk,\n              });\n\n              return result;\n            }),\n          );\n\n          for (const result of results) {\n            embeddings.push(...result.embeddings);\n            warnings.push(...result.warnings);\n            responses.push(result.response);\n            tokens += result.usage.tokens;\n            if (result.providerMetadata) {\n              if (!providerMetadata) {\n                providerMetadata = { ...result.providerMetadata };\n              } else {\n                for (const [providerName, metadata] of Object.entries(\n                  result.providerMetadata,\n                )) {\n                  providerMetadata[providerName] = {\n                    ...(providerMetadata[providerName] ?? {}),\n                    ...metadata,\n                  };\n                }\n              }\n            }\n          }\n        }\n\n        logWarnings({\n          warnings,\n          provider: model.provider,\n          model: model.modelId,\n        });\n\n        await notify({\n          event: {\n            callId,\n            operationId: 'ai.embedMany',\n            runtimeContext,\n            provider: model.provider,\n            modelId: model.modelId,\n            value: values,\n            embedding: embeddings,\n            usage: { tokens },\n            warnings,\n            providerMetadata,\n            response: responses,\n          },\n          callbacks: [resolvedOnEnd, telemetryDispatcher.onEnd],\n        });\n\n        return new DefaultEmbedManyResult({\n          values,\n          embeddings,\n          usage: { tokens },\n          warnings,\n          providerMetadata: providerMetadata,\n          responses,\n        });\n      } catch (error) {\n        await telemetryDispatcher.onError?.({ callId, error });\n        throw error;\n      }\n    },\n  });\n}\n\nfunction validateEmbeddingCount({\n  embeddings,\n  values,\n}: {\n  embeddings: Array<Embedding>;\n  values: Array<string>;\n}) {\n  if (embeddings.length !== values.length) {\n    throw new InvalidResponseDataError({\n      data: embeddings,\n      message: `Expected ${values.length} embeddings, but received ${embeddings.length}.`,\n    });\n  }\n}\n\nconst textEncoder = new TextEncoder();\n\nfunction splitByEmbeddingLimits({\n  values,\n  maxEmbeddingsPerCall,\n  maxInputBytesPerCall,\n}: {\n  values: Array<string>;\n  maxEmbeddingsPerCall: number;\n  maxInputBytesPerCall: number;\n}): Array<Array<string>> {\n  if (maxEmbeddingsPerCall <= 0) {\n    throw new Error('maxEmbeddingsPerCall must be greater than 0');\n  }\n\n  if (maxInputBytesPerCall <= 0) {\n    throw new Error('maxInputBytesPerCall must be greater than 0');\n  }\n\n  if (values.length === 0) {\n    return [];\n  }\n\n  const chunks: Array<Array<string>> = [];\n  let currentChunk: Array<string> = [];\n  let currentInputBytes = 0;\n\n  for (const value of values) {\n    const inputBytes = textEncoder.encode(value).length;\n\n    if (\n      currentChunk.length > 0 &&\n      (currentChunk.length >= maxEmbeddingsPerCall ||\n        currentInputBytes + inputBytes > maxInputBytesPerCall)\n    ) {\n      chunks.push(currentChunk);\n      currentChunk = [];\n      currentInputBytes = 0;\n    }\n\n    currentChunk.push(value);\n    currentInputBytes += inputBytes;\n  }\n\n  chunks.push(currentChunk);\n\n  return chunks;\n}\n\nclass DefaultEmbedManyResult implements EmbedManyResult {\n  readonly values: EmbedManyResult['values'];\n  readonly embeddings: EmbedManyResult['embeddings'];\n  readonly usage: EmbedManyResult['usage'];\n  readonly warnings: EmbedManyResult['warnings'];\n  readonly providerMetadata: EmbedManyResult['providerMetadata'];\n  readonly responses: EmbedManyResult['responses'];\n\n  constructor(options: {\n    values: EmbedManyResult['values'];\n    embeddings: EmbedManyResult['embeddings'];\n    usage: EmbedManyResult['usage'];\n    warnings: EmbedManyResult['warnings'];\n    providerMetadata?: EmbedManyResult['providerMetadata'];\n    responses?: EmbedManyResult['responses'];\n  }) {\n    this.values = options.values;\n    this.embeddings = options.embeddings;\n    this.usage = options.usage;\n    this.warnings = options.warnings;\n    this.providerMetadata = options.providerMetadata;\n    this.responses = options.responses;\n  }\n}\n","import type { EmbeddingModelV4 } from '@ai-sdk/provider';\nimport { EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL } from '@ai-sdk/provider-utils';\n\nexport type EmbeddingModelWithMaxInputBytesPerCall = EmbeddingModelV4 & {\n  readonly [EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL]?:\n    | PromiseLike<number | undefined>\n    | number\n    | undefined;\n};\n\nexport function getEmbeddingModelMaxInputBytesPerCall(model: EmbeddingModelV4) {\n  return (model as EmbeddingModelWithMaxInputBytesPerCall)[\n    EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL\n  ];\n}\n","import { InvalidArgumentError } from '../error/invalid-argument-error';\n\n/**\n * Splits an array into chunks of a specified size.\n *\n * @template T - The type of elements in the array.\n * @param {T[]} array - The array to split.\n * @param {number} chunkSize - The size of each chunk.\n * @returns {T[][]} - A new array containing the chunks.\n * @throws {InvalidArgumentError} If the chunk size is not greater than 0.\n */\nexport function splitArray<T>(array: T[], chunkSize: number): T[][] {\n  if (chunkSize <= 0) {\n    throw new InvalidArgumentError({\n      parameter: 'chunkSize',\n      value: chunkSize,\n      message: 'chunkSize must be greater than 0',\n    });\n  }\n\n  const result = [];\n  for (let i = 0; i < array.length; i += chunkSize) {\n    result.push(array.slice(i, i + chunkSize));\n  }\n\n  return result;\n}\n","import {\n  Experimental_EvaluationUnsupportedQuestionTypeError as EvaluationUnsupportedQuestionTypeError,\n  type Experimental_EvaluationModelV4CallOptions as EvaluationModelV4CallOptions,\n} from '@ai-sdk/provider';\nimport {\n  withUserAgentSuffix,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { resolveEvaluationModel } from '../model/resolve-model';\nimport { logWarnings } from '../logger/log-warnings';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\nimport type {\n  EvaluationModel,\n  EvaluationQuestion,\n  EvaluationResult,\n} from './evaluation-result';\nimport {\n  validateEvaluationInput,\n  validateEvaluationAnswers,\n} from './validate-evaluation';\n\n/** Evaluate typed questions against one shared state. Experimental. */\nexport async function evaluate<\n  const QUESTIONS extends Record<string, EvaluationQuestion>,\n>({\n  model: modelArg,\n  state,\n  questions,\n  maxRetries,\n  abortSignal,\n  headers,\n  providerOptions = {},\n}: {\n  /** An evaluation model instance or an ID resolved by the configured default provider. */\n  model: EvaluationModel;\n  state: EvaluationModelV4CallOptions['state'];\n  questions: QUESTIONS;\n  /** Maximum retries for transient provider failures. Defaults to 2. */\n  maxRetries?: number;\n  abortSignal?: AbortSignal;\n  headers?: Record<string, string>;\n  providerOptions?: ProviderOptions;\n}): Promise<EvaluationResult<QUESTIONS>> {\n  const model = resolveEvaluationModel(modelArg);\n\n  validateEvaluationInput({ state, questions });\n\n  for (const [questionId, question] of Object.entries(questions)) {\n    if (!model.supportedQuestionTypes.includes(question.type)) {\n      throw new EvaluationUnsupportedQuestionTypeError({\n        questionId,\n        questionType: question.type,\n        provider: model.provider,\n        modelId: model.modelId,\n      });\n    }\n  }\n\n  const { retry } = prepareRetries({ maxRetries, abortSignal });\n  const result = await retry(() => {\n    abortSignal?.throwIfAborted();\n    return model.doEvaluate({\n      state,\n      questions,\n      abortSignal,\n      headers: withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`),\n      providerOptions,\n    });\n  });\n\n  abortSignal?.throwIfAborted();\n  validateEvaluationAnswers({\n    questions,\n    answers: result.answers,\n    rounding: result.rounding,\n  });\n  logWarnings({\n    warnings: result.warnings,\n    provider: model.provider,\n    model: model.modelId,\n  });\n\n  const inputTokens = result.usage?.inputTokens;\n  const outputTokens = result.usage?.outputTokens;\n\n  return {\n    answers: result.answers as EvaluationResult<QUESTIONS>['answers'],\n    usage: {\n      inputTokens,\n      outputTokens,\n      totalTokens:\n        inputTokens != null && outputTokens != null\n          ? inputTokens + outputTokens\n          : undefined,\n    },\n    warnings: result.warnings,\n    rounding: result.rounding,\n    providerMetadata: result.providerMetadata,\n    response: {\n      ...result.response,\n      timestamp: result.response?.timestamp ?? new Date(),\n      modelId: result.response?.modelId ?? model.modelId,\n    },\n  };\n}\n","import {\n  InvalidResponseDataError,\n  type Experimental_EvaluationModelV4CallOptions as EvaluationModelV4CallOptions,\n  type Experimental_EvaluationModelV4Result as EvaluationModelV4Result,\n} from '@ai-sdk/provider';\nimport { InvalidArgumentError } from '../error/invalid-argument-error';\n\n// Absolute tolerance for sums and means. Never renormalize provider output.\nconst tolerance = 1e-6;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  if (value == null || typeof value !== 'object' || Array.isArray(value))\n    return false;\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction isJSON(value: unknown, ancestors = new Set<object>()): boolean {\n  if (value === null || typeof value === 'string' || typeof value === 'boolean')\n    return true;\n  if (typeof value === 'number') return Number.isFinite(value);\n  if (typeof value !== 'object' || (!Array.isArray(value) && !isRecord(value)))\n    return false;\n  if (ancestors.has(value)) return false;\n  ancestors.add(value);\n  const valid =\n    Object.getOwnPropertySymbols(value).length === 0 &&\n    (Array.isArray(value)\n      ? Array.from(value).every(item => isJSON(item, ancestors))\n      : Object.values(value).every(item => isJSON(item, ancestors)));\n  ancestors.delete(value);\n  return valid;\n}\n\nfunction isInput(value: unknown): boolean {\n  return (\n    (typeof value === 'string' || Array.isArray(value) || isRecord(value)) &&\n    isJSON(value)\n  );\n}\n\nfunction invalidInput(\n  parameter: string,\n  value: unknown,\n  message: string,\n): never {\n  throw new InvalidArgumentError({ parameter, value, message });\n}\n\nexport function validateEvaluationInput({\n  state,\n  questions,\n}: EvaluationModelV4CallOptions) {\n  if (!isInput(state)) {\n    invalidInput(\n      'state',\n      state,\n      'must be a JSON-compatible string, object, or array',\n    );\n  }\n  if (!isRecord(questions) || Object.keys(questions).length === 0) {\n    invalidInput('questions', questions, 'must be a nonempty question map');\n  }\n\n  for (const [id, question] of Object.entries(questions)) {\n    const parameter = `questions.${id}`;\n    if (!isRecord(question) || !isInput(question.instructions)) {\n      invalidInput(\n        parameter,\n        question,\n        'instructions must be a JSON-compatible string, object, or array',\n      );\n    }\n    const criteria = question.criteria;\n    switch (question.type) {\n      case 'choice':\n        if (!isRecord(criteria) || Object.keys(criteria).length === 0) {\n          invalidInput(\n            parameter,\n            question,\n            'choice criteria must be a nonempty option map',\n          );\n        }\n        break;\n      case 'score':\n        if (!Array.isArray(criteria) || criteria.length < 2) {\n          invalidInput(\n            parameter,\n            question,\n            'score criteria must contain at least two ordered levels',\n          );\n        }\n        break;\n      case 'boolean':\n        if (criteria === undefined) continue;\n        if (\n          !isRecord(criteria) ||\n          Object.keys(criteria).some(key => key !== 'true' && key !== 'false')\n        ) {\n          invalidInput(\n            parameter,\n            question,\n            'boolean criteria may only describe true and false',\n          );\n        }\n        break;\n      default:\n        invalidInput(\n          parameter,\n          question,\n          'question type must be choice, score, or boolean',\n        );\n    }\n    if (\n      !isJSON(criteria) ||\n      Object.values(criteria).some(value => value !== null && !isInput(value))\n    ) {\n      invalidInput(\n        parameter,\n        question,\n        'criteria descriptions must be JSON-compatible strings, objects, arrays, or null',\n      );\n    }\n  }\n}\n\nfunction invalidAnswer(answers: unknown, message: string): never {\n  throw new InvalidResponseDataError({ data: answers, message });\n}\n\nfunction isProbability(value: unknown): value is number {\n  return (\n    typeof value === 'number' &&\n    Number.isFinite(value) &&\n    value >= 0 &&\n    value <= 1\n  );\n}\n\nfunction hasExactKeys(value: Record<string, unknown>, keys: string[]): boolean {\n  return (\n    Object.keys(value).length === keys.length &&\n    keys.every(key => Object.hasOwn(value, key))\n  );\n}\n\nfunction validateDistribution(\n  value: unknown,\n  keys: string[],\n  answers: unknown,\n  id: string,\n  roundingError: number,\n): asserts value is Record<string, number> {\n  if (\n    !isRecord(value) ||\n    !hasExactKeys(value, keys) ||\n    !Object.values(value).every(isProbability)\n  ) {\n    invalidAnswer(\n      answers,\n      `Question \"${id}\" must have a complete distribution of finite probabilities in [0, 1].`,\n    );\n  }\n  const sum = Object.values(value).reduce<number>(\n    (total, probability) => total + (probability as number),\n    0,\n  );\n  if (Math.abs(sum - 1) > tolerance + keys.length * roundingError) {\n    invalidAnswer(\n      answers,\n      `Question \"${id}\" probabilities must sum to 1 within the declared rounding precision.`,\n    );\n  }\n}\n\nexport function validateEvaluationAnswers({\n  questions,\n  answers,\n  rounding,\n}: {\n  questions: EvaluationModelV4CallOptions['questions'];\n  answers: unknown;\n  rounding?: EvaluationModelV4Result['rounding'];\n}) {\n  function roundingError(decimals: number | undefined): number {\n    if (decimals === undefined) return 0;\n    if (!Number.isInteger(decimals) || decimals < 0 || decimals > 15) {\n      invalidAnswer(\n        answers,\n        'Evaluation rounding decimals must be integers between 0 and 15.',\n      );\n    }\n    return 0.5 * 10 ** -decimals;\n  }\n  const probabilityError = roundingError(rounding?.probabilityDecimals);\n  const scoreError = roundingError(rounding?.scoreDecimals);\n  if (!isRecord(answers) || !hasExactKeys(answers, Object.keys(questions))) {\n    invalidAnswer(\n      answers,\n      'Evaluation must return exactly one answer for every question.',\n    );\n  }\n\n  for (const [id, question] of Object.entries(questions)) {\n    const answer = answers[id];\n    if (!isRecord(answer) || answer.type !== question.type) {\n      invalidAnswer(\n        answers,\n        `Question \"${id}\" returned an answer with the wrong type.`,\n      );\n    }\n\n    switch (question.type) {\n      case 'choice': {\n        if (\n          typeof answer.choice !== 'string' ||\n          !Object.hasOwn(question.criteria, answer.choice)\n        ) {\n          invalidAnswer(\n            answers,\n            `Question \"${id}\" selected an unknown option.`,\n          );\n        }\n        if (answer.probabilities !== undefined) {\n          validateDistribution(\n            answer.probabilities,\n            Object.keys(question.criteria),\n            answers,\n            id,\n            probabilityError,\n          );\n          const selected = answer.probabilities[answer.choice];\n          if (\n            Object.values(answer.probabilities).some(\n              probability => probability > selected + tolerance,\n            )\n          ) {\n            invalidAnswer(\n              answers,\n              `Question \"${id}\" did not select a highest-probability option.`,\n            );\n          }\n        }\n        break;\n      }\n      case 'score': {\n        if (\n          typeof answer.score !== 'number' ||\n          !Number.isFinite(answer.score) ||\n          answer.score < 0 ||\n          answer.score > question.criteria.length - 1\n        ) {\n          invalidAnswer(\n            answers,\n            `Question \"${id}\" score must be in [0, ${question.criteria.length - 1}].`,\n          );\n        }\n        if (answer.probabilities !== undefined) {\n          const keys = question.criteria.map((_, index) => String(index));\n          validateDistribution(\n            answer.probabilities,\n            keys,\n            answers,\n            id,\n            probabilityError,\n          );\n          const mean = Object.entries(answer.probabilities).reduce(\n            (total, [index, probability]) =>\n              total + Number(index) * probability,\n            0,\n          );\n          const meanRoundingError = keys.reduce(\n            (total, index) => total + Number(index) * probabilityError,\n            0,\n          );\n          if (\n            Math.abs(mean - answer.score) >\n            tolerance + meanRoundingError + scoreError\n          ) {\n            invalidAnswer(\n              answers,\n              `Question \"${id}\" score must equal the probability-weighted mean within the declared rounding precision.`,\n            );\n          }\n        }\n        break;\n      }\n      case 'boolean':\n        if (!isProbability(answer.probability)) {\n          invalidAnswer(\n            answers,\n            `Question \"${id}\" must return P(true) as a finite probability in [0, 1].`,\n          );\n        }\n        break;\n    }\n  }\n}\n","import type { JSONValue } from '@ai-sdk/provider';\nimport {\n  createIdGenerator,\n  withUserAgentSuffix,\n  type FlexibleSchema,\n  type InferSchema,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { NoObjectGeneratedError } from '../error/no-object-generated-error';\nimport { extractReasoningContent } from '../generate-text/extract-reasoning-content';\nimport { extractTextContent } from '../generate-text/extract-text-content';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveLanguageModel } from '../model/resolve-model';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport type { LanguageModelCallOptions } from '../prompt/language-model-call-options';\nimport { prepareLanguageModelCallOptions } from '../prompt/prepare-language-model-call-options';\nimport type { Prompt } from '../prompt/prompt';\nimport type { RequestOptions } from '../prompt/request-options';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport { wrapGatewayError } from '../prompt/wrap-gateway-error';\nimport { createTelemetryDispatcher } from '../telemetry/create-telemetry-dispatcher';\nimport type { TelemetryOptions } from '../telemetry/telemetry-options';\nimport type { LanguageModel } from '../types/language-model';\nimport type { LanguageModelRequestMetadata } from '../types/language-model-request-metadata';\nimport type { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';\nimport { asLanguageModelUsage } from '../types/usage';\nimport type { Callback } from '../util/callback';\nimport type { DownloadFunction } from '../util/download/download-function';\nimport { notify } from '../util/notify';\nimport { prepareHeaders } from '../util/prepare-headers';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\nimport type { GenerateObjectResult } from './generate-object-result';\nimport { getOutputStrategy } from './output-strategy';\nimport { parseAndValidateObjectResultWithRepair } from './parse-and-validate-object-result';\nimport type { RepairTextFunction } from './repair-text';\nimport type {\n  GenerateObjectEndEvent,\n  GenerateObjectStartEvent,\n  GenerateObjectStepEndEvent,\n  GenerateObjectStepStartEvent,\n} from './structured-output-events';\nimport { validateObjectGenerationInput } from './validate-object-generation-input';\n\nconst originalGenerateId = createIdGenerator({ prefix: 'aiobj', size: 24 });\n\n/**\n * Generate a structured, typed object for a given prompt and schema using a language model.\n *\n * This function does not stream the output. If you want to stream the output, use `streamObject` instead.\n *\n * @param model - The language model to use.\n *\n * @param system - A system message that will be part of the prompt.\n * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n * @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false.\n *\n * @param maxOutputTokens - Maximum number of tokens to generate.\n * @param temperature - Temperature setting.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topP - Nucleus sampling.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topK - Only sample from the top K options for each subsequent token.\n * Used to remove \"long tail\" low probability responses.\n * Recommended for advanced use cases only. You usually only need to use temperature.\n * @param presencePenalty - Presence penalty setting.\n * It affects the likelihood of the model to repeat information that is already in the prompt.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param frequencyPenalty - Frequency penalty setting.\n * It affects the likelihood of the model to repeatedly use the same words or phrases.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param stopSequences - Stop sequences.\n * If set, the model will stop generating text when one of the stop sequences is generated.\n * @param seed - The seed (integer) to use for random sampling.\n * If set and supported by the model, calls will generate deterministic results.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @param schema - The schema of the object that the model should generate.\n * @param schemaName - Optional name of the output that should be generated.\n * Used by some providers for additional LLM guidance, e.g.\n * via tool or schema name.\n * @param schemaDescription - Optional description of the output that should be generated.\n * Used by some providers for additional LLM guidance, e.g.\n * via tool or schema description.\n *\n * @param output - The type of the output.\n *\n * - 'object': The output is an object.\n * - 'array': The output is an array.\n * - 'enum': The output is an enum.\n * - 'no-schema': The output is not a schema.\n *\n * @param repairText - A function that attempts to repair the raw output of the model\n * to enable JSON parsing.\n * @param experimental_repairText - Deprecated alias for `repairText`.\n *\n * @param telemetry - Optional telemetry configuration.\n *\n * @param providerOptions - Additional provider-specific options. They are passed through\n * to the provider from the AI SDK and enable provider-specific\n * functionality that can be fully encapsulated in the provider.\n *\n * @param onStart - Callback invoked when generation begins, before the LLM call.\n * @param experimental_onStart - Deprecated alias for `onStart`.\n * @param onStepStart - Callback invoked when the model call begins.\n * @param experimental_onStepStart - Deprecated alias for `onStepStart`.\n * @param onStepEnd - Callback invoked when the model call completes with the raw result.\n * @param onStepFinish - Deprecated alias for `onStepEnd`.\n * @param onFinish - Callback invoked when the entire operation completes with the parsed object.\n *\n * @returns\n * A result object that contains the generated object, the finish reason, the token usage, and additional information.\n *\n * @deprecated Use `generateText` with an `output` setting instead.\n */\nexport async function generateObject<\n  SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<JSONValue>,\n  OUTPUT extends 'object' | 'array' | 'enum' | 'no-schema' =\n    InferSchema<SCHEMA> extends string ? 'enum' : 'object',\n  RESULT = OUTPUT extends 'array'\n    ? Array<InferSchema<SCHEMA>>\n    : InferSchema<SCHEMA>,\n>(\n  options: Omit<LanguageModelCallOptions, 'stopSequences'> &\n    Omit<RequestOptions, 'timeout'> &\n    Prompt &\n    (OUTPUT extends 'enum'\n      ? {\n          /**\n           * The enum values that the model should use.\n           */\n          enum: Array<RESULT>;\n          output: 'enum';\n        }\n      : OUTPUT extends 'no-schema'\n        ? {}\n        : {\n            /**\n             * The schema of the object that the model should generate.\n             */\n            schema: SCHEMA;\n\n            /**\n             * Optional name of the output that should be generated.\n             * Used by some providers for additional LLM guidance, e.g.\n             * via tool or schema name.\n             */\n            schemaName?: string;\n\n            /**\n             * Optional description of the output that should be generated.\n             * Used by some providers for additional LLM guidance, e.g.\n             * via tool or schema description.\n             */\n            schemaDescription?: string;\n          }) & {\n      output?: OUTPUT;\n\n      /**\n       * The language model to use.\n       */\n      model: LanguageModel;\n      /**\n       * A function that attempts to repair the raw output of the model\n       * to enable JSON parsing.\n       */\n      repairText?: RepairTextFunction;\n\n      /**\n       * A function that attempts to repair the raw output of the model\n       * to enable JSON parsing.\n       *\n       * @deprecated Use `repairText` instead.\n       */\n      experimental_repairText?: RepairTextFunction;\n\n      /**\n       * Optional telemetry configuration.\n       */\n      telemetry?: TelemetryOptions;\n\n      /**\n       * Optional telemetry configuration.\n       *\n       * @deprecated Use `telemetry` instead. This alias will be removed in a future major release.\n       */\n      experimental_telemetry?: TelemetryOptions;\n\n      /**\n       * Custom download function to use for URLs.\n       *\n       * By default, files are downloaded if the model does not support the URL for the given media type.\n       */\n      experimental_download?: DownloadFunction | undefined;\n\n      /**\n       * Additional provider-specific options. They are passed through\n       * to the provider from the AI SDK and enable provider-specific\n       * functionality that can be fully encapsulated in the provider.\n       */\n      providerOptions?: ProviderOptions;\n\n      /**\n       * Callback that is called when the generateObject operation begins,\n       * before the LLM call is made.\n       */\n      onStart?: Callback<GenerateObjectStartEvent>;\n\n      /**\n       * Callback that is called when the generateObject operation begins,\n       * before the LLM call is made.\n       *\n       * @deprecated Use `onStart` instead.\n       */\n      experimental_onStart?: Callback<GenerateObjectStartEvent>;\n\n      /**\n       * Callback that is called when the model call (step) begins,\n       * before the provider is called.\n       */\n      onStepStart?: Callback<GenerateObjectStepStartEvent>;\n\n      /**\n       * Callback that is called when the model call (step) begins,\n       * before the provider is called.\n       *\n       * @deprecated Use `onStepStart` instead.\n       */\n      experimental_onStepStart?: Callback<GenerateObjectStepStartEvent>;\n\n      /**\n       * Callback that is called when the model call (step) completes,\n       * with the raw result before JSON parsing.\n       */\n      onStepEnd?: Callback<GenerateObjectStepEndEvent>;\n\n      /**\n       * Callback that is called when the model call (step) completes,\n       * with the raw result before JSON parsing.\n       *\n       * @deprecated Use `onStepEnd` instead.\n       */\n      onStepFinish?: Callback<GenerateObjectStepEndEvent>;\n\n      /**\n       * Callback that is called when the entire operation completes\n       * with the final parsed and validated object.\n       */\n      onFinish?: Callback<GenerateObjectEndEvent<RESULT>>;\n\n      /**\n       * Internal. For test use only. May change without notice.\n       */\n      _internal?: {\n        generateId?: () => string;\n        currentDate?: () => Date;\n      };\n    },\n): Promise<GenerateObjectResult<RESULT>> {\n  const {\n    model: modelArg,\n    output = 'object',\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    maxRetries: maxRetriesArg,\n    abortSignal,\n    headers,\n    experimental_repairText,\n    repairText = experimental_repairText,\n    experimental_telemetry,\n    telemetry = experimental_telemetry,\n    experimental_download: download,\n    providerOptions,\n    onStart,\n    experimental_onStart,\n    onStepStart,\n    experimental_onStepStart,\n    onStepEnd,\n    onStepFinish,\n    onFinish,\n    _internal: {\n      generateId = originalGenerateId,\n      currentDate = () => new Date(),\n    } = {},\n    ...settings\n  } = options;\n\n  const model = resolveLanguageModel(modelArg);\n\n  const enumValues = 'enum' in options ? options.enum : undefined;\n  const {\n    schema: inputSchema,\n    schemaDescription,\n    schemaName,\n  } = 'schema' in options ? options : {};\n\n  validateObjectGenerationInput({\n    output,\n    schema: inputSchema,\n    schemaName,\n    schemaDescription,\n    enumValues,\n  });\n\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  const outputStrategy = getOutputStrategy({\n    output,\n    schema: inputSchema,\n    enumValues,\n  });\n\n  const callSettings = prepareLanguageModelCallOptions(settings);\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const telemetryDispatcher = createTelemetryDispatcher({\n    telemetry,\n  });\n  const resolvedOnStart = onStart ?? experimental_onStart;\n  const resolvedOnStepStart = onStepStart ?? experimental_onStepStart;\n  const resolvedOnStepEnd = onStepEnd ?? onStepFinish;\n\n  const jsonSchema = await outputStrategy.jsonSchema();\n  const callId = generateId();\n\n  await notify({\n    event: {\n      callId,\n      operationId: 'ai.generateObject' as const,\n      provider: model.provider,\n      modelId: model.modelId,\n      system: instructions ?? system,\n      prompt,\n      messages,\n      maxOutputTokens: callSettings.maxOutputTokens,\n      temperature: callSettings.temperature,\n      topP: callSettings.topP,\n      topK: callSettings.topK,\n      presencePenalty: callSettings.presencePenalty,\n      frequencyPenalty: callSettings.frequencyPenalty,\n      seed: callSettings.seed,\n      maxRetries,\n      headers: headersWithUserAgent,\n      providerOptions,\n      output: outputStrategy.type as 'object' | 'array' | 'enum' | 'no-schema',\n      schema: jsonSchema as Record<string, unknown> | undefined,\n      schemaName,\n      schemaDescription,\n    },\n    callbacks: [resolvedOnStart, telemetryDispatcher.onStart],\n  });\n\n  try {\n    const standardizedPrompt = await standardizePrompt({\n      instructions,\n      system,\n      prompt,\n      messages,\n      allowSystemInMessages,\n    } as Prompt);\n\n    const promptMessages = await convertToLanguageModelPrompt({\n      prompt: standardizedPrompt,\n      supportedUrls: await model.supportedUrls,\n      download,\n      provider: model.provider.split('.')[0],\n    });\n\n    await notify({\n      event: {\n        callId,\n        stepNumber: 0 as const,\n        provider: model.provider,\n        modelId: model.modelId,\n        providerOptions,\n        headers: headersWithUserAgent,\n        promptMessages,\n      },\n      callbacks: [resolvedOnStepStart, telemetryDispatcher.onObjectStepStart],\n    });\n\n    const generateResult = await retry(() =>\n      model.doGenerate({\n        responseFormat: {\n          type: 'json',\n          schema: jsonSchema,\n          name: schemaName,\n          description: schemaDescription,\n        },\n        ...prepareLanguageModelCallOptions(settings),\n        prompt: promptMessages,\n        providerOptions,\n        abortSignal,\n        headers: headersWithUserAgent,\n      }),\n    );\n\n    const responseData = {\n      id: generateResult.response?.id ?? generateId(),\n      timestamp: generateResult.response?.timestamp ?? currentDate(),\n      modelId: generateResult.response?.modelId ?? model.modelId,\n      headers: generateResult.response?.headers,\n      body: generateResult.response?.body,\n    };\n\n    const text = extractTextContent(generateResult.content);\n    const reasoning = extractReasoningContent(generateResult.content);\n\n    if (text === undefined) {\n      throw new NoObjectGeneratedError({\n        message: 'No object generated: the model did not return a response.',\n        response: responseData,\n        usage: asLanguageModelUsage(generateResult.usage),\n        finishReason: generateResult.finishReason.unified,\n      });\n    }\n\n    const finishReason = generateResult.finishReason.unified;\n    const usage = asLanguageModelUsage(generateResult.usage);\n    const warnings = generateResult.warnings;\n    const resultProviderMetadata = generateResult.providerMetadata;\n    const request: Omit<LanguageModelRequestMetadata, 'messages'> =\n      generateResult.request ?? {};\n    const response: Omit<LanguageModelResponseMetadata, 'messages'> =\n      responseData;\n\n    logWarnings({\n      warnings,\n      provider: model.provider,\n      model: model.modelId,\n    });\n\n    const stepFinishEvent: GenerateObjectStepEndEvent = {\n      callId,\n      stepNumber: 0 as const,\n      provider: model.provider,\n      modelId: model.modelId,\n      finishReason,\n      usage,\n      objectText: text,\n      msToFirstChunk: undefined,\n      reasoning,\n      warnings,\n      request,\n      response,\n      providerMetadata: resultProviderMetadata,\n    };\n\n    await notify({\n      event: stepFinishEvent,\n      callbacks: [resolvedOnStepEnd, telemetryDispatcher.onObjectStepEnd],\n    });\n\n    const object = await parseAndValidateObjectResultWithRepair(\n      text,\n      outputStrategy,\n      repairText,\n      {\n        response,\n        usage,\n        finishReason,\n      },\n    );\n\n    await notify({\n      event: {\n        callId,\n        object,\n        error: undefined,\n        reasoning,\n        finishReason,\n        usage,\n        warnings,\n        request,\n        response,\n        providerMetadata: resultProviderMetadata,\n      },\n      callbacks: [onFinish, telemetryDispatcher.onEnd],\n    });\n\n    return new DefaultGenerateObjectResult({\n      object,\n      reasoning,\n      finishReason,\n      usage,\n      warnings,\n      request,\n      response,\n      providerMetadata: resultProviderMetadata,\n    });\n  } catch (error) {\n    await telemetryDispatcher.onError?.({ callId, error });\n    throw wrapGatewayError(error);\n  }\n}\n\nclass DefaultGenerateObjectResult<T> implements GenerateObjectResult<T> {\n  readonly object: GenerateObjectResult<T>['object'];\n  readonly finishReason: GenerateObjectResult<T>['finishReason'];\n  readonly usage: GenerateObjectResult<T>['usage'];\n  readonly warnings: GenerateObjectResult<T>['warnings'];\n  readonly providerMetadata: GenerateObjectResult<T>['providerMetadata'];\n  readonly response: GenerateObjectResult<T>['response'];\n  readonly request: GenerateObjectResult<T>['request'];\n  readonly reasoning: GenerateObjectResult<T>['reasoning'];\n\n  constructor(options: {\n    object: GenerateObjectResult<T>['object'];\n    finishReason: GenerateObjectResult<T>['finishReason'];\n    usage: GenerateObjectResult<T>['usage'];\n    warnings: GenerateObjectResult<T>['warnings'];\n    providerMetadata: GenerateObjectResult<T>['providerMetadata'];\n    response: GenerateObjectResult<T>['response'];\n    request: GenerateObjectResult<T>['request'];\n    reasoning: GenerateObjectResult<T>['reasoning'];\n  }) {\n    this.object = options.object;\n    this.finishReason = options.finishReason;\n    this.usage = options.usage;\n    this.warnings = options.warnings;\n    this.providerMetadata = options.providerMetadata;\n    this.response = options.response;\n    this.request = options.request;\n    this.reasoning = options.reasoning;\n  }\n\n  toJsonResponse(init?: ResponseInit): Response {\n    return new Response(JSON.stringify(this.object), {\n      status: init?.status ?? 200,\n      headers: prepareHeaders(init?.headers, {\n        'content-type': 'application/json; charset=utf-8',\n      }),\n    });\n  }\n}\n","import type {\n  LanguageModelV4Content,\n  LanguageModelV4Reasoning,\n} from '@ai-sdk/provider';\n\nexport function extractReasoningContent(\n  content: LanguageModelV4Content[],\n): string | undefined {\n  const parts = content.filter(\n    (content): content is LanguageModelV4Reasoning =>\n      content.type === 'reasoning',\n  );\n\n  return parts.length === 0\n    ? undefined\n    : parts.map(content => content.text).join('\\n');\n}\n","import type {\n  LanguageModelV4Content,\n  LanguageModelV4Text,\n} from '@ai-sdk/provider';\n\nexport function extractTextContent(\n  content: LanguageModelV4Content[],\n): string | undefined {\n  const parts = content.filter(\n    (content): content is LanguageModelV4Text => content.type === 'text',\n  );\n\n  if (parts.length === 0) {\n    return undefined;\n  }\n\n  return parts.map(content => content.text).join('');\n}\n","import {\n  isJSONArray,\n  isJSONObject,\n  TypeValidationError,\n  UnsupportedFunctionalityError,\n  type JSONObject,\n  type JSONSchema7,\n  type JSONValue,\n} from '@ai-sdk/provider';\nimport {\n  asSchema,\n  safeValidateTypes,\n  type FlexibleSchema,\n  type Schema,\n  type ValidationResult,\n} from '@ai-sdk/provider-utils';\nimport { NoObjectGeneratedError } from '../error/no-object-generated-error';\nimport type {\n  FinishReason,\n  LanguageModelResponseMetadata,\n  LanguageModelUsage,\n} from '../types';\nimport {\n  createAsyncIterableStream,\n  type AsyncIterableStream,\n} from '../util/async-iterable-stream';\nimport type { DeepPartial } from '../util/deep-partial';\nimport type { ObjectStreamPart } from './stream-object-result';\n\nexport interface OutputStrategy<PARTIAL, RESULT, ELEMENT_STREAM> {\n  readonly type: 'object' | 'array' | 'enum' | 'no-schema';\n\n  jsonSchema(): Promise<JSONSchema7 | undefined>;\n\n  validatePartialResult({\n    value,\n    textDelta,\n    isFinalDelta,\n  }: {\n    value: JSONValue;\n    textDelta: string;\n    isFirstDelta: boolean;\n    isFinalDelta: boolean;\n    latestObject: PARTIAL | undefined;\n  }): Promise<\n    ValidationResult<{\n      partial: PARTIAL;\n      textDelta: string;\n    }>\n  >;\n  validateFinalResult(\n    value: JSONValue | undefined,\n    context: {\n      text: string;\n      response: Omit<LanguageModelResponseMetadata, 'messages'>;\n      usage: LanguageModelUsage;\n    },\n  ): Promise<ValidationResult<RESULT>>;\n\n  createElementStream(\n    originalStream: ReadableStream<ObjectStreamPart<PARTIAL>>,\n  ): ELEMENT_STREAM;\n}\n\nconst noSchemaOutputStrategy: OutputStrategy<JSONValue, JSONValue, never> = {\n  type: 'no-schema',\n  jsonSchema: async () => undefined,\n\n  async validatePartialResult({ value, textDelta }) {\n    return { success: true, value: { partial: value, textDelta } };\n  },\n\n  async validateFinalResult(\n    value: JSONValue | undefined,\n    context: {\n      text: string;\n      response: LanguageModelResponseMetadata;\n      usage: LanguageModelUsage;\n      finishReason: FinishReason;\n    },\n  ): Promise<ValidationResult<JSONValue>> {\n    return value === undefined\n      ? {\n          success: false,\n          error: new NoObjectGeneratedError({\n            message: 'No object generated: response did not match schema.',\n            text: context.text,\n            response: context.response,\n            usage: context.usage,\n            finishReason: context.finishReason,\n          }),\n        }\n      : { success: true, value };\n  },\n\n  createElementStream() {\n    throw new UnsupportedFunctionalityError({\n      functionality: 'element streams in no-schema mode',\n    });\n  },\n};\n\nconst objectOutputStrategy = <OBJECT>(\n  schema: Schema<OBJECT>,\n): OutputStrategy<DeepPartial<OBJECT>, OBJECT, never> => ({\n  type: 'object',\n  jsonSchema: async () => await schema.jsonSchema,\n\n  async validatePartialResult({ value, textDelta }) {\n    return {\n      success: true,\n      value: {\n        // Note: currently no validation of partial results:\n        partial: value as DeepPartial<OBJECT>,\n        textDelta,\n      },\n    };\n  },\n\n  async validateFinalResult(\n    value: JSONValue | undefined,\n  ): Promise<ValidationResult<OBJECT>> {\n    return safeValidateTypes({ value, schema });\n  },\n\n  createElementStream() {\n    throw new UnsupportedFunctionalityError({\n      functionality: 'element streams in object mode',\n    });\n  },\n});\n\nconst arrayOutputStrategy = <ELEMENT>(\n  schema: Schema<ELEMENT>,\n): OutputStrategy<ELEMENT[], ELEMENT[], AsyncIterableStream<ELEMENT>> => {\n  return {\n    type: 'array',\n\n    // wrap in object that contains array of elements, since most LLMs will not\n    // be able to generate an array directly:\n    // possible future optimization: use arrays directly when model supports grammar-guided generation\n    jsonSchema: async () => {\n      // keep root-level definitions available to root-relative references:\n      const {\n        $schema: _$schema,\n        definitions,\n        $defs,\n        ...itemSchema\n      } = (await schema.jsonSchema) as JSONSchema7 & {\n        $defs?: JSONSchema7['definitions'];\n      };\n\n      return {\n        $schema: 'http://json-schema.org/draft-07/schema#',\n        ...(definitions != null && { definitions }),\n        ...($defs != null && { $defs }),\n        type: 'object',\n        properties: {\n          elements: { type: 'array', items: itemSchema },\n        },\n        required: ['elements'],\n        additionalProperties: false,\n      };\n    },\n\n    async validatePartialResult({\n      value,\n      latestObject,\n      isFirstDelta,\n      isFinalDelta,\n    }) {\n      // check that the value is an object that contains an array of elements:\n      if (!isJSONObject(value) || !isJSONArray(value.elements)) {\n        return {\n          success: false,\n          error: new TypeValidationError({\n            value,\n            cause: 'value must be an object that contains an array of elements',\n          }),\n        };\n      }\n\n      const inputArray = value.elements as Array<JSONObject>;\n      const resultArray: Array<ELEMENT> = [];\n\n      for (let i = 0; i < inputArray.length; i++) {\n        const element = inputArray[i];\n        const result = await safeValidateTypes({ value: element, schema });\n\n        // special treatment for last processed element:\n        // ignore parse or validation failures, since they indicate that the\n        // last element is incomplete and should not be included in the result,\n        // unless it is the final delta\n        if (i === inputArray.length - 1 && !isFinalDelta) {\n          continue;\n        }\n\n        if (!result.success) {\n          return result;\n        }\n\n        resultArray.push(result.value);\n      }\n\n      // calculate delta:\n      const publishedElementCount = latestObject?.length ?? 0;\n\n      let textDelta = '';\n\n      if (isFirstDelta) {\n        textDelta += '[';\n      }\n\n      if (publishedElementCount > 0) {\n        textDelta += ',';\n      }\n\n      textDelta += resultArray\n        .slice(publishedElementCount) // only new elements\n        .map(element => JSON.stringify(element))\n        .join(',');\n\n      if (isFinalDelta) {\n        textDelta += ']';\n      }\n\n      return {\n        success: true,\n        value: {\n          partial: resultArray,\n          textDelta,\n        },\n      };\n    },\n\n    async validateFinalResult(\n      value: JSONValue | undefined,\n    ): Promise<ValidationResult<Array<ELEMENT>>> {\n      // check that the value is an object that contains an array of elements:\n      if (!isJSONObject(value) || !isJSONArray(value.elements)) {\n        return {\n          success: false,\n          error: new TypeValidationError({\n            value,\n            cause: 'value must be an object that contains an array of elements',\n          }),\n        };\n      }\n\n      const inputArray = value.elements as Array<JSONObject>;\n      const resultArray: Array<ELEMENT> = [];\n\n      // check that each element in the array is of the correct type:\n      for (const element of inputArray) {\n        const result = await safeValidateTypes({ value: element, schema });\n        if (!result.success) {\n          return result;\n        }\n        resultArray.push(result.value);\n      }\n\n      return { success: true, value: resultArray };\n    },\n\n    createElementStream(\n      originalStream: ReadableStream<ObjectStreamPart<ELEMENT[]>>,\n    ) {\n      let publishedElements = 0;\n\n      return createAsyncIterableStream(\n        originalStream.pipeThrough(\n          new TransformStream<ObjectStreamPart<ELEMENT[]>, ELEMENT>({\n            transform(chunk, controller) {\n              switch (chunk.type) {\n                case 'object': {\n                  const array = chunk.object;\n\n                  // publish new elements one by one:\n                  for (\n                    ;\n                    publishedElements < array.length;\n                    publishedElements++\n                  ) {\n                    controller.enqueue(array[publishedElements]);\n                  }\n\n                  break;\n                }\n\n                case 'text-delta':\n                case 'finish':\n                case 'error': // suppress error (use onError instead)\n                  break;\n\n                default: {\n                  const _exhaustiveCheck: never = chunk;\n                  throw new Error(\n                    `Unsupported chunk type: ${_exhaustiveCheck}`,\n                  );\n                }\n              }\n            },\n          }),\n        ),\n      );\n    },\n  };\n};\n\nconst enumOutputStrategy = <ENUM extends string>(\n  enumValues: Array<ENUM>,\n): OutputStrategy<string, ENUM, never> => {\n  return {\n    type: 'enum',\n\n    // wrap in object that contains result, since most LLMs will not\n    // be able to generate an enum value directly:\n    // possible future optimization: use enums directly when model supports top-level enums\n    jsonSchema: async () => ({\n      $schema: 'http://json-schema.org/draft-07/schema#',\n      type: 'object',\n      properties: {\n        result: { type: 'string', enum: enumValues },\n      },\n      required: ['result'],\n      additionalProperties: false,\n    }),\n\n    async validateFinalResult(\n      value: JSONValue | undefined,\n    ): Promise<ValidationResult<ENUM>> {\n      // check that the value is an object that contains an array of elements:\n      if (!isJSONObject(value) || typeof value.result !== 'string') {\n        return {\n          success: false,\n          error: new TypeValidationError({\n            value,\n            cause:\n              'value must be an object that contains a string in the \"result\" property.',\n          }),\n        };\n      }\n\n      const result = value.result as string;\n\n      return enumValues.includes(result as ENUM)\n        ? { success: true, value: result as ENUM }\n        : {\n            success: false,\n            error: new TypeValidationError({\n              value,\n              cause: 'value must be a string in the enum',\n            }),\n          };\n    },\n\n    async validatePartialResult({ value, textDelta }) {\n      if (!isJSONObject(value) || typeof value.result !== 'string') {\n        return {\n          success: false,\n          error: new TypeValidationError({\n            value,\n            cause:\n              'value must be an object that contains a string in the \"result\" property.',\n          }),\n        };\n      }\n\n      const result = value.result as string;\n      const possibleEnumValues = enumValues.filter(enumValue =>\n        enumValue.startsWith(result),\n      );\n\n      if (value.result.length === 0 || possibleEnumValues.length === 0) {\n        return {\n          success: false,\n          error: new TypeValidationError({\n            value,\n            cause: 'value must be a string in the enum',\n          }),\n        };\n      }\n\n      return {\n        success: true,\n        value: {\n          partial:\n            possibleEnumValues.length > 1 ? result : possibleEnumValues[0],\n          textDelta,\n        },\n      };\n    },\n\n    createElementStream() {\n      // no streaming in enum mode\n      throw new UnsupportedFunctionalityError({\n        functionality: 'element streams in enum mode',\n      });\n    },\n  };\n};\n\nexport function getOutputStrategy<SCHEMA>({\n  output,\n  schema,\n  enumValues,\n}: {\n  output: 'object' | 'array' | 'enum' | 'no-schema';\n  schema?: FlexibleSchema<SCHEMA>;\n  enumValues?: Array<SCHEMA>;\n}): OutputStrategy<any, any, any> {\n  switch (output) {\n    case 'object':\n      return objectOutputStrategy(asSchema(schema!));\n    case 'array':\n      return arrayOutputStrategy(asSchema(schema!));\n    case 'enum':\n      return enumOutputStrategy(enumValues! as Array<string>);\n    case 'no-schema':\n      return noSchemaOutputStrategy;\n    default: {\n      const _exhaustiveCheck: never = output;\n      throw new Error(`Unsupported output: ${_exhaustiveCheck}`);\n    }\n  }\n}\n","import { JSONParseError, TypeValidationError } from '@ai-sdk/provider';\nimport { safeParseJSON } from '@ai-sdk/provider-utils';\nimport { NoObjectGeneratedError } from '../error/no-object-generated-error';\nimport type {\n  FinishReason,\n  LanguageModelResponseMetadata,\n  LanguageModelUsage,\n} from '../types';\nimport type { OutputStrategy } from './output-strategy';\nimport type { RepairTextFunction } from './repair-text';\n\n/**\n * Parses and validates a result string by parsing it as JSON and validating against the output strategy.\n *\n * @param result - The result string to parse and validate\n * @param outputStrategy - The output strategy containing validation logic\n * @param context - Additional context for error reporting\n * @returns The validated result\n * @throws NoObjectGeneratedError if parsing or validation fails\n */\nasync function parseAndValidateObjectResult<RESULT>(\n  result: string,\n  outputStrategy: OutputStrategy<any, RESULT, any>,\n  context: {\n    response: Omit<LanguageModelResponseMetadata, 'messages'>;\n    usage: LanguageModelUsage;\n    finishReason: FinishReason;\n  },\n): Promise<RESULT> {\n  const parseResult = await safeParseJSON({ text: result });\n\n  if (!parseResult.success) {\n    throw new NoObjectGeneratedError({\n      message: 'No object generated: could not parse the response.',\n      cause: parseResult.error,\n      text: result,\n      response: context.response,\n      usage: context.usage,\n      finishReason: context.finishReason,\n    });\n  }\n\n  const validationResult = await outputStrategy.validateFinalResult(\n    parseResult.value,\n    {\n      text: result,\n      response: context.response,\n      usage: context.usage,\n    },\n  );\n\n  if (!validationResult.success) {\n    throw new NoObjectGeneratedError({\n      message: 'No object generated: response did not match schema.',\n      cause: validationResult.error,\n      text: result,\n      response: context.response,\n      usage: context.usage,\n      finishReason: context.finishReason,\n    });\n  }\n\n  return validationResult.value;\n}\n\n/**\n * Parses and validates a result string by parsing it as JSON and validating against the output strategy.\n * If the result cannot be parsed, it attempts to repair the result using the repairText function.\n *\n * @param result - The result string to parse and validate\n * @param outputStrategy - The output strategy containing validation logic\n * @param repairText - A function that attempts to repair the result string\n * @param context - Additional context for error reporting\n * @returns The validated result\n * @throws NoObjectGeneratedError if parsing or validation fails\n */\nexport async function parseAndValidateObjectResultWithRepair<RESULT>(\n  result: string,\n  outputStrategy: OutputStrategy<any, RESULT, any>,\n  repairText: RepairTextFunction | undefined,\n  context: {\n    response: Omit<LanguageModelResponseMetadata, 'messages'>;\n    usage: LanguageModelUsage;\n    finishReason: FinishReason;\n  },\n): Promise<RESULT> {\n  try {\n    return await parseAndValidateObjectResult(result, outputStrategy, context);\n  } catch (error) {\n    if (\n      repairText != null &&\n      NoObjectGeneratedError.isInstance(error) &&\n      (JSONParseError.isInstance(error.cause) ||\n        TypeValidationError.isInstance(error.cause))\n    ) {\n      const repairedText = await repairText({\n        text: result,\n        error: error.cause,\n      });\n      if (repairedText === null) {\n        throw error;\n      }\n      return await parseAndValidateObjectResult(\n        repairedText,\n        outputStrategy,\n        context,\n      );\n    }\n    throw error;\n  }\n}\n","import type { FlexibleSchema } from '@ai-sdk/provider-utils';\nimport { InvalidArgumentError } from '../error/invalid-argument-error';\n\nexport function validateObjectGenerationInput({\n  output,\n  schema,\n  schemaName,\n  schemaDescription,\n  enumValues,\n}: {\n  output?: 'object' | 'array' | 'enum' | 'no-schema';\n  schema?: FlexibleSchema<unknown>;\n  schemaName?: string;\n  schemaDescription?: string;\n  enumValues?: Array<unknown>;\n}) {\n  if (\n    output != null &&\n    output !== 'object' &&\n    output !== 'array' &&\n    output !== 'enum' &&\n    output !== 'no-schema'\n  ) {\n    throw new InvalidArgumentError({\n      parameter: 'output',\n      value: output,\n      message: 'Invalid output type.',\n    });\n  }\n\n  if (output === 'no-schema') {\n    if (schema != null) {\n      throw new InvalidArgumentError({\n        parameter: 'schema',\n        value: schema,\n        message: 'Schema is not supported for no-schema output.',\n      });\n    }\n\n    if (schemaDescription != null) {\n      throw new InvalidArgumentError({\n        parameter: 'schemaDescription',\n        value: schemaDescription,\n        message: 'Schema description is not supported for no-schema output.',\n      });\n    }\n\n    if (schemaName != null) {\n      throw new InvalidArgumentError({\n        parameter: 'schemaName',\n        value: schemaName,\n        message: 'Schema name is not supported for no-schema output.',\n      });\n    }\n\n    if (enumValues != null) {\n      throw new InvalidArgumentError({\n        parameter: 'enumValues',\n        value: enumValues,\n        message: 'Enum values are not supported for no-schema output.',\n      });\n    }\n  }\n\n  if (output === 'object') {\n    if (schema == null) {\n      throw new InvalidArgumentError({\n        parameter: 'schema',\n        value: schema,\n        message: 'Schema is required for object output.',\n      });\n    }\n\n    if (enumValues != null) {\n      throw new InvalidArgumentError({\n        parameter: 'enumValues',\n        value: enumValues,\n        message: 'Enum values are not supported for object output.',\n      });\n    }\n  }\n\n  if (output === 'array') {\n    if (schema == null) {\n      throw new InvalidArgumentError({\n        parameter: 'schema',\n        value: schema,\n        message: 'Element schema is required for array output.',\n      });\n    }\n\n    if (enumValues != null) {\n      throw new InvalidArgumentError({\n        parameter: 'enumValues',\n        value: enumValues,\n        message: 'Enum values are not supported for array output.',\n      });\n    }\n  }\n\n  if (output === 'enum') {\n    if (schema != null) {\n      throw new InvalidArgumentError({\n        parameter: 'schema',\n        value: schema,\n        message: 'Schema is not supported for enum output.',\n      });\n    }\n\n    if (schemaDescription != null) {\n      throw new InvalidArgumentError({\n        parameter: 'schemaDescription',\n        value: schemaDescription,\n        message: 'Schema description is not supported for enum output.',\n      });\n    }\n\n    if (schemaName != null) {\n      throw new InvalidArgumentError({\n        parameter: 'schemaName',\n        value: schemaName,\n        message: 'Schema name is not supported for enum output.',\n      });\n    }\n\n    if (enumValues == null) {\n      throw new InvalidArgumentError({\n        parameter: 'enumValues',\n        value: enumValues,\n        message: 'Enum values are required for enum output.',\n      });\n    }\n\n    for (const value of enumValues) {\n      if (typeof value !== 'string') {\n        throw new InvalidArgumentError({\n          parameter: 'enumValues',\n          value,\n          message: 'Enum values must be strings.',\n        });\n      }\n    }\n  }\n}\n","import type {\n  JSONValue,\n  LanguageModelV4FinishReason,\n  LanguageModelV4StreamPart,\n  LanguageModelV4Usage,\n  SharedV4ProviderMetadata,\n  SharedV4Warning,\n} from '@ai-sdk/provider';\nimport {\n  createIdGenerator,\n  DelayedPromise,\n  type InferSchema,\n  type FlexibleSchema,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport type { ServerResponse } from 'http';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveLanguageModel } from '../model/resolve-model';\nimport type { LanguageModelCallOptions } from '../prompt/language-model-call-options';\nimport { prepareLanguageModelCallOptions } from '../prompt/prepare-language-model-call-options';\nimport type { RequestOptions } from '../prompt/request-options';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport type { Prompt } from '../prompt/prompt';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport { wrapGatewayError } from '../prompt/wrap-gateway-error';\nimport { createTelemetryDispatcher } from '../telemetry/create-telemetry-dispatcher';\nimport type { TelemetryOptions } from '../telemetry/telemetry-options';\nimport { createTextStreamResponse } from '../text-stream/create-text-stream-response';\nimport { pipeTextStreamToResponse } from '../text-stream/pipe-text-stream-to-response';\nimport type {\n  CallWarning,\n  FinishReason,\n  LanguageModel,\n} from '../types/language-model';\nimport type { LanguageModelRequestMetadata } from '../types/language-model-request-metadata';\nimport type { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';\nimport type { ProviderMetadata } from '../types/provider-metadata';\nimport {\n  asLanguageModelUsage,\n  createNullLanguageModelUsage,\n  type LanguageModelUsage,\n} from '../types/usage';\nimport { isDeepEqualData, parsePartialJson, type DeepPartial } from '../util';\nimport {\n  createAsyncIterableStream,\n  type AsyncIterableStream,\n} from '../util/async-iterable-stream';\nimport type { Callback } from '../util/callback';\nimport { createStitchableStream } from '../util/create-stitchable-stream';\nimport type { DownloadFunction } from '../util/download/download-function';\nimport { notify } from '../util/notify';\nimport { now as originalNow } from '../util/now';\nimport { prepareRetries } from '../util/prepare-retries';\nimport type {\n  GenerateObjectEndEvent,\n  GenerateObjectStartEvent,\n  GenerateObjectStepEndEvent,\n  GenerateObjectStepStartEvent,\n} from './structured-output-events';\nimport { getOutputStrategy, type OutputStrategy } from './output-strategy';\nimport { parseAndValidateObjectResultWithRepair } from './parse-and-validate-object-result';\nimport type { RepairTextFunction } from './repair-text';\nimport type {\n  ObjectStreamPart,\n  StreamObjectResult,\n} from './stream-object-result';\nimport { validateObjectGenerationInput } from './validate-object-generation-input';\n\nconst originalGenerateId = createIdGenerator({ prefix: 'aiobj', size: 24 });\n\nasync function markPromiseAsHandled<T>(promise: Promise<T>): Promise<void> {\n  try {\n    await promise;\n  } catch {}\n}\n\n/**\n * Callback that is set using the `onError` option.\n *\n * @param event - The event that is passed to the callback.\n */\nexport type StreamObjectOnErrorCallback = (event: {\n  error: unknown;\n}) => Promise<void> | void;\n\n/**\n * Callback that is set using the `onFinish` option.\n *\n * @param event - The event that is passed to the callback.\n */\nexport type StreamObjectOnFinishCallback<RESULT> = (event: {\n  /**\n   * The token usage of the generated response.\n   */\n  usage: LanguageModelUsage;\n\n  /**\n   * The generated object. Can be undefined if the final object does not match the schema.\n   */\n  object: RESULT | undefined;\n\n  /**\n   * Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n   */\n  error: unknown | undefined;\n\n  /**\n   * Response metadata.\n   */\n  response: LanguageModelResponseMetadata;\n\n  /**\n   * Warnings from the model provider (e.g. unsupported settings).\n   */\n  warnings?: CallWarning[];\n\n  /**\n   * Additional provider-specific metadata. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerMetadata: ProviderMetadata | undefined;\n}) => Promise<void> | void;\n\n/**\n * Generate a structured, typed object for a given prompt and schema using a language model.\n *\n * This function streams the output. If you do not want to stream the output, use `generateObject` instead.\n *\n * @param model - The language model to use.\n *\n * @param system - A system message that will be part of the prompt.\n * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n * @param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false.\n *\n * @param maxOutputTokens - Maximum number of tokens to generate.\n * @param temperature - Temperature setting.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topP - Nucleus sampling.\n * The value is passed through to the provider. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n * @param topK - Only sample from the top K options for each subsequent token.\n * Used to remove \"long tail\" low probability responses.\n * Recommended for advanced use cases only. You usually only need to use temperature.\n * @param presencePenalty - Presence penalty setting.\n * It affects the likelihood of the model to repeat information that is already in the prompt.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param frequencyPenalty - Frequency penalty setting.\n * It affects the likelihood of the model to repeatedly use the same words or phrases.\n * The value is passed through to the provider. The range depends on the provider and model.\n * @param stopSequences - Stop sequences.\n * If set, the model will stop generating text when one of the stop sequences is generated.\n * @param seed - The seed (integer) to use for random sampling.\n * If set and supported by the model, calls will generate deterministic results.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @param schema - The schema of the object that the model should generate.\n * @param schemaName - Optional name of the output that should be generated.\n * Used by some providers for additional LLM guidance, e.g.\n * via tool or schema name.\n * @param schemaDescription - Optional description of the output that should be generated.\n * Used by some providers for additional LLM guidance, e.g.\n * via tool or schema description.\n *\n * @param output - The type of the output.\n *\n * - 'object': The output is an object.\n * - 'array': The output is an array.\n * - 'enum': The output is an enum.\n * - 'no-schema': The output is not a schema.\n *\n * @param repairText - A function that attempts to repair the raw output of the model\n * to enable JSON parsing.\n * @param experimental_repairText - Deprecated alias for `repairText`.\n *\n * @param telemetry - Optional telemetry configuration.\n *\n * @param providerOptions - Additional provider-specific options. They are passed through\n * to the provider from the AI SDK and enable provider-specific\n * functionality that can be fully encapsulated in the provider.\n *\n * @returns\n * A result object for accessing the partial object stream and additional information.\n *\n * @deprecated Use `streamText` with an `output` setting instead.\n */\nexport function streamObject<\n  SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<JSONValue>,\n  OUTPUT extends 'object' | 'array' | 'enum' | 'no-schema' =\n    InferSchema<SCHEMA> extends string ? 'enum' : 'object',\n  RESULT = OUTPUT extends 'array'\n    ? Array<InferSchema<SCHEMA>>\n    : InferSchema<SCHEMA>,\n>(\n  options: Omit<LanguageModelCallOptions, 'stopSequences'> &\n    Omit<RequestOptions, 'timeout'> &\n    Prompt &\n    (OUTPUT extends 'enum'\n      ? {\n          /**\n           * The enum values that the model should use.\n           */\n          enum: Array<RESULT>;\n          output: 'enum';\n        }\n      : OUTPUT extends 'no-schema'\n        ? {}\n        : {\n            /**\n             * The schema of the object that the model should generate.\n             */\n            schema: SCHEMA;\n\n            /**\n             * Optional name of the output that should be generated.\n             * Used by some providers for additional LLM guidance, e.g.\n             * via tool or schema name.\n             */\n            schemaName?: string;\n\n            /**\n             * Optional description of the output that should be generated.\n             * Used by some providers for additional LLM guidance, e.g.\n             * via tool or schema description.\n             */\n            schemaDescription?: string;\n          }) & {\n      output?: OUTPUT;\n\n      /**\n       * The language model to use.\n       */\n      model: LanguageModel;\n\n      /**\n       * A function that attempts to repair the raw output of the model\n       * to enable JSON parsing.\n       */\n      repairText?: RepairTextFunction;\n\n      /**\n       * A function that attempts to repair the raw output of the model\n       * to enable JSON parsing.\n       *\n       * @deprecated Use `repairText` instead.\n       */\n      experimental_repairText?: RepairTextFunction;\n\n      /**\n       * Optional telemetry configuration.\n       */\n      telemetry?: TelemetryOptions;\n\n      /**\n       * Optional telemetry configuration.\n       *\n       * @deprecated Use `telemetry` instead. This alias will be removed in a future major release.\n       */\n      experimental_telemetry?: TelemetryOptions;\n\n      /**\n       * Custom download function to use for URLs.\n       *\n       * By default, files are downloaded if the model does not support the URL for the given media type.\n       */\n      experimental_download?: DownloadFunction | undefined;\n\n      /**\n       * Additional provider-specific options. They are passed through\n       * to the provider from the AI SDK and enable provider-specific\n       * functionality that can be fully encapsulated in the provider.\n       */\n      providerOptions?: ProviderOptions;\n\n      /**\n       * Callback that is called when the streamObject operation begins,\n       * before the LLM call is made.\n       */\n      onStart?: Callback<GenerateObjectStartEvent>;\n\n      /**\n       * Callback that is called when the streamObject operation begins,\n       * before the LLM call is made.\n       *\n       * @deprecated Use `onStart` instead.\n       */\n      experimental_onStart?: Callback<GenerateObjectStartEvent>;\n\n      /**\n       * Callback that is called when the model call (step) begins,\n       * before the provider is called.\n       */\n      onStepStart?: Callback<GenerateObjectStepStartEvent>;\n\n      /**\n       * Callback that is called when the model call (step) begins,\n       * before the provider is called.\n       *\n       * @deprecated Use `onStepStart` instead.\n       */\n      experimental_onStepStart?: Callback<GenerateObjectStepStartEvent>;\n\n      /**\n       * Callback that is called when the model streaming step completes,\n       * with the raw accumulated text before final schema validation.\n       */\n      onStepEnd?: Callback<GenerateObjectStepEndEvent>;\n\n      /**\n       * Callback that is called when the model streaming step completes,\n       * with the raw accumulated text before final schema validation.\n       *\n       * @deprecated Use `onStepEnd` instead.\n       */\n      onStepFinish?: Callback<GenerateObjectStepEndEvent>;\n\n      /**\n       * Callback that is invoked when an error occurs during streaming.\n       * You can use it to log errors.\n       * The stream processing will pause until the callback promise is resolved.\n       */\n      onError?: StreamObjectOnErrorCallback;\n\n      /**\n       * Callback that is called when the LLM response and the final object validation are finished.\n       */\n      onFinish?: Callback<GenerateObjectEndEvent<RESULT>>;\n\n      /**\n       * Internal. For test use only. May change without notice.\n       */\n      _internal?: {\n        generateId?: () => string;\n        currentDate?: () => Date;\n        now?: () => number;\n      };\n    },\n): StreamObjectResult<\n  OUTPUT extends 'enum'\n    ? string\n    : OUTPUT extends 'array'\n      ? RESULT\n      : DeepPartial<RESULT>,\n  OUTPUT extends 'array' ? RESULT : RESULT,\n  OUTPUT extends 'array'\n    ? RESULT extends Array<infer U>\n      ? AsyncIterableStream<U>\n      : never\n    : never\n> {\n  const {\n    model,\n    output = 'object',\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    maxRetries,\n    abortSignal,\n    headers,\n    experimental_repairText,\n    repairText = experimental_repairText,\n    experimental_telemetry,\n    telemetry = experimental_telemetry,\n    experimental_download: download,\n    providerOptions,\n    onStart,\n    experimental_onStart,\n    onStepStart,\n    experimental_onStepStart,\n    onStepEnd,\n    onStepFinish,\n    onError = ({ error }: { error: unknown }) => {\n      console.error(error);\n    },\n    onFinish,\n    _internal: {\n      generateId = originalGenerateId,\n      currentDate = () => new Date(),\n      now = originalNow,\n    } = {},\n    ...settings\n  } = options;\n\n  const enumValues =\n    'enum' in options && options.enum ? options.enum : undefined;\n\n  const {\n    schema: inputSchema,\n    schemaDescription,\n    schemaName,\n  } = 'schema' in options ? options : {};\n\n  validateObjectGenerationInput({\n    output,\n    schema: inputSchema,\n    schemaName,\n    schemaDescription,\n    enumValues,\n  });\n\n  const outputStrategy = getOutputStrategy({\n    output,\n    schema: inputSchema,\n    enumValues,\n  });\n\n  return new DefaultStreamObjectResult({\n    model,\n    telemetry,\n    headers,\n    settings,\n    maxRetries,\n    abortSignal,\n    outputStrategy,\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    schemaName,\n    schemaDescription,\n    providerOptions,\n    repairText,\n    onStart: onStart ?? experimental_onStart,\n    onStepStart: onStepStart ?? experimental_onStepStart,\n    onStepFinish: onStepEnd ?? onStepFinish,\n    onError,\n    onFinish,\n    download,\n    generateId,\n    currentDate,\n    now,\n  });\n}\n\nclass DefaultStreamObjectResult<\n  PARTIAL,\n  RESULT,\n  ELEMENT_STREAM,\n> implements StreamObjectResult<PARTIAL, RESULT, ELEMENT_STREAM> {\n  private readonly _object = new DelayedPromise<RESULT>();\n  private readonly _usage = new DelayedPromise<LanguageModelUsage>();\n  private readonly _providerMetadata = new DelayedPromise<\n    ProviderMetadata | undefined\n  >();\n  private readonly _warnings = new DelayedPromise<CallWarning[] | undefined>();\n  private readonly _request = new DelayedPromise<\n    Omit<LanguageModelRequestMetadata, 'messages'>\n  >();\n  private readonly _response = new DelayedPromise<\n    Omit<LanguageModelResponseMetadata, 'messages'>\n  >();\n  private readonly _finishReason = new DelayedPromise<FinishReason>();\n\n  private readonly baseStream: ReadableStream<ObjectStreamPart<PARTIAL>>;\n\n  private readonly outputStrategy: OutputStrategy<\n    PARTIAL,\n    RESULT,\n    ELEMENT_STREAM\n  >;\n\n  constructor({\n    model: modelArg,\n    headers,\n    telemetry,\n    settings,\n    maxRetries: maxRetriesArg,\n    abortSignal,\n    outputStrategy,\n    instructions,\n    system,\n    prompt,\n    messages,\n    allowSystemInMessages,\n    schemaName,\n    schemaDescription,\n    providerOptions,\n    repairText,\n    onStart,\n    onStepStart,\n    onStepFinish,\n    onError,\n    onFinish,\n    download,\n    generateId,\n    currentDate,\n    now,\n  }: {\n    model: LanguageModel;\n    telemetry: TelemetryOptions | undefined;\n    headers: Record<string, string | undefined> | undefined;\n    settings: LanguageModelCallOptions;\n    maxRetries: number | undefined;\n    abortSignal: AbortSignal | undefined;\n    outputStrategy: OutputStrategy<PARTIAL, RESULT, ELEMENT_STREAM>;\n    instructions: Prompt['instructions'];\n    system: Prompt['system'];\n    prompt: Prompt['prompt'];\n    messages: Prompt['messages'];\n    allowSystemInMessages: Prompt['allowSystemInMessages'];\n    schemaName: string | undefined;\n    schemaDescription: string | undefined;\n    providerOptions: ProviderOptions | undefined;\n    repairText: RepairTextFunction | undefined;\n    onStart: Callback<GenerateObjectStartEvent> | undefined;\n    onStepStart: Callback<GenerateObjectStepStartEvent> | undefined;\n    onStepFinish: Callback<GenerateObjectStepEndEvent> | undefined;\n    onError: StreamObjectOnErrorCallback;\n    onFinish: Callback<GenerateObjectEndEvent<RESULT>> | undefined;\n    download: DownloadFunction | undefined;\n    generateId: () => string;\n    currentDate: () => Date;\n    now: () => number;\n  }) {\n    const model = resolveLanguageModel(modelArg);\n\n    const { maxRetries, retry } = prepareRetries({\n      maxRetries: maxRetriesArg,\n      abortSignal,\n    });\n\n    const callSettings = prepareLanguageModelCallOptions(settings);\n\n    const telemetryDispatcher = createTelemetryDispatcher({\n      telemetry,\n    });\n\n    const self = this;\n\n    const stitchableStream =\n      createStitchableStream<ObjectStreamPart<PARTIAL>>();\n\n    const eventProcessor = new TransformStream<\n      ObjectStreamPart<PARTIAL>,\n      ObjectStreamPart<PARTIAL>\n    >({\n      transform(chunk, controller) {\n        controller.enqueue(chunk);\n\n        if (chunk.type === 'error') {\n          void notify({\n            event: { error: wrapGatewayError(chunk.error) },\n            callbacks: onError,\n          });\n        }\n      },\n    });\n\n    this.baseStream = stitchableStream.stream.pipeThrough(eventProcessor);\n\n    const callId = generateId();\n\n    (async () => {\n      const jsonSchema = await outputStrategy.jsonSchema();\n\n      await notify({\n        event: {\n          callId,\n          operationId: 'ai.streamObject' as const,\n          provider: model.provider,\n          modelId: model.modelId,\n          system: instructions ?? system,\n          prompt,\n          messages,\n          maxOutputTokens: callSettings.maxOutputTokens,\n          temperature: callSettings.temperature,\n          topP: callSettings.topP,\n          topK: callSettings.topK,\n          presencePenalty: callSettings.presencePenalty,\n          frequencyPenalty: callSettings.frequencyPenalty,\n          seed: callSettings.seed,\n          maxRetries,\n          headers,\n          providerOptions,\n          output: outputStrategy.type as\n            | 'object'\n            | 'array'\n            | 'enum'\n            | 'no-schema',\n          schema: jsonSchema as Record<string, unknown> | undefined,\n          schemaName,\n          schemaDescription,\n        },\n        callbacks: [onStart, telemetryDispatcher.onStart],\n      });\n\n      const standardizedPrompt = await standardizePrompt({\n        instructions,\n        system,\n        prompt,\n        messages,\n        allowSystemInMessages,\n      } as Prompt);\n\n      const callOptions = {\n        responseFormat: {\n          type: 'json' as const,\n          schema: jsonSchema,\n          name: schemaName,\n          description: schemaDescription,\n        },\n        ...prepareLanguageModelCallOptions(settings),\n        prompt: await convertToLanguageModelPrompt({\n          prompt: standardizedPrompt,\n          supportedUrls: await model.supportedUrls,\n          download,\n          provider: model.provider.split('.')[0],\n        }),\n        providerOptions,\n        abortSignal,\n        headers,\n        includeRawChunks: false,\n      };\n\n      await notify({\n        event: {\n          callId,\n          stepNumber: 0 as const,\n          provider: model.provider,\n          modelId: model.modelId,\n          providerOptions,\n          headers,\n          promptMessages: callOptions.prompt,\n        },\n        callbacks: [onStepStart, telemetryDispatcher.onObjectStepStart],\n      });\n\n      const transformer: Transformer<\n        LanguageModelV4StreamPart,\n        ObjectStreamInputPart\n      > = {\n        transform: (chunk, controller) => {\n          switch (chunk.type) {\n            case 'text-delta':\n              controller.enqueue(chunk.delta);\n              break;\n            case 'response-metadata':\n            case 'finish':\n            case 'error':\n            case 'stream-start':\n              controller.enqueue(chunk);\n              break;\n          }\n        },\n      };\n\n      const startTimestampMs = now();\n      const { stream, response, request } = await retry(() =>\n        model.doStream(callOptions),\n      );\n\n      self._request.resolve(request ?? {});\n\n      let warnings: SharedV4Warning[] | undefined;\n      let usage: LanguageModelUsage = createNullLanguageModelUsage();\n      let finishReason: FinishReason | undefined;\n      let providerMetadata: ProviderMetadata | undefined;\n      let object: RESULT | undefined;\n      let error: unknown | undefined;\n      let terminalError: { error: unknown } | undefined;\n      let msToFirstChunk: number | undefined = undefined;\n\n      let accumulatedText = '';\n      let textDelta = '';\n      let fullResponse: {\n        id: string;\n        timestamp: Date;\n        modelId: string;\n      } = {\n        id: generateId(),\n        timestamp: currentDate(),\n        modelId: model.modelId,\n      };\n\n      let latestObjectJson: JSONValue | undefined = undefined;\n      let latestObject: PARTIAL | undefined = undefined;\n      let isFirstChunk = true;\n      let isFirstDelta = true;\n\n      const transformedStream = stream\n        .pipeThrough(new TransformStream(transformer))\n        .pipeThrough(\n          new TransformStream<\n            string | ObjectStreamInputPart,\n            ObjectStreamPart<PARTIAL>\n          >({\n            async transform(chunk, controller): Promise<void> {\n              if (typeof chunk === 'object' && chunk.type === 'stream-start') {\n                warnings = chunk.warnings;\n                return;\n              }\n\n              if (isFirstChunk) {\n                msToFirstChunk = now() - startTimestampMs;\n                isFirstChunk = false;\n              }\n\n              if (typeof chunk === 'string') {\n                accumulatedText += chunk;\n                textDelta += chunk;\n\n                const { value: currentObjectJson, state: parseState } =\n                  await parsePartialJson(accumulatedText);\n\n                if (\n                  currentObjectJson !== undefined &&\n                  !isDeepEqualData(latestObjectJson, currentObjectJson)\n                ) {\n                  const validationResult =\n                    await outputStrategy.validatePartialResult({\n                      value: currentObjectJson,\n                      textDelta,\n                      latestObject,\n                      isFirstDelta,\n                      isFinalDelta: parseState === 'successful-parse',\n                    });\n\n                  if (\n                    validationResult.success &&\n                    !isDeepEqualData(\n                      latestObject,\n                      validationResult.value.partial,\n                    )\n                  ) {\n                    latestObjectJson = currentObjectJson;\n                    latestObject = validationResult.value.partial;\n\n                    controller.enqueue({\n                      type: 'object',\n                      object: latestObject,\n                    });\n\n                    controller.enqueue({\n                      type: 'text-delta',\n                      textDelta: validationResult.value.textDelta,\n                    });\n\n                    textDelta = '';\n                    isFirstDelta = false;\n                  }\n                }\n\n                return;\n              }\n\n              switch (chunk.type) {\n                case 'response-metadata': {\n                  fullResponse = {\n                    id: chunk.id ?? fullResponse.id,\n                    timestamp: chunk.timestamp ?? fullResponse.timestamp,\n                    modelId: chunk.modelId ?? fullResponse.modelId,\n                  };\n                  break;\n                }\n\n                case 'error': {\n                  if (terminalError === undefined) {\n                    const wrappedError = wrapGatewayError(chunk.error);\n                    terminalError = { error: wrappedError };\n                    error = wrappedError;\n                    finishReason = 'error';\n                    self.rejectResultPromises(wrappedError);\n                  }\n\n                  controller.enqueue(chunk);\n                  break;\n                }\n\n                case 'finish': {\n                  if (textDelta !== '') {\n                    controller.enqueue({ type: 'text-delta', textDelta });\n                  }\n\n                  finishReason =\n                    terminalError === undefined\n                      ? chunk.finishReason.unified\n                      : 'error';\n\n                  usage = asLanguageModelUsage(chunk.usage);\n                  providerMetadata = chunk.providerMetadata;\n\n                  controller.enqueue({\n                    ...chunk,\n                    finishReason,\n                    usage,\n                    response: fullResponse,\n                  });\n\n                  logWarnings({\n                    warnings: warnings ?? [],\n                    provider: model.provider,\n                    model: model.modelId,\n                  });\n\n                  if (terminalError !== undefined) {\n                    break;\n                  }\n\n                  self._usage.resolve(usage);\n                  self._providerMetadata.resolve(providerMetadata);\n                  self._warnings.resolve(warnings);\n                  self._response.resolve({\n                    ...fullResponse,\n                    headers: response?.headers,\n                  });\n                  self._finishReason.resolve(finishReason ?? 'other');\n\n                  try {\n                    object = await parseAndValidateObjectResultWithRepair(\n                      accumulatedText,\n                      outputStrategy,\n                      repairText,\n                      {\n                        response: fullResponse,\n                        usage,\n                        finishReason,\n                      },\n                    );\n                    self._object.resolve(object);\n                  } catch (e) {\n                    error = e;\n                    self._object.reject(e);\n                  }\n                  break;\n                }\n\n                default: {\n                  controller.enqueue(chunk);\n                  break;\n                }\n              }\n            },\n\n            async flush(controller) {\n              try {\n                const finalUsage = usage ?? {\n                  promptTokens: NaN,\n                  completionTokens: NaN,\n                  totalTokens: NaN,\n                };\n\n                await notify({\n                  event: {\n                    callId,\n                    stepNumber: 0 as const,\n                    provider: model.provider,\n                    modelId: model.modelId,\n                    finishReason: finishReason ?? 'other',\n                    usage: finalUsage,\n                    objectText: accumulatedText,\n                    msToFirstChunk,\n                    reasoning: undefined,\n                    warnings,\n                    request: request ?? {},\n                    response: {\n                      ...fullResponse,\n                      headers: response?.headers,\n                    },\n                    providerMetadata,\n                  },\n                  callbacks: [\n                    onStepFinish,\n                    telemetryDispatcher.onObjectStepEnd,\n                  ],\n                });\n\n                await notify({\n                  event: {\n                    callId,\n                    object,\n                    error,\n                    reasoning: undefined,\n                    finishReason: finishReason ?? 'other',\n                    usage: finalUsage,\n                    warnings,\n                    request: request ?? {},\n                    response: {\n                      ...fullResponse,\n                      headers: response?.headers,\n                    },\n                    providerMetadata,\n                  },\n                  callbacks: [onFinish, telemetryDispatcher.onEnd],\n                });\n              } catch (error) {\n                controller.enqueue({ type: 'error', error });\n              }\n            },\n          }),\n        );\n\n      stitchableStream.addStream(transformedStream, {\n        onError(error) {\n          const wrappedError = wrapGatewayError(error);\n          self.rejectResultPromises(wrappedError);\n          void notify({\n            event: { error: wrappedError },\n            callbacks: onError,\n          });\n        },\n      });\n    })()\n      .catch(async error => {\n        self.rejectResultPromises(error);\n        await telemetryDispatcher.onError?.({ callId, error });\n\n        stitchableStream.addStream(\n          new ReadableStream({\n            start(controller) {\n              controller.enqueue({ type: 'error', error });\n              controller.close();\n            },\n          }),\n        );\n      })\n      .finally(() => {\n        stitchableStream.close();\n      });\n\n    this.outputStrategy = outputStrategy;\n  }\n\n  private rejectResultPromises(error: unknown) {\n    this.rejectResultPromise({ delayedPromise: this._object, error });\n    this.rejectResultPromise({ delayedPromise: this._usage, error });\n    this.rejectResultPromise({ delayedPromise: this._providerMetadata, error });\n    this.rejectResultPromise({ delayedPromise: this._warnings, error });\n    this.rejectResultPromise({ delayedPromise: this._request, error });\n    this.rejectResultPromise({ delayedPromise: this._response, error });\n    this.rejectResultPromise({ delayedPromise: this._finishReason, error });\n  }\n\n  private rejectResultPromise<T>({\n    delayedPromise,\n    error,\n  }: {\n    delayedPromise: DelayedPromise<T>;\n    error: unknown;\n  }) {\n    if (delayedPromise.isPending()) {\n      delayedPromise.reject(error);\n      markPromiseAsHandled(delayedPromise.promise);\n    }\n  }\n\n  get object() {\n    return this._object.promise;\n  }\n\n  get usage() {\n    return this._usage.promise;\n  }\n\n  get providerMetadata() {\n    return this._providerMetadata.promise;\n  }\n\n  get warnings() {\n    return this._warnings.promise;\n  }\n\n  get request() {\n    return this._request.promise;\n  }\n\n  get response() {\n    return this._response.promise;\n  }\n\n  get finishReason() {\n    return this._finishReason.promise;\n  }\n\n  get partialObjectStream(): AsyncIterableStream<PARTIAL> {\n    return createAsyncIterableStream(\n      this.baseStream.pipeThrough(\n        new TransformStream<ObjectStreamPart<PARTIAL>, PARTIAL>({\n          transform(chunk, controller) {\n            switch (chunk.type) {\n              case 'object':\n                controller.enqueue(chunk.object);\n                break;\n\n              case 'text-delta':\n              case 'finish':\n              case 'error': // suppress error (use onError instead)\n                break;\n\n              default: {\n                const _exhaustiveCheck: never = chunk;\n                throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);\n              }\n            }\n          },\n        }),\n      ),\n    );\n  }\n\n  get elementStream(): ELEMENT_STREAM {\n    return this.outputStrategy.createElementStream(this.baseStream);\n  }\n\n  get textStream(): AsyncIterableStream<string> {\n    return createAsyncIterableStream(\n      this.baseStream.pipeThrough(\n        new TransformStream<ObjectStreamPart<PARTIAL>, string>({\n          transform(chunk, controller) {\n            switch (chunk.type) {\n              case 'text-delta':\n                controller.enqueue(chunk.textDelta);\n                break;\n\n              case 'object':\n              case 'finish':\n              case 'error': // suppress error (use onError instead)\n                break;\n\n              default: {\n                const _exhaustiveCheck: never = chunk;\n                throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);\n              }\n            }\n          },\n        }),\n      ),\n    );\n  }\n\n  get fullStream(): AsyncIterableStream<ObjectStreamPart<PARTIAL>> {\n    return createAsyncIterableStream(this.baseStream);\n  }\n\n  pipeTextStreamToResponse(response: ServerResponse, init?: ResponseInit) {\n    return pipeTextStreamToResponse({\n      response,\n      stream: this.textStream,\n      ...init,\n    });\n  }\n\n  toTextStreamResponse(init?: ResponseInit): Response {\n    return createTextStreamResponse({\n      stream: this.textStream,\n      ...init,\n    });\n  }\n}\n\nexport type ObjectStreamInputPart =\n  | string\n  | {\n      type: 'stream-start';\n      warnings: SharedV4Warning[];\n    }\n  | {\n      type: 'error';\n      error: unknown;\n    }\n  | {\n      type: 'response-metadata';\n      id?: string;\n      timestamp?: Date;\n      modelId?: string;\n    }\n  | {\n      type: 'finish';\n      finishReason: LanguageModelV4FinishReason;\n      usage: LanguageModelV4Usage;\n      providerMetadata?: SharedV4ProviderMetadata;\n    };\n","import { InvalidArgumentError } from '../error/invalid-argument-error';\n\n/**\n * Calculates the cosine similarity between two vectors. This is a useful metric for\n * comparing the similarity of two vectors such as embeddings.\n *\n * @param vector1 - The first vector.\n * @param vector2 - The second vector.\n *\n * @returns The cosine similarity between vector1 and vector2, or 0 if either vector is the zero vector.\n *\n * @throws {InvalidArgumentError} If the vectors do not have the same length.\n */\nexport function cosineSimilarity(vector1: number[], vector2: number[]): number {\n  if (vector1.length !== vector2.length) {\n    throw new InvalidArgumentError({\n      parameter: 'vector1,vector2',\n      value: { vector1Length: vector1.length, vector2Length: vector2.length },\n      message: `Vectors must have the same length`,\n    });\n  }\n\n  const n = vector1.length;\n\n  if (n === 0) {\n    return 0; // Return 0 for empty vectors if no error is thrown\n  }\n\n  let magnitudeSquared1 = 0;\n  let magnitudeSquared2 = 0;\n  let dotProduct = 0;\n\n  for (let i = 0; i < n; i++) {\n    const value1 = vector1[i];\n    const value2 = vector2[i];\n\n    magnitudeSquared1 += value1 * value1;\n    magnitudeSquared2 += value2 * value2;\n    dotProduct += value1 * value2;\n  }\n\n  return magnitudeSquared1 === 0 || magnitudeSquared2 === 0\n    ? 0\n    : dotProduct /\n        (Math.sqrt(magnitudeSquared1) * Math.sqrt(magnitudeSquared2));\n}\n","import { download as internalDownload } from './download';\n\n/**\n * Creates a download function with configurable options.\n *\n * @param options - Configuration options for the download function.\n * @param options.maxBytes - Maximum allowed download size in bytes. Default: 2 GiB.\n * @returns A download function that can be passed to `transcribe()` or `experimental_generateVideo()`.\n */\nexport function createDownload(options?: { maxBytes?: number }) {\n  return ({ url, abortSignal }: { url: URL; abortSignal?: AbortSignal }) =>\n    internalDownload({ url, maxBytes: options?.maxBytes, abortSignal });\n}\n","import { InvalidArgumentError } from '../error/invalid-argument-error';\n\n// atob needs to be invoked as a function call, not as a method call.\n// Otherwise Cloudflare will throw a\n// \"TypeError: Illegal invocation: function called with incorrect this reference\"\nconst { atob } = globalThis;\n\n/**\n * Converts a data URL of type text/* to a text string.\n *\n * @throws {InvalidArgumentError} If the data URL is malformed or cannot be decoded.\n */\nexport function getTextFromDataUrl(dataUrl: string): string {\n  const [header, base64Content] = dataUrl.split(',');\n  const mediaType = header.split(';')[0].split(':')[1];\n\n  if (mediaType == null || base64Content == null) {\n    throw new InvalidArgumentError({\n      parameter: 'dataUrl',\n      value: dataUrl,\n      message: 'Invalid data URL format',\n    });\n  }\n\n  try {\n    return atob(base64Content);\n  } catch {\n    throw new InvalidArgumentError({\n      parameter: 'dataUrl',\n      value: dataUrl,\n      message: 'Error decoding data URL',\n    });\n  }\n}\n","import type { Job } from './job';\n\nexport class SerialJobExecutor {\n  private queue: Array<Job> = [];\n  private isProcessing = false;\n\n  private async processQueue() {\n    if (this.isProcessing) {\n      return;\n    }\n\n    this.isProcessing = true;\n\n    while (this.queue.length > 0) {\n      await this.queue[0]();\n      this.queue.shift();\n    }\n\n    this.isProcessing = false;\n  }\n\n  async run(job: Job): Promise<void> {\n    return new Promise<void>((resolve, reject) => {\n      this.queue.push(async () => {\n        try {\n          await job();\n          resolve();\n        } catch (error) {\n          reject(error);\n        }\n      });\n\n      void this.processQueue();\n    });\n  }\n}\n","import { delay as delayFunction } from '@ai-sdk/provider-utils';\n\n/**\n * Creates a ReadableStream that emits the provided values with an optional delay between each value.\n *\n * @param options - The configuration options\n * @param options.chunks - Array of values to be emitted by the stream\n * @param options.initialDelayInMs - Optional initial delay in milliseconds before emitting the first value (default: 0). Can be set to `null` to skip the initial delay. The difference between `initialDelayInMs: null` and `initialDelayInMs: 0` is that `initialDelayInMs: null` will emit the values without any delay, while `initialDelayInMs: 0` will emit the values with a delay of 0 milliseconds.\n * @param options.chunkDelayInMs - Optional delay in milliseconds between emitting each value (default: 0). Can be set to `null` to skip the delay. The difference between `chunkDelayInMs: null` and `chunkDelayInMs: 0` is that `chunkDelayInMs: null` will emit the values without any delay, while `chunkDelayInMs: 0` will emit the values with a delay of 0 milliseconds.\n * @returns A ReadableStream that emits the provided values\n */\nexport function simulateReadableStream<T>({\n  chunks,\n  initialDelayInMs = 0,\n  chunkDelayInMs = 0,\n  _internal,\n}: {\n  chunks: T[];\n  initialDelayInMs?: number | null;\n  chunkDelayInMs?: number | null;\n  _internal?: {\n    delay?: (ms: number | null) => Promise<void>;\n  };\n}): ReadableStream<T> {\n  const delay = _internal?.delay ?? delayFunction;\n\n  let index = 0;\n\n  return new ReadableStream({\n    async pull(controller) {\n      if (index < chunks.length) {\n        await delay(index === 0 ? initialDelayInMs : chunkDelayInMs);\n        controller.enqueue(chunks[index++]);\n      } else {\n        controller.close();\n      }\n    },\n  });\n}\n","import type { JSONObject } from '@ai-sdk/provider';\nimport {\n  detectMediaType,\n  withUserAgentSuffix,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { NoSpeechGeneratedError } from '../error/no-speech-generated-error';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveSpeechModel } from '../model/resolve-model';\nimport type { SpeechModel } from '../types/speech-model';\nimport type { SpeechModelResponseMetadata } from '../types/speech-model-response-metadata';\nimport type { Warning } from '../types/warning';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\nimport type { SpeechResult } from './generate-speech-result';\nimport {\n  DefaultGeneratedAudioFile,\n  type GeneratedAudioFile,\n} from './generated-audio-file';\n/**\n * Generates speech audio using a speech model.\n *\n * @param model - The speech model to use.\n * @param text - The text to convert to speech.\n * @param voice - The voice to use for speech generation.\n * @param outputFormat - The output format to use for speech generation e.g. \"mp3\", \"wav\", etc.\n * @param instructions - Instructions for the speech generation e.g. \"Speak in a slow and steady tone\".\n * @param speed - The speed of the speech generation.\n * @param language - The language for speech generation (ISO 639-1 code e.g. \"en\", \"es\", \"fr\") or \"auto\" for automatic detection.\n * @param providerOptions - Additional provider-specific options that are passed through to the provider\n * as body parameters.\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @returns A result object that contains the generated audio data.\n */\nexport async function generateSpeech({\n  model,\n  text,\n  voice,\n  outputFormat,\n  instructions,\n  speed,\n  language,\n  providerOptions = {},\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n}: {\n  /**\n   * The speech model to use.\n   */\n  model: SpeechModel;\n\n  /**\n   * The text to convert to speech.\n   */\n  text: string;\n\n  /**\n   * The voice to use for speech generation.\n   */\n  voice?: string;\n\n  /**\n   * The desired output format for the audio e.g. \"mp3\", \"wav\", etc.\n   */\n  outputFormat?: 'mp3' | 'wav' | (string & {});\n\n  /**\n   * Instructions for the speech generation e.g. \"Speak in a slow and steady tone\".\n   */\n  instructions?: string;\n\n  /**\n   * The speed of the speech generation.\n   */\n  speed?: number;\n\n  /**\n   * The language for speech generation. This should be an ISO 639-1 language code (e.g. \"en\", \"es\", \"fr\")\n   * or \"auto\" for automatic language detection. Provider support varies.\n   */\n  language?: string;\n\n  /**\n   * Additional provider-specific options that are passed through to the provider\n   * as body parameters.\n   *\n   * The outer record is keyed by the provider name, and the inner\n   * record is keyed by the provider-specific metadata key.\n   * ```ts\n   * {\n   * \"openai\": {}\n   * }\n   * ```\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Maximum number of retries per speech model call. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n}): Promise<SpeechResult> {\n  const resolvedModel = resolveSpeechModel(model);\n  if (!resolvedModel) {\n    throw new Error('Model could not be resolved');\n  }\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  const result = await retry(() =>\n    resolvedModel.doGenerate({\n      text,\n      voice,\n      outputFormat,\n      instructions,\n      speed,\n      language,\n      abortSignal,\n      headers: headersWithUserAgent,\n      providerOptions,\n    }),\n  );\n\n  if (!result.audio || result.audio.length === 0) {\n    throw new NoSpeechGeneratedError({ responses: [result.response] });\n  }\n\n  logWarnings({\n    warnings: result.warnings,\n    provider: resolvedModel.provider,\n    model: resolvedModel.modelId,\n  });\n\n  return new DefaultSpeechResult({\n    audio: new DefaultGeneratedAudioFile({\n      data: result.audio,\n      mediaType:\n        detectMediaType({\n          data: result.audio,\n          topLevelType: 'audio',\n        }) ?? 'audio/mp3',\n    }),\n    warnings: result.warnings,\n    responses: [result.response],\n    providerMetadata: result.providerMetadata,\n  });\n}\n\nclass DefaultSpeechResult implements SpeechResult {\n  readonly audio: GeneratedAudioFile;\n  readonly warnings: Array<Warning>;\n  readonly responses: Array<SpeechModelResponseMetadata>;\n  readonly providerMetadata: Record<string, JSONObject>;\n\n  constructor(options: {\n    audio: GeneratedAudioFile;\n    warnings: Array<Warning>;\n    responses: Array<SpeechModelResponseMetadata>;\n    providerMetadata: Record<string, JSONObject> | undefined;\n  }) {\n    this.audio = options.audio;\n    this.warnings = options.warnings;\n    this.responses = options.responses;\n    this.providerMetadata = options.providerMetadata ?? {};\n  }\n}\n","import {\n  DefaultGeneratedFile,\n  type GeneratedFile,\n} from '../generate-text/generated-file';\n/**\n * A generated audio file.\n */\nexport interface GeneratedAudioFile extends GeneratedFile {\n  /**\n   * Audio format of the file (e.g., 'mp3', 'wav', etc.)\n   */\n  readonly format: string;\n}\n\nexport class DefaultGeneratedAudioFile\n  extends DefaultGeneratedFile\n  implements GeneratedAudioFile\n{\n  readonly format: string;\n\n  constructor({\n    data,\n    mediaType,\n  }: {\n    data: string | Uint8Array;\n    mediaType: string;\n  }) {\n    super({ data, mediaType });\n    let format = 'mp3';\n\n    // If format is not provided, try to determine it from the media type\n    if (mediaType) {\n      const mediaTypeParts = mediaType.split('/');\n\n      if (mediaTypeParts.length === 2) {\n        // Handle special cases for audio formats\n        if (mediaType !== 'audio/mpeg') {\n          format = mediaTypeParts[1];\n        }\n      }\n    }\n\n    if (!format) {\n      // TODO this should be an AI SDK error\n      throw new Error(\n        'Audio format must be provided or determinable from media type',\n      );\n    }\n\n    this.format = format;\n  }\n}\n\nexport class DefaultGeneratedAudioFileWithType extends DefaultGeneratedAudioFile {\n  readonly type = 'audio';\n\n  constructor(options: {\n    data: string | Uint8Array;\n    mediaType: string;\n    format: string;\n  }) {\n    super(options);\n  }\n}\n","import type { SpeechResult } from './generate-speech-result';\nimport { generateSpeech } from './generate-speech';\n\nexport { generateSpeech } from './generate-speech';\nexport type { SpeechResult } from './generate-speech-result';\nexport type { GeneratedAudioFile } from './generated-audio-file';\n\n// deprecated exports\n\n/**\n * @deprecated Use `generateSpeech` instead.\n */\nconst experimental_generateSpeech = generateSpeech;\nexport { experimental_generateSpeech };\n\n/**\n * @deprecated Use `SpeechResult` instead.\n */\ntype Experimental_SpeechResult = SpeechResult;\nexport type { Experimental_SpeechResult };\n","import type {\n  AssistantModelMessage,\n  ModelMessage,\n  ToolModelMessage,\n} from '@ai-sdk/provider-utils';\n\n/**\n * Prunes model messages from a list of model messages.\n *\n * @param messages - The list of model messages to prune.\n * @param reasoning - How to remove reasoning content from assistant messages. Default is `'none'`.\n * @param toolCalls - How to prune tool call/results/approval content. Default is `[]`.\n * @param emptyMessages - Whether to keep or remove messages whose content is empty after pruning. Default is `'remove'`.\n *\n * @returns The pruned list of model messages.\n */\nexport function pruneMessages({\n  messages,\n  reasoning = 'none',\n  toolCalls = [],\n  emptyMessages = 'remove',\n}: {\n  messages: ModelMessage[];\n  reasoning?: 'all' | 'before-last-message' | 'none';\n  toolCalls?:\n    | 'all'\n    | 'before-last-message'\n    | `before-last-${number}-messages`\n    | 'none'\n    | Array<{\n        type: 'all' | 'before-last-message' | `before-last-${number}-messages`;\n        tools?: string[];\n      }>;\n  emptyMessages?: 'keep' | 'remove';\n}): ModelMessage[] {\n  // filter reasoning parts:\n  if (reasoning === 'all' || reasoning === 'before-last-message') {\n    messages = messages.map((message, messageIndex) => {\n      if (\n        message.role !== 'assistant' ||\n        typeof message.content === 'string' ||\n        (reasoning === 'before-last-message' &&\n          messageIndex === messages.length - 1)\n      ) {\n        return message;\n      }\n\n      return {\n        ...message,\n        content: message.content.filter(part => part.type !== 'reasoning'),\n      };\n    });\n  }\n\n  // filter tool calls, results, errors, and approvals:\n  if (toolCalls === 'none') {\n    toolCalls = [];\n  } else if (toolCalls === 'all') {\n    toolCalls = [{ type: 'all' }];\n  } else if (toolCalls === 'before-last-message') {\n    toolCalls = [{ type: 'before-last-message' }];\n  } else if (typeof toolCalls === 'string') {\n    toolCalls = [{ type: toolCalls }];\n  }\n\n  for (const toolCall of toolCalls) {\n    // determine how many trailing messages to keep:\n    const keepLastMessagesCount =\n      toolCall.type === 'all'\n        ? undefined\n        : toolCall.type === 'before-last-message'\n          ? 1\n          : Number(\n              toolCall.type\n                .slice('before-last-'.length)\n                .slice(0, -'-messages'.length),\n            );\n\n    // scan kept messages to identify tool calls and approvals that need to be kept:\n    const keptToolCallIds: Set<string> = new Set();\n    const keptApprovalIds: Set<string> = new Set();\n\n    if (keepLastMessagesCount != null) {\n      for (const message of messages.slice(-keepLastMessagesCount)) {\n        if (\n          (message.role === 'assistant' || message.role === 'tool') &&\n          typeof message.content !== 'string'\n        ) {\n          for (const part of message.content) {\n            if (part.type === 'tool-call' || part.type === 'tool-result') {\n              keptToolCallIds.add(part.toolCallId);\n            } else if (\n              part.type === 'tool-approval-request' ||\n              part.type === 'tool-approval-response'\n            ) {\n              keptApprovalIds.add(part.approvalId);\n            }\n          }\n        }\n      }\n    }\n\n    // Build global maps from tool call id and approval id to tool name.\n    // These must be global (not per-message) because a `tool-approval-response`\n    // lives in a separate `tool` message from its `tool-approval-request`\n    // (assistant message), so the tool name of a response can only be resolved\n    // by looking across messages. Resolving names per-message left responses\n    // unresolved, which caused them to be kept while their request was pruned,\n    // producing orphaned approval responses.\n    const toolCallIdToToolName = new Map<string, string>();\n    for (const message of messages) {\n      if (\n        (message.role === 'assistant' || message.role === 'tool') &&\n        typeof message.content !== 'string'\n      ) {\n        for (const part of message.content) {\n          if (part.type === 'tool-call' || part.type === 'tool-result') {\n            toolCallIdToToolName.set(part.toolCallId, part.toolName);\n          }\n        }\n      }\n    }\n\n    const approvalIdToToolName = new Map<string, string>();\n    for (const message of messages) {\n      if (\n        (message.role === 'assistant' || message.role === 'tool') &&\n        typeof message.content !== 'string'\n      ) {\n        for (const part of message.content) {\n          if (part.type === 'tool-approval-request') {\n            const toolName = toolCallIdToToolName.get(part.toolCallId);\n            if (toolName != null) {\n              approvalIdToToolName.set(part.approvalId, toolName);\n            }\n          }\n        }\n      }\n    }\n\n    messages = messages.map((message, messageIndex) => {\n      if (\n        (message.role !== 'assistant' && message.role !== 'tool') ||\n        typeof message.content === 'string' ||\n        (keepLastMessagesCount &&\n          messageIndex >= messages.length - keepLastMessagesCount)\n      ) {\n        return message;\n      }\n\n      return {\n        ...message,\n        content: message.content.filter(part => {\n          // keep non-tool parts:\n          if (\n            part.type !== 'tool-call' &&\n            part.type !== 'tool-result' &&\n            part.type !== 'tool-approval-request' &&\n            part.type !== 'tool-approval-response'\n          ) {\n            return true;\n          }\n\n          // keep parts that are associated with a tool call or approval that needs to be kept:\n          if (\n            ((part.type === 'tool-call' || part.type === 'tool-result') &&\n              keptToolCallIds.has(part.toolCallId)) ||\n            ((part.type === 'tool-approval-request' ||\n              part.type === 'tool-approval-response') &&\n              keptApprovalIds.has(part.approvalId))\n          ) {\n            return true;\n          }\n\n          // keep parts that are not associated with a tool that should be removed:\n          const partToolName =\n            part.type === 'tool-call' || part.type === 'tool-result'\n              ? part.toolName\n              : approvalIdToToolName.get(part.approvalId);\n\n          return (\n            toolCall.tools != null &&\n            partToolName != null &&\n            !toolCall.tools.includes(partToolName)\n          );\n        }),\n      } as AssistantModelMessage | ToolModelMessage;\n    });\n  }\n\n  if (emptyMessages === 'remove') {\n    messages = messages.filter(message => message.content.length > 0);\n  }\n\n  return messages;\n}\n","import { delay as originalDelay, type ToolSet } from '@ai-sdk/provider-utils';\nimport {\n  InvalidArgumentError,\n  type SharedV4ProviderMetadata,\n} from '@ai-sdk/provider';\nimport type { TextStreamPart } from './stream-text-result';\n\nconst CHUNKING_REGEXPS = {\n  word: /\\S+\\s+/m,\n  line: /\\n+/m,\n};\n\n// Browsers heavily throttle timers in hidden documents (e.g. background tabs),\n// which would stall the smoothing delay and, through backpressure, the entire\n// stream. Smoothing has no visual purpose there, so the delay is skipped.\nfunction isDocumentHidden(): boolean {\n  return (\n    typeof document !== 'undefined' && document.visibilityState === 'hidden'\n  );\n}\n\n/**\n * Detects the first chunk in a buffer.\n *\n * @param buffer - The buffer to detect the first chunk in.\n *\n * @returns The first detected chunk, or `undefined` if no chunk was detected.\n */\nexport type ChunkDetector = (buffer: string) => string | undefined | null;\n\n/**\n * Smooths text and reasoning streaming output.\n *\n * @param delayInMs - The delay in milliseconds between each chunk. Defaults to 10ms. Can be set to `null` to skip the delay. The delay is skipped while the document is hidden (e.g. browser background tabs), where timer throttling would otherwise stall the stream.\n * @param chunking - Controls how the text is chunked for streaming. Use \"word\" to stream word by word (default), \"line\" to stream line by line, provide a custom RegExp pattern that does not match the empty string for custom chunking, provide an Intl.Segmenter for locale-aware word segmentation (recommended for CJK languages), or provide a custom ChunkDetector function.\n *\n * @returns A transform stream that smooths text streaming output.\n */\nexport function smoothStream<TOOLS extends ToolSet>({\n  delayInMs = 10,\n  chunking = 'word',\n  _internal: { delay = originalDelay } = {},\n}: {\n  delayInMs?: number | null;\n  chunking?: 'word' | 'line' | RegExp | ChunkDetector | Intl.Segmenter;\n  /**\n   * Internal. For test use only. May change without notice.\n   */\n  _internal?: {\n    delay?: (delayInMs: number | null) => Promise<void>;\n  };\n} = {}): (options: {\n  tools: TOOLS;\n}) => TransformStream<TextStreamPart<TOOLS>, TextStreamPart<TOOLS>> {\n  let detectChunk: ChunkDetector;\n\n  // Check if chunking is an Intl.Segmenter (duck-typing for segment method)\n  if (\n    chunking != null &&\n    typeof chunking === 'object' &&\n    'segment' in chunking &&\n    typeof chunking.segment === 'function'\n  ) {\n    const segmenter = chunking as Intl.Segmenter;\n    detectChunk = (buffer: string) => {\n      if (buffer.length === 0) return null;\n      const iterator = segmenter.segment(buffer)[Symbol.iterator]();\n      const first = iterator.next().value;\n      return first?.segment || null;\n    };\n  } else if (typeof chunking === 'function') {\n    detectChunk = buffer => {\n      const match = chunking(buffer);\n\n      if (match == null) {\n        return null;\n      }\n\n      if (!match.length) {\n        throw new Error(`Chunking function must return a non-empty string.`);\n      }\n\n      if (!buffer.startsWith(match)) {\n        throw new Error(\n          `Chunking function must return a match that is a prefix of the buffer. Received: \"${match}\" expected to start with \"${buffer}\"`,\n        );\n      }\n\n      return match;\n    };\n  } else {\n    const chunkingRegex =\n      typeof chunking === 'string'\n        ? CHUNKING_REGEXPS[chunking]\n        : chunking instanceof RegExp\n          ? chunking\n          : undefined;\n\n    if (chunkingRegex == null) {\n      throw new InvalidArgumentError({\n        argument: 'chunking',\n        message: `Chunking must be \"word\", \"line\", a RegExp, an Intl.Segmenter, or a ChunkDetector function. Received: ${chunking}`,\n      });\n    }\n\n    detectChunk = buffer => {\n      const lastIndex = chunkingRegex.lastIndex;\n      chunkingRegex.lastIndex = 0;\n\n      let match: RegExpExecArray | null;\n      try {\n        match = chunkingRegex.exec(buffer);\n      } finally {\n        chunkingRegex.lastIndex = lastIndex;\n      }\n\n      if (!match) {\n        return null;\n      }\n\n      if (!match[0].length) {\n        throw new Error(`Chunking RegExp must not match an empty string.`);\n      }\n\n      return buffer.slice(0, match.index) + match[0];\n    };\n  }\n\n  return () => {\n    let buffer = '';\n    let id = '';\n    let type: 'text-delta' | 'reasoning-delta' | undefined = undefined;\n    let providerMetadata: SharedV4ProviderMetadata | undefined = undefined;\n\n    function flushBuffer(\n      controller: TransformStreamDefaultController<TextStreamPart<TOOLS>>,\n    ) {\n      if (\n        type !== undefined &&\n        (buffer.length > 0 || providerMetadata != null)\n      ) {\n        controller.enqueue({\n          type,\n          text: buffer,\n          id,\n          ...(providerMetadata != null ? { providerMetadata } : {}),\n        });\n        buffer = '';\n        providerMetadata = undefined;\n      }\n    }\n\n    return new TransformStream<TextStreamPart<TOOLS>, TextStreamPart<TOOLS>>({\n      async transform(chunk, controller) {\n        // Handle non-smoothable chunks: flush buffer and pass through\n        if (chunk.type !== 'text-delta' && chunk.type !== 'reasoning-delta') {\n          flushBuffer(controller);\n          controller.enqueue(chunk);\n          return;\n        }\n\n        // Flush buffer when type or id changes\n        if (\n          (chunk.type !== type || chunk.id !== id) &&\n          (buffer.length > 0 || providerMetadata != null)\n        ) {\n          flushBuffer(controller);\n        }\n\n        buffer += chunk.text;\n        id = chunk.id;\n        type = chunk.type;\n\n        // Preserve providerMetadata (e.g., Anthropic thinking signatures)\n        if (chunk.providerMetadata != null) {\n          providerMetadata = chunk.providerMetadata;\n        }\n\n        let match;\n\n        while ((match = detectChunk(buffer)) != null) {\n          controller.enqueue({ type, text: match, id });\n          buffer = buffer.slice(match.length);\n\n          await delay(isDocumentHidden() ? null : delayInMs);\n        }\n      },\n    });\n  };\n}\n","import { asSchema, type ToolSet } from '@ai-sdk/provider-utils';\nimport { hashCanonical } from '../util/canonical-hash';\n\n/**\n * Tag a tool description for hashing. A function description is developer-owned\n * (evaluated per call from local context), not a server-controlled \"rug pull\"\n * vector, so only its presence is pinned, not its identity. The tagged shape\n * keeps a literal string equal to some placeholder from ever hashing like a\n * function.\n */\nfunction tagDescription(description: unknown) {\n  if (typeof description === 'string') {\n    return { type: 'string', value: description } as const;\n  }\n  if (description == null) {\n    return { type: 'none' } as const;\n  }\n  return { type: 'function' } as const;\n}\n\n/**\n * Fingerprint the server-controlled, security-relevant fields of each tool in a\n * `ToolSet`: `description` (string form only), the resolved input JSON schema,\n * and `title`. Returns a map of tool name to a stable digest.\n *\n * Capture a baseline at trust time (first connect, human-reviewed) and compare\n * later fetches with {@link detectToolDrift} to catch MCP tool-definition drift\n * (\"rug pull\"). Baseline storage and the drift response are the app's concern.\n */\nexport async function fingerprintTools(\n  tools: ToolSet,\n): Promise<Record<string, string>> {\n  const entries = await Promise.all(\n    Object.keys(tools).map(async name => {\n      const tool = tools[name];\n      const digest = await hashCanonical({\n        description: tagDescription(tool.description),\n        inputSchema: await asSchema(tool.inputSchema).jsonSchema,\n        title: tool.title,\n      });\n      return [name, digest] as const;\n    }),\n  );\n  return Object.fromEntries(entries);\n}\n\n/**\n * Pure diff of two fingerprint maps produced by {@link fingerprintTools}.\n * `added`/`removed` are tools present in only one map; `changed` are tools whose\n * pinned definition differs. Uses own-property lookups so a tool literally named\n * `constructor` or `toString` diffs correctly.\n */\nexport function detectToolDrift(\n  current: Record<string, string>,\n  baseline: Record<string, string>,\n): { added: string[]; removed: string[]; changed: string[] } {\n  const added: string[] = [];\n  const removed: string[] = [];\n  const changed: string[] = [];\n\n  for (const name of Object.keys(current)) {\n    if (!Object.hasOwn(baseline, name)) {\n      added.push(name);\n    } else if (current[name] !== baseline[name]) {\n      changed.push(name);\n    }\n  }\n\n  for (const name of Object.keys(baseline)) {\n    if (!Object.hasOwn(current, name)) {\n      removed.push(name);\n    }\n  }\n\n  return { added, removed, changed };\n}\n","import type {\n  Experimental_VideoModelV4,\n  Experimental_VideoModelV4CallOptions,\n  Experimental_VideoModelV4File,\n  Experimental_VideoModelV4Result,\n  Experimental_VideoModelV4OperationWebhook,\n  Experimental_VideoModelV4FrameImage,\n  Experimental_VideoModelV4FrameType,\n  SharedV4ProviderMetadata,\n} from '@ai-sdk/provider';\nimport {\n  convertBase64ToUint8Array,\n  delay as defaultDelay,\n  generateId,\n  withUserAgentSuffix,\n  type DataContent,\n  detectMediaType,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { NoVideoGeneratedError } from '../error/no-video-generated-error';\nimport {\n  DefaultGeneratedFile,\n  type GeneratedFile,\n} from '../generate-text/generated-file';\nimport { logWarnings } from '../logger/log-warnings';\nimport { mergeAbortSignals } from '../util/merge-abort-signals';\nimport { resolveVideoModel } from '../model/resolve-model';\nimport type { VideoModel } from '../types/video-model';\nimport type { VideoModelResponseMetadata } from '../types/video-model-response-metadata';\nimport type { Warning } from '../types/warning';\nimport { createDownload } from '../util/download/create-download';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\nimport type { GenerateVideoResult } from './generate-video-result';\nimport { splitDataUrl } from '../prompt/split-data-url';\n\nexport type GenerateVideoPrompt =\n  | string\n  | {\n      image: DataContent;\n      text?: string;\n    };\n\n/**\n * Polling configuration for models that support the asynchronous\n * start/status flow.\n *\n * When used with `webhook`, `timeoutMs` also limits how long the SDK waits for\n * the webhook notification. If the model does not support webhooks, these\n * options configure the automatic polling fallback.\n */\nexport type GenerateVideoPollOptions = {\n  /**\n   * Interval between status checks in milliseconds.\n   *\n   * @default 5000\n   */\n  intervalMs?: number;\n\n  /**\n   * Maximum time to wait for completion in milliseconds.\n   *\n   * @default 600000 (10 minutes)\n   */\n  timeoutMs?: number;\n\n  /**\n   * Custom delay implementation for polling intervals and webhook timeouts.\n   * This can be used with durable workflow sleep functions.\n   *\n   * @default the built-in timer-based delay\n   */\n  delay?: (\n    delayInMs: number,\n    options?: { abortSignal?: AbortSignal },\n  ) => PromiseLike<void>;\n};\n\n/**\n * Webhook factory for models that support the asynchronous start/status flow.\n *\n * The factory should return a URL for the provider to send notifications to,\n * and a `received` promise that resolves when the notification arrives.\n */\nexport type GenerateVideoWebhookFactory = () => PromiseLike<{\n  url: string;\n  received: PromiseLike<Experimental_VideoModelV4OperationWebhook>;\n}>;\n\n/**\n * Generates videos using a video model.\n *\n * @param model - The video model to use.\n * @param prompt - The prompt that should be used to generate the video.\n * @param n - Number of videos to generate. Default: 1.\n * @param aspectRatio - Aspect ratio of the videos to generate. Must have the format `{width}:{height}`, or `'adaptive'`.\n * @param resolution - Resolution of the videos to generate. Must have the format `{width}x{height}`.\n * @param duration - Duration of the video in seconds.\n * @param fps - Frames per second for the video.\n * @param seed - Seed for the video generation.\n * @param frameImages - Role-tagged image inputs for image-to-video and first-last-frame generation.\n * @param inputReferences - Reference image or video inputs for reference-to-video generation.\n * @param generateAudio - Whether the model should generate audio alongside the video.\n * @param providerOptions - Additional provider-specific options that are passed through to the provider\n * as body parameters.\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n * @param poll - Polling configuration for models that support the start/status flow.\n * @param webhook - Webhook factory for models that support the start/status flow.\n *\n * @returns A result object that contains the generated videos.\n */\nconst defaultDownload = createDownload();\n\nexport async function experimental_generateVideo({\n  model: modelArg,\n  prompt: promptArg,\n  n = 1,\n  maxVideosPerCall,\n  aspectRatio,\n  resolution,\n  duration,\n  fps,\n  seed,\n  frameImages,\n  inputReferences,\n  generateAudio,\n  providerOptions,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  download: downloadFn = defaultDownload,\n  poll,\n  webhook,\n}: {\n  /**\n   * The video model to use.\n   */\n  model: VideoModel;\n\n  /**\n   * The prompt that should be used to generate the video.\n   */\n  prompt: GenerateVideoPrompt;\n\n  /**\n   * Number of videos to generate.\n   */\n  n?: number;\n\n  /**\n   * Maximum number of videos per API call. If not provided, the model's default will be used.\n   */\n  maxVideosPerCall?: number;\n\n  /**\n   * Aspect ratio of the videos to generate. Must have the format\n   * `{width}:{height}`, or `'adaptive'` to inherit the ratio from the input media.\n   */\n  aspectRatio?: `${number}:${number}` | 'adaptive';\n\n  /**\n   * Resolution of the videos to generate. Must have the format `{width}x${height}`.\n   */\n  resolution?: `${number}x${number}`;\n\n  /**\n   * Duration of the video in seconds.\n   */\n  duration?: number;\n\n  /**\n   * Frames per second for the video.\n   */\n  fps?: number;\n\n  /**\n   * Seed for the video generation.\n   */\n  seed?: number;\n\n  /**\n   * Role-tagged image inputs for image-to-video and first-last-frame generation.\n   */\n  frameImages?: Array<{\n    /**\n     * The image for this frame.\n     */\n    image: DataContent;\n\n    /**\n     * Which frame this image represents.\n     */\n    frameType: Experimental_VideoModelV4FrameType;\n  }>;\n\n  /**\n   * Reference inputs for reference-to-video generation.\n   *\n   * Each entry may be a plain image/video ({@link DataContent}), or an object\n   * form that carries an explicit `mediaType`.\n   */\n  inputReferences?: Array<\n    | DataContent\n    | {\n        /**\n         * The reference image or video.\n         */\n        data: DataContent;\n\n        /**\n         * The media type of the reference (e.g. 'image/png',\n         * 'video/mp4').\n         */\n        mediaType?: string;\n      }\n  >;\n\n  /**\n   * Whether the model should generate audio alongside the video.\n   */\n  generateAudio?: boolean;\n\n  /**\n   * Additional provider-specific options that are passed through to the provider\n   * as body parameters.\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Maximum number of retries per video model call. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * Custom download function for fetching videos from URLs.\n   * Use `createDownload()` from `ai` to create a download function with custom size limits.\n   *\n   * @default createDownload() (2 GiB limit)\n   */\n  download?: (options: {\n    url: URL;\n    abortSignal?: AbortSignal;\n  }) => Promise<{ data: Uint8Array; mediaType: string | undefined }>;\n\n  /**\n   * Polling configuration for models that support the asynchronous\n   * start/status flow. When provided and the model implements `doStart`\n   * and `doStatus`, the SDK will orchestrate polling automatically.\n   *\n   * This option can be combined with `webhook`: `timeoutMs` limits the webhook\n   * wait, and the polling settings apply if the model does not support\n   * webhooks.\n   */\n  poll?: GenerateVideoPollOptions;\n\n  /**\n   * Webhook factory for models that support the asynchronous\n   * start/status flow. When provided and the model implements `doStart`\n   * and `doStatus`, the SDK will use webhooks instead of polling.\n   *\n   * The factory should return a URL for the provider to send notifications to,\n   * and a `received` promise that resolves when the notification arrives.\n   * `poll` can also be provided to configure the webhook timeout and polling\n   * fallback.\n   */\n  webhook?: GenerateVideoWebhookFactory;\n}): Promise<GenerateVideoResult> {\n  const model = resolveVideoModel(modelArg);\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  const {\n    prompt,\n    resolvedImage,\n    normalizedFrameImages,\n    effectiveInputReferences,\n    warnings,\n  } = normalizeVideoCallInputs({ promptArg, frameImages, inputReferences });\n\n  const maxVideosPerCallWithDefault =\n    maxVideosPerCall ?? (await invokeModelMaxVideosPerCall(model)) ?? 1;\n\n  // Determine whether to use the start/status flow:\n  const hasStartStatus = model.doStart != null && model.doStatus != null;\n  const useStartStatus =\n    hasStartStatus &&\n    (poll != null || webhook != null || model.doGenerate == null);\n\n  // Validate model capabilities\n  if (model.doGenerate == null && !hasStartStatus) {\n    throw new Error(\n      `Video model ${model.modelId} does not implement doGenerate or doStart/doStatus.`,\n    );\n  }\n\n  // Warn if poll/webhook provided but model doesn't support start/status\n  if ((poll != null || webhook != null) && !hasStartStatus) {\n    logWarnings({\n      warnings: [\n        {\n          type: 'other',\n          message:\n            'poll/webhook options were provided but the model does not support doStart/doStatus. Falling back to doGenerate.',\n        },\n      ],\n      provider: model.provider,\n      model: model.modelId,\n    });\n  }\n\n  // parallelize calls to the model:\n  const callCount = Math.ceil(n / maxVideosPerCallWithDefault);\n  const callVideoCounts = Array.from({ length: callCount }, (_, index) => {\n    const remaining = n - index * maxVideosPerCallWithDefault;\n    return Math.min(remaining, maxVideosPerCallWithDefault);\n  });\n\n  const results = await Promise.all(\n    callVideoCounts.map(async callVideoCount => {\n      const callOptions: Experimental_VideoModelV4CallOptions = {\n        prompt,\n        n: callVideoCount,\n        aspectRatio,\n        resolution,\n        duration,\n        fps,\n        seed,\n        image: resolvedImage,\n        frameImages: normalizedFrameImages,\n        inputReferences: effectiveInputReferences,\n        generateAudio,\n        providerOptions: providerOptions ?? {},\n        headers: headersWithUserAgent,\n        abortSignal,\n      };\n\n      if (useStartStatus) {\n        return executeStartStatusFlow({\n          model,\n          callOptions,\n          poll,\n          webhook,\n          retry,\n        });\n      }\n\n      return retry(() => model.doGenerate!(callOptions));\n    }),\n  );\n\n  // collect result videos, warnings, and response metadata\n  const videos: Array<GeneratedFile> = [];\n  const responses: Array<VideoModelResponseMetadata> = [];\n  const providerMetadata: SharedV4ProviderMetadata = {};\n\n  for (const result of results) {\n    for (const videoData of result.videos) {\n      switch (videoData.type) {\n        case 'url': {\n          const { data, mediaType: downloadedMediaType } = await downloadFn({\n            url: new URL(videoData.url),\n            abortSignal,\n          });\n\n          // Filter out generic/unknown media types that should fall through to detection\n          const isUsableMediaType = (type: string | undefined): boolean =>\n            !!type && type !== 'application/octet-stream';\n\n          const mediaType =\n            (isUsableMediaType(videoData.mediaType) && videoData.mediaType) ||\n            (isUsableMediaType(downloadedMediaType) && downloadedMediaType) ||\n            detectMediaType({\n              data,\n              topLevelType: 'video',\n            }) ||\n            'video/mp4';\n\n          videos.push(\n            new DefaultGeneratedFile({\n              data,\n              mediaType,\n            }),\n          );\n          break;\n        }\n\n        case 'base64': {\n          videos.push(\n            new DefaultGeneratedFile({\n              data: videoData.data,\n              mediaType: videoData.mediaType || 'video/mp4',\n            }),\n          );\n          break;\n        }\n\n        case 'binary': {\n          const mediaType =\n            videoData.mediaType ||\n            detectMediaType({\n              data: videoData.data,\n              topLevelType: 'video',\n            }) ||\n            'video/mp4';\n\n          videos.push(\n            new DefaultGeneratedFile({\n              data: videoData.data,\n              mediaType,\n            }),\n          );\n          break;\n        }\n      }\n    }\n\n    warnings.push(...result.warnings);\n\n    responses.push({\n      timestamp: result.response.timestamp,\n      modelId: result.response.modelId,\n      headers: result.response.headers,\n      providerMetadata: result.providerMetadata,\n    });\n\n    if (result.providerMetadata != null) {\n      mergeProviderMetadata(providerMetadata, result.providerMetadata);\n    }\n  }\n\n  if (videos.length === 0) {\n    throw new NoVideoGeneratedError({ responses });\n  }\n\n  if (warnings.length > 0) {\n    logWarnings({\n      warnings,\n      provider: model.provider,\n      model: model.modelId,\n    });\n  }\n\n  return {\n    video: videos[0],\n    videos,\n    warnings,\n    responses,\n    providerMetadata,\n  };\n}\n\nasync function executeStartStatusFlow({\n  model,\n  callOptions,\n  poll: pollConfig,\n  webhook: webhookFactory,\n  retry,\n}: {\n  model: Experimental_VideoModelV4;\n  callOptions: Experimental_VideoModelV4CallOptions;\n  poll?: GenerateVideoPollOptions;\n  webhook?: GenerateVideoWebhookFactory;\n  retry: <OUTPUT>(fn: () => PromiseLike<OUTPUT>) => PromiseLike<OUTPUT>;\n}): Promise<Experimental_VideoModelV4Result> {\n  // 1. If webhook and provider supports it, set up the webhook\n  const earlyWarnings: Experimental_VideoModelV4Result['warnings'] = [];\n  let webhookUrl: string | undefined;\n  let webhookReceived:\n    | Promise<Experimental_VideoModelV4OperationWebhook>\n    | undefined;\n\n  if (webhookFactory != null) {\n    if (model.handleWebhookOption != null) {\n      const result = await model.handleWebhookOption({\n        webhook: webhookFactory,\n      });\n      webhookReceived = Promise.resolve(result.received);\n      // Observe early failures without changing the error awaited after doStart.\n      webhookReceived.catch(() => {});\n      webhookUrl = result.webhookUrl;\n    } else {\n      earlyWarnings.push({\n        type: 'unsupported',\n        feature: 'webhook',\n        details:\n          'This model does not support webhooks. Falling back to polling.',\n      });\n    }\n  }\n\n  // 2. Start the generation. `doStart` is billable: mint one idempotency token\n  // per logical start, outside the retry closure; a caller-supplied key wins.\n  const callerIdempotencyKey = Object.entries(callOptions.headers ?? {}).find(\n    ([key, value]) =>\n      key.toLowerCase() === 'idempotency-key' && value !== undefined,\n  );\n  const startCallOptions = {\n    ...callOptions,\n    headers: {\n      ...callOptions.headers,\n      ...(callerIdempotencyKey\n        ? {}\n        : { 'idempotency-key': `aisdk_vid_${generateId()}` }),\n    },\n    webhookUrl,\n  };\n  const startResult = await retry(() => model.doStart!(startCallOptions));\n\n  const allWarnings = [...earlyWarnings, ...startResult.warnings];\n  let operationProviderMetadata =\n    startResult.providerMetadata == null\n      ? undefined\n      : { ...startResult.providerMetadata };\n  const intervalMs = pollConfig?.intervalMs ?? 5000;\n  const timeoutMs = pollConfig?.timeoutMs ?? 600_000;\n  const delay = pollConfig?.delay ?? defaultDelay;\n  const startTime = Date.now();\n\n  if (webhookReceived != null) {\n    // 3a. Webhook flow: wait for webhook, then get final status\n    await waitForWebhook({\n      received: webhookReceived,\n      timeoutMs,\n      abortSignal: callOptions.abortSignal,\n      delay,\n    });\n  }\n\n  while (true) {\n    if (webhookReceived == null) {\n      // 3b. Polling flow (also used when webhooks are not supported)\n      const elapsedMs = Date.now() - startTime;\n      if (elapsedMs >= timeoutMs) {\n        throw new Error(`Video generation timed out after ${timeoutMs}ms.`);\n      }\n      await delay(Math.min(intervalMs, timeoutMs - elapsedMs), {\n        abortSignal: callOptions.abortSignal,\n      });\n      if (Date.now() - startTime >= timeoutMs) {\n        throw new Error(`Video generation timed out after ${timeoutMs}ms.`);\n      }\n    }\n\n    const statusResult = await retry(() =>\n      model.doStatus!({\n        operation: startResult.operation,\n        abortSignal: callOptions.abortSignal,\n        headers: callOptions.headers,\n      }),\n    );\n\n    if (statusResult.status === 'error') {\n      throw new Error(statusResult.error);\n    }\n\n    if (statusResult.warnings != null) {\n      allWarnings.push(...statusResult.warnings);\n    }\n    if (statusResult.providerMetadata != null) {\n      operationProviderMetadata ??= {};\n      mergeProviderMetadata(\n        operationProviderMetadata,\n        statusResult.providerMetadata,\n      );\n    }\n\n    if (statusResult.status === 'completed') {\n      return {\n        videos: statusResult.videos,\n        warnings: allWarnings,\n        providerMetadata: operationProviderMetadata,\n        response: statusResult.response,\n      };\n    }\n\n    if (webhookReceived != null) {\n      throw new Error(\n        'Video generation did not complete after webhook notification.',\n      );\n    }\n  }\n}\n\nasync function waitForWebhook({\n  received,\n  timeoutMs,\n  abortSignal,\n  delay,\n}: {\n  received: PromiseLike<Experimental_VideoModelV4OperationWebhook>;\n  timeoutMs: number;\n  abortSignal?: AbortSignal;\n  delay: (\n    delayInMs: number,\n    options?: { abortSignal?: AbortSignal },\n  ) => PromiseLike<void>;\n}) {\n  // Cancel the timeout delay once the webhook arrives (or we abort/time out),\n  // so its timer does not keep the event loop alive on the success path.\n  const timeoutController =\n    typeof globalThis.AbortController === 'function'\n      ? new globalThis.AbortController()\n      : undefined;\n  try {\n    await Promise.race([\n      received,\n      delay(timeoutMs, {\n        abortSignal:\n          timeoutController == null\n            ? abortSignal\n            : mergeAbortSignals(abortSignal, timeoutController.signal),\n      }).then(() => {\n        throw new Error(`Video generation timed out after ${timeoutMs}ms.`);\n      }),\n    ]);\n  } finally {\n    timeoutController?.abort();\n  }\n}\n\nfunction mergeProviderMetadata(\n  target: SharedV4ProviderMetadata,\n  source: SharedV4ProviderMetadata,\n): void {\n  for (const [providerName, metadataValue] of Object.entries(source)) {\n    const existingMetadata = target[providerName];\n    if (\n      existingMetadata != null &&\n      typeof existingMetadata === 'object' &&\n      metadataValue != null &&\n      typeof metadataValue === 'object'\n    ) {\n      target[providerName] = {\n        ...existingMetadata,\n        ...metadataValue,\n      };\n\n      if (\n        'videos' in existingMetadata &&\n        Array.isArray(existingMetadata.videos) &&\n        'videos' in metadataValue &&\n        Array.isArray(metadataValue.videos)\n      ) {\n        (target[providerName] as { videos: unknown[] }).videos = [\n          ...existingMetadata.videos,\n          ...metadataValue.videos,\n        ];\n      }\n    } else {\n      target[providerName] = metadataValue;\n    }\n  }\n}\n\nfunction normalizePrompt(promptArg: GenerateVideoPrompt): {\n  prompt: string | undefined;\n  image: Experimental_VideoModelV4File | undefined;\n} {\n  if (typeof promptArg === 'string') {\n    return {\n      prompt: promptArg,\n      image: undefined,\n    };\n  }\n\n  return {\n    prompt: promptArg.text,\n    image:\n      promptArg.image != null ? normalizeImageData(promptArg.image) : undefined,\n  };\n}\n\n/**\n * Shared input normalization for `experimental_generateVideo` and\n * `experimental_startVideo`: prompt/image plus the frameImages /\n * inputReferences precedence rules and their warnings.\n */\nexport function normalizeVideoCallInputs({\n  promptArg,\n  frameImages,\n  inputReferences,\n}: {\n  promptArg: GenerateVideoPrompt;\n  frameImages?: Array<{\n    image: DataContent;\n    frameType: Experimental_VideoModelV4FrameType;\n  }>;\n  inputReferences?: Array<\n    DataContent | { data: DataContent; mediaType?: string }\n  >;\n}): {\n  prompt: string | undefined;\n  resolvedImage: Experimental_VideoModelV4File | undefined;\n  normalizedFrameImages: Array<Experimental_VideoModelV4FrameImage> | undefined;\n  effectiveInputReferences: Array<Experimental_VideoModelV4File> | undefined;\n  warnings: Array<Warning>;\n} {\n  const { prompt, image } = normalizePrompt(promptArg);\n\n  const normalizedFrameImages:\n    | Array<Experimental_VideoModelV4FrameImage>\n    | undefined = frameImages?.flatMap(frame => {\n    const normalizedImage = normalizeImageData(frame.image);\n    return normalizedImage != null\n      ? [{ image: normalizedImage, frameType: frame.frameType }]\n      : [];\n  });\n\n  const normalizedInputReferences:\n    | Array<Experimental_VideoModelV4File>\n    | undefined = inputReferences?.flatMap(reference => {\n    const normalized = normalizeReferenceData(reference);\n    return normalized != null ? [normalized] : [];\n  });\n\n  const effectiveInputReferences =\n    normalizedFrameImages != null && normalizedFrameImages.length > 0\n      ? undefined\n      : normalizedInputReferences;\n\n  const warnings: Array<Warning> = [];\n\n  if (\n    normalizedFrameImages != null &&\n    normalizedFrameImages.length > 0 &&\n    normalizedInputReferences != null &&\n    normalizedInputReferences.length > 0\n  ) {\n    warnings.push({\n      type: 'other',\n      message:\n        'inputReferences were ignored because frameImages were provided; ' +\n        'frameImages and inputReferences cannot be combined.',\n    });\n  }\n\n  const firstFrameImage = normalizedFrameImages?.find(\n    frame => frame.frameType === 'first_frame',\n  )?.image;\n\n  if (image != null && firstFrameImage != null) {\n    warnings.push({\n      type: 'other',\n      message:\n        'prompt.image was ignored because a first_frame frameImage was provided; ' +\n        'the first_frame frameImage takes precedence as the start image.',\n    });\n  }\n\n  const resolvedImage = firstFrameImage ?? image;\n\n  return {\n    prompt,\n    resolvedImage,\n    normalizedFrameImages,\n    effectiveInputReferences,\n    warnings,\n  };\n}\n\nfunction detectFileMediaType(\n  data: Uint8Array,\n  restrictToImages: boolean,\n): string {\n  const detected = restrictToImages\n    ? detectMediaType({ data, topLevelType: 'image' })\n    : detectMediaType({ data });\n  return detected ?? 'image/png';\n}\n\n/**\n * Normalizes a {@link DataContent} image into a {@link Experimental_VideoModelV4File}.\n * Accepts a URL string, a data URL, a base64 string, or binary image data.\n */\nfunction normalizeImageData(\n  dataContent: DataContent,\n  { restrictToImages = true }: { restrictToImages?: boolean } = {},\n): Experimental_VideoModelV4File | undefined {\n  if (typeof dataContent === 'string') {\n    if (\n      dataContent.startsWith('http://') ||\n      dataContent.startsWith('https://')\n    ) {\n      return {\n        type: 'url',\n        url: dataContent,\n      };\n    }\n\n    if (dataContent.startsWith('data:')) {\n      const { mediaType, base64Content } = splitDataUrl(dataContent);\n      const data = convertBase64ToUint8Array(base64Content ?? '');\n      return {\n        type: 'file',\n        mediaType: mediaType ?? detectFileMediaType(data, restrictToImages),\n        data,\n      };\n    }\n\n    const bytes = convertBase64ToUint8Array(dataContent);\n    return {\n      type: 'file',\n      mediaType: detectFileMediaType(bytes, restrictToImages),\n      data: bytes,\n    };\n  }\n\n  if (dataContent instanceof Uint8Array || dataContent instanceof ArrayBuffer) {\n    const bytes =\n      dataContent instanceof Uint8Array\n        ? dataContent\n        : new Uint8Array(dataContent);\n    return {\n      type: 'file',\n      mediaType: detectFileMediaType(bytes, restrictToImages),\n      data: bytes,\n    };\n  }\n\n  return undefined;\n}\n\n/**\n * Normalizes a reference input into a {@link Experimental_VideoModelV4File},\n * accepting either a plain {@link DataContent} or the object form that carries\n * an explicit `mediaType`.\n */\nfunction normalizeReferenceData(\n  reference:\n    | DataContent\n    | {\n        data: DataContent;\n        mediaType?: string;\n      },\n): Experimental_VideoModelV4File | undefined {\n  const isObjectForm =\n    typeof reference === 'object' &&\n    reference != null &&\n    !(reference instanceof Uint8Array) &&\n    !(reference instanceof ArrayBuffer) &&\n    'data' in reference;\n\n  if (!isObjectForm) {\n    return normalizeImageData(reference as DataContent, {\n      restrictToImages: false,\n    });\n  }\n\n  const normalized = normalizeImageData(reference.data, {\n    restrictToImages: false,\n  });\n  if (normalized == null) {\n    return normalized;\n  }\n\n  return {\n    ...normalized,\n    ...(reference.mediaType != null ? { mediaType: reference.mediaType } : {}),\n  };\n}\n\nasync function invokeModelMaxVideosPerCall(model: Experimental_VideoModelV4) {\n  if (typeof model.maxVideosPerCall === 'function') {\n    return await model.maxVideosPerCall({ modelId: model.modelId });\n  }\n\n  return model.maxVideosPerCall;\n}\n","import type {\n  Experimental_VideoModelV4CallOptions,\n  Experimental_VideoModelV4FrameType,\n  JSONValue,\n} from '@ai-sdk/provider';\nimport {\n  generateId,\n  withUserAgentSuffix,\n  type DataContent,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { resolveVideoModel } from '../model/resolve-model';\nimport type {\n  VideoModel,\n  VideoModelProviderMetadata,\n} from '../types/video-model';\nimport type { VideoModelResponseMetadata } from '../types/video-model-response-metadata';\nimport type { Warning } from '../types/warning';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\nimport {\n  normalizeVideoCallInputs,\n  type GenerateVideoPrompt,\n} from './generate-video';\n\n/**\n * The result of an `experimental_startVideo` call.\n */\nexport interface StartVideoResult {\n  /**\n   * JSON-serializable opaque reference to the started generation.\n   * Persist it and pass it to `experimental_getVideoStatus` to retrieve the\n   * status and result later — from any process.\n   */\n  readonly operation: JSONValue;\n\n  /**\n   * Warnings for the call, e.g. unsupported settings.\n   */\n  readonly warnings: Array<Warning>;\n\n  /**\n   * Provider-specific metadata passed through from the provider.\n   * Carries the provider's own job identifiers (e.g. the AI Gateway's\n   * `providerMetadata.gateway.asyncJob.jobId` and, when `webhookUrl` was\n   * given, its `webhookSigningSecret`).\n   */\n  readonly providerMetadata?: VideoModelProviderMetadata;\n\n  /**\n   * Response metadata from the provider.\n   */\n  readonly response: VideoModelResponseMetadata;\n}\n\n/**\n * Starts an asynchronous video generation and returns immediately with an\n * opaque `operation` reference — without waiting for the video to finish.\n *\n * This is the fire-and-forget counterpart to `experimental_generateVideo`:\n * use it to fan out many jobs, to submit from a process that will not stay\n * alive, or together with `webhookUrl` so the provider notifies your endpoint\n * at the terminal state. Check the outcome with `experimental_getVideoStatus`,\n * or let your webhook receiver fetch the result.\n *\n * @param model - The video model to use. Must implement `doStart`.\n * @param prompt - The prompt that should be used to generate the video.\n * @param n - Number of videos to generate. Default: 1. Must not exceed the\n * model's `maxVideosPerCall` — fan out with multiple `startVideo` calls.\n * @param aspectRatio - Aspect ratio of the videos to generate. Must have the format `{width}:{height}`, or `'adaptive'`.\n * @param resolution - Resolution of the videos to generate. Must have the format `{width}x${height}`.\n * @param duration - Duration of the video in seconds.\n * @param fps - Frames per second for the video.\n * @param seed - Seed for the video generation.\n * @param frameImages - Role-tagged image inputs for image-to-video and first-last-frame generation.\n * @param inputReferences - Reference image or video inputs for reference-to-video generation.\n * @param generateAudio - Whether the model should generate audio alongside the video.\n * @param providerOptions - Additional provider-specific options that are passed through to the provider\n * as body parameters.\n * @param maxRetries - Maximum number of retries for the start call. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n * @param webhookUrl - A URL the provider should notify when the generation\n * reaches a terminal state.\n *\n * @returns A result object that contains the opaque `operation` reference,\n * warnings, provider metadata (including the provider's job id), and response\n * metadata.\n */\nexport async function experimental_startVideo({\n  model: modelArg,\n  prompt: promptArg,\n  n = 1,\n  maxVideosPerCall,\n  aspectRatio,\n  resolution,\n  duration,\n  fps,\n  seed,\n  frameImages,\n  inputReferences,\n  generateAudio,\n  providerOptions,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  webhookUrl,\n}: {\n  model: VideoModel;\n  prompt: GenerateVideoPrompt;\n  n?: number;\n  maxVideosPerCall?: number;\n  aspectRatio?: `${number}:${number}` | 'adaptive';\n  resolution?: `${number}x${number}`;\n  duration?: number;\n  fps?: number;\n  seed?: number;\n  frameImages?: Array<{\n    image: DataContent;\n    frameType: Experimental_VideoModelV4FrameType;\n  }>;\n  inputReferences?: Array<\n    DataContent | { data: DataContent; mediaType?: string }\n  >;\n  generateAudio?: boolean;\n  providerOptions?: ProviderOptions;\n  maxRetries?: number;\n  abortSignal?: AbortSignal;\n  headers?: Record<string, string>;\n  webhookUrl?: string;\n}): Promise<StartVideoResult> {\n  const model = resolveVideoModel(modelArg);\n\n  if (model.doStart == null) {\n    throw new Error(\n      `Video model ${model.modelId} does not implement doStart. ` +\n        'Use generateVideo for models without an asynchronous start/status flow.',\n    );\n  }\n\n  if (!Number.isInteger(n) || n < 1) {\n    throw new Error(\n      `Invalid n: expected a positive integer, received ${JSON.stringify(n)}.`,\n    );\n  }\n\n  // A start yields one operation covering all n videos: refuse to silently\n  // exceed a known per-call limit instead of splitting into several starts.\n  const knownMaxVideosPerCall =\n    maxVideosPerCall ??\n    (typeof model.maxVideosPerCall === 'function'\n      ? await model.maxVideosPerCall({ modelId: model.modelId })\n      : model.maxVideosPerCall);\n  if (knownMaxVideosPerCall != null && n > knownMaxVideosPerCall) {\n    throw new Error(\n      `Video model ${model.modelId} supports at most ${knownMaxVideosPerCall} video(s) per call, ` +\n        `but ${n} were requested. Split the batch across multiple startVideo calls.`,\n    );\n  }\n\n  const {\n    prompt,\n    resolvedImage,\n    normalizedFrameImages,\n    effectiveInputReferences,\n    warnings,\n  } = normalizeVideoCallInputs({ promptArg, frameImages, inputReferences });\n\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  // `doStart` is billable: mint one idempotency token per logical start,\n  // outside the retry closure; a caller-supplied key wins.\n  const callerIdempotencyKey = Object.entries(headers ?? {}).find(\n    ([key, value]) =>\n      key.toLowerCase() === 'idempotency-key' && value !== undefined,\n  );\n\n  const callOptions: Experimental_VideoModelV4CallOptions & {\n    webhookUrl?: string;\n  } = {\n    prompt,\n    n,\n    aspectRatio,\n    resolution,\n    duration,\n    fps,\n    seed,\n    image: resolvedImage,\n    frameImages: normalizedFrameImages,\n    inputReferences: effectiveInputReferences,\n    generateAudio,\n    providerOptions: providerOptions ?? {},\n    headers: {\n      ...withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`),\n      ...(callerIdempotencyKey\n        ? {}\n        : { 'idempotency-key': `aisdk_vid_${generateId()}` }),\n    },\n    abortSignal,\n    webhookUrl,\n  };\n\n  const startResult = await retry(() => model.doStart!(callOptions));\n\n  return {\n    operation: startResult.operation,\n    warnings: [...warnings, ...startResult.warnings],\n    providerMetadata: startResult.providerMetadata,\n    response: startResult.response,\n  };\n}\n","import type {\n  Experimental_VideoModelV4OperationStatusResult,\n  JSONValue,\n} from '@ai-sdk/provider';\nimport { withUserAgentSuffix } from '@ai-sdk/provider-utils';\nimport { resolveVideoModel } from '../model/resolve-model';\nimport type { VideoModel } from '../types/video-model';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\n\n/**\n * The result of an `experimental_getVideoStatus` call: the spec-level status\n * payload, discriminated by `status` (`pending` | `completed` | `error`).\n */\nexport type GetVideoStatusResult =\n  Experimental_VideoModelV4OperationStatusResult;\n\n/**\n * Checks the status of an asynchronous video generation started with\n * `experimental_startVideo`.\n *\n * A single check — no polling loop. Poll by calling this on your own\n * schedule, or skip polling entirely when the start used `webhookUrl` and\n * your receiver fetches the result after the terminal notification arrives.\n *\n * @param model - The video model the operation was started on.\n * @param operation - The opaque reference returned by `experimental_startVideo`.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param maxRetries - Maximum number of retries for the status call. Set to 0 to disable retries. Default: 2.\n */\nexport async function experimental_getVideoStatus(\n  modelArg: VideoModel,\n  {\n    operation,\n    headers,\n    abortSignal,\n    maxRetries: maxRetriesArg,\n  }: {\n    operation: JSONValue;\n    headers?: Record<string, string>;\n    abortSignal?: AbortSignal;\n    maxRetries?: number;\n  },\n): Promise<GetVideoStatusResult> {\n  const model = resolveVideoModel(modelArg);\n\n  if (model.doStatus == null) {\n    throw new Error(\n      `Video model ${model.modelId} does not implement doStatus.`,\n    );\n  }\n\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  return retry(() =>\n    model.doStatus!({\n      operation,\n      headers: withUserAgentSuffix(headers ?? {}, `ai/${VERSION}`),\n      abortSignal,\n    }),\n  );\n}\n","import type { EmbeddingModelV4CallOptions } from '@ai-sdk/provider';\nimport type { EmbeddingModelMiddleware } from '../types';\nimport { mergeObjects } from '../util/merge-objects';\n\n/**\n * Applies default settings for an embedding model.\n */\nexport function defaultEmbeddingSettingsMiddleware({\n  settings,\n}: {\n  settings: Partial<{\n    headers?: EmbeddingModelV4CallOptions['headers'];\n    providerOptions?: EmbeddingModelV4CallOptions['providerOptions'];\n  }>;\n}): EmbeddingModelMiddleware {\n  return {\n    specificationVersion: 'v4',\n    transformParams: async ({ params }) => {\n      return mergeObjects(settings, params) as EmbeddingModelV4CallOptions;\n    },\n  };\n}\n","import type { LanguageModelV4Prompt } from '@ai-sdk/provider';\nimport { asArray } from '@ai-sdk/provider-utils';\nimport type { Instructions } from '../prompt/prompt';\nimport type { LanguageModelMiddleware } from '../types';\n\n/**\n * Applies default instructions to a language model when a call does not\n * already contain a system message.\n */\nexport function defaultInstructionsMiddleware({\n  instructions,\n}: {\n  /**\n   * Default instructions to prepend to calls that do not contain a system\n   * message.\n   */\n  instructions: Instructions;\n}): LanguageModelMiddleware {\n  const defaultSystemMessages: LanguageModelV4Prompt =\n    typeof instructions === 'string'\n      ? [{ role: 'system', content: instructions }]\n      : asArray(instructions).map(message => ({\n          role: 'system',\n          content: message.content,\n          providerOptions: message.providerOptions,\n        }));\n\n  return {\n    specificationVersion: 'v4',\n    transformParams: async ({ params }) => {\n      if (\n        defaultSystemMessages.length === 0 ||\n        params.prompt.some(message => message.role === 'system')\n      ) {\n        return params;\n      }\n\n      return {\n        ...params,\n        prompt: [...defaultSystemMessages, ...params.prompt],\n      };\n    },\n  };\n}\n","import type { LanguageModelV4CallOptions } from '@ai-sdk/provider';\nimport type { LanguageModelMiddleware } from '../types';\nimport { mergeObjects } from '../util/merge-objects';\n\n/**\n * Applies default settings for a language model.\n */\nexport function defaultSettingsMiddleware({\n  settings,\n}: {\n  settings: Partial<{\n    maxOutputTokens?: LanguageModelV4CallOptions['maxOutputTokens'];\n    temperature?: LanguageModelV4CallOptions['temperature'];\n    stopSequences?: LanguageModelV4CallOptions['stopSequences'];\n    topP?: LanguageModelV4CallOptions['topP'];\n    topK?: LanguageModelV4CallOptions['topK'];\n    presencePenalty?: LanguageModelV4CallOptions['presencePenalty'];\n    frequencyPenalty?: LanguageModelV4CallOptions['frequencyPenalty'];\n    responseFormat?: LanguageModelV4CallOptions['responseFormat'];\n    seed?: LanguageModelV4CallOptions['seed'];\n    tools?: LanguageModelV4CallOptions['tools'];\n    toolChoice?: LanguageModelV4CallOptions['toolChoice'];\n    headers?: LanguageModelV4CallOptions['headers'];\n    providerOptions?: LanguageModelV4CallOptions['providerOptions'];\n  }>;\n}): LanguageModelMiddleware {\n  return {\n    specificationVersion: 'v4',\n    transformParams: async ({ params }) => {\n      return mergeObjects(settings, params) as LanguageModelV4CallOptions;\n    },\n  };\n}\n","import type {\n  LanguageModelV4Content,\n  LanguageModelV4StreamPart,\n} from '@ai-sdk/provider';\nimport type { LanguageModelMiddleware } from '../types/language-model-middleware';\nimport { createIdMap } from '../util/create-id-map';\n\n/**\n * Default transform function that strips markdown code fences from text.\n */\nfunction defaultTransform(text: string): string {\n  return text\n    .replace(/^```(?:json)?\\s*\\n?/, '')\n    .replace(/\\n?```\\s*$/, '')\n    .trim();\n}\n\nfunction stripMarkdownCodeFenceSuffix(text: string): string {\n  return text.replace(/\\n?```\\s*$/, '').trimEnd();\n}\n\n/**\n * Middleware that extracts JSON from text content by stripping\n * markdown code fences and other formatting.\n *\n * This is useful when using Output.object() with models that wrap\n * JSON responses in markdown code blocks.\n *\n * @param options - Configuration options for the middleware.\n * @param options.transform - Custom transform function. If provided, this will be\n * used instead of the default markdown fence stripping.\n */\nexport function extractJsonMiddleware(options?: {\n  /**\n   * Custom transform function to apply to text content.\n   * Receives the raw text and should return the transformed text.\n   * If not provided, the default transform strips markdown code fences.\n   */\n  transform?: (text: string) => string;\n}): LanguageModelMiddleware {\n  const transform = options?.transform ?? defaultTransform;\n  const hasCustomTransform = options?.transform !== undefined;\n\n  return {\n    specificationVersion: 'v4',\n\n    wrapGenerate: async ({ doGenerate }) => {\n      const { content, ...rest } = await doGenerate();\n\n      const transformedContent: LanguageModelV4Content[] = [];\n      for (const part of content) {\n        if (part.type !== 'text') {\n          transformedContent.push(part);\n          continue;\n        }\n\n        transformedContent.push({\n          ...part,\n          text: transform(part.text),\n        });\n      }\n\n      return { content: transformedContent, ...rest };\n    },\n    wrapStream: async ({ doStream }) => {\n      const { stream, ...rest } = await doStream();\n\n      const textBlocks: Record<\n        string,\n        {\n          startEvent: LanguageModelV4StreamPart;\n          phase: 'prefix' | 'streaming' | 'buffering';\n          buffer: string;\n          prefixStripped: boolean;\n        }\n      > = createIdMap();\n\n      const SUFFIX_BUFFER_SIZE = 12;\n\n      return {\n        stream: stream.pipeThrough(\n          new TransformStream<\n            LanguageModelV4StreamPart,\n            LanguageModelV4StreamPart\n          >({\n            transform: (chunk, controller) => {\n              if (chunk.type === 'text-start') {\n                textBlocks[chunk.id] = {\n                  startEvent: chunk,\n                  // Custom transforms need to buffer all content\n                  phase: hasCustomTransform ? 'buffering' : 'prefix',\n                  buffer: '',\n                  prefixStripped: false,\n                };\n                return;\n              }\n\n              if (chunk.type === 'text-delta') {\n                const block = textBlocks[chunk.id];\n                if (!block) {\n                  controller.enqueue(chunk);\n                  return;\n                }\n\n                block.buffer += chunk.delta;\n\n                // Custom transform: buffer everything, transform at end\n                if (block.phase === 'buffering') {\n                  return;\n                }\n\n                if (block.phase === 'prefix') {\n                  // Check if we can determine prefix status\n                  if (\n                    block.buffer.length > 0 &&\n                    !block.buffer.startsWith('`')\n                  ) {\n                    block.phase = 'streaming';\n                    controller.enqueue(block.startEvent);\n                  } else if (block.buffer.startsWith('```')) {\n                    // Only strip prefix when we have a newline (fence is complete)\n                    if (block.buffer.includes('\\n')) {\n                      const prefixMatch =\n                        block.buffer.match(/^```(?:json)?\\s*\\n/);\n                      if (prefixMatch) {\n                        block.buffer = block.buffer.slice(\n                          prefixMatch[0].length,\n                        );\n                        block.prefixStripped = true;\n                        block.phase = 'streaming';\n                        controller.enqueue(block.startEvent);\n                      } else {\n                        // Has newline but doesn't match fence pattern\n                        block.phase = 'streaming';\n                        controller.enqueue(block.startEvent);\n                      }\n                    }\n                    // else keep buffering until we see a newline\n                  } else if (\n                    block.buffer.length >= 3 &&\n                    !block.buffer.startsWith('```')\n                  ) {\n                    block.phase = 'streaming';\n                    controller.enqueue(block.startEvent);\n                  }\n                }\n\n                // Stream content\n                if (\n                  block.phase === 'streaming' &&\n                  block.buffer.length > SUFFIX_BUFFER_SIZE\n                ) {\n                  const toStream = block.buffer.slice(0, -SUFFIX_BUFFER_SIZE);\n                  block.buffer = block.buffer.slice(-SUFFIX_BUFFER_SIZE);\n                  controller.enqueue({\n                    type: 'text-delta',\n                    id: chunk.id,\n                    delta: toStream,\n                  });\n                }\n                return;\n              }\n\n              if (chunk.type === 'text-end') {\n                const block = textBlocks[chunk.id];\n                if (block) {\n                  if (block.phase === 'prefix' || block.phase === 'buffering') {\n                    controller.enqueue(block.startEvent);\n                  }\n\n                  let remaining = block.buffer;\n                  if (block.phase === 'buffering') {\n                    remaining = transform(remaining);\n                  } else if (block.prefixStripped) {\n                    // strip suffix since prefix already handled\n                    remaining = stripMarkdownCodeFenceSuffix(remaining);\n                  } else if (block.phase === 'prefix') {\n                    // No text has streamed yet, so the full transform is safe.\n                    remaining = transform(remaining);\n                  } else {\n                    // Only strip the suffix. Since earlier text may already have\n                    // streamed, trimming the remaining suffix would remove valid\n                    // leading whitespace at the stream boundary.\n                    remaining = stripMarkdownCodeFenceSuffix(remaining);\n                  }\n\n                  if (remaining.length > 0) {\n                    controller.enqueue({\n                      type: 'text-delta',\n                      id: chunk.id,\n                      delta: remaining,\n                    });\n                  }\n                  controller.enqueue(chunk);\n                  delete textBlocks[chunk.id];\n                  return;\n                }\n              }\n              controller.enqueue(chunk);\n            },\n          }),\n        ),\n        ...rest,\n      };\n    },\n  };\n}\n","/**\n * Finds the potential starting index where searchedText could begin in text.\n *\n * This function checks for both complete and partial matches:\n * - If searchedText is found as a complete substring, returns the index of the first occurrence.\n * - If the end of text matches the beginning of searchedText (partial match),\n *   returns the index where that partial match starts.\n *\n * @param text - The text to search within.\n * @param searchedText - The text to search for.\n * @returns The starting index of the match (complete or partial), or null if\n *          searchedText is empty or no match is found.\n */\nexport function getPotentialStartIndex(\n  text: string,\n  searchedText: string,\n): number | null {\n  // Return null immediately if searchedText is empty.\n  if (searchedText.length === 0) {\n    return null;\n  }\n\n  // Check if the searchedText exists as a direct substring of text.\n  const directIndex = text.indexOf(searchedText);\n  if (directIndex !== -1) {\n    return directIndex;\n  }\n\n  // Otherwise, look for the largest suffix of \"text\" that matches\n  // a prefix of \"searchedText\". We go from the end of text inward.\n  for (let i = text.length - 1; i >= 0; i--) {\n    const suffix = text.substring(i);\n    if (searchedText.startsWith(suffix)) {\n      return i;\n    }\n  }\n\n  return null;\n}\n","import type {\n  LanguageModelV4Content,\n  LanguageModelV4StreamPart,\n} from '@ai-sdk/provider';\nimport type { LanguageModelMiddleware } from '../types/language-model-middleware';\nimport { createIdMap } from '../util/create-id-map';\nimport { getPotentialStartIndex } from '../util/get-potential-start-index';\n\n/**\n * Extracts an XML-tagged reasoning section from the generated text and exposes it\n * as a `reasoning` property on the result.\n *\n * @param tagName - The name of the XML tag to extract reasoning from.\n * @param separator - The separator to use between reasoning and text sections.\n * @param startWithReasoning - Whether to start with reasoning tokens.\n */\nexport function extractReasoningMiddleware({\n  tagName,\n  separator = '\\n',\n  startWithReasoning = false,\n}: {\n  tagName: string;\n  separator?: string;\n  startWithReasoning?: boolean;\n}): LanguageModelMiddleware {\n  const openingTag = `<${tagName}>`;\n  const closingTag = `<\\/${tagName}>`;\n\n  return {\n    specificationVersion: 'v4',\n    wrapGenerate: async ({ doGenerate }) => {\n      const { content, ...rest } = await doGenerate();\n\n      const transformedContent: LanguageModelV4Content[] = [];\n      for (const part of content) {\n        if (part.type !== 'text') {\n          transformedContent.push(part);\n          continue;\n        }\n\n        const text = startWithReasoning ? openingTag + part.text : part.text;\n\n        const regexp = new RegExp(`${openingTag}(.*?)${closingTag}`, 'gs');\n        const matches = Array.from(text.matchAll(regexp));\n\n        if (!matches.length) {\n          transformedContent.push(part);\n          continue;\n        }\n\n        const reasoningText = matches.map(match => match[1]).join(separator);\n\n        let textWithoutReasoning = text;\n        for (let i = matches.length - 1; i >= 0; i--) {\n          const match = matches[i];\n\n          const beforeMatch = textWithoutReasoning.slice(0, match.index);\n          const afterMatch = textWithoutReasoning.slice(\n            match.index! + match[0].length,\n          );\n\n          textWithoutReasoning =\n            beforeMatch +\n            (beforeMatch.length > 0 && afterMatch.length > 0 ? separator : '') +\n            afterMatch;\n        }\n\n        transformedContent.push({\n          type: 'reasoning',\n          text: reasoningText,\n        });\n\n        transformedContent.push({\n          type: 'text',\n          text: textWithoutReasoning,\n        });\n      }\n\n      return { content: transformedContent, ...rest };\n    },\n\n    wrapStream: async ({ doStream }) => {\n      const { stream, ...rest } = await doStream();\n\n      const reasoningExtractions: Record<\n        string,\n        {\n          isFirstReasoning: boolean;\n          isFirstText: boolean;\n          afterSwitch: boolean;\n          isReasoning: boolean;\n          buffer: string;\n          idCounter: number;\n          textId: string;\n        }\n      > = createIdMap();\n\n      let delayedTextStart: LanguageModelV4StreamPart | undefined;\n\n      return {\n        stream: stream.pipeThrough(\n          new TransformStream<\n            LanguageModelV4StreamPart,\n            LanguageModelV4StreamPart\n          >({\n            transform: (chunk, controller) => {\n              // do not send `text-start` before `reasoning-start`\n              // https://github.com/vercel/ai/issues/7774\n              if (chunk.type === 'text-start') {\n                delayedTextStart = chunk;\n                return;\n              }\n\n              if (chunk.type === 'text-end' && delayedTextStart) {\n                controller.enqueue(delayedTextStart);\n                delayedTextStart = undefined;\n              }\n\n              if (chunk.type !== 'text-delta') {\n                controller.enqueue(chunk);\n                return;\n              }\n\n              if (reasoningExtractions[chunk.id] == null) {\n                reasoningExtractions[chunk.id] = {\n                  isFirstReasoning: true,\n                  isFirstText: true,\n                  afterSwitch: false,\n                  isReasoning: startWithReasoning,\n                  buffer: '',\n                  idCounter: 0,\n                  textId: chunk.id,\n                };\n              }\n\n              const activeExtraction = reasoningExtractions[chunk.id];\n\n              activeExtraction.buffer += chunk.delta;\n\n              function publish(text: string) {\n                if (text.length > 0) {\n                  const prefix =\n                    activeExtraction.afterSwitch &&\n                    (activeExtraction.isReasoning\n                      ? !activeExtraction.isFirstReasoning\n                      : !activeExtraction.isFirstText)\n                      ? separator\n                      : '';\n\n                  if (\n                    activeExtraction.isReasoning &&\n                    (activeExtraction.afterSwitch ||\n                      activeExtraction.isFirstReasoning)\n                  ) {\n                    controller.enqueue({\n                      type: 'reasoning-start',\n                      id: `reasoning-${activeExtraction.idCounter}`,\n                    });\n                  }\n\n                  if (activeExtraction.isReasoning) {\n                    controller.enqueue({\n                      type: 'reasoning-delta',\n                      delta: prefix + text,\n                      id: `reasoning-${activeExtraction.idCounter}`,\n                    });\n                  } else {\n                    if (delayedTextStart) {\n                      controller.enqueue(delayedTextStart);\n                      delayedTextStart = undefined;\n                    }\n                    controller.enqueue({\n                      type: 'text-delta',\n                      delta: prefix + text,\n                      id: activeExtraction.textId,\n                    });\n                  }\n                  activeExtraction.afterSwitch = false;\n\n                  if (activeExtraction.isReasoning) {\n                    activeExtraction.isFirstReasoning = false;\n                  } else {\n                    activeExtraction.isFirstText = false;\n                  }\n                }\n              }\n\n              do {\n                const nextTag = activeExtraction.isReasoning\n                  ? closingTag\n                  : openingTag;\n\n                const startIndex = getPotentialStartIndex(\n                  activeExtraction.buffer,\n                  nextTag,\n                );\n\n                // no opening or closing tag found, publish the buffer\n                if (startIndex == null) {\n                  publish(activeExtraction.buffer);\n                  activeExtraction.buffer = '';\n                  break;\n                }\n\n                // publish text before the tag\n                publish(activeExtraction.buffer.slice(0, startIndex));\n\n                const foundFullMatch =\n                  startIndex + nextTag.length <= activeExtraction.buffer.length;\n\n                if (foundFullMatch) {\n                  activeExtraction.buffer = activeExtraction.buffer.slice(\n                    startIndex + nextTag.length,\n                  );\n\n                  if (activeExtraction.isReasoning) {\n                    // Emit reasoning-start for empty reasoning blocks (no delta was published).\n                    // This handles both cases:\n                    // - startWithReasoning=false: <think></think> (afterSwitch=true)\n                    // - startWithReasoning=true: immediate </think> (afterSwitch=false)\n                    if (activeExtraction.isFirstReasoning) {\n                      controller.enqueue({\n                        type: 'reasoning-start',\n                        id: `reasoning-${activeExtraction.idCounter}`,\n                      });\n                    }\n\n                    // reasoning part finished:\n                    controller.enqueue({\n                      type: 'reasoning-end',\n                      id: `reasoning-${activeExtraction.idCounter++}`,\n                    });\n                  }\n\n                  activeExtraction.isReasoning = !activeExtraction.isReasoning;\n                  activeExtraction.afterSwitch = true;\n                } else {\n                  activeExtraction.buffer =\n                    activeExtraction.buffer.slice(startIndex);\n                  break;\n                }\n              } while (true);\n            },\n          }),\n        ),\n        ...rest,\n      };\n    },\n  };\n}\n","import type { LanguageModelV4StreamPart } from '@ai-sdk/provider';\nimport type { LanguageModelMiddleware } from '../types';\n\n/**\n * Simulates streaming chunks with the response from a generate call.\n */\nexport function simulateStreamingMiddleware(): LanguageModelMiddleware {\n  return {\n    specificationVersion: 'v4',\n    wrapStream: async ({ doGenerate }) => {\n      const result = await doGenerate();\n\n      let id = 0;\n\n      const simulatedStream = new ReadableStream<LanguageModelV4StreamPart>({\n        start(controller) {\n          controller.enqueue({\n            type: 'stream-start',\n            warnings: result.warnings,\n          });\n\n          controller.enqueue({ type: 'response-metadata', ...result.response });\n\n          for (const part of result.content) {\n            switch (part.type) {\n              case 'text': {\n                if (part.text.length > 0) {\n                  controller.enqueue({ type: 'text-start', id: String(id) });\n                  controller.enqueue({\n                    type: 'text-delta',\n                    id: String(id),\n                    delta: part.text,\n                  });\n                  controller.enqueue({ type: 'text-end', id: String(id) });\n                  id++;\n                }\n                break;\n              }\n              case 'reasoning': {\n                controller.enqueue({\n                  type: 'reasoning-start',\n                  id: String(id),\n                  providerMetadata: part.providerMetadata,\n                });\n                controller.enqueue({\n                  type: 'reasoning-delta',\n                  id: String(id),\n                  delta: part.text,\n                });\n                controller.enqueue({ type: 'reasoning-end', id: String(id) });\n                id++;\n                break;\n              }\n              default: {\n                controller.enqueue(part);\n                break;\n              }\n            }\n          }\n\n          controller.enqueue({\n            type: 'finish',\n            finishReason: result.finishReason,\n            usage: result.usage,\n            providerMetadata: result.providerMetadata,\n          });\n\n          controller.close();\n        },\n      });\n\n      return {\n        stream: simulatedStream,\n        request: result.request,\n        response: result.response,\n      };\n    },\n  };\n}\n","import type { JSONObject, LanguageModelV4FunctionTool } from '@ai-sdk/provider';\nimport type { LanguageModelMiddleware } from '../types';\n\nfunction defaultFormatExample(example: { input: JSONObject }): string {\n  return JSON.stringify(example.input);\n}\n\n/**\n * Middleware that appends input examples to tool descriptions.\n *\n * This is useful for providers that don't natively support the `inputExamples`\n * property. The middleware serializes examples into the tool's description text.\n *\n * @param options - Configuration options for the middleware.\n * @param options.prefix - A prefix to prepend before the examples. Default: 'Input Examples:'\n * @param options.format - Optional custom formatter for each example.\n *   Receives the example object and its index. Default: JSON.stringify(example.input)\n * @param options.remove - Whether to remove the inputExamples property\n *   after adding them to the description. Default: true\n *\n * @example\n * ```ts\n * import { wrapLanguageModel, addToolInputExamplesMiddleware } from 'ai';\n *\n * const model = wrapLanguageModel({\n *   model: yourModel,\n *   middleware: addToolInputExamplesMiddleware(),\n * });\n * ```\n */\nexport function addToolInputExamplesMiddleware({\n  prefix = 'Input Examples:',\n  format = defaultFormatExample,\n  remove = true,\n}: {\n  /**\n   * A prefix to prepend before the examples.\n   */\n  prefix?: string;\n\n  /**\n   * Optional custom formatter for each example.\n   * Receives the example object and its index.\n   * Default: JSON.stringify(example.input)\n   */\n  format?: (example: { input: JSONObject }, index: number) => string;\n\n  /**\n   * Whether to remove the inputExamples property after adding them to the description.\n   * Default: true\n   */\n  remove?: boolean;\n} = {}): LanguageModelMiddleware {\n  return {\n    specificationVersion: 'v4',\n    transformParams: async ({ params }) => {\n      if (!params.tools?.length) {\n        return params;\n      }\n\n      const transformedTools = params.tools.map(tool => {\n        // Only transform function tools that have inputExamples\n        if (tool.type !== 'function' || !tool.inputExamples?.length) {\n          return tool;\n        }\n\n        const formattedExamples = tool.inputExamples\n          .map((example, index) => format(example, index))\n          .join('\\n');\n\n        const examplesSection = `${prefix}\\n${formattedExamples}`;\n\n        const toolDescription = tool.description\n          ? `${tool.description}\\n\\n${examplesSection}`\n          : examplesSection;\n\n        return {\n          ...tool,\n          description: toolDescription,\n          inputExamples: remove ? undefined : tool.inputExamples,\n        } satisfies LanguageModelV4FunctionTool;\n      });\n\n      return {\n        ...params,\n        tools: transformedTools,\n      };\n    },\n  };\n}\n","import type {\n  LanguageModelV2,\n  LanguageModelV3,\n  LanguageModelV4,\n  LanguageModelV4CallOptions,\n  LanguageModelV4GenerateResult,\n  LanguageModelV4StreamResult,\n} from '@ai-sdk/provider';\nimport { asArray } from '@ai-sdk/provider-utils';\nimport { asLanguageModelV4 } from '../model/as-language-model-v4';\nimport type { LanguageModelMiddleware } from '../types';\n\n/**\n * Wraps a LanguageModelV4 instance with middleware functionality.\n * This function allows you to apply middleware to transform parameters,\n * wrap generate operations, and wrap stream operations of a language model.\n *\n * @param options - Configuration options for wrapping the language model.\n * @param options.model - The original LanguageModelV4 instance to be wrapped.\n * @param options.middleware - The middleware to be applied to the language model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @param options.modelId - Optional custom model ID to override the original model's ID.\n * @param options.providerId - Optional custom provider ID to override the original model's provider ID.\n * @returns A new LanguageModelV4 instance with middleware applied.\n */\nexport const wrapLanguageModel = ({\n  model: inputModel,\n  middleware: middlewareArg,\n  modelId,\n  providerId,\n}: {\n  model: LanguageModelV2 | LanguageModelV3 | LanguageModelV4;\n  middleware: LanguageModelMiddleware | LanguageModelMiddleware[];\n  modelId?: string;\n  providerId?: string;\n}): LanguageModelV4 => {\n  const model = asLanguageModelV4(inputModel);\n  return [...asArray(middlewareArg)]\n    .reverse()\n    .reduce((wrappedModel, middleware) => {\n      return doWrap({ model: wrappedModel, middleware, modelId, providerId });\n    }, model);\n};\n\nconst doWrap = ({\n  model,\n  middleware: {\n    transformParams,\n    wrapGenerate,\n    wrapStream,\n    overrideProvider,\n    overrideModelId,\n    overrideSupportedUrls,\n  },\n  modelId,\n  providerId,\n}: {\n  model: LanguageModelV4;\n  middleware: LanguageModelMiddleware;\n  modelId?: string;\n  providerId?: string;\n}): LanguageModelV4 => {\n  async function doTransform({\n    params,\n    type,\n  }: {\n    params: LanguageModelV4CallOptions;\n    type: 'generate' | 'stream';\n  }) {\n    return transformParams\n      ? await transformParams({ params, type, model })\n      : params;\n  }\n\n  return {\n    specificationVersion: 'v4',\n\n    provider: providerId ?? overrideProvider?.({ model }) ?? model.provider,\n    modelId: modelId ?? overrideModelId?.({ model }) ?? model.modelId,\n    supportedUrls: overrideSupportedUrls?.({ model }) ?? model.supportedUrls,\n\n    async doGenerate(\n      params: LanguageModelV4CallOptions,\n    ): Promise<LanguageModelV4GenerateResult> {\n      const transformedParams = await doTransform({ params, type: 'generate' });\n      const doGenerate = async () => await model.doGenerate(transformedParams);\n      const doStream = async () => await model.doStream(transformedParams);\n      return wrapGenerate\n        ? await wrapGenerate({\n            doGenerate,\n            doStream,\n            params: transformedParams,\n            model,\n          })\n        : await doGenerate();\n    },\n\n    async doStream(\n      params: LanguageModelV4CallOptions,\n    ): Promise<LanguageModelV4StreamResult> {\n      const transformedParams = await doTransform({ params, type: 'stream' });\n      const doGenerate = async () => await model.doGenerate(transformedParams);\n      const doStream = async () => await model.doStream(transformedParams);\n      return wrapStream\n        ? await wrapStream({\n            doGenerate,\n            doStream,\n            params: transformedParams,\n            model,\n          })\n        : await doStream();\n    },\n  };\n};\n","import type {\n  EmbeddingModelV3,\n  EmbeddingModelV4,\n  EmbeddingModelV4CallOptions,\n  EmbeddingModelV4Result,\n} from '@ai-sdk/provider';\nimport {\n  asArray,\n  EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL,\n} from '@ai-sdk/provider-utils';\nimport { asEmbeddingModelV4 } from '../model/as-embedding-model-v4';\nimport {\n  getEmbeddingModelMaxInputBytesPerCall,\n  type EmbeddingModelWithMaxInputBytesPerCall,\n} from '../model/get-embedding-model-max-input-bytes-per-call';\nimport type { EmbeddingModelMiddleware } from '../types';\n\n/**\n * Wraps an EmbeddingModelV4 instance with middleware functionality.\n * This function allows you to apply middleware to transform parameters,\n * wrap embed operations of an embedding model.\n *\n * @param options - Configuration options for wrapping the embedding model.\n * @param options.model - The original EmbeddingModelV4 instance to be wrapped.\n * @param options.middleware - The middleware to be applied to the embedding model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @param options.modelId - Optional custom model ID to override the original model's ID.\n * @param options.providerId - Optional custom provider ID to override the original model's provider ID.\n * @returns A new EmbeddingModelV4 instance with middleware applied.\n */\nexport const wrapEmbeddingModel = ({\n  model: inputModel,\n  middleware: middlewareArg,\n  modelId,\n  providerId,\n}: {\n  model: EmbeddingModelV3 | EmbeddingModelV4;\n  middleware: EmbeddingModelMiddleware | EmbeddingModelMiddleware[];\n  modelId?: string;\n  providerId?: string;\n}): EmbeddingModelV4 => {\n  const model = asEmbeddingModelV4(inputModel);\n  return [...asArray(middlewareArg)]\n    .reverse()\n    .reduce((wrappedModel, middleware) => {\n      return doWrap({ model: wrappedModel, middleware, modelId, providerId });\n    }, model);\n};\n\nconst doWrap = ({\n  model,\n  middleware: {\n    transformParams,\n    wrapEmbed,\n    overrideProvider,\n    overrideModelId,\n    overrideMaxEmbeddingsPerCall,\n    overrideSupportsParallelCalls,\n  },\n  modelId,\n  providerId,\n}: {\n  model: EmbeddingModelV4;\n  middleware: EmbeddingModelMiddleware;\n  modelId?: string;\n  providerId?: string;\n}): EmbeddingModelWithMaxInputBytesPerCall => {\n  async function doTransform({\n    params,\n  }: {\n    params: EmbeddingModelV4CallOptions;\n  }) {\n    return transformParams ? await transformParams({ params, model }) : params;\n  }\n\n  return {\n    specificationVersion: 'v4',\n    provider: providerId ?? overrideProvider?.({ model }) ?? model.provider,\n    modelId: modelId ?? overrideModelId?.({ model }) ?? model.modelId,\n    maxEmbeddingsPerCall:\n      overrideMaxEmbeddingsPerCall?.({ model }) ?? model.maxEmbeddingsPerCall,\n    [EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL]:\n      getEmbeddingModelMaxInputBytesPerCall(model),\n    supportsParallelCalls:\n      overrideSupportsParallelCalls?.({ model }) ?? model.supportsParallelCalls,\n    async doEmbed(\n      params: EmbeddingModelV4CallOptions,\n    ): Promise<EmbeddingModelV4Result> {\n      const transformedParams = await doTransform({ params });\n      const doEmbed = async () => await model.doEmbed(transformedParams);\n      return wrapEmbed\n        ? await wrapEmbed({\n            doEmbed,\n            params: transformedParams,\n            model,\n          })\n        : await doEmbed();\n    },\n  };\n};\n","import type {\n  ImageModelV2,\n  ImageModelV3,\n  ImageModelV4,\n  ImageModelV4CallOptions,\n  ImageModelV4Result,\n} from '@ai-sdk/provider';\nimport { asArray } from '@ai-sdk/provider-utils';\nimport { asImageModelV4 } from '../model/as-image-model-v4';\nimport type { ImageModelMiddleware } from '../types';\n\n/**\n * Wraps an ImageModelV4 instance with middleware functionality.\n * This function allows you to apply middleware to transform parameters\n * and wrap generate operations of an image model.\n *\n * @param options - Configuration options for wrapping the image model.\n * @param options.model - The original ImageModelV4 instance to be wrapped.\n * @param options.middleware - The middleware to be applied to the image model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @param options.modelId - Optional custom model ID to override the original model's ID.\n * @param options.providerId - Optional custom provider ID to override the original model's provider ID.\n * @returns A new ImageModelV4 instance with middleware applied.\n */\nexport const wrapImageModel = ({\n  model: inputModel,\n  middleware: middlewareArg,\n  modelId,\n  providerId,\n}: {\n  model: ImageModelV2 | ImageModelV3 | ImageModelV4;\n  middleware: ImageModelMiddleware | ImageModelMiddleware[];\n  modelId?: string;\n  providerId?: string;\n}): ImageModelV4 => {\n  const model = asImageModelV4(inputModel);\n  return [...asArray(middlewareArg)]\n    .reverse()\n    .reduce((wrappedModel, middleware) => {\n      return doWrap({ model: wrappedModel, middleware, modelId, providerId });\n    }, model);\n};\n\nconst doWrap = ({\n  model,\n  middleware: {\n    transformParams,\n    wrapGenerate,\n    overrideProvider,\n    overrideModelId,\n    overrideMaxImagesPerCall,\n  },\n  modelId,\n  providerId,\n}: {\n  model: ImageModelV4;\n  middleware: ImageModelMiddleware;\n  modelId?: string;\n  providerId?: string;\n}): ImageModelV4 => {\n  async function doTransform({ params }: { params: ImageModelV4CallOptions }) {\n    return transformParams ? await transformParams({ params, model }) : params;\n  }\n\n  const maxImagesPerCallRaw =\n    overrideMaxImagesPerCall?.({ model }) ?? model.maxImagesPerCall;\n\n  // Ensure provider implementations that rely on `this` inside `maxImagesPerCall`\n  // keep working after the value is copied onto the wrapper object.\n  const maxImagesPerCall =\n    maxImagesPerCallRaw instanceof Function\n      ? maxImagesPerCallRaw.bind(model)\n      : maxImagesPerCallRaw;\n\n  return {\n    specificationVersion: 'v4',\n    provider: providerId ?? overrideProvider?.({ model }) ?? model.provider,\n    modelId: modelId ?? overrideModelId?.({ model }) ?? model.modelId,\n    maxImagesPerCall,\n    async doGenerate(\n      params: ImageModelV4CallOptions,\n    ): Promise<ImageModelV4Result> {\n      const transformedParams = await doTransform({ params });\n      const doGenerate = async () => await model.doGenerate(transformedParams);\n      return wrapGenerate\n        ? await wrapGenerate({\n            doGenerate,\n            params: transformedParams,\n            model,\n          })\n        : await doGenerate();\n    },\n  };\n};\n","import type { ProviderV2, ProviderV3, ProviderV4 } from '@ai-sdk/provider';\nimport type { ImageModelMiddleware } from '../types/image-model-middleware';\nimport type { LanguageModelMiddleware } from '../types/language-model-middleware';\nimport { wrapImageModel } from './wrap-image-model';\nimport { wrapLanguageModel } from './wrap-language-model';\nimport { asProviderV4 } from '../model/as-provider-v4';\n\n/**\n * Wraps a ProviderV4 instance with middleware functionality.\n * This function allows you to apply middleware to all language models\n * from the provider, enabling you to transform parameters, wrap generate\n * operations, and wrap stream operations for every language model.\n *\n * @param options - Configuration options for wrapping the provider.\n * @param options.provider - The original ProviderV4 instance to be wrapped.\n * @param options.languageModelMiddleware - The middleware to be applied to all language models from the provider. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @param options.imageModelMiddleware - Optional middleware to be applied to all image models from the provider. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @returns A new ProviderV4 instance with middleware applied to all language models.\n */\nexport function wrapProvider({\n  provider,\n  languageModelMiddleware,\n  imageModelMiddleware,\n}: {\n  provider: ProviderV4 | ProviderV3 | ProviderV2;\n  languageModelMiddleware: LanguageModelMiddleware | LanguageModelMiddleware[];\n  imageModelMiddleware?: ImageModelMiddleware | ImageModelMiddleware[];\n}): ProviderV4 {\n  const providerV4 = asProviderV4(provider);\n  return {\n    specificationVersion: 'v4',\n    languageModel: (modelId: string) =>\n      wrapLanguageModel({\n        model: providerV4.languageModel(modelId),\n        middleware: languageModelMiddleware,\n      }),\n    embeddingModel: providerV4.embeddingModel,\n    imageModel: (modelId: string) => {\n      let model = providerV4.imageModel(modelId);\n\n      if (imageModelMiddleware != null) {\n        model = wrapImageModel({ model, middleware: imageModelMiddleware });\n      }\n\n      return model;\n    },\n    transcriptionModel: providerV4.transcriptionModel,\n    speechModel: providerV4.speechModel,\n    rerankingModel: providerV4.rerankingModel,\n  };\n}\n","/**\n * Converts Float32 audio samples to a base64-encoded PCM16 string\n * for sending to a realtime model via input_audio_buffer.append.\n *\n * Samples are expected to be in the range [-1.0, 1.0].\n * Output is 16-bit signed integer, little-endian, base64-encoded.\n */\nexport function encodeRealtimeAudio(float32Array: Float32Array): string {\n  const buffer = new ArrayBuffer(float32Array.length * 2);\n  const view = new DataView(buffer);\n\n  for (let i = 0; i < float32Array.length; i++) {\n    const s = Math.max(-1, Math.min(1, float32Array[i]));\n    view.setInt16(i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true);\n  }\n\n  const bytes = new Uint8Array(buffer);\n  const chunkSize = 0x8000;\n  let binary = '';\n  for (let i = 0; i < bytes.length; i += chunkSize) {\n    const chunk = bytes.subarray(i, i + chunkSize);\n    binary += String.fromCharCode(...chunk);\n  }\n  return btoa(binary);\n}\n\n/**\n * Converts a base64-encoded PCM16 string (from a realtime model's\n * audio-delta event) back to Float32 audio samples.\n *\n * Input is expected to be 16-bit signed integer, little-endian, base64-encoded.\n * Output samples are in the range [-1.0, 1.0].\n */\nexport function decodeRealtimeAudio(base64Audio: string): Float32Array {\n  const binaryString = atob(base64Audio);\n  const bytes = new Uint8Array(binaryString.length);\n  for (let i = 0; i < binaryString.length; i++) {\n    bytes[i] = binaryString.charCodeAt(i);\n  }\n\n  const pcm16 = new Int16Array(bytes.buffer);\n  const float32 = new Float32Array(pcm16.length);\n  for (let i = 0; i < pcm16.length; i++) {\n    float32[i] = pcm16[i] / 32768.0;\n  }\n  return float32;\n}\n\n/**\n * Resamples audio from one sample rate to another using linear\n * interpolation. Suitable for voice audio.\n *\n * @param input - Float32 audio samples at the input sample rate.\n * @param inputRate - The sample rate of the input audio (e.g. 48000).\n * @param outputRate - The desired output sample rate (e.g. 24000).\n * @returns Float32 audio samples at the output sample rate.\n */\nexport function resampleAudio(\n  input: Float32Array,\n  inputRate: number,\n  outputRate: number,\n): Float32Array {\n  if (inputRate === outputRate) {\n    return input;\n  }\n\n  const ratio = inputRate / outputRate;\n  const outputLength = Math.round(input.length / ratio);\n  const output = new Float32Array(outputLength);\n\n  for (let i = 0; i < outputLength; i++) {\n    const srcIndex = i * ratio;\n    const srcIndexFloor = Math.floor(srcIndex);\n    const srcIndexCeil = Math.min(srcIndexFloor + 1, input.length - 1);\n    const fraction = srcIndex - srcIndexFloor;\n\n    output[i] =\n      input[srcIndexFloor] * (1 - fraction) + input[srcIndexCeil] * fraction;\n  }\n\n  return output;\n}\n","import {\n  asSchema,\n  type InferToolSetContext,\n  type Tool,\n  type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type { RealtimeToolDefinition } from '../types/realtime-model';\n\nexport async function getRealtimeToolDefinitions<TOOLS extends ToolSet>({\n  tools,\n  toolsContext = {} as InferToolSetContext<TOOLS>,\n}: {\n  tools: TOOLS;\n  toolsContext?: InferToolSetContext<TOOLS>;\n}): Promise<RealtimeToolDefinition[]> {\n  const definitions: RealtimeToolDefinition[] = [];\n\n  for (const [name, tool] of Object.entries(tools)) {\n    const toolType = tool.type;\n\n    switch (toolType) {\n      case undefined:\n      case 'function':\n      case 'dynamic': {\n        const description = resolveRealtimeToolDescription({\n          tool,\n          toolName: name,\n          toolsContext,\n        });\n        definitions.push({\n          type: 'function',\n          name,\n          description,\n          parameters: await asSchema(tool.inputSchema).jsonSchema,\n        });\n        break;\n      }\n      case 'provider':\n        break;\n      default: {\n        const exhaustiveCheck: never = toolType as never;\n        throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);\n      }\n    }\n  }\n\n  return definitions;\n}\n\nfunction resolveRealtimeToolDescription<TOOLS extends ToolSet>({\n  tool,\n  toolName,\n  toolsContext,\n}: {\n  tool: Tool;\n  toolName: string;\n  toolsContext: InferToolSetContext<TOOLS>;\n}): string | undefined {\n  return tool.description === undefined\n    ? undefined\n    : typeof tool.description === 'string'\n      ? tool.description\n      : tool.description({\n          context: toolsContext[toolName as keyof InferToolSetContext<TOOLS>],\n        });\n}\n","import { UnsupportedFunctionalityError } from '@ai-sdk/provider';\nimport type {\n  RealtimeClientEvent,\n  RealtimeModel,\n  RealtimeServerEvent,\n  RealtimeSessionConfig,\n} from '../types/realtime-model';\nimport { BrowserRealtimeAudio } from './browser-realtime-audio';\nimport { BrowserRealtimeTransport } from './browser-realtime-transport';\nimport { BrowserRealtimeLiveWebSocket } from './browser-realtime-live-websocket';\nimport { BrowserRealtimeWebRTC } from './browser-realtime-webrtc';\nimport { RealtimeAttempt } from './realtime-attempt';\nimport { RealtimeCommandTracker } from './realtime-command-tracker';\nimport { validateRealtimeSetup } from './validate-realtime-setup';\nimport {\n  createSessionState,\n  reduceSessionState,\n} from './realtime-session-state';\nimport {\n  createInitialRealtimeState,\n  RealtimeEventReducer,\n  type RealtimeReducerEffect,\n  type RealtimeState,\n} from './realtime-event-reducer';\n\nexport type { RealtimeSessionState } from './realtime-session-state';\nexport type { RealtimeState, RealtimeStatus } from './realtime-event-reducer';\n\nexport type RealtimeSessionOptions = {\n  model: RealtimeModel;\n  /** websocket uses a raw-protocol relay; session exchanges SDP; token fetches client-secret setup. */\n  api:\n    | { token: string; session?: never; websocket?: never; protocols?: never }\n    | { session: string; token?: never; websocket?: never; protocols?: never }\n    | {\n        websocket: string;\n        protocols?: string[];\n        token?: never;\n        session?: never;\n      };\n  sessionConfig?: Partial<RealtimeSessionConfig>;\n  sampleRate?: number;\n  maxEvents?: number;\n  /** Maximum time to establish transport and receive readiness. Default: 30s. */\n  startupTimeoutMs?: number;\n  /** Maximum wait for final usage after close(). Default: 15s. */\n  closeTimeoutMs?: number;\n  /** WebRTC peer disconnect recovery grace period. Default: 5s. */\n  rtcDisconnectTimeoutMs?: number;\n  /** Continuous PCM only: pause at this budget until resumePlayback(). Default: 2s. */\n  maxPlaybackBufferSeconds?: number;\n  onToolCall?: (args: {\n    toolCall: { toolCallId: string; toolName: string; args: unknown };\n  }) => Promise<unknown> | unknown | undefined;\n  onEvent?: (event: RealtimeServerEvent) => void;\n  onError?: (error: Error) => void;\n};\n\nexport abstract class AbstractRealtimeSession {\n  protected state: RealtimeState = createInitialRealtimeState();\n  protected maxEvents: number;\n  onToolCall: RealtimeSessionOptions['onToolCall'];\n  onEvent: RealtimeSessionOptions['onEvent'];\n  onError: RealtimeSessionOptions['onError'];\n  private reducer: RealtimeEventReducer;\n  private readonly sessionLifecycle: boolean;\n  private readonly continuous: boolean;\n  private attempt?: RealtimeAttempt;\n  private commands?: RealtimeCommandTracker;\n  private publication = 0;\n  private transport?: BrowserRealtimeTransport;\n  private audio?: BrowserRealtimeAudio;\n  private pcm?: BrowserRealtimeLiveWebSocket;\n  private rtc?: BrowserRealtimeWebRTC;\n  private suppliedStream?: MediaStream;\n  private captureGeneration = 0;\n  private captureRequested = false;\n  private currentResponseItemId: string | null = null;\n  private readonly toolCallsInResponse = new Set<string>();\n  private readonly submittedToolOutputs = new Set<string>();\n  private responseToolCallsClosed = false;\n\n  protected abstract setState<K extends keyof RealtimeState>(\n    key: K,\n    value: RealtimeState[K],\n  ): void;\n\n  constructor(private readonly options: RealtimeSessionOptions) {\n    const capabilities = options.model.capabilities;\n    this.sessionLifecycle =\n      capabilities?.startup === 'session-start' ||\n      capabilities?.finalization === 'session-close';\n    this.continuous = capabilities?.conversation === 'continuous';\n    this.maxEvents = options.maxEvents ?? 500;\n    if (!Number.isSafeInteger(this.maxEvents) || this.maxEvents < 1)\n      throw new Error('maxEvents must be a positive integer');\n    for (const timeout of [\n      options.startupTimeoutMs ?? 30_000,\n      options.closeTimeoutMs ?? 15_000,\n      options.rtcDisconnectTimeoutMs ?? 5_000,\n    ]) {\n      if (!Number.isFinite(timeout) || timeout <= 0 || timeout > 2_147_483_647)\n        throw new Error(\n          'Realtime timeouts must be positive finite timer durations',\n        );\n    }\n    const budget = options.maxPlaybackBufferSeconds ?? 2;\n    if (!Number.isFinite(budget) || budget <= 0)\n      throw new Error('maxPlaybackBufferSeconds must be positive and finite');\n    this.reducer = new RealtimeEventReducer(this.maxEvents);\n    this.onToolCall = options.onToolCall;\n    this.onEvent = options.onEvent;\n    this.onError = options.onError;\n  }\n\n  private validateConnection(): void {\n    const { model, api } = this.options;\n    if (\n      (!this.continuous || api.session != null) &&\n      this.options.maxPlaybackBufferSeconds != null\n    )\n      throw new Error(\n        'maxPlaybackBufferSeconds is supported only for continuous PCM sessions',\n      );\n    const connection =\n      api.session != null\n        ? 'webrtc'\n        : api.token != null\n          ? 'client-secret-websocket'\n          : 'server-websocket';\n    if (\n      !(\n        model.capabilities?.connections ?? ['client-secret-websocket']\n      ).includes(connection) ||\n      (model.capabilities?.transports != null &&\n        !model.capabilities.transports.includes(\n          api.session != null ? 'webrtc' : 'websocket',\n        ))\n    )\n      throw new Error(`Realtime model does not support ${connection}`);\n    if (api.session != null) {\n      if (model.getWebRTCConfig == null)\n        throw new Error('Realtime model does not support WebRTC configuration');\n      return;\n    }\n    if (this.continuous && api.websocket == null)\n      throw new Error(\n        'Continuous PCM sessions require an application WebSocket relay',\n      );\n    if (api.token != null && model.getWebSocketConfig == null)\n      throw new Error(\n        'Realtime model does not support client-secret WebSocket configuration',\n      );\n  }\n\n  connect(): Promise<void>;\n  connect(options: { stream?: MediaStream; capture?: boolean }): Promise<void>;\n  async connect(connectOptions?: {\n    stream?: MediaStream;\n    capture?: boolean;\n  }): Promise<void> {\n    if (this.attempt?.active)\n      throw new Error('Realtime session is already active');\n    const attempt = new RealtimeAttempt();\n    this.attempt = attempt;\n    const current = () => this.attempt === attempt && attempt.active;\n    try {\n      this.applyState({ ...this.state, status: 'connecting' });\n      if (!current()) return;\n      this.validateConnection();\n      const { model, api, sessionConfig } = this.options;\n      if (connectOptions?.capture === false) this.stopAudioCapture();\n      if (!current()) return;\n      if (\n        connectOptions?.stream != null &&\n        connectOptions.stream !== this.suppliedStream\n      ) {\n        if (\n          this.captureRequested &&\n          !this.sessionLifecycle &&\n          !this.continuous &&\n          api.session == null\n        )\n          this.startAudioCapture(connectOptions.stream);\n        else this.suppliedStream = connectOptions.stream;\n      }\n      if (!current()) return;\n      this.reducer = new RealtimeEventReducer(this.maxEvents);\n      this.currentResponseItemId = null;\n      this.toolCallsInResponse.clear();\n      this.submittedToolOutputs.clear();\n      this.responseToolCallsClosed = false;\n      if (this.sessionLifecycle)\n        this.applyState({ ...this.state, session: createSessionState() });\n      if (!current()) return;\n      this.commands = new RealtimeCommandTracker(event => {\n        const writable = () =>\n          current() &&\n          !attempt.transportClosing &&\n          attempt.cause == null &&\n          (!attempt.closing || event.type === 'session-close');\n        if (!writable()) throw new Error('Realtime connection is closed');\n        return this.sendTransport(event, writable);\n      });\n      attempt.timer('startup', this.options.startupTimeoutMs ?? 30_000, () => {\n        if (current())\n          this.fail(new Error('Realtime session startup timed out'));\n      });\n      const reportedTransportErrors = new WeakSet<Error>();\n      const callbacks = {\n        model,\n        onEvent: async (event: RealtimeServerEvent) => {\n          if (!current()) return;\n          try {\n            await this.handleServerEvent(event, attempt);\n          } catch (error) {\n            if (current())\n              this.fail(\n                error,\n                (this.rtc ?? this.pcm ?? this.transport)?.finish(),\n              );\n          }\n        },\n        onError: (error: Error) => {\n          if (current()) {\n            reportedTransportErrors.add(error);\n            void this.reportError(error, attempt);\n          }\n        },\n        onFatalError: (error: Error, drain?: Promise<void>) => {\n          if (current()) this.fail(error, drain);\n        },\n        onClosing: () => {\n          if (!current()) return;\n          attempt.beginClose();\n          attempt.transportClosing = true;\n          attempt.clearTimer('startup');\n          attempt.clearTimer('close');\n          this.stopAudioCapture();\n          if (!current()) return;\n          this.applyState({\n            ...this.state,\n            status: attempt.cause == null ? 'closing' : 'error',\n          });\n        },\n        onClose: (error?: Error) => {\n          if (!current()) return;\n          const finalizationConfirmed =\n            model.capabilities?.finalization === 'session-close' &&\n            this.state.session?.finalization === 'confirmed';\n          if (error != null && !finalizationConfirmed)\n            this.fail(error, undefined, !reportedTransportErrors.has(error));\n          else if (!attempt.ready && !finalizationConfirmed)\n            this.fail(\n              new Error('Realtime connection closed before becoming ready'),\n            );\n          else this.disconnect();\n        },\n        onCapturing: (isCapturing: boolean) => {\n          if (current()) this.applyState({ ...this.state, isCapturing });\n        },\n        onPlaying: (isPlaying: boolean) => {\n          if (current()) this.applyState({ ...this.state, isPlaying });\n        },\n      };\n      if (api.session != null) {\n        this.rtc = new BrowserRealtimeWebRTC({\n          ...callbacks,\n          disconnectTimeoutMs: this.options.rtcDisconnectTimeoutMs,\n        });\n        await this.rtc.connect({\n          api: api.session,\n          sessionConfig,\n          stream: connectOptions?.stream,\n          capture: connectOptions?.capture,\n          timeoutMs: this.options.startupTimeoutMs ?? 30_000,\n        });\n      } else if (\n        api.websocket != null &&\n        model.capabilities?.conversation === 'continuous'\n      ) {\n        this.pcm = new BrowserRealtimeLiveWebSocket({\n          ...callbacks,\n          sessionConfig,\n          sampleRate: this.options.sampleRate,\n          maxPlaybackBufferSeconds: this.options.maxPlaybackBufferSeconds,\n        });\n        this.pcm.connect({\n          url: api.websocket,\n          protocols: api.protocols,\n          stream: connectOptions?.stream,\n          capture: connectOptions?.capture,\n        });\n      } else {\n        this.ensureAudio();\n        let config: RealtimeSessionConfig = sessionConfig ?? {};\n        let token: string | undefined;\n        let url = api.websocket;\n        if (api.token != null) {\n          const response = await fetch(api.token, {\n            method: 'POST',\n            headers: { 'Content-Type': 'application/json' },\n            body: JSON.stringify({ sessionConfig }),\n            signal: attempt.abort.signal,\n          });\n          if (!current()) return;\n          if (!response.ok)\n            throw new Error(\n              `Failed to fetch realtime setup: ${response.status}`,\n            );\n          const payload: unknown = await response.json().catch(() => {\n            throw new Error('Invalid realtime setup response');\n          });\n          if (!current() || attempt.closing) return;\n          const setup = validateRealtimeSetup(payload);\n          token = setup.token;\n          url = setup.url;\n          config = {\n            ...sessionConfig,\n            ...(setup.tools == null ? {} : { tools: setup.tools }),\n          };\n        }\n        if (url == null) throw new Error('Realtime WebSocket URL is missing');\n        if (api.token != null && token == null)\n          throw new Error('Realtime client-secret connection requires a token');\n        this.ensureAudio().ensurePlaybackContext();\n        if (!current()) return;\n        this.transport = new BrowserRealtimeTransport({\n          ...callbacks,\n          onServerEvent: callbacks.onEvent,\n        });\n        this.transport.connect({\n          ...(token != null\n            ? { mode: 'client-secret' as const, token }\n            : { mode: 'relay' as const, protocols: api.protocols }),\n          url,\n          onOpen: () => {\n            const writable = () =>\n              current() && !attempt.closing && attempt.cause == null;\n            if (!writable()) return;\n            return this.sendTransport(\n              {\n                type: model.capabilities?.startup ?? 'session-update',\n                config,\n              },\n              writable,\n            );\n          },\n        });\n      }\n    } catch (error) {\n      if (current()) this.fail(error);\n    }\n  }\n\n  private fail(error: unknown, drain?: Promise<void>, report = true): void {\n    const attempt = this.attempt;\n    if (attempt == null || !attempt.active || attempt.cause != null) return;\n    attempt.cause = error instanceof Error ? error : new Error(String(error));\n    if (drain != null) attempt.beginClose();\n    this.applyState({ ...this.state, status: 'error' });\n    if (this.attempt !== attempt || !attempt.active) return;\n    this.stopAudioCapture();\n    if (this.attempt !== attempt || !attempt.active) return;\n    if (drain == null) this.disconnect();\n    else void this.drainAttempt(attempt, drain);\n    if (report) void this.reportError(attempt.cause, attempt);\n  }\n\n  private async drainAttempt(\n    attempt: RealtimeAttempt,\n    drain?: Promise<void>,\n  ): Promise<void> {\n    if (this.attempt === attempt && attempt.active)\n      attempt.timer('drain', 1_000, () => this.finishAttempt(attempt));\n    try {\n      await drain;\n    } catch {\n      /* Finalize unconfirmed when draining fails. */\n    }\n    this.finishAttempt(attempt);\n  }\n\n  private finishAttempt(attempt: RealtimeAttempt): void {\n    if (this.attempt !== attempt || !attempt.active) return;\n    try {\n      this.disconnect();\n    } catch (error) {\n      void this.reportError(error, attempt);\n    }\n  }\n\n  private closeFailed(attempt: RealtimeAttempt, error: unknown): void {\n    if (this.attempt !== attempt || !attempt.active || attempt.transportClosing)\n      return;\n    attempt.clearTimer('close');\n    const transport = this.rtc ?? this.pcm ?? this.transport;\n    void this.drainAttempt(attempt, transport?.finish());\n    void this.reportError(error, attempt);\n  }\n\n  disconnect(): void {\n    const attempt = this.attempt;\n    this.captureGeneration++;\n    this.captureRequested = false;\n    this.suppliedStream = undefined;\n    const transport = this.transport;\n    const audio = this.audio;\n    const pcm = this.pcm;\n    const rtc = this.rtc;\n    this.transport = undefined;\n    this.audio = undefined;\n    this.pcm = undefined;\n    this.rtc = undefined;\n    this.commands = undefined;\n    attempt?.retire();\n    transport?.dispose();\n    audio?.dispose();\n    pcm?.dispose();\n    rtc?.dispose();\n    if (this.attempt !== attempt) return;\n    const session = this.state.session;\n    this.applyState({\n      ...this.state,\n      status: attempt?.cause != null ? 'error' : 'disconnected',\n      isCapturing: false,\n      isPlaying: false,\n      ...(session != null\n        ? {\n            session:\n              session.finalization === 'confirmed'\n                ? session\n                : { ...session, finalization: 'unconfirmed' },\n          }\n        : {}),\n    });\n  }\n\n  /** Wait for final usage when the model supports a session-close acknowledgement. */\n  close(options?: { eventId?: string }): Promise<void> {\n    const attempt = this.attempt;\n    if (attempt?.closePromise != null) return attempt.closePromise;\n    if (\n      this.state.status !== 'connected' ||\n      this.options.model.capabilities?.finalization !== 'session-close' ||\n      attempt == null\n    ) {\n      this.disconnect();\n      return Promise.resolve();\n    }\n    if (options?.eventId != null) this.commands?.validateId(options.eventId);\n    const promise = attempt.beginClose();\n    this.applyState({ ...this.state, status: 'closing' });\n    if (this.attempt !== attempt || !attempt.active || attempt.transportClosing)\n      return promise;\n    this.stopAudioCapture();\n    if (this.attempt !== attempt || !attempt.active || attempt.transportClosing)\n      return promise;\n    attempt.timer('close', this.options.closeTimeoutMs ?? 15_000, () =>\n      this.finishAttempt(attempt),\n    );\n    const failed = (error: unknown) => this.closeFailed(attempt, error);\n    try {\n      void this.commands\n        ?.send({ type: 'session-close', eventId: options?.eventId })\n        .catch(failed);\n    } catch (error) {\n      failed(error);\n    }\n    return promise;\n  }\n\n  private sendTransport(\n    event: RealtimeClientEvent,\n    guard?: () => boolean,\n    automaticAudio = false,\n  ): Promise<void> {\n    const transport = this.rtc ?? this.pcm ?? this.transport;\n    if (transport == null) throw new Error('Realtime connection is not open');\n    if (transport === this.transport)\n      return this.transport.sendEvent(event, guard, automaticAudio);\n    return transport.sendEvent(event, guard);\n  }\n\n  sendEvent(event: RealtimeClientEvent): Promise<void> {\n    if (\n      this.state.status === 'error' ||\n      this.state.status === 'closing' ||\n      this.attempt?.closing ||\n      !this.attempt?.active\n    )\n      throw new Error('Realtime session is not accepting submissions');\n    if (this.sessionLifecycle && this.state.status !== 'connected')\n      throw new Error('Realtime session is not accepting submissions');\n    if (\n      (this.rtc != null && event.type === 'input-audio-append') ||\n      ((this.continuous || this.rtc != null) &&\n        (event.type === 'input-audio-commit' ||\n          event.type === 'input-audio-clear'))\n    )\n      throw new UnsupportedFunctionalityError({\n        functionality:\n          'JSON audio commands unsupported for this session transport',\n      });\n    if (event.type === 'session-close')\n      return this.close({ eventId: event.eventId });\n    if (event.type === 'session-start' && this.sessionLifecycle)\n      throw new Error('Realtime session has already started');\n    if (!this.sessionLifecycle && this.state.session == null) {\n      const attempt = this.attempt;\n      return this.sendTransport(\n        event,\n        () =>\n          this.attempt === attempt &&\n          attempt.active &&\n          !attempt.closing &&\n          attempt.cause == null,\n      );\n    }\n    return this.commands?.send(event) ?? this.sendTransport(event);\n  }\n\n  sendTextMessage(text: string): void {\n    if (this.continuous)\n      throw new UnsupportedFunctionalityError({\n        functionality:\n          'sendTextMessage for continuous sessions; client-delegation text is application-owned, use context-append for context',\n      });\n    this.sendEvent({\n      type: 'conversation-item-create',\n      item: { type: 'text-message', role: 'user', text },\n    });\n    this.sendEvent({ type: 'response-create' });\n    this.applyState(this.reducer.addUserTextMessage(this.state, text));\n  }\n\n  sendAudio(audio: string): void {\n    const attempt = this.attempt;\n    void this.sendEvent({ type: 'input-audio-append', audio }).catch(error => {\n      if (attempt?.active && this.attempt === attempt)\n        void this.reportError(error, attempt);\n    });\n  }\n  commitAudio(): void {\n    this.sendEvent({ type: 'input-audio-commit' });\n  }\n  clearAudioBuffer(): void {\n    this.sendEvent({ type: 'input-audio-clear' });\n  }\n  requestResponse(options?: { modalities?: string[] }): void {\n    this.sendEvent({\n      type: 'response-create',\n      ...(options != null ? { options } : {}),\n    });\n  }\n  cancelResponse(): void {\n    this.sendEvent({ type: 'response-cancel' });\n  }\n\n  private sendAutomaticAudio(audio: string): void {\n    if (\n      this.state.status !== 'connected' ||\n      !this.attempt?.active ||\n      this.attempt.closing\n    )\n      return;\n    const attempt = this.attempt;\n    const failed = (error: unknown) => {\n      if (attempt?.active && this.attempt === attempt && !attempt.closing)\n        this.fail(error);\n    };\n    try {\n      void this.sendTransport(\n        { type: 'input-audio-append', audio },\n        () => this.attempt === attempt && attempt.active && !attempt.closing,\n        true,\n      ).catch(failed);\n    } catch (error) {\n      failed(error);\n    }\n  }\n\n  addToolOutput(callId: string, result: unknown): void {\n    if (this.continuous)\n      throw new UnsupportedFunctionalityError({\n        functionality:\n          'addToolOutput for continuous sessions; client delegation is application-owned',\n      });\n    const attempt = this.attempt;\n    if (!attempt?.active || attempt.closing || attempt.cause != null)\n      throw new Error('Realtime session is not accepting submissions');\n    const { state, output } = this.reducer.addToolOutput(\n      this.state,\n      callId,\n      result,\n    );\n    this.applyState(state);\n    if (this.attempt !== attempt || !attempt?.active) return;\n    this.sendEvent({\n      type: 'conversation-item-create',\n      item: { type: 'function-call-output', ...output },\n    });\n    this.submittedToolOutputs.add(callId);\n    this.maybeRequestToolResponse();\n  }\n\n  private maybeRequestToolResponse(): void {\n    if (\n      this.state.status !== 'connected' ||\n      this.attempt?.closing ||\n      !this.responseToolCallsClosed ||\n      this.toolCallsInResponse.size === 0 ||\n      [...this.toolCallsInResponse].some(\n        id => !this.submittedToolOutputs.has(id),\n      )\n    )\n      return;\n    this.sendEvent({ type: 'response-create' });\n    this.toolCallsInResponse.clear();\n    this.submittedToolOutputs.clear();\n    this.responseToolCallsClosed = false;\n  }\n\n  startAudioCapture(stream: MediaStream): void {\n    const legacy =\n      !this.sessionLifecycle &&\n      !this.continuous &&\n      this.options.api.session == null;\n    if (!legacy && this.state.status !== 'connected')\n      throw new Error('Realtime session is not accepting capture');\n    if (\n      this.attempt?.active &&\n      (this.attempt.closing || this.attempt.cause != null)\n    )\n      throw new Error('Realtime session is not accepting capture');\n    this.suppliedStream = stream;\n    if (legacy) {\n      this.captureGeneration++;\n      this.captureRequested = true;\n      this.ensureAudio().startCapture(stream);\n      return;\n    }\n    const attempt = this.attempt;\n    void this.resumeAudioCapture().catch(error => {\n      if (attempt?.active) void this.reportError(error, attempt);\n    });\n  }\n\n  async resumeAudioCapture(): Promise<void> {\n    const accepting = () =>\n      !this.attempt?.closing &&\n      this.attempt?.cause == null &&\n      (this.state.status === 'connected' ||\n        (!this.sessionLifecycle && this.state.status === 'connecting'));\n    if (!accepting())\n      throw new Error('Realtime session is not accepting capture');\n    this.captureRequested = true;\n    if (this.rtc != null) return this.rtc.startCapture(this.suppliedStream);\n    if (this.pcm != null) return this.pcm.resumeCapture(this.suppliedStream);\n    const audio = this.audio;\n    if (audio == null)\n      throw new Error('Realtime capture transport is not ready');\n    const captureGeneration = ++this.captureGeneration;\n    const attempt = this.attempt;\n    const supplied = this.suppliedStream;\n    const stream =\n      supplied ?? (await navigator.mediaDevices.getUserMedia({ audio: true }));\n    if (\n      !attempt?.active ||\n      this.attempt !== attempt ||\n      this.audio !== audio ||\n      !accepting() ||\n      captureGeneration !== this.captureGeneration\n    ) {\n      if (supplied == null) stream.getTracks().forEach(track => track.stop());\n      return;\n    }\n    audio.startCapture(stream, {\n      ownsStream:\n        supplied == null ||\n        !this.sessionLifecycle ||\n        this.options.api.token != null,\n    });\n  }\n\n  stopAudioCapture(): void {\n    this.captureGeneration++;\n    this.captureRequested = false;\n    if (\n      this.audio != null &&\n      (!this.sessionLifecycle || this.options.api.token != null)\n    )\n      this.suppliedStream = undefined;\n    const pcm = this.pcm;\n    const audio = this.audio;\n    const rtc = this.rtc;\n    const attempt = this.attempt;\n    if (rtc != null)\n      void rtc.stopCapture().catch(error => {\n        if (attempt?.active && this.attempt === attempt)\n          void this.reportError(error, attempt);\n      });\n    pcm?.stopCapture();\n    audio?.stopCapture();\n  }\n  stopPlayback(): void {\n    (this.rtc ?? this.pcm ?? this.audio)?.stopPlayback();\n  }\n  async resumePlayback(): Promise<void> {\n    await (this.rtc ?? this.pcm ?? this.audio)?.resumePlayback();\n  }\n  dispose(): void {\n    this.disconnect();\n  }\n\n  private ensureAudio(): BrowserRealtimeAudio {\n    if (this.audio != null) return this.audio;\n    const { sessionConfig, sampleRate } = this.options;\n    const audio = new BrowserRealtimeAudio({\n      captureSampleRate:\n        sessionConfig?.inputAudioFormat?.rate ?? sampleRate ?? 24000,\n      playbackSampleRate:\n        sessionConfig?.outputAudioFormat?.rate ?? sampleRate ?? 24000,\n      onAudio: value => {\n        if (this.audio === audio) this.sendAutomaticAudio(value);\n      },\n      onError: error => {\n        if (this.audio !== audio) return;\n        void this.reportError(error, this.attempt);\n      },\n      onCapturingChange: isCapturing => {\n        if (this.audio === audio)\n          this.applyState({ ...this.state, isCapturing });\n      },\n      onPlayingChange: isPlaying => {\n        if (this.audio === audio) this.applyState({ ...this.state, isPlaying });\n      },\n    });\n    this.audio = audio;\n    return audio;\n  }\n\n  private applyState(nextState: RealtimeState): void {\n    const publication = ++this.publication;\n    const previous = this.state;\n    this.state = nextState;\n    const update = <K extends keyof RealtimeState>(key: K) => {\n      if (publication === this.publication && previous[key] !== nextState[key])\n        this.setState(key, nextState[key]);\n    };\n    update('status');\n    update('messages');\n    update('events');\n    update('isCapturing');\n    update('isPlaying');\n    update('session');\n  }\n\n  private async executeTool(\n    callId: string,\n    name: string,\n    args: unknown,\n    attempt: RealtimeAttempt,\n  ): Promise<void> {\n    if (\n      this.continuous ||\n      this.attempt !== attempt ||\n      !attempt.active ||\n      attempt.closing ||\n      attempt.cause != null\n    )\n      return;\n    try {\n      if (this.onToolCall == null) {\n        void this.reportError(\n          new Error(`No handler provided for tool \"${name}\"`),\n          attempt,\n        );\n        return;\n      }\n      const result = await this.onToolCall({\n        toolCall: { toolCallId: callId, toolName: name, args },\n      });\n      if (\n        result !== undefined &&\n        this.attempt === attempt &&\n        attempt?.active &&\n        this.state.status === 'connected'\n      )\n        this.addToolOutput(callId, result);\n    } catch (error) {\n      if (attempt.active) void this.reportError(error, attempt);\n    }\n  }\n\n  private async handleServerEvent(\n    event: RealtimeServerEvent,\n    attempt: RealtimeAttempt,\n  ): Promise<void> {\n    const current = () => this.attempt === attempt && attempt.active;\n    if (!current()) return;\n    if (event.type === 'session-started' && event.delegationMode === 'provider')\n      throw new UnsupportedFunctionalityError({\n        functionality:\n          'Provider delegation mode; this realtime runtime supports client delegation only',\n      });\n    if (this.continuous && event.type === 'audio-delta')\n      throw new UnsupportedFunctionalityError({\n        functionality:\n          'Turn-based audio-delta in a continuous PCM session; use audio-chunk',\n      });\n    const command = this.commands?.receive(event);\n    const result = await this.reducer.reduceServerEvent(this.state, event);\n    if (!current()) return;\n    const session =\n      this.state.session ??\n      (event.type === 'session-started' ? createSessionState() : undefined);\n    this.applyState({\n      ...result.state,\n      status: this.state.status,\n      ...(session == null\n        ? {}\n        : {\n            session: reduceSessionState(\n              session,\n              event,\n              this.maxEvents,\n              command?.muted,\n            ),\n          }),\n    });\n    if (!current()) return;\n    for (const effect of result.effects) {\n      this.handleReducerEffect(effect, attempt);\n      if (!current()) return;\n    }\n    if (event.type === 'audio-chunk')\n      (this.pcm ?? this.audio)?.playAudio(event.delta);\n    if (!current()) return;\n    if (event.type === 'response-done' && this.toolCallsInResponse.size > 0) {\n      this.responseToolCallsClosed = true;\n      this.maybeRequestToolResponse();\n    }\n    if (!current()) return;\n    if (event.type === 'session-closed' && session != null) {\n      this.disconnect();\n      this.notifyEvent(event, attempt, true);\n      return;\n    }\n    if (\n      (event.type === 'session-started' ||\n        event.type === 'session-created' ||\n        event.type === 'session-updated') &&\n      attempt.active &&\n      !attempt.closing &&\n      attempt.cause == null\n    ) {\n      const ready =\n        this.options.model.capabilities?.startup === 'session-start'\n          ? event.type === 'session-started'\n          : event.type !== 'session-started';\n      if (ready) {\n        attempt.ready = true;\n        attempt.clearTimer('startup');\n        this.applyState({ ...this.state, status: 'connected' });\n        if (!current() || attempt.closing) return;\n        this.pcm?.startCapture();\n      }\n    }\n    if (current()) this.notifyEvent(event, attempt);\n  }\n\n  private handleReducerEffect(\n    effect: RealtimeReducerEffect,\n    attempt: RealtimeAttempt,\n  ): void {\n    switch (effect.type) {\n      case 'play-audio':\n        this.currentResponseItemId = effect.itemId;\n        this.audio?.playAudio(effect.delta);\n        break;\n      case 'speech-started':\n        if (!this.continuous && this.state.isPlaying) {\n          const playedMs = this.audio?.getPlaybackOffsetMs() ?? 0;\n          const itemId = this.currentResponseItemId;\n          this.audio?.stopPlayback();\n          if (this.attempt !== attempt || !attempt.active) return;\n          if (itemId != null && !attempt.closing && attempt.cause == null)\n            this.sendEvent({\n              type: 'conversation-item-truncate',\n              itemId,\n              contentIndex: 0,\n              audioEndMs: Math.round(playedMs),\n            });\n        }\n        break;\n      case 'tool-call':\n        if (this.continuous) break;\n        this.toolCallsInResponse.add(effect.callId);\n        void this.executeTool(effect.callId, effect.name, effect.args, attempt);\n        break;\n      case 'error':\n        void this.reportError(effect.error, attempt);\n        break;\n    }\n  }\n\n  private async reportError(\n    error: unknown,\n    attempt?: RealtimeAttempt,\n  ): Promise<void> {\n    if (this.attempt !== attempt) return;\n    try {\n      await this.onError?.(\n        error instanceof Error ? error : new Error(String(error)),\n      );\n    } catch {\n      /* Application callbacks cannot interrupt cleanup. */\n    }\n  }\n\n  private notifyEvent(\n    event: RealtimeServerEvent,\n    attempt: RealtimeAttempt,\n    terminal = false,\n  ): void {\n    if (this.attempt !== attempt || (!attempt.active && !terminal)) return;\n    const report = (error: unknown) => {\n      if (attempt.active || terminal) void this.reportError(error, attempt);\n    };\n    try {\n      void Promise.resolve(this.onEvent?.(event)).catch(report);\n    } catch (error) {\n      report(error);\n    }\n  }\n}\n","import {\n  decodeRealtimeAudio,\n  encodeRealtimeAudio,\n  resampleAudio,\n} from './audio-utils';\n\nexport type BrowserRealtimeAudioOptions = {\n  captureSampleRate: number;\n  playbackSampleRate: number;\n  onAudio: (base64Audio: string) => void;\n  onPlayingChange: (isPlaying: boolean) => void;\n  onCapturingChange: (isCapturing: boolean) => void;\n  maxPlaybackSeconds?: number;\n  onError?: (error: Error) => void;\n};\n\nexport class BrowserRealtimeAudio {\n  private readonly captureSampleRate: number;\n  private readonly playbackSampleRate: number;\n  private readonly onAudio: BrowserRealtimeAudioOptions['onAudio'];\n  private readonly onPlayingChange: BrowserRealtimeAudioOptions['onPlayingChange'];\n  private readonly onCapturingChange: BrowserRealtimeAudioOptions['onCapturingChange'];\n\n  private captureContext: AudioContext | null = null;\n  private captureProcessor: ScriptProcessorNode | null = null;\n  private captureSource: MediaStreamAudioSourceNode | null = null;\n  private captureStream: MediaStream | null = null;\n  private ownsCaptureStream = true;\n  private captureCleanup: Array<() => void> = [];\n  private captureGeneration = 0;\n\n  private playbackContext: AudioContext | null = null;\n  private playbackQueue: Float32Array[] = [];\n  private playbackTime = 0;\n  private playbackStartTime = 0;\n  private activeSources = new Set<AudioBufferSourceNode>();\n  private isPlaying = false;\n  private playbackPaused = false;\n  private readonly maxPlaybackSeconds: number;\n  private readonly onError: ((error: Error) => void) | undefined;\n\n  constructor(options: BrowserRealtimeAudioOptions) {\n    this.captureSampleRate = options.captureSampleRate;\n    this.playbackSampleRate = options.playbackSampleRate;\n    this.onAudio = options.onAudio;\n    this.onPlayingChange = options.onPlayingChange;\n    this.maxPlaybackSeconds = options.maxPlaybackSeconds ?? Infinity;\n    this.onError = options.onError;\n    this.onCapturingChange = options.onCapturingChange;\n  }\n\n  ensurePlaybackContext(): void {\n    if (this.playbackContext == null) {\n      this.playbackContext = new AudioContext({\n        sampleRate: this.playbackSampleRate,\n      });\n      const context = this.playbackContext;\n      context.onstatechange = () => {\n        if (this.playbackContext === context)\n          this.setPlaying(\n            context.state === 'running' && this.activeSources.size > 0,\n          );\n      };\n    }\n  }\n\n  async resumePlayback(): Promise<void> {\n    this.ensurePlaybackContext();\n    const context = this.playbackContext;\n    if (this.playbackPaused) this.stopPlayback();\n    if (this.playbackContext !== context) return;\n    await context?.resume();\n    if (this.playbackContext !== context) return;\n    this.playbackPaused = false;\n    this.setPlaying(\n      this.playbackContext?.state === 'running' && this.activeSources.size > 0,\n    );\n  }\n\n  startCapture(stream: MediaStream, options?: { ownsStream?: boolean }): void {\n    const generation = this.captureGeneration + 1;\n    this.stopCapture();\n    if (generation !== this.captureGeneration) {\n      if (options?.ownsStream ?? true)\n        stream.getTracks().forEach(track => track.stop());\n      return;\n    }\n    this.captureStream = stream;\n    this.ownsCaptureStream = options?.ownsStream ?? true;\n    const ctx = new AudioContext({ sampleRate: this.captureSampleRate });\n    this.captureContext = ctx;\n    void ctx.resume().catch(error => {\n      if (this.captureContext === ctx) this.onError?.(error);\n    });\n\n    const source = ctx.createMediaStreamSource(stream);\n    this.captureSource = source;\n\n    const processor = ctx.createScriptProcessor(1024, 1, 1);\n    this.captureProcessor = processor;\n\n    processor.onaudioprocess = event => {\n      if (this.captureContext !== ctx) return;\n      const inputData = event.inputBuffer.getChannelData(0);\n      const samples = resampleAudio(\n        new Float32Array(inputData),\n        ctx.sampleRate,\n        this.captureSampleRate,\n      );\n      try {\n        this.onAudio(encodeRealtimeAudio(samples));\n      } catch (error) {\n        this.onError?.(\n          error instanceof Error ? error : new Error(String(error)),\n        );\n      }\n    };\n\n    source.connect(processor);\n    processor.connect(ctx.destination);\n    const updateCapturing = () =>\n      this.onCapturingChange(\n        stream\n          .getAudioTracks()\n          .some(\n            track =>\n              track.enabled && !track.muted && track.readyState === 'live',\n          ),\n      );\n    for (const track of stream.getAudioTracks()) {\n      for (const event of ['ended', 'mute', 'unmute']) {\n        track.addEventListener(event, updateCapturing);\n        this.captureCleanup.push(() =>\n          track.removeEventListener(event, updateCapturing),\n        );\n      }\n    }\n    updateCapturing();\n  }\n\n  stopCapture(): void {\n    this.captureGeneration++;\n    if (this.captureProcessor != null)\n      this.captureProcessor.onaudioprocess = null;\n    for (const cleanup of this.captureCleanup) cleanup();\n    this.captureCleanup = [];\n    this.captureProcessor?.disconnect();\n    this.captureSource?.disconnect();\n    void this.captureContext?.close().catch(() => {});\n    if (this.ownsCaptureStream)\n      this.captureStream?.getTracks().forEach(track => track.stop());\n\n    this.captureProcessor = null;\n    this.captureSource = null;\n    this.captureContext = null;\n    this.captureStream = null;\n    this.onCapturingChange(false);\n  }\n\n  playAudio(base64Audio: string): void {\n    if (this.playbackPaused) return;\n    this.ensurePlaybackContext();\n    const samples = decodeRealtimeAudio(base64Audio);\n    if (\n      Math.max(\n        0,\n        this.playbackTime - (this.playbackContext?.currentTime ?? 0),\n      ) +\n        samples.length / this.playbackSampleRate >\n      this.maxPlaybackSeconds\n    ) {\n      this.playbackPaused = true;\n      this.stopPlayback();\n      this.onError?.(\n        new Error(\n          'Realtime audio playback buffer is full; playback paused, call resumePlayback() to resume at the live edge',\n        ),\n      );\n      return;\n    }\n    this.playbackQueue.push(samples);\n    this.schedulePlayback();\n  }\n\n  stopPlayback(): void {\n    this.playbackQueue = [];\n\n    for (const source of this.activeSources) {\n      try {\n        source.onended = null;\n        source.stop();\n        source.disconnect();\n      } catch {\n        // Source may already be stopped by the browser.\n      }\n    }\n    this.activeSources.clear();\n\n    if (this.playbackContext != null) {\n      this.playbackTime = this.playbackContext.currentTime;\n    }\n    this.setPlaying(false);\n  }\n\n  getPlaybackOffsetMs(): number {\n    const ctx = this.playbackContext;\n    if (ctx == null) return 0;\n    return (ctx.currentTime - this.playbackStartTime) * 1000;\n  }\n\n  dispose(): void {\n    this.stopCapture();\n    this.stopPlayback();\n    if (this.playbackContext != null) this.playbackContext.onstatechange = null;\n    void this.playbackContext?.close().catch(() => {});\n    this.playbackContext = null;\n    this.playbackTime = 0;\n    this.playbackPaused = false;\n  }\n\n  private setPlaying(isPlaying: boolean): void {\n    if (isPlaying && !this.isPlaying) {\n      this.playbackStartTime = this.playbackContext?.currentTime ?? 0;\n    }\n    if (this.isPlaying !== isPlaying) {\n      this.isPlaying = isPlaying;\n      this.onPlayingChange(isPlaying);\n    }\n  }\n\n  private schedulePlayback(): void {\n    const ctx = this.playbackContext;\n    if (ctx == null || this.playbackQueue.length === 0) return;\n\n    while (this.playbackQueue.length > 0) {\n      const samples = this.playbackQueue.shift()!;\n      const buffer = ctx.createBuffer(\n        1,\n        samples.length,\n        this.playbackSampleRate,\n      );\n      buffer.getChannelData(0).set(samples);\n\n      const source = ctx.createBufferSource();\n      source.buffer = buffer;\n      source.connect(ctx.destination);\n\n      const startTime = Math.max(this.playbackTime, ctx.currentTime);\n      source.start(startTime);\n      this.playbackTime = startTime + buffer.duration;\n\n      this.activeSources.add(source);\n      this.setPlaying(ctx.state === 'running');\n      if (this.playbackContext !== ctx) return;\n\n      source.onended = () => {\n        source.disconnect();\n        this.activeSources.delete(source);\n        if (this.playbackQueue.length === 0 && this.activeSources.size === 0) {\n          this.setPlaying(false);\n        }\n      };\n    }\n  }\n}\n","import { safeParseJSON } from '@ai-sdk/provider-utils';\nimport type {\n  RealtimeClientEvent,\n  RealtimeModel,\n  RealtimeServerEvent,\n} from '../types/realtime-model';\n\n/** One codec queue per connection; retired connections cannot deliver late work. */\nexport class RealtimeEventChannel {\n  private active = true;\n  private finishing = false;\n  private readonly parse: (\n    raw: unknown,\n  ) => RealtimeServerEvent | RealtimeServerEvent[];\n  private incoming = Promise.resolve();\n  private outgoing = Promise.resolve();\n  private incomingCount = 0;\n  private incomingBytes = 0;\n  private outgoingCount = 0;\n\n  constructor(\n    private readonly options: {\n      model: RealtimeModel;\n      send: (data: unknown) => void;\n      onEvent: (event: RealtimeServerEvent) => void | Promise<void>;\n      onError: (error: Error) => void;\n      onFatalError?: (error: Error) => void;\n      maxPending?: number;\n      maxPendingBytes?: number;\n    },\n  ) {\n    this.parse =\n      options.model.createServerEventParser?.() ??\n      options.model.parseServerEvent.bind(options.model);\n  }\n\n  get hasPendingIncoming(): boolean {\n    return this.incomingCount > 0;\n  }\n\n  dispose(): void {\n    this.active = false;\n  }\n\n  /** Stop accepting messages, but deliver already received terminal events. */\n  async finish(): Promise<void> {\n    this.stopWriting();\n    await this.incoming;\n    this.dispose();\n  }\n\n  stopWriting(): void {\n    this.finishing = true;\n  }\n\n  send(event: RealtimeClientEvent, shouldSend?: () => boolean): Promise<void> {\n    if (!this.active || this.finishing)\n      throw new Error('Realtime connection is closed');\n    if (this.outgoingCount >= (this.options.maxPending ?? 512)) {\n      throw new Error('Realtime outgoing queue is full');\n    }\n    this.outgoingCount++;\n    const operation = this.outgoing.then(async () => {\n      if (!this.active || this.finishing)\n        throw new Error('Realtime connection is closed');\n      if (shouldSend?.() === false) return;\n      if (!this.active || this.finishing)\n        throw new Error('Realtime connection is closed');\n      const data = await this.options.model.serializeClientEvent(event);\n      if (!this.active || this.finishing)\n        throw new Error('Realtime connection is closed');\n      if (shouldSend?.() === false) return;\n      if (!this.active || this.finishing)\n        throw new Error('Realtime connection is closed');\n      if (data != null) this.options.send(data);\n    });\n    this.outgoing = operation\n      .catch(error => {\n        if (!this.finishing) {\n          // Capture owners escalate automatic audio failures; manual sends stay recoverable.\n          if (\n            event.type !== 'input-audio-append' &&\n            event.type !== 'session-close'\n          )\n            this.report(error);\n        }\n      })\n      .finally(() => {\n        this.outgoingCount--;\n      });\n    return operation;\n  }\n\n  receive(data: unknown): void {\n    if (!this.active || this.finishing) return;\n    const bytes =\n      typeof data === 'string'\n        ? data.length * 2\n        : data instanceof Blob\n          ? data.size\n          : ((data as ArrayBuffer).byteLength ?? 0);\n    if (\n      this.incomingCount >= (this.options.maxPending ?? 512) ||\n      this.incomingBytes + bytes >\n        (this.options.maxPendingBytes ?? 8 * 1024 * 1024)\n    ) {\n      this.finishing = true;\n      this.fatal(\n        new Error(\n          'Realtime incoming queue is full; input protocol continuity was lost',\n        ),\n      );\n      return;\n    }\n    this.incomingCount++;\n    this.incomingBytes += bytes;\n    this.incoming = this.incoming\n      .then(async () => {\n        if (!this.active) return;\n        const text =\n          typeof data === 'string'\n            ? data\n            : data instanceof Blob\n              ? await data.text()\n              : new TextDecoder().decode(data as ArrayBuffer);\n        const parsed = await safeParseJSON({ text });\n        if (!this.active) return;\n        if (!parsed.success)\n          throw new Error('Invalid JSON in realtime server message', {\n            cause: parsed.error,\n          });\n        const health = this.options.model.getHealthCheckResponse?.(\n          parsed.value,\n        );\n        if (!this.active) return;\n        if (health != null && !this.finishing) this.options.send(health);\n        if (!this.active) return;\n        const result = this.parse(parsed.value);\n        for (const event of Array.isArray(result) ? result : [result]) {\n          if (!this.active) return;\n          try {\n            await this.options.onEvent(event);\n          } catch (error) {\n            this.report(error);\n          }\n        }\n      })\n      .catch(error => {\n        this.finishing = true;\n        this.fatal(error instanceof Error ? error : new Error(String(error)));\n      })\n      .finally(() => {\n        this.incomingCount--;\n        this.incomingBytes -= bytes;\n      });\n  }\n\n  private fatal(error: Error): void {\n    if (!this.active) return;\n    if (this.options.onFatalError != null) this.options.onFatalError(error);\n    else this.report(error);\n  }\n\n  private report(error: unknown): void {\n    if (!this.active) return;\n    try {\n      this.options.onError(\n        error instanceof Error ? error : new Error(String(error)),\n      );\n    } catch {\n      /* Application callbacks cannot break the codec queue. */\n    }\n  }\n}\n","/** Private Live continuous wire budgets; legacy transports do not enforce them. */\nexport const REALTIME_MAX_FRAME_BYTES = 128 * 1024;\nexport const REALTIME_MAX_BUFFERED_BYTES = 128 * 1024;\n\nexport type EncodedRealtimeFrame = {\n  data: string | ArrayBuffer | ArrayBufferView | Blob;\n  byteLength: number;\n};\n\n/** Serialize once, measuring the exact payload passed to the browser. */\nexport function encodeRealtimeFrame(value: unknown): EncodedRealtimeFrame {\n  if (value instanceof ArrayBuffer || ArrayBuffer.isView(value))\n    return { data: value, byteLength: value.byteLength };\n  if (value instanceof Blob) return { data: value, byteLength: value.size };\n  const data = typeof value === 'string' ? value : JSON.stringify(value);\n  if (data === undefined)\n    throw new Error('Realtime event could not be encoded as JSON');\n  return { data, byteLength: new TextEncoder().encode(data).byteLength };\n}\n\nexport function assertRealtimeFrameBudget(\n  frame: EncodedRealtimeFrame,\n  bufferedAmount: number,\n): void {\n  if (frame.byteLength > REALTIME_MAX_FRAME_BYTES)\n    throw new Error(\n      `Realtime frame exceeds the ${REALTIME_MAX_FRAME_BYTES}-byte limit; reduce the event payload`,\n    );\n  if (bufferedAmount + frame.byteLength > REALTIME_MAX_BUFFERED_BYTES)\n    throw new Error(\n      `Realtime send buffer is full (${REALTIME_MAX_BUFFERED_BYTES}-byte limit); wait before retrying`,\n    );\n}\n","import { RealtimeEventChannel } from './realtime-event-channel';\nimport {\n  assertRealtimeFrameBudget,\n  encodeRealtimeFrame,\n} from './encode-realtime-frame';\nimport type {\n  RealtimeClientEvent,\n  RealtimeModel,\n  RealtimeServerEvent,\n} from '../types/realtime-model';\n\nexport type BrowserRealtimeTransportOptions = {\n  model: RealtimeModel;\n  onServerEvent: (event: RealtimeServerEvent) => void | Promise<void>;\n  onError: (error: Error) => void;\n  onFatalError?: (error: Error, drain?: Promise<void>) => void;\n  onClosing?: () => void;\n  onClose: (error?: Error) => void;\n};\n\nfunction getCloseError(event: CloseEvent): Error | undefined {\n  if (event.code === 1000 && event.wasClean) return undefined;\n  return new Error(\n    `Realtime WebSocket closed unexpectedly (code ${event.code}${\n      event.reason === '' ? '' : `: ${event.reason}`\n    })`,\n  );\n}\n\nexport class BrowserRealtimeTransport {\n  private readonly model: RealtimeModel;\n  private readonly continuous: boolean;\n  private readonly onServerEvent: BrowserRealtimeTransportOptions['onServerEvent'];\n  private readonly onError: BrowserRealtimeTransportOptions['onError'];\n  private readonly onClose: BrowserRealtimeTransportOptions['onClose'];\n  private ws: WebSocket | null = null;\n  private codec: RealtimeEventChannel | undefined;\n  private epoch = 0;\n  private drainTimer?: ReturnType<typeof setTimeout>;\n  private failing = false;\n  private closing = false;\n\n  constructor(private readonly options: BrowserRealtimeTransportOptions) {\n    this.model = options.model;\n    this.continuous = options.model.capabilities?.conversation === 'continuous';\n    this.onServerEvent = options.onServerEvent;\n    this.onError = options.onError;\n    this.onClose = options.onClose;\n  }\n\n  get isOpen(): boolean {\n    return (\n      !this.closing && !this.failing && this.ws?.readyState === WebSocket.OPEN\n    );\n  }\n\n  connect({\n    mode,\n    token,\n    url,\n    onOpen,\n    protocols,\n  }: (\n    | { mode: 'client-secret'; token: string; protocols?: never }\n    | { mode: 'relay'; token?: never; protocols?: string[] }\n  ) & {\n    url: string;\n    onOpen: () => void | Promise<void>;\n  }): void {\n    this.disconnect();\n\n    const epoch = this.epoch;\n    if (\n      mode !== 'relay' &&\n      (mode !== 'client-secret' ||\n        typeof token !== 'string' ||\n        token.trim() === '')\n    )\n      throw new Error(\n        'Realtime client-secret connection requires a nonempty token',\n      );\n    const wsConfig =\n      mode === 'relay'\n        ? { url, protocols }\n        : this.model.getWebSocketConfig?.({ token, url });\n    if (this.epoch !== epoch) return;\n    if (wsConfig == null)\n      throw new Error('Model does not support client-secret WebSockets');\n    const finalUrl = wsConfig.url;\n    const finalProtocols = wsConfig.protocols;\n    if (this.epoch !== epoch) return;\n    try {\n      if (typeof finalUrl !== 'string' || !/^wss?:\\/\\//i.test(finalUrl))\n        throw new Error('Invalid realtime WebSocket URL');\n      const parsed = new URL(finalUrl);\n      if (\n        !['ws:', 'wss:'].includes(parsed.protocol) ||\n        parsed.hostname === '' ||\n        finalUrl.includes('#')\n      )\n        throw new Error('Invalid realtime WebSocket URL');\n    } catch {\n      throw new Error(\n        'Invalid realtime WebSocket URL; expected an absolute ws:// or wss:// URL with a host and no fragment',\n      );\n    }\n    if (this.epoch !== epoch) return;\n    const ws = new WebSocket(finalUrl, finalProtocols);\n\n    // Track the socket immediately (not just in `onopen`) so that calling\n    // `disconnect()` while it is still connecting actually closes it. Otherwise\n    // `close()` would be a no-op and the socket could open afterwards and fire\n    // the `onOpen` (session-update) callback against a disconnected session.\n    this.ws = ws;\n    let starting = false;\n    let connectionError: Error | undefined;\n    const codec = new RealtimeEventChannel({\n      model: this.model,\n      send: data => {\n        if (this.epoch !== epoch || this.ws !== ws || !this.isOpen)\n          throw new Error('Realtime WebSocket is not open');\n        this.sendRaw(data);\n      },\n      onEvent: this.onServerEvent,\n      onError: error => {\n        if (!starting) this.onError(error);\n      },\n      onFatalError: error => this.fail(error),\n    });\n    if (this.epoch !== epoch) {\n      codec.dispose();\n      return;\n    }\n    this.codec = codec;\n\n    ws.onopen = () => {\n      // Ignore a late open for a socket that has since been replaced/closed.\n      if (this.ws !== ws) return;\n      starting = true;\n      try {\n        void Promise.resolve(onOpen())\n          .catch(error => {\n            if (this.ws === ws)\n              this.fail(\n                error instanceof Error ? error : new Error(String(error)),\n              );\n          })\n          .finally(() => {\n            starting = false;\n          });\n      } catch (error) {\n        if (this.epoch === epoch)\n          this.fail(error instanceof Error ? error : new Error(String(error)));\n      }\n    };\n\n    ws.onmessage = messageEvent => {\n      if (this.ws === ws) this.codec?.receive(messageEvent.data);\n    };\n\n    ws.onerror = () => {\n      if (this.ws === ws) {\n        connectionError = new Error('WebSocket connection error');\n        this.failing = true;\n      }\n    };\n\n    ws.onclose = event => {\n      if (this.ws === ws) {\n        this.ws = null;\n        const closeError = getCloseError(event) ?? connectionError;\n        const reportCloseErrorImmediately =\n          closeError != null && !codec.hasPendingIncoming;\n        codec.stopWriting();\n        this.notifyClosing();\n        if (this.epoch !== epoch) return;\n        const drain = codec.finish();\n        if (reportCloseErrorImmediately) {\n          try {\n            this.onError(closeError);\n          } catch {\n            /* Application callbacks cannot interrupt teardown. */\n          }\n          if (this.epoch !== epoch) return;\n        }\n        const complete = () => {\n          if (this.epoch !== epoch) return;\n          clearTimeout(this.drainTimer);\n          this.epoch++;\n          codec.dispose();\n          try {\n            this.onClose(closeError);\n          } catch (error) {\n            this.reportCallbackError(error);\n          }\n        };\n        this.drainTimer = setTimeout(complete, 1_000);\n        void this.awaitDrain(drain, complete);\n      }\n    };\n  }\n\n  disconnect(): void {\n    this.epoch++;\n    clearTimeout(this.drainTimer);\n    const ws = this.ws;\n    this.ws = null;\n    this.codec?.dispose();\n    this.codec = undefined;\n    this.failing = false;\n    this.closing = false;\n    ws?.close();\n  }\n\n  sendEvent(\n    event: RealtimeClientEvent,\n    shouldSend?: () => boolean,\n    automaticAudio = false,\n  ): Promise<void> {\n    if (this.failing || this.closing)\n      throw new Error('Realtime connection is closed');\n    if (this.codec == null) return Promise.resolve();\n    const epoch = this.epoch;\n    const failed = (error: unknown) => {\n      if (automaticAudio && this.epoch === epoch && this.isOpen)\n        this.fail(error instanceof Error ? error : new Error(String(error)));\n    };\n    try {\n      const sent = this.codec.send(event, shouldSend);\n      void sent.catch(failed);\n      return sent;\n    } catch (error) {\n      failed(error);\n      throw error;\n    }\n  }\n\n  finish(): Promise<void> {\n    return this.codec?.finish() ?? Promise.resolve();\n  }\n\n  /** Drain accepted events when media or protocol continuity is lost. */\n  fail(error: Error): void {\n    if (this.failing) return;\n    this.failing = true;\n    const epoch = this.epoch;\n    const ws = this.ws;\n    this.ws = null;\n    this.codec?.stopWriting();\n    ws?.close();\n    this.notifyClosing();\n    if (this.epoch !== epoch) return;\n    const drain = this.finish();\n    if (this.options.onFatalError != null)\n      this.options.onFatalError(error, drain);\n    else {\n      const complete = () => {\n        if (epoch !== this.epoch) return;\n        this.disconnect();\n        try {\n          this.onClose();\n        } catch (cause) {\n          this.reportCallbackError(cause);\n        }\n      };\n      this.drainTimer = setTimeout(complete, 1_000);\n      void this.awaitDrain(drain, complete);\n      this.reportCallbackError(error);\n    }\n  }\n\n  private notifyClosing(): void {\n    if (this.closing) return;\n    this.closing = true;\n    try {\n      this.options.onClosing?.();\n    } catch (error) {\n      this.reportCallbackError(error);\n    }\n  }\n\n  private async awaitDrain(\n    drain: Promise<void>,\n    complete: () => void,\n  ): Promise<void> {\n    try {\n      await drain;\n    } catch {\n      /* Transport loss still requires finalization. */\n    }\n    try {\n      complete();\n    } catch (error) {\n      this.reportCallbackError(error);\n    }\n  }\n\n  private reportCallbackError(error: unknown): void {\n    try {\n      this.onError(error instanceof Error ? error : new Error(String(error)));\n    } catch {\n      /* Application callbacks cannot interrupt teardown. */\n    }\n  }\n\n  sendRaw(data: unknown): void {\n    const ws = this.ws;\n    const epoch = this.epoch;\n    if (ws == null || !this.isOpen) return;\n    const frame = encodeRealtimeFrame(data);\n    if (this.epoch !== epoch || this.ws !== ws || !this.isOpen)\n      throw new Error('Realtime connection is closed');\n    if (this.continuous) assertRealtimeFrameBudget(frame, ws.bufferedAmount);\n    ws.send(frame.data);\n  }\n\n  dispose(): void {\n    this.disconnect();\n  }\n}\n","import { UnsupportedFunctionalityError } from '@ai-sdk/provider';\nimport type {\n  RealtimeClientEvent,\n  RealtimeModel,\n  RealtimeServerEvent,\n  RealtimeSessionConfig,\n} from '../types/realtime-model';\nimport { BrowserRealtimeAudio } from './browser-realtime-audio';\nimport { BrowserRealtimeTransport } from './browser-realtime-transport';\n\n/** Continuous PCM16 audio-chunk media for an application-owned WebSocket relay. */\nexport class BrowserRealtimeLiveWebSocket {\n  private readonly transport: BrowserRealtimeTransport;\n  private readonly audio: BrowserRealtimeAudio;\n  private readonly config: RealtimeSessionConfig;\n  private generation = 0;\n  private ready = false;\n  private capturingStarted = false;\n  private stream?: MediaStream;\n  private pendingAudio = 0;\n  private captureGeneration = 0;\n  private captureEnabled = true;\n\n  constructor(\n    private readonly options: {\n      model: RealtimeModel;\n      sessionConfig?: Partial<RealtimeSessionConfig>;\n      sampleRate?: number;\n      maxPlaybackBufferSeconds?: number;\n      onEvent: (event: RealtimeServerEvent) => Promise<void>;\n      onError: (error: Error) => void;\n      onFatalError: (error: Error, drain?: Promise<void>) => void;\n      onClosing?: () => void;\n      onClose: (error?: Error) => void;\n      onCapturing: (value: boolean) => void;\n      onPlaying: (value: boolean) => void;\n    },\n  ) {\n    const input = options.sessionConfig?.inputAudioFormat;\n    const output = options.sessionConfig?.outputAudioFormat;\n    const sampleRate =\n      input?.rate ?? output?.rate ?? options.sampleRate ?? 24000;\n    const format = {\n      type: input?.type ?? output?.type ?? 'audio/pcm',\n      rate: sampleRate,\n    };\n    this.config = {\n      ...options.sessionConfig,\n      inputAudioFormat: {\n        ...format,\n        ...input,\n      },\n      outputAudioFormat: {\n        ...format,\n        ...output,\n      },\n    };\n    this.transport = new BrowserRealtimeTransport({\n      model: options.model,\n      onServerEvent: options.onEvent,\n      onError: options.onError,\n      onFatalError: options.onFatalError,\n      onClosing: () => {\n        const generation = this.generation;\n        options.onClosing?.();\n        if (generation === this.generation) this.stopCapture();\n      },\n      onClose: options.onClose,\n    });\n    this.audio = new BrowserRealtimeAudio({\n      captureSampleRate: this.config.inputAudioFormat?.rate ?? sampleRate,\n      playbackSampleRate: this.config.outputAudioFormat?.rate ?? sampleRate,\n      maxPlaybackSeconds: options.maxPlaybackBufferSeconds ?? 2,\n      onAudio: audio => this.sendAudio(audio),\n      onError: options.onError,\n      onCapturingChange: options.onCapturing,\n      onPlayingChange: options.onPlaying,\n    });\n  }\n\n  connect(options: {\n    url: string;\n    protocols?: string[];\n    stream?: MediaStream;\n    capture?: boolean;\n  }): void {\n    const generation = this.generation + 1;\n    this.dispose();\n    if (generation !== this.generation) return;\n    for (const format of [\n      this.config.inputAudioFormat,\n      this.config.outputAudioFormat,\n    ]) {\n      if (format?.type !== 'audio/pcm')\n        throw new UnsupportedFunctionalityError({\n          functionality:\n            'Continuous browser WebSocket audio supports PCM16 only',\n        });\n      if (\n        format.rate == null ||\n        !Number.isFinite(format.rate) ||\n        format.rate < 8000 ||\n        format.rate > 96000\n      )\n        throw new Error('Invalid realtime PCM sample rate');\n    }\n    this.stream = options.stream;\n    this.captureEnabled = options.capture !== false;\n    // Create/resume playback while connect is still in the caller's user gesture.\n    this.audio.ensurePlaybackContext();\n    void this.audio.resumePlayback().catch(error => {\n      if (generation === this.generation) this.options.onError(error);\n    });\n    this.transport.connect({\n      mode: 'relay',\n      url: options.url,\n      protocols: options.protocols,\n      onOpen: () => {\n        return this.transport.sendEvent({\n          type: this.options.model.capabilities?.startup ?? 'session-update',\n          config: this.config,\n        });\n      },\n    });\n  }\n\n  startCapture(): void {\n    this.ready = true;\n    if (!this.captureEnabled || this.capturingStarted) return;\n    void this.resumeCapture().catch(error => this.options.onError(error));\n  }\n\n  async resumeCapture(suppliedStream?: MediaStream): Promise<void> {\n    const generation = this.captureGeneration + 1;\n    this.stopCapture();\n    if (generation !== this.captureGeneration) return;\n    this.ready = true;\n    this.capturingStarted = true;\n    this.captureEnabled = true;\n    if (suppliedStream != null) this.stream = suppliedStream;\n    const supplied = this.stream;\n    const stream =\n      supplied ?? (await navigator.mediaDevices.getUserMedia({ audio: true }));\n    if (generation !== this.captureGeneration || !this.ready) {\n      if (supplied == null) stream.getTracks().forEach(track => track.stop());\n      return;\n    }\n    if (!stream.getAudioTracks().some(track => track.readyState === 'live')) {\n      if (supplied == null) stream.getTracks().forEach(track => track.stop());\n      throw new Error('Realtime requires a live audio track');\n    }\n    this.audio.startCapture(stream, { ownsStream: supplied == null });\n  }\n\n  private sendAudio(audio: string): void {\n    if (!this.ready || !this.transport.isOpen) return;\n    if (this.pendingAudio >= 8) {\n      this.transport.fail(new Error('Realtime audio send queue is full'));\n      return;\n    }\n    const generation = this.generation;\n    let sent: Promise<void>;\n    try {\n      sent = this.transport.sendEvent(\n        { type: 'input-audio-append', audio },\n        undefined,\n        true,\n      );\n    } catch (error) {\n      if (!this.ready || !this.transport.isOpen) return;\n      throw error;\n    }\n    this.pendingAudio++;\n    void sent.then(\n      () => {\n        if (generation === this.generation) this.pendingAudio--;\n      },\n      error => {\n        if (\n          generation === this.generation &&\n          this.ready &&\n          this.transport.isOpen\n        )\n          this.options.onFatalError(error);\n      },\n    );\n  }\n\n  sendEvent(\n    event: RealtimeClientEvent,\n    shouldSend?: () => boolean,\n  ): Promise<void> {\n    if (event.type === 'session-update') {\n      for (const key of ['inputAudioFormat', 'outputAudioFormat'] as const) {\n        const update = event.config[key];\n        if (\n          update != null &&\n          (update.type !== this.config[key]?.type ||\n            (update.rate != null && update.rate !== this.config[key]?.rate))\n        ) {\n          throw new Error(\n            'Changing Live WebSocket audio format requires reconnecting',\n          );\n        }\n      }\n    }\n    return this.transport.sendEvent(event, shouldSend);\n  }\n  playAudio(audio: string): void {\n    try {\n      this.audio.playAudio(audio);\n    } catch (error) {\n      this.options.onError(\n        error instanceof Error ? error : new Error(String(error)),\n      );\n    }\n  }\n  stopPlayback(): void {\n    this.audio.stopPlayback();\n  }\n  resumePlayback(): Promise<void> {\n    return this.audio.resumePlayback();\n  }\n\n  stopCapture(): void {\n    this.captureGeneration++;\n    this.ready = false;\n    this.capturingStarted = false;\n    this.captureEnabled = false;\n    this.audio.stopCapture();\n  }\n\n  finish(): Promise<void> {\n    return this.transport.finish();\n  }\n\n  dispose(): void {\n    this.generation++;\n    this.stopCapture();\n    this.ready = false;\n    this.capturingStarted = false;\n    this.pendingAudio = 0;\n    this.stream = undefined;\n    this.transport.disconnect();\n    this.audio.dispose();\n  }\n}\n","import { safeParseJSON } from '@ai-sdk/provider-utils';\nimport type {\n  RealtimeClientEvent,\n  RealtimeModel,\n  RealtimeServerEvent,\n  RealtimeSessionConfig,\n} from '../types/realtime-model';\nimport { RealtimeEventChannel } from './realtime-event-channel';\n\nconst MAX_SESSION_ANSWER_BYTES = 1024 * 1024;\n\nasync function readSessionAnswer(response: Response): Promise<string> {\n  const reader = response.body?.getReader();\n  if (reader == null) throw new Error('Invalid realtime session answer');\n  const decoder = new TextDecoder();\n  let bytes = 0;\n  let text = '';\n  try {\n    if (\n      Number(response.headers.get('content-length')) > MAX_SESSION_ANSWER_BYTES\n    )\n      throw new Error('Realtime session answer exceeds the 1 MiB limit');\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) return text + decoder.decode();\n      bytes += value.byteLength;\n      if (bytes > MAX_SESSION_ANSWER_BYTES)\n        throw new Error('Realtime session answer exceeds the 1 MiB limit');\n      text += decoder.decode(value, { stream: true });\n    }\n  } catch (error) {\n    void reader.cancel(error).catch(() => {});\n    throw error;\n  } finally {\n    reader.releaseLock();\n  }\n}\n\nfunction selectAudioTrack(stream: MediaStream): MediaStreamTrack | undefined {\n  const live = stream\n    .getAudioTracks()\n    .filter(track => track.readyState === 'live');\n  return live.find(track => track.enabled && !track.muted) ?? live[0];\n}\n\nexport class BrowserRealtimeWebRTC {\n  private pc?: RTCPeerConnection;\n  private dc?: RTCDataChannel;\n  private codec?: RealtimeEventChannel;\n  private stream?: MediaStream;\n  private ownsStream = false;\n  private audio?: HTMLAudioElement;\n  private abort?: AbortController;\n  private generation = 0;\n  private finishTimer?: ReturnType<typeof setTimeout>;\n  private finishing?: 'close' | 'failure';\n  private closingNotified = false;\n  private disconnectTimer?: ReturnType<typeof setTimeout>;\n  private captureGeneration = 0;\n  private sender?: RTCRtpSender;\n  private senderOperations = Promise.resolve();\n  private rejectStartup?: (error: Error) => void;\n  private trackCleanups: Array<() => void> = [];\n\n  constructor(\n    private readonly options: {\n      model: RealtimeModel;\n      onEvent: (event: RealtimeServerEvent) => void | Promise<void>;\n      onError: (error: Error) => void;\n      onFatalError?: (error: Error, drain?: Promise<void>) => void;\n      disconnectTimeoutMs?: number;\n      onClose: (error?: Error) => void;\n      onClosing?: () => void;\n      onCapturing: (value: boolean) => void;\n      onPlaying: (value: boolean) => void;\n    },\n  ) {}\n\n  async connect({\n    api,\n    sessionConfig,\n    stream,\n    timeoutMs,\n    capture = true,\n  }: {\n    api: string;\n    sessionConfig?: Partial<RealtimeSessionConfig>;\n    /** Caller-owned tracks are detached, never stopped, on disconnect. */\n    stream?: MediaStream;\n    timeoutMs: number;\n    capture?: boolean;\n  }): Promise<void> {\n    const generation = this.generation + 1;\n    this.dispose();\n    const current = () => generation === this.generation;\n    if (!current()) return;\n    const config = this.options.model.getWebRTCConfig?.();\n    if (!current()) return;\n    if (config == null)\n      throw new Error('This model does not support WebRTC configuration');\n    const abort = new AbortController();\n    this.abort = abort;\n    const timeout = setTimeout(\n      () => abort.abort(new Error('Realtime startup timed out')),\n      timeoutMs,\n    );\n    const cancelled = new Promise<never>((_, reject) => {\n      abort.signal.addEventListener(\n        'abort',\n        () => reject(abort.signal.reason),\n        { once: true },\n      );\n    });\n    const start = async () => {\n      const captureGeneration = this.captureGeneration;\n      let media = capture\n        ? (stream ??\n          (await navigator.mediaDevices.getUserMedia({ audio: true })))\n        : undefined;\n      if (!current() || abort.signal.aborted) {\n        if (stream == null) media?.getTracks().forEach(track => track.stop());\n        throw new Error('Realtime connection cancelled');\n      }\n      if (captureGeneration !== this.captureGeneration) {\n        if (stream == null) media?.getTracks().forEach(track => track.stop());\n        media = undefined;\n      }\n      this.stream = media;\n      this.ownsStream = stream == null;\n      const track = media == null ? undefined : selectAudioTrack(media);\n      if (media != null && track == null) {\n        throw new Error('Realtime requires a live audio track');\n      }\n      const pc = new RTCPeerConnection();\n      this.pc = pc;\n      const audio = document.createElement('audio');\n      audio.autoplay = true;\n      this.audio = audio;\n      audio.onplaying = () => {\n        if (current()) this.options.onPlaying(true);\n      };\n      const stopped = () => {\n        if (current()) this.options.onPlaying(false);\n      };\n      audio.onpause = stopped;\n      audio.onended = stopped;\n      audio.onwaiting = stopped;\n      pc.ontrack = event => {\n        if (!current()) return;\n        audio.srcObject = event.streams[0] ?? new MediaStream([event.track]);\n        void audio.play().catch(error => {\n          if (current()) this.options.onError(error);\n        });\n      };\n      pc.onconnectionstatechange = () => {\n        if (!current()) return;\n        if (pc.connectionState === 'connected')\n          clearTimeout(this.disconnectTimer);\n        else if (pc.connectionState === 'disconnected') {\n          clearTimeout(this.disconnectTimer);\n          this.disconnectTimer = setTimeout(() => {\n            if (current() && pc.connectionState === 'disconnected')\n              this.fail(\n                new Error(\n                  'Realtime peer disconnected beyond recovery grace period',\n                ),\n              );\n          }, this.options.disconnectTimeoutMs ?? 5_000);\n        } else if (pc.connectionState === 'closed') {\n          this.drainClose(new Error('Realtime peer connection closed'));\n        } else if (pc.connectionState === 'failed') {\n          this.fail(\n            new Error(`Realtime peer connection ${pc.connectionState}`),\n          );\n        }\n      };\n      pc.oniceconnectionstatechange = () => {\n        if (current() && pc.iceConnectionState === 'failed')\n          this.fail(new Error('Realtime ICE connection failed'));\n      };\n      const dc = pc.createDataChannel(config.dataChannelLabel);\n      this.dc = dc;\n      const codec = new RealtimeEventChannel({\n        model: this.options.model,\n        onEvent: this.options.onEvent,\n        onError: this.options.onError,\n        onFatalError: error => {\n          if (current()) this.fail(error);\n        },\n        send: data => {\n          if (!current() || this.finishing || dc.readyState !== 'open')\n            throw new Error('Realtime data channel is not open');\n          if (dc.bufferedAmount > 1024 * 1024)\n            throw new Error('Realtime data channel buffer is full');\n          const encoded =\n            typeof data === 'string' ? data : JSON.stringify(data);\n          if (!current() || this.finishing || dc.readyState !== 'open')\n            throw new Error('Realtime data channel is not open');\n          dc.send(encoded);\n        },\n      });\n      if (!current()) {\n        codec.dispose();\n        return;\n      }\n      this.codec = codec;\n      dc.onmessage = event => {\n        if (current()) this.codec?.receive(event.data);\n      };\n      dc.onclose = () => {\n        if (current())\n          this.drainClose(new Error('Realtime data channel closed'));\n      };\n      dc.onerror = () => {\n        if (current()) this.fail(new Error('Realtime data channel error'));\n      };\n      const opened = new Promise<void>((resolve, reject) => {\n        this.rejectStartup = reject;\n        dc.onopen = () => {\n          this.rejectStartup = undefined;\n          resolve();\n        };\n      });\n      void opened.catch(() => {});\n      const gathered = new Promise<void>(resolve => {\n        pc.onicegatheringstatechange = () => {\n          if (pc.iceGatheringState === 'complete') resolve();\n        };\n      });\n      this.sender =\n        media != null && track != null\n          ? pc.addTrack(track, media)\n          : pc.addTransceiver('audio', { direction: 'sendrecv' }).sender;\n      this.observeCapture();\n      if (!current() || abort.signal.aborted) return;\n      const offer = await pc.createOffer();\n      if (!current() || abort.signal.aborted) return;\n      await pc.setLocalDescription(offer);\n      if (pc.iceGatheringState !== 'complete')\n        await Promise.race([gathered, cancelled]);\n      if (!current() || abort.signal.aborted) return;\n      const sdp = pc.localDescription?.sdp;\n      if (sdp == null) throw new Error('Realtime offer has no SDP');\n      const response = await fetch(api, {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json' },\n        body: JSON.stringify({ sdp, sessionConfig }),\n        signal: abort.signal,\n      });\n      if (!response.ok)\n        throw new Error(\n          `Failed to create realtime session: ${response.status}`,\n        );\n      const parsed = await safeParseJSON({\n        text: await readSessionAnswer(response),\n      });\n      if (!current() || abort.signal.aborted) return;\n      if (\n        !parsed.success ||\n        typeof parsed.value !== 'object' ||\n        parsed.value == null ||\n        !('sdp' in parsed.value) ||\n        typeof parsed.value.sdp !== 'string' ||\n        parsed.value.sdp.trim().length === 0 ||\n        !('sessionId' in parsed.value) ||\n        typeof parsed.value.sessionId !== 'string' ||\n        parsed.value.sessionId.trim().length === 0\n      ) {\n        throw new Error('Invalid realtime session answer');\n      }\n      await pc.setRemoteDescription({ type: 'answer', sdp: parsed.value.sdp });\n      await Promise.race([opened, cancelled]);\n    };\n    try {\n      await Promise.race([start(), cancelled]);\n    } catch (error) {\n      if (current()) this.dispose();\n      throw error;\n    } finally {\n      clearTimeout(timeout);\n      this.rejectStartup = undefined;\n    }\n  }\n\n  sendEvent(\n    event: RealtimeClientEvent,\n    shouldSend?: () => boolean,\n  ): Promise<void> {\n    if (this.finishing || this.dc?.readyState !== 'open')\n      throw new Error('Realtime data channel is not open');\n    return this.codec?.send(event, shouldSend) ?? Promise.resolve();\n  }\n\n  async resumePlayback(): Promise<void> {\n    if (this.audio == null)\n      throw new Error('Realtime playback is not connected');\n    await this.audio.play();\n  }\n\n  stopPlayback(): void {\n    this.audio?.pause();\n  }\n\n  finish(): Promise<void> {\n    return this.codec?.finish() ?? Promise.resolve();\n  }\n\n  private fail(error: Error): void {\n    if (this.finishing === 'failure') return;\n    this.finishing = 'failure';\n    clearTimeout(this.finishTimer);\n    if (this.rejectStartup != null) {\n      this.rejectStartup(error);\n      this.abort?.abort(error);\n      return;\n    }\n    const generation = this.generation;\n    const drain = this.finish();\n    this.notifyClosing();\n    if (generation !== this.generation) return;\n    void this.stopCaptureForShutdown(generation);\n    if (generation !== this.generation) return;\n    if (this.options.onFatalError != null) {\n      this.options.onFatalError(error, drain);\n      return;\n    }\n    const complete = () => {\n      if (generation !== this.generation) return;\n      this.dispose();\n      try {\n        this.options.onClose();\n      } catch (cause) {\n        this.reportCallbackError(cause);\n      }\n    };\n    this.finishTimer = setTimeout(complete, 1_000);\n    void this.awaitDrain(drain, complete);\n    try {\n      this.options.onError(error);\n    } catch {\n      /* Cleanup is already scheduled. */\n    }\n  }\n\n  private drainClose(error: Error): void {\n    if (this.finishing) return;\n    if (this.rejectStartup != null) {\n      this.fail(error);\n      return;\n    }\n    this.finishing = 'close';\n    const generation = this.generation;\n    const complete = () => {\n      if (generation !== this.generation || this.finishing !== 'close') return;\n      clearTimeout(this.finishTimer);\n      try {\n        this.options.onClose(error);\n      } catch (cause) {\n        this.reportCallbackError(cause);\n      } finally {\n        if (generation === this.generation) this.dispose();\n      }\n    };\n    this.finishTimer = setTimeout(complete, 1_000);\n    void this.awaitDrain(this.finish(), complete);\n    this.notifyClosing();\n    if (generation !== this.generation) return;\n    void this.stopCaptureForShutdown(generation);\n  }\n\n  private notifyClosing(): void {\n    if (this.closingNotified) return;\n    this.closingNotified = true;\n    try {\n      this.options.onClosing?.();\n    } catch (error) {\n      this.reportCallbackError(error);\n    }\n  }\n\n  private async stopCaptureForShutdown(generation: number): Promise<void> {\n    try {\n      await this.stopCapture();\n    } catch (cause) {\n      if (generation !== this.generation || this.finishing !== 'close') return;\n      try {\n        this.fail(cause instanceof Error ? cause : new Error(String(cause)));\n      } catch (error) {\n        this.reportCallbackError(error);\n      }\n    }\n  }\n\n  private async awaitDrain(\n    drain: Promise<void>,\n    complete: () => void,\n  ): Promise<void> {\n    try {\n      await drain;\n    } catch {\n      /* Transport loss still requires finalization. */\n    }\n    try {\n      complete();\n    } catch (error) {\n      this.reportCallbackError(error);\n    }\n  }\n\n  private reportCallbackError(error: unknown): void {\n    try {\n      this.options.onError(\n        error instanceof Error ? error : new Error(String(error)),\n      );\n    } catch {\n      /* Application callbacks cannot interrupt teardown. */\n    }\n  }\n\n  async stopCapture(): Promise<void> {\n    const generation = ++this.captureGeneration;\n    for (const cleanup of this.trackCleanups) cleanup();\n    this.trackCleanups = [];\n    if (this.ownsStream)\n      this.stream?.getTracks().forEach(track => track.stop());\n    this.stream = undefined;\n    const pc = this.pc;\n    const sender = this.sender;\n    await this.queueSenderOperation(async () => {\n      if (pc !== this.pc || sender !== this.sender) return;\n      if (pc != null && sender != null) await this.detachSender(pc, sender);\n      if (generation === this.captureGeneration && pc === this.pc)\n        this.options.onCapturing(false);\n    });\n  }\n\n  async startCapture(supplied?: MediaStream): Promise<void> {\n    const generation = this.captureGeneration + 1;\n    await this.stopCapture();\n    if (\n      generation !== this.captureGeneration ||\n      this.pc == null ||\n      this.finishing\n    )\n      return;\n    const media =\n      supplied ?? (await navigator.mediaDevices.getUserMedia({ audio: true }));\n    if (\n      generation !== this.captureGeneration ||\n      this.pc == null ||\n      this.finishing\n    ) {\n      if (supplied == null) media.getTracks().forEach(track => track.stop());\n      return;\n    }\n    const track = selectAudioTrack(media);\n    if (track == null) {\n      if (supplied == null) media.getTracks().forEach(track => track.stop());\n      throw new Error('Realtime requires a live audio track');\n    }\n    const pc = this.pc;\n    const sender = this.sender;\n    await this.queueSenderOperation(async () => {\n      const current = () =>\n        generation === this.captureGeneration &&\n        pc === this.pc &&\n        sender === this.sender &&\n        pc.connectionState !== 'closed' &&\n        !this.finishing;\n      let attached = false;\n      try {\n        if (!current() || sender == null) return;\n        await sender.replaceTrack(track);\n        if (!current()) {\n          if (pc === this.pc) await this.detachSender(pc, sender);\n          return;\n        }\n        this.stream = media;\n        this.ownsStream = supplied == null;\n        attached = true;\n        this.observeCapture();\n      } finally {\n        if (!attached && supplied == null)\n          media.getTracks().forEach(track => track.stop());\n      }\n    });\n  }\n\n  private queueSenderOperation(operation: () => Promise<void>): Promise<void> {\n    const pending = this.senderOperations.then(operation);\n    this.senderOperations = pending.catch(() => {});\n    return pending;\n  }\n\n  private async detachSender(\n    pc: RTCPeerConnection,\n    sender: RTCRtpSender,\n  ): Promise<void> {\n    if (pc.connectionState === 'closed') return;\n    try {\n      await sender.replaceTrack(null);\n    } catch (error) {\n      if (pc !== this.pc) return;\n      // A rejected detach can still transmit borrowed audio. Close the peer first.\n      this.closePeer(pc);\n      this.fail(error instanceof Error ? error : new Error(String(error)));\n    }\n  }\n\n  private closePeer(pc: RTCPeerConnection): void {\n    pc.ontrack = null;\n    pc.onconnectionstatechange = null;\n    pc.oniceconnectionstatechange = null;\n    pc.onicegatheringstatechange = null;\n    if (pc.connectionState !== 'closed') pc.close();\n  }\n\n  private observeCapture(): void {\n    const generation = this.captureGeneration;\n    const sender = this.sender;\n    const track = sender?.track;\n    const update = () => {\n      if (generation === this.captureGeneration && this.sender === sender)\n        this.options.onCapturing(\n          sender?.track != null &&\n            sender.track.readyState === 'live' &&\n            sender.track.enabled &&\n            !sender.track.muted,\n        );\n    };\n    if (track != null) {\n      for (const event of ['ended', 'mute', 'unmute']) {\n        track.addEventListener(event, update);\n        this.trackCleanups.push(() => track.removeEventListener(event, update));\n      }\n    }\n    update();\n  }\n\n  dispose(): void {\n    this.generation++;\n    this.captureGeneration++;\n    clearTimeout(this.finishTimer);\n    clearTimeout(this.disconnectTimer);\n    this.finishing = undefined;\n    this.closingNotified = false;\n    this.senderOperations = Promise.resolve();\n    this.abort?.abort(new Error('Realtime connection cancelled'));\n    this.abort = undefined;\n    this.codec?.dispose();\n    this.codec = undefined;\n    if (this.dc != null) {\n      this.dc.onopen = null;\n      this.dc.onclose = null;\n      this.dc.onerror = null;\n      this.dc.onmessage = null;\n      this.dc.close();\n      this.dc = undefined;\n    }\n    if (this.pc != null) {\n      this.closePeer(this.pc);\n      this.pc = undefined;\n    }\n    for (const cleanup of this.trackCleanups) cleanup();\n    this.trackCleanups = [];\n    if (this.ownsStream)\n      this.stream?.getTracks().forEach(track => track.stop());\n    this.stream = undefined;\n    this.sender = undefined;\n    if (this.audio != null) {\n      this.audio.onplaying = null;\n      this.audio.onpause = null;\n      this.audio.onended = null;\n      this.audio.onwaiting = null;\n      this.audio.pause();\n      this.audio.srcObject = null;\n      this.audio = undefined;\n    }\n    this.options.onCapturing(false);\n    this.options.onPlaying(false);\n  }\n}\n","/** Cancellation and settlement belong to one connection attempt. */\nexport class RealtimeAttempt {\n  readonly abort = new AbortController();\n  private timers = new Map<string, ReturnType<typeof setTimeout>>();\n  private settleClose?: () => void;\n  closePromise?: Promise<void>;\n  active = true;\n  ready = false;\n  closing = false;\n  transportClosing = false;\n  cause?: Error;\n\n  timer(name: string, duration: number, callback: () => void): void {\n    this.clearTimer(name);\n    this.timers.set(\n      name,\n      setTimeout(() => {\n        this.timers.delete(name);\n        if (this.active) callback();\n      }, duration),\n    );\n  }\n\n  clearTimer(name: string): void {\n    clearTimeout(this.timers.get(name));\n    this.timers.delete(name);\n  }\n\n  beginClose(): Promise<void> {\n    this.closing = true;\n    return (this.closePromise ??= new Promise(resolve => {\n      this.settleClose = resolve;\n    }));\n  }\n\n  retire(): void {\n    if (!this.active) return;\n    this.active = false;\n    this.abort.abort();\n    for (const timer of this.timers.values()) clearTimeout(timer);\n    this.timers.clear();\n    this.settleClose?.();\n    this.settleClose = undefined;\n  }\n}\n","import { generateId } from '@ai-sdk/provider-utils';\nimport type {\n  RealtimeClientEvent,\n  RealtimeServerEvent,\n} from '../types/realtime-model';\n\n/** Attempt-local ACK correlation; unresolved commands are never evicted. */\nexport class RealtimeCommandTracker {\n  private readonly pending = new Map<string, { muted?: boolean }>();\n  private readonly recent = new Set<string>();\n\n  constructor(\n    private readonly sendCommand: (event: RealtimeClientEvent) => Promise<void>,\n  ) {}\n\n  validateId(id: string): void {\n    if (this.pending.has(id) || this.recent.has(id))\n      throw new Error(\n        'Realtime command ID was already used; retry with a fresh eventId',\n      );\n    if (this.pending.size >= 512)\n      throw new Error('Too many pending realtime commands');\n  }\n\n  private complete(id: string): { muted?: boolean } | undefined {\n    const command = this.pending.get(id);\n    if (command == null) return;\n    this.pending.delete(id);\n    this.recent.add(id);\n    if (this.recent.size > 4096) {\n      const oldest = this.recent.values().next().value;\n      if (oldest != null) this.recent.delete(oldest);\n    }\n    return command;\n  }\n\n  send(event: RealtimeClientEvent): Promise<void> {\n    const muted =\n      event.type === 'input-audio-mute'\n        ? true\n        : event.type === 'input-audio-unmute'\n          ? false\n          : undefined;\n    if (\n      event.type === 'input-audio-mute' ||\n      event.type === 'input-audio-unmute'\n    )\n      event = { ...event, eventId: event.eventId ?? generateId() };\n    const id = 'eventId' in event ? event.eventId : undefined;\n    if (id != null) {\n      this.validateId(id);\n      this.pending.set(id, { muted });\n    }\n    const awaitsAcknowledgement =\n      event.type === 'context-append' ||\n      event.type === 'session-update' ||\n      muted != null;\n    try {\n      const sent = this.sendCommand(event);\n      void sent.then(\n        () => {\n          if (id != null && !awaitsAcknowledgement) this.complete(id);\n        },\n        () => {\n          if (id != null) this.complete(id);\n        },\n      );\n      return sent;\n    } catch (error) {\n      if (id != null) this.complete(id);\n      throw error;\n    }\n  }\n\n  receive(event: RealtimeServerEvent): { muted?: boolean } | undefined {\n    if (event.type === 'command-acknowledged' && event.clientEventId != null)\n      return this.complete(event.clientEventId);\n    if (event.type === 'error' && event.clientEventId != null)\n      this.complete(event.clientEventId);\n  }\n}\n","import { z } from '../util/zod';\nimport type { RealtimeSetupResponse } from './realtime-types';\n\nconst setupSchema = z.object({\n  token: z.string().refine(value => value.trim().length > 0),\n  url: z.string().refine(value => {\n    try {\n      const url = new URL(value);\n      return (\n        (url.protocol === 'ws:' || url.protocol === 'wss:') &&\n        url.hostname !== ''\n      );\n    } catch {\n      return false;\n    }\n  }),\n  expiresAt: z.number().positive().max(Number.MAX_SAFE_INTEGER).optional(),\n  tools: z\n    .array(\n      z.object({\n        type: z.literal('function'),\n        name: z.string().min(1),\n        description: z.string().optional(),\n        parameters: z.record(z.string(), z.unknown()),\n      }),\n    )\n    .optional(),\n});\n\nexport function validateRealtimeSetup(payload: unknown): RealtimeSetupResponse {\n  const result = setupSchema.safeParse(payload);\n  if (!result.success)\n    throw new Error(\n      'Invalid realtime setup: expected a nonempty token, a ws(s) URL, and valid optional expiresAt/tools',\n    );\n  return result.data;\n}\n","import type { RealtimeServerEvent } from '../types/realtime-model';\n\nexport type RealtimeSessionState = {\n  delegationMode?: 'client' | 'provider';\n  sessionId?: string;\n  transcripts: Extract<RealtimeServerEvent, { type: 'transcript-fragment' }>[];\n  delegations: Extract<RealtimeServerEvent, { type: 'delegation-created' }>[];\n  usage?: { seconds: number };\n  finalization: 'pending' | 'confirmed' | 'unconfirmed';\n  terminationReason?: string;\n  isInputMuted: boolean;\n};\n\nexport function createSessionState(): RealtimeSessionState {\n  return {\n    transcripts: [],\n    delegations: [],\n    isInputMuted: false,\n    finalization: 'pending',\n  };\n}\n\nexport function reduceSessionState(\n  state: RealtimeSessionState,\n  event: RealtimeServerEvent,\n  limit: number,\n  muted?: boolean,\n): RealtimeSessionState {\n  switch (event.type) {\n    case 'session-started':\n      return {\n        ...state,\n        sessionId: event.sessionId,\n        delegationMode: event.delegationMode,\n      };\n    case 'session-usage':\n      return { ...state, usage: event.usage };\n    case 'session-closed':\n      return {\n        ...state,\n        sessionId: event.sessionId ?? state.sessionId,\n        usage: event.usage,\n        terminationReason: event.reason,\n        finalization: 'confirmed',\n      };\n    case 'transcript-fragment':\n      return {\n        ...state,\n        transcripts: [...state.transcripts, event].slice(-limit),\n      };\n    case 'delegation-created':\n      return state.delegations.some(\n        item => item.delegationId === event.delegationId,\n      )\n        ? state\n        : {\n            ...state,\n            delegations: [...state.delegations, event].slice(-limit),\n          };\n    case 'command-acknowledged':\n      return muted == null ? state : { ...state, isInputMuted: muted };\n    default:\n      return state;\n  }\n}\n","import { safeParseJSON } from '@ai-sdk/provider-utils';\nimport type { RealtimeServerEvent } from '../types/realtime-model';\nimport type { RealtimeSessionState } from './realtime-session-state';\nimport type {\n  DynamicToolUIPart,\n  TextUIPart,\n  UIMessage,\n} from '../ui/ui-messages';\n\nexport type RealtimeStatus =\n  | 'disconnected'\n  | 'connecting'\n  | 'connected'\n  | 'closing'\n  | 'error';\n\nexport interface RealtimeState {\n  status: RealtimeStatus;\n  messages: UIMessage[];\n  events: RealtimeServerEvent[];\n  isCapturing: boolean;\n  isPlaying: boolean;\n  session?: RealtimeSessionState;\n}\n\nexport type RealtimeReducerEffect =\n  | {\n      type: 'play-audio';\n      itemId: string;\n      delta: string;\n    }\n  | {\n      type: 'speech-started';\n    }\n  | {\n      type: 'tool-call';\n      callId: string;\n      name: string;\n      args: Record<string, unknown>;\n      rawArguments: string;\n    }\n  | {\n      type: 'error';\n      error: Error;\n    };\n\nexport type RealtimeToolOutput = {\n  callId: string;\n  name?: string;\n  output: string;\n};\n\nexport function createInitialRealtimeState(): RealtimeState {\n  return {\n    status: 'disconnected',\n    messages: [],\n    events: [],\n    isCapturing: false,\n    isPlaying: false,\n  };\n}\n\nexport class RealtimeEventReducer {\n  private currentAssistantMessageId: string | null = null;\n  private textAccumulators = new Map<string, string>();\n  private toolArgAccumulators = new Map<string, string>();\n  private toolCallIdToMessageId = new Map<string, string>();\n  private toolCallIdToName = new Map<string, string>();\n  private inputAudioMessageInsertIndex = new Map<string, number>();\n  private itemIdToPartLocation = new Map<\n    string,\n    { messageId: string; partIndex: number }\n  >();\n\n  constructor(private readonly maxEvents = 500) {}\n\n  setStatus(state: RealtimeState, status: RealtimeStatus): RealtimeState {\n    return { ...state, status };\n  }\n\n  setCapturing(state: RealtimeState, isCapturing: boolean): RealtimeState {\n    return { ...state, isCapturing };\n  }\n\n  setPlaying(state: RealtimeState, isPlaying: boolean): RealtimeState {\n    return { ...state, isPlaying };\n  }\n\n  addUserTextMessage(state: RealtimeState, text: string): RealtimeState {\n    return {\n      ...state,\n      messages: [\n        ...state.messages,\n        {\n          id: `user-${Date.now()}`,\n          role: 'user',\n          parts: [{ type: 'text', text, state: 'done' } as TextUIPart],\n        },\n      ],\n    };\n  }\n\n  addToolOutput(\n    state: RealtimeState,\n    callId: string,\n    result: unknown,\n  ): { state: RealtimeState; output: RealtimeToolOutput } {\n    return {\n      state: this.updateToolPartState(state, callId, result),\n      output: {\n        callId,\n        name: this.toolCallIdToName.get(callId),\n        output: JSON.stringify(result),\n      },\n    };\n  }\n\n  async reduceServerEvent(\n    state: RealtimeState,\n    event: RealtimeServerEvent,\n  ): Promise<{ state: RealtimeState; effects: RealtimeReducerEffect[] }> {\n    let nextState = this.pushEvent(state, event);\n    const effects: RealtimeReducerEffect[] = [];\n\n    switch (event.type) {\n      case 'session-created':\n      case 'session-updated': {\n        if (nextState.status === 'connecting') {\n          nextState = this.setStatus(nextState, 'connected');\n        }\n        break;\n      }\n\n      case 'audio-delta': {\n        effects.push({\n          type: 'play-audio',\n          itemId: event.itemId,\n          delta: event.delta,\n        });\n        break;\n      }\n\n      case 'audio-committed': {\n        if (event.itemId != null) {\n          this.inputAudioMessageInsertIndex.set(\n            event.itemId,\n            nextState.messages.length,\n          );\n        }\n        break;\n      }\n\n      case 'audio-transcript-delta':\n      case 'text-delta': {\n        nextState = this.appendTextDelta(nextState, event.itemId, event.delta);\n        break;\n      }\n\n      case 'audio-transcript-done': {\n        nextState = this.finalizeText(\n          nextState,\n          event.itemId,\n          event.transcript,\n        );\n        break;\n      }\n\n      case 'text-done': {\n        nextState = this.finalizeText(nextState, event.itemId, event.text);\n        break;\n      }\n\n      case 'input-transcription-completed': {\n        nextState = this.addInputTranscriptionMessage(\n          nextState,\n          event.itemId,\n          event.transcript,\n        );\n        break;\n      }\n\n      case 'response-created':\n      case 'response-done': {\n        this.currentAssistantMessageId = null;\n        break;\n      }\n\n      case 'speech-started': {\n        this.currentAssistantMessageId = null;\n        effects.push({ type: 'speech-started' });\n        break;\n      }\n\n      case 'function-call-arguments-delta': {\n        const { state: updatedState, messageId } =\n          this.getOrCreateAssistantMessage(nextState);\n        nextState = updatedState;\n        this.toolCallIdToMessageId.set(event.callId, messageId);\n\n        const acc = this.toolArgAccumulators.get(event.callId) ?? '';\n        this.toolArgAccumulators.set(event.callId, acc + event.delta);\n\n        nextState = this.ensureToolPart(nextState, messageId, event.callId);\n        break;\n      }\n\n      case 'function-call-arguments-done': {\n        this.toolArgAccumulators.delete(event.callId);\n        this.toolCallIdToName.set(event.callId, event.name);\n\n        const parseResult = await safeParseJSON({ text: event.arguments });\n        const parsedInput = parseResult.success\n          ? (parseResult.value as Record<string, unknown>)\n          : {};\n\n        const messageId = this.toolCallIdToMessageId.get(event.callId);\n        if (messageId != null) {\n          nextState = this.markToolInputAvailable(\n            nextState,\n            messageId,\n            event.callId,\n            event.name,\n            parsedInput,\n          );\n        }\n\n        if (!parseResult.success) {\n          effects.push({\n            type: 'error',\n            error: new Error(\n              `Failed to parse tool arguments: ${event.arguments}`,\n            ),\n          });\n        } else {\n          effects.push({\n            type: 'tool-call',\n            callId: event.callId,\n            name: event.name,\n            args: parsedInput,\n            rawArguments: event.arguments,\n          });\n        }\n        break;\n      }\n\n      case 'error': {\n        effects.push({ type: 'error', error: new Error(event.message) });\n        break;\n      }\n    }\n\n    return { state: nextState, effects };\n  }\n\n  private pushEvent(\n    state: RealtimeState,\n    event: RealtimeServerEvent,\n  ): RealtimeState {\n    const events = [...state.events, event];\n    return {\n      ...state,\n      events:\n        events.length > this.maxEvents ? events.slice(-this.maxEvents) : events,\n    };\n  }\n\n  private getOrCreateAssistantMessage(state: RealtimeState): {\n    state: RealtimeState;\n    messageId: string;\n  } {\n    if (this.currentAssistantMessageId != null) {\n      return { state, messageId: this.currentAssistantMessageId };\n    }\n\n    const messageId = `assistant-${Date.now()}-${Math.random()\n      .toString(36)\n      .slice(2, 6)}`;\n    this.currentAssistantMessageId = messageId;\n\n    return {\n      state: {\n        ...state,\n        messages: [\n          ...state.messages,\n          {\n            id: messageId,\n            role: 'assistant',\n            parts: [],\n          },\n        ],\n      },\n      messageId,\n    };\n  }\n\n  private addInputTranscriptionMessage(\n    state: RealtimeState,\n    itemId: string,\n    transcript: string,\n  ): RealtimeState {\n    const messageId = `user-${itemId}`;\n    const existingMessage = state.messages.find(\n      message => message.id === messageId,\n    );\n\n    if (existingMessage != null) {\n      return {\n        ...state,\n        messages: state.messages.map(message =>\n          message.id === messageId\n            ? {\n                ...message,\n                parts: [\n                  {\n                    type: 'text',\n                    text: transcript,\n                    state: 'done',\n                  } as TextUIPart,\n                ],\n              }\n            : message,\n        ),\n      };\n    }\n\n    const insertIndex = Math.min(\n      this.inputAudioMessageInsertIndex.get(itemId) ?? state.messages.length,\n      state.messages.length,\n    );\n\n    const messages = [...state.messages];\n    messages.splice(insertIndex, 0, {\n      id: messageId,\n      role: 'user',\n      parts: [\n        {\n          type: 'text',\n          text: transcript,\n          state: 'done',\n        } as TextUIPart,\n      ],\n    });\n\n    return {\n      ...state,\n      messages,\n    };\n  }\n\n  private appendTextDelta(\n    state: RealtimeState,\n    itemId: string,\n    delta: string,\n  ): RealtimeState {\n    const { state: stateWithMessage, messageId } =\n      this.getOrCreateAssistantMessage(state);\n\n    const acc = this.textAccumulators.get(itemId) ?? '';\n    const text = acc + delta;\n    this.textAccumulators.set(itemId, text);\n\n    const location = this.itemIdToPartLocation.get(itemId);\n    if (location != null) {\n      return this.updateMessagePart(\n        stateWithMessage,\n        location.messageId,\n        location.partIndex,\n        { type: 'text', text, state: 'streaming' } as TextUIPart,\n      );\n    }\n\n    return {\n      ...stateWithMessage,\n      messages: stateWithMessage.messages.map(message => {\n        if (message.id !== messageId) return message;\n\n        const partIndex = message.parts.length;\n        this.itemIdToPartLocation.set(itemId, { messageId, partIndex });\n\n        return {\n          ...message,\n          parts: [\n            ...message.parts,\n            { type: 'text', text, state: 'streaming' } as TextUIPart,\n          ],\n        };\n      }),\n    };\n  }\n\n  private finalizeText(\n    state: RealtimeState,\n    itemId: string,\n    finalText?: string,\n  ): RealtimeState {\n    const text = finalText ?? this.textAccumulators.get(itemId) ?? '';\n    this.textAccumulators.delete(itemId);\n\n    const location = this.itemIdToPartLocation.get(itemId);\n    if (location == null) return state;\n\n    this.itemIdToPartLocation.delete(itemId);\n\n    return this.updateMessagePart(\n      state,\n      location.messageId,\n      location.partIndex,\n      { type: 'text', text, state: 'done' } as TextUIPart,\n    );\n  }\n\n  private ensureToolPart(\n    state: RealtimeState,\n    messageId: string,\n    callId: string,\n  ): RealtimeState {\n    return {\n      ...state,\n      messages: state.messages.map(message => {\n        if (message.id !== messageId) return message;\n\n        const existingPart = message.parts.find(\n          part =>\n            part.type === 'dynamic-tool' &&\n            (part as DynamicToolUIPart).toolCallId === callId,\n        );\n        if (existingPart != null) return message;\n\n        return {\n          ...message,\n          parts: [\n            ...message.parts,\n            {\n              type: 'dynamic-tool',\n              toolName: '',\n              toolCallId: callId,\n              state: 'input-streaming',\n              input: undefined,\n            } as DynamicToolUIPart,\n          ],\n        };\n      }),\n    };\n  }\n\n  private markToolInputAvailable(\n    state: RealtimeState,\n    messageId: string,\n    callId: string,\n    name: string,\n    input: Record<string, unknown>,\n  ): RealtimeState {\n    return {\n      ...state,\n      messages: state.messages.map(message => {\n        if (message.id !== messageId) return message;\n\n        return {\n          ...message,\n          parts: message.parts.map(part => {\n            if (part.type !== 'dynamic-tool') return part;\n            const toolPart = part as DynamicToolUIPart;\n            if (toolPart.toolCallId !== callId) return part;\n\n            return {\n              ...toolPart,\n              toolName: name,\n              state: 'input-available',\n              input,\n            } as DynamicToolUIPart;\n          }),\n        };\n      }),\n    };\n  }\n\n  private updateToolPartState(\n    state: RealtimeState,\n    callId: string,\n    result: unknown,\n  ): RealtimeState {\n    const messageId = this.toolCallIdToMessageId.get(callId);\n    if (messageId == null) return state;\n\n    return {\n      ...state,\n      messages: state.messages.map(message => {\n        if (message.id !== messageId) return message;\n\n        return {\n          ...message,\n          parts: message.parts.map(part => {\n            if (part.type !== 'dynamic-tool') return part;\n            const toolPart = part as DynamicToolUIPart;\n            if (toolPart.toolCallId !== callId) return part;\n\n            return {\n              ...toolPart,\n              state: 'output-available',\n              output: result,\n            } as DynamicToolUIPart;\n          }),\n        };\n      }),\n    };\n  }\n\n  private updateMessagePart(\n    state: RealtimeState,\n    messageId: string,\n    partIndex: number,\n    part: TextUIPart,\n  ): RealtimeState {\n    return {\n      ...state,\n      messages: state.messages.map(message => {\n        if (message.id !== messageId) return message;\n\n        const parts = [...message.parts];\n        parts[partIndex] = part;\n\n        return { ...message, parts };\n      }),\n    };\n  }\n}\n","import {\n  type Experimental_EvaluationModelV4 as EvaluationModelV4,\n  type EmbeddingModelV4,\n  type Experimental_VideoModelV4,\n  type FilesV4,\n  type ImageModelV4,\n  type LanguageModelV4,\n  NoSuchModelError,\n  type ProviderV2,\n  type ProviderV3,\n  type ProviderV4,\n  type RerankingModelV4,\n  type SkillsV4,\n  type SpeechModelV4,\n  type TranscriptionModelV4,\n} from '@ai-sdk/provider';\nimport type { EvaluationModel } from '../evaluate/evaluation-result';\nimport type { EvaluationProvider } from '../evaluate/evaluation-provider';\nimport { asProviderV4 } from '../model/as-provider-v4';\nimport {\n  resolveEmbeddingModel,\n  resolveImageModel,\n  resolveLanguageModel,\n  resolveRerankingModel,\n  resolveSpeechModel,\n  resolveTranscriptionModel,\n  resolveVideoModel,\n  resolveEvaluationModel,\n} from '../model/resolve-model';\nimport type { EmbeddingModel } from '../types/embedding-model';\nimport type { ImageModel } from '../types/image-model';\nimport type { LanguageModel } from '../types/language-model';\nimport type { RerankingModel } from '../types/reranking-model';\nimport type { SpeechModel } from '../types/speech-model';\nimport type { TranscriptionModel } from '../types/transcription-model';\nimport type { VideoModel } from '../types/video-model';\n\n/**\n * Creates a custom provider with specified language models, text embedding models, image models, transcription models, speech models, file APIs, skill APIs, and an optional fallback provider.\n *\n * @param {Object} options - The options for creating the custom provider.\n * @param {Record<string, LanguageModel>} [options.languageModels] - A record of language models, where keys are model IDs and values are language model instances.\n * @param {Record<string, EmbeddingModel>} [options.embeddingModels] - A record of text embedding models, where keys are model IDs and values are embedding model instances.\n * @param {Record<string, ImageModel>} [options.imageModels] - A record of image models, where keys are model IDs and values are image model instances.\n * @param {Record<string, TranscriptionModel>} [options.transcriptionModels] - A record of transcription models, where keys are model IDs and values are transcription model instances.\n * @param {Record<string, SpeechModel>} [options.speechModels] - A record of speech models, where keys are model IDs and values are speech model instances.\n * @param {Record<string, RerankingModel>} [options.rerankingModels] - A record of reranking models, where keys are model IDs and values are reranking model instances.\n * @param {Record<string, VideoModel>} [options.videoModels] - A record of video models, where keys are model IDs and values are video model instances.\n * @param {Record<string, EvaluationModel>} [options.evaluationModels] - Experimental evaluation models or default-provider model IDs, keyed by alias.\n * @param {FilesV4} [options.files] - A files interface for uploading files.\n * @param {SkillsV4} [options.skills] - A skills interface for uploading skills.\n * @param {ProviderV2 | ProviderV3 | ProviderV4} [options.fallbackProvider] - An optional fallback provider to use when a requested model is not found in the custom provider.\n * @returns {ProviderV4} A ProviderV4 object with languageModel, embeddingModel, imageModel, transcriptionModel, speechModel, rerankingModel, and videoModel methods.\n *\n * @throws {NoSuchModelError} Throws when a requested model is not found and no fallback provider is available.\n */\nexport function customProvider<\n  LANGUAGE_MODELS extends Record<string, LanguageModel>,\n  EMBEDDING_MODELS extends Record<string, EmbeddingModel>,\n  IMAGE_MODELS extends Record<string, ImageModel>,\n  TRANSCRIPTION_MODELS extends Record<string, TranscriptionModel>,\n  SPEECH_MODELS extends Record<string, SpeechModel>,\n  RERANKING_MODELS extends Record<string, RerankingModel>,\n  VIDEO_MODELS extends Record<string, VideoModel>,\n  FILES extends FilesV4 | undefined = undefined,\n  SKILLS extends SkillsV4 | undefined = undefined,\n  FALLBACK extends ProviderV2 | ProviderV3 | ProviderV4 | undefined = undefined,\n  EVALUATION_MODELS extends Record<string, EvaluationModel> = Record<\n    string,\n    EvaluationModel\n  >,\n>({\n  languageModels,\n  embeddingModels,\n  imageModels,\n  transcriptionModels,\n  speechModels,\n  rerankingModels,\n  videoModels,\n  evaluationModels,\n  files,\n  skills,\n  fallbackProvider: fallbackProviderArg,\n}: {\n  languageModels?: LANGUAGE_MODELS;\n  embeddingModels?: EMBEDDING_MODELS;\n  imageModels?: IMAGE_MODELS;\n  transcriptionModels?: TRANSCRIPTION_MODELS;\n  speechModels?: SPEECH_MODELS;\n  rerankingModels?: RERANKING_MODELS;\n  videoModels?: VIDEO_MODELS;\n  evaluationModels?: EVALUATION_MODELS;\n  files?: FILES;\n  skills?: SKILLS;\n  fallbackProvider?: FALLBACK;\n}): ProviderV4 & {\n  languageModel(modelId: ExtractModelId<LANGUAGE_MODELS>): LanguageModelV4;\n  embeddingModel(modelId: ExtractModelId<EMBEDDING_MODELS>): EmbeddingModelV4;\n  imageModel(modelId: ExtractModelId<IMAGE_MODELS>): ImageModelV4;\n  transcriptionModel(\n    modelId: ExtractModelId<TRANSCRIPTION_MODELS>,\n  ): TranscriptionModelV4;\n  rerankingModel(modelId: ExtractModelId<RERANKING_MODELS>): RerankingModelV4;\n  speechModel(modelId: ExtractModelId<SPEECH_MODELS>): SpeechModelV4;\n  videoModel(modelId: ExtractModelId<VIDEO_MODELS>): Experimental_VideoModelV4;\n  evaluationModel(\n    modelId: ExtractModelId<EVALUATION_MODELS>,\n  ): EvaluationModelV4;\n} & (FILES extends FilesV4\n    ? { files(): FilesV4 }\n    : [FALLBACK] extends [{ files: () => FilesV4 }]\n      ? { files(): FilesV4 }\n      : { files?(): FilesV4 }) &\n  (SKILLS extends SkillsV4\n    ? { skills(): SkillsV4 }\n    : [FALLBACK] extends [{ skills: () => SkillsV4 }]\n      ? { skills(): SkillsV4 }\n      : { skills?(): SkillsV4 }) {\n  const fallbackProvider =\n    fallbackProviderArg == null ? undefined : asProviderV4(fallbackProviderArg);\n\n  const baseProvider: ProviderV4 & {\n    languageModel(modelId: ExtractModelId<LANGUAGE_MODELS>): LanguageModelV4;\n    embeddingModel(modelId: ExtractModelId<EMBEDDING_MODELS>): EmbeddingModelV4;\n    imageModel(modelId: ExtractModelId<IMAGE_MODELS>): ImageModelV4;\n    transcriptionModel(\n      modelId: ExtractModelId<TRANSCRIPTION_MODELS>,\n    ): TranscriptionModelV4;\n    rerankingModel(modelId: ExtractModelId<RERANKING_MODELS>): RerankingModelV4;\n    speechModel(modelId: ExtractModelId<SPEECH_MODELS>): SpeechModelV4;\n    videoModel(\n      modelId: ExtractModelId<VIDEO_MODELS>,\n    ): Experimental_VideoModelV4;\n    evaluationModel(\n      modelId: ExtractModelId<EVALUATION_MODELS>,\n    ): EvaluationModelV4;\n  } = {\n    specificationVersion: 'v4',\n    languageModel(modelId: ExtractModelId<LANGUAGE_MODELS>): LanguageModelV4 {\n      if (languageModels != null && modelId in languageModels) {\n        return resolveLanguageModel(languageModels[modelId]);\n      }\n\n      if (fallbackProvider) {\n        return fallbackProvider.languageModel(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'languageModel' });\n    },\n\n    embeddingModel(\n      modelId: ExtractModelId<EMBEDDING_MODELS>,\n    ): EmbeddingModelV4 {\n      if (embeddingModels != null && modelId in embeddingModels) {\n        return resolveEmbeddingModel(embeddingModels[modelId]);\n      }\n\n      if (fallbackProvider) {\n        return fallbackProvider.embeddingModel(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'embeddingModel' });\n    },\n\n    imageModel(modelId: ExtractModelId<IMAGE_MODELS>): ImageModelV4 {\n      if (imageModels != null && modelId in imageModels) {\n        return resolveImageModel(imageModels[modelId]);\n      }\n\n      if (fallbackProvider?.imageModel) {\n        return fallbackProvider.imageModel(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'imageModel' });\n    },\n\n    transcriptionModel(\n      modelId: ExtractModelId<TRANSCRIPTION_MODELS>,\n    ): TranscriptionModelV4 {\n      if (transcriptionModels != null && modelId in transcriptionModels) {\n        const model = resolveTranscriptionModel(transcriptionModels[modelId]);\n\n        if (model != null) {\n          return model;\n        }\n      }\n\n      if (fallbackProvider?.transcriptionModel) {\n        return fallbackProvider.transcriptionModel(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'transcriptionModel' });\n    },\n\n    speechModel(modelId: ExtractModelId<SPEECH_MODELS>): SpeechModelV4 {\n      if (speechModels != null && modelId in speechModels) {\n        const model = resolveSpeechModel(speechModels[modelId]);\n\n        if (model != null) {\n          return model;\n        }\n      }\n\n      if (fallbackProvider?.speechModel) {\n        return fallbackProvider.speechModel(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'speechModel' });\n    },\n    rerankingModel(\n      modelId: ExtractModelId<RERANKING_MODELS>,\n    ): RerankingModelV4 {\n      if (rerankingModels != null && modelId in rerankingModels) {\n        return resolveRerankingModel(rerankingModels[modelId]);\n      }\n\n      if (fallbackProvider?.rerankingModel) {\n        return fallbackProvider.rerankingModel(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'rerankingModel' });\n    },\n    evaluationModel(\n      modelId: ExtractModelId<EVALUATION_MODELS>,\n    ): EvaluationModelV4 {\n      if (\n        evaluationModels != null &&\n        Object.hasOwn(evaluationModels, modelId)\n      ) {\n        return resolveEvaluationModel(evaluationModels[modelId]);\n      }\n\n      const provider = fallbackProviderArg as EvaluationProvider | undefined;\n      if (typeof provider?.evaluationModel === 'function') {\n        const model = provider.evaluationModel(modelId);\n        if (model != null) {\n          return resolveEvaluationModel(model);\n        }\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'evaluationModel' });\n    },\n    videoModel(\n      modelId: ExtractModelId<VIDEO_MODELS>,\n    ): Experimental_VideoModelV4 {\n      if (videoModels != null && modelId in videoModels) {\n        return resolveVideoModel(videoModels[modelId]);\n      }\n\n      // TODO AI SDK v7\n      // @ts-expect-error - videoModel support is experimental\n      const videoModel = fallbackProvider?.videoModel;\n      if (videoModel) {\n        return videoModel(modelId);\n      }\n\n      throw new NoSuchModelError({ modelId, modelType: 'videoModel' });\n    },\n  };\n\n  const filesAndSkills = {\n    ...(files != null || fallbackProvider?.files != null\n      ? {\n          files(): FilesV4 {\n            return files ?? fallbackProvider!.files!();\n          },\n        }\n      : {}),\n\n    ...(skills != null || fallbackProvider?.skills != null\n      ? {\n          skills(): SkillsV4 {\n            return skills ?? fallbackProvider!.skills!();\n          },\n        }\n      : {}),\n  } as (FILES extends FilesV4\n    ? { files(): FilesV4 }\n    : [FALLBACK] extends [{ files: () => FilesV4 }]\n      ? { files(): FilesV4 }\n      : { files?(): FilesV4 }) &\n    (SKILLS extends SkillsV4\n      ? { skills(): SkillsV4 }\n      : [FALLBACK] extends [{ skills: () => SkillsV4 }]\n        ? { skills(): SkillsV4 }\n        : { skills?(): SkillsV4 });\n\n  return Object.assign(baseProvider, filesAndSkills);\n}\n\ntype ExtractModelId<MODELS extends Record<string, unknown>> = Extract<\n  keyof MODELS,\n  string\n>;\n","import { AISDKError, NoSuchModelError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoSuchProviderError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchProviderError extends NoSuchModelError {\n  private readonly [symbol] = true; // used in isInstance\n\n  readonly providerId: string;\n  readonly availableProviders: string[];\n\n  constructor({\n    modelId,\n    modelType,\n    providerId,\n    availableProviders,\n    message = `No such provider: ${providerId} (available providers: ${availableProviders.join()})`,\n  }: {\n    modelId: string;\n    modelType:\n      | 'languageModel'\n      | 'embeddingModel'\n      | 'imageModel'\n      | 'transcriptionModel'\n      | 'speechModel'\n      | 'rerankingModel'\n      | 'videoModel'\n      | 'evaluationModel';\n    providerId: string;\n    availableProviders: string[];\n    message?: string;\n  }) {\n    super({ errorName: name, modelId, modelType, message });\n\n    this.providerId = providerId;\n    this.availableProviders = availableProviders;\n  }\n\n  static isInstance(error: unknown): error is NoSuchProviderError {\n    return AISDKError.hasMarker(error, marker);\n  }\n}\n","import {\n  type Experimental_EvaluationModelV4 as EvaluationModelV4,\n  type EmbeddingModelV4,\n  type Experimental_VideoModelV3,\n  type Experimental_VideoModelV4,\n  type FilesV4,\n  type ImageModelV4,\n  type LanguageModelV4,\n  NoSuchModelError,\n  type ProviderV3,\n  type ProviderV4,\n  type RerankingModelV4,\n  type SkillsV4,\n  type SpeechModelV4,\n  type TranscriptionModelV4,\n} from '@ai-sdk/provider';\nimport type { EvaluationProvider } from '../evaluate/evaluation-provider';\nimport { resolveEvaluationModel } from '../model/resolve-model';\nimport { wrapImageModel } from '../middleware/wrap-image-model';\nimport { wrapLanguageModel } from '../middleware/wrap-language-model';\nimport { asProviderV4 } from '../model/as-provider-v4';\nimport { asVideoModelV4 } from '../model/as-video-model-v4';\nimport type { ImageModelMiddleware, LanguageModelMiddleware } from '../types';\nimport type { ExtractLiteralUnion } from '../util/extract-literal-union';\nimport { NoSuchProviderError } from './no-such-provider-error';\n\ntype ProviderWithOptionalVideoModel = {\n  videoModel?: (\n    modelId: string,\n  ) => Experimental_VideoModelV3 | Experimental_VideoModelV4;\n};\n\ntype RegistryModelType =\n  | 'languageModel'\n  | 'embeddingModel'\n  | 'imageModel'\n  | 'transcriptionModel'\n  | 'speechModel'\n  | 'rerankingModel'\n  | 'videoModel'\n  | 'evaluationModel';\n\ntype ProviderVideoModelIdentifier<PROVIDER> = PROVIDER extends {\n  videoModel: (...args: infer ARGS) => unknown;\n}\n  ? ExtractLiteralUnion<ARGS[0]>\n  : never;\n\ntype ProviderEvaluationModelIdentifier<PROVIDER> = PROVIDER extends {\n  evaluationModel: (...args: infer ARGS) => unknown;\n}\n  ? ExtractLiteralUnion<ARGS[0]>\n  : never;\n\n/** Registry with experimental evaluation access, separate from the stable interface. */\nexport type EvaluationProviderRegistry<\n  PROVIDERS extends Record<string, ProviderV4 | ProviderV3> = Record<\n    string,\n    ProviderV4 | ProviderV3\n  >,\n  SEPARATOR extends string = ':',\n> = ProviderRegistryProvider<PROVIDERS, SEPARATOR> & {\n  evaluationModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ProviderEvaluationModelIdentifier<PROVIDERS[KEY]>}`\n      : never,\n  ): EvaluationModelV4;\n  evaluationModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): EvaluationModelV4;\n};\n\nexport interface ProviderRegistryProvider<\n  PROVIDERS extends Record<string, ProviderV4 | ProviderV3> = Record<\n    string,\n    ProviderV4 | ProviderV3\n  >,\n  SEPARATOR extends string = ':',\n> {\n  languageModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['languageModel']>>[0]>}`\n      : never,\n  ): LanguageModelV4;\n  languageModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): LanguageModelV4;\n\n  embeddingModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['embeddingModel']>>[0]>}`\n      : never,\n  ): EmbeddingModelV4;\n  embeddingModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): EmbeddingModelV4;\n\n  imageModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['imageModel']>>[0]>}`\n      : never,\n  ): ImageModelV4;\n  imageModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): ImageModelV4;\n\n  transcriptionModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['transcriptionModel']>>[0]>}`\n      : never,\n  ): TranscriptionModelV4;\n  transcriptionModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): TranscriptionModelV4;\n\n  speechModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['speechModel']>>[0]>}`\n      : never,\n  ): SpeechModelV4;\n  speechModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): SpeechModelV4;\n\n  rerankingModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['rerankingModel']>>[0]>}`\n      : never,\n  ): RerankingModelV4;\n  rerankingModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): RerankingModelV4;\n\n  videoModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string\n      ? `${KEY & string}${SEPARATOR}${ProviderVideoModelIdentifier<PROVIDERS[KEY]>}`\n      : never,\n  ): Experimental_VideoModelV4;\n  videoModel<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,\n  ): Experimental_VideoModelV4;\n\n  files<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? KEY & string : never,\n  ): FilesV4;\n\n  skills<KEY extends keyof PROVIDERS>(\n    id: KEY extends string ? KEY & string : never,\n  ): SkillsV4;\n}\n\n/**\n * Creates a registry for the given providers with optional middleware functionality.\n * This function allows you to register multiple providers and optionally apply middleware\n * to all language models from the registry, enabling you to transform parameters, wrap generate\n * operations, and wrap stream operations for every language model accessed through the registry.\n *\n * @param providers - A record of provider instances to be registered in the registry.\n * @param options - Configuration options for the provider registry.\n * @param options.separator - The separator used between provider ID and model ID in the combined identifier. Defaults to ':'.\n * @param options.languageModelMiddleware - Optional middleware to be applied to all language models from the registry. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @param options.imageModelMiddleware - Optional middleware to be applied to all image models from the registry. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.\n * @returns A new ProviderRegistryProvider instance that provides access to all registered providers with optional middleware applied to language and image models.\n */\nexport function createProviderRegistry<\n  PROVIDERS extends Record<string, ProviderV4 | ProviderV3>,\n  SEPARATOR extends string = ':',\n>(\n  providers: PROVIDERS,\n  {\n    separator = ':' as SEPARATOR,\n    languageModelMiddleware,\n    imageModelMiddleware,\n  }: {\n    separator?: SEPARATOR;\n    languageModelMiddleware?:\n      | LanguageModelMiddleware\n      | LanguageModelMiddleware[];\n    imageModelMiddleware?: ImageModelMiddleware | ImageModelMiddleware[];\n  } = {},\n): EvaluationProviderRegistry<PROVIDERS, SEPARATOR> {\n  const registry = new DefaultProviderRegistry<PROVIDERS, SEPARATOR>({\n    separator,\n    languageModelMiddleware,\n    imageModelMiddleware,\n  });\n\n  for (const [id, provider] of Object.entries(providers)) {\n    registry.registerProvider({ id, provider } as {\n      id: keyof PROVIDERS;\n      provider: PROVIDERS[keyof PROVIDERS];\n    });\n  }\n\n  return registry;\n}\n\n/**\n * @deprecated Use `createProviderRegistry` instead.\n */\nexport const experimental_createProviderRegistry = createProviderRegistry;\n\nclass DefaultProviderRegistry<\n  PROVIDERS extends Record<string, ProviderV4 | ProviderV3>,\n  SEPARATOR extends string,\n>\n  implements\n    ProviderRegistryProvider<PROVIDERS, SEPARATOR>,\n    EvaluationProviderRegistry<PROVIDERS, SEPARATOR>\n{\n  private providers: Partial<\n    Record<\n      keyof PROVIDERS,\n      ProviderV4 & ProviderWithOptionalVideoModel & EvaluationProvider\n    >\n  > = {};\n  private separator: SEPARATOR;\n  private languageModelMiddleware?:\n    | LanguageModelMiddleware\n    | LanguageModelMiddleware[];\n  private imageModelMiddleware?: ImageModelMiddleware | ImageModelMiddleware[];\n\n  constructor({\n    separator,\n    languageModelMiddleware,\n    imageModelMiddleware,\n  }: {\n    separator: SEPARATOR;\n    languageModelMiddleware?:\n      | LanguageModelMiddleware\n      | LanguageModelMiddleware[];\n    imageModelMiddleware?: ImageModelMiddleware | ImageModelMiddleware[];\n  }) {\n    this.separator = separator;\n    this.languageModelMiddleware = languageModelMiddleware;\n    this.imageModelMiddleware = imageModelMiddleware;\n  }\n\n  registerProvider<K extends keyof PROVIDERS>({\n    id,\n    provider,\n  }: {\n    id: K;\n    provider: PROVIDERS[K];\n  }): void {\n    const providerV4 = asProviderV4(provider);\n    const videoModel = (\n      provider as ProviderWithOptionalVideoModel\n    ).videoModel?.bind(provider);\n\n    const evaluationModel = (\n      provider as EvaluationProvider\n    ).evaluationModel?.bind(provider);\n\n    const registeredProvider =\n      videoModel == null\n        ? providerV4\n        : Object.assign(Object.create(Object.getPrototypeOf(providerV4)), {\n            ...providerV4,\n            videoModel: (modelId: string) =>\n              asVideoModelV4(videoModel(modelId)),\n          });\n\n    // Keep v4 instances intact. Adapted providers need the original evaluation receiver.\n    if (registeredProvider !== provider && evaluationModel != null) {\n      Object.assign(registeredProvider, { evaluationModel });\n    }\n    this.providers[id] = registeredProvider;\n  }\n\n  private getProvider(\n    id: string,\n    modelType: RegistryModelType,\n  ): ProviderV4 & ProviderWithOptionalVideoModel & EvaluationProvider {\n    const provider = this.providers[id as keyof PROVIDERS];\n\n    if (provider == null) {\n      throw new NoSuchProviderError({\n        modelId: id,\n        modelType,\n        providerId: id,\n        availableProviders: Object.keys(this.providers),\n      });\n    }\n\n    return provider;\n  }\n\n  private splitId(id: string, modelType: RegistryModelType): [string, string] {\n    const index = id.indexOf(this.separator);\n\n    if (index === -1) {\n      throw new NoSuchModelError({\n        modelId: id,\n        modelType,\n        message:\n          `Invalid ${modelType} id for registry: ${id} ` +\n          `(must be in the format \"providerId${this.separator}modelId\")`,\n      });\n    }\n\n    return [id.slice(0, index), id.slice(index + this.separator.length)];\n  }\n\n  languageModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): LanguageModelV4 {\n    const [providerId, modelId] = this.splitId(id, 'languageModel');\n    let model = this.getProvider(providerId, 'languageModel').languageModel?.(\n      modelId,\n    );\n\n    if (model == null) {\n      throw new NoSuchModelError({ modelId: id, modelType: 'languageModel' });\n    }\n\n    if (this.languageModelMiddleware != null) {\n      model = wrapLanguageModel({\n        model,\n        middleware: this.languageModelMiddleware,\n      });\n    }\n\n    return model;\n  }\n\n  embeddingModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): EmbeddingModelV4 {\n    const [providerId, modelId] = this.splitId(id, 'embeddingModel');\n    const provider = this.getProvider(providerId, 'embeddingModel');\n\n    const model = provider.embeddingModel?.(modelId);\n\n    if (model == null) {\n      throw new NoSuchModelError({\n        modelId: id,\n        modelType: 'embeddingModel',\n      });\n    }\n\n    return model;\n  }\n\n  imageModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): ImageModelV4 {\n    const [providerId, modelId] = this.splitId(id, 'imageModel');\n    const provider = this.getProvider(providerId, 'imageModel');\n\n    let model = provider.imageModel?.(modelId);\n\n    if (model == null) {\n      throw new NoSuchModelError({ modelId: id, modelType: 'imageModel' });\n    }\n\n    if (this.imageModelMiddleware != null) {\n      model = wrapImageModel({\n        model,\n        middleware: this.imageModelMiddleware,\n      });\n    }\n\n    return model;\n  }\n\n  transcriptionModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): TranscriptionModelV4 {\n    const [providerId, modelId] = this.splitId(id, 'transcriptionModel');\n    const provider = this.getProvider(providerId, 'transcriptionModel');\n\n    const model = provider.transcriptionModel?.(modelId);\n\n    if (model == null) {\n      throw new NoSuchModelError({\n        modelId: id,\n        modelType: 'transcriptionModel',\n      });\n    }\n\n    return model;\n  }\n\n  speechModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): SpeechModelV4 {\n    const [providerId, modelId] = this.splitId(id, 'speechModel');\n    const provider = this.getProvider(providerId, 'speechModel');\n\n    const model = provider.speechModel?.(modelId);\n\n    if (model == null) {\n      throw new NoSuchModelError({ modelId: id, modelType: 'speechModel' });\n    }\n\n    return model;\n  }\n\n  rerankingModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): RerankingModelV4 {\n    const [providerId, modelId] = this.splitId(id, 'rerankingModel');\n    const provider = this.getProvider(providerId, 'rerankingModel');\n\n    const model = provider.rerankingModel?.(modelId);\n\n    if (model == null) {\n      throw new NoSuchModelError({ modelId: id, modelType: 'rerankingModel' });\n    }\n\n    return model;\n  }\n\n  videoModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): Experimental_VideoModelV4 {\n    const [providerId, modelId] = this.splitId(id, 'videoModel');\n    const provider = this.getProvider(providerId, 'videoModel');\n\n    const model = provider.videoModel?.(modelId);\n\n    if (model == null) {\n      throw new NoSuchModelError({ modelId: id, modelType: 'videoModel' });\n    }\n\n    return asVideoModelV4(model);\n  }\n\n  evaluationModel<KEY extends keyof PROVIDERS>(\n    id: `${KEY & string}${SEPARATOR}${string}`,\n  ): EvaluationModelV4 {\n    const [providerId, modelId] = this.splitId(id, 'evaluationModel');\n    const provider = this.getProvider(providerId, 'evaluationModel');\n    const model = provider.evaluationModel?.(modelId);\n\n    if (model == null) {\n      throw new NoSuchModelError({ modelId: id, modelType: 'evaluationModel' });\n    }\n\n    return resolveEvaluationModel(model);\n  }\n\n  files<KEY extends keyof PROVIDERS>(id: KEY & string): FilesV4 {\n    const provider = this.getProvider(id, 'languageModel');\n    const files = provider.files?.();\n\n    if (files == null) {\n      throw new Error(\n        `The provider \"${id}\" does not support file uploads. Make sure it exposes a files() method.`,\n      );\n    }\n\n    return files;\n  }\n\n  skills<KEY extends keyof PROVIDERS>(id: KEY & string): SkillsV4 {\n    const provider = this.getProvider(id, 'languageModel');\n    const skills = provider.skills?.();\n\n    if (skills == null) {\n      throw new Error(\n        `The provider \"${id}\" does not support skills. Make sure it exposes a skills() method.`,\n      );\n    }\n\n    return skills;\n  }\n}\n","import {\n  InvalidResponseDataError,\n  type JSONObject,\n  type RerankingModelV4CallOptions,\n  type RerankingModelV4Result,\n} from '@ai-sdk/provider';\nimport {\n  createIdGenerator,\n  type Context,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { prepareRetries } from '../../src/util/prepare-retries';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveRerankingModel } from '../model/resolve-model';\nimport { createRestrictedTelemetryDispatcher } from './restricted-telemetry-dispatcher';\nimport type { TelemetryOptions } from '../telemetry/telemetry-options';\nimport type { RerankingModel } from '../types';\nimport type { Callback } from '../util/callback';\nimport { notify } from '../util/notify';\nimport type { RerankEndEvent, RerankStartEvent } from './rerank-events';\nimport type { RerankResult } from './rerank-result';\n\nconst originalGenerateCallId = createIdGenerator({\n  prefix: 'call',\n  size: 24,\n});\n\n/**\n * Rerank documents using a reranking model. The type of the value is defined by the reranking model.\n *\n * @param model - The reranking model to use.\n * @param documents - The documents that should be reranked.\n * @param query - The query to rerank the documents against.\n * @param topN - Number of top documents to return.\n *\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n * @param providerOptions - Additional provider-specific options.\n * @param telemetry - Optional telemetry configuration.\n * @param runtimeContext - User-defined runtime context passed to callbacks and, when explicitly included, telemetry.\n *\n * @returns A result object that contains the reranked documents, the reranked indices, and additional information.\n */\nexport async function rerank<\n  VALUE extends JSONObject | string,\n  RUNTIME_CONTEXT extends Context = Context,\n>({\n  model: modelArg,\n  documents,\n  query,\n  topN,\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  providerOptions,\n  experimental_telemetry,\n  telemetry = experimental_telemetry,\n  runtimeContext = {} as RUNTIME_CONTEXT,\n  onStart,\n  experimental_onStart,\n  onEnd,\n  experimental_onEnd,\n  _internal: { generateCallId = originalGenerateCallId } = {},\n}: {\n  /**\n   * The reranking model to use.\n   */\n  model: RerankingModel;\n\n  /**\n   * The documents that should be reranked.\n   */\n  documents: Array<VALUE>;\n\n  /**\n   * The query to rerank the documents against.\n   */\n  query: string;\n\n  /**\n   * Number of top documents to return.\n   */\n  topN?: number;\n\n  /**\n   * Maximum number of retries per reranking model call. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * Optional telemetry configuration.\n   */\n  telemetry?: TelemetryOptions<RUNTIME_CONTEXT>;\n\n  /**\n   * Optional telemetry configuration.\n   *\n   * @deprecated Use `telemetry` instead. This alias will be removed in a future major release.\n   */\n  experimental_telemetry?: TelemetryOptions<RUNTIME_CONTEXT>;\n\n  /**\n   * User-defined runtime context. Treat runtime context as immutable.\n   */\n  runtimeContext?: RUNTIME_CONTEXT;\n\n  /**\n   * Additional provider-specific options. They are passed through\n   * to the provider from the AI SDK and enable provider-specific\n   * functionality that can be fully encapsulated in the provider.\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Callback that is called when the rerank operation begins,\n   * before the reranking model is called.\n   */\n  onStart?: Callback<RerankStartEvent<RUNTIME_CONTEXT>>;\n\n  /**\n   * Callback that is called when the rerank operation begins,\n   * before the reranking model is called.\n   *\n   * @deprecated Use `onStart` instead.\n   */\n  experimental_onStart?: Callback<RerankStartEvent<RUNTIME_CONTEXT>>;\n\n  /**\n   * Callback that is called when the rerank operation completes,\n   * after the reranking model returns.\n   */\n  onEnd?: Callback<RerankEndEvent<RUNTIME_CONTEXT>>;\n\n  /**\n   * Callback that is called when the rerank operation completes,\n   * after the reranking model returns.\n   *\n   * @deprecated Use `onEnd` instead.\n   */\n  experimental_onEnd?: Callback<RerankEndEvent<RUNTIME_CONTEXT>>;\n\n  /**\n   * Internal. For test use only. May change without notice.\n   */\n  _internal?: {\n    generateCallId?: () => string;\n  };\n}): Promise<RerankResult<VALUE>> {\n  const model = resolveRerankingModel(modelArg);\n  const callId = generateCallId();\n  const resolvedOnStart = onStart ?? experimental_onStart;\n  const resolvedOnEnd = onEnd ?? experimental_onEnd;\n\n  const telemetryDispatcher = createRestrictedTelemetryDispatcher({\n    telemetry,\n  });\n\n  const runInTracingChannelSpan =\n    telemetryDispatcher.runInTracingChannelSpan ??\n    (async <T>({ execute }: { execute: () => PromiseLike<T> }) =>\n      await execute());\n\n  if (documents.length === 0) {\n    await notify({\n      event: {\n        callId,\n        operationId: 'ai.rerank',\n        runtimeContext,\n        provider: model.provider,\n        modelId: model.modelId,\n        documents,\n        query,\n        topN,\n        maxRetries: maxRetriesArg ?? 2,\n        headers,\n        providerOptions,\n      },\n      callbacks: [resolvedOnStart, telemetryDispatcher.onStart],\n    });\n\n    await notify({\n      event: {\n        callId,\n        operationId: 'ai.rerank',\n        runtimeContext,\n        provider: model.provider,\n        modelId: model.modelId,\n        documents,\n        query,\n        ranking: [],\n        warnings: [],\n        providerMetadata: undefined,\n        response: {\n          timestamp: new Date(),\n          modelId: model.modelId,\n        },\n      },\n      callbacks: [resolvedOnEnd, telemetryDispatcher.onEnd],\n    });\n\n    return new DefaultRerankResult({\n      originalDocuments: [],\n      ranking: [],\n      providerMetadata: undefined,\n      response: {\n        timestamp: new Date(),\n        modelId: model.modelId,\n      },\n    });\n  }\n\n  const { maxRetries, retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  const documentsToSend: RerankingModelV4CallOptions['documents'] =\n    typeof documents[0] === 'string'\n      ? { type: 'text', values: documents as string[] }\n      : { type: 'object', values: documents as JSONObject[] };\n\n  const startEvent = {\n    callId,\n    operationId: 'ai.rerank',\n    runtimeContext,\n    provider: model.provider,\n    modelId: model.modelId,\n    documents,\n    query,\n    topN,\n    maxRetries,\n    headers,\n    providerOptions,\n  };\n\n  return await runInTracingChannelSpan({\n    type: 'rerank',\n    event: startEvent,\n    execute: async () => {\n      await notify({\n        event: startEvent,\n        callbacks: [resolvedOnStart, telemetryDispatcher.onStart],\n      });\n\n      try {\n        const { ranking, response, providerMetadata, warnings } = await retry(\n          async () => {\n            await notify({\n              event: {\n                callId,\n                operationId: 'ai.rerank.doRerank',\n                provider: model.provider,\n                modelId: model.modelId,\n                documents,\n                documentsType: documentsToSend.type,\n                query,\n                topN,\n              },\n              callbacks: [telemetryDispatcher.onRerankStart],\n            });\n\n            const modelResponse = await model.doRerank({\n              documents: documentsToSend,\n              query,\n              topN,\n              providerOptions,\n              abortSignal,\n              headers,\n            });\n\n            const ranking = modelResponse.ranking;\n\n            await notify({\n              event: {\n                callId,\n                operationId: 'ai.rerank.doRerank',\n                provider: model.provider,\n                modelId: model.modelId,\n                documentsType: documentsToSend.type,\n                ranking,\n              },\n              callbacks: [telemetryDispatcher.onRerankEnd],\n            });\n\n            return {\n              ranking,\n              providerMetadata: modelResponse.providerMetadata,\n              response: modelResponse.response,\n              warnings: modelResponse.warnings,\n            };\n          },\n        );\n\n        validateRankingIndices({ ranking, documents });\n\n        logWarnings({\n          warnings: warnings ?? [],\n          provider: model.provider,\n          model: model.modelId,\n        });\n\n        await notify({\n          event: {\n            callId,\n            operationId: 'ai.rerank',\n            runtimeContext,\n            provider: model.provider,\n            modelId: model.modelId,\n            documents,\n            query,\n            ranking: ranking.map(ranking => ({\n              originalIndex: ranking.index,\n              score: ranking.relevanceScore,\n              document: documents[ranking.index],\n            })),\n            warnings: warnings ?? [],\n            providerMetadata,\n            response: {\n              id: response?.id,\n              timestamp: response?.timestamp ?? new Date(),\n              modelId: response?.modelId ?? model.modelId,\n              headers: response?.headers,\n              body: response?.body,\n            },\n          },\n          callbacks: [resolvedOnEnd, telemetryDispatcher.onEnd],\n        });\n\n        return new DefaultRerankResult({\n          originalDocuments: documents,\n          ranking: ranking.map(ranking => ({\n            originalIndex: ranking.index,\n            score: ranking.relevanceScore,\n            document: documents[ranking.index],\n          })),\n          providerMetadata,\n          response: {\n            id: response?.id,\n            timestamp: response?.timestamp ?? new Date(),\n            modelId: response?.modelId ?? model.modelId,\n            headers: response?.headers,\n            body: response?.body,\n          },\n        });\n      } catch (error) {\n        await telemetryDispatcher.onError?.({ callId, error });\n        throw error;\n      }\n    },\n  });\n}\n\nfunction validateRankingIndices<VALUE>({\n  ranking,\n  documents,\n}: {\n  ranking: RerankingModelV4Result['ranking'];\n  documents: Array<VALUE>;\n}) {\n  for (const { index } of ranking) {\n    if (!Number.isInteger(index) || index < 0 || index >= documents.length) {\n      throw new InvalidResponseDataError({\n        data: ranking,\n        message: `Invalid ranking index ${index}. Expected an integer between 0 and ${documents.length - 1}.`,\n      });\n    }\n  }\n}\n\nclass DefaultRerankResult<VALUE> implements RerankResult<VALUE> {\n  readonly originalDocuments: RerankResult<VALUE>['originalDocuments'];\n  readonly ranking: RerankResult<VALUE>['ranking'];\n  readonly response: RerankResult<VALUE>['response'];\n  readonly providerMetadata: RerankResult<VALUE>['providerMetadata'];\n\n  constructor(options: {\n    originalDocuments: RerankResult<VALUE>['originalDocuments'];\n    ranking: RerankResult<VALUE>['ranking'];\n    providerMetadata?: RerankResult<VALUE>['providerMetadata'];\n    response: RerankResult<VALUE>['response'];\n  }) {\n    this.originalDocuments = options.originalDocuments;\n    this.ranking = options.ranking;\n    this.response = options.response;\n    this.providerMetadata = options.providerMetadata;\n  }\n\n  get rerankedDocuments(): RerankResult<VALUE>['rerankedDocuments'] {\n    return this.ranking.map(ranking => ranking.document);\n  }\n}\n","import type { Context } from '@ai-sdk/provider-utils';\nimport { createTelemetryDispatcher } from '../telemetry/create-telemetry-dispatcher';\nimport { filterIncludedContext } from '../telemetry/filter-included-context';\nimport type { TelemetryDispatcher } from '../telemetry/telemetry';\nimport type { TelemetryOptions } from '../telemetry/telemetry-options';\nimport type { Callback } from '../util/callback';\nimport type { RerankStartEvent, RerankEndEvent } from './rerank-events';\n\n/**\n * Filters runtime context before sending operation events to telemetry integrations.\n * User callbacks continue to receive the original context.\n */\nexport function createRestrictedTelemetryDispatcher<\n  RUNTIME_CONTEXT extends Context,\n>({\n  telemetry,\n}: {\n  telemetry?: TelemetryOptions<RUNTIME_CONTEXT>;\n}): Omit<TelemetryDispatcher, 'onStart' | 'onEnd'> & {\n  onStart: Callback<RerankStartEvent<RUNTIME_CONTEXT>>;\n  onEnd: Callback<RerankEndEvent<RUNTIME_CONTEXT>>;\n} {\n  const dispatcher = createTelemetryDispatcher({ telemetry });\n\n  return {\n    ...dispatcher,\n    onStart: event =>\n      dispatcher.onStart?.({\n        ...event,\n        runtimeContext: filterIncludedContext({\n          context: event.runtimeContext,\n          includeContext: telemetry?.includeRuntimeContext,\n        }),\n      }),\n    onEnd: event =>\n      dispatcher.onEnd?.({\n        ...event,\n        runtimeContext: filterIncludedContext({\n          context: event.runtimeContext,\n          includeContext: telemetry?.includeRuntimeContext,\n        }),\n      }),\n  };\n}\n","import type { JSONObject } from '@ai-sdk/provider';\nimport {\n  detectMediaType,\n  withUserAgentSuffix,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { NoTranscriptGeneratedError } from '../error/no-transcript-generated-error';\nimport { logWarnings } from '../logger/log-warnings';\nimport type { DataContent } from '../prompt';\nimport { convertDataContentToUint8Array } from '../prompt/data-content';\nimport type { TranscriptionModel } from '../types/transcription-model';\nimport type { TranscriptionModelResponseMetadata } from '../types/transcription-model-response-metadata';\nimport { createDownload } from '../util/download/create-download';\nimport { prepareRetries } from '../util/prepare-retries';\nimport type { TranscriptionResult } from './transcribe-result';\nimport { VERSION } from '../version';\nimport { resolveTranscriptionModel } from '../model/resolve-model';\nimport type { Warning } from '../types';\n/**\n * Generates transcripts using a transcription model.\n *\n * @param model - The transcription model to use.\n * @param audio - The audio data to transcribe as DataContent (string | Uint8Array | ArrayBuffer | Buffer) or a URL.\n * @param providerOptions - Additional provider-specific options that are passed through to the provider\n * as body parameters.\n * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n *\n * @returns A result object that contains the generated transcript.\n */\nconst defaultDownload = createDownload();\n\nexport async function transcribe({\n  model,\n  audio,\n  providerOptions = {},\n  maxRetries: maxRetriesArg,\n  abortSignal,\n  headers,\n  download: downloadFn = defaultDownload,\n}: {\n  /**\n   * The transcription model to use.\n   */\n  model: TranscriptionModel;\n\n  /**\n   * The audio data to transcribe.\n   */\n  audio: DataContent | URL;\n\n  /**\n   * Additional provider-specific options that are passed through to the provider\n   * as body parameters.\n   *\n   * The outer record is keyed by the provider name, and the inner\n   * record is keyed by the provider-specific metadata key.\n   * ```ts\n   * {\n   *   \"openai\": {\n   *     \"temperature\": 0\n   *   }\n   * }\n   * ```\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Maximum number of retries per transcript model call. Set to 0 to disable retries.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request.\n   * Only applicable for HTTP-based providers.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * Custom download function for fetching audio from URLs.\n   * Use `createDownload()` from `ai` to create a download function with custom size limits.\n   *\n   * @default createDownload() (2 GiB limit)\n   */\n  download?: (options: {\n    url: URL;\n    abortSignal?: AbortSignal;\n  }) => Promise<{ data: Uint8Array; mediaType: string | undefined }>;\n}): Promise<TranscriptionResult> {\n  const resolvedModel = resolveTranscriptionModel(model);\n  if (!resolvedModel) {\n    throw new Error('Model could not be resolved');\n  }\n\n  const { retry } = prepareRetries({\n    maxRetries: maxRetriesArg,\n    abortSignal,\n  });\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const audioData =\n    audio instanceof URL\n      ? (await downloadFn({ url: audio, abortSignal })).data\n      : convertDataContentToUint8Array(audio);\n\n  const result = await retry(() =>\n    resolvedModel.doGenerate({\n      audio: audioData,\n      abortSignal,\n      headers: headersWithUserAgent,\n      providerOptions,\n      mediaType:\n        detectMediaType({\n          data: audioData,\n          topLevelType: 'audio',\n        }) ?? 'audio/wav',\n    }),\n  );\n\n  logWarnings({\n    warnings: result.warnings,\n    provider: resolvedModel.provider,\n    model: resolvedModel.modelId,\n  });\n\n  if (!result.text) {\n    throw new NoTranscriptGeneratedError({ responses: [result.response] });\n  }\n\n  return new DefaultTranscriptionResult({\n    text: result.text,\n    segments: result.segments,\n    language: result.language,\n    durationInSeconds: result.durationInSeconds,\n    warnings: result.warnings,\n    responses: [result.response],\n    providerMetadata: result.providerMetadata,\n  });\n}\n\nclass DefaultTranscriptionResult implements TranscriptionResult {\n  readonly text: string;\n  readonly segments: Array<{\n    text: string;\n    startSecond: number;\n    endSecond: number;\n  }>;\n  readonly language: string | undefined;\n  readonly durationInSeconds: number | undefined;\n  readonly warnings: Array<Warning>;\n  readonly responses: Array<TranscriptionModelResponseMetadata>;\n  readonly providerMetadata: Record<string, JSONObject>;\n\n  constructor(options: {\n    text: string;\n    segments: Array<{\n      text: string;\n      startSecond: number;\n      endSecond: number;\n    }>;\n    language: string | undefined;\n    durationInSeconds: number | undefined;\n    warnings: Array<Warning>;\n    responses: Array<TranscriptionModelResponseMetadata>;\n    providerMetadata: Record<string, JSONObject> | undefined;\n  }) {\n    this.text = options.text;\n    this.segments = options.segments;\n    this.language = options.language;\n    this.durationInSeconds = options.durationInSeconds;\n    this.warnings = options.warnings;\n    this.responses = options.responses;\n    this.providerMetadata = options.providerMetadata ?? {};\n  }\n}\n","import {\n  UnsupportedFunctionalityError,\n  type Experimental_TranscriptionModelV4StreamPart,\n  type JSONObject,\n  type SharedV4AudioFormat,\n} from '@ai-sdk/provider';\nimport {\n  DelayedPromise,\n  withUserAgentSuffix,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { NoTranscriptGeneratedError } from '../error/no-transcript-generated-error';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveTranscriptionModel } from '../model/resolve-model';\nimport type { TranscriptionModel } from '../types/transcription-model';\nimport type { TranscriptionModelResponseMetadata } from '../types/transcription-model-response-metadata';\nimport type { Warning } from '../types/warning';\nimport { asAsyncIterableStream } from '../util/async-iterable-stream';\nimport { mergeAbortSignals } from '../util/merge-abort-signals';\nimport { VERSION } from '../version';\nimport type {\n  StreamTranscriptionResult,\n  TranscriptionStreamPart,\n} from './stream-transcribe-result';\n\ntype TranscriptSegment = {\n  text: string;\n  startSecond: number;\n  endSecond: number;\n};\n\n/**\n * Streams transcripts using a transcription model.\n *\n * @param model - The transcription model to use.\n * @param audio - Raw audio chunks to transcribe.\n * @param inputAudioFormat - The input audio format for the raw audio chunks.\n * @param providerOptions - Additional provider-specific options.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP/WebSocket headers to send when supported by the provider.\n *\n * @returns A result object that contains the streaming transcript and final transcript metadata.\n */\nexport function streamTranscribe({\n  model,\n  audio,\n  inputAudioFormat,\n  providerOptions = {},\n  abortSignal,\n  headers,\n  includeRawChunks,\n  _internal: { currentDate = () => new Date() } = {},\n}: {\n  /**\n   * The transcription model to use.\n   */\n  model: TranscriptionModel;\n\n  /**\n   * Raw audio chunks to transcribe.\n   */\n  audio: ReadableStream<Uint8Array | string>;\n\n  /**\n   * The input audio format for the raw audio chunks.\n   */\n  inputAudioFormat: SharedV4AudioFormat;\n\n  /**\n   * Additional provider-specific options.\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request, if supported by the provider.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * When true, providers should include raw provider chunks in the stream.\n   */\n  includeRawChunks?: boolean;\n\n  /**\n   * Internal test hooks.\n   */\n  _internal?: {\n    currentDate?: () => Date;\n  };\n}): StreamTranscriptionResult {\n  const resolvedModel = resolveTranscriptionModel(model);\n  if (!resolvedModel) {\n    throw new Error('Model could not be resolved');\n  }\n\n  const doStream = resolvedModel.doStream?.bind(resolvedModel);\n  if (doStream == null) {\n    throw new UnsupportedFunctionalityError({\n      functionality: 'streaming transcription',\n      message:\n        `The ${resolvedModel.provider} model \"${resolvedModel.modelId}\" does not support streaming transcription.` +\n        (typeof model === 'string'\n          ? ' String model IDs resolve through the global provider (AI Gateway by default).' +\n            ' If that provider does not support streaming transcription, pass a provider model' +\n            \" instance instead (e.g. openai.transcription('gpt-realtime-whisper'))\" +\n            ' or upgrade @ai-sdk/gateway to a version with streaming transcription support.'\n          : ''),\n    });\n  }\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const textPromise = new DelayedPromise<string>();\n  const segmentsPromise = new DelayedPromise<Array<TranscriptSegment>>();\n  const languagePromise = new DelayedPromise<string | undefined>();\n  const durationInSecondsPromise = new DelayedPromise<number | undefined>();\n  const warningsPromise = new DelayedPromise<Array<Warning>>();\n  const responsesPromise = new DelayedPromise<\n    Array<TranscriptionModelResponseMetadata>\n  >();\n  const providerMetadataPromise = new DelayedPromise<\n    Record<string, JSONObject>\n  >();\n\n  const rejectPendingPromises = (error: unknown) => {\n    for (const promise of [\n      textPromise,\n      segmentsPromise,\n      languagePromise,\n      durationInSecondsPromise,\n      warningsPromise,\n      responsesPromise,\n      providerMetadataPromise,\n    ]) {\n      if (promise.isPending()) {\n        promise.reject(error);\n      }\n    }\n  };\n\n  const startedAt = currentDate();\n  let response: TranscriptionModelResponseMetadata | undefined;\n  const currentResponseMetadata = () =>\n    response ?? { timestamp: startedAt, modelId: resolvedModel.modelId };\n\n  const resolveWarnings = (warnings: Array<Warning>) => {\n    warningsPromise.resolve(warnings);\n    logWarnings({\n      warnings,\n      provider: resolvedModel.provider,\n      model: resolvedModel.modelId,\n    });\n  };\n\n  // When the consumer cancels `fullStream` early, we abort the model pipe below\n  // with a defined reason via this controller. Relying on the default cancel\n  // cascade aborts the pipe with an `undefined` reason, which surfaces as a\n  // spurious unhandled rejection on Node.js 26 when the transform drops chunks.\n  const pipeAbortController = new AbortController();\n\n  // `Transformer.cancel` is part of the Streams spec (and supported at runtime),\n  // but not yet reflected in the ambient `Transformer` type, so widen it here.\n  const transformer: Transformer<\n    Experimental_TranscriptionModelV4StreamPart,\n    TranscriptionStreamPart\n  > & { cancel?: (reason?: unknown) => void } = {\n    transform(value, controller) {\n      switch (value.type) {\n        case 'stream-start': {\n          resolveWarnings(value.warnings);\n          break;\n        }\n\n        case 'response-metadata': {\n          response = {\n            timestamp: value.timestamp ?? currentResponseMetadata().timestamp,\n            modelId: value.modelId ?? currentResponseMetadata().modelId,\n            headers: value.headers ?? response?.headers,\n          };\n          break;\n        }\n\n        case 'transcript-delta':\n        case 'transcript-partial':\n        case 'transcript-final':\n        case 'raw':\n        case 'error': {\n          controller.enqueue(value);\n          break;\n        }\n\n        case 'finish': {\n          if (!warningsPromise.isResolved()) {\n            resolveWarnings([]);\n          }\n\n          if (!value.text) {\n            throw new NoTranscriptGeneratedError({\n              responses: [currentResponseMetadata()],\n            });\n          }\n\n          textPromise.resolve(value.text);\n          segmentsPromise.resolve(value.segments);\n          languagePromise.resolve(value.language);\n          durationInSecondsPromise.resolve(value.durationInSeconds);\n          responsesPromise.resolve([currentResponseMetadata()]);\n          providerMetadataPromise.resolve(value.providerMetadata ?? {});\n          break;\n        }\n      }\n    },\n\n    flush() {\n      if (textPromise.isPending()) {\n        throw new NoTranscriptGeneratedError({\n          responses: [currentResponseMetadata()],\n        });\n      }\n    },\n\n    cancel(reason) {\n      pipeAbortController.abort(\n        reason ?? new Error('Transcription stream was cancelled.'),\n      );\n    },\n  };\n\n  const transform = new TransformStream<\n    Experimental_TranscriptionModelV4StreamPart,\n    TranscriptionStreamPart\n  >(transformer);\n\n  // Piping (instead of an eager read loop) preserves consumer backpressure\n  // and propagates cancellation of `fullStream` to the model stream.\n  void (async () => {\n    const result = await doStream({\n      audio,\n      inputAudioFormat,\n      providerOptions,\n      // merged so cancelling fullStream also aborts a still-pending doStream\n      abortSignal: mergeAbortSignals(abortSignal, pipeAbortController.signal),\n      headers: headersWithUserAgent,\n      includeRawChunks,\n    });\n\n    response = {\n      timestamp: result.response?.timestamp ?? startedAt,\n      modelId: result.response?.modelId ?? resolvedModel.modelId,\n      headers: result.response?.headers,\n    };\n\n    await result.stream.pipeTo(transform.writable, {\n      signal: pipeAbortController.signal,\n    });\n  })().catch(error => {\n    const reason =\n      error ?? new Error('Transcription stream was cancelled or errored.');\n    rejectPendingPromises(reason);\n    // When `doStream` rejects before the model stream exists (e.g. auth or\n    // header resolution failure), nothing has taken ownership of `audio` yet,\n    // so cancel it directly — otherwise an upstream producer piping into it\n    // hangs forever. When the model did take a reader, `audio` is locked and\n    // the cancel rejects, which is fine: the model's cleanup owns it then.\n    audio.cancel(reason).catch(() => {});\n    transform.writable.abort(reason).catch(() => {\n      // the writable is already errored when the model stream failed mid-pipe\n    });\n  });\n\n  // Transcription streams can be unbounded (live microphone + raw chunks), so\n  // unlike streamText we cannot retain an unread tee branch for replay. The\n  // output stream has one owner: either fullStream, or the first result promise\n  // getter which claims and drains it internally.\n  let streamOwner: 'unclaimed' | 'full-stream' | 'result-promises' =\n    'unclaimed';\n\n  function consumeStream() {\n    if (streamOwner === 'full-stream' || streamOwner === 'result-promises') {\n      return;\n    }\n    streamOwner = 'result-promises';\n    const reader = transform.readable.getReader();\n    void (async () => {\n      while (!(await reader.read()).done) {\n        // drain; results surface via the promises\n      }\n    })().catch(() => {\n      // stream errors reject the promises via the pipe handler above\n    });\n  }\n\n  function getFullStream() {\n    if (streamOwner !== 'unclaimed') {\n      throw new Error(\n        streamOwner === 'full-stream'\n          ? 'fullStream can only be accessed once.'\n          : 'fullStream cannot be accessed after a result promise.',\n      );\n    }\n    streamOwner = 'full-stream';\n    // Direct ownership preserves backpressure and cancellation: cancelling\n    // this stream reaches Transformer.cancel and aborts the model pipe.\n    return asAsyncIterableStream(transform.readable);\n  }\n\n  return {\n    get text() {\n      consumeStream();\n      return textPromise.promise;\n    },\n    get segments() {\n      consumeStream();\n      return segmentsPromise.promise;\n    },\n    get language() {\n      consumeStream();\n      return languagePromise.promise;\n    },\n    get durationInSeconds() {\n      consumeStream();\n      return durationInSecondsPromise.promise;\n    },\n    get warnings() {\n      consumeStream();\n      return warningsPromise.promise;\n    },\n    get responses() {\n      consumeStream();\n      return responsesPromise.promise;\n    },\n    get providerMetadata() {\n      consumeStream();\n      return providerMetadataPromise.promise;\n    },\n    get fullStream() {\n      return getFullStream();\n    },\n  };\n}\n","import type { TranscriptionResult } from './transcribe-result';\nimport { transcribe } from './transcribe';\n\nexport { transcribe } from './transcribe';\nexport { streamTranscribe as experimental_streamTranscribe } from './stream-transcribe';\nexport type {\n  StreamTranscriptionResult,\n  TranscriptionStreamPart,\n} from './stream-transcribe-result';\nexport type { TranscriptionResult } from './transcribe-result';\n\n// deprecated exports\n\n/**\n * @deprecated Use `transcribe` instead.\n */\nconst experimental_transcribe = transcribe;\nexport { experimental_transcribe };\n\n/**\n * @deprecated Use `TranscriptionResult` instead.\n */\ntype Experimental_TranscriptionResult = TranscriptionResult;\nexport type { Experimental_TranscriptionResult };\n","import type {\n  Experimental_SpeechTranslationModelV4StreamPart,\n  Experimental_SpeechTranslationModelV4Usage,\n  JSONObject,\n  SharedV4AudioFormat,\n} from '@ai-sdk/provider';\nimport {\n  DelayedPromise,\n  withUserAgentSuffix,\n  type ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { NoTranslationGeneratedError } from '../error/no-translation-generated-error';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveSpeechTranslationModel } from '../model/resolve-model';\nimport type { SpeechTranslationModel } from '../types/speech-translation-model';\nimport type { SpeechTranslationModelResponseMetadata } from '../types/speech-translation-model-response-metadata';\nimport type { Warning } from '../types/warning';\nimport { asAsyncIterableStream } from '../util/async-iterable-stream';\nimport { mergeAbortSignals } from '../util/merge-abort-signals';\nimport { VERSION } from '../version';\nimport type {\n  StreamTranslationResult,\n  TranslationStreamPart,\n} from './stream-translate-result';\n\n/**\n * Streams speech-to-speech translations using a speech translation model.\n *\n * @param model - The speech translation model to use.\n * @param audio - Raw audio chunks to translate.\n * @param inputAudioFormat - The input audio format for the raw audio chunks.\n * @param targetLanguage - The language to translate the audio into.\n * @param sourceLanguage - The language of the source audio. Auto-detected when absent.\n * @param outputAudioFormat - The desired audio format for translated audio chunks.\n * @param providerOptions - Additional provider-specific options.\n * @param abortSignal - An optional abort signal that can be used to cancel the call.\n * @param headers - Additional HTTP/WebSocket headers to send when supported by the provider.\n * @param includeRawChunks - When true, providers include raw provider chunks in the stream as `raw` parts.\n *\n * @returns A result object that contains the streaming translation and final translation metadata.\n */\nexport function streamTranslate({\n  model,\n  audio,\n  inputAudioFormat,\n  targetLanguage,\n  sourceLanguage,\n  outputAudioFormat,\n  providerOptions = {},\n  abortSignal,\n  headers,\n  includeRawChunks,\n  _internal: { currentDate = () => new Date() } = {},\n}: {\n  /**\n   * The speech translation model to use.\n   */\n  model: SpeechTranslationModel;\n\n  /**\n   * Raw audio chunks to translate.\n   */\n  audio: ReadableStream<Uint8Array | string>;\n\n  /**\n   * The input audio format for the raw audio chunks.\n   */\n  inputAudioFormat: SharedV4AudioFormat;\n\n  /**\n   * The language to translate the audio into, as a BCP-47-style language\n   * tag (e.g. `en`, `es`, `fr-CA`). Supported values are provider-specific\n   * and validated by the provider.\n   */\n  targetLanguage: string;\n\n  /**\n   * The language of the source audio, as a BCP-47-style language tag.\n   * When absent, providers auto-detect the source language.\n   */\n  sourceLanguage?: string;\n\n  /**\n   * The desired audio format for translated audio chunks.\n   * When absent, the provider default output format is used.\n   */\n  outputAudioFormat?: SharedV4AudioFormat;\n\n  /**\n   * Additional provider-specific options.\n   */\n  providerOptions?: ProviderOptions;\n\n  /**\n   * Abort signal.\n   */\n  abortSignal?: AbortSignal;\n\n  /**\n   * Additional headers to include in the request, if supported by the provider.\n   */\n  headers?: Record<string, string>;\n\n  /**\n   * When true, providers should include raw provider chunks in the stream.\n   */\n  includeRawChunks?: boolean;\n\n  /**\n   * Internal test hooks.\n   */\n  _internal?: {\n    currentDate?: () => Date;\n  };\n}): StreamTranslationResult {\n  const resolvedModel = resolveSpeechTranslationModel(model);\n\n  const doStream = resolvedModel.doStream.bind(resolvedModel);\n\n  const headersWithUserAgent = withUserAgentSuffix(\n    headers ?? {},\n    `ai/${VERSION}`,\n  );\n\n  const sourceTextPromise = new DelayedPromise<string>();\n  const translationTextPromise = new DelayedPromise<string>();\n  const durationInSecondsPromise = new DelayedPromise<number | undefined>();\n  const usagePromise = new DelayedPromise<\n    Experimental_SpeechTranslationModelV4Usage | undefined\n  >();\n  const warningsPromise = new DelayedPromise<Array<Warning>>();\n  const responsePromise =\n    new DelayedPromise<SpeechTranslationModelResponseMetadata>();\n  const providerMetadataPromise = new DelayedPromise<\n    Record<string, JSONObject>\n  >();\n\n  const rejectPendingPromises = (error: unknown) => {\n    for (const promise of [\n      sourceTextPromise,\n      translationTextPromise,\n      durationInSecondsPromise,\n      usagePromise,\n      warningsPromise,\n      responsePromise,\n      providerMetadataPromise,\n    ]) {\n      if (promise.isPending()) {\n        promise.reject(error);\n      }\n    }\n  };\n\n  const startedAt = currentDate();\n  let response: SpeechTranslationModelResponseMetadata | undefined;\n  const currentResponseMetadata = () =>\n    response ?? { timestamp: startedAt, modelId: resolvedModel.modelId };\n\n  const resolveWarnings = (warnings: Array<Warning>) => {\n    warningsPromise.resolve(warnings);\n    logWarnings({\n      warnings,\n      provider: resolvedModel.provider,\n      model: resolvedModel.modelId,\n    });\n  };\n\n  // When the consumer cancels `fullStream` early, we abort the model pipe below\n  // with a defined reason via this controller. Relying on the default cancel\n  // cascade aborts the pipe with an `undefined` reason, which surfaces as a\n  // spurious unhandled rejection on Node.js 26 when the transform drops chunks.\n  const pipeAbortController = new AbortController();\n\n  // A stream is successful when at least one `audio` part was emitted or the\n  // final `outputText` is non-empty (audio-only providers may report an empty\n  // `outputText`).\n  let hasAudioOutput = false;\n\n  // `Transformer.cancel` is part of the Streams spec (and supported at runtime),\n  // but not yet reflected in the ambient `Transformer` type, so widen it here.\n  const transformer: Transformer<\n    Experimental_SpeechTranslationModelV4StreamPart,\n    TranslationStreamPart\n  > & { cancel?: (reason?: unknown) => void } = {\n    transform(value, controller) {\n      switch (value.type) {\n        case 'stream-start': {\n          resolveWarnings(value.warnings);\n          break;\n        }\n\n        case 'response-metadata': {\n          response = {\n            timestamp: value.timestamp ?? currentResponseMetadata().timestamp,\n            modelId: value.modelId ?? currentResponseMetadata().modelId,\n            headers: value.headers ?? response?.headers,\n          };\n          break;\n        }\n\n        case 'audio': {\n          hasAudioOutput = true;\n          controller.enqueue(value);\n          break;\n        }\n\n        case 'output-text-delta':\n        case 'output-text-final':\n        case 'source-transcript-delta':\n        case 'source-transcript-partial':\n        case 'source-transcript-final':\n        case 'raw':\n        case 'error': {\n          controller.enqueue(value);\n          break;\n        }\n\n        case 'finish': {\n          if (!warningsPromise.isResolved()) {\n            resolveWarnings([]);\n          }\n\n          if (!hasAudioOutput && !value.outputText) {\n            throw new NoTranslationGeneratedError({\n              response: currentResponseMetadata(),\n            });\n          }\n\n          sourceTextPromise.resolve(value.sourceText);\n          translationTextPromise.resolve(value.outputText);\n          durationInSecondsPromise.resolve(value.durationInSeconds);\n          usagePromise.resolve(value.usage);\n          responsePromise.resolve(currentResponseMetadata());\n          providerMetadataPromise.resolve(value.providerMetadata ?? {});\n          break;\n        }\n\n        default: {\n          const _exhaustiveCheck: never = value;\n          throw new Error(`Unsupported part type: ${_exhaustiveCheck}`);\n        }\n      }\n    },\n\n    flush() {\n      if (translationTextPromise.isPending()) {\n        throw new NoTranslationGeneratedError({\n          response: currentResponseMetadata(),\n        });\n      }\n    },\n\n    cancel(reason) {\n      pipeAbortController.abort(\n        reason ?? new Error('Translation stream was cancelled.'),\n      );\n    },\n  };\n\n  const transform = new TransformStream<\n    Experimental_SpeechTranslationModelV4StreamPart,\n    TranslationStreamPart\n  >(transformer);\n\n  // Piping (instead of an eager read loop) preserves consumer backpressure\n  // and propagates cancellation of `fullStream` to the model stream.\n  void (async () => {\n    const result = await doStream({\n      audio,\n      inputAudioFormat,\n      targetLanguage,\n      sourceLanguage,\n      outputAudioFormat,\n      providerOptions,\n      // merged so cancelling fullStream also aborts a still-pending doStream\n      abortSignal: mergeAbortSignals(abortSignal, pipeAbortController.signal),\n      headers: headersWithUserAgent,\n      includeRawChunks,\n    });\n\n    response = {\n      timestamp: result.response?.timestamp ?? startedAt,\n      modelId: result.response?.modelId ?? resolvedModel.modelId,\n      headers: result.response?.headers,\n    };\n\n    await result.stream.pipeTo(transform.writable, {\n      signal: pipeAbortController.signal,\n    });\n  })().catch(error => {\n    const reason =\n      error ?? new Error('Translation stream was cancelled or errored.');\n    rejectPendingPromises(reason);\n    // When `doStream` rejects before the model stream exists (e.g. auth or\n    // header resolution failure), nothing has taken ownership of `audio` yet,\n    // so cancel it directly — otherwise an upstream producer piping into it\n    // hangs forever. When the model did take a reader, `audio` is locked and\n    // the cancel rejects, which is fine: the model's cleanup owns it then.\n    audio.cancel(reason).catch(() => {});\n    transform.writable.abort(reason).catch(() => {\n      // the writable is already errored when the model stream failed mid-pipe\n    });\n  });\n\n  // Translation streams can be unbounded (live microphone + raw chunks), so\n  // unlike streamText we cannot retain an unread tee branch for replay. The\n  // output stream has one owner: either fullStream, or the first result promise\n  // getter which claims and drains it internally.\n  let streamOwner: 'unclaimed' | 'full-stream' | 'result-promises' =\n    'unclaimed';\n\n  function consumeStream() {\n    if (streamOwner === 'full-stream' || streamOwner === 'result-promises') {\n      return;\n    }\n    streamOwner = 'result-promises';\n    const reader = transform.readable.getReader();\n    void (async () => {\n      while (!(await reader.read()).done) {\n        // drain; results surface via the promises\n      }\n    })().catch(() => {\n      // stream errors reject the promises via the pipe handler above\n    });\n  }\n\n  function getFullStream() {\n    if (streamOwner !== 'unclaimed') {\n      throw new Error(\n        streamOwner === 'full-stream'\n          ? 'fullStream can only be accessed once.'\n          : 'fullStream cannot be accessed after a result promise.',\n      );\n    }\n    streamOwner = 'full-stream';\n    // Direct ownership preserves backpressure and cancellation: cancelling\n    // this stream reaches Transformer.cancel and aborts the model pipe.\n    return asAsyncIterableStream(transform.readable);\n  }\n\n  return {\n    get sourceText() {\n      consumeStream();\n      return sourceTextPromise.promise;\n    },\n    get translationText() {\n      consumeStream();\n      return translationTextPromise.promise;\n    },\n    get durationInSeconds() {\n      consumeStream();\n      return durationInSecondsPromise.promise;\n    },\n    get usage() {\n      consumeStream();\n      return usagePromise.promise;\n    },\n    get warnings() {\n      consumeStream();\n      return warningsPromise.promise;\n    },\n    get response() {\n      consumeStream();\n      return responsePromise.promise;\n    },\n    get providerMetadata() {\n      consumeStream();\n      return providerMetadataPromise.promise;\n    },\n    get fullStream() {\n      return getFullStream();\n    },\n  };\n}\n","import {\n  parseJsonEventStream,\n  withUserAgentSuffix,\n  getRuntimeEnvironmentUserAgent,\n  type ParseResult,\n} from '@ai-sdk/provider-utils';\nimport { EmptyResponseBodyError } from '@ai-sdk/provider';\nimport { InvalidArgumentError } from '../error/invalid-argument-error';\nimport { UIMessageStreamError } from '../error/ui-message-stream-error';\nimport {\n  uiMessageChunkSchema,\n  type UIMessageChunk,\n} from '../ui-message-stream/ui-message-chunks';\nimport { consumeStream } from '../util/consume-stream';\nimport { createUIApiCallError } from './create-ui-api-call-error';\nimport { processTextStream } from './process-text-stream';\nimport { VERSION } from '../version';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport async function callCompletionApi({\n  api,\n  prompt,\n  credentials,\n  headers,\n  body,\n  streamProtocol = 'data',\n  setCompletion,\n  setLoading,\n  setError,\n  setAbortController,\n  onFinish,\n  onError,\n  fetch = getOriginalFetch(),\n}: {\n  api: string;\n  prompt: string;\n  credentials: RequestCredentials | undefined;\n  headers: HeadersInit | undefined;\n  body: Record<string, any>;\n  streamProtocol: 'data' | 'text' | undefined;\n  setCompletion: (completion: string) => void;\n  setLoading: (loading: boolean) => void;\n  setError: (error: Error | undefined) => void;\n  setAbortController: (abortController: AbortController | null) => void;\n  onFinish: ((prompt: string, completion: string) => void) | undefined;\n  onError: ((error: Error) => void) | undefined;\n  fetch: ReturnType<typeof getOriginalFetch> | undefined;\n}) {\n  try {\n    setLoading(true);\n    setError(undefined);\n\n    const abortController = new AbortController();\n    setAbortController(abortController);\n\n    // Empty the completion immediately.\n    setCompletion('');\n\n    const response = await fetch(api, {\n      method: 'POST',\n      body: JSON.stringify({\n        prompt,\n        ...body,\n      }),\n      credentials,\n      headers: withUserAgentSuffix(\n        {\n          'Content-Type': 'application/json',\n          ...headers,\n        },\n        `ai-sdk/${VERSION}`,\n        getRuntimeEnvironmentUserAgent(),\n      ),\n      signal: abortController.signal,\n    }).catch(err => {\n      throw err;\n    });\n\n    if (!response.ok) {\n      throw await createUIApiCallError({\n        response,\n        url: api,\n        fallbackMessage: 'Failed to fetch the chat response.',\n      });\n    }\n\n    if (!response.body) {\n      throw new EmptyResponseBodyError({\n        message: 'The response body is empty.',\n      });\n    }\n\n    let result = '';\n\n    switch (streamProtocol) {\n      case 'text': {\n        await processTextStream({\n          stream: response.body,\n          onTextPart: chunk => {\n            result += chunk;\n            setCompletion(result);\n          },\n        });\n        break;\n      }\n      case 'data': {\n        await consumeStream({\n          stream: parseJsonEventStream({\n            stream: response.body,\n            schema: uiMessageChunkSchema,\n          }).pipeThrough(\n            new TransformStream<ParseResult<UIMessageChunk>, UIMessageChunk>({\n              async transform(part) {\n                if (!part.success) {\n                  throw part.error;\n                }\n\n                const streamPart = part.value;\n                if (streamPart.type === 'text-delta') {\n                  result += streamPart.delta;\n                  setCompletion(result);\n                } else if (streamPart.type === 'error') {\n                  throw new UIMessageStreamError({\n                    chunkType: 'error',\n                    chunkId: '',\n                    message: streamPart.errorText,\n                  });\n                }\n              },\n            }),\n          ),\n          onError: error => {\n            throw error;\n          },\n        });\n        break;\n      }\n      default: {\n        const exhaustiveCheck: never = streamProtocol;\n        throw new InvalidArgumentError({\n          parameter: 'streamProtocol',\n          value: exhaustiveCheck,\n          message: `Unknown stream protocol: ${exhaustiveCheck}`,\n        });\n      }\n    }\n\n    if (onFinish) {\n      onFinish(prompt, result);\n    }\n\n    setAbortController(null);\n    return result;\n  } catch (err) {\n    // Ignore abort errors as they are expected.\n    if ((err as any).name === 'AbortError') {\n      setAbortController(null);\n      return null;\n    }\n\n    if (err instanceof Error) {\n      if (onError) {\n        onError(err);\n      }\n    }\n\n    setError(err as Error);\n  } finally {\n    setLoading(false);\n  }\n}\n","import { APICallError } from '@ai-sdk/provider';\n\nexport async function createUIApiCallError({\n  response,\n  url,\n  fallbackMessage,\n}: {\n  response: Response;\n  url: string;\n  fallbackMessage: string;\n}) {\n  const responseBody = await response.text();\n\n  return new APICallError({\n    message: responseBody || fallbackMessage,\n    url,\n    // UI requests can contain prompts, messages, and other sensitive values.\n    // Keep them out of client-facing error objects.\n    requestBodyValues: undefined,\n    statusCode: response.status,\n    responseBody,\n  });\n}\n","export async function processTextStream({\n  stream,\n  onTextPart,\n}: {\n  stream: ReadableStream<Uint8Array>;\n  onTextPart: (chunk: string) => Promise<void> | void;\n}): Promise<void> {\n  const reader = stream.pipeThrough(new TextDecoderStream()).getReader();\n  while (true) {\n    const { done, value } = await reader.read();\n    if (done) {\n      break;\n    }\n    await onTextPart(value);\n  }\n}\n","import {\n  generateId as generateIdFunc,\n  type FlexibleSchema,\n  type IdGenerator,\n  type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { InvalidArgumentError } from '../error/invalid-argument-error';\nimport type { FinishReason } from '../types/language-model';\nimport type { UIMessageChunk } from '../ui-message-stream/ui-message-chunks';\nimport { consumeStream } from '../util/consume-stream';\nimport { SerialJobExecutor } from '../util/serial-job-executor';\nimport type { ChatTransport } from './chat-transport';\nimport { convertFileListToFileUIParts } from './convert-file-list-to-file-ui-parts';\nimport { DefaultChatTransport } from './default-chat-transport';\nimport {\n  createStreamingUIMessageState,\n  processUIMessageStream,\n  type StreamingUIMessageState,\n  type UIMessageStreamWriteOptions,\n} from './process-ui-message-stream';\nimport {\n  isToolUIPart,\n  type DataUIPart,\n  type FileUIPart,\n  type InferUIMessageData,\n  type InferUIMessageMetadata,\n  type InferUIMessageTools,\n  type UIDataTypes,\n  type UIMessage,\n  type InferUIMessageToolCall,\n  type UIMessagePart,\n  type UITools,\n} from './ui-messages';\nexport type CreateUIMessage<UI_MESSAGE extends UIMessage> = Omit<\n  UI_MESSAGE,\n  'id' | 'role'\n> & {\n  id?: UI_MESSAGE['id'];\n  role?: UI_MESSAGE['role'];\n};\n\nexport type UIDataPartSchemas = Record<string, FlexibleSchema>;\n\nexport type UIDataTypesToSchemas<T extends UIDataTypes> = {\n  [K in keyof T]: FlexibleSchema<T[K]>;\n};\n\nexport type InferUIDataParts<T extends UIDataPartSchemas> = {\n  [K in keyof T]: InferSchema<T[K]>;\n};\n\nexport type ChatRequestOptions = {\n  /**\n   * Additional headers that should be to be passed to the API endpoint.\n   */\n  headers?: Record<string, string> | Headers;\n\n  /**\n   * Additional body JSON properties that should be sent to the API endpoint.\n   */\n  body?: object; // TODO JSONStringifyable\n\n  metadata?: unknown;\n};\n\n/**\n * Function that can be called to add a tool approval response to the chat.\n */\nexport type ChatAddToolApproveResponseFunction = ({\n  id,\n  approved,\n  reason,\n  options,\n}: {\n  id: string;\n\n  /**\n   * Flag indicating whether the approval was granted or denied.\n   */\n  approved: boolean;\n\n  /**\n   * Optional reason for the approval or denial.\n   */\n  reason?: string;\n\n  /**\n   * Optional request options to be used if `sendAutomaticallyWhen` callback returns true.\n   */\n  options?: ChatRequestOptions;\n}) => void | PromiseLike<void>;\n\n/**\n * Function that can be called to add a tool output to the chat.\n */\nexport type ChatAddToolOutputFunction<UI_MESSAGE extends UIMessage> = <\n  TOOL extends keyof InferUIMessageTools<UI_MESSAGE>,\n>({\n  state,\n  tool,\n  toolCallId,\n  output,\n  errorText,\n  options,\n}: {\n  /**\n   * Name of the tool that was called.\n   */\n  tool: TOOL;\n\n  /**\n   * Identifier of the tool call to add output for.\n   */\n  toolCallId: string;\n\n  /**\n   * Optional request options to be used if `sendAutomaticallyWhen` callback returns true.\n   */\n  options?: ChatRequestOptions;\n} & (\n  | {\n      state?: 'output-available';\n      output: InferUIMessageTools<UI_MESSAGE>[TOOL]['output'];\n      errorText?: never;\n    }\n  | {\n      state: 'output-error';\n      output?: never;\n      errorText: string;\n    }\n)) => void | PromiseLike<void>;\n\nexport type ChatStatus = 'submitted' | 'streaming' | 'ready' | 'error';\n\ntype ActiveResponse<UI_MESSAGE extends UIMessage> = {\n  state: StreamingUIMessageState<UI_MESSAGE>;\n  abortController: AbortController;\n};\n\ntype ActiveResumeRequest = {\n  abortController: AbortController;\n};\n\nexport interface ChatState<UI_MESSAGE extends UIMessage> {\n  status: ChatStatus;\n\n  error: Error | undefined;\n\n  messages: UI_MESSAGE[];\n  pushMessage: (message: UI_MESSAGE) => void;\n  popMessage: () => void;\n  replaceMessage: (index: number, message: UI_MESSAGE) => void;\n\n  snapshot: <T>(thing: T) => T;\n}\n\nexport type ChatOnErrorCallback = (error: Error) => void;\n\nexport type ChatOnToolCallCallback<UI_MESSAGE extends UIMessage = UIMessage> =\n  (options: {\n    toolCall: InferUIMessageToolCall<UI_MESSAGE>;\n  }) => void | PromiseLike<void>;\n\nexport type ChatOnDataCallback<UI_MESSAGE extends UIMessage> = (\n  dataPart: DataUIPart<InferUIMessageData<UI_MESSAGE>>,\n) => void;\n\n/**\n * Function that is called when the assistant response has finished streaming.\n *\n * @param message The assistant message that was streamed.\n * @param messages The full chat history, including the assistant message.\n *\n * @param isAbort Indicates whether the request has been aborted.\n * @param isDisconnect Indicates whether the request has been ended by a network error.\n * @param isError Indicates whether the request has been ended by an error.\n * @param finishReason The reason why the generation finished.\n */\nexport type ChatOnFinishCallback<UI_MESSAGE extends UIMessage> = (options: {\n  message: UI_MESSAGE;\n  messages: UI_MESSAGE[];\n  isAbort: boolean;\n  isDisconnect: boolean;\n  isError: boolean;\n  finishReason?: FinishReason;\n}) => void;\n\nexport interface ChatInit<UI_MESSAGE extends UIMessage> {\n  /**\n   * A unique identifier for the chat. If not provided, a random one will be\n   * generated.\n   */\n  id?: string;\n\n  messageMetadataSchema?: FlexibleSchema<UI_MESSAGE['metadata']>;\n  dataPartSchemas?: UIDataTypesToSchemas<InferUIMessageData<UI_MESSAGE>>;\n\n  messages?: UI_MESSAGE[];\n\n  /**\n   * A way to provide a function that is going to be used for ids for messages and the chat.\n   * If not provided the default AI SDK `generateId` is used.\n   */\n  generateId?: IdGenerator;\n\n  transport?: ChatTransport<UI_MESSAGE>;\n\n  /**\n   * Callback function to be called when an error is encountered.\n   */\n  onError?: ChatOnErrorCallback;\n\n  /**\n   * Optional callback function that is invoked when a tool call is received.\n   * Intended for automatic client-side tool execution.\n   *\n   * To add the tool output, call `addToolOutput` without awaiting it inside\n   * this callback. The callback's return value is not used.\n   */\n  onToolCall?: ChatOnToolCallCallback<UI_MESSAGE>;\n\n  /**\n   * Function that is called when the assistant response has finished streaming.\n   */\n  onFinish?: ChatOnFinishCallback<UI_MESSAGE>;\n\n  /**\n   * Optional callback function that is called when a data part is received.\n   *\n   * @param data The data part that was received.\n   */\n  onData?: ChatOnDataCallback<UI_MESSAGE>;\n\n  /**\n   * When provided, this function will be called when the stream is finished or a tool call is added\n   * to determine if the current messages should be resubmitted.\n   */\n  sendAutomaticallyWhen?: (options: {\n    messages: UI_MESSAGE[];\n  }) => boolean | PromiseLike<boolean>;\n}\n\nexport abstract class AbstractChat<UI_MESSAGE extends UIMessage> {\n  readonly id: string;\n  readonly generateId: IdGenerator;\n\n  protected state: ChatState<UI_MESSAGE>;\n\n  private messageMetadataSchema:\n    | FlexibleSchema<UI_MESSAGE['metadata']>\n    | undefined;\n  private dataPartSchemas:\n    | UIDataTypesToSchemas<InferUIMessageData<UI_MESSAGE>>\n    | undefined;\n  private readonly transport: ChatTransport<UI_MESSAGE>;\n  private onError?: ChatInit<UI_MESSAGE>['onError'];\n  private onToolCall?: ChatInit<UI_MESSAGE>['onToolCall'];\n  private onFinish?: ChatInit<UI_MESSAGE>['onFinish'];\n  private onData?: ChatInit<UI_MESSAGE>['onData'];\n  private sendAutomaticallyWhen?: ChatInit<UI_MESSAGE>['sendAutomaticallyWhen'];\n\n  private pendingMessagePreparations = new Set<AbortController>();\n  private activeResponse: ActiveResponse<UI_MESSAGE> | undefined = undefined;\n  private activeResumeRequest: ActiveResumeRequest | undefined = undefined;\n  private jobExecutor = new SerialJobExecutor();\n\n  constructor({\n    generateId = generateIdFunc,\n    id = generateId(),\n    transport = new DefaultChatTransport(),\n    messageMetadataSchema,\n    dataPartSchemas,\n    state,\n    onError,\n    onToolCall,\n    onFinish,\n    onData,\n    sendAutomaticallyWhen,\n  }: Omit<ChatInit<UI_MESSAGE>, 'messages'> & {\n    state: ChatState<UI_MESSAGE>;\n  }) {\n    this.id = id;\n    this.transport = transport;\n    this.generateId = generateId;\n    this.messageMetadataSchema = messageMetadataSchema;\n    this.dataPartSchemas = dataPartSchemas;\n    this.state = state;\n    this.onError = onError;\n    this.onToolCall = onToolCall;\n    this.onFinish = onFinish;\n    this.onData = onData;\n    this.sendAutomaticallyWhen = sendAutomaticallyWhen;\n  }\n\n  /**\n   * Hook status:\n   *\n   * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n   * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n   * - `ready`: The full response has been received and processed; a new user message can be submitted.\n   * - `error`: An error occurred during the API request, preventing successful completion.\n   */\n  get status(): ChatStatus {\n    return this.state.status;\n  }\n\n  protected setStatus({\n    status,\n    error,\n  }: {\n    status: ChatStatus;\n    error?: Error;\n  }) {\n    if (this.status === status) return;\n\n    this.state.status = status;\n    this.state.error = error;\n  }\n\n  get error() {\n    return this.state.error;\n  }\n\n  get messages(): UI_MESSAGE[] {\n    return this.state.messages;\n  }\n\n  get lastMessage(): UI_MESSAGE | undefined {\n    return this.state.messages[this.state.messages.length - 1];\n  }\n\n  set messages(messages: UI_MESSAGE[]) {\n    this.state.messages = messages;\n  }\n\n  /**\n   * Appends or replaces a user message to the chat list. This triggers the API call to fetch\n   * the assistant's response.\n   *\n   * If a messageId is provided, the message will be replaced.\n   */\n  sendMessage = async (\n    message?:\n      | (CreateUIMessage<UI_MESSAGE> & {\n          text?: never;\n          files?: never;\n          messageId?: string;\n        })\n      | {\n          text: string;\n          files?: FileList | FileUIPart[];\n          metadata?: InferUIMessageMetadata<UI_MESSAGE>;\n          parts?: never;\n          messageId?: string;\n        }\n      | {\n          files: FileList | FileUIPart[];\n          metadata?: InferUIMessageMetadata<UI_MESSAGE>;\n          parts?: never;\n          messageId?: string;\n        },\n    options?: ChatRequestOptions,\n  ): Promise<void> => {\n    if (message == null) {\n      await this.makeRequest({\n        trigger: 'submit-message',\n        messageId: this.lastMessage?.id,\n        ...options,\n      });\n      return;\n    }\n\n    let uiMessage: CreateUIMessage<UI_MESSAGE>;\n\n    if ('text' in message || 'files' in message) {\n      const abortController = new AbortController();\n      this.pendingMessagePreparations.add(abortController);\n\n      let fileParts: FileUIPart[];\n      try {\n        fileParts = Array.isArray(message.files)\n          ? message.files\n          : await convertFileListToFileUIParts(message.files);\n      } finally {\n        this.pendingMessagePreparations.delete(abortController);\n      }\n\n      if (abortController.signal.aborted) {\n        return;\n      }\n\n      uiMessage = {\n        parts: [\n          ...fileParts,\n          ...('text' in message && message.text != null\n            ? [{ type: 'text' as const, text: message.text }]\n            : []),\n        ],\n      } as UI_MESSAGE;\n    } else {\n      uiMessage = message;\n    }\n\n    if (message.messageId != null) {\n      const messageIndex = this.state.messages.findIndex(\n        m => m.id === message.messageId,\n      );\n\n      if (messageIndex === -1) {\n        throw new InvalidArgumentError({\n          parameter: 'message.messageId',\n          value: message.messageId,\n          message: `message with id ${message.messageId} not found`,\n        });\n      }\n\n      if (this.state.messages[messageIndex].role !== 'user') {\n        throw new InvalidArgumentError({\n          parameter: 'message.messageId',\n          value: message.messageId,\n          message: `message with id ${message.messageId} is not a user message`,\n        });\n      }\n\n      // remove all messages after the message with the given id\n      this.state.messages = this.state.messages.slice(0, messageIndex + 1);\n\n      // update the message with the new content\n      this.state.replaceMessage(messageIndex, {\n        id: message.messageId,\n        ...uiMessage,\n        role: uiMessage.role ?? 'user',\n        metadata: message.metadata,\n      } as UI_MESSAGE);\n    } else {\n      this.state.pushMessage({\n        ...uiMessage,\n        id: uiMessage.id ?? this.generateId(),\n        role: uiMessage.role ?? 'user',\n        metadata: message.metadata,\n      } as UI_MESSAGE);\n    }\n\n    await this.makeRequest({\n      trigger: 'submit-message',\n      messageId: message.messageId,\n      ...options,\n    });\n  };\n\n  /**\n   * Regenerate the assistant message with the provided message id.\n   * If no message id is provided, the last assistant message will be regenerated.\n   */\n  regenerate = async ({\n    messageId,\n    ...options\n  }: {\n    messageId?: string;\n  } & ChatRequestOptions = {}): Promise<void> => {\n    const messageIndex =\n      messageId == null\n        ? this.state.messages.length - 1\n        : this.state.messages.findIndex(message => message.id === messageId);\n\n    if (messageIndex === -1) {\n      throw new InvalidArgumentError({\n        parameter: 'messageId',\n        value: messageId,\n        message: `message ${messageId} not found`,\n      });\n    }\n\n    // set the messages to the message before the assistant message\n    this.state.messages = this.state.messages.slice(\n      0,\n      // if the message is a user message, we need to include it in the request:\n      this.messages[messageIndex].role === 'assistant'\n        ? messageIndex\n        : messageIndex + 1,\n    );\n\n    await this.makeRequest({\n      trigger: 'regenerate-message',\n      messageId,\n      ...options,\n    });\n  };\n\n  /**\n   * Attempt to resume an ongoing streaming response.\n   */\n  resumeStream = async (options: ChatRequestOptions = {}): Promise<void> => {\n    await this.makeRequest({ trigger: 'resume-stream', ...options });\n  };\n\n  /**\n   * Clear the error state and set the status to ready if the chat is in an error state.\n   */\n  clearError = () => {\n    if (this.status === 'error') {\n      this.state.error = undefined;\n      this.setStatus({ status: 'ready' });\n    }\n  };\n\n  addToolApprovalResponse: ChatAddToolApproveResponseFunction = async ({\n    id,\n    approved,\n    reason,\n    options,\n  }) =>\n    this.jobExecutor.run(async () => {\n      const messages = this.state.messages;\n      const lastMessage = messages[messages.length - 1];\n\n      const updatePart = (\n        part: UIMessagePart<UIDataTypes, UITools>,\n      ): UIMessagePart<UIDataTypes, UITools> =>\n        isToolUIPart(part) &&\n        part.state === 'approval-requested' &&\n        part.approval.id === id\n          ? {\n              ...part,\n              state: 'approval-responded',\n              approval: { ...part.approval, id, approved, reason },\n            }\n          : part;\n\n      // update the message to trigger an immediate UI update\n      this.state.replaceMessage(messages.length - 1, {\n        ...lastMessage,\n        parts: lastMessage.parts.map(updatePart),\n      });\n\n      // update the active response if it exists\n      if (this.activeResponse) {\n        this.activeResponse.state.message.parts =\n          this.activeResponse.state.message.parts.map(updatePart);\n      }\n\n      // automatically send the message if the sendAutomaticallyWhen function returns true\n      if (\n        this.status !== 'streaming' &&\n        this.status !== 'submitted' &&\n        this.sendAutomaticallyWhen\n      ) {\n        this.shouldSendAutomatically().then(shouldSend => {\n          if (shouldSend) {\n            // no await to avoid deadlocking\n            this.makeRequest({\n              trigger: 'submit-message',\n              messageId: this.lastMessage?.id,\n              ...options,\n            });\n          }\n        });\n      }\n    });\n\n  addToolOutput: ChatAddToolOutputFunction<UI_MESSAGE> = async ({\n    state = 'output-available',\n    toolCallId,\n    output,\n    errorText,\n    options,\n  }) =>\n    this.jobExecutor.run(async () => {\n      const messages = this.state.messages;\n      const lastMessage = messages[messages.length - 1];\n\n      const updatePart = (\n        part: UIMessagePart<UIDataTypes, UITools>,\n      ): UIMessagePart<UIDataTypes, UITools> =>\n        isToolUIPart(part) && part.toolCallId === toolCallId\n          ? ({ ...part, state, output, errorText } as typeof part)\n          : part;\n\n      // update the message to trigger an immediate UI update\n      this.state.replaceMessage(messages.length - 1, {\n        ...lastMessage,\n        parts: lastMessage.parts.map(updatePart),\n      });\n\n      // update the active response if it exists\n      if (this.activeResponse) {\n        this.activeResponse.state.message.parts =\n          this.activeResponse.state.message.parts.map(updatePart);\n      }\n\n      // automatically send the message if the sendAutomaticallyWhen function returns true\n      if (\n        this.status !== 'streaming' &&\n        this.status !== 'submitted' &&\n        this.sendAutomaticallyWhen\n      ) {\n        this.shouldSendAutomatically().then(shouldSend => {\n          if (shouldSend) {\n            // no await to avoid deadlocking\n            this.makeRequest({\n              trigger: 'submit-message',\n              messageId: this.lastMessage?.id,\n              ...options,\n            });\n          }\n        });\n      }\n    });\n\n  /** @deprecated Use addToolOutput */\n  addToolResult = this.addToolOutput;\n\n  /**\n   * Abort the current request immediately, keep the generated tokens if any.\n   */\n  stop = async () => {\n    for (const controller of this.pendingMessagePreparations) {\n      controller.abort();\n    }\n    this.activeResumeRequest?.abortController.abort();\n    this.activeResponse?.abortController.abort();\n  };\n\n  private async shouldSendAutomatically(): Promise<boolean> {\n    if (!this.sendAutomaticallyWhen) return false;\n\n    const result = this.sendAutomaticallyWhen({\n      messages: this.state.messages,\n    });\n\n    // Check if result is a promise\n    if (result && typeof result === 'object' && 'then' in result) {\n      return await result;\n    }\n\n    return result as boolean;\n  }\n\n  private async makeRequest({\n    trigger,\n    metadata,\n    headers,\n    body,\n    messageId,\n  }: {\n    trigger: 'submit-message' | 'resume-stream' | 'regenerate-message';\n    messageId?: string;\n  } & ChatRequestOptions) {\n    const abortController = new AbortController();\n    const activeResumeRequest =\n      trigger === 'resume-stream' ? { abortController } : undefined;\n\n    if (activeResumeRequest) {\n      this.activeResumeRequest?.abortController.abort();\n      this.activeResumeRequest = activeResumeRequest;\n    }\n\n    const isCurrentRequest = () =>\n      activeResumeRequest == null ||\n      this.activeResumeRequest === activeResumeRequest;\n\n    const clearActiveResumeRequest = () => {\n      if (this.activeResumeRequest === activeResumeRequest) {\n        this.activeResumeRequest = undefined;\n      }\n    };\n\n    // For resume-stream, check if there's an active stream before\n    // changing status. This avoids a brief flash of 'submitted' status\n    // when there is no stream to resume (e.g. on page load).\n    let resumeStream: ReadableStream<UIMessageChunk> | undefined;\n    if (trigger === 'resume-stream') {\n      try {\n        const reconnect = await this.transport.reconnectToStream({\n          chatId: this.id,\n          abortSignal: abortController.signal,\n          metadata,\n          headers,\n          body,\n        });\n\n        if (abortController.signal.aborted || !isCurrentRequest()) {\n          await reconnect?.cancel().catch(() => {});\n          if (isCurrentRequest()) {\n            this.setStatus({ status: 'ready' });\n          }\n          clearActiveResumeRequest();\n          return;\n        }\n\n        if (reconnect == null) {\n          this.setStatus({ status: 'ready' });\n          clearActiveResumeRequest();\n          return; // no active stream found, so we do not resume\n        }\n\n        resumeStream = reconnect;\n      } catch (err) {\n        if (\n          abortController.signal.aborted ||\n          (err as { name?: string }).name === 'AbortError'\n        ) {\n          if (isCurrentRequest()) {\n            this.setStatus({ status: 'ready' });\n          }\n          clearActiveResumeRequest();\n          return;\n        }\n\n        if (!isCurrentRequest()) {\n          return;\n        }\n\n        if (this.onError && err instanceof Error) {\n          this.onError(err);\n        }\n        this.setStatus({ status: 'error', error: err as Error });\n        clearActiveResumeRequest();\n        return;\n      }\n    }\n\n    this.setStatus({ status: 'submitted', error: undefined });\n\n    const lastMessage = this.lastMessage;\n\n    let isAbort = false;\n    let isDisconnect = false;\n    let isError = false;\n    let activeResponse: ActiveResponse<UI_MESSAGE> | undefined;\n\n    try {\n      const response = {\n        state: createStreamingUIMessageState({\n          lastMessage:\n            trigger === 'resume-stream' || trigger === 'regenerate-message'\n              ? undefined\n              : this.state.snapshot(lastMessage),\n          messageId: this.generateId(),\n        }),\n        abortController,\n      } as ActiveResponse<UI_MESSAGE>;\n\n      activeResponse = response;\n\n      response.abortController.signal.addEventListener('abort', () => {\n        isAbort = true;\n      });\n\n      this.activeResponse = response;\n\n      let stream: ReadableStream<UIMessageChunk>;\n\n      if (trigger === 'resume-stream') {\n        stream = resumeStream!;\n      } else {\n        stream = await this.transport.sendMessages({\n          chatId: this.id,\n          messages: this.state.messages,\n          abortSignal: response.abortController.signal,\n          metadata,\n          headers,\n          body,\n          trigger,\n          messageId,\n        });\n      }\n\n      const runUpdateMessageJob = (\n        job: (options: {\n          state: StreamingUIMessageState<UI_MESSAGE>;\n          write: (options?: UIMessageStreamWriteOptions) => void;\n        }) => Promise<void>,\n      ) =>\n        // serialize the job execution to avoid race conditions:\n        this.jobExecutor.run(() => {\n          if (response.abortController.signal.aborted) {\n            return Promise.resolve();\n          }\n\n          return job({\n            state: response.state,\n            write: ({ updateStatus = true } = {}) => {\n              if (response.abortController.signal.aborted) {\n                return;\n              }\n\n              if (updateStatus) {\n                this.setStatus({ status: 'streaming' });\n              }\n\n              const replaceLastMessage =\n                response.state.message.id === this.lastMessage?.id;\n\n              if (replaceLastMessage) {\n                this.state.replaceMessage(\n                  this.state.messages.length - 1,\n                  response.state.message,\n                );\n              } else {\n                this.state.pushMessage(response.state.message);\n              }\n            },\n          });\n        });\n\n      await consumeStream({\n        stream: processUIMessageStream({\n          stream,\n          onToolCall: this.onToolCall,\n          onData: this.onData,\n          messageMetadataSchema: this.messageMetadataSchema,\n          dataPartSchemas: this.dataPartSchemas,\n          runUpdateMessageJob,\n          onError: error => {\n            throw error;\n          },\n        }),\n        abortSignal: response.abortController.signal,\n        onError: error => {\n          throw error;\n        },\n      });\n\n      if (isAbort) {\n        if (isCurrentRequest()) {\n          this.setStatus({ status: 'ready' });\n        }\n        return null;\n      }\n\n      if (isCurrentRequest()) {\n        this.setStatus({ status: 'ready' });\n      }\n    } catch (err) {\n      // Ignore abort errors as they are expected.\n      if (isAbort || (err as any).name === 'AbortError') {\n        isAbort = true;\n        if (isCurrentRequest()) {\n          this.setStatus({ status: 'ready' });\n        }\n        return null;\n      }\n\n      if (!isCurrentRequest()) {\n        return null;\n      }\n\n      isError = true;\n\n      // Network errors such as disconnected, timeout, etc.\n      if (\n        err instanceof TypeError &&\n        (err.message.toLowerCase().includes('fetch') ||\n          err.message.toLowerCase().includes('network'))\n      ) {\n        isDisconnect = true;\n      }\n\n      if (this.onError && err instanceof Error) {\n        this.onError(err);\n      }\n\n      this.setStatus({ status: 'error', error: err as Error });\n    } finally {\n      try {\n        if (activeResponse) {\n          this.onFinish?.({\n            message: activeResponse.state.message,\n            messages: this.state.messages,\n            isAbort,\n            isDisconnect,\n            isError,\n            finishReason: activeResponse.state.finishReason,\n          });\n        }\n      } finally {\n        if (this.activeResponse === activeResponse) {\n          this.activeResponse = undefined;\n        }\n\n        clearActiveResumeRequest();\n      }\n    }\n\n    // automatically send the message if the sendAutomaticallyWhen function returns true\n    if (!isError && (await this.shouldSendAutomatically())) {\n      await this.makeRequest({\n        trigger: 'submit-message',\n        messageId: this.lastMessage?.id,\n        metadata,\n        headers,\n        body,\n      });\n    }\n  }\n}\n","import { UnsupportedFunctionalityError } from '@ai-sdk/provider';\nimport type { FileUIPart } from './ui-messages';\n\nexport async function convertFileListToFileUIParts(\n  files: FileList | undefined,\n): Promise<Array<FileUIPart>> {\n  if (files == null) {\n    return [];\n  }\n\n  // React-native doesn't have a FileList global:\n  if (!globalThis.FileList || !(files instanceof globalThis.FileList)) {\n    throw new UnsupportedFunctionalityError({\n      functionality: 'FileList',\n      message: 'FileList is not supported in the current environment',\n    });\n  }\n\n  return Promise.all(\n    Array.from(files).map(async file => {\n      const { name, type } = file;\n\n      const dataUrl = await new Promise<string>((resolve, reject) => {\n        const reader = new FileReader();\n        reader.onload = readerEvent => {\n          resolve(readerEvent.target?.result as string);\n        };\n        reader.onerror = error => reject(error);\n        reader.readAsDataURL(file);\n      });\n\n      return {\n        type: 'file',\n        mediaType: type,\n        filename: name,\n        url: dataUrl,\n      };\n    }),\n  );\n}\n","import { parseJsonEventStream, type ParseResult } from '@ai-sdk/provider-utils';\nimport {\n  uiMessageChunkSchema,\n  type UIMessageChunk,\n} from '../ui-message-stream/ui-message-chunks';\nimport {\n  HttpChatTransport,\n  type HttpChatTransportInitOptions,\n} from './http-chat-transport';\nimport type { UIMessage } from './ui-messages';\n\nexport class DefaultChatTransport<\n  UI_MESSAGE extends UIMessage,\n> extends HttpChatTransport<UI_MESSAGE> {\n  constructor(options: HttpChatTransportInitOptions<UI_MESSAGE> = {}) {\n    super(options);\n  }\n\n  protected processResponseStream(\n    stream: ReadableStream<Uint8Array<ArrayBufferLike>>,\n  ): ReadableStream<UIMessageChunk> {\n    return parseJsonEventStream({\n      stream,\n      schema: uiMessageChunkSchema,\n    }).pipeThrough(\n      new TransformStream<ParseResult<UIMessageChunk>, UIMessageChunk>({\n        async transform(chunk, controller) {\n          if (!chunk.success) {\n            throw chunk.error;\n          }\n          controller.enqueue(chunk.value);\n        },\n      }),\n    );\n  }\n}\n","import {\n  normalizeHeaders,\n  resolve,\n  type FetchFunction,\n  type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport { EmptyResponseBodyError } from '@ai-sdk/provider';\nimport type { UIMessageChunk } from '../ui-message-stream/ui-message-chunks';\nimport type { ChatTransport } from './chat-transport';\nimport { createUIApiCallError } from './create-ui-api-call-error';\nimport type { UIMessage } from './ui-messages';\n\nexport type PrepareSendMessagesRequest<UI_MESSAGE extends UIMessage> = (\n  options: {\n    id: string;\n    messages: UI_MESSAGE[];\n    requestMetadata: unknown;\n    body: Record<string, any> | undefined;\n    credentials: RequestCredentials | undefined;\n    headers: HeadersInit | undefined;\n    api: string;\n  } & {\n    trigger: 'submit-message' | 'regenerate-message';\n    messageId: string | undefined;\n  },\n) =>\n  | {\n      body: object;\n      headers?: HeadersInit;\n      credentials?: RequestCredentials;\n      api?: string;\n    }\n  | PromiseLike<{\n      body: object;\n      headers?: HeadersInit;\n      credentials?: RequestCredentials;\n      api?: string;\n    }>;\n\nexport type PrepareReconnectToStreamRequest = (options: {\n  id: string;\n  requestMetadata: unknown;\n  body: Record<string, any> | undefined;\n  credentials: RequestCredentials | undefined;\n  headers: HeadersInit | undefined;\n  api: string;\n}) =>\n  | {\n      headers?: HeadersInit;\n      credentials?: RequestCredentials;\n      api?: string;\n    }\n  | PromiseLike<{\n      headers?: HeadersInit;\n      credentials?: RequestCredentials;\n      api?: string;\n    }>;\n\n/**\n * Options for the `HttpChatTransport` class.\n *\n * @param UI_MESSAGE - The type of message to be used in the chat.\n */\nexport type HttpChatTransportInitOptions<UI_MESSAGE extends UIMessage> = {\n  /**\n   * The API URL to be used for the chat transport.\n   * Defaults to '/api/chat'.\n   */\n  api?: string;\n\n  /**\n   * The credentials mode to be used for the fetch request.\n   * Possible values are: 'omit', 'same-origin', 'include'.\n   * Defaults to 'same-origin'.\n   */\n  credentials?: Resolvable<RequestCredentials>;\n\n  /**\n   * HTTP headers to be sent with the API request.\n   */\n  headers?: Resolvable<Record<string, string> | Headers>;\n\n  /**\n   * Extra body object to be sent with the API request.\n   * @example\n   * Send a `sessionId` to the API along with the messages.\n   * ```js\n   * useChat({\n   *   body: {\n   *     sessionId: '123',\n   *   }\n   * })\n   * ```\n   */\n  body?: Resolvable<object>;\n\n  /**\n   * Custom fetch implementation. You can use it as a middleware to intercept requests,\n   * or to provide a custom fetch implementation for e.g. testing.\n   */\n  fetch?: FetchFunction;\n\n  /**\n   * When a function is provided, it will be used\n   * to prepare the request body for the chat API. This can be useful for\n   * customizing the request body based on the messages and data in the chat.\n   */\n  prepareSendMessagesRequest?: PrepareSendMessagesRequest<UI_MESSAGE>;\n\n  /**\n   * When a function is provided, it will be used\n   * to prepare the reconnect request for the chat API. This can be useful for\n   * customizing the request based on the chat session.\n   */\n  prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest;\n};\n\nexport abstract class HttpChatTransport<\n  UI_MESSAGE extends UIMessage,\n> implements ChatTransport<UI_MESSAGE> {\n  protected api: string;\n  protected credentials: HttpChatTransportInitOptions<UI_MESSAGE>['credentials'];\n  protected headers: HttpChatTransportInitOptions<UI_MESSAGE>['headers'];\n  protected body: HttpChatTransportInitOptions<UI_MESSAGE>['body'];\n  protected fetch?: FetchFunction;\n  protected prepareSendMessagesRequest?: PrepareSendMessagesRequest<UI_MESSAGE>;\n  protected prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest;\n\n  constructor({\n    api = '/api/chat',\n    credentials,\n    headers,\n    body,\n    fetch,\n    prepareSendMessagesRequest,\n    prepareReconnectToStreamRequest,\n  }: HttpChatTransportInitOptions<UI_MESSAGE>) {\n    this.api = api;\n    this.credentials = credentials;\n    this.headers = headers;\n    this.body = body;\n    this.fetch = fetch;\n    this.prepareSendMessagesRequest = prepareSendMessagesRequest;\n    this.prepareReconnectToStreamRequest = prepareReconnectToStreamRequest;\n  }\n\n  async sendMessages({\n    abortSignal,\n    ...options\n  }: Parameters<ChatTransport<UI_MESSAGE>['sendMessages']>[0]) {\n    const resolvedBody = await resolve(this.body);\n    const resolvedHeaders = await resolve(this.headers);\n    const resolvedCredentials = await resolve(this.credentials);\n\n    const baseHeaders = {\n      ...normalizeHeaders(resolvedHeaders),\n      ...normalizeHeaders(options.headers),\n    };\n\n    const preparedRequest = await this.prepareSendMessagesRequest?.({\n      api: this.api,\n      id: options.chatId,\n      messages: options.messages,\n      body: { ...resolvedBody, ...options.body },\n      headers: baseHeaders,\n      credentials: resolvedCredentials,\n      requestMetadata: options.metadata,\n      trigger: options.trigger,\n      messageId: options.messageId,\n    });\n\n    const api = preparedRequest?.api ?? this.api;\n    const headers =\n      preparedRequest?.headers !== undefined\n        ? normalizeHeaders(preparedRequest.headers)\n        : baseHeaders;\n    const body =\n      preparedRequest?.body !== undefined\n        ? preparedRequest.body\n        : {\n            ...resolvedBody,\n            ...options.body,\n            id: options.chatId,\n            messages: options.messages,\n            trigger: options.trigger,\n            messageId: options.messageId,\n          };\n    const credentials = preparedRequest?.credentials ?? resolvedCredentials;\n\n    // avoid caching globalThis.fetch in case it is patched by other libraries\n    const fetch = this.fetch ?? globalThis.fetch;\n\n    const response = await fetch(api, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n        ...headers,\n      },\n      body: JSON.stringify(body),\n      credentials,\n      signal: abortSignal,\n    });\n\n    if (!response.ok) {\n      throw await createUIApiCallError({\n        response,\n        url: api,\n        fallbackMessage: 'Failed to fetch the chat response.',\n      });\n    }\n\n    if (!response.body) {\n      throw new EmptyResponseBodyError({\n        message: 'The response body is empty.',\n      });\n    }\n\n    return this.processResponseStream(response.body);\n  }\n\n  async reconnectToStream(\n    options: Parameters<ChatTransport<UI_MESSAGE>['reconnectToStream']>[0],\n  ): Promise<ReadableStream<UIMessageChunk> | null> {\n    const resolvedBody = await resolve(this.body);\n    const resolvedHeaders = await resolve(this.headers);\n    const resolvedCredentials = await resolve(this.credentials);\n\n    const baseHeaders = {\n      ...normalizeHeaders(resolvedHeaders),\n      ...normalizeHeaders(options.headers),\n    };\n\n    const preparedRequest = await this.prepareReconnectToStreamRequest?.({\n      api: this.api,\n      id: options.chatId,\n      body: { ...resolvedBody, ...options.body },\n      headers: baseHeaders,\n      credentials: resolvedCredentials,\n      requestMetadata: options.metadata,\n    });\n\n    const api = preparedRequest?.api ?? `${this.api}/${options.chatId}/stream`;\n    const headers =\n      preparedRequest?.headers !== undefined\n        ? normalizeHeaders(preparedRequest.headers)\n        : baseHeaders;\n    const credentials = preparedRequest?.credentials ?? resolvedCredentials;\n\n    // avoid caching globalThis.fetch in case it is patched by other libraries\n    const fetch = this.fetch ?? globalThis.fetch;\n\n    const response = await fetch(api, {\n      method: 'GET',\n      headers,\n      credentials,\n      signal: options.abortSignal,\n    });\n\n    // no active stream found, so we do not resume\n    if (response.status === 204) {\n      return null;\n    }\n\n    if (!response.ok) {\n      throw await createUIApiCallError({\n        response,\n        url: api,\n        fallbackMessage: 'Failed to fetch the chat response.',\n      });\n    }\n\n    if (!response.body) {\n      throw new EmptyResponseBodyError({\n        message: 'The response body is empty.',\n      });\n    }\n\n    return this.processResponseStream(response.body);\n  }\n\n  protected abstract processResponseStream(\n    stream: ReadableStream<Uint8Array<ArrayBufferLike>>,\n  ): ReadableStream<UIMessageChunk>;\n}\n","import type { Context, Tool, ToolSet } from '@ai-sdk/provider-utils';\nimport type { Agent } from '../agent/agent';\nimport type { Output } from '../generate-text/output';\nimport type { UIMessageStreamOptions } from '../generate-text/stream-text-result';\nimport { toUIMessageStream } from '../ui-message-stream/to-ui-message-stream';\nimport type { UIMessageChunk } from '../ui-message-stream/ui-message-chunks';\nimport type { ChatTransport } from './chat-transport';\nimport { convertToModelMessages } from './convert-to-model-messages';\nimport type {\n  InferUIMessageTools,\n  InferUITools,\n  UIMessage,\n} from './ui-messages';\nimport { validateUIMessagesForAgent } from './validate-ui-messages';\n\n/**\n * Options for the `DirectChatTransport` class.\n */\nexport type DirectChatTransportOptions<\n  CALL_OPTIONS,\n  TOOLS extends ToolSet,\n  RUNTIME_CONTEXT extends Context,\n  OUTPUT extends Output,\n  UI_MESSAGE extends UIMessage<unknown, never, InferUITools<TOOLS>>,\n> = {\n  /**\n   * The agent to use for generating responses.\n   */\n  agent: Agent<CALL_OPTIONS, TOOLS, RUNTIME_CONTEXT, OUTPUT>;\n\n  /**\n   * Options to pass to the agent when calling it.\n   */\n  options?: CALL_OPTIONS;\n} & Omit<UIMessageStreamOptions<UI_MESSAGE>, 'onFinish'>;\n\n/**\n * A transport that directly communicates with an Agent in-process,\n * without going through HTTP. This is useful for:\n * - Server-side rendering scenarios\n * - Testing without network\n * - Single-process applications\n *\n * @example\n * ```tsx\n * import { useChat } from '@ai-sdk/react';\n * import { DirectChatTransport } from 'ai';\n * import { myAgent } from './my-agent';\n *\n * const { messages, sendMessage } = useChat({\n *   transport: new DirectChatTransport({ agent: myAgent }),\n * });\n * ```\n */\nexport class DirectChatTransport<\n  CALL_OPTIONS = never,\n  TOOLS extends ToolSet = {},\n  RUNTIME_CONTEXT extends Context = Context,\n  OUTPUT extends Output = never,\n  UI_MESSAGE extends UIMessage<unknown, never, InferUITools<TOOLS>> = UIMessage<\n    unknown,\n    never,\n    InferUITools<TOOLS>\n  >,\n> implements ChatTransport<UI_MESSAGE> {\n  private readonly agent: Agent<CALL_OPTIONS, TOOLS, RUNTIME_CONTEXT, OUTPUT>;\n  private readonly agentOptions: CALL_OPTIONS | undefined;\n  private readonly uiMessageStreamOptions: Omit<\n    UIMessageStreamOptions<UI_MESSAGE>,\n    'onFinish'\n  >;\n\n  constructor({\n    agent,\n    options,\n    ...uiMessageStreamOptions\n  }: DirectChatTransportOptions<\n    CALL_OPTIONS,\n    TOOLS,\n    RUNTIME_CONTEXT,\n    OUTPUT,\n    UI_MESSAGE\n  >) {\n    this.agent = agent;\n    this.agentOptions = options;\n    this.uiMessageStreamOptions = uiMessageStreamOptions;\n  }\n\n  async sendMessages({\n    messages,\n    abortSignal,\n  }: Parameters<ChatTransport<UI_MESSAGE>['sendMessages']>[0]): Promise<\n    ReadableStream<UIMessageChunk>\n  > {\n    // Validate the incoming UI messages\n    const validatedMessages = await validateUIMessagesForAgent<UI_MESSAGE>({\n      messages,\n      // tools are compatible; the casting is required because the context param is\n      // not available in ui messages\n      tools: this.agent.tools as unknown as {\n        [NAME in keyof InferUIMessageTools<UI_MESSAGE> & string]?: Tool<\n          InferUIMessageTools<UI_MESSAGE>[NAME]['input'],\n          InferUIMessageTools<UI_MESSAGE>[NAME]['output']\n        >;\n      },\n    });\n\n    // Convert UI messages to model messages\n    const modelMessages = await convertToModelMessages(validatedMessages, {\n      tools: this.agent.tools,\n    });\n\n    // Stream from the agent\n    const result = await this.agent.stream({\n      prompt: modelMessages,\n      abortSignal,\n      ...(this.agentOptions !== undefined\n        ? { options: this.agentOptions }\n        : {}),\n    } as Parameters<\n      Agent<CALL_OPTIONS, TOOLS, RUNTIME_CONTEXT, OUTPUT>['stream']\n    >[0]);\n\n    // Return the UI message stream\n    return toUIMessageStream({\n      ...this.uiMessageStreamOptions,\n      stream: result.stream,\n      tools: this.agent.tools,\n    });\n  }\n\n  /**\n   * Direct transport does not support reconnection since there is no\n   * persistent server-side stream to reconnect to.\n   *\n   * @returns Always returns `null`\n   */\n  async reconnectToStream(\n    _options: Parameters<ChatTransport<UI_MESSAGE>['reconnectToStream']>[0],\n  ): Promise<ReadableStream<UIMessageChunk> | null> {\n    return null;\n  }\n}\n","import { isToolUIPart, type UIMessage } from './ui-messages';\n/**\n * Check if the last message is an assistant message with completed tool call approvals.\n * The last step of the message must have at least one tool approval response and\n * all tool approvals must have a response.\n */\nexport function lastAssistantMessageIsCompleteWithApprovalResponses({\n  messages,\n}: {\n  messages: UIMessage[];\n}): boolean {\n  const message = messages[messages.length - 1];\n\n  if (!message) {\n    return false;\n  }\n\n  if (message.role !== 'assistant') {\n    return false;\n  }\n\n  const lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n    return part.type === 'step-start' ? index : lastIndex;\n  }, -1);\n\n  const lastStepToolInvocations = message.parts\n    .slice(lastStepStartIndex + 1)\n    .filter(isToolUIPart);\n\n  return (\n    // has at least one tool approval response\n    lastStepToolInvocations.filter(part => part.state === 'approval-responded')\n      .length > 0 &&\n    // all tool approvals must have a response\n    lastStepToolInvocations.every(\n      part =>\n        part.state === 'output-available' ||\n        part.state === 'output-error' ||\n        part.state === 'output-denied' ||\n        part.state === 'approval-responded',\n    )\n  );\n}\n","import { isToolUIPart, type UIMessage } from './ui-messages';\n/**\n * Check if the last message is an assistant message with completed tool calls.\n * The last step of the message must have at least one tool invocation and\n * all tool invocations must have a result.\n */\nexport function lastAssistantMessageIsCompleteWithToolCalls({\n  messages,\n}: {\n  messages: UIMessage[];\n}): boolean {\n  const message = messages[messages.length - 1];\n\n  if (!message) {\n    return false;\n  }\n\n  if (message.role !== 'assistant') {\n    return false;\n  }\n\n  const lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n    return part.type === 'step-start' ? index : lastIndex;\n  }, -1);\n\n  const lastStepToolInvocations = message.parts\n    .slice(lastStepStartIndex + 1)\n    .filter(isToolUIPart)\n    .filter(part => !part.providerExecuted);\n\n  return (\n    lastStepToolInvocations.length > 0 &&\n    lastStepToolInvocations.every(\n      part =>\n        part.state === 'output-available' || part.state === 'output-error',\n    )\n  );\n}\n","import type { UIMessageChunk } from '../ui-message-stream/ui-message-chunks';\n\nexport function transformTextToUiMessageStream({\n  stream,\n}: {\n  stream: ReadableStream<string>;\n}) {\n  return stream.pipeThrough(\n    new TransformStream<string, UIMessageChunk>({\n      start(controller) {\n        controller.enqueue({ type: 'start' });\n        controller.enqueue({ type: 'start-step' });\n        controller.enqueue({ type: 'text-start', id: 'text-1' });\n      },\n\n      async transform(part, controller) {\n        controller.enqueue({ type: 'text-delta', id: 'text-1', delta: part });\n      },\n\n      async flush(controller) {\n        controller.enqueue({ type: 'text-end', id: 'text-1' });\n        controller.enqueue({ type: 'finish-step' });\n        controller.enqueue({ type: 'finish' });\n      },\n    }),\n  );\n}\n","import type { UIMessageChunk } from '../ui-message-stream/ui-message-chunks';\nimport {\n  HttpChatTransport,\n  type HttpChatTransportInitOptions,\n} from './http-chat-transport';\nimport { transformTextToUiMessageStream } from './transform-text-to-ui-message-stream';\nimport type { UIMessage } from './ui-messages';\n\nexport class TextStreamChatTransport<\n  UI_MESSAGE extends UIMessage,\n> extends HttpChatTransport<UI_MESSAGE> {\n  constructor(options: HttpChatTransportInitOptions<UI_MESSAGE> = {}) {\n    super(options);\n  }\n\n  protected processResponseStream(\n    stream: ReadableStream<Uint8Array<ArrayBufferLike>>,\n  ): ReadableStream<UIMessageChunk> {\n    return transformTextToUiMessageStream({\n      stream: stream.pipeThrough(new TextDecoderStream()),\n    });\n  }\n}\n","import type {\n  FilesV4,\n  FilesV4UploadFileCallOptions,\n  ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n  convertBase64ToUint8Array,\n  detectMediaType,\n} from '@ai-sdk/provider-utils';\nimport type { ProviderMetadata } from '../types/provider-metadata';\nimport type { ProviderReference } from '../types/provider-reference';\nimport type { Warning } from '../types/warning';\nimport type { UploadFileResult } from './upload-file-result';\n\n/**\n * Uploads a file using a files API interface.\n *\n * @param api - The Files API interface to use for uploading.\n * @param data - The file data to upload (tagged `{ type: 'data' | 'text' | 'stream' }`).\n * Stream data is sent without buffering by providers that support streaming\n * uploads (others reject with `UnsupportedFunctionalityError`); the provider\n * consumes the stream — any failed upload, including validation failures\n * before a request is made, cancels it. Do not reuse it.\n * @param mediaType - Optional IANA media type. Auto-detected from file bytes\n * when omitted (falls back to `text/plain` for the `text` variant and\n * `application/octet-stream` for the `stream` variant, which cannot be sniffed).\n * @param filename - Optional filename for the uploaded file. Multipart-based\n * providers default it to `\"blob\"` when omitted.\n * @param abortSignal - Optional signal to cancel the upload.\n * @param headers - Optional additional HTTP headers for the request.\n * @param providerOptions - Additional provider-specific options.\n *\n * @returns A result object containing the provider reference, optional\n * metadata, and — when reported by the provider — `byteSize`, `createdAt`,\n * and `expiresAt` (the provider-applied retention expiry).\n */\nexport async function uploadFile({\n  api,\n  data: dataArg,\n  mediaType: mediaTypeArg,\n  filename,\n  abortSignal,\n  headers,\n  providerOptions,\n}: {\n  /**\n   * The files API interface to use for uploading.\n   * Can be a `FilesV4` instance or a `ProviderV4` instance with a `files()` method.\n   */\n  api: FilesV4 | ProviderV4;\n} & Omit<FilesV4UploadFileCallOptions, 'mediaType' | 'data'> & {\n    /**\n     * The file data. Accepts the tagged `{ type: 'data' | 'text' }` shapes, or\n     * the shorthand `Uint8Array | string` (treated as `{ type: 'data', data }`).\n     */\n    data: FilesV4UploadFileCallOptions['data'] | Uint8Array | string;\n\n    /**\n     * Optional IANA media type of the file. Auto-detected from file bytes when\n     * omitted; falls back to `text/plain` for the `text` variant.\n     */\n    mediaType?: string;\n  }): Promise<UploadFileResult> {\n  const data: FilesV4UploadFileCallOptions['data'] =\n    dataArg instanceof Uint8Array || typeof dataArg === 'string'\n      ? { type: 'data', data: dataArg }\n      : dataArg;\n\n  // stream data cannot be sniffed without consuming it\n  const mediaType =\n    mediaTypeArg ??\n    (data.type === 'text'\n      ? 'text/plain'\n      : data.type === 'stream'\n        ? 'application/octet-stream'\n        : (detectMediaType({ data: data.data }) ??\n          (isLikelyText(data.data)\n            ? 'text/plain'\n            : 'application/octet-stream')));\n\n  let result;\n  try {\n    const filesApi: FilesV4 =\n      'uploadFile' in api\n        ? api\n        : typeof api.files === 'function'\n          ? api.files()\n          : (() => {\n              throw new Error(\n                'The provider does not support file uploads. Make sure it exposes a files() method.',\n              );\n            })();\n\n    result = await filesApi.uploadFile({\n      data,\n      mediaType,\n      filename,\n      abortSignal,\n      headers,\n      providerOptions,\n    });\n  } catch (error) {\n    // ownership guarantee: a failed upload releases the stream, even when\n    // the provider rejected before (or without) consuming it\n    if (data.type === 'stream') {\n      await data.stream.cancel(error).catch(() => {});\n    }\n    throw error;\n  }\n\n  return new DefaultUploadFileResult({\n    providerReference: result.providerReference,\n    mediaType: result.mediaType,\n    filename: result.filename,\n    byteSize: result.byteSize,\n    createdAt: result.createdAt,\n    expiresAt: result.expiresAt,\n    providerMetadata: result.providerMetadata,\n    warnings: result.warnings,\n  });\n}\n\nclass DefaultUploadFileResult implements UploadFileResult {\n  readonly providerReference: ProviderReference;\n  readonly mediaType?: string;\n  readonly filename?: string;\n  readonly byteSize?: number;\n  readonly createdAt?: Date;\n  readonly expiresAt?: Date;\n  readonly providerMetadata?: ProviderMetadata;\n  readonly warnings: Array<Warning>;\n\n  constructor(options: {\n    providerReference: ProviderReference;\n    mediaType?: string;\n    filename?: string;\n    byteSize?: number;\n    createdAt?: Date;\n    expiresAt?: Date;\n    providerMetadata?: ProviderMetadata;\n    warnings: Array<Warning>;\n  }) {\n    this.providerReference = options.providerReference;\n    this.mediaType = options.mediaType;\n    this.filename = options.filename;\n    this.byteSize = options.byteSize;\n    this.createdAt = options.createdAt;\n    this.expiresAt = options.expiresAt;\n    this.providerMetadata = options.providerMetadata;\n    this.warnings = options.warnings;\n  }\n}\n\nfunction isLikelyText(data: Uint8Array | string): boolean {\n  /*\n   * Limit checks to 512 bytes for performance.\n   * 4 base64 characters represent 3 bytes, and we use a small margin of 4 bytes just to be safe.\n   */\n  const CHECK_LENGTH = 512;\n  const BASE64_CHECK_LENGTH = Math.ceil((CHECK_LENGTH + 4) / 3) * 4;\n\n  const bytes =\n    typeof data === 'string'\n      ? convertBase64ToUint8Array(\n          data.substring(0, Math.min(data.length, BASE64_CHECK_LENGTH)),\n        )\n      : data;\n\n  const checkLength = Math.min(bytes.length, CHECK_LENGTH);\n  if (checkLength === 0) return false;\n\n  for (let i = 0; i < checkLength; i++) {\n    const byte = bytes[i];\n    if (\n      byte === 0x00 ||\n      (byte < 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d)\n    ) {\n      return false;\n    }\n  }\n  return true;\n}\n","import type {\n  ProviderV4,\n  SkillsV4,\n  SkillsV4File,\n  SkillsV4UploadSkillCallOptions,\n} from '@ai-sdk/provider';\nimport type { UploadSkillResult } from './upload-skill-result';\n\ntype UploadSkillFile = Omit<SkillsV4File, 'data'> & {\n  /**\n   * The file data. Accepts the tagged `{ type: 'data' | 'text' }` shapes, or\n   * the shorthand `Uint8Array | string` (treated as `{ type: 'data', data }`).\n   */\n  data: SkillsV4File['data'] | Uint8Array | string;\n};\n\nexport async function uploadSkill({\n  api,\n  files,\n  displayTitle,\n  providerOptions,\n}: {\n  api: SkillsV4 | ProviderV4;\n} & Omit<SkillsV4UploadSkillCallOptions, 'files'> & {\n    files: UploadSkillFile[];\n  }): Promise<UploadSkillResult> {\n  const skillsApi: SkillsV4 =\n    'uploadSkill' in api\n      ? api\n      : typeof api.skills === 'function'\n        ? api.skills()\n        : (() => {\n            throw new Error(\n              'The provider does not support skills. Make sure it exposes a skills() method.',\n            );\n          })();\n\n  const normalizedFiles: SkillsV4File[] = files.map(file => ({\n    ...file,\n    data:\n      file.data instanceof Uint8Array || typeof file.data === 'string'\n        ? { type: 'data', data: file.data }\n        : file.data,\n  }));\n\n  const result = await skillsApi.uploadSkill({\n    files: normalizedFiles,\n    displayTitle,\n    providerOptions,\n  });\n\n  return result;\n}\n","// From https://github.com/vercel/swr/blob/master/src/libs/hash.ts\n// use WeakMap to store the object->key mapping\n// so the objects can be garbage collected.\n// WeakMap uses a hashtable under the hood, so the lookup\n// complexity is almost O(1).\nconst table = new WeakMap()\n\n// counter of the key\nlet counter = 0\n\n// hashes an array of objects and returns a string\nexport default function hash (args: any[]): string {\n  if (!args.length) return ''\n  let key = 'arg'\n  for (let i = 0; i < args.length; ++i) {\n    let _hash\n    if (\n      args[i] === null ||\n      (typeof args[i] !== 'object' && typeof args[i] !== 'function')\n    ) {\n      // need to consider the case that args[i] is a string:\n      // args[i]        _hash\n      // \"undefined\" -> '\"undefined\"'\n      // undefined   -> 'undefined'\n      // 123         -> '123'\n      // null        -> 'null'\n      // \"null\"      -> '\"null\"'\n      if (typeof args[i] === 'string') {\n        _hash = '\"' + args[i] + '\"'\n      } else {\n        _hash = String(args[i])\n      }\n    } else {\n      if (!table.has(args[i])) {\n        _hash = counter\n        table.set(args[i], counter++)\n      } else {\n        _hash = table.get(args[i])\n      }\n    }\n    key += '@' + _hash\n  }\n  return key\n}\n","import { IKey } from '../types'\nimport hash from '../lib/hash'\nexport interface ICacheItem<Data> {\n  data: Data,\n  createdAt: number,\n  expiresAt: number\n}\n\nfunction serializeKeyDefault (key: IKey): string {\n  if (typeof key === 'function') {\n    try {\n      key = key()\n    } catch (err) {\n      // dependencies not ready\n      key = ''\n    }\n  }\n\n  if (Array.isArray(key)) {\n    key = hash(key)\n  } else {\n    // convert null to ''\n    key = String(key || '')\n  }\n\n  return key\n}\n\nexport default class SWRVCache<CacheData> {\n  protected ttl: number\n  private items?: Map<string, ICacheItem<CacheData>>\n\n  constructor (ttl = 0) {\n    this.items = new Map()\n    this.ttl = ttl\n  }\n\n  serializeKey (key: IKey): string {\n    return serializeKeyDefault(key)\n  }\n\n  get (k: string): ICacheItem<CacheData> {\n    const _key = this.serializeKey(k)\n    return this.items.get(_key)\n  }\n\n  set (k: string, v: any, ttl: number) {\n    const _key = this.serializeKey(k)\n    const timeToLive = ttl || this.ttl\n    const now = Date.now()\n    const item = {\n      data: v,\n      createdAt: now,\n      expiresAt: timeToLive ? now + timeToLive : Infinity\n    }\n\n    this.dispatchExpire(timeToLive, item, _key)\n    this.items.set(_key, item)\n  }\n\n  dispatchExpire (ttl, item, serializedKey) {\n    ttl && setTimeout(() => {\n      const current = Date.now()\n      const hasExpired = current >= item.expiresAt\n      if (hasExpired) this.delete(serializedKey)\n    }, ttl)\n  }\n\n  delete (serializedKey: string) {\n    this.items.delete(serializedKey)\n  }\n}\n","/**              ____\n *--------------/    \\.------------------/\n *            /  swrv  \\.               /    //\n *          /         / /\\.            /    //\n *        /     _____/ /   \\.         /\n *      /      /  ____/   .  \\.      /\n *    /        \\ \\_____        \\.   /\n *  /     .     \\_____ \\         \\ /    //\n *  \\          _____/ /        ./ /    //\n *    \\       / _____/       ./  /\n *      \\    / /      .    ./   /\n *        \\ / /          ./    /\n *    .     \\/         ./     /    //\n *            \\      ./      /    //\n *              \\.. /       /\n *         .     |||       /\n *               |||      /\n *     .         |||     /    //\n *               |||    /    //\n *               |||   /\n */\nimport {\n  reactive,\n  watch,\n  ref,\n  toRefs,\n  // isRef,\n  getCurrentScope,\n  onScopeDispose,\n  isReadonly\n} from 'vue'\nimport webPreset from './lib/web-preset'\nimport SWRVCache from './cache'\nimport { IConfig, IKey, IResponse, fetcherFn, revalidateOptions } from './types'\n\ntype StateRef<Data, Error> = {\n  data: Data, error: Error, isValidating: boolean, isLoading: boolean, revalidate: Function, key: any\n};\n\nconst DATA_CACHE = new SWRVCache<Omit<IResponse, 'mutate'>>()\nconst REF_CACHE = new SWRVCache<StateRef<any, any>[]>()\nconst PROMISES_CACHE = new SWRVCache<Omit<IResponse, 'mutate'>>()\n\nconst defaultConfig: IConfig = {\n  cache: DATA_CACHE,\n  refreshInterval: 0,\n  ttl: 0,\n  serverTTL: 1000,\n  dedupingInterval: 2000,\n  revalidateOnFocus: true,\n  revalidateDebounce: 0,\n  shouldRetryOnError: true,\n  errorRetryInterval: 5000,\n  errorRetryCount: 5,\n  fetcher: webPreset.fetcher,\n  isOnline: webPreset.isOnline,\n  isDocumentVisible: webPreset.isDocumentVisible\n}\n\n/**\n * Cache the refs for later revalidation\n */\nfunction setRefCache (key: string, theRef: StateRef<any, any>, ttl: number) {\n  const refCacheItem = REF_CACHE.get(key)\n  if (refCacheItem) {\n    refCacheItem.data.push(theRef)\n  } else {\n    // #51 ensures ref cache does not evict too soon\n    const gracePeriod = 5000\n    REF_CACHE.set(key, [theRef], ttl > 0 ? ttl + gracePeriod : ttl)\n  }\n}\n\nfunction onErrorRetry (revalidate: (any, opts: revalidateOptions) => void, errorRetryCount: number, config: IConfig): void {\n  if (!config.isDocumentVisible()) {\n    return\n  }\n\n  if (config.errorRetryCount !== undefined && errorRetryCount > config.errorRetryCount) {\n    return\n  }\n\n  const count = Math.min(errorRetryCount || 0, config.errorRetryCount)\n  const timeout = count * config.errorRetryInterval\n  setTimeout(() => {\n    revalidate(null, { errorRetryCount: count + 1, shouldRetryOnError: true })\n  }, timeout)\n}\n\n/**\n * Evaluate shouldRetryOnError option\n */\nfunction resolveRetryFlag ({\n  shouldRetry = undefined,\n  error\n}: {\n   shouldRetry?: boolean | ((err: Error) => boolean),\n   error: unknown,\n }): boolean {\n  if (typeof shouldRetry === 'function') {\n    return shouldRetry(error as Error)\n  }\n\n  if (typeof shouldRetry === 'boolean') {\n    return shouldRetry\n  }\n\n  return defaultConfig.shouldRetryOnError as boolean\n}\n\n/**\n * Main mutation function for receiving data from promises to change state and\n * set data cache\n */\nconst mutate = async <Data>(key: string, res: Promise<Data> | Data, cache = DATA_CACHE, ttl = defaultConfig.ttl) => {\n  let data, error, isValidating\n\n  if (isPromise(res)) {\n    try {\n      data = await res\n    } catch (err) {\n      error = err\n    }\n  } else {\n    data = res\n  }\n\n  // eslint-disable-next-line prefer-const\n  isValidating = false\n\n  const newData = { data, error, isValidating }\n  if (typeof data !== 'undefined') {\n    try {\n      cache.set(key, newData, ttl)\n    } catch (err) {\n      console.error('swrv(mutate): failed to set cache', err)\n    }\n  }\n\n  /**\n   * Revalidate all swrv instances with new data\n   */\n  const stateRef = REF_CACHE.get(key)\n  if (stateRef && stateRef.data.length) {\n    // This filter fixes #24 race conditions to only update ref data of current\n    // key, while data cache will continue to be updated if revalidation is\n    // fired\n    let refs = stateRef.data.filter(r => r.key === key)\n\n    refs.forEach((r, idx) => {\n      if (typeof newData.data !== 'undefined') {\n        r.data = newData.data\n      }\n      r.error = newData.error\n      r.isValidating = newData.isValidating\n      r.isLoading = newData.isValidating\n\n      const isLast = idx === refs.length - 1\n      if (!isLast) {\n        // Clean up refs that belonged to old keys\n        delete refs[idx]\n      }\n    })\n\n    refs = refs.filter(Boolean)\n  }\n\n  return newData\n}\n\n/* Stale-While-Revalidate hook to handle fetching, caching, validation, and more... */\nfunction useSWRV<Data = any, Error = any>(\n  key: IKey\n): IResponse<Data, Error>\nfunction useSWRV<Data = any, Error = any>(\n  key: IKey,\n  fn: fetcherFn<Data> | undefined | null,\n  config?: IConfig\n): IResponse<Data, Error>\nfunction useSWRV<Data = any, E = any> (...args): IResponse<Data, E> {\n  let key: IKey\n  let fn: fetcherFn<Data> | undefined | null\n  let config: IConfig = { ...defaultConfig }\n  let unmounted = false\n  let isHydrated = false\n\n  if (!getCurrentScope()) {\n    console.error('useSWRV must be called inside setup() or an active effectScope().')\n    return null\n  }\n\n  const IS_SERVER = typeof window === 'undefined' || typeof document === 'undefined'\n\n  // #region ssr\n  /**\n  const isSsrHydration = Boolean(\n    \\!IS_SERVER &&\n    vm.$vnode &&\n    vm.$vnode.elm &&\n    vm.$vnode.elm.dataset &&\n    vm.$vnode.elm.dataset.swrvKey)\n  */\n  // #endregion\n\n  if (args.length >= 1) {\n    key = args[0]\n  }\n  if (args.length >= 2) {\n    fn = args[1]\n  }\n  if (args.length > 2) {\n    config = {\n      ...config,\n      ...args[2]\n    }\n  }\n\n  const ttl = IS_SERVER ? config.serverTTL : config.ttl\n  const keyRef = typeof key === 'function' ? (key as any) : ref(key)\n\n  if (typeof fn === 'undefined') {\n    // use the global fetcher\n    fn = config.fetcher\n  }\n\n  let stateRef = null as StateRef<Data, E>\n\n  // #region ssr\n  // if (isSsrHydration) {\n  //   // component was ssrHydrated, so make the ssr reactive as the initial data\n  //   const swrvState = (window as any).__SWRV_STATE__ ||\n  //     ((window as any).__NUXT__ && (window as any).__NUXT__.swrv) || []\n  //   const swrvKey = +(vm as any).$vnode.elm.dataset.swrvKey\n\n  //   if (swrvKey !== undefined && swrvKey !== null) {\n  //     const nodeState = swrvState[swrvKey] || []\n  //     const instanceState = nodeState[isRef(keyRef) ? keyRef.value : keyRef()]\n\n  //     if (instanceState) {\n  //       stateRef = reactive(instanceState)\n  //       isHydrated = true\n  //     }\n  //   }\n  // }\n  // #endregion\n\n  if (!stateRef) {\n    stateRef = reactive({\n      data: undefined,\n      error: undefined,\n      isValidating: true,\n      isLoading: true,\n      key: null\n    }) as StateRef<Data, E>\n  }\n\n  /**\n   * Revalidate the cache, mutate data\n   */\n  const revalidate = async (data?: fetcherFn<Data>, opts?: revalidateOptions) => {\n    const isFirstFetch = stateRef.data === undefined\n    const keyVal = keyRef.value\n    if (!keyVal) { return }\n\n    const cacheItem = config.cache.get(keyVal)\n    const newData = cacheItem && cacheItem.data\n\n    stateRef.isValidating = true\n    stateRef.isLoading = !newData\n    if (newData) {\n      stateRef.data = newData.data\n      stateRef.error = newData.error\n    }\n\n    const fetcher = data || fn\n    if (\n      !fetcher ||\n      (!config.isDocumentVisible() && !isFirstFetch) ||\n      (opts?.forceRevalidate !== undefined && !opts?.forceRevalidate)\n    ) {\n      stateRef.isValidating = false\n      stateRef.isLoading = false\n      return\n    }\n\n    // Dedupe items that were created in the last interval #76\n    if (cacheItem) {\n      const shouldRevalidate = Boolean(\n        ((Date.now() - cacheItem.createdAt) >= config.dedupingInterval) || opts?.forceRevalidate\n      )\n\n      if (!shouldRevalidate) {\n        stateRef.isValidating = false\n        stateRef.isLoading = false\n        return\n      }\n    }\n\n    const trigger = async () => {\n      const promiseFromCache = PROMISES_CACHE.get(keyVal)\n      if (!promiseFromCache) {\n        const fetcherArgs = Array.isArray(keyVal) ? keyVal : [keyVal]\n        const newPromise = fetcher(...fetcherArgs)\n        PROMISES_CACHE.set(keyVal, newPromise, config.dedupingInterval)\n        await mutate(keyVal, newPromise, config.cache, ttl)\n      } else {\n        await mutate(keyVal, promiseFromCache.data, config.cache, ttl)\n      }\n      stateRef.isValidating = false\n      stateRef.isLoading = false\n      PROMISES_CACHE.delete(keyVal)\n      if (stateRef.error !== undefined) {\n        const configAllows = resolveRetryFlag({ shouldRetry: config.shouldRetryOnError, error: stateRef.error })\n        const optsAllows = resolveRetryFlag({\n          shouldRetry: opts ? opts.shouldRetryOnError : true,\n          error: stateRef.error\n        })\n\n        const shouldRetryOnError: boolean = !unmounted && configAllows && optsAllows\n        if (shouldRetryOnError) {\n          onErrorRetry(revalidate, opts ? opts.errorRetryCount : 1, config)\n        }\n      }\n    }\n\n    if (newData && config.revalidateDebounce) {\n      setTimeout(async () => {\n        if (!unmounted) {\n          await trigger()\n        }\n      }, config.revalidateDebounce)\n    } else {\n      await trigger()\n    }\n  }\n\n  const revalidateCall = async () => revalidate(null, { shouldRetryOnError: false })\n  let timer = null\n  if (!IS_SERVER) {\n    const tick = async () => {\n      // component might un-mount during revalidate, so do not set a new timeout\n      // if this is the case, but continue to revalidate since promises can't\n      // be cancelled and new hook instances might rely on promise/data cache or\n      // from pre-fetch\n      if (!stateRef.error && config.isOnline()) {\n        // if API request errored, we stop polling in this round\n        // and let the error retry function handle it\n        await revalidate()\n      } else {\n        if (timer) {\n          clearTimeout(timer)\n          timer = null\n        }\n      }\n\n      if (config.refreshInterval && !unmounted) {\n        timer = setTimeout(tick, config.refreshInterval)\n      }\n    }\n\n    if (config.refreshInterval) {\n      timer = setTimeout(tick, config.refreshInterval)\n    }\n\n    if (config.revalidateOnFocus) {\n      document.addEventListener('visibilitychange', revalidateCall, false)\n      window.addEventListener('focus', revalidateCall, false)\n    }\n  }\n\n  onScopeDispose(() => {\n    unmounted = true\n\n    if (timer) {\n      clearTimeout(timer)\n      timer = null\n    }\n\n    if (!IS_SERVER && config.revalidateOnFocus) {\n      document.removeEventListener('visibilitychange', revalidateCall, false)\n      window.removeEventListener('focus', revalidateCall, false)\n    }\n\n    const refCacheItem = REF_CACHE.get(keyRef.value)\n    if (refCacheItem) {\n      refCacheItem.data = refCacheItem.data.filter((ref) => ref !== stateRef)\n    }\n  })\n\n  // #region ssr\n  // if (IS_SERVER) {\n  //   // make sure srwv exists in ssrContext\n  //   let swrvRes = []\n  //   if (vm.$ssrContext) {\n  //     swrvRes = vm.$ssrContext.swrv = vm.$ssrContext.swrv || swrvRes\n  //   }\n\n  //   const ssrKey = swrvRes.length\n  //   if (!vm.$vnode || (vm.$node && !vm.$node.data)) {\n  //     vm.$vnode = {\n  //       data: { attrs: { 'data-swrv-key': ssrKey } }\n  //     }\n  //   }\n\n  //   const attrs = (vm.$vnode.data.attrs = vm.$vnode.data.attrs || {})\n  //   attrs['data-swrv-key'] = ssrKey\n\n  //   // Nuxt compatibility\n  //   if (vm.$ssrContext && vm.$ssrContext.nuxt) {\n  //     vm.$ssrContext.nuxt.swrv = swrvRes\n  //   }\n\n  //   onServerPrefetch(async () => {\n  //     await revalidate()\n\n  //     if (!swrvRes[ssrKey]) swrvRes[ssrKey] = {}\n\n  //     swrvRes[ssrKey][keyRef.value] = {\n  //       data: stateRef.data,\n  //       error: stateRef.error,\n  //       isValidating: stateRef.isValidating\n  //     }\n  //   })\n  // }\n  // #endregion\n\n  /**\n   * Revalidate when key dependencies change\n   */\n  try {\n    watch(keyRef, (val) => {\n      if (!isReadonly(keyRef)) {\n        keyRef.value = val\n      }\n      stateRef.key = val\n      stateRef.isValidating = Boolean(val)\n      setRefCache(keyRef.value, stateRef, ttl)\n\n      if (!IS_SERVER && !isHydrated && keyRef.value) {\n        revalidate()\n      }\n      isHydrated = false\n    }, {\n      immediate: true\n    })\n  } catch {\n    // do nothing\n  }\n\n  const res: IResponse = {\n    ...toRefs(stateRef),\n    mutate: (data, opts: revalidateOptions) => revalidate(data, {\n      ...opts,\n      forceRevalidate: true\n    })\n  }\n\n  return res\n}\n\nfunction isPromise<T> (p: any): p is Promise<T> {\n  return p !== null && typeof p === 'object' && typeof p.then === 'function'\n}\n\nexport { mutate }\nexport default useSWRV\n","function isOnline (): boolean {\n  if (typeof navigator.onLine !== 'undefined') {\n    return navigator.onLine\n  }\n  // always assume it's online\n  return true\n}\n\nfunction isDocumentVisible (): boolean {\n  if (\n    typeof document !== 'undefined' &&\n    typeof document.visibilityState !== 'undefined'\n  ) {\n    return document.visibilityState !== 'hidden'\n  }\n  // always assume it's visible\n  return true\n}\n\nconst fetcher = url => fetch(url).then(res => res.json())\n\nexport default {\n  isOnline,\n  isDocumentVisible,\n  fetcher\n}\n\n","import SWRVCache from './cache'\nimport useSWRV, { mutate } from './use-swrv'\n\nexport {\n  IConfig\n} from './types'\nexport { mutate, SWRVCache }\nexport default useSWRV\n","import {\n  isAbortError,\n  safeValidateTypes,\n  type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport {\n  asSchema,\n  isDeepEqualData,\n  parsePartialJson,\n  type DeepPartial,\n  type FlexibleSchema,\n  type InferSchema,\n} from 'ai';\nimport type * as SwrvModule from 'swrv';\nimport swrv from 'swrv';\nimport { ref, type Ref } from 'vue';\n// use function to allow for mocking in tests\nconst getOriginalFetch = () => fetch;\n\nexport type UseObjectOptions<SCHEMA extends FlexibleSchema, RESULT> = {\n  /** API endpoint that streams JSON chunks matching the schema */\n  api: string;\n\n  /** Schema that defines the final object shape */\n  schema: SCHEMA;\n\n  /** Shared state key. If omitted a random one is generated */\n  id?: string;\n\n  /** Initial partial value */\n  initialValue?: DeepPartial<RESULT>;\n\n  /** Optional custom fetch implementation */\n  fetch?: FetchFunction;\n\n  /** Called when stream ends */\n  onFinish?: (event: {\n    object: RESULT | undefined;\n    error: Error | undefined;\n  }) => Promise<void> | void;\n\n  /** Called on error */\n  onError?: (error: Error) => void;\n\n  /** Extra request headers */\n  headers?: Record<string, string> | Headers;\n\n  /** Request credentials mode. Defaults to 'same-origin' if omitted */\n  credentials?: RequestCredentials;\n};\n\nexport type UseObjectHelpers<RESULT, INPUT> = {\n  /** POST the input and start streaming */\n  submit: (input: INPUT) => void;\n\n  /** Current partial object, updated as chunks arrive */\n  object: Ref<DeepPartial<RESULT> | undefined>;\n\n  /** Latest error if any */\n  error: Ref<Error | undefined>;\n\n  /** Loading flag for the in-flight request */\n  isLoading: Ref<boolean | undefined>;\n\n  /** Abort the current request. Keeps current partial object. */\n  stop: () => void;\n\n  /** Abort and clear all state */\n  clear: () => void;\n};\n\nlet uniqueId = 0;\n\n// @ts-expect-error - some issues with the default export of useSWRV\nconst useSWRV = (swrv.default as (typeof SwrvModule)['default']) || swrv;\nconst store: Record<string, any> = {};\n\nexport function useObject<\n  SCHEMA extends FlexibleSchema,\n  RESULT = InferSchema<SCHEMA>,\n  INPUT = any,\n>({\n  api,\n  id,\n  schema,\n  initialValue,\n  fetch,\n  onError,\n  onFinish,\n  headers,\n  credentials,\n}: UseObjectOptions<SCHEMA, RESULT>): UseObjectHelpers<RESULT, INPUT> {\n  // Generate an unique id for the object if not provided.\n  const completionId = id || `completion-${uniqueId++}`;\n\n  const key = `${api}|${completionId}`;\n  const { data, mutate: originalMutate } = useSWRV<\n    DeepPartial<RESULT> | undefined\n  >(key, () => (key in store ? store[key] : initialValue));\n\n  const { data: isLoading, mutate: mutateLoading } = useSWRV<boolean>(\n    `${completionId}-loading`,\n    null,\n  );\n\n  isLoading.value ??= false;\n  data.value ||= initialValue as DeepPartial<RESULT> | undefined;\n\n  const mutateObject = (value: DeepPartial<RESULT> | undefined) => {\n    store[key] = value;\n    return originalMutate();\n  };\n\n  const error = ref<Error | undefined>(undefined);\n  let abortController: AbortController | null = null;\n\n  const stop = async () => {\n    if (abortController) {\n      try {\n        abortController.abort();\n      } catch {\n        // ignore\n      } finally {\n        abortController = null;\n      }\n    }\n    await mutateLoading(() => false);\n  };\n\n  const clearObject = async () => {\n    error.value = undefined;\n    await mutateLoading(() => false);\n    await mutateObject(undefined);\n    // Need to explicitly set the value to undefined to trigger a re-render\n    data.value = undefined;\n  };\n\n  const clear = async () => {\n    await stop();\n    await clearObject();\n  };\n\n  const submit = async (input: INPUT) => {\n    try {\n      await clearObject();\n      await mutateLoading(() => true);\n\n      abortController = new AbortController();\n\n      const actualFetch = fetch ?? getOriginalFetch();\n      const response = await actualFetch(api, {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/json',\n          ...(headers as any),\n        },\n        credentials: credentials ?? 'same-origin',\n        signal: abortController.signal,\n        body: JSON.stringify(input),\n      });\n\n      if (!response.ok) {\n        throw new Error(\n          (await response.text()) || 'Failed to fetch the response.',\n        );\n      }\n\n      if (!response.body) {\n        throw new Error('The response body is empty.');\n      }\n\n      let accumulatedText = '';\n      let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n      await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n        new WritableStream<string>({\n          async write(chunk) {\n            accumulatedText += chunk;\n            const { value } = await parsePartialJson(accumulatedText);\n            const currentObject = value as DeepPartial<RESULT>;\n            if (!isDeepEqualData(latestObject, currentObject)) {\n              latestObject = currentObject;\n              await mutateObject(currentObject);\n            }\n          },\n          async close() {\n            await mutateLoading(() => false);\n            abortController = null;\n\n            if (onFinish) {\n              const validationResult = await safeValidateTypes({\n                value: latestObject,\n                schema: asSchema(schema),\n              });\n\n              onFinish(\n                validationResult.success\n                  ? {\n                      object: validationResult.value as RESULT,\n                      error: undefined,\n                    }\n                  : { object: undefined, error: validationResult.error },\n              );\n            }\n          },\n        }),\n      );\n    } catch (err: unknown) {\n      if (isAbortError(err)) return;\n\n      if (onError && err instanceof Error) onError(err);\n\n      await mutateLoading(() => false);\n      error.value = err instanceof Error ? err : new Error(String(err));\n    }\n  };\n\n  return {\n    submit,\n    object: data,\n    error,\n    isLoading,\n    stop,\n    clear,\n  };\n}\n","import {\n  callCompletionApi,\n  type CompletionRequestOptions,\n  type UseCompletionOptions,\n} from 'ai';\nimport type * as SwrvModule from 'swrv';\nimport swrv from 'swrv';\nimport { ref, unref, type Ref } from 'vue';\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers<BODY extends object = object> = {\n  /** The current completion result */\n  completion: Ref<string>;\n  /** The error object of the API request */\n  error: Ref<undefined | Error>;\n  /**\n   * Send a new prompt to the API endpoint and update the completion state.\n   */\n  complete: (\n    prompt: string,\n    options?: CompletionRequestOptions<BODY>,\n  ) => Promise<string | null | undefined>;\n  /**\n   * Abort the current API request but keep the generated tokens.\n   */\n  stop: () => void;\n  /**\n   * Update the `completion` state locally.\n   */\n  setCompletion: (completion: string) => void;\n  /** The current value of the input */\n  input: Ref<string>;\n  /**\n   * Form submission handler to automatically reset input and append a user message\n   * @example\n   * ```jsx\n   * <form @submit=\"handleSubmit\">\n   *  <input @change=\"handleInputChange\" v-model=\"input\" />\n   * </form>\n   * ```\n   */\n  handleSubmit: (event?: { preventDefault?: () => void }) => void;\n  /** Whether the API request is in progress */\n  isLoading: Ref<boolean | undefined>;\n};\n\nlet uniqueId = 0;\n\n// @ts-expect-error - some issues with the default export of useSWRV\nconst useSWRV = (swrv.default as (typeof SwrvModule)['default']) || swrv;\nconst store: Record<string, any> = {};\n\nexport function useCompletion<BODY extends object = object>({\n  api = '/api/completion',\n  id,\n  initialCompletion = '',\n  initialInput = '',\n  credentials,\n  headers,\n  body,\n  streamProtocol,\n  onFinish,\n  onError,\n  fetch,\n}: UseCompletionOptions<NoInfer<BODY>> = {}): UseCompletionHelpers<BODY> {\n  // Generate an unique id for the completion if not provided.\n  const completionId = id || `completion-${uniqueId++}`;\n\n  const key = `${api}|${completionId}`;\n  const { data, mutate: originalMutate } = useSWRV<string>(\n    key,\n    () => store[key] ?? initialCompletion,\n  );\n\n  const { data: isLoading, mutate: mutateLoading } = useSWRV<boolean>(\n    `${completionId}-loading`,\n    null,\n  );\n\n  isLoading.value ??= false;\n\n  // Force the `data` to be `initialCompletion` if it's `undefined`.\n  data.value ??= initialCompletion;\n\n  const mutate = (data: string) => {\n    store[key] = data;\n    return originalMutate();\n  };\n\n  // Because of the `initialData` option, the `data` will never be `undefined`.\n  const completion = data as Ref<string>;\n\n  const error = ref<undefined | Error>(undefined);\n\n  let abortController: AbortController | null = null;\n\n  async function triggerRequest(\n    prompt: string,\n    options?: CompletionRequestOptions<BODY>,\n  ) {\n    return callCompletionApi({\n      api,\n      prompt,\n      credentials,\n      headers: {\n        ...headers,\n        ...options?.headers,\n      },\n      body: {\n        ...unref(body),\n        ...options?.body,\n      },\n      streamProtocol,\n      setCompletion: mutate,\n      setLoading: loading => mutateLoading(() => loading),\n      setError: err => {\n        error.value = err;\n      },\n      setAbortController: controller => {\n        abortController = controller;\n      },\n      onFinish,\n      onError,\n      fetch,\n    });\n  }\n\n  const complete: UseCompletionHelpers<BODY>['complete'] = async (\n    prompt,\n    options,\n  ) => {\n    return triggerRequest(prompt, options);\n  };\n\n  const stop = () => {\n    if (abortController) {\n      abortController.abort();\n      abortController = null;\n    }\n  };\n\n  const setCompletion = (completion: string) => {\n    mutate(completion);\n  };\n\n  const input = ref(initialInput);\n\n  const handleSubmit = (event?: { preventDefault?: () => void }) => {\n    event?.preventDefault?.();\n    const inputValue = input.value;\n    return inputValue ? complete(inputValue) : undefined;\n  };\n\n  return {\n    completion,\n    complete,\n    error,\n    stop,\n    setCompletion,\n    input,\n    handleSubmit,\n    isLoading,\n  };\n}\n","import {\n  AbstractChat,\n  type ChatInit,\n  type ChatState,\n  type ChatStatus,\n  type UIMessage,\n} from 'ai';\nimport { ref, type Ref } from 'vue';\nclass VueChatState<\n  UI_MESSAGE extends UIMessage,\n> implements ChatState<UI_MESSAGE> {\n  private messagesRef: Ref<UI_MESSAGE[]>;\n  private statusRef = ref<ChatStatus>('ready');\n  private errorRef = ref<Error | undefined>(undefined);\n\n  constructor(messages?: UI_MESSAGE[]) {\n    this.messagesRef = ref(messages ?? []) as Ref<UI_MESSAGE[]>;\n  }\n\n  get messages(): UI_MESSAGE[] {\n    return this.messagesRef.value;\n  }\n\n  set messages(messages: UI_MESSAGE[]) {\n    this.messagesRef.value = messages;\n  }\n\n  get status(): ChatStatus {\n    return this.statusRef.value;\n  }\n\n  set status(status: ChatStatus) {\n    this.statusRef.value = status;\n  }\n\n  get error(): Error | undefined {\n    return this.errorRef.value;\n  }\n\n  set error(error: Error | undefined) {\n    this.errorRef.value = error;\n  }\n\n  pushMessage = (message: UI_MESSAGE) => {\n    this.messagesRef.value = [...this.messagesRef.value, message];\n  };\n\n  popMessage = () => {\n    this.messagesRef.value = this.messagesRef.value.slice(0, -1);\n  };\n\n  replaceMessage = (index: number, message: UI_MESSAGE) => {\n    // message is cloned here because vue's deep reactivity shows unexpected behavior, particularly when updating tool invocation parts\n    this.messagesRef.value[index] = { ...message };\n  };\n\n  snapshot = <T>(value: T): T => value;\n}\n\n/**\n * @deprecated Use the {@link useChat} composable instead. It exposes reactive\n * refs and automatically recreates the chat when its init object changes.\n */\nexport class Chat<\n  UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n  constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n    super({\n      ...init,\n      state: new VueChatState(messages),\n    });\n  }\n}\n","import {\n  AbstractChat,\n  type ChatInit as BaseChatInit,\n  type ChatInit,\n  type ChatState,\n  type ChatStatus,\n  type UIMessage,\n} from 'ai';\nimport {\n  computed,\n  shallowRef,\n  toValue,\n  triggerRef,\n  watch,\n  type ComputedRef,\n  type MaybeRefOrGetter,\n  type ShallowRef,\n} from 'vue';\n\n/**\n * @internal\n */\nexport class VueChat<\n  UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n  constructor({\n    state,\n    ...init\n  }: Omit<ChatInit<UI_MESSAGE>, 'messages'> & {\n    state: ChatState<UI_MESSAGE>;\n  }) {\n    super({\n      ...init,\n      state,\n    });\n  }\n}\n\n/**\n * Return type of the {@link useChat} composable, which includes the chat\n * instance methods and reactive properties for messages, status, and error.\n */\nexport interface UseChatHelpers<UI_MESSAGE extends UIMessage> extends Pick<\n  AbstractChat<UI_MESSAGE>,\n  | 'sendMessage'\n  | 'regenerate'\n  | 'stop'\n  | 'resumeStream'\n  | 'addToolOutput'\n  | 'addToolApprovalResponse'\n  | 'clearError'\n> {\n  /**\n   * The id of the chat.\n   */\n  id: ComputedRef<string>;\n\n  /**\n   * The current error state of the chat, if any.\n   */\n  error: ShallowRef<Error | undefined>;\n\n  /**\n   * The current status of the chat, which can be 'ready', 'generating', 'streaming', or 'error'.\n   */\n  status: ShallowRef<ChatStatus>;\n\n  /**\n   * The list of messages in the chat, which can be updated by the chat instance methods or directly by setting this property.\n   */\n  messages: ShallowRef<UI_MESSAGE[]>;\n}\n\n/**\n * Composable to access messages, status, and other chat properties and\n * methods. Accepts an optional reactive initial configuration object\n *\n * @example\n *\n * ```ts\n * // passing a getter if any reactive properties are used within\n * // the init object\n * const { messages, sendMessage } = useChat(() => ({\n *   // ...\n * })\n * ```\n *\n * @see BaseChatInit\n */\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>(\n  init?: MaybeRefOrGetter<BaseChatInit<UI_MESSAGE>>,\n): UseChatHelpers<UI_MESSAGE> {\n  const messages = shallowRef<UI_MESSAGE[]>([]);\n  const status = shallowRef<ChatStatus>('ready');\n  const error = shallowRef<Error | undefined>();\n\n  // this wrapper doesn't need to be reactive and can be reused across chat\n  // instance changes, because the inner refs are reactive and the wrapper\n  // methods trigger updates when needed\n  const chatStateWrapper = {\n    get messages(): UI_MESSAGE[] {\n      return messages.value;\n    },\n\n    set messages(messageList: UI_MESSAGE[]) {\n      messages.value = messageList;\n    },\n\n    get status(): ChatStatus {\n      return status.value;\n    },\n\n    set status(statusValue: ChatStatus) {\n      status.value = statusValue;\n    },\n\n    get error(): Error | undefined {\n      return error.value;\n    },\n\n    set error(errorValue: Error | undefined) {\n      error.value = errorValue;\n    },\n\n    pushMessage(message: UI_MESSAGE) {\n      messages.value.push(message);\n      // needed because messagesRef is a shallowRef\n      triggerRef(messages);\n    },\n\n    popMessage() {\n      messages.value.pop();\n      triggerRef(messages);\n    },\n\n    replaceMessage(index: number, message: UI_MESSAGE) {\n      // message is cloned here because vue's deep reactivity shows unexpected behavior, particularly when updating tool invocation parts\n      messages.value[index] = { ...message };\n      triggerRef(messages);\n    },\n\n    snapshot: <T>(value: T): T => value,\n  } satisfies ChatState<UI_MESSAGE>;\n\n  // the instance is created right away thanks to immediate: true. We do it this\n  // way instead of a computed to ensure all changes to reactive state happen\n  // in the same tick\n  const chatInstance = shallowRef<VueChat<UI_MESSAGE>>() as ShallowRef<\n    VueChat<UI_MESSAGE>\n  >;\n\n  watch(\n    () => toValue(init),\n    opts => {\n      // reset the initial state\n      messages.value = opts?.messages ?? [];\n      status.value = 'ready';\n      error.value = undefined;\n\n      chatInstance.value = new VueChat<UI_MESSAGE>({\n        ...opts,\n        state: chatStateWrapper,\n      });\n    },\n    { immediate: true },\n  );\n\n  return {\n    id: computed(() => chatInstance.value.id),\n    status,\n    messages,\n    error,\n    addToolApprovalResponse: opts =>\n      chatInstance.value.addToolApprovalResponse(opts),\n    addToolOutput: opts => chatInstance.value.addToolOutput(opts),\n    clearError: () => chatInstance.value.clearError(),\n    regenerate: opts => chatInstance.value.regenerate(opts),\n    sendMessage: (...args) => chatInstance.value.sendMessage(...args),\n    stop: () => chatInstance.value.stop(),\n    resumeStream: opts => chatInstance.value.resumeStream(opts),\n  };\n}\n","import type { FlexibleSchema } from '@ai-sdk/provider-utils';\nimport {\n  useObject,\n  type UseObjectHelpers,\n  type UseObjectOptions,\n} from './use-object';\n\nexport * from './use-completion';\nexport { Chat } from './chat.vue';\nexport { useChat, type UseChatHelpers } from './use-chat';\nexport * from './use-object';\n\n// deprecated aliases\n// note: declared here (instead of export aliases) so that the `@deprecated`\n// tags are preserved in the bundled type declarations\n\n/**\n * @deprecated Use `useObject` instead.\n */\nexport const experimental_useObject = useObject;\n\n/**\n * @deprecated Use `UseObjectOptions` instead.\n */\nexport type Experimental_UseObjectOptions<\n  SCHEMA extends FlexibleSchema,\n  RESULT,\n> = UseObjectOptions<SCHEMA, RESULT>;\n\n/**\n * @deprecated Use `UseObjectHelpers` instead.\n */\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = UseObjectHelpers<\n  RESULT,\n  INPUT\n>;\n","import { rpc as createRpcClient, type OmitRPCContextArgs } from \"@webhare/rpc\";\nimport type { PublicRPC } from \"@mod-btw/js/public-rpc\";\n\n// Canonical @webhare/rpc client for the BTW Coach public RPC service:\n// - typed against PublicRPC (the leading `context` arg stripped)\n// - auto-adds ?pathname=location.pathname so the router resolves the\n//   siteprofile <wrdauth> rule for cookie-based auth\n//\n// baseUrl: location.origin works in WebHare (same-origin).\nexport const api = createRpcClient<OmitRPCContextArgs<typeof PublicRPC>>(\"btw:public\", {\n  baseUrl: location.origin,\n});\n\n// Mint a short-lived v2 chat token (auth-gated) for the chat gateway routes\n// (/api/btw/chat and /api/btw/meta).\nexport function issueChatToken() {\n  return api.issueChatToken();\n}\n\n// Leave feedback (thumbs up/down + optional/required comment) on one assistant\n// answer. Stored in WebHare (same WRD schema as the conversation log); auth-gated\n// like the chat itself. Upserts per messageId, so a repeat vote edits in place.\nexport function submitFeedback(payload: {\n  externalId: string;\n  messageId: string;\n  rating: \"positive\" | \"negative\";\n  comment?: string;\n  question?: string;\n  response?: string;\n}) {\n  return api.submitFeedback(payload);\n}\n\n// Password reset (\"Wachtwoord vergeten\") flow: emailed 6-digit code, then set\n// a new password. All three are unauthenticated by design (see public-rpc.ts).\nexport function requestPasswordReset(email: string) {\n  return api.requestPasswordReset({ email });\n}\n\nexport function checkResetCode(email: string, code: string) {\n  return api.checkResetCode({ email, code });\n}\n\nexport function resetPassword(payload: { email: string; code: string; newPassword: string }) {\n  return api.resetPassword(payload);\n}\n","// Token handling for the cross-origin chat gateway, kept free of Vue and WebHare\n// imports so tests/frontend can exercise it directly with node --test.\n\nexport const SESSION_EXPIRED_MESSAGE = \"Je sessie is verlopen. Herlaad de pagina en meld je opnieuw aan.\";\n\n/** A token is renewed when it expires within this window. */\nexport const REFRESH_MARGIN_MS = 60_000;\n\nexport interface IssuedChatToken {\n  token: string;\n  /** Expiry in milliseconds since epoch. */\n  exp: number;\n}\n\nexport interface ChatTokenStoreOptions {\n  issue: () => Promise<IssuedChatToken>;\n  now?: () => number;\n}\n\nexport class ChatTokenStore {\n  #issue: () => Promise<IssuedChatToken>;\n  #now: () => number;\n  #token = \"\";\n  #exp = 0;\n  #pending: Promise<string> | null = null;\n\n  public constructor(options: ChatTokenStoreOptions) {\n    this.#issue = options.issue;\n    this.#now = options.now ?? Date.now;\n  }\n\n  public get token(): string {\n    return this.#token;\n  }\n\n  /** A token that stays valid for at least another REFRESH_MARGIN_MS. */\n  public async ensure(): Promise<string> {\n    if (this.#token && this.#now() < this.#exp - REFRESH_MARGIN_MS) return this.#token;\n    return await this.refresh();\n  }\n\n  /** Always requests a new token; concurrent callers share one request. */\n  public async refresh(): Promise<string> {\n    this.#pending ??= this.#request().finally(() => {\n      this.#pending = null;\n    });\n    return await this.#pending;\n  }\n\n  async #request(): Promise<string> {\n    try {\n      const issued = await this.#issue();\n      this.#token = issued.token;\n      this.#exp = issued.exp;\n      return this.#token;\n    } catch (error) {\n      this.#token = \"\";\n      this.#exp = 0;\n      throw error;\n    }\n  }\n}\n\nexport interface AuthorizedFetchOptions {\n  tokens: ChatTokenStore;\n  fetch?: typeof fetch;\n}\n\n/**\n * fetch with a bearer token. A 401 gets one fresh token and one retry; when that\n * fails too the session counts as expired.\n */\nexport function createAuthorizedFetch(options: AuthorizedFetchOptions): typeof fetch {\n  const { tokens } = options;\n  const baseFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));\n\n  const withToken = (init: RequestInit | undefined, token: string): RequestInit => {\n    const headers = new Headers(init?.headers);\n    headers.set(\"Authorization\", `Bearer ${token}`);\n    return { ...init, headers };\n  };\n\n  return async (input, init) => {\n    let token: string;\n    try {\n      token = await tokens.ensure();\n    } catch {\n      throw new Error(SESSION_EXPIRED_MESSAGE);\n    }\n\n    const response = await baseFetch(input, withToken(init, token));\n    if (response.status !== 401) return response;\n\n    try {\n      token = await tokens.refresh();\n    } catch {\n      throw new Error(SESSION_EXPIRED_MESSAGE);\n    }\n    const retried = await baseFetch(input, withToken(init, token));\n    if (retried.status === 401) throw new Error(SESSION_EXPIRED_MESSAGE);\n    return retried;\n  };\n}\n","// The chat gateway (btw.chat_api_base, routes under /api/btw/) lives cross-origin\n// on Vercel and requires a short-lived v2 token from the WebHare public RPC\n// issueChatToken on every route, /api/btw/meta included.\nimport { getFrontendData } from \"./runtime\";\nimport { issueChatToken } from \"./api\";\nimport { ChatTokenStore, createAuthorizedFetch } from \"./chatAuth\";\n\n// Base URL from frontend-data `btw:coach.chatApiBase`. Empty → same-origin.\n// Trailing slash stripped.\nexport function chatApiBase(): string {\n  const data = getFrontendData(\"btw:coach\");\n  const base = data?.chatApiBase ?? \"\";\n  return base.replace(/\\/$/, \"\");\n}\n\nexport function chatApiUrl(path: \"chat\" | \"meta\"): string {\n  return `${chatApiBase()}/api/btw/${path}`;\n}\n\nexport const chatTokens = new ChatTokenStore({ issue: () => issueChatToken() });\n\nexport const chatFetch = createAuthorizedFetch({ tokens: chatTokens });\n\n/** Fetch a new token now (app load, fresh login); failures surface on the next request. */\nexport async function refreshChatToken(): Promise<void> {\n  try {\n    await chatTokens.refresh();\n  } catch (err) {\n    console.error(\"issueChatToken failed:\", err);\n  }\n}\n","import type { UIMessage } from \"ai\";\n\n// Client-side chat persistence + URL-hash sync so a refresh resumes the current\n// conversation (real or test mode). One conversation id per browser tab lives in\n// the URL hash (`#gesprek/<id>`) and its state in localStorage (`btw-chat-<id>`).\n// The id doubles as the @ai-sdk Chat id, keeping server-side WRD logging coherent\n// across a refresh. Mirrors the one-way hash pattern in LoginForm.vue.\n\nconst STORAGE_PREFIX = \"btw-chat-\";\nconst HASH_PREFIX = \"#gesprek/\";\n\n/** Feedback the user left on one assistant answer, keyed by message id. */\nexport interface FeedbackState {\n  rating: \"positive\" | \"negative\";\n  comment: string;\n}\n\nexport interface PersistedChat {\n  messages: UIMessage[];\n  mock: { active: boolean; conversationId: string | null };\n  /** Per assistant message.id, so the active thumb survives a refresh. */\n  feedback?: Record<string, FeedbackState>;\n}\n\n/** Read the conversation id from `#gesprek/<id>`, or null when absent/malformed. */\nexport function conversationIdFromHash(): string | null {\n  const hash = window.location.hash;\n  if (!hash.startsWith(HASH_PREFIX)) return null;\n  const id = hash.slice(HASH_PREFIX.length).trim();\n  return id || null;\n}\n\n/** Generate a fresh conversation id (secure context: localhost + https). */\nexport function newConversationId(): string {\n  return crypto.randomUUID();\n}\n\nexport function loadChat(id: string): PersistedChat | null {\n  try {\n    const raw = localStorage.getItem(STORAGE_PREFIX + id);\n    if (!raw) return null;\n    return JSON.parse(raw) as PersistedChat;\n  } catch {\n    return null;\n  }\n}\n\nexport function saveChat(id: string, data: PersistedChat): void {\n  try {\n    localStorage.setItem(STORAGE_PREFIX + id, JSON.stringify(data));\n  } catch { /* quota / disabled storage: ignore */ }\n}\n\nexport function removeChat(id: string): void {\n  try {\n    localStorage.removeItem(STORAGE_PREFIX + id);\n  } catch { /* ignore */ }\n}\n\n/** Point the URL hash at this conversation, only writing when it actually changes. */\nexport function setConversationHash(id: string): void {\n  const target = HASH_PREFIX + id;\n  if (window.location.hash === target) return;\n  const url = window.location.pathname + window.location.search + target;\n  history.replaceState(null, \"\", url);\n}\n\n/** Drop the conversation hash, only writing when a conversation hash is present. */\nexport function clearConversationHash(): void {\n  if (!window.location.hash.startsWith(HASH_PREFIX)) return;\n  const url = window.location.pathname + window.location.search;\n  history.replaceState(null, \"\", url);\n}\n","// Single source of truth bridge: prompt, model list and mock-conversation\n// metadata live server-side on the chat gateway and are fetched via GET\n// /api/btw/meta (bearer token required). The Vue client uses this for the model\n// selector, prompt viewer, mock picker and the auto-prefill of the next mock\n// question.\nimport { chatApiUrl, chatFetch } from \"./chatGateway\";\n\nexport interface ModelMeta {\n  id: string;\n  name: string;\n  provider: string;\n  /** Greyed-out / non-selectable in the picker when true (server falls back to\n   * the default model). Used for the Mistral-only prod setup. */\n  disabled?: boolean;\n}\n\nexport interface MockConversationMeta {\n  id: string;\n  title: string;\n  description: string;\n  /** First user question, used to start a mock conversation. */\n  firstQuestion: string;\n  /** All user questions in order, for auto-prefilling the next one. */\n  questions: string[];\n}\n\nexport interface ChatMeta {\n  systemPrompt: string;\n  models: ModelMeta[];\n  defaultModelId: string;\n  mockConversations: MockConversationMeta[];\n}\n\n// True when the app is served from a local dev host. Used to show a developer\n// hint when the chat-API isn't running (the picker/chat depend on it).\nexport function isLocalhost(): boolean {\n  return [\"localhost\", \"127.0.0.1\"].includes(window.location.hostname);\n}\n\nexport async function fetchMeta(): Promise<ChatMeta> {\n  const res = await chatFetch(chatApiUrl(\"meta\"));\n  if (!res.ok) throw new Error(`meta HTTP ${res.status}`);\n  return await res.json() as ChatMeta;\n}\n","import { createVNode as _createVNode, toDisplayString as _toDisplayString, createElementVNode as _createElementVNode, openBlock as _openBlock, createElementBlock as _createElementBlock, createCommentVNode as _createCommentVNode, createTextVNode as _createTextVNode, renderList as _renderList, Fragment as _Fragment, createBlock as _createBlock } from \"vue\"\n\nconst _hoisted_1 = { class: \"chat\" }\nconst _hoisted_2 = [\"aria-busy\"]\nconst _hoisted_3 = {\n  key: 0,\n  class: \"chat__history-error\",\n  role: \"alert\"\n}\nconst _hoisted_4 = {\n  key: 1,\n  class: \"chat__history-loading\",\n  role: \"status\"\n}\nconst _hoisted_5 = {\n  key: 2,\n  class: \"chat__api-warning\",\n  role: \"alert\"\n}\nconst _hoisted_6 = {\n  key: 0,\n  class: \"chat__header\"\n}\nconst _hoisted_7 = [\"title\"]\nconst _hoisted_8 = { class: \"chat__inner\" }\nconst _hoisted_9 = {\n  key: 0,\n  class: \"chat__empty\"\n}\nconst _hoisted_10 = { class: \"chat__empty-head\" }\nconst _hoisted_11 = { class: \"chat__suggestions\" }\nconst _hoisted_12 = { class: \"chat__suggestions-grid\" }\nconst _hoisted_13 = [\"onClick\"]\nconst _hoisted_14 = {\n  key: 0,\n  class: \"chat__suggestion-note\"\n}\nconst _hoisted_15 = { class: \"chat__suggestions\" }\nconst _hoisted_16 = { class: \"chat__suggestions-grid\" }\nconst _hoisted_17 = [\"onClick\"]\nconst _hoisted_18 = {\n  key: 0,\n  class: \"chat__suggestion-note\"\n}\nconst _hoisted_19 = {\n  key: 0,\n  class: \"chat__thinking\"\n}\nconst _hoisted_20 = {\n  key: 2,\n  class: \"chat__error\",\n  role: \"alert\"\n}\nconst _hoisted_21 = { key: 0 }\nconst _hoisted_22 = { key: 1 }\nconst _hoisted_23 = { class: \"chat__dock\" }\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createElementBlock(\"div\", _hoisted_1, [\n    _createVNode($setup[\"Sidebar\"], {\n      chats: $setup.sidebarChats,\n      \"current-chat-id\": $setup.conversationId,\n      busy: $setup.isBusy || $props.historyLoading,\n      \"has-messages\": $setup.chat.messages.length > 0,\n      active: $setup.mockState.active,\n      \"active-conversation-title\": $setup.activeConversation?.title,\n      \"system-prompt\": $setup.meta?.systemPrompt ?? '',\n      \"api-offline\": $setup.showApiWarning,\n      onStartTestMode: _cache[0] || (_cache[0] = $event => ($setup.pickerOpen = true)),\n      onStopTestMode: $setup.stopTestMode,\n      onSelectChat: _cache[1] || (_cache[1] = $event => ($setup.emit('select-chat', $event))),\n      onNewChat: _cache[2] || (_cache[2] = $event => ($setup.emit('new-chat'))),\n      onDownload: $setup.downloadMarkdown\n    }, null, 8 /* PROPS */, [\"chats\", \"current-chat-id\", \"busy\", \"has-messages\", \"active\", \"active-conversation-title\", \"system-prompt\", \"api-offline\"]),\n    _createElementVNode(\"div\", {\n      class: \"chat__main\",\n      \"aria-busy\": $props.historyLoading\n    }, [\n      ($props.historyError)\n        ? (_openBlock(), _createElementBlock(\"div\", _hoisted_3, [\n            _createElementVNode(\"span\", null, _toDisplayString($props.historyError), 1 /* TEXT */),\n            _createElementVNode(\"button\", {\n              type: \"button\",\n              class: \"chat__retry\",\n              onClick: _cache[3] || (_cache[3] = $event => ($setup.emit('retry-history')))\n            }, \"Opnieuw proberen\")\n          ]))\n        : _createCommentVNode(\"v-if\", true),\n      ($props.historyLoading)\n        ? (_openBlock(), _createElementBlock(\"div\", _hoisted_4, \"Gesprek laden…\"))\n        : _createCommentVNode(\"v-if\", true),\n      ($setup.showApiWarning)\n        ? (_openBlock(), _createElementBlock(\"div\", _hoisted_5, [\n            _createVNode($setup[\"AlertTriangle\"], {\n              size: 16,\n              class: \"chat__api-warning-icon\"\n            }),\n            _cache[11] || (_cache[11] = _createElementVNode(\"span\", null, [\n              _createTextVNode(\" De chat-API draait niet op \"),\n              _createElementVNode(\"code\", null, \"localhost:4104\"),\n              _createTextVNode(\". Start 'm met \"),\n              _createElementVNode(\"code\", null, \"./start\"),\n              _createTextVNode(\" — zonder API geen modellen en geen antwoorden. \")\n            ], -1 /* CACHED */))\n          ]))\n        : _createCommentVNode(\"v-if\", true),\n      _createElementVNode(\"div\", {\n        ref: \"scrollEl\",\n        class: \"chat__scroll\",\n        onScroll: $setup.onScroll\n      }, [\n        _createCommentVNode(\" Sticky header: gesprekstitel links, download rechts \"),\n        ($setup.chat.messages.length > 0)\n          ? (_openBlock(), _createElementBlock(\"header\", _hoisted_6, [\n              _createElementVNode(\"span\", {\n                class: \"chat__header-title\",\n                title: $setup.conversationTitle\n              }, _toDisplayString($setup.conversationTitle), 9 /* TEXT, PROPS */, _hoisted_7),\n              _createElementVNode(\"button\", {\n                type: \"button\",\n                class: \"chat__header-action\",\n                \"aria-label\": \"Download gesprek\",\n                title: \"Download als Markdown\",\n                onClick: $setup.downloadMarkdown\n              }, [\n                _createVNode($setup[\"Download\"], { size: 16 })\n              ])\n            ]))\n          : _createCommentVNode(\"v-if\", true),\n        _createElementVNode(\"div\", _hoisted_8, [\n          _createCommentVNode(\" Empty state \"),\n          ($setup.chat.messages.length === 0)\n            ? (_openBlock(), _createElementBlock(\"div\", _hoisted_9, [\n                _createElementVNode(\"div\", _hoisted_10, [\n                  _createVNode($setup[\"MessageSquare\"], {\n                    size: 32,\n                    class: \"chat__empty-icon\"\n                  }),\n                  _cache[12] || (_cache[12] = _createElementVNode(\"h2\", { class: \"chat__empty-title\" }, \"Welkom bij de BTW Coach\", -1 /* CACHED */)),\n                  _cache[13] || (_cache[13] = _createElementVNode(\"p\", { class: \"chat__empty-desc\" }, \" Stel je vraag over Brede Welvaart in Twente — bijvoorbeeld over beleid, welzijn, duurzaamheid of sociale cohesie in de regio. \", -1 /* CACHED */))\n                ]),\n                _createElementVNode(\"div\", _hoisted_11, [\n                  _cache[14] || (_cache[14] = _createElementVNode(\"h3\", { class: \"chat__suggestions-label\" }, \"Relevante test-vragen\", -1 /* CACHED */)),\n                  _createElementVNode(\"div\", _hoisted_12, [\n                    (_openBlock(), _createElementBlock(_Fragment, null, _renderList($setup.RELEVANT_QUESTIONS, (q, i) => {\n                      return _createElementVNode(\"button\", {\n                        key: `r${i}`,\n                        type: \"button\",\n                        class: \"chat__suggestion\",\n                        onClick: $event => ($setup.sendText(q.text))\n                      }, [\n                        _createTextVNode(_toDisplayString(q.text) + \" \", 1 /* TEXT */),\n                        (q.note)\n                          ? (_openBlock(), _createElementBlock(\"span\", _hoisted_14, _toDisplayString(q.note), 1 /* TEXT */))\n                          : _createCommentVNode(\"v-if\", true)\n                      ], 8 /* PROPS */, _hoisted_13)\n                    }), 64 /* STABLE_FRAGMENT */))\n                  ])\n                ]),\n                _createElementVNode(\"div\", _hoisted_15, [\n                  _cache[15] || (_cache[15] = _createElementVNode(\"h3\", { class: \"chat__suggestions-label\" }, \"Niet-relevante test-vragen\", -1 /* CACHED */)),\n                  _createElementVNode(\"div\", _hoisted_16, [\n                    (_openBlock(), _createElementBlock(_Fragment, null, _renderList($setup.IRRELEVANT_QUESTIONS, (q, i) => {\n                      return _createElementVNode(\"button\", {\n                        key: `i${i}`,\n                        type: \"button\",\n                        class: \"chat__suggestion\",\n                        onClick: $event => ($setup.sendText(q.text))\n                      }, [\n                        _createTextVNode(_toDisplayString(q.text) + \" \", 1 /* TEXT */),\n                        (q.note)\n                          ? (_openBlock(), _createElementBlock(\"span\", _hoisted_18, _toDisplayString(q.note), 1 /* TEXT */))\n                          : _createCommentVNode(\"v-if\", true)\n                      ], 8 /* PROPS */, _hoisted_17)\n                    }), 64 /* STABLE_FRAGMENT */))\n                  ])\n                ])\n              ]))\n            : (_openBlock(), _createElementBlock(_Fragment, { key: 1 }, [\n                _createCommentVNode(\" Messages \"),\n                (_openBlock(true), _createElementBlock(_Fragment, null, _renderList($setup.chat.messages, (m, i) => {\n                  return (_openBlock(), _createBlock($setup[\"MessageItem\"], {\n                    key: m.id,\n                    message: m,\n                    \"is-last\": i === $setup.chat.messages.length - 1,\n                    \"is-streaming\": $setup.chat.status === 'streaming',\n                    feedback: $setup.feedbackMap[m.id],\n                    onFeedback: (rating) => $setup.openFeedback(m, rating)\n                  }, null, 8 /* PROPS */, [\"message\", \"is-last\", \"is-streaming\", \"feedback\", \"onFeedback\"]))\n                }), 128 /* KEYED_FRAGMENT */)),\n                ($setup.chat.status === 'submitted')\n                  ? (_openBlock(), _createElementBlock(\"div\", _hoisted_19, _cache[16] || (_cache[16] = [\n                      _createElementVNode(\"span\", { class: \"chat__dot\" }, null, -1 /* CACHED */),\n                      _createElementVNode(\"span\", { class: \"chat__dot\" }, null, -1 /* CACHED */),\n                      _createElementVNode(\"span\", { class: \"chat__dot\" }, null, -1 /* CACHED */)\n                    ])))\n                  : _createCommentVNode(\"v-if\", true)\n              ], 64 /* STABLE_FRAGMENT */)),\n          ($setup.chat.error)\n            ? (_openBlock(), _createElementBlock(\"div\", _hoisted_20, [\n                _createVNode($setup[\"AlertTriangle\"], {\n                  size: 18,\n                  \"aria-hidden\": \"true\"\n                }),\n                _createElementVNode(\"div\", null, [\n                  ($setup.sessionExpired)\n                    ? (_openBlock(), _createElementBlock(\"p\", _hoisted_21, _toDisplayString($setup.SESSION_EXPIRED_MESSAGE), 1 /* TEXT */))\n                    : (_openBlock(), _createElementBlock(\"p\", _hoisted_22, \"Het gekozen model kan nu geen antwoord geven. Probeer het later opnieuw.\")),\n                  (!$setup.sessionExpired)\n                    ? (_openBlock(), _createElementBlock(\"button\", {\n                        key: 2,\n                        type: \"button\",\n                        class: \"chat__retry\",\n                        onClick: _cache[4] || (_cache[4] = $event => ($setup.chat.regenerate()))\n                      }, \" Opnieuw proberen \"))\n                    : _createCommentVNode(\"v-if\", true)\n                ])\n              ]))\n            : _createCommentVNode(\"v-if\", true)\n        ]),\n        _createCommentVNode(\" Scroll to bottom \"),\n        (!$setup.isAtBottom)\n          ? (_openBlock(), _createElementBlock(\"button\", {\n              key: 1,\n              type: \"button\",\n              class: \"chat__float chat__float--scroll\",\n              \"aria-label\": \"Naar beneden\",\n              onClick: _cache[5] || (_cache[5] = $event => ($setup.scrollToBottom('smooth')))\n            }, [\n              _createVNode($setup[\"ArrowDown\"], { size: 16 })\n            ]))\n          : _createCommentVNode(\"v-if\", true)\n      ], 544 /* NEED_HYDRATION, NEED_PATCH */),\n      _createElementVNode(\"div\", _hoisted_23, [\n        _createVNode($setup[\"PromptInput\"], {\n          modelValue: $setup.input,\n          \"onUpdate:modelValue\": _cache[6] || (_cache[6] = $event => (($setup.input) = $event)),\n          \"model-id\": $setup.modelId,\n          \"onUpdate:modelId\": _cache[7] || (_cache[7] = $event => (($setup.modelId) = $event)),\n          models: $setup.meta?.models ?? [],\n          status: $props.historyLoading ? 'submitted' : $setup.chat.status,\n          onSubmit: $setup.handleSubmit,\n          onStop: _cache[8] || (_cache[8] = $event => ($setup.chat.stop()))\n        }, null, 8 /* PROPS */, [\"modelValue\", \"model-id\", \"models\", \"status\"])\n      ])\n    ], 8 /* PROPS */, _hoisted_2),\n    _createVNode($setup[\"TestModePicker\"], {\n      open: $setup.pickerOpen,\n      \"onUpdate:open\": _cache[9] || (_cache[9] = $event => (($setup.pickerOpen) = $event)),\n      conversations: $setup.meta?.mockConversations ?? [],\n      onSelect: $setup.selectConversation\n    }, null, 8 /* PROPS */, [\"open\", \"conversations\"]),\n    _createVNode($setup[\"FeedbackDialog\"], {\n      open: $setup.feedbackDialog.open,\n      \"onUpdate:open\": _cache[10] || (_cache[10] = $event => (($setup.feedbackDialog.open) = $event)),\n      rating: $setup.feedbackDialog.rating,\n      \"existing-comment\": $setup.feedbackDialog.existingComment,\n      onSubmit: $setup.onFeedbackSubmit\n    }, null, 8 /* PROPS */, [\"open\", \"rating\", \"existing-comment\"])\n  ]))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChatView.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChatView.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChatView.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChatView.vue\";script.__scopeId = \"data-v-883c0dae\";export default script;","import { computed, ref, shallowRef } from \"vue\";\nimport type { PersistedChat } from \"./chatHistory\";\n\nexport interface ConversationSummary {\n  id: string;\n  title: string;\n  updatedAt: number;\n}\n\nexport interface ConversationSession {\n  id: string;\n  revision: number;\n  snapshot: PersistedChat;\n}\n\nexport function useConversationHistory(options: {\n  list: () => Promise<{ chats: ConversationSummary[] }>;\n  load: (id: string) => Promise<PersistedChat | null>;\n  navigate: (id: string | null) => void;\n}) {\n  const chats = shallowRef<ConversationSummary[]>([]);\n  const session = shallowRef<ConversationSession>({\n    id: crypto.randomUUID(),\n    revision: 0,\n    snapshot: { messages: [], mock: { active: false, conversationId: null } },\n  });\n  const loading = ref(false);\n  const listError = ref(\"\");\n  const loadError = ref(\"\");\n  const error = computed(() => loadError.value || listError.value);\n  let request = 0;\n  let listRequest = 0;\n  let requestedId: string | null = null;\n\n  async function refresh() {\n    const current = ++listRequest;\n    try {\n      const result = await options.list();\n      if (current !== listRequest) return;\n      chats.value = result.chats;\n      listError.value = \"\";\n    } catch {\n      if (current === listRequest) listError.value = \"Je gesprekken konden niet worden geladen. Probeer het opnieuw.\";\n    }\n  }\n\n  async function open(id: string) {\n    const current = ++request;\n    requestedId = id;\n    loading.value = true;\n    loadError.value = \"\";\n    try {\n      const snapshot = await options.load(id);\n      if (current !== request) return;\n      if (!snapshot) {\n        loadError.value = \"Dit gesprek is niet beschikbaar voor jouw account.\";\n        return;\n      }\n      session.value = { id, snapshot, revision: session.value.revision + 1 };\n      options.navigate(id);\n    } catch {\n      if (current === request) loadError.value = \"Het gesprek kon niet worden geladen. Probeer het opnieuw.\";\n    } finally {\n      if (current === request) loading.value = false;\n    }\n  }\n\n  function start(snapshot?: PersistedChat) {\n    ++request;\n    requestedId = null;\n    loading.value = false;\n    loadError.value = \"\";\n    session.value = {\n      id: crypto.randomUUID(),\n      revision: session.value.revision + 1,\n      snapshot: snapshot ?? { messages: [], mock: { active: false, conversationId: null } },\n    };\n    options.navigate(null);\n  }\n\n  async function retry() {\n    await Promise.all([refresh(), loadError.value && requestedId ? open(requestedId) : Promise.resolve()]);\n  }\n\n  return { chats, session, loading, error, refresh, open, start, retry };\n}\n","import { openBlock as _openBlock, createElementBlock as _createElementBlock, createCommentVNode as _createCommentVNode, createBlock as _createBlock } from \"vue\"\n\nconst _hoisted_1 = {\n  key: 0,\n  class: \"workspace-loading\",\n  role: \"status\"\n}\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return ($setup.initialLoading)\n    ? (_openBlock(), _createElementBlock(\"div\", _hoisted_1, \"Gesprek laden…\"))\n    : (_openBlock(), _createBlock($setup[\"ChatView\"], {\n        key: $setup.session.revision,\n        session: $setup.session,\n        chats: $setup.chats,\n        \"history-loading\": $setup.loading,\n        \"history-error\": $setup.error,\n        onSelectChat: $setup.open,\n        onNewChat: $setup.start,\n        onRefreshHistory: $setup.refresh,\n        onRetryHistory: $setup.retry,\n        onBusy: _cache[0] || (_cache[0] = $event => ($setup.busy = $event))\n      }, null, 8 /* PROPS */, [\"session\", \"chats\", \"history-loading\", \"history-error\", \"onSelectChat\", \"onNewChat\", \"onRefreshHistory\", \"onRetryHistory\"]))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChatWorkspace.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChatWorkspace.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChatWorkspace.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/ChatWorkspace.vue\";script.__scopeId = \"data-v-57104fd4\";export default script;","<script setup lang=\"ts\">\nimport { ref } from \"vue\";\nimport ThemeToggle from \"./ThemeToggle.vue\";\nimport CodeInput from \"./CodeInput.vue\";\nimport FieldError from \"./FieldError.vue\";\nimport { useLoginCode } from \"../lib/useLoginCode\";\n\nconst emailInput = ref<HTMLInputElement | null>(null);\nconst codeInput = ref<InstanceType<typeof CodeInput> | null>(null);\nconst { email, code, step, error, busy, devCode, cooldown, changeEmail, requestCode, verifyCode } = useLoginCode({\n  focusEmail: () => emailInput.value?.focus(),\n  focusCode: () => codeInput.value?.focus(),\n});\n</script>\n\n<template>\n  <div class=\"login\">\n    <div class=\"login__topbar\">\n      <ThemeToggle />\n    </div>\n\n    <button type=\"button\" class=\"login__brand\" :disabled=\"busy\" @click=\"changeEmail\" aria-label=\"Terug naar inloggen\">\n      <span class=\"login__wordmark\">BTW Coach</span>\n      <span class=\"login__tagline\">Brede Welvaart in Twente</span>\n    </button>\n\n    <form class=\"login-form\" novalidate @submit.prevent=\"step === 'email' ? requestCode() : verifyCode()\">\n      <h2 class=\"login-form__title\">{{ step === \"email\" ? \"Inloggen\" : \"Controleer je e-mail\" }}</h2>\n      <p v-if=\"step === 'email'\" class=\"login-form__subtitle\">\n        Vul je e-mailadres in. Je ontvangt een code om in te loggen bij BTW Coach.\n      </p>\n      <p v-else class=\"login-form__subtitle\" role=\"status\">\n        Als <strong>{{ email }}</strong> toegang heeft, ontvang je een code.\n        De code is 15 minuten geldig. Controleer ook je spammap.\n      </p>\n\n      <label v-if=\"step === 'email'\" class=\"login-form__field\">\n        <span class=\"login-form__label\">E-mailadres</span>\n        <input\n          ref=\"emailInput\"\n          v-model=\"email\"\n          name=\"email\"\n          type=\"email\"\n          required\n          maxlength=\"254\"\n          autocomplete=\"email\"\n          class=\"login-form__input\"\n          :disabled=\"busy\"\n          :aria-invalid=\"!!error\"\n          aria-describedby=\"login-error\"\n        />\n      </label>\n      <div v-else class=\"login-form__field\">\n        <span class=\"login-form__label\">Inlogcode</span>\n        <CodeInput ref=\"codeInput\" v-model=\"code\" :disabled=\"busy\" :error=\"!!error\" aria-describedby=\"login-error\" @paste-complete=\"verifyCode\" />\n      </div>\n      <FieldError v-if=\"error\" id=\"login-error\">{{ error }}</FieldError>\n\n      <button type=\"submit\" class=\"login-form__submit\" :disabled=\"busy\" :aria-busy=\"busy\">\n        <span v-if=\"busy\" class=\"login-form__spinner\" aria-hidden=\"true\"></span>\n        {{ step === \"email\" ? (busy ? \"Versturen…\" : \"Stuur inlogcode\") : (busy ? \"Inloggen…\" : \"Inloggen\") }}\n      </button>\n\n      <template v-if=\"step === 'code'\">\n        <button type=\"button\" class=\"login-form__forgot\" :disabled=\"busy || cooldown > 0\" @click=\"requestCode\">\n          {{ cooldown > 0 ? `Opnieuw versturen over ${cooldown} seconden` : \"Geen code ontvangen? Opnieuw versturen\" }}\n        </button>\n        <button type=\"button\" class=\"login-form__forgot\" :disabled=\"busy\" @click=\"changeEmail\">Ander e-mailadres gebruiken</button>\n        <p v-if=\"devCode\" class=\"login-form__hint\">\n          Developmentmodus: code is <code>{{ devCode }}</code>\n        </p>\n      </template>\n    </form>\n  </div>\n</template>\n\n<style scoped>\n.login {\n  flex: 1;\n  position: relative;\n  display: flex;\n  flex-direction: column;\n  align-items: stretch;\n  justify-content: center;\n  gap: 28px;\n  padding: calc(32px + env(safe-area-inset-top)) 20px calc(32px + env(safe-area-inset-bottom));\n  width: 100%;\n  max-width: 540px;\n  margin: 0 auto;\n}\n.login__topbar {\n  position: absolute;\n  top: calc(16px + env(safe-area-inset-top));\n  right: 16px;\n  z-index: 2;\n}\n.login__brand {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: 6px;\n  /* Acts as a \"home\" button: back to the login form from forgot/reset. */\n  padding: 8px 0;\n  border: 0;\n  background: transparent;\n  cursor: pointer;\n  transition: opacity 0.12s;\n}\n@media (hover: hover) {\n  .login__brand:hover { opacity: 0.8; }\n}\n.login__wordmark {\n  font-size: 26px;\n  font-weight: 700;\n  letter-spacing: -0.02em;\n  color: var(--btw-fg);\n}\n.login__tagline {\n  font-size: 11px;\n  letter-spacing: 0.18em;\n  text-transform: uppercase;\n  color: var(--btw-fg-subtle);\n  font-weight: 600;\n}\n.login-form {\n  display: flex;\n  flex-direction: column;\n  gap: 14px;\n  padding: 24px 20px;\n  border: 1px solid var(--btw-line);\n  border-radius: var(--btw-radius-lg);\n  background: var(--btw-surface);\n  color: var(--btw-fg);\n  box-shadow: var(--btw-shadow-card);\n  animation: btw-rise 0.4s var(--ease-spring);\n}\n.login-form__title { margin: 0; font-size: 22px; font-weight: 700; letter-spacing: -0.025em; }\n.login-form__subtitle { margin: -4px 0 8px; font-size: 13.5px; color: var(--btw-fg-muted); line-height: 1.5; }\n.login-form__field { display: flex; flex-direction: column; gap: 6px; }\n.login-form__label {\n  font-size: 11.5px; font-weight: 600; letter-spacing: 0.04em;\n  text-transform: uppercase; color: var(--btw-fg-muted);\n}\n.login-form__input {\n  height: 48px;\n  padding: 0 14px;\n  border: 1px solid var(--btw-line);\n  border-radius: 14px;\n  background: var(--btw-surface-2);\n  color: var(--btw-fg);\n  font-size: 15px;\n  outline: none;\n  transition: border-color 0.12s, box-shadow 0.12s;\n}\n.login-form__input:focus {\n  border-color: var(--btw-accent);\n  box-shadow: 0 0 0 3px var(--btw-accent-soft);\n}\n.login-form__persist {\n  display: flex; align-items: center; gap: 8px;\n  font-size: 13px; color: var(--btw-fg-muted);\n  cursor: pointer; user-select: none;\n}\n.login-form__submit {\n  height: 52px;\n  margin-top: 4px;\n  border: 0;\n  border-radius: 16px;\n  background: var(--btw-accent);\n  color: var(--btw-accent-fg);\n  font-size: 15px;\n  font-weight: 700;\n  cursor: pointer;\n  transition: transform 0.12s var(--ease-spring), background 0.12s, opacity 0.12s;\n}\n.login-form__submit:hover:not(:disabled) { transform: translateY(-1px); background: var(--btw-accent-strong); }\n.login-form__submit:disabled { opacity: 0.6; cursor: not-allowed; }\n.login-form__spinner {\n  display: inline-block;\n  width: 16px; height: 16px;\n  margin-right: 8px;\n  vertical-align: -3px;\n  border: 2px solid rgba(255, 255, 255, 0.45);\n  border-top-color: #fff;\n  border-radius: 50%;\n  animation: btw-spin 0.6s linear infinite;\n}\n.login-form__forgot {\n  align-self: center;\n  margin-top: 2px;\n  padding: 4px 8px;\n  border: 0;\n  background: transparent;\n  color: var(--btw-fg-muted);\n  font-size: 13px;\n  font-weight: 600;\n  text-decoration: underline;\n  text-underline-offset: 2px;\n  cursor: pointer;\n  transition: color 0.12s;\n}\n@media (hover: hover) {\n  .login-form__forgot:hover { color: var(--btw-fg); }\n}\n.login-form__notice {\n  margin: 0;\n  padding: 10px 14px;\n  border-radius: 14px;\n  border: 1px solid var(--btw-mint-soft);\n  background: var(--btw-mint-soft);\n  color: var(--btw-fg);\n  font-size: 13px;\n  line-height: 1.5;\n}\n/* Reserved slot under a field so a message (error/strength/hint) appearing or\n   disappearing never shifts the layout. The slot keeps a fixed min-height; its\n   single child is taken out of flow (absolute) so it fills the reserved space\n   instead of pushing siblings. */\n.login-form__msg {\n  position: relative;\n  min-height: 32px;\n}\n.login-form__msg > * {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  margin-top: 0;\n}\n.login-form__minhint {\n  font-size: 11.5px;\n  color: var(--btw-fg-subtle);\n}\n.login-form__okhint {\n  display: flex;\n  align-items: center;\n  gap: 5px;\n  margin-top: 2px;\n  font-size: 12px;\n  font-weight: 600;\n  color: var(--btw-mint);\n}\n\n/* Password strength meter */\n.pwstrength {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  margin-top: 2px;\n}\n.pwstrength__bars {\n  display: flex;\n  gap: 4px;\n  flex: 1;\n}\n.pwstrength__bar {\n  height: 4px;\n  flex: 1;\n  border-radius: 999px;\n  background: var(--btw-line-strong);\n  transition: background 0.15s;\n}\n.pwstrength__label {\n  font-size: 11.5px;\n  font-weight: 600;\n  min-width: 56px;\n  text-align: right;\n  color: var(--btw-fg-muted);\n}\n.pwstrength[data-score=\"1\"] .pwstrength__bar--on { background: var(--btw-danger-text); }\n.pwstrength[data-score=\"2\"] .pwstrength__bar--on { background: var(--btw-golden); }\n.pwstrength[data-score=\"3\"] .pwstrength__bar--on { background: var(--btw-mint); }\n.pwstrength[data-score=\"4\"] .pwstrength__bar--on { background: var(--btw-mint); }\n.pwstrength[data-score=\"1\"] .pwstrength__label { color: var(--btw-danger-text); }\n.pwstrength[data-score=\"2\"] .pwstrength__label { color: var(--btw-golden); }\n.pwstrength[data-score=\"3\"] .pwstrength__label { color: var(--btw-mint); }\n.pwstrength[data-score=\"4\"] .pwstrength__label { color: var(--btw-mint); }\n\n.login-form__hint { margin: 0; font-size: 11.5px; color: var(--btw-fg-subtle); }\n.login-form__hint code {\n  font-family: var(--font-mono);\n  font-size: 11px;\n  padding: 2px 6px;\n  border-radius: 6px;\n  background: var(--btw-surface-2);\n  color: var(--btw-mint);\n}\n</style>\n","<template>\n  <div\n    ref=\"rootEl\"\n    class=\"codeinput\"\n    :class=\"{ 'codeinput--error': error, 'codeinput--valid': valid }\"\n    role=\"group\"\n    aria-label=\"Verificatiecode\"\n    @focusout=\"onFocusOut\"\n  >\n    <input\n      v-for=\"(cell, i) in cells\"\n      :key=\"i\"\n      :ref=\"(el) => setRef(el, i)\"\n      class=\"codeinput__cell\"\n      type=\"text\"\n      inputmode=\"numeric\"\n      autocomplete=\"one-time-code\"\n      maxlength=\"1\"\n      :aria-label=\"`Cijfer ${i + 1}`\"\n      :disabled=\"disabled\"\n      :value=\"cell\"\n      @input=\"onInput(i, $event)\"\n      @keydown=\"onKeydown(i, $event)\"\n      @focus=\"onFocus($event)\"\n      @paste=\"onPaste($event)\"\n    />\n  </div>\n</template>\n\n<script setup lang=\"ts\">\n// Ported from statiegeldnl/webdesigns/feedback (6-cell one-time-code input).\nimport { ref, watch } from \"vue\";\n\nconst props = withDefaults(\n  defineProps<{ modelValue: string; length?: number; disabled?: boolean; error?: boolean; valid?: boolean }>(),\n  { length: 6, disabled: false, error: false, valid: false },\n);\nconst emit = defineEmits<{\n  (e: \"update:modelValue\", value: string): void;\n  (e: \"complete\", value: string): void;\n  (e: \"paste-complete\", value: string): void;\n  (e: \"blur\"): void;\n}>();\n\nconst cells = ref<string[]>(Array.from({ length: props.length }, () => \"\"));\nconst inputs = ref<HTMLInputElement[]>([]);\nconst rootEl = ref<HTMLElement | null>(null);\n\n// Fire `blur` only when focus leaves the whole group (not when moving between\n// cells) so the parent can verify the code as soon as the user tabs/clicks away.\nfunction onFocusOut(event: FocusEvent) {\n  const next = event.relatedTarget as Node | null;\n  if (!next || !rootEl.value?.contains(next)) emit(\"blur\");\n}\n\nfunction setRef(el: Element | null, i: number) {\n  if (el) inputs.value[i] = el as HTMLInputElement;\n}\n\n// Keep cells in sync when the parent resets the value (e.g. clears it after a\n// failed reset). Only react to external changes, splitting the incoming string\n// into per-cell digits.\nwatch(\n  () => props.modelValue,\n  (val) => {\n    if (val === cells.value.join(\"\")) return;\n    const digits = (val ?? \"\").replace(/\\D/g, \"\").slice(0, props.length).split(\"\");\n    cells.value = Array.from({ length: props.length }, (_, i) => digits[i] ?? \"\");\n  },\n  { immediate: true },\n);\n\nfunction commit() {\n  const value = cells.value.join(\"\");\n  emit(\"update:modelValue\", value);\n  // Each cell holds at most 1 char, so a joined length === length means all\n  // cells are filled. (Do NOT use value.includes(\"\"), that's always true.)\n  if (value.length === props.length) emit(\"complete\", value);\n}\n\nfunction focusCell(i: number) {\n  const el = inputs.value[i];\n  if (el) {\n    el.focus();\n    el.select();\n  }\n}\n\ndefineExpose({ focus: () => focusCell(0) });\n\nfunction onInput(i: number, event: Event) {\n  const target = event.target as HTMLInputElement;\n  // Keep only the last typed digit (handles fast typing / replacing a filled cell).\n  const digit = target.value.replace(/\\D/g, \"\").slice(-1);\n  cells.value[i] = digit;\n  target.value = digit;\n  commit();\n  if (digit && i < props.length - 1) focusCell(i + 1);\n}\n\nfunction onKeydown(i: number, event: KeyboardEvent) {\n  if (event.key === \"Backspace\") {\n    if (cells.value[i]) {\n      // Non-empty: let the input event clear this cell.\n      return;\n    }\n    // Empty: step back and clear the previous cell.\n    if (i > 0) {\n      event.preventDefault();\n      cells.value[i - 1] = \"\";\n      commit();\n      focusCell(i - 1);\n    }\n  } else if (event.key === \"ArrowLeft\" && i > 0) {\n    event.preventDefault();\n    focusCell(i - 1);\n  } else if (event.key === \"ArrowRight\" && i < props.length - 1) {\n    event.preventDefault();\n    focusCell(i + 1);\n  }\n}\n\nfunction onFocus(event: FocusEvent) {\n  (event.target as HTMLInputElement).select();\n}\n\nfunction onPaste(event: ClipboardEvent) {\n  event.preventDefault();\n  if (props.disabled) return;\n  const text = event.clipboardData?.getData(\"text\") ?? \"\";\n  const digits = text.replace(/\\D/g, \"\").slice(0, props.length).split(\"\");\n  if (digits.length === 0) return;\n  cells.value = Array.from({ length: props.length }, (_, i) => digits[i] ?? \"\");\n  commit();\n  // Focus the first empty cell, or the last one when fully filled.\n  const firstEmpty = cells.value.findIndex((c) => !c);\n  focusCell(firstEmpty === -1 ? props.length - 1 : firstEmpty);\n  if (new RegExp(`^\\\\d{${props.length}}$`).test(text.trim()))\n    emit(\"paste-complete\", cells.value.join(\"\"));\n}\n</script>\n\n<style scoped>\n.codeinput {\n  display: flex;\n  gap: 8px;\n  justify-content: space-between;\n}\n.codeinput__cell {\n  flex: 1;\n  min-width: 0;\n  height: 56px;\n  padding: 0;\n  text-align: center;\n  font-size: 24px;\n  font-weight: 700;\n  font-variant-numeric: tabular-nums;\n  border: 1px solid var(--btw-line);\n  border-radius: 14px;\n  background: var(--btw-surface-2);\n  color: var(--btw-fg);\n  outline: none;\n  transition: border-color 0.12s, box-shadow 0.12s;\n}\n.codeinput__cell:focus {\n  border-color: var(--btw-accent);\n  box-shadow: 0 0 0 3px var(--btw-accent-soft);\n}\n.codeinput__cell:disabled {\n  opacity: 0.6;\n  cursor: not-allowed;\n}\n.codeinput--error .codeinput__cell {\n  border-color: var(--btw-danger-border);\n}\n.codeinput--valid .codeinput__cell {\n  border-color: var(--btw-mint);\n}\n</style>\n","import { renderList as _renderList, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock, normalizeClass as _normalizeClass } from \"vue\"\n\nconst _hoisted_1 = [\"aria-label\", \"disabled\", \"value\", \"onInput\", \"onKeydown\"]\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createElementBlock(\"div\", {\n    ref: \"rootEl\",\n    class: _normalizeClass([\"codeinput\", { 'codeinput--error': $props.error, 'codeinput--valid': $props.valid }]),\n    role: \"group\",\n    \"aria-label\": \"Verificatiecode\",\n    onFocusout: $setup.onFocusOut\n  }, [\n    (_openBlock(true), _createElementBlock(_Fragment, null, _renderList($setup.cells, (cell, i) => {\n      return (_openBlock(), _createElementBlock(\"input\", {\n        key: i,\n        ref_for: true,\n        ref: (el) => $setup.setRef(el, i),\n        class: \"codeinput__cell\",\n        type: \"text\",\n        inputmode: \"numeric\",\n        autocomplete: \"one-time-code\",\n        maxlength: \"1\",\n        \"aria-label\": `Cijfer ${i + 1}`,\n        disabled: $props.disabled,\n        value: cell,\n        onInput: $event => ($setup.onInput(i, $event)),\n        onKeydown: $event => ($setup.onKeydown(i, $event)),\n        onFocus: _cache[0] || (_cache[0] = $event => ($setup.onFocus($event))),\n        onPaste: _cache[1] || (_cache[1] = $event => ($setup.onPaste($event)))\n      }, null, 40 /* PROPS, NEED_HYDRATION */, _hoisted_1))\n    }), 128 /* KEYED_FRAGMENT */))\n  ], 34 /* CLASS, NEED_HYDRATION */))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/CodeInput.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/CodeInput.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/CodeInput.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/CodeInput.vue\";script.__scopeId = \"data-v-b7496913\";export default script;","import { nextTick, onBeforeUnmount, onMounted, shallowRef } from \"vue\";\nimport { api } from \"./api\";\n\nconst EMAIL_KEY = \"btw-login-email\";\nconst STEP_HASH = \"#inlogcode\";\n\nexport function useLoginCode(options: { focusEmail: () => void; focusCode: () => void }) {\n  const email = shallowRef(\"\");\n  const code = shallowRef(\"\");\n  const step = shallowRef<\"email\" | \"code\">(\"email\");\n  const error = shallowRef(\"\");\n  const busy = shallowRef(false);\n  const devCode = shallowRef(\"\");\n  const cooldown = shallowRef(0);\n  let resendAfter = 0;\n  let timer: ReturnType<typeof setInterval> | undefined;\n\n  async function changeEmail() {\n    if (busy.value) return;\n    step.value = \"email\";\n    code.value = \"\";\n    devCode.value = \"\";\n    error.value = \"\";\n    if (location.hash === STEP_HASH)\n      history.replaceState(null, \"\", location.pathname + location.search);\n    await nextTick();\n    options.focusEmail();\n  }\n\n  async function requestCode() {\n    if (busy.value || (step.value === \"code\" && cooldown.value > 0)) return;\n    error.value = \"\";\n    email.value = email.value.trim().toLowerCase();\n    if (email.value.length > 254 || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email.value)) {\n      error.value = \"Vul een geldig e-mailadres in.\";\n      options.focusEmail();\n      return;\n    }\n    busy.value = true;\n    try {\n      const result = await api.requestLoginCode({ email: email.value });\n      if (!result.success) {\n        error.value = result.error;\n        return;\n      }\n      try { localStorage.setItem(EMAIL_KEY, email.value); } catch { /* Browser storage is optional. */ }\n      code.value = result.code ?? \"\";\n      devCode.value = result.code ?? \"\";\n      step.value = \"code\";\n      if (!location.hash)\n        history.pushState(null, \"\", location.pathname + location.search + STEP_HASH);\n      resendAfter = Date.now() + 60000;\n      cooldown.value = 60;\n    } catch {\n      error.value = \"De code kon niet worden verstuurd. Controleer je verbinding en probeer het opnieuw.\";\n    } finally {\n      busy.value = false;\n      await nextTick();\n      if (step.value === \"code\") options.focusCode();\n    }\n  }\n\n  async function verifyCode() {\n    if (busy.value) return;\n    error.value = \"\";\n    if (!/^\\d{6}$/.test(code.value)) {\n      error.value = \"Vul de code van zes cijfers in.\";\n      options.focusCode();\n      return;\n    }\n    busy.value = true;\n    try {\n      const result = await api.verifyLoginCode({ email: email.value, code: code.value });\n      if (!result.success) {\n        error.value = result.error;\n        busy.value = false;\n        await nextTick();\n        options.focusCode();\n        return;\n      }\n      const form = document.createElement(\"form\");\n      form.method = \"post\";\n      form.action = result.form.action;\n      form.hidden = true;\n      for (const variable of result.form.vars) {\n        const input = document.createElement(\"input\");\n        input.type = \"hidden\";\n        input.name = variable.name;\n        input.value = variable.value;\n        form.append(input);\n      }\n      document.body.append(form);\n      form.submit();\n    } catch {\n      busy.value = false;\n      error.value = \"Inloggen is niet gelukt. Controleer je verbinding en probeer het opnieuw.\";\n    }\n  }\n\n  function onHashChange() {\n    if (location.hash === STEP_HASH && email.value) step.value = \"code\";\n    else void changeEmail();\n  }\n\n  onMounted(() => {\n    try { email.value = localStorage.getItem(EMAIL_KEY) ?? \"\"; } catch { /* Browser storage is optional. */ }\n    if (!email.value && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(location.hostname))\n      email.value = \"btw-test@beta.webhare.net\";\n    if (location.hash === STEP_HASH && email.value) step.value = \"code\";\n    timer = setInterval(() => {\n      cooldown.value = Math.max(0, Math.ceil((resendAfter - Date.now()) / 1000));\n    }, 1000);\n    window.addEventListener(\"hashchange\", onHashChange);\n  });\n\n  onBeforeUnmount(() => {\n    clearInterval(timer);\n    window.removeEventListener(\"hashchange\", onHashChange);\n  });\n\n  return { email, code, step, error, busy, devCode, cooldown, changeEmail, requestCode, verifyCode };\n}\n","import { createVNode as _createVNode, createElementVNode as _createElementVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createElementBlock as _createElementBlock, createCommentVNode as _createCommentVNode, createTextVNode as _createTextVNode, vModelText as _vModelText, withDirectives as _withDirectives, withCtx as _withCtx, createBlock as _createBlock, Fragment as _Fragment, withModifiers as _withModifiers } from \"vue\"\n\nconst _hoisted_1 = { class: \"login\" }\nconst _hoisted_2 = { class: \"login__topbar\" }\nconst _hoisted_3 = [\"disabled\"]\nconst _hoisted_4 = { class: \"login-form__title\" }\nconst _hoisted_5 = {\n  key: 0,\n  class: \"login-form__subtitle\"\n}\nconst _hoisted_6 = {\n  key: 1,\n  class: \"login-form__subtitle\",\n  role: \"status\"\n}\nconst _hoisted_7 = {\n  key: 2,\n  class: \"login-form__field\"\n}\nconst _hoisted_8 = [\"disabled\", \"aria-invalid\"]\nconst _hoisted_9 = {\n  key: 3,\n  class: \"login-form__field\"\n}\nconst _hoisted_10 = [\"disabled\", \"aria-busy\"]\nconst _hoisted_11 = {\n  key: 0,\n  class: \"login-form__spinner\",\n  \"aria-hidden\": \"true\"\n}\nconst _hoisted_12 = [\"disabled\"]\nconst _hoisted_13 = [\"disabled\"]\nconst _hoisted_14 = {\n  key: 0,\n  class: \"login-form__hint\"\n}\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return (_openBlock(), _createElementBlock(\"div\", _hoisted_1, [\n    _createElementVNode(\"div\", _hoisted_2, [\n      _createVNode($setup[\"ThemeToggle\"])\n    ]),\n    _createElementVNode(\"button\", {\n      type: \"button\",\n      class: \"login__brand\",\n      disabled: $setup.busy,\n      onClick: _cache[0] || (_cache[0] = (...args) => ($setup.changeEmail && $setup.changeEmail(...args))),\n      \"aria-label\": \"Terug naar inloggen\"\n    }, _cache[6] || (_cache[6] = [\n      _createElementVNode(\"span\", { class: \"login__wordmark\" }, \"BTW Coach\", -1 /* CACHED */),\n      _createElementVNode(\"span\", { class: \"login__tagline\" }, \"Brede Welvaart in Twente\", -1 /* CACHED */)\n    ]), 8 /* PROPS */, _hoisted_3),\n    _createElementVNode(\"form\", {\n      class: \"login-form\",\n      novalidate: \"\",\n      onSubmit: _cache[5] || (_cache[5] = _withModifiers($event => ($setup.step === 'email' ? $setup.requestCode() : $setup.verifyCode()), [\"prevent\"]))\n    }, [\n      _createElementVNode(\"h2\", _hoisted_4, _toDisplayString($setup.step === \"email\" ? \"Inloggen\" : \"Controleer je e-mail\"), 1 /* TEXT */),\n      ($setup.step === 'email')\n        ? (_openBlock(), _createElementBlock(\"p\", _hoisted_5, \" Vul je e-mailadres in. Je ontvangt een code om in te loggen bij BTW Coach. \"))\n        : (_openBlock(), _createElementBlock(\"p\", _hoisted_6, [\n            _cache[7] || (_cache[7] = _createTextVNode(\" Als \", -1 /* CACHED */)),\n            _createElementVNode(\"strong\", null, _toDisplayString($setup.email), 1 /* TEXT */),\n            _cache[8] || (_cache[8] = _createTextVNode(\" toegang heeft, ontvang je een code. De code is 15 minuten geldig. Controleer ook je spammap. \", -1 /* CACHED */))\n          ])),\n      ($setup.step === 'email')\n        ? (_openBlock(), _createElementBlock(\"label\", _hoisted_7, [\n            _cache[9] || (_cache[9] = _createElementVNode(\"span\", { class: \"login-form__label\" }, \"E-mailadres\", -1 /* CACHED */)),\n            _withDirectives(_createElementVNode(\"input\", {\n              ref: \"emailInput\",\n              \"onUpdate:modelValue\": _cache[1] || (_cache[1] = $event => (($setup.email) = $event)),\n              name: \"email\",\n              type: \"email\",\n              required: \"\",\n              maxlength: \"254\",\n              autocomplete: \"email\",\n              class: \"login-form__input\",\n              disabled: $setup.busy,\n              \"aria-invalid\": !!$setup.error,\n              \"aria-describedby\": \"login-error\"\n            }, null, 8 /* PROPS */, _hoisted_8), [\n              [_vModelText, $setup.email]\n            ])\n          ]))\n        : (_openBlock(), _createElementBlock(\"div\", _hoisted_9, [\n            _cache[10] || (_cache[10] = _createElementVNode(\"span\", { class: \"login-form__label\" }, \"Inlogcode\", -1 /* CACHED */)),\n            _createVNode($setup[\"CodeInput\"], {\n              ref: \"codeInput\",\n              modelValue: $setup.code,\n              \"onUpdate:modelValue\": _cache[2] || (_cache[2] = $event => (($setup.code) = $event)),\n              disabled: $setup.busy,\n              error: !!$setup.error,\n              \"aria-describedby\": \"login-error\",\n              onPasteComplete: $setup.verifyCode\n            }, null, 8 /* PROPS */, [\"modelValue\", \"disabled\", \"error\", \"onPasteComplete\"])\n          ])),\n      ($setup.error)\n        ? (_openBlock(), _createBlock($setup[\"FieldError\"], {\n            key: 4,\n            id: \"login-error\"\n          }, {\n            default: _withCtx(() => [\n              _createTextVNode(_toDisplayString($setup.error), 1 /* TEXT */)\n            ]),\n            _: 1 /* STABLE */\n          }))\n        : _createCommentVNode(\"v-if\", true),\n      _createElementVNode(\"button\", {\n        type: \"submit\",\n        class: \"login-form__submit\",\n        disabled: $setup.busy,\n        \"aria-busy\": $setup.busy\n      }, [\n        ($setup.busy)\n          ? (_openBlock(), _createElementBlock(\"span\", _hoisted_11))\n          : _createCommentVNode(\"v-if\", true),\n        _createTextVNode(\" \" + _toDisplayString($setup.step === \"email\" ? ($setup.busy ? \"Versturen…\" : \"Stuur inlogcode\") : ($setup.busy ? \"Inloggen…\" : \"Inloggen\")), 1 /* TEXT */)\n      ], 8 /* PROPS */, _hoisted_10),\n      ($setup.step === 'code')\n        ? (_openBlock(), _createElementBlock(_Fragment, { key: 5 }, [\n            _createElementVNode(\"button\", {\n              type: \"button\",\n              class: \"login-form__forgot\",\n              disabled: $setup.busy || $setup.cooldown > 0,\n              onClick: _cache[3] || (_cache[3] = (...args) => ($setup.requestCode && $setup.requestCode(...args)))\n            }, _toDisplayString($setup.cooldown > 0 ? `Opnieuw versturen over ${$setup.cooldown} seconden` : \"Geen code ontvangen? Opnieuw versturen\"), 9 /* TEXT, PROPS */, _hoisted_12),\n            _createElementVNode(\"button\", {\n              type: \"button\",\n              class: \"login-form__forgot\",\n              disabled: $setup.busy,\n              onClick: _cache[4] || (_cache[4] = (...args) => ($setup.changeEmail && $setup.changeEmail(...args)))\n            }, \"Ander e-mailadres gebruiken\", 8 /* PROPS */, _hoisted_13),\n            ($setup.devCode)\n              ? (_openBlock(), _createElementBlock(\"p\", _hoisted_14, [\n                  _cache[11] || (_cache[11] = _createTextVNode(\" Developmentmodus: code is \", -1 /* CACHED */)),\n                  _createElementVNode(\"code\", null, _toDisplayString($setup.devCode), 1 /* TEXT */)\n                ]))\n              : _createCommentVNode(\"v-if\", true)\n          ], 64 /* STABLE_FRAGMENT */))\n        : _createCommentVNode(\"v-if\", true)\n    ], 32 /* NEED_HYDRATION */)\n  ]))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/LoginForm.vue?type=script\";import \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/LoginForm.vue?type=style&index=0\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/LoginForm.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/components/LoginForm.vue\";script.__scopeId = \"data-v-74de84dc\";export default script;","<template>\n  <ChatWorkspace v-if=\"isLoggedIn\" />\n  <LoginForm v-else />\n</template>\n\n<script setup lang=\"ts\">\nimport { useWrdAuthState } from \"./lib/useWrdAuthState\";\nimport ChatWorkspace from \"./components/ChatWorkspace.vue\";\nimport LoginForm from \"./components/LoginForm.vue\";\n\nconst { isLoggedIn } = useWrdAuthState();\n</script>\n","import { openBlock as _openBlock, createBlock as _createBlock, createCommentVNode as _createCommentVNode } from \"vue\"\n\nexport function render(_ctx, _cache, $props, $setup, $data, $options) {\n  return ($setup.isLoggedIn)\n    ? (_openBlock(), _createBlock($setup[\"ChatWorkspace\"], { key: 0 }))\n    : (_openBlock(), _createBlock($setup[\"LoginForm\"], { key: 1 }))\n}","import script from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/App.vue?type=script\";import { render } from \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/App.vue?type=template\"; script.render = render;script.__file = \"../opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/App.vue\";export default script;","import \"@webhare/frontend/src/init\";import \"/opt/wh/whtree/modules/publisher/js/internal/polyfills/all\";\nimport \"/opt/whdata/installedmodules/btw.20261010T192823.471Z/webdesigns/btwcoach/frontend/frontend\";const aps = globalThis.whAssetPacks ||= {}; aps[\"btw:btwcoach\"]=\"2026-10-10T19:28:39.762Z\";"],"mappings":"+OAAA,IAAAA,GAAAC,EAAAC,IAAA,cAOA,OAAO,eAAeA,GAAS,aAAc,CAAE,MAAO,EAAK,CAAC,EAI5D,SAASC,GAAQC,EAAK,CACpB,IAAMC,EAAsB,OAAO,OAAO,IAAI,EAC9C,QAAWC,KAAOF,EAAI,MAAM,GAAG,EAAGC,EAAIC,CAAG,EAAI,EAC7C,OAAQC,GAAQA,KAAOF,CACzB,CAEA,IAAMG,IAAY,CAAC,EACbC,IAAY,CAAC,EACbC,IAAO,IAAM,CACnB,EACMC,IAAK,IAAM,GACXC,IAAQN,GAAQA,EAAI,WAAW,CAAC,IAAM,KAAOA,EAAI,WAAW,CAAC,IAA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AQ,CACb,CACC,KAAM,OACN,GAAI,OACL,EACA,CACC,KAAM,QACN,GAAI,MACL,EACA,CACC,KAAM,OACN,GAAI,MACL,EACA,CACC,KAAM,MACN,GAAI,KACL,EACA,CACC,KAAM,OACN,GAAI,IACL,EACA,CACC,KAAM,SACN,GAAI,GACL,EACA,CACC,KAAM,SACN,GAAI,GACL,CACD,EAwJMvgD,IAAoC,OAAO,OAAO,CAAC,EAAG,CAAE,OAAQ2D,EAAS,EAAG,CACjF,WAAY,CACX,IACA,EACA,IACA,CACD,EACA,YAAa,CACZ,IACA,EACA,IACA,CACD,EACA,cAAe,CACd,IACA,EACA,IACA,CACD,EACA,WAAY,CACX,IACA,EACA,GACA,CACD,EACA,YAAa,CACZ,GACA,EACA,IACA,CACD,EACA,cAAe,CACd,IACA,EACA,IACA,CACD,EACA,YAAa,CACZ,IACA,EACA,IACA,CACD,EACA,aAAc,CACb,IACA,EACA,IACA,CACD,EACA,eAAgB,CACf,IACA,EACA,IACA,CACD,EACA,YAAa,CACZ,GACA,EACA,IACA,CACD,EACA,aAAc,CACb,IACA,EACA,GACA,CACD,EACA,eAAgB,CACf,IACA,EACA,IACA,CACD,EACA,YAAa,CACZ,IACA,EACA,IACA,CACD,EACA,aAAc,CACb,IACA,EACA,IACA,CACD,EACA,eAAgB,CACf,IACA,EACA,IACA,CACD,EACA,WAAY,CACX,GACA,EACA,IACA,CACD,EACA,YAAa,CACZ,IACA,EACA,GACA,CACD,EACA,cAAe,CACd,IACA,EACA,IACA,CACD,EACA,WAAY,CACX,IACA,EACA,EACA,GACD,EACA,YAAa,CACZ,EACA,IACA,IACA,CACD,EACA,cAAe,CACd,IACA,EACA,IACA,CACD,EACA,WAAY,CACX,IACA,EACA,IACA,IACD,EACA,YAAa,CACZ,IACA,KACA,IACA,CACD,EACA,cAAe,CACd,IACA,IACA,IACA,GACD,CACD,CAAC,EA6eK0jD,IAAwC,CAC7C,WAAY,aACZ,SAAU,WACX,EA+LMqD,GAAuB,mFC93P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,IAAMC,EAAQ,KAAO,OAAOH,CAAI,EAChC,OAAOE,GAAQD,GAAQ,CAACH,IAAa,KAAK,OAAO,aAAaG,CAAI,CAAC,EAC/DE,EACAA,EAAQ,GACd,CCVO,IAAMC,GAA0B,CACrC,QACA,MACA,SACA,QACA,SACA,QACA,SACA,OACA,OACA,SACA,MACA,SACA,QACA,SACA,OACA,KACA,SACA,QACA,SACA,OACA,KACA,SACA,SACA,QACA,SACA,SACA,SACA,OACA,OACA,MACA,QACA,SACA,QACA,SACA,OACA,SACA,SACA,QACA,QACA,QACA,SACA,MACA,QACA,SACA,OACA,SACA,SACA,QACA,OACA,OACA,SACA,MACA,SACA,SACA,QACA,SACA,MACA,OACA,SACA,SACA,SACA,KACA,SACA,QACA,QACA,SACA,SACA,OACA,QACA,KACA,OACA,QACA,SACA,OACA,MACA,SACA,SACA,QACA,SACA,OACA,OACA,SACA,SACA,OACA,OACA,SACA,QACA,OACA,QACA,MACA,OACA,MACA,OACA,OACA,OACA,QACA,QACA,QACA,SACA,QACA,SACA,MACA,OACA,SACA,MACA,MACF,EC3GO,IAAMC,GAAyB,CACpC,KAAM,OACN,MAAO,OACP,KAAM,OACN,MAAO,OACP,OAAQ,OACR,IAAK,OACL,OAAQ,OACR,KAAM,OACN,IAAK,OACL,KAAM,OACN,KAAM,OACN,MAAO,OACP,IAAK,OACL,IAAK,OACL,IAAK,OACL,KAAM,OACN,IAAK,OACL,OAAQ,OACR,KAAM,OACN,KAAM,OACN,MAAO,OACP,MAAO,OACP,KAAM,OACN,OAAQ,OACR,MAAO,OACP,KAAM,OACN,KAAM,OACN,MAAO,OACP,OAAQ,OACR,OAAQ,OACR,OAAQ,OACR,OAAQ,OACR,OAAQ,OACR,OAAQ,OACR,MAAO,OACP,OAAQ,OACR,KAAM,OACN,MAAO,OACP,MAAO,OACP,OAAQ,OACR,OAAQ,OACR,OAAQ,OACR,MAAO,OACP,KAAM,OACN,OAAQ,OACR,OAAQ,OACR,MAAO,OACP,KAAM,O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IAAOC,EAAMC,EAAQC,EAAQC,EAAQC,EAAOC,EAAU,CACpE,OAAQF,EAAO,eACV,GAAAG,WAAW,KAAG,GAAAC,aAAaJ,EAAO,cAAkB,CAAE,IAAK,CAAE,CAAC,OAC9D,GAAAG,WAAW,KAAG,GAAAC,aAAaJ,EAAO,UAAc,CAAE,IAAK,CAAE,CAAC,EACjE,CCN+PK,GAAO,OAASC,IAAOD,GAAO,OAAS,+FAA+F,IAAOA,IAAQA,GnuBiBpZ,IAAME,IAAkB,yBAIxBC,IAAU,EAEVC,GAAW,IAAM,IACf,eAAUC,GAAG,EAAE,MAAM,MAAM,EAM3BC,GAAa,CACX,QAAS,SAAY,CACnB,MAAMC,GAAiB,CACzB,CACF,CAAC,EAIG,SAAS,gBAAgB,UAAU,SAASL,GAAe,GACxDK,GAAiB,CAE1B,CAAC,EouBxCoG,IAAMC,IAAM,WAAW,eAAiB,CAAC,EAAGA,IAAI,cAAc,EAAE","names":["require_shared_cjs_prod","__commonJSMin","exports","makeMap","str","map","key","val","EMPTY_OBJ","EMPTY_ARR","NOOP","NO","isOn","isModelListener","extend","remove","arr","el","i","hasOwnProperty","hasOwn","isArray","isMap","toTypeString","isSet","isDate","isRegExp","isFunction","isString","isSymbol","isObject","isPromise","objectToString","value","toRawType","isPlainObject","isIntegerKey","isReservedProp","isBuiltInDirective","cacheStringFunction","fn","cache","camelizeRE","camelize","_","c","hyphenateRE","hyphenate","capitalize","toHandlerKey","hasChanged","oldValue","invokeArrayFns","fns","arg","def","obj","writable","looseToNumber","n","toNumber","_globalThis","getGlobalThis","identRE","genPropsAccessExp","name","genCacheKey","source","options","PatchFlags","PatchFlagNames","ShapeFlags","SlotFlags","slotFlagsText","GLOBALS_ALLOWED","isGloballyAllowed","isGloballyWhitelisted","range","generateCodeFrame","start","end","lines","newlineSequences","idx","count","res","j","line","lineLength","newLineSeqLength","pad","length","normalizeStyle","item","normalized","parseStringStyle","listDelimiterRE","propertyDelimiterRE","styleCommentRE","cssText","ret","tmp","stringifyStyle","styles","normalizedKey","normalizeClass","normalizeProps","props","klass","style","HTML_TAGS","SVG_TAGS","MATH_TAGS","VOID_TAGS","isHTMLTag","isSVGTag","isMathMLTag","isVoidTag","specialBooleanAttrs","isSpecialBooleanAttr","isBooleanAttr","includeBooleanAttr","unsafeAttrCharRE","attrValidationCache","isSSRSafeAttrName","isUnsafe","propsToAttrMap","isKnownHtmlAttr","isKnownSvgAttr","isKnownMathMLAttr","isRenderableAttrValue","type","escapeRE","escapeHtml","string","match","html","escaped","index","lastIndex","commentStripRE","escapeHtmlComment","src","cssVarNameEscapeSymbolsRE","getEscapedCssVarName","doubleEscape","s","looseCompareArrays","a","b","equal","looseEqual","aValidType","bValidType","aKeysCount","bKeysCount","aHasKey","bHasKey","looseIndexOf","isRef","toDisplayString","replacer","_key","entries","val2","stringifySymbol","v","_a","normalizeCssVarValue","require_shared","__commonJSMin","exports","module","exports","c","exports","c","decodeMap","exports","_a","codePoint","output","replaceCodePoint","decodeCodePoint","decode_data_html_js_1","__importDefault","exports","decode_data_xml_js_1","decode_codepoint_js_1","__importStar","decode_codepoint_js_2","CharCodes","TO_LOWER_BIT","BinTrieFlags","isNumber","code","isHexadecimalCharacter","isAsciiAlphaNumeric","isEntityInAttributeInvalidEnd","EntityDecoderState","DecodingMode","EntityDecoder","decodeTree","emitCodePoint","errors","decodeMode","str","offset","start","end","base","digitCount","startIdx","char","lastCp","expectedLength","_a","current","valueLength","determineBranch","_b","result","consumed","getDecoder","ret","decoder","lastIndex","len","nodeIdx","branchCount","jumpOffset","value","lo","hi","mid","midVal","htmlDecoder","xmlDecoder","decodeHTML","mode","decodeHTMLAttribute","decodeHTMLStrict","decodeXML","Position","constructor","line","col","index","column","SourceLocation","start","end","filename","identifierName","createPositionWithColumnOffset","position","columnOffset","code","ModuleErrors","ImportMetaOutsideModule","message","ImportOutsideModule","NodeDescriptions","ArrayPattern","AssignmentExpression","AssignmentPattern","ArrowFunctionExpression","ConditionalExpression","CatchClause","ForOfStatement","ForInStatement","ForStatement","FormalParameters","Identifier","ImportSpecifier","ImportDefaultSpecifier","ImportNamespaceSpecifier","ObjectPattern","ParenthesizedExpression","RestElement","UpdateExpression","true","false","VariableDeclarator","YieldExpression","toNodeDescription","node","type","prefix","StandardErrors","AccessorIsGenerator","kind","ArgumentsInClass","AsyncFunctionInSingleStatementContext","AwaitBindingIdentifier","AwaitBindingIdentifierInStaticBlock","AwaitExpressionFormalParameter","AwaitUsingNotInAsyncContext","AwaitNotInAsyncContext","BadGetterArity","BadSetterArity","BadSetterRestParameter","ConstructorClassField","ConstructorClassPrivateField","ConstructorIsAccessor","ConstructorIsAsync","ConstructorIsGenerator","DeclarationMissingInitializer","DecoratorArgumentsOutsideParentheses","DecoratorBeforeExport","DecoratorsBeforeAfterExport","DecoratorConstructor","DecoratorExportClass","DecoratorSemicolon","DecoratorStaticBlock","DeferImportRequiresNamespace","DeletePrivateField","DestructureNamedImport","DuplicateConstructor","DuplicateDefaultExport","DuplicateExport","exportName","DuplicateProto","DuplicateRegExpFlags","ElementAfterRest","EscapedCharNotAnIdentifier","ExportBindingIsString","localName","ExportDefaultFromAsIdentifier","ForInOfLoopInitializer","ForInUsing","ForOfAsync","ForOfLet","GeneratorInSingleStatementContext","IllegalBreakContinue","IllegalLanguageModeDirective","IllegalReturn","ImportAttributesUseAssert","ImportBindingIsString","importName","ImportCallArity","ImportCallNotNewExpression","ImportCallSpreadArgument","ImportJSONBindingNotDefault","ImportReflectionHasAssertion","ImportReflectionNotBinding","IncompatibleRegExpUVFlags","InvalidBigIntLiteral","InvalidCodePoint","InvalidCoverDiscardElement","InvalidCoverInitializedName","InvalidDecimal","InvalidDigit","radix","InvalidEscapeSequence","InvalidEscapeSequenceTemplate","InvalidEscapedReservedWord","reservedWord","InvalidIdentifier","InvalidLhs","ancestor","InvalidLhsBinding","InvalidLhsOptionalChaining","InvalidNumber","InvalidOrMissingExponent","InvalidOrUnexpectedToken","unexpected","InvalidParenthesizedAssignment","InvalidPrivateFieldResolution","InvalidPropertyBindingPattern","InvalidRecordProperty","InvalidRestAssignmentPattern","LabelRedeclaration","labelName","LetInLexicalBinding","LineTerminatorBeforeArrow","MalformedRegExpFlags","MissingClassName","MissingEqInAssignment","MissingSemicolon","MissingPlugin","missingPlugin","map","name","JSON","stringify","join","MissingOneOfPlugins","MissingUnicodeEscape","MixingCoalesceWithLogical","ModuleAttributeDifferentFromType","ModuleAttributeInvalidValue","ModuleAttributesWithDuplicateKeys","key","ModuleExportNameHasLoneSurrogate","surrogateCharCode","toString","ModuleExportUndefined","MultipleDefaultsInSwitch","NewlineAfterThrow","NoCatchOrFinally","NumberIdentifier","NumericSeparatorInEscapeSequence","ObsoleteAwaitStar","OptionalChainingNoNew","OptionalChainingNoTemplate","OverrideOnConstructor","ParamDupe","PatternHasAccessor","PatternHasMethod","PrivateInExpectedIn","PrivateNameRedeclaration","RecordExpressionBarIncorrectEndSyntaxType","RecordExpressionBarIncorrectStartSyntaxType","RecordExpressionHashIncorrectStartSyntaxType","RecordNoProto","RestTrailingComma","SloppyFunction","SloppyFunctionAnnexB","SourcePhaseImportRequiresDefault","StaticPrototype","SuperNotAllowed","SuperPrivateField","TrailingDecorator","TupleExpressionBarIncorrectEndSyntaxType","TupleExpressionBarIncorrectStartSyntaxType","TupleExpressionHashIncorrectStartSyntaxType","UnexpectedArgumentPlaceholder","UnexpectedAwaitAfterPipelineBody","UnexpectedDigitAfterHash","UnexpectedImportExport","UnexpectedKeyword","keyword","UnexpectedLeadingDecorator","UnexpectedLexicalDeclaration","UnexpectedNewTarget","UnexpectedNumericSeparator","UnexpectedPrivateField","UnexpectedReservedWord","UnexpectedSuper","UnexpectedToken","expected","UnexpectedTokenUnaryExponentiation","UnexpectedUsingDeclaration","UnexpectedVoidPattern","UnsupportedBind","UnsupportedDecoratorExport","UnsupportedDefaultExport","UnsupportedImport","UnsupportedMetaProperty","target","onlyValidPropertyName","UnsupportedParameterDecorator","UnsupportedPropertyDecorator","UnsupportedSuper","UnterminatedComment","UnterminatedRegExp","UnterminatedString","UnterminatedTemplate","UsingDeclarationExport","UsingDeclarationHasBindingPattern","VarRedeclaration","VoidPatternCatchClauseParam","VoidPatternInitializer","YieldBindingIdentifier","YieldInParameter","YieldNotInGeneratorFunction","ZeroDigitNumericSeparator","StrictModeErrors","StrictDelete","StrictEvalArguments","referenceName","StrictEvalArgumentsBinding","bindingName","StrictFunction","StrictNumericEscape","StrictOctalLiteral","StrictWith","ParseExpressionErrors","ParseExpressionEmptyInput","ParseExpressionExpectsEOF","String","fromCodePoint","UnparenthesizedPipeBodyDescriptions","Set","Object","assign","PipeBodyIsTighter","PipeTopicRequiresHackPipes","PipeTopicUnbound","PipeTopicUnconfiguredToken","token","PipeTopicUnused","PipeUnparenthesizedBody","PipelineBodyNoArrow","PipelineBodySequenceExpression","PipelineHeadSequenceExpression","PipelineTopicUnused","PrimaryTopicNotAllowed","PrimaryTopicRequiresSmartPipeline","defineHidden","obj","value","defineProperty","enumerable","configurable","toParseErrorConstructor","toMessage","reasonCode","syntaxPlugin","hasMissingPlugin","oldReasonCodes","AccessorCannotDeclareThisParameter","AccessorCannotHaveTypeParameters","ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference","SetAccessorCannotHaveOptionalParameter","SetAccessorCannotHaveRestParameter","SetAccessorCannotHaveReturnType","loc","details","error","SyntaxError","pos","overrides","_overrides$loc","get","set","writable","ParseErrorEnum","argument","Array","isArray","parseErrorTemplates","ParseErrorConstructors","keys","template","_ref","rest","_objectWithoutPropertiesLoose","_excluded","Errors","PipelineOperatorErrors","createDefaultOptions","sourceType","sourceFilename","undefined","startIndex","startColumn","startLine","allowAwaitOutsideFunction","allowReturnOutsideFunction","allowNewTargetOutsideFunction","allowImportExportEverywhere","allowSuperOutsideMethod","allowUndeclaredExports","allowYieldOutsideFunction","plugins","strictMode","ranges","tokens","createImportExpressions","createParenthesizedExpressions","errorRecovery","attachComment","annexB","getOptions","opts","options","Error","toUnenumerable","object","toESTreeLocation","estree","superClass","parse","file","optionFlags","parseRegExpLiteral","pattern","flags","regex","RegExp","estreeParseLiteral","parseBigIntLiteral","bigInt","BigInt","bigint","parseDecimalLiteral","decimal","parseLiteral","parseStringLiteral","parseNumericLiteral","parseNullLiteral","parseBooleanLiteral","estreeParseChainExpression","endLoc","chain","startNodeAtNode","expression","finishNodeAt","directiveToStmt","directive","castNodeTo","raw","extra","expressionValue","stmt","rawValue","fillOptionalPropertiesForTSESLint","cloneEstreeStringLiteral","range","cloned","create","prototype","initFunction","isAsync","checkDeclaration","isObjectProperty","getObjectOrClassMethodParams","method","params","isValidDirective","_stmt$expression$extr","parenthesized","parseBlockBody","allowDirectives","topLevel","afterBlockParse","directiveStatements","directives","d","body","concat","parsePrivateName","getPluginOption","convertPrivateNameToPrivateIdentifier","getPrivateNameSV","id","isPrivateName","parseFunctionBody","allowExpression","isMethod","parseMethod","isGenerator","isConstructor","allowDirectSuper","inClassScope","funcNode","startNode","typeParameters","resetStartLocationFromNode","valueNode","computed","shorthand","finishNode","nameIsConstructor","parseClassProperty","args","propertyNode","parseClassPrivateProperty","parseClassAccessorProperty","accessorPropertyNode","abstract","hasPlugin","parseObjectProperty","prop","startLoc","isPattern","refExpressionErrors","finishObjectProperty","isValidLVal","isUnparenthesizedInAssign","binding","isAssignable","isBinding","toAssignable","isLHS","classScope","usePrivateName","toAssignableObjectExpressionProp","isLast","raise","finishCallExpression","unfinished","optional","callee","source","arguments","_ref2","attributes","toReferencedArguments","parseExport","decorators","exportStartLoc","state","lastTokStartLoc","exported","specifiers","length","_declaration$decorato","declaration","resetStartLocation","stopParseSubscript","base","optionalChainMember","parseMember","isOptionalMemberExpression","hasPropertyAsPrivateName","isObjectMethod","result","cloneIdentifier","cloneStringLiteral","resetEndLocation","lastTokEndLoc","TokContext","preserveSpace","types","brace","j_oTag","j_cTag","j_expr","beforeExpr","startsExpr","isLoop","isAssign","postfix","ExportedTokenType","label","conf","rightAssociative","binop","updateContext","keywords","Map","createKeyword","createToken","createBinop","tokenTypeCounter","tokenTypes","tokenLabels","tokenBinops","tokenBeforeExprs","tokenStartsExprs","tokenPrefixes","_options$binop","_options$beforeExpr","_options$startsExpr","_options$prefix","push","createKeywordLike","_options$binop2","_options$beforeExpr2","_options$startsExpr2","_options$prefix2","tt","bracketL","bracketHashL","bracketBarL","bracketR","bracketBarR","braceL","braceBarL","braceHashL","braceR","braceBarR","parenL","parenR","comma","semi","colon","doubleColon","dot","question","questionDot","arrow","ellipsis","backQuote","dollarBraceL","templateTail","templateNonTail","at","hash","interpreterDirective","eq","slashAssign","xorAssign","moduloAssign","incDec","bang","tilde","doubleCaret","doubleAt","pipeline","nullishCoalescing","logicalOR","logicalAND","bitwiseOR","bitwiseXOR","bitwiseAND","equality","lt","gt","relational","bitShift","bitShiftL","bitShiftR","plusMin","modulo","star","slash","exponent","_in","_instanceof","_break","_case","_catch","_continue","_debugger","_default","_else","_finally","_function","_if","_return","_switch","_throw","_try","_var","_const","_with","_new","_this","_super","_class","_extends","_export","_import","_null","_true","_false","_typeof","_void","_delete","_do","_for","_while","_as","_assert","_async","_await","_defer","_from","_get","_let","_meta","_of","_sent","_set","_source","_static","_using","_yield","_asserts","_checks","_exports","_global","_implements","_intrinsic","_infer","_is","_mixins","_proto","_require","_satisfies","_keyof","_readonly","_unique","_abstract","_declare","_enum","_module","_namespace","_interface","_type","_opaque","placeholder","string","num","regexp","privateName","eof","jsxName","jsxText","jsxTagStart","jsxTagEnd","tokenIsIdentifier","tokenKeywordOrIdentifierIsKeyword","tokenIsKeywordOrIdentifier","tokenIsLiteralPropertyName","tokenComesBeforeExpression","tokenCanStartExpression","tokenIsAssignment","tokenIsFlowInterfaceOrTypeOrOpaque","tokenIsLoop","tokenIsKeyword","tokenIsOperator","tokenIsPostfix","tokenIsPrefix","tokenIsTSTypeOperator","tokenIsTSDeclarationStart","tokenLabelName","tokenOperatorPrecedence","tokenIsRightAssociative","tokenIsTemplate","getExportedToken","context","pop","tc","nonASCIIidentifierStartChars","nonASCIIidentifierChars","nonASCIIidentifierStart","nonASCIIidentifier","astralIdentifierStartCodes","astralIdentifierCodes","isInAstralSet","i","isIdentifierStart","test","fromCharCode","isIdentifierChar","reservedWords","strict","strictBind","reservedWordsStrictSet","reservedWordsStrictBindSet","isReservedWord","word","inModule","isStrictReservedWord","has","isStrictBindOnlyReservedWord","isStrictBindReservedWord","isKeyword","isIteratorStart","current","next","next2","reservedWordLikeSet","canBeReservedWord","Scope","names","firstLexicalName","ScopeHandler","parser","scopeStack","undefinedExports","inTopLevel","currentScope","inFunction","currentVarScopeFlags","allowSuper","currentThisScopeFlags","allowNewTarget","inClass","inClassAndNotInNonArrowFunction","inStaticBlock","ScopeFlag","inNonArrowFunction","inBareCaseStatement","treatFunctionsAsVar","treatFunctionsAsVarInScope","createScope","enter","exit","scope","declareName","bindingType","checkRedeclarationInScope","maybeExportDefined","delete","isRedeclaredInScope","checkLocalExport","FlowScope","declareFunctions","FlowScopeHandler","add","reservedTypes","FlowErrors","AmbiguousConditionalArrow","AmbiguousDeclareModuleKind","AssignReservedType","reservedType","DeclareClassElement","DeclareClassFieldInitializer","DuplicateDeclareModuleExports","EnumBooleanMemberNotInitialized","memberName","enumName","EnumDuplicateMemberName","EnumInconsistentMemberValues","EnumInvalidExplicitType","invalidEnumType","EnumInvalidExplicitTypeUnknownSupplied","EnumInvalidMemberInitializerPrimaryType","explicitType","EnumInvalidMemberInitializerSymbolType","EnumInvalidMemberInitializerUnknownType","EnumInvalidMemberName","suggestion","EnumNumberMemberNotInitialized","EnumStringMemberInconsistentlyInitialized","GetterMayNotHaveThisParam","ImportReflectionHasImportType","ImportTypeShorthandOnlyInPureImport","InexactInsideExact","InexactInsideNonObject","InexactVariance","InvalidNonTypeImportInDeclareModule","MissingTypeParamDefault","NestedDeclareModule","NestedFlowComment","PatternIsOptional","SetterMayNotHaveThisParam","SpreadVariance","ThisParamAnnotationRequired","ThisParamBannedInConstructor","ThisParamMayNotBeOptional","ThisParamMustBeFirst","ThisParamNoDefault","TypeBeforeInitializer","TypeCastInPattern","UnexpectedExplicitInexactInObject","UnexpectedReservedType","UnexpectedReservedUnderscore","UnexpectedSpaceBetweenModuloChecks","UnexpectedSpreadType","UnexpectedSubtractionOperand","UnexpectedTokenAfterTypeParameter","UnexpectedTypeParameterBeforeAsyncArrowFunction","UnsupportedDeclareExportKind","unsupportedExportKind","UnsupportedStatementInDeclareModule","UnterminatedFlowComment","isEsModuleType","bodyElement","hasTypeImportKind","importKind","exportSuggestions","const","let","interface","partition","list","list1","list2","FLOW_PRAGMA_REGEX","flow","flowPragma","getScopeHandler","shouldParseTypes","finishToken","val","addComment","comment","matches","exec","flowParseTypeInitialiser","tok","oldInType","inType","expect","flowParseType","flowParsePredicate","moduloLoc","expectContextual","eat","parseExpression","flowParseTypeAndPredicateInitialiser","predicate","match","flowParseDeclareClass","flowParseInterfaceish","flowParseDeclareFunction","parseIdentifier","typeNode","typeContainer","flowParseTypeParameterDeclaration","tmp","flowParseFunctionTypeParams","this","returnType","typeAnnotation","semicolon","flowParseDeclare","insideModule","flowParseDeclareVariable","eatContextual","flowParseDeclareModuleExports","flowParseDeclareModule","isContextual","flowParseDeclareTypeAlias","flowParseDeclareOpaqueType","flowParseDeclareInterface","flowParseDeclareExportDeclaration","flowParseTypeAnnotatableIdentifier","parseExprAtom","bodyNode","parseImport","hasModuleExport","forEach","default","isLet","exportKind","flowParseTypeAnnotation","finished","flowParseTypeAlias","flowParseOpaqueType","isClass","flowParseRestrictedIdentifier","extends","flowParseInterfaceExtends","implements","mixins","flowParseObjectType","allowStatic","allowExact","allowSpread","allowProto","allowInexact","flowParseQualifiedTypeIdentifier","flowParseTypeParameterInstantiation","flowParseInterface","checkNotUnderscore","checkReservedType","liberal","right","declare","supertype","impltype","flowParseTypeParameter","requireDefault","nodeStartLoc","variance","flowParseVariance","ident","bound","defaultRequired","typeParameter","flowInTopLevelContext","cb","curContext","oldContext","flowParseTypeParameterInstantiationInExpression","reScan_lt","oldNoAnonFunctionType","noAnonFunctionType","reScan_lt_gt","flowParseTypeParameterInstantiationCallOrNew","flowParseTypeOrImplicitInstantiation","flowParseInterfaceType","flowParseObjectPropertyKey","flowParseObjectTypeIndexer","isStatic","static","lookahead","flowParseObjectTypeInternalSlot","flowParseObjectTypeMethodish","startNodeAt","flowParseFunctionTypeParam","flowParseObjectTypeCallProperty","nodeStart","callProperties","properties","indexers","internalSlots","endDelim","exact","inexact","protoStartLoc","inexactStartLoc","propOrInexact","flowParseObjectTypeProperty","flowObjectTypeSemicolon","out","proto","flowCheckGetterSetterParams","property","paramCount","node2","qualification","flowParseGenericType","flowParseTypeofType","flowParsePrimaryType","flowParseTupleType","first","lh","isThis","reinterpretTypeAsFunctionTypeParam","flowIdentToTypeAnnotation","isGroupedType","parseLiteralAtNode","createIdentifier","flowParsePostfixType","seenOptionalIndexedAccess","canInsertSemicolon","elementType","objectType","indexType","flowParsePrefixType","flowParseAnonFunctionWithoutParens","param","flowParseIntersectionType","flowParseUnionType","allowPrimitiveOverride","typeCastToParameter","allowExpressionBody","forwardNoArrowParamsConversionAt","parseFunctionBodyAndFinish","parseStatementLike","flowParseEnumDeclaration","parseExpressionStatement","expr","shouldParseExportDeclaration","containsEsc","isExportDefaultSpecifier","parseExportDefaultExpression","parseConditional","maybeInArrowParameters","nextCh","lookaheadCharCode","setOptionalParametersError","clone","originalNoArrowAt","noArrowAt","consequent","failed","tryParseConditionalConsequent","valid","invalid","getArrowLikeExpressions","alternate","parseMaybeAssign","noArrowParamsConversionAt","parseMaybeAssignAllowIn","disallowInvalid","stack","arrows","finishArrowValidation","every","_node$extra","toAssignableList","trailingCommaLoc","checkParams","includes","offsetToSourcePos","parseParenItem","newNode","typeCastNode","assertModuleNodeAllowed","parseExportDeclaration","declarationNode","parseExportSpecifiers","parseExportFrom","eatExportStar","maybeParseExportNamespaceSpecifier","hasNamespace","parseClassId","isStatement","optionalId","parseClassMember","classBody","member","parseClassMemberFromModifier","isIterator","readIterator","readWord1","fullWord","curPosition","getTokenFromCode","input","charCodeAt","finishOp","left","exprList","toReferencedList","isParenthesizedExpr","_expr$extra","parseArrayLike","close","canBePattern","isTuple","elements","isParenthesized","isClassMethod","isClassProperty","isNonstaticConstructor","pushClassMethod","allowsDirectSuper","isThisParam","pushClassPrivateMethod","parseClassSuper","superTypeParameters","implemented","checkGetterSetterParams","parsePropertyNamePrefixOperator","parseObjPropValue","isAccessor","parseFunctionParamType","parseMaybeDefault","checkImportReflection","module","parseImportSpecifierLocal","specifier","local","finishImportSpecifier","isPotentialImportPhase","isExport","ch","applyImportPhase","phase","parseImportSpecifier","importedIsString","isInTypeOnlyImport","isMaybeTypeOnly","firstIdent","imported","specifierTypeKind","isLookaheadContextual","as_ident","specifierIsTypeImport","checkReservedWord","parseBindingAtom","parseFunctionParams","parseVarId","decl","parseAsyncArrowFromCallExpression","call","shouldParseAsyncArrow","afterLeftParse","_jsx","jsx","tryParse","currentContext","_jsx2","_jsx3","abort","_arrowExpression$extr","arrowExpression","maybeUnwrapTypeCastExpression","aborted","async","failState","thrown","parseArrow","shouldParseArrow","setArrowFunctionParameters","allowDuplicates","isArrowFunction","strictModeChanged","parseParenAndDistinguishExpression","canBeArrow","sourceToOffsetPos","parseSubscripts","noCalls","parseCallExpressionArguments","parseAsyncArrowWithTypeParameters","parseSubscript","subscriptState","isLookaheadToken_lt","stop","typeArguments","parseNewCallee","targs","parseArrowExpression","readToken_mult_modulo","hasFlowComment","nextToken","readToken_pipe_amp","parseTopLevel","program","fileNode","skipBlockComment","skipFlowComment","hasFlowCommentCompletion","commentSkip","shiftToFirstNonWhiteSpace","ch2","ch3","slice","indexOf","flowEnumErrorBooleanMemberNotInitialized","flowEnumErrorInvalidMemberInitializer","enumContext","flowEnumErrorNumberMemberNotInitialized","flowEnumErrorStringMemberInconsistentlyInitialized","flowEnumMemberInit","endOfInit","literal","flowEnumMemberRaw","init","flowEnumCheckExplicitTypeMismatch","expectedType","flowEnumMembers","seenNames","members","booleanMembers","numberMembers","stringMembers","defaultedMembers","hasUnknownMembers","memberNode","toUpperCase","flowEnumStringMembers","initializedMembers","flowEnumParseExplicitType","flowEnumBody","nameLoc","empty","boolsLen","numsLen","strsLen","defaultedLen","jsxParseOpeningElementAfterName","nextTokenStart","afterNext","readToken_lt","readToken_gt","entities","__proto__","quot","amp","apos","nbsp","iexcl","cent","pound","curren","yen","brvbar","sect","uml","copy","ordf","laquo","not","shy","reg","macr","deg","plusmn","sup2","sup3","acute","micro","para","middot","cedil","sup1","ordm","raquo","frac14","frac12","frac34","iquest","Agrave","Aacute","Acirc","Atilde","Auml","Aring","AElig","Ccedil","Egrave","Eacute","Ecirc","Euml","Igrave","Iacute","Icirc","Iuml","ETH","Ntilde","Ograve","Oacute","Ocirc","Otilde","Ouml","times","Oslash","Ugrave","Uacute","Ucirc","Uuml","Yacute","THORN","szlig","agrave","aacute","acirc","atilde","auml","aring","aelig","ccedil","egrave","eacute","ecirc","euml","igrave","iacute","icirc","iuml","eth","ntilde","ograve","oacute","ocirc","otilde","ouml","divide","oslash","ugrave","uacute","ucirc","uuml","yacute","thorn","yuml","OElig","oelig","Scaron","scaron","Yuml","fnof","circ","Alpha","Beta","Gamma","Delta","Epsilon","Zeta","Eta","Theta","Iota","Kappa","Lambda","Mu","Nu","Xi","Omicron","Pi","Rho","Sigma","Tau","Upsilon","Phi","Chi","Psi","Omega","alpha","beta","gamma","delta","epsilon","zeta","eta","theta","iota","kappa","lambda","mu","nu","xi","omicron","pi","rho","sigmaf","sigma","tau","upsilon","phi","chi","psi","omega","thetasym","upsih","piv","ensp","emsp","thinsp","zwnj","zwj","lrm","rlm","ndash","mdash","lsquo","rsquo","sbquo","ldquo","rdquo","bdquo","dagger","Dagger","bull","hellip","permil","prime","Prime","lsaquo","rsaquo","oline","frasl","euro","image","weierp","real","trade","alefsym","larr","uarr","rarr","darr","harr","crarr","lArr","uArr","rArr","dArr","hArr","forall","part","exist","nabla","isin","notin","ni","prod","sum","minus","lowast","radic","infin","ang","and","or","cap","cup","int","there4","sim","cong","asymp","ne","equiv","le","ge","sub","sup","nsub","sube","supe","oplus","otimes","perp","sdot","lceil","rceil","lfloor","rfloor","lang","rang","loz","spades","clubs","hearts","diams","lineBreak","lineBreakG","isNewLine","hasNewLine","skipWhiteSpace","skipWhiteSpaceInLine","isWhitespace","JsxErrors","AttributeIsEmpty","MissingClosingTagElement","openingTagName","MissingClosingTagFragment","UnexpectedSequenceExpression","HTMLEntity","UnsupportedJsxValue","UnterminatedJsxContent","UnwrappedAdjacentJSXElements","isFragment","getQualifiedJSXName","namespace","jsxReadToken","chunkStart","canStartJSXElement","jsxReadEntity","jsxReadNewLine","normalizeCRLF","curLine","lineStart","jsxReadString","quote","startPos","codePointAtPos","codePoint","readInt","count","desc","entity","XHTMLEntities","jsxReadWord","jsxParseIdentifier","jsxParseNamespacedName","jsxParseElementName","jsxParseAttributeValue","setContext","jsxParseExpressionContainer","jsxParseEmptyExpression","jsxParseSpreadChild","previousContext","jsxParseAttribute","jsxParseOpeningElementAt","selfClosing","jsxParseClosingElementAt","jsxParseElementAt","children","openingElement","closingElement","contents","openingFragment","closingFragment","jsxParseElement","newContext","replaceToken","skipSpace","prevType","splice","TypeScriptScope","tsNames","TypeScriptScopeHandler","importsStack","hasImport","allowShadow","len","isConst","wasConst","ProductionParameterHandler","stacks","currentFlags","hasAwait","hasYield","hasReturn","hasIn","functionFlags","BaseParser","sawUnambiguousESM","ambiguousScriptDifferentAst","sourcePos","offsetPos","pluginConfig","pluginName","pluginOptions","actualOptions","plugin","_this$plugins$get","setTrailingComments","comments","trailingComments","unshift","setLeadingComments","leadingComments","setInnerComments","innerComments","adjustInnerComments","commentWS","lastElement","CommentsParser","commentsLen","processComment","commentStack","commentStackLength","lastCommentWS","leadingNode","commentEnd","containingNode","finalizeComment","trailingNode","_node$options","commentStart","finalizeRemainingComments","resetPreviousNodeTrailingComments","takeSurroundingComments","State","errors","potentialArrowAt","topicContext","maxNumOfResolvableTopics","maxTopicIndex","labels","ct","firstInvalidTemplateEscapePos","strictErrors","tokensLength","v","isAmbientContext","inAbstractClass","inDisallowConditionalTypesContext","soloAwait","inFSharpPipelineDirectBody","hasTopLevelAwait","forbiddenNumericSeparatorSiblings","decBinOct","hex","isAllowedNumericSeparatorSibling","bin","oct","dec","readStringContents","initialPos","initialLineStart","initialCurLine","firstInvalidLoc","unterminated","isStringEnd","res","readEscapedChar","str","containsInvalid","inTemplate","throwOnInvalid","readHexChar","readCodePoint","strictNumericEscape","octalStr","octal","parseInt","forceLen","n","invalidEscapeSequence","allowNumSeparator","bailOnError","forbiddenSiblings","isAllowedSibling","total","e","Infinity","prev","Number","isNaN","unexpectedNumericSeparator","numericSeparatorInEscapeSequence","_isDigit","invalidDigit","invalidCodePoint","buildPosition","VALID_REGEX_FLAGS","Token","Tokenizer","isLookahead","errorHandlers_readInt","errorBuilder","errorHandlers_readCodePoint","errorHandlers_readStringContents_string","recordStrictModeErrors","errorHandlers_readStringContents_template","pushToken","checkKeywordEscapes","createLookaheadState","old","curr","nextTokenStartSince","lastIndex","lookaheadCharCodeSince","nextTokenInLineStart","nextTokenInLineStartSince","lookaheadInLineCharCode","cp","trail","setStrict","toParseError","clear","skipLineComment","startSkip","spaceStart","loop","commentWhitespace","readToken_numberSign","readToken_interpreter","nextPos","expectPlugin","readToken_dot","readNumber","readToken_slash","width","readToken_caret","proposal","topicToken","codePointAt","readToken_atSign","readToken_plus_min","size","readToken_eq_excl","readToken_question","readTemplateToken","readRadixNumber","readString","readWord","readRegexp","escaped","content","mods","char","isBigInt","replace","startsWithDot","isFloat","hasExponent","isOctal","hasLeadingZero","integer","underscorePos","isDecimal","parseFloat","readTemplateContinuation","opening","firstCode","escStart","identifierCheck","esc","keywordTypes","raiseOverwrite","expectOnePlugin","pluginNames","some","ClassScope","privateNames","loneAccessors","undefinedPrivateNames","ClassScopeHandler","oldClassScope","from","declarePrivateName","redefined","accessor","oldStatic","newStatic","oldKind","newKind","ExpressionScope","canBeArrowParameterDeclaration","isCertainlyParameterDeclaration","ArrowHeadParsingScope","declarationErrors","recordDeclarationError","ParsingErrorClass","clearDeclarationError","iterateErrors","iterator","ExpressionScopeHandler","recordParameterInitializerError","origin","recordArrowParameterBindingError","recordAsyncArrowParametersError","validateAsPattern","newParameterDeclarationScope","newArrowHeadScope","newAsyncArrowScope","newExpressionScope","UtilParser","addExtra","isUnparsedContextual","nameStart","startsWith","hasPrecedingLineBreak","hasFollowingLineBreak","isLineTerminator","allowAsi","fn","oldState","abortSignal","checkExpressionErrors","andThrow","shorthandAssignLoc","doubleProtoLoc","privateKeyLoc","optionalParametersLoc","voidPatternLoc","hasErrors","isLiteralPropertyName","initializeScopes","oldLabels","oldExportedIdentifiers","exportedIdentifiers","oldInModule","oldScope","oldProdParam","prodParam","oldExpressionScope","expressionScope","enterInitialScopes","paramFlags","isCommonJS","scopeFlags","checkDestructuringPrivate","ExpressionErrors","Node","NodePrototype","__clone","NodeUtils","locationNode","unwrapParenthesizedExpression","LValParser","_node$extra3","last","_node$extra2","operator","arg","checkToRestConversion","elt","toAssignableListItem","element","toReferencedListDeep","parseSpread","parseRestBinding","parseBindingList","ParseBindingListFlags","parseObjectLike","parseVoidPattern","closeCharCode","allowEmpty","elts","checkCommaAfterRest","parseDecorator","parseBindingElement","parseBindingRestProperty","parseBindingProperty","parsePropertyName","checkLVal","checkClashes","hasParenthesizedAncestor","_expression$extra","checkIdentifier","validity","ParseErrorClass","isParenthesizedExpression","nextAncestor","child","declareNameFromIdentifier","identifier","allowPattern","nonNull","x","assert","TSErrors","AbstractMethodHasImplementation","methodName","AbstractPropertyHasInitializer","propertyName","AccessorCannotBeOptional","ClassMethodHasDeclare","ClassMethodHasReadonly","ConstructorHasTypeParameters","DeclareAccessor","DeclareClassFieldHasInitializer","DeclareFunctionHasImplementation","DuplicateAccessibilityModifier","modifier","DuplicateModifier","EmptyHeritageClauseType","EmptyTypeArguments","EmptyTypeParameters","ExpectedAmbientAfterExportDeclare","ImportAliasHasImportType","IncompatibleModifiers","modifiers","IndexSignatureHasAbstract","IndexSignatureHasAccessibility","IndexSignatureHasDeclare","IndexSignatureHasOverride","IndexSignatureHasStatic","InitializerNotAllowedInAmbientContext","InvalidHeritageClauseType","InvalidModifierOnAwaitUsingDeclaration","InvalidModifierOnTypeMember","InvalidModifierOnTypeParameter","InvalidModifierOnTypeParameterPositions","InvalidModifierOnUsingDeclaration","InvalidModifiersOrder","orderedModifiers","InvalidPropertyAccessAfterInstantiationExpression","InvalidTupleMemberLabel","MissingInterfaceName","NonAbstractClassHasAbstractMethod","NonClassMethodPropertyHasAbstractModifier","OptionalTypeBeforeRequired","OverrideNotInSubClass","PrivateElementHasAbstract","PrivateElementHasAccessibility","ReadonlyForMethodSignature","ReservedArrowTypeParam","ReservedTypeAssertion","SingleTypeParameterWithoutTrailingComma","typeParameterName","StaticBlockCannotHaveModifier","TupleOptionalAfterType","TypeAnnotationAfterAssign","TypeImportCannotSpecifyDefaultAndNamed","TypeModifierIsUsedInTypeExports","TypeModifierIsUsedInTypeImports","UnexpectedParameterModifier","UnexpectedReadonly","UnexpectedTypeAnnotation","UnexpectedTypeCastInParameter","UnsupportedImportTypeArgument","UnsupportedParameterPropertyKind","UnsupportedSignatureParameterKind","UsingDeclarationInAmbientContext","keywordTypeFromName","tsIsAccessModifier","tsIsVarianceAnnotations","typescript","tsParseInOutModifiers","tsParseModifiers","bind","allowedModifiers","disallowedModifiers","errorTemplate","tsParseConstModifier","tsParseInOutConstModifiers","tsIsIdentifier","tsTokenCanFollowModifier","tsNextTokenOnSameLineAndCanFollowModifier","tsNextTokenCanFollowModifier","tsParseModifier","stopOnStartOfClassStaticBlock","hasSeenStaticModifier","tsIsStartOfStaticBlocks","tsTryParse","modified","enforceOrder","before","after","incompatible","mod1","mod2","accessibility","hasOwnProperty","tsIsListTerminator","tsParseList","parseElement","tsParseDelimitedList","refTrailingCommaPos","tsParseDelimitedListWorker","expectSuccess","trailingCommaPos","tsParseBracketedList","bracket","skipFirstToken","tsParseImportType","tsParseImportTypeOptions","qualifier","tsParseEntityName","tsParseEntityNameFlags","tsParseTypeArguments","withProperty","tsParseImportTypeWithPropertyValue","parsePropertyDefinition","tsParseTypeReference","typeName","tsParseThisTypePredicate","lhs","parameterName","tsParseTypeAnnotation","asserts","tsParseThisTypeNode","tsParseTypeQuery","exprName","tsParseTypeParameter","parseModifiers","tsParseTypeParameterName","constraint","tsEatThenParseType","tsTryParseTypeParameters","tsParseTypeParameters","tsFillSignature","returnToken","signature","returnTokenRequired","paramsKey","returnTypeKey","tsParseBindingListForSignature","tsParseTypeOrTypePredicateAnnotation","tsParseTypeMemberSemicolon","tsParseSignatureMember","tsIsUnambiguouslyIndexSignature","tsTryParseIndexSignature","tsLookAhead","parameters","tsTryParseTypeAnnotation","tsParsePropertyOrMethodSignature","readonly","firstParameter","tsParseTypeMember","idx","tsParseTypeLiteral","tsParseObjectTypeMembers","tsIsStartOfMappedType","tsParseMappedType","tsExpectThenParseType","nameType","tsParseType","tsTryParseType","tsParseTupleType","elementTypes","tsParseTupleElementType","seenOptionalElement","elementNode","restStartLoc","labeled","chAfterWord","wordName","typeOrLabel","tsParseNonArrayType","labeledNode","optionalTypeNode","restNode","tsParseParenthesizedType","tsParseFunctionOrConstructorType","tsInAllowConditionalTypesContext","tsParseLiteralTypeNode","tsParseTemplateLiteralType","parseTemplate","parseTemplateSubstitution","tsParseThisTypeOrThisTypePredicate","thisKeyword","parseMaybeUnary","nodeType","tsParseArrayTypeOrHigher","tsParseTypeOperator","tsParseTypeOperatorOrHigher","tsCheckTypeAnnotationForReadOnly","tsParseInferType","tsParseConstraintForInferType","tsInDisallowConditionalTypesContext","tsParseUnionOrIntersectionType","parseConstituentType","hasLeadingOperator","tsParseIntersectionTypeOrHigher","tsParseUnionTypeOrHigher","tsIsStartOfFunctionType","tsIsUnambiguouslyStartOfFunctionType","tsSkipParameterStart","previousErrorCount","tsInType","t","tsParseTypePredicateAsserts","thisTypePredicate","typePredicateVariable","tsParseTypePredicatePrefix","tsTryParseTypeOrTypePredicateAnnotation","eatColon","tsParseNonConditionalType","checkType","extendsType","trueType","falseType","isAbstractConstructorSignature","tsParseTypeAssertion","tsParseHeritageClause","originalStartLoc","delimitedList","tsParseInterfaceDeclaration","tsParseTypeAliasDeclaration","tsInTopLevelContext","oldInDisallowConditionalTypesContext","tsNextThenParseType","tsParseEnumMember","initializer","tsParseEnumDeclaration","tsParseEnumBody","tsParseModuleBlock","parseBlockOrModuleBlockBody","tsParseModuleOrNamespaceDeclaration","nested","inner","tsParseAmbientExternalModuleDeclaration","global","tsParseImportEqualsDeclaration","maybeDefaultIdentifier","moduleReference","tsParseModuleReference","tsIsExternalModuleReference","tsParseExternalModuleReference","f","tsTryParseAndCatch","tsTryParseDeclare","startType","tsInAmbientContext","parseFunctionStatement","parseClass","parseVarStatement","isUsing","isAwaitUsing","tsParseDeclaration","tsTryParseExportDeclaration","tsParseExpressionStatement","mod","tsCheckLineTerminator","tsParseAbstractDeclaration","tsTryParseGenericAsyncArrowFunction","oldMaybeInArrowParameters","tsParseTypeArgumentsInExpression","tsIsDeclarationStart","override","pp","parameter","isSimpleParameter","tsDisallowOptionalPattern","bodilessType","registerFunctionStatementId","tsCheckForInvalidTypeCasts","items","isInParens","nonNullExpression","isOptionalCall","missingParenErrorLoc","atPossibleAsyncArrow","asyncArrowFn","parseTaggedTemplateExpression","tokenType","_callee$extra","parseExprOp","leftStartLoc","minPrec","isSatisfies","checkKeywords","checkDuplicateExports","importNode","parseMaybeImportPhase","parseImportSpecifiersAndAfter","nodeImportEquals","isAbstractClass","cls","allowMissingInitializer","declarations","isValidAmbientConstInitializer","parseStatementContent","parseAccessModifier","tsHasSomeModifiers","callParseClassMemberWithIsStatic","parseClassStaticBlock","parseClassMemberWithIsStatic","hadSuperClass","parsePostMemberNameModifiers","methodOrProp","isDeclare","parseClassPropertyAnnotation","definite","declareClassPrivateMethodInScope","_typeCast","_typeCast2","typeCast","_typeParameters","reportReservedArrowTypeParam","trailingComma","sawUnary","toAssignableParenthesizedExpression","parseMaybeDecoratorArguments","canHaveLeadingDecorator","getGetterSetterExpectedParamCount","baseCount","firstParam","parseCatchClauseParam","oldIsAmbientContext","oldStrict","oldInAbstractClass","maybeTakeDecorators","shouldParseAsAmbientContext","getExpression","parseExportSpecifier","isString","isInTypeExport","parseTypeOnlyImportExportSpecifier","isImport","isInTypeOnlyImportExport","leftOfAsKey","rightOfAsKey","leftOfAs","rightOfAs","hasTypeSpecifier","canParseAsKeyword","firstAs","secondAs","parseModuleExportName","kindKey","_node$directive","_node$decorators","_node$optional","_node$typeAnnotation","_node$accessibility","_node$decorators2","_node$override","_node$readonly","_node$static","_node$declare","_node$returnType","_node$typeParameters","_node$optional2","_node$optional3","_node$accessibility2","_node$readonly2","_node$static2","_node$declare2","_node$definite","_node$readonly3","_node$typeAnnotation2","_node$accessibility3","_node$decorators3","_node$override2","_node$optional4","_node$id","_node$abstract","_node$declare3","_node$decorators4","_node$implements","_node$superTypeArgume","_node$typeParameters2","_node$declare4","_node$definite2","_node$const","_node$declare5","_node$computed","_node$qualifier","_node$declare6","_node$extends","_node$declare7","_node$global","_node$const2","_node$in","_node$out","superTypeArguments","in","isPossiblyLiteralEnum","expressions","isUncomputedMemberExpressionChain","isNumber","isNegativeNumber","PlaceholderErrors","ClassNameIsRequired","UnexpectedSpace","placeholders","parsePlaceholder","expectedNode","assertNoSpace","finishPlaceholder","chStartsBindingIdentifier","verifyBreakContinue","isBreak","parseStatementOrSloppyAnnexBFunctionDeclaration","stmtPlaceholder","parseBlock","createNewLexicalScope","parseFunctionId","requireId","parseClassBody","maybeParseExportDefaultSpecifier","_specifiers","checkExport","filter","maybeParseStarImportSpecifier","parseNamedImportSpecifiers","parseImportSource","v8intrinsic","parseV8Intrinsic","v8IntrinsicStartLoc","parseIdentifierName","PIPELINE_PROPOSALS","TOPIC_TOKENS","validatePlugins","pluginsMap","decoratorsBeforeExport","allowCallParenthesized","_pluginsMap$get2","proposalList","p","tokenList","_pluginsMap$get","syntaxType","version","deprecatedAssertSyntax","RECORD_AND_TUPLE_SYNTAX_TYPES","missingPlugins","mixinPlugins","mixinPluginNames","ExpressionParser","checkProto","isRecord","sawProto","shouldExitDescending","disallowIn","disallowInAnd","parseExpressionBase","allowInAnd","parseMaybeAssignDisallowIn","isYield","parseYield","ownExpressionErrors","parseMaybeConditional","isAmbiguousPrefixOrIdentifier","parseExprOps","parseMaybeUnaryOrPrivate","op","prec","checkPipelineAtInfixOperator","logical","coalesce","parseExprOpRightExpr","finishedNode","nextOp","withTopicBindingContext","parseHackPipeBody","withSoloAwaitPermittingContext","parseFSharpPipelineBody","parseSmartPipelineBodyInStyle","parseExprOpBaseRightExpr","_body$extra","topicReferenceWasUsedInCurrentContext","checkExponentialAfterUnary","isAwait","recordAwaitIfAllowed","parseAwait","update","isDelete","parseUpdate","updateExpressionNode","parseExprSubscripts","maybeAsyncArrow","parseBind","parseCoverCallAndAsyncArrowHead","parseNoCallExpr","tag","quasi","allowPlaceholder","nodeForExtra","oldInFSharpPipelineDirectBody","addTrailingCommaExtraToNode","parseExprListItem","_call$extra","parseSuper","parseImportMetaPropertyOrPhaseCall","parseImportCall","parseDo","parseFunctionOrFunctionSent","parseDecorators","parseNewOrNewTarget","parseTopicReferenceThenEqualsSign","parseTopicReference","pipeProposal","lookaheadCh","parseModuleExpression","parseAsyncFunctionExpression","parseAsyncArrowUnaryFunction","topicTokenType","topicTokenValue","finishTopicReference","testTopicReferenceConfiguration","topicReferenceIsAllowedInCurrentContext","registerTopicReference","meta","parseMetaProperty","parseFunction","isSource","createIdentifierAt","innerStartLoc","spreadStartLoc","optionalCommaStartLoc","spreadNodeStartLoc","parseMaybeAssignAllowInOrVoidPattern","innerEndLoc","arrowNode","wrapParenthesis","parenExpression","metaProp","parseNew","parseExprList","parseTemplateElement","isTagged","elemStart","elem","isTail","endOffset","elemEnd","cooked","tail","curElt","quasis","substitutions","maybeAsyncOrAccessorProp","keyName","_params","parseObjectMethod","finishedProp","generator","isExpression","hasStrictModeDirective","nonSimple","isSimpleParamList","formalParameters","isAwaitAllowed","delegating","delegate","childExpr","isSimpleReference","checkSmartPipeTopicBodyEarlyErrors","callback","outerContextTopicState","withSmartMixTopicForbiddingContext","outerContextSoloAwaitState","ParamKind","ret","revertScopes","parseProgram","nextCode","loopLabel","switchLabel","loneSurrogate","keywordRelationalOperator","babel7CompatTokens","hashEndPos","hashEndLoc","backquoteEnd","backquoteEndLoc","startToken","templateValue","templateElementEnd","templateElementEndLoc","endToken","StatementParser","interpreter","parseInterpreterDirective","finishedProgram","stmtToDirective","directiveLiteral","hasFollowingBindingAtom","isForUsing","nextCharAfterOf","endCh","chStartsBindingPattern","hasInLineFollowingBindingIdentifierOrBrace","allowsUsing","parseModuleItem","ParseStatementFlag","parseStatementListItem","allowLabeledFunction","parseStatement","allowDeclaration","allowFunctionDeclaration","parseBreakContinueStatement","parseDebuggerStatement","parseDoWhileStatement","parseForStatement","parseIfStatement","parseReturnStatement","parseSwitchStatement","parseThrowStatement","parseTryStatement","parseWhileStatement","parseWithStatement","parseEmptyStatement","nextTokenCharCode","isAsyncFunction","maybeName","parseLabeledStatement","decoratorsEnabledBeforeExport","maybeDecorators","classNode","exportNode","_classNode$decorators","allowExport","paramsStartLoc","lab","parseHeaderExpression","awaitAt","parseFor","startsWithLet","startsWithAwaitUsing","starsWithUsingDeclaration","isLetOrUsing","initNode","parseVar","isForIn","parseForIn","startsWithAsync","isForOf","isHangingDeclaration","ParseFunctionFlag","discriminant","cases","cur","sawDefault","isCase","block","handler","clause","finalizer","statementStart","parsedNonDirective","await","isFor","hangingDeclaration","isDeclaration","hadConstructor","publicMethod","privateMethod","publicProp","privateProp","accessorProp","publicMember","parseClassElementName","maybeContextualKw","isPrivate","maybeQuestionTokenStartLoc","pushClassPrivateProperty","pushClassProperty","pushClassAccessorProperty","_member$decorators","parseInitializer","hasDefault","parseAfterDefault","hasStar","parseAfterNamespace","isFromRequired","hasSpecifiers","maybeParseExportNamedSpecifiers","hasDeclaration","maybeParseExportDeclaration","_node2$declaration","_ref$specifiers","isTypeExport","assertions","nextChar","hasFrom","nextAfterFrom","maybeParseImportAttributes","checkJSONModuleImport","checkNames","isDefault","isFrom","_node$specifiers","_declaration$extra","nodes","surrogate","isJSONModuleImport","singleBindingType","_node$assertions","nonDefaultNamedSpecifier","find","phaseIdentifier","phaseIdentifierName","isPrecedingIdImportPhase","parseImportSourceAndAttributes","parseNext","maybeParseDefaultImportSpecifier","_node$specifiers2","parseImportAttributes","attrs","attrNames","parseModuleAttributes","useWith","importSpecifier","Parser","_options","getParser","ast","moduleError","generateExportedTokenTypes","internalTokenTypes","tokTypes","getParserClass","parserClassCache","pluginList","require_estree_walker","__commonJSMin","exports","module","global","factory","WalkerBase","node","parent","prop","index","SyncWalker","enter","leave","_should_skip","_should_remove","_replacement","skipped","removed","key","value","i","AsyncWalker","walk","ast","asyncWalk","require_base64","__commonJSMin","exports","intToCharMap","number","charCode","bigA","bigZ","littleA","littleZ","zero","nine","plus","slash","littleOffset","numberOffset","require_base64_vlq","__commonJSMin","exports","base64","VLQ_BASE_SHIFT","VLQ_BASE","VLQ_BASE_MASK","VLQ_CONTINUATION_BIT","toVLQSigned","aValue","fromVLQSigned","isNegative","shifted","encoded","digit","vlq","aStr","aIndex","aOutParam","strLen","result","shift","continuation","require_util","__commonJSMin","exports","getArg","aArgs","aName","aDefaultValue","urlRegexp","dataUrlRegexp","urlParse","aUrl","match","urlGenerate","aParsedUrl","url","MAX_CACHED_INPUTS","lruMemoize","f","cache","input","i","temp","result","normalize","aPath","path","isAbsolute","parts","start","part","up","join","aRoot","aPathUrl","aRootUrl","joined","relative","level","index","supportsNullProto","obj","identity","s","toSetString","aStr","isProtoString","fromSetString","length","compareByOriginalPositions","mappingA","mappingB","onlyCompareOriginal","cmp","strcmp","compareByOriginalPositionsNoSource","compareByGeneratedPositionsDeflated","onlyCompareGenerated","compareByGeneratedPositionsDeflatedNoLine","aStr1","aStr2","compareByGeneratedPositionsInflated","parseSourceMapInput","str","computeSourceURL","sourceRoot","sourceURL","sourceMapURL","parsed","require_array_set","__commonJSMin","exports","util","has","hasNativeMap","ArraySet","aArray","aAllowDuplicates","set","i","len","aStr","sStr","isDuplicate","idx","aIdx","require_mapping_list","__commonJSMin","exports","util","generatedPositionAfter","mappingA","mappingB","lineA","lineB","columnA","columnB","MappingList","aCallback","aThisArg","aMapping","require_source_map_generator","__commonJSMin","exports","base64VLQ","util","ArraySet","MappingList","SourceMapGenerator","aArgs","aSourceMapConsumer","generatorOps","sourceRoot","generator","mapping","newMapping","sourceFile","sourceRelative","content","generated","original","source","name","aSourceFile","aSourceContent","aSourceMapPath","newSources","newNames","aGenerated","aOriginal","aSource","aName","message","previousGeneratedColumn","previousGeneratedLine","previousOriginalColumn","previousOriginalLine","previousName","previousSource","result","next","nameIdx","sourceIdx","mappings","i","len","aSources","aSourceRoot","key","map","require_binary_search","__commonJSMin","exports","recursiveSearch","aLow","aHigh","aNeedle","aHaystack","aCompare","aBias","mid","cmp","index","require_quick_sort","__commonJSMin","exports","SortTemplate","comparator","swap","ary","x","y","temp","randomIntInRange","low","high","doQuickSort","p","r","pivotIndex","i","pivot","j","q","cloneSort","template","sortCache","start","require_source_map_consumer","__commonJSMin","exports","util","binarySearch","ArraySet","base64VLQ","quickSort","SourceMapConsumer","aSourceMap","aSourceMapURL","sourceMap","IndexedSourceMapConsumer","BasicSourceMapConsumer","aStr","index","c","aSourceRoot","aCallback","aContext","aOrder","context","order","mappings","sourceRoot","boundCallback","names","sources","sourceMapURL","i","n","mapping","source","aArgs","line","needle","originalLine","originalColumn","version","sourcesContent","file","s","aSource","relativeSource","smc","generatedMappings","destGeneratedMappings","destOriginalMappings","length","srcMapping","destMapping","Mapping","compareGenerated","sortGenerated","array","start","l","b","j","a","generatedLine","previousGeneratedColumn","previousOriginalLine","previousOriginalColumn","previousSource","previousName","cachedSegments","temp","originalMappings","str","segment","end","value","subarrayStart","currentSource","aNeedle","aMappings","aLineName","aColumnName","aComparator","aBias","nextMapping","name","sc","nullOnMissing","url","fileUriAbsPath","sections","lastOffset","offset","offsetLine","offsetColumn","sectionIndex","section","cmp","content","generatedPosition","ret","sectionMappings","adjustedMapping","require_source_node","__commonJSMin","exports","SourceMapGenerator","util","REGEX_NEWLINE","NEWLINE_CODE","isSourceNode","SourceNode","aLine","aColumn","aSource","aChunks","aName","aGeneratedCode","aSourceMapConsumer","aRelativePath","node","remainingLines","remainingLinesIndex","shiftNextLine","lineContents","getNextLine","newLine","lastGeneratedLine","lastGeneratedColumn","lastMapping","mapping","addMappingWithCode","nextLine","code","sourceFile","content","source","aChunk","chunk","i","aFn","len","aSep","newChildren","aPattern","aReplacement","lastChild","aSourceFile","aSourceContent","sources","str","aArgs","generated","map","sourceMappingActive","lastOriginalSource","lastOriginalLine","lastOriginalColumn","lastOriginalName","original","idx","length","sourceContent","require_source_map","__commonJSMin","exports","require_compiler_core_cjs_prod","__commonJSMin","exports","shared","decode_js","parser","estreeWalker","sourceMapJs","FRAGMENT","TELEPORT","SUSPENSE","KEEP_ALIVE","BASE_TRANSITION","OPEN_BLOCK","CREATE_BLOCK","CREATE_ELEMENT_BLOCK","CREATE_VNODE","CREATE_ELEMENT_VNODE","CREATE_COMMENT","CREATE_TEXT","CREATE_STATIC","RESOLVE_COMPONENT","RESOLVE_DYNAMIC_COMPONENT","RESOLVE_DIRECTIVE","RESOLVE_FILTER","WITH_DIRECTIVES","RENDER_LIST","RENDER_SLOT","CREATE_SLOTS","TO_DISPLAY_STRING","MERGE_PROPS","NORMALIZE_CLASS","NORMALIZE_STYLE","NORMALIZE_PROPS","GUARD_REACTIVE_PROPS","TO_HANDLERS","CAMELIZE","CAPITALIZE","TO_HANDLER_KEY","SET_BLOCK_TRACKING","PUSH_SCOPE_ID","POP_SCOPE_ID","WITH_CTX","UNREF","IS_REF","WITH_MEMO","IS_MEMO_SAME","helperNameMap","registerRuntimeHelpers","helpers","s","Namespaces","NodeTypes","ElementTypes","ConstantTypes","locStub","createRoot","children","source","createVNodeCall","context","tag","props","patchFlag","dynamicProps","directives","isBlock","disableTracking","isComponent","loc","getVNodeBlockHelper","getVNodeHelper","createArrayExpression","elements","createObjectExpression","properties","createObjectProperty","key","value","createSimpleExpression","content","isStatic","constType","createInterpolation","createCompoundExpression","createCallExpression","callee","args","createFunctionExpression","params","returns","newline","isSlot","createConditionalExpression","test","consequent","alternate","createCacheExpression","index","needPauseTracking","inVOnce","createBlockStatement","body","createTemplateLiteral","createIfStatement","createAssignmentExpression","left","right","createSequenceExpression","expressions","createReturnStatement","ssr","convertToBlock","node","helper","removeHelper","inSSR","defaultDelimitersOpen","defaultDelimitersClose","isTagStartChar","c","isWhitespace","isEndOfTagSection","toCharCodes","str","ret","i","Sequences","Tokenizer","stack","cbs","cp","consumed","line","column","newlineIndex","start","isEnd","endOfText","actualIndex","cc","sequence","offset","quote","length","input","endIndex","CompilerDeprecationTypes","deprecationData","getCompatValue","compatConfig","isCompatEnabled","mode","checkCompatEnabled","warnDeprecation","message","link","msg","err","defaultOnError","error","defaultOnWarn","createCompilerError","code","messages","additionalMessage","errorMessages","ErrorCodes","walkIdentifiers","root","onIdentifier","includeAll","parentStack","knownIds","rootExp","parent","TS_NODE_TYPES","isLocal","isRefed","isReferencedIdentifier","isFunctionType","id","markKnownIds","walkFunctionParams","markScopeIdentifier","walkBlockDeclarations","extractIdentifiers","isForStatement","walkForStatement","isReferenced","isInDestructureAssignment","p","isInNewExpression","onIdent","block","stmt","decl","isVar","variable","param","nodes","object","prop","element","name","child","isStaticProperty","isStaticPropertyKey","grandparent","unwrapTSNode","isStaticExp","isCoreComponent","nonIdentifierRE","isSimpleIdentifier","validFirstIdentCharRE","validIdentCharRE","whitespaceRE","getExpSource","exp","isMemberExpressionBrowser","path","state","stateStack","currentOpenBracketCount","currentOpenParensCount","currentStringType","char","isMemberExpressionNode","isMemberExpression","fnExpRE","isFnExpressionBrowser","isFnExpressionNode","isFnExpression","advancePositionWithClone","pos","numberOfCharacters","advancePositionWithMutation","linesCount","lastNewLinePos","assert","condition","findDir","allowEmpty","findProp","dynamicOnly","isStaticArgOf","arg","hasDynamicKeyVBind","isText$1","isVPre","isVSlot","isTemplateNode","isSlotOutlet","propsHelperSet","getUnnormalizedProps","callPath","injectProp","propsWithInjection","parentCall","first","hasProp","result","propKeyName","toValidAssetId","type","searchValue","replaceValue","hasScopeRef","ids","b","getMemoedVNodeCall","forAliasRE","defaultParserOptions","currentOptions","currentRoot","currentInput","currentOpenTag","currentProp","currentAttrValue","currentAttrStartIndex","currentAttrEndIndex","inPre","inVPre","currentVPreBoundary","tokenizer","emitError","end","onText","getSlice","innerStart","innerEnd","addNode","createExp","getLoc","endOpenTag","found","j","el","onCloseTag","backTrack","raw","dirToAttr","setLocEnd","mod","condense","expParseMode","parseForExpression","syncIndex","forIteratorRE","stripParensRE","inMatch","LHS","RHS","createAliasExpression","asParam","valueContent","trimmedOffset","iteratorMatch","keyContent","keyOffset","indexContent","ns","lastNode","isImplied","lookAhead","isFragmentTemplate","condenseWhitespace","inlineTemplateProp","specialTemplateDir","isUpperCase","windowsNewlineRE","shouldCondense","removedWhitespace","isAllWhitespace","prev","next","hasNewlineChar","prevCharIsWhitespace","cloneLoc","dir","attr","parseMode","plugins","options","e","reset","baseParse","delimiters","cacheStatic","walk","getSingleElementRoot","x","doNotHoistNode","inFor","toCache","constantType","getConstantType","codegenNode","flag","getGeneratedPropsConstantType","getNodeProps","i2","cachedAsArray","slotCacheKeys","getCacheExpression","slot","getSlotNode","slotName","node2","constantCache","cached","returnType2","generatedPropsType","childType","expType","returnType","allowHoistedHelperSet","getConstantTypeOfHelperCall","keyType","valueType","createTransformContext","filename","prefixIdentifiers","hoistStatic","hmr","cacheHandlers","nodeTransforms","directiveTransforms","transformHoist","isBuiltInComponent","isCustomElement","expressionPlugins","scopeId","slotted","ssrCssVars","bindingMetadata","inline","isTS","onError","onWarn","nameMatch","count","currentCount","list","removalIndex","addId","removeId","identifier","isVNode","cacheExp","identifiers","transform","traverseNode","createRootCodegen","singleElementRootChild","traverseChildren","nodeRemoved","exitFns","onExit","createStructuralDirectiveTransform","fn","matches","PURE_ANNOTATION","aliasHelper","createCodegenContext","ast","sourceMap","optimizeImports","runtimeGlobalName","runtimeModuleName","ssrRuntimeModuleName","addMapping","withoutNewLine","n","_names","_mappings","generate","push","indent","deindent","hasHelpers","useWithBlock","genScopeId","isSetupInlined","preambleContext","genModulePreamble","genFunctionPreamble","functionName","signature","genAssets","genNode","VueBinding","staticHelpers","genHoists","genImports","assets","resolver","maybeSelfReference","hoists","importsOptions","imports","isText","genNodeListAsArray","multilines","genNodeList","comma","genText","genExpression","genInterpolation","genCompoundExpression","genComment","genVNodeCall","genCallExpression","genObjectExpression","genArrayExpression","genFunctionExpression","genConditionalExpression","genCacheExpression","genTemplateLiteral","genIfStatement","genAssignmentExpression","genSequenceExpression","genReturnStatement","pure","genExpressionAsPropertyKey","text","patchFlagString","callHelper","genNullableArgs","needNewline","needsParens","isNested","needArraySpread","l","isLiteralWhitelisted","transformExpression","processExpression","memo","asParams","asRawStatements","localVars","rewriteIdentifier","isAssignmentLVal","isUpdateArg","isDestructureAssignment","isNewExpression","wrapWithUnref","raw2","wrapped","isConst","rVal","operator","rExp","rawExp","rExpString","stringifyExpression","isPrefix","prefix","postfix","isScopeVarReference","isAllowedGlobal","isLiteral","_","needPrefix","canPrefix","a","last","leadingText","transformIf","processIf","ifNode","branch","isRoot","siblings","sibling","createCodegenNodeForBranch","parentCondition","getParentCondition","processCodegen","createIfBranch","userKey","isSameKey","isTemplateIf","keyIndex","createChildrenCodegenNode","keyProperty","firstChild","vnodeCall","branchExp","transformBind","_node","modifiers","transformBindShorthand","injectPrefix","propName","transformFor","processFor","forNode","renderExp","isTemplate","keyProp","isDirKey","keyExp","isStableFragment","fragmentFlag","childBlock","needFragmentWrapper","slotOutlet","loop","createForLoopParams","parseResult","finalizeForParseResult","addIdentifiers","removeIdentifiers","scopes","memoArgs","createParamsList","defaultFallback","trackSlotScopes","vSlot","slotProps","trackVForSlotScopes","vFor","buildClientSlotFn","_vForExp","buildSlots","buildSlotFn","slotsProperties","dynamicSlots","hasDynamicSlots","onComponentSlot","hasTemplateSlots","hasNamedDefaultSlot","implicitDefaultChildren","seenSlotNames","conditionalBranchIndex","slotElement","slotDir","slotChildren","slotLoc","dirLoc","staticSlotName","slotFunction","vIf","vElse","buildDynamicSlot","isNonWhitespaceContent","conditional","buildDefaultSlotProperty","children2","slotFlag","hasForwardedSlots","slots","directiveImportMap","transformElement","vnodeTag","resolveComponentType","isDynamicComponent","vnodeProps","vnodeChildren","vnodeDynamicProps","dynamicPropNames","vnodeDirectives","shouldUseBlock","propsBuildResult","buildProps","buildDirectiveArgs","hasDynamicTextChild","stringifyDynamicPropNames","isExplicitDynamic","isComponentTag","isProp","builtIn","fromSetup","resolveSetupReference","dotIndex","bindings","camelName","PascalName","checkType","fromConst","fromMaybeRef","fromProps","elementLoc","mergeArgs","runtimeDirectives","hasChildren","hasRef","hasClassBinding","hasStyleBinding","hasHydrationEventBinding","hasDynamicKeys","hasVnodeHook","pushMergeArg","dedupeProperties","pushRefVForMarker","analyzePatchFlag","isEventHandler","nameLoc","binding","isVBind","isVOn","directiveTransform","props2","needRuntime","propsExpression","classKeyIndex","styleKeyIndex","hasDynamicKey","classProp","styleProp","knownProps","deduped","existing","mergeAsArray","incoming","dirArgs","runtime","trueExpression","modifier","propsNamesString","transformSlotOutlet","processSlotOutlet","slotArgs","expectedLen","nonNameProps","transformOn","augmentor","eventName","rawName","eventString","shouldCache","isMemberExp","isInlineStatement","hasMultipleStatements","transformText","currentContainer","hasText","callArgs","seen$1","transformOnce","cur","transformModel","createTransformProps","expString","bindingType","maybeRef","assignmentExp","eventArg","altAssignment","m","modifiersKey","validDivisionCharRE","transformFilter","rewriteFilter","parseFilter","inSingle","inDouble","inTemplateString","inRegex","curly","square","paren","lastFilterIndex","expression","filters","pushFilter","wrapFilter","filter","seen","transformMemo","getBaseTransformPreset","baseCompile","isModuleMode","resolvedOptions","BindingTypes","noopDirectiveTransform","require_compiler_core","__commonJSMin","exports","module","require_compiler_dom_cjs_prod","__commonJSMin","exports","compilerCore","shared","V_MODEL_RADIO","V_MODEL_CHECKBOX","V_MODEL_TEXT","V_MODEL_SELECT","V_MODEL_DYNAMIC","V_ON_WITH_MODIFIERS","V_ON_WITH_KEYS","V_SHOW","TRANSITION","TRANSITION_GROUP","parserOptions","tag","parent","rootNamespace","ns","transformStyle","node","p","i","parseInlineCSS","cssText","loc","normalized","createDOMCompilerError","code","DOMErrorMessages","DOMErrorCodes","transformVHtml","dir","context","exp","transformVText","transformModel","baseResult","isCustomElement","directiveToUse","isInvalidType","type","isEventOptionModifier","isNonKeyModifier","maybeKeyModifier","isKeyboardEvent","resolveModifiers","key","modifiers","keyModifiers","nonKeyModifiers","eventOptionModifiers","modifier","transformClick","event","transformOn","handlerExp","modifierPostfix","transformShow","expReplaceRE","stringifyStatic","children","isParentCached","nc","ec","currentChunk","stringifyCurrentChunk","currentIndex","staticCall","stringifyNode","deleteCount","cacheIndex","i2","c","child","getCachedNode","result","analyzeNode","dataAriaRE","isStringifiableAttr","name","isNonStringifiable","bailed","bail","walk","node2","isOptionTag","stringifyElement","evaluateConstant","res","innerHTML","evaluated","arg","ignoreSideEffectTags","DOMNodeTransforms","DOMDirectiveTransforms","compile","src","options","parse","template","k","require_compiler_dom","__commonJSMin","exports","module","require_reactivity_cjs_prod","__commonJSMin","exports","shared","activeEffectScope","EffectScope","detached","i","l","fn","currentEffectScope","fromParent","last","effectScope","getCurrentScope","onScopeDispose","failSilently","activeSub","EffectFlags","pausedQueueEffects","ReactiveEffect","batch","cleanupEffect","prepareDeps","prevEffect","prevShouldTrack","shouldTrack","cleanupDeps","link","removeSub","isDirty","batchDepth","batchedSub","batchedComputed","sub","isComputed","startBatch","endBatch","e","next","error","err","head","tail","prev","removeDep","refreshComputed","computed","globalVersion","dep","prevSub","value","soft","nextSub","prevDep","nextDep","effect","options","runner","stop","trackStack","pauseTracking","enableTracking","resetTracking","onEffectCleanup","cleanup","Link","Dep","debugInfo","addSub","currentTail","targetMap","ITERATE_KEY","MAP_KEY_ITERATE_KEY","ARRAY_ITERATE_KEY","track","target","type","key","depsMap","trigger","newValue","oldValue","oldTarget","run","targetIsArray","isArrayIndex","newLength","key2","getDepFromReactive","object","depMap","reactiveReadArray","array","raw","toRaw","isShallow","toReactive","shallowReadArray","arr","arrayInstrumentations","iterator","args","x","thisArg","apply","v","searchProxy","separator","noTracking","reduce","comparer","self","method","wrapValue","iter","result","arrayProto","wrappedRetFn","needsWrap","methodFn","result2","wrappedFn","item","index","acc","res","isProxy","isNonTrackableKeys","builtInSymbols","hasOwnProperty","obj","BaseReactiveHandler","_isReadonly","_isShallow","receiver","isReadonly2","isShallow2","shallowReadonlyMap","readonlyMap","shallowReactiveMap","reactiveMap","isRef","readonly","reactive","MutableReactiveHandler","isOldValueReadonly","isReadonly","hadKey","ReadonlyReactiveHandler","mutableHandlers","readonlyHandlers","shallowReactiveHandlers","shallowReadonlyHandlers","toShallow","getProto","createIterableMethod","rawTarget","targetIsMap","isPair","isKeyOnly","innerIterator","wrap","toReadonly","done","createReadonlyMethod","createInstrumentations","shallow","instrumentations","rawKey","has","callback","observed","get","hadItems","createInstrumentationGetter","mutableCollectionHandlers","shallowCollectionHandlers","readonlyCollectionHandlers","shallowReadonlyCollectionHandlers","targetTypeMap","rawType","getTargetType","createReactiveObject","shallowReactive","shallowReadonly","baseHandlers","collectionHandlers","proxyMap","targetType","existingProxy","proxy","isReactive","markRaw","r","ref","createRef","shallowRef","rawValue","RefImpl","useDirectValue","triggerRef","ref2","unref","toValue","source","shallowUnwrapHandlers","proxyRefs","objectWithRefs","CustomRefImpl","factory","set","newVal","customRef","toRefs","ret","propertyToRef","ObjectRefImpl","_object","_key","_defaultValue","val","GetterRefImpl","_getter","toRef","defaultValue","ComputedRefImpl","setter","isSSR","getterOrOptions","debugOptions","getter","TrackOpTypes","TriggerOpTypes","ReactiveFlags","WatchErrorCodes","INITIAL_WATCHER_VALUE","cleanupMap","activeWatcher","getCurrentWatcher","onWatcherCleanup","cleanupFn","owner","cleanups","watch","cb","immediate","deep","once","scheduler","augmentJob","call","reactiveGetter","source2","traverse","boundCleanup","forceTrigger","isMultiSource","s","currentEffect","baseGetter","depth","scope","watchHandle","_cb","job","immediateFirstRun","currentWatcher","cleanup2","seen","require_reactivity","__commonJSMin","exports","module","require_runtime_core_cjs_prod","__commonJSMin","exports","reactivity","shared","pushWarningContext","vnode","popWarningContext","assertNumber","val","type","ErrorCodes","ErrorTypeStrings$1","callWithErrorHandling","fn","instance","args","err","handleError","callWithAsyncErrorHandling","res","values","i","throwInDev","contextVNode","errorHandler","throwUnhandledErrorInProduction","cur","exposedInstance","errorInfo","errorCapturedHooks","logError","throwInProd","queue","flushIndex","pendingPostFlushCbs","activePostFlushCbs","postFlushIndex","resolvedPromise","currentFlushPromise","nextTick","p","findInsertionIndex","id","start","end","middle","middleJob","middleJobId","getId","queueJob","job","jobId","lastJob","queueFlush","flushJobs","queuePostFlushCb","cb","flushPreFlushCbs","seen","flushPostFlushCbs","deduped","a","b","currentRenderingInstance","currentScopeId","setCurrentRenderingInstance","prev","pushScopeId","popScopeId","withScopeId","_id","withCtx","ctx","isNonScopedSlot","renderFnWithContext","setBlockTracking","prevInstance","withDirectives","directives","getComponentPublicInstance","bindings","dir","value","arg","modifiers","invokeDirectiveHook","prevVNode","name","oldBindings","binding","hook","TeleportEndKey","isTeleport","isTeleportDisabled","props","isTeleportDeferred","isTargetSVG","target","isTargetMathML","resolveTarget","select","targetSelector","TeleportImpl","n1","n2","container","anchor","parentComponent","parentSuspense","namespace","slotScopeIds","optimized","internals","mountChildren","patchChildren","patchBlockChildren","insert","querySelector","createText","createComment","disabled","shapeFlag","children","dynamicChildren","placeholder","mainAnchor","mount","container2","anchor2","mountToTarget","targetAnchor","prepareAnchor","updateCssVars","queuePostRenderEffect","wasDisabled","currentContainer","currentAnchor","traverseStaticChildren","moveTeleport","nextTarget","unmount","hostRemove","doRemove","targetStart","shouldRemove","child","hydrateTeleport","parentAnchor","move","moveType","el","isReorder","node","nextSibling","parentNode","hydrateChildren","targetNode","Teleport","isDisabled","leaveCbKey","enterCbKey","useTransitionState","state","onMounted","onBeforeUnmount","TransitionHookValidator","BaseTransitionPropsValidators","recursiveGetSubtree","subTree","BaseTransitionImpl","slots","getCurrentInstance","getTransitionRawChildren","findNonCommentChild","rawProps","mode","emptyPlaceholder","innerChild","getInnerChild$1","enterHooks","resolveTransitionHooks","hooks","Comment","setTransitionHooks","oldInnerChild","isSameVNodeType","leavingHooks","earlyRemove","delayedLeave","leavingVNodesCache","getLeavingNodesForType","c","BaseTransition","leavingVNodes","postClone","appear","persisted","onBeforeEnter","onEnter","onAfterEnter","onEnterCancelled","onBeforeLeave","onLeave","onAfterLeave","onLeaveCancelled","onBeforeAppear","onAppear","onAfterAppear","onAppearCancelled","key","callHook","callAsyncHook","done","hook2","leavingVNode","afterHook","cancelHook","called","cancelled","remove","key2","vnode2","hooks2","isKeepAlive","cloneVNode","keepComment","parentKey","ret","keyedFragmentCount","Fragment","defineComponent","options","extraOptions","useId","markAsyncBoundary","useTemplateRef","refs","setRef","rawRef","oldRawRef","isUnmount","r","isAsyncWrapper","refValue","owner","ref","oldRef","setupState","rawSetupState","canSetSetupRef","_isString","_isRef","doSet","existing","hasLoggedMismatchError","logMismatchError","isSVGContainer","isMathMLContainer","getContainerType","isComment","createHydrationFunctions","rendererInternals","mountComponent","patch","patchProp","hydrate","hydrateNode","isFragmentStart","onMismatch","handleMismatch","patchFlag","domType","nextNode","Text","isTemplateNode","replaceNode","Static","needToAdoptContent","hydrateFragment","hydrateElement","locateClosingAnchor","createVNode","createTextVNode","dirs","transition","forcePatch","needCallTransitionHooks","needTransition","content","cls","next","isMismatchAllowed","clientText","isCustomElement","vnodeHooks","invokeVNodeHook","queueEffectWithSuspense","parentVNode","l","normalizeVNode","isText","fragmentSlotScopeIds","isFragment","next2","updateHOCHostEl","open","close","match","newNode","oldNode","parentNode2","parent","allowMismatchAttr","MismatchTypeString","allowedType","allowedAttr","list","requestIdleCallback","cancelIdleCallback","hydrateOnIdle","timeout","elementIsVisibleInViewport","top","left","bottom","right","innerHeight","innerWidth","hydrateOnVisible","opts","forEach","ob","entries","e","hydrateOnMediaQuery","query","mql","hydrateOnInteraction","interactions","hasHydrated","doHydrate","teardown","forEachElement","depth","defineAsyncComponent","source","loader","loadingComponent","errorComponent","delay","hydrateStrategy","suspensible","userOnError","pendingRequest","resolvedComp","retries","retry","load","thisRequest","resolve","reject","comp","patched","performHydrate","currentInstance","createInnerComp","onError","isInSSRComponentSetup","loaded","error","delayed","ref2","ce","KeepAliveImpl","sharedContext","cache","keys","current","_unmount","createElement","storageContainer","instance2","vnodeHook","invalidateMount","resetShapeFlag","pruneCache","filter","getComponentName","pruneCacheEntry","cached","watch","include","exclude","matches","pendingCacheKey","cacheSubtree","isSuspense","getInnerChild","onUpdated","suspense","da","rawVNode","isVNode","max","cachedVNode","KeepAlive","pattern","onActivated","registerKeepAliveHook","onDeactivated","wrappedHook","injectHook","injectToKeepAliveRoot","keepAliveRoot","injected","onUnmounted","prepend","reset","setCurrentInstance","createHook","lifecycle","onBeforeMount","onBeforeUpdate","onServerPrefetch","onRenderTriggered","onRenderTracked","onErrorCaptured","COMPONENTS","DIRECTIVES","resolveComponent","maybeSelfReference","resolveAsset","NULL_DYNAMIC_COMPONENT","resolveDynamicComponent","component","resolveDirective","warnMissing","Component","selfName","registry","renderList","renderItem","index","sourceIsArray","sourceIsReactiveArray","needsWrap","isReadonlySource","item","createSlots","dynamicSlots","slot","j","renderSlot","fallback","noSlotted","openBlock","createBlock","validSlotContent","ensureValidVNode","slotKey","rendered","vnodes","toHandlers","obj","preserveCaseIfNecessary","getPublicInstance","isStatefulComponent","publicPropertiesMap","resolveMergedOptions","instanceWatch","hasSetupBinding","PublicInstanceProxyHandlers","data","accessCache","appContext","normalizedProps","n","shouldCacheAccess","publicGetter","cssModule","globalProperties","propsOptions","descriptor","RuntimeCompiledPublicInstanceProxyHandlers","_","defineProps","defineEmits","defineExpose","exposed","defineOptions","defineSlots","defineModel","withDefaults","defaults","useSlots","getContext","useAttrs","calledFunctionName","createSetupContext","normalizePropsOrEmits","normalized","mergeDefaults","raw","opt","mergeModels","createPropsRestProxy","excludedKeys","withAsyncContext","getAwaitable","awaitable","unsetCurrentInstance","applyOptions","publicThis","dataOptions","computedOptions","methods","watchOptions","provideOptions","injectOptions","created","beforeMount","mounted","beforeUpdate","updated","activated","deactivated","beforeDestroy","beforeUnmount","destroyed","unmounted","render","renderTracked","renderTriggered","errorCaptured","serverPrefetch","expose","inheritAttrs","components","filters","resolveInjections","methodHandler","get","set","computed","v","createWatcher","provides","provide","registerLifecycleHook","register","_hook","checkDuplicateProperties","normalizeInject","inject","h","getter","createPathGetter","handler","base","mixins","extendsOptions","globalMixins","optionMergeStrategies","resolved","m","mergeOptions","to","from","strats","asMixin","strat","internalOptionMergeStrats","mergeDataFn","mergeEmitsOrPropsOptions","mergeObjectOptions","mergeAsArray","mergeWatchOptions","mergeInject","merged","createAppContext","uid$1","createAppAPI","rootComponent","rootProps","context","installedPlugins","pluginCleanupFns","isMounted","app","version","plugin","mixin","directive","rootContainer","isHydrate","cleanupFn","lastApp","currentApp","parentProvides","defaultValue","treatDefaultAsFactory","hasInjectionContext","internalObjectProto","createInternalObject","isInternalObject","initProps","isStateful","isSSR","attrs","setFullProps","updateProps","rawPrevProps","rawCurrentProps","hasAttrsChanged","propsToUpdate","isEmitListener","camelizedKey","resolvePropValue","kebabKey","needCastKeys","rawCastValues","camelKey","castValues","isAbsent","hasDefault","propsDefaults","mixinPropsCache","normalizePropsOptions","hasExtends","extendProps","raw2","normalizedKey","validatePropName","prop","propType","shouldCast","shouldCastTrue","typeName","isInternalKey","normalizeSlotValue","normalizeSlot","rawSlot","normalizeObjectSlots","rawSlots","normalizeVNodeSlots","assignSlots","initSlots","cacheIndexes","updateSlots","needDeletionCheck","deletionComparisonTarget","createRenderer","baseCreateRenderer","createHydrationRenderer","createHydrationFns","hostInsert","hostPatchProp","hostCreateElement","hostCreateText","hostCreateComment","hostSetText","hostSetElementText","hostParentNode","hostNextSibling","hostSetScopeId","hostInsertStaticContent","getNextHostNode","processText","processCommentNode","mountStaticNode","processFragment","processElement","processComponent","moveStaticNode","removeStaticNode","mountElement","patchElement","resolveChildrenNamespace","setScopeId","scopeId","cloneIfMounted","oldProps","newProps","toggleRecurse","patchProps","oldChildren","newChildren","fallbackContainer","oldVNode","newVNode","fragmentStartAnchor","fragmentEndAnchor","updateComponent","initialVNode","createComponentInstance","setupComponent","setupRenderEffect","shouldUpdateComponent","updateComponentPreRender","componentUpdateFn","bu","u","nonHydratedAsyncRoot","locateNonHydratedAsyncRoot","originNext","nextTree","renderComponentRoot","prevTree","bm","root","isAsyncWrapperVNode","hydrateSubTree","scopedInitialVNode","effect","update","nextVNode","prevProps","c1","prevShapeFlag","c2","patchKeyedChildren","patchUnkeyedChildren","unmountChildren","oldLength","newLength","commonLength","nextChild","l2","e1","e2","nextPos","s1","s2","keyToNewIndexMap","toBePatched","moved","maxNewIndexSoFar","newIndexToOldIndexMap","prevChild","newIndex","increasingNewIndexSequence","getSequence","nextIndex","anchorVNode","leave","delayLeave","afterLeave","remove2","performLeave","cacheIndex","shouldInvokeDirs","shouldInvokeVnodeHook","unmountComponent","removeFragment","performRemove","bum","scope","um","slotCacheKeys","teleportEnd","isFlushing","currentNamespace","allowed","shallow","ch1","ch2","arr","result","len","arrI","subComponent","ssrContextKey","useSSRContext","watchEffect","doWatch","watchPostEffect","watchSyncEffect","immediate","deep","flush","once","baseWatchOptions","runsImmediately","ssrCleanup","watchStopHandle","isPre","isFirstRun","watchHandle","path","segments","useModel","camelizedName","hyphenatedName","getModelModifiers","track","trigger","localValue","prevSetValue","prevEmittedValue","propValue","emittedValue","i2","modelName","emit","event","rawArgs","isModelListener","handlerName","onceHandler","normalizeEmitsOptions","extendEmits","normalizedFromExtend","proxy","withProxy","renderCache","fallthroughAttrs","proxyToUse","thisProxy","render2","getFunctionalFallthrough","blockStack","filterModelListeners","filterSingleRoot","recurse","singleRoot","prevChildren","nextProps","nextChildren","emits","hasPropsChanged","dynamicProps","emitsOptions","nextKeys","suspenseId","SuspenseImpl","mountSuspense","patchSuspense","hydrateSuspense","normalizeSuspenseChildren","Suspense","triggerEvent","eventListener","hiddenContainer","createSuspenseBoundary","setActiveBranch","newBranch","newFallback","activeBranch","pendingBranch","isInFallback","isHydrating","pendingId","parentSuspenseId","isSuspensible","isVNodeSuspensible","initialAnchor","resume","sync","effects","parentComponent2","delayEnter","hasUnresolvedAncestor","fallbackVNode","namespace2","mountFallback","optimized2","isInPendingSuspense","hydratedEl","asyncSetupResult","handleSetupResult","parentSuspense2","isSlotChildren","normalizeSuspenseSlot","s","block","trackBlock","isBlockTreeEnabled","currentBlock","closeBlock","branch","disableTracking","inVOnce","setupBlock","createElementBlock","createBaseVNode","transformVNodeArgs","transformer","normalizeKey","normalizeRef","ref_key","ref_for","isBlockNode","needFullChildrenNormalization","normalizeChildren","_createVNode","cloned","isClassComponent","guardReactiveProps","klass","style","extraProps","mergeRef","cloneTransition","mergedProps","mergeProps","text","flag","createStaticVNode","numberOfNodes","createCommentVNode","asBlock","slotFlag","toMerge","incoming","emptyAppContext","uid","internalSetCurrentInstance","setInSSRSetupState","g","registerGlobalSetter","setter","setters","setupResult","setupStatefulComponent","setup","setupContext","isAsyncSetup","resolvedResult","finishComponentSetup","compile","installWithProxy","registerRuntimeCompiler","_compile","isRuntimeOnly","skipOptions","template","compilerOptions","delimiters","componentCompilerOptions","finalCompilerOptions","attrsProxyHandlers","includeInferred","getterOrOptions","debugOptions","propsOrChildren","initCustomFormatter","withMemo","memo","isMemoSame","warn$1","ErrorTypeStrings","devtools","setDevtoolsHook","_ssrUtils","ssrUtils","resolveFilter","compatUtils","DeprecationTypes","require_runtime_core","__commonJSMin","exports","module","require_runtime_dom_cjs_prod","__commonJSMin","exports","runtimeCore","shared","policy","tt","val","unsafeToTrustedHTML","svgNS","mathmlNS","doc","templateContainer","nodeOps","child","parent","anchor","tag","namespace","is","props","el","text","node","selector","id","content","start","end","before","template","wrapper","TRANSITION","ANIMATION","vtcKey","DOMTransitionPropsValidators","TransitionPropsValidators","decorate$1","t","Transition","slots","resolveTransitionProps","callHook","hook","args","h2","hasExplicitCallback","rawProps","baseProps","key","name","type","duration","enterFromClass","enterActiveClass","enterToClass","appearFromClass","appearActiveClass","appearToClass","leaveFromClass","leaveActiveClass","leaveToClass","durations","normalizeDuration","enterDuration","leaveDuration","onBeforeEnter","onEnter","onEnterCancelled","onLeave","onLeaveCancelled","onBeforeAppear","onAppear","onAppearCancelled","finishEnter","isAppear","done","isCancelled","removeTransitionClass","finishLeave","makeEnterHook","resolve","nextFrame","addTransitionClass","whenTransitionEnds","forceReflow","NumberOf","n","cls","c","_vtc","cb","endId","expectedType","explicitTimeout","resolveIfNotStale","timeout","propCount","getTransitionInfo","endEvent","ended","onEnd","e","styles","getStyleProperties","transitionDelays","transitionDurations","transitionTimeout","getTimeout","animationDelays","animationDurations","animationTimeout","hasTransform","delays","d","i","toMs","s","patchClass","value","isSVG","transitionClasses","vShowOriginalDisplay","vShowHidden","vShow","transition","setDisplay","oldValue","initVShowForSSR","CSS_VAR_TEXT","useCssVars","getter","displayRE","patchStyle","prev","next","style","isCssString","hasControlledDisplay","prevStyle","setStyle","cssVarText","importantRE","v","prefixed","autoPrefix","prefixes","prefixCache","rawName","cached","xlinkNS","patchAttr","instance","isBoolean","patchDOMProp","parentComponent","attrName","newValue","needRemove","addEventListener","event","handler","options","removeEventListener","veiKey","patchEvent","prevValue","nextValue","invokers","existingInvoker","parseName","invoker","createInvoker","optionsModifierRE","m","cachedNow","p","getNow","initialValue","patchStopImmediatePropagation","originalStop","fn","e2","isNativeOn","patchProp","shouldSetAsProp","REMOVAL","defineCustomElement","extraOptions","_createApp","Comp","VueCustomElement","VueElement","initialProps","defineSSRCustomElement","createSSRApp","BaseClass","_VueElement","_def","_props","createApp","mutations","def","isAsync","numberProps","opt","asyncDef","exposed","declaredPropKeys","has","camelKey","shouldReflect","shouldUpdate","ob","vnode","render","dispatch","owner","nonce","slotName","outlets","scopeId","o","walker","comp","useHost","caller","useShadowRoot","useCssModule","modules","mod","positionMap","newPositionMap","moveCbKey","enterCbKey","decorate","TransitionGroupImpl","state","prevChildren","children","moveClass","hasCSSTransform","callPendingCbs","recordPosition","movedChildren","applyTranslation","cssTransitionProps","TransitionGroup","oldPos","newPos","dx","dy","root","clone","container","getModelAssigner","onCompositionStart","onCompositionEnd","target","assignKey","vModelText","lazy","trim","number","castToNumber","domValue","elValue","vModelCheckbox","_","modelValue","elementValue","getValue","checked","assign","index","found","filtered","cloned","getCheckboxValue","setChecked","binding","vModelRadio","vModelSelect","isSetModel","selectedVal","setSelected","_binding","isMultiple","isArrayValue","l","option","optionValue","optionType","vModelDynamic","callModelHook","prevVNode","resolveDynamicModel","tagName","initVModelForSSR","modelToUse","systemModifiers","modifierGuards","modifiers","withModifiers","cache","cacheKey","guard","keyNames","withKeys","eventKey","k","rendererOptions","renderer","enabledHydration","ensureRenderer","ensureHydrationRenderer","hydrate","app","mount","containerOrSelector","normalizeContainer","component","proxy","resolveRootNamespace","ssrDirectiveInitialized","initDirectivesForSSR","require_runtime_dom","__commonJSMin","exports","module","require_vue_cjs_prod","__commonJSMin","exports","compilerDom","runtimeDom","shared","_interopNamespaceDefault","n","k","runtimeDom__namespace","compileCache","compileToFunction","template","options","key","cached","el","opts","tag","code","render","require_vue","__commonJSMin","exports","module","require_extend","__commonJSMin","exports","module","hasOwn","toStr","defineProperty","gOPD","isArray","arr","isPlainObject","obj","hasOwnConstructor","hasIsPrototypeOf","key","setProperty","target","options","getProperty","name","extend","src","copy","copyIsArray","clone","i","length","deep","require_rolldown_runtime","__commonJSMin","exports","__create","__defProp","__getOwnPropDesc","__getOwnPropNames","__getProtoOf","__hasOwnProp","__copyProps","to","from","except","desc","keys","i","n","key","k","__toESM","mod","isNodeMode","target","serialize","o","c","isEqual","object1","object2","init_ohash_D_AXeF1","__esmMin","#t","t","r","e","n","a","l","s","digest","_","k","z","R","S","r","l","init_js","__esmMin","e","s","t","i","a","c","h","g","f","y","n","d","j","B","m","p","u","b","w","M","_l","dist_exports","__export","digest","hash","isEqual","serialize","input","init_dist","__esmMin","init_ohash_D_AXeF1","init_js","areEqual","arrayA: any[]","arrayB: any[]","arrayA","arrayB","index","chunk","arr: T[]","size: number","result","i","arr","size","findValuesBetween","array: T[]","start: T","end: T","startIndex","array","ohash","start","endIndex","end","minIndex","maxIndex","a","b","isBrowser","clamp","value: number","min: number","max: number","max","min","value","roundToStepPrecision","step: number","roundedValue","stepString","step","pointIndex","precision","pow","snapValueToStep","min: number | undefined","max: number | undefined","remainder","snappedValue","createContext","providerComponentName: string | string[]","contextName?: string","symbolDescription","providerComponentName","contextName","injectionKey: InjectionKey<ContextValue | null>","fallback?: T","context","vue","injectionKey","fallback","contextValue: ContextValue","contextValue","getActiveElement","activeElement","handleAndDispatchCustomEvent","name: string","handler: ((event: E) => void) | undefined","detail: { originalEvent: OriginalEvent } & (E extends CustomEvent<infer D>\n    ? D\n    : never)","target","detail","event","name","handler","isValidVNodeElement","input: any","input","isNullish","value: any","value","isValueEqualOrExist","base: T | T[] | undefined","current: T | T[] | undefined","require_shared_nullish","base","val","ohash","current","pick","object: T","keys: K[]","keys","key","object","omit","obj: T","obj","dist_exports","__export","assert","autoResetRef","bypassFilter","camelize","clamp","computedEager","computedWithControl","containsProp","controlledComputed","controlledRef","createDisposableDirective","createEventHook","createFilterWrapper","createGlobalState","createInjectionState","createReactiveFn","createRef","createSharedComposable","createSingletonPromise","debounceFilter","debouncedRef","debouncedWatch","eagerComputed","extendRef","formatDate","get","getLifeCycleTarget","hasOwn","hyphenate","identity","ignorableWatch","increaseWithUnit","injectLocal","invoke","isClient","isDef","isDefined","isIOS","isObject","isWorker","makeDestructurable","noop","normalizeDate","notNullish","now","objectEntries","objectOmit","objectPick","pausableFilter","pausableWatch","promiseTimeout","provideLocal","pxValue","rand","reactify","reactifyObject","reactiveComputed","reactiveOmit","reactivePick","refAutoReset","refDebounced","refDefault","refManualReset","refThrottled","refWithControl","set","syncRef","syncRefs","throttleFilter","throttledRef","throttledWatch","timestamp","toArray","toReactive","toRef","toRefs","tryOnBeforeMount","tryOnBeforeUnmount","tryOnMounted","tryOnScopeDispose","tryOnUnmounted","until","useArrayDifference","useArrayEvery","useArrayFilter","useArrayFind","useArrayFindIndex","useArrayFindLast","useArrayIncludes","useArrayJoin","useArrayMap","useArrayReduce","useArraySome","useArrayUnique","useCounter","useDateFormat","useDebounce","useDebounceFn","useInterval","useIntervalFn","useLastChanged","useThrottle","useThrottleFn","useTimeout","useTimeoutFn","useToNumber","useToString","useToggle","watchArray","watchAtMost","watchDebounced","watchDeep","watchIgnorable","watchImmediate","watchOnce","watchPausable","watchThrottled","watchTriggerable","watchWithFilter","whenever","fn","options","_options$flush","result","source","v","track","trigger","dirty","update","_track","_trigger","origin","isFunc","normalisedOrigin","mounted","unmounted","scopeWeakMap","el","binding","vNode","prevNode","_scopeWeakMap$get","scope","_scopeWeakMap$get2","failSilently","fns","off","offFn","args","stateFactory","initialized","state","key","value","_getCurrentInstance","instance","owner","localProvidedStateMap","localProvidedState","composable","defaultValue","deep","getIsIOS","_window","_window2","_window3","toRef$1","r","filter","wrapper","resolve","reject","ms","timer","maxTimer","lastRejector","_clearTimeout","lastInvoker","duration","maxDuration","lastExec","isLeading","lastValue","trailing","leading","rejectOnCancel","clear","_invoke","elapsed","extendFilter","initialState","isActive","pause","resume","eventFilter","throwOnTimeout","reason","arg","_promise","_prev","obj","props","k","target","delta","_target$match","unit","px","keys","omitUndefined","cacheStringFunction","cache","str","subscribers","dispose","ref","extend","enumerable","unwrap","arr","clone","index","unrefFn","i","optionsOrKeys","includeOwnProperties","objectRef","_","p","receiver","flatKeys","predicate","toRefs$1","e","afterMs","resetAfter","newValue","debounced","updater","_source$value","reset","refValue","delay","throttled","initial","tracking","triggering","_options$onBeforeChan","_options$onChanged","old","cb","watchOptions","left","right","flush","immediate","direction","transform","watchers","transformLTR","transformRTL","w","targets","targetsArray","_toValue","copy","newObject","sync","createUntil","isNot","toMatch","condition","timeout","stop","promises","toBe","v1","v2","toBeTruthy","toBeNull","toBeUndefined","toBeNaN","toContains","array","changed","changedTimes","n","count","defaultComparator","othVal","_args$","_args$2","list","values","compareFn","symmetric","diff1","x","y","diff2","element","findLast","isArrayIncludesOptions","_comparator","comparator","formIndex","_comparator$fromIndex","separator","reducer","reduceCallback","sum","resolved","uniq","uniqueElementsBy","acc","resolvedList","initialValue","_initialValue","max","min","inc","dec","val","defaultMeridiem","hours","minutes","isLowercase","hasPeriod","m","curr","formatOrdinal","num","suffixes","date","formatStr","_options$customMeridi","years","month","days","seconds","milliseconds","day","meridiem","stripTimeZone","dateString","_dateString$split$","matches","REGEX_FORMAT","match","$1","_ref","_matches$match","d","REGEX_PARSE","interval","immediateCallback","clean","intervalValue","exposeControls","callback","counter","controls","_options$initialValue","isPending","start","ready","method","radix","nanToZero","truthyValue","falsyValue","valueIsRef","_value","toggle","truthy","oldList","newList","onCleanup","oldListRemains","added","found","removed","current","debounce","maxWait","filteredCb","ignoreUpdates","ignorePrevAsyncUpdates","ignore","disposables","ignoreCounter","syncCounter","syncCounterPrev","throttle","cleanupFn","onEffect","_cb","oldValue","res","getWatchSources","getOldValue","sources","item","ov","onInvalidate","import_vue","toString","hyphenateRE","camelizeRE","init_dist","__esmMin","infos","c","dist_exports","__export","DefaultMagicKeysAliasMap","StorageSerializers","TransitionPresets","assert","asyncComputed","autoResetRef","breakpointsAntDesign","breakpointsBootstrapV5","breakpointsElement","breakpointsMasterCss","breakpointsPrimeFlex","breakpointsQuasar","breakpointsSematic","breakpointsTailwind","breakpointsVuetify","breakpointsVuetifyV2","breakpointsVuetifyV3","bypassFilter","camelize","clamp","cloneFnJSON","computedAsync","computedEager","computedInject","computedWithControl","containsProp","controlledComputed","controlledRef","createDisposableDirective","createEventHook","createFetch","createFilterWrapper","createGlobalState","createInjectionState","createReactiveFn","createRef","createReusableTemplate","createSharedComposable","createSingletonPromise","createTemplatePromise","createUnrefFn","customStorageEventName","debounceFilter","debouncedRef","debouncedWatch","defaultDocument","defaultLocation","defaultNavigator","defaultWindow","eagerComputed","executeTransition","extendRef","formatDate","formatTimeAgo","formatTimeAgoIntl","formatTimeAgoIntlParts","get","getLifeCycleTarget","getSSRHandler","hasOwn","hyphenate","identity","ignorableWatch","increaseWithUnit","injectLocal","invoke","isClient","isDef","isDefined","isIOS","isObject","isWorker","makeDestructurable","mapGamepadToXbox360Controller","noop","normalizeDate","notNullish","now","objectEntries","objectOmit","objectPick","onClickOutside","onElementRemoval","onKeyDown","onKeyPressed","onKeyStroke","onKeyUp","onLongPress","onStartTyping","pausableFilter","pausableWatch","promiseTimeout","provideLocal","provideSSRWidth","pxValue","rand","reactify","reactifyObject","reactiveComputed","reactiveOmit","reactivePick","refAutoReset","refDebounced","refDefault","refManualReset","refThrottled","refWithControl","set","setSSRHandler","syncRef","syncRefs","templateRef","throttleFilter","throttledRef","throttledWatch","timestamp","toArray","toReactive","toRef","toRefs","transition","tryOnBeforeMount","tryOnBeforeUnmount","tryOnMounted","tryOnScopeDispose","tryOnUnmounted","unrefElement","until","useActiveElement","useAnimate","useArrayDifference","useArrayEvery","useArrayFilter","useArrayFind","useArrayFindIndex","useArrayFindLast","useArrayIncludes","useArrayJoin","useArrayMap","useArrayReduce","useArraySome","useArrayUnique","useAsyncQueue","useAsyncState","useBase64","useBattery","useBluetooth","useBreakpoints","useBroadcastChannel","useBrowserLocation","useCached","useClipboard","useClipboardItems","useCloned","useColorMode","useConfirmDialog","useCountdown","useCounter","useCssSupports","useCssVar","useCurrentElement","useCycleList","useDark","useDateFormat","useDebounce","useDebounceFn","useDebouncedRefHistory","useDeviceMotion","useDeviceOrientation","useDevicePixelRatio","useDevicesList","useDisplayMedia","useDocumentVisibility","useDraggable","useDropZone","useElementBounding","useElementByPoint","useElementHover","useElementSize","useElementVisibility","useEventBus","useEventListener","useEventSource","useEyeDropper","useFavicon","useFetch","useFileDialog","useFileSystemAccess","useFocus","useFocusWithin","useFps","useFullscreen","useGamepad","useGeolocation","useIdle","useImage","useInfiniteScroll","useIntersectionObserver","useInterval","useIntervalFn","useKeyModifier","useLastChanged","useLocalStorage","useMagicKeys","useManualRefHistory","useMediaControls","useMediaQuery","useMemoize","useMemory","useMounted","useMouse","useMouseInElement","useMousePressed","useMutationObserver","useNavigatorLanguage","useNetwork","useNow","useObjectUrl","useOffsetPagination","useOnline","usePageLeave","useParallax","useParentElement","usePerformanceObserver","usePermission","usePointer","usePointerLock","usePointerSwipe","usePreferredColorScheme","usePreferredContrast","usePreferredDark","usePreferredLanguages","usePreferredReducedMotion","usePreferredReducedTransparency","usePrevious","useRafFn","useRefHistory","useResizeObserver","useSSRWidth","useScreenOrientation","useScreenSafeArea","useScriptTag","useScroll","useScrollLock","useSessionStorage","useShare","useSorted","useSpeechRecognition","useSpeechSynthesis","useStepper","useStorage","useStorageAsync","useStyleTag","useSupported","useSwipe","useTemplateRefsList","useTextDirection","useTextSelection","useTextareaAutosize","useThrottle","useThrottleFn","useThrottledRefHistory","useTimeAgo","useTimeAgoIntl","useTimeout","useTimeoutFn","useTimeoutPoll","useTimestamp","useTitle","useToNumber","useToString","useToggle","useTransition","useUrlSearchParams","useUserMedia","useVModel","useVModels","useVibrate","useVirtualList","useWakeLock","useWebNotification","useWebSocket","useWebWorker","useWebWorkerFn","useWindowFocus","useWindowScroll","useWindowSize","watchArray","watchAtMost","watchDebounced","watchDeep","watchIgnorable","watchImmediate","watchOnce","watchPausable","watchThrottled","watchTriggerable","watchWithFilter","whenever","evaluationCallback","initialState","optionsOrRef","_globalThis$reportErr","options","lazy","flush","evaluating","shallow","onError","started","current","counter","onInvalidate","counterAtBeginning","hasFinished","result","cancelCallback","e","key","defaultSource","treatDefaultAsFactory","source","oldValue","inheritAttrs","name","render","define","_","slots","reuse","props","attrs","_render$value","vnode","keysToCamelKebabCase","obj","newObj","index","instances","create","args","_resolve","_reject","v","start","component","renderList","_slots$default","fn","i","elRef","_$el","plain","register","el","event","listener","firstParamTargets","test","_firstParamTargets$va","_firstParamTargets$va2","raw_targets","raw_events","raw_listeners","raw_options","onCleanup","optionsClone","cleanups","target","handler","window","ignore","capture","detectIframe","controls","_iOSWorkaround","listenerOptions","shouldListen","shouldIgnore","hasMultipleRoots","vm","checkMultipleRoots","children","child","isProcessingClick","cleanup","activeEl","stop","isMounted","instance","callback","mutationOptions","observer","isSupported","stopWatch","items","newTargets","takeRecords","document","stopFn","cleanupAndUpdate","mutationsList","mutation","node","stopHandle","createKeyPredicate","keyFilter","eventName","passive","dedupe","predicate","_options$modifiers10","_options$modifiers11","elementRef","timeout","posStart","startTimestamp","hasLongPressed","clear","getDelay","ev","delay","DEFAULT_DELAY","onRelease","_options$modifiers","_options$modifiers2","_options$modifiers3","_startTimestamp","_posStart","_hasLongPressed","dx","dy","distance","onDown","_options$modifiers4","_options$modifiers5","_options$modifiers6","onMove","_options$modifiers7","_options$modifiers8","_options$modifiers9","_options$distanceThre","DEFAULT_THRESHOLD","isFocusedElementEditable","activeElement","body","isTypedCharValid","keyCode","metaKey","ctrlKey","altKey","initialValue","_trigger","element","track","trigger","_instance$proxy$$refs","_instance$proxy","_options$document","deep","triggerOnRemoval","getDeepActiveElement","_element$shadowRoot","immediate","fpsLimit","once","isActive","intervalLimit","limit","previousFrameTimestamp","rafId","loop","delta","resume","pause","keyframes","config","animateOptions","commitStyles","persist","_playbackRate","onReady","animate","store","pending","playState","replaceState","startTime","value","currentTime","syncResume","timeline","playbackRate","play","syncPause","update","_animate$value","reverse","_animate$value2","finish","_animate$value3","cancel","_animate$value4","targetEl","init","_animate$value5","resumeRef","pauseRef","tasks","interrupt","onFinished","signal","promiseState","activeIndex","updateResult","state","res","prev","curr","prevRes","_result$activeIndex$v","done","currentRes","whenAborted","resolve","reject","error","promise","onSuccess","resetOnExecute","throwError","isReady","isLoading","executionsCount","execute","executionId","_promise","data","shell","waitUntilIsLoaded","onFulfilled","onRejected","getDefaultSerialization","defaults","base64","_target","blobToBase64","img","imgLoaded","canvas","ctx","serialized","blob","fr","navigator","events","charging","chargingTime","dischargingTime","level","battery","updateBatteryInfo","_battery","acceptAllDevices","filters","optionalServices","device","connectToBluetoothGATTServer","requestDevice","err","server","isConnected","reset","_device$value$gatt","_device$value$gatt2","ssrWidth","ssrWidthSymbol","width","app","query","ssrSupport","mediaQuery","matches","queryString","not","minWidth","maxWidth","breakpoints","getValue","k","strategy","mounted","match","size","greaterOrEqual","smallerOrEqual","shortcutMethods","shortcuts","points","a","b","bps","isClosed","channel","post","close","refs","WRITABLE_PROPERTIES","ref","buildState","_window$location","length","origin","refValue","comparator","newSourceValue","cachedValue","deepRefs","watchOptions","permissionDesc","permissionStatus","desc","_permissionStatus$val","_permissionStatus$val2","read","copiedDuring","legacy","isClipboardApiSupported","permissionRead","permissionWrite","text","copied","copyPending","lastLegacyId","updateText","useLegacy","isAllowed","legacyRead","copy","resolvedValue","clipboardItem","createClipboardItem","legacyCopy","currentId","resolvedText","ta","_document$getSelectio","_document","_document$getSelectio2","status","content","updateContent","cloned","isModified","_lastSync","manual","clone","sync","getHandlers","globalKey","_global","fallback","handlers","guessSerializerType","rawInit","storage","_options$serializer","listenToStorageChanges","writeDefaults","mergeDefaults","eventFilter","initOnMounted","keyComputed","type","serializer","pauseWatch","resumeWatch","newValue","write","firstMounted","onStorageEvent","onStorageCustomEvent","updateFromCustomEvent","dispatchWriteEvent","payload","rawValue","serializedData","selector","attribute","storageKey","storageRef","emitAuto","disableTransition","modes","preferredDark","system","updateHTMLAttrs","classesToAdd","classesToRemove","attributeToChange","style","CSS_DISABLE_TRANS","c","defaultOnChanged","mode","_modes$mode","onChanged","auto","revealed","confirmHook","cancelHook","revealHook","reveal","confirm","getDefaultScheduler$8","interval","cb","initialCountdown","remaining","scheduler","onTick","onComplete","countdown","_toValue","prop","ssrValue","observe","variable","_window$document","updateCssVar","_window$getComputedSt","old","val","raw_prop","rootComponent","currentElement","list","getInitialValue","listRef","_options$fallbackInde","targetList","shift","next","n","_options$initialValue","valueDark","valueLight","defaultHandler","_options$onChanged","modeVal","fnBypass","fnSetSource","defaultDump","defaultParse","dump","parse","setSource","_createHistoryRecord","last","undoStack","redoStack","_setSource","record","commit","undo","redo","shouldCommit","composedFilter","resumeTracking","isTracking","lastRawValue","ignoreUpdates","ignorePrevAsyncUpdates","manualHistory","manualCommit","commitNow","batch","canceled","dispose","filter","requestPermissions","requirePermissions","permissionGranted","acceleration","rotationRate","accelerationIncludingGravity","_event$acceleration","_event$acceleration2","_event$acceleration3","_event$accelerationIn","_event$accelerationIn2","_event$accelerationIn3","_event$rotationRate","_event$rotationRate2","_event$rotationRate3","ensurePermissions","requestPermission","isAbsolute","alpha","beta","gamma","pixelRatio","constraints","onUpdated","devices","videoInputs","audioInputs","audioOutputs","stream","t","deviceName","granted","allDevices","hasCamera","hasMicrophone","_options$enabled","enabled","video","audio","_navigator$mediaDevic","constraint","_start","_stream$value","_stop","_stream$value2","visibility","clampContainerScroll","container","_toValue2","_toValue3","_scrollConfig$directi","pointerTypes","preventDefault","stopPropagation","exact","onEnd","onStart","axis","draggingElement","containerElement","draggingHandle","buttons","restrictInView","autoScroll","position","pressedDelta","filterEvent","handleEvent","scrollConfig","scrollSettings","defaultScrollConfig","getScrollAxisValues","handleAutoScroll","targetRect","clientWidth","clientHeight","scrollLeft","scrollTop","scrollWidth","scrollHeight","marginX","marginY","speedX","speedY","deltaX","deltaY","autoScrollInterval","startAutoScroll","x","y","relativePosition","stopAutoScroll","isPointerNearEdge","pointer","margin","checkAutoScroll","_container$getBoundin","containerRect","pos","move","relativeX","relativeY","end","_options$capture","isOverDropZone","files","isValid","_options$multiple","_options$preventDefau","_options","multiple","preventDefaultForUnhandled","getFiles","_event$dataTransfer$f","_event$dataTransfer","checkDataTypes","types","dataTypes","allowedType","checkValidity","dataTypesValid","item","multipleFilesValid","isSafari","handleDragEvent","eventType","_event$dataTransfer2","_ref","dataTransferItemList","currentFiles","_options$onEnter","_options$onOver","_options$onLeave","_options$onDrop","observerOptions","_targets","els","_el","windowResize","windowScroll","updateTiming","height","bottom","left","right","top","recalculate","rect","ele","getDefaultScheduler$7","_document$elementsFro","_document$elementFrom","delayEnter","delayLeave","isHovered","timer","toggle","entering","initialSize","box","isSVG","_unrefElement","stop1","entry","boxSize","$elem","formatBoxSize","acc","inlineSize","blockSize","stop2","root","rootMargin","threshold","targets","scrollTarget","isVisible","observerController","intersectionObserverEntries","isIntersecting","latestTime","scope","on","_scope$cleanups","listeners","_off","off","_listener","emit","_events$get","resolveNestedOptions$1","url","eventSource","urlRef","lastEventId","explicitlyClosed","retried","withCredentials","autoConnect","autoReconnect","_init","es","retries","onFailed","_serializer$read","event_name","_serializer$read2","_e$lastEventId","open","sRGBHex","openOptions","newIcon","baseUrl","rel","favicon","applyIcon","icon","elements","link","o","isFetchOptions","isAbsoluteURL","reAbsolute","headersToObject","headers","combineCallbacks","combination","callbacks","_combination","_fetchOptions","useFactoryFetch","computedUrl","targetUrl","joinPaths","fetchOptions","_defaultWindow$fetch","_globalThis","supportsAbort","fetch","initialData","responseEvent","errorEvent","finallyEvent","isFinished","isFetching","aborted","statusCode","response","canAbort","controller","abort","reason","loading","executeCounter","throwOnFailed","_context$options","currentExecuteCounter","defaultFetchOptions","_payloadMapping$confi","proto","payloadMapping","isCanceled","context","responseData","fetchResponse","fetchError","errorData","refetch","setMethod","setType","method","payloadType","waitUntilFinished","prepareInitialFiles","dt","file","onChange","changeTrigger","onCancel","cancelTrigger","inputRef","input","applyOptions","localOptions","mergedOptions","DEFAULT_OPTIONS","_window","dataType","fileHandle","fileName","_file$value$name","_file$value","fileMIME","_file$value$type","_file$value2","fileSize","_file$value$size","_file$value3","fileLastModified","_file$value$lastModif","_file$value4","handle","updateData","save","saveAs","writableStream","updateFile","_fileHandle$value","_file$value5","_file$value6","focusVisible","preventScroll","innerFocused","targetElement","_matches","focused","_targetElement$value","_targetElement$value2","_focused","EVENT_FOCUS_IN","EVENT_FOCUS_OUT","_targetElement$value$","_targetElement$value$2","PSEUDO_CLASS_FOCUS_WITHIN","_options$every","fps","every","ticks","diff","autoExit","targetRef","isFullscreen","requestMethod","m","exitMethod","fullscreenEnabled","fullscreenElementMethod","isCurrentElementFullScreen","isElementFullScreen","exit","enter","handlerCallback","isElementFullScreenValue","eventHandlers","gamepad","gamepads","onConnectedHook","onDisconnectedHook","stateFromGamepad","hapticActuators","vibrationActuator","axes","button","updateGamepadState","_gamepads","onGamepadConnected","onGamepadDisconnected","enableHighAccuracy","maximumAge","locatedAt","coords","updatePosition","watcher","oneMinute","listenForVisibilityChange","defaultEvents$1","idle","lastActive","isPending","onEvent","loadImage","src","srcset","sizes","clazz","crossorigin","referrerPolicy","decoding","fetchPriority","ismap","usemap","asyncStateOptions","resolveElement","throttle","onStop","onScroll","offset","_observe","eventListenerOptions","behavior","internalX","internalY","scrollTo","_x","_y","_element","scrollContainer","isScrolling","arrivedState","directions","onScrollEnd","onScrollEndDebounced","setArrivedState","_document2","display","flexDirection","direction","directionMultipler","ARRIVED_STATE_THRESHOLD_PIXELS","onScrollHandler","_documentElement","onLoadMore","_options$distance","canLoadMore","observedElement","isElementVisible","canLoad","checkAndLoad","isNarrower","modifier","defaultEvents","initial","listenerEvent","evt","useReactive","aliasMap","onEventFired","metaDeps","depsMap","usedKeys","setRefs","updateDeps","keys","depsSet","clearDeps","depsMapKey","deps","depsArray","depsIndex","updateRefs","_e$key","_e$code","values","proxy","rec","r","usingElRef","timeRangeToArray","timeRanges","ranges","tracksToArray","tracks","label","kind","language","activeCues","cues","inBandMetadataTrackDispatchType","id","defaultOptions","duration","seeking","volume","waiting","ended","playing","rate","stalled","buffered","selectedTrack","isPictureInPicture","muted","supportsPictureInPicture","sourceErrorEvent","playbackErrorEvent","disableTrack","enableTrack","disableTracks","togglePictureInPicture","sources","media","textTracks","isDefault","srcLang","ignoreCurrentTimeUpdates","time","ignorePlayingUpdates","isPlaying","resolver","cache","generateKey","_loadData","loadData","deleteData","clearData","memoized","getDefaultScheduler$6","immediateCallback","memory","touch","resetOnTouchEnds","scroll","_prevMouseEvent","_prevScrollX","_prevScrollY","sourceType","extractor","UseMouseBuiltinExtractors","mouseHandler","touchHandler","scrollHandler","mouseHandlerWrapper","touchHandlerWrapper","scrollHandlerWrapper","handleOutside","elementX","elementY","elementPositionX","elementPositionY","elementHeight","elementWidth","isOutside","elX","elY","stopFnList","stopResizeObserver","stopMutationObserver","drag","pressed","onPressed","srcType","_options$onPressed","onReleased","_options$onReleased","isOnline","saveData","offlineAt","onlineAt","downlink","downlinkMax","rtt","effectiveType","connection","updateNetworkInformation","getDefaultScheduler$5","exposeControls","object","release","newObject","useClamp","min","max","_value","total","pageSize","page","onPageChange","onPageSizeChange","onPageCountChange","currentPageSize","pageCount","currentPage","isFirstPage","isLastPage","returnValue","isLeft","screenOrientation","orientation","angle","deviceOrientationTiltAdjust","deviceOrientationRollAdjust","mouseTiltAdjust","mouseRollAdjust","parentElement","performanceOptions","isInside","defaultState","triggerElement","_pointerLockElement","_pointerLockElement2","action","lock","unlock","onSwipe","onSwipeEnd","onSwipeStart","disableTextSelect","updatePosStart","posEnd","updatePosEnd","distanceX","distanceY","abs","isThresholdExceeded","isSwiping","isPointerDown","eventIsAllowed","_options$pointerTypes","_options$pointerTypes2","isReleasingButton","isPrimaryButton","stops","eventTarget","_targetRef$value","_targetRef$value2","_targetRef$value3","_targetRef$value4","s","isLight","isDark","isMore","isLess","isCustom","isReduced","previous","topCssVar","topVarName","rightCssVar","rightVarName","bottomCssVar","bottomVarName","leftCssVar","leftVarName","onLoaded","async","crossOrigin","noModule","defer","nonce","scriptTag","loadScript","waitForScriptLoad","resolveWithElement","shouldAppend","load","unload","checkOverflowScroll","parent","rawEvent","isLocked","stopTouchMoveListener","initialOverflow","elInitialOverflow","shareOptions","_navigator","overrideOptions","compareFn","defaultCompare","_options$compareFn","_args$","_args$2","_args$3","dirty","sortFn","defaultSortFn","interimResults","continuous","maxAlternatives","lang","isListening","isFinal","recognition","SpeechRecognition","currentResult","transcript","pitch","onBoundary","synth","spokenText","bindEventsForUtterance","utterance","newUtterance","speak","steps","initialStep","stepsRef","stepNames","at","isFirst","isLast","step","goTo","goToNext","goToPrevious","goBackTo","isAfter","isNext","isPrevious","isCurrent","isBefore","css","isLoaded","_id","cssRef","coordsStart","coordsEnd","diffX","diffY","getTouchEventCoords","updateCoordsStart","updateCoordsEnd","onTouchEnd","_document$querySelect","dir","_document$querySelect2","_document$querySelect3","getRangesFromSelection","selection","_selection$rangeCount","rangeCount","_window$getSelection","_selection$value$toSt","_selection$value","rects","range","onSelectionChange","tryRequestAnimationFrame","_options$input","_options$styleProp","textarea","styleProp","textareaScrollHeight","textareaOldWidth","triggerResize","_textarea$value","maxHeight","_styleTarget","styleHeight","_options$onResize","contentRect","trailing","DEFAULT_FORMATTER","date","getDefaultScheduler$4","updateInterval","timeAgo","from","messages","DEFAULT_MESSAGES","fullDateFormatter","units","DEFAULT_UNITS","showSecond","rounding","roundFn","absDiff","unit","format","past","str","applyFormat","isPast","formatter","_units$find","unitMax","idx","getDefaultScheduler$3","getTimeAgoIntlResult","parts","timeAgoIntl","resolvedLocale","_options$units","locale","relativeTimeFormatOptions","rtf","UNITS","ms","insertSpace","joinParts","part","getDefaultScheduler$2","ts","newTitle","_document$title","restoreOnUnmount","originalTitle","title","isReadonly","template","_document$head","restoredTitle","createEasingFunction","p0","p1","p2","p3","a1","a2","calcBezier","getSlope","getTforX","aGuessT","currentSlope","currentX","lerp","defaultInterpolation","aVal","bVal","normalizeEasing","easing","to","fromVal","toVal","startedAt","endAt","interpolation","trans","ease","tick","_options$abort","sourceVal","outputRef","_options$onStarted","_options$onFinished","_options$abort2","disabled","removeNullishValues","removeFalsyValues","enableWrite","writeMode","stringify","params","getRawParams","hash","constructQuery","stringified","updateState","unusedKeys","paramsForKey","mapEntry","shouldUpdate","shouldWriteHistory","_options$autoSwitch","autoSwitch","getDeviceOptions","restart","_vm$$emit","_vm$proxy","defaultValue","shouldEmit","_emit","cloneFn","triggerEmit","isUpdating","ret","getDefaultScheduler$1","pattern","patternRef","vibrate","intervalControls","containerStyle","wrapperProps","calculateRange","currentList","containerRef","useVerticalVirtualList","useHorizontalVirtualList","useVirtualListResources","createGetViewCapacity","itemSize","containerSize","sum","capacity","createGetOffset","scrollDirection","createCalculateRange","overscan","getOffset","getViewCapacity","viewCapacity","createGetDistance","useWatchForSizes","createComputedTotalSize","createScrollTo","getDistance","scrollToDictionaryForElementScrollKey","resources","itemWidth","getDistanceLeft","offsetLeft","totalWidth","itemHeight","getDistanceTop","offsetTop","totalHeight","requestedType","sentinel","documentVisibility","_sentinel$value$type","_sentinel$value","forceRequest","_sentinel$value2","request","_requestForPermissions","defaultWebNotificationOptions","notification","onClick","clickTrigger","onShow","showTrigger","errorTrigger","onClose","closeTrigger","show","overrides","resolveNestedOptions","getDefaultScheduler","onConnected","onDisconnected","onMessage","autoClose","protocols","wsRef","heartbeatPause","heartbeatResume","bufferedData","retryTimeout","pongTimeoutWait","_sendBuffer","buffer","resetRetry","resetHeartbeat","code","send","useBuffer","ws","delayTime","message","DEFAULT_PING_MESSAGE","responseMessage","pongTimeout","arg0","workerOptions","worker","terminate","depsParser","localDeps","depsString","dep","depsFunctionString","importString","jobRunner","userFunc","userFuncArgs","createWorkerBlobUrl","blobCode","dependencies","localDependencies","workerStatus","timeoutId","workerTerminate","generateWorker","blobUrl","newWorker","callWorker","fnArgs","rest","initialWidth","initialHeight","listenOrientation","includeScrollbar","visualViewportWidth","visualViewportHeight","scale","import_vue","init_dist","__esmMin","onFocusOutside","element: MaybeElementRef","handler: (event: FocusEvent) => void","handleFocusOut","ev: FocusEvent","el","__vueuse_core","element","ev","handler","vue","renderSlotFragments","children?: VNode[]","children","child","Fragment","trapFocus","element: HTMLElement","element","focusableEls","el","firstFocusableEl","lastFocusableEl","KEYCODE_TAB","e","require_shared_getActiveElement","ignoredElement","useArrowNavigation","e: KeyboardEvent","currentElement: HTMLElement","parentElement: HTMLElement | undefined","options: ArrowNavigationOptions","currentElement","options","arrowKeyOptions","attributeName","itemsArray","loop","dir","preventScroll","focus","right","left","up","down","home","end","goingVertical","goingHorizontal","allCollectionItems: HTMLElement[]","parentElement","allCollectionItems","item: HTMLElement | null","item","findNextFocusableElement","elements: HTMLElement[]","options: FindNextFocusableElementOptions","iterations","elements","index","newIndex: number","newIndex","adjustedNewIndex","candidate","injectConfigProviderContext","provideConfigProviderContext","require_shared_createContext","props","__props","dir","locale","scrollBody","nonce","vue","_ctx","require_defu","__commonJSMin","exports","isPlainObject","value","prototype","_defu","baseObject","defaults","namespace","merger","object","key","createDefu","arguments_","p","c","defu","defuFn","currentValue","defuArrayFn","require_defu","__commonJSMin","exports","module","defu","createDefu","defuFn","defuArrayFn","useBodyLockStackCount","__vueuse_core","map","vue","initialOverflow","locked","value","context","require_ConfigProvider_ConfigProvider","stopTouchMoveListener: Fn | null","resetBodyStyle","__vueuse_shared","stopTouchMoveListener","val","oldVal","isClient","verticalScrollbarWidth","defaultConfig","config","defu","isIOS","e: TouchEvent","preventDefault","e","useBodyScrollLock","initialState?: boolean | undefined","id","initialState","checkOverflowScroll","ele: Element","style","ele","parent","rawEvent: TouchEvent","rawEvent","_target","useComposing","onEnd?: (event: CompositionEvent) => void","isComposing","vue","handleCompositionStart","handleCompositionEnd","event: CompositionEvent","onEnd","event","$09f945753a699862$export$842a2cf37af977e1","amount","numerator","$05031860ba2f881f$var$EPOCH","$05031860ba2f881f$export$f297eb839006d339","era","year","month","day","$05031860ba2f881f$export$c36e0ecb2d4fa69d","y1","monthOffset","$05031860ba2f881f$export$553d7fa8e3805fc0","$05031860ba2f881f$export$4475b7e617eb123c","$05031860ba2f881f$var$daysInMonth","$05031860ba2f881f$export$80ee6245ec4f29ec","jd","jd0","depoch","quadricent","dqc","$09f945753a699862$exports","cent","dcent","quad","dquad","yindex","extendedYear","yearDay","leapAdj","$c51b7e0106f45dea$exports","date","$621d1537dc806c0f$export$7a5acbd77d414bd9","$84a63d30beb0af0f$export$ea39ec197993aef0","a","b","$e13115b3b86b9007$exports","$84a63d30beb0af0f$export$a18c89cbd24170ff","$84a63d30beb0af0f$export$a5a3b454ada2268e","$84a63d30beb0af0f$export$5841f9eb9773f25f","$84a63d30beb0af0f$export$f91e89d3d0406102","$84a63d30beb0af0f$export$91b62ebf2ba703ee","$84a63d30beb0af0f$export$dbc69fd56b53d5e","$84a63d30beb0af0f$export$5a8da0c44a3afdf2","$84a63d30beb0af0f$export$ea840f5a6dda8147","$84a63d30beb0af0f$export$629b0a497aa65267","date","timeZone","$84a63d30beb0af0f$export$d0bdf45af03a6ea3","$84a63d30beb0af0f$var$DAY_MAP","$84a63d30beb0af0f$export$2061056d06d7cdf7","locale","firstDayOfWeek","julian","weekStart","$84a63d30beb0af0f$var$getWeekStart","dayOfWeek","$84a63d30beb0af0f$export$461939dd4422153","$84a63d30beb0af0f$export$68781ddf31c0090f","$84a63d30beb0af0f$export$c19a80a9721b80f6","$84a63d30beb0af0f$var$timeToMs","$84a63d30beb0af0f$export$126c91c941de7e","ms","tomorrow","$84a63d30beb0af0f$var$localTimeZone","$84a63d30beb0af0f$var$localTimeZoneOverride","$84a63d30beb0af0f$export$aa8b41735afcabd2","$84a63d30beb0af0f$export$61a9d83ceb59a3dd","$84a63d30beb0af0f$export$55753838ffe79333","$84a63d30beb0af0f$export$6ab69b273755230b","$84a63d30beb0af0f$export$a2258d9c4118825c","$84a63d30beb0af0f$export$8b7aa55c66d5569e","$84a63d30beb0af0f$export$5412ac11713b72ad","$84a63d30beb0af0f$export$b2f4953d301981d5","$84a63d30beb0af0f$export$42c81a444fbfb5d4","$84a63d30beb0af0f$export$ef8b6d9133084f4e","$84a63d30beb0af0f$var$cachedRegions","$84a63d30beb0af0f$var$cachedWeekInfo","$84a63d30beb0af0f$var$getRegion","region","part","weekInfo","localeInst","day","$621d1537dc806c0f$exports","$84a63d30beb0af0f$export$ccc1b2479e7dd654","days","$84a63d30beb0af0f$export$5c333a116e949cdd","$84a63d30beb0af0f$export$a75f2bff57811055","$84a63d30beb0af0f$var$WEEKEND_DATA","$84a63d30beb0af0f$export$618d60ea299da42","start","end","$84a63d30beb0af0f$export$ee9d87258e1d19ed","$e13115b3b86b9007$export$bd4fb2bc8bb06fb","date","$e13115b3b86b9007$export$b4a036af3fc0b032","$05031860ba2f881f$exports","year","$e13115b3b86b9007$var$epochFromParts","month","day","hour","minute","second","millisecond","$e13115b3b86b9007$export$59c99f3515d3493f","ms","timeZone","$84a63d30beb0af0f$exports","$e13115b3b86b9007$var$getTimeZoneParts","$e13115b3b86b9007$var$formattersByTimeZone","formatter","parts","namedParts","part","$e13115b3b86b9007$var$DAYMILLIS","$e13115b3b86b9007$export$136f38efe7caf549","earlier","later","$e13115b3b86b9007$var$getValidWallTimes","absolute","$e13115b3b86b9007$var$isValidWallTime","$e13115b3b86b9007$export$5107c82f94518f5c","disambiguation","dateTime","$e13115b3b86b9007$export$b21e0b124e224484","offsetBefore","offsetAfter","valid","$e13115b3b86b9007$export$e67a095c620b86fe","$e13115b3b86b9007$export$1b96692a1ba042ac","offset","$c51b7e0106f45dea$exports","$e13115b3b86b9007$export$e57ff100d91bd4b9","$e13115b3b86b9007$export$d7f92bcd3596b086","$e13115b3b86b9007$export$93522d1a439f3617","time","$e13115b3b86b9007$export$d33f79e3ffc3dc83","calendar","calendarDate","copy","$19485913bea41f19$exports","$e13115b3b86b9007$export$84c95a83c799e074","$e13115b3b86b9007$export$538b00033cc11c75","$e13115b3b86b9007$export$83aac07b4c37b25","$e13115b3b86b9007$export$d9b67bc93c097491","$19485913bea41f19$var$ONE_HOUR","$19485913bea41f19$export$e16d8520af44a096","date","duration","mutableDate","days","$19485913bea41f19$var$addTimeFields","$19485913bea41f19$var$addYears","$19485913bea41f19$var$balanceYearMonth","$19485913bea41f19$var$constrainMonthDay","$19485913bea41f19$var$balanceDay","maxYear","isInverseEra","maxMonth","years","monthsInYear","$19485913bea41f19$export$c4e2ecac49351ef2","$19485913bea41f19$export$3e2544e88a25bff8","inverseDuration","key","$19485913bea41f19$export$4e2d2ead65e5f7e3","$19485913bea41f19$export$adaa4cf7ef1b65be","fields","$19485913bea41f19$export$e5d5e1c1822b6e56","value","mutableValue","$19485913bea41f19$export$7555de1e070510cb","$19485913bea41f19$var$balanceTime","time","$19485913bea41f19$var$nonNegativeMod","a","b","result","$19485913bea41f19$export$7ed87b6bc2506470","res","$19485913bea41f19$export$fe34d3a381cd7501","$19485913bea41f19$export$d52ced6badfb9a4c","field","amount","options","mutable","eras","eraIndex","$19485913bea41f19$var$cycleValue","$19485913bea41f19$export$dd02b3e0007dfe28","hours","min","max","isPM","round","div","$19485913bea41f19$export$96b1d28349274637","dateTime","ms","$e13115b3b86b9007$exports","$19485913bea41f19$export$6814caac34ca03c7","$19485913bea41f19$export$9a297d111fc86b79","plainDateTime","minDate","$05031860ba2f881f$exports","minAbsolute","maxDate","maxAbsolute","remainder","$19485913bea41f19$export$31b5430eb18be4f8","disambiguation","$1b358053f79e3a77$var$TIME_RE","$1b358053f79e3a77$var$DATE_RE","$1b358053f79e3a77$var$DATE_TIME_RE","$1b358053f79e3a77$var$ZONED_DATE_TIME_RE","$1b358053f79e3a77$var$ABSOLUTE_RE","$1b358053f79e3a77$var$DATE_TIME_DURATION_RE","$1b358053f79e3a77$var$requiredDurationTimeGroups","$1b358053f79e3a77$var$requiredDurationGroups","$1b358053f79e3a77$export$c9698ec7f05a07e1","value","m","$c51b7e0106f45dea$exports","$1b358053f79e3a77$var$parseNumber","$1b358053f79e3a77$export$6b862160d295c8e","date","$1b358053f79e3a77$export$588937bcd60ade55","year","era","$1b358053f79e3a77$export$fd7893f06e92a6a4","disambiguation","plainDateTime","$e13115b3b86b9007$exports","ms","hourOffset","$1b358053f79e3a77$var$offsetToString","$1b358053f79e3a77$export$4223de14708adc63","$1b358053f79e3a77$export$5adfdab05168c219","timeZone","$1b358053f79e3a77$export$8e384432362ed0f0","$84a63d30beb0af0f$exports","min","max","val","$1b358053f79e3a77$export$f59dee82248f5ad4","time","$1b358053f79e3a77$export$60dfd74aa96791bd","gregorianDate","$05031860ba2f881f$exports","offset","sign","offsetHours","offsetMinutes","offsetSeconds","stringOffset","$1b358053f79e3a77$export$bf79f1ebf4b18792","$1b358053f79e3a77$export$ecae829bb3747ea6","match","parseDurationGroup","group","isNegative","duration","$c51b7e0106f45dea$var$shiftArgs","args","calendar","$05031860ba2f881f$exports","era","eras","year","month","day","$c51b7e0106f45dea$export$99faa760c7908e4f","_$c51b7e0106f45dea$export$99faa760c7908e4f","#type","$19485913bea41f19$exports","duration","fields","field","amount","options","timeZone","$e13115b3b86b9007$exports","$1b358053f79e3a77$exports","b","$84a63d30beb0af0f$exports","$c51b7e0106f45dea$export$680ea196effce5f","_$c51b7e0106f45dea$export$680ea196effce5f","hour","minute","second","millisecond","$c51b7e0106f45dea$export$ca871e8dbb80966f","_$c51b7e0106f45dea$export$ca871e8dbb80966f","disambiguation","res","$c51b7e0106f45dea$export$d3b7288e7994edea","_$c51b7e0106f45dea$export$d3b7288e7994edea","offset","$a90e2192fa9a0f41$var$ERA_START_DATES","$a90e2192fa9a0f41$var$ERA_END_DATES","$a90e2192fa9a0f41$var$ERA_ADDENDS","$a90e2192fa9a0f41$var$ERA_NAMES","$a90e2192fa9a0f41$var$findEraFromGregorianDate","date","idx","year","month","day","$a90e2192fa9a0f41$var$toGregorian","eraAddend","$c51b7e0106f45dea$exports","$a90e2192fa9a0f41$export$b746ab2b60cdffbf","$05031860ba2f881f$exports","jd","era","gregorianDate","end","endYear","endMonth","endDay","maxYear","startMonth","startDay","cur","next","years","start","$a90e2192fa9a0f41$var$getMinimums","args","$0ce473f03e925476$var$BUDDHIST_ERA_START","$0ce473f03e925476$export$42d20a78301dee44","$05031860ba2f881f$exports","jd","gregorianDate","year","$c51b7e0106f45dea$exports","date","$0ce473f03e925476$var$toGregorian","args","era","$2dab1d4ea1fc722b$var$TAIWAN_ERA_START","$2dab1d4ea1fc722b$var$gregorianYear","date","$2dab1d4ea1fc722b$var$gregorianToTaiwan","year","y","$2dab1d4ea1fc722b$export$65e01080afcb0799","$05031860ba2f881f$exports","jd","extendedYear","era","$c51b7e0106f45dea$exports","$2dab1d4ea1fc722b$var$toGregorian","args","$4100faec94dc031c$var$PERSIAN_EPOCH","$4100faec94dc031c$var$MONTH_START","$4100faec94dc031c$export$37fccdbfd14c5939","jd","daysSinceEpoch","year","farvardin1","dayOfYear","month","day","$c51b7e0106f45dea$exports","date","$09f945753a699862$exports","$9dc8610ad30fbfe5$var$INDIAN_ERA_START","$9dc8610ad30fbfe5$var$INDIAN_YEAR_START","$9dc8610ad30fbfe5$export$39f31c639fa15726","$05031860ba2f881f$exports","jd","date","indianYear","yDay","leapMonth","indianMonth","indianDay","mDay","$c51b7e0106f45dea$exports","extendedYear","era","year","args","$fbcc6aba7cd7f47c$var$CIVIL_EPOC","$fbcc6aba7cd7f47c$var$ASTRONOMICAL_EPOC","$fbcc6aba7cd7f47c$var$UMALQURA_YEAR_START","$fbcc6aba7cd7f47c$var$UMALQURA_YEAR_END","$fbcc6aba7cd7f47c$var$UMALQURA_START_DAYS","$fbcc6aba7cd7f47c$var$islamicToJulianDay","epoch","year","month","day","$fbcc6aba7cd7f47c$var$julianDayToIslamic","calendar","jd","$c51b7e0106f45dea$exports","$fbcc6aba7cd7f47c$var$isLeapYear","$fbcc6aba7cd7f47c$export$2066795aadd37bfc","date","length","$fbcc6aba7cd7f47c$export$37f0887f2f9d22f7","args","$fbcc6aba7cd7f47c$var$UMALQURA_DATA","$fbcc6aba7cd7f47c$var$UMALQURA_MONTHLENGTH","$fbcc6aba7cd7f47c$var$UMALQURA_YEAR_START_TABLE","$fbcc6aba7cd7f47c$var$umalquraYearStart","$fbcc6aba7cd7f47c$var$umalquraMonthLength","idx","mask","$fbcc6aba7cd7f47c$var$umalquraMonthStart","i","$fbcc6aba7cd7f47c$var$umalquraYearLength","$fbcc6aba7cd7f47c$export$5baab4758c231076","c","yearStart","days","startDays","endDays","y","m","d","yearLength","monthLength","$1aa25867248bd474$var$HEBREW_EPOCH","$1aa25867248bd474$var$HOUR_PARTS","$1aa25867248bd474$var$DAY_PARTS","$1aa25867248bd474$var$MONTH_DAYS","$1aa25867248bd474$var$MONTH_FRACT","$1aa25867248bd474$var$MONTH_PARTS","$1aa25867248bd474$var$isLeapYear","year","$09f945753a699862$exports","$1aa25867248bd474$var$hebrewDelay1","months","parts","day","$1aa25867248bd474$var$hebrewDelay2","last","present","$1aa25867248bd474$var$startOfYear","$1aa25867248bd474$var$getDaysInYear","$1aa25867248bd474$var$getYearType","yearLength","$1aa25867248bd474$var$getDaysInMonth","month","yearType","$1aa25867248bd474$export$ca405048b8fb5af","jd","d","m","ys","dayOfYear","monthStart","$c51b7e0106f45dea$exports","date","previousDate","$b6b43214f5cff964$var$ETHIOPIC_EPOCH","$b6b43214f5cff964$var$COPTIC_EPOCH","$b6b43214f5cff964$var$AMETE_MIHRET_DELTA","$b6b43214f5cff964$var$ceToJulianDay","epoch","year","month","day","$b6b43214f5cff964$var$julianDayToCE","jd","$b6b43214f5cff964$var$getLeapDay","$b6b43214f5cff964$var$getDaysInMonth","$b6b43214f5cff964$export$26ba6eab5e20cd7d","era","$c51b7e0106f45dea$exports","date","$b6b43214f5cff964$export$d72e0c37005a4914","args","$b6b43214f5cff964$export$fe6243cbe1a4b7c1","$9d3159c6111892aa$export$dd0bbc9b26defe37","name","$0ce473f03e925476$exports","$b6b43214f5cff964$exports","$1aa25867248bd474$exports","$9dc8610ad30fbfe5$exports","$fbcc6aba7cd7f47c$exports","$a90e2192fa9a0f41$exports","$4100faec94dc031c$exports","$2dab1d4ea1fc722b$exports","$05031860ba2f881f$exports","$10afcf45c4831ff7$var$formatterCache","$10afcf45c4831ff7$export$ad991b66133851cf","locale","options","$10afcf45c4831ff7$var$getCachedDateFormatter","value","start","end","startParts","endParts","p","resolvedOptions","$10afcf45c4831ff7$var$hasBuggyResolvedHourCycle","$10afcf45c4831ff7$var$getResolvedHourCycle","$10afcf45c4831ff7$var$hour12Preferences","$10afcf45c4831ff7$var$hasBuggyHour12Behavior","pref","defaultHourCycle","cacheKey","b","numberFormatter","$10afcf45c4831ff7$var$_hasBuggyHour12Behavior","$10afcf45c4831ff7$var$_hasBuggyResolvedHourCycle","formatter","min","max","parseStringToDateValue","dateStr: string","referenceVal: DateValue","dateValue: DateValue","isZonedDateTime","referenceVal","dateValue","__internationalized_date","dateStr","isCalendarDateTime","toDate","tz: string","tz","CalendarDateTime","ZonedDateTime","hasTime","getDaysInMonth","date: Date | DateValue","date","year","month","isBefore","dateToCompare: DateValue","referenceDate: DateValue","dateToCompare","referenceDate","isAfter","isBeforeOrSame","isAfterOrSame","isBetweenInclusive","date: DateValue","start: DateValue","end: DateValue","start","end","isBetween","getLastFirstDayOfWeek","date: T","firstDayOfWeek: number","locale: string","day","locale","firstDayOfWeek","getNextLastDayOfWeek","lastDayOfWeek","isSameYearMonth","a: DateValue","b: DateValue","a","b","isSameYear","areAllDaysBetweenValid","isUnavailable: Matcher | undefined","isDisabled: Matcher | undefined","isHighlightable?: Matcher | undefined","isUnavailable","isDisabled","isHighlightable","dCurrent","dEnd","compareYearMonth","isMonthBetweenInclusive","isYearBetweenInclusive","getMonthsBetween","getYearsBetween","areAllMonthsBetweenValid","current","endMonth","areAllYearsBetweenValid","endYear","getDefaultDate","props: GetDefaultDateProps","defaultValue","defaultPlaceholder","granularity","props","calendarDateTimeGranularities","defaultFormatter","DateFormatter","calendar","CalendarDate","getDefaultTime","props: GetDefaultTimeProps","Time","chunk","arr: T[]","size: number","result","i","arr","size","getOptsByGranularity","granularity: Granularity","hourCycle: HourCycle","isTimeValue: boolean","opts: Intl.DateTimeFormatOptions","normalizeHourCycle","hourCycle","normalizeHour12","isTimeValue","opts","granularity","normalizeDateStep","props?: GetDefaultDateStepProps","defu","props","handleCalendarInitialFocus","calendar: HTMLElement","selectedDay","calendar","today","firstDay","getInputType","normalizeInputValue","date: DateValue | undefined","date","type","year","month","day","hour","minute","second","getDaysBetween","start: DateValue","end: DateValue","days: DateValue[]","dCurrent","start","dEnd","end","days","createMonth","props: CreateMonthProps","dateObj","weekStartsOn","fixedWeeks","locale","props","daysInMonth","require_date_comparators","datesArray","_","i","firstDayOfMonth","__internationalized_date","lastDayOfMonth","lastSunday","nextSaturday","lastMonthDays","nextMonthDays","totalDays","extraDays","startFrom","extraDaysArray","incr","allDays","weeks","require_date_utils","startOfDecade","dateObj: DateValue","endOfDecade","createDecade","props: SetDecadeProps","startIndex","endIndex","decadeArray","a: DateValue","b: DateValue","a","b","createYear","props: SetYearProps","numberOfMonths","pagedNavigation","createMonths","props: SetMonthProps","monthProps","months: Grid<DateValue>[]","months","nextMonth","createMonthGrid","props: CreateSelectProps","createYearGrid","props: CreateSelectProps & { yearsPerPage?: number, decadeAligned?: boolean }","yearsPerPage","decadeAligned","startYear: number","startYear","years","createYearRange","years: DateValue[]","current","createDateRange","dates: DateValue[]","dates","getWeekStartsOn","locale: string","monday","CalendarDate","getWeekNumber","date: DateValue","firstDayOfWeek?: DayOfWeek","jan1","date","usesISOWeek","firstDayOfWeek","firstWeekContainsDate","dayOfWeek","weekYear","week1Ref","week1Start","currentWeekStart","MS_PER_WEEK","require_date","__commonJSMin","useDateFormatter","initialLocale: string","opts: DateFormatterOptions","locale","vue","initialLocale","getLocale","setLocale","newLocale: string","newLocale","custom","date: Date","options: DateFormatterOptions","DateFormatter","opts","options","date","selectedDate","date: DateValue","includeTime","require_date_comparators","fullMonthAndYear","fullMonth","getMonths","defaultDate","__internationalized_date","item","fullYear","toParts","options?: DateFormatterOptions","dayOfWeek","length: DateFormatterOptions['weekday']","length","dayPeriod","value","p","defaultPartOptions: DateFormatterOptions","part","dateObj: DateValue","type: Intl.DateTimeFormatPartTypes","defaultPartOptions","dateObj","type","useDirection","dir?: Ref<Direction | undefined>","context","require_ConfigProvider_ConfigProvider","vue","dir","useEmitAsProps","emit: (name: Name, ...args: any[]) => void","vm","vue","events","result: Record<string, any>","ev","result","arg","emit","useFilter","options?: MaybeRef<Intl.CollatorOptions>","computedOptions","vue","options","collator","string: string","substring: string","substring","string","scan","sliceLen","slice","count","useFocusGuards","vue","cleanupFn","isClient","edgeGuards","createFocusGuard","node","element","useFormControl","el: MaybeElementRef","vue","el","__vueuse_core","useForwardExpose","instance","vue","currentRef","currentElement","resolveCurrentElement","__vueuse_core","localExpose: Record<string, any> | null","ret: Record<string, any>","key","ret","localExpose","forwardRef","ref: Element | T | null","ref","childExposed","merged","useForwardProps","props: MaybeRefOrGetter<T>","vm","vue","defaultProps","prev","curr","defaultValue","refProps","props","preservedProps","assignedProps","key","useForwardPropsEmits","props: MaybeRefOrGetter<T>","emit?: (name: Name, ...args: any[]) => void","parsedProps","require_shared_useForwardProps","props","emitsAsProps","emit","require_shared_useEmitAsProps","vue","useForwardRef","instance","vue","handleRefChange","ref: Element | ComponentPublicInstance | null","ref","useGraceArea","triggerElement: Ref<HTMLElement | undefined>","containerElement: Ref<HTMLElement | undefined>","isPointerInTransit","__vueuse_shared","pointerGraceArea","vue","pointerExit","handleRemoveGraceArea","handleCreateGraceArea","event: PointerEvent","hoverTarget: HTMLElement | undefined","hoverTarget","currentTarget","event","exitPoint","exitSide","getExitSideFromRect","paddedExitPoints","getPaddedExitPoints","hoverTargetPoints","getPointsFromRect","graceArea","getHull","cleanupFn","triggerElement","containerElement","handleTriggerLeave","handleContentLeave","handleTrackPointerGrace","target","pointerPosition","hasEnteredTarget","isPointerOutsideGraceArea","isPointInPolygon","isAnotherGraceAreaTrigger","point: Point","rect: DOMRect","top","rect","point","bottom","right","left","exitPoint: Point","exitSide: Side","padding","paddedExitPoints: Point[]","polygon: Polygon","x","y","inside","i","j","polygon","xi","yi","xj","yj","points: Readonly<Array<P>>","newPoints: Array<P>","points","newPoints","a: Point","b: Point","a","b","getHullPresorted","upperHull: Array<P>","p","upperHull","q","r","lowerHull: Array<P>","lowerHull","require_es5","__commonJSMin","exports","getDefaultParent","originalTarget","sampleTarget","counterMap","uncontrolledNodes","markerMap","lockCount","unwrapHost","node","correctTargets","parent","targets","target","correctedTarget","x","applyAttributeToOthers","parentNode","markerName","controlAttribute","markerCounter","hiddenNodes","elementsToKeep","elementsToStop","keep","el","deep","attr","alreadyHidden","counterValue","markerValue","e","hideOthers","activeParentNode","inertOthers","supportsInert","suppressOthers","useHideOthers","target: MaybeElementRef","undo: ReturnType<typeof hideOthers>","vue","__vueuse_core","target","el","isInsideClosedPopover","undo","aria_hidden","count","useId","deterministicId?: string | null | undefined","prefix","deterministicId","id: string","configProviderContext","require_ConfigProvider_ConfigProvider","id","vue","useKbd","useTestKbd","kbd","acc","key","value","useLocale","locale?: Ref<string | undefined>","context","require_ConfigProvider_ConfigProvider","vue","locale","useSelectionBehavior","modelValue: Ref<T | T[]>","props: UnwrapNestedRefs<{ multiple?: boolean, selectionBehavior?: 'toggle' | 'replace' }>","firstValue","vue","onSelectItem","val: T","condition: (existingValue: T) => boolean","props","modelValue","val","index","v","condition","_","i","handleMultipleReplace","intent: 'first' | 'last' | 'prev' | 'next'","currentElement: HTMLElement | Element | null","getItems: () => { ref: HTMLElement, value?: any }[]","options: any[]","lastValue","getItems","currentElement","value: T[] | null","intent","value","require_shared_arrays","options","useSize","element: MaybeElementRef","size","vue","width","height","el","__vueuse_core","element","resizeObserver","entries","entry","width: number","height: number","borderSizeEntry","borderSize","width$1","height$1","useStateMachine","initialState: MachineState<M>","machine: M & Machine<MachineState<M>>","state","vue","initialState","reducer","event: MachineEvent<M>","machine","event","useTypeahead","callback?: (search: string) => void","search","__vueuse_shared","key: string","items: { ref: HTMLElement, value?: any }[]","key","callback","currentItem","require_shared_getActiveElement","itemsWithTextValue","items","item","currentMatch","values","nextMatch","getNextMatch","newItem","wrapArray","array: T[]","startIndex: number","array","_","index","startIndex","values: string[]","search: string","currentMatch?: string","normalizedSearch","char","currentMatchIndex","wrappedValues","v","value","withDefault","WrappedComponent: T","options?: MountingOptions<any>","WrappedComponent","_","ctx","optionProps","options","forwardRef","require_shared_useForwardExpose","mergedProps","vue","require_shared","__commonJSMin","usePresence","present: Ref<boolean>","node: Ref<HTMLElement | undefined>","stylesRef","vue","prevAnimationNameRef","prevPresentRef","present","initialState","timeoutId: number | undefined","ownerWindow","node","defaultWindow","state","dispatch","require_shared_useStateMachine","dispatchCustomEvent","name: 'enter' | 'after-enter' | 'leave' | 'after-leave'","isClient","customEvent","name","currentPresent","prevPresent","hasPresentChanged","prevAnimationName","currentAnimationName","getAnimationName","handleAnimationEnd","event: AnimationEvent","isCurrentAnimation","event","directionName","currentFillMode","timeoutId","handleAnimationStart","watcher","newNode","oldNode","stateWatcher","node?: HTMLElement","Presence_default","vue","props","slots","expose","present","forceMount","node","isPresent","require_Presence_usePresence","children","require_shared_renderSlotFragments","instance","componentName","line","v","el","__vueuse_core","Slot","vue","_","attrs","slots","children","require_shared_renderSlotFragments","firstNonCommentChildrenIndex","child","Comment","firstNonCommentChildren","mergedProps","cloned","SELF_CLOSING_TAGS","Primitive","vue","props","attrs","slots","asTag","Slot","usePrimitiveElement","primitiveElement","vue","currentElement","__vueuse_core","injectCollapsibleRootContext","provideCollapsibleRootContext","require_shared_createContext","props","__props","emit","__emit","open","__vueuse_core","disabled","unmountOnHide","vue","__expose","require_shared_useForwardExpose","require_Primitive_Primitive","as","_ctx","props","__props","emits","__emit","rootContext","require_Collapsible_CollapsibleRoot","require_shared_useId","presentRef","vue","forwardRef","currentElement","require_shared_useForwardExpose","width","height","isOpen","isMountAnimationPrevented","currentStyle","node","rect","skipAnimation","__vueuse_core","ev","require_Presence_Presence","forceMount","present","require_Primitive_Primitive","$attrs","as","_ctx","props","__props","require_shared_useForwardExpose","rootContext","require_Collapsible_CollapsibleRoot","vue","require_Primitive_Primitive","as","_ctx","validateProps","type","defaultValue","modelValue","value","getDefaultType","getDefaultValue","useSingleOrMultipleValue","props: P","emits: (name: Name, ...args: any[]) => void","vue","props","__vueuse_core","emits","changeModelValue","value: AcceptableValue","ohash","modelValueArray","require_shared_isValueEqualOrExist","index","i","isSingle","injectAccordionRootContext","provideAccordionRootContext","require_shared_createContext","props","__props","emits","__emit","dir","disabled","unmountOnHide","vue","direction","require_shared_useDirection","modelValue","changeModelValue","isSingle","require_shared_useSingleOrMultipleValue","forwardRef","parentElement","require_shared_useForwardExpose","require_Primitive_Primitive","asChild","as","_ctx","AccordionItemState","AccordionItemState$1","injectAccordionItemContext","provideAccordionItemContext","require_shared_createContext","props","__props","rootContext","require_Accordion_AccordionRoot","open","vue","disabled","dataDisabled","dataState","__expose","currentRef","currentElement","require_shared_useForwardExpose","handleArrowKey","e","target","item","require_shared_useArrowNavigation","require_Collapsible_CollapsibleRoot","_ctx","props","__props","rootContext","require_Accordion_AccordionRoot","itemContext","require_Accordion_AccordionItem","require_shared_useForwardExpose","vue","require_Collapsible_CollapsibleContent","as","_cache","$event","_ctx","props","__props","rootContext","require_Accordion_AccordionRoot","itemContext","require_Accordion_AccordionItem","require_shared_useForwardExpose","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_Accordion_AccordionRoot","itemContext","require_Accordion_AccordionItem","require_shared_useId","changeItem","triggerDisabled","vue","require_Collapsible_CollapsibleTrigger","_ctx","injectDialogRootContext","provideDialogRootContext","require_shared_createContext","props","__props","emit","__emit","open","__vueuse_core","triggerElement","vue","contentElement","modal","value","_ctx","props","__props","require_shared_useForwardExpose","rootContext","require_Dialog_DialogRoot","vue","require_Primitive_Primitive","as","_cache","$event","_ctx","POINTER_DOWN_OUTSIDE","FOCUS_OUTSIDE","isLayerExist","layerElement: HTMLElement","targetElement: HTMLElement","targetElement","targetLayer","mainLayer","layerElement","nodeList","usePointerDownOutside","onPointerDownOutside?: (event: PointerDownOutsideEvent) => void","element?: Ref<HTMLElement | undefined>","enabled: MaybeRefOrGetter<boolean>","ownerDocument: Document","element","isPointerInsideDOMTree","vue","handleClickRef","cleanupFn","isClient","enabled","handlePointerDown","event: PointerEvent","target","event","handleAndDispatchPointerDownOutsideEvent","require_shared_handleAndDispatchCustomEvent","onPointerDownOutside","eventDetail","ownerDocument","timerId","useFocusOutside","onFocusOutside?: (event: FocusOutsideEvent) => void","isFocusInsideDOMTree","handleFocus","event: FocusEvent","onFocusOutside","context","vue","props","__props","emits","__emit","forwardRef","layerElement","require_shared_useForwardExpose","ownerDocument","layers","index","isBodyPointerEventsDisabled","isPointerEventsEnabled","localLayers","highestLayerWithOutsidePointerEventsDisabled","highestLayerWithOutsidePointerEventsDisabledIndex","pointerDownOutside","require_DismissableLayer_utils","event","isPointerDownOnBranch","branch","focusOutside","__vueuse_core","element","disableOutsidePointerEvents","_","onCleanup","require_shared_nullish","cleanupFn","require_Primitive_Primitive","asChild","as","_ctx","props","__props","forwardRef","currentElement","require_shared_useForwardExpose","vue","require_DismissableLayer_DismissableLayer","require_Primitive_Primitive","_ctx","useFocusStackState","__vueuse_core","vue","createFocusScopesStack","stack","focusScope: FocusScopeAPI","activeFocusScope","focusScope","arrayRemove","array: T[]","item: T","updatedArray","array","index","item","AUTOFOCUS_ON_MOUNT","AUTOFOCUS_ON_UNMOUNT","EVENT_OPTIONS","focusFirst","candidates: HTMLElement[]","select","previouslyFocusedElement","require_shared_getActiveElement","candidate","candidates","focus","getTabbableEdges","container: HTMLElement","getTabbableCandidates","container","first","findVisible","last","nodes: HTMLElement[]","walker","node: any","isHiddenInput","node","nodes","elements: HTMLElement[]","element","elements","isHidden","node: HTMLElement","upTo","isSelectableInput","element: any","element?: FocusableTarget | null","props","__props","emits","__emit","currentRef","currentElement","require_shared_useForwardExpose","lastFocusedElementRef","vue","focusScopesStack","require_FocusScope_stack","focusScope","cleanupFn","__vueuse_shared","container","handleFocusIn","event","target","require_FocusScope_utils","handleFocusOut","relatedTarget","handleMutations","mutations","lastFocusedElement","m","mutationObserver","previouslyFocusedElement","require_shared_getActiveElement","mountEvent","ev","unmountEvent","unmountEventHandler","handleKeyDown","isTabKey","focusedElement","first","last","require_Primitive_Primitive","asChild","as","_ctx","ITEM_SELECT","SELECTION_KEYS","FIRST_KEYS","LAST_KEYS","FIRST_LAST_KEYS","SUB_OPEN_KEYS: Record<Direction, string[]>","SUB_CLOSE_KEYS: Record<Direction, string[]>","getOpenState","open: boolean","open","isIndeterminate","checked?: CheckedState","checked","getCheckedState","checked: CheckedState","focusFirst","candidates: HTMLElement[]","PREVIOUSLY_FOCUSED_ELEMENT","require_shared_getActiveElement","candidate","candidates","isPointInPolygon","point: Point","polygon: Polygon","x","y","point","inside","i","j","polygon","xi","yi","xj","yj","isPointerInGraceArea","event: PointerEvent","area?: Polygon","area","cursorPos","event","isMouseEvent","DEFAULT_TITLE_NAME","DEFAULT_CONTENT_NAME","useWarning","titleName","contentName","componentLink","titleId","descriptionId","contentElement","TITLE_MESSAGE","DESCRIPTION_MESSAGE","vue","describedById","props","__props","emits","__emit","rootContext","require_Dialog_DialogRoot","forwardRef","contentElement","require_shared_useForwardExpose","require_shared_useId","vue","require_shared_getActiveElement","require_FocusScope_FocusScope","_cache","$event","require_DismissableLayer_DismissableLayer","as","asChild","disableOutsidePointerEvents","require_Menu_utils","$attrs","_ctx","props","__props","emits","__emit","rootContext","require_Dialog_DialogRoot","emitsAsProps","require_shared_useEmitAsProps","forwardRef","currentElement","require_shared_useForwardExpose","require_shared_useHideOthers","vue","require_Dialog_DialogContentImpl","_cache","event","originalEvent","ctrlLeftClick","_ctx","props","__props","emits","__emit","emitsAsProps","require_shared_useEmitAsProps","require_shared_useForwardExpose","rootContext","require_Dialog_DialogRoot","hasInteractedOutsideRef","vue","hasPointerDownOutsideRef","require_Dialog_DialogContentImpl","_cache","event","target","_ctx","props","__props","emits","__emit","rootContext","require_Dialog_DialogRoot","emitsAsProps","require_shared_useEmitAsProps","forwardRef","require_shared_useForwardExpose","vue","require_Presence_Presence","forceMount","require_Dialog_DialogContentModal","$attrs","_ctx","require_Dialog_DialogContentNonModal","props","__props","require_shared_useForwardExpose","rootContext","require_Dialog_DialogRoot","vue","require_Primitive_Primitive","_ctx","rootContext","require_Dialog_DialogRoot","require_shared_useBodyScrollLock","require_shared_useForwardExpose","vue","require_Primitive_Primitive","as","asChild","_cache","_ctx","rootContext","require_Dialog_DialogRoot","forwardRef","require_shared_useForwardExpose","vue","require_Presence_Presence","forceMount","require_Dialog_DialogOverlayImpl","$attrs","as","asChild","_ctx","isMounted","__vueuse_core","vue","forceMount","to","disabled","defer","_ctx","props","__props","vue","require_Teleport_Teleport","_ctx","props","__props","rootContext","require_Dialog_DialogRoot","require_shared_useForwardExpose","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_Dialog_DialogRoot","forwardRef","currentElement","require_shared_useForwardExpose","require_shared_useId","vue","require_Primitive_Primitive","as","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Dialog_DialogClose","_ctx","injectAlertDialogContentContext","provideAlertDialogContentContext","require_shared_createContext","props","__props","emits","__emit","emitsAsProps","require_shared_useEmitAsProps","require_shared_useForwardExpose","cancelElement","vue","el","require_Dialog_DialogContent","_cache","_ctx","props","__props","contentContext","require_AlertDialog_AlertDialogContent","forwardRef","currentElement","require_shared_useForwardExpose","vue","require_Dialog_DialogClose","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Dialog_DialogDescription","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Dialog_DialogOverlay","_ctx","props","__props","vue","require_Teleport_Teleport","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","require_shared_useForwardExpose","vue","require_Dialog_DialogRoot","slotProps","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Dialog_DialogTitle","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Dialog_DialogTrigger","_ctx","props","__props","forwardRef","require_shared_useForwardExpose","aspect","vue","require_Primitive_Primitive","asChild","as","$attrs","_ctx","ITEM_DATA_ATTR","useCollection","options: { key?: string, isProvider?: boolean }","key","isProvider","options","injectionKey","context: CollectionContext<ItemData>","itemMap","vue","context","getItems","includeDisabledItem","collectionNode","orderedNodes","orderedItems","a","b","i","CollectionSlot","_","slots","attrs","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","Slot","CollectionItem","props","cleanupFn","reactiveItems","itemMapSize","vue","require_Primitive_Primitive","as","asChild","feature","_ctx","props","__props","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","valueState","vue","cur","prev","input","inputProto","setValue","inputEvent","changeEvent","require_VisuallyHidden_VisuallyHidden","$attrs","props","__props","isFormArrayEmptyAndRequired","vue","parsedValue","obj","index","key","value","require_VisuallyHidden_VisuallyHiddenInputBubble","name","$attrs","parsed","queryCheckedElement","parentEl: HTMLElement | null","parentEl","valueComparator","value: T | T[] | undefined","currentValue: T","comparator?: string | ((a: T, b: T) => boolean)","value","val","compare","currentValue","comparator","value?: T","currentValue?: T","ohash","ENTRY_FOCUS","EVENT_OPTIONS","MAP_KEY_TO_FOCUS_INTENT: Record<string, FocusIntent>","getDirectionAwareKey","key: string","dir?: Direction","dir","key","getFocusIntent","event: KeyboardEvent","orientation?: Orientation","event","orientation","MAP_KEY_TO_FOCUS_INTENT","focusFirst","candidates: HTMLElement[]","preventScroll","PREVIOUSLY_FOCUSED_ELEMENT","require_shared_getActiveElement","candidate","candidates","wrapArray","array: T[]","startIndex: number","array","_","index","startIndex","injectListboxRootContext","provideListboxRootContext","require_shared_createContext","props","__props","emits","__emit","multiple","highlightOnHover","orientation","disabled","selectionBehavior","propDir","vue","getItems","require_Collection_Collection","handleTypeaheadSearch","require_shared_useTypeahead","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","kbd","require_shared_useKbd","dir","require_shared_useDirection","isFormControl","require_shared_useFormControl","firstValue","isUserAction","focusable","modelValue","__vueuse_core","onValueChange","val","modelArray","index","i","require_Listbox_utils","highlightedElement","previousElement","isVirtual","isComposing","virtualFocusHook","virtualKeydownHook","virtualHighlightHook","getCollectionItem","changeHighlight","el","scrollIntoView","focus","highlightedItem","highlightItem","value","item","onKeydownEnter","event","onKeydownTypeAhead","isMetaKey","collection","values","lastItem","onCompositionStart","onCompositionEnd","highlightFirstItem","onKeydownNavigation","onLeave","onEnter","entryFocusEvent","intent","require_RovingFocus_utils","currentIndex","handleMultipleReplace","targetEl","lastValue","require_shared_arrays","highlightSelected","scroll","__vueuse_shared","hasHighlightedOnMount","__expose","require_Primitive_Primitive","as","asChild","_cache","target","_ctx","name","require_VisuallyHidden_VisuallyHiddenInput","required","CollectionSlot","require_Collection_Collection","rootContext","require_Listbox_ListboxRoot","isClickFocus","__vueuse_shared","vue","require_Primitive_Primitive","as","asChild","_cache","$event","ev","event","_ctx","props","__props","emits","__emit","modelValue","__vueuse_core","rootContext","require_Listbox_ListboxRoot","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","disabled","vue","activedescendant","isComposing","handleCompositionStart","handleCompositionEnd","require_shared_useComposing","event","onCompositionStart","handleInput","handleKeydownNavigation","handleKeydownEnter","require_Primitive_Primitive","as","asChild","_ctx","injectListboxGroupContext","provideListboxGroupContext","require_shared_createContext","props","__props","id","require_shared_useId","vue","require_Primitive_Primitive","_ctx","props","__props","groupContext","require_Listbox_ListboxGroup","vue","require_Primitive_Primitive","_ctx","LISTBOX_SELECT","injectListboxItemContext","provideListboxItemContext","require_shared_createContext","props","__props","emits","__emit","id","require_shared_useId","CollectionItem","require_Collection_Collection","forwardRef","currentElement","require_shared_useForwardExpose","rootContext","require_Listbox_ListboxRoot","isHighlighted","vue","isSelected","require_Listbox_utils","disabled","handleSelect","ev","handleSelectCustomEvent","eventDetail","require_shared_handleAndDispatchCustomEvent","value","require_Primitive_Primitive","$attrs","as","asChild","_cache","_ctx","props","__props","require_shared_useForwardExpose","itemContext","require_Listbox_ListboxItem","vue","require_Primitive_Primitive","_ctx","createLazyMeasurementsView","count","flat","getItemKey","cache","target","prop","receiver","c","i","v","s","memo","getDeps","fn","opts","deps","result","isInitial","memoizedFunction","depTime","newDeps","dep","index","resultTime","notUndefined","value","msg","approxEqual","a","b","debounce","targetWindow","ms","timeoutId","args","_isIOSResult","isIOSWebKit","mtp","_resetIOSDetectionForTests","getRect","element","offsetWidth","offsetHeight","defaultKeyExtractor","index","defaultRangeExtractor","range","start","len","arr","i","observeElementRect","instance","cb","targetWindow","handler","rect","width","height","observer","entries","run","entry","box","addEventListenerOptions","observeWindowRect","supportsScrollend","observeOffset","readOffset","registerScrollendEvent","offset","fallback","debounce","createHandler","isScrolling","endHandler","observeElementOffset","el","horizontal","isRtl","observeWindowOffset","win","measureElement","key","cachedSize","scrollWithAdjustments","adjustments","behavior","_b","_a","windowScroll","elementScroll","Virtualizer","opts","_c","_ro","get","node","cacheKey","cachedNode","target","merged","v","prevOptions","anchor","followOnAppend","edgeKeysChanged","prevCount","nextCount","measurements","prevFirstKey","prevLastKey","item","anchorResolved","anchorDelta","anchorKey","anchorOffset","newMeasurements","count","getItemKey","idx","anchorItem","newOffset","sync","memo","d","scrollElement","cached","scrollEl","onTouchStart","onTouchEnd","_offset","cur","max","delta","furthestMeasurementsFound","furthestMeasurements","m","measurement","previousFurthestMeasurement","a","b","paddingStart","scrollMargin","enabled","lanes","laneAssignmentMode","_itemSizeCacheVersion","itemSizeCache","min","gap","need","flat","next","runningStart","prevIdx","measuredSize","size","view","createLazyMeasurementsView","laneLastIndex","cachedLane","lane","shouldCacheLane","prevIndex","prevInLane","furthestMeasurement","end","outerSize","scrollOffset","calculateRange","startIndex","endIndex","rangeExtractor","overscan","attributeName","indexStr","scrollIndex","bufferSize","minIndex","maxIndex","prevNode","itemStart","itemSize","wasAtEnd","prevTotalSize","shouldAdjustScroll","indexes","virtualItems","k","useFlat","findNearestBinarySearch","notUndefined","doc","threshold","toOffset","align","maxOffset","now","initialAlign","offsetInfo","lastIdx","endByLane","val","snapshot","targetOffset","STABLE_FRAMES","targetChanged","approxEqual","viewport","distance","keepSmooth","low","high","getCurrentValue","value","middle","currentValue","lastIndex","getStart","getEnd","endPerLane","pos","startPerLane","useVirtualizerBase","options","virtualizer","Virtualizer","unref","state","shallowRef","cleanup","watch","el","instance","sync","triggerRef","onScopeDispose","useVirtualizer","computed","observeElementRect","observeElementOffset","elementScroll","useWindowVirtualizer","observeWindowRect","observeWindowOffset","windowScroll","props","__props","slots","vue","rootContext","require_Listbox_ListboxRoot","parentEl","__vueuse_core","getItems","require_Collection_Collection","padding","el","styles","virtualizer","__tanstack_vue_virtual","index","virtualizedItems","item","defaultNode","targetNode","child","event","scroll","option","require_Listbox_utils","i","value","search","__vueuse_shared","optionsWithMetadata","parseTextContent","handleMultipleReplace","intent","lastValue","require_shared_arrays","isMetaKey","require_RovingFocus_utils","items","currentIndex","require_shared_getActiveElement","currentMatch","filteredOptions","next","require_shared_useTypeahead","nextMatch","is","injectPopperRootContext","providePopperRootContext","require_shared_createContext","anchor","vue","element","_ctx","props","__props","forwardRef","currentElement","require_shared_useForwardExpose","rootContext","require_Popper_PopperRoot","vue","require_Primitive_Primitive","as","asChild","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Primitive_Primitive","width","height","asChild","_ctx","rounded","_hoisted_2","_hoisted_1","isNotNull","value: T | null","value","transformOrigin","options: {\n  arrowWidth: number\n  arrowHeight: number\n}","options","data","placement","rects","middlewareData","isArrowHidden","arrowWidth","arrowHeight","placedSide","placedAlign","getSideAndAlignFromPlacement","noArrowAlign","arrowXCenter","arrowYCenter","x","y","placement: Placement","side","align","clamp","start","value","end","max","min","evaluate","param","getSide","placement","getAlignment","getOppositeAxis","axis","getAxisLength","getSideAxis","firstChar","getAlignmentAxis","getAlignmentSides","rects","rtl","alignment","alignmentAxis","length","mainAlignmentSide","getOppositePlacement","getExpandedPlacements","oppositePlacement","getOppositeAlignmentPlacement","getSideList","side","isStart","rlPlacement","lrPlacement","tbPlacement","btPlacement","getOppositeAxisPlacements","flipAlignment","direction","list","oppositeSideMap","expandPaddingObject","padding","getPaddingObject","rectToClientRect","rect","x","y","width","height","sides","alignments","placements","round","floor","createCoords","init_floating_ui_utils","__esmMin","acc","v","computeCoordsFromPlacement","_ref","placement","rtl","reference","floating","sideAxis","getSideAxis","alignmentAxis","getAlignmentAxis","alignLength","getAxisLength","side","getSide","isVertical","commonX","commonY","commonAlign","coords","getAlignment","detectOverflow","state","options","_await$platform$isEle","x","y","platform","rects","elements","strategy","boundary","rootBoundary","elementContext","altBoundary","padding","evaluate","paddingObject","getPaddingObject","element","clippingClientRect","rectToClientRect","rect","offsetParent","offsetScale","elementClientRect","getPlacementList","alignment","autoAlignment","allowedPlacements","getOppositeAlignmentPlacement","getSideOffsets","overflow","isAnySideFullyClipped","sides","getBoundingRect","minX","min","minY","maxX","max","maxY","getRectsByLine","sortedRects","b","groups","prevRect","i","convertValueToCoords","mainAxisMulti","originSides","crossAxisMulti","rawValue","mainAxis","crossAxis","MAX_RESET_COUNT","computePosition","arrow","autoPlacement","flip","hide","inline","offset","shift","limitShift","size","init_floating_ui_core","__esmMin","init_floating_ui_utils","config","middleware","platformWithDetectOverflow","statefulPlacement","resetCount","middlewareData","currentMiddleware","name","fn","nextX","nextY","data","reset","axis","length","arrowDimensions","isYAxis","minProp","maxProp","clientProp","endDiff","startDiff","arrowOffsetParent","clientSize","centerToReference","largestPossiblePadding","minPadding","maxPadding","min$1","center","clamp","shouldAddOffset","alignmentOffset","_middlewareData$autoP","_middlewareData$autoP2","_placementsThatFitOnE","placements","detectOverflowOptions","placements$1","currentIndex","currentPlacement","alignmentSides","getAlignmentSides","currentOverflows","allOverflows","nextPlacement","placementsSortedByMostSpace","d","acc","v","a","resetPlacement","_middlewareData$arrow","_middlewareData$flip","initialPlacement","checkMainAxis","checkCrossAxis","specifiedFallbackPlacements","fallbackStrategy","fallbackAxisSideDirection","flipAlignment","initialSideAxis","isBasePlacement","fallbackPlacements","getOppositePlacement","getExpandedPlacements","hasFallbackAxisSideDirection","getOppositeAxisPlacements","overflows","overflowsData","_middlewareData$flip2","_overflowsData$filter","nextIndex","_overflowsData$filter2","currentSideAxis","offsets","nativeClientRects","clientRects","fallback","getBoundingClientRect","firstRect","lastRect","isTop","top","bottom","left","right","width","height","isLeftSide","maxRight","minLeft","measureRects","resetRects","_middlewareData$offse","diffCoords","limiter","getOppositeAxis","mainAxisCoord","crossAxisCoord","minSide","maxSide","limitedCoords","rawOffset","computedOffset","len","limitMin","limitMax","_middlewareData$offse2","isOriginSide","_state$middlewareData","_state$middlewareData2","apply","heightSide","widthSide","maximumClippingHeight","maximumClippingWidth","overflowAvailableHeight","overflowAvailableWidth","noShift","availableHeight","availableWidth","xMin","xMax","yMin","yMax","nextDimensions","hasWindow","getNodeName","node","isNode","getWindow","_node$ownerDocument","getDocumentElement","_ref","value","isElement","isHTMLElement","isShadowRoot","isOverflowElement","element","overflow","overflowX","overflowY","display","getComputedStyle","isTableElement","isTopLayer","isContainingBlock","elementOrCss","css","isNotNone","isWebKit","willChangeRe","containRe","getContainingBlock","currentNode","getParentNode","isLastTraversableNode","isWebKitValue","getNodeScroll","result","getNearestOverflowAncestor","parentNode","getOverflowAncestors","list","traverseIframes","_node$ownerDocument2","scrollableAncestor","isBody","win","frameElement","getFrameElement","init_floating_ui_utils_dom","__esmMin","getCssDimensions","element","css","getComputedStyle","width","height","hasOffset","isHTMLElement","offsetWidth","offsetHeight","shouldFallback","round","unwrapElement","isElement","getScale","domElement","createCoords","rect","$","x","y","getVisualOffsets","win","getWindow","isWebKit","noOffsets","shouldAddVisualOffsets","isFixed","floatingOffsetParent","getBoundingClientRect","includeScale","isFixedStrategy","offsetParent","clientRect","scale","visualOffsets","offsetWin","currentWin","currentIFrame","getFrameElement","iframeScale","iframeRect","left","top","rectToClientRect","getWindowScrollBarX","leftScroll","getNodeScroll","getDocumentElement","getHTMLOffset","documentElement","scroll","htmlRect","convertOffsetParentRelativeRectToViewportRelativeRect","_ref","elements","strategy","topLayer","isTopLayer","offsets","isOffsetParentAnElement","getNodeName","isOverflowElement","offsetRect","htmlOffset","getClientRects","getDocumentRect","html","body","max","getViewportRect","visualViewport","visualViewportBased","windowScrollbarX","doc","bodyStyles","bodyMarginInline","clippingStableScrollbarWidth","SCROLLBAR_MAX","getInnerBoundingClientRect","getClientRectFromClippingAncestor","clippingAncestor","hasFixedPositionAncestor","stopNode","parentNode","getParentNode","isLastTraversableNode","getClippingElementAncestors","cache","cachedResult","result","getOverflowAncestors","el","currentContainingBlockComputedStyle","elementIsFixed","currentNode","computedStyle","currentNodeIsContaining","isContainingBlock","ancestor","getClippingRect","boundary","rootBoundary","clippingAncestors","firstRect","right","bottom","i","min","getDimensions","getRectRelativeToOffsetParent","setLeftRTLScrollbarOffset","isStaticPositioned","getTrueOffsetParent","polyfill","rawOffsetParent","getOffsetParent","svgOffsetParent","isTableElement","getContainingBlock","isRTL","rectsAreEqual","a","b","observeMove","onMove","io","timeoutId","root","cleanup","_io","refresh","skip","threshold","elementRectForRootMargin","insetTop","floor","insetRight","insetBottom","insetLeft","options","isFirstUpdate","handleObserve","entries","ratio","autoUpdate","reference","floating","update","ancestorScroll","ancestorResize","elementResize","layoutShift","animationFrame","referenceEl","ancestors","cleanupIo","reobserveFrame","resizeObserver","firstEntry","_resizeObserver","frameId","prevRefRect","frameLoop","nextRefRect","_resizeObserver2","getElementRects","platform","detectOverflow","offset","autoPlacement","shift","flip","size","hide","arrow","inline","limitShift","computePosition","init_floating_ui_dom","__esmMin","init_floating_ui_core","init_floating_ui_utils","init_floating_ui_utils_dom","data","getOffsetParentFn","getDimensionsFn","floatingDimensions","mergedOptions","platformWithCache","require_lib","__commonJSMin","exports","Vue","key","target","val","floating_ui_vue_esm_exports","__export","arrow","autoPlacement","autoUpdate","computePosition","detectOverflow","flip","getOverflowAncestors","hide","inline","limitShift","offset","platform","shift","size","useFloating","isComponentPublicInstance","target","unwrapElement","element","isNode","getNodeName","toValue","source","options","args","getDPR","roundByDPR","value","dpr","reference","floating","whileElementsMountedOption","openOption","_toValue","middlewareOption","placementOption","_toValue2","strategyOption","_toValue3","transformOption","_toValue4","referenceElement","floatingElement","x","y","strategy","placement","middlewareData","isPositioned","floatingStyles","initialStyles","xVal","yVal","whileElementsMountedCleanup","update","open","position","cleanup","attach","reset","import_vue_demi","init_floating_ui_vue_esm","__esmMin","init_floating_ui_dom","init_floating_ui_utils_dom","PopperContentPropsDefaultValue","injectPopperContentContext","providePopperContentContext","require_shared_createContext","props","__props","emits","__emit","rootContext","require_Popper_PopperRoot","forwardRef","contentElement","require_shared_useForwardExpose","floatingRef","vue","arrow","arrowWidth","arrowHeight","require_shared_useSize","desiredPlacement","collisionPadding","boundary","detectOverflowOptions","require_Popper_utils","flipOptions","computedMiddleware","__vueuse_core","__floating_ui_vue","elements","rects","availableWidth","availableHeight","anchorWidth","anchorHeight","contentStyle","reference","floatingStyles","placement","isPositioned","middlewareData","update","args","placedSide","placedAlign","shouldHideArrow","cannotCenterArrow","contentZIndex","arrowX","arrowY","element","require_Primitive_Primitive","$attrs","as","_ctx","OPPOSITE_SIDE","forwardRef","require_shared_useForwardExpose","contentContext","require_Popper_PopperContent","baseSide","vue","el","require_component_Arrow","$attrs","as","asChild","rounded","width","height","_ctx","injectComboboxRootContext","provideComboboxRootContext","require_shared_createContext","props","__props","emits","__emit","primitiveElement","parentElement","require_Primitive_usePrimitiveElement","multiple","disabled","ignoreFilter","resetSearchTermOnSelect","openOnFocus","openOnClick","propDir","resetModelValueOnClear","highlightOnHover","vue","dir","require_shared_useDirection","modelValue","__vueuse_core","open","onOpenChange","val","filterSearch","isUserInputted","inputElement","resetSearchTerm","isVirtual","triggerElement","highlightedElement","allItems","allGroups","contains","require_shared_useFilter","filterState","oldValue","itemCount","filteredItems","filteredGroups","id","value","score","groupId","group","itemId","inst","__expose","require_Popper_PopperRoot","require_Listbox_ListboxRoot","$attrs","$event","as","asChild","name","required","_cache","_ctx","injectAutocompleteRootContext","provideAutocompleteRootContext","require_shared_createContext","props","__props","emits","__emit","primitiveElement","parentElement","require_Primitive_usePrimitiveElement","disabled","ignoreFilter","openOnFocus","openOnClick","propDir","highlightOnHover","vue","dir","require_shared_useDirection","modelValue","__vueuse_core","open","contextModelValue","val","onOpenChange","filterSearch","isUserInputted","inputElement","resetSearchTerm","isVirtual","triggerElement","highlightedElement","allItems","allGroups","contains","require_shared_useFilter","filterState","oldValue","itemCount","filteredItems","filteredGroups","id","value","score","groupId","group","itemId","inst","__expose","require_Combobox_ComboboxRoot","require_Popper_PopperRoot","require_Listbox_ListboxRoot","$attrs","$event","as","asChild","name","required","_cache","_ctx","props","__props","emits","__emit","rootContext","require_Combobox_ComboboxRoot","autocompleteContext","require_Autocomplete_AutocompleteRoot","listboxContext","require_Listbox_ListboxRoot","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","modelValue","__vueuse_core","vue","isComposing","handleCompositionStart","handleCompositionEnd","require_shared_useComposing","event","el","processInputValue","handleKeyDown","ev","value","handleInput","handleFocus","handleClick","newVal","text","_newValue","oldValue","require_Listbox_ListboxFilter","$event","as","asChild","autoFocus","disabled","_ctx","forwardRef","require_shared_useForwardExpose","vue","require_Popper_PopperAnchor","reference","require_Primitive_Primitive","asChild","as","$attrs","_ctx","injectComboboxContentContext","provideComboboxContentContext","require_shared_createContext","props","__props","emits","__emit","position","vue","rootContext","require_Combobox_ComboboxRoot","isEmpty","forwardRef","currentElement","require_shared_useForwardExpose","require_shared_useBodyScrollLock","require_shared_useFocusGuards","require_shared_useHideOthers","pickedProps","forwardedProps","require_shared_useForwardProps","popperStyle","isInputWithinContent","activeElement","require_shared_getActiveElement","isEventTargetWithinCombobox","target","control","require_Listbox_ListboxContent","require_FocusScope_FocusScope","_cache","require_DismissableLayer_DismissableLayer","disableOutsidePointerEvents","$event","ev","require_Popper_PopperContent","require_Primitive_Primitive","$attrs","_ctx","props","__props","rootContext","require_Combobox_ComboboxRoot","contentContext","require_Combobox_ComboboxContentImpl","require_shared_useForwardExpose","vue","require_Popper_PopperArrow","_ctx","props","__props","require_shared_useForwardExpose","rootContext","require_Combobox_ComboboxRoot","handleClick","vue","require_Primitive_Primitive","as","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","forwardRef","require_shared_useForwardExpose","rootContext","require_Combobox_ComboboxRoot","require_shared_useId","vue","require_Presence_Presence","forceMount","require_Combobox_ComboboxContentImpl","$attrs","_ctx","props","__props","rootContext","require_Combobox_ComboboxRoot","isRender","vue","require_Primitive_Primitive","_ctx","_cache","injectComboboxGroupContext","provideComboboxGroupContext","require_shared_createContext","props","__props","id","require_shared_useId","rootContext","require_Combobox_ComboboxRoot","isRender","vue","context","require_Listbox_ListboxGroup","_ctx","props","__props","emits","__emit","rootContext","require_Combobox_ComboboxRoot","listboxContext","require_Listbox_ListboxRoot","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","modelValue","__vueuse_core","vue","isComposing","handleCompositionStart","handleCompositionEnd","require_shared_useComposing","event","el","processInputValue","handleKeyDown","ev","value","handleInput","handleFocus","handleBlur","nextFocus","isInsideRoot","isInsideContent","active","handleClick","resetSearchTerm","rootModelValue","_newValue","oldValue","require_Listbox_ListboxFilter","$event","as","asChild","autoFocus","disabled","_ctx","props","__props","emits","__emit","id","require_shared_useId","rootContext","require_Combobox_ComboboxRoot","groupContext","require_Combobox_ComboboxGroup","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","isRender","vue","filteredCurrentItem","groupId","require_Listbox_ListboxItem","disabled","_cache","event","_ctx","value","props","__props","vue","require_Listbox_ListboxItemIndicator","_ctx","props","__props","require_shared_useForwardExpose","groupContext","require_Combobox_ComboboxGroup","require_shared_useId","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Teleport_Teleport","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Primitive_Primitive","_ctx","props","__props","forwardRef","currentElement","require_shared_useForwardExpose","rootContext","require_Combobox_ComboboxRoot","disabled","vue","require_Primitive_Primitive","as","_cache","$event","_ctx","useNonce","nonce?: Ref<string | undefined>","context","require_ConfigProvider_ConfigProvider","vue","nonce","props","__props","forwardRef","require_shared_useForwardExpose","propNonce","vue","nonce","require_shared_useNonce","rootContext","require_Combobox_ComboboxRoot","require_Primitive_Primitive","$attrs","_ctx","_cache","props","__props","rootContext","require_Combobox_ComboboxRoot","vue","require_Listbox_ListboxVirtualizer","slotProps","_ctx","injectAvatarRootContext","provideAvatarRootContext","require_shared_createContext","require_shared_useForwardExpose","vue","require_Primitive_Primitive","asChild","as","_ctx","props","__props","rootContext","require_Avatar_AvatarRoot","require_shared_useForwardExpose","canRender","vue","onCleanup","__vueuse_shared","timerId","require_Primitive_Primitive","asChild","as","_ctx","resolveLoadingStatus","image: HTMLImageElement | null","src?: string","image","src","useImageLoadingStatus","src: Ref<string>","referrerPolicy","crossOrigin","isMounted","vue","imageRef","isClient","loadingStatus","updateStatus","status: ImageLoadingStatus","status","onCleanup","img","handleLoad","handleError","props","__props","emits","__emit","src","referrerPolicy","crossOrigin","vue","require_shared_useForwardExpose","rootContext","require_Avatar_AvatarRoot","imageLoadingStatus","require_Avatar_utils","newValue","require_Primitive_Primitive","asChild","as","_ctx","DATE_SEGMENT_PARTS","TIME_SEGMENT_PARTS","NON_EDITABLE_SEGMENT_PARTS","EDITABLE_SEGMENT_PARTS","EDITABLE_TIME_SEGMENT_PARTS","ALL_SEGMENT_PARTS","ALL_EXCEPT_LITERAL_PARTS","part","isDateSegmentPart","part: unknown","isSegmentPart","part: string","supportedLocales","placeholderFields","placeholders: PlaceholderMap","getPlaceholderObj","locale: SupportedLocale | (string & {})","isSupportedLocale","locale","placeholders","localeLanguage","getLocaleLanguage","getPlaceholder","field: Field","value: string","isPlaceholderField","field","isDefaultField","value","isTimeField","locale: string","field: unknown","calendarDateTimeGranularities","syncTimeSegmentValues","props: SyncTimeSegmentValuesProps","require_date_parts","part","props","require_date_comparators","syncSegmentValues","props: SyncDateSegmentValuesProps","formatter","dateValues","timeValues","initializeTimeSegmentValues","granularity: 'hour' | 'minute' | 'second'","key","granularity","initializeSegmentValues","granularity: Granularity","initialParts","createContentObj","props: CreateContentObjProps","segmentValues","locale","getPartContent","part: DateSegmentPart | TimeSegmentPart","value","require_date_utils","require_date_placeholders","obj","createContentArr","props: CreateContentArrProps","contentObj","hideTimeZone","hourCycle","isTimeValue","segment","createContent","props: CreateContentProps","contentArr","isSegmentNavigationKey","key: string","kbd","require_shared_useKbd","key","isNumberString","value: string","value","isAcceptableSegmentKey","getSegmentElements","parentElement: HTMLElement","parentElement","item","getTimeFieldSegmentElements","DIGIT_REG","commonSegmentAttrs","props: SegmentAttrProps","props","daySegmentAttrs","segmentValues","placeholder","isEmpty","dateFields: { day?: number, month?: number }","dateFields","date","valueNow","valueMin","valueMax","require_date_comparators","valueText","monthSegmentAttrs","formatter","yearSegmentAttrs","hourSegmentAttrs","hourCycle","minuteSegmentAttrs","secondSegmentAttrs","dayPeriodSegmentAttrs","literalSegmentAttrs","_props: SegmentAttrProps","timeZoneSegmentAttrs","eraSegmentAttrs","segmentBuilders","useDateField","props: UseDateFieldProps","kbd","require_shared_useKbd","minuteSecondIncrementation","e","part","dateRef","prevValue","step","sign","min","max","cycleArgs: [keyof TimeFields, number]","cycleArgs","deleteValue","prevValue: number | null","str","dateTimeValueIncrementation","cycleArgs: [keyof DateFields | keyof TimeFields, number]","cycleArgs: [keyof DateFields, number]","updateDayOrMonth","max: number","num: number","prev: number | null","moveToNext","maxStart","prev","num","digits","total","updateMinuteOrSecond","updateHour","updateYear","attributes","vue","handleDaySegmentKeydown","e: KeyboardEvent","require_date_segment","segmentMonthValue","daysInMonth","value","handleMonthSegmentKeydown","handleYearSegmentKeydown","uses12HourFormat","locale: string","DateFormatter","locale","handleHourSegmentKeydown","newHour","is12Hour","displayPrev","internalValue","period","handleMinuteSegmentKeydown","handleSecondSegmentKeydown","handleDayPeriodSegmentKeydown","handleSegmentClick","e: MouseEvent","handleSegmentKeydown","disabled","readonly","item","updateObject","handleSegmentFocusOut","require_shared_clamp","preCompositionNodes: { node: ChildNode, value: string | null }[] | null","handleSegmentBeforeInput","e: InputEvent","handleSegmentCompositionStart","e: CompositionEvent","el","preCompositionNodes","node","handleSegmentCompositionEnd","original","o","data","char","target","require_shared_getActiveElement","useCalendarState","props: UseCalendarStateProps","isDateSelected","dateObj: DateValue","props","d","__internationalized_date","dateObj","isInvalid","vue","hasSelectedDate","isSelectedDateDisabled","handleNextDisabled","lastPeriodInView: DateValue","nextPageFunc: (date: DateValue) => DateValue","firstPeriodOfNextPage","nextPageFunc","lastPeriodInView","diff","duration: DateFields","duration","require_date_comparators","handlePrevDisabled","firstPeriodInView: DateValue","prevPageFunc: (date: DateValue) => DateValue","lastPeriodOfPrevPage","prevPageFunc","firstPeriodInView","handleNextPage","date: DateValue","date","handlePrevPage","useCalendar","props: UseCalendarProps","formatter","require_shared_useDateFormatter","headingFormatOptions","options: DateFormatterOptions","options","grid","require_date_calendar","visibleView","month","isOutsideVisibleView","isNextButtonDisabled","nextPageFunc?: (date: DateValue) => DateValue","isPrevButtonDisabled","prevPageFunc?: (date: DateValue) => DateValue","isDateDisabled","isDateUnavailable","weekdays","nextPage","firstDate","newDate","newGrid","newGrid$1","prevPage","value","headingValue","startMonth","endMonth","startMonthName","endMonthName","startMonthYear","endMonthYear","fullCalendarLabel","isPlaceholderFocusable","firstFocusableDate","daysInMonth","startDay","day","injectCalendarRootContext","provideCalendarRootContext","require_shared_createContext","props","__props","emits","__emit","disabled","readonly","initialFocus","pagedNavigation","weekdayFormat","fixedWeeks","multiple","minValue","maxValue","numberOfMonths","preventDeselect","propsIsDateDisabled","propsIsDateUnavailable","calendarLabel","defaultValue","propsNextPage","propsPrevPage","propDir","propLocale","disableDaysOutsideCurrentView","vue","primitiveElement","parentElement","require_Primitive_usePrimitiveElement","locale","require_shared_useLocale","dir","require_shared_useDirection","weekStartsOn","require_date_calendar","modelValue","__vueuse_core","defaultDate","require_date_comparators","placeholder","onPlaceholderChange","value","fullCalendarLabel","headingValue","isDateDisabled","isDateUnavailable","isNextButtonDisabled","isPrevButtonDisabled","weekdays","isOutsideVisibleView","nextPage","prevPage","formatter","grid","isPlaceholderFocusable","firstFocusableDate","require_Calendar_useCalendar","isInvalid","isDateSelected","hasSelectedDate","isSelectedDateDisabled","_modelValue","lastValue","__internationalized_date","onDateChange","date","next","require_date_utils","require_Primitive_Primitive","as","asChild","_ctx","_hoisted_1","_hoisted_2","rootContext","require_Calendar_CalendarRoot","vue","require_Primitive_Primitive","as","asChild","date","_ctx","props","__props","kbd","require_shared_useKbd","rootContext","require_Calendar_CalendarRoot","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","dayValue","vue","labelText","require_date_comparators","isUnavailable","isDateToday","__internationalized_date","isOutsideView","isOutsideVisibleView","isDisabled","isFocusedDate","isSelectedDate","changeDate","date","handleClick","handleArrowKey","e","parentElement","indexIncrementation","sign","shiftFocus","day","add","candidateDayValue","candidateDay","require_Primitive_Primitive","_cache","_ctx","props","__props","rootContext","require_Calendar_CalendarRoot","disabled","vue","readonly","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_Calendar_CalendarRoot","vue","require_Primitive_Primitive","_ctx","props","__props","disabled","vue","rootContext","require_Calendar_CalendarRoot","handleClick","require_Primitive_Primitive","_ctx","_cache","props","__props","disabled","vue","rootContext","require_Calendar_CalendarRoot","handleClick","require_Primitive_Primitive","_ctx","_cache","injectRovingFocusGroupContext","provideRovingFocusGroupContext","require_shared_createContext","props","__props","emits","__emit","loop","orientation","propDir","vue","dir","require_shared_useDirection","currentTabStopId","__vueuse_core","isTabbingBackOut","isClickFocus","focusableItemsCount","getItems","CollectionSlot","require_Collection_Collection","handleFocus","event","isKeyboardFocus","entryFocusEvent","require_RovingFocus_utils","items","i","activeItem","item","highlightedItem","currentItem","candidateItems","handleMouseUp","__expose","tabStopId","require_Primitive_Primitive","as","asChild","_cache","$event","_ctx","props","__props","context","require_RovingFocus_RovingFocusGroup","randomId","require_shared_useId","id","vue","isCurrentTabStop","getItems","CollectionItem","require_Collection_Collection","handleKeydown","event","focusIntent","require_RovingFocus_utils","candidateNodes","i","currentIndex","require_Primitive_Primitive","active","focusable","as","asChild","_cache","$event","_ctx","injectCheckboxGroupRootContext","provideCheckboxGroupRootContext","require_shared_createContext","props","__props","emits","__emit","disabled","rovingFocus","propDir","vue","dir","require_shared_useDirection","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","isFormControl","require_shared_useFormControl","modelValue","__vueuse_core","rovingFocusProps","require_RovingFocus_RovingFocusGroup","require_Primitive_Primitive","as","asChild","_ctx","name","require_VisuallyHidden_VisuallyHiddenInput","required","isIndeterminate","checked?: CheckedState","checked","getState","checked: CheckedState","injectCheckboxRootContext","provideCheckboxRootContext","require_shared_createContext","props","__props","emits","__emit","forwardRef","currentElement","require_shared_useForwardExpose","checkboxGroupContext","require_Checkbox_CheckboxGroupRoot","modelValue","__vueuse_core","disabled","vue","isChecked","ohash","checkboxState","require_shared_nullish","require_shared_isValueEqualOrExist","handleClick","modelValueArray","index","i","isFormControl","require_shared_useFormControl","ariaLabel","require_RovingFocus_RovingFocusItem","require_Primitive_Primitive","$attrs","id","asChild","as","require_Checkbox_utils","required","_ctx","name","require_VisuallyHidden_VisuallyHiddenInput","value","forwardRef","require_shared_useForwardExpose","rootContext","require_Checkbox_CheckboxRoot","vue","require_Presence_Presence","forceMount","require_Checkbox_utils","require_Primitive_Primitive","asChild","as","$attrs","_ctx","colorToString","color: Color","format: ColorFormat","format","colorToHex","color","colorToRgb","colorToHsl","colorToHsb","rgb","convertToRgb","toHex","n: number","alpha","g","b","hsl","convertToHsl","h","s","l","hsb","convertToHsb","hslToRgb","hsbToRgb","rgbToHsl","rgbToHsb","rgb: RGBColor","r","max","min","d","hsl: HSLColor","r: number","g: number","b: number","hue2rgb","p: number","q: number","t: number","t","p","q","v","hsb: HSBColor","i","f","getChannelRange","channel: ColorChannel","channel","getChannelName","getChannelValue","color: Color","color","require_color_convert","setChannelValue","value: number","range","clamped","value","newRgb: RGBColor","convertFromRgb","newRgb","newHsl: HSLColor","convertFromHsl","newHsl","newHsb: HSBColor","convertFromHsb","newHsb","setChannelValues","channels: Array<{ channel: ColorChannel, value: number }>","channels","channelNames","c","hasBrightness","hasLightness","hasRgb","workingColor: Color","workingColor","rgb: RGBColor","targetSpace: ColorSpace","targetSpace","rgb","rgbToHsl","rgbToHsb","hsl: HSLColor","hsl","hslToRgb","hsb: HSBColor","hsb","hsbToRgb","r","g","b","max","min","h","l","d","s","r: number","g: number","b: number","hue2rgb","p: number","q: number","t: number","t","p","q","v","i","f","getSliderGradient","color: Color","channel: ColorChannel","colorSpace: ColorSpace","color","hsl","require_color_convert","hsb","channel","getHueGradient","getSaturationGradient","colorSpace","getLightnessGradient","getBrightnessGradient","getRedGradient","getGreenGradient","getBlueGradient","getAlphaGradient","getAreaGradient","xChannel: ColorChannel","yChannel: ColorChannel","gradientX","getChannelGradientForArea","xChannel","gradientY","yChannel","getAreaBackgroundColor","hsl: { h: number, s: number, l: number, alpha: number }","start","end","mid","hsb: { h: number, s: number, b: number, alpha: number }","g","b","alpha","r","CHECKERBOARD_LAYERS","axis: 'x' | 'y'","direction","axis","fullColor","getAreaBackgroundStyle","hueGradient","hueColor","satGradient","rgb","allChannels","varyingChannels","constantChannel","c","constantValue","xColorStart: RGBColor","xColorEnd: RGBColor","xGradient","xColorStart","xColorEnd","yColorEnd: RGBColor","yGradient","yColorEnd","bgColor: RGBColor","bgColor","background","gradients: string[]","gradients","getSliderBackgroundStyle","gradient","HEX3_RE","HEX6_RE","HEX8_RE","RGB_RE","HSL_RE","HSB_RE","parseColor","value: string","trimmed","value","parseHex","parseRgb","parseHsl","parseHsb","hex: string","normalized","hex","c","bigint","rgb: string","match","rgb","hsl: string","hsl","hsb: string","hsb","normalizeColor","value: string | Color","isValidColor","HASH_PREFIX_RE","HEX6_RE","HEX3_RE","hexToRGB","hex: string","hex","c","bigint","g","b","hexToHSL","r","max","min","h: number","s: number","l: number","h","l","d","getColorName","s","baseName","descriptors","getColorContrast","injectColorAreaRootContext","provideColorAreaRootContext","require_shared_createContext","props","__props","emits","__emit","colorSpace","xChannel","yChannel","disabled","vue","forwardRef","currentElement","require_shared_useForwardExpose","isFormControl","require_shared_useFormControl","modelValue","__vueuse_core","color","require_color_parse","newColor","hexString","require_color_convert","xRange","require_color_channel","yRange","xValue","yValue","hueValue","isUpdating","newX","newY","hsl","hsb","areaStyles","bgColor","require_color_gradient","updateValues","x","y","clampedX","clampedY","channels","commitValues","thumbRef","require_Primitive_Primitive","as","asChild","_ctx","xName","require_VisuallyHidden_VisuallyHiddenInput","yName","linearScale","input: readonly [number, number]","output: readonly [number, number]","value: number","input","output","ratio","value","convertValueToPercentage","min: number","max: number","max","min","percentage","require_shared_clamp","props","__props","rootContext","require_ColorArea_ColorAreaRoot","primitiveElement","areaElement","require_Primitive_usePrimitiveElement","isDragging","vue","getValuesFromPointer","event","rect","xInput","xOutput","xValue","require_ColorArea_utils","yInput","yOutput","yValue","handlePointerDown","x","y","handlePointerMove","handlePointerUp","handleKeyDown","stepMultiplier","xStepSize","yStepSize","xDelta","yDelta","require_Primitive_Primitive","asChild","as","_ctx","props","__props","rootContext","require_ColorArea_ColorAreaRoot","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","vue","xPercent","require_ColorArea_utils","yPercent","ariaLabel","require_color_channel","ariaValueText","require_Primitive_Primitive","asChild","as","_ctx","injectColorFieldRootContext","provideColorFieldRootContext","require_shared_createContext","props","__props","emits","__emit","colorSpace","channel","disabled","readonly","disableWheelChange","placeholder","propLocale","stepProp","vue","forwardRef","currentElement","require_shared_useForwardExpose","isFormControl","require_shared_useFormControl","locale","require_shared_useLocale","modelValue","__vueuse_core","color","require_color_parse","newColor","hexString","require_color_convert","inputValue","isEditing","formatValue","c","value","require_color_channel","MIN_HEX_INT","MAX_HEX_INT","PAGE_STEP_MULTIPLIER","getStep","updateValue","commit","numValue","range","clamped","trimmed","addHexValue","delta","intDelta","hexInt","rgb","hex","increment","step","currentValue","decrement","incrementPage","decrementPage","incrementToMax","decrementToMin","handleWheel","event","require_Primitive_Primitive","as","asChild","_ctx","name","require_VisuallyHidden_VisuallyHiddenInput","required","ALLOWED_INPUT_RE","props","__props","rootContext","require_ColorField_ColorFieldRoot","isFocused","vue","isComposing","handleCompositionStart","handleCompositionEnd","require_shared_useComposing","inputType","inputMode","handleInput","event","target","handleBlur","handleFocus","handleWheel","handleKeydown","handleBeforeInput","data","nextValue","numValue","require_Primitive_Primitive","asChild","as","_ctx","getNextSortedValues","prevValues: number[]","nextValue: number","atIndex: number","nextValues","prevValues","atIndex","nextValue","b","convertValueToPercentage","value: number","min: number","max: number","percentage","max","min","value","require_shared_clamp","getLabel","index: number","totalValues: number","totalValues","index","getClosestValueIndex","values: number[]","values","distances","closestDistance","getThumbInBoundsOffset","width: number","left: number","direction: number","halfWidth","width","offset","linearScale","left","direction","getStepsBetweenValues","hasMinStepsBetweenValues","minStepsBetweenValues: number","minStepsBetweenValues","stepsBetweenValues","input: readonly [number, number]","output: readonly [number, number]","input","output","ratio","getDecimalCount","roundValue","decimalCount: number","rounder","decimalCount","PAGE_KEYS","ARROW_KEYS","BACK_KEYS: Record<SlideDirection, string[]>","injectSliderOrientationContext","provideSliderOrientationContext","require_shared_createContext","props","__props","emits","__emit","max","min","dir","inverted","vue","forwardRef","sliderElement","require_shared_useForwardExpose","rootContext","require_Slider_SliderRoot","offsetPosition","rectRef","isSlidingFromLeft","getValueFromPointerEvent","event","slideStart","rect","thumb","thumbWidth","input","output","value","require_Slider_utils","position","startEdge","endEdge","direction","require_Slider_SliderImpl","_cache","slideDirection","isBackKey","$event","_ctx","props","__props","emits","__emit","max","min","inverted","vue","rootContext","require_Slider_SliderRoot","forwardRef","sliderElement","require_shared_useForwardExpose","offsetPosition","rectRef","isSlidingFromBottom","getValueFromPointerEvent","event","slideStart","rect","thumb","thumbHeight","input","output","value","require_Slider_utils","position","startEdge","endEdge","direction","require_Slider_SliderImpl","_cache","slideDirection","isBackKey","$event","_ctx","injectSliderRootContext","provideSliderRootContext","require_shared_createContext","props","__props","emits","__emit","min","max","step","minStepsBetweenThumbs","orientation","disabled","thumbAlignment","propDir","vue","dir","require_shared_useDirection","forwardRef","currentElement","require_shared_useForwardExpose","isFormControl","require_shared_useFormControl","CollectionSlot","require_Collection_Collection","modelValue","__vueuse_core","currentModelValue","valueIndexToChangeRef","valuesBeforeSlideStartRef","handleSlideStart","value","closestIndex","require_Slider_utils","updateValues","handleSlideMove","handleSlideEnd","prevValue","atIndex","commit","decimalCount","snapToStep","nextValue","require_shared_clamp","nextValues","hasChanged","thumbElements","require_Slider_SliderHorizontal","require_Slider_SliderVertical","$attrs","asChild","as","inverted","_cache","$event","event","direction","multiplier","stepInDirection","_ctx","name","require_VisuallyHidden_VisuallyHiddenInput","required","props","__props","emits","__emit","rootContext","require_Slider_SliderRoot","vue","require_Primitive_Primitive","_cache","event","require_Slider_utils","target","_ctx","rootContext","require_Slider_SliderRoot","orientation","require_Slider_utils","require_shared_useForwardExpose","percentages","vue","value","offsetStart","offsetEnd","require_Primitive_Primitive","asChild","as","_ctx","props","__props","rootContext","require_Slider_SliderRoot","orientation","require_Slider_utils","forwardRef","thumbElement","require_shared_useForwardExpose","CollectionItem","require_Collection_Collection","value","vue","percent","label","size","require_shared_useSize","orientationSize","thumbInBoundsOffset","isMounted","__vueuse_core","i","i$1","require_Primitive_Primitive","$attrs","asChild","as","_cache","index","_ctx","props","__props","getItems","require_Collection_Collection","forwardRef","thumbElement","require_shared_useForwardExpose","index","vue","require_Slider_SliderThumbImpl","_ctx","rootContext","require_Slider_SliderRoot","require_shared_useForwardExpose","vue","require_Primitive_Primitive","asChild","as","_ctx","injectColorSliderRootContext","provideColorSliderRootContext","require_shared_createContext","props","__props","emits","__emit","orientation","disabled","inverted","propDir","channel","colorSpace","stepProp","vue","dir","require_shared_useDirection","forwardRef","currentElement","require_shared_useForwardExpose","isFormControl","require_shared_useFormControl","modelValue","__vueuse_core","toNativeSpace","color$1","ch","space","require_color_convert","internalColor","require_color_parse","isAchromatic","hsl","newVal","parsed","currentHex","newHex","nativeColor","currentChannelVal","require_color_channel","newChannelVal","range","channelRange","color","newColor","hexString","min","max","step","channelValue","sliderValue","newValue","clamped","handleValueCommit","values","require_Slider_SliderRoot","$attrs","$event","as","asChild","_ctx","name","require_VisuallyHidden_VisuallyHiddenInput","required","props","__props","rootContext","require_ColorSlider_ColorSliderRoot","ariaLabel","vue","require_color_channel","ariaValueText","value","require_Slider_SliderThumb","as","asChild","_ctx","props","__props","rootContext","require_ColorSlider_ColorSliderRoot","backgroundStyle","vue","require_color_gradient","require_Slider_SliderTrack","as","asChild","_ctx","props","__props","colorString","vue","require_color_convert","colorObj","require_color_parse","alpha","isNoColor","label","require_color_utils","colorContrast","require_Primitive_Primitive","asChild","as","_ctx","injectColorSwatchPickerItemContext","provideColorSwatchPickerItemContext","require_shared_createContext","props","__props","emits","__emit","value","vue","forwarded","require_shared_useForwardPropsEmits","colorLabel","require_color_utils","require_Listbox_ListboxItem","_ctx","props","__props","vue","require_Listbox_ListboxItemIndicator","_ctx","props","__props","colorSwatchPickerItemContext","require_ColorSwatchPicker_ColorSwatchPickerItem","vue","require_ColorSwatch_ColorSwatch","props","__props","emits","__emit","modelValue","__vueuse_core","forwarded","require_shared_useForwardPropsEmits","vue","require_Listbox_ListboxRoot","$event","require_Listbox_ListboxContent","asChild","as","_ctx","props","__props","vue","require_Popper_PopperAnchor","_ctx","props","__props","vue","require_Popper_PopperArrow","_ctx","useIsUsingKeyboardImpl","isUsingKeyboard","vue","__vueuse_core","useIsUsingKeyboard","injectMenuContext","provideMenuContext","require_shared_createContext","injectMenuRootContext","provideMenuRootContext","props","__props","emits","__emit","modal","propDir","vue","dir","require_shared_useDirection","open","__vueuse_core","content","isUsingKeyboardRef","require_shared_useIsUsingKeyboard","value","element","require_Popper_PopperRoot","_ctx","injectMenuContentContext","provideMenuContentContext","require_shared_createContext","props","__props","emits","__emit","menuContext","require_Menu_MenuRoot","rootContext","trapFocus","disableOutsidePointerEvents","loop","vue","require_shared_useFocusGuards","require_shared_useBodyScrollLock","searchRef","timerRef","pointerGraceTimerRef","pointerGraceIntentRef","pointerDirRef","lastPointerXRef","currentItemId","rovingFocusGroupRef","forwardRef","contentElement","require_shared_useForwardExpose","handleTypeaheadSearch","require_shared_useTypeahead","highlightedElement","onKeydownNavigation","event","el","require_shared_useArrowNavigation","require_shared_getActiveElement","onKeydownEnter","filterElement","activeSubmenuContext","isPointerMovingToSubmenu","require_Menu_utils","handleMountAutoFocus","handleKeyDown","target","isKeyDownInside","isKeyDownInTextField","isModifierKey","isCharacterKey","collectionItems","candidateNodes","item","handleBlur","handlePointerMove","pointerXHasChanged","newDir","handlePointerEnter","intent","require_FocusScope_FocusScope","_cache","$event","require_DismissableLayer_DismissableLayer","require_RovingFocus_RovingFocusGroup","require_Popper_PopperContent","as","asChild","side","sideOffset","align","alignOffset","avoidCollisions","collisionBoundary","collisionPadding","arrowPadding","prioritizePosition","positionStrategy","updatePositionStrategy","sticky","hideWhenDetached","reference","_ctx","props","__props","contentContext","require_Menu_MenuContentImpl","forwardRef","currentElement","require_shared_useForwardExpose","CollectionItem","require_Collection_Collection","isFocused","vue","isHighlighted","handlePointerMove","event","require_Menu_utils","item","require_shared_getActiveElement","handlePointerLeave","textValue","require_Primitive_Primitive","$attrs","as","asChild","disabled","_cache","_ctx","props","__props","emits","__emit","forwardRef","currentElement","require_shared_useForwardExpose","rootContext","require_Menu_MenuRoot","contentContext","require_Menu_MenuContentImpl","isPointerDownRef","vue","handleSelect","menuItem","itemSelectEvent","require_Menu_utils","require_Menu_MenuItemImpl","_cache","event","isTypingAhead","disabled","_ctx","injectMenuItemIndicatorContext","provideMenuItemIndicatorContext","require_shared_createContext","indicatorContext","vue","require_Presence_Presence","forceMount","require_Menu_utils","require_Primitive_Primitive","as","asChild","_ctx","props","__props","emits","__emit","delegatedProps","__vueuse_core","forwarded","require_shared_useForwardProps","modelValue","require_Menu_MenuItemIndicator","vue","require_Menu_MenuItem","require_Menu_utils","_cache","event","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","menuContext","require_Menu_MenuRoot","forwardRef","currentElement","require_shared_useForwardExpose","require_shared_useHideOthers","vue","require_Menu_MenuContentImpl","_cache","$event","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","menuContext","require_Menu_MenuRoot","vue","require_Menu_MenuContentImpl","_cache","$event","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","menuContext","require_Menu_MenuRoot","rootContext","vue","require_Presence_Presence","forceMount","require_Menu_MenuRootContentModal","$attrs","_ctx","require_Menu_MenuRootContentNonModal","injectMenuGroupContext","provideMenuGroupContext","require_shared_createContext","props","__props","id","require_shared_useId","vue","require_Primitive_Primitive","_ctx","props","__props","groupContext","require_Menu_MenuGroup","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Teleport_Teleport","_ctx","injectMenuRadioGroupContext","provideMenuRadioGroupContext","require_shared_createContext","props","__props","emits","__emit","delegatedProps","__vueuse_core","forwarded","require_shared_useForwardProps","modelValue","payload","vue","require_Menu_MenuGroup","_ctx","props","__props","emits","__emit","delegatedProps","__vueuse_shared","forwarded","require_shared_useForwardProps","value","vue","radioGroupContext","require_Menu_MenuRadioGroup","modelValue","require_Menu_MenuItemIndicator","require_Menu_MenuItem","require_Menu_utils","_cache","event","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","injectMenuSubContext","provideMenuSubContext","require_shared_createContext","props","__props","emits","__emit","open","__vueuse_core","parentMenuContext","require_Menu_MenuRoot","trigger","vue","content","cleanupFn","value","element","require_Popper_PopperRoot","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","menuContext","require_Menu_MenuRoot","rootContext","menuSubContext","require_Menu_MenuSub","parentContentContext","require_Menu_MenuContentImpl","forwardRef","subContentElement","require_shared_useForwardExpose","require_shared_useId","vue","require_Presence_Presence","forceMount","_cache","event","isMovingToParentContent","isKeyDownInside","isCloseKey","require_Menu_utils","_ctx","props","__props","menuContext","require_Menu_MenuRoot","rootContext","subContext","require_Menu_MenuSub","contentContext","require_Menu_MenuContentImpl","vue","open","openTimerRef","require_shared_useId","clearOpenTimer","handlePointerMove","event","require_Menu_utils","handlePointerLeave","contentRect","side","rightSide","bleed","contentNearEdge","contentFarEdge","handleKeyDown","isTypingAhead","require_Menu_MenuAnchor","require_Menu_MenuItemImpl","vnode","_cache","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuArrow","_ctx","props","__props","emits","__emit","emitsAsProps","require_shared_useEmitAsProps","require_shared_useForwardExpose","vue","require_Menu_MenuCheckboxItem","_ctx","injectContextMenuRootContext","provideContextMenuRootContext","require_shared_createContext","props","__props","emits","__emit","propDir","modal","pressOpenDelay","vue","require_shared_useForwardExpose","dir","require_shared_useDirection","open","triggerElement","value","require_Menu_MenuRoot","$event","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","require_shared_useForwardExpose","rootContext","require_ContextMenu_ContextMenuRoot","hasInteractedOutside","vue","require_Menu_MenuContent","_cache","event","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuGroup","_ctx","props","__props","emits","__emit","emitsAsProps","require_shared_useEmitAsProps","require_shared_useForwardExpose","vue","require_Menu_MenuItem","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuItemIndicator","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuLabel","_ctx","props","__props","vue","require_Menu_MenuPortal","_ctx","props","__props","emits","__emit","emitsAsProps","require_shared_useEmitAsProps","require_shared_useForwardExpose","vue","require_Menu_MenuRadioGroup","_ctx","props","__props","emits","__emit","emitsAsProps","require_shared_useEmitAsProps","require_shared_useForwardExpose","vue","require_Menu_MenuRadioItem","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuSeparator","_ctx","props","__props","emit","__emit","require_shared_useForwardExpose","open","__vueuse_core","vue","require_Menu_MenuSub","$event","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","require_shared_useForwardExpose","vue","require_Menu_MenuSubContent","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuSubTrigger","_ctx","isTouchOrPen","event: PointerEvent","event","props","__props","disabled","vue","forwardRef","currentElement","require_shared_useForwardExpose","rootContext","require_ContextMenu_ContextMenuRoot","point","virtualEl","longPressTimer","clearLongPress","handleOpen","event","handleContextMenu","handlePointerDown","require_ContextMenu_utils","handlePointerEvent","require_Menu_MenuAnchor","require_Primitive_Primitive","as","asChild","$attrs","_ctx","injectDateFieldRootContext","provideDateFieldRootContext","require_shared_createContext","props","__props","emits","__emit","disabled","readonly","propsIsDateUnavailable","granularity","defaultValue","propDir","propLocale","vue","locale","require_shared_useLocale","dir","require_shared_useDirection","formatter","require_shared_useDateFormatter","require_date_utils","primitiveElement","parentElement","require_Primitive_usePrimitiveElement","segmentElements","require_date_segment","item","modelValue","__vueuse_core","defaultDate","require_date_comparators","placeholder","step","inferredGranularity","isInvalid","initialSegments","require_date_parser","segmentValues","allSegmentContent","segmentContents","editableSegmentContents","part","value","_modelValue","require_shared_nullish","currentFocusedElement","currentSegmentIndex","el","nextFocusableSegment","sign","prevFocusableSegment","inputType","inputValue","inputMaxValue","inputMinValue","kbd","require_shared_useKbd","handleKeydown","e","setFocusedElement","__expose","require_Primitive_Primitive","$attrs","_ctx","require_VisuallyHidden_VisuallyHidden","id","name","required","_cache","$event","props","__props","rootContext","require_DateField_DateFieldRoot","hasLeftFocus","vue","lastKeyZero","handleSegmentClick","handleSegmentKeydown","handleSegmentBeforeInput","handleSegmentCompositionStart","handleSegmentCompositionEnd","attributes","require_date_useDateField","disabled","readonly","isInvalid","require_Primitive_Primitive","as","asChild","part","e","_ctx","injectPopoverRootContext","providePopoverRootContext","require_shared_createContext","props","__props","emit","__emit","modal","vue","open","__vueuse_core","triggerElement","hasCustomAnchor","value","require_Popper_PopperRoot","_ctx","props","__props","require_shared_useForwardExpose","rootContext","require_Popover_PopoverRoot","vue","require_Popper_PopperAnchor","_ctx","props","__props","vue","require_Popover_PopoverAnchor","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Popper_PopperArrow","_ctx","props","__props","vue","require_Popover_PopoverArrow","_ctx","injectDatePickerRootContext","provideDatePickerRootContext","require_shared_createContext","props","__props","emits","__emit","propLocale","disabled","readonly","pagedNavigation","weekdayFormat","fixedWeeks","numberOfMonths","preventDeselect","propsIsDateDisabled","propsIsDateUnavailable","defaultOpen","modal","id","name","required","minValue","maxValue","granularity","hideTimeZone","hourCycle","defaultValue","propDir","step","closeOnSelect","vue","dir","require_shared_useDirection","locale","require_shared_useLocale","weekStartsOn","require_date_calendar","modelValue","__vueuse_core","defaultDate","require_date_comparators","placeholder","open","dateFieldRef","resetTime","date","value","require_Popover_PopoverRoot","$event","_ctx","rootContext","require_DatePicker_DatePickerRoot","vue","require_Calendar_CalendarRoot","_cache","date","__internationalized_date","weekDays","grid","weekStartsOn","locale","fixedWeeks","_ctx","props","__props","vue","require_Calendar_CalendarCell","_ctx","props","__props","vue","require_Calendar_CalendarCellTrigger","slotProps","_ctx","props","__props","require_shared_useForwardExpose","rootContext","require_Popover_PopoverRoot","vue","require_Primitive_Primitive","as","_cache","$event","_ctx","props","__props","vue","require_Popover_PopoverClose","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardProps","__vueuse_shared","forwardRef","require_shared_useForwardExpose","rootContext","require_Popover_PopoverRoot","require_shared_useFocusGuards","vue","require_FocusScope_FocusScope","trapFocus","_cache","$event","require_DismissableLayer_DismissableLayer","disableOutsidePointerEvents","require_Popper_PopperContent","_ctx","props","__props","emits","__emit","rootContext","require_Popover_PopoverRoot","isRightClickOutsideRef","vue","require_shared_useBodyScrollLock","forwarded","require_shared_useForwardPropsEmits","forwardRef","currentElement","require_shared_useForwardExpose","require_shared_useHideOthers","require_Popover_PopoverContentImpl","_cache","event","originalEvent","ctrlLeftClick","isRightClick","_ctx","props","__props","emits","__emit","rootContext","require_Popover_PopoverRoot","hasInteractedOutsideRef","vue","hasPointerDownOutsideRef","forwarded","require_shared_useForwardPropsEmits","require_Popover_PopoverContentImpl","_cache","event","target","_ctx","props","__props","emits","__emit","rootContext","require_Popover_PopoverRoot","forwarded","require_shared_useForwardPropsEmits","forwardRef","require_shared_useForwardExpose","require_shared_useId","vue","require_Presence_Presence","forceMount","require_Popover_PopoverContentModal","_ctx","require_Popover_PopoverContentNonModal","props","__props","vue","require_Teleport_Teleport","_ctx","props","__props","emits","__emit","propsToForward","vue","forwarded","require_shared_useForwardPropsEmits","require_Popover_PopoverPortal","portal","require_Popover_PopoverContent","$attrs","_cache","event","require_date_utils","_ctx","rootContext","require_DatePicker_DatePickerRoot","vue","require_DateField_DateFieldRoot","_cache","date","segments","modelValue","_ctx","props","__props","vue","require_Calendar_CalendarGrid","_ctx","props","__props","vue","require_Calendar_CalendarGridBody","_ctx","props","__props","vue","require_Calendar_CalendarGridHead","_ctx","props","__props","vue","require_Calendar_CalendarGridRow","_ctx","props","__props","vue","require_Calendar_CalendarHeadCell","_ctx","props","__props","vue","require_Calendar_CalendarHeader","_ctx","props","__props","vue","require_Calendar_CalendarHeading","headingValue","_ctx","props","__props","vue","require_DateField_DateFieldInput","_ctx","props","__props","vue","require_Calendar_CalendarNext","slotProps","_ctx","props","__props","vue","require_Calendar_CalendarPrev","slotProps","_ctx","props","__props","rootContext","require_Popover_PopoverRoot","forwardRef","triggerElement","require_shared_useForwardExpose","require_shared_useId","vue","require_Primitive_Primitive","require_Popper_PopperAnchor","as","_ctx","props","__props","rootContext","require_DatePicker_DatePickerRoot","vue","require_Popover_PopoverTrigger","_cache","e","_ctx","injectDateRangeFieldRootContext","provideDateRangeFieldRootContext","require_shared_createContext","props","__props","emits","__emit","disabled","readonly","propsIsDateUnavailable","propDir","propLocale","vue","locale","require_shared_useLocale","dir","require_shared_useDirection","formatter","require_shared_useDateFormatter","require_date_utils","primitiveElement","parentElement","require_Primitive_usePrimitiveElement","segmentElements","require_date_segment","item","modelValue","__vueuse_core","defaultDate","require_date_comparators","placeholder","step","inferredGranularity","isStartInvalid","isEndInvalid","isInvalid","initialSegments","require_date_parser","startSegmentValues","endSegmentValues","startSegmentContent","endSegmentContent","segmentContents","editableSegmentContents","part","startValue","endValue","_startValue","_endValue","_modelValue","value","currentFocusedElement","currentSegmentIndex","el","nextFocusableSegment","sign","prevFocusableSegment","kbd","require_shared_useKbd","handleKeydown","e","setFocusedElement","__expose","require_Primitive_Primitive","$attrs","_ctx","require_VisuallyHidden_VisuallyHidden","id","name","required","_cache","$event","props","__props","rootContext","require_DateRangeField_DateRangeFieldRoot","hasLeftFocus","vue","lastKeyZero","handleSegmentClick","handleSegmentKeydown","handleSegmentBeforeInput","handleSegmentCompositionStart","handleSegmentCompositionEnd","attributes","require_date_useDateField","disabled","readonly","isInvalid","require_Primitive_Primitive","as","asChild","part","type","e","_ctx","props","__props","vue","require_Popover_PopoverAnchor","_ctx","props","__props","vue","require_Popover_PopoverArrow","_ctx","injectDateRangePickerRootContext","provideDateRangePickerRootContext","require_shared_createContext","props","__props","emits","__emit","propLocale","disabled","readonly","pagedNavigation","weekdayFormat","fixedWeeks","numberOfMonths","preventDeselect","propsIsDateDisabled","propsIsDateUnavailable","propsIsDateHighlightable","defaultOpen","modal","id","name","required","minValue","maxValue","granularity","hideTimeZone","hourCycle","propsDir","allowNonContiguousRanges","fixedDate","maximumDays","step","closeOnSelect","vue","dir","require_shared_useDirection","locale","require_shared_useLocale","weekStartsOn","require_date_calendar","modelValue","__vueuse_core","defaultDate","require_date_comparators","placeholder","open","dateFieldRef","value","date","require_Popover_PopoverRoot","$event","_ctx","useRangeCalendarState","props: UseRangeCalendarProps","isStartInvalid","vue","props","isEndInvalid","isInvalid","require_date_comparators","isSelectionStart","date: DateValue","__internationalized_date","date","isSelectionEnd","isSelected","rangeIsDateDisabled","diff","require_date_calendar","daysLeft","startLimit","endLimit","maxDate","minDate","isDateHighlightable","highlightedRange","isStartBeforeFocused","start","end","maximumDays","anchor","focused","isHighlightedStart","isHighlightedEnd","hasSelectedDate","isStartDateDisabled","isEndDateDisabled","isSelectedDisabled","hasStart","hasEnd","selectedFocusableDate","injectRangeCalendarRootContext","provideRangeCalendarRootContext","require_shared_createContext","props","__props","emits","__emit","disabled","readonly","initialFocus","pagedNavigation","weekdayFormat","fixedWeeks","numberOfMonths","preventDeselect","propsIsDateUnavailable","propsIsDateHighlightable","propsIsDateDisabled","calendarLabel","maxValue","minValue","propDir","propLocale","propsNextPage","propsPrevPage","allowNonContiguousRanges","disableDaysOutsideCurrentView","fixedDate","maximumDays","vue","primitiveElement","parentElement","require_Primitive_usePrimitiveElement","dir","require_shared_useDirection","locale","require_shared_useLocale","weekStartsOn","require_date_calendar","lastPressedDateValue","focusedValue","isEditing","modelValue","__vueuse_core","normalizeRange","value","normalizedModelValue","validModelValue","defaultDate","require_date_comparators","startValue","endValue","placeholder","onPlaceholderChange","fullCalendarLabel","headingValue","isDateDisabled","isDateUnavailable","isNextButtonDisabled","isPrevButtonDisabled","grid","weekdays","isOutsideVisibleView","nextPage","prevPage","formatter","isPlaceholderFocusable","firstFocusableDate","require_Calendar_useCalendar","isInvalid","isSelected","isDateHighlightable","highlightedRange","isSelectionStart","isSelectionEnd","isHighlightedStart","isHighlightedEnd","rangeIsDateDisabled","hasSelectedDate","isSelectedDisabled","selectedFocusableDate","require_RangeCalendar_useRangeCalendar","_modelValue","next","__internationalized_date","_startValue","_endValue","nextValue","kbd","require_shared_useKbd","ev","require_date_utils","require_Primitive_Primitive","as","asChild","_hoisted_1","_hoisted_2","_ctx","rootContext","require_DateRangePicker_DateRangePickerRoot","vue","require_RangeCalendar_RangeCalendarRoot","_cache","date","__internationalized_date","weekDays","grid","weekStartsOn","locale","fixedWeeks","_ctx","rootContext","require_RangeCalendar_RangeCalendarRoot","vue","require_Primitive_Primitive","as","asChild","date","_ctx","props","__props","vue","require_RangeCalendar_RangeCalendarCell","_ctx","props","__props","rootContext","require_RangeCalendar_RangeCalendarRoot","kbd","require_shared_useKbd","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","labelText","vue","require_date_comparators","isUnavailable","isSelectedDate","isSelectionStart","isSelectionEnd","isHighlightStart","isHighlightEnd","isHighlighted","allowNonContiguousRanges","isDateToday","__internationalized_date","isOutsideView","isOutsideVisibleView","isDisabled","dayValue","isFocusedDate","changeDate","e","date","handleClick","handleFocus","handleArrowKey","parentElement","indexIncrementation","sign","shiftFocus","day","add","candidateDayValue","candidateDay","require_Primitive_Primitive","as","asChild","_ctx","props","__props","vue","require_RangeCalendar_RangeCalendarCellTrigger","slotProps","_ctx","props","__props","vue","require_Popover_PopoverClose","_ctx","props","__props","emits","__emit","propsToForward","vue","forwarded","require_shared_useForwardPropsEmits","require_Popover_PopoverPortal","portal","require_Popover_PopoverContent","$attrs","_cache","event","require_date_utils","_ctx","rootContext","require_DateRangePicker_DateRangePickerRoot","vue","require_DateRangeField_DateRangeFieldRoot","_cache","date","__internationalized_date","segments","modelValue","_ctx","props","__props","rootContext","require_RangeCalendar_RangeCalendarRoot","disabled","vue","readonly","require_Primitive_Primitive","_cache","$event","_ctx","props","__props","vue","require_RangeCalendar_RangeCalendarGrid","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_RangeCalendar_RangeCalendarGridBody","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_RangeCalendar_RangeCalendarGridHead","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_RangeCalendar_RangeCalendarGridRow","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_RangeCalendar_RangeCalendarHeadCell","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_RangeCalendar_RangeCalendarHeader","_ctx","props","__props","rootContext","require_RangeCalendar_RangeCalendarRoot","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_RangeCalendar_RangeCalendarHeading","headingValue","_ctx","props","__props","vue","require_DateRangeField_DateRangeFieldInput","_ctx","props","__props","disabled","vue","rootContext","require_RangeCalendar_RangeCalendarRoot","handleClick","require_Primitive_Primitive","_ctx","_cache","props","__props","vue","require_RangeCalendar_RangeCalendarNext","slotProps","_ctx","props","__props","disabled","vue","rootContext","require_RangeCalendar_RangeCalendarRoot","handleClick","require_Primitive_Primitive","_ctx","_cache","props","__props","vue","require_RangeCalendar_RangeCalendarPrev","slotProps","_ctx","props","__props","rootContext","require_DateRangePicker_DateRangePickerRoot","vue","require_Popover_PopoverTrigger","_cache","e","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuArrow","_ctx","props","__props","emits","__emit","emitsAsProps","require_shared_useEmitAsProps","require_shared_useForwardExpose","vue","require_Menu_MenuCheckboxItem","_ctx","injectDropdownMenuRootContext","provideDropdownMenuRootContext","require_shared_createContext","props","__props","emit","__emit","require_shared_useForwardExpose","open","__vueuse_core","triggerElement","vue","modal","propDir","dir","require_shared_useDirection","value","require_Menu_MenuRoot","$event","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","require_shared_useForwardExpose","rootContext","require_DropdownMenu_DropdownMenuRoot","hasInteractedOutsideRef","vue","handleCloseAutoFocus","event","require_shared_useId","require_Menu_MenuContent","_cache","originalEvent","ctrlLeftClick","isRightClick","_ctx","props","__props","emits","__emit","modelValue","__vueuse_core","rootContext","require_Menu_MenuRoot","contentContext","require_Menu_MenuContentImpl","subContext","require_Menu_MenuSub","vue","v","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","disabled","activedescendant","isComposing","handleCompositionStart","handleCompositionEnd","require_shared_useComposing","event","el","handleInput","target","handleKeyDown","require_Primitive_Primitive","as","asChild","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuGroup","_ctx","props","__props","emits","__emit","emitsAsProps","require_shared_useEmitAsProps","require_shared_useForwardExpose","vue","require_Menu_MenuItem","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuItemIndicator","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuLabel","_ctx","props","__props","vue","require_Menu_MenuPortal","_ctx","props","__props","emits","__emit","emitsAsProps","require_shared_useEmitAsProps","require_shared_useForwardExpose","vue","require_Menu_MenuRadioGroup","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","require_shared_useForwardExpose","vue","require_Menu_MenuRadioItem","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuSeparator","_ctx","props","__props","emit","__emit","open","__vueuse_core","require_shared_useForwardExpose","vue","require_Menu_MenuSub","$event","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","require_shared_useForwardExpose","vue","require_Menu_MenuSubContent","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuSubTrigger","_ctx","props","__props","rootContext","require_DropdownMenu_DropdownMenuRoot","forwardRef","triggerElement","require_shared_useForwardExpose","vue","require_shared_useId","require_Menu_MenuAnchor","require_Primitive_Primitive","as","disabled","_cache","event","_ctx","injectEditableRootContext","provideEditableRootContext","require_shared_createContext","props","__props","emits","__emit","id","name","defaultValue","startWithEditMode","propPlaceholder","maxLength","disabled","propDir","submitMode","activationMode","selectOnFocus","readonly","autoResize","required","vue","inputRef","dir","require_shared_useDirection","isEditing","modelValue","__vueuse_core","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","isFormControl","require_shared_useFormControl","placeholder","inputValue","cancel","edit","submit","handleDismiss","pointerDownOutside","require_DismissableLayer_utils","focusOutside","isEmpty","__expose","require_Primitive_Primitive","$attrs","as","asChild","_ctx","require_VisuallyHidden_VisuallyHiddenInput","props","__props","context","require_Editable_EditableRoot","vue","require_Primitive_Primitive","_ctx","props","__props","context","require_Editable_EditableRoot","vue","require_Primitive_Primitive","as","_ctx","_cache","props","__props","context","require_Editable_EditableRoot","vue","require_Primitive_Primitive","as","_ctx","_cache","props","__props","kbd","require_shared_useKbd","context","require_Editable_EditableRoot","disabled","vue","placeholder","primitiveElement","inputRef","require_Primitive_usePrimitiveElement","value","handleSubmitKeyDown","event","require_Primitive_Primitive","_cache","$event","_ctx","props","__props","context","require_Editable_EditableRoot","placeholder","vue","handleFocus","handleDoubleClick","require_Primitive_Primitive","_ctx","props","__props","context","require_Editable_EditableRoot","vue","require_Primitive_Primitive","as","_ctx","_cache","props","__props","require_shared_useForwardExpose","vue","require_Popper_PopperArrow","_ctx","injectHoverCardRootContext","provideHoverCardRootContext","require_shared_createContext","props","__props","emit","__emit","openDelay","closeDelay","vue","require_shared_useForwardExpose","open","__vueuse_core","openTimerRef","closeTimerRef","hasSelectionRef","isPointerDownOnContentRef","isPointerInTransitRef","triggerElement","handleOpen","handleClose","handleDismiss","value","require_Popper_PopperRoot","_ctx","excludeTouch","eventHandler: () => void","event: PointerEvent","event","eventHandler","getTabbableNodes","container: HTMLElement","nodes: HTMLElement[]","walker","container","node: any","node","nodes","props","__props","emits","__emit","forwarded","require_shared_useForwardProps","forwardRef","contentElement","require_shared_useForwardExpose","rootContext","require_HoverCard_HoverCardRoot","isPointerInTransit","onPointerExit","require_shared_useGraceArea","__vueuse_shared","containSelection","vue","originalBodyUserSelect","cleanupFn","body","handlePointerUp","require_HoverCard_utils","tabbable","__vueuse_core","event","require_DismissableLayer_DismissableLayer","_cache","$event","require_Popper_PopperContent","$attrs","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","forwardRef","require_shared_useForwardExpose","rootContext","require_HoverCard_HoverCardRoot","vue","require_Presence_Presence","forceMount","require_HoverCard_HoverCardContentImpl","_cache","$event","require_HoverCard_utils","_ctx","props","__props","vue","require_Teleport_Teleport","_ctx","forwardRef","currentElement","require_shared_useForwardExpose","rootContext","require_HoverCard_HoverCardRoot","handleLeave","vue","require_Popper_PopperAnchor","reference","require_Primitive_Primitive","asChild","as","_cache","$event","require_HoverCard_utils","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Primitive_Primitive","_cache","event","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuArrow","_ctx","props","__props","emits","__emit","emitsAsProps","require_shared_useEmitAsProps","require_shared_useForwardExpose","vue","require_Menu_MenuCheckboxItem","_ctx","injectMenubarRootContext","provideMenubarRootContext","require_shared_createContext","props","__props","emit","__emit","forwardRef","require_shared_useForwardExpose","CollectionSlot","require_Collection_Collection","modelValue","__vueuse_core","currentTabStopId","vue","propDir","loop","dir","require_shared_useDirection","value","require_RovingFocus_RovingFocusGroup","$event","require_Primitive_Primitive","_ctx","injectMenubarMenuContext","provideMenubarMenuContext","require_shared_createContext","props","__props","value","require_shared_useId","rootContext","require_Menubar_MenubarRoot","require_shared_useForwardExpose","triggerElement","vue","wasKeyboardTriggerOpenRef","open","require_Menu_MenuRoot","_cache","value$1","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","require_shared_useForwardExpose","rootContext","require_Menubar_MenubarRoot","menuContext","require_Menubar_MenubarMenu","require_shared_useId","getItems","require_Collection_Collection","hasInteractedOutsideRef","vue","handleArrowNavigation","event","targetIsSubTrigger","isPrevKey","candidateValues","i","currentIndex","require_shared_useTypeahead","nextValue","require_Menu_MenuContent","_cache","target","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuGroup","_ctx","props","__props","emits","__emit","emitsAsProps","require_shared_useEmitAsProps","require_shared_useForwardExpose","vue","require_Menu_MenuItem","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuItemIndicator","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuLabel","_ctx","props","__props","vue","require_Menu_MenuPortal","_ctx","props","__props","emits","__emit","emitsAsProps","require_shared_useEmitAsProps","require_shared_useForwardExpose","vue","require_Menu_MenuRadioGroup","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","require_shared_useForwardExpose","vue","require_Menu_MenuRadioItem","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuSeparator","_ctx","props","__props","emit","__emit","require_shared_useForwardExpose","open","__vueuse_core","vue","require_Menu_MenuSub","$event","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","require_shared_useForwardExpose","getItems","require_Collection_Collection","rootContext","require_Menubar_MenubarRoot","menuContext","require_Menubar_MenubarMenu","handleArrowNavigation","event","candidateValues","i","currentIndex","require_shared_useTypeahead","nextValue","vue","require_Menu_MenuSubContent","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Menu_MenuSubTrigger","_ctx","rootContext","require_Menubar_MenubarRoot","menuContext","require_Menubar_MenubarMenu","forwardRef","triggerElement","require_shared_useForwardExpose","CollectionItem","require_Collection_Collection","isFocused","vue","open","require_RovingFocus_RovingFocusItem","disabled","require_Menu_MenuAnchor","require_Primitive_Primitive","as","asChild","_cache","event","$event","_ctx","useMonthPickerState","props: UseMonthPickerStateProps","isMonthSelected","dateObj: DateValue","props","d","require_date_comparators","dateObj","isInvalid","vue","useMonthPicker","props: UseMonthPickerProps","formatter","require_shared_useDateFormatter","resolveMatcher","matcher?: Matcher | Ref<Matcher | undefined>","matcher","headingFormatOptions","options: DateFormatterOptions","options","grid","require_date_calendar","isMonthDisabled","__internationalized_date","isMonthUnavailable","date: DateValue","date","isNextButtonDisabled","nextPageFunc?: (date: DateValue) => DateValue","currentDate","nextPageFunc","nextDate","nextYear","isPrevButtonDisabled","prevPageFunc?: (date: DateValue) => DateValue","prevPageFunc","prevDate","prevYear","nextPage","newDate","newDate$1","prevPage","value","headingValue","fullCalendarLabel","injectMonthPickerRootContext","provideMonthPickerRootContext","require_shared_createContext","props","__props","emits","__emit","disabled","readonly","initialFocus","multiple","minValue","maxValue","preventDeselect","propsIsMonthDisabled","propsIsMonthUnavailable","calendarLabel","defaultValue","propsNextPage","propsPrevPage","propDir","propLocale","vue","primitiveElement","parentElement","require_Primitive_usePrimitiveElement","locale","require_shared_useLocale","dir","require_shared_useDirection","headingId","require_shared_useId","modelValue","__vueuse_core","defaultDate","require_date_comparators","placeholder","onPlaceholderChange","value","fullCalendarLabel","headingValue","isMonthDisabled","isMonthUnavailable","isNextButtonDisabled","isPrevButtonDisabled","nextPage","prevPage","formatter","grid","require_MonthPicker_useMonthPicker","isInvalid","isMonthSelected","_modelValue","lastValue","resolveMonthValue","reference","onMonthChange","modelValueArray","index","date","next","require_date_utils","require_Primitive_Primitive","as","asChild","_ctx","_hoisted_1","_hoisted_2","rootContext","require_MonthPicker_MonthPickerRoot","vue","require_Primitive_Primitive","as","asChild","date","_ctx","props","__props","kbd","require_shared_useKbd","rootContext","require_MonthPicker_MonthPickerRoot","primitiveElement","require_Primitive_usePrimitiveElement","shortMonthValue","vue","require_date_comparators","labelText","isUnavailable","isCurrentMonth","todayDate","__internationalized_date","isDisabled","isFocusedMonth","isSelectedMonth","changeMonth","date","handleClick","handleArrowKey","e","parentElement","sign","shiftFocus","shiftFocusYear","currentMonth","add","depth","candidateMonthValue","candidateMonth","years","require_Primitive_Primitive","month","_cache","_ctx","props","__props","rootContext","require_MonthPicker_MonthPickerRoot","disabled","vue","readonly","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_MonthPicker_MonthPickerRoot","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_MonthPicker_MonthPickerRoot","disabled","vue","handleClick","require_Primitive_Primitive","_ctx","_cache","props","__props","rootContext","require_MonthPicker_MonthPickerRoot","disabled","vue","handleClick","require_Primitive_Primitive","_ctx","_cache","useRangeMonthPickerState","props: UseRangeMonthPickerProps","isStartInvalid","vue","props","isEndInvalid","isInvalid","require_date_comparators","isSelectionStart","date: DateValue","date","isSelectionEnd","isSelected","rangeIsMonthDisabled","maximumMonths","diff","monthsLeft","startLimit","endLimit","fixedValue","maxDate","minDate","highlightedRange","isStartBeforeFocused","start","end","anchor","focused","maxEnd","cappedEnd","minStart","injectMonthRangePickerRootContext","provideMonthRangePickerRootContext","require_shared_createContext","props","__props","emits","__emit","disabled","readonly","initialFocus","preventDeselect","propsIsMonthUnavailable","propsIsMonthDisabled","calendarLabel","maxValue","minValue","propDir","propLocale","propsNextPage","propsPrevPage","allowNonContiguousRanges","fixedDate","maximumMonths","vue","primitiveElement","parentElement","require_Primitive_usePrimitiveElement","dir","require_shared_useDirection","locale","require_shared_useLocale","headingId","require_shared_useId","lastPressedDateValue","focusedValue","isEditing","modelValue","__vueuse_core","normalizeRange","value","normalizedModelValue","validModelValue","defaultDate","require_date_comparators","startValue","endValue","placeholder","onPlaceholderChange","fullCalendarLabel","headingValue","isMonthDisabled","isMonthUnavailable","isNextButtonDisabled","isPrevButtonDisabled","grid","nextPage","prevPage","formatter","require_MonthPicker_useMonthPicker","isInvalid","isSelected","highlightedRange","isSelectionStart","isSelectionEnd","isHighlightedStart","isHighlightedEnd","rangeIsMonthDisabled","require_MonthRangePicker_useRangeMonthPicker","_modelValue","next","_startValue","_endValue","nextValue","kbd","require_shared_useKbd","ev","require_date_utils","require_Primitive_Primitive","as","asChild","_hoisted_1","_hoisted_2","_ctx","rootContext","require_MonthRangePicker_MonthRangePickerRoot","vue","require_Primitive_Primitive","as","asChild","date","_ctx","props","__props","kbd","require_shared_useKbd","rootContext","require_MonthRangePicker_MonthRangePickerRoot","primitiveElement","require_Primitive_usePrimitiveElement","shortMonthValue","vue","require_date_comparators","labelText","isUnavailable","isCurrentMonth","todayDate","__internationalized_date","isDisabled","isFocusedMonth","isSelectedMonth","isSelectionStart","isSelectionEnd","isHighlightStart","isHighlightEnd","isHighlighted","allowNonContiguousRanges","changeMonth","e","date","handleClick","handleFocus","handleArrowKey","parentElement","sign","shiftFocus","shiftFocusYear","currentMonth","add","depth","candidateMonthValue","candidateMonth","years","require_Primitive_Primitive","month","_cache","_ctx","props","__props","rootContext","require_MonthRangePicker_MonthRangePickerRoot","disabled","vue","readonly","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_MonthRangePicker_MonthRangePickerRoot","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_MonthRangePicker_MonthRangePickerRoot","disabled","vue","handleClick","require_Primitive_Primitive","_ctx","_cache","props","__props","rootContext","require_MonthRangePicker_MonthRangePickerRoot","disabled","vue","handleClick","require_Primitive_Primitive","_ctx","_cache","getOpenState","open: boolean","open","makeTriggerId","baseId: string","value: string","baseId","value","makeContentId","LINK_SELECT","EVENT_ROOT_CONTENT_DISMISS","getTabbableCandidates","container: HTMLElement","nodes: HTMLElement[]","walker","container","node: any","isHiddenInput","node","nodes","focusFirst","candidates: HTMLElement[]","previouslyFocusedElement","require_shared_getActiveElement","candidates","candidate","removeFromTabOrder","prevTabIndex","whenMouse","handler: (event?: E) => void","event: E","event","handler","injectNavigationMenuContext","provideNavigationMenuContext","require_shared_createContext","props","__props","emits","__emit","modelValue","__vueuse_core","previousValue","vue","forwardRef","rootNavigationMenu","require_shared_useForwardExpose","indicatorTrack","viewport","activeTrigger","getItems","CollectionSlot","require_Collection_Collection","delayDuration","skipDelayDuration","propDir","disableClickTrigger","disableHoverTrigger","unmountOnHide","dir","require_shared_useDirection","isDelaySkipped","skipNextClose","computedDelay","debouncedFn","val","items","i","item","require_NavigationMenu_utils","onItemDismiss","require_shared_useId","require_Primitive_Primitive","as","asChild","orientation","_ctx","injectNavigationMenuItemContext","provideNavigationMenuItemContext","require_shared_createContext","props","__props","require_shared_useForwardExpose","getItems","require_Collection_Collection","context","require_NavigationMenu_NavigationMenuRoot","value","require_shared_useId","triggerRef","vue","focusProxyRef","contentId","require_NavigationMenu_utils","restoreContentTabOrderRef","wasEscapeCloseRef","handleContentEntry","side","el","candidates","handleContentExit","handleClose","handleKeydown","ev","currentFocus","require_shared_getActiveElement","itemsArray","i","newSelectedElement","require_shared_useArrowNavigation","require_Primitive_Primitive","asChild","as","_ctx","props","__props","emits","__emit","getItems","require_Collection_Collection","forwardRef","currentElement","require_shared_useForwardExpose","menuContext","require_NavigationMenu_NavigationMenuRoot","itemContext","require_NavigationMenu_NavigationMenuItem","triggerId","require_NavigationMenu_utils","contentId","prevMotionAttributeRef","vue","motionAttribute","values","i","index","prevIndex","isSelected","wasSelected","attribute","handleFocusOutside","ev","target$1","handlePointerDownOutside","target","isTrigger","isRootViewport","cleanupFn","content","handleClose","require_shared_getActiveElement","handleEscapeKeyDown","handleKeydown","isMetaKey","isTabKey","candidates","focusedElement","candidate","nextCandidates","require_shared_useArrowNavigation","handleDismiss","rootContentDismissEvent","require_DismissableLayer_DismissableLayer","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","__vueuse_shared","forwardRef","require_shared_useForwardExpose","menuContext","require_NavigationMenu_NavigationMenuRoot","itemContext","require_NavigationMenu_NavigationMenuItem","open","vue","isLastActiveValue","require_Presence_Presence","forceMount","present","require_NavigationMenu_NavigationMenuContentImpl","require_NavigationMenu_utils","$attrs","_cache","$event","_ctx","props","__props","forwardRef","require_shared_useForwardExpose","menuContext","require_NavigationMenu_NavigationMenuRoot","indicatorStyle","vue","isHorizontal","isVisible","activeTrigger","handlePositionChange","__vueuse_core","require_Presence_Presence","forceMount","require_Primitive_Primitive","as","$attrs","_ctx","props","__props","emits","__emit","CollectionItem","require_Collection_Collection","require_shared_useForwardExpose","handleClick","ev","linkSelectEvent","require_NavigationMenu_utils","rootContentDismissEvent","vue","require_Primitive_Primitive","as","active","_ctx","props","__props","menuContext","require_NavigationMenu_NavigationMenuRoot","forwardRef","currentElement","require_shared_useForwardExpose","vue","require_Primitive_Primitive","$attrs","as","_ctx","props","__props","emits","__emit","modelValue","__vueuse_core","previousValue","vue","menuContext","require_NavigationMenu_NavigationMenuRoot","forwardRef","currentElement","require_shared_useForwardExpose","indicatorTrack","viewport","activeTrigger","getItems","CollectionSlot","require_Collection_Collection","items","i","item","val","require_Primitive_Primitive","orientation","as","_ctx","props","__props","menuContext","require_NavigationMenu_NavigationMenuRoot","itemContext","require_NavigationMenu_NavigationMenuItem","CollectionItem","require_Collection_Collection","forwardRef","triggerElement","require_shared_useForwardExpose","triggerId","vue","contentId","hasPointerMoveOpenedRef","__vueuse_core","wasClickCloseRef","open","require_NavigationMenu_utils","handlePointerEnter","handlePointerMove","ev","handlePointerLeave","handleClick","event","handleKeydown","entryKey","setFocusProxyRef","node","handleVisuallyHiddenFocus","content","prevFocusedElement","wasTriggerFocused","wasFocusFromContent","require_Primitive_Primitive","disabled","as","$attrs","_ctx","require_VisuallyHidden_VisuallyHidden","props","__props","forwardRef","currentElement","require_shared_useForwardExpose","menuContext","require_NavigationMenu_NavigationMenuRoot","activeTrigger","rootNavigationMenu","modelValue","size","vue","position","open","content","el","updatePosition","bodyWidth","bodyHeight","rootRect","rect","offsetWidth","offsetHeight","startPositionLeft","startPositionTop","posLeft","posTop","screenOffset","rightOffset","bottomOffset","__vueuse_core","require_Presence_Presence","forceMount","_cache","present","require_Primitive_Primitive","$attrs","as","asChild","require_NavigationMenu_utils","$event","_ctx","$7fe67f77592add0a$var$formatterCache","$7fe67f77592add0a$var$supportsSignDisplay","$7fe67f77592add0a$var$supportsUnit","$7fe67f77592add0a$var$UNITS","$7fe67f77592add0a$export$cc77c4ff7e8673c5","locale","options","$7fe67f77592add0a$var$getCachedNumberFormatter","value","res","$7fe67f77592add0a$export$711b50b3c525e0f2","unit","unitDisplay","values","start","end","startParts","endParts","p","numberingSystem","cacheKey","a","b","numberFormatter","numberFormat","signDisplay","num","needsPositiveSign","negative","noSign","minus","$52ebab2a875d5a2c$var$CURRENCY_SIGN_REGEX","$52ebab2a875d5a2c$var$NUMBERING_SYSTEMS","$52ebab2a875d5a2c$export$cd11ab140839f11d","locale","options","value","$52ebab2a875d5a2c$var$getNumberParserImpl","minValue","maxValue","$52ebab2a875d5a2c$var$numberParserCache","defaultParser","$52ebab2a875d5a2c$var$getCachedNumberParser","numberingSystem","parser","cacheKey","b","$52ebab2a875d5a2c$var$NumberParserImpl","$52ebab2a875d5a2c$var$getSymbols","isGroupSymbolAllowed","fullySanitizedValue","isNegative","index","newValue","$7fe67f77592add0a$exports","obj","$52ebab2a875d5a2c$var$replaceAll","$52ebab2a875d5a2c$var$nonLiteralParts","$52ebab2a875d5a2c$var$pluralNumbers","formatter","intlOptions","originalOptions","symbolFormatter","allParts","posAllParts","pluralParts","n","noNumeralUnits","p","i","unit","minusSign","plusSign","decimal","group","allPartsLiterals","$52ebab2a875d5a2c$var$escapeRegex","pluralPartsLiterals","sortedLiterals","a","literals","numerals","indexes","d","numeral","str","find","replace","string","usePressedHold","options: { target?: MaybeComputedElementRef, disabled: Ref<boolean> }","disabled","options","timeout","vue","triggerHook","__vueuse_shared","resetTimeout","onIncrementPressStart","delay: number","delay","handlePressStart","handlePressEnd","isPressed","target","__vueuse_core","onPressStart","event: PointerEvent","event","onPressRelease","isClient","useNumberFormatter","locale: Ref<string>","options: Ref<Intl.NumberFormatOptions | undefined>","NumberFormatter","locale","useNumberParser","NumberParser","handleDecimalOperation","operator: '-' | '+'","value1: number","value2: number","result","operator","value1","value2","value1Decimal","value2Decimal","value1DecimalLength","value2DecimalLength","multiplier","injectNumberFieldRootContext","provideNumberFieldRootContext","require_shared_createContext","props","__props","emits","__emit","disabled","readonly","disableWheelChange","invertWheelChange","min","max","step","stepSnapping","formatOptions","id","propLocale","vue","modelValue","__vueuse_core","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","locale","require_shared_useLocale","isFormControl","require_shared_useFormControl","inputEl","isDecreaseDisabled","require_shared_nullish","clampInputValue","require_NumberField_utils","isIncreaseDisabled","handleChangingValue","type","multiplier","currentInputValue","numberParser","handleIncrease","handleDecrease","handleMinMaxValue","numberFormatter","inputMode","textValueFormatter","textValue","validate","val","setInputValue","clampedValue","require_shared_clamp","applyInputValue","parsedValue","el","require_Primitive_Primitive","$attrs","as","asChild","_ctx","name","require_VisuallyHidden_VisuallyHiddenInput","required","props","__props","rootContext","require_NumberField_NumberFieldRoot","isDisabled","vue","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","isPressed","onTrigger","require_NumberField_utils","require_Primitive_Primitive","as","_cache","_ctx","props","__props","rootContext","require_NumberField_NumberFieldRoot","isDisabled","vue","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","isPressed","onTrigger","require_NumberField_utils","require_Primitive_Primitive","as","_cache","_ctx","props","__props","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","rootContext","require_NumberField_NumberFieldRoot","kbd","require_shared_useKbd","isComposing","handleCompositionStart","handleCompositionEnd","require_shared_useComposing","handleKeydown","event","handleWheelEvent","require_shared_getActiveElement","vue","inputValue","handleChange","require_Primitive_Primitive","_cache","target","nextValue","$event","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Primitive_Primitive","_ctx","_cache","injectPaginationRootContext","providePaginationRootContext","require_shared_createContext","props","__props","emits","__emit","siblingCount","disabled","showEdges","vue","require_shared_useForwardExpose","page","__vueuse_core","pageCount","value","require_Primitive_Primitive","as","asChild","_ctx","props","__props","rootContext","require_Pagination_PaginationRoot","require_shared_useForwardExpose","disabled","vue","require_Primitive_Primitive","as","_cache","$event","_ctx","props","__props","rootContext","require_Pagination_PaginationRoot","require_shared_useForwardExpose","disabled","vue","require_Primitive_Primitive","as","_cache","$event","_ctx","range","start: number","end: number","length","end","start","_","idx","transform","items: (string | number)[]","items","value","ELLIPSIS","getRange","currentPage: number","pageCount: number","siblingCount: number","showEdges: boolean","lastPageIndex","pageCount","leftSiblingIndex","currentPage","siblingCount","rightSiblingIndex","showEdges","itemCount","showLeftEllipsis","showRightEllipsis","rightRange","middleRange","props","__props","require_shared_useForwardExpose","rootContext","require_Pagination_PaginationRoot","transformedRange","vue","require_Pagination_utils","require_Primitive_Primitive","_ctx","props","__props","require_shared_useForwardExpose","rootContext","require_Pagination_PaginationRoot","isSelected","vue","disabled","require_Primitive_Primitive","value","as","_cache","$event","_ctx","props","__props","require_shared_useForwardExpose","rootContext","require_Pagination_PaginationRoot","disabled","vue","require_Primitive_Primitive","as","_cache","$event","_ctx","props","__props","require_shared_useForwardExpose","rootContext","require_Pagination_PaginationRoot","disabled","vue","require_Primitive_Primitive","as","_cache","$event","_ctx","injectPinInputRootContext","providePinInputRootContext","require_shared_createContext","props","__props","emits","__emit","mask","otp","placeholder","type","disabled","propDir","vue","forwardRef","require_shared_useForwardExpose","dir","require_shared_useDirection","modelValue","__vueuse_core","currentModelValue","inputElements","onInputElementChange","el","isNumericMode","isCompleted","i","require_Primitive_Primitive","$attrs","_ctx","require_VisuallyHidden_VisuallyHiddenInput","id","name","required","_cache","$event","props","__props","context","require_PinInput_PinInputRoot","inputElements","vue","currentValue","disabled","isOtpMode","isPasswordMode","NUMBER_REG","NON_NUMBER_REG","primitiveElement","currentElement","require_Primitive_usePrimitiveElement","isComposing","handleCompositionStart","handleCompositionEnd","require_shared_useComposing","event","target","value","filtered","handleMultipleCharacter","updateModelValueAt","nextEl$1","nextEl","handleInput","updatePlaceholder","require_shared_getActiveElement","handleKeydown","require_shared_useArrowNavigation","handleBackspace","prevEl","handleDelete","handleFocus","firstEmptyInputIdx","_","idx","handleBlur","handlePaste","clipboardData","rawValues","values","tempModelValue","initialIndex","lastIndex","i","input","num","removeTrailingEmptyStrings","index","require_Primitive_Primitive","as","asChild","_cache","$event","_ctx","DEFAULT_MAX","injectProgressRootContext","provideProgressRootContext","require_shared_createContext","isNumber","v","validateValue","value","max","require_shared_nullish","validateMax","props","__props","emit","__emit","require_shared_useForwardExpose","modelValue","__vueuse_core","vue","correctedValue","newMax","correctedMax","progressState","require_Primitive_Primitive","asChild","as","getValueText","getValueLabel","_ctx","props","__props","rootContext","require_Progress_ProgressRoot","require_shared_useForwardExpose","vue","require_Primitive_Primitive","_ctx","RADIO_SELECT","handleSelect","event: MouseEvent","value: AcceptableValue | undefined","callback: (event: SelectEvent) => void","eventDetail","event","value","require_shared_handleAndDispatchCustomEvent","callback","props","__props","emits","__emit","checked","__vueuse_core","value","vue","forwardRef","triggerElement","require_shared_useForwardExpose","isFormControl","require_shared_useFormControl","ariaLabel","handleClick","event","require_RadioGroup_utils","ev","require_Primitive_Primitive","$attrs","id","as","asChild","disabled","required","name","_ctx","require_VisuallyHidden_VisuallyHiddenInput","injectRadioGroupRootContext","provideRadioGroupRootContext","require_shared_createContext","props","__props","emits","__emit","forwardRef","currentElement","require_shared_useForwardExpose","modelValue","__vueuse_core","disabled","loop","orientation","name","required","propDir","vue","dir","require_shared_useDirection","isFormControl","require_shared_useFormControl","value","require_RovingFocus_RovingFocusGroup","require_Primitive_Primitive","asChild","as","_ctx","require_VisuallyHidden_VisuallyHiddenInput","injectRadioGroupItemContext","provideRadiogroupItemContext","require_shared_createContext","props","__props","emits","__emit","forwardRef","currentElement","require_shared_useForwardExpose","rootContext","require_RadioGroup_RadioGroupRoot","disabled","vue","required","checked","ohash","isArrowKeyPressed","ARROW_KEYS","__vueuse_core","event","handleFocus","require_RovingFocus_RovingFocusItem","require_RadioGroup_Radio","$attrs","_cache","$event","value","_ctx","forwardRef","require_shared_useForwardExpose","itemContext","require_RadioGroup_RadioGroupItem","vue","require_Presence_Presence","forceMount","require_Primitive_Primitive","asChild","as","$attrs","_ctx","injectScrollAreaRootContext","provideScrollAreaRootContext","require_shared_createContext","props","__props","cornerWidth","vue","cornerHeight","viewport","content","scrollbarX","scrollbarY","scrollbarXEnabled","scrollbarYEnabled","type","propDir","scrollHideDelay","dir","require_shared_useDirection","scrollTop","scrollTopLeft","__expose","forwardRef","scrollArea","require_shared_useForwardExpose","el","scrollbar","rendered","width","height","require_Primitive_Primitive","as","_ctx","rootContext","require_ScrollArea_ScrollAreaRoot","width","vue","height","hasSize","setCornerHeight","offsetHeight","setCornerWidth","offsetWidth","__vueuse_core","require_Primitive_Primitive","$parent","_ctx","props","__props","forwardRef","require_shared_useForwardExpose","rootContext","require_ScrollArea_ScrollAreaRoot","hasBothScrollbarsVisible","vue","hasCorner","require_ScrollArea_ScrollAreaCornerImpl","_ctx","linearScale","input: readonly [number, number]","output: readonly [number, number]","value: number","input","output","ratio","value","getThumbSize","sizes: Sizes","getThumbRatio","sizes","scrollbarPadding","thumbSize","viewportSize: number","contentSize: number","viewportSize","contentSize","addUnlinkedScrollListener","node: HTMLElement","handler","prevPosition","node","rAF","loop","position","isHorizontalScroll","isVerticalScroll","getThumbOffsetFromScroll","scrollPos: number","dir: Direction","thumbSizePx","scrollbar","maxScrollPos","maxThumbPos","scrollClampRange","dir","scrollWithoutMomentum","require_shared_clamp","scrollPos","toInt","value?: string","getScrollPositionFromPointer","pointerPos: number","pointerOffset: number","thumbCenter","offset","pointerOffset","thumbOffsetFromEnd","minPointerPos","maxPointerPos","scrollRange","pointerPos","isScrollingWithinScrollbarBounds","maxScrollPos: number","rootContext","require_ScrollArea_ScrollAreaRoot","scrollbarVisibleContext","require_ScrollArea_ScrollAreaScrollbarVisible","forwardRef","scrollbarElement","require_shared_useForwardExpose","vue","sizes","require_ScrollArea_ScrollAreaScrollbarImpl","require_ScrollArea_utils","_cache","$event","_ctx","rootContext","require_ScrollArea_ScrollAreaRoot","scrollbarVisibleContext","require_ScrollArea_ScrollAreaScrollbarVisible","forwardRef","scrollbarElement","require_shared_useForwardExpose","vue","sizes","require_ScrollArea_ScrollAreaScrollbarImpl","require_ScrollArea_utils","_cache","$event","_ctx","rootContext","require_ScrollArea_ScrollAreaRoot","scrollbarContext","require_ScrollArea_ScrollAreaScrollbar","forwardRef","require_shared_useForwardExpose","visible","vue","handleResize","__vueuse_core","isOverflowX","isOverflowY","require_Presence_Presence","forceMount","require_ScrollArea_ScrollAreaScrollbarVisible","$attrs","_ctx","rootContext","require_ScrollArea_ScrollAreaRoot","scrollbarContext","require_ScrollArea_ScrollAreaScrollbar","forwardRef","require_shared_useForwardExpose","state","dispatch","require_shared_useStateMachine","visible","vue","handlePointerEnter","handlePointerLeave","debounceScrollEnd","__vueuse_core","onCleanup","timeId","viewport","scrollDirection","prevScrollPos","handleScroll","scrollPos","scrollArea","require_Presence_Presence","forceMount","require_ScrollArea_ScrollAreaScrollbarAuto","$attrs","_ctx","rootContext","require_ScrollArea_ScrollAreaRoot","forwardRef","require_shared_useForwardExpose","timeout","visible","vue","handlePointerEnter","handlePointerLeave","scrollArea","require_Presence_Presence","forceMount","require_ScrollArea_ScrollAreaScrollbarAuto","$attrs","_ctx","rootContext","require_ScrollArea_ScrollAreaRoot","scrollbarContext","require_ScrollArea_ScrollAreaScrollbar","forwardRef","require_shared_useForwardExpose","state","dispatch","require_shared_useStateMachine","visible","vue","onCleanup","timeId","debounceScrollEnd","__vueuse_core","viewport","scrollDirection","prevScrollPos","handleScroll","scrollPos","require_Presence_Presence","forceMount","require_ScrollArea_ScrollAreaScrollbarVisible","$attrs","_ctx","injectScrollAreaScrollbarContext","provideScrollAreaScrollbarContext","require_shared_createContext","props","__props","forwardRef","require_shared_useForwardExpose","rootContext","require_ScrollArea_ScrollAreaRoot","isHorizontal","vue","orientation","forceMount","asChild","as","require_ScrollArea_ScrollAreaScrollbarHover","$attrs","_ctx","require_ScrollArea_ScrollAreaScrollbarScroll","require_ScrollArea_ScrollAreaScrollbarGlimpse","require_ScrollArea_ScrollAreaScrollbarAuto","require_ScrollArea_ScrollAreaScrollbarVisible","injectScrollAreaScrollbarVisibleContext","provideScrollAreaScrollbarVisibleContext","require_shared_createContext","rootContext","require_ScrollArea_ScrollAreaRoot","scrollbarContext","require_ScrollArea_ScrollAreaScrollbar","forwardRef","require_shared_useForwardExpose","sizes","vue","hasThumb","thumbRatio","require_ScrollArea_utils","thumbRef","pointerOffset","handleWheelScroll","event","payload","isShowingScrollbarX","scrollPos","handleThumbDown","handleThumbUp","handleSizeChange","getScrollPosition","pointerPos","dir","onDragScroll","onThumbPositionChange","offset","onThumbChange","element","require_ScrollArea_ScrollAreaScrollbarX","$attrs","_ctx","require_ScrollArea_ScrollAreaScrollbarY","props","__props","emit","__emit","rootContext","require_ScrollArea_ScrollAreaRoot","scrollbarVisibleContext","require_ScrollArea_ScrollAreaScrollbarVisible","scrollbarContext","require_ScrollArea_ScrollAreaScrollbar","forwardRef","scrollbar","require_shared_useForwardExpose","prevWebkitUserSelectRef","vue","rectRef","handleDragScroll","event","x","y","handlePointerDown","handlePointerMove","handlePointerUp","element","handleWheel","isScrollbarWheel","maxScrollPos","handleSizeChange","require_ScrollArea_utils","__vueuse_core","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_ScrollArea_ScrollAreaRoot","scrollbarContextVisible","require_ScrollArea_ScrollAreaScrollbarVisible","handlePointerDown","event","thumbRect","x","handlePointerUp","forwardRef","thumbElement","require_shared_useForwardExpose","removeUnlinkedScrollListenerRef","vue","viewport","handleScroll","listener","require_ScrollArea_utils","sizes","__vueuse_core","require_Primitive_Primitive","as","_ctx","props","__props","propNonce","vue","nonce","require_shared_useNonce","rootContext","require_ScrollArea_ScrollAreaRoot","viewportElement","contentElement","__expose","forwardRef","require_shared_useForwardExpose","$attrs","require_Primitive_Primitive","as","_ctx","_cache","OPEN_KEYS","SELECTION_KEYS","CONTENT_MARGIN","valueComparator","value: T | T[] | undefined","currentValue: T","comparator?: string | ((a: T, b: T) => boolean)","value","val","compare","currentValue","comparator","value?: T","currentValue?: T","ohash","shouldShowPlaceholder","value?: AcceptableValue | AcceptableValue[]","injectSelectRootContext","provideSelectRootContext","require_shared_createContext","props","__props","emits","__emit","required","disabled","multiple","propDir","vue","modelValue","__vueuse_core","open","triggerElement","valueElement","triggerPointerDownPosRef","isEmptyModelValue","require_shared_nullish","require_Collection_Collection","dir","require_shared_useDirection","isFormControl","require_shared_useFormControl","optionsSet","nativeSelectKey","option","handleValueChange","value","array","index","i","require_Select_utils","getOption","node","existingOption","require_Popper_PopperRoot","_ctx","name","require_Select_BubbleSelect","autocomplete","_hoisted_1","props","__props","selectElement","vue","rootContext","require_Select_SelectRoot","cur","prev","selectProto","setValue","event","handleInput","require_VisuallyHidden_VisuallyHidden","_ctx","props","__props","forwarded","require_shared_useForwardProps","vue","require_Popper_PopperContent","_ctx","SelectContentDefaultContextValue","injectSelectContentContext","provideSelectContentContext","require_shared_createContext","props","__props","emits","__emit","rootContext","require_Select_SelectRoot","require_shared_useFocusGuards","require_shared_useBodyScrollLock","CollectionSlot","getItems","require_Collection_Collection","content","vue","require_shared_useHideOthers","search","handleTypeaheadSearch","require_shared_useTypeahead","viewport","selectedItem","selectedItemText","isPositioned","firstValidItemFoundRef","firstSelectedItemInArrayFoundRef","focusSelectedItem","require_Menu_utils","onOpenChange","triggerPointerDownPosRef","cleanupFn","pointerMoveDelta","handlePointerMove","event","handlePointerUp","handleKeyDown","isModifierKey","candidateNodes","i","currentElement","currentIndex","pickedProps","forwardedProps","require_shared_useForwardProps","node","value","disabled","isFirstValidItem","isSelectedItem","require_Select_utils","require_FocusScope_FocusScope","_cache","require_DismissableLayer_DismissableLayer","disableOutsidePointerEvents","$event","position","require_Select_SelectPopperPosition","require_Select_SelectItemAlignedPosition","$attrs","vnode","el","__vueuse_core","_ctx","injectSelectItemAlignedPositionContext","provideSelectItemAlignedPositionContext","require_shared_createContext","props","__props","emits","__emit","getItems","require_Collection_Collection","rootContext","require_Select_SelectRoot","contentContext","require_Select_SelectContentImpl","shouldExpandOnScrollRef","vue","shouldRepositionRef","contentWrapperElement","forwardRef","contentElement","require_shared_useForwardExpose","viewport","selectedItem","selectedItemText","focusSelectedItem","position","triggerRect","contentRect","valueNodeRect","itemTextRect","itemTextOffset","left","leftDelta","minContentWidth","contentWidth","rightEdge","require_Select_utils","clampedLeft","require_shared_clamp","right","rightDelta","leftEdge","clampedRight","items","i","availableHeight","itemsHeight","contentStyles","contentBorderTopWidth","contentPaddingTop","contentBorderBottomWidth","contentPaddingBottom","fullContentHeight","minContentHeight","viewportStyles","viewportPaddingTop","viewportPaddingBottom","topEdgeToTriggerMiddle","triggerMiddleToBottomEdge","selectedItemHalfHeight","itemOffsetMiddle","contentTopToItemMiddle","itemMiddleToContentBottom","isLastItem","viewportOffsetBottom","clampedTriggerMiddleToBottomEdge","height","isFirstItem","contentZIndex","handleScrollButtonChange","node","__vueuse_core","require_Primitive_Primitive","$attrs","_ctx","props","__props","contentContext","require_Select_SelectContentImpl","vue","require_Popper_PopperArrow","_ctx","props","__props","require_Select_SelectRoot","require_Select_SelectContentImpl","vue","_ctx","props","__props","emits","__emit","forwarded","require_shared_useForwardPropsEmits","rootContext","require_Select_SelectRoot","fragment","vue","presenceRef","present","renderPresence","renderPresenceTimeout","clearRenderPresenceTimeout","_value","_oldValue","onCleanup","require_Presence_Presence","require_Select_SelectContentImpl","$attrs","_ctx","_hoisted_1","require_Select_SelectProvider","injectSelectGroupContext","provideSelectGroupContext","require_shared_createContext","props","__props","id","require_shared_useId","vue","require_Primitive_Primitive","_ctx","vue","require_Primitive_Primitive","as","asChild","_ctx","_cache","injectSelectItemContext","provideSelectItemContext","require_shared_createContext","props","__props","emits","__emit","disabled","vue","rootContext","require_Select_SelectRoot","contentContext","require_Select_SelectContentImpl","forwardRef","currentElement","require_shared_useForwardExpose","CollectionItem","require_Collection_Collection","isSelected","require_Select_utils","isFocused","textValue","textId","require_shared_useId","SELECT_SELECT","handleSelectCustomEvent","ev","eventDetail","require_shared_handleAndDispatchCustomEvent","handleSelect","handlePointerMove","event","handlePointerLeave","require_shared_getActiveElement","handleKeyDown","node","require_Primitive_Primitive","as","asChild","_cache","$event","_ctx","props","__props","itemContext","require_Select_SelectItem","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_Select_SelectRoot","contentContext","require_Select_SelectContentImpl","itemContext","require_Select_SelectItem","forwardRef","itemTextElement","require_shared_useForwardExpose","optionProps","vue","require_Primitive_Primitive","$attrs","_ctx","props","__props","groupContext","require_Select_SelectGroup","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Teleport_Teleport","_ctx","emits","__emit","getItems","require_Collection_Collection","contentContext","require_Select_SelectContentImpl","autoScrollTimerRef","vue","clearAutoScrollTimer","i","item","require_shared_getActiveElement","handlePointerDown","handlePointerMove","require_Primitive_Primitive","$parent","_cache","_ctx","contentContext","require_Select_SelectContentImpl","alignedPositionContext","require_Select_SelectItemAlignedPosition","forwardRef","currentElement","require_shared_useForwardExpose","canScrollDown","vue","cleanupFn","handleScroll","maxScroll","viewport","require_Select_SelectScrollButtonImpl","_cache","selectedItem","_ctx","contentContext","require_Select_SelectContentImpl","alignedPositionContext","require_Select_SelectItemAlignedPosition","forwardRef","currentElement","require_shared_useForwardExpose","canScrollUp","vue","cleanupFn","handleScroll","viewport","require_Select_SelectScrollButtonImpl","_cache","selectedItem","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_Select_SelectRoot","forwardRef","triggerElement","require_shared_useForwardExpose","isDisabled","vue","require_shared_useId","getItems","require_Collection_Collection","search","handleTypeaheadSearch","resetTypeahead","require_shared_useTypeahead","handleOpen","handlePointerOpen","event","require_Popper_PopperAnchor","reference","require_Primitive_Primitive","as","require_Select_utils","asChild","_cache","target","isTypingAhead","_ctx","props","__props","forwardRef","currentElement","require_shared_useForwardExpose","rootContext","require_Select_SelectRoot","vue","selectedLabel","list","options","getOption","value","option","require_Select_utils","slotText","require_Primitive_Primitive","as","asChild","_ctx","props","__props","propNonce","vue","nonce","require_shared_useNonce","contentContext","require_Select_SelectContentImpl","alignedPositionContext","require_Select_SelectItemAlignedPosition","forwardRef","currentElement","require_shared_useForwardExpose","prevScrollTopRef","handleScroll","event","viewport","shouldExpandOnScrollRef","contentWrapper","scrolledBy","availableHeight","require_Select_utils","cssMinHeight","cssHeight","prevHeight","nextHeight","clampedNextHeight","heightDiff","require_Primitive_Primitive","$attrs","_ctx","_cache","props","__props","ORIENTATIONS","isValidOrientation","orientation","computedOrientation","vue","ariaOrientation","semanticProps","require_Primitive_Primitive","as","asChild","_ctx","props","__props","vue","require_component_BaseSeparator","_ctx","assert","expectedCondition: any","message","expectedCondition","getPanelGroupElement","id: string","rootElement: ParentNode | HTMLElement","isBrowser","rootElement","id","element","getResizeHandleElement","scope: ParentNode | HTMLElement","scope","getResizeHandleElementIndex","groupId: string","getResizeHandleElementsForGroup","groupId","handle","getResizeHandlePanelIds","handleId: string","panelsArray: PanelData[]","handleId","handles","index","idBefore: string | null","panelsArray","idAfter: string | null","idBefore","idAfter","isKeyDown","event: ResizeEvent","event","isMouseEvent","isTouchEvent","getResizeEventCoordinates","touch","getResizeEventCursorPosition","direction: Direction","isHorizontal","direction","x","y","calculateDragOffsetPercentage","event: ResizeEvent","dragHandleId: string","direction: Direction","initialDragState: DragState","panelGroupElement: HTMLElement","isHorizontal","direction","handleElement","require_utils_dom","dragHandleId","panelGroupElement","require_utils_assert","groupId","initialCursorPosition","initialDragState","cursorPosition","require_utils_events","event","groupElement","groupRect","groupSizeInPixels","calculateDeltaPercentage","initialDragState: DragState | null","keyboardResizeBy: number | null","delta","keyboardResizeBy","movement","calculateAriaValues","layout","panelsArray","pivotIndices","currentMinSize","currentMaxSize","totalMinSize","totalMaxSize","firstIndex","panelData","index","constraints","maxSize","minSize","valueMax","valueMin","valueNow","calculateUnsafeDefaultLayout","panelDataArray","layout: number[]","panelConstraintsArray","numPanelsWithSizes","remainingSize","panelConstraints","defaultSize","numRemainingPanels","size","fuzzyCompareNumbers","actual: number","expected: number","fractionDigits: number","PRECISION","actual","fractionDigits","expected","delta","fuzzyNumbersEqual","fractionDigits?: number","callPanelCallbacks","panelsArray: PanelData[]","layout: number[]","panelIdToLastNotifiedSizeMap: Record<string, number>","groupSizeInPixels?: number | null","layout","size","index","panelData","panelsArray","require_utils_assert","callbacks","constraints","panelId","collapsedSize","collapsible","sizeUnit","displaySize","groupSizeInPixels","lastNotifiedSize","panelIdToLastNotifiedSizeMap","require_utils_compare","onCollapse","onExpand","onResize","debounce","callback: T","durationMs","timeoutId: NodeJS.Timeout | null","args","timeoutId","callback","resizePanel","panelConstraintsArray","panelIndex","size","panelConstraints","require_utils_assert","collapsedSize","collapsible","maxSize","minSize","require_utils_compare","halfwayPoint","PRECISION","compareLayouts","a: number[]","b: number[]","a","b","index","adjustLayoutByDelta","delta","prevLayout","panelConstraintsArray","pivotIndices","trigger","require_utils_compare","nextLayout","firstPivotIndex","secondPivotIndex","require_utils_assert","deltaApplied","panelConstraints","prevSize","collapsedSize","minSize","localDelta","collapsible","increment","maxAvailableDelta","require_utils_resizePanel","minAbsDelta","deltaRemaining","unsafeSize","safeSize","pivotIndex","totalSize","total","size","determinePivotIndices","groupId: string","dragHandleId: string","panelGroupElement: ParentNode","index","require_utils_dom","groupId","dragHandleId","panelGroupElement","intersects","rectOne: Rectangle","rectTwo: Rectangle","strict: boolean","strict","rectOne","rectTwo","compare","a: HTMLElement","b: HTMLElement","a","b","ancestors","getAncestors","common_ancestor","require_utils_assert","z_indexes","getZIndex","findStackingContext","children","furthest_ancestors","i","child","props","isFlexItem","node: HTMLElement","display","getParent","node","createsStackingContext","style","nodes: HTMLElement[]","nodes","node: HTMLElement | null","EXCEEDED_HORIZONTAL_MIN","EXCEEDED_HORIZONTAL_MAX","EXCEEDED_VERTICAL_MIN","EXCEEDED_VERTICAL_MAX","getInputType","isCoarsePointer","intersectingHandles: ResizeHandlerData[]","isPointerDown","ownerDocumentCounts: Map<Document, number>","panelConstraintFlags: Map<string, number>","registeredResizeHandlers","registerResizeHandle","resizeHandleId: string","element: HTMLElement","direction: Ref<Direction>","hitAreaMargins: PointerHitAreaMargins","nonce: Ref<string | undefined>","setResizeHandlerState: SetResizeHandlerState","ownerDocument","element","data: ResizeHandlerData","direction","hitAreaMargins","nonce","setResizeHandlerState","count","ownerDocumentCounts","data","updateListeners","panelConstraintFlags","resizeHandleId","require_utils_style","handlePointerDown","event: ResizeEvent","target","event","x","y","require_utils_events","recalculateIntersectingHandles","intersectingHandles","updateResizeHandlerStates","handlePointerMove","updateCursor","handlePointerUp","targetElement: HTMLElement | null","targetElement","dragHandleElement","dragHandleRect","bottom","left","right","top","margin","require_utils_stackingOrder","currentElement: HTMLElement | null","didIntersect","currentElement","require_utils_rects","reportConstraintsViolation","flag: number","flag","intersectsHorizontal","intersectsVertical","nonce: string | undefined","_nonce","constraintFlags","_","body","action: ResizeHandlerAction","isActive","action","currentCursorStyle: string | null","styleElement: HTMLStyleElement | null","getCursorStyle","state: CursorState","constraintFlags: number","constraintFlags","horizontalMin","EXCEEDED_HORIZONTAL_MIN","horizontalMax","EXCEEDED_HORIZONTAL_MAX","verticalMin","EXCEEDED_VERTICAL_MIN","verticalMax","EXCEEDED_VERTICAL_MAX","state","resetGlobalCursorStyle","styleElement","currentCursorStyle","setGlobalCursorStyle","nonce?: string","style","nonce","computePanelFlexBoxStyle","defaultSize","dragState","layout","panelData","panelIndex","precision","size","flexGrow","convertValueToPercent","sizeUnit","groupSizeInPixels","value","convertPanelConstraintsToPercent","panelDataArray","panelData","constraints","collapsedSize","defaultSize","maxSize","minSize","hasPixelSizedPanel","panelDataArray: PanelData[]","recalculateLayoutForPixelPanels","layout","prevGroupSize","nextGroupSize","pixelPanelIndices","indices","index","pixelIndexSet","nextLayout","size","prevPercentForPixelPanels","sum","nextPixelPercents","totalNextPixelPercent","prevPercentForPercentPanels","availableNextPercent","scaleFactor","panelIndex","arrayIndex","prevSize","total","factor","validatePanelGroupLayout","prevLayout","panelConstraints","nextLayout","nextLayoutTotalSize","accumulated","current","size","require_utils_compare","index","unsafeSize","require_utils_assert","safeSize","remainingSize","require_utils_resizePanel","prevSize","useWindowSplitterPanelGroupBehavior","eagerValuesRef","groupId","layout","panelDataArray","panelGroupElement","setLayout","getPanelDataWithPercentConstraints","vue","onCleanup","_panelGroupElement","panelDataArrayWithPercentConstraints","resizeHandleElements","require_utils_dom","index","valueMax","valueMin","valueNow","require_utils_calculate","resizeHandleElement","panelData","require_utils_assert","eagerValues","panelDataArray$1","groupElement","handles","cleanupFunctions","handle","handleId","idBefore","idAfter","onKeyDown","event: KeyboardEvent","event","size","collapsedSize","collapsible","minSize","nextLayout","require_utils_layout","require_utils_compare","panelData$1","require_utils_pivot","cleanupFunction","initializeDefaultStorage","storageObject: PanelGroupStorage","storageObject","name: string","name","value: string","value","error","getPanelGroupKey","autoSaveId: string","autoSaveId","getPanelKey","panels: PanelData[]","panels","panel","constraints","id","idIsFromProps","order","a","b","loadSerializedPanelGroupState","storage: PanelGroupStorage","panelGroupKey","serialized","storage","parsed","loadPanelGroupState","state","panelKey","savePanelGroupState","panelSizesBeforeCollapse: Map<string, number>","sizes: number[]","sizeUnits: { [panelIndex: number]: 'px' | '%' }","index","sizeUnits","panelSizesBeforeCollapse","sizes","LOCAL_STORAGE_DEBOUNCE_INTERVAL","defaultStorage","name","require_utils_storage","value","injectPanelGroupContext","providePanelGroupContext","require_shared_createContext","props","__props","emits","__emit","debounceMap","direction","vue","groupId","require_shared_useId","dir","require_shared_useDirection","forwardRef","panelGroupElementRef","require_shared_useForwardExpose","dragState","groupSizeInPixels","groupSizeAtLastLayoutInit","layout","panelIdToLastNotifiedSizeMapRef","panelSizeBeforeCollapseRef","prevDeltaRef","committedValuesRef","eagerValuesRef","getGroupSizeInPixels","element","rect","size","getPanelConstraintsInPercent","groupSizeOverride","groupSize","require_utils_units","getPanelDataWithPercentConstraints","percentConstraints","panelData","index","setLayout","val","convertLayoutToNativeUnits","internalLayout","panelDataArray","require_composables_useWindowSplitterPanelGroupBehavior","onCleanup","resizeObserver","entries","entry","height","width","nextSize","autoSaveId","debouncedSave","require_utils_debounce","clonedPanelDataArray","clonedPanelSizesBeforeCollapse","getPanelStyle","defaultSize","panelIndex","findPanelDataIndex","require_utils_style","registerPanel","panelA","panelB","orderA","orderB","storage","prevLayout","unsafeLayout","state","panelDataArrayWithPercentConstraints","require_utils_calculate","panelConstraints","nextLayout","require_utils_validation","require_shared_arrays","require_utils_callPanelCallbacks","prevSize","initSize","recalculatedLayout","require_utils_layout","registerResizeHandle","dragHandleId","event","panelGroupElement","direction$1","dragState$1","groupId$1","keyboardResizeBy","initialLayout","pivotIndices","require_utils_pivot","delta","isHorizontal","require_utils_events","layoutChanged","require_utils_registry","resizePanel","unsafePanelSize","panelConstraintsArray","panelUnit","sizeInPercent","panelSize","panelDataHelper","require_utils_assert","reevaluatePanelConstraints","prevConstraints","layout$1","nextConstraints","prevPanelSize","nextCollapsedSize","nextMaxSize","nextMinSize","isPanelCollapsed","startDragging","handleElement","require_utils_dom","initialCursorPosition","stopDragging","unregisterPanel","collapsePanel","collapsedSize","sizeUnit","sizeBeforeCollapse","expandPanel","minSize","require_utils_compare","restoredSize","baseSize","getPanelSize","collapsible","constraints","isPanelExpanded","prevPanelData","panelConstraintsFromGroup","require_Primitive_Primitive","as","asChild","_ctx","props","__props","emits","__emit","panelGroupContext","require_Splitter_SplitterGroup","collapsePanel","expandPanel","getPanelSize","getPanelStyle","isPanelCollapsed","resizePanel","groupId","reevaluatePanelConstraints","registerPanel","unregisterPanel","panelId","require_shared_useId","panelDataRef","vue","args","require_utils_constants","constraints","prevConstraints","style","isCollapsed","isExpanded","collapse","expand","resize","size","__expose","require_Primitive_Primitive","as","asChild","collapsible","_ctx","useWindowSplitterResizeHandlerBehavior","disabled","handleId","resizeHandler","panelGroupElement","vue","onCleanup","_panelGroupElement","handleElement","require_utils_dom","onKeyDown","event: KeyboardEvent","event","groupId","require_utils_assert","handles","index","nextIndex","props","__props","emits","__emit","forwardRef","currentElement","require_shared_useForwardExpose","disabled","vue","panelGroupContext","require_Splitter_SplitterGroup","direction","groupId","registerResizeHandleWithParentGroup","startDragging","stopDragging","panelGroupElement","resizeHandleId","require_shared_useId","state","isFocused","resizeHandler","propNonce","nonce","require_shared_useNonce","require_shared_browser","onCleanup","element","require_utils_assert","setResizeHandlerState","action","isActive","event","require_utils_registry","require_composables_useWindowSplitterBehavior","require_Primitive_Primitive","as","asChild","tabindex","_cache","$event","_ctx","injectStepperRootContext","provideStepperRootContext","require_shared_createContext","props","__props","emits","__emit","propDir","propOrientation","linear","vue","dir","require_shared_useDirection","totalStepperItems","modelValue","__vueuse_core","totalStepperItemsArray","isFirstStep","isLastStep","totalSteps","goToStep","step","nextStep","prevStep","hasNext","hasPrev","nextStepperItem","prevStepperItem","isNextDisabled","isPrevDisabled","value","__expose","require_shared_useForwardExpose","require_Primitive_Primitive","as","asChild","orientation","_ctx","_hoisted_1","injectStepperItemContext","provideStepperItemContext","require_shared_createContext","props","__props","disabled","step","completed","vue","forwardRef","require_shared_useForwardExpose","rootContext","require_Stepper_StepperRoot","titleId","require_shared_useId","descriptionId","itemState","isFocusable","require_Primitive_Primitive","as","asChild","_ctx","props","__props","require_shared_useForwardExpose","itemContext","require_Stepper_StepperItem","vue","require_Primitive_Primitive","_ctx","props","__props","itemContext","require_Stepper_StepperItem","require_shared_useForwardExpose","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_Stepper_StepperRoot","itemContext","require_Stepper_StepperItem","require_shared_useForwardExpose","vue","require_Separator_Separator","_ctx","props","__props","itemContext","require_Stepper_StepperItem","require_shared_useForwardExpose","vue","require_Primitive_Primitive","_ctx","rootContext","require_Stepper_StepperRoot","itemContext","require_Stepper_StepperItem","kbd","require_shared_useKbd","stepperItems","vue","handleMouseDown","event","handleKeyDown","require_shared_useArrowNavigation","require_shared_getActiveElement","forwardRef","currentElement","require_shared_useForwardExpose","require_Primitive_Primitive","as","asChild","_ctx","injectSwitchRootContext","provideSwitchRootContext","require_shared_createContext","props","__props","emit","__emit","disabled","vue","modelValue","__vueuse_core","checked","toggleCheck","forwardRef","currentElement","require_shared_useForwardExpose","isFormControl","require_shared_useFormControl","ariaLabel","require_Primitive_Primitive","$attrs","id","as","value","required","asChild","_ctx","name","require_VisuallyHidden_VisuallyHiddenInput","rootContext","require_Switch_SwitchRoot","require_shared_useForwardExpose","vue","require_Primitive_Primitive","asChild","as","_ctx","injectTabsRootContext","provideTabsRootContext","require_shared_createContext","props","__props","emits","__emit","orientation","unmountOnHide","propDir","vue","dir","require_shared_useDirection","require_shared_useForwardExpose","modelValue","__vueuse_core","tabsList","contentIds","value","require_shared_useId","newSet","require_Primitive_Primitive","asChild","as","_ctx","makeTriggerId","baseId: string","value: StringOrNumber","baseId","value","makeContentId","props","__props","forwardRef","require_shared_useForwardExpose","rootContext","require_Tabs_TabsRoot","triggerId","vue","require_Tabs_utils","contentId","isSelected","isMountAnimationPreventedRef","require_Presence_Presence","forceMount","present","require_Primitive_Primitive","asChild","as","_ctx","props","__props","context","require_Tabs_TabsRoot","__expose","updateIndicatorStyle","require_shared_useForwardExpose","isMounted","__vueuse_core","indicatorStyle","vue","tabs","activeTab","require_Primitive_Primitive","_ctx","props","__props","loop","vue","forwardRef","currentElement","require_shared_useForwardExpose","context","require_Tabs_TabsRoot","require_RovingFocus_RovingFocusGroup","require_Primitive_Primitive","asChild","as","_ctx","props","__props","forwardRef","require_shared_useForwardExpose","rootContext","require_Tabs_TabsRoot","triggerId","vue","require_Tabs_utils","contentId","isSelected","require_RovingFocus_RovingFocusItem","disabled","require_Primitive_Primitive","as","asChild","_cache","event","value","$event","isAutomaticActivation","_ctx","injectTagsInputRootContext","provideTagsInputRootContext","require_shared_createContext","props","__props","emits","__emit","addOnPaste","disabled","delimiter","max","id","propDir","addOnBlur","addOnTab","vue","dir","require_shared_useDirection","modelValue","__vueuse_core","forwardRef","currentElement","require_shared_useForwardExpose","focused","isFormControl","require_shared_useFormControl","getItems","CollectionSlot","require_Collection_Collection","selectedElement","isInvalidInput","currentModelValue","handleRemoveTag","index","collection","i","_","_payload","array","modelValueIsObject","defaultValueIsObject","payload","event","target","lastTag","isArrowRight","isArrowLeft","el","require_shared_useArrowNavigation","require_Primitive_Primitive","as","asChild","_ctx","name","require_VisuallyHidden_VisuallyHiddenInput","required","props","__props","require_shared_useForwardExpose","context","require_TagsInput_TagsInputRoot","handleCancel","vue","require_Primitive_Primitive","as","_ctx","props","__props","context","require_TagsInput_TagsInputRoot","forwardRef","currentElement","require_shared_useForwardExpose","handleBlur","event","target","relatedTarget","controlledId","handleTab","handleCustomKeydown","isComposing","handleCompositionStart","handleCompositionEnd","require_shared_useComposing","vue","handleInput","delimiter","handleInputKeydown","handlePaste","clipboardData","value","inputEl","require_Primitive_Primitive","as","asChild","maxLength","placeholder","_ctx","injectTagsInputItemContext","provideTagsInputItemContext","require_shared_createContext","props","__props","value","vue","context","require_TagsInput_TagsInputRoot","forwardRef","currentElement","require_shared_useForwardExpose","CollectionItem","require_Collection_Collection","isSelected","disabled","itemContext","require_Primitive_Primitive","as","asChild","_ctx","props","__props","require_shared_useForwardExpose","context","require_TagsInput_TagsInputRoot","itemContext","require_TagsInput_TagsInputItem","disabled","vue","handleDelete","index","i","ohash","require_Primitive_Primitive","as","_ctx","props","__props","itemContext","require_TagsInput_TagsInputItem","require_shared_useForwardExpose","require_shared_useId","vue","require_Primitive_Primitive","_ctx","injectTimeFieldRootContext","provideTimeFieldRootContext","require_shared_createContext","convertValue","value","date","__internationalized_date","props","__props","emits","__emit","disabled","readonly","granularity","defaultValue","minValue","maxValue","stepSnapping","propDir","propLocale","vue","locale","require_shared_useLocale","dir","require_shared_useDirection","formatter","require_shared_useDateFormatter","require_date_utils","primitiveElement","parentElement","require_Primitive_usePrimitiveElement","segmentElements","step","convertedMinValue","convertedMaxValue","require_date_segment","item","modelValue","__vueuse_core","convertedModelValue","require_shared_nullish","newValue","defaultDate","require_date_comparators","placeholder","convertedPlaceholder","inferredGranularity","isInvalid","initialSegments","require_date_parser","segmentValues","allSegmentContent","segmentContents","contents","segment","hour","displayHour","editableSegmentContents","part","_modelValue","currentFocusedElement","currentSegmentIndex","el","nextFocusableSegment","sign","prevFocusableSegment","kbd","require_shared_useKbd","handleKeydown","e","setFocusedElement","__expose","require_Primitive_Primitive","$attrs","_ctx","require_VisuallyHidden_VisuallyHidden","id","name","required","_cache","$event","props","__props","rootContext","require_TimeField_TimeFieldRoot","hasLeftFocus","vue","lastKeyZero","handleSegmentClick","handleSegmentKeydown","handleSegmentBeforeInput","handleSegmentCompositionStart","handleSegmentCompositionEnd","handleSegmentFocusOut","attributes","require_date_useDateField","disabled","readonly","isInvalid","require_Primitive_Primitive","as","asChild","part","e","_ctx","injectTimeRangeFieldRootContext","provideTimeRangeFieldRootContext","require_shared_createContext","convertValue","value","date","__internationalized_date","props","__props","emits","__emit","disabled","readonly","granularity","defaultValue","minValue","maxValue","propDir","propLocale","propsIsTimeUnavailable","vue","locale","require_shared_useLocale","dir","require_shared_useDirection","formatter","require_shared_useDateFormatter","require_date_utils","primitiveElement","parentElement","require_Primitive_usePrimitiveElement","segmentElements","step","convertedMinValue","convertedMaxValue","require_date_segment","item","modelValue","__vueuse_core","isStartInvalid","convertedStartValue$1","require_date_comparators","isEndInvalid","convertedEndValue$1","isInvalid","convertedModelValue$1","startValue","endValue","_startValue","_endValue","convertedStartValue","require_shared_nullish","newValue","convertedEndValue","convertedModelValue","defaultDate","placeholder","convertedPlaceholder","inferredGranularity","initialSegments","require_date_parser","startSegmentValues","endSegmentValues","startSegmentContent","endSegmentContent","segmentContents","editableSegmentContents","part","_modelValue","currentFocusedElement","currentSegmentIndex","el","nextFocusableSegment","sign","prevFocusableSegment","kbd","require_shared_useKbd","handleKeydown","e","setFocusedElement","__expose","require_Primitive_Primitive","$attrs","_ctx","require_VisuallyHidden_VisuallyHidden","id","name","required","_cache","$event","props","__props","rootContext","require_TimeRangeField_TimeRangeFieldRoot","hasLeftFocus","vue","lastKeyZero","handleSegmentClick","handleSegmentKeydown","handleSegmentBeforeInput","handleSegmentCompositionStart","handleSegmentCompositionEnd","attributes","require_date_useDateField","disabled","readonly","isInvalid","require_Primitive_Primitive","as","asChild","part","type","e","_ctx","vue","require_Primitive_Primitive","as","asChild","altText","_ctx","injectToastProviderContext","provideToastProviderContext","require_shared_createContext","props","__props","label","duration","disableSwipe","swipeDirection","swipeThreshold","vue","require_Collection_Collection","viewport","toastCount","isFocusedToastEscapeKeyDownRef","isClosePausedRef","error","el","_ctx","providerContext","require_Toast_ToastProvider","isAnnounced","__vueuse_shared","renderAnnounceText","vue","raf1","raf2","require_VisuallyHidden_VisuallyHidden","_ctx","TOAST_SWIPE_START","TOAST_SWIPE_MOVE","TOAST_SWIPE_CANCEL","TOAST_SWIPE_END","VIEWPORT_PAUSE","VIEWPORT_RESUME","handleAndDispatchCustomEvent","name: string","handler: ((event: E) => void) | undefined","detail: { originalEvent: OriginalEvent } & (E extends CustomEvent<infer D>\n    ? D\n    : never)","currentTarget","detail","event","name","handler","isDeltaInDirection","delta: { x: number, y: number }","direction: SwipeDirection","threshold","deltaX","delta","deltaY","isDeltaX","direction","isHTMLElement","node: any","node","getAnnounceTextContent","container: HTMLElement","textContent: string[]","container","textContent","isHidden","isExcluded","altText","injectToastRootContext","provideToastRootContext","require_shared_createContext","props","__props","emits","__emit","forwardRef","currentElement","require_shared_useForwardExpose","CollectionItem","require_Collection_Collection","providerContext","require_Toast_ToastProvider","pointerStartRef","vue","swipeDeltaRef","duration","closeTimerStartTimeRef","closeTimerRemainingTimeRef","closeTimerRef","remainingTime","remainingRaf","__vueuse_core","elapsedTime","startTimer","duration$1","__vueuse_shared","handleClose","event","isNonPointerEvent","require_shared_getActiveElement","announceTextContent","require_Toast_utils","error","cleanupFn","viewport","handleResume","handlePause","require_Toast_ToastAnnounce","type","text","i","require_Primitive_Primitive","$attrs","as","asChild","open","_cache","y","hasSwipeMoveStarted","isHorizontalSwipe","clamp","clampedX","clampedY","moveStartBuffer","delta","eventDetail","ev","target","toast","event$1","_ctx","props","__props","rootContext","require_Toast_ToastRootImpl","forwardRef","require_shared_useForwardExpose","vue","require_Toast_ToastAnnounceExclude","require_Primitive_Primitive","as","_ctx","__props","forwardRef","require_shared_useForwardExpose","altText","vue","require_Toast_ToastAnnounceExclude","require_Toast_ToastClose","as","asChild","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Teleport_Teleport","_ctx","props","__props","emits","__emit","forwardRef","require_shared_useForwardExpose","open","__vueuse_core","vue","require_Presence_Presence","forceMount","require_Toast_ToastRootImpl","type","as","asChild","duration","$attrs","_cache","$event","event","x","y","target","remaining","_duration","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Primitive_Primitive","_ctx","emits","__emit","providerContext","require_Toast_ToastProvider","vue","require_VisuallyHidden_VisuallyHidden","_cache","event","prevFocusedElement","_ctx","props","__props","hotkey","label","vue","forwardRef","currentElement","require_shared_useForwardExpose","CollectionSlot","getItems","require_Collection_Collection","providerContext","require_Toast_ToastProvider","hasToasts","headFocusProxyRef","tailFocusProxyRef","KEY_RE","DIGIT_RE","hotkeyMessage","__vueuse_core","cleanupFn","viewport","handlePause","pauseEvent","require_Toast_utils","handleResume","resumeEvent","handleFocusOutResume","event","handlePointerLeaveResume","require_shared_getActiveElement","handleKeyDown","isMetaKey","focusedElement","isTabbingBackwards","sortedCandidates","getSortedTabbableCandidates","index","candidate","require_FocusScope_utils","tabbingDirection","tabbableCandidates","i","toastNode","toastTabbableCandidates","require_DismissableLayer_DismissableLayerBranch","require_Toast_FocusProxy","node","_cache","require_Primitive_Primitive","as","asChild","$attrs","_ctx","injectToggleGroupRootContext","provideToggleGroupRootContext","require_shared_createContext","props","__props","emits","__emit","loop","rovingFocus","disabled","propDir","vue","dir","require_shared_useDirection","forwardRef","currentElement","require_shared_useForwardExpose","modelValue","changeModelValue","isSingle","require_shared_useSingleOrMultipleValue","isFormControl","require_shared_useFormControl","require_RovingFocus_RovingFocusGroup","require_Primitive_Primitive","orientation","asChild","as","_ctx","name","require_VisuallyHidden_VisuallyHiddenInput","required","props","__props","emits","__emit","forwardRef","currentElement","require_shared_useForwardExpose","toggleGroupContext","require_ToggleGroup_ToggleGroupRoot","modelValue","__vueuse_core","togglePressed","dataState","vue","isFormControl","require_shared_useFormControl","require_Primitive_Primitive","as","disabled","_ctx","name","require_VisuallyHidden_VisuallyHiddenInput","required","props","__props","rootContext","require_ToggleGroup_ToggleGroupRoot","disabled","vue","pressed","require_shared_isValueEqualOrExist","forwardRef","require_shared_useForwardExpose","require_RovingFocus_RovingFocusItem","require_Primitive_Primitive","require_Toggle_Toggle","_cache","$event","value","slotProps","_ctx","props","__props","forwardRef","require_shared_useForwardExpose","vue","require_RovingFocus_RovingFocusItem","disabled","require_Primitive_Primitive","as","_ctx","props","__props","forwardRef","require_shared_useForwardExpose","vue","require_RovingFocus_RovingFocusItem","require_Primitive_Primitive","_cache","event","_ctx","injectToolbarRootContext","provideToolbarRootContext","require_shared_createContext","props","__props","orientation","propDir","vue","dir","require_shared_useDirection","forwardRef","require_shared_useForwardExpose","require_RovingFocus_RovingFocusGroup","loop","require_Primitive_Primitive","asChild","as","_ctx","props","__props","rootContext","require_Toolbar_ToolbarRoot","require_shared_useForwardExpose","vue","require_component_BaseSeparator","as","_ctx","props","__props","emits","__emit","rootContext","require_Toolbar_ToolbarRoot","emitsAsProps","require_shared_useEmitAsProps","require_shared_useForwardExpose","vue","require_ToggleGroup_ToggleGroupRoot","_ctx","props","__props","forwardRef","require_shared_useForwardExpose","vue","require_Toolbar_ToolbarButton","require_ToggleGroup_ToggleGroupItem","_ctx","props","__props","require_shared_useForwardExpose","vue","require_Popper_PopperArrow","_ctx","injectTooltipProviderContext","provideTooltipProviderContext","require_shared_createContext","props","__props","delayDuration","skipDelayDuration","disableHoverableContent","disableClosingTrigger","ignoreNonKeyboardFocus","disabled","content","vue","require_shared_useForwardExpose","isOpenDelayed","isPointerInTransitRef","startTimer","clearTimer","__vueuse_shared","_ctx","TOOLTIP_OPEN","injectTooltipRootContext","provideTooltipRootContext","require_shared_createContext","props","__props","emit","__emit","require_shared_useForwardExpose","providerContext","require_Tooltip_TooltipProvider","disableHoverableContent","vue","disableClosingTrigger","disableTooltip","delayDuration","ignoreNonKeyboardFocus","open","__vueuse_core","isOpen","require_Tooltip_utils","wasOpenDelayedRef","trigger","stateAttribute","startTimer","clearTimer","handleOpen","handleClose","handleDelayedOpen","el","require_Popper_PopperRoot","_ctx","props","__props","emits","__emit","rootContext","require_Tooltip_TooltipRoot","providerContext","require_Tooltip_TooltipProvider","forwardRef","currentElement","require_shared_useForwardExpose","ariaLabel","vue","popperContentProps","_","restProps","defu","__vueuse_core","event","require_Tooltip_utils","require_DismissableLayer_DismissableLayer","_cache","$event","require_Popper_PopperContent","$attrs","_ctx","require_VisuallyHidden_VisuallyHidden","props","__props","forwardedProps","require_shared_useForwardProps","forwardRef","currentElement","require_shared_useForwardExpose","trigger","onClose","require_Tooltip_TooltipRoot","providerContext","require_Tooltip_TooltipProvider","isPointerInTransit","onPointerExit","require_shared_useGraceArea","vue","require_Tooltip_TooltipContentImpl","_ctx","props","__props","emits","__emit","rootContext","require_Tooltip_TooltipRoot","forwarded","require_shared_useForwardPropsEmits","forwardRef","require_shared_useForwardExpose","vue","require_Presence_Presence","forceMount","require_Tooltip_TooltipContentImpl","require_Tooltip_TooltipContentHoverable","_ctx","props","__props","vue","require_Teleport_Teleport","_ctx","props","__props","rootContext","require_Tooltip_TooltipRoot","providerContext","require_Tooltip_TooltipProvider","require_shared_useId","forwardRef","triggerElement","require_shared_useForwardExpose","isPointerDown","vue","hasPointerMoveOpened","tooltipListeners","handleClick","handleFocus","handlePointerMove","handlePointerLeave","handlePointerDown","handleBlur","handlePointerUp","event","require_Popper_PopperAnchor","reference","require_Primitive_Primitive","as","_ctx","flatten","items: T[]","items","acc: any[]","item: T","acc","item","injectTreeRootContext","provideTreeRootContext","require_shared_createContext","props","__props","emits","__emit","items","multiple","disabled","propagateSelect","propDir","bubbleSelect","vue","handleTypeaheadSearch","require_shared_useTypeahead","dir","require_shared_useDirection","rovingFocusGroupRef","isVirtual","virtualKeydownHook","__vueuse_core","modelValue","expanded","onSelectItem","handleMultipleReplace","require_shared_useSelectionBehavior","selectedKeys","i","flattenItems","items$1","level","parentItem","acc","item","index","key","children","isExpanded","flattenedItem","expandedItems","expandedKeys","handleKeydown","event","collections","handleKeydownNavigation","intent","require_RovingFocus_utils","require_shared_getActiveElement","handleBubbleSelect","v","val","condition","baseValue","exist","require_Tree_utils","child","val$1","require_RovingFocus_RovingFocusGroup","require_Primitive_Primitive","as","asChild","_ctx","TREE_SELECT","TREE_TOGGLE","props","__props","emits","__emit","rootContext","require_Tree_TreeRoot","getItems","require_Collection_Collection","hasChildren","vue","isExpanded","key","isSelected","isIndeterminate","children","require_Tree_utils","child","v","handleKeydownRight","ev","collection","i","currentElement","require_shared_getActiveElement","currentIndex","nextElement","el","handleToggleCustomEvent","handleKeydownLeft","parentElement","handleSelect","handleToggle","handleSelectCustomEvent","eventDetail","require_shared_handleAndDispatchCustomEvent","__expose","require_RovingFocus_RovingFocusItem","value","require_Primitive_Primitive","$attrs","as","asChild","level","_cache","_ctx","props","__props","slots","vue","rootContext","require_Tree_TreeRoot","parentEl","__vueuse_core","getItems","require_Collection_Collection","search","optionsWithMetadata","parseTextContent","option","index","padding","el","styles","virtualizer","__tanstack_vue_virtual","virtualizedItems","item","scrollToIndexAndFocus","event","isMetaKey","intent","require_RovingFocus_utils","items","currentElement","require_shared_getActiveElement","currentIndex","currentLevel","parentItem","currentMatch","filteredOptions","i","next","require_shared_useTypeahead","nextMatch","is","props","__props","forwardRef","require_shared_useForwardExpose","propNonce","vue","nonce","require_shared_useNonce","require_Primitive_Primitive","$attrs","_ctx","_cache","useYearPickerState","props: UseYearPickerStateProps","isYearSelected","dateObj: DateValue","props","d","require_date_comparators","dateObj","isInvalid","vue","useYearPicker","props: UseYearPickerProps","formatter","require_shared_useDateFormatter","resolveMatcher","matcher?: Matcher | Ref<Matcher | undefined>","matcher","headingFormatOptions","options: DateFormatterOptions","options","grid","require_date_calendar","isYearDisabled","__internationalized_date","isYearUnavailable","date: DateValue","date","isNextButtonDisabled","nextPageFunc?: (date: DateValue) => DateValue","lastYearInView","nextPageFunc","nextDate","nextPageStart","isPrevButtonDisabled","prevPageFunc?: (date: DateValue) => DateValue","firstYearInView","prevPageFunc","prevDate","prevPageEnd","nextPage","firstYearInGrid","newDate","newDate$1","prevPage","value","lastYearInGrid","headingValue","firstYear","lastYear","fullCalendarLabel","injectYearPickerRootContext","provideYearPickerRootContext","require_shared_createContext","props","__props","emits","__emit","disabled","readonly","initialFocus","multiple","minValue","maxValue","preventDeselect","propsIsYearDisabled","propsIsYearUnavailable","calendarLabel","defaultValue","propsNextPage","propsPrevPage","propDir","propLocale","yearsPerPage","vue","primitiveElement","parentElement","require_Primitive_usePrimitiveElement","locale","require_shared_useLocale","dir","require_shared_useDirection","headingId","require_shared_useId","modelValue","__vueuse_core","defaultDate","require_date_comparators","placeholder","onPlaceholderChange","value","fullCalendarLabel","headingValue","isYearDisabled","isYearUnavailable","isNextButtonDisabled","isPrevButtonDisabled","nextPage","prevPage","formatter","grid","require_YearPicker_useYearPicker","isInvalid","isYearSelected","_modelValue","lastValue","resolveYearValue","reference","onYearChange","index","date","next","require_date_utils","require_Primitive_Primitive","as","asChild","_ctx","_hoisted_1","_hoisted_2","rootContext","require_YearPicker_YearPickerRoot","vue","require_Primitive_Primitive","as","asChild","date","_ctx","props","__props","kbd","require_shared_useKbd","rootContext","require_YearPicker_YearPickerRoot","primitiveElement","require_Primitive_usePrimitiveElement","yearValue","vue","require_date_comparators","labelText","isUnavailable","isCurrentYear","todayDate","__internationalized_date","isDisabled","isFocusedYear","isSelectedYear","changeYear","date","handleClick","handleArrowKey","e","parentElement","sign","shiftFocus","shiftFocusPage","currentYear","add","depth","candidateYearValue","candidateYear","direction","yearsPerPage","require_Primitive_Primitive","year","_cache","_ctx","props","__props","rootContext","require_YearPicker_YearPickerRoot","disabled","vue","readonly","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_YearPicker_YearPickerRoot","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_YearPicker_YearPickerRoot","disabled","vue","handleClick","require_Primitive_Primitive","_ctx","_cache","props","__props","rootContext","require_YearPicker_YearPickerRoot","disabled","vue","handleClick","require_Primitive_Primitive","_ctx","_cache","useRangeYearPickerState","props: UseRangeYearPickerProps","isStartInvalid","vue","props","isEndInvalid","isInvalid","isSelectionStart","date: DateValue","require_date_comparators","date","isSelectionEnd","isSelected","rangeIsYearDisabled","maximumYears","diff","yearsLeft","startLimit","endLimit","fixedValue","maxDate","minDate","highlightedRange","isStartBeforeFocused","start","end","anchor","focused","maxEnd","cappedEnd","minStart","injectYearRangePickerRootContext","provideYearRangePickerRootContext","require_shared_createContext","props","__props","emits","__emit","disabled","readonly","initialFocus","preventDeselect","propsIsYearUnavailable","propsIsYearDisabled","calendarLabel","maxValue","minValue","propDir","propLocale","propsNextPage","propsPrevPage","allowNonContiguousRanges","fixedDate","maximumYears","yearsPerPage","vue","primitiveElement","parentElement","require_Primitive_usePrimitiveElement","dir","require_shared_useDirection","locale","require_shared_useLocale","headingId","require_shared_useId","lastPressedDateValue","focusedValue","isEditing","modelValue","__vueuse_core","normalizeRange","value","normalizedModelValue","validModelValue","defaultDate","require_date_comparators","startValue","endValue","placeholder","onPlaceholderChange","fullCalendarLabel","headingValue","isYearDisabled","isYearUnavailable","isNextButtonDisabled","isPrevButtonDisabled","grid","nextPage","prevPage","formatter","require_YearPicker_useYearPicker","isInvalid","isSelected","highlightedRange","isSelectionStart","isSelectionEnd","isHighlightedStart","isHighlightedEnd","rangeIsYearDisabled","require_YearRangePicker_useRangeYearPicker","_modelValue","next","_startValue","_endValue","nextValue","kbd","require_shared_useKbd","ev","require_date_utils","require_Primitive_Primitive","as","asChild","_hoisted_1","_hoisted_2","_ctx","rootContext","require_YearRangePicker_YearRangePickerRoot","vue","require_Primitive_Primitive","as","asChild","date","_ctx","props","__props","kbd","require_shared_useKbd","rootContext","require_YearRangePicker_YearRangePickerRoot","primitiveElement","require_Primitive_usePrimitiveElement","yearValue","vue","require_date_comparators","labelText","isUnavailable","isCurrentYear","todayDate","__internationalized_date","isDisabled","isFocusedYear","isSelectedYear","isSelectionStart","isSelectionEnd","isHighlightStart","isHighlightEnd","isHighlighted","allowNonContiguousRanges","changeYear","e","date","handleClick","handleFocus","handleArrowKey","parentElement","sign","shiftFocus","shiftFocusPage","currentYear","add","depth","candidateYearValue","candidateYear","direction","yearsPerPage","require_Primitive_Primitive","year","_cache","_ctx","props","__props","rootContext","require_YearRangePicker_YearRangePickerRoot","disabled","vue","readonly","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_YearRangePicker_YearRangePickerRoot","vue","require_Primitive_Primitive","_ctx","props","__props","rootContext","require_YearRangePicker_YearRangePickerRoot","disabled","vue","handleClick","require_Primitive_Primitive","_ctx","_cache","props","__props","rootContext","require_YearRangePicker_YearRangePickerRoot","disabled","vue","handleClick","require_Primitive_Primitive","_ctx","_cache","require_index2","__commonJSMin","require_dist","__commonJSMin","exports","require_shared_createContext","require_ConfigProvider_ConfigProvider","require_shared_useBodyScrollLock","require_shared_useDateFormatter","require_shared_useDirection","require_shared_useEmitAsProps","require_shared_useFilter","require_shared_useForwardExpose","require_shared_useForwardProps","require_shared_useForwardPropsEmits","require_shared_useId","require_shared_useLocale","require_shared_useStateMachine","require_shared_withDefault","require_Presence_Presence","require_Primitive_Slot","require_Primitive_Primitive","require_Collapsible_CollapsibleRoot","require_Collapsible_CollapsibleContent","require_Collapsible_CollapsibleTrigger","require_Accordion_AccordionRoot","require_Accordion_AccordionItem","require_Accordion_AccordionContent","require_Accordion_AccordionHeader","require_Accordion_AccordionTrigger","require_Dialog_DialogRoot","require_Dialog_DialogClose","require_FocusScope_FocusScope","require_Dialog_DialogContent","require_Dialog_DialogDescription","require_Dialog_DialogOverlay","require_Dialog_DialogPortal","require_Dialog_DialogTitle","require_Dialog_DialogTrigger","require_AlertDialog_AlertDialogAction","require_AlertDialog_AlertDialogContent","require_AlertDialog_AlertDialogCancel","require_AlertDialog_AlertDialogDescription","require_AlertDialog_AlertDialogOverlay","require_AlertDialog_AlertDialogPortal","require_AlertDialog_AlertDialogRoot","require_AlertDialog_AlertDialogTitle","require_AlertDialog_AlertDialogTrigger","require_AspectRatio_AspectRatio","require_VisuallyHidden_VisuallyHidden","require_Listbox_ListboxRoot","require_Listbox_ListboxContent","require_Listbox_ListboxFilter","require_Listbox_ListboxGroup","require_Listbox_ListboxGroupLabel","require_Listbox_ListboxItem","require_Listbox_ListboxItemIndicator","require_Listbox_ListboxVirtualizer","require_Combobox_ComboboxRoot","require_Autocomplete_AutocompleteRoot","require_Autocomplete_AutocompleteInput","require_Combobox_ComboboxAnchor","require_Combobox_ComboboxArrow","require_Combobox_ComboboxCancel","require_Combobox_ComboboxContent","require_Combobox_ComboboxEmpty","require_Combobox_ComboboxGroup","require_Combobox_ComboboxInput","require_Combobox_ComboboxItem","require_Combobox_ComboboxItemIndicator","require_Combobox_ComboboxLabel","require_Combobox_ComboboxPortal","require_Combobox_ComboboxSeparator","require_Combobox_ComboboxTrigger","require_Combobox_ComboboxViewport","require_Combobox_ComboboxVirtualizer","require_Avatar_AvatarRoot","require_Avatar_AvatarFallback","require_Avatar_AvatarImage","require_Calendar_CalendarRoot","require_Calendar_CalendarCell","require_Calendar_CalendarCellTrigger","require_Calendar_CalendarGrid","require_Calendar_CalendarGridBody","require_Calendar_CalendarGridHead","require_Calendar_CalendarGridRow","require_Calendar_CalendarHeadCell","require_Calendar_CalendarHeader","require_Calendar_CalendarHeading","require_Calendar_CalendarNext","require_Calendar_CalendarPrev","require_RovingFocus_RovingFocusGroup","require_RovingFocus_RovingFocusItem","require_Checkbox_CheckboxGroupRoot","require_Checkbox_CheckboxRoot","require_Checkbox_CheckboxIndicator","require_color_convert","require_color_channel","require_color_gradient","require_color_parse","require_ColorArea_ColorAreaRoot","require_ColorArea_ColorAreaArea","require_ColorArea_ColorAreaThumb","require_ColorField_ColorFieldRoot","require_ColorField_ColorFieldInput","require_Slider_SliderRoot","require_Slider_SliderRange","require_Slider_SliderThumb","require_Slider_SliderTrack","require_ColorSlider_ColorSliderRoot","require_ColorSlider_ColorSliderThumb","require_ColorSlider_ColorSliderTrack","require_ColorSwatch_ColorSwatch","require_ColorSwatchPicker_ColorSwatchPickerItem","require_ColorSwatchPicker_ColorSwatchPickerItemIndicator","require_ColorSwatchPicker_ColorSwatchPickerItemSwatch","require_ColorSwatchPicker_ColorSwatchPickerRoot","require_ContextMenu_ContextMenuArrow","require_ContextMenu_ContextMenuCheckboxItem","require_ContextMenu_ContextMenuRoot","require_ContextMenu_ContextMenuContent","require_ContextMenu_ContextMenuGroup","require_ContextMenu_ContextMenuItem","require_ContextMenu_ContextMenuItemIndicator","require_ContextMenu_ContextMenuLabel","require_ContextMenu_ContextMenuPortal","require_ContextMenu_ContextMenuRadioGroup","require_ContextMenu_ContextMenuRadioItem","require_ContextMenu_ContextMenuSeparator","require_ContextMenu_ContextMenuSub","require_ContextMenu_ContextMenuSubContent","require_ContextMenu_ContextMenuSubTrigger","require_ContextMenu_ContextMenuTrigger","require_DateField_DateFieldRoot","require_DateField_DateFieldInput","require_DatePicker_DatePickerAnchor","require_DatePicker_DatePickerArrow","require_DatePicker_DatePickerRoot","require_DatePicker_DatePickerCalendar","require_DatePicker_DatePickerCell","require_DatePicker_DatePickerCellTrigger","require_DatePicker_DatePickerClose","require_DatePicker_DatePickerContent","require_DatePicker_DatePickerField","require_DatePicker_DatePickerGrid","require_DatePicker_DatePickerGridBody","require_DatePicker_DatePickerGridHead","require_DatePicker_DatePickerGridRow","require_DatePicker_DatePickerHeadCell","require_DatePicker_DatePickerHeader","require_DatePicker_DatePickerHeading","require_DatePicker_DatePickerInput","require_DatePicker_DatePickerNext","require_DatePicker_DatePickerPrev","require_DatePicker_DatePickerTrigger","require_DateRangeField_DateRangeFieldRoot","require_DateRangeField_DateRangeFieldInput","require_DateRangePicker_DateRangePickerAnchor","require_DateRangePicker_DateRangePickerArrow","require_DateRangePicker_DateRangePickerRoot","require_DateRangePicker_DateRangePickerCalendar","require_DateRangePicker_DateRangePickerCell","require_DateRangePicker_DateRangePickerCellTrigger","require_DateRangePicker_DateRangePickerClose","require_DateRangePicker_DateRangePickerContent","require_DateRangePicker_DateRangePickerField","require_DateRangePicker_DateRangePickerGrid","require_DateRangePicker_DateRangePickerGridBody","require_DateRangePicker_DateRangePickerGridHead","require_DateRangePicker_DateRangePickerGridRow","require_DateRangePicker_DateRangePickerHeadCell","require_DateRangePicker_DateRangePickerHeader","require_DateRangePicker_DateRangePickerHeading","require_DateRangePicker_DateRangePickerInput","require_DateRangePicker_DateRangePickerNext","require_DateRangePicker_DateRangePickerPrev","require_DateRangePicker_DateRangePickerTrigger","require_DropdownMenu_DropdownMenuArrow","require_DropdownMenu_DropdownMenuCheckboxItem","require_DropdownMenu_DropdownMenuRoot","require_DropdownMenu_DropdownMenuContent","require_DropdownMenu_DropdownMenuFilter","require_DropdownMenu_DropdownMenuGroup","require_DropdownMenu_DropdownMenuItem","require_DropdownMenu_DropdownMenuItemIndicator","require_DropdownMenu_DropdownMenuLabel","require_DropdownMenu_DropdownMenuPortal","require_DropdownMenu_DropdownMenuRadioGroup","require_DropdownMenu_DropdownMenuRadioItem","require_DropdownMenu_DropdownMenuSeparator","require_DropdownMenu_DropdownMenuSub","require_DropdownMenu_DropdownMenuSubContent","require_DropdownMenu_DropdownMenuSubTrigger","require_DropdownMenu_DropdownMenuTrigger","require_Editable_EditableRoot","require_Editable_EditableArea","require_Editable_EditableCancelTrigger","require_Editable_EditableEditTrigger","require_Editable_EditableInput","require_Editable_EditablePreview","require_Editable_EditableSubmitTrigger","require_HoverCard_HoverCardArrow","require_HoverCard_HoverCardRoot","require_HoverCard_HoverCardContent","require_HoverCard_HoverCardPortal","require_HoverCard_HoverCardTrigger","require_Label_Label","require_Menubar_MenubarArrow","require_Menubar_MenubarCheckboxItem","require_Menubar_MenubarRoot","require_Menubar_MenubarMenu","require_Menubar_MenubarContent","require_Menubar_MenubarGroup","require_Menubar_MenubarItem","require_Menubar_MenubarItemIndicator","require_Menubar_MenubarLabel","require_Menubar_MenubarPortal","require_Menubar_MenubarRadioGroup","require_Menubar_MenubarRadioItem","require_Menubar_MenubarSeparator","require_Menubar_MenubarSub","require_Menubar_MenubarSubContent","require_Menubar_MenubarSubTrigger","require_Menubar_MenubarTrigger","require_MonthPicker_MonthPickerRoot","require_MonthPicker_MonthPickerCell","require_MonthPicker_MonthPickerCellTrigger","require_MonthPicker_MonthPickerGrid","require_MonthPicker_MonthPickerGridBody","require_MonthPicker_MonthPickerGridRow","require_MonthPicker_MonthPickerHeader","require_MonthPicker_MonthPickerHeading","require_MonthPicker_MonthPickerNext","require_MonthPicker_MonthPickerPrev","require_MonthRangePicker_MonthRangePickerRoot","require_MonthRangePicker_MonthRangePickerCell","require_MonthRangePicker_MonthRangePickerCellTrigger","require_MonthRangePicker_MonthRangePickerGrid","require_MonthRangePicker_MonthRangePickerGridBody","require_MonthRangePicker_MonthRangePickerGridRow","require_MonthRangePicker_MonthRangePickerHeader","require_MonthRangePicker_MonthRangePickerHeading","require_MonthRangePicker_MonthRangePickerNext","require_MonthRangePicker_MonthRangePickerPrev","require_NavigationMenu_NavigationMenuRoot","require_NavigationMenu_NavigationMenuItem","require_NavigationMenu_NavigationMenuContent","require_NavigationMenu_NavigationMenuIndicator","require_NavigationMenu_NavigationMenuLink","require_NavigationMenu_NavigationMenuList","require_NavigationMenu_NavigationMenuSub","require_NavigationMenu_NavigationMenuTrigger","require_NavigationMenu_NavigationMenuViewport","require_NumberField_NumberFieldRoot","require_NumberField_NumberFieldDecrement","require_NumberField_NumberFieldIncrement","require_NumberField_NumberFieldInput","require_Pagination_PaginationEllipsis","require_Pagination_PaginationRoot","require_Pagination_PaginationFirst","require_Pagination_PaginationLast","require_Pagination_PaginationList","require_Pagination_PaginationListItem","require_Pagination_PaginationNext","require_Pagination_PaginationPrev","require_PinInput_PinInputRoot","require_PinInput_PinInputInput","require_Popover_PopoverRoot","require_Popover_PopoverAnchor","require_Popover_PopoverArrow","require_Popover_PopoverClose","require_Popover_PopoverContent","require_Popover_PopoverPortal","require_Popover_PopoverTrigger","require_Progress_ProgressRoot","require_Progress_ProgressIndicator","require_RadioGroup_RadioGroupRoot","require_RadioGroup_RadioGroupItem","require_RadioGroup_RadioGroupIndicator","require_RangeCalendar_RangeCalendarRoot","require_RangeCalendar_RangeCalendarCell","require_RangeCalendar_RangeCalendarCellTrigger","require_RangeCalendar_RangeCalendarGrid","require_RangeCalendar_RangeCalendarGridBody","require_RangeCalendar_RangeCalendarGridHead","require_RangeCalendar_RangeCalendarGridRow","require_RangeCalendar_RangeCalendarHeadCell","require_RangeCalendar_RangeCalendarHeader","require_RangeCalendar_RangeCalendarHeading","require_RangeCalendar_RangeCalendarNext","require_RangeCalendar_RangeCalendarPrev","require_ScrollArea_ScrollAreaRoot","require_ScrollArea_ScrollAreaCorner","require_ScrollArea_ScrollAreaScrollbarGlimpse","require_ScrollArea_ScrollAreaScrollbar","require_ScrollArea_ScrollAreaThumb","require_ScrollArea_ScrollAreaViewport","require_Select_SelectRoot","require_Select_SelectArrow","require_Select_SelectContent","require_Select_SelectGroup","require_Select_SelectIcon","require_Select_SelectItem","require_Select_SelectItemIndicator","require_Select_SelectItemText","require_Select_SelectLabel","require_Select_SelectPortal","require_Select_SelectScrollDownButton","require_Select_SelectScrollUpButton","require_Select_SelectSeparator","require_Select_SelectTrigger","require_Select_SelectValue","require_Select_SelectViewport","require_Separator_Separator","require_Splitter_SplitterGroup","require_Splitter_SplitterPanel","require_Splitter_SplitterResizeHandle","require_Stepper_StepperRoot","require_Stepper_StepperItem","require_Stepper_StepperDescription","require_Stepper_StepperIndicator","require_Stepper_StepperSeparator","require_Stepper_StepperTitle","require_Stepper_StepperTrigger","require_Switch_SwitchRoot","require_Switch_SwitchThumb","require_Tabs_TabsRoot","require_Tabs_TabsContent","require_Tabs_TabsIndicator","require_Tabs_TabsList","require_Tabs_TabsTrigger","require_TagsInput_TagsInputRoot","require_TagsInput_TagsInputClear","require_TagsInput_TagsInputInput","require_TagsInput_TagsInputItem","require_TagsInput_TagsInputItemDelete","require_TagsInput_TagsInputItemText","require_TimeField_TimeFieldRoot","require_TimeField_TimeFieldInput","require_TimeRangeField_TimeRangeFieldRoot","require_TimeRangeField_TimeRangeFieldInput","require_Toast_ToastProvider","require_Toast_ToastClose","require_Toast_ToastAction","require_Toast_ToastDescription","require_Toast_ToastPortal","require_Toast_ToastRoot","require_Toast_ToastTitle","require_Toast_ToastViewport","require_ToggleGroup_ToggleGroupRoot","require_Toggle_Toggle","require_ToggleGroup_ToggleGroupItem","require_Toolbar_ToolbarButton","require_Toolbar_ToolbarLink","require_Toolbar_ToolbarRoot","require_Toolbar_ToolbarSeparator","require_Toolbar_ToolbarToggleGroup","require_Toolbar_ToolbarToggleItem","require_Tooltip_TooltipArrow","require_Tooltip_TooltipProvider","require_Tooltip_TooltipRoot","require_Tooltip_TooltipContent","require_Tooltip_TooltipPortal","require_Tooltip_TooltipTrigger","require_Tree_TreeRoot","require_Tree_TreeItem","require_Tree_TreeVirtualizer","require_Viewport_Viewport","require_YearPicker_YearPickerRoot","require_YearPicker_YearPickerCell","require_YearPicker_YearPickerCellTrigger","require_YearPicker_YearPickerGrid","require_YearPicker_YearPickerGridBody","require_YearPicker_YearPickerGridRow","require_YearPicker_YearPickerHeader","require_YearPicker_YearPickerHeading","require_YearPicker_YearPickerNext","require_YearPicker_YearPickerPrev","require_YearRangePicker_YearRangePickerRoot","require_YearRangePicker_YearRangePickerCell","require_YearRangePicker_YearRangePickerCellTrigger","require_YearRangePicker_YearRangePickerGrid","require_YearRangePicker_YearRangePickerGridBody","require_YearRangePicker_YearRangePickerGridRow","require_YearRangePicker_YearRangePickerHeader","require_YearRangePicker_YearRangePickerHeading","require_YearRangePicker_YearRangePickerNext","require_YearRangePicker_YearRangePickerPrev","settingschangedcallbacks","globalDebugFlags","localDebugFlags","debugFlagsOverridesCB","DebugFlagsProxyHandler","debugFlagsOverridesCB","localDebugFlags","globalDebugFlags","target","p","record","keys","key","newValue","toModify","runSettingsCallbacks","value","debugFlags","formatForConsoleLogs","cb","settingschangedcallbacks","e","dtapStage","isLive","backendBase","dtapstage","dtapStage","islive","isLive","initEnv","setDtapStage","setBackendBase","dtapStage","isLive","backendBase","dtapstage","islive","getBrowserDebugFlags","varname","flags","urldebugvar","debugcookie","debugcookievalue","flag","sessionDebug","qR","node_or_selector","selector","matches","qSA","isElement","node","isHTMLElement","parseLanguageTag","languageTag","match","getLang","node","tag","getWHType","obj","isCrossRealm","value","isMoney","isTemporalInstant","isTemporalPlainDateTime","isTemporalPlainDate","isTemporalPlainTime","isTemporalZonedDateTime","isDate","isBlob","isFile","stdTypeOf","value","isMoney","isBlob","isFile","isDate","isTemporalInstant","isTemporalPlainTime","isTemporalPlainDate","isTemporalPlainDateTime","isTemporalZonedDateTime","stripUnneededDecimals","num","decimals","isneg","toText","amount","decimalpoint","mindecimals","isnegative","astext","splitValue","money","split","sign","joinPrice","parts","adjustDecimals","requiredecimals","toadd","multiplier","idx","__add","lhs","rhs","requiredecimals","adjustDecimals","add","amount1","amount2","joinPrice","splitValue","subtract","amount","tosubtract","__multiply","multiply","cmp","diff","getPercentageOfAmount","perc","result","normalize","__roundIntegerToMultiple","value","roundunit","mode","roundToMultiple","unit","split_value","splitValue","split_unit","requiredecimals","adjustDecimals","result","joinPrice","min","amount","amounts","val","cmp","max","getNonNegativePowerOf10","exp","retval","running_exp","divide","divisor","lhs","rhs","mul10exp","mulfactor","test","lhs","relation","rhs","compareresult","cmp","stripUnneededDecimals","num","decimals","isneg","splitValue","money","split","sign","toText","amount","decimalpoint","mindecimals","thousandpoint","isnegative","astext","beforepoint","afterpoint","Money","_Money","value","intvalue","param","isMoney","left","right","sum","item","add","subtract","roundto","mode","roundToMultiple","lhs","rhs","cmp","relation","test","multiply","percentage","getPercentageOfAmount","numerator","divisor","divide","amounts","min","max","format","escapeRegExp","text","options","mask","isHTMLUnrepresentableChar","curch","encodeEntities","str","html","s","char","stringify","arg","options","usereplacer","key","value","origvalue","type","stdTypeOf","lhs","rhs","result","encodeEntities","parseTyped","input","Money","omit","value","keys","elt","ret","key","val","unlock","LocalMutex","defer","LocalLock","mutex","config","siteroot","dtapStage","whconfigel","parsedConfig","omit","initEnv","flag","getBrowserDebugFlags","debugFlags","frontendConfig","getLang","prop","getFrontendData","dataObject","allowMissing","retval","resolve","reject","_resolve","_reject","items","callbackfn","retval","idx","item","key","list","IteratorPrototype","ArrayIteratorPrototype","OriginalIteratorPrototype","callback","it","value","next_value","real_value","max_count","values","limit","remaining","index","mapper","mapped","reducer","initial_value","acc","count","string","final","first","iterables","others","it_array","e","finished","partition1","partition2","i","max","min","isObject","t","GetIteratorFlattenable","obj","method","iterator","Iterator","WrappedIterator","#iterator","args","returnMethod","Iterator_from","submitForm","action","values","method","form","item","input","navigateTo","navigation","debugFlags","CustomEvent","dispatchCustomEvent","node","event","params","prop","evt","CustomEvent","defaultaction","stop","event","addDocEventListener","node","type","listener","options","locallocks","modallocked","uiwatcher","installedanticancelhandler","currentbusymodaldialog","currentbusymodaluserdialog","busymodalcontent","mylockmgr","getLockmgr","getParentLockManager","LockManager","anyModalLocks","l","scheduleCheckUIFree","checkUIFree","toggleBusyModal","lockmgr","isDialogElement","el","checkCancelEvent","evt","show","dispatchCustomEvent","dialog","toembed","lock","pos","debugFlags","BusyLock","options","lockmgr","getLockmgr","locallocks","modallocked","toggleBusyModal","debugFlags","lockpos","scheduleCheckUIFree","flagUIBusy","options","BusyLock","getParentLockManager","debugFlags","locallocks","l","lockmgr","getLockmgr","locallockmgr","LockManager","lock","mylockmgr","isDomReady","onDomReady","callback","e","components","map","isNodeCompletelyInDom","node","processRegistration","item","reg","domready","list","applyRegistration","startnode","isDomReady","items","e","register","selector","handler","options","newreg","components","isDomReady","onDomReady","registerMissed","applyRegistration","startnode","item","getCookie","key","value","escapeRegExp","parseUserAgent","ua","UA","platform","name","version","device","browser","parseUserAgent","getBrowser","config","forwardPublisherNavigation","event","isHTMLElement","navaction","desturl","origin","configureForCMS","import_vue","UNKNOWN_FUNCTION","parse","stackString","lines","stack","line","parseResult","parseChrome","parseWinjs","parseGecko","parseNode","parseJSC","chromeRe","chromeEvalRe","parts","isNative","isEval","submatch","winjsRe","geckoRe","geckoEvalRe","javaScriptCoreRe","nodeRe","parseTrace","parse","i","formatTrace","trace","e","prependStackTrace","error","stacklines","tracelines","isAbsolute","url","getBaseURL","backendBase","ControlledCall","client","method","stack","options","callurl","fetchoptions","fetchpromise","requestStack","response","exception","retryafter","resolve","jsonresponse","parseTyped","logitem","omit","err","prependStackTrace","RPCClient","debugFlags","error","params","stringify","parseTrace","ServiceProxy","target","prop","receiver","newoptions","rpc","args","service","servicematch","rpcclient","PublicCookieSuffix","authOptions","getCookieName","getFrontendData","getAuthLocalData","c","parseTyped","getCookie","PublicCookieSuffix","submitLoginForm","node","event","_stack","stop","username","password","site","returnto","persistentlogin","login","lock","__using","flagUIBusy","loginresult","refreshLoginStatus","navigateTo","failLogin","_","_error","_hasError","__callDispose","loggedIn","isLoggedIn","setupWRDAuth","options","register","addDocEventListener","evt","handleLogoutClick","doLogout","logout","onDomReady","message","response","form","evtdetail","dispatchCustomEvent","loginfield","qR","getLoginTweaks","tweaks","getLang","urlvars","login","username","password","options","cookieName","getCookieName","result","rpc","getBrowser","getAuthLocalData","doLogout","logout","navigateTo","postRenderChecks","log","logtext","onDomReady","import_vue","LOGGED_IN_CLASS","useWrdAuthState","isLoggedIn","observer","read","import_vue","import_vue","hasA11yProp","props","prop","isEmptyString","value","mergeClasses","classes","className","index","array","toKebabCase","string","toCamelCase","string","match","p1","p2","toPascalCase","string","camelCase","toCamelCase","defaultAttributes","Icon","name","iconNode","absoluteStrokeWidth","absoluteStrokeWidthKebabCase","strokeWidth","strokeWidthKebabCase","size","defaultAttributes","color","props","slots","isEmptyString","mergeClasses","toKebabCase","toPascalCase","hasA11yProp","child","createLucideIcon","iconName","iconNode","props","slots","attrs","Icon","ArrowDown","createLucideIcon","Brain","createLucideIcon","Check","createLucideIcon","ChevronDown","createLucideIcon","CircleAlert","createLucideIcon","Copy","createLucideIcon","CornerDownLeft","createLucideIcon","Download","createLucideIcon","FileText","createLucideIcon","FlaskConical","createLucideIcon","LoaderCircle","createLucideIcon","LogOut","createLucideIcon","Menu","createLucideIcon","MessageSquare","createLucideIcon","Moon","createLucideIcon","Search","createLucideIcon","SquarePen","createLucideIcon","Square","createLucideIcon","Sun","createLucideIcon","ThumbsUp","createLucideIcon","ThumbsDown","createLucideIcon","TriangleAlert","createLucideIcon","X","createLucideIcon","import_vue","import_vue","bail","error","import_extend","isPlainObject","value","prototype","trough","fns","pipeline","run","use","values","middlewareIndex","callback","next","error","output","fn","index","wrap","middelware","middleware","called","wrapped","parameters","fnExpectsCallback","result","done","exception","then","value","stringifyPosition","value","position","point","index","pos","VFileMessage","causeOrReason","optionsOrParentOrPlace","origin","reason","options","legacyCause","index","parent","start","stringifyPosition","minpath","basename","dirname","extname","join","path","assertPath","start","end","index","seenNonSlash","firstNonSlashEnd","extnameIndex","unmatchedSlash","startPart","startDot","preDotState","code","segments","joined","normalize","absolute","value","normalizeString","allowAboveRoot","result","lastSegmentLength","lastSlash","dots","lastSlashIndex","minproc","cwd","isUrl","fileUrlOrPath","urlToPath","path","isUrl","error","getPathFromURLPosix","url","pathname","index","third","order","VFile","value","options","isUrl","isUint8Array","minproc","index","field","minpath","basename","assertNonEmpty","assertPart","dirname","assertPath","extname","path","urlToPath","stem","causeOrReason","optionsOrParentOrPlace","origin","message","VFileMessage","encoding","part","name","CallableInstance","property","proto","value","apply","own","Processor","_Processor","CallableInstance","trough","destination","index","attacher","extend","key","value","assertUnfrozen","self","options","transformer","file","realFile","vfile","parser","assertParser","done","assertCompiler","executor","resolve","reject","parseTree","error","tree","realDone","compileTree","compileResult","looksLikeAValue","complete","result","assertDone","bail","assertNode","transformers","outputTree","resultingTree","compiler","parameters","attachers","namespace","addPlugin","addList","addPreset","add","plugin","plugins","thing","entryIndex","primary","rest","currentPrimary","isPlainObject","unified","name","frozen","node","asyncName","looksLikeAVFile","VFile","isUint8Array","emptyOptions","toString","value","options","settings","includeImageAlt","includeHtml","one","node","all","values","result","index","element","decodeNamedCharacterReference","value","characterReference","character","splice","list","start","remove","items","end","chunkStart","parameters","push","hasOwnProperty","combineExtensions","extensions","all","index","syntaxExtension","extension","hook","left","right","code","value","constructs","existing","list","before","splice","decodeNumericCharacterReference","value","base","code","normalizeIdentifier","value","asciiAlpha","regexCheck","asciiAlphanumeric","asciiAtext","asciiControl","code","asciiDigit","asciiHexDigit","asciiPunctuation","markdownLineEnding","markdownLineEndingOrSpace","markdownSpace","unicodePunctuation","unicodeWhitespace","regex","check","normalizeUri","value","result","index","start","skip","code","replace","asciiAlphanumeric","next","factorySpace","effects","ok","type","max","limit","size","start","code","markdownSpace","prefix","content","initializeContent","effects","contentStart","afterContentStartConstruct","paragraphInitial","previous","code","factorySpace","lineStart","token","data","markdownLineEnding","document","initializeDocument","containerConstruct","tokenizeContainer","effects","self","stack","continued","childFlow","childToken","lineStartOffset","start","code","item","documentContinue","checkNewContainers","closeFlow","indexBeforeExits","indexBeforeFlow","point","exitContainers","index","splice","documentContinued","flowStart","thereIsANewContainer","thereIsNoNewContainer","containerContinue","flowContinue","writeToChild","markdownLineEnding","token","endOfFile","stream","seen","size","entry","ok","nok","factorySpace","classifyCharacter","code","markdownLineEndingOrSpace","unicodeWhitespace","unicodePunctuation","resolveAll","constructs","events","context","called","index","resolve","attention","resolveAllAttention","tokenizeAttention","events","context","index","open","group","text","openingSequence","closingSequence","use","nextEvents","offset","start","end","movePoint","push","resolveAll","splice","effects","ok","attentionMarkers","previous","before","classifyCharacter","marker","code","inside","token","after","close","point","autolink","tokenizeAutolink","effects","ok","nok","size","start","code","open","asciiAlpha","schemeOrEmailAtext","emailAtext","asciiAlphanumeric","schemeInsideOrEmailAtext","urlInside","asciiControl","emailAtSignOrDot","asciiAtext","emailLabel","emailValue","next","blankLine","tokenizeBlankLine","effects","ok","nok","start","code","markdownSpace","factorySpace","after","markdownLineEnding","blockQuote","tokenizeBlockQuoteContinuation","exit","tokenizeBlockQuoteStart","effects","ok","nok","self","start","code","state","after","markdownSpace","contStart","factorySpace","contBefore","characterEscape","tokenizeCharacterEscape","effects","ok","nok","start","code","inside","asciiPunctuation","characterReference","tokenizeCharacterReference","effects","ok","nok","self","size","max","test","start","code","open","numeric","asciiAlphanumeric","value","asciiHexDigit","asciiDigit","token","decodeNamedCharacterReference","nonLazyContinuation","tokenizeNonLazyContinuation","codeFenced","tokenizeCodeFenced","effects","ok","nok","self","closeStart","tokenizeCloseStart","initialPrefix","sizeOpen","marker","start","code","beforeSequenceOpen","tail","sequenceOpen","markdownSpace","factorySpace","infoBefore","markdownLineEnding","atNonLazyBreak","after","info","metaBefore","meta","contentBefore","contentStart","beforeContentChunk","contentChunk","size","startBefore","beforeSequenceClose","sequenceClose","sequenceCloseAfter","lineStart","codeIndented","tokenizeCodeIndented","furtherStart","tokenizeFurtherStart","effects","ok","nok","self","start","code","factorySpace","afterPrefix","tail","atBreak","after","markdownLineEnding","inside","codeText","previous","resolveCodeText","tokenizeCodeText","events","tailExitIndex","headEnterIndex","index","enter","code","effects","ok","nok","self","sizeOpen","size","token","start","sequenceOpen","between","sequenceClose","markdownLineEnding","data","SpliceBuffer","initial","index","start","end","stop","deleteCount","items","count","removed","chunkedPush","item","n","list","right","chunkStart","subtokenize","eventsArray","jumps","index","event","lineIndex","otherIndex","otherEvent","parameters","subevents","more","events","SpliceBuffer","subcontent","splice","eventIndex","token","context","startPosition","startPositions","tokenizer","childEvents","gaps","stream","previous","current","adjust","start","breaks","slice","content","resolveContent","tokenizeContent","continuationConstruct","tokenizeContinuation","events","subtokenize","effects","ok","previous","chunkStart","code","chunkInside","contentEnd","markdownLineEnding","contentContinue","nok","self","startLookahead","factorySpace","prefixed","tail","factoryDestination","effects","ok","nok","type","literalType","literalMarkerType","rawType","stringType","max","limit","balance","start","code","enclosedBefore","asciiControl","raw","enclosed","markdownLineEnding","enclosedEscape","markdownLineEndingOrSpace","rawEscape","factoryLabel","effects","ok","nok","type","markerType","stringType","self","size","seen","start","code","atBreak","markdownLineEnding","labelInside","markdownSpace","labelEscape","factoryTitle","effects","ok","nok","type","markerType","stringType","marker","start","code","begin","atBreak","markdownLineEnding","factorySpace","inside","escape","factoryWhitespace","effects","ok","seen","start","code","markdownLineEnding","markdownSpace","factorySpace","definition","tokenizeDefinition","titleBefore","tokenizeTitleBefore","effects","ok","nok","self","identifier","start","code","before","factoryLabel","labelAfter","normalizeIdentifier","markerAfter","markdownLineEndingOrSpace","factoryWhitespace","destinationBefore","factoryDestination","destinationAfter","after","markdownSpace","factorySpace","afterWhitespace","markdownLineEnding","beforeMarker","factoryTitle","titleAfter","titleAfterOptionalWhitespace","hardBreakEscape","tokenizeHardBreakEscape","effects","ok","nok","start","code","after","markdownLineEnding","headingAtx","resolveHeadingAtx","tokenizeHeadingAtx","events","context","contentEnd","contentStart","content","text","splice","effects","ok","nok","size","start","code","before","sequenceOpen","markdownLineEndingOrSpace","atBreak","sequenceFurther","markdownLineEnding","markdownSpace","factorySpace","data","htmlBlockNames","htmlRawNames","htmlFlow","resolveToHtmlFlow","tokenizeHtmlFlow","blankLineBefore","tokenizeBlankLineBefore","nonLazyContinuationStart","tokenizeNonLazyContinuationStart","events","index","effects","ok","nok","self","marker","closingTag","buffer","markerB","start","code","before","open","declarationOpen","tagCloseStart","continuationDeclarationInside","asciiAlpha","tagName","commentOpenInside","cdataOpenInside","value","continuation","markdownLineEndingOrSpace","slash","name","htmlRawNames","htmlBlockNames","basicSelfClosing","completeClosingTagAfter","completeAttributeNameBefore","asciiAlphanumeric","markdownSpace","completeEnd","completeAttributeName","completeAttributeNameAfter","completeAttributeValueBefore","completeAttributeValueQuoted","completeAttributeValueUnquoted","completeAttributeValueQuotedAfter","markdownLineEnding","completeAfter","continuationCommentInside","continuationRawTagOpen","continuationClose","continuationCdataInside","continuationAfter","continuationStart","continuationStartNonLazy","continuationBefore","continuationRawEndTag","after","blankLine","htmlText","tokenizeHtmlText","effects","ok","nok","self","marker","index","returnState","start","code","open","declarationOpen","tagCloseStart","instruction","asciiAlpha","tagOpen","commentOpenInside","cdataOpenInside","declaration","commentEnd","comment","commentClose","markdownLineEnding","lineEndingBefore","end","value","cdata","cdataClose","cdataEnd","instructionClose","tagClose","asciiAlphanumeric","tagCloseBetween","markdownSpace","markdownLineEndingOrSpace","tagOpenBetween","tagOpenAttributeName","tagOpenAttributeNameAfter","tagOpenAttributeValueBefore","tagOpenAttributeValueQuoted","tagOpenAttributeValueUnquoted","tagOpenAttributeValueQuotedAfter","lineEndingAfter","factorySpace","lineEndingAfterPrefix","labelEnd","resolveAllLabelEnd","resolveToLabelEnd","tokenizeLabelEnd","resourceConstruct","tokenizeResource","referenceFullConstruct","tokenizeReferenceFull","referenceCollapsedConstruct","tokenizeReferenceCollapsed","events","index","newEvents","token","offset","splice","context","open","close","media","group","label","text","push","resolveAll","effects","ok","nok","self","labelStart","defined","start","code","labelEndNok","normalizeIdentifier","after","labelEndOk","referenceNotFull","resourceStart","resourceBefore","markdownLineEndingOrSpace","factoryWhitespace","resourceOpen","resourceEnd","factoryDestination","resourceDestinationAfter","resourceDestinationMissing","resourceBetween","factoryTitle","resourceTitleAfter","referenceFull","factoryLabel","referenceFullAfter","referenceFullMissing","referenceCollapsedStart","referenceCollapsedOpen","labelStartImage","labelEnd","tokenizeLabelStartImage","effects","ok","nok","self","start","code","open","after","labelStartLink","labelEnd","tokenizeLabelStartLink","effects","ok","nok","self","start","code","after","lineEnding","tokenizeLineEnding","effects","ok","start","code","factorySpace","thematicBreak","tokenizeThematicBreak","effects","ok","nok","size","marker","start","code","before","atBreak","sequence","markdownLineEnding","markdownSpace","factorySpace","list","tokenizeListContinuation","tokenizeListEnd","tokenizeListStart","listItemPrefixWhitespaceConstruct","tokenizeListItemPrefixWhitespace","indentConstruct","tokenizeIndent","effects","ok","nok","self","tail","initialSize","size","start","code","kind","asciiDigit","thematicBreak","atMarker","inside","blankLine","onBlank","endOfPrefix","otherPrefix","markdownSpace","notBlank","factorySpace","notInCurrentItem","afterPrefix","setextUnderline","resolveToSetextUnderline","tokenizeSetextUnderline","events","context","index","content","text","definition","heading","effects","ok","nok","self","marker","start","code","paragraph","before","inside","markdownSpace","factorySpace","after","markdownLineEnding","flow","initializeFlow","effects","self","initial","blankLine","atBlankEnding","afterConstruct","factorySpace","content","code","resolver","createResolver","string","initializeFactory","text","field","resolveAllLineSuffixes","initializeText","effects","self","constructs","start","notText","code","atBreak","data","list","index","item","extraResolver","resolveAllText","events","context","enter","eventIndex","chunks","bufferIndex","size","tabs","chunk","token","constructs_exports","__export","attentionMarkers","contentInitial","disable","document","flow","flowInitial","insideSpan","string","text","document","list","blockQuote","contentInitial","definition","flowInitial","codeIndented","flow","headingAtx","thematicBreak","setextUnderline","htmlFlow","codeFenced","string","characterReference","characterEscape","text","lineEnding","labelStartImage","attention","autolink","htmlText","labelStartLink","hardBreakEscape","labelEnd","codeText","insideSpan","resolver","attentionMarkers","disable","createTokenizer","parser","initialize","from","point","columnStart","resolveAllConstructs","chunks","stack","consumed","effects","constructFactory","onsuccessfulconstruct","onsuccessfulcheck","consume","enter","exit","context","defineSkip","now","sliceSerialize","sliceStream","write","state","expectedCode","slice","push","main","addResult","resolveAll","token","expandTabs","serializeChunks","sliceChunks","_bufferIndex","_index","line","column","offset","value","accountForPotentialSkip","chunkIndex","chunk","go","code","markdownLineEnding","type","fields","construct","info","_","onreturn","hook","constructs","returnState","bogusState","listOfConstructs","constructIndex","currentConstruct","handleListOfConstructs","handleMapOfConstructs","map","start","left","all","list","handleConstruct","store","nok","ok","splice","startPoint","startPrevious","startCurrentConstruct","startEventsIndex","startStack","restore","startIndex","startBufferIndex","endIndex","endBufferIndex","view","head","index","result","atTab","parse","options","parser","combineExtensions","constructs_exports","create","content","document","flow","string","text","initial","creator","from","createTokenizer","postprocess","events","subtokenize","search","preprocess","column","buffer","start","atCarriageReturn","preprocessor","value","encoding","end","chunks","match","next","startPosition","endPosition","code","characterEscapeOrReference","decodeString","value","decode","$0","$1","$2","head","hex","decodeNumericCharacterReference","decodeNamedCharacterReference","own","fromMarkdown","value","encoding","options","compiler","postprocess","parse","preprocess","config","opener","link","onenterdata","heading","blockQuote","codeFlow","buffer","codeText","definition","emphasis","hardBreak","html","image","listItem","onenterlistitemvalue","list","onenterlistordered","paragraph","onenterreference","strong","thematicBreak","closer","onexitatxheadingsequence","onexitautolinkemail","onexitautolinkprotocol","onexitdata","onexitcharacterreferencemarker","onexitcharacterreferencevalue","onexitcharacterreference","onexitcodefenced","onexitcodefencedfence","onexitcodefencedfenceinfo","onexitcodefencedfencemeta","onexitcodeindented","onexitcodetext","onexitdefinitiondestinationstring","onexitdefinitionlabelstring","onexitdefinitiontitlestring","onexithardbreak","onexithtmlflow","onexithtmltext","onexitimage","onexitlabel","onexitlabeltext","onexitlineending","onexitlink","onexitreferencestring","onexitresourcedestinationstring","onexitresourcetitlestring","onexitresource","onexitsetextheading","onexitsetextheadinglinesequence","onexitsetextheadingtext","configure","data","compile","events","tree","context","enter","exit","resume","listStack","index","tail","prepareList","handler","defaultOnError","point","start","length","containerBalance","listSpread","lineIndex","firstBlankLineIndex","atMarker","event","tailIndex","tailEvent","item","create","and","open","token","node","errorHandler","close","onExitError","stringifyPosition","toString","ancestor","label","normalizeIdentifier","depth","siblings","text","referenceType","string","decodeString","fragment","children","type","decodeNumericCharacterReference","decodeNamedCharacterReference","d","combined","extensions","extension","key","right","left","remarkParse","options","self","parser","doc","fromMarkdown","ccount","value","character","source","count","index","escapeStringRegexp","string","convert","test","ok","castFactory","anyFactory","propertiesFactory","typeFactory","tests","checks","index","any","parameters","check","checkAsRecord","all","node","nodeAsRecord","key","type","testFunction","value","parent","looksLikeANode","empty","CONTINUE","EXIT","SKIP","visitParents","tree","test","visitor","reverse","check","is","convert","step","factory","node","index","parents","value","name","visit","result","subresult","offset","grandparents","toResult","nodeAsParent","child","findAndReplace","tree","list","options","ignored","convert","pairs","toPairs","pairIndex","visitParents","visitor","node","parents","index","grandparent","parent","siblings","handler","find","replace","start","change","nodes","match","position","matchObject","value","tupleOrList","result","tuple","toExpression","toFunction","escapeStringRegexp","inConstruct","notInConstruct","gfmAutolinkLiteralFromMarkdown","transformGfmAutolinkLiterals","enterLiteralAutolink","enterLiteralAutolinkValue","exitLiteralAutolink","exitLiteralAutolinkEmail","exitLiteralAutolinkHttp","exitLiteralAutolinkWww","gfmAutolinkLiteralToMarkdown","token","node","tree","findAndReplace","findUrl","findEmail","_","protocol","domain","path","match","prefix","previous","isCorrectDomain","parts","splitUrl","result","atext","label","url","trailExec","trail","closingParenIndex","openingParens","ccount","closingParens","email","code","unicodeWhitespace","unicodePunctuation","footnoteReference","footnoteReferencePeek","enterFootnoteCallString","enterFootnoteCall","token","enterFootnoteDefinitionLabelString","enterFootnoteDefinition","exitFootnoteCallString","label","node","normalizeIdentifier","exitFootnoteCall","exitFootnoteDefinitionLabelString","exitFootnoteDefinition","_","state","info","tracker","value","exit","subexit","gfmFootnoteFromMarkdown","gfmFootnoteToMarkdown","options","firstLineBlank","footnoteDefinition","mapAll","mapExceptFirst","line","index","blank","constructsWithoutStrikethrough","handleDelete","peekDelete","gfmStrikethroughFromMarkdown","enterStrikethrough","exitStrikethrough","gfmStrikethroughToMarkdown","token","node","_","state","info","tracker","exit","value","defaultStringLength","value","markdownTable","table","options","settings","align","stringLength","alignments","cellMatrix","sizeMatrix","longestCellByColumn","mostCellsPerRow","rowIndex","row","sizes","columnIndex","cell","serialize","size","toAlignment","code","before","after","lines","line","own","zwitch","key","options","settings","one","value","parameters","fn","handlers","id","blockquote","node","_","state","info","exit","tracker","value","map","line","blank","patternInScope","stack","pattern","listInScope","list","none","index","hardBreak","_","_1","state","info","index","patternInScope","longestStreak","value","substring","source","index","expected","count","max","formatCodeAsIndented","node","state","checkFence","state","marker","code","node","_","state","info","marker","checkFence","raw","suffix","formatCodeAsIndented","exit","value","map","tracker","sequence","longestStreak","subexit","line","blank","checkQuote","state","marker","definition","node","_","state","info","quote","checkQuote","suffix","exit","subexit","tracker","value","checkEmphasis","state","marker","encodeCharacterReference","code","encodeInfo","outside","inside","marker","outsideKind","classifyCharacter","insideKind","emphasis","emphasisPeek","node","_","state","info","marker","checkEmphasis","exit","tracker","before","between","betweenHead","open","encodeInfo","encodeCharacterReference","betweenTail","close","after","_1","visit","tree","testOrVisitor","visitorOrReverse","maybeReverse","reverse","test","visitor","visitParents","overload","node","parents","parent","index","formatHeadingAsSetext","node","state","literalWithBreak","visit","EXIT","toString","heading","node","_","state","info","rank","tracker","formatHeadingAsSetext","exit","subexit","value","sequence","encodeCharacterReference","html","htmlPeek","node","image","imagePeek","node","_","state","info","quote","checkQuote","suffix","exit","subexit","tracker","value","imageReference","imageReferencePeek","node","_","state","info","type","exit","subexit","tracker","value","alt","stack","reference","inlineCode","inlineCodePeek","node","_","state","value","sequence","index","pattern","expression","match","position","formatLinkAsAutolink","node","state","raw","toString","link","linkPeek","node","_","state","info","quote","checkQuote","suffix","tracker","exit","subexit","formatLinkAsAutolink","stack","value","linkReference","linkReferencePeek","node","_","state","info","type","exit","subexit","tracker","value","text","stack","reference","checkBullet","state","marker","checkBulletOther","state","bullet","checkBullet","bulletOther","checkBulletOrdered","state","marker","checkRule","state","marker","list","node","parent","state","info","exit","bulletCurrent","bullet","checkBulletOrdered","checkBullet","bulletOther","checkBulletOther","useDifferentMarker","firstListItem","checkRule","index","item","value","checkListItemIndent","state","style","listItem","node","parent","state","info","listItemIndent","checkListItemIndent","bullet","checkBullet","size","tracker","exit","value","map","line","index","blank","paragraph","node","_","state","info","exit","subexit","value","phrasing","convert","root","node","_","state","info","d","phrasing","checkStrong","state","marker","strong","strongPeek","node","_","state","info","marker","checkStrong","exit","tracker","before","between","betweenHead","open","encodeInfo","encodeCharacterReference","betweenTail","close","after","_1","text","node","_","state","info","checkRuleRepetition","state","repetition","thematicBreak","_","_1","state","value","checkRule","checkRuleRepetition","handle","blockquote","hardBreak","code","definition","emphasis","heading","html","image","imageReference","inlineCode","link","linkReference","list","listItem","paragraph","root","strong","text","thematicBreak","gfmTableFromMarkdown","enterTable","enterCell","enterRow","exitCodeText","exitTable","exit","token","align","d","value","replace","node","$0","$1","gfmTableToMarkdown","options","settings","padding","alignDelimiters","stringLength","around","inlineCodeWithTable","handleTable","handleTableCell","handleTableRow","_","state","info","serializeData","handleTableAsData","row","handleTableRowAsData","subexit","matrix","markdownTable","children","index","result","parent","handle","gfmTaskListItemFromMarkdown","exitCheck","exitParagraphWithTaskListItem","gfmTaskListItemToMarkdown","listItemWithTaskListItem","token","node","parent","head","siblings","index","firstParaghraph","sibling","state","info","checkable","checkbox","tracker","value","handle","check","$0","gfmFromMarkdown","gfmAutolinkLiteralFromMarkdown","gfmFootnoteFromMarkdown","gfmStrikethroughFromMarkdown","gfmTableFromMarkdown","gfmTaskListItemFromMarkdown","gfmToMarkdown","options","gfmAutolinkLiteralToMarkdown","gfmFootnoteToMarkdown","gfmStrikethroughToMarkdown","gfmTableToMarkdown","gfmTaskListItemToMarkdown","wwwPrefix","tokenizeWwwPrefix","domain","tokenizeDomain","path","tokenizePath","trail","tokenizeTrail","emailDomainDotTrail","tokenizeEmailDomainDotTrail","wwwAutolink","tokenizeWwwAutolink","previousWww","protocolAutolink","tokenizeProtocolAutolink","previousProtocol","emailAutolink","tokenizeEmailAutolink","previousEmail","text","gfmAutolinkLiteral","code","effects","ok","nok","self","dot","data","start","gfmAtext","previousUnbalanced","atext","emailDomain","emailDomainAfter","emailDomainDot","asciiAlphanumeric","asciiAlpha","wwwStart","wwwAfter","buffer","seen","protocolStart","protocolPrefixInside","protocol","protocolSlashesInside","afterProtocol","asciiControl","markdownLineEndingOrSpace","unicodeWhitespace","unicodePunctuation","protocolAfter","size","wwwPrefixInside","wwwPrefixAfter","underscoreInLastSegment","underscoreInLastLastSegment","domainInside","domainAfter","domainAtPunctuation","sizeOpen","sizeClose","pathInside","pathAtPunctuation","trailCharacterReferenceStart","trailBracketAfter","trailCharacterReferenceInside","after","events","index","result","token","indent","tokenizeIndent","gfmFootnote","tokenizeDefinitionStart","tokenizeDefinitionContinuation","gfmFootnoteDefinitionEnd","tokenizeGfmFootnoteCall","tokenizePotentialGfmFootnoteCall","resolveToPotentialGfmFootnoteCall","effects","ok","nok","self","index","defined","labelStart","token","start","code","id","normalizeIdentifier","events","context","call","marker","string","chunk","replacement","size","data","callStart","callData","markdownLineEndingOrSpace","callEscape","identifier","labelAtMarker","labelInside","labelAfter","labelEscape","factorySpace","whitespaceAfter","blankLine","afterPrefix","tail","gfmStrikethrough","options","single","tokenizer","tokenizeStrikethrough","resolveAllStrikethrough","events","context","index","open","strikethrough","text","nextEvents","insideSpan","splice","resolveAll","effects","ok","nok","previous","size","start","code","more","before","classifyCharacter","token","after","EditMap","index","remove","add","addImplementation","events","a","b","vecs","slice","element","editMap","at","gfmTableAlign","events","index","inDelimiterRow","align","event","alignIndex","gfmTable","tokenizeTable","resolveTable","effects","ok","nok","self","size","sizeB","seen","start","code","index","type","tail","next","bodyRowStart","headRowBefore","headRowStart","headRowBreak","markdownLineEnding","headDelimiterStart","markdownSpace","factorySpace","headRowData","markdownLineEndingOrSpace","headRowEscape","headDelimiterBefore","headDelimiterValueBefore","headDelimiterCellBefore","headDelimiterNok","headDelimiterLeftAlignmentAfter","headDelimiterCellAfter","headDelimiterFiller","headDelimiterRightAlignmentAfter","bodyRowBreak","bodyRowData","bodyRowEscape","events","context","inFirstCellAwaitingPipe","rowKind","lastCell","cell","afterHeadAwaitingFirstBodyRow","lastTableEnd","currentTable","currentBody","currentCell","map","EditMap","event","token","flushTableEnd","flushCell","gfmTableAlign","range","rowEnd","previousCell","groupName","valueName","getPoint","now","relatedStart","relatedEnd","valueToken","end","a","b","table","tableBody","exits","related","side","tasklistCheck","tokenizeTasklistCheck","gfmTaskListItem","effects","ok","nok","self","open","code","inside","markdownLineEndingOrSpace","close","after","markdownLineEnding","markdownSpace","spaceThenNonSpace","factorySpace","gfm","options","combineExtensions","gfmAutolinkLiteral","gfmFootnote","gfmStrikethrough","gfmTable","gfmTaskListItem","emptyOptions","remarkGfm","options","self","settings","data","micromarkExtensions","fromMarkdownExtensions","toMarkdownExtensions","gfm","gfmFromMarkdown","gfmToMarkdown","mathFromMarkdown","enterMathFlow","enterMathFlowMeta","enterMathText","exitMathFlow","exitMathFlowFence","exitMathFlowMeta","exitMathData","exitMathText","token","code","data","node","mathToMarkdown","options","single","inlineMath","inlineMathPeek","math","_","state","info","raw","tracker","sequence","longestStreak","exit","value","subexit","size","index","pattern","expression","match","position","mathFlow","tokenizeMathFenced","nonLazyContinuation","tokenizeNonLazyContinuation","effects","ok","nok","self","tail","initialSize","sizeOpen","start","code","sequenceOpen","factorySpace","metaBefore","markdownLineEnding","metaAfter","meta","beforeNonLazyContinuation","after","tokenizeClosingFence","contentStart","beforeContentChunk","contentChunk","size","beforeSequenceClose","sequenceClose","afterSequenceClose","lineStart","mathText","options","single","tokenizeMathText","resolveMathText","previous","effects","ok","nok","self","sizeOpen","size","token","start","code","sequenceOpen","between","sequenceClose","markdownLineEnding","data","events","tailExitIndex","headEnterIndex","index","enter","math","options","mathFlow","mathText","emptyOptions","remarkMath","options","self","settings","data","micromarkExtensions","fromMarkdownExtensions","toMarkdownExtensions","math","mathFromMarkdown","mathToMarkdown","blockquote","state","node","result","hardBreak","state","node","result","code","state","node","value","properties","language","result","strikethrough","state","node","result","emphasis","state","node","result","footnoteReference","state","node","clobberPrefix","id","safeId","normalizeUri","index","counter","reuseCounter","link","sup","heading","state","node","result","html","state","node","result","revert","state","node","subtype","suffix","contents","head","tail","imageReference","state","node","id","definition","revert","properties","normalizeUri","result","image","state","node","properties","normalizeUri","result","inlineCode","state","node","text","result","linkReference","state","node","id","definition","revert","properties","normalizeUri","result","link","state","node","properties","normalizeUri","result","listItem","state","node","parent","results","loose","listLoose","listItemLoose","properties","children","head","paragraph","index","child","tail","result","spread","list","state","node","properties","results","index","child","result","paragraph","state","node","result","root","state","node","result","strong","state","node","result","pointEnd","point","pointStart","type","node","position","start","end","table","state","node","rows","firstRow","tableContent","head","body","start","pointStart","end","pointEnd","result","tableRow","state","node","parent","siblings","tagName","align","length","cellIndex","cells","cell","properties","alignValue","result","tableCell","state","node","result","trimLines","value","source","search","match","last","lines","trimLine","start","end","startIndex","endIndex","code","text","state","node","result","trimLines","thematicBreak","state","node","result","handlers","blockquote","hardBreak","code","strikethrough","emphasis","footnoteReference","heading","html","imageReference","image","inlineCode","linkReference","link","listItem","list","paragraph","root","strong","table","tableCell","tableRow","text","thematicBreak","ignore","env","guard","name","init","deserializer","$","_","as","out","index","unpair","type","value","arr","object","key","source","flags","map","set","message","buffer","deserialize","serialized","EMPTY","toString","keys","typeOf","value","type","asString","shouldSkip","TYPE","serializer","strict","json","$","_","as","out","index","pair","entry","spread","arr","entries","key","source","flags","message","serialize","lossy","esm_default","any","options","deserialize","serialize","defaultFootnoteBackContent","_","rereferenceIndex","result","defaultFootnoteBackLabel","referenceIndex","footer","state","clobberPrefix","footnoteBackContent","footnoteBackLabel","footnoteLabel","footnoteLabelTagName","footnoteLabelProperties","listItems","definition","content","id","safeId","normalizeUri","backReferences","counts","children","tail","tailTail","listItem","esm_default","own","emptyOptions","createState","tree","options","settings","definitionById","footnoteById","footnoteCounts","handlers","state","all","applyData","one","patch","wrap","visit","node","map","id","parent","type","handle","children","shallow","result","esm_default","defaultUnknownHandler","values","nodes","index","trimMarkdownSpaceStart","head","from","to","position","hName","hChildren","hProperties","data","loose","value","code","toHast","tree","options","state","createState","node","foot","footer","result","remarkRehype","destination","options","tree","file","hastTree","toHast","Schema","property","normal","space","merge","definitions","space","property","normal","definition","Schema","normalize","value","Info","property","attribute","types_exports","__export","boolean","booleanish","commaOrSpaceSeparated","commaSeparated","number","overloadedBoolean","spaceSeparated","powers","increment","checks","types_exports","DefinedInfo","Info","property","attribute","mask","space","index","mark","check","values","key","value","create","definition","properties","normals","property","value","info","DefinedInfo","normalize","Schema","aria","create","booleanish","number","spaceSeparated","_","property","caseSensitiveTransform","attributes","attribute","caseInsensitiveTransform","attributes","property","caseSensitiveTransform","html","create","commaSeparated","spaceSeparated","boolean","number","booleanish","overloadedBoolean","caseInsensitiveTransform","svg","create","commaOrSpaceSeparated","number","spaceSeparated","boolean","commaSeparated","caseSensitiveTransform","xlink","create","_","property","xmlns","create","caseInsensitiveTransform","xml","create","_","property","cap","dash","valid","find","schema","value","normal","normalize","property","Type","Info","rest","camelcase","dashes","kebab","DefinedInfo","$0","html","merge","aria","xlink","xmlns","xml","svg","parse","value","tokens","input","index","start","end","token","stringify","values","options","settings","search","parseSelector","selector","defaultTagName","value","props","start","previous","tagName","match","subvalue","parse","value","input","stringify","values","createH","schema","defaultTagName","caseSensitive","adjust","createAdjustMap","h","selector","properties","children","node","child","parseSelector","lower","adjusted","isChild","key","value","addProperty","addChild","record","keys","list","item","info","find","result","parse","parsePrimitive","style","finalResult","nodes","name","normalize","styles","values","svgCaseSensitiveTagNames","h","createH","html","s","svg","svgCaseSensitiveTagNames","webNamespaces","fromDom","tree","options","transform","node","transformed","one","element","text","comment","root","doctype","all","space","x","webNamespaces","s","h","tagName","content","attributes","properties","index","nodes","children","child","parser","fromHtmlIsomorphic","value","options","node","parseFragment","fromDom","template","findAfter","parent","index","test","is","convert","convertElement","test","element","tagNameFactory","anyFactory","castFactory","tests","checks","index","any","parameters","check","tagName","testFunction","value","parent","looksLikeAnElement","searchLineFeeds","searchTabOrSpaces","br","convertElement","cell","isCell","p","row","notRendered","hidden","closedDialog","blockOrCaption","toText","tree","options","options_","children","block","whitespace","inferWhitespace","results","collectText","index","renderedTextCollection","result","count","value","node","parent","info","collectElement","collectPreText","items","prefix","suffix","findAfter","lines","start","match","end","trimAndCollapseSpacesAndTabs","join","breakBefore","breakAfter","properties","emptyOptions","emptyClasses","rehypeKatex","options","settings","tree","file","visitParents","element","parents","classes","languageMath","mathDisplay","mathInline","displayMode","parent","scope","value","toText","result","katex","error","cause","ruleId","fromHtmlIsomorphic","index","SKIP","ShikiError","message","clone","something","doClone","cloneArray","cloneObj","arr","r","i","len","obj","key","mergeObjects","target","sources","source","basename","path","idx","CAPTURING_REGEX_SOURCE","RegexSource","regexSource","captureSource","captureIndices","match","index","commandIndex","command","capture","result","strcmp","a","b","strArrCmp","len1","len2","res","isValidHexColor","hex","escapeRegExpCharacters","value","CachedFn","fn","Theme","_colorMap","_defaults","_root","colorMap","parseTheme","resolveParsedThemeRules","scopeName","scopePath","effectiveRule","v","_scopePathMatchesParentScopes","StyleAttributes","ScopeStack","_ScopeStack","parent","scopeNames","name","segments","item","other","base","parentScopes","scopePattern","scopeMustMatch","_matchesScope","fontStyle","foregroundId","backgroundId","settings","resultLen","entry","scopes","_scope","j","lenJ","foreground","background","scope","ParsedThemeRule","FontStyle","FontStyle2","parsedThemeRules","defaultFontStyle","defaultForeground","defaultBackground","incomingDefaults","ColorMap","defaults","root","ThemeTrieElement","ThemeTrieElementRule","rule","color","emptyParentScopes","_ThemeTrieElementRule","scopeDepth","_ThemeTrieElement","_mainRule","rulesWithParentScopes","_children","aParentIndex","bParentIndex","parentScopeLengthDiff","dotIndex","head","tail","rules","child","EncodedTokenMetadata","_EncodedTokenMetadata","encodedTokenAttributes","languageId","tokenType","containsBalancedBrackets","_languageId","_tokenType","_containsBalancedBracketsBit","_fontStyle","_foreground","_background","createMatchers","selector","matchesName","results","tokenizer","newTokenizer","token","priority","matcher","parseConjunction","parseOperand","expressionToNegate","matcherInput","expressionInParents","parseInnerExpression","isIdentifier","identifiers","matchers","matcher2","input","regex","match","res","disposeOnigString","str","TopLevelRuleReference","scopeName","TopLevelRepositoryRuleReference","ruleName","ExternalReferenceCollector","reference","key","ScopeDependencyProcessor","repo","initialScopeName","q","deps","dep","collectReferencesOfReference","baseGrammarScopeName","result","selfGrammar","baseGrammar","collectExternalReferencesInTopLevelRule","collectExternalReferencesInTopLevelRepositoryRule","injections","injection","context","rule","collectExternalReferencesInRules","rules","patternRepository","mergeObjects","include","parseInclude","newContext","BaseReference","SelfReference","RelativeReference","TopLevelReference","TopLevelRepositoryReference","indexOfSharp","HAS_BACK_REFERENCES","BACK_REFERENCING_END","endRuleId","whileRuleId","Rule","$location","id","name","contentName","RegexSource","location","basename","lineText","captureIndices","CaptureRule","retokenizeCapturedWithRuleId","grammar","out","endRegexSource","allowA","allowG","MatchRule","match","captures","RegExpSource","RegExpSourceList","IncludeOnlyRule","patterns","pattern","BeginEndRule","begin","beginCaptures","end","endCaptures","applyEndPatternLast","BeginWhileRule","_while","whileCaptures","whileRuleId","RuleFactory","_RuleFactory","helper","desc","repository","mergeObjects","r","maximumCaptureId","captureId","numericCaptureId","i","len","ruleId","reference","parseInclude","localIncludedRule","externalGrammarName","externalGrammarInclude","externalGrammar","externalIncludedRule","rule","skipRule","_RegExpSource","regExpSource","lastPushedPos","output","hasAnchor","pos","nextCh","HAS_BACK_REFERENCES","newSource","capturedValues","capture","BACK_REFERENCING_END","g1","escapeRegExpCharacters","A0_G0_result","A0_G1_result","A1_G0_result","A1_G1_result","ch","item","index","onigLib","regExps","e","CompiledRule","rules","string","startPosition","options","result","BasicScopeAttributes","languageId","tokenType","BasicScopeAttributesProvider","_BasicScopeAttributesProvider","initialLanguageId","embeddedLanguages","ScopeMatcher","scopeName","CachedFn","standardTokenType","scope","m","values","escapedScopes","value","DebugFlags","UseOnigurumaFindOptions","TokenizeStringResult","stack","stoppedEarly","_tokenizeString","isFirstLine","linePos","lineTokens","checkWhileConditions","timeLimit","lineLength","STOP","anchorPosition","whileCheckResult","_checkWhileConditions","startTime","scanNext","matchRuleOrInjections","matchedRuleId","hasAdvanced","endRuleId","poppedRule","handleCaptures","popped","_rule","beforePush","nameScopesList","pushedRule","contentNameScopesList","whileRules","node","nodeRule","whileRule","ruleScanner","findOptions","prepareRuleWhileSearch","matchResult","matchRule","injections","injectionResult","matchInjections","matchResultScore","injectionResultScore","prepareRuleSearch","bestMatchRating","bestMatchCaptureIndices","bestMatchRuleId","bestMatchResultPriority","scopes","injection","matchRating","ruleScanner2","getFindOptions","lineTextContent","localStack","maxEnd","captureRule","captureIndex","stackClone","onigSubStr","disposeOnigString","captureRuleScopeName","captureRuleScopesList","LocalStackElement","endPos","createGrammar","initialLanguage","tokenTypes","balancedBracketSelectors","grammarRepository","Grammar","collectInjections","selector","ruleFactoryHelper","matchers","createMatchers","nameMatcher","matcher","identifers","lastIndex","identifier","scopesAreMatching","thisScopeName","_rootScopeName","_onigLib","initGrammar","sources","scopeName2","rawInjections","expression","injectionScopeNames","injectionScopeName","injectionGrammar","i1","i2","factory","rawIncludedGrammar","prevState","emitBinaryTokens","StateStackImpl","rawDefaultMetadata","defaultStyle","defaultMetadata","EncodedTokenMetadata","rootScopeName","scopeList","AttributedScopeStack","onigLineText","LineTokens","base","clone","_AttributedScopeStack","parent","scopePath","tokenAttributes","namesScopeList","current","scopeNames","frame","ScopeStack","rawRootMetadata","rootStyle","resolvedTokenAttributes","other","a","b","existingTokenAttributes","basicScopeAttributes","styleAttributes","fontStyle","foreground","background","target","rawMetadata","newPath","scopeThemeMatchResult","metadata","self","_StateStackImpl","enterPos","anchorPos","beginRuleCapturedEOL","endRule","el","res","outIndex","contentNameScopeStack","BalancedBracketSelectors","balancedBracketScopes","unbalancedBracketScopes","excluder","includer","tokenTypeOverrides","endIndex","scopesList","containsBalancedBrackets","scopes2","SyncRegistry","theme","targetScope","rawGrammar","Registry","Theme","colorMap","initialScopeName","configuration","dependencyProcessor","ScopeDependencyProcessor","request","INITIAL","htmlVoidElements","defaultSubsetRegex","surrogatePairsRegex","controlCharactersRegex","regexEscapeRegex","subsetToRegexCache","core","value","options","charactersToExpressionCached","basic","surrogate","pair","index","all","character","subset","cached","charactersToExpression","groups","hexadecimalRegex","toHexadecimal","code","next","omit","value","decimalRegex","toDecimal","code","next","omit","value","characterEntitiesLegacy","characterEntitiesHtml4","dangerous","own","characters","key","characterEntitiesHtml4","notAlphanumericRegex","toNamed","code","next","omit","attribute","character","name","value","characterEntitiesLegacy","dangerous","formatSmart","code","next","options","numeric","toHexadecimal","named","toNamed","decimal","toDecimal","stringifyEntities","value","options","core","formatSmart","htmlCommentRegex","bogusCommentEntitySubset","commentEntitySubset","comment","node","_1","_2","state","stringifyEntities","encode","$0","doctype","_1","_2","_3","state","re","whitespace","thing","empty","value","siblingAfter","siblings","siblingBefore","emptyChildren","increment","sibling","parent","index","includeWhitespace","offset","next","whitespace","own","omission","handlers","omit","node","index","parent","closing","omission","body","headOrColgroupOrCaption","dd","dt","html","li","optgroup","option","p","rubyElement","tbody","cells","tfoot","thead","tr","_","index","parent","next","siblingAfter","whitespace","opening","omission","body","colgroup","head","html","tbody","node","siblingAfter","seen","child","whitespace","index","parent","previous","siblingBefore","closing","constants","element","node","index","parent","state","schema","omit","selfClosing","parts","last","svg","attributes","serializeAttributes","content","opening","closing","properties","values","key","value","serializeAttribute","info","find","x","y","quote","result","name","stringifyEntities","stringify","ccount","textEntitySubset","text","node","_","parent","state","stringifyEntities","raw","node","index","parent","state","text","root","node","_1","_2","state","handle","zwitch","invalid","unknown","comment","doctype","element","raw","root","text","node","node_","emptyOptions","emptyCharacterReferences","emptyChildren","toHtml","tree","options","options_","quote","alternative","one","all","htmlVoidElements","svg","html","node","index","parent","handle","results","children","resolveColorReplacements","theme","options","replacements","themeName","key","value","applyColorReplacements","color","toArray","x","normalizeGetter","p","r","isPlainLang","lang","isSpecialLang","isNoneTheme","isSpecialTheme","addClassToHast","node","className","targets","c","splitLines","code","preserveEnding","parts","index","lines","i","line","createPositionConverter","indexToPos","character","lineText","posToIndex","DEFAULT_COLOR_LIGHT_DARK","COLOR_KEYS","splitToken","token","offsets","lastOffset","tokens","offset","splitTokens","breakpoints","sorted","a","b","line","breakpointsInToken","flatTokenVariants","merged","variantsOrder","cssVariablePrefix","defaultColor","colorsRendering","styles","t","getTokenStyleObject","styleKeys","mergedStyles","varKey","idx","key","keyName","cur","value","lightIndex","darkIndex","ShikiError","lightValue","darkValue","FontStyle","decorations","stringifyTokenStyle","_grammarStateMap","setLastGrammarStateToMap","keys","state","getLastGrammarStateFromMap","GrammarState","_GrammarState","lang","themes","toArray","theme","INITIAL","args","stacksMap","stack","getScopes","scopes","visited","pushScope","stack2","name","getGrammarStack","transformerDecorations","map","getContext","shiki","normalizePosition","p","converter","character","createPositionConverter","d","verifyIntersections","codeEl","ctx","lines","i","applyLineSection","start","end","decoration","lineEl","text","startIndex","endIndex","stringify","children","applyDecoration","wrapper","applyLine","el","type","properties","transform","addClassToHast","lineApplies","items","foo","j","bar","isFooHasBarStart","isFooHasBarEnd","isBarHasFooStart","isBarHasFooEnd","builtInTransformers","getTransformers","options","transformers","sortTransformersByEnforcement","pre","post","normal","transformer","namedColors","findSequence","position","nextEscape","nextClose","parseColor","sequence","colorMode","rgb","x","index","parseSequence","commands","code","codeInt","color","createAnsiSequenceParser","foreground","background","decorations2","findResult","styleToken","defaultNamedColorsMap","createColorPalette","namedColorsMap","namedColor","rgbColor","colorTable","getColorTable","levels","r","g","level","tableColor","defaultAnsiColors","tokenizeAnsiWithTheme","fileContents","colorReplacements","resolveColorReplacements","splitLines","ansiPalette","themeColor","colorPalette","parser","bgColor","applyColorReplacements","dimColor","fontStyle","hexMatch","hex","alpha","cssVarMatch","codeToTokensBase","internal","themeName","isPlainLang","isNoneTheme","colorMap","_grammar","tokenizeWithTheme","getLastGrammarState","_tokenizeWithTheme","grammar","result","grammarState","tokenizeMaxLineLength","tokenizeTimeLimit","stateStack","actual","final","len","lineOffset","resultWithScopes","tokensWithScopes","tokensWithScopesIndex","tokensLength","nextStartIndex","metadata","EncodedTokenMetadata","themeSettingsSelectors","setting","selectors","scope","selector","tokenWithScopes","tokenWithScopesText","explainThemeScopesNameOnly","explainThemeScopesFull","themeSelectors","explainThemeScope","matchesOne","matches","parentScopes","selectorParentIndex","parentIndex","settings","selectorPieces","codeToTokensWithThemes","themedTokens","tokens2","syncThemesTokenization","mergedTokens","lineIdx","_token","tokenIdx","mergedToken","themeIdx","_","__","___","mergedGrammarState","s","outThemes","count","outLines","i2","indexes","current","l","minLength","n","codeToTokens","bg","fg","rootStyle","themeTokens","themeRegs","themesOrder","themeColorReplacements","mapThemeColors","_theme","property","cssVar","t2","codeToHast","transformerContext","_code","_options","input","mergeWhitespaces","mergeSameStyleTokens","mergeWhitespaceTokens","splitWhitespaceTokens","mergeAdjacentStyledTokens","contextSource","tokensToHast","root","structure","tabindex","preNode","codeNode","lineNodes","context","lineNode","col","tokenNode","style","syntheticLines","currentLine","child","transformedCode","newLine","carryOnContent","firstOffset","couldMerge","match","leading","content","trailing","expanded","prevToken","prevStyle","currentStyle","isPrevDecorated","isDecorated","hastToHtml","toHtml","codeToHtml","VSCODE_FALLBACK_EDITOR_FG","VSCODE_FALLBACK_EDITOR_BG","RESOLVED_KEY","normalizeTheme","rawTheme","globalSetting","replacementCount","replacementMap","getReplacementColor","replaceFg","replaceBg","clone","replacement","resolveLangs","langs","isSpecialLang","normalizeGetter","resolveThemes","isSpecialTheme","_emitDeprecation","_emitError","warnDeprecated","message","version","_emitDeprecation","_emitError","ShikiError","resolveLangAlias","name","alias","resolved","Registry","_resolver","_themes","_langs","_alias","t","theme","_theme","normalizeTheme","textmateTheme","Theme","lang","embeddedLazilyBy","i","grammarConfig","g","e","langs","langsGraphArray","missingLangs","_","dependents","l","embedded","embeddedLang","Resolver","engine","patterns","s","langIdOrAlias","scopeName","a","scopeParts","injections","subScopeName","instancesCount","createShikiInternalSync","options","isDisposed","themes","resolver","_registry","_lastTheme","resolveLangAlias$1","getLanguage","ensureNotDisposed","_lang","getTheme","setTheme","colorMap","getLoadedThemes","getLoadedLanguages","loadLanguageSync","langs2","loadLanguage","resolveLangs","loadThemeSync","themes2","loadTheme","resolveThemes","dispose","createShikiInternal","createHighlighterCore","internal","args","getLastGrammarState","code","options2","codeToTokensBase","codeToTokensWithThemes","codeToTokens","codeToHast","codeToHtml","cpOf","char","getOrInsert","map","key","defaultValue","PosixClassNames","r","throwIfNullish","value","msg","charClassOpenPattern","r","sharedEscapesPattern","quantifierRe","tokenRe","charClassTokenRe","tokenize","pattern","options","opts","flagProperties","getFlagProperties","xStack","context","isXOn","tokens","match","result","getTokenWithDetails","potentialUnnamedCaptureTokens","numNamedAndOptInUnnamedCaptures","t","i","numCaptures","splitEscapedNumberToken","m","lastIndex","m0","m1","getAllTokensForCharClass","createAssertionToken","createSubroutineToken","createBackreferenceToken","createDirectiveToken","createCharacterSetToken","tokenizeSharedEscape","tokenizeNamedCallout","tokenizeFlagModifier","createGroupOpenToken","createGroupCloseToken","end","re","kind","createAlternatorToken","splitQuantifierMatch","createCharacterToken","cpOf","opener","createCharacterClassOpenToken","numCharClassesOpen","createCharacterClassCloseToken","tokenizeAnyTokenWithinCharClass","raw","posix","PosixClassNames","createCharacterClassHyphenToken","createCharacterClassIntersectorToken","inCharClass","char1","tokenizeControlCharacter","tokenizeShorthand","tokenizeUnicodeProperty","bytes","hex","decoded","encoder","char","byte","getValidatedHexCharCode","EscapeCharCodes","createEscapedNumberToken","value","negate","throwIfNullish","createNamedCalloutToken","tag","args","createQuantifierToken","min","max","CalloutNames","on","off","enabledFlags","getFlagGroupSwitches","disabledFlags","flagChanges","callout","name","argsArray","arg","arg0","arg1","arg2","tokenizeQuantifier","minStr","maxStr","limit","lower","p","neg","flags","obj","token","matches","str","withG","parts","hasOnlyChild","node","props","kid","key","isQuantifiable","node","quantifiableTypes","parse","pattern","options","opts","tokenized","tokenize","walk","parent","state","token","context","createAlternative","parseAssertion","parseBackreference","createCharacter","parseCharacterClassHyphen","parseCharacterClassOpen","parseCharacterSet","createDirective","parseGroupOpen","createNamedCallout","parseQuantifier","parseSubroutine","ast","createRegex","createFlags","top","node","capturingGroups","hasNumberedRef","namedGroupsByName","subroutines","ref","r","kind","createAssertion","throwIfNullish","raw","hasKWrapper","fromNum","num","isRelative","numCapturesToLeft","orphan","createBackreference","numberedRef","_","tokens","prevSiblingNode","nextToken","nextNode","createCharacterClassRange","cpOf","negate","intersections","createCharacterClass","ccFirstToken","throwIfUnclosedCharacterClass","cc","value","normalizeUnknownPropertyNames","skipPropertyNameValidation","unicodePropertyMap","normalized","slug","PosixClassNames","createUnicodeProperty","createPosixClass","createCharacterSet","skipLookbehindValidation","createByGroupKind","isThisAbsenceFunction","isThisLookbehind","isLookbehind","isThisNegLookbehind","getOrInsert","throwIfUnclosedGroup","alt","child","msg","isLookahead","min","max","quantifiedNode","isQuantifiable","createQuantifier","createSubroutine","createAbsenceFunction","getBodyForAlternativeContainer","getBodyForElementContainer","createCapturingGroup","number","isValidGroupName","charCode","hex","flags","createGroup","atomic","createLookaroundAssertion","tag","args","name","body","normalizeUnicodePropertyName","m","first","traverse","root","visitor","state","traverseArray","array","parent","i","keyShift","traverseNode","node","key","container","skipTraversingKidsOfPath","path","arrayContainer","numericKey","shifted","newNode","options","traverseNew","throwIfNullish","newNodes","keyShiftInLoop","type","anyTypeVisitor","thisTypeVisitor","enterAllFn","enterThisFn","value","noncapturingDelim","incrementIfAtLeast","arr","threshold","i","spliceStr","str","pos","oldValue","newValue","Context","replaceUnescaped","expression","needle","replacement","context","re","negated","numCharClassesOpen","result","match","m","$skip","forEachUnescaped","callback","execUnescaped","pos","hasUnescaped","getGroupContents","contentsStartPos","token","contentsEndPos","numGroupsOpen","atomicPluginToken","noncapturingDelim","atomic","expression","data","hiddenCaptures","captureTransfers","aGDelim","emulatedAGDelim","captureNumMap","addedHiddenCaptures","numCapturesBeforeAG","numAGs","aGPos","hasProcessedAG","numCharClassesOpen","numGroupsOpenInAG","inAG","match","m","index","capturingStart","noncapturingStart","addedCaptureNum","incrementIfAtLeast","newCaptureTransfers","from","to","f","replaceUnescaped","backrefNum","wrappedBackrefNum","bNum","Context","baseQuantifier","possessivePluginToken","possessive","openGroupIndices","lastGroupIndex","lastCharClassIndex","lastToken","qBase","qMod","invalidQ","charsAdded","spliceStr","nodeIndex","r","gRToken","recursiveToken","namedCaptureDelim","captureDelim","token","overlappingRecursionMsg","recursion","pattern","data","hiddenCaptures","mode","captureTransfers","hasUnescaped","Context","addedHiddenCaptures","hasNumberedBackref","groupContentsStartPos","openGroups","hasRecursed","numCharClassesOpen","numCapturesPassed","match","m","captureName","rDepth","gRNameOrNum","gRDepth","assertMaxInBounds","left","right","reps","makeRecursive","mapCaptureTransfers","isWithinReffedGroup","g","startPos","groupContents","getGroupContents","groupContentsLeft","groupContentsRight","numAddedHiddenCapturesPreExpansion","expansion","pre","post","isUnnamedCapture","max","errMsg","isSubpattern","namesInRecursed","forEachUnescaped","rest","repeatWithDepth","direction","getDepthNum","i","result","depthNum","replaceUnescaped","unnamed","backref","suffix","addedCaptureNum","incrementIfAtLeast","arr","threshold","numCapturesAddedInExpansion","numCapturesInLeft","recursionDelimCaptureNum","newCaptureTransfers","from","to","numCapturesInRight","numCapturesAddedInLeft","newTo","newFrom","f","cp","r","envFlags","globalRegExp","getNewCurrentFlags","current","enable","disable","getOrInsert","map","key","defaultValue","isMinTarget","target","min","EsVersion","throwIfNullish","value","msg","Target","getOptions","options","opts","asciiSpaceChar","CharsWithoutIgnoreCaseExpansion","defaultWordChar","getIgnoreCaseMatchChars","char","set","lower","upper","title","LowerToTitleCaseMap","altLower","LowerToAlternativeLowerCaseMap","altUpper","LowerToAlternativeUpperCaseMap","JsUnicodePropertyMap","p","w","titleEntry","titleRange","PosixClassMap","range","start","end","i","codePoint","UnicodePropertiesWithSpecificCase","transform","ast","addParentProperties","firstPassState","S","FirstPassVisitor","globalFlags","secondPassState","SecondPassVisitor","thirdPassState","ThirdPassVisitor","node","parent","replaceWith","body","kind","innerGroup","A","K","Q","outerGroup","_","setParentDeep","flagDirectivesByAlt","flagDirectives","el","forwardSiblingAlt","flags","getCombinedFlagModsFromFlagNodes","flagGroup","container","root","remove","state","negate","asciiWordBoundaries","avoidSubclass","supportedGNodes","wordIsAscii","b","F","m","parseFragment","prev","isAlwaysNonZeroLength","setParent","B","jsGroupNameMap","ref","isValidJsGroupName","getAndStoreJsGroupName","subroutineRefMap","name","cc","C","accuracy","minTargetEs2024","digitIsAscii","spaceIsAscii","E","setNegate","eBase","emoji","ascii","slug","removeAllPrevSiblings","removeAllNextSiblings","firstAlt","topLevel","o","lookbehind","f","group","leadingGs","hasAltWithLeadG","hasAltWithoutLeadG","alt","leadingG","getLeadingG","g","passedLookbehind","strategy","multiplexCapturesToLeftByRef","reffedNodesByReferencer","orphan","skip","groupOriginByCopy","groupsByName","openRefs","origin","recursion","createRecursion","multiplexNodes","multiplex","groupsWithSameName","hasDuplicateNameToRemove","groupInfo","isRecursive","reffed","reffedGroupNode","isGlobalRecursion","expandedSubroutine","cloneCapturingGroup","replacement","reffedGroupFlagMods","getAllParents","reffedGroupFlags","areFlagsEqual","getFlagModsFromFlags","participants","canParticipateWithNode","k","numCapsNeeded","emptyCapture","P","a","capture","rightmostPoint","kidsOfParent","getKids","kid","isAncestorOf","obj","originMap","up","up2","store","O","filterFn","results","jsName","flagNodes","flagProps","combinedFlags","prop","dotAll","ignoreCase","mods","els","firstToConsider","isLoneGLookaround","isAlwaysZeroLength","gNodesForGroup","descendant","kids","type","types","pattern","alts","J","generate","minTargetEs2025","recursionLimit","hasCaseInsensitiveNode","hasCaseSensitiveNode","iStack","traverse","FlagModifierVisitor","isIOn","appliedGlobalFlags","lastNode","gen","generator","result","isAnyGroup","currentModI","charHasCase","getCasesOutsideCharClassRange","number","data","escaped","getCharEscape","cases","isLiteralHyphen","createCharacter","genClass","negatedChildClasses","createGroup","groupFirstAlt","newAlt","createAlternative","firstEl","max","escOpts","minStr","maxStr","extraChars","charsOutsideRange","getCodePointRangesFromChars","atomic","currentFlags","contents","getGroupPrefix","getQuantifierStr","limit","BaseEscapeChars","CharClassEscapeChars","CharClassEscapeCharsFlagV","CharCodeEscapeMap","casedRe","firstOnly","found","caseOfChar","num","escDigit","inCharClass","useFlagV","isDigitCharCode","escapeChars","chars","codePoints","values","flagMods","useFlagMods","base","EmulatedRegExp","_EmulatedRegExp","#captureMap","#compiled","#pattern","#nameMap","#strategy","lazyCompile","re","createCaptureMap","str","rest","useLastIndex","pos","match","#execCore","adjustMatchDetailsForOffset","matchCopy","indicesCopy","mappedNums","hidden","transferTo","to","createNameMap","offset","input","hasIndices","indices","arr","groupIndices","hiddenCaptures","transfers","captureMap","from","numCharClassesOpen","numCaptures","toRegExp","d","toRegExpDetails","onigurumaAst","parse","regexPlusAst","generated","recursionResult","possessiveResult","possessive","atomicResult","details","JavaScriptScanner","patterns","options","forgiving","cache","regexConstructor","p","cached","regex","e","string","startPosition","_options","str","pending","toResult","index","match","offset","indice","i","regexp","minIndex","m","defaultJavaScriptRegexConstructor","pattern","options","toRegExp","createJavaScriptRegexEngine","_options","patterns","JavaScriptScanner","s","github_light_default","github_dark_default","Ie","Me","ce","je","Ne","M","n","Pe","Ee","O","j","E","te","de","Te","O","j","te","n","_e","ue","n","r","c","l","de","O","g","j","xe","He","Re","M","ne","Jt","_e","re","Ue","n","r","ze","We","ae","T","qe","c","l","g","o","p","m","L","Z","Fe","Ge","Ve","J","Ke","he","_","P","K","Ze","Je","V","q","Xe","github_light_default","github_dark_default","F","Ye","createJavaScriptRegexEngine","Qe","He","xe","ue","Ne","et","tt","createHighlighterCore","se","me","s","v","u","h","d","N","A","w","y","i","k","f","C","B","le","ge","pe","ke","oe","G","nt","rt","R","$","at","st","a","ot","it","lt","ct","dt","ut","ht","ft","U","mt","gt","pt","kt","yt","bt","wt","vt","$t","Ct","St","Bt","Lt","At","It","ie","Mt","jt","Nt","Pt","x","Et","fe","Dt","Tt","Xt","remarkMath","unified","remarkParse","remarkGfm","remarkRehype","rehypeKatex","S","b","D","I","X","z","Y","H","W","Q","Jt","import_reka_ui","import_vue","import_reka_ui","import_vue","STORAGE_KEY","ATTR","readStored","v","prefersLight","resolveInitialTheme","apply","theme","initTheme","useTheme","setTheme","next","toggleTheme","mq","onSystemChange","setThemeInternal","theme","toggleTheme","useTheme","import_vue","_hoisted_1","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createElementBlock","_normalizeClass","args","_createBlock","ThemeToggle_default","render","import_vue","_hoisted_1","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createElementBlock","_createVNode","_createElementVNode","_renderSlot","FieldError_default","render","props","__props","sortedChats","a","b","logoutOpen","loggingOut","logoutError","handleLogout","logout","import_vue","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createElementBlock","_createElementVNode","$event","_createVNode","_createTextVNode","_Fragment","_renderList","chat","_normalizeClass","_toDisplayString","_createCommentVNode","_withCtx","_createBlock","SidebarNavigation_default","render","import_vue","import_vue","usePersistedSize","opts","key","load","raw","parsed","size","timer","props","__props","emit","__emit","size","usePersistedSize","boxEl","observer","close","isOpen","entries","bs","w","import_vue","_hoisted_1","_hoisted_2","_hoisted_3","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createBlock","_Teleport","_createElementBlock","_withKeys","_createElementVNode","_normalizeStyle","_toDisplayString","_createVNode","_renderSlot","_createCommentVNode","ResizableDialog_default","render","props","__props","emit","__emit","menuOpen","promptOpen","mobileTitle","chat","navigationProps","selectChat","id","navigate","action","showPrompt","desktopQuery","closeDesktopMenu","import_vue","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createElementBlock","_Fragment","_createElementVNode","_createVNode","_mergeProps","$event","_withCtx","_toDisplayString","_createCommentVNode","_createTextVNode","_createBlock","Sidebar_default","render","import_vue","props","__props","emit","__emit","placeholder","isStreaming","isBusy","textareaEl","composing","onInput","e","onModelChange","onKeydown","onSubmit","import_vue","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createElementBlock","_withModifiers","_createElementVNode","$event","_Fragment","_renderList","m","_toDisplayString","_createVNode","_createBlock","PromptInput_default","render","import_vue","import_vue","AUTO_CLOSE_DELAY","props","__props","isOpen","duration","startTime","hasEverStreamed","hasAutoClosed","closeTimer","label","streaming","was","import_vue","_hoisted_1","_hoisted_2","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createElementBlock","_createElementVNode","$event","_createVNode","_normalizeClass","_toDisplayString","_withDirectives","_vShow","Reasoning_default","render","import_vue","import_vue","import_reka_ui","citationSourcesKey","citationMarkdown","reference","preprocessCitations","text","match","ids","citationReference","href","record","value","sourcesFromParts","parts","sources","part","results","item","hit","id","source","resolveCitation","options","exact","citationLabel","file","props","__props","label","citationLabel","passages","resolveCitation","missingTitle","passageLabel","source","chunk","import_vue","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createBlock","_withCtx","_createVNode","_createElementVNode","_toDisplayString","_createElementBlock","_createCommentVNode","_createTextVNode","_Fragment","_renderList","passage","SourceBadge_default","render","props","__props","isOpen","isComplete","part","queryOf","resultsOf","sourcesFromParts","allComplete","totalSources","sum","p","headerText","import_vue","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createElementBlock","_createElementVNode","$event","_createVNode","_toDisplayString","_normalizeClass","_withDirectives","_Fragment","_renderList","part","i","_createBlock","_createCommentVNode","r","_vShow","ChainOfThought_default","render","import_vue","props","__props","sources","citationSourcesKey","reference","citationReference","import_vue","_hoisted_1","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createBlock","_createElementBlock","_renderSlot","CitationLink_default","render","import_vue","props","__props","copied","timer","copy","import_vue","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createElementBlock","_createElementVNode","_createBlock","_normalizeClass","$event","_createVNode","MessageActions_default","render","props","__props","markdownComponents","CitationLink_default","markdownLinkPrefixes","citationSourcesKey","sourcesFromParts","assistantText","p","showActions","reasoningParts","reasoningText","hasReasoning","isReasoningStreaming","last","toolParts","logged","parts","part","import_vue","_hoisted_1","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createElementBlock","_normalizeClass","_createElementVNode","_createCommentVNode","_createBlock","_Fragment","_renderList","part","i","rating","MessageItem_default","render","import_vue","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createBlock","$event","_withCtx","_createElementVNode","_createElementBlock","_Fragment","_renderList","conv","_createVNode","_toDisplayString","TestModePicker_default","render","import_vue","props","__props","emit","__emit","comment","textareaEl","fieldId","title","placeholder","isValid","isOpen","close","submit","import_vue","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createBlock","_Teleport","_createElementBlock","_withKeys","_createElementVNode","_toDisplayString","_createVNode","_withDirectives","$event","_vModelText","_createCommentVNode","FeedbackDialog_default","render","import_vue","marker","symbol","_a","_b","AISDKError","_AISDKError","name","message","cause","error","markerSymbol","APICallError","url","requestBodyValues","statusCode","responseHeaders","responseBody","isRetryable","data","EmptyResponseBodyError","EvaluationUnsupportedQuestionTypeError","questionId","questionType","provider","modelId","getErrorMessage","InvalidArgumentError","argument","InvalidPromptError","prompt","InvalidResponseDataError","JSONParseError","text","LoadAPIKeyError","LoadSettingError","NoContentGeneratedError","NoSuchModelError","errorName","modelType","NoSuchProviderReferenceError","reference","TooManyEmbeddingValuesForCallError","options","TypeValidationError","_TypeValidationError","value","context","contextPrefix","parts","_c","UnsupportedFunctionalityError","functionality","_a","$constructor","name","initializer","params","init","inst","def","_","proto","keys","i","k","Parent","Definition","_a","fn","$ZodAsyncError","$ZodEncodeError","name","_a","globalConfig","config","newConfig","util_exports","__export","BIGINT_FORMAT_RANGES","Class","NUMBER_FORMAT_RANGES","aborted","allowsEval","assert","assertEqual","assertIs","assertNever","assertNotEqual","assignProp","base64ToUint8Array","base64urlToUint8Array","cached","captureStackTrace","cleanEnum","cleanRegex","clone","cloneDef","createTransparentProxy","defineLazy","esc","escapeRegex","explicitlyAborted","extend","finalizeIssue","floatSafeRemainder","getElementAtPath","getEnumValues","getLengthableOrigin","getParsedType","getSizableOrigin","hexToUint8Array","isObject","isPlainObject","issue","joinValues","jsonStringifyReplacer","merge","mergeDefs","normalizeParams","nullish","numKeys","objectClone","omit","optionalKeys","parsedType","partial","pick","prefixIssues","primitiveTypes","promiseAllObject","propertyKeyTypes","randomString","required","safeExtend","shallowClone","slugify","stringifyPrimitive","uint8ArrayToBase64","uint8ArrayToBase64url","uint8ArrayToHex","unwrapMessage","assertEqual","val","assertNotEqual","assertIs","_arg","assertNever","_x","assert","_","getEnumValues","entries","numericValues","v","k","joinValues","array","separator","stringifyPrimitive","jsonStringifyReplacer","value","cached","getter","nullish","input","cleanRegex","source","start","end","floatSafeRemainder","step","ratio","roundedRatio","tolerance","EVALUATING","defineLazy","object","key","objectClone","obj","assignProp","target","prop","mergeDefs","defs","mergedDescriptors","def","descriptors","cloneDef","schema","getElementAtPath","path","acc","promiseAllObject","promisesObj","keys","promises","results","resolvedObj","i","randomString","length","chars","str","esc","slugify","captureStackTrace","_args","isObject","data","allowsEval","globalConfig","F","isPlainObject","o","ctor","prot","shallowClone","numKeys","keyCount","getParsedType","propertyKeyTypes","primitiveTypes","escapeRegex","clone","inst","params","cl","normalizeParams","_params","createTransparentProxy","receiver","descriptor","optionalKeys","shape","NUMBER_FORMAT_RANGES","BIGINT_FORMAT_RANGES","pick","mask","currDef","checks","newShape","omit","extend","existingShape","_shape","safeExtend","merge","a","b","partial","Class","oldShape","required","aborted","x","startIndex","explicitlyAborted","prefixIssues","issues","iss","_a","unwrapMessage","message","finalizeIssue","ctx","config","_inst","_continue","_input","rest","getSizableOrigin","getLengthableOrigin","parsedType","issue","args","cleanEnum","el","base64ToUint8Array","base64","binaryString","bytes","uint8ArrayToBase64","base64urlToUint8Array","base64url","padding","uint8ArrayToBase64url","hexToUint8Array","hex","cleanHex","uint8ArrayToHex","initializer","inst","def","jsonStringifyReplacer","$ZodError","$constructor","$ZodRealError","flattenError","error","mapper","issue","fieldErrors","formErrors","sub","formatError","processError","path","issues","fullpath","curr","i","el","_parse","_Err","schema","value","_ctx","_params","ctx","result","$ZodAsyncError","e","iss","finalizeIssue","config","captureStackTrace","_parseAsync","_Err","schema","value","_ctx","params","ctx","result","e","iss","finalizeIssue","config","captureStackTrace","_safeParse","_Err","schema","value","_ctx","ctx","result","$ZodAsyncError","$ZodError","iss","finalizeIssue","config","safeParse","$ZodRealError","_safeParseAsync","safeParseAsync","_encode","_parse","_decode","_Err","schema","value","_ctx","_parse","_encodeAsync","_Err","schema","value","_ctx","ctx","_parseAsync","_decodeAsync","_Err","schema","value","_ctx","_parseAsync","_safeEncode","_Err","schema","value","_ctx","ctx","_safeParse","_safeDecode","_Err","schema","value","_ctx","_safeParse","_safeEncodeAsync","_Err","schema","value","_ctx","ctx","_safeParseAsync","_safeDecodeAsync","_Err","schema","value","_ctx","_safeParseAsync","cuid","cuid2","ulid","xid","ksuid","nanoid","duration","guid","uuid","version","email","_emoji","emoji","ipv4","ipv6","cidrv4","cidrv6","base64","base64url","httpProtocol","e164","dateSource","date","timeSource","args","hhmm","time","datetime","opts","timeRegex","string","params","regex","integer","number","boolean","_null","lowercase","uppercase","$ZodCheck","$constructor","inst","def","_a","numericOriginMap","$ZodCheckLessThan","origin","bag","curr","payload","$ZodCheckGreaterThan","$ZodCheckMultipleOf","floatSafeRemainder","$ZodCheckNumberFormat","isInt","minimum","maximum","NUMBER_FORMAT_RANGES","integer","input","$ZodCheckMaxLength","$constructor","inst","def","_a","$ZodCheck","payload","val","nullish","curr","input","origin","getLengthableOrigin","$ZodCheckMinLength","$ZodCheckLengthEquals","bag","length","tooBig","$ZodCheckStringFormat","_b","$ZodCheckRegex","$ZodCheckLowerCase","lowercase","$ZodCheckUpperCase","uppercase","$ZodCheckIncludes","escapedRegex","escapeRegex","pattern","$ZodCheckStartsWith","$ZodCheckEndsWith","$ZodCheckOverwrite","$constructor","inst","def","$ZodCheck","payload","Doc","args","fn","arg","lines","x","minIndent","dedented","line","F","version","$ZodType","$constructor","inst","def","_a","version","checks","ch","fn","runChecks","payload","ctx","isAborted","aborted","asyncResult","explicitlyAborted","currLen","_","$ZodAsyncError","handleCanaryResult","canary","checkResult","result","defineLazy","value","r","safeParse","safeParseAsync","$ZodString","string","$ZodStringFormat","$ZodCheckStringFormat","$ZodGUID","guid","$ZodUUID","v","uuid","$ZodEmail","email","$ZodURL","trimmed","httpProtocol","url","$ZodEmoji","emoji","$ZodNanoID","nanoid","$ZodCUID","cuid","$ZodCUID2","cuid2","$ZodULID","ulid","$ZodXID","xid","$ZodKSUID","ksuid","$ZodISODateTime","datetime","$ZodISODate","date","$ZodISOTime","time","$ZodISODuration","duration","$ZodIPv4","ipv4","$ZodIPv6","ipv6","$ZodCIDRv4","$constructor","inst","def","cidrv4","$ZodStringFormat","$ZodCIDRv6","cidrv6","payload","parts","address","prefix","prefixNum","isValidBase64","data","$ZodBase64","base64","isValidBase64URL","base64url","c","padded","$ZodBase64URL","$ZodE164","e164","isValidJWT","token","algorithm","tokensParts","header","parsedHeader","$ZodJWT","$ZodNumber","$constructor","inst","def","$ZodType","number","payload","_ctx","input","received","$ZodNumberFormat","$ZodCheckNumberFormat","$ZodBoolean","boolean","$ZodNull","$constructor","inst","def","$ZodType","_null","payload","_ctx","input","$ZodUnknown","$constructor","inst","def","$ZodType","payload","$ZodNever","_ctx","handleArrayResult","result","final","index","prefixIssues","$ZodArray","$constructor","inst","def","$ZodType","payload","ctx","input","proms","item","handlePropertyResult","key","isOptionalIn","isOptionalOut","isPresent","normalizeDef","keys","k","okeys","optionalKeys","handleCatchall","unrecognized","keySet","_catchall","t","r","$ZodObject","sh","newSh","_normalized","cached","defineLazy","shape","propValues","field","v","isObject","catchall","value","el","$ZodObjectJIT","superParse","generateFastpass","doc","Doc","normalized","parseStr","esc","ids","counter","id","schema","fn","fastpass","jit","globalConfig","fastEnabled","allowsEval","handleUnionResults","results","nonaborted","aborted","iss","finalizeIssue","config","$ZodUnion","o","option","patterns","p","cleanRegex","first","async","$ZodDiscriminatedUnion","$constructor","inst","def","$ZodUnion","_super","defineLazy","propValues","option","pv","k","v","val","disc","cached","opts","map","o","values","payload","ctx","input","isObject","opt","$ZodIntersection","$ZodType","left","right","handleIntersectionResults","mergeValues","a","b","isPlainObject","bKeys","sharedKeys","key","newObj","sharedValue","newArray","index","itemA","itemB","result","unrecKeys","unrecIssue","iss","bothKeys","f","aborted","merged","$ZodRecord","$constructor","inst","def","$ZodType","payload","ctx","input","isPlainObject","proms","values","recordKeys","key","keyResult","iss","finalizeIssue","config","outKey","result","prefixIssues","unrecognized","number","retryResult","$ZodEnum","$constructor","inst","def","$ZodType","values","getEnumValues","valuesSet","k","propertyKeyTypes","o","escapeRegex","payload","_ctx","input","$ZodLiteral","$ZodTransform","$constructor","inst","def","$ZodType","payload","ctx","$ZodEncodeError","_out","output","$ZodAsyncError","handleOptionalResult","result","input","$ZodOptional","defineLazy","pattern","cleanRegex","r","$ZodExactOptional","$ZodNullable","$ZodDefault","handleDefaultResult","$ZodPrefault","$ZodNonOptional","v","x","handleNonOptionalResult","$ZodCatch","$constructor","inst","def","$ZodType","defineLazy","payload","ctx","result","iss","finalizeIssue","config","$ZodPipe","$constructor","inst","def","$ZodType","defineLazy","payload","ctx","right","handlePipeResult","left","next","$ZodReadonly","$constructor","inst","def","$ZodType","defineLazy","payload","ctx","result","handleReadonlyResult","$ZodLazy","$constructor","inst","def","$ZodType","defineLazy","d","payload","ctx","$ZodCustom","$ZodCheck","_","input","r","handleRefineResult","result","_iss","issue","_a","$ZodRegistry","schema","_meta","meta","p","pm","f","registry","_a","globalRegistry","_string","Class","params","normalizeParams","_email","Class","params","normalizeParams","_guid","_uuid","_uuidv4","_uuidv6","_uuidv7","_url","_emoji","_nanoid","_cuid","_cuid2","_ulid","_xid","_ksuid","_ipv4","_ipv6","_cidrv4","Class","params","normalizeParams","_cidrv6","_base64","_base64url","_e164","_jwt","_isoDateTime","Class","params","normalizeParams","_isoDate","_isoTime","_isoDuration","_number","_int","Class","params","normalizeParams","_boolean","Class","params","normalizeParams","_null","Class","params","normalizeParams","_unknown","Class","_never","params","normalizeParams","_lt","value","params","$ZodCheckLessThan","normalizeParams","_lte","_gt","value","params","$ZodCheckGreaterThan","normalizeParams","_gte","_multipleOf","value","params","$ZodCheckMultipleOf","normalizeParams","_maxLength","maximum","params","$ZodCheckMaxLength","normalizeParams","_minLength","minimum","$ZodCheckMinLength","_length","length","$ZodCheckLengthEquals","_regex","pattern","$ZodCheckRegex","_lowercase","$ZodCheckLowerCase","_uppercase","$ZodCheckUpperCase","_includes","includes","$ZodCheckIncludes","_startsWith","prefix","$ZodCheckStartsWith","_endsWith","suffix","$ZodCheckEndsWith","_overwrite","tx","$ZodCheckOverwrite","_normalize","form","input","_trim","_toLowerCase","_toUpperCase","_slugify","slugify","_array","Class","element","params","normalizeParams","_custom","Class","fn","_params","norm","normalizeParams","_refine","_superRefine","params","ch","_check","payload","issue","_issue","$ZodCheck","initializeContext","params","target","globalRegistry","process","schema","ctx","_params","_a","def","seen","result","overrideSchema","_json","processor","parent","meta","isTransforming","extractDefs","root","idToSchema","entry","id","existing","makeURI","defsSegment","externalId","uriGenerator","defUriPrefix","defId","extractToDef","ref","key","ext","finalize","flattenRef","zodSchema","_cached","refSeen","refSchema","parentSeen","rootMetaId","defs","finalized","createStandardJSONSchemaMethod","_schema","_ctx","option","item","createToJSONSchemaMethod","processors","io","libraryOptions","formatMap","stringProcessor","schema","ctx","_json","_params","json","minimum","maximum","format","patterns","contentEncoding","regexes","regex","numberProcessor","multipleOf","exclusiveMaximum","exclusiveMinimum","exMin","exMax","legacy","booleanProcessor","_schema","_ctx","bigintProcessor","symbolProcessor","nullProcessor","undefinedProcessor","voidProcessor","neverProcessor","anyProcessor","unknownProcessor","dateProcessor","enumProcessor","def","values","getEnumValues","v","literalProcessor","vals","val","nanProcessor","templateLiteralProcessor","pattern","fileProcessor","file","mime","m","successProcessor","customProcessor","functionProcessor","transformProcessor","mapProcessor","setProcessor","arrayProcessor","params","process","objectProcessor","shape","key","allKeys","requiredKeys","unionProcessor","isExclusive","options","x","i","intersectionProcessor","a","b","isSimpleIntersection","allOf","tupleProcessor","prefixPath","restPath","prefixItems","rest","recordProcessor","keyType","valueSchema","keyValues","validKeyValues","nullableProcessor","inner","seen","nonoptionalProcessor","defaultProcessor","prefaultProcessor","catchProcessor","catchValue","pipeProcessor","inIsTransform","innerType","readonlyProcessor","promiseProcessor","optionalProcessor","lazyProcessor","allProcessors","toJSONSchema","input","registry","initializeContext","defs","entry","_","schemas","external","extractDefs","finalize","defsSegment","ZodISODateTime","$constructor","inst","def","$ZodISODateTime","ZodStringFormat","datetime","params","_isoDateTime","ZodISODate","$ZodISODate","date","_isoDate","ZodISOTime","$ZodISOTime","time","_isoTime","ZodISODuration","$ZodISODuration","duration","_isoDuration","initializer","inst","issues","$ZodError","mapper","formatError","flattenError","issue","jsonStringifyReplacer","ZodRealError","$constructor","initializer","parse","_parse","ZodRealError","parseAsync","_parseAsync","safeParse","_safeParse","safeParseAsync","_safeParseAsync","encode","_encode","decode","_decode","encodeAsync","_encodeAsync","decodeAsync","_decodeAsync","safeEncode","_safeEncode","safeDecode","_safeDecode","safeEncodeAsync","_safeEncodeAsync","safeDecodeAsync","_safeDecodeAsync","_installedGroups","_installLazyMethods","inst","group","methods","proto","installed","key","fn","bound","v","ZodType","$constructor","def","$ZodType","createStandardJSONSchemaMethod","createToJSONSchemaMethod","data","params","parse","safeParse","parseAsync","safeParseAsync","encode","decode","encodeAsync","decodeAsync","safeEncode","safeDecode","safeEncodeAsync","safeDecodeAsync","chks","util_exports","ch","clone","reg","meta","check","refine","refinement","superRefine","_overwrite","optional","exactOptional","nullable","nonoptional","array","arg","union","intersection","tx","pipe","transform","d","_default","prefault","_catch","target","readonly","description","cl","globalRegistry","args","_ZodString","$ZodString","ctx","json","stringProcessor","bag","_regex","_includes","_startsWith","_endsWith","_minLength","_maxLength","_length","_lowercase","_uppercase","_trim","_normalize","_toLowerCase","_toUpperCase","_slugify","ZodString","_email","ZodEmail","_url","ZodURL","_jwt","ZodJWT","_emoji","ZodEmoji","_guid","ZodGUID","_uuid","ZodUUID","_uuidv4","_uuidv6","_uuidv7","_nanoid","ZodNanoID","_cuid","ZodCUID","_cuid2","ZodCUID2","_ulid","ZodULID","_base64","ZodBase64","_base64url","ZodBase64URL","_xid","ZodXID","_ksuid","ZodKSUID","_ipv4","ZodIPv4","_ipv6","ZodIPv6","_cidrv4","ZodCIDRv4","_cidrv6","ZodCIDRv6","_e164","ZodE164","datetime","date","time","duration","string","_string","ZodStringFormat","$ZodStringFormat","$ZodEmail","ZodGUID","$constructor","inst","def","$ZodGUID","ZodStringFormat","ZodUUID","$constructor","inst","def","$ZodUUID","ZodStringFormat","ZodURL","$constructor","inst","def","$ZodURL","ZodStringFormat","ZodEmoji","$constructor","inst","def","$ZodEmoji","ZodStringFormat","ZodNanoID","$constructor","inst","def","$ZodNanoID","ZodStringFormat","ZodCUID","$constructor","inst","def","$ZodCUID","ZodStringFormat","ZodCUID2","$constructor","inst","def","$ZodCUID2","ZodStringFormat","ZodULID","$constructor","inst","def","$ZodULID","ZodStringFormat","ZodXID","$constructor","inst","def","$ZodXID","ZodStringFormat","ZodKSUID","$constructor","inst","def","$ZodKSUID","ZodStringFormat","ZodIPv4","$constructor","inst","def","$ZodIPv4","ZodStringFormat","ZodIPv6","$constructor","inst","def","$ZodIPv6","ZodStringFormat","ZodCIDRv4","$constructor","inst","def","$ZodCIDRv4","ZodStringFormat","ZodCIDRv6","$constructor","inst","def","$ZodCIDRv6","ZodStringFormat","ZodBase64","$constructor","inst","def","$ZodBase64","ZodStringFormat","ZodBase64URL","$constructor","inst","def","$ZodBase64URL","ZodStringFormat","ZodE164","$constructor","inst","def","$ZodE164","ZodStringFormat","ZodJWT","$constructor","inst","def","$ZodJWT","ZodStringFormat","ZodNumber","$constructor","inst","def","$ZodNumber","ZodType","ctx","json","params","numberProcessor","_installLazyMethods","value","_gt","_gte","_lt","_lte","int","_multipleOf","bag","number","_number","ZodNumberFormat","$ZodNumberFormat","_int","ZodBoolean","$constructor","inst","def","$ZodBoolean","ZodType","ctx","json","params","booleanProcessor","boolean","_boolean","ZodNull","$constructor","inst","def","$ZodNull","ZodType","ctx","json","params","nullProcessor","_null","ZodUnknown","$constructor","inst","def","$ZodUnknown","ZodType","ctx","json","params","unknownProcessor","unknown","_unknown","ZodNever","$ZodNever","neverProcessor","never","_never","ZodArray","$constructor","inst","def","$ZodArray","ZodType","ctx","json","params","arrayProcessor","_installLazyMethods","n","_minLength","_maxLength","_length","array","element","_array","ZodObject","$constructor","inst","def","$ZodObjectJIT","ZodType","ctx","json","params","objectProcessor","util_exports","_installLazyMethods","_enum","catchall","unknown","never","incoming","other","mask","args","ZodOptional","ZodNonOptional","object","shape","looseObject","shape","params","ZodObject","unknown","util_exports","ZodUnion","$constructor","inst","def","$ZodUnion","ZodType","ctx","json","unionProcessor","union","options","ZodDiscriminatedUnion","$constructor","inst","def","ZodUnion","$ZodDiscriminatedUnion","discriminatedUnion","discriminator","options","params","util_exports","ZodIntersection","$ZodIntersection","ZodType","ctx","json","intersectionProcessor","intersection","left","right","ZodRecord","$constructor","inst","def","$ZodRecord","ZodType","ctx","json","params","recordProcessor","record","keyType","valueType","string","util_exports","ZodEnum","$constructor","inst","def","$ZodEnum","ZodType","ctx","json","params","enumProcessor","keys","values","newEntries","value","util_exports","_enum","entries","v","ZodLiteral","$constructor","inst","def","$ZodLiteral","ZodType","ctx","json","params","literalProcessor","literal","value","util_exports","ZodTransform","$constructor","inst","def","$ZodTransform","ZodType","ctx","json","params","transformProcessor","payload","_ctx","$ZodEncodeError","issue","util_exports","_issue","output","transform","fn","ZodOptional","$ZodOptional","optionalProcessor","optional","innerType","ZodExactOptional","$ZodExactOptional","exactOptional","ZodNullable","$ZodNullable","nullableProcessor","nullable","ZodDefault","$constructor","inst","def","$ZodDefault","ZodType","ctx","json","params","defaultProcessor","_default","innerType","defaultValue","util_exports","ZodPrefault","$ZodPrefault","prefaultProcessor","prefault","ZodNonOptional","$ZodNonOptional","nonoptionalProcessor","nonoptional","ZodCatch","$constructor","inst","def","$ZodCatch","ZodType","ctx","json","params","catchProcessor","_catch","innerType","catchValue","ZodPipe","$constructor","inst","def","$ZodPipe","ZodType","ctx","json","params","pipeProcessor","pipe","in_","out","ZodReadonly","$constructor","inst","def","$ZodReadonly","ZodType","ctx","json","params","readonlyProcessor","readonly","innerType","ZodLazy","$constructor","inst","def","$ZodLazy","ZodType","ctx","json","params","lazyProcessor","lazy","getter","ZodCustom","$constructor","inst","def","$ZodCustom","ZodType","ctx","json","params","customProcessor","custom","fn","_params","_custom","ZodCustom","refine","_refine","superRefine","params","_superRefine","_instanceof","cls","params","inst","ZodCustom","data","util_exports","payload","ParseError","message","options","LF","CR","SPACE","noop","_arg","createParser","config","onEvent","onError","onRetry","onComment","maxBufferSize","pendingFragments","pendingFragmentsLength","isFirstChunk","id","data","dataLines","eventType","terminated","feed","chunk","trailing","processLines","checkBufferSize","input","searchIndex","lfIndex","firstCharCode","isDataPrefix","valueStart","value","isEventPrefix","parseLine","crIndex","lineEnd","start","end","dispatchEvent","line","fieldSeparatorIndex","processField","field","offset","reset","incompleteLine","i","EventSourceParserStream","onError","onRetry","onComment","maxBufferSize","parser","controller","createParser","event","error","chunk","textDecoder","btoa","atob","getRuntimeEnvironmentUserAgent","globalThisAny","_a","_b","_c","normalizeHeaders","headers","normalized","value","key","withUserAgentSuffix","userAgentSuffixParts","normalizedHeaders","currentUserAgentHeader","audioMediaTypeSignaturesWithoutMp4","audioMediaTypeSignatures","MAX_SIGNATURE_BYTES","MAX_ID3_TAG_BYTES","ID3_SCAN_BYTES","cancelResponseBody","response","_a","name","marker","symbol","_b","DownloadError","AISDKError","url","statusCode","statusText","cause","message","error","isBrowserRuntime","globalThisAny","isSameOrigin","baseUrl","validateDownloadUrl","parsed","hostname","ipv6","isPrivateIPv6","isIPv4","isPrivateIPv4","validateDownloadAddress","address","family","parts","part","num","ip","a","b","c","parseIPv6","zoneIndex","halves","toGroups","segment","groups","i","d","head","tail","fill","topZero","count","group","createSafeLookup","lookup","options","callback","addresses","firstAddress","safeNodeFetchPromise","isNodeRuntime","_c","runtimeProcess","getDefaultDownloadFetch","createSafeNodeFetch","createRequire","loadBuiltinModule","Agent","fetch","getCurrentModulePath","dispatcher","input","init","id","processWithBuiltins","builtinModule","originalPrepareStackTrace","_error","callSites","caller","fileName","BLOCKED_REQUEST_HEADERS","sanitizeRequestHeaders","headers","MAX_DOWNLOAD_REDIRECTS","REDIRECT_STATUS_CODES","getValidatedFetch","customFetch","fetchWithValidatedRedirects","url","headers","abortSignal","maxRedirects","MAX_DOWNLOAD_REDIRECTS","customFetch","trustedOrigin","_a","currentHeaders","sanitizeRequestHeaders","perHopInit","redirect","init","currentUrl","redirectCount","isTrustedHop","isSameOrigin","validateDownloadUrl","fetch","getValidatedFetch","response","isBrowserRuntime","DownloadError","location","REDIRECT_STATUS_CODES","cancelResponseBody","nextUrl","userAgent","DEFAULT_MAX_DOWNLOAD_SIZE","readResponseWithSizeLimit","maxBytes","contentLength","length","body","reader","chunks","totalBytes","done","value","result","offset","chunk","createIdGenerator","prefix","size","alphabet","separator","generator","alphabetLength","chars","i","InvalidArgumentError","generateId","isBuffer","value","_a","_b","suspectProtoRx","suspectConstructorRx","_parse","text","obj","filter","next","nodes","node","key","value","secureJsonParse","stackTraceLimit","addAdditionalPropertiesToJsonSchema","jsonSchema","additionalProperties","visit","properties","definitions","def","ignoreOverride","defaultOptions","getDefaultOptions","options","parseAnyDef","parseArrayDef","refs","_a","_b","_c","res","parseDef","parseBigintDef","check","parseBooleanDef","parseBrandedDef","_def","parseCatchDef","parseDateDef","overrideDateStrategy","strategy","item","integerDateParser","parseDefaultDef","parseEffectsDef","parseEnumDef","isJsonSchema7AllOfType","type","parseIntersectionDef","allOf","x","mergedAllOf","schema","nestedSchema","_additionalProperties","rest","parseLiteralDef","parsedType","emojiRegex","zodPatterns","parseStringDef","addFormat","addPattern","escapeLiteralCheckValue","literal","escapeNonAlphaNumeric","ALPHA_NUMERIC","source","result","i","message","regex","stringifyRegExpWithFlags","flags","pattern","isEscaped","inCharGroup","inCharRange","parseRecordDef","_d","_e","_f","_type","keyType","parseMapDef","keys","values","parseNativeEnumDef","object","actualValues","parsedTypes","parseNeverDef","parseNullDef","primitiveMappings","parseUnionDef","types","acc","uniqueTypes","a","asAnyOf","anyOf","parseNullableDef","base","parseNumberDef","parseObjectDef","required","shape","propName","propDef","propOptional","safeIsOptional","parsedDef","decideAdditionalProperties","parseOptionalDef","innerSchema","parsePipelineDef","inputSchema","outputSchema","parsePromiseDef","parseSetDef","parseTupleDef","parseUndefinedDef","parseUnknownDef","parseReadonlyDef","selectParser","typeName","_","getRelativePath","pathA","pathB","forceResolution","seenItem","overrideResult","seenSchema","get$ref","newItem","jsonSchemaOrGetter","addMeta","postProcessResult","index","getRefs","_options","currentPath","name","zod3ToJsonSchema","main","title","combined","schemaSymbol","lazySchema","createSchema","validate","isSchema","asSchema","zodSchema","standardSchema","hasStandardJsonSchema","TypeValidationError","zod3Schema","useReferences","zod4Schema","toJSONSchema","safeParseAsync","isZod4Schema","validateTypes","context","safeValidateTypes","actualSchema","error","safeParseJSON","text","schema","value","secureJsonParse","safeValidateTypes","error","JSONParseError","parseJsonEventStream","stream","schema","EventSourceParserStream","data","controller","safeParseJSON","resolve","value","textDecoder","name","marker","symbol","_a","_b","SerializationError","AISDKError","message","cause","error","name","marker","symbol","_a","_b","InvalidArgumentError","AISDKError","parameter","value","message","error","InvalidStreamPartError","chunk","InvalidToolApprovalError","approvalId","InvalidToolApprovalSignatureError","toolCallId","reason","InvalidToolInputError","toolInput","toolName","cause","getErrorMessage","ToolCallNotFoundForApprovalError","MissingToolResultsError","toolCallIds","NoImageGeneratedError","calls","responses","NoObjectGeneratedError","text","response","usage","finishReason","NoOutputGeneratedError","NoSpeechGeneratedError","options","NoTranscriptGeneratedError","NoTranslationGeneratedError","NoVideoGeneratedError","NoSuchToolError","availableTools","StreamProviderError","type","code","statusCode","isRetryable","isRetryableStatusCode","data","ToolCallRepairError","originalError","ToolChoiceViolationError","toolChoice","provider","modelId","content","name","marker","symbol","_a","_b","UIMessageStreamError","AISDKError","chunkType","chunkId","message","error","InvalidDataContentError","content","cause","InvalidMessageRoleError","role","MessageConversionError","originalMessage","RetryError","reason","errors","formatWarning","warning","provider","model","prefix","FIRST_WARNING_INFO_MESSAGE","hasLoggedBefore","emitWarning","type","logWarnings","options","logger","VERSION","download","url","maxBytes","abortSignal","_a","urlText","headers","withUserAgentSuffix","getRuntimeEnvironmentUserAgent","response","fetchWithValidatedRedirects","cancelResponseBody","DownloadError","readResponseWithSizeLimit","DEFAULT_MAX_DOWNLOAD_SIZE","error","mergeObjects","base","overrides","result","key","overridesValue","baseValue","isSourceObject","isTargetObject","z","array","boolean","custom","discriminatedUnion","_enum","_instanceof","lazy","literal","looseObject","never","_null","number","object","record","string","union","unknown","jsonValueSchema","providerMetadataSchema","fileInlineDataSchema","isBuffer","providerReferenceSchema","textPartSchema","imagePartSchema","taggedFileDataSchema","taggedReasoningFileDataSchema","filePartSchema","reasoningPartSchema","customPartSchema","value","reasoningFilePartSchema","toolCallPartSchema","outputSchema","toolResultPartSchema","toolApprovalRequestSchema","toolApprovalResponseSchema","systemModelMessageSchema","userModelMessageSchema","assistantModelMessageSchema","toolModelMessageSchema","modelMessageSchema","output_exports","__export","array","choice","json","object","text","fixJson","input","stack","lastValidIndex","literalStart","unicodeEscapeDigits","isHexDigit","char","processValueStart","i","swapState","processAfterObjectValue","processAfterArrayValue","partialLiteral","result","parsePartialJson","jsonText","safeParseJSON","inputSchema","name","description","schema","asSchema","resolve","jsonSchema","context","parseResult","NoObjectGeneratedError","validationResult","safeValidateTypes","inputElementSchema","minItems","maxItems","validateArrayBound","InvalidArgumentError","elementSchema","_$schema","definitions","$defs","itemSchema","outerValue","TypeValidationError","lengthValidationError","getArrayLengthValidationError","validatedElements","element","rawElements","parsedElements","rawElement","publishedElements","partialOutput","controller","value","choiceOptions","potentialMatches","choiceOption","encoder","encoder","originalGenerateId","createIdGenerator","originalGenerateCallId","JsonToSseTransformStream","part","controller","toolMetadataSchema","z","jsonValueSchema","uiMessageChunkSchema","lazySchema","zodSchema","providerMetadataSchema","value","isDataUIMessageChunk","chunk","createIdMap","isStaticToolUIPart","part","isDynamicToolUIPart","isToolUIPart","getStaticToolName","part","rawInputDeprecationWarning","warnIfUIMessageHasDeprecatedRawInput","messages","message","part","logWarnings","createStreamingUIMessageState","lastMessage","messageId","createIdMap","processUIMessageStream","stream","messageMetadataSchema","dataPartSchemas","runUpdateMessageJob","onError","onToolCall","onData","chunk","controller","state","write","_a","_b","_c","_d","getCurrentStepParts","parts","currentStepStartIndex","getCurrentStepToolInvocations","isToolUIPart","getToolInvocation","toolCallId","toolInvocation","invocation","i","UIMessageStreamError","getToolInvocationByApprovalId","approvalId","updateToolPart","options","existingPart","isStaticToolUIPart","anyOptions","anyPart","providerMetadata","resultPart","updateDynamicToolPart","updateMessageMetadata","metadata","mergedMetadata","mergeObjects","validateTypes","textPart","customPart","reasoningPart","toolInvocations","partialToolCall","partialArgs","parsePartialJson","p","approval","getStaticToolName","currentStepParts","isDataUIMessageChunk","partIdx","actualPartIdx","dataChunk","existingUIPart","chunkArg","consumeStream","stream","onError","abortSignal","reader","cancelOnAbort","done","error","originalGenerateId","createIdGenerator","originalGenerateCallId","originalGenerateId","createIdGenerator","originalGenerateCallId","toolMetadataSchema","z","jsonValueSchema","providerReferenceSchema","uiMessagesSchema","lazySchema","zodSchema","z","providerMetadataSchema","providerReferenceSchema","toolMetadataSchema","message","context","originalGenerateCallId","createIdGenerator","originalGenerateCallId","createIdGenerator","textEncoder","originalGenerateId","createIdGenerator","createDownload","options","url","abortSignal","download","atob","SerialJobExecutor","job","resolve","reject","error","originalGenerateId","createIdGenerator","defaultDownload","createDownload","REALTIME_MAX_FRAME_BYTES","REALTIME_MAX_BUFFERED_BYTES","MAX_SESSION_ANSWER_BYTES","setupSchema","z","value","url","name","marker","symbol","_a","_b","NoSuchProviderError","NoSuchModelError","modelId","modelType","providerId","availableProviders","message","error","AISDKError","originalGenerateCallId","createIdGenerator","defaultDownload","createDownload","createUIApiCallError","response","url","fallbackMessage","responseBody","APICallError","convertFileListToFileUIParts","files","UnsupportedFunctionalityError","file","name","type","dataUrl","resolve","reject","reader","readerEvent","_a","error","HttpChatTransport","api","credentials","headers","body","fetch","prepareSendMessagesRequest","prepareReconnectToStreamRequest","abortSignal","options","_b","_c","_d","resolvedBody","resolvedHeaders","resolvedCredentials","baseHeaders","normalizeHeaders","preparedRequest","response","createUIApiCallError","EmptyResponseBodyError","DefaultChatTransport","stream","parseJsonEventStream","uiMessageChunkSchema","chunk","controller","AbstractChat","generateId","generateIdFunc","id","transport","messageMetadataSchema","dataPartSchemas","state","onError","onToolCall","onFinish","onData","sendAutomaticallyWhen","SerialJobExecutor","message","uiMessage","abortController","fileParts","messageIndex","m","InvalidArgumentError","messageId","approved","reason","messages","lastMessage","updatePart","part","isToolUIPart","shouldSend","toolCallId","output","errorText","status","result","trigger","metadata","activeResumeRequest","isCurrentRequest","clearActiveResumeRequest","resumeStream","reconnect","err","isAbort","isDisconnect","isError","activeResponse","createStreamingUIMessageState","runUpdateMessageJob","job","updateStatus","consumeStream","processUIMessageStream","table","counter","hash","args","key","i","_hash","serializeKeyDefault","key","hash","SWRVCache","ttl","k","_key","v","timeToLive","now","item","serializedKey","_this","current","hasExpired","import_vue","isOnline","isDocumentVisible","fetcher","url","res","web_preset_default","DATA_CACHE","cache_default","REF_CACHE","PROMISES_CACHE","defaultConfig","web_preset_default","setRefCache","key","theRef","ttl","refCacheItem","gracePeriod","onErrorRetry","revalidate","errorRetryCount","config","count","timeout","resolveRetryFlag","_a","_b","shouldRetry","error","mutate","res","cache","isPromise","data","err_1","isValidating","newData","err","stateRef","refs_1","r","idx","isLast","useSWRV","_this","args","_i","fn","__assign","unmounted","isHydrated","IS_SERVER","keyRef","opts","__awaiter","isFirstFetch","keyVal","cacheItem","fetcher","shouldRevalidate","trigger","promiseFromCache","fetcherArgs","newPromise","__spreadArray","__read","configAllows","optsAllows","shouldRetryOnError","revalidateCall","__generator","timer","tick_1","ref","val","p","use_swrv_default","useSWRV","esm_default","use_swrv_default","import_vue","import_vue","import_vue","import_vue","useSWRV","esm_default","useSWRV","swrv","VueChat","AbstractChat","state","init","useChat","messages","status","error","chatStateWrapper","messageList","statusValue","errorValue","message","index","value","chatInstance","opts","_a","args","api","rpc","issueChatToken","submitFeedback","payload","SESSION_EXPIRED_MESSAGE","ChatTokenStore","#issue","#now","#token","#exp","#pending","options","#request","issued","error","createAuthorizedFetch","tokens","baseFetch","input","init","withToken","token","headers","SESSION_EXPIRED_MESSAGE","response","retried","chatApiBase","getFrontendData","chatApiUrl","path","chatTokens","ChatTokenStore","issueChatToken","chatFetch","createAuthorizedFetch","refreshChatToken","err","createChat","opts","useChat","error","DefaultChatTransport","chatApiUrl","chatFetch","id","messages","trigger","messageId","body","HASH_PREFIX","conversationIdFromHash","hash","setConversationHash","id","target","HASH_PREFIX","url","clearConversationHash","isLocalhost","fetchMeta","res","chatFetch","chatApiUrl","DEFAULT_MODEL_ID","MODEL_STORAGE_KEY","props","__props","emit","__emit","RELEVANT_QUESTIONS","IRRELEVANT_QUESTIONS","input","modelId","conversationId","persisted","mockState","pickerOpen","meta","metaFailed","showApiWarning","isLocalhost","chat","createChat","isBusy","sessionExpired","SESSION_EXPIRED_MESSAGE","value","sidebarChats","item","conversationTitle","activeConversation","c","firstUser","m","text","textOf","feedbackMap","feedbackDialog","p","openFeedback","message","rating","idx","priorUser","onFeedbackSubmit","comment","d","res","submitFeedback","err","stored","fetchMeta","current","prefillNextMockQuestion","scrollToBottom","id","handleSubmit","sendText","selectConversation","stopTestMode","conv","userCount","next","_status","previous","setConversationHash","scrollEl","isAtBottom","onScroll","el","behavior","downloadMarkdown","md","role","blob","url","a","import_vue","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","_hoisted_18","_hoisted_19","_hoisted_20","_hoisted_21","_hoisted_22","_hoisted_23","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createElementBlock","_createVNode","$event","_createElementVNode","_toDisplayString","_createCommentVNode","_createTextVNode","_Fragment","_renderList","q","i","m","_createBlock","rating","ChatView_default","render","import_vue","useConversationHistory","options","chats","session","loading","listError","loadError","error","request","listRequest","requestedId","refresh","current","result","open","id","snapshot","start","retry","chats","session","loading","error","refresh","open","start","retry","useConversationHistory","api","id","setConversationHash","clearConversationHash","initialLoading","conversationIdFromHash","busy","readHash","refreshOnFocus","import_vue","_hoisted_1","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createElementBlock","_createBlock","$event","ChatWorkspace_default","render","import_vue","import_vue","props","__props","emit","__emit","cells","inputs","rootEl","onFocusOut","event","next","setRef","el","i","val","digits","_","commit","value","focusCell","__expose","onInput","target","digit","onKeydown","onFocus","onPaste","text","firstEmpty","c","import_vue","_hoisted_1","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createElementBlock","_normalizeClass","_Fragment","_renderList","cell","i","el","$event","CodeInput_default","render","import_vue","EMAIL_KEY","STEP_HASH","useLoginCode","options","email","code","step","error","busy","devCode","cooldown","resendAfter","timer","changeEmail","requestCode","result","api","verifyCode","form","variable","input","onHashChange","emailInput","codeInput","email","code","step","error","busy","devCode","cooldown","changeEmail","requestCode","verifyCode","useLoginCode","import_vue","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createElementBlock","_createElementVNode","_createVNode","args","_withModifiers","$event","_toDisplayString","_createTextVNode","_withDirectives","_vModelText","_createBlock","_withCtx","_createCommentVNode","_Fragment","LoginForm_default","render","isLoggedIn","useWrdAuthState","import_vue","render","_ctx","_cache","$props","$setup","$data","$options","_openBlock","_createBlock","App_default","render","LOGGED_IN_CLASS","initTheme","onDomReady","App_default","setupWRDAuth","refreshChatToken","aps"]}